@jskit-ai/realtime 0.2.3 → 0.2.5
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 +2 -2
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/client/RealtimeClientProvider.js +15 -1
- package/src/client/connectionRecovery.js +15 -2
- package/src/server/realtimeAudience.js +35 -24
- package/src/server/realtimeDelivery.js +3 -2
- package/test/authorization.test.js +38 -5
- package/test/clientRuntime.test.js +21 -0
- package/test/providerRuntime.test.js +10 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/realtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "node --test --test-concurrency=1"
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"socket.io-client": "^4.8.3"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"@jskit-ai/kernel": "0.2.
|
|
24
|
+
"@jskit-ai/kernel": "0.2.2",
|
|
25
25
|
"vue": "^3.5.13"
|
|
26
26
|
},
|
|
27
27
|
"description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
|
|
@@ -49,6 +49,7 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
49
49
|
const servedClientBuild = trackServedClientBuild(socket, logger);
|
|
50
50
|
const detach = [];
|
|
51
51
|
let initialized = false;
|
|
52
|
+
let beforeReconnect = null;
|
|
52
53
|
|
|
53
54
|
function initialize(vueApp = null) {
|
|
54
55
|
if (initialized) {
|
|
@@ -57,7 +58,7 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
57
58
|
initialized = true;
|
|
58
59
|
|
|
59
60
|
if (typeof socket.on === "function") {
|
|
60
|
-
detach.push(attachSocketConnectionRecovery(socket));
|
|
61
|
+
detach.push(attachSocketConnectionRecovery(socket, { prepareReconnect: () => beforeReconnect?.() }));
|
|
61
62
|
const onConnect = () => logger.debug({ socketConnected: true }, "Realtime client socket connected.");
|
|
62
63
|
const onDisconnect = (reason) =>
|
|
63
64
|
logger.debug(
|
|
@@ -108,11 +109,24 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
108
109
|
initialized = false;
|
|
109
110
|
}
|
|
110
111
|
|
|
112
|
+
// The step to run before recovery reconnects after the server refused or
|
|
113
|
+
// dropped the socket, such as auth refreshing the session.
|
|
114
|
+
function setBeforeReconnect(prepare) {
|
|
115
|
+
if (typeof prepare !== "function") {
|
|
116
|
+
throw new TypeError("setBeforeReconnect requires a function.");
|
|
117
|
+
}
|
|
118
|
+
beforeReconnect = prepare;
|
|
119
|
+
return () => {
|
|
120
|
+
if (beforeReconnect === prepare) beforeReconnect = null;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
111
124
|
return Object.freeze({
|
|
112
125
|
config,
|
|
113
126
|
dispose,
|
|
114
127
|
initialize,
|
|
115
128
|
onServedClientBuild: servedClientBuild.subscribe,
|
|
129
|
+
setBeforeReconnect,
|
|
116
130
|
socket
|
|
117
131
|
});
|
|
118
132
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { reconnectSocketIoClient } from "./runtime.js";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// `prepareReconnect` runs before each recovery reconnect; auth uses it to
|
|
4
|
+
// refresh an expired session over HTTP so the handshake carries fresh cookies.
|
|
5
|
+
function attachSocketConnectionRecovery(socket, { prepareReconnect = null } = {}) {
|
|
4
6
|
let timer = null;
|
|
5
7
|
let delay = 1_000;
|
|
6
8
|
let recovering = false;
|
|
@@ -18,11 +20,22 @@ function attachSocketConnectionRecovery(socket) {
|
|
|
18
20
|
!document?.hidden && window?.navigator?.onLine !== false;
|
|
19
21
|
}
|
|
20
22
|
|
|
23
|
+
async function retry() {
|
|
24
|
+
if (prepareReconnect) {
|
|
25
|
+
try {
|
|
26
|
+
await prepareReconnect();
|
|
27
|
+
} catch {
|
|
28
|
+
// The handshake then decides; a refusal schedules the next retry.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (canRetry()) socket.connect();
|
|
32
|
+
}
|
|
33
|
+
|
|
21
34
|
function scheduleRetry() {
|
|
22
35
|
if (timer !== null || !canRetry()) return;
|
|
23
36
|
timer = setTimeout(() => {
|
|
24
37
|
timer = null;
|
|
25
|
-
if (canRetry())
|
|
38
|
+
if (canRetry()) void retry();
|
|
26
39
|
}, delay);
|
|
27
40
|
delay = Math.min(delay * 2, 30_000);
|
|
28
41
|
}
|
|
@@ -53,11 +53,6 @@ function roomForScope(scope = {}) {
|
|
|
53
53
|
return null;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
// Every room roomForScope() names has one of these prefixes.
|
|
57
|
-
function isScopeRoom(room) {
|
|
58
|
-
return /^(?:user|workspace):/u.test(String(room));
|
|
59
|
-
}
|
|
60
|
-
|
|
61
56
|
// Packages that know which scopes an actor belongs to (for example workspace
|
|
62
57
|
// memberships) contribute them here; realtime only turns scopes into rooms.
|
|
63
58
|
function createAudienceContributors() {
|
|
@@ -74,9 +69,10 @@ function createAudienceContributors() {
|
|
|
74
69
|
}
|
|
75
70
|
contributors.set(contributorId, resolveActorScopes);
|
|
76
71
|
},
|
|
77
|
-
// Whether revalidation could make a socket join this room
|
|
72
|
+
// Whether revalidation could make a socket join this room: every room
|
|
73
|
+
// roomForScope() names starts with user: or workspace:.
|
|
78
74
|
mayContribute(room) {
|
|
79
|
-
return contributors.size > 0 &&
|
|
75
|
+
return contributors.size > 0 && /^(?:user|workspace):/u.test(String(room));
|
|
80
76
|
},
|
|
81
77
|
async resolveActorRooms(actorId) {
|
|
82
78
|
const rooms = new Set();
|
|
@@ -238,13 +234,16 @@ function createSocketRequest(socket) {
|
|
|
238
234
|
return request;
|
|
239
235
|
}
|
|
240
236
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
237
|
+
// A socket cannot store a refreshed session, so its checks never refresh one.
|
|
238
|
+
// A provider that would have to (its access token expired) answers
|
|
239
|
+
// `refreshRequired`, and the client refreshes over HTTP before reconnecting.
|
|
240
|
+
async function resolveSocketAuthentication(authService, socket, request = createSocketRequest(socket),
|
|
241
|
+
authenticateRequest = (value) => authService.authenticateRequest(value, { refreshSession: false })) {
|
|
242
|
+
if (typeof authService?.authenticateRequest !== "function") return { actor: null, refreshRequired: false };
|
|
244
243
|
const result = await authenticateRequest(request);
|
|
245
244
|
const id = result?.authenticated === true
|
|
246
245
|
? normalizeRecordId(result?.actor?.id, { fallback: null }) : null;
|
|
247
|
-
return id ? { ...result.actor, id } : null;
|
|
246
|
+
return { actor: id ? { ...result.actor, id } : null, refreshRequired: result?.refreshRequired === true };
|
|
248
247
|
}
|
|
249
248
|
|
|
250
249
|
function realtimeAuthenticationRequired(authService = null) {
|
|
@@ -257,28 +256,42 @@ function authenticationRequiredError() {
|
|
|
257
256
|
return error;
|
|
258
257
|
}
|
|
259
258
|
|
|
259
|
+
function sessionRefreshRequiredError() {
|
|
260
|
+
const error = new Error("Session refresh required.");
|
|
261
|
+
error.data = Object.freeze({ code: "SESSION_REFRESH_REQUIRED" });
|
|
262
|
+
return error;
|
|
263
|
+
}
|
|
264
|
+
|
|
260
265
|
function rememberSocketActorId(socket, actorId) {
|
|
261
266
|
socket.data = socket.data && typeof socket.data === "object" ? socket.data : {};
|
|
262
267
|
socket.data.actorId = actorId;
|
|
263
268
|
}
|
|
264
269
|
|
|
265
|
-
|
|
266
|
-
|
|
270
|
+
// Every handshake is authenticated here. A login that needs a session refresh
|
|
271
|
+
// is refused even when sign-in is optional, so the client refreshes and
|
|
272
|
+
// reconnects instead of silently connecting without its user's rooms.
|
|
273
|
+
function registerSocketAuthentication({ io, logger, authService }) {
|
|
274
|
+
const required = realtimeAuthenticationRequired(authService);
|
|
275
|
+
if (!required && typeof authService?.authenticateRequest !== "function") return;
|
|
267
276
|
if (typeof io?.use !== "function") {
|
|
268
|
-
throw new TypeError("Realtime
|
|
277
|
+
throw new TypeError("Realtime socket authentication requires Socket.IO middleware support.");
|
|
269
278
|
}
|
|
270
279
|
io.use(async (socket, next) => {
|
|
271
280
|
try {
|
|
272
|
-
const
|
|
273
|
-
if (
|
|
281
|
+
const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket);
|
|
282
|
+
if (refreshRequired) {
|
|
283
|
+
next(sessionRefreshRequiredError());
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (!actor && required) {
|
|
274
287
|
next(authenticationRequiredError());
|
|
275
288
|
return;
|
|
276
289
|
}
|
|
277
|
-
rememberSocketActorId(socket,
|
|
290
|
+
if (actor) rememberSocketActorId(socket, actor.id);
|
|
278
291
|
next();
|
|
279
292
|
} catch (error) {
|
|
280
293
|
logger.warn({ error: String(error?.message || error) }, "Realtime socket authentication failed.");
|
|
281
|
-
next(authenticationRequiredError());
|
|
294
|
+
next(required ? authenticationRequiredError() : undefined);
|
|
282
295
|
}
|
|
283
296
|
});
|
|
284
297
|
}
|
|
@@ -294,14 +307,12 @@ async function joinContributedRooms(socket, actorId, audiences) {
|
|
|
294
307
|
|
|
295
308
|
function registerSocketAudienceBootstrap({ io, logger, authService = null, audiences = null }) {
|
|
296
309
|
if (typeof io?.on !== "function") return;
|
|
297
|
-
|
|
310
|
+
registerSocketAuthentication({ io, logger, authService });
|
|
298
311
|
io.on("connection", async (socket) => {
|
|
299
312
|
try {
|
|
300
313
|
socket.join(ALL_CLIENTS_ROOM);
|
|
301
|
-
const actorId = normalizeRecordId(socket?.data?.actorId, { fallback: null })
|
|
302
|
-
|| (await resolveSocketActor(authService, socket))?.id;
|
|
314
|
+
const actorId = normalizeRecordId(socket?.data?.actorId, { fallback: null });
|
|
303
315
|
if (!actorId) return;
|
|
304
|
-
rememberSocketActorId(socket, actorId);
|
|
305
316
|
socket.join(ALL_USERS_ROOM);
|
|
306
317
|
socket.join(roomForUser(actorId));
|
|
307
318
|
await joinContributedRooms(socket, actorId, audiences);
|
|
@@ -312,9 +323,9 @@ function registerSocketAudienceBootstrap({ io, logger, authService = null, audie
|
|
|
312
323
|
}
|
|
313
324
|
|
|
314
325
|
async function revalidateSocket({ socket, authService, audiences = null, request, authenticateRequest }) {
|
|
315
|
-
const actor = await
|
|
326
|
+
const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket, request, authenticateRequest);
|
|
316
327
|
const previousActorId = socket.data?.actorId;
|
|
317
|
-
if ((!actor && realtimeAuthenticationRequired(authService)) ||
|
|
328
|
+
if (refreshRequired || (!actor && realtimeAuthenticationRequired(authService)) ||
|
|
318
329
|
(previousActorId && previousActorId !== actor?.id)) {
|
|
319
330
|
socket.disconnect(true);
|
|
320
331
|
return null;
|
|
@@ -32,11 +32,12 @@ function sharedWithinPass(load, keyOf = (value) => value) {
|
|
|
32
32
|
// The checks of one publish or 30-second pass. Identical socket requests share
|
|
33
33
|
// one authentication (the auth service sees only the request), and sockets of
|
|
34
34
|
// one actor share its contributed rooms. Revalidation asks only who is signed
|
|
35
|
-
// in, so the provider reads the app profile instead of synchronizing it
|
|
35
|
+
// in, so the provider reads the app profile instead of synchronizing it, and
|
|
36
|
+
// never refreshes a session the socket could not store.
|
|
36
37
|
function createPassChecks(authService, audiences) {
|
|
37
38
|
return {
|
|
38
39
|
authenticateRequest: sharedWithinPass(
|
|
39
|
-
(request) => authService.authenticateRequest(request, { syncProfile: false }),
|
|
40
|
+
(request) => authService.authenticateRequest(request, { syncProfile: false, refreshSession: false }),
|
|
40
41
|
JSON.stringify
|
|
41
42
|
),
|
|
42
43
|
audiences: audiences && { resolveActorRooms: sharedWithinPass((actorId) => audiences.resolveActorRooms(actorId)) }
|
|
@@ -14,18 +14,24 @@ const arrival = (emitter, name) => once(emitter, name, { signal: AbortSignal.tim
|
|
|
14
14
|
|
|
15
15
|
// Real sockets whose session cookies name their actors. `checks` lists each
|
|
16
16
|
// authentication's session cookie, so a test sees which sockets were checked,
|
|
17
|
-
//
|
|
18
|
-
|
|
17
|
+
// `profileSyncs` those that asked the provider to sync the profile, and
|
|
18
|
+
// `sessionRefreshes` those that let it refresh the session. Sessions in
|
|
19
|
+
// `expired` answer that they need a refresh.
|
|
20
|
+
async function signedInSockets(t, { audiences = null, requireAuthentication = true } = {}) {
|
|
19
21
|
const httpServer = createServer();
|
|
20
22
|
const io = createSocketIoServer({ httpServer });
|
|
21
23
|
const sessions = new Map();
|
|
24
|
+
const expired = new Set();
|
|
22
25
|
const checks = [];
|
|
23
26
|
const profileSyncs = [];
|
|
27
|
+
const sessionRefreshes = [];
|
|
24
28
|
const authService = {
|
|
25
|
-
realtime: { requireAuthentication
|
|
26
|
-
async authenticateRequest(request, { syncProfile = true } = {}) {
|
|
29
|
+
realtime: { requireAuthentication },
|
|
30
|
+
async authenticateRequest(request, { syncProfile = true, refreshSession = true } = {}) {
|
|
27
31
|
checks.push(request.cookies.session);
|
|
28
32
|
if (syncProfile) profileSyncs.push(request.cookies.session);
|
|
33
|
+
if (refreshSession) sessionRefreshes.push(request.cookies.session);
|
|
34
|
+
if (expired.has(request.cookies.session)) return { authenticated: false, refreshRequired: true };
|
|
29
35
|
const id = sessions.get(request.cookies.session);
|
|
30
36
|
return { authenticated: Boolean(id), actor: id ? { id } : null };
|
|
31
37
|
}
|
|
@@ -44,9 +50,12 @@ async function signedInSockets(t, { audiences = null } = {}) {
|
|
|
44
50
|
const url = `http://127.0.0.1:${httpServer.address().port}`;
|
|
45
51
|
return {
|
|
46
52
|
checks,
|
|
53
|
+
expired,
|
|
47
54
|
profileSyncs,
|
|
55
|
+
sessionRefreshes,
|
|
48
56
|
sessions,
|
|
49
57
|
io,
|
|
58
|
+
url,
|
|
50
59
|
publish: (audience, name = "item.changed") => delivery.handle({
|
|
51
60
|
type: "entity.changed", realtime: { audience, event: name, payload: { name } }
|
|
52
61
|
}),
|
|
@@ -244,6 +253,30 @@ test("revalidation never syncs profiles, and one actor's logins share a room loo
|
|
|
244
253
|
assert.equal(roomLookups, 1, "Both logins are Alice, so one publish looks up her rooms once");
|
|
245
254
|
});
|
|
246
255
|
|
|
256
|
+
test("a login whose session needs refreshing is dropped and refused until the client refreshes", async (t) => {
|
|
257
|
+
const f = await signedInSockets(t, { requireAuthentication: false });
|
|
258
|
+
f.sessions.set("alice", "1");
|
|
259
|
+
const alice = await f.connect("alice");
|
|
260
|
+
|
|
261
|
+
f.expired.add("alice");
|
|
262
|
+
const disconnected = arrival(alice.client, "disconnect");
|
|
263
|
+
await f.publish({ userId: 1 });
|
|
264
|
+
assert.equal((await disconnected)[0], "io server disconnect");
|
|
265
|
+
assert.equal(alice.received.length, 0);
|
|
266
|
+
|
|
267
|
+
// Even with sign-in optional, the handshake refuses instead of connecting
|
|
268
|
+
// without Alice's rooms, so the client refreshes and reconnects.
|
|
269
|
+
const again = connect(f.url, { transports: ["websocket"], extraHeaders: { Cookie: "session=alice" }, reconnection: false });
|
|
270
|
+
t.after(() => again.disconnect());
|
|
271
|
+
const [refused] = await arrival(again, "connect_error");
|
|
272
|
+
assert.equal(refused.data.code, "SESSION_REFRESH_REQUIRED");
|
|
273
|
+
|
|
274
|
+
f.expired.delete("alice");
|
|
275
|
+
again.connect();
|
|
276
|
+
await arrival(again, "connect");
|
|
277
|
+
assert.deepEqual(f.sessionRefreshes, [], "A socket never lets the provider refresh a session it cannot store");
|
|
278
|
+
});
|
|
279
|
+
|
|
247
280
|
test("idle socket sessions are revalidated without an application event, once per login", async (t) => {
|
|
248
281
|
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
249
282
|
const tab = () => ({ data: { actorId: "1" }, handshake: {}, disconnect() { this.connected = false; }, connected: true });
|
|
@@ -265,7 +298,7 @@ test("idle socket sessions are revalidated without an application event, once pe
|
|
|
265
298
|
await new Promise((resolve) => setImmediate(resolve));
|
|
266
299
|
assert.deepEqual(sockets.map((socket) => socket.connected), [false, false]);
|
|
267
300
|
assert.equal(checks, 1, "Identical handshakes share one check per pass");
|
|
268
|
-
assert.deepEqual(options, { syncProfile: false });
|
|
301
|
+
assert.deepEqual(options, { syncProfile: false, refreshSession: false });
|
|
269
302
|
});
|
|
270
303
|
|
|
271
304
|
test("delivery failures never reject a committed mutation and room unions emit once", async () => {
|
|
@@ -117,6 +117,27 @@ test("server disconnect recovery backs off middleware rejection and resets after
|
|
|
117
117
|
assert.equal(socket.connect.mock.callCount(), 8);
|
|
118
118
|
});
|
|
119
119
|
|
|
120
|
+
test("recovery runs its prepare step, such as a session refresh, before reconnecting", async (t) => {
|
|
121
|
+
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
122
|
+
const socket = Object.assign(new EventEmitter(), {
|
|
123
|
+
active: false,
|
|
124
|
+
connected: false,
|
|
125
|
+
connect: t.mock.fn(),
|
|
126
|
+
io: { reconnection: () => true }
|
|
127
|
+
});
|
|
128
|
+
let finishPreparing;
|
|
129
|
+
const prepareReconnect = t.mock.fn(() => new Promise((resolve) => { finishPreparing = resolve; }));
|
|
130
|
+
t.after(attachSocketConnectionRecovery(socket, { prepareReconnect }));
|
|
131
|
+
|
|
132
|
+
socket.emit("connect_error", new Error("Session refresh required."));
|
|
133
|
+
t.mock.timers.tick(1_000);
|
|
134
|
+
assert.equal(prepareReconnect.mock.callCount(), 1);
|
|
135
|
+
assert.equal(socket.connect.mock.callCount(), 0, "The handshake waits for the refreshed session");
|
|
136
|
+
finishPreparing();
|
|
137
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
138
|
+
assert.equal(socket.connect.mock.callCount(), 1);
|
|
139
|
+
});
|
|
140
|
+
|
|
120
141
|
test("recovery leaves transport retries and intentional disconnects to Socket.IO", (t) => {
|
|
121
142
|
const { socket, detach } = recoverySocket(t);
|
|
122
143
|
socket.active = true;
|
|
@@ -347,9 +347,13 @@ test("socket audience bootstrap authenticates explicitly and joins contributed s
|
|
|
347
347
|
}
|
|
348
348
|
});
|
|
349
349
|
let connectionHandler = null;
|
|
350
|
+
let authenticationMiddleware = null;
|
|
350
351
|
const io = {
|
|
351
352
|
on(eventName, handler) {
|
|
352
353
|
if (eventName === "connection") connectionHandler = handler;
|
|
354
|
+
},
|
|
355
|
+
use(handler) {
|
|
356
|
+
authenticationMiddleware = handler;
|
|
353
357
|
}
|
|
354
358
|
};
|
|
355
359
|
const authenticateCalls = [];
|
|
@@ -374,6 +378,9 @@ test("socket audience bootstrap authenticates explicitly and joins contributed s
|
|
|
374
378
|
data: {},
|
|
375
379
|
join(room) { joinedRooms.push(room); }
|
|
376
380
|
};
|
|
381
|
+
const handshakeErrors = [];
|
|
382
|
+
await authenticationMiddleware(socket, (error) => handshakeErrors.push(error));
|
|
383
|
+
assert.deepEqual(handshakeErrors, [undefined]);
|
|
377
384
|
await connectionHandler(socket);
|
|
378
385
|
assert.deepEqual(authenticateCalls, [{
|
|
379
386
|
cookies: { session: "abc123", theme: "dark" },
|
|
@@ -516,7 +523,9 @@ async function startRealtimeClient({ mobile = null } = {}) {
|
|
|
516
523
|
|
|
517
524
|
test("RealtimeClientProvider publishes one explicit client capability", async () => {
|
|
518
525
|
const fixture = await startRealtimeClient();
|
|
519
|
-
assert.deepEqual(Object.keys(fixture.realtime).sort(), [
|
|
526
|
+
assert.deepEqual(Object.keys(fixture.realtime).sort(), [
|
|
527
|
+
"config", "dispose", "initialize", "onServedClientBuild", "setBeforeReconnect", "socket"
|
|
528
|
+
]);
|
|
520
529
|
assert.equal(fixture.realtime.config.url, "");
|
|
521
530
|
assert.equal(fixture.registrations.has("realtime.web.connection.indicator"), true);
|
|
522
531
|
assert.equal(
|