@spooky-sync/core 1.0.0-beta.8 → 1.0.0-beta.9
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/AGENTS.md +1 -1
- package/dist/index.d.ts +99 -2
- package/dist/index.js +942 -27
- package/dist/types.d.ts +68 -2
- package/package.json +3 -3
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/sp00ky-client.test.ts +64 -1
- package/src/client/sp00ky-client.ts +53 -10
- package/src/index.ts +7 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/types.ts +5 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import type { Logger } from '../../services/logger/index';
|
|
2
|
+
import type { ChannelTransport, ChannelTransportFactory, ChannelWire, TransportHooks } from './index';
|
|
3
|
+
import { webrtcTransport, type Signal, type SignalKind } from './webrtc';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The link between the browsers of one user.
|
|
7
|
+
*
|
|
8
|
+
* Every browser keeps one socket to the room relay (`sp00ky-relay`, see
|
|
9
|
+
* `apps/relay`). The relay proves the user from the session token, puts the
|
|
10
|
+
* socket into that user's room and forwards what the members send each
|
|
11
|
+
* other without reading it. So a message is there after one hop to the relay
|
|
12
|
+
* and one back, whatever network each device sits in, and nothing waits for
|
|
13
|
+
* a connection to be negotiated.
|
|
14
|
+
*
|
|
15
|
+
* Two browsers alone in a room also open a WebRTC data channel to each other
|
|
16
|
+
* (its offer and answer travel through the relay) and use it while it is up:
|
|
17
|
+
* on one network that is a millisecond instead of a trip to the relay. A
|
|
18
|
+
* third browser joining ends that, and everybody talks through the room.
|
|
19
|
+
*
|
|
20
|
+
* Nothing here is kept or retried: a message lost on the way is one the
|
|
21
|
+
* normal sync delivers a moment later.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** A browser in the room, by the id it joined with. */
|
|
25
|
+
export type RoomPeer = string;
|
|
26
|
+
|
|
27
|
+
export interface RoomLinkHooks {
|
|
28
|
+
/** Who this browser is, or null while signed out. */
|
|
29
|
+
self(): { user: string; peer: RoomPeer } | null;
|
|
30
|
+
onPeer(peer: RoomPeer, up: boolean): void;
|
|
31
|
+
onMessage(from: RoomPeer, data: unknown): void;
|
|
32
|
+
onStatus(status: 'connecting' | 'connected' | 'failed'): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface RoomLink {
|
|
36
|
+
/** Send to these browsers of the room, or (`null`) to all of them. Fire and forget. */
|
|
37
|
+
send(to: ReadonlyArray<RoomPeer> | null, data: unknown): void;
|
|
38
|
+
close(): void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type RoomLinkFactory = (hooks: RoomLinkHooks) => RoomLink;
|
|
42
|
+
|
|
43
|
+
export interface RoomLinkOptions {
|
|
44
|
+
/** The relay's WebSocket address. */
|
|
45
|
+
url: string;
|
|
46
|
+
/** The session token the relay proves the user with; null while there is none. */
|
|
47
|
+
token: () => string | null;
|
|
48
|
+
/** `false`: never open the direct link. */
|
|
49
|
+
direct?: boolean;
|
|
50
|
+
iceServers?: RTCIceServer[];
|
|
51
|
+
logger?: Pick<Logger, 'debug' | 'warn'>;
|
|
52
|
+
/** Injectable for tests and non-browser runtimes. */
|
|
53
|
+
WebSocket?: typeof WebSocket;
|
|
54
|
+
RTCPeerConnection?: typeof RTCPeerConnection;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const PROTOCOL = 1;
|
|
58
|
+
const RETRY_BASE_MS = 500;
|
|
59
|
+
const RETRY_MAX_MS = 30_000;
|
|
60
|
+
/** After a refusal that a retry will not fix soon (not signed in at the relay, room full). */
|
|
61
|
+
const RETRY_REFUSED_MS = 30_000;
|
|
62
|
+
const BEAT_MS = 20_000;
|
|
63
|
+
|
|
64
|
+
const SIGNAL_KINDS: ReadonlySet<string> = new Set<SignalKind>(['hello', 'offer', 'answer', 'ice']);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Two spellings of one record id. The database prints a key the way it would
|
|
68
|
+
* have to be written (`user:⟨a-b⟩`, backticks, or `user:u'0190…'` for a
|
|
69
|
+
* uuid), the client keeps it bare (`user:a-b`): the wrapping is not part of
|
|
70
|
+
* who it is. Verified against SurrealDB 4.0.1.
|
|
71
|
+
*/
|
|
72
|
+
const bareId = (id: string): string => {
|
|
73
|
+
const at = id.indexOf(':');
|
|
74
|
+
return id.slice(0, at + 1) + id.slice(at + 1).replace(/^u(?=['"])/, '').replace(/[⟨⟩`'"]/g, '');
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export const sameUser = (a: string, b: string): boolean => bareId(a) === bareId(b);
|
|
78
|
+
|
|
79
|
+
/** Whether this runtime can hold a room link at all. */
|
|
80
|
+
export const roomSupported = (ws?: typeof WebSocket): boolean =>
|
|
81
|
+
(ws ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket) !== undefined;
|
|
82
|
+
|
|
83
|
+
export function roomLink(hooks: RoomLinkHooks, opts: RoomLinkOptions): RoomLink {
|
|
84
|
+
const WS = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
|
|
85
|
+
const log = opts.logger;
|
|
86
|
+
const peers = new Set<RoomPeer>();
|
|
87
|
+
/** Members the data channel to is open: they get their messages there. */
|
|
88
|
+
const directOpen = new Set<RoomPeer>();
|
|
89
|
+
let socket: WebSocket | null = null;
|
|
90
|
+
let welcomed = false;
|
|
91
|
+
let closed = false;
|
|
92
|
+
let attempts = 0;
|
|
93
|
+
let retry: ReturnType<typeof setTimeout> | null = null;
|
|
94
|
+
let beat: ReturnType<typeof setInterval> | null = null;
|
|
95
|
+
let awaitingPong = false;
|
|
96
|
+
let onSignal: ((s: Signal) => void) | null = null;
|
|
97
|
+
|
|
98
|
+
const relay = (to: ReadonlyArray<RoomPeer> | null, d: unknown): void => {
|
|
99
|
+
const ws = socket;
|
|
100
|
+
if (!ws || !welcomed || ws.readyState !== 1) return;
|
|
101
|
+
try {
|
|
102
|
+
ws.send(JSON.stringify(to === null ? { t: 'msg', d } : { t: 'msg', to, d }));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
log?.debug({ error, Category: 'sp00ky-client::channel' }, 'room send failed');
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// The direct link is the WebRTC transport the channels between users use,
|
|
109
|
+
// with the relay as its signaling: both ends are members of one room, which
|
|
110
|
+
// is what proves they are the same user.
|
|
111
|
+
const direct: ChannelTransport | null =
|
|
112
|
+
opts.direct === false
|
|
113
|
+
? null
|
|
114
|
+
: webrtcTransport(
|
|
115
|
+
{
|
|
116
|
+
self: () => hooks.self(),
|
|
117
|
+
onPeer: (ref, up) => {
|
|
118
|
+
if (up) directOpen.add(ref.peer);
|
|
119
|
+
else directOpen.delete(ref.peer);
|
|
120
|
+
},
|
|
121
|
+
onMessage: (ref, message) => {
|
|
122
|
+
if (peers.has(ref.peer)) hooks.onMessage(ref.peer, message);
|
|
123
|
+
},
|
|
124
|
+
onStatus: () => {},
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
signal: {
|
|
128
|
+
send: async (s) => relay(s.toPeer === null ? null : [s.toPeer], { s: { kind: s.kind, payload: s.payload, toPeer: s.toPeer } }),
|
|
129
|
+
listen: (_self, cb) => {
|
|
130
|
+
onSignal = cb;
|
|
131
|
+
return () => {
|
|
132
|
+
if (onSignal === cb) onSignal = null;
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
iceServers: opts.iceServers,
|
|
137
|
+
logger: log,
|
|
138
|
+
RTCPeerConnection: opts.RTCPeerConnection,
|
|
139
|
+
}
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
/** The direct link is for two: wanted while there is exactly one other member. */
|
|
143
|
+
const syncDirect = (): void => {
|
|
144
|
+
const self = hooks.self();
|
|
145
|
+
direct?.want(new Set(self && welcomed && peers.size === 1 ? [self.user] : []));
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const stopBeat = (): void => {
|
|
149
|
+
if (beat) clearInterval(beat);
|
|
150
|
+
beat = null;
|
|
151
|
+
awaitingPong = false;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const scheduleRetry = (delay: number): void => {
|
|
155
|
+
if (closed || retry) return;
|
|
156
|
+
retry = setTimeout(() => {
|
|
157
|
+
retry = null;
|
|
158
|
+
connect();
|
|
159
|
+
}, delay);
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** The socket is gone: every member with it, and the direct link (it has nobody to prove its peer anymore). */
|
|
163
|
+
const dropped = (delay?: number): void => {
|
|
164
|
+
socket = null;
|
|
165
|
+
stopBeat();
|
|
166
|
+
const was = [...peers];
|
|
167
|
+
peers.clear();
|
|
168
|
+
welcomed = false;
|
|
169
|
+
syncDirect();
|
|
170
|
+
for (const p of was) hooks.onPeer(p, false);
|
|
171
|
+
if (closed) return;
|
|
172
|
+
attempts++;
|
|
173
|
+
hooks.onStatus(attempts > 2 || delay !== undefined ? 'failed' : 'connecting');
|
|
174
|
+
scheduleRetry(delay ?? Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (attempts - 1)) * (0.75 + Math.random() * 0.5));
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const onFrame = (ws: WebSocket, text: string, self: { user: string; peer: RoomPeer }): void => {
|
|
178
|
+
let f: Record<string, unknown>;
|
|
179
|
+
try {
|
|
180
|
+
const parsed: unknown = JSON.parse(text);
|
|
181
|
+
if (parsed === null || typeof parsed !== 'object') return;
|
|
182
|
+
f = parsed as Record<string, unknown>;
|
|
183
|
+
} catch {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
switch (f.t) {
|
|
187
|
+
case 'welcome': {
|
|
188
|
+
if (welcomed) return;
|
|
189
|
+
if (typeof f.user !== 'string' || !sameUser(f.user, self.user)) {
|
|
190
|
+
// The token belongs to somebody else than the client thinks is
|
|
191
|
+
// signed in: not a room to speak in under this name.
|
|
192
|
+
log?.warn({ Category: 'sp00ky-client::channel' }, 'the room relay answered for another user; not joining');
|
|
193
|
+
socket = null;
|
|
194
|
+
ws.close();
|
|
195
|
+
dropped(RETRY_REFUSED_MS);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
welcomed = true;
|
|
199
|
+
attempts = 0;
|
|
200
|
+
awaitingPong = false;
|
|
201
|
+
beat = setInterval(() => {
|
|
202
|
+
// Two beats without an answer in between: the socket is dead, however
|
|
203
|
+
// far apart a hidden tab's timers were allowed to fire.
|
|
204
|
+
if (awaitingPong) return ws.close();
|
|
205
|
+
awaitingPong = true;
|
|
206
|
+
try {
|
|
207
|
+
ws.send('{"t":"ping"}');
|
|
208
|
+
} catch {
|
|
209
|
+
// closing: `onclose` does the rest
|
|
210
|
+
}
|
|
211
|
+
}, BEAT_MS);
|
|
212
|
+
hooks.onStatus('connected');
|
|
213
|
+
for (const p of Array.isArray(f.peers) ? f.peers : []) {
|
|
214
|
+
if (typeof p !== 'string' || p === self.peer || peers.has(p)) continue;
|
|
215
|
+
peers.add(p);
|
|
216
|
+
hooks.onPeer(p, true);
|
|
217
|
+
}
|
|
218
|
+
syncDirect();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
case 'join': {
|
|
222
|
+
if (!welcomed || typeof f.peer !== 'string' || f.peer === self.peer || peers.has(f.peer)) return;
|
|
223
|
+
peers.add(f.peer);
|
|
224
|
+
hooks.onPeer(f.peer, true);
|
|
225
|
+
syncDirect();
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
case 'leave': {
|
|
229
|
+
if (typeof f.peer !== 'string' || !peers.delete(f.peer)) return;
|
|
230
|
+
hooks.onPeer(f.peer, false);
|
|
231
|
+
syncDirect();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
case 'msg': {
|
|
235
|
+
if (typeof f.from !== 'string' || !peers.has(f.from) || f.d === null || typeof f.d !== 'object') return;
|
|
236
|
+
const d = f.d as { s?: unknown; m?: unknown };
|
|
237
|
+
if (d.s !== undefined) {
|
|
238
|
+
const s = d.s as { kind?: unknown; payload?: unknown; toPeer?: unknown } | null;
|
|
239
|
+
if (!s || typeof s.kind !== 'string' || !SIGNAL_KINDS.has(s.kind)) return;
|
|
240
|
+
onSignal?.({
|
|
241
|
+
from: self.user,
|
|
242
|
+
fromPeer: f.from,
|
|
243
|
+
toPeer: typeof s.toPeer === 'string' ? s.toPeer : null,
|
|
244
|
+
kind: s.kind as SignalKind,
|
|
245
|
+
payload: typeof s.payload === 'string' ? s.payload : null,
|
|
246
|
+
});
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if ('m' in d) hooks.onMessage(f.from, d.m);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
case 'pong':
|
|
253
|
+
awaitingPong = false;
|
|
254
|
+
return;
|
|
255
|
+
case 'error': {
|
|
256
|
+
const code = typeof f.code === 'string' ? f.code : 'unknown';
|
|
257
|
+
log?.debug({ code, Category: 'sp00ky-client::channel' }, 'room relay refused');
|
|
258
|
+
socket = null;
|
|
259
|
+
ws.close();
|
|
260
|
+
// `reauth` is the relay ending a long session: come back with the
|
|
261
|
+
// token of now. Everything else is not fixed by asking again at once.
|
|
262
|
+
if (code === 'reauth') {
|
|
263
|
+
attempts = 0;
|
|
264
|
+
dropped();
|
|
265
|
+
} else dropped(RETRY_REFUSED_MS);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
function connect(): void {
|
|
272
|
+
if (closed || socket || !WS) return;
|
|
273
|
+
const self = hooks.self();
|
|
274
|
+
if (!self) return;
|
|
275
|
+
const token = opts.token();
|
|
276
|
+
if (!token) {
|
|
277
|
+
// Signed in, and the session has no token yet (it is being restored).
|
|
278
|
+
scheduleRetry(RETRY_BASE_MS);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
let ws: WebSocket;
|
|
282
|
+
try {
|
|
283
|
+
ws = new WS(opts.url);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
log?.warn({ error, Category: 'sp00ky-client::channel' }, 'the room relay address cannot be opened');
|
|
286
|
+
hooks.onStatus('failed');
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
socket = ws;
|
|
290
|
+
ws.onopen = () => {
|
|
291
|
+
if (socket === ws) ws.send(JSON.stringify({ t: 'hello', v: PROTOCOL, token, peer: self.peer }));
|
|
292
|
+
};
|
|
293
|
+
ws.onmessage = (event: MessageEvent) => {
|
|
294
|
+
if (socket === ws && typeof event.data === 'string') onFrame(ws, event.data, self);
|
|
295
|
+
};
|
|
296
|
+
ws.onclose = () => {
|
|
297
|
+
if (socket === ws) dropped();
|
|
298
|
+
};
|
|
299
|
+
ws.onerror = () => {
|
|
300
|
+
// `onclose` follows and does the work.
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
hooks.onStatus('connecting');
|
|
305
|
+
connect();
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
send(to, data) {
|
|
309
|
+
if (closed || !welcomed) return;
|
|
310
|
+
const self = hooks.self();
|
|
311
|
+
const targets = to === null ? [...peers] : to.filter((p) => peers.has(p));
|
|
312
|
+
const viaRelay: RoomPeer[] = [];
|
|
313
|
+
for (const p of targets) {
|
|
314
|
+
if (direct && self && directOpen.has(p)) direct.send({ user: self.user, peer: p }, data as ChannelWire);
|
|
315
|
+
else viaRelay.push(p);
|
|
316
|
+
}
|
|
317
|
+
if (viaRelay.length > 0) relay(viaRelay.length === peers.size ? null : viaRelay, { m: data });
|
|
318
|
+
},
|
|
319
|
+
close() {
|
|
320
|
+
if (closed) return;
|
|
321
|
+
closed = true;
|
|
322
|
+
if (retry) clearTimeout(retry);
|
|
323
|
+
retry = null;
|
|
324
|
+
stopBeat();
|
|
325
|
+
direct?.close();
|
|
326
|
+
const ws = socket;
|
|
327
|
+
socket = null;
|
|
328
|
+
welcomed = false;
|
|
329
|
+
peers.clear();
|
|
330
|
+
directOpen.clear();
|
|
331
|
+
try {
|
|
332
|
+
ws?.close();
|
|
333
|
+
} catch {
|
|
334
|
+
// already gone
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* One transport out of two: the user's own devices are reached through
|
|
342
|
+
* `own` (the room), everybody else through `others` (the mesh between
|
|
343
|
+
* users). Without `own`, the user's own devices are simply never reached.
|
|
344
|
+
*/
|
|
345
|
+
export function splitTransport(own: ChannelTransportFactory | null, others: ChannelTransportFactory): ChannelTransportFactory {
|
|
346
|
+
return (hooks: TransportHooks): ChannelTransport => {
|
|
347
|
+
const mesh = others(hooks);
|
|
348
|
+
const room = own ? own(hooks) : null;
|
|
349
|
+
return {
|
|
350
|
+
supported: mesh.supported || (room?.supported ?? false),
|
|
351
|
+
want(users) {
|
|
352
|
+
const self = hooks.self()?.user ?? null;
|
|
353
|
+
const rest = new Set(users);
|
|
354
|
+
const mine = self !== null && rest.delete(self);
|
|
355
|
+
room?.want(new Set(mine && self !== null ? [self] : []));
|
|
356
|
+
mesh.want(rest);
|
|
357
|
+
},
|
|
358
|
+
send(to, message) {
|
|
359
|
+
(room && to.user === hooks.self()?.user ? room : mesh).send(to, message);
|
|
360
|
+
},
|
|
361
|
+
close() {
|
|
362
|
+
room?.close();
|
|
363
|
+
mesh.close();
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
};
|
|
367
|
+
}
|