@stefan.inc/game-networking 0.0.0-stage → 0.1.0

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/src/wire.ts ADDED
@@ -0,0 +1,167 @@
1
+ import type { Patch } from "./patch.ts";
2
+ import { ID_PATTERN } from "./signal-protocol.ts";
3
+ import { MAX_FRAME_BYTES } from "./transport.ts";
4
+ import { NetError, type PeerId, type PeerInfo } from "./types.ts";
5
+
6
+ export type ReliableWire =
7
+ | { t: "hello"; name: string }
8
+ | { t: "roster"; peers: PeerInfo[] }
9
+ | { t: "msg"; d: unknown }
10
+ /** The whole state, as it stood after the host's change number `seq`. */
11
+ | { t: "state"; seq: number; state: unknown }
12
+ /** What change `seq` did to the state this peer was last sent, which was change `base`. */
13
+ | { t: "patch"; seq: number; base: number; patch: Patch[] }
14
+ /** A peer that cannot apply a patch asks for the whole state. */
15
+ | { t: "resync" }
16
+ | { t: "replaced" }
17
+ | { t: "removed"; reason: string };
18
+
19
+ /** `from` is set only host to peer. The host never trusts a peer's claim and uses the link's id. */
20
+ export type LossyWire = { d: unknown; from?: PeerId };
21
+
22
+ const MORE = 0;
23
+ const LAST = 1;
24
+ const MAX_MESSAGE_BYTES = 32 * 1024 * 1024;
25
+
26
+ const encoder = new TextEncoder();
27
+ const decoder = new TextDecoder();
28
+
29
+ /**
30
+ * The reliable lane is ordered and a message's frames are sent back to back, so one header byte saying whether more
31
+ * frames follow is all reassembly needs.
32
+ */
33
+ export function encodeReliable(wire: ReliableWire): Uint8Array[] {
34
+ const bytes = encoder.encode(JSON.stringify(wire));
35
+ const body = MAX_FRAME_BYTES - 1;
36
+ const frames: Uint8Array[] = [];
37
+ for (let offset = 0; ; offset += body) {
38
+ const end = Math.min(offset + body, bytes.length);
39
+ const frame = new Uint8Array(1 + end - offset);
40
+ frame[0] = end === bytes.length ? LAST : MORE;
41
+ frame.set(bytes.subarray(offset, end), 1);
42
+ frames.push(frame);
43
+ if (end === bytes.length) return frames;
44
+ }
45
+ }
46
+
47
+ export function createReassembler() {
48
+ let parts: Uint8Array[] = [];
49
+ let size = 0;
50
+ return {
51
+ push(frame: Uint8Array): ReliableWire | undefined {
52
+ parts.push(frame.subarray(1));
53
+ size += frame.length - 1;
54
+ if (size > MAX_MESSAGE_BYTES) {
55
+ parts = [];
56
+ size = 0;
57
+ throw new NetError("protocol", `Message exceeds ${MAX_MESSAGE_BYTES} bytes`);
58
+ }
59
+ if (frame[0] !== LAST) return undefined;
60
+ const bytes = new Uint8Array(size);
61
+ let offset = 0;
62
+ for (const part of parts) {
63
+ bytes.set(part, offset);
64
+ offset += part.length;
65
+ }
66
+ parts = [];
67
+ size = 0;
68
+ return parseReliable(decodeJson(bytes));
69
+ },
70
+ };
71
+ }
72
+
73
+ export function encodeLossy(wire: LossyWire): Uint8Array {
74
+ const frame = encoder.encode(JSON.stringify(wire));
75
+ if (frame.length > MAX_FRAME_BYTES)
76
+ throw new RangeError(`Presence must encode to at most ${MAX_FRAME_BYTES} bytes`);
77
+ return frame;
78
+ }
79
+
80
+ export function decodeLossy(frame: Uint8Array): LossyWire {
81
+ const raw = decodeJson(frame);
82
+ if (!isRecord(raw) || !("d" in raw)) throw new NetError("protocol", "Malformed presence frame");
83
+ if (raw.from === undefined) return { d: raw.d };
84
+ if (isPeerId(raw.from)) return { d: raw.d, from: raw.from };
85
+ throw new NetError("protocol", "Malformed presence sender");
86
+ }
87
+
88
+ function parseReliable(raw: unknown): ReliableWire {
89
+ if (isRecord(raw)) {
90
+ if (raw.t === "hello" && typeof raw.name === "string") return { t: "hello", name: raw.name };
91
+ if (raw.t === "roster" && Array.isArray(raw.peers) && raw.peers.every(isPeerInfo))
92
+ return { t: "roster", peers: raw.peers };
93
+ if (raw.t === "msg" && "d" in raw) return { t: "msg", d: raw.d };
94
+ if (raw.t === "state" && isCount(raw.seq) && "state" in raw)
95
+ return { t: "state", seq: raw.seq, state: raw.state };
96
+ if (
97
+ raw.t === "patch" &&
98
+ isCount(raw.seq) &&
99
+ isCount(raw.base) &&
100
+ Array.isArray(raw.patch) &&
101
+ raw.patch.every(isPatch)
102
+ )
103
+ return { t: "patch", seq: raw.seq, base: raw.base, patch: raw.patch };
104
+ if (raw.t === "resync") return { t: "resync" };
105
+ if (raw.t === "replaced") return { t: "replaced" };
106
+ if (raw.t === "removed" && typeof raw.reason === "string")
107
+ return { t: "removed", reason: raw.reason };
108
+ }
109
+ throw new NetError("protocol", "Malformed reliable frame");
110
+ }
111
+
112
+ function decodeJson(bytes: Uint8Array): unknown {
113
+ try {
114
+ return JSON.parse(decoder.decode(bytes));
115
+ } catch (error) {
116
+ throw new NetError("protocol", "Frame is not valid JSON", { cause: error });
117
+ }
118
+ }
119
+
120
+ /** The fields a frame may carry, none of them checked yet. Named, so a game's strictest compiler settings pass. */
121
+ type Raw = Partial<
122
+ Record<
123
+ | "t"
124
+ | "name"
125
+ | "peers"
126
+ | "d"
127
+ | "from"
128
+ | "seq"
129
+ | "base"
130
+ | "state"
131
+ | "patch"
132
+ | "reason"
133
+ | "p"
134
+ | "id"
135
+ | "connected",
136
+ unknown
137
+ >
138
+ >;
139
+
140
+ function isRecord(value: unknown): value is Raw {
141
+ return typeof value === "object" && value !== null && !Array.isArray(value);
142
+ }
143
+
144
+ function isCount(value: unknown): value is number {
145
+ return Number.isSafeInteger(value) && (value as number) >= 0;
146
+ }
147
+
148
+ function isPatch(value: unknown): value is Patch {
149
+ return (
150
+ isRecord(value) &&
151
+ Array.isArray(value.p) &&
152
+ value.p.every((key) => typeof key === "string" || isCount(key))
153
+ );
154
+ }
155
+
156
+ function isPeerId(value: unknown): value is PeerId {
157
+ return typeof value === "string" && ID_PATTERN.test(value);
158
+ }
159
+
160
+ function isPeerInfo(value: unknown): value is PeerInfo {
161
+ return (
162
+ isRecord(value) &&
163
+ isPeerId(value.id) &&
164
+ typeof value.name === "string" &&
165
+ typeof value.connected === "boolean"
166
+ );
167
+ }
@@ -0,0 +1,287 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import {
3
+ DEFAULT_ROOM,
4
+ ID_PATTERN,
5
+ KEEPALIVE,
6
+ MAX_ROOM_INFO_LENGTH,
7
+ SignalClose,
8
+ type ClientMessage,
9
+ type IceServer,
10
+ type RoomListing,
11
+ type ServerMessage,
12
+ } from "../signal-protocol.ts";
13
+
14
+ /**
15
+ * What the Worker that mounts this needs: the `SignalHub` binding and, unless it runs open, `SIGNAL_SECRET`. A
16
+ * Cloudflare TURN key is optional: without one, players connect directly or not at all.
17
+ */
18
+ export type SignalEnv = {
19
+ SIGNAL_HUB: DurableObjectNamespace<SignalHub>;
20
+ SIGNAL_SECRET?: string;
21
+ TURN_KEY_ID?: string;
22
+ TURN_KEY_API_TOKEN?: string;
23
+ };
24
+
25
+ type Member = { role: "host" | "peer"; room: string; id: string; at: number; info: unknown };
26
+ type Attachment = Member | { role: "watch" };
27
+
28
+ /** How long the relay credentials handed to players work, and how long one set is handed out before a new one is made. */
29
+ const ICE_TTL_SECONDS = 24 * 60 * 60;
30
+ const ICE_REUSE_MS = 6 * 60 * 60 * 1000;
31
+ /**
32
+ * A client pings every 30 seconds. A host silent for this long has gone without closing, as a laptop that went to
33
+ * sleep does: its room is free to host again and leaves the room list.
34
+ */
35
+ const GONE_MS = 150_000;
36
+
37
+ /**
38
+ * Every room of one deployment. It only relays offers, answers, and ICE candidates between a room's host and the
39
+ * peers that are connecting, and tells watchers which rooms are listed; game traffic never touches it. All state
40
+ * lives in socket tags and attachments, so hibernation loses nothing and the object stores no rows.
41
+ *
42
+ * One object holds all rooms, not one each: this is for a group of friends, signaling is a handful of messages per
43
+ * connection, and the room list is then a read of the open sockets.
44
+ */
45
+ export class SignalHub extends DurableObject<SignalEnv> {
46
+ constructor(ctx: DurableObjectState, env: SignalEnv) {
47
+ super(ctx, env);
48
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(KEEPALIVE.ping, KEEPALIVE.pong));
49
+ }
50
+
51
+ private ice: { at: number; servers: IceServer[] } | null = null;
52
+
53
+ /**
54
+ * Relay servers with short-lived credentials. Two players behind strict NATs or firewalls have no direct path,
55
+ * and their traffic then goes through Cloudflare's TURN service. A failure here leaves players with direct
56
+ * connections only, which is what they have without a key.
57
+ */
58
+ private async iceServers(): Promise<IceServer[]> {
59
+ const { TURN_KEY_ID, TURN_KEY_API_TOKEN } = this.env;
60
+ if (!TURN_KEY_ID || !TURN_KEY_API_TOKEN) return [];
61
+ if (this.ice && Date.now() - this.ice.at < ICE_REUSE_MS) return this.ice.servers;
62
+ try {
63
+ const response = await fetch(
64
+ `https://rtc.live.cloudflare.com/v1/turn/keys/${TURN_KEY_ID}/credentials/generate-ice-servers`,
65
+ {
66
+ method: "POST",
67
+ headers: {
68
+ Authorization: `Bearer ${TURN_KEY_API_TOKEN}`,
69
+ "Content-Type": "application/json",
70
+ },
71
+ body: JSON.stringify({ ttl: ICE_TTL_SECONDS }),
72
+ },
73
+ );
74
+ if (!response.ok) throw new Error(`TURN credentials: ${response.status}`);
75
+ const { iceServers } = (await response.json()) as { iceServers: IceServer[] };
76
+ this.ice = { at: Date.now(), servers: iceServers };
77
+ return iceServers;
78
+ } catch (error) {
79
+ console.warn(error);
80
+ return this.ice?.servers ?? [];
81
+ }
82
+ }
83
+
84
+ override async fetch(request: Request): Promise<Response> {
85
+ const url = new URL(request.url);
86
+ const role = url.searchParams.get("role") as Attachment["role"];
87
+ const [client, server] = Object.values(new WebSocketPair()) as [WebSocket, WebSocket];
88
+
89
+ if (role === "watch") {
90
+ this.ctx.acceptWebSocket(server, ["watch"]);
91
+ server.serializeAttachment({ role } satisfies Attachment);
92
+ send(server, { t: "rooms", rooms: this.rooms() });
93
+ return new Response(null, { status: 101, webSocket: client });
94
+ }
95
+
96
+ const room = url.searchParams.get("room") ?? DEFAULT_ROOM;
97
+ const id = url.searchParams.get("id")!;
98
+ // Fetched before anything below reads who is connected, so the rest runs without a pause in it.
99
+ const servers = await this.iceServers();
100
+
101
+ const closed = new Set<WebSocket>();
102
+ const end = (ws: WebSocket, code: number, reason: string) => {
103
+ closed.add(ws);
104
+ ws.close(code, reason);
105
+ };
106
+ if (role === "host") {
107
+ for (const other of this.ctx.getWebSockets(hostTag(room))) {
108
+ if (other.readyState !== WebSocket.OPEN || member(other).id === id) continue;
109
+ if (!this.alive(other)) end(other, SignalClose.gone, "gone");
110
+ else if (url.searchParams.has("takeover")) end(other, SignalClose.replaced, "replaced");
111
+ else return rejectSocket(SignalClose.hostTaken, `${member(other).id} is already hosting`);
112
+ }
113
+ }
114
+ // One tab per player, and the newest wins. A tab that joins the room its own player hosts would close the
115
+ // host and with it the game, so there it is the newcomer that is turned away.
116
+ for (const same of this.open(idTag(room, id))) {
117
+ if (role === "peer" && member(same).role === "host")
118
+ return rejectSocket(SignalClose.replaced, "this id hosts the room");
119
+ end(same, SignalClose.replaced, "replaced");
120
+ }
121
+
122
+ this.ctx.acceptWebSocket(
123
+ server,
124
+ role === "host" ? ["host", hostTag(room), idTag(room, id)] : [peerTag(room), idTag(room, id)],
125
+ );
126
+ server.serializeAttachment({ role, room, id, at: Date.now(), info: null } satisfies Attachment);
127
+ send(server, { t: "ice", servers });
128
+
129
+ if (role === "host") {
130
+ send(server, { t: "ready" });
131
+ for (const peer of this.open(peerTag(room))) send(peer, { t: "host", id });
132
+ } else {
133
+ const host = this.host(room, closed);
134
+ send(server, { t: "host", id: host ? member(host).id : null });
135
+ }
136
+ if ([...closed].some((ws) => listed(ws))) this.announce(closed);
137
+ return new Response(null, { status: 101, webSocket: client });
138
+ }
139
+
140
+ override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
141
+ const from = attachment(ws);
142
+ const msg = typeof message === "string" ? parseClientMessage(message) : null;
143
+ if (!msg || from.role === "watch") return;
144
+ if (msg.t === "signal") {
145
+ const target = this.open(idTag(from.room, msg.to))[0];
146
+ if (!target || member(target).role === from.role) return;
147
+ send(target, { t: "signal", from: from.id, data: msg.data });
148
+ } else if (from.role === "host") {
149
+ ws.serializeAttachment({ ...from, info: msg.info } satisfies Attachment);
150
+ this.announce();
151
+ }
152
+ }
153
+
154
+ override async webSocketClose(ws: WebSocket): Promise<void> {
155
+ this.left(ws);
156
+ }
157
+
158
+ override async webSocketError(ws: WebSocket): Promise<void> {
159
+ this.left(ws);
160
+ }
161
+
162
+ private left(ws: WebSocket) {
163
+ const from = attachment(ws);
164
+ if (from.role !== "host") return;
165
+ const gone = new Set([ws]);
166
+ if (!this.host(from.room, gone))
167
+ for (const peer of this.open(peerTag(from.room))) send(peer, { t: "host", id: null });
168
+ if (from.info !== null) this.announce(gone);
169
+ }
170
+
171
+ private open(tag: string): WebSocket[] {
172
+ return this.ctx.getWebSockets(tag).filter((ws) => ws.readyState === WebSocket.OPEN);
173
+ }
174
+
175
+ private alive(ws: WebSocket): boolean {
176
+ const seen = this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? member(ws).at;
177
+ return Date.now() - seen < GONE_MS;
178
+ }
179
+
180
+ private host(room: string, except: Set<WebSocket>): WebSocket | undefined {
181
+ return this.open(hostTag(room)).find((ws) => !except.has(ws) && this.alive(ws));
182
+ }
183
+
184
+ private rooms(except?: Set<WebSocket>): RoomListing[] {
185
+ return this.open("host")
186
+ .filter((ws) => !except?.has(ws) && listed(ws) && this.alive(ws))
187
+ .map((ws) => {
188
+ const { room, id, info } = member(ws);
189
+ return { room, host: id, info };
190
+ })
191
+ .sort((a, b) => (a.room < b.room ? -1 : 1));
192
+ }
193
+
194
+ private announce(except?: Set<WebSocket>) {
195
+ const watchers = this.open("watch");
196
+ if (watchers.length === 0) return;
197
+ const rooms = this.rooms(except);
198
+ for (const watcher of watchers) send(watcher, { t: "rooms", rooms });
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The Worker's side of signaling: checks the request and the secret, then hands the socket to the hub. Mount it on
204
+ * the path the game gives its transport as `signalUrl`. A Worker without `SIGNAL_SECRET` fails every connection
205
+ * unless it is mounted with `open`, where knowing a room's name is all it takes to join it.
206
+ */
207
+ export async function handleSignal(
208
+ request: Request,
209
+ env: SignalEnv,
210
+ options: { open?: boolean } = {},
211
+ ): Promise<Response> {
212
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket")
213
+ return new Response("Expected a WebSocket upgrade", { status: 426 });
214
+
215
+ const { searchParams } = new URL(request.url);
216
+ const role = searchParams.get("role");
217
+ if (role !== "host" && role !== "peer" && role !== "watch")
218
+ return new Response("Expected role=host|peer|watch", { status: 400 });
219
+ if (
220
+ role !== "watch" &&
221
+ !(
222
+ ID_PATTERN.test(searchParams.get("id") ?? "") &&
223
+ ID_PATTERN.test(searchParams.get("room") ?? DEFAULT_ROOM)
224
+ )
225
+ )
226
+ return new Response("Expected a valid id and room", { status: 400 });
227
+
228
+ if (!options.open) {
229
+ if (!env.SIGNAL_SECRET)
230
+ throw new Error("SIGNAL_SECRET is not configured: set it, or mount handleSignal with open");
231
+ if (!(await secretMatches(searchParams.get("secret") ?? "", env.SIGNAL_SECRET)))
232
+ return rejectSocket(SignalClose.unauthorized, "unauthorized");
233
+ }
234
+ return env.SIGNAL_HUB.getByName("hub").fetch(request);
235
+ }
236
+
237
+ /** Browsers hide HTTP status on a failed upgrade, so refusals complete the upgrade and close with a code they can read. */
238
+ function rejectSocket(code: number, reason: string): Response {
239
+ const [client, server] = Object.values(new WebSocketPair()) as [WebSocket, WebSocket];
240
+ server.accept();
241
+ server.close(code, reason);
242
+ return new Response(null, { status: 101, webSocket: client });
243
+ }
244
+
245
+ async function secretMatches(given: string, expected: string): Promise<boolean> {
246
+ const encoder = new TextEncoder();
247
+ const [a, b] = await Promise.all([
248
+ crypto.subtle.digest("SHA-256", encoder.encode(given)),
249
+ crypto.subtle.digest("SHA-256", encoder.encode(expected)),
250
+ ]);
251
+ return crypto.subtle.timingSafeEqual(a, b);
252
+ }
253
+
254
+ const hostTag = (room: string) => `host:${room}`;
255
+ const peerTag = (room: string) => `peer:${room}`;
256
+ const idTag = (room: string, id: string) => `id:${room}/${id}`;
257
+
258
+ function attachment(ws: WebSocket): Attachment {
259
+ return ws.deserializeAttachment() as Attachment;
260
+ }
261
+
262
+ /** The attachment of a socket found by a host, peer or id tag, which no watcher carries. */
263
+ function member(ws: WebSocket): Member {
264
+ return ws.deserializeAttachment() as Member;
265
+ }
266
+
267
+ function listed(ws: WebSocket): boolean {
268
+ const from = attachment(ws);
269
+ return from.role === "host" && from.info !== null;
270
+ }
271
+
272
+ function send(ws: WebSocket, msg: ServerMessage): void {
273
+ ws.send(JSON.stringify(msg));
274
+ }
275
+
276
+ function parseClientMessage(text: string): ClientMessage | null {
277
+ try {
278
+ const raw = JSON.parse(text) as Partial<Record<"t" | "to" | "data" | "info", unknown>> | null;
279
+ if (raw?.t === "signal" && typeof raw.to === "string" && ID_PATTERN.test(raw.to))
280
+ return { t: "signal", to: raw.to, data: raw.data };
281
+ if (raw?.t === "publish" && "info" in raw && text.length <= MAX_ROOM_INFO_LENGTH + 64)
282
+ return { t: "publish", info: raw.info ?? null };
283
+ return null;
284
+ } catch {
285
+ return null;
286
+ }
287
+ }