@terreno/api 0.31.0 → 56.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +121 -26
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.js +23 -4
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +13 -0
- package/dist/plugins.js +47 -1
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +2 -0
- package/dist/realtime/realtimeApp.js +83 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +54 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +899 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +7 -6
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/api.errors.test.ts +32 -23
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -296
- package/src/auth.test.ts +202 -0
- package/src/auth.ts +134 -23
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +56 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +101 -17
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +64 -0
- package/src/plugins.ts +56 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +82 -14
- package/src/realtime/realtimeAppSetup.test.ts +25 -27
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +54 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +705 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +641 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +730 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// noExplicitAny: test mocks use dynamic shapes for sockets and auth stubs
|
|
2
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mocks use dynamic shapes for sockets and auth stubs
|
|
3
|
+
/**
|
|
4
|
+
* Full validator matrix for the socket authentication chain (D1):
|
|
5
|
+
* - Legacy JWT validator (valid / expired / wrong-secret / wrong-issuer / missing token)
|
|
6
|
+
* - Better Auth session validator (valid / invalid session / missing token)
|
|
7
|
+
* - Chain fall-through and precedence
|
|
8
|
+
* - Bearer-prefix stripping
|
|
9
|
+
* - Issuer parity with the HTTP JWT path (D1), including per-handshake freshness
|
|
10
|
+
*
|
|
11
|
+
* Moved out of sync/syncSocket.test.ts (which still covers the higher-level
|
|
12
|
+
* subscribe/mutate socket handlers) into its own file per the syncdb hardening plan.
|
|
13
|
+
*/
|
|
14
|
+
import {describe, expect, it} from "bun:test";
|
|
15
|
+
import jwt from "jsonwebtoken";
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
type AuthenticatableSocket,
|
|
19
|
+
createBetterAuthValidator,
|
|
20
|
+
createLegacyJwtValidator,
|
|
21
|
+
createSocketAuthMiddleware,
|
|
22
|
+
} from "./socketAuth";
|
|
23
|
+
|
|
24
|
+
describe("socketAuth", () => {
|
|
25
|
+
const tokenSecret = "socket-auth-test-secret";
|
|
26
|
+
|
|
27
|
+
const makeAuthSocket = (token?: string): AuthenticatableSocket & {decodedToken?: any} => ({
|
|
28
|
+
handshake: {auth: token === undefined ? {} : {token}},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const runMiddleware = (
|
|
32
|
+
middleware: (socket: any, next: (error?: Error) => void) => void,
|
|
33
|
+
socket: AuthenticatableSocket
|
|
34
|
+
): Promise<Error | undefined> =>
|
|
35
|
+
new Promise((resolve) => {
|
|
36
|
+
middleware(socket, (error?: Error) => resolve(error));
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe("createLegacyJwtValidator", () => {
|
|
40
|
+
it("accepts a valid Bearer JWT and populates decodedToken", async () => {
|
|
41
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
42
|
+
const token = jwt.sign({admin: true, id: "jwt-user"}, tokenSecret);
|
|
43
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
44
|
+
await validator(socket);
|
|
45
|
+
expect(socket.decodedToken?.id).toBe("jwt-user");
|
|
46
|
+
expect(socket.decodedToken?.admin).toBe(true);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("stamps authKind: 'jwt' on a successful validation (D1 sweep discriminator)", async () => {
|
|
50
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
51
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret);
|
|
52
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
53
|
+
await validator(socket);
|
|
54
|
+
expect(socket.decodedToken?.authKind).toBe("jwt");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("rejects an expired JWT", async () => {
|
|
58
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
59
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret, {expiresIn: -10});
|
|
60
|
+
await expect(validator(makeAuthSocket(`Bearer ${token}`))).rejects.toThrow(
|
|
61
|
+
"Token is missing or invalid Bearer"
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("rejects a token signed with the wrong secret", async () => {
|
|
66
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
67
|
+
const token = jwt.sign({id: "jwt-user"}, "wrong-secret");
|
|
68
|
+
await expect(validator(makeAuthSocket(`Bearer ${token}`))).rejects.toThrow(
|
|
69
|
+
"Token is missing or invalid Bearer"
|
|
70
|
+
);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("rejects a token without the Bearer prefix", async () => {
|
|
74
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
75
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret);
|
|
76
|
+
await expect(validator(makeAuthSocket(token))).rejects.toThrow(
|
|
77
|
+
"Format is Authorization: Bearer [token]"
|
|
78
|
+
);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("rejects when no token is provided", async () => {
|
|
82
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
83
|
+
await expect(validator(makeAuthSocket(undefined))).rejects.toThrow("no token provided");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// D1: parity with the HTTP JWT path's jwt.verify(token, secret, {issuer}).
|
|
87
|
+
describe("issuer parity (D1)", () => {
|
|
88
|
+
it("accepts a token whose iss matches the required issuer", async () => {
|
|
89
|
+
const validator = createLegacyJwtValidator(tokenSecret, "expected-issuer");
|
|
90
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret, {issuer: "expected-issuer"});
|
|
91
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
92
|
+
await validator(socket);
|
|
93
|
+
expect(socket.decodedToken?.id).toBe("jwt-user");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("rejects a validly-signed token issued for a different issuer", async () => {
|
|
97
|
+
const validator = createLegacyJwtValidator(tokenSecret, "expected-issuer");
|
|
98
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret, {issuer: "some-other-issuer"});
|
|
99
|
+
await expect(validator(makeAuthSocket(`Bearer ${token}`))).rejects.toThrow(
|
|
100
|
+
"Token is missing or invalid Bearer"
|
|
101
|
+
);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("rejects a token with no iss claim when an issuer is required", async () => {
|
|
105
|
+
const validator = createLegacyJwtValidator(tokenSecret, "expected-issuer");
|
|
106
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret);
|
|
107
|
+
await expect(validator(makeAuthSocket(`Bearer ${token}`))).rejects.toThrow(
|
|
108
|
+
"Token is missing or invalid Bearer"
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("does not check issuer when none is configured (pre-D1 behavior preserved)", async () => {
|
|
113
|
+
const validator = createLegacyJwtValidator(tokenSecret);
|
|
114
|
+
const token = jwt.sign({id: "jwt-user"}, tokenSecret, {issuer: "whatever"});
|
|
115
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
116
|
+
await validator(socket);
|
|
117
|
+
expect(socket.decodedToken?.id).toBe("jwt-user");
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("resolves a thunk issuer fresh on every handshake (no staleness from a captured value)", async () => {
|
|
121
|
+
let currentIssuer = "issuer-v1";
|
|
122
|
+
const validator = createLegacyJwtValidator(tokenSecret, () => currentIssuer);
|
|
123
|
+
|
|
124
|
+
const tokenV1 = jwt.sign({id: "user-1"}, tokenSecret, {issuer: "issuer-v1"});
|
|
125
|
+
await validator(makeAuthSocket(`Bearer ${tokenV1}`));
|
|
126
|
+
|
|
127
|
+
// Simulate the issuer changing after the validator was constructed (the real
|
|
128
|
+
// bug this guards: RealtimeApp used to capture process.env.TOKEN_ISSUER once
|
|
129
|
+
// at onServerCreated() time instead of reading it fresh per handshake).
|
|
130
|
+
currentIssuer = "issuer-v2";
|
|
131
|
+
const tokenV1Again = jwt.sign({id: "user-1"}, tokenSecret, {issuer: "issuer-v1"});
|
|
132
|
+
await expect(validator(makeAuthSocket(`Bearer ${tokenV1Again}`))).rejects.toThrow(
|
|
133
|
+
"Token is missing or invalid Bearer"
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
const tokenV2 = jwt.sign({id: "user-2"}, tokenSecret, {issuer: "issuer-v2"});
|
|
137
|
+
const socket = makeAuthSocket(`Bearer ${tokenV2}`);
|
|
138
|
+
await validator(socket);
|
|
139
|
+
expect(socket.decodedToken?.id).toBe("user-2");
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe("createBetterAuthValidator", () => {
|
|
145
|
+
const stubAuth = (session: unknown, capture?: {headers?: unknown}): any => ({
|
|
146
|
+
api: {
|
|
147
|
+
getSession: async ({headers}: {headers: unknown}) => {
|
|
148
|
+
if (capture) {
|
|
149
|
+
capture.headers = headers;
|
|
150
|
+
}
|
|
151
|
+
return session;
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("populates decodedToken from a valid Better Auth session", async () => {
|
|
157
|
+
const validator = createBetterAuthValidator({
|
|
158
|
+
auth: stubAuth({session: {id: "sess-1"}, user: {id: "ba-user-1"}}),
|
|
159
|
+
});
|
|
160
|
+
const socket = makeAuthSocket("session-token-abc");
|
|
161
|
+
await validator(socket);
|
|
162
|
+
expect(socket.decodedToken).toEqual({
|
|
163
|
+
admin: false,
|
|
164
|
+
authKind: "better-auth",
|
|
165
|
+
id: "ba-user-1",
|
|
166
|
+
isAnonymous: false,
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("retains the raw session token on socket.encodedToken (for D1's sweep re-check)", async () => {
|
|
171
|
+
const validator = createBetterAuthValidator({
|
|
172
|
+
auth: stubAuth({session: {id: "sess-1"}, user: {id: "ba-user-1"}}),
|
|
173
|
+
});
|
|
174
|
+
const socket = makeAuthSocket("Bearer session-token-abc");
|
|
175
|
+
await validator(socket);
|
|
176
|
+
expect(socket.encodedToken).toBe("session-token-abc");
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("passes the token as a bearer authorization header only", async () => {
|
|
180
|
+
const capture: {headers?: any} = {};
|
|
181
|
+
const validator = createBetterAuthValidator({
|
|
182
|
+
auth: stubAuth({session: {id: "s"}, user: {id: "u"}}, capture),
|
|
183
|
+
});
|
|
184
|
+
await validator(makeAuthSocket("Bearer session-token-xyz"));
|
|
185
|
+
expect(capture.headers.authorization).toBe("Bearer session-token-xyz");
|
|
186
|
+
// A raw (unsigned) token cookie fails signature verification and can shadow the
|
|
187
|
+
// bearer path, so the validator must not send one.
|
|
188
|
+
expect(capture.headers.cookie).toBeUndefined();
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("rejects when the session lookup returns null", async () => {
|
|
192
|
+
const validator = createBetterAuthValidator({auth: stubAuth(null)});
|
|
193
|
+
await expect(validator(makeAuthSocket("bad-session"))).rejects.toThrow(
|
|
194
|
+
"Better Auth session is missing or invalid"
|
|
195
|
+
);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it("rejects when no token is provided", async () => {
|
|
199
|
+
const validator = createBetterAuthValidator({auth: stubAuth(null)});
|
|
200
|
+
await expect(validator(makeAuthSocket(undefined))).rejects.toThrow("no token provided");
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("resolves the app user for id and admin when a userModel is provided", async () => {
|
|
204
|
+
const userModel = {
|
|
205
|
+
find: () => {
|
|
206
|
+
throw new Error("unused");
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
const appUser = {_id: "app-user-1", admin: true};
|
|
210
|
+
const findOneOrNone = async (query: Record<string, unknown>) =>
|
|
211
|
+
query.betterAuthId === "ba-user-1" ? appUser : null;
|
|
212
|
+
const validator = createBetterAuthValidator({
|
|
213
|
+
auth: stubAuth({session: {id: "s"}, user: {id: "ba-user-1"}}),
|
|
214
|
+
userModel: {...userModel, findOneOrNone} as any,
|
|
215
|
+
});
|
|
216
|
+
const socket = makeAuthSocket("session-token");
|
|
217
|
+
await validator(socket);
|
|
218
|
+
expect(socket.decodedToken).toEqual({
|
|
219
|
+
admin: true,
|
|
220
|
+
authKind: "better-auth",
|
|
221
|
+
id: "app-user-1",
|
|
222
|
+
isAnonymous: false,
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("rejects when the Better Auth user has no application user", async () => {
|
|
227
|
+
const validator = createBetterAuthValidator({
|
|
228
|
+
auth: stubAuth({session: {id: "s"}, user: {id: "ba-orphan"}}),
|
|
229
|
+
userModel: {findOneOrNone: async () => null} as any,
|
|
230
|
+
});
|
|
231
|
+
await expect(validator(makeAuthSocket("session-token"))).rejects.toThrow(
|
|
232
|
+
"no application user"
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe("createSocketAuthMiddleware — validator chain", () => {
|
|
238
|
+
it("accepts a legacy JWT with the default chain", async () => {
|
|
239
|
+
const middleware = createSocketAuthMiddleware({tokenSecret});
|
|
240
|
+
const token = jwt.sign({admin: false, id: "chain-user"}, tokenSecret);
|
|
241
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
242
|
+
const error = await runMiddleware(middleware, socket);
|
|
243
|
+
expect(error).toBeUndefined();
|
|
244
|
+
expect(socket.decodedToken?.id).toBe("chain-user");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it("rejects an invalid token with the default chain", async () => {
|
|
248
|
+
const middleware = createSocketAuthMiddleware({tokenSecret});
|
|
249
|
+
const socket = makeAuthSocket("Bearer not-a-jwt");
|
|
250
|
+
const error = await runMiddleware(middleware, socket);
|
|
251
|
+
expect(error).toBeDefined();
|
|
252
|
+
expect(error?.message).toContain("invalid");
|
|
253
|
+
expect(socket.decodedToken).toBeUndefined();
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("falls through to the Better Auth validator when the JWT validator fails", async () => {
|
|
257
|
+
const middleware = createSocketAuthMiddleware({
|
|
258
|
+
betterAuth: {
|
|
259
|
+
auth: {
|
|
260
|
+
api: {getSession: async () => ({session: {id: "s"}, user: {id: "ba-user-2"}})},
|
|
261
|
+
} as any,
|
|
262
|
+
},
|
|
263
|
+
tokenSecret,
|
|
264
|
+
});
|
|
265
|
+
const socket = makeAuthSocket("better-auth-session-token");
|
|
266
|
+
const error = await runMiddleware(middleware, socket);
|
|
267
|
+
expect(error).toBeUndefined();
|
|
268
|
+
expect(socket.decodedToken).toEqual({
|
|
269
|
+
admin: false,
|
|
270
|
+
authKind: "better-auth",
|
|
271
|
+
id: "ba-user-2",
|
|
272
|
+
isAnonymous: false,
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("falls through to Better Auth when the JWT is expired", async () => {
|
|
277
|
+
const middleware = createSocketAuthMiddleware({
|
|
278
|
+
betterAuth: {
|
|
279
|
+
auth: {
|
|
280
|
+
api: {getSession: async () => ({session: {id: "s"}, user: {id: "ba-fallback"}})},
|
|
281
|
+
} as any,
|
|
282
|
+
},
|
|
283
|
+
tokenSecret,
|
|
284
|
+
});
|
|
285
|
+
const expiredToken = jwt.sign({id: "expired-jwt-user"}, tokenSecret, {expiresIn: -10});
|
|
286
|
+
const socket = makeAuthSocket(`Bearer ${expiredToken}`);
|
|
287
|
+
const error = await runMiddleware(middleware, socket);
|
|
288
|
+
expect(error).toBeUndefined();
|
|
289
|
+
expect(socket.decodedToken?.id).toBe("ba-fallback");
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("prefers the legacy JWT validator when both would work", async () => {
|
|
293
|
+
const middleware = createSocketAuthMiddleware({
|
|
294
|
+
betterAuth: {
|
|
295
|
+
auth: {
|
|
296
|
+
api: {
|
|
297
|
+
getSession: async () => {
|
|
298
|
+
throw new Error("should not be called for a valid JWT");
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
} as any,
|
|
302
|
+
},
|
|
303
|
+
tokenSecret,
|
|
304
|
+
});
|
|
305
|
+
const token = jwt.sign({admin: true, id: "jwt-first"}, tokenSecret);
|
|
306
|
+
const socket = makeAuthSocket(`Bearer ${token}`);
|
|
307
|
+
const error = await runMiddleware(middleware, socket);
|
|
308
|
+
expect(error).toBeUndefined();
|
|
309
|
+
expect(socket.decodedToken?.id).toBe("jwt-first");
|
|
310
|
+
expect(socket.decodedToken?.admin).toBe(true);
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it("rejects with the last validator's error when every validator fails", async () => {
|
|
314
|
+
const middleware = createSocketAuthMiddleware({
|
|
315
|
+
betterAuth: {auth: {api: {getSession: async () => null}} as any},
|
|
316
|
+
tokenSecret,
|
|
317
|
+
});
|
|
318
|
+
const socket = makeAuthSocket("neither-jwt-nor-session");
|
|
319
|
+
const error = await runMiddleware(middleware, socket);
|
|
320
|
+
expect(error?.message).toContain("Better Auth session is missing or invalid");
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it("passes the configured issuer through to the JWT validator", async () => {
|
|
324
|
+
const middleware = createSocketAuthMiddleware({issuer: "chain-issuer", tokenSecret});
|
|
325
|
+
const wrongIssuerToken = jwt.sign({id: "u"}, tokenSecret, {issuer: "not-chain-issuer"});
|
|
326
|
+
const socket = makeAuthSocket(`Bearer ${wrongIssuerToken}`);
|
|
327
|
+
const error = await runMiddleware(middleware, socket);
|
|
328
|
+
expect(error).toBeDefined();
|
|
329
|
+
expect(error?.message).toContain("invalid");
|
|
330
|
+
// The wrapped socketio-jwt middleware sets decodedToken from the raw JWT payload
|
|
331
|
+
// before the post-verify onAuthentication issuer check runs, so the property is
|
|
332
|
+
// present (but never stamped with authKind, since that only happens on success)
|
|
333
|
+
// — the connection is still rejected via the returned error either way.
|
|
334
|
+
expect(socket.decodedToken?.authKind).toBeUndefined();
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it("supports extra validators appended to the chain", async () => {
|
|
338
|
+
const middleware = createSocketAuthMiddleware({
|
|
339
|
+
extraValidators: [
|
|
340
|
+
async (socket) => {
|
|
341
|
+
if (socket.handshake.auth.token !== "magic") {
|
|
342
|
+
throw new Error("not magic");
|
|
343
|
+
}
|
|
344
|
+
socket.decodedToken = {admin: false, id: "magic-user", isAnonymous: false};
|
|
345
|
+
},
|
|
346
|
+
],
|
|
347
|
+
tokenSecret,
|
|
348
|
+
});
|
|
349
|
+
const socket = makeAuthSocket("magic");
|
|
350
|
+
const error = await runMiddleware(middleware, socket);
|
|
351
|
+
expect(error).toBeUndefined();
|
|
352
|
+
expect(socket.decodedToken?.id).toBe("magic-user");
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
});
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import {authorize, UnauthorizedError} from "@thream/socketio-jwt";
|
|
2
|
+
import type {Socket} from "socket.io";
|
|
3
|
+
|
|
4
|
+
import type {UserModel} from "../auth";
|
|
5
|
+
import type {BetterAuthInstance} from "../betterAuthSetup";
|
|
6
|
+
import {logger} from "../logger";
|
|
7
|
+
import {findOneOrNoneFor} from "../plugins";
|
|
8
|
+
import type {SocketWithDecodedToken} from "./socketUser";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Pluggable socket authentication for RealtimeApp.
|
|
12
|
+
*
|
|
13
|
+
* The Socket.io handshake token (`socket.handshake.auth.token`) is validated by a chain of
|
|
14
|
+
* validators tried in order; the first one that succeeds populates `socket.decodedToken`
|
|
15
|
+
* (the shape `getSocketUser` consumes) and the connection proceeds. If every validator
|
|
16
|
+
* fails, the connection is rejected with the last validator's error.
|
|
17
|
+
*
|
|
18
|
+
* Validators:
|
|
19
|
+
* 1. Legacy JWT (default, always first) — the existing `@thream/socketio-jwt` middleware,
|
|
20
|
+
* wrapped unchanged so accepted payloads, secret handling, and error shapes are
|
|
21
|
+
* byte-for-byte identical to the previous hardcoded setup.
|
|
22
|
+
* 2. Better Auth session (optional) — enabled via `RealtimeAppOptions.betterAuth`. The
|
|
23
|
+
* handshake token is validated as a Better Auth session via `auth.api.getSession`
|
|
24
|
+
* (presented as an `Authorization: Bearer` credential, resolved by Better Auth's
|
|
25
|
+
* bearer plugin), and `socket.decodedToken` is populated as `{id, admin,
|
|
26
|
+
* isAnonymous: false}` exactly like the JWT path.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** The subset of a Socket.io socket the validators need. Lets tests pass a stub. */
|
|
30
|
+
export interface AuthenticatableSocket extends SocketWithDecodedToken {
|
|
31
|
+
handshake: {auth: {[key: string]: unknown; token?: string}};
|
|
32
|
+
encodedToken?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A socket auth validator: resolve after populating `socket.decodedToken`, or reject to
|
|
37
|
+
* let the next validator in the chain try.
|
|
38
|
+
*/
|
|
39
|
+
export type SocketAuthValidator = (socket: AuthenticatableSocket) => Promise<void>;
|
|
40
|
+
|
|
41
|
+
/** Options for the Better Auth session validator. */
|
|
42
|
+
export interface BetterAuthSocketOptions {
|
|
43
|
+
/** The instance returned by `createBetterAuth`. */
|
|
44
|
+
auth: BetterAuthInstance;
|
|
45
|
+
/**
|
|
46
|
+
* Optional application user model. When provided, the Better Auth user is resolved to
|
|
47
|
+
* the app user (via `betterAuthId`) so `decodedToken.id`/`admin` match the identity the
|
|
48
|
+
* REST layer uses. Without it, the Better Auth user id is used and `admin` is false.
|
|
49
|
+
*/
|
|
50
|
+
userModel?: UserModel;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Legacy JWT validator: wraps the `@thream/socketio-jwt` middleware so its observable
|
|
55
|
+
* behavior (token format requirements, secret verification, `decodedToken` payload,
|
|
56
|
+
* `UnauthorizedError` shapes) is identical to the previous direct `io.use(authorize(...))`.
|
|
57
|
+
*
|
|
58
|
+
* D1: `@thream/socketio-jwt`'s `authorize()` has no `issuer` option — it only verifies
|
|
59
|
+
* the signature/algorithm — so without this the socket path silently accepted a
|
|
60
|
+
* validly-signed token issued for a DIFFERENT `TOKEN_ISSUER` (e.g. a token from another
|
|
61
|
+
* environment sharing the same `TOKEN_SECRET`), unlike the HTTP path's
|
|
62
|
+
* `jwt.verify(token, secret, {issuer})`. When `issuer` is provided, the post-verify
|
|
63
|
+
* `onAuthentication` hook checks `decodedToken.iss` and rejects a mismatch with the
|
|
64
|
+
* same `UnauthorizedError` shape the signature-verification failure path uses, so
|
|
65
|
+
* callers cannot distinguish "bad signature" from "wrong issuer" from the error alone
|
|
66
|
+
* (matching the non-disclosure posture the HTTP path also has).
|
|
67
|
+
*
|
|
68
|
+
* `issuer` may be a plain string or a thunk (`() => string | undefined`) resolved on
|
|
69
|
+
* EVERY handshake — the HTTP path's `jwt.verify` reads `process.env.TOKEN_ISSUER` fresh
|
|
70
|
+
* per request rather than once at server startup, and a static string captured once at
|
|
71
|
+
* `RealtimeApp.onServerCreated()` time would go stale if `TOKEN_ISSUER` changes later
|
|
72
|
+
* (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
|
|
73
|
+
* per-request freshness; a plain string is still supported for callers who intentionally
|
|
74
|
+
* want a fixed value.
|
|
75
|
+
*/
|
|
76
|
+
export const createLegacyJwtValidator = (
|
|
77
|
+
tokenSecret: string,
|
|
78
|
+
issuer?: string | (() => string | undefined)
|
|
79
|
+
): SocketAuthValidator => {
|
|
80
|
+
const resolveIssuer = (): string | undefined =>
|
|
81
|
+
typeof issuer === "function" ? issuer() : issuer;
|
|
82
|
+
const middleware = authorize({
|
|
83
|
+
onAuthentication: (decodedToken: {iss?: string}) => {
|
|
84
|
+
const expectedIssuer = resolveIssuer();
|
|
85
|
+
if (expectedIssuer && decodedToken?.iss !== expectedIssuer) {
|
|
86
|
+
throw new UnauthorizedError("invalid_token", {
|
|
87
|
+
message: "Unauthorized: Token is missing or invalid Bearer",
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
secret: tokenSecret,
|
|
92
|
+
});
|
|
93
|
+
return (socket) =>
|
|
94
|
+
new Promise<void>((resolve, reject) => {
|
|
95
|
+
// The socketio-jwt middleware types demand a full Socket; it only reads
|
|
96
|
+
// handshake.auth.token and writes encodedToken/decodedToken.
|
|
97
|
+
middleware(socket as unknown as Socket, (error) => {
|
|
98
|
+
if (error) {
|
|
99
|
+
reject(error);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
// D1: stamp which validator authenticated this socket so the periodic
|
|
103
|
+
// re-validation sweep knows to re-check local JWT expiry (not a Better Auth
|
|
104
|
+
// session lookup) for it. The library already populated decodedToken with the
|
|
105
|
+
// full JWT payload (exp/iss included), so this only adds the discriminator.
|
|
106
|
+
if (socket.decodedToken) {
|
|
107
|
+
socket.decodedToken.authKind = "jwt";
|
|
108
|
+
}
|
|
109
|
+
resolve();
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** Strip an optional `Bearer ` prefix from the handshake token. */
|
|
115
|
+
const extractRawToken = (socket: AuthenticatableSocket): string | null => {
|
|
116
|
+
const {token} = socket.handshake.auth;
|
|
117
|
+
if (typeof token !== "string" || token.length === 0) {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
const parts = token.split(" ");
|
|
121
|
+
if (parts.length === 2 && parts[0] === "Bearer") {
|
|
122
|
+
return parts[1];
|
|
123
|
+
}
|
|
124
|
+
return token;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Better Auth session validator: treats the handshake token as a Better Auth session token
|
|
129
|
+
* and validates it via `auth.api.getSession` (the same lookup the HTTP session middleware
|
|
130
|
+
* uses). The token is presented both as a bearer Authorization header (for the Better Auth
|
|
131
|
+
* bearer plugin) and as the session cookie, so either transport configuration works.
|
|
132
|
+
*/
|
|
133
|
+
export const createBetterAuthValidator = (
|
|
134
|
+
options: BetterAuthSocketOptions
|
|
135
|
+
): SocketAuthValidator => {
|
|
136
|
+
const {auth, userModel} = options;
|
|
137
|
+
return async (socket) => {
|
|
138
|
+
const rawToken = extractRawToken(socket);
|
|
139
|
+
if (!rawToken) {
|
|
140
|
+
throw new UnauthorizedError("credentials_required", {message: "no token provided"});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Validate as a bearer credential only. Better Auth's bearer plugin signs and
|
|
144
|
+
// resolves the raw session token from the Authorization header. We deliberately do
|
|
145
|
+
// NOT also present it as a session cookie: a raw (unsigned) token cookie fails
|
|
146
|
+
// signature verification and, when both are sent, can shadow the working bearer path.
|
|
147
|
+
const session = await auth.api.getSession({
|
|
148
|
+
headers: {authorization: `Bearer ${rawToken}`} as Record<string, string>,
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
const betterAuthUserId = session?.user?.id;
|
|
152
|
+
if (!betterAuthUserId) {
|
|
153
|
+
throw new UnauthorizedError("invalid_token", {
|
|
154
|
+
message: "Unauthorized: Better Auth session is missing or invalid",
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let id = String(betterAuthUserId);
|
|
159
|
+
let admin = false;
|
|
160
|
+
if (userModel) {
|
|
161
|
+
const appUser = (await findOneOrNoneFor(userModel, {
|
|
162
|
+
betterAuthId: betterAuthUserId,
|
|
163
|
+
})) as unknown as {_id?: unknown; admin?: boolean} | null;
|
|
164
|
+
if (!appUser?._id) {
|
|
165
|
+
throw new UnauthorizedError("invalid_token", {
|
|
166
|
+
message: "Unauthorized: Better Auth user has no application user",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
id = String(appUser._id);
|
|
170
|
+
admin = appUser.admin === true;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
socket.decodedToken = {admin, authKind: "better-auth", id, isAnonymous: false};
|
|
174
|
+
// D1: retain the raw session token so the periodic re-validation sweep can re-run
|
|
175
|
+
// `auth.api.getSession` for this socket without re-deriving it from the handshake
|
|
176
|
+
// (which may have since changed if the client reconnected with a new token).
|
|
177
|
+
socket.encodedToken = rawToken;
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Build the Socket.io auth middleware from a validator chain: validators run in order and
|
|
183
|
+
* the first success wins; when all fail the connection is rejected with the last error.
|
|
184
|
+
*/
|
|
185
|
+
export const createSocketAuthMiddleware = ({
|
|
186
|
+
tokenSecret,
|
|
187
|
+
issuer,
|
|
188
|
+
betterAuth,
|
|
189
|
+
extraValidators = [],
|
|
190
|
+
}: {
|
|
191
|
+
/** Secret for the legacy JWT validator (same handling as before the refactor). */
|
|
192
|
+
tokenSecret: string;
|
|
193
|
+
/**
|
|
194
|
+
* JWT issuer to require (D1 parity with the HTTP path's `jwt.verify(token, secret,
|
|
195
|
+
* {issuer})`). Omitted means no issuer check, matching pre-D1 behavior. A thunk is
|
|
196
|
+
* resolved fresh on every handshake (see {@link createLegacyJwtValidator}).
|
|
197
|
+
*/
|
|
198
|
+
issuer?: string | (() => string | undefined);
|
|
199
|
+
/** Enables the Better Auth session validator after the legacy JWT validator. */
|
|
200
|
+
betterAuth?: BetterAuthSocketOptions;
|
|
201
|
+
/** Additional validators appended to the chain (after JWT and Better Auth). */
|
|
202
|
+
extraValidators?: SocketAuthValidator[];
|
|
203
|
+
}): ((socket: Socket, next: (error?: Error) => void) => void) => {
|
|
204
|
+
const validators: SocketAuthValidator[] = [createLegacyJwtValidator(tokenSecret, issuer)];
|
|
205
|
+
if (betterAuth) {
|
|
206
|
+
validators.push(createBetterAuthValidator(betterAuth));
|
|
207
|
+
}
|
|
208
|
+
validators.push(...extraValidators);
|
|
209
|
+
|
|
210
|
+
return (socket, next): void => {
|
|
211
|
+
void (async () => {
|
|
212
|
+
let lastError: Error = new UnauthorizedError("credentials_required", {
|
|
213
|
+
message: "no token provided",
|
|
214
|
+
});
|
|
215
|
+
for (const validator of validators) {
|
|
216
|
+
try {
|
|
217
|
+
await validator(socket as unknown as AuthenticatableSocket);
|
|
218
|
+
next();
|
|
219
|
+
return;
|
|
220
|
+
} catch (error: unknown) {
|
|
221
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
logger.debug(`[realtime] Socket authentication failed: ${lastError.message}`);
|
|
225
|
+
next(lastError);
|
|
226
|
+
})();
|
|
227
|
+
};
|
|
228
|
+
};
|
|
@@ -4,13 +4,67 @@ export interface DecodedRealtimeToken {
|
|
|
4
4
|
admin?: boolean;
|
|
5
5
|
id?: string;
|
|
6
6
|
isAnonymous?: boolean;
|
|
7
|
+
/** JWT `exp` claim (seconds since epoch) — present for the legacy JWT validator only. */
|
|
8
|
+
exp?: number;
|
|
9
|
+
/** JWT `iss` claim — present for the legacy JWT validator only. */
|
|
10
|
+
iss?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Which validator in the chain authenticated this socket (D1: the periodic
|
|
13
|
+
* re-validation sweep uses this to pick the matching cheap re-check — local JWT
|
|
14
|
+
* expiry verification vs. a Better Auth session lookup). Undefined for handshakes
|
|
15
|
+
* that predate this field (never actually observable at runtime — set by every
|
|
16
|
+
* validator — but kept optional so structural test doubles compile without it).
|
|
17
|
+
*/
|
|
18
|
+
authKind?: "jwt" | "better-auth";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Per-socket data bag. `fullUser` is populated once at handshake (see
|
|
23
|
+
* `loadFullUserForSocket` / `RealtimeApp`'s connection handler) by loading the full
|
|
24
|
+
* Mongoose user document for `decodedToken.id`, and refreshed by D1's periodic
|
|
25
|
+
* re-validation sweep. When present it is authoritative for authorization (permits
|
|
26
|
+
* fields like `organizationIds` that the synthetic decoded-token shape never carries
|
|
27
|
+
* — see D2); the synthetic shape remains a fallback for setups with no `userModel`
|
|
28
|
+
* configured, or while the handshake load is still in flight.
|
|
29
|
+
*/
|
|
30
|
+
export interface SocketDataBag {
|
|
31
|
+
// noExplicitAny: the full user is a consumer Mongoose document with app-specific fields
|
|
32
|
+
// biome-ignore lint/suspicious/noExplicitAny: the full user is a consumer Mongoose document with app-specific fields
|
|
33
|
+
fullUser?: any;
|
|
34
|
+
/**
|
|
35
|
+
* The in-flight handshake load of {@link SocketDataBag.fullUser}, published so handlers
|
|
36
|
+
* that must not authorize against the synthetic token user can await it
|
|
37
|
+
* (see {@link awaitSocketFullUser}). Never rejects.
|
|
38
|
+
*/
|
|
39
|
+
fullUserLoad?: Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Sync collection tag -> joined `sync:{stream}` rooms (see `socketHandlers.ts`).
|
|
42
|
+
* Lives on the data bag (not the handler closure) so D1's sweep can re-resolve
|
|
43
|
+
* stream membership and `socket.leave()` rooms no longer held (D4) without needing
|
|
44
|
+
* access to `installSyncSocketHandlers`'s internal state.
|
|
45
|
+
*/
|
|
46
|
+
syncSubscriptions?: Map<string, Set<string>>;
|
|
7
47
|
}
|
|
8
48
|
|
|
9
49
|
export interface SocketWithDecodedToken {
|
|
10
50
|
decodedToken?: DecodedRealtimeToken;
|
|
51
|
+
data?: SocketDataBag;
|
|
11
52
|
}
|
|
12
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Resolve the authorization-ready user for a socket: the full user document loaded at
|
|
56
|
+
* handshake (`socket.data.fullUser`, see D2) when available, otherwise the synthetic
|
|
57
|
+
* `{_id, admin, id, isAnonymous}` shape derived from the decoded token alone. Consumers
|
|
58
|
+
* (permission checks, `getUserScopes`, delta filters) should always go through this
|
|
59
|
+
* function rather than reading `decodedToken` directly, so they transparently benefit
|
|
60
|
+
* once a `userModel` is configured.
|
|
61
|
+
*/
|
|
13
62
|
export const getSocketUser = (socket: SocketWithDecodedToken): User | undefined => {
|
|
63
|
+
const fullUser = socket.data?.fullUser as User | undefined;
|
|
64
|
+
if (fullUser) {
|
|
65
|
+
return fullUser;
|
|
66
|
+
}
|
|
67
|
+
|
|
14
68
|
const userId = socket.decodedToken?.id;
|
|
15
69
|
if (!userId) {
|
|
16
70
|
return undefined;
|
|
@@ -23,3 +77,18 @@ export const getSocketUser = (socket: SocketWithDecodedToken): User | undefined
|
|
|
23
77
|
isAnonymous: socket.decodedToken?.isAnonymous,
|
|
24
78
|
};
|
|
25
79
|
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Task 9.21: {@link getSocketUser}, but first awaiting the handshake full-user load when it
|
|
83
|
+
* is still in flight. Sync handlers use this so a `sync:subscribe` / `sync:mutate` that
|
|
84
|
+
* lands inside the handshake window is authorized against the same user every later event
|
|
85
|
+
* sees — scope membership must not depend on event timing. Falls back to the synthetic
|
|
86
|
+
* token user exactly as `getSocketUser` does when no `userModel` is configured.
|
|
87
|
+
*/
|
|
88
|
+
export const awaitSocketFullUser = async (
|
|
89
|
+
socket: SocketWithDecodedToken
|
|
90
|
+
): Promise<User | undefined> => {
|
|
91
|
+
// The load swallows and logs its own failures; this await only orders the events.
|
|
92
|
+
await socket.data?.fullUserLoad;
|
|
93
|
+
return getSocketUser(socket);
|
|
94
|
+
};
|