tickflare 0.0.0-stage → 0.2.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.
Files changed (125) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/buffered.d.ts +88 -0
  11. package/dist/client/buffered.js +229 -0
  12. package/dist/client/buffered.js.map +1 -0
  13. package/dist/client/clock.d.ts +36 -0
  14. package/dist/client/clock.js +83 -0
  15. package/dist/client/clock.js.map +1 -0
  16. package/dist/client/draft.d.ts +17 -0
  17. package/dist/client/draft.js +133 -0
  18. package/dist/client/draft.js.map +1 -0
  19. package/dist/client/index.d.ts +182 -0
  20. package/dist/client/index.js +496 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/interpolate.d.ts +31 -0
  23. package/dist/client/interpolate.js +59 -0
  24. package/dist/client/interpolate.js.map +1 -0
  25. package/dist/client/lockstep.d.ts +86 -0
  26. package/dist/client/lockstep.js +339 -0
  27. package/dist/client/lockstep.js.map +1 -0
  28. package/dist/client/matchmaking.d.ts +21 -0
  29. package/dist/client/matchmaking.js +55 -0
  30. package/dist/client/matchmaking.js.map +1 -0
  31. package/dist/client/pacer.d.ts +22 -0
  32. package/dist/client/pacer.js +65 -0
  33. package/dist/client/pacer.js.map +1 -0
  34. package/dist/client/predict.d.ts +75 -0
  35. package/dist/client/predict.js +203 -0
  36. package/dist/client/predict.js.map +1 -0
  37. package/dist/client/token.d.ts +10 -0
  38. package/dist/client/token.js +15 -0
  39. package/dist/client/token.js.map +1 -0
  40. package/dist/lockstep.d.ts +154 -0
  41. package/dist/lockstep.js +140 -0
  42. package/dist/lockstep.js.map +1 -0
  43. package/dist/patch.d.ts +54 -0
  44. package/dist/patch.js +186 -0
  45. package/dist/patch.js.map +1 -0
  46. package/dist/protocol.d.ts +268 -0
  47. package/dist/protocol.js +54 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/dist/server/accounts.d.ts +320 -0
  50. package/dist/server/accounts.js +1223 -0
  51. package/dist/server/accounts.js.map +1 -0
  52. package/dist/server/delta.d.ts +50 -0
  53. package/dist/server/delta.js +426 -0
  54. package/dist/server/delta.js.map +1 -0
  55. package/dist/server/frames.d.ts +15 -0
  56. package/dist/server/frames.js +23 -0
  57. package/dist/server/frames.js.map +1 -0
  58. package/dist/server/gateway.d.ts +80 -0
  59. package/dist/server/gateway.js +144 -0
  60. package/dist/server/gateway.js.map +1 -0
  61. package/dist/server/index.d.ts +21 -0
  62. package/dist/server/index.js +22 -0
  63. package/dist/server/index.js.map +1 -0
  64. package/dist/server/limiter.d.ts +12 -0
  65. package/dist/server/limiter.js +43 -0
  66. package/dist/server/limiter.js.map +1 -0
  67. package/dist/server/lockstep.d.ts +127 -0
  68. package/dist/server/lockstep.js +549 -0
  69. package/dist/server/lockstep.js.map +1 -0
  70. package/dist/server/matches.d.ts +31 -0
  71. package/dist/server/matches.js +69 -0
  72. package/dist/server/matches.js.map +1 -0
  73. package/dist/server/matchmaker.d.ts +121 -0
  74. package/dist/server/matchmaker.js +479 -0
  75. package/dist/server/matchmaker.js.map +1 -0
  76. package/dist/server/room.d.ts +402 -0
  77. package/dist/server/room.js +1896 -0
  78. package/dist/server/room.js.map +1 -0
  79. package/dist/server/signals.d.ts +18 -0
  80. package/dist/server/signals.js +37 -0
  81. package/dist/server/signals.js.map +1 -0
  82. package/dist/server/storage.d.ts +117 -0
  83. package/dist/server/storage.js +330 -0
  84. package/dist/server/storage.js.map +1 -0
  85. package/dist/server/tokens.d.ts +74 -0
  86. package/dist/server/tokens.js +117 -0
  87. package/dist/server/tokens.js.map +1 -0
  88. package/dist/server/tracked.d.ts +47 -0
  89. package/dist/server/tracked.js +270 -0
  90. package/dist/server/tracked.js.map +1 -0
  91. package/dist/world.d.ts +20 -0
  92. package/dist/world.js +21 -0
  93. package/dist/world.js.map +1 -0
  94. package/package.json +74 -4
  95. package/src/binary.ts +496 -0
  96. package/src/client/accounts.ts +423 -0
  97. package/src/client/buffered.ts +264 -0
  98. package/src/client/clock.ts +86 -0
  99. package/src/client/draft.ts +138 -0
  100. package/src/client/index.ts +631 -0
  101. package/src/client/interpolate.ts +60 -0
  102. package/src/client/lockstep.ts +398 -0
  103. package/src/client/matchmaking.ts +61 -0
  104. package/src/client/pacer.ts +67 -0
  105. package/src/client/predict.ts +239 -0
  106. package/src/client/token.ts +22 -0
  107. package/src/lockstep.ts +285 -0
  108. package/src/patch.ts +188 -0
  109. package/src/protocol.ts +300 -0
  110. package/src/server/accounts.ts +1474 -0
  111. package/src/server/delta.ts +467 -0
  112. package/src/server/frames.ts +23 -0
  113. package/src/server/gateway.ts +213 -0
  114. package/src/server/index.ts +86 -0
  115. package/src/server/limiter.ts +41 -0
  116. package/src/server/lockstep.ts +617 -0
  117. package/src/server/matches.ts +99 -0
  118. package/src/server/matchmaker.ts +537 -0
  119. package/src/server/room.ts +1999 -0
  120. package/src/server/signals.ts +46 -0
  121. package/src/server/storage.ts +392 -0
  122. package/src/server/tokens.ts +184 -0
  123. package/src/server/tracked.ts +260 -0
  124. package/src/world.ts +29 -0
  125. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,46 @@
