@jskit-ai/realtime 0.2.1 → 0.2.3
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
|
@@ -53,6 +53,11 @@ 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
|
+
|
|
56
61
|
// Packages that know which scopes an actor belongs to (for example workspace
|
|
57
62
|
// memberships) contribute them here; realtime only turns scopes into rooms.
|
|
58
63
|
function createAudienceContributors() {
|
|
@@ -69,6 +74,10 @@ function createAudienceContributors() {
|
|
|
69
74
|
}
|
|
70
75
|
contributors.set(contributorId, resolveActorScopes);
|
|
71
76
|
},
|
|
77
|
+
// Whether revalidation could make a socket join this room.
|
|
78
|
+
mayContribute(room) {
|
|
79
|
+
return contributors.size > 0 && isScopeRoom(room);
|
|
80
|
+
},
|
|
72
81
|
async resolveActorRooms(actorId) {
|
|
73
82
|
const rooms = new Set();
|
|
74
83
|
for (const resolveActorScopes of contributors.values()) {
|
|
@@ -229,9 +238,10 @@ function createSocketRequest(socket) {
|
|
|
229
238
|
return request;
|
|
230
239
|
}
|
|
231
240
|
|
|
232
|
-
async function resolveSocketActor(authService, socket, request = createSocketRequest(socket)
|
|
241
|
+
async function resolveSocketActor(authService, socket, request = createSocketRequest(socket),
|
|
242
|
+
authenticateRequest = (value) => authService.authenticateRequest(value)) {
|
|
233
243
|
if (typeof authService?.authenticateRequest !== "function") return null;
|
|
234
|
-
const result = await
|
|
244
|
+
const result = await authenticateRequest(request);
|
|
235
245
|
const id = result?.authenticated === true
|
|
236
246
|
? normalizeRecordId(result?.actor?.id, { fallback: null }) : null;
|
|
237
247
|
return id ? { ...result.actor, id } : null;
|
|
@@ -301,8 +311,8 @@ function registerSocketAudienceBootstrap({ io, logger, authService = null, audie
|
|
|
301
311
|
});
|
|
302
312
|
}
|
|
303
313
|
|
|
304
|
-
async function revalidateSocket({ socket, authService, audiences = null, request }) {
|
|
305
|
-
const actor = await resolveSocketActor(authService, socket, request);
|
|
314
|
+
async function revalidateSocket({ socket, authService, audiences = null, request, authenticateRequest }) {
|
|
315
|
+
const actor = await resolveSocketActor(authService, socket, request, authenticateRequest);
|
|
306
316
|
const previousActorId = socket.data?.actorId;
|
|
307
317
|
if ((!actor && realtimeAuthenticationRequired(authService)) ||
|
|
308
318
|
(previousActorId && previousActorId !== actor?.id)) {
|
|
@@ -19,6 +19,30 @@ function publicRealtimePayload(event) {
|
|
|
19
19
|
return Object.freeze({ ...(payload || {}), ...canonical });
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
// One answer per question within one pass.
|
|
23
|
+
function sharedWithinPass(load, keyOf = (value) => value) {
|
|
24
|
+
const answers = new Map();
|
|
25
|
+
return (value) => {
|
|
26
|
+
const key = keyOf(value);
|
|
27
|
+
if (!answers.has(key)) answers.set(key, (async () => load(value))());
|
|
28
|
+
return answers.get(key);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The checks of one publish or 30-second pass. Identical socket requests share
|
|
33
|
+
// one authentication (the auth service sees only the request), and sockets of
|
|
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.
|
|
36
|
+
function createPassChecks(authService, audiences) {
|
|
37
|
+
return {
|
|
38
|
+
authenticateRequest: sharedWithinPass(
|
|
39
|
+
(request) => authService.authenticateRequest(request, { syncProfile: false }),
|
|
40
|
+
JSON.stringify
|
|
41
|
+
),
|
|
42
|
+
audiences: audiences && { resolveActorRooms: sharedWithinPass((actorId) => audiences.resolveActorRooms(actorId)) }
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
22
46
|
function createRealtimeDelivery({ io, database = null, logger, authService = null, audiences = null }) {
|
|
23
47
|
if (!io || typeof io.emit !== "function" || typeof io.to !== "function") {
|
|
24
48
|
throw new TypeError("Realtime delivery requires a Socket.IO server.");
|
|
@@ -38,9 +62,14 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
38
62
|
let revalidationTimer = null;
|
|
39
63
|
let stopped = false;
|
|
40
64
|
|
|
41
|
-
async function revalidate(socket) {
|
|
65
|
+
async function revalidate(socket, checks) {
|
|
42
66
|
try {
|
|
43
|
-
return await revalidateSocket({
|
|
67
|
+
return await revalidateSocket({
|
|
68
|
+
socket,
|
|
69
|
+
authService,
|
|
70
|
+
audiences: checks.audiences,
|
|
71
|
+
authenticateRequest: checks.authenticateRequest
|
|
72
|
+
});
|
|
44
73
|
} catch (error) {
|
|
45
74
|
socket.disconnect(true);
|
|
46
75
|
logger.warn({ error: String(error?.message || error) }, "Realtime socket revalidation failed.");
|
|
@@ -48,10 +77,19 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
48
77
|
}
|
|
49
78
|
}
|
|
50
79
|
|
|
80
|
+
// A socket outside every target room can enter one only by revalidation
|
|
81
|
+
// joining a contributed room; otherwise checking it cannot change delivery.
|
|
82
|
+
function candidateSockets(targets) {
|
|
83
|
+
const sockets = [...io.sockets.sockets.values()];
|
|
84
|
+
if (targets.broadcastAllClients || targets.rooms.some((room) => audiences?.mayContribute(room))) return sockets;
|
|
85
|
+
return sockets.filter((socket) => targets.rooms.some((room) => socket.rooms.has(room)));
|
|
86
|
+
}
|
|
87
|
+
|
|
51
88
|
async function deliverLocal({ eventName, payload, targets }) {
|
|
52
|
-
|
|
89
|
+
const checks = createPassChecks(authService, audiences);
|
|
90
|
+
await Promise.all(candidateSockets(targets).map(async (socket) => {
|
|
53
91
|
try {
|
|
54
|
-
const actor = await revalidate(socket);
|
|
92
|
+
const actor = await revalidate(socket, checks);
|
|
55
93
|
if (!socket.connected) return;
|
|
56
94
|
if (!targets.broadcastAllClients && !targets.rooms.some((room) => socket.rooms.has(room))) return;
|
|
57
95
|
if (typeof authService.realtime?.authorizeEvent === "function") {
|
|
@@ -79,7 +117,8 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
79
117
|
function scheduleRevalidation() {
|
|
80
118
|
if (stopped) return;
|
|
81
119
|
revalidationTimer = setTimeout(async () => {
|
|
82
|
-
|
|
120
|
+
const checks = createPassChecks(authService, audiences);
|
|
121
|
+
await Promise.all([...io.sockets.sockets.values()].map((socket) => revalidate(socket, checks)));
|
|
83
122
|
scheduleRevalidation();
|
|
84
123
|
}, 30_000);
|
|
85
124
|
revalidationTimer.unref();
|
|
@@ -5,9 +5,70 @@ import test from "node:test";
|
|
|
5
5
|
import { io as connect } from "socket.io-client";
|
|
6
6
|
import { createSocketIoServer, closeSocketIoServer } from "../src/server/runtime.js";
|
|
7
7
|
import { createRealtimeDelivery } from "../src/server/realtimeDelivery.js";
|
|
8
|
-
import { registerSocketAudienceBootstrap } from "../src/server/realtimeAudience.js";
|
|
8
|
+
import { createAudienceContributors, registerSocketAudienceBootstrap } from "../src/server/realtimeAudience.js";
|
|
9
9
|
|
|
10
10
|
const logger = { debug() {}, warn() {} };
|
|
11
|
+
|
|
12
|
+
// A wait that fails instead of hanging when the event never comes.
|
|
13
|
+
const arrival = (emitter, name) => once(emitter, name, { signal: AbortSignal.timeout(5_000) });
|
|
14
|
+
|
|
15
|
+
// Real sockets whose session cookies name their actors. `checks` lists each
|
|
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 } = {}) {
|
|
19
|
+
const httpServer = createServer();
|
|
20
|
+
const io = createSocketIoServer({ httpServer });
|
|
21
|
+
const sessions = new Map();
|
|
22
|
+
const checks = [];
|
|
23
|
+
const profileSyncs = [];
|
|
24
|
+
const authService = {
|
|
25
|
+
realtime: { requireAuthentication: true },
|
|
26
|
+
async authenticateRequest(request, { syncProfile = true } = {}) {
|
|
27
|
+
checks.push(request.cookies.session);
|
|
28
|
+
if (syncProfile) profileSyncs.push(request.cookies.session);
|
|
29
|
+
const id = sessions.get(request.cookies.session);
|
|
30
|
+
return { authenticated: Boolean(id), actor: id ? { id } : null };
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
registerSocketAudienceBootstrap({ io, authService, logger, audiences });
|
|
34
|
+
const delivery = createRealtimeDelivery({ io, authService, logger, audiences });
|
|
35
|
+
delivery.start();
|
|
36
|
+
t.after(async () => {
|
|
37
|
+
delivery.stop();
|
|
38
|
+
await closeSocketIoServer(io);
|
|
39
|
+
httpServer.closeAllConnections();
|
|
40
|
+
await new Promise((resolve) => httpServer.close(resolve));
|
|
41
|
+
});
|
|
42
|
+
httpServer.listen(0, "127.0.0.1");
|
|
43
|
+
await once(httpServer, "listening");
|
|
44
|
+
const url = `http://127.0.0.1:${httpServer.address().port}`;
|
|
45
|
+
return {
|
|
46
|
+
checks,
|
|
47
|
+
profileSyncs,
|
|
48
|
+
sessions,
|
|
49
|
+
io,
|
|
50
|
+
publish: (audience, name = "item.changed") => delivery.handle({
|
|
51
|
+
type: "entity.changed", realtime: { audience, event: name, payload: { name } }
|
|
52
|
+
}),
|
|
53
|
+
async connect(session) {
|
|
54
|
+
const client = connect(url, { transports: ["websocket"], extraHeaders: { Cookie: `session=${session}` }, reconnection: false });
|
|
55
|
+
t.after(() => client.disconnect());
|
|
56
|
+
const received = [];
|
|
57
|
+
client.on("item.changed", (payload) => received.push(payload));
|
|
58
|
+
await arrival(client, "connect");
|
|
59
|
+
return { client, received };
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Events on one connection arrive in order, so once a later marker arrives an
|
|
65
|
+
// earlier event that was not received was never sent.
|
|
66
|
+
async function afterMarker(f, userId, ...clients) {
|
|
67
|
+
const markers = clients.map((client) => arrival(client, "marker"));
|
|
68
|
+
await f.publish({ userId }, "marker");
|
|
69
|
+
await Promise.all(markers);
|
|
70
|
+
}
|
|
71
|
+
|
|
11
72
|
const event = {
|
|
12
73
|
type: "entity.changed", entity: "session", entityId: "s1",
|
|
13
74
|
meta: { secret: "server-only" },
|
|
@@ -82,19 +143,129 @@ test("real sockets authorize each conversation delivery and disconnect a revoked
|
|
|
82
143
|
assert.equal(received.denied.length, 1);
|
|
83
144
|
});
|
|
84
145
|
|
|
85
|
-
test("
|
|
146
|
+
test("guarded delivery checks only the sockets that can receive an event, once per login", async (t) => {
|
|
147
|
+
const f = await signedInSockets(t);
|
|
148
|
+
f.sessions.set("alice", "1").set("bob", "2").set("carol", "3");
|
|
149
|
+
const [aliceTab, aliceOtherTab] = [await f.connect("alice"), await f.connect("alice")];
|
|
150
|
+
await f.connect("bob");
|
|
151
|
+
await f.connect("carol");
|
|
152
|
+
|
|
153
|
+
f.checks.length = 0;
|
|
154
|
+
const reached = [arrival(aliceTab.client, "item.changed"), arrival(aliceOtherTab.client, "item.changed")];
|
|
155
|
+
await f.publish({ userId: 1 });
|
|
156
|
+
await Promise.all(reached);
|
|
157
|
+
assert.deepEqual(f.checks, ["alice"], "Only Alice's tabs can receive, and they share one login check");
|
|
158
|
+
|
|
159
|
+
f.checks.length = 0;
|
|
160
|
+
await f.publish("all_clients");
|
|
161
|
+
assert.deepEqual(f.checks.sort(), ["alice", "bob", "carol"], "A broadcast checks each login once");
|
|
162
|
+
|
|
163
|
+
// The shared check still stops a revoked login on the very next publish.
|
|
164
|
+
await afterMarker(f, 1, aliceTab.client, aliceOtherTab.client);
|
|
165
|
+
f.sessions.delete("alice");
|
|
166
|
+
const received = aliceTab.received.length + aliceOtherTab.received.length;
|
|
167
|
+
const disconnected = [arrival(aliceTab.client, "disconnect"), arrival(aliceOtherTab.client, "disconnect")];
|
|
168
|
+
await f.publish({ userId: 1 });
|
|
169
|
+
await Promise.all(disconnected);
|
|
170
|
+
assert.equal(aliceTab.received.length + aliceOtherTab.received.length, received);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("membership changes and revoked logins take effect on the very next publish", async (t) => {
|
|
174
|
+
const memberships = new Map([["1", [7]], ["2", []]]);
|
|
175
|
+
const audiences = createAudienceContributors();
|
|
176
|
+
audiences.register({
|
|
177
|
+
id: "test.memberships",
|
|
178
|
+
resolveActorScopes: (actorId) => (memberships.get(actorId) || []).map((id) => ({ kind: "workspace", id }))
|
|
179
|
+
});
|
|
180
|
+
const f = await signedInSockets(t, { audiences });
|
|
181
|
+
f.sessions.set("alice", "1").set("bob", "2");
|
|
182
|
+
const alice = await f.connect("alice");
|
|
183
|
+
const bob = await f.connect("bob");
|
|
184
|
+
|
|
185
|
+
await f.publish({ workspaceId: 7 });
|
|
186
|
+
await afterMarker(f, 1, alice.client);
|
|
187
|
+
await afterMarker(f, 2, bob.client);
|
|
188
|
+
assert.equal(alice.received.length, 1);
|
|
189
|
+
assert.equal(bob.received.length, 0);
|
|
190
|
+
|
|
191
|
+
// Granted: Bob was outside the room, and still receives the next publish.
|
|
192
|
+
memberships.set("2", [7]);
|
|
193
|
+
const granted = arrival(bob.client, "item.changed");
|
|
194
|
+
await f.publish({ workspaceId: 7 });
|
|
195
|
+
await granted;
|
|
196
|
+
|
|
197
|
+
// Removed: Alice was inside the room, and does not receive the next publish.
|
|
198
|
+
await afterMarker(f, 1, alice.client);
|
|
199
|
+
const aliceReceived = alice.received.length;
|
|
200
|
+
memberships.set("1", []);
|
|
201
|
+
await f.publish({ workspaceId: 7 });
|
|
202
|
+
await afterMarker(f, 1, alice.client);
|
|
203
|
+
assert.equal(alice.received.length, aliceReceived);
|
|
204
|
+
|
|
205
|
+
// A room no contributor can name is still checked only for its members.
|
|
206
|
+
const bobSocket = [...f.io.sockets.sockets.values()].find((socket) => socket.data.actorId === "2");
|
|
207
|
+
await bobSocket.join("live");
|
|
208
|
+
f.checks.length = 0;
|
|
209
|
+
await f.publish({ room: "live" });
|
|
210
|
+
assert.deepEqual(f.checks, ["bob"]);
|
|
211
|
+
|
|
212
|
+
// Revoked: Bob is disconnected instead of receiving the next publish.
|
|
213
|
+
await afterMarker(f, 2, bob.client);
|
|
214
|
+
f.sessions.delete("bob");
|
|
215
|
+
const received = bob.received.length;
|
|
216
|
+
const disconnected = arrival(bob.client, "disconnect");
|
|
217
|
+
await f.publish({ workspaceId: 7 });
|
|
218
|
+
await disconnected;
|
|
219
|
+
assert.equal(bob.received.length, received);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("revalidation never syncs profiles, and one actor's logins share a room lookup", async (t) => {
|
|
223
|
+
let roomLookups = 0;
|
|
224
|
+
const audiences = createAudienceContributors();
|
|
225
|
+
audiences.register({
|
|
226
|
+
id: "test.memberships",
|
|
227
|
+
resolveActorScopes() {
|
|
228
|
+
roomLookups += 1;
|
|
229
|
+
return [{ kind: "workspace", id: 7 }];
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
const f = await signedInSockets(t, { audiences });
|
|
233
|
+
f.sessions.set("alice-laptop", "1").set("alice-phone", "1");
|
|
234
|
+
const laptop = await f.connect("alice-laptop");
|
|
235
|
+
const phone = await f.connect("alice-phone");
|
|
236
|
+
assert.deepEqual(f.profileSyncs.sort(), ["alice-laptop", "alice-phone"], "Connecting signs in as usual");
|
|
237
|
+
|
|
238
|
+
f.profileSyncs.length = 0;
|
|
239
|
+
roomLookups = 0;
|
|
240
|
+
const reached = [arrival(laptop.client, "item.changed"), arrival(phone.client, "item.changed")];
|
|
241
|
+
await f.publish({ workspaceId: 7 });
|
|
242
|
+
await Promise.all(reached);
|
|
243
|
+
assert.deepEqual(f.profileSyncs, []);
|
|
244
|
+
assert.equal(roomLookups, 1, "Both logins are Alice, so one publish looks up her rooms once");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("idle socket sessions are revalidated without an application event, once per login", async (t) => {
|
|
86
248
|
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
87
|
-
const
|
|
88
|
-
const
|
|
249
|
+
const tab = () => ({ data: { actorId: "1" }, handshake: {}, disconnect() { this.connected = false; }, connected: true });
|
|
250
|
+
const sockets = [tab(), tab()];
|
|
251
|
+
const io = { emit() {}, to() {}, on() {}, off() {}, sockets: { sockets: new Map(sockets.map((socket, index) => [`s${index}`, socket])) } };
|
|
252
|
+
let checks = 0;
|
|
253
|
+
let options = null;
|
|
89
254
|
const delivery = createRealtimeDelivery({ io, logger, authService: {
|
|
90
255
|
realtime: { requireAuthentication: true },
|
|
91
|
-
async authenticateRequest() {
|
|
256
|
+
async authenticateRequest(_request, passOptions) {
|
|
257
|
+
checks += 1;
|
|
258
|
+
options = passOptions;
|
|
259
|
+
return { authenticated: false };
|
|
260
|
+
}
|
|
92
261
|
} });
|
|
93
262
|
t.after(() => delivery.stop());
|
|
94
263
|
delivery.start();
|
|
95
264
|
t.mock.timers.tick(30_000);
|
|
96
265
|
await new Promise((resolve) => setImmediate(resolve));
|
|
97
|
-
assert.
|
|
266
|
+
assert.deepEqual(sockets.map((socket) => socket.connected), [false, false]);
|
|
267
|
+
assert.equal(checks, 1, "Identical handshakes share one check per pass");
|
|
268
|
+
assert.deepEqual(options, { syncProfile: false });
|
|
98
269
|
});
|
|
99
270
|
|
|
100
271
|
test("delivery failures never reject a committed mutation and room unions emit once", async () => {
|