@jskit-ai/realtime 0.2.5 → 0.2.7
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 +7 -2
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/client/RealtimeClientProvider.js +8 -3
- package/src/server/RealtimeProvider.js +36 -151
- package/src/server/realtimeAudience.js +172 -78
- package/src/server/realtimeCapability.js +160 -0
- package/src/server/realtimeDelivery.js +109 -72
- package/src/server/runtime.js +47 -26
- package/src/server/servedClientBuild.js +10 -4
- package/src/server/types.js +18 -0
- package/test/authorization.test.js +21 -13
- package/test/providerRuntime.test.js +43 -4
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
2
2
|
import { resolveAudienceTargets, revalidateSocket } from "./realtimeAudience.js";
|
|
3
|
+
import { countConnectedClients } from "./runtime.js";
|
|
4
|
+
|
|
5
|
+
/** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
|
|
6
|
+
/** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
|
|
7
|
+
/** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
|
|
3
8
|
|
|
4
9
|
const DELIVERY_EVENT = "jskit:realtime:delivery";
|
|
5
10
|
|
|
6
11
|
function publicRealtimePayload(event) {
|
|
7
|
-
const { realtime } = event
|
|
12
|
+
const { realtime } = event;
|
|
8
13
|
const canonical = {};
|
|
9
14
|
for (const key of [
|
|
10
15
|
"type", "source", "entity", "operation", "entityId", "scope", "actorId",
|
|
@@ -16,11 +21,22 @@ function publicRealtimePayload(event) {
|
|
|
16
21
|
if (payload != null && (typeof payload !== "object" || Array.isArray(payload))) {
|
|
17
22
|
throw new TypeError("Realtime event payload must be an object when provided.");
|
|
18
23
|
}
|
|
19
|
-
return Object.freeze({
|
|
24
|
+
return Object.freeze({
|
|
25
|
+
...(payload || {}),
|
|
26
|
+
...canonical
|
|
27
|
+
});
|
|
20
28
|
}
|
|
21
29
|
|
|
22
|
-
|
|
23
|
-
|
|
30
|
+
/**
|
|
31
|
+
* A question's key when its value is the key.
|
|
32
|
+
* @param {unknown} value
|
|
33
|
+
*/
|
|
34
|
+
function valueAsKey(value) {
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One answer per question within one pass. */
|
|
39
|
+
function sharedWithinPass(load, keyOf = valueAsKey) {
|
|
24
40
|
const answers = new Map();
|
|
25
41
|
return (value) => {
|
|
26
42
|
const key = keyOf(value);
|
|
@@ -29,36 +45,43 @@ function sharedWithinPass(load, keyOf = (value) => value) {
|
|
|
29
45
|
};
|
|
30
46
|
}
|
|
31
47
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
48
|
+
/**
|
|
49
|
+
* The checks of one publish or 30-second pass. Identical socket requests share
|
|
50
|
+
* one authentication (the auth service sees only the request), and sockets of
|
|
51
|
+
* one actor share its contributed rooms. Revalidation asks only who is signed
|
|
52
|
+
* in, so the provider reads the app profile instead of synchronizing it, and
|
|
53
|
+
* never refreshes a session the socket could not store.
|
|
54
|
+
* @param {AuthService} authService
|
|
55
|
+
* @param {ActorRoomsResolver} resolveActorRooms
|
|
56
|
+
*/
|
|
57
|
+
function createPassChecks(authService, resolveActorRooms) {
|
|
38
58
|
return {
|
|
39
59
|
authenticateRequest: sharedWithinPass(
|
|
40
60
|
(request) => authService.authenticateRequest(request, { syncProfile: false, refreshSession: false }),
|
|
41
61
|
JSON.stringify
|
|
42
62
|
),
|
|
43
|
-
audiences:
|
|
63
|
+
audiences: { resolveActorRooms: sharedWithinPass(resolveActorRooms) }
|
|
44
64
|
};
|
|
45
65
|
}
|
|
46
66
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
67
|
+
/**
|
|
68
|
+
* @param {object} dependencies
|
|
69
|
+
* @param {import("socket.io").Server} dependencies.io
|
|
70
|
+
* @param {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase | null} dependencies.database Absent when no runtime.database is installed.
|
|
71
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
72
|
+
* @param {AuthService | null} dependencies.authService Absent when no auth.service is installed.
|
|
73
|
+
* @param {AudienceContributors} dependencies.audiences The rooms revalidation may make a socket join.
|
|
74
|
+
* With no contributors registered, a socket stays in the rooms it already has.
|
|
75
|
+
*/
|
|
76
|
+
function createRealtimeDelivery({ io, database, logger, authService, audiences: { mayContribute, resolveActorRooms } }) {
|
|
77
|
+
// With an auth.service, each socket is revalidated before it receives an event;
|
|
78
|
+
// without one, events go straight to their rooms.
|
|
79
|
+
const guarded = Boolean(authService);
|
|
80
|
+
const authorizeEvent = authService?.realtime?.authorizeEvent ?? null;
|
|
81
|
+
// readable-check: allow method-probe - input validation: an auth provider's realtime policy may name authorizeEvent()
|
|
82
|
+
if (authorizeEvent !== null && typeof authorizeEvent !== "function") {
|
|
57
83
|
throw new TypeError("Realtime authorizeEvent must be a function.");
|
|
58
84
|
}
|
|
59
|
-
if ((authService?.realtime?.requireAuthentication === true || authService?.realtime?.authorizeEvent) && !guarded) {
|
|
60
|
-
throw new TypeError("Realtime authorization requires auth.service.authenticateRequest().");
|
|
61
|
-
}
|
|
62
85
|
let redisEnabled = false;
|
|
63
86
|
let revalidationTimer = null;
|
|
64
87
|
let stopped = false;
|
|
@@ -78,22 +101,24 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
78
101
|
}
|
|
79
102
|
}
|
|
80
103
|
|
|
81
|
-
|
|
82
|
-
|
|
104
|
+
/**
|
|
105
|
+
* A socket outside every target room can enter one only by revalidation
|
|
106
|
+
* joining a contributed room; otherwise checking it cannot change delivery.
|
|
107
|
+
*/
|
|
83
108
|
function candidateSockets(targets) {
|
|
84
109
|
const sockets = [...io.sockets.sockets.values()];
|
|
85
|
-
if (targets.broadcastAllClients || targets.rooms.some((room) =>
|
|
110
|
+
if (targets.broadcastAllClients || targets.rooms.some((room) => mayContribute(room))) return sockets;
|
|
86
111
|
return sockets.filter((socket) => targets.rooms.some((room) => socket.rooms.has(room)));
|
|
87
112
|
}
|
|
88
113
|
|
|
89
114
|
async function deliverLocal({ eventName, payload, targets }) {
|
|
90
|
-
const checks = createPassChecks(authService,
|
|
115
|
+
const checks = createPassChecks(authService, resolveActorRooms);
|
|
91
116
|
await Promise.all(candidateSockets(targets).map(async (socket) => {
|
|
92
117
|
try {
|
|
93
118
|
const actor = await revalidate(socket, checks);
|
|
94
119
|
if (!socket.connected) return;
|
|
95
120
|
if (!targets.broadcastAllClients && !targets.rooms.some((room) => socket.rooms.has(room))) return;
|
|
96
|
-
if (
|
|
121
|
+
if (authorizeEvent) {
|
|
97
122
|
const authorized = await authService.realtime.authorizeEvent({
|
|
98
123
|
actor,
|
|
99
124
|
event: { name: eventName, payload }
|
|
@@ -118,60 +143,72 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
|
|
|
118
143
|
function scheduleRevalidation() {
|
|
119
144
|
if (stopped) return;
|
|
120
145
|
revalidationTimer = setTimeout(async () => {
|
|
121
|
-
const checks = createPassChecks(authService,
|
|
146
|
+
const checks = createPassChecks(authService, resolveActorRooms);
|
|
122
147
|
await Promise.all([...io.sockets.sockets.values()].map((socket) => revalidate(socket, checks)));
|
|
123
148
|
scheduleRevalidation();
|
|
124
149
|
}, 30_000);
|
|
125
150
|
revalidationTimer.unref();
|
|
126
151
|
}
|
|
127
152
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
153
|
+
function start({ redisConfigured = false } = {}) {
|
|
154
|
+
redisEnabled = redisConfigured;
|
|
155
|
+
if (guarded) {
|
|
156
|
+
io.on(DELIVERY_EVENT, receive);
|
|
157
|
+
scheduleRevalidation();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function stop() {
|
|
162
|
+
stopped = true;
|
|
163
|
+
clearTimeout(revalidationTimer);
|
|
164
|
+
if (guarded) io.off(DELIVERY_EVENT, receive);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** @param {object} event A published runtime event whose realtime part names a socket event (see matchesRealtimeEvent). */
|
|
168
|
+
async function handle(event) {
|
|
169
|
+
try {
|
|
170
|
+
const eventName = normalizeText(event.realtime.event);
|
|
171
|
+
const targets = await resolveAudienceTargets(event.realtime.audience, event, { database, logger });
|
|
172
|
+
const payload = publicRealtimePayload(event);
|
|
131
173
|
if (guarded) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
clearTimeout(revalidationTimer);
|
|
139
|
-
if (guarded) io.off(DELIVERY_EVENT, receive);
|
|
140
|
-
},
|
|
141
|
-
async handle(event = {}) {
|
|
142
|
-
try {
|
|
143
|
-
const eventName = normalizeText(event?.realtime?.event);
|
|
144
|
-
if (!eventName) return;
|
|
145
|
-
const targets = await resolveAudienceTargets(event.realtime.audience, event, { database, logger });
|
|
146
|
-
const payload = publicRealtimePayload(event);
|
|
147
|
-
if (guarded) {
|
|
148
|
-
const envelope = { eventName, payload, targets };
|
|
149
|
-
if (redisEnabled) {
|
|
150
|
-
try {
|
|
151
|
-
io.serverSideEmit(DELIVERY_EVENT, envelope);
|
|
152
|
-
} catch (error) {
|
|
153
|
-
logger.warn({ socketEvent: eventName, error: String(error?.message || error) }, "Realtime peer publication failed.");
|
|
154
|
-
}
|
|
174
|
+
const envelope = { eventName, payload, targets };
|
|
175
|
+
if (redisEnabled) {
|
|
176
|
+
try {
|
|
177
|
+
io.serverSideEmit(DELIVERY_EVENT, envelope);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
logger.warn({ socketEvent: eventName, error: String(error?.message || error) }, "Realtime peer publication failed.");
|
|
155
180
|
}
|
|
156
|
-
await deliverLocal(envelope);
|
|
157
|
-
} else if (targets.broadcastAllClients) {
|
|
158
|
-
io.emit(eventName, payload);
|
|
159
|
-
} else if (targets.rooms.length) {
|
|
160
|
-
io.to(targets.rooms).emit(eventName, payload);
|
|
161
181
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
? Number(io.engine.clientsCount)
|
|
168
|
-
: null
|
|
169
|
-
}, "Realtime delivered an action event.");
|
|
170
|
-
} catch (error) {
|
|
171
|
-
logger.warn({ socketEvent: event?.realtime?.event, error: String(error?.message || error) }, "Realtime delivery failed; the domain mutation remains successful.");
|
|
182
|
+
await deliverLocal(envelope);
|
|
183
|
+
} else if (targets.broadcastAllClients) {
|
|
184
|
+
io.emit(eventName, payload);
|
|
185
|
+
} else if (targets.rooms.length) {
|
|
186
|
+
io.to(targets.rooms).emit(eventName, payload);
|
|
172
187
|
}
|
|
188
|
+
logger.debug({
|
|
189
|
+
socketEvent: eventName,
|
|
190
|
+
rooms: targets.rooms,
|
|
191
|
+
broadcastAllClients: targets.broadcastAllClients,
|
|
192
|
+
connectedClients: countConnectedClients(io)
|
|
193
|
+
}, "Realtime delivered an action event.");
|
|
194
|
+
} catch (error) {
|
|
195
|
+
logger.warn({ socketEvent: event.realtime?.event, error: String(error?.message || error) }, "Realtime delivery failed; the domain mutation remains successful.");
|
|
173
196
|
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return Object.freeze({
|
|
200
|
+
start,
|
|
201
|
+
stop,
|
|
202
|
+
handle
|
|
174
203
|
});
|
|
175
204
|
}
|
|
176
205
|
|
|
177
|
-
|
|
206
|
+
/**
|
|
207
|
+
* Whether a published runtime event names a socket event for realtime to deliver.
|
|
208
|
+
* @param {object} event
|
|
209
|
+
*/
|
|
210
|
+
function matchesRealtimeEvent(event) {
|
|
211
|
+
return Boolean(normalizeText(event.realtime?.event));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export { createRealtimeDelivery, matchesRealtimeEvent };
|
package/src/server/runtime.js
CHANGED
|
@@ -2,22 +2,15 @@ import { Server as SocketIoServer } from "socket.io";
|
|
|
2
2
|
import { createAdapter as createSocketIoRedisAdapter } from "@socket.io/redis-adapter";
|
|
3
3
|
import { createClient as createRedisClient } from "redis";
|
|
4
4
|
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
5
|
-
import {
|
|
5
|
+
import { toRequestPathname } from "@jskit-ai/kernel/shared/surface/paths";
|
|
6
6
|
|
|
7
7
|
const SOCKET_IO_PATH = "/socket.io";
|
|
8
8
|
const REDIS_URL_ENV_KEY = "REDIS_URL";
|
|
9
9
|
const REDIS_NAMESPACE_ENV_KEY = "REDIS_NAMESPACE";
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
const rawUrl = String(urlValue || "").trim() || "/";
|
|
13
|
-
try {
|
|
14
|
-
return normalizePathname(new URL(rawUrl, "http://localhost").pathname || "/");
|
|
15
|
-
} catch {
|
|
16
|
-
return normalizePathname(rawUrl.split("?")[0] || "/");
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
11
|
+
/** @param {import("@jskit-ai/kernel/server/types").RuntimeFastify | null} fastify */
|
|
20
12
|
function registerSocketIoUpgradeHandoff(fastify) {
|
|
13
|
+
// readable-check: allow method-probe - input validation: a host that hands over only its HTTP server ({ server }) has no addHook()
|
|
21
14
|
if (typeof fastify?.addHook !== "function") return;
|
|
22
15
|
fastify.addHook("onRequest", async (request, reply) => {
|
|
23
16
|
if (request?.ws !== true) return;
|
|
@@ -38,12 +31,20 @@ function resolveHttpServer({ httpServer = null, fastify = null } = {}) {
|
|
|
38
31
|
throw new Error("createSocketIoServer requires httpServer or fastify.server.");
|
|
39
32
|
}
|
|
40
33
|
|
|
34
|
+
/**
|
|
35
|
+
* @param {object} [options]
|
|
36
|
+
* @param {import("node:http").Server | null} [options.httpServer] The HTTP server to attach to; Fastify's when absent.
|
|
37
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeFastify | null} [options.fastify]
|
|
38
|
+
* @param {Partial<import("socket.io").ServerOptions>} [options.options]
|
|
39
|
+
* @param {typeof SocketIoServer} [options.ServerCtor]
|
|
40
|
+
*/
|
|
41
41
|
function createSocketIoServer({
|
|
42
42
|
httpServer = null,
|
|
43
43
|
fastify = null,
|
|
44
44
|
options = {},
|
|
45
45
|
ServerCtor = SocketIoServer
|
|
46
46
|
} = {}) {
|
|
47
|
+
// readable-check: allow method-probe - input validation: a caller may pass its own Socket.IO Server class
|
|
47
48
|
if (typeof ServerCtor !== "function") {
|
|
48
49
|
throw new Error("createSocketIoServer requires a valid socket.io Server constructor.");
|
|
49
50
|
}
|
|
@@ -52,11 +53,10 @@ function createSocketIoServer({
|
|
|
52
53
|
httpServer,
|
|
53
54
|
fastify
|
|
54
55
|
});
|
|
55
|
-
const source = options && typeof options === "object" && !Array.isArray(options) ? options : {};
|
|
56
56
|
const normalizedOptions = {
|
|
57
57
|
// Application WebSocket routes may still be authorizing their upgrades.
|
|
58
58
|
destroyUpgrade: false,
|
|
59
|
-
...
|
|
59
|
+
...options,
|
|
60
60
|
path: SOCKET_IO_PATH
|
|
61
61
|
};
|
|
62
62
|
registerSocketIoUpgradeHandoff(fastify);
|
|
@@ -79,14 +79,22 @@ async function closeSocketIoServer(io) {
|
|
|
79
79
|
await io.sockets.adapter.close();
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return normalizeText(
|
|
82
|
+
/** @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env */
|
|
83
|
+
function resolveRealtimeRedisUrl(env) {
|
|
84
|
+
return normalizeText(env[REDIS_URL_ENV_KEY]);
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
return normalizeText(
|
|
87
|
+
/** @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env */
|
|
88
|
+
function resolveRealtimeRedisNamespace(env) {
|
|
89
|
+
return normalizeText(env[REDIS_NAMESPACE_ENV_KEY]);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* How many clients the Socket.IO engine holds, or null before it is attached.
|
|
94
|
+
* @param {import("socket.io").Server} io
|
|
95
|
+
*/
|
|
96
|
+
function countConnectedClients(io) {
|
|
97
|
+
return Number.isInteger(Number(io.engine?.clientsCount)) ? Number(io.engine.clientsCount) : null;
|
|
90
98
|
}
|
|
91
99
|
|
|
92
100
|
function buildSocketIoRedisAdapterKey(redisNamespace = "") {
|
|
@@ -97,15 +105,24 @@ function buildSocketIoRedisAdapterKey(redisNamespace = "") {
|
|
|
97
105
|
return `${normalizedRedisNamespace}:socket.io`;
|
|
98
106
|
}
|
|
99
107
|
|
|
108
|
+
/**
|
|
109
|
+
* @param {import("socket.io").Server} io
|
|
110
|
+
* @param {object} options
|
|
111
|
+
* @param {string} [options.redisUrl]
|
|
112
|
+
* @param {string} [options.redisNamespace]
|
|
113
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} options.logger Warned when a Redis connection fails.
|
|
114
|
+
* @param {typeof createSocketIoRedisAdapter} [options.createRedisAdapter]
|
|
115
|
+
* @param {typeof createRedisClient} [options.createRedisConnection]
|
|
116
|
+
*/
|
|
100
117
|
async function configureSocketIoRedisAdapter(
|
|
101
118
|
io,
|
|
102
119
|
{
|
|
103
120
|
redisUrl = "",
|
|
104
121
|
redisNamespace = "",
|
|
105
|
-
logger
|
|
122
|
+
logger,
|
|
106
123
|
createRedisAdapter = createSocketIoRedisAdapter,
|
|
107
124
|
createRedisConnection = createRedisClient
|
|
108
|
-
}
|
|
125
|
+
}
|
|
109
126
|
) {
|
|
110
127
|
const normalizedRedisUrl = normalizeText(redisUrl);
|
|
111
128
|
const adapterKey = buildSocketIoRedisAdapterKey(redisNamespace);
|
|
@@ -119,10 +136,6 @@ async function configureSocketIoRedisAdapter(
|
|
|
119
136
|
subClient: null
|
|
120
137
|
});
|
|
121
138
|
}
|
|
122
|
-
if (!io || typeof io.adapter !== "function") {
|
|
123
|
-
throw new Error("configureSocketIoRedisAdapter requires socket.io server instance with adapter().");
|
|
124
|
-
}
|
|
125
|
-
|
|
126
139
|
const pubClient = createRedisConnection({
|
|
127
140
|
url: normalizedRedisUrl
|
|
128
141
|
});
|
|
@@ -164,18 +177,25 @@ async function configureSocketIoRedisAdapter(
|
|
|
164
177
|
});
|
|
165
178
|
}
|
|
166
179
|
|
|
167
|
-
|
|
180
|
+
/**
|
|
181
|
+
* @param {object} connections
|
|
182
|
+
* @param {object | null} connections.pubClient
|
|
183
|
+
* @param {object | null} connections.subClient
|
|
184
|
+
*/
|
|
185
|
+
async function closeSocketIoRedisConnections({ pubClient, subClient }) {
|
|
168
186
|
const connections = [subClient, pubClient];
|
|
169
187
|
for (const connection of connections) {
|
|
170
188
|
if (!connection) {
|
|
171
189
|
continue;
|
|
172
190
|
}
|
|
191
|
+
// readable-check: allow method-probe - platform object: a Redis client closes with quit(), or with disconnect() where it has no quit()
|
|
173
192
|
if (typeof connection.quit === "function") {
|
|
174
193
|
try {
|
|
175
194
|
await connection.quit();
|
|
176
195
|
} catch {}
|
|
177
196
|
continue;
|
|
178
197
|
}
|
|
198
|
+
// readable-check: allow method-probe - platform object: a Redis client closes with quit(), or with disconnect() where it has no quit()
|
|
179
199
|
if (typeof connection.disconnect === "function") {
|
|
180
200
|
try {
|
|
181
201
|
await connection.disconnect();
|
|
@@ -192,5 +212,6 @@ export {
|
|
|
192
212
|
resolveRealtimeRedisUrl,
|
|
193
213
|
resolveRealtimeRedisNamespace,
|
|
194
214
|
configureSocketIoRedisAdapter,
|
|
195
|
-
closeSocketIoRedisConnections
|
|
215
|
+
closeSocketIoRedisConnections,
|
|
216
|
+
countConnectedClients
|
|
196
217
|
};
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { readServedClientBuildId } from "@jskit-ai/kernel/server/support";
|
|
2
2
|
import { SERVED_CLIENT_BUILD_EVENT } from "../shared/servedClientBuild.js";
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Each connection, including a reconnection to a restarted server, learns the
|
|
6
|
+
* client build this server serves now. A page running an older build can then
|
|
7
|
+
* offer a reload without polling.
|
|
8
|
+
* @param {object} dependencies
|
|
9
|
+
* @param {import("socket.io").Server} dependencies.io
|
|
10
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot | null} dependencies.appRoot Absent when no runtime.app-root is installed.
|
|
11
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
12
|
+
*/
|
|
7
13
|
function announceServedClientBuild({ io, appRoot, logger }) {
|
|
8
|
-
if (!appRoot
|
|
14
|
+
if (!appRoot) return;
|
|
9
15
|
io.on("connection", async (socket) => {
|
|
10
16
|
try {
|
|
11
17
|
const buildId = await readServedClientBuildId({ appRoot });
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The type of the `runtime.realtime` capability, for features that require it, and the
|
|
2
|
+
// types realtime's modules share.
|
|
3
|
+
|
|
4
|
+
/** @typedef {ReturnType<typeof import("./realtimeCapability.js").createRealtimeCapability>} RuntimeRealtime */
|
|
5
|
+
/**
|
|
6
|
+
* The rooms an actor's contributed scopes name.
|
|
7
|
+
* @typedef {(actorId: string) => Promise<Set<string>>} ActorRoomsResolver
|
|
8
|
+
*/
|
|
9
|
+
/** @typedef {ReturnType<typeof import("./realtimeAudience.js").createAudienceContributors>} AudienceContributors */
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A package that knows which scopes an actor belongs to.
|
|
13
|
+
* @typedef {object} RealtimeAudienceContributor
|
|
14
|
+
* @property {string} id
|
|
15
|
+
* @property {(actorId: string) => unknown} resolveActorScopes Returns, or resolves to, the actor's scopes.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export {};
|
|
@@ -17,7 +17,7 @@ const arrival = (emitter, name) => once(emitter, name, { signal: AbortSignal.tim
|
|
|
17
17
|
// `profileSyncs` those that asked the provider to sync the profile, and
|
|
18
18
|
// `sessionRefreshes` those that let it refresh the session. Sessions in
|
|
19
19
|
// `expired` answer that they need a refresh.
|
|
20
|
-
async function signedInSockets(t, { audiences =
|
|
20
|
+
async function signedInSockets(t, { audiences = createAudienceContributors(), requireAuthentication = true } = {}) {
|
|
21
21
|
const httpServer = createServer();
|
|
22
22
|
const io = createSocketIoServer({ httpServer });
|
|
23
23
|
const sessions = new Map();
|
|
@@ -89,12 +89,11 @@ const event = {
|
|
|
89
89
|
|
|
90
90
|
test("invalid authorization configuration fails closed at startup", () => {
|
|
91
91
|
const io = { emit() {}, to() {} };
|
|
92
|
-
|
|
92
|
+
const audiences = createAudienceContributors();
|
|
93
|
+
assert.throws(() => createRealtimeDelivery({ io, logger, audiences, authService: {
|
|
93
94
|
authenticateRequest() {}, realtime: { authorizeEvent: true }
|
|
94
95
|
} }), /authorizeEvent must be a function/u);
|
|
95
|
-
assert.throws(() => createRealtimeDelivery({ io, logger, authService:
|
|
96
|
-
realtime: { requireAuthentication: true }
|
|
97
|
-
} }), /authenticateRequest/u);
|
|
96
|
+
assert.throws(() => createRealtimeDelivery({ io, logger, authService: null }), /mayContribute/u);
|
|
98
97
|
});
|
|
99
98
|
|
|
100
99
|
test("real sockets authorize each conversation delivery and disconnect a revoked session", async (t) => {
|
|
@@ -112,8 +111,9 @@ test("real sockets authorize each conversation delivery and disconnect a revoked
|
|
|
112
111
|
return { authenticated: Boolean(actor), actor };
|
|
113
112
|
}
|
|
114
113
|
};
|
|
115
|
-
|
|
116
|
-
|
|
114
|
+
const audiences = createAudienceContributors();
|
|
115
|
+
registerSocketAudienceBootstrap({ io, authService, logger, audiences });
|
|
116
|
+
const delivery = createRealtimeDelivery({ io, authService, logger, audiences });
|
|
117
117
|
delivery.start();
|
|
118
118
|
t.after(async () => {
|
|
119
119
|
delivery.stop();
|
|
@@ -279,12 +279,15 @@ test("a login whose session needs refreshing is dropped and refused until the cl
|
|
|
279
279
|
|
|
280
280
|
test("idle socket sessions are revalidated without an application event, once per login", async (t) => {
|
|
281
281
|
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
282
|
-
const tab = () => ({
|
|
282
|
+
const tab = () => ({
|
|
283
|
+
data: { actorId: "1" }, handshake: { headers: {} }, request: { headers: {}, socket: {} }, conn: {},
|
|
284
|
+
disconnect() { this.connected = false; }, connected: true
|
|
285
|
+
});
|
|
283
286
|
const sockets = [tab(), tab()];
|
|
284
287
|
const io = { emit() {}, to() {}, on() {}, off() {}, sockets: { sockets: new Map(sockets.map((socket, index) => [`s${index}`, socket])) } };
|
|
285
288
|
let checks = 0;
|
|
286
289
|
let options = null;
|
|
287
|
-
const delivery = createRealtimeDelivery({ io, logger, authService: {
|
|
290
|
+
const delivery = createRealtimeDelivery({ io, logger, audiences: createAudienceContributors(), authService: {
|
|
288
291
|
realtime: { requireAuthentication: true },
|
|
289
292
|
async authenticateRequest(_request, passOptions) {
|
|
290
293
|
checks += 1;
|
|
@@ -304,7 +307,11 @@ test("idle socket sessions are revalidated without an application event, once pe
|
|
|
304
307
|
test("delivery failures never reject a committed mutation and room unions emit once", async () => {
|
|
305
308
|
const warnings = [];
|
|
306
309
|
const io = { emit() { throw new Error("transport down"); }, to() { throw new Error("transport down"); } };
|
|
307
|
-
const delivery = createRealtimeDelivery({
|
|
310
|
+
const delivery = createRealtimeDelivery({
|
|
311
|
+
io,
|
|
312
|
+
logger: { debug() {}, warn(value) { warnings.push(value); } },
|
|
313
|
+
audiences: createAudienceContributors()
|
|
314
|
+
});
|
|
308
315
|
await assert.doesNotReject(delivery.handle(event));
|
|
309
316
|
await assert.doesNotReject(delivery.handle({ ...event, realtime: { ...event.realtime, payload: "invalid" } }));
|
|
310
317
|
assert.equal(warnings.length, 2);
|
|
@@ -314,7 +321,8 @@ test("Redis peer deliveries authorize the receiving server's sockets without reb
|
|
|
314
321
|
const delivered = [];
|
|
315
322
|
const peerHandlers = new Map();
|
|
316
323
|
const socket = {
|
|
317
|
-
connected: true, data: { actorId: "2" }, handshake: {},
|
|
324
|
+
connected: true, data: { actorId: "2" }, handshake: { headers: {} }, request: { headers: {}, socket: {} }, conn: {},
|
|
325
|
+
rooms: new Set(["users", "user:2"]),
|
|
318
326
|
disconnect() { this.connected = false; },
|
|
319
327
|
emit(name, payload) { delivered.push({ name, payload }); }
|
|
320
328
|
};
|
|
@@ -323,7 +331,7 @@ test("Redis peer deliveries authorize the receiving server's sockets without reb
|
|
|
323
331
|
realtime: { requireAuthentication: true, authorizeEvent: () => allowed },
|
|
324
332
|
async authenticateRequest() { return { authenticated: true, actor: { id: "2" } }; }
|
|
325
333
|
};
|
|
326
|
-
const peer = createRealtimeDelivery({ logger, authService, io: {
|
|
334
|
+
const peer = createRealtimeDelivery({ logger, authService, audiences: createAudienceContributors(), io: {
|
|
327
335
|
emit() { assert.fail("must authorize individual sockets"); }, to() {},
|
|
328
336
|
sockets: { sockets: new Map([["peer-socket", socket]]) },
|
|
329
337
|
on(name, handler) { peerHandlers.set(name, handler); },
|
|
@@ -331,7 +339,7 @@ test("Redis peer deliveries authorize the receiving server's sockets without reb
|
|
|
331
339
|
serverSideEmit() { assert.fail("must not rebroadcast a received event"); }
|
|
332
340
|
} });
|
|
333
341
|
const pending = [];
|
|
334
|
-
const origin = createRealtimeDelivery({ logger, authService, io: {
|
|
342
|
+
const origin = createRealtimeDelivery({ logger, authService, audiences: createAudienceContributors(), io: {
|
|
335
343
|
emit() {}, to() {}, sockets: { sockets: new Map() }, on() {}, off() {},
|
|
336
344
|
serverSideEmit(name, envelope) { pending.push(peerHandlers.get(name)(structuredClone(envelope))); }
|
|
337
345
|
} });
|
|
@@ -250,7 +250,7 @@ test("RealtimeProvider assembles an event-driven runtime capability", async () =
|
|
|
250
250
|
|
|
251
251
|
test("realtime delivery sends explicit action events to their selected rooms", async () => {
|
|
252
252
|
const io = createIoDouble();
|
|
253
|
-
const delivery = createRealtimeDelivery({ io, logger });
|
|
253
|
+
const delivery = createRealtimeDelivery({ io, logger, audiences: createAudienceContributors() });
|
|
254
254
|
await delivery.handle({
|
|
255
255
|
type: "entity.changed",
|
|
256
256
|
source: "workspace",
|
|
@@ -284,7 +284,11 @@ test("realtime delivery sends explicit action events to their selected rooms", a
|
|
|
284
284
|
test("realtime event_scope delivery never widens an undeliverable scope to every user", async () => {
|
|
285
285
|
const io = createIoDouble();
|
|
286
286
|
const warnings = [];
|
|
287
|
-
const delivery = createRealtimeDelivery({
|
|
287
|
+
const delivery = createRealtimeDelivery({
|
|
288
|
+
io,
|
|
289
|
+
logger: { ...logger, warn: (details) => warnings.push(details) },
|
|
290
|
+
audiences: createAudienceContributors()
|
|
291
|
+
});
|
|
288
292
|
const scopes = [undefined, { kind: "scope", id: "11" }, { kind: "public" }, { kind: "user" }];
|
|
289
293
|
for (const scope of scopes) {
|
|
290
294
|
await delivery.handle({
|
|
@@ -302,11 +306,43 @@ test("realtime event_scope delivery never widens an undeliverable scope to every
|
|
|
302
306
|
assert.deepEqual(warnings, scopes.map((scope) => ({ audience: "event_scope", scope: scope || null })));
|
|
303
307
|
});
|
|
304
308
|
|
|
309
|
+
test("realtime delivery warns and continues when an event's scope is null", async () => {
|
|
310
|
+
const io = createIoDouble();
|
|
311
|
+
const warnings = [];
|
|
312
|
+
const delivery = createRealtimeDelivery({
|
|
313
|
+
io,
|
|
314
|
+
logger: { ...logger, warn: (details, message) => warnings.push({ details, message }) },
|
|
315
|
+
audiences: createAudienceContributors()
|
|
316
|
+
});
|
|
317
|
+
await delivery.handle({
|
|
318
|
+
type: "entity.changed",
|
|
319
|
+
source: "crud",
|
|
320
|
+
entity: "record",
|
|
321
|
+
operation: "updated",
|
|
322
|
+
entityId: "5",
|
|
323
|
+
scope: null,
|
|
324
|
+
realtime: { event: "things.record.changed", audience: ["all_workspace_users", "event_scope", "all_users"] }
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
assert.deepEqual(warnings, [
|
|
328
|
+
{
|
|
329
|
+
details: { audience: "all_workspace_users", scope: null },
|
|
330
|
+
message: "Realtime audience requires a workspace scope."
|
|
331
|
+
},
|
|
332
|
+
{
|
|
333
|
+
details: { audience: "event_scope", scope: null },
|
|
334
|
+
message: "Realtime event_scope audience has no deliverable scope."
|
|
335
|
+
}
|
|
336
|
+
]);
|
|
337
|
+
assert.deepEqual(io.emitted.map((entry) => entry.room), [["users"]]);
|
|
338
|
+
});
|
|
339
|
+
|
|
305
340
|
test("realtime delivery resolves an explicit database-backed audience without exposing query controls", async () => {
|
|
306
341
|
const io = createIoDouble();
|
|
307
342
|
const delivery = createRealtimeDelivery({
|
|
308
343
|
io,
|
|
309
344
|
logger,
|
|
345
|
+
audiences: createAudienceContributors(),
|
|
310
346
|
database: {
|
|
311
347
|
knex() {}
|
|
312
348
|
}
|
|
@@ -446,6 +482,7 @@ test("socket audience bootstrap rejects unauthenticated handshakes when the auth
|
|
|
446
482
|
registerSocketAudienceBootstrap({
|
|
447
483
|
io,
|
|
448
484
|
logger,
|
|
485
|
+
audiences: createAudienceContributors(),
|
|
449
486
|
authService: {
|
|
450
487
|
realtime: { requireAuthentication: true },
|
|
451
488
|
async authenticateRequest(request) {
|
|
@@ -460,7 +497,8 @@ test("socket audience bootstrap rejects unauthenticated handshakes when the auth
|
|
|
460
497
|
await authenticationMiddleware({
|
|
461
498
|
data: {},
|
|
462
499
|
handshake: { headers: { cookie: "session=invalid" } },
|
|
463
|
-
request: { headers: {} }
|
|
500
|
+
request: { headers: {}, socket: {} },
|
|
501
|
+
conn: {}
|
|
464
502
|
}, (error) => rejected.push(error));
|
|
465
503
|
assert.equal(rejected.length, 1);
|
|
466
504
|
assert.equal(rejected[0].data.code, "AUTHENTICATION_REQUIRED");
|
|
@@ -468,7 +506,8 @@ test("socket audience bootstrap rejects unauthenticated handshakes when the auth
|
|
|
468
506
|
const socket = {
|
|
469
507
|
data: {},
|
|
470
508
|
handshake: { headers: { cookie: "session=valid" } },
|
|
471
|
-
request: { headers: {} },
|
|
509
|
+
request: { headers: {}, socket: {} },
|
|
510
|
+
conn: {},
|
|
472
511
|
join(room) {
|
|
473
512
|
this.joinedRooms ||= [];
|
|
474
513
|
this.joinedRooms.push(room);
|