@jskit-ai/realtime 0.2.6 → 0.2.7
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/package.json +7 -2
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/client/RealtimeClientProvider.js +8 -3
- package/src/server/RealtimeProvider.js +36 -151
- package/src/server/realtimeAudience.js +172 -78
- package/src/server/realtimeCapability.js +160 -0
- package/src/server/realtimeDelivery.js +109 -72
- package/src/server/runtime.js +47 -26
- package/src/server/servedClientBuild.js +10 -4
- package/src/server/types.js +18 -0
- package/test/authorization.test.js +21 -13
- package/test/providerRuntime.test.js +43 -4
|
@@ -1,9 +1,21 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
1
2
|
import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
2
3
|
|
|
4
|
+
/** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
|
|
5
|
+
/** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
|
|
6
|
+
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
|
|
7
|
+
/** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
|
|
8
|
+
/** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
|
|
9
|
+
|
|
3
10
|
const ALL_CLIENTS_ROOM = "clients";
|
|
4
11
|
const ALL_USERS_ROOM = "users";
|
|
5
12
|
|
|
6
|
-
|
|
13
|
+
/**
|
|
14
|
+
* The value's entries as one flat list without null or undefined: nested
|
|
15
|
+
* arrays are flattened and a single value becomes a one-entry list.
|
|
16
|
+
* @param {unknown} value
|
|
17
|
+
*/
|
|
18
|
+
function flattenEntries(value) {
|
|
7
19
|
const queue = Array.isArray(value) ? [...value] : [value];
|
|
8
20
|
const list = [];
|
|
9
21
|
while (queue.length > 0) {
|
|
@@ -26,7 +38,8 @@ function roomForWorkspaceUser(workspaceId, userId) {
|
|
|
26
38
|
return `workspace:${String(workspaceId || "").trim()}:user:${String(userId || "").trim()}`;
|
|
27
39
|
}
|
|
28
40
|
|
|
29
|
-
|
|
41
|
+
/** @param {object | null | undefined} scope An event's scope; null or absent names none. */
|
|
42
|
+
function resolveScopeWorkspaceId(scope) {
|
|
30
43
|
const kind = normalizeText(scope?.kind).toLowerCase();
|
|
31
44
|
if (kind === "workspace") return normalizeRecordId(scope.id, { fallback: null });
|
|
32
45
|
if (kind === "workspace_user") {
|
|
@@ -35,15 +48,19 @@ function resolveScopeWorkspaceId(scope = {}) {
|
|
|
35
48
|
return normalizeRecordId(scope?.workspaceId, { fallback: null });
|
|
36
49
|
}
|
|
37
50
|
|
|
38
|
-
|
|
51
|
+
/** @param {object | null | undefined} scope An event's scope; null or absent names none. */
|
|
52
|
+
function resolveScopeUserId(scope) {
|
|
39
53
|
const kind = normalizeText(scope?.kind).toLowerCase();
|
|
40
54
|
if (kind === "user") return normalizeRecordId(scope.id, { fallback: null });
|
|
41
55
|
return normalizeRecordId(scope?.userId, { fallback: null });
|
|
42
56
|
}
|
|
43
57
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
58
|
+
/**
|
|
59
|
+
* The single mapping from a kernel event scope ({ kind: "user" | "workspace" |
|
|
60
|
+
* "workspace_user" }) to its Socket.IO room; null when the scope names no room.
|
|
61
|
+
* @param {object | null | undefined} scope
|
|
62
|
+
*/
|
|
63
|
+
function roomForScope(scope) {
|
|
47
64
|
const kind = normalizeText(scope?.kind).toLowerCase();
|
|
48
65
|
const workspaceId = resolveScopeWorkspaceId(scope);
|
|
49
66
|
const userId = resolveScopeUserId(scope);
|
|
@@ -53,37 +70,52 @@ function roomForScope(scope = {}) {
|
|
|
53
70
|
return null;
|
|
54
71
|
}
|
|
55
72
|
|
|
56
|
-
|
|
57
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Packages that know which scopes an actor belongs to (for example workspace
|
|
75
|
+
* memberships) contribute them here; realtime only turns scopes into rooms.
|
|
76
|
+
*/
|
|
58
77
|
function createAudienceContributors() {
|
|
59
78
|
const contributors = new Map();
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
79
|
+
|
|
80
|
+
/** @param {import("./types.js").RealtimeAudienceContributor} contributor Validated here. */
|
|
81
|
+
function register({ id, resolveActorScopes }) {
|
|
82
|
+
const contributorId = normalizeText(id);
|
|
83
|
+
if (!contributorId) throw new TypeError("Realtime audience contributors require an id.");
|
|
84
|
+
// readable-check: allow method-probe - input validation: a package registers its own contributor
|
|
85
|
+
if (typeof resolveActorScopes !== "function") {
|
|
86
|
+
throw new TypeError(`Realtime audience contributor "${contributorId}" requires resolveActorScopes().`);
|
|
87
|
+
}
|
|
88
|
+
if (contributors.has(contributorId)) {
|
|
89
|
+
throw new Error(`Realtime audience contributor "${contributorId}" is already registered.`);
|
|
90
|
+
}
|
|
91
|
+
contributors.set(contributorId, resolveActorScopes);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Whether revalidation could make a socket join this room: every room
|
|
96
|
+
* roomForScope() names starts with user: or workspace:.
|
|
97
|
+
* @param {string} room
|
|
98
|
+
*/
|
|
99
|
+
function mayContribute(room) {
|
|
100
|
+
return contributors.size > 0 && /^(?:user|workspace):/u.test(String(room));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @type {ActorRoomsResolver} */
|
|
104
|
+
async function resolveActorRooms(actorId) {
|
|
105
|
+
const rooms = new Set();
|
|
106
|
+
for (const resolveActorScopes of contributors.values()) {
|
|
107
|
+
for (const scope of flattenEntries(await resolveActorScopes(actorId))) {
|
|
108
|
+
const room = roomForScope(scope);
|
|
109
|
+
if (room) rooms.add(room);
|
|
84
110
|
}
|
|
85
|
-
return rooms;
|
|
86
111
|
}
|
|
112
|
+
return rooms;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return Object.freeze({
|
|
116
|
+
register,
|
|
117
|
+
mayContribute,
|
|
118
|
+
resolveActorRooms
|
|
87
119
|
});
|
|
88
120
|
}
|
|
89
121
|
|
|
@@ -121,7 +153,7 @@ function applyAudiencePreset(preset, { event, rooms, flags, logger }) {
|
|
|
121
153
|
|
|
122
154
|
function addAudienceRooms(selection, state) {
|
|
123
155
|
if (!selection || typeof selection !== "object" || Array.isArray(selection)) return;
|
|
124
|
-
const {
|
|
156
|
+
const { rooms, flags } = state;
|
|
125
157
|
if (Object.hasOwn(selection, "preset")) {
|
|
126
158
|
applyAudiencePreset(selection.preset, state);
|
|
127
159
|
}
|
|
@@ -129,38 +161,36 @@ function addAudienceRooms(selection, state) {
|
|
|
129
161
|
|
|
130
162
|
const directRoom = normalizeText(selection.room);
|
|
131
163
|
if (directRoom) rooms.add(directRoom);
|
|
132
|
-
for (const entry of
|
|
164
|
+
for (const entry of flattenEntries(selection.rooms)) {
|
|
133
165
|
const room = normalizeText(entry);
|
|
134
166
|
if (room) rooms.add(room);
|
|
135
167
|
}
|
|
136
168
|
|
|
137
169
|
const directUserId = normalizeRecordId(selection.userId, { fallback: null });
|
|
138
170
|
if (directUserId) rooms.add(roomForUser(directUserId));
|
|
139
|
-
for (const entry of
|
|
171
|
+
for (const entry of flattenEntries(selection.userIds)) {
|
|
140
172
|
const userId = normalizeRecordId(entry, { fallback: null });
|
|
141
173
|
if (userId) rooms.add(roomForUser(userId));
|
|
142
174
|
}
|
|
143
175
|
|
|
144
176
|
const directWorkspaceId = normalizeRecordId(selection.workspaceId, { fallback: null });
|
|
145
177
|
if (directWorkspaceId) rooms.add(roomForWorkspace(directWorkspaceId));
|
|
146
|
-
for (const entry of
|
|
178
|
+
for (const entry of flattenEntries(selection.workspaceIds)) {
|
|
147
179
|
const workspaceId = normalizeRecordId(entry, { fallback: null });
|
|
148
180
|
if (workspaceId) rooms.add(roomForWorkspace(workspaceId));
|
|
149
181
|
}
|
|
150
182
|
|
|
151
|
-
for (const entry of
|
|
183
|
+
for (const entry of flattenEntries([selection.workspaceUser, selection.workspaceUsers])) {
|
|
152
184
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
153
185
|
const workspaceId = normalizeRecordId(entry.workspaceId, { fallback: null });
|
|
154
186
|
const userId = normalizeRecordId(entry.userId, { fallback: null });
|
|
155
187
|
if (workspaceId && userId) rooms.add(roomForWorkspaceUser(workspaceId, userId));
|
|
156
188
|
}
|
|
157
|
-
|
|
158
|
-
if (!event || !logger) throw new TypeError("Realtime audience state is incomplete.");
|
|
159
189
|
}
|
|
160
190
|
|
|
161
191
|
function collectUserIds(rows) {
|
|
162
192
|
const ids = new Set();
|
|
163
|
-
for (const row of
|
|
193
|
+
for (const row of flattenEntries(rows)) {
|
|
164
194
|
const rawId = typeof row === "number" ? row : row?.userId || row?.user_id || row?.id;
|
|
165
195
|
const id = normalizeRecordId(rawId, { fallback: null });
|
|
166
196
|
if (id) ids.add(id);
|
|
@@ -168,20 +198,28 @@ function collectUserIds(rows) {
|
|
|
168
198
|
return [...ids];
|
|
169
199
|
}
|
|
170
200
|
|
|
171
|
-
|
|
201
|
+
/**
|
|
202
|
+
* @param {unknown} audience
|
|
203
|
+
* @param {object} event
|
|
204
|
+
* @param {object} dependencies
|
|
205
|
+
* @param {RuntimeDatabase | null} dependencies.database Absent when no runtime.database is installed.
|
|
206
|
+
* @param {RuntimeLogger} dependencies.logger
|
|
207
|
+
*/
|
|
208
|
+
async function resolveAudienceTargets(audience, event, { database, logger }) {
|
|
172
209
|
const rooms = new Set();
|
|
173
210
|
const flags = { broadcastAllClients: false };
|
|
174
211
|
const state = { event, rooms, flags, logger };
|
|
175
212
|
|
|
176
|
-
for (const entry of
|
|
213
|
+
for (const entry of flattenEntries(audience)) {
|
|
177
214
|
if (typeof entry === "string") {
|
|
178
215
|
applyAudiencePreset(entry, state);
|
|
179
216
|
continue;
|
|
180
217
|
}
|
|
181
218
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
182
219
|
addAudienceRooms(entry, state);
|
|
220
|
+
// readable-check: allow method-probe - data: an event's audience entry may name a userQuery()
|
|
183
221
|
if (typeof entry.userQuery === "function") {
|
|
184
|
-
if (
|
|
222
|
+
if (!database) {
|
|
185
223
|
logger.warn("Realtime audience userQuery requires runtime.database.");
|
|
186
224
|
continue;
|
|
187
225
|
}
|
|
@@ -213,12 +251,16 @@ function parseCookieHeader(value = "") {
|
|
|
213
251
|
return cookies;
|
|
214
252
|
}
|
|
215
253
|
|
|
254
|
+
/**
|
|
255
|
+
* The request a socket's handshake stands for, as the auth service reads one.
|
|
256
|
+
* @param {import("socket.io").Socket} socket
|
|
257
|
+
*/
|
|
216
258
|
function createSocketRequest(socket) {
|
|
217
|
-
const handshakeHeaders = socket
|
|
218
|
-
const requestHeaders = socket
|
|
259
|
+
const handshakeHeaders = socket.handshake.headers;
|
|
260
|
+
const requestHeaders = socket.request.headers;
|
|
219
261
|
const host = normalizeText(handshakeHeaders.host || requestHeaders.host);
|
|
220
262
|
const remoteAddress = normalizeText(
|
|
221
|
-
socket
|
|
263
|
+
socket.request.socket.remoteAddress || socket.conn.remoteAddress || socket.handshake.address
|
|
222
264
|
);
|
|
223
265
|
const request = {
|
|
224
266
|
cookies: parseCookieHeader(handshakeHeaders.cookie || requestHeaders.cookie)
|
|
@@ -229,53 +271,85 @@ function createSocketRequest(socket) {
|
|
|
229
271
|
if (value !== undefined) headers[name] = value;
|
|
230
272
|
}
|
|
231
273
|
if (Object.keys(headers).length > 0) request.headers = headers;
|
|
232
|
-
request.socket = { encrypted: socket
|
|
274
|
+
request.socket = { encrypted: socket.request.socket.encrypted === true };
|
|
233
275
|
if (remoteAddress) request.socket.remoteAddress = remoteAddress;
|
|
234
276
|
return request;
|
|
235
277
|
}
|
|
236
278
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
279
|
+
/**
|
|
280
|
+
* The auth service's check of a socket request: who is signed in, without
|
|
281
|
+
* refreshing a session the socket could not store.
|
|
282
|
+
* @param {AuthService} authService
|
|
283
|
+
* @returns {(request: object) => ReturnType<AuthService["authenticateRequest"]>}
|
|
284
|
+
*/
|
|
285
|
+
function authenticateWithoutRefresh(authService) {
|
|
286
|
+
return (request) => authService.authenticateRequest(request, { refreshSession: false });
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* A socket cannot store a refreshed session, so its checks never refresh one.
|
|
291
|
+
* A provider that would have to (its access token expired) answers
|
|
292
|
+
* `refreshRequired`, and the client refreshes over HTTP before reconnecting.
|
|
293
|
+
* @param {AuthService | null} authService Absent when no auth.service is installed.
|
|
294
|
+
* @param {import("socket.io").Socket} socket
|
|
295
|
+
* @param {object} [request]
|
|
296
|
+
* @param {(request: object) => ReturnType<AuthService["authenticateRequest"]>} [authenticateRequest]
|
|
297
|
+
*/
|
|
240
298
|
async function resolveSocketAuthentication(authService, socket, request = createSocketRequest(socket),
|
|
241
|
-
authenticateRequest = (
|
|
242
|
-
if (
|
|
299
|
+
authenticateRequest = authenticateWithoutRefresh(authService)) {
|
|
300
|
+
if (!authService) return { actor: null, refreshRequired: false };
|
|
243
301
|
const result = await authenticateRequest(request);
|
|
244
|
-
const id = result
|
|
245
|
-
? normalizeRecordId(result
|
|
246
|
-
return { actor: id ? { ...result.actor, id } : null, refreshRequired: result
|
|
302
|
+
const id = result.authenticated === true
|
|
303
|
+
? normalizeRecordId(result.actor.id, { fallback: null }) : null;
|
|
304
|
+
return { actor: id ? { ...result.actor, id } : null, refreshRequired: result.refreshRequired === true };
|
|
247
305
|
}
|
|
248
306
|
|
|
249
|
-
|
|
307
|
+
/** @param {AuthService | null} authService Absent when no auth.service is installed. */
|
|
308
|
+
function realtimeAuthenticationRequired(authService) {
|
|
250
309
|
return authService?.realtime?.requireAuthentication === true;
|
|
251
310
|
}
|
|
252
311
|
|
|
312
|
+
/**
|
|
313
|
+
* A refused realtime caller. The code lets a client show the English in the
|
|
314
|
+
* user's language: as the error's code at a host's action boundary, and in its
|
|
315
|
+
* data, which Socket.IO sends with a refused handshake.
|
|
316
|
+
*/
|
|
317
|
+
class RealtimeAuthenticationError extends AppError {
|
|
318
|
+
/**
|
|
319
|
+
* @param {string} message
|
|
320
|
+
* @param {{ code: string }} options
|
|
321
|
+
*/
|
|
322
|
+
constructor(message, { code }) {
|
|
323
|
+
super(401, message, { code });
|
|
324
|
+
this.name = "RealtimeAuthenticationError";
|
|
325
|
+
this.data = Object.freeze({ code });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
253
329
|
function authenticationRequiredError() {
|
|
254
|
-
|
|
255
|
-
error.data = Object.freeze({ code: "AUTHENTICATION_REQUIRED" });
|
|
256
|
-
return error;
|
|
330
|
+
return new RealtimeAuthenticationError("Authentication required.", { code: "AUTHENTICATION_REQUIRED" });
|
|
257
331
|
}
|
|
258
332
|
|
|
259
333
|
function sessionRefreshRequiredError() {
|
|
260
|
-
|
|
261
|
-
error.data = Object.freeze({ code: "SESSION_REFRESH_REQUIRED" });
|
|
262
|
-
return error;
|
|
334
|
+
return new RealtimeAuthenticationError("Session refresh required.", { code: "SESSION_REFRESH_REQUIRED" });
|
|
263
335
|
}
|
|
264
336
|
|
|
265
337
|
function rememberSocketActorId(socket, actorId) {
|
|
266
|
-
socket.data = socket.data && typeof socket.data === "object" ? socket.data : {};
|
|
267
338
|
socket.data.actorId = actorId;
|
|
268
339
|
}
|
|
269
340
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
341
|
+
/**
|
|
342
|
+
* Every handshake is authenticated here. A login that needs a session refresh
|
|
343
|
+
* is refused even when sign-in is optional, so the client refreshes and
|
|
344
|
+
* reconnects instead of silently connecting without its user's rooms.
|
|
345
|
+
* @param {object} dependencies
|
|
346
|
+
* @param {import("socket.io").Server} dependencies.io
|
|
347
|
+
* @param {RuntimeLogger} dependencies.logger
|
|
348
|
+
* @param {AuthService | null} dependencies.authService Absent when no auth.service is installed.
|
|
349
|
+
*/
|
|
273
350
|
function registerSocketAuthentication({ io, logger, authService }) {
|
|
351
|
+
if (!authService) return;
|
|
274
352
|
const required = realtimeAuthenticationRequired(authService);
|
|
275
|
-
if (!required && typeof authService?.authenticateRequest !== "function") return;
|
|
276
|
-
if (typeof io?.use !== "function") {
|
|
277
|
-
throw new TypeError("Realtime socket authentication requires Socket.IO middleware support.");
|
|
278
|
-
}
|
|
279
353
|
io.use(async (socket, next) => {
|
|
280
354
|
try {
|
|
281
355
|
const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket);
|
|
@@ -296,22 +370,33 @@ function registerSocketAuthentication({ io, logger, authService }) {
|
|
|
296
370
|
});
|
|
297
371
|
}
|
|
298
372
|
|
|
373
|
+
/**
|
|
374
|
+
* @param {import("socket.io").Socket} socket
|
|
375
|
+
* @param {string} actorId
|
|
376
|
+
* @param {{ resolveActorRooms: ActorRoomsResolver }} audiences
|
|
377
|
+
*/
|
|
299
378
|
async function joinContributedRooms(socket, actorId, audiences) {
|
|
300
|
-
const rooms =
|
|
301
|
-
for (const room of
|
|
379
|
+
const rooms = await audiences.resolveActorRooms(actorId);
|
|
380
|
+
for (const room of flattenEntries(socket.data.contributedRooms)) {
|
|
302
381
|
if (!rooms.has(room)) await socket.leave(room);
|
|
303
382
|
}
|
|
304
383
|
for (const room of rooms) await socket.join(room);
|
|
305
384
|
socket.data.contributedRooms = [...rooms];
|
|
306
385
|
}
|
|
307
386
|
|
|
308
|
-
|
|
309
|
-
|
|
387
|
+
/**
|
|
388
|
+
* @param {object} dependencies
|
|
389
|
+
* @param {import("socket.io").Server} dependencies.io
|
|
390
|
+
* @param {RuntimeLogger} dependencies.logger
|
|
391
|
+
* @param {AuthService | null} dependencies.authService Absent when no auth.service is installed.
|
|
392
|
+
* @param {AudienceContributors} dependencies.audiences
|
|
393
|
+
*/
|
|
394
|
+
function registerSocketAudienceBootstrap({ io, logger, authService, audiences }) {
|
|
310
395
|
registerSocketAuthentication({ io, logger, authService });
|
|
311
396
|
io.on("connection", async (socket) => {
|
|
312
397
|
try {
|
|
313
398
|
socket.join(ALL_CLIENTS_ROOM);
|
|
314
|
-
const actorId = normalizeRecordId(socket
|
|
399
|
+
const actorId = normalizeRecordId(socket.data.actorId, { fallback: null });
|
|
315
400
|
if (!actorId) return;
|
|
316
401
|
socket.join(ALL_USERS_ROOM);
|
|
317
402
|
socket.join(roomForUser(actorId));
|
|
@@ -322,9 +407,17 @@ function registerSocketAudienceBootstrap({ io, logger, authService = null, audie
|
|
|
322
407
|
});
|
|
323
408
|
}
|
|
324
409
|
|
|
325
|
-
|
|
410
|
+
/**
|
|
411
|
+
* @param {object} options
|
|
412
|
+
* @param {import("socket.io").Socket} options.socket
|
|
413
|
+
* @param {AuthService | null} options.authService Absent when no auth.service is installed.
|
|
414
|
+
* @param {{ resolveActorRooms: ActorRoomsResolver }} options.audiences
|
|
415
|
+
* @param {object} [options.request]
|
|
416
|
+
* @param {Parameters<typeof resolveSocketAuthentication>[3]} [options.authenticateRequest]
|
|
417
|
+
*/
|
|
418
|
+
async function revalidateSocket({ socket, authService, audiences, request, authenticateRequest }) {
|
|
326
419
|
const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket, request, authenticateRequest);
|
|
327
|
-
const previousActorId = socket.data
|
|
420
|
+
const previousActorId = socket.data.actorId;
|
|
328
421
|
if (refreshRequired || (!actor && realtimeAuthenticationRequired(authService)) ||
|
|
329
422
|
(previousActorId && previousActorId !== actor?.id)) {
|
|
330
423
|
socket.disconnect(true);
|
|
@@ -338,6 +431,7 @@ async function revalidateSocket({ socket, authService, audiences = null, request
|
|
|
338
431
|
}
|
|
339
432
|
|
|
340
433
|
export {
|
|
434
|
+
authenticationRequiredError,
|
|
341
435
|
createAudienceContributors,
|
|
342
436
|
createSocketRequest,
|
|
343
437
|
realtimeAuthenticationRequired,
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import {
|
|
2
|
+
authenticationRequiredError,
|
|
3
|
+
createAudienceContributors,
|
|
4
|
+
createSocketRequest,
|
|
5
|
+
realtimeAuthenticationRequired,
|
|
6
|
+
registerSocketAudienceBootstrap,
|
|
7
|
+
revalidateSocket
|
|
8
|
+
} from "./realtimeAudience.js";
|
|
9
|
+
import { createRealtimeDelivery, matchesRealtimeEvent } from "./realtimeDelivery.js";
|
|
10
|
+
import { announceServedClientBuild } from "./servedClientBuild.js";
|
|
11
|
+
import {
|
|
12
|
+
closeSocketIoRedisConnections,
|
|
13
|
+
closeSocketIoServer,
|
|
14
|
+
configureSocketIoRedisAdapter,
|
|
15
|
+
countConnectedClients
|
|
16
|
+
} from "./runtime.js";
|
|
17
|
+
|
|
18
|
+
/** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
|
|
19
|
+
/** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
|
|
20
|
+
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} RuntimeAppRoot */
|
|
21
|
+
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeEvents} RuntimeEvents */
|
|
22
|
+
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The `runtime.realtime` capability over one Socket.IO server. It starts
|
|
26
|
+
* delivering once every provider has booted, because the auth service may be
|
|
27
|
+
* ready only then, and stops with the runtime.
|
|
28
|
+
* @param {object} dependencies
|
|
29
|
+
* @param {import("socket.io").Server} dependencies.io
|
|
30
|
+
* @param {RuntimeLogger} dependencies.logger
|
|
31
|
+
* @param {AuthService | null} dependencies.authService
|
|
32
|
+
* @param {RuntimeDatabase | null} dependencies.database
|
|
33
|
+
* @param {RuntimeEvents} dependencies.events
|
|
34
|
+
* @param {RuntimeAppRoot | null} dependencies.appRoot
|
|
35
|
+
* @param {{ redisUrl: string, redisNamespace: string }} dependencies.redis
|
|
36
|
+
*/
|
|
37
|
+
function createRealtimeCapability({ io, logger, authService, database, events, appRoot, redis }) {
|
|
38
|
+
const audiences = createAudienceContributors();
|
|
39
|
+
const connectionListeners = new Set();
|
|
40
|
+
let authenticationRequired = false;
|
|
41
|
+
/** @type {ReturnType<typeof createRealtimeDelivery> | null} */
|
|
42
|
+
let delivery = null;
|
|
43
|
+
/** @type {Awaited<ReturnType<typeof configureSocketIoRedisAdapter>> | null} */
|
|
44
|
+
let redisConnection = null;
|
|
45
|
+
|
|
46
|
+
function onConnection(listener) {
|
|
47
|
+
// readable-check: allow method-probe - input validation: an application hands over its connection listener
|
|
48
|
+
if (typeof listener !== "function") throw new TypeError("Realtime connection listener must be a function.");
|
|
49
|
+
const releases = new Map();
|
|
50
|
+
function attach(socket) {
|
|
51
|
+
if (releases.has(socket)) return;
|
|
52
|
+
let detach;
|
|
53
|
+
async function readRequest() {
|
|
54
|
+
const request = createSocketRequest(socket);
|
|
55
|
+
const actor = await revalidateSocket({ socket, request, authService, audiences });
|
|
56
|
+
if (!socket.connected || (!actor && realtimeAuthenticationRequired(authService))) {
|
|
57
|
+
throw authenticationRequiredError();
|
|
58
|
+
}
|
|
59
|
+
if (actor) request.user = actor;
|
|
60
|
+
return request;
|
|
61
|
+
}
|
|
62
|
+
function release() {
|
|
63
|
+
socket.off("disconnect", release);
|
|
64
|
+
releases.delete(socket);
|
|
65
|
+
try { detach?.(); }
|
|
66
|
+
catch (error) {
|
|
67
|
+
logger.warn({ error: String(error?.message || error) }, "Realtime connection cleanup failed.");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
detach = listener({
|
|
72
|
+
socket,
|
|
73
|
+
// Hosts authorize this real connection request through their own
|
|
74
|
+
// action boundary. Reading it alone does not grant local access.
|
|
75
|
+
readRequest,
|
|
76
|
+
async authenticate() {
|
|
77
|
+
const request = await readRequest();
|
|
78
|
+
if (!request.user) throw authenticationRequiredError();
|
|
79
|
+
return request;
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
// readable-check: allow method-probe - input validation: an application's listener returns its cleanup
|
|
83
|
+
if (detach != null && typeof detach !== "function") {
|
|
84
|
+
throw new TypeError("Realtime connection listeners must return a cleanup function or undefined.");
|
|
85
|
+
}
|
|
86
|
+
releases.set(socket, release);
|
|
87
|
+
socket.on("disconnect", release);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
logger.warn({ error: String(error?.message || error) }, "Realtime connection listener failed.");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function stopListening() {
|
|
93
|
+
io.off("connection", attach);
|
|
94
|
+
for (const release of [...releases.values()]) release();
|
|
95
|
+
connectionListeners.delete(stopListening);
|
|
96
|
+
}
|
|
97
|
+
connectionListeners.add(stopListening);
|
|
98
|
+
io.on("connection", attach);
|
|
99
|
+
for (const socket of io.sockets.sockets.values()) attach(socket);
|
|
100
|
+
return stopListening;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A package that knows which scopes (kind "user", "workspace" or
|
|
105
|
+
* "workspace_user") an actor belongs to registers them during setup; sockets
|
|
106
|
+
* join, and on revalidation leave, exactly the rooms its scopes name.
|
|
107
|
+
* @param {import("./types.js").RealtimeAudienceContributor} contributor
|
|
108
|
+
*/
|
|
109
|
+
function registerAudienceContributor(contributor) {
|
|
110
|
+
audiences.register(contributor);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function diagnostics() {
|
|
114
|
+
return Object.freeze({
|
|
115
|
+
authenticationRequired,
|
|
116
|
+
connectedClients: countConnectedClients(io),
|
|
117
|
+
redisConfigured: redisConnection?.enabled === true
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Authenticates each socket and delivers every event that names a socket
|
|
123
|
+
* event, to the other servers too when Redis is configured.
|
|
124
|
+
*/
|
|
125
|
+
async function start() {
|
|
126
|
+
delivery = createRealtimeDelivery({ io, database, logger, authService, audiences });
|
|
127
|
+
authenticationRequired = realtimeAuthenticationRequired(authService);
|
|
128
|
+
registerSocketAudienceBootstrap({ io, logger, authService, audiences });
|
|
129
|
+
announceServedClientBuild({ io, appRoot, logger });
|
|
130
|
+
redisConnection = await configureSocketIoRedisAdapter(io, { logger, ...redis });
|
|
131
|
+
delivery.start({ redisConfigured: redisConnection.enabled });
|
|
132
|
+
events.register({
|
|
133
|
+
id: "runtime.realtime.delivery",
|
|
134
|
+
matches: matchesRealtimeEvent,
|
|
135
|
+
handle: delivery.handle
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Closes Socket.IO's part of the HTTP server; the server's owner closes the server.
|
|
141
|
+
*/
|
|
142
|
+
async function stop() {
|
|
143
|
+
for (const release of [...connectionListeners]) release();
|
|
144
|
+
if (delivery) delivery.stop();
|
|
145
|
+
await closeSocketIoServer(io);
|
|
146
|
+
if (redisConnection) await closeSocketIoRedisConnections(redisConnection);
|
|
147
|
+
authenticationRequired = false;
|
|
148
|
+
redisConnection = null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return Object.freeze({
|
|
152
|
+
onConnection,
|
|
153
|
+
registerAudienceContributor,
|
|
154
|
+
diagnostics,
|
|
155
|
+
start,
|
|
156
|
+
stop
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export { createRealtimeCapability };
|