@jskit-ai/realtime 0.2.1 → 0.2.2
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,17 @@ function publicRealtimePayload(event) {
|
|
|
19
19
|
return Object.freeze({ ...(payload || {}), ...canonical });
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
// One check for all identical socket requests within one pass: the auth service
|
|
23
|
+
// sees only the request, so they would get the same answer.
|
|
24
|
+
function createSharedAuthentication(authService) {
|
|
25
|
+
const checks = new Map();
|
|
26
|
+
return (request) => {
|
|
27
|
+
const key = JSON.stringify(request);
|
|
28
|
+
if (!checks.has(key)) checks.set(key, (async () => authService.authenticateRequest(request))());
|
|
29
|
+
return checks.get(key);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
22
33
|
function createRealtimeDelivery({ io, database = null, logger, authService = null, audiences = null }) {
|
|
23
34
|
if (!io || typeof io.emit !== "function" || typeof io.to !== "function") {
|
|
24
35
|
throw new TypeError("Realtime delivery requires a Socket.IO server.");
|
|
@@ -38,9 +49,9 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
38
49
|
let revalidationTimer = null;
|
|
39
50
|
let stopped = false;
|
|
40
51
|
|
|
41
|
-
async function revalidate(socket) {
|
|
52
|
+
async function revalidate(socket, authenticateRequest) {
|
|
42
53
|
try {
|
|
43
|
-
return await revalidateSocket({ socket, authService, audiences });
|
|
54
|
+
return await revalidateSocket({ socket, authService, audiences, authenticateRequest });
|
|
44
55
|
} catch (error) {
|
|
45
56
|
socket.disconnect(true);
|
|
46
57
|
logger.warn({ error: String(error?.message || error) }, "Realtime socket revalidation failed.");
|
|
@@ -48,10 +59,19 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
48
59
|
}
|
|
49
60
|
}
|
|
50
61
|
|
|
62
|
+
// A socket outside every target room can enter one only by revalidation
|
|
63
|
+
// joining a contributed room; otherwise checking it cannot change delivery.
|
|
64
|
+
function candidateSockets(targets) {
|
|
65
|
+
const sockets = [...io.sockets.sockets.values()];
|
|
66
|
+
if (targets.broadcastAllClients || targets.rooms.some((room) => audiences?.mayContribute(room))) return sockets;
|
|
67
|
+
return sockets.filter((socket) => targets.rooms.some((room) => socket.rooms.has(room)));
|
|
68
|
+
}
|
|
69
|
+
|
|
51
70
|
async function deliverLocal({ eventName, payload, targets }) {
|
|
52
|
-
|
|
71
|
+
const authenticateRequest = createSharedAuthentication(authService);
|
|
72
|
+
await Promise.all(candidateSockets(targets).map(async (socket) => {
|
|
53
73
|
try {
|
|
54
|
-
const actor = await revalidate(socket);
|
|
74
|
+
const actor = await revalidate(socket, authenticateRequest);
|
|
55
75
|
if (!socket.connected) return;
|
|
56
76
|
if (!targets.broadcastAllClients && !targets.rooms.some((room) => socket.rooms.has(room))) return;
|
|
57
77
|
if (typeof authService.realtime?.authorizeEvent === "function") {
|
|
@@ -79,7 +99,8 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
79
99
|
function scheduleRevalidation() {
|
|
80
100
|
if (stopped) return;
|
|
81
101
|
revalidationTimer = setTimeout(async () => {
|
|
82
|
-
|
|
102
|
+
const authenticateRequest = createSharedAuthentication(authService);
|
|
103
|
+
await Promise.all([...io.sockets.sockets.values()].map((socket) => revalidate(socket, authenticateRequest)));
|
|
83
104
|
scheduleRevalidation();
|
|
84
105
|
}, 30_000);
|
|
85
106
|
revalidationTimer.unref();
|
|
@@ -5,9 +5,66 @@ 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
|
+
async function signedInSockets(t, { audiences = null } = {}) {
|
|
18
|
+
const httpServer = createServer();
|
|
19
|
+
const io = createSocketIoServer({ httpServer });
|
|
20
|
+
const sessions = new Map();
|
|
21
|
+
const checks = [];
|
|
22
|
+
const authService = {
|
|
23
|
+
realtime: { requireAuthentication: true },
|
|
24
|
+
async authenticateRequest(request) {
|
|
25
|
+
checks.push(request.cookies.session);
|
|
26
|
+
const id = sessions.get(request.cookies.session);
|
|
27
|
+
return { authenticated: Boolean(id), actor: id ? { id } : null };
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
registerSocketAudienceBootstrap({ io, authService, logger, audiences });
|
|
31
|
+
const delivery = createRealtimeDelivery({ io, authService, logger, audiences });
|
|
32
|
+
delivery.start();
|
|
33
|
+
t.after(async () => {
|
|
34
|
+
delivery.stop();
|
|
35
|
+
await closeSocketIoServer(io);
|
|
36
|
+
httpServer.closeAllConnections();
|
|
37
|
+
await new Promise((resolve) => httpServer.close(resolve));
|
|
38
|
+
});
|
|
39
|
+
httpServer.listen(0, "127.0.0.1");
|
|
40
|
+
await once(httpServer, "listening");
|
|
41
|
+
const url = `http://127.0.0.1:${httpServer.address().port}`;
|
|
42
|
+
return {
|
|
43
|
+
checks,
|
|
44
|
+
sessions,
|
|
45
|
+
io,
|
|
46
|
+
publish: (audience, name = "item.changed") => delivery.handle({
|
|
47
|
+
type: "entity.changed", realtime: { audience, event: name, payload: { name } }
|
|
48
|
+
}),
|
|
49
|
+
async connect(session) {
|
|
50
|
+
const client = connect(url, { transports: ["websocket"], extraHeaders: { Cookie: `session=${session}` }, reconnection: false });
|
|
51
|
+
t.after(() => client.disconnect());
|
|
52
|
+
const received = [];
|
|
53
|
+
client.on("item.changed", (payload) => received.push(payload));
|
|
54
|
+
await arrival(client, "connect");
|
|
55
|
+
return { client, received };
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Events on one connection arrive in order, so once a later marker arrives an
|
|
61
|
+
// earlier event that was not received was never sent.
|
|
62
|
+
async function afterMarker(f, userId, ...clients) {
|
|
63
|
+
const markers = clients.map((client) => arrival(client, "marker"));
|
|
64
|
+
await f.publish({ userId }, "marker");
|
|
65
|
+
await Promise.all(markers);
|
|
66
|
+
}
|
|
67
|
+
|
|
11
68
|
const event = {
|
|
12
69
|
type: "entity.changed", entity: "session", entityId: "s1",
|
|
13
70
|
meta: { secret: "server-only" },
|
|
@@ -82,19 +139,98 @@ test("real sockets authorize each conversation delivery and disconnect a revoked
|
|
|
82
139
|
assert.equal(received.denied.length, 1);
|
|
83
140
|
});
|
|
84
141
|
|
|
85
|
-
test("
|
|
142
|
+
test("guarded delivery checks only the sockets that can receive an event, once per login", async (t) => {
|
|
143
|
+
const f = await signedInSockets(t);
|
|
144
|
+
f.sessions.set("alice", "1").set("bob", "2").set("carol", "3");
|
|
145
|
+
const [aliceTab, aliceOtherTab] = [await f.connect("alice"), await f.connect("alice")];
|
|
146
|
+
await f.connect("bob");
|
|
147
|
+
await f.connect("carol");
|
|
148
|
+
|
|
149
|
+
f.checks.length = 0;
|
|
150
|
+
const reached = [arrival(aliceTab.client, "item.changed"), arrival(aliceOtherTab.client, "item.changed")];
|
|
151
|
+
await f.publish({ userId: 1 });
|
|
152
|
+
await Promise.all(reached);
|
|
153
|
+
assert.deepEqual(f.checks, ["alice"], "Only Alice's tabs can receive, and they share one login check");
|
|
154
|
+
|
|
155
|
+
f.checks.length = 0;
|
|
156
|
+
await f.publish("all_clients");
|
|
157
|
+
assert.deepEqual(f.checks.sort(), ["alice", "bob", "carol"], "A broadcast checks each login once");
|
|
158
|
+
|
|
159
|
+
// The shared check still stops a revoked login on the very next publish.
|
|
160
|
+
await afterMarker(f, 1, aliceTab.client, aliceOtherTab.client);
|
|
161
|
+
f.sessions.delete("alice");
|
|
162
|
+
const received = aliceTab.received.length + aliceOtherTab.received.length;
|
|
163
|
+
const disconnected = [arrival(aliceTab.client, "disconnect"), arrival(aliceOtherTab.client, "disconnect")];
|
|
164
|
+
await f.publish({ userId: 1 });
|
|
165
|
+
await Promise.all(disconnected);
|
|
166
|
+
assert.equal(aliceTab.received.length + aliceOtherTab.received.length, received);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test("membership changes and revoked logins take effect on the very next publish", async (t) => {
|
|
170
|
+
const memberships = new Map([["1", [7]], ["2", []]]);
|
|
171
|
+
const audiences = createAudienceContributors();
|
|
172
|
+
audiences.register({
|
|
173
|
+
id: "test.memberships",
|
|
174
|
+
resolveActorScopes: (actorId) => (memberships.get(actorId) || []).map((id) => ({ kind: "workspace", id }))
|
|
175
|
+
});
|
|
176
|
+
const f = await signedInSockets(t, { audiences });
|
|
177
|
+
f.sessions.set("alice", "1").set("bob", "2");
|
|
178
|
+
const alice = await f.connect("alice");
|
|
179
|
+
const bob = await f.connect("bob");
|
|
180
|
+
|
|
181
|
+
await f.publish({ workspaceId: 7 });
|
|
182
|
+
await afterMarker(f, 1, alice.client);
|
|
183
|
+
await afterMarker(f, 2, bob.client);
|
|
184
|
+
assert.equal(alice.received.length, 1);
|
|
185
|
+
assert.equal(bob.received.length, 0);
|
|
186
|
+
|
|
187
|
+
// Granted: Bob was outside the room, and still receives the next publish.
|
|
188
|
+
memberships.set("2", [7]);
|
|
189
|
+
const granted = arrival(bob.client, "item.changed");
|
|
190
|
+
await f.publish({ workspaceId: 7 });
|
|
191
|
+
await granted;
|
|
192
|
+
|
|
193
|
+
// Removed: Alice was inside the room, and does not receive the next publish.
|
|
194
|
+
await afterMarker(f, 1, alice.client);
|
|
195
|
+
const aliceReceived = alice.received.length;
|
|
196
|
+
memberships.set("1", []);
|
|
197
|
+
await f.publish({ workspaceId: 7 });
|
|
198
|
+
await afterMarker(f, 1, alice.client);
|
|
199
|
+
assert.equal(alice.received.length, aliceReceived);
|
|
200
|
+
|
|
201
|
+
// A room no contributor can name is still checked only for its members.
|
|
202
|
+
const bobSocket = [...f.io.sockets.sockets.values()].find((socket) => socket.data.actorId === "2");
|
|
203
|
+
await bobSocket.join("live");
|
|
204
|
+
f.checks.length = 0;
|
|
205
|
+
await f.publish({ room: "live" });
|
|
206
|
+
assert.deepEqual(f.checks, ["bob"]);
|
|
207
|
+
|
|
208
|
+
// Revoked: Bob is disconnected instead of receiving the next publish.
|
|
209
|
+
await afterMarker(f, 2, bob.client);
|
|
210
|
+
f.sessions.delete("bob");
|
|
211
|
+
const received = bob.received.length;
|
|
212
|
+
const disconnected = arrival(bob.client, "disconnect");
|
|
213
|
+
await f.publish({ workspaceId: 7 });
|
|
214
|
+
await disconnected;
|
|
215
|
+
assert.equal(bob.received.length, received);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("idle socket sessions are revalidated without an application event, once per login", async (t) => {
|
|
86
219
|
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
87
|
-
const
|
|
88
|
-
const
|
|
220
|
+
const tab = () => ({ data: { actorId: "1" }, handshake: {}, disconnect() { this.connected = false; }, connected: true });
|
|
221
|
+
const sockets = [tab(), tab()];
|
|
222
|
+
const io = { emit() {}, to() {}, on() {}, off() {}, sockets: { sockets: new Map(sockets.map((socket, index) => [`s${index}`, socket])) } };
|
|
223
|
+
let checks = 0;
|
|
89
224
|
const delivery = createRealtimeDelivery({ io, logger, authService: {
|
|
90
225
|
realtime: { requireAuthentication: true },
|
|
91
|
-
async authenticateRequest() { return { authenticated: false }; }
|
|
226
|
+
async authenticateRequest() { checks += 1; return { authenticated: false }; }
|
|
92
227
|
} });
|
|
93
228
|
t.after(() => delivery.stop());
|
|
94
229
|
delivery.start();
|
|
95
230
|
t.mock.timers.tick(30_000);
|
|
96
231
|
await new Promise((resolve) => setImmediate(resolve));
|
|
97
|
-
assert.
|
|
232
|
+
assert.deepEqual(sockets.map((socket) => socket.connected), [false, false]);
|
|
233
|
+
assert.equal(checks, 1, "Identical handshakes share one check per pass");
|
|
98
234
|
});
|
|
99
235
|
|
|
100
236
|
test("delivery failures never reject a committed mutation and room unions emit once", async () => {
|