Skip to content

Commit 3567540

Browse files
committed
fix: reset auth state on failed auth, so a new auth message can run auth hooks again. fixes #944
1 parent 667e145 commit 3567540

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

packages/server/src/ClientConnection.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,12 @@ export class ClientConnection<Context = any> {
382382
);
383383

384384
this.websocket.send(message.toUint8Array());
385+
386+
// Clean up all state for this document so a retry is treated
387+
// as a fresh first connection attempt.
388+
this.documentConnectionsEstablished.delete(documentName);
389+
delete this.hookPayloads[documentName];
390+
delete this.incomingMessageQueue[documentName];
385391
}
386392

387393
// Catch errors due to failed decoding of data
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import test from "ava";
2+
import {
3+
newHocuspocus,
4+
newHocuspocusProvider,
5+
newHocuspocusProviderWebsocket,
6+
sleep,
7+
} from "../utils/index.ts";
8+
9+
test("provider retries auth with token function after initial failure", async (t) => {
10+
const docName = "superSecretDoc";
11+
const requiredToken = "SUPER-SECRET-TOKEN";
12+
13+
const server = await newHocuspocus({
14+
async onAuthenticate({ token, documentName }) {
15+
if (documentName !== docName) {
16+
throw new Error();
17+
}
18+
19+
if (token !== requiredToken) {
20+
throw new Error();
21+
}
22+
},
23+
});
24+
25+
const socket = newHocuspocusProviderWebsocket(server);
26+
27+
let tokenCallCount = 0;
28+
29+
const provider = newHocuspocusProvider(server, {
30+
websocketProvider: socket,
31+
name: docName,
32+
token: () => {
33+
tokenCallCount++;
34+
return tokenCallCount === 1 ? "wrongToken" : requiredToken;
35+
},
36+
onAuthenticationFailed() {
37+
provider.sendToken();
38+
provider.startSync();
39+
},
40+
});
41+
42+
await sleep(2000);
43+
44+
t.is(tokenCallCount, 2);
45+
t.is(provider.isAuthenticated, true);
46+
});

0 commit comments

Comments
 (0)