1
+ /** A message from one room to another. */
2
+ export interface Signal {
3
+ to: string;
4
+ data: unknown;
5
+ /** Skip rooms that last reported nobody connected. */
6
+ onlyIfWatched: boolean;
7
+ }
8
+
9
+ /** How long a room that reported nobody connected, or could not be reached, is left alone. */
10
+ const BACK_OFF_MS = 2000;
11
+
12
+ /**
13
+ * Sends committed signals to other rooms. Best effort: each goes out once
14
+ * and is not retried.
15
+ */
16
+ export class SignalSender {
17
+ #waiting: Signal[] = [];
18
+ /** Rooms to leave alone, and until when. */
19
+ #unwatched = new Map<string, number>();
20
+
21
+ get pending(): boolean {
22
+ return this.#waiting.length > 0;
23
+ }
24
+
25
+ add(signals: Signal[]): void {
26
+ this.#waiting.push(...signals);
27
+ }
28
+
29
+ /** Sends everything waiting. `relay` delivers one signal and resolves to whether anyone is connected there. */
30
+ async send(relay: (to: string, data: unknown) => Promise<boolean>): Promise<void> {
31
+ const now = Date.now();
32
+ await Promise.all(
33
+ this.#waiting.splice(0).map(async ({ to, data, onlyIfWatched }) => {
34
+ if (onlyIfWatched && (this.#unwatched.get(to) ?? 0) > now) return;
35
+ try {
36
+ if (await relay(to, data)) this.#unwatched.delete(to);
37
+ else this.#unwatched.set(to, now + BACK_OFF_MS);
38
+ } catch (err) {
39
+ // Not retried by design. Back off so a broken neighbour is not hammered at tick rate.
40
+ this.#unwatched.set(to, now + BACK_OFF_MS);
41
+ console.error(`[tickflare] could not signal ${to}:`, err);
42
+ }
43
+ }),
44
+ );
45
+ }
46
+ }
@@ -0,0 +1,392 @@
1
+ import type { MatchResult } from "../protocol.js";
2
+
3
+ /** The room as last saved. `state` and `roster` are JSON. */
4
+ export interface StoredRoom {
5
+ seq: number;
6
+ state: string;
7
+ roster: string;
8
+ /** How many times the simulation has ticked. 0 in a room that does not tick. */
9
+ tick: number;
10
+ }
11
+
12
+ /** Something a committed hook promised to deliver: a finished match, or a player handed to another room. */
13
+ export type OutboxEntry =
14
+ | { message: MatchResult; replay?: string; move?: undefined }
15
+ | { move: { player: string; to: string; carry: unknown } };
16
+
17
+ /** Where a player who was handed to another room has gone. */
18
+ export interface Forward {
19
+ room: string;
20
+ /** The other room has accepted them. */
21
+ delivered: boolean;
22
+ /** When this stops being followed, in epoch milliseconds. Null until the player has been told. */
23
+ expires: number | null;
24
+ }
25
+
26
+ /**
27
+ * Everything a room keeps in its Durable Object's SQLite database, in one
28
+ * place. Calls are synchronous; writes made within one event are committed
29
+ * together by the runtime.
30
+ *
31
+ * Nothing is written, not even the tables, until the room has something to
32
+ * keep. A Durable Object that never wrote does not exist once it shuts down,
33
+ * so a room that was only looked at, or that refused whoever came, leaves
34
+ * nothing behind.
35
+ *
36
+ * Tables:
37
+ * tickflare_room one row: seq, state, seats, tick counter
38
+ * tickflare_parts the rest of a state or a delivery too long for one row
39
+ * tickflare_timers named timers and when they fire
40
+ * tickflare_meta small values by key (room id, invited players)
41
+ * tickflare_outbox deliveries that are owed (finished matches, handovers)
42
+ * tickflare_arrivals players another room has handed over, until they connect
43
+ * tickflare_forwards players handed to another room, and where they went
44
+ */
45
+ /**
46
+ * The most a piece of text may take in one row, in bytes. Cloudflare allows a
47
+ * row 2 MB. This leaves room for the row's other columns and for whatever
48
+ * the limit turns out to count.
49
+ */
50
+ export const ROW_BYTES = 1_500_000;
51
+
52
+ /**
53
+ * Cuts `text` into pieces of at most `bytes` bytes as UTF-8, so that each
54
+ * fits in a row. Nearly always that is one piece, the text itself, and
55
+ * finding that out costs nothing: a text of n characters is at most 3n bytes.
56
+ * A piece never ends in the middle of a character.
57
+ */
58
+ export function pieces(text: string, bytes = ROW_BYTES): string[] {
59
+ if (text.length * 3 <= bytes) return [text];
60
+ const encoder = new TextEncoder();
61
+ const buffer = new Uint8Array(bytes);
62
+ const out: string[] = [];
63
+ for (let at = 0; at < text.length; ) {
64
+ // A character is at least a byte, so no piece is longer than `bytes` characters, and that
65
+ // many are all that need looking at. `encodeInto` stops before a character it has no room
66
+ // for, a pair of surrogates included. The slice may end between the two of a pair, but then
67
+ // everything before it was one byte each, and the half that is left does not fit either.
68
+ const { read } = encoder.encodeInto(text.slice(at, at + bytes), buffer);
69
+ if (read === 0) throw new RangeError("A row is too small to hold a single character");
70
+ out.push(text.slice(at, at + read));
71
+ at += read;
72
+ }
73
+ return out;
74
+ }
75
+
76
+ export class RoomStorage {
77
+ readonly #storage: DurableObjectStorage;
78
+ readonly #sql: SqlStorage;
79
+ /** The tables are there. */
80
+ #made: boolean;
81
+ /** The id the room is reached under, to be written with the first thing that is. */
82
+ #roomId: string | undefined;
83
+ /**
84
+ * What has pieces in tickflare_parts: "state", or "outbox:" and an entry's
85
+ * id. Empty for nearly every room, which then never looks at the table,
86
+ * or has one.
87
+ */
88
+ #split = new Set<string>();
89
+
90
+ constructor(storage: DurableObjectStorage) {
91
+ this.#storage = storage;
92
+ const sql = (this.#sql = storage.sql);
93
+ this.#made = this.#exists();
94
+ if (!this.#made) return;
95
+ // A room saved by an older version may lack tables and columns that came later: it gets them
96
+ // now, before anything reads them. Making a table that is there already writes nothing.
97
+ this.#tables();
98
+ this.#findSplit();
99
+ // The tick counter used to be a row of its own in tickflare_meta, which made every save of a
100
+ // ticking room two rows. A room that was created before has no column for it yet.
101
+ try {
102
+ sql.exec("SELECT tick FROM tickflare_room LIMIT 0");
103
+ } catch {
104
+ sql.exec("ALTER TABLE tickflare_room ADD COLUMN tick INTEGER NOT NULL DEFAULT 0");
105
+ }
106
+ }
107
+
108
+ /** Creates the tables, before the first thing is written. */
109
+ #make(): void {
110
+ if (this.#made) return;
111
+ this.#sql.exec(
112
+ `CREATE TABLE IF NOT EXISTS tickflare_room (
113
+ id INTEGER PRIMARY KEY CHECK (id = 1),
114
+ seq INTEGER NOT NULL,
115
+ state TEXT NOT NULL,
116
+ players TEXT NOT NULL,
117
+ tick INTEGER NOT NULL DEFAULT 0
118
+ )`,
119
+ );
120
+ this.#tables();
121
+ this.#made = true;
122
+ if (this.#roomId !== undefined) this.setMeta("room", this.#roomId);
123
+ }
124
+
125
+ /**
126
+ * Every table but `tickflare_room`, made if it is not there. A table added to Tickflare goes
127
+ * here, so that rooms saved before it get it too. (`tickflare_parts` is made when first
128
+ * written, and read only once it exists.)
129
+ */
130
+ #tables(): void {
131
+ const sql = this.#sql;
132
+ // WITHOUT ROWID: a table keyed by text otherwise keeps a second index, and every write to it is
133
+ // billed as two rows. These two are written on every save and every timer.
134
+ sql.exec(
135
+ `CREATE TABLE IF NOT EXISTS tickflare_timers (
136
+ name TEXT PRIMARY KEY,
137
+ fire_at INTEGER NOT NULL
138
+ ) WITHOUT ROWID`,
139
+ );
140
+ sql.exec("CREATE TABLE IF NOT EXISTS tickflare_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID");
141
+ sql.exec("CREATE TABLE IF NOT EXISTS tickflare_outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL)");
142
+ sql.exec("CREATE TABLE IF NOT EXISTS tickflare_arrivals (player TEXT PRIMARY KEY, carry TEXT NOT NULL)");
143
+ sql.exec(
144
+ `CREATE TABLE IF NOT EXISTS tickflare_forwards (
145
+ player TEXT PRIMARY KEY,
146
+ room TEXT NOT NULL,
147
+ delivered INTEGER NOT NULL DEFAULT 0,
148
+ expires INTEGER
149
+ )`,
150
+ );
151
+ }
152
+
153
+ /** Whether the room has stored anything at all. */
154
+ get stored(): boolean {
155
+ return this.#made;
156
+ }
157
+
158
+ /**
159
+ * The id the room is reached under. Kept with the room once the room has
160
+ * anything else to keep: knowing its name is no reason for a room to exist.
161
+ */
162
+ rememberRoomId(roomId: string): void {
163
+ this.#roomId = roomId;
164
+ if (this.#made) this.setMeta("room", roomId);
165
+ }
166
+
167
+ /**
168
+ * Runs `work` so that everything it writes to the database is kept
169
+ * together or, if it throws, not at all. Returns what `work` returns.
170
+ */
171
+ atomically<T>(work: () => T): T {
172
+ try {
173
+ return this.#storage.transactionSync(work);
174
+ } catch (error) {
175
+ // What was undone may include the tables themselves, if this was the first thing written,
176
+ // and pieces of a long text that `#split` already counts.
177
+ this.#made = this.#exists();
178
+ this.#findSplit();
179
+ throw error;
180
+ }
181
+ }
182
+
183
+ /** Reads from storage which texts are split. */
184
+ #findSplit(): void {
185
+ this.#split.clear();
186
+ const sql = this.#sql;
187
+ if (sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tickflare_parts'").toArray().length === 0) return;
188
+ for (const { owner } of sql.exec<{ owner: string }>("SELECT DISTINCT owner FROM tickflare_parts")) this.#split.add(owner);
189
+ }
190
+
191
+ #exists(): boolean {
192
+ return this.#sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tickflare_room'").toArray().length > 0;
193
+ }
194
+
195
+ room(): StoredRoom | undefined {
196
+ if (!this.#made) return undefined;
197
+ const row = this.#sql
198
+ .exec<{ seq: number; state: string; players: string; tick: number }>(
199
+ "SELECT seq, state, players, tick FROM tickflare_room WHERE id = 1",
200
+ )
201
+ .toArray()[0];
202
+ return row && { seq: row.seq, state: row.state + this.#rest("state"), roster: row.players, tick: row.tick };
203
+ }
204
+
205
+ /**
206
+ * One row, whatever changed: this is what a save costs. A state too long
207
+ * for a row, which Cloudflare limits to 2 MB, takes a row more for each
208
+ * 1.5 MB.
209
+ */
210
+ writeRoom(room: StoredRoom): void {
211
+ this.#make();
212
+ const [first, ...rest] = pieces(room.state);
213
+ this.#sql.exec(
214
+ "INSERT OR REPLACE INTO tickflare_room (id, seq, state, players, tick) VALUES (1, ?, ?, ?, ?)",
215
+ room.seq,
216
+ first,
217
+ room.roster,
218
+ room.tick,
219
+ );
220
+ this.#putRest("state", rest);
221
+ }
222
+
223
+ /** What follows the first piece of a text that was split, or "" for one that was not. */
224
+ #rest(owner: string): string {
225
+ if (!this.#split.has(owner)) return "";
226
+ return this.#sql
227
+ .exec<{ part: string }>("SELECT part FROM tickflare_parts WHERE owner = ? ORDER BY n", owner)
228
+ .toArray()
229
+ .map((row) => row.part)
230
+ .join("");
231
+ }
232
+
233
+ /** Stores the pieces that follow the first, in place of any that were there. */
234
+ #putRest(owner: string, rest: string[]): void {
235
+ if (rest.length === 0 && !this.#split.has(owner)) return;
236
+ this.#sql.exec(
237
+ `CREATE TABLE IF NOT EXISTS tickflare_parts (
238
+ owner TEXT NOT NULL, n INTEGER NOT NULL, part TEXT NOT NULL, PRIMARY KEY (owner, n)
239
+ ) WITHOUT ROWID`,
240
+ );
241
+ for (const [n, part] of rest.entries()) {
242
+ this.#sql.exec("INSERT OR REPLACE INTO tickflare_parts (owner, n, part) VALUES (?, ?, ?)", owner, n, part);
243
+ }
244
+ this.#sql.exec("DELETE FROM tickflare_parts WHERE owner = ? AND n >= ?", owner, rest.length);
245
+ if (rest.length > 0) this.#split.add(owner);
246
+ else this.#split.delete(owner);
247
+ }
248
+
249
+ /** Timer names and when they fire, ordered by name. */
250
+ timers(): [name: string, firesAt: number][] {
251
+ if (!this.#made) return [];
252
+ return this.#sql
253
+ .exec<{ name: string; fire_at: number }>("SELECT name, fire_at FROM tickflare_timers ORDER BY name")
254
+ .toArray()
255
+ .map((timer) => [timer.name, timer.fire_at]);
256
+ }
257
+
258
+ /** Makes the stored timers match `timers`, writing only the ones that differ: reads are all but free, rows written are not. */
259
+ replaceTimers(timers: Iterable<[name: string, firesAt: number]>): void {
260
+ const wanted = new Map(timers);
261
+ if (wanted.size === 0 && !this.#made) return;
262
+ this.#make();
263
+ for (const [name, firesAt] of this.timers()) {
264
+ if (!wanted.has(name)) this.#sql.exec("DELETE FROM tickflare_timers WHERE name = ?", name);
265
+ else if (wanted.get(name) === firesAt) wanted.delete(name);
266
+ }
267
+ for (const [name, firesAt] of wanted) {
268
+ this.#sql.exec("INSERT OR REPLACE INTO tickflare_timers (name, fire_at) VALUES (?, ?)", name, firesAt);
269
+ }
270
+ }
271
+
272
+ meta(): Map<string, string> {
273
+ if (!this.#made) return new Map();
274
+ return new Map(
275
+ this.#sql
276
+ .exec<{ key: string; value: string }>("SELECT key, value FROM tickflare_meta")
277
+ .toArray()
278
+ .map((row) => [row.key, row.value]),
279
+ );
280
+ }
281
+
282
+ setMeta(key: string, value: string): void {
283
+ this.#make();
284
+ this.#sql.exec("INSERT OR REPLACE INTO tickflare_meta (key, value) VALUES (?, ?)", key, value);
285
+ }
286
+
287
+ hasOutbox(): boolean {
288
+ if (!this.#made) return false;
289
+ return this.#sql.exec("SELECT 1 FROM tickflare_outbox LIMIT 1").toArray().length > 0;
290
+ }
291
+
292
+ /**
293
+ * The oldest thing owed that was added after entry `id`, or undefined when
294
+ * there is none. Entries are numbered in the order they were added, so
295
+ * walking the outbox with this also finds what is added along the way.
296
+ */
297
+ nextInOutbox(after: number): { id: number; entry: OutboxEntry } | undefined {
298
+ if (!this.#made) return undefined;
299
+ const row = this.#sql
300
+ .exec<{ id: number; body: string }>(
301
+ "SELECT id, body FROM tickflare_outbox WHERE id > ? ORDER BY id LIMIT 1",
302
+ after,
303
+ )
304
+ .toArray()[0];
305
+ return row && { id: row.id, entry: JSON.parse(row.body + this.#rest(`outbox:${row.id}`)) as OutboxEntry };
306
+ }
307
+
308
+ /** `body` is an `OutboxEntry` as JSON. A long one, a match with a long recording, is split like the state. */
309
+ addToOutbox(body: string): void {
310
+ this.#make();
311
+ const [first, ...rest] = pieces(body);
312
+ const { id } = this.#sql.exec<{ id: number }>("INSERT INTO tickflare_outbox (body) VALUES (?) RETURNING id", first).one();
313
+ this.#putRest(`outbox:${id}`, rest);
314
+ }
315
+
316
+ removeFromOutbox(id: number): void {
317
+ if (!this.#made) return;
318
+ this.#sql.exec("DELETE FROM tickflare_outbox WHERE id = ?", id);
319
+ this.#putRest(`outbox:${id}`, []);
320
+ }
321
+
322
+ /** What a player handed over by another room carries, as JSON, or undefined if they were not handed over. */
323
+ arrival(player: string): string | undefined {
324
+ if (!this.#made) return undefined;
325
+ return this.#sql
326
+ .exec<{ carry: string }>("SELECT carry FROM tickflare_arrivals WHERE player = ?", player)
327
+ .toArray()[0]?.carry;
328
+ }
329
+
330
+ putArrival(player: string, carry: unknown): void {
331
+ this.#make();
332
+ this.#sql.exec(
333
+ "INSERT OR REPLACE INTO tickflare_arrivals (player, carry) VALUES (?, ?)",
334
+ player,
335
+ JSON.stringify(carry ?? null),
336
+ );
337
+ }
338
+
339
+ removeArrival(player: string): void {
340
+ if (!this.#made) return;
341
+ this.#sql.exec("DELETE FROM tickflare_arrivals WHERE player = ?", player);
342
+ }
343
+
344
+ /** Where `player` was handed to, if they were. */
345
+ forward(player: string): Forward | undefined {
346
+ if (!this.#made) return undefined;
347
+ const row = this.#sql
348
+ .exec<{ room: string; delivered: number; expires: number | null }>(
349
+ "SELECT room, delivered, expires FROM tickflare_forwards WHERE player = ?",
350
+ player,
351
+ )
352
+ .toArray()[0];
353
+ return row && { room: row.room, delivered: row.delivered === 1, expires: row.expires };
354
+ }
355
+
356
+ /** `player` is being handed to `room`. */
357
+ putForward(player: string, room: string): void {
358
+ this.#make();
359
+ this.#sql.exec(
360
+ "INSERT OR REPLACE INTO tickflare_forwards (player, room, delivered, expires) VALUES (?, ?, 0, NULL)",
361
+ player,
362
+ room,
363
+ );
364
+ }
365
+
366
+ /** `room` has accepted `player`. */
367
+ deliverForward(player: string, room: string, expires: number | null): void {
368
+ if (!this.#made) return;
369
+ this.#sql.exec(
370
+ "UPDATE tickflare_forwards SET delivered = 1, expires = ? WHERE player = ? AND room = ?",
371
+ expires,
372
+ player,
373
+ room,
374
+ );
375
+ }
376
+
377
+ expireForward(player: string, expires: number): void {
378
+ if (!this.#made) return;
379
+ this.#sql.exec("UPDATE tickflare_forwards SET expires = ? WHERE player = ?", expires, player);
380
+ }
381
+
382
+ removeForward(player: string): void {
383
+ if (!this.#made) return;
384
+ this.#sql.exec("DELETE FROM tickflare_forwards WHERE player = ?", player);
385
+ }
386
+
387
+ /** Drops the forwards that ran out before `now`. */
388
+ purgeForwards(now: number): void {
389
+ if (!this.#made) return;
390
+ this.#sql.exec("DELETE FROM tickflare_forwards WHERE expires IS NOT NULL AND expires <= ?", now);
391
+ }
392
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Signed join tokens: how a room knows who is connecting without trusting
3
+ * the client.
4
+ *
5
+ * Your own backend creates a token once it knows who the player is (after a
6
+ * login, or when it hands out a guest account). The client presents it when
7
+ * connecting, and `tokenAuth` checks it at the gateway. A token is an
8
+ * HMAC-SHA256 signature over the player id and an expiry, so it cannot be
9
+ * forged or altered without the secret.
10
+ */
11
+
12
+ import type { Authenticated } from "./gateway.js";
13
+
14
+ /** What a join token says. See `createJoinToken`. */
15
+ export interface JoinTokenClaims {
16
+ /** The player this token speaks for. */
17
+ player: string;
18
+ /**
19
+ * The player's account name. Rooms see it as `player.name`. Leave it out
20
+ * for guests: `Accounts` takes a token with a name for a signed-in player.
21
+ */
22
+ name?: string;
23
+ /** If set, the token only opens the room or matchmaking queue with this id. */
24
+ scope?: string;
25
+ /**
26
+ * The party the player queues with: friends who are to be matched
27
+ * together. Every member's token carries the same `id`, and `size` says
28
+ * how many they are. Only your server should make these, once it knows
29
+ * the player is in that party: a player who could name any party could
30
+ * join a stranger's.
31
+ */
32
+ party?: Party;
33
+ /** Lifetime in seconds. Defaults to one hour. */
34
+ expiresIn?: number;
35
+ }
36
+
37
+ /** Friends who queue together. See `JoinTokenClaims.party`. */
38
+ export interface Party {
39
+ /** The same for every member: any string of up to 64 visible characters. */
40
+ id: string;
41
+ /** How many members the party has, the player included. */
42
+ size: number;
43
+ }
44
+
45
+ /** What a valid join token said. See `verifyJoinToken`. */
46
+ export interface VerifiedJoinToken {
47
+ /** The player it speaks for. */
48
+ player: string;
49
+ /** The account name, if it carried one. */
50
+ name?: string;
51
+ /** The room or queue it is limited to, if any. */
52
+ scope?: string;
53
+ /** The party the player queues with, if it carried one. */
54
+ party?: Party;
55
+ /** When it stops working, in epoch seconds. */
56
+ expiresAt: number;
57
+ }
58
+
59
+ interface Payload {
60
+ p: string;
61
+ n?: string;
62
+ s?: string;
63
+ /** The party's id and size. */
64
+ pa?: string;
65
+ ps?: number;
66
+ e: number;
67
+ }
68
+
69
+ const VERSION = "v1";
70
+ const MIN_SECRET_LENGTH = 16;
71
+ const encoder = new TextEncoder();
72
+ const decoder = new TextDecoder();
73
+ const keys = new Map<string, Promise<CryptoKey>>();
74
+
75
+ /** Sign a token for a player. Keep the secret on the server: `wrangler secret put JOIN_SECRET`. */
76
+ export async function createJoinToken(secret: string, claims: JoinTokenClaims): Promise<string> {
77
+ const payload: Payload = {
78
+ p: claims.player,
79
+ e: Math.floor(Date.now() / 1000) + (claims.expiresIn ?? 3600),
80
+ };
81
+ if (claims.name !== undefined) payload.n = claims.name;
82
+ if (claims.scope !== undefined) payload.s = claims.scope;
83
+ if (claims.party !== undefined) {
84
+ payload.pa = claims.party.id;
85
+ payload.ps = claims.party.size;
86
+ }
87
+ const body = `${VERSION}.${toBase64Url(encoder.encode(JSON.stringify(payload)))}`;
88
+ const signature = await crypto.subtle.sign("HMAC", await keyFor(secret), encoder.encode(body));
89
+ return `${body}.${toBase64Url(new Uint8Array(signature))}`;
90
+ }
91
+
92
+ /**
93
+ * Check a token. Returns what it says, or `null` if it is malformed, signed
94
+ * with another secret, expired, or scoped to a different room or queue than
95
+ * `scope`.
96
+ */
97
+ export async function verifyJoinToken(
98
+ secret: string,
99
+ token: string,
100
+ scope?: string,
101
+ ): Promise<VerifiedJoinToken | null> {
102
+ const key = await keyFor(secret);
103
+ const parts = token.split(".");
104
+ if (parts.length !== 3 || parts[0] !== VERSION) return null;
105
+ try {
106
+ const valid = await crypto.subtle.verify(
107
+ "HMAC",
108
+ key,
109
+ fromBase64Url(parts[2]!),
110
+ encoder.encode(`${parts[0]}.${parts[1]}`),
111
+ );
112
+ if (!valid) return null;
113
+ const payload = JSON.parse(decoder.decode(fromBase64Url(parts[1]!))) as Payload;
114
+ if (typeof payload.p !== "string" || typeof payload.e !== "number") return null;
115
+ if (payload.e <= Date.now() / 1000) return null;
116
+ if (payload.s !== undefined && payload.s !== scope) return null;
117
+ const verified: VerifiedJoinToken = { player: payload.p, expiresAt: payload.e };
118
+ if (typeof payload.n === "string") verified.name = payload.n;
119
+ if (payload.s !== undefined) verified.scope = payload.s;
120
+ if (typeof payload.pa === "string" && typeof payload.ps === "number") verified.party = { id: payload.pa, size: payload.ps };
121
+ return verified;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ /** How `tokenAuth` checks tokens. */
128
+ export interface TokenAuthOptions {
129
+ /** The signing secret, e.g. `env.JOIN_SECRET`. At least 16 characters. */
130
+ secret: string;
131
+ /** Query parameter the client sends the token in. Defaults to `token`. */
132
+ param?: string;
133
+ }
134
+
135
+ /**
136
+ * An `authenticate` function for `routeToRoom` and `routeToMatchmaker` that
137
+ * accepts signed join tokens. The client connects with `?token=...`; plain
138
+ * HTTP requests may send `Authorization: Bearer ...` instead.
139
+ */
140
+ export function tokenAuth(
141
+ options: TokenAuthOptions,
142
+ ): (request: Request, scope: string) => Promise<Authenticated | Response> {
143
+ const param = options.param ?? "token";
144
+ return async (request, scope) => {
145
+ const bearer = /^Bearer (.+)$/.exec(request.headers.get("Authorization") ?? "")?.[1];
146
+ const token = new URL(request.url).searchParams.get(param) ?? bearer;
147
+ if (!token) return new Response("Missing join token", { status: 401 });
148
+ const verified = await verifyJoinToken(options.secret, token, scope);
149
+ if (!verified) return new Response("Invalid or expired join token", { status: 401 });
150
+ if (verified.name === undefined && verified.party === undefined) return verified.player;
151
+ return {
152
+ id: verified.player,
153
+ ...(verified.name !== undefined ? { name: verified.name } : {}),
154
+ ...(verified.party !== undefined ? { party: verified.party } : {}),
155
+ };
156
+ };
157
+ }
158
+
159
+ function keyFor(secret: string): Promise<CryptoKey> {
160
+ if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
161
+ // Also catches a missing binding, which would otherwise sign with "undefined".
162
+ throw new TypeError(`The join token secret must be a string of at least ${MIN_SECRET_LENGTH} characters`);
163
+ }
164
+ let key = keys.get(secret);
165
+ if (!key) {
166
+ key = crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
167
+ "sign",
168
+ "verify",
169
+ ]);
170
+ keys.set(secret, key);
171
+ }
172
+ return key;
173
+ }
174
+
175
+ function toBase64Url(bytes: Uint8Array): string {
176
+ let binary = "";
177
+ for (const byte of bytes) binary += String.fromCharCode(byte);
178
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
179
+ }
180
+
181
+ function fromBase64Url(text: string): Uint8Array {
182
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
183
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
184
+ }