Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/server/src/ClientConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,12 @@ export class ClientConnection<Context = any> {
);

this.websocket.send(message.toUint8Array());

// Clean up all state for this document so a retry is treated
// as a fresh first connection attempt.
this.documentConnectionsEstablished.delete(documentName);
delete this.hookPayloads[documentName];
delete this.incomingMessageQueue[documentName];
}

// Catch errors due to failed decoding of data
Expand Down
90 changes: 90 additions & 0 deletions tests/provider/onAuthenticationFailedRetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import test from "ava";
import {
newHocuspocus,
newHocuspocusProvider,
newHocuspocusProviderWebsocket,
sleep,
} from "../utils/index.ts";

test("provider retries auth with token function after initial failure", async (t) => {
const docName = "superSecretDoc";
const requiredToken = "SUPER-SECRET-TOKEN";

const server = await newHocuspocus({
async onAuthenticate({ token, documentName }) {
if (documentName !== docName) {
throw new Error();
}

if (token !== requiredToken) {
throw new Error();
}
},
});

const socket = newHocuspocusProviderWebsocket(server);

let tokenCallCount = 0;

const provider = newHocuspocusProvider(server, {
websocketProvider: socket,
name: docName,
token: () => {
tokenCallCount++;
return tokenCallCount === 1 ? "wrongToken" : requiredToken;
},
onAuthenticationFailed() {
provider.sendToken();
provider.startSync();
},
});

await sleep(2000);

t.is(tokenCallCount, 2);
t.is(provider.isAuthenticated, true);
});

test("second provider with same doc name succeeds after first fails auth", async (t) => {
const docName = "superSecretDoc";
const requiredToken = "SUPER-SECRET-TOKEN";

const server = await newHocuspocus({
async onAuthenticate({ token, documentName }) {
if (documentName !== docName) {
throw new Error();
}

if (token !== requiredToken) {
throw new Error();
}
},
});

const socket = newHocuspocusProviderWebsocket(server);

const providerFail = newHocuspocusProvider(server, {
websocketProvider: socket,
token: "wrongToken",
name: docName,
onAuthenticated() {
t.fail("providerFail should not authenticate");
},
});

await sleep(1000);

const providerOK = newHocuspocusProvider(server, {
websocketProvider: socket,
token: requiredToken,
name: docName,
onAuthenticationFailed() {
t.fail("providerOK should not fail auth");
},
});

await sleep(1000);

t.is(providerFail.isAuthenticated, false);
t.is(providerOK.isAuthenticated, true);
});