@jskit-ai/realtime 0.2.53 → 0.2.54
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/PATTERN.md +5 -1
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/server/realtimeAudience.js +50 -2
- package/src/server/realtimeDelivery.js +12 -4
- package/test/authorization.test.js +48 -2
- package/test/i18nCatalog.test.js +3 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/realtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.54",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"socket.io-client": "^4.8.3"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"@jskit-ai/kernel": "0.2.
|
|
27
|
+
"@jskit-ai/kernel": "0.2.34",
|
|
28
28
|
"vue": "^3.5.13"
|
|
29
29
|
},
|
|
30
30
|
"description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
|
|
@@ -74,7 +74,11 @@ so the next handshake resolves the new actor.
|
|
|
74
74
|
Use `auth.service.realtime.authorizeEvent({ actor, event: { name, payload } })`
|
|
75
75
|
for resource-specific read authorization. Return `true` only when the current
|
|
76
76
|
actor can read that event's resource. Authentication is revalidated before
|
|
77
|
-
delivery and every 30 seconds while idle.
|
|
77
|
+
delivery and every 30 seconds while idle. A service that can tell when a login
|
|
78
|
+
ends offers `realtime.holdSocket(request, close)`: realtime holds each signed-in
|
|
79
|
+
socket with it, the service calls `close` the moment that login ends, and the
|
|
80
|
+
socket is then authenticated at its handshake and every 30 seconds instead of
|
|
81
|
+
before every delivery (`authorizeEvent` still answers each one). Redis peers perform the same checks
|
|
78
82
|
locally. Realtime failures are logged without failing an already-successful
|
|
79
83
|
mutation; one mutation owner publishes each completion, while progress events
|
|
80
84
|
describe distinct lifecycle states.
|
|
@@ -448,6 +448,36 @@ function rememberSocketActorId(socket, actorId) {
|
|
|
448
448
|
socket.data.actorId = actorId;
|
|
449
449
|
}
|
|
450
450
|
|
|
451
|
+
// The socket's own keys, never sent with socket.data: the actor its handshake resolved, for its connection to hold,
|
|
452
|
+
// and the actor a held socket last authenticated as. An auth service whose realtime.holdSocket(request, close) closes
|
|
453
|
+
// a socket the moment its login ends has that socket authenticated at its handshake and by the 30-second pass, not
|
|
454
|
+
// before every event: a publish otherwise authenticated each receiving login again, which a streaming reply does up
|
|
455
|
+
// to 40 times a second.
|
|
456
|
+
const HANDSHAKE_ACTOR = Symbol("jskit.realtime.handshakeActor");
|
|
457
|
+
const HELD_ACTOR = Symbol("jskit.realtime.heldActor");
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Holds a signed-in socket with its auth service until its login ends, so deliveries reuse its actor.
|
|
461
|
+
* @param {import("socket.io").Socket} socket
|
|
462
|
+
* @param {object} actor
|
|
463
|
+
* @param {NonNullable<import("@jskit-ai/auth-core/server/types").AuthRealtimePolicy["holdSocket"]>} holdSocket
|
|
464
|
+
* @param {RuntimeLogger} logger
|
|
465
|
+
*/
|
|
466
|
+
function holdUntilLoginEnds(socket, actor, holdSocket, logger) {
|
|
467
|
+
let release;
|
|
468
|
+
try {
|
|
469
|
+
release = holdSocket(createSocketRequest(socket), () => socket.disconnect(true));
|
|
470
|
+
// readable-check: allow method-probe - input validation: an auth service's hold answers its release
|
|
471
|
+
if (typeof release !== "function") throw new TypeError("Realtime holdSocket must return a release function.");
|
|
472
|
+
} catch (error) {
|
|
473
|
+
logger.warn({ error: String(error?.message || error) }, "Realtime socket hold failed.");
|
|
474
|
+
socket.disconnect(true);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
socket.once("disconnect", () => release());
|
|
478
|
+
if (socket.connected) socket[HELD_ACTOR] = actor;
|
|
479
|
+
}
|
|
480
|
+
|
|
451
481
|
/**
|
|
452
482
|
* Every handshake is authenticated here. A login that needs a session refresh
|
|
453
483
|
* is refused even when sign-in is optional, so the client refreshes and
|
|
@@ -471,7 +501,10 @@ function registerSocketAuthentication({ io, logger, authService }) {
|
|
|
471
501
|
next(authenticationRequiredError());
|
|
472
502
|
return;
|
|
473
503
|
}
|
|
474
|
-
if (actor)
|
|
504
|
+
if (actor) {
|
|
505
|
+
rememberSocketActorId(socket, actor.id);
|
|
506
|
+
socket[HANDSHAKE_ACTOR] = actor;
|
|
507
|
+
}
|
|
475
508
|
next();
|
|
476
509
|
} catch (error) {
|
|
477
510
|
logger.warn({ error: String(error?.message || error) }, "Realtime socket authentication failed.");
|
|
@@ -503,11 +536,19 @@ async function joinContributedRooms(socket, actorId, audiences) {
|
|
|
503
536
|
*/
|
|
504
537
|
function registerSocketAudienceBootstrap({ io, logger, authService, audiences }) {
|
|
505
538
|
registerSocketAuthentication({ io, logger, authService });
|
|
539
|
+
const holdSocket = authService?.realtime?.holdSocket ?? null;
|
|
540
|
+
// readable-check: allow method-probe - input validation: an auth provider's realtime policy may name holdSocket()
|
|
541
|
+
if (holdSocket !== null && typeof holdSocket !== "function") {
|
|
542
|
+
throw new TypeError("Realtime holdSocket must be a function.");
|
|
543
|
+
}
|
|
506
544
|
io.on("connection", async (socket) => {
|
|
507
545
|
try {
|
|
508
546
|
socket.join(ALL_CLIENTS_ROOM);
|
|
509
547
|
const actorId = normalizeRecordId(socket.data.actorId, { fallback: null });
|
|
510
548
|
if (!actorId) return;
|
|
549
|
+
const actor = socket[HANDSHAKE_ACTOR];
|
|
550
|
+
delete socket[HANDSHAKE_ACTOR];
|
|
551
|
+
if (holdSocket && actor) holdUntilLoginEnds(socket, actor, holdSocket, logger);
|
|
511
552
|
socket.join(ALL_USERS_ROOM);
|
|
512
553
|
socket.join(roomForUser(actorId));
|
|
513
554
|
await joinContributedRooms(socket, actorId, audiences);
|
|
@@ -524,8 +565,14 @@ function registerSocketAudienceBootstrap({ io, logger, authService, audiences })
|
|
|
524
565
|
* @param {{ resolveActorRooms: ActorRoomsResolver }} options.audiences
|
|
525
566
|
* @param {object} [options.request]
|
|
526
567
|
* @param {Parameters<typeof resolveSocketAuthentication>[3]} [options.authenticateRequest]
|
|
568
|
+
* @param {boolean} [options.reuseHeld] A held socket keeps the actor it last authenticated as (a delivery's check).
|
|
527
569
|
*/
|
|
528
|
-
async function revalidateSocket({ socket, authService, audiences, request, authenticateRequest }) {
|
|
570
|
+
async function revalidateSocket({ socket, authService, audiences, request, authenticateRequest, reuseHeld = false }) {
|
|
571
|
+
const held = reuseHeld ? socket[HELD_ACTOR] : undefined;
|
|
572
|
+
if (held) {
|
|
573
|
+
await joinContributedRooms(socket, held.id, audiences);
|
|
574
|
+
return held;
|
|
575
|
+
}
|
|
529
576
|
const { actor, refreshRequired } = await resolveSocketAuthentication(authService, socket, request, authenticateRequest);
|
|
530
577
|
const previousActorId = socket.data.actorId;
|
|
531
578
|
if (refreshRequired || (!actor && realtimeAuthenticationRequired(authService)) ||
|
|
@@ -536,6 +583,7 @@ async function revalidateSocket({ socket, authService, audiences, request, authe
|
|
|
536
583
|
if (!actor) return null;
|
|
537
584
|
|
|
538
585
|
rememberSocketActorId(socket, actor.id);
|
|
586
|
+
if (socket[HELD_ACTOR]) socket[HELD_ACTOR] = actor;
|
|
539
587
|
await joinContributedRooms(socket, actor.id, audiences);
|
|
540
588
|
return actor;
|
|
541
589
|
}
|
|
@@ -97,7 +97,8 @@ function rememberedActorId(socket) {
|
|
|
97
97
|
* audience's audienceUsers reads in; absent when no feature provides `realtime.audience-scope`.
|
|
98
98
|
*/
|
|
99
99
|
function createRealtimeDelivery({ io, logger, authService, audiences: { mayContribute, resolveActorsRooms }, audienceScope }) {
|
|
100
|
-
// With an auth.service, each socket is revalidated before it receives an event
|
|
100
|
+
// With an auth.service, each socket is revalidated before it receives an event, except one the service holds until
|
|
101
|
+
// its login ends (realtime.holdSocket), which keeps the actor its handshake or the 30-second pass authenticated;
|
|
101
102
|
// without one, events go straight to their rooms.
|
|
102
103
|
const guarded = Boolean(authService);
|
|
103
104
|
const authorizeEvent = authService?.realtime?.authorizeEvent ?? null;
|
|
@@ -109,13 +110,20 @@ function createRealtimeDelivery({ io, logger, authService, audiences: { mayContr
|
|
|
109
110
|
let revalidationTimer = null;
|
|
110
111
|
let stopped = false;
|
|
111
112
|
|
|
112
|
-
|
|
113
|
+
/**
|
|
114
|
+
* @param {import("socket.io").Socket} socket
|
|
115
|
+
* @param {ReturnType<typeof createPassChecks>} checks
|
|
116
|
+
* @param {{ reuseHeld?: boolean }} [options] A delivery reuses the actor of a socket its auth service holds until
|
|
117
|
+
* its login ends; the 30-second pass authenticates every socket.
|
|
118
|
+
*/
|
|
119
|
+
async function revalidate(socket, checks, { reuseHeld = false } = {}) {
|
|
113
120
|
try {
|
|
114
121
|
return await revalidateSocket({
|
|
115
122
|
socket,
|
|
116
123
|
authService,
|
|
117
124
|
audiences: checks.audiences,
|
|
118
|
-
authenticateRequest: checks.authenticateRequest
|
|
125
|
+
authenticateRequest: checks.authenticateRequest,
|
|
126
|
+
reuseHeld
|
|
119
127
|
});
|
|
120
128
|
} catch (error) {
|
|
121
129
|
socket.disconnect(true);
|
|
@@ -169,7 +177,7 @@ function createRealtimeDelivery({ io, logger, authService, audiences: { mayContr
|
|
|
169
177
|
checks.lookUpActorsRooms(candidates.map(rememberedActorId).filter(Boolean));
|
|
170
178
|
await Promise.all(candidates.map(async (socket) => {
|
|
171
179
|
try {
|
|
172
|
-
const actor = await revalidate(socket, checks);
|
|
180
|
+
const actor = await revalidate(socket, checks, { reuseHeld: true });
|
|
173
181
|
if (!socket.connected) return;
|
|
174
182
|
if (!targets.broadcastAllClients && !targets.rooms.some((room) => socket.rooms.has(room))) return;
|
|
175
183
|
if (authorizeEvent) {
|
|
@@ -20,7 +20,7 @@ const scopesByActor = (actorIds, scopesOf) => new Map(actorIds.map((actorId) =>
|
|
|
20
20
|
// `profileSyncs` those that asked the provider to sync the profile, and
|
|
21
21
|
// `sessionRefreshes` those that let it refresh the session. Sessions in
|
|
22
22
|
// `expired` answer that they need a refresh.
|
|
23
|
-
async function signedInSockets(t, { audiences = createAudienceContributors(), requireAuthentication = true } = {}) {
|
|
23
|
+
async function signedInSockets(t, { audiences = createAudienceContributors(), requireAuthentication = true, realtime = {} } = {}) {
|
|
24
24
|
const httpServer = createServer();
|
|
25
25
|
const io = createSocketIoServer({ httpServer });
|
|
26
26
|
const sessions = new Map();
|
|
@@ -29,7 +29,7 @@ async function signedInSockets(t, { audiences = createAudienceContributors(), re
|
|
|
29
29
|
const profileSyncs = [];
|
|
30
30
|
const sessionRefreshes = [];
|
|
31
31
|
const authService = {
|
|
32
|
-
realtime: { requireAuthentication },
|
|
32
|
+
realtime: { requireAuthentication, ...realtime },
|
|
33
33
|
async authenticateRequest(request, { syncProfile = true, refreshSession = true } = {}) {
|
|
34
34
|
checks.push(request.cookies.session);
|
|
35
35
|
if (syncProfile) profileSyncs.push(request.cookies.session);
|
|
@@ -97,6 +97,9 @@ test("invalid authorization configuration fails closed at startup", () => {
|
|
|
97
97
|
authenticateRequest() {}, realtime: { authorizeEvent: true }
|
|
98
98
|
} }), /authorizeEvent must be a function/u);
|
|
99
99
|
assert.throws(() => createRealtimeDelivery({ io, logger, authService: null }), /mayContribute/u);
|
|
100
|
+
assert.throws(() => registerSocketAudienceBootstrap({ io: { use() {}, on() {} }, logger, audiences, authService: {
|
|
101
|
+
authenticateRequest() {}, realtime: { holdSocket: true }
|
|
102
|
+
} }), /holdSocket must be a function/u);
|
|
100
103
|
});
|
|
101
104
|
|
|
102
105
|
test("real sockets authorize each conversation delivery and disconnect a revoked session", async (t) => {
|
|
@@ -182,6 +185,49 @@ test("guarded delivery checks only the sockets that can receive an event, once p
|
|
|
182
185
|
assert.equal(aliceTab.received.length + aliceOtherTab.received.length, received);
|
|
183
186
|
});
|
|
184
187
|
|
|
188
|
+
test("a socket its auth service holds until its login ends is authenticated at its handshake, not once per publish", async (t) => {
|
|
189
|
+
// The service's holds: each login's close callbacks, as a session store holding connections keeps them.
|
|
190
|
+
const holds = new Map();
|
|
191
|
+
const authorized = [];
|
|
192
|
+
const f = await signedInSockets(t, { realtime: {
|
|
193
|
+
holdSocket(request, close) {
|
|
194
|
+
const session = request.cookies.session;
|
|
195
|
+
holds.set(session, [...(holds.get(session) || []), close]);
|
|
196
|
+
return () => holds.set(session, (holds.get(session) || []).filter((held) => held !== close));
|
|
197
|
+
},
|
|
198
|
+
authorizeEvent({ actor }) {
|
|
199
|
+
authorized.push(actor.id);
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
} });
|
|
203
|
+
f.sessions.set("alice", "1").set("bob", "2");
|
|
204
|
+
const [aliceTab, aliceOtherTab] = [await f.connect("alice"), await f.connect("alice")];
|
|
205
|
+
const bob = await f.connect("bob");
|
|
206
|
+
|
|
207
|
+
async function checksFor(publishes) {
|
|
208
|
+
f.checks.length = 0;
|
|
209
|
+
authorized.length = 0;
|
|
210
|
+
for (let index = 0; index < publishes; index += 1) await f.publish({ userId: 1 });
|
|
211
|
+
await afterMarker(f, 1, aliceTab.client, aliceOtherTab.client);
|
|
212
|
+
return { checks: f.checks.length, authorized: authorized.length };
|
|
213
|
+
}
|
|
214
|
+
const one = await checksFor(1);
|
|
215
|
+
const many = await checksFor(20);
|
|
216
|
+
assert.equal(many.checks, one.checks, `20 publishes authenticated ${many.checks} times, 1 publish ${one.checks}`);
|
|
217
|
+
assert.equal(one.checks, 0);
|
|
218
|
+
assert.equal(many.authorized, 2 * 21, "Each delivery is still authorized, with the held actor");
|
|
219
|
+
assert.equal(aliceTab.received.length, 21);
|
|
220
|
+
assert.equal(holds.get("alice").length, 2);
|
|
221
|
+
|
|
222
|
+
// The login ending closes its sockets at once, with no publish, and leaves other logins connected.
|
|
223
|
+
const disconnected = [arrival(aliceTab.client, "disconnect"), arrival(aliceOtherTab.client, "disconnect")];
|
|
224
|
+
for (const close of holds.get("alice")) close();
|
|
225
|
+
await Promise.all(disconnected);
|
|
226
|
+
assert.deepEqual(holds.get("alice"), [], "A disconnected socket releases its hold");
|
|
227
|
+
await afterMarker(f, 2, bob.client);
|
|
228
|
+
assert.equal(bob.client.connected, true);
|
|
229
|
+
});
|
|
230
|
+
|
|
185
231
|
test("membership changes and revoked logins take effect on the very next publish", async (t) => {
|
|
186
232
|
const memberships = new Map([["1", [7]], ["2", []]]);
|
|
187
233
|
const audiences = createAudienceContributors();
|
package/test/i18nCatalog.test.js
CHANGED
|
@@ -11,8 +11,9 @@ test("realtime English catalog matches its source", () => {
|
|
|
11
11
|
const { problems } = evaluateI18nCatalogContract({
|
|
12
12
|
repoRoot: REPO_ROOT,
|
|
13
13
|
packageDir: path.join(REPO_ROOT, "packages", "realtime"),
|
|
14
|
-
// The client socket's injection key
|
|
15
|
-
|
|
14
|
+
// The client socket's injection key and the server socket's two Symbol keys (realtimeAudience.js) share the
|
|
15
|
+
// jskit.realtime prefix but are not message keys.
|
|
16
|
+
nonMessageLiterals: ["jskit.realtime.runtime.client.socket", "jskit.realtime.handshakeActor", "jskit.realtime.heldActor"]
|
|
16
17
|
});
|
|
17
18
|
assert.deepEqual(problems, []);
|
|
18
19
|
});
|