@jskit-ai/realtime 0.2.3 → 0.2.4

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/realtime",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/realtime": "0.2.3",
5
+ "@jskit-ai/realtime": "0.2.4",
6
6
  "@jskit-ai/shell-web": "0.2.1"
7
7
  }
8
8
  }
@@ -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
- function attachSocketConnectionRecovery(socket) {
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()) socket.connect();
38
+ if (canRetry()) void retry();
26
39
  }, delay);
27
40
  delay = Math.min(delay * 2, 30_000);
28
41
  }
@@ -238,13 +238,16 @@ function createSocketRequest(socket) {
238
238
  return request;
239
239
  }
240
240
 
241
- async function resolveSocketActor(authService, socket, request = createSocketRequest(socket),
242
- authenticateRequest = (value) => authService.authenticateRequest(value)) {
243
- if (typeof authService?.authenticateRequest !== "function") return null;
241
+ // A socket cannot store a refreshed session, so its checks never refresh one.
242
+ // A provider that would have to (its access token expired) answers
243
+ // `refreshRequired`, and the client refreshes over HTTP before reconnecting.
244
+ async function resolveSocketAuthentication(authService, socket, request = createSocketRequest(socket),
245
+ authenticateRequest = (value) => authService.authenticateRequest(value, { refreshSession: false })) {
246
+ if (typeof authService?.authenticateRequest !== "function") return { actor: null, refreshRequired: false };
244
247
  const result = await authenticateRequest(request);
245
248
  const id = result?.authenticated === true
246
249
  ? normalizeRecordId(result?.actor?.id, { fallback: null }) : null;
247
- return id ? { ...result.actor, id } : null;
250
+ return { actor: id ? { ...result.actor, id } : null, refreshRequired: result?.refreshRequired === true };
248
251
  }
249
252
 
250
253
  function realtimeAuthenticationRequired(authService = null) {
@@ -257,28 +260,42 @@ function authenticationRequiredError() {
257
260
  return error;
258
261
  }
259
262
 
263
+ function sessionRefreshRequiredError() {
264
+ const error = new Error("Session refresh required.");
265
+ error.data = Object.freeze({ code: "SESSION_REFRESH_REQUIRED" });
266
+ return error;
267
+ }
268
+
260
269
  function rememberSocketActorId(socket, actorId) {
261
270
  socket.data = socket.data && typeof socket.data === "object" ? socket.data : {};
262
271
  socket.data.actorId = actorId;
263
272
  }
264
273
 
265
- function registerRequiredSocketAuthentication({ io, logger, authService }) {
266
- if (!realtimeAuthenticationRequired(authService)) return;
274
+ // Every handshake is authenticated here. A login that needs a session refresh
275
+ // is refused even when sign-in is optional, so the client refreshes and
276
+ // reconnects instead of silently connecting without its user's rooms.
277
+ function registerSocketAuthentication({ io, logger, authService }) {
278
+ const required = realtimeAuthenticationRequired(authService);
279
+ if (!required && typeof authService?.authenticateRequest !== "function") return;
267
280
  if (typeof io?.use !== "function") {
268
- throw new TypeError("Realtime authenticated-client mode requires Socket.IO middleware support.");
281
+ throw new TypeError("Realtime socket authentication requires Socket.IO middleware support.");
269
282
  }
270
283
  io.use(async (socket, next) => {
271
284
  try {
272
- const actorId = (await resolveSocketActor(authService, socket))?.id;
273
- if (!actorId) {
285
+ const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket);
286
+ if (refreshRequired) {
287
+ next(sessionRefreshRequiredError());
288
+ return;
289
+ }
290
+ if (!actor && required) {
274
291
  next(authenticationRequiredError());
275
292
  return;
276
293
  }
277
- rememberSocketActorId(socket, actorId);
294
+ if (actor) rememberSocketActorId(socket, actor.id);
278
295
  next();
279
296
  } catch (error) {
280
297
  logger.warn({ error: String(error?.message || error) }, "Realtime socket authentication failed.");
281
- next(authenticationRequiredError());
298
+ next(required ? authenticationRequiredError() : undefined);
282
299
  }
283
300
  });
284
301
  }
@@ -294,14 +311,12 @@ async function joinContributedRooms(socket, actorId, audiences) {
294
311
 
295
312
  function registerSocketAudienceBootstrap({ io, logger, authService = null, audiences = null }) {
296
313
  if (typeof io?.on !== "function") return;
297
- registerRequiredSocketAuthentication({ io, logger, authService });
314
+ registerSocketAuthentication({ io, logger, authService });
298
315
  io.on("connection", async (socket) => {
299
316
  try {
300
317
  socket.join(ALL_CLIENTS_ROOM);
301
- const actorId = normalizeRecordId(socket?.data?.actorId, { fallback: null })
302
- || (await resolveSocketActor(authService, socket))?.id;
318
+ const actorId = normalizeRecordId(socket?.data?.actorId, { fallback: null });
303
319
  if (!actorId) return;
304
- rememberSocketActorId(socket, actorId);
305
320
  socket.join(ALL_USERS_ROOM);
306
321
  socket.join(roomForUser(actorId));
307
322
  await joinContributedRooms(socket, actorId, audiences);
@@ -312,9 +327,9 @@ function registerSocketAudienceBootstrap({ io, logger, authService = null, audie
312
327
  }
313
328
 
314
329
  async function revalidateSocket({ socket, authService, audiences = null, request, authenticateRequest }) {
315
- const actor = await resolveSocketActor(authService, socket, request, authenticateRequest);
330
+ const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket, request, authenticateRequest);
316
331
  const previousActorId = socket.data?.actorId;
317
- if ((!actor && realtimeAuthenticationRequired(authService)) ||
332
+ if (refreshRequired || (!actor && realtimeAuthenticationRequired(authService)) ||
318
333
  (previousActorId && previousActorId !== actor?.id)) {
319
334
  socket.disconnect(true);
320
335
  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
- // and `profileSyncs` those that asked the provider to sync the profile.
18
- async function signedInSockets(t, { audiences = null } = {}) {
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: true },
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(), ["config", "dispose", "initialize", "onServedClientBuild", "socket"]);
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(