fix: pass OAuth cookie token to Hocuspocus WebSocket auth
Browse filesThe WebSocket provider doesn't send the OAuth token in the protocol
message. Extract it from the HTTP cookie during the upgrade request
and pass it via context to onAuthenticate.
Made-with: Cursor
- backend/src/server.ts +7 -3
backend/src/server.ts
CHANGED
|
@@ -54,13 +54,16 @@ if (oauthEnabled) {
|
|
| 54 |
}
|
| 55 |
|
| 56 |
const hocuspocus = new Hocuspocus({
|
| 57 |
-
async onAuthenticate({ token }: { token: string }) {
|
| 58 |
if (!oauthEnabled) return;
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
if (!user || !user.canEdit) {
|
| 62 |
throw new Error("Unauthorized: no write access");
|
| 63 |
}
|
|
|
|
| 64 |
return { user };
|
| 65 |
},
|
| 66 |
extensions: [
|
|
@@ -143,7 +146,8 @@ app.get("/api/auth/status", async (req, res) => {
|
|
| 143 |
// ---------- Collab WebSocket ----------
|
| 144 |
|
| 145 |
app.ws("/collab/:doc", (ws, req) => {
|
| 146 |
-
|
|
|
|
| 147 |
});
|
| 148 |
|
| 149 |
// ---------- AI Chat ----------
|
|
|
|
| 54 |
}
|
| 55 |
|
| 56 |
const hocuspocus = new Hocuspocus({
|
| 57 |
+
async onAuthenticate({ token, context }: { token: string; context: any }) {
|
| 58 |
if (!oauthEnabled) return;
|
| 59 |
|
| 60 |
+
// Prefer WebSocket protocol token, fall back to cookie token passed via context
|
| 61 |
+
const authToken = token || context?.token;
|
| 62 |
+
const user = await resolveUser(authToken);
|
| 63 |
if (!user || !user.canEdit) {
|
| 64 |
throw new Error("Unauthorized: no write access");
|
| 65 |
}
|
| 66 |
+
if (authToken) setUserToken(authToken);
|
| 67 |
return { user };
|
| 68 |
},
|
| 69 |
extensions: [
|
|
|
|
| 146 |
// ---------- Collab WebSocket ----------
|
| 147 |
|
| 148 |
app.ws("/collab/:doc", (ws, req) => {
|
| 149 |
+
const token = extractToken(req.headers.cookie);
|
| 150 |
+
hocuspocus.handleConnection(ws, req, { token });
|
| 151 |
});
|
| 152 |
|
| 153 |
// ---------- AI Chat ----------
|