tickflare 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.
Files changed (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -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/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,1474 @@
1
+ import { createJoinToken, verifyJoinToken, type Party } from "./tokens.js";
2
+
3
+ /*
4
+ * Player accounts and player data, in D1.
5
+ *
6
+ * What a game backend service such as Talo does for accounts, cut down to
7
+ * what most games need: name and password accounts, sessions, guests that
8
+ * can register without losing their progress, ways back into an account
9
+ * whose password was forgotten, per-player data, server-side stats and
10
+ * leaderboards, public profiles, and the means to export or delete
11
+ * everything about a player.
12
+ *
13
+ * Everything lives in tables prefixed `tickflare_` in one D1 database, so
14
+ * `wrangler d1 execute` and `wrangler d1 export` work on it like on any other.
15
+ */
16
+
17
+ /** Who may read or write one key of a player's data. */
18
+ export interface DataPolicy {
19
+ /** "owner": only the player (and the server). "public": anyone, on the player's profile. Default "owner". */
20
+ read?: "owner" | "public";
21
+ /** "owner": the player may set it from the client. "server": only server code may. Default "server". */
22
+ write?: "owner" | "server";
23
+ }
24
+
25
+ /** How `Accounts` behaves. Only `secret` is required. */
26
+ export interface AccountsOptions {
27
+ /** Signs guest and join tokens. The same secret `tokenAuth` uses. At least 16 characters. */
28
+ secret: string;
29
+ /** Where the HTTP API is served. Default "/api/accounts". */
30
+ prefix?: string;
31
+ /** The session cookie's name. Default "tf_session". */
32
+ cookie?: string;
33
+ /**
34
+ * The session cookie's SameSite. "Lax" (the default) keeps players signed in
35
+ * when they follow a link to your game; "Strict" does not send the cookie on
36
+ * that first page load. A cookie set for an allowed origin of its own is
37
+ * "None" either way, or it could not be used there.
38
+ */
39
+ sameSite?: "Lax" | "Strict";
40
+ /** How long a session lasts since it was last used, in milliseconds. Default 30 days. */
41
+ sessionTtlMs?: number;
42
+ /** How long a guest token lasts, in seconds. A guest renews it, keeping their id, before then. Default 30 days. */
43
+ guestTtlSeconds?: number;
44
+ /** How long a join token from `/token` lasts, in seconds. Default ten minutes. */
45
+ joinTokenTtlSeconds?: number;
46
+ /**
47
+ * Browser origins, besides the API's own, that may make signed-in requests
48
+ * with the session cookie: where your game's pages are served from if that
49
+ * is another origin. Anything else is refused, which is what stops another
50
+ * site from acting as a signed-in player.
51
+ */
52
+ allowedOrigins?: string[];
53
+ /** Policies per data key. Keys not listed are private and server-written. */
54
+ data?: Record<string, DataPolicy>;
55
+ /** The largest value one data key may hold, in bytes of JSON. Default 64 KiB. */
56
+ maxDataBytes?: number;
57
+ /** How many data keys one player may have. Default 100. */
58
+ maxDataKeys?: number;
59
+ /**
60
+ * Your own rules for account names, in place of the default (3 to 24
61
+ * letters, digits, spaces, dots, dashes and underscores). Return the name
62
+ * as it should be stored, or null to refuse it. Uniqueness is checked after,
63
+ * ignoring case, spaces, dots, dashes and underscores.
64
+ */
65
+ normalizeName?(name: string): string | null;
66
+ /**
67
+ * Checks a password against a hash this module did not make, so accounts
68
+ * imported from another service keep working. On success the password is
69
+ * hashed again the usual way. Return false for hashes you do not recognise.
70
+ */
71
+ verifyImportedPassword?(hash: string, password: string): boolean | Promise<boolean>;
72
+ /**
73
+ * Sends a player the link to set a new password: Tickflare makes the
74
+ * token, and sending the email is yours to do, with whichever mail service
75
+ * you use. Setting this turns `POST /forgot` on. Put `reset.token` in a
76
+ * link to a page of yours that asks for a new password and sends both to
77
+ * `POST /reset`.
78
+ */
79
+ sendPasswordReset?(reset: PasswordReset, request: Request): void | Promise<void>;
80
+ /** How long a password reset token lasts, in seconds. Default one hour. */
81
+ passwordResetTtlSeconds?: number;
82
+ }
83
+
84
+ /** What `sendPasswordReset` is given: whom to write to, and the token that lets them set a new password. */
85
+ export interface PasswordReset {
86
+ /** The player id. */
87
+ id: string;
88
+ /** The account name, to remind the player of it. */
89
+ name: string;
90
+ /** The account's email address. */
91
+ email: string;
92
+ /** Lets its holder set a new password, once. Only its hash is stored. */
93
+ token: string;
94
+ /** When the token stops working, in epoch milliseconds. */
95
+ expiresAt: number;
96
+ }
97
+
98
+ /** Who is behind a request. */
99
+ export interface Identity {
100
+ /** The player id: the account's, or the guest's. */
101
+ id: string;
102
+ /** The account name, or undefined for a guest without an account. */
103
+ name?: string;
104
+ /** True for a guest without an account. */
105
+ guest: boolean;
106
+ /** The party the player queues with, if their join token carried one. See `JoinTokenClaims.party`. */
107
+ party?: Party;
108
+ }
109
+
110
+ /** What anyone may see of a player. */
111
+ export interface PublicProfile {
112
+ /** The player id. */
113
+ id: string;
114
+ /** The account name. */
115
+ name: string;
116
+ /** When the account was made, in epoch milliseconds. */
117
+ createdAt: number;
118
+ /** The data keys whose policy is `read: "public"`. */
119
+ data: Record<string, unknown>;
120
+ /** Every stat the player has. */
121
+ stats: Record<string, number>;
122
+ }
123
+
124
+ /** What a player sees of their own account. */
125
+ export interface OwnAccount {
126
+ /** The player id. */
127
+ id: string;
128
+ /** The account name. */
129
+ name: string;
130
+ /** The email address, if one was given. */
131
+ email: string | null;
132
+ /** When the account was made, in epoch milliseconds. */
133
+ createdAt: number;
134
+ /** Whether the account has a recovery code. The code itself is shown once, when it is made. */
135
+ recoveryCode: boolean;
136
+ /** Every data key the player has, private ones included. */
137
+ data: Record<string, unknown>;
138
+ /** Every stat the player has. */
139
+ stats: Record<string, number>;
140
+ }
141
+
142
+ /** One line of a leaderboard. */
143
+ export interface LeaderboardEntry {
144
+ /** 1 for the highest value. Players with the same value share a rank. */
145
+ rank: number;
146
+ /** The player id. */
147
+ id: string;
148
+ /** The account name. */
149
+ name: string;
150
+ /** The player's value of the stat. */
151
+ value: number;
152
+ }
153
+
154
+ /** A page of a leaderboard, highest value first. */
155
+ export interface LeaderboardPage {
156
+ /** The stat it ranks. */
157
+ stat: string;
158
+ /** This page's lines. */
159
+ entries: LeaderboardEntry[];
160
+ /** Players with a value for this stat, in total. */
161
+ total: number;
162
+ }
163
+
164
+ /** An account taken over from another service. See `Accounts.importAccount`. */
165
+ export interface ImportedAccount {
166
+ /** The player id to keep, so references to it elsewhere stay valid. */
167
+ id: string;
168
+ /** The account name. It must follow the name rules and be free. */
169
+ name: string;
170
+ /** The email address, if there is one. */
171
+ email?: string | null;
172
+ /** A hash `verifyImportedPassword` understands. */
173
+ passwordHash: string;
174
+ /** When the account was made, in epoch milliseconds. Defaults to now. */
175
+ createdAt?: number;
176
+ }
177
+
178
+ /** The tables, in case you prefer to apply them as a migration. `Accounts` creates them on first use. */
179
+ export const ACCOUNTS_SCHEMA = `
180
+ CREATE TABLE IF NOT EXISTS tickflare_accounts (
181
+ id TEXT PRIMARY KEY,
182
+ name TEXT NOT NULL,
183
+ name_key TEXT NOT NULL UNIQUE,
184
+ email TEXT,
185
+ password_hash TEXT NOT NULL,
186
+ created_at INTEGER NOT NULL,
187
+ password_changed_at INTEGER NOT NULL
188
+ );
189
+ CREATE TABLE IF NOT EXISTS tickflare_sessions (
190
+ token_hash TEXT PRIMARY KEY,
191
+ account_id TEXT NOT NULL,
192
+ created_at INTEGER NOT NULL,
193
+ expires_at INTEGER NOT NULL
194
+ );
195
+ CREATE INDEX IF NOT EXISTS tickflare_sessions_account ON tickflare_sessions (account_id);
196
+ CREATE TABLE IF NOT EXISTS tickflare_player_data (
197
+ player TEXT NOT NULL,
198
+ key TEXT NOT NULL,
199
+ value TEXT NOT NULL,
200
+ updated_at INTEGER NOT NULL,
201
+ PRIMARY KEY (player, key)
202
+ );
203
+ CREATE TABLE IF NOT EXISTS tickflare_player_stats (
204
+ player TEXT NOT NULL,
205
+ stat TEXT NOT NULL,
206
+ value REAL NOT NULL,
207
+ updated_at INTEGER NOT NULL,
208
+ PRIMARY KEY (player, stat)
209
+ );
210
+ CREATE INDEX IF NOT EXISTS tickflare_player_stats_board ON tickflare_player_stats (stat, value DESC);
211
+ CREATE TABLE IF NOT EXISTS tickflare_stat_awards (
212
+ key TEXT PRIMARY KEY,
213
+ awarded_at INTEGER NOT NULL
214
+ );
215
+ CREATE TABLE IF NOT EXISTS tickflare_sign_in_failures (
216
+ key TEXT PRIMARY KEY,
217
+ failures INTEGER NOT NULL,
218
+ window_start INTEGER NOT NULL
219
+ );
220
+ CREATE TABLE IF NOT EXISTS tickflare_recovery (
221
+ token_hash TEXT PRIMARY KEY,
222
+ account_id TEXT NOT NULL,
223
+ kind TEXT NOT NULL,
224
+ created_at INTEGER NOT NULL,
225
+ expires_at INTEGER
226
+ );
227
+ CREATE INDEX IF NOT EXISTS tickflare_recovery_account ON tickflare_recovery (account_id);
228
+ `;
229
+
230
+ const DAY_MS = 24 * 60 * 60 * 1000;
231
+ const PBKDF2_ITERATIONS = 100_000; // The most the Workers runtime allows.
232
+ const MIN_PASSWORD = 8;
233
+ const MAX_PASSWORD = 256;
234
+ const NAME_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} _.-]{1,22}[\p{L}\p{N}]$/u;
235
+ const KEY_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
236
+ const STAT_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
237
+ /** Sign-in failures allowed per name, and per address, within one window. */
238
+ const FAILURE_WINDOW_MS = 15 * 60 * 1000;
239
+ const MAX_FAILURES_PER_NAME = 10;
240
+ const MAX_FAILURES_PER_ADDRESS = 50;
241
+ /** Password reset emails one account, or one email address, can be sent within one window. */
242
+ const MAX_RESET_REQUESTS = 3;
243
+ /** Accounts with the same email address that one request for a reset writes to. */
244
+ const MAX_RESETS_PER_EMAIL = 5;
245
+ /** Recovery codes are written in these: no I, L, O or U, which read as other characters. */
246
+ const CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
247
+ /** A session is extended at most once per this interval, so using it does not mean a write every time. */
248
+ const SESSION_REFRESH_MS = DAY_MS;
249
+
250
+ const encoder = new TextEncoder();
251
+ const ready = new WeakSet<D1Database>();
252
+
253
+ /** Raised for requests that cannot be done. `status` is the HTTP status the API answers with. */
254
+ export class AccountError extends Error {
255
+ /** The HTTP status the API answers with, e.g. 409. */
256
+ readonly status: number;
257
+ /** Machine-readable, e.g. `name_taken` or `invalid_credentials`. */
258
+ readonly code: string;
259
+
260
+ constructor(status: number, code: string, message: string) {
261
+ super(message);
262
+ this.status = status;
263
+ this.code = code;
264
+ }
265
+ }
266
+
267
+ /**
268
+ * A small player backend on D1: accounts with a name and a password,
269
+ * sessions, guests who can sign up without losing what they earned,
270
+ * per-player data, stats and leaderboards, public profiles, and a player's
271
+ * right to download or delete everything about them.
272
+ *
273
+ * Make one per request; it holds no state of its own beyond its options.
274
+ *
275
+ * const accounts = new Accounts(env.DB, { secret: env.JOIN_SECRET });
276
+ * return (await accounts.route(request)) ?? new Response("Not found", { status: 404 });
277
+ */
278
+ export class Accounts {
279
+ readonly #db: D1Database;
280
+ readonly #secret: string;
281
+ readonly #prefix: string;
282
+ readonly #cookie: string;
283
+ readonly #sameSite: "Lax" | "Strict";
284
+ readonly #sessionTtl: number;
285
+ readonly #guestTtl: number;
286
+ readonly #joinTtl: number;
287
+ readonly #origins: Set<string>;
288
+ readonly #policies: Record<string, DataPolicy>;
289
+ readonly #maxDataBytes: number;
290
+ readonly #maxDataKeys: number;
291
+ readonly #verifyImported: AccountsOptions["verifyImportedPassword"];
292
+ readonly #sendReset: AccountsOptions["sendPasswordReset"];
293
+ readonly #resetTtl: number;
294
+ readonly #normalizeName: (name: string) => string;
295
+
296
+ constructor(db: D1Database, options: AccountsOptions) {
297
+ if (typeof options.secret !== "string" || options.secret.length < 16) {
298
+ throw new TypeError("Accounts needs a secret of at least 16 characters");
299
+ }
300
+ this.#db = db;
301
+ this.#secret = options.secret;
302
+ this.#prefix = (options.prefix ?? "/api/accounts").replace(/\/+$/, "");
303
+ this.#cookie = options.cookie ?? "tf_session";
304
+ this.#sameSite = options.sameSite ?? "Lax";
305
+ this.#sessionTtl = options.sessionTtlMs ?? 30 * DAY_MS;
306
+ this.#guestTtl = options.guestTtlSeconds ?? 30 * 24 * 60 * 60;
307
+ this.#joinTtl = options.joinTokenTtlSeconds ?? 10 * 60;
308
+ this.#origins = new Set(options.allowedOrigins ?? []);
309
+ this.#policies = options.data ?? {};
310
+ this.#maxDataBytes = options.maxDataBytes ?? 64 * 1024;
311
+ this.#maxDataKeys = options.maxDataKeys ?? 100;
312
+ this.#verifyImported = options.verifyImportedPassword;
313
+ this.#sendReset = options.sendPasswordReset;
314
+ this.#resetTtl = options.passwordResetTtlSeconds ?? 60 * 60;
315
+ const custom = options.normalizeName;
316
+ this.#normalizeName = custom
317
+ ? name => {
318
+ const normalized = typeof name === "string" ? custom(name) : null;
319
+ if (typeof normalized !== "string" || normalized.length === 0 || nameKey(normalized).length === 0) {
320
+ throw new AccountError(400, "invalid_name", "That name is not allowed.");
321
+ }
322
+ return normalized;
323
+ }
324
+ : normalizeName;
325
+ }
326
+
327
+ /** Creates the tables if they are not there yet. Called for you before the first query. */
328
+ async migrate(): Promise<void> {
329
+ if (ready.has(this.#db)) return;
330
+ const statements = ACCOUNTS_SCHEMA.split(";")
331
+ .map((sql) => sql.trim())
332
+ .filter(Boolean)
333
+ .map((sql) => this.#db.prepare(sql));
334
+ await this.#db.batch(statements);
335
+ ready.add(this.#db);
336
+ }
337
+
338
+ // --- Identity ------------------------------------------------------------------
339
+
340
+ /**
341
+ * Who is making this request: the account its session cookie or bearer
342
+ * session token belongs to, else the player a join token (`?token=` or
343
+ * bearer) speaks for, else nobody. `scope` is checked against scoped join
344
+ * tokens, as `tokenAuth` does.
345
+ */
346
+ async identify(request: Request, scope?: string): Promise<Identity | null> {
347
+ // A cookie rides along with requests other sites' pages make, WebSocket
348
+ // connections included, so it only counts from pages allowed to use it.
349
+ const session = this.#originAllowed(request) ? this.#sessionToken(request) : bearerSession(request);
350
+ if (session) {
351
+ const account = await this.#accountForSession(session);
352
+ if (account) return { id: account.id, name: account.name, guest: false };
353
+ }
354
+ const token = new URL(request.url).searchParams.get("token") ?? bearer(request);
355
+ if (token && token.startsWith("v1.")) {
356
+ const verified = await verifyJoinToken(this.#secret, token, scope);
357
+ if (!verified) return null;
358
+ const party = verified.party ? { party: verified.party } : {};
359
+ if (verified.name !== undefined) return { id: verified.player, name: verified.name, guest: false, ...party };
360
+ // A guest who has since registered signs in as the account: their old guest token no longer works.
361
+ if (await this.#hasAccount(verified.player)) return null;
362
+ return { id: verified.player, guest: true, ...party };
363
+ }
364
+ return null;
365
+ }
366
+
367
+ /**
368
+ * For `routeToRoom` and `routeToMatchmaker`: lets in signed-in players and
369
+ * holders of a join token, guests included, and answers 401 otherwise. The
370
+ * room learns the player's name too.
371
+ */
372
+ readonly authenticate = async (request: Request, scope: string): Promise<Identity | Response> => {
373
+ const identity = await this.identify(request, scope);
374
+ return identity ?? new Response("Not authenticated", { status: 401 });
375
+ };
376
+
377
+ /** Like `authenticate`, for places that need an account: guests get 401 too. */
378
+ readonly requireAccount = async (request: Request, scope: string): Promise<Identity | Response> => {
379
+ const identity = await this.identify(request, scope);
380
+ if (!identity || identity.guest) return new Response("Sign in to play here", { status: 401 });
381
+ return identity;
382
+ };
383
+
384
+ // --- The HTTP API ----------------------------------------------------------------
385
+
386
+ /**
387
+ * Answers requests to the accounts API, under `prefix`; null for any other
388
+ * URL so your Worker can try its other routes.
389
+ *
390
+ * POST /guest a guest player and a join token for them
391
+ * POST /register { name, password, email?, guestToken? }
392
+ * POST /login { name, password }
393
+ * POST /logout
394
+ * GET /me your account, data and stats
395
+ * DELETE /me { password }: delete your account and everything in it
396
+ * POST /password { current, next }: change it and sign out everywhere else
397
+ * POST /recovery-code { password }: a code that sets a new password once, shown this one time
398
+ * POST /recover { name, code, password }: set a new password with that code, and sign in
399
+ * POST /forgot { name } or { email }: send a reset link, if `sendPasswordReset` is set
400
+ * POST /reset { token, password }: set a new password with the link's token, and sign in
401
+ * POST /name { name }: take another name
402
+ * POST /email { password, email }: set or (with null) remove the email address
403
+ * GET /export everything stored about you, as a JSON download
404
+ * POST /token { scope? }: a short-lived join token for a room or queue
405
+ * GET /data/:key PUT /data/:key { value } DELETE /data/:key
406
+ * GET /players/:id a public profile
407
+ * GET /leaderboards/:stat?limit=&offset=
408
+ *
409
+ * Pass the Worker's `ctx` as well if you reset passwords by email: the
410
+ * email is then sent after the answer, which takes as long whether or not
411
+ * there was an account to write to.
412
+ */
413
+ async route(request: Request, ctx?: Pick<ExecutionContext, "waitUntil">): Promise<Response | null> {
414
+ const url = new URL(request.url);
415
+ if (url.pathname !== this.#prefix && !url.pathname.startsWith(`${this.#prefix}/`)) return null;
416
+ const path = url.pathname.slice(this.#prefix.length) || "/";
417
+ const cors = this.#corsHeaders(request);
418
+ if (request.method === "OPTIONS" && cors) {
419
+ return new Response(null, {
420
+ status: 204,
421
+ headers: {
422
+ ...cors,
423
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
424
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
425
+ "Access-Control-Max-Age": "86400",
426
+ },
427
+ });
428
+ }
429
+ let response: Response;
430
+ try {
431
+ await this.migrate();
432
+ response = await this.#dispatch(request, url, path, ctx);
433
+ } catch (error) {
434
+ if (error instanceof AccountError) {
435
+ response = json({ error: error.code, message: error.message }, error.status);
436
+ } else {
437
+ console.error("[tickflare] accounts request failed:", error);
438
+ response = json({ error: "internal_error", message: "Something went wrong." }, 500);
439
+ }
440
+ }
441
+ if (cors) for (const [name, value] of Object.entries(cors)) response.headers.set(name, value);
442
+ return response;
443
+ }
444
+
445
+ async #dispatch(
446
+ request: Request,
447
+ url: URL,
448
+ path: string,
449
+ ctx: Pick<ExecutionContext, "waitUntil"> | undefined,
450
+ ): Promise<Response> {
451
+ const method = request.method;
452
+ let segments: string[];
453
+ try {
454
+ segments = path.split("/").filter(Boolean).map(decodeURIComponent);
455
+ } catch {
456
+ throw new AccountError(400, "invalid_request", "Malformed URL.");
457
+ }
458
+
459
+ if (path === "/guest" && method === "POST") {
460
+ let id: string = crypto.randomUUID();
461
+ if (request.headers.get("Content-Type")?.includes("application/json")) {
462
+ // Renewing: the same guest, with a fresh token, as long as the old one is still good.
463
+ const body = await readJson(request);
464
+ const old = typeof body.token === "string" ? await verifyJoinToken(this.#secret, body.token) : null;
465
+ if (old && old.name === undefined && old.scope === undefined && !(await this.#hasAccount(old.player))) id = old.player;
466
+ }
467
+ const token = await createJoinToken(this.#secret, { player: id, expiresIn: this.#guestTtl });
468
+ const now = Date.now();
469
+ return json({ id, token, expiresAt: now + this.#guestTtl * 1000, renewAt: now + (this.#guestTtl * 1000) / 2 });
470
+ }
471
+ if (path === "/register" && method === "POST") {
472
+ this.#checkOrigin(request);
473
+ const body = await readJson(request);
474
+ let id: string | undefined;
475
+ if (typeof body.guestToken === "string") {
476
+ const guest = await verifyJoinToken(this.#secret, body.guestToken);
477
+ // A guest who registers keeps their id, and with it what they earned as a guest.
478
+ if (guest && guest.name === undefined) id = guest.player;
479
+ }
480
+ const account = await this.register({
481
+ id,
482
+ name: stringField(body, "name"),
483
+ password: stringField(body, "password"),
484
+ email: typeof body.email === "string" ? body.email : null,
485
+ });
486
+ return this.#signedIn(request, account.id, 201);
487
+ }
488
+ if (path === "/login" && method === "POST") {
489
+ this.#checkOrigin(request);
490
+ const body = await readJson(request);
491
+ const account = await this.signIn(stringField(body, "name"), stringField(body, "password"), address(request));
492
+ return this.#signedIn(request, account.id, 200);
493
+ }
494
+ if (path === "/logout" && method === "POST") {
495
+ this.#checkOrigin(request);
496
+ const token = this.#sessionToken(request);
497
+ if (token) await this.#db.prepare("DELETE FROM tickflare_sessions WHERE token_hash = ?").bind(await sha256(token)).run();
498
+ return new Response(null, { status: 204, headers: { "Set-Cookie": this.#clearCookie(request) } });
499
+ }
500
+ if (path === "/me" && method === "GET") {
501
+ const account = await this.#requireAccount(request);
502
+ return json(await this.ownAccount(account.id));
503
+ }
504
+ if (path === "/me" && method === "DELETE") {
505
+ this.#checkOrigin(request);
506
+ const account = await this.#requireAccount(request);
507
+ const body = await readJson(request);
508
+ await this.#checkPassword(account.id, stringField(body, "password"));
509
+ await this.deleteAccount(account.id);
510
+ return new Response(null, { status: 204, headers: { "Set-Cookie": this.#clearCookie(request) } });
511
+ }
512
+ if (path === "/password" && method === "POST") {
513
+ this.#checkOrigin(request);
514
+ const account = await this.#requireAccount(request);
515
+ const body = await readJson(request);
516
+ await this.#checkPassword(account.id, stringField(body, "current"));
517
+ await this.setPassword(account.id, stringField(body, "next"));
518
+ // Every session ends, this one included; it is replaced with a fresh one.
519
+ return this.#signedIn(request, account.id, 200);
520
+ }
521
+ if (path === "/recovery-code" && method === "POST") {
522
+ this.#checkOrigin(request);
523
+ const account = await this.#requireAccount(request);
524
+ const body = await readJson(request);
525
+ await this.#checkPassword(account.id, stringField(body, "password"));
526
+ return json({ code: await this.createRecoveryCode(account.id) }, 201, { "Cache-Control": "no-store" });
527
+ }
528
+ if (path === "/recover" && method === "POST") {
529
+ this.#checkOrigin(request);
530
+ const body = await readJson(request);
531
+ const account = await this.recoverWithCode(
532
+ stringField(body, "name"),
533
+ stringField(body, "code"),
534
+ stringField(body, "password"),
535
+ address(request),
536
+ );
537
+ return this.#signedIn(request, account.id, 200);
538
+ }
539
+ if (path === "/forgot" && method === "POST") {
540
+ this.#checkOrigin(request);
541
+ const send = this.#sendReset;
542
+ if (!send) throw new AccountError(404, "not_enabled", "This game does not reset passwords by email.");
543
+ const body = await readJson(request);
544
+ const who =
545
+ typeof body.email === "string" && body.email.trim() !== ""
546
+ ? { email: body.email.trim() }
547
+ : { name: stringField(body, "name") };
548
+ // Every request counts, whether or not there is such an account: nobody's inbox is filled this way.
549
+ const keys = [`forgot:${who.email?.toLowerCase() ?? nameKey(who.name!.trim())}`, `forgot-address:${address(request)}`];
550
+ await this.#checkThrottle(keys);
551
+ await this.#recordFailure(keys);
552
+ const work = (async () => {
553
+ for (const reset of await this.startPasswordReset(who)) await send(reset, request);
554
+ })().catch((error) => console.error("[tickflare] could not send a password reset:", error));
555
+ // The answer is the same, and with `ctx` as quick, whether or not anything was sent.
556
+ if (ctx) ctx.waitUntil(work);
557
+ else await work;
558
+ return new Response(null, { status: 204 });
559
+ }
560
+ if (path === "/reset" && method === "POST") {
561
+ this.#checkOrigin(request);
562
+ const body = await readJson(request);
563
+ const account = await this.resetPassword(stringField(body, "token"), stringField(body, "password"));
564
+ return this.#signedIn(request, account.id, 200);
565
+ }
566
+ if (path === "/name" && method === "POST") {
567
+ this.#checkOrigin(request);
568
+ const account = await this.#requireAccount(request);
569
+ const body = await readJson(request);
570
+ await this.rename(account.id, stringField(body, "name"));
571
+ return json(await this.ownAccount(account.id));
572
+ }
573
+ if (path === "/email" && method === "POST") {
574
+ this.#checkOrigin(request);
575
+ const account = await this.#requireAccount(request);
576
+ const body = await readJson(request);
577
+ await this.#checkPassword(account.id, stringField(body, "password"));
578
+ await this.setEmail(account.id, typeof body.email === "string" ? body.email : null);
579
+ return json(await this.ownAccount(account.id));
580
+ }
581
+ if (path === "/export" && method === "GET") {
582
+ const account = await this.#requireAccount(request);
583
+ return new Response(JSON.stringify(await this.exportAccount(account.id), null, 2), {
584
+ headers: {
585
+ "Content-Type": "application/json",
586
+ "Content-Disposition": `attachment; filename="account-${account.id}.json"`,
587
+ "Cache-Control": "no-store",
588
+ },
589
+ });
590
+ }
591
+ if (path === "/token" && method === "POST") {
592
+ this.#checkOrigin(request);
593
+ const account = await this.#requireAccount(request);
594
+ const body = request.headers.get("Content-Type")?.includes("json") ? await readJson(request) : {};
595
+ const scope = typeof body.scope === "string" ? body.scope : undefined;
596
+ const token = await createJoinToken(this.#secret, {
597
+ player: account.id,
598
+ name: account.name,
599
+ scope,
600
+ expiresIn: this.#joinTtl,
601
+ });
602
+ return json({ token, expiresAt: Date.now() + this.#joinTtl * 1000 });
603
+ }
604
+ if (segments[0] === "data" && segments.length === 2) {
605
+ const key = segments[1]!;
606
+ const account = await this.#requireAccount(request);
607
+ if (method === "GET") {
608
+ const value = await this.getData(account.id, key);
609
+ return value === undefined ? json({ error: "not_found", message: "No such key." }, 404) : json({ key, value });
610
+ }
611
+ this.#checkOrigin(request);
612
+ if (this.#policy(key).write !== "owner") throw new AccountError(403, "read_only", `"${key}" can only be set by the game.`);
613
+ if (method === "PUT") {
614
+ const body = await readJson(request);
615
+ if (!("value" in body)) throw new AccountError(400, "invalid_request", "Send { value }.");
616
+ await this.setData(account.id, key, body.value);
617
+ return json({ key, value: body.value });
618
+ }
619
+ if (method === "DELETE") {
620
+ await this.deleteData(account.id, key);
621
+ return new Response(null, { status: 204 });
622
+ }
623
+ }
624
+ if (segments[0] === "players" && segments.length === 2 && method === "GET") {
625
+ const profile = await this.profile(segments[1]!);
626
+ return profile ? json(profile) : json({ error: "not_found", message: "No such player." }, 404);
627
+ }
628
+ if (segments[0] === "leaderboards" && segments.length === 2 && method === "GET") {
629
+ const limit = Number(url.searchParams.get("limit") ?? 20);
630
+ const offset = Number(url.searchParams.get("offset") ?? 0);
631
+ return json(await this.leaderboard(segments[1]!, { limit, offset }), 200, { "Cache-Control": "public, max-age=10" });
632
+ }
633
+ return json({ error: "not_found", message: "No such accounts endpoint." }, 404);
634
+ }
635
+
636
+ // --- Accounts ---------------------------------------------------------------------
637
+
638
+ /** Creates an account. `id` lets a guest keep theirs; it is made up otherwise. */
639
+ async register(input: { name: string; password: string; email?: string | null; id?: string }): Promise<Identity> {
640
+ await this.migrate();
641
+ const name = this.#normalizeName(input.name);
642
+ checkPassword(input.password);
643
+ const email = normalizeEmail(input.email ?? null);
644
+ const id = input.id ?? crypto.randomUUID();
645
+ const now = Date.now();
646
+ const hash = await hashPassword(input.password);
647
+ try {
648
+ await this.#db
649
+ .prepare(
650
+ "INSERT INTO tickflare_accounts (id, name, name_key, email, password_hash, created_at, password_changed_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
651
+ )
652
+ .bind(id, name, nameKey(name), email, hash, now, now)
653
+ .run();
654
+ } catch (error) {
655
+ if (String(error).includes("UNIQUE") && String(error).includes("name_key")) {
656
+ throw new AccountError(409, "name_taken", "That name is taken.");
657
+ }
658
+ if (String(error).includes("UNIQUE")) throw new AccountError(409, "account_exists", "This player already has an account.");
659
+ throw error;
660
+ }
661
+ return { id, name, guest: false };
662
+ }
663
+
664
+ /** Brings in an account from another service. Its password works through `verifyImportedPassword`. */
665
+ async importAccount(account: ImportedAccount): Promise<void> {
666
+ await this.migrate();
667
+ const name = this.#normalizeName(account.name);
668
+ const createdAt = account.createdAt ?? Date.now();
669
+ await this.#db
670
+ .prepare(
671
+ "INSERT INTO tickflare_accounts (id, name, name_key, email, password_hash, created_at, password_changed_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
672
+ )
673
+ .bind(account.id, name, nameKey(name), normalizeEmail(account.email ?? null), account.passwordHash, createdAt, createdAt)
674
+ .run();
675
+ }
676
+
677
+ /** Checks a name and password. Repeated failures for one name or one address are refused for a while. */
678
+ async signIn(name: string, password: string, from = "unknown"): Promise<Identity> {
679
+ await this.migrate();
680
+ const keys = [`name:${nameKey(name.trim())}`, `address:${from}`];
681
+ await this.#checkThrottle(keys);
682
+ const row = await this.#db
683
+ .prepare("SELECT id, name, password_hash FROM tickflare_accounts WHERE name_key = ?")
684
+ .bind(nameKey(name.trim()))
685
+ .first<{ id: string; name: string; password_hash: string }>();
686
+ const valid = row ? await this.#verify(row.id, row.password_hash, password) : await hashPassword(password).then(() => false);
687
+ if (!row || !valid) {
688
+ await this.#recordFailure(keys);
689
+ throw new AccountError(401, "invalid_credentials", "Wrong name or password.");
690
+ }
691
+ await this.#db.prepare("DELETE FROM tickflare_sign_in_failures WHERE key = ?").bind(keys[0]).run();
692
+ return { id: row.id, name: row.name, guest: false };
693
+ }
694
+
695
+ /** Gives an account another name, if nobody has it. Sessions and join tokens issued later carry the new one. */
696
+ async rename(accountId: string, name: string): Promise<Identity> {
697
+ await this.migrate();
698
+ const normalized = this.#normalizeName(name);
699
+ try {
700
+ const result = await this.#db
701
+ .prepare("UPDATE tickflare_accounts SET name = ?, name_key = ? WHERE id = ?")
702
+ .bind(normalized, nameKey(normalized), accountId)
703
+ .run();
704
+ if (result.meta.changes === 0) throw new AccountError(404, "not_found", "No such account.");
705
+ } catch (error) {
706
+ if (String(error).includes("UNIQUE")) throw new AccountError(409, "name_taken", "That name is taken.");
707
+ throw error;
708
+ }
709
+ return { id: accountId, name: normalized, guest: false };
710
+ }
711
+
712
+ /** Sets the email address, or removes it with null. */
713
+ async setEmail(accountId: string, email: string | null): Promise<void> {
714
+ await this.migrate();
715
+ await this.#db
716
+ .prepare("UPDATE tickflare_accounts SET email = ? WHERE id = ?")
717
+ .bind(normalizeEmail(email), accountId)
718
+ .run();
719
+ }
720
+
721
+ /**
722
+ * Sets a new password, ends every session of the account, and makes any
723
+ * password reset token it was sent useless. Its recovery code stays.
724
+ */
725
+ async setPassword(accountId: string, password: string): Promise<void> {
726
+ checkPassword(password);
727
+ await this.migrate();
728
+ const now = Date.now();
729
+ await this.#db.batch([
730
+ this.#db
731
+ .prepare("UPDATE tickflare_accounts SET password_hash = ?, password_changed_at = ? WHERE id = ?")
732
+ .bind(await hashPassword(password), now, accountId),
733
+ this.#db.prepare("DELETE FROM tickflare_sessions WHERE account_id = ?").bind(accountId),
734
+ this.#db.prepare("DELETE FROM tickflare_recovery WHERE account_id = ? AND kind = 'reset'").bind(accountId),
735
+ ]);
736
+ }
737
+
738
+ // --- Recovery ---------------------------------------------------------------------
739
+
740
+ /**
741
+ * Makes a recovery code for an account and returns it: twenty letters and
742
+ * digits the player keeps somewhere safe, which set a new password once,
743
+ * with no email involved. It replaces the code the account had, if any.
744
+ * Only its hash is stored, so this is the one time it can be shown.
745
+ */
746
+ async createRecoveryCode(accountId: string): Promise<string> {
747
+ await this.migrate();
748
+ if (!(await this.#hasAccount(accountId))) throw new AccountError(404, "not_found", "No such account.");
749
+ const code = recoveryCode();
750
+ await this.#db.batch([
751
+ this.#db.prepare("DELETE FROM tickflare_recovery WHERE account_id = ? AND kind = 'code'").bind(accountId),
752
+ this.#db
753
+ .prepare("INSERT INTO tickflare_recovery (token_hash, account_id, kind, created_at, expires_at) VALUES (?, ?, 'code', ?, NULL)")
754
+ .bind(await sha256(codeKey(code)), accountId, Date.now()),
755
+ ]);
756
+ return code;
757
+ }
758
+
759
+ /**
760
+ * Sets a new password for the account called `name`, given its recovery
761
+ * code, and ends its sessions. The code is used up: make another once
762
+ * signed in. Wrong guesses are counted as wrong passwords are.
763
+ */
764
+ async recoverWithCode(name: string, code: string, password: string, from = "unknown"): Promise<Identity> {
765
+ await this.migrate();
766
+ checkPassword(password);
767
+ const keys = [`recover:${nameKey(name.trim())}`, `address:${from}`];
768
+ await this.#checkThrottle(keys);
769
+ const account = await this.#db
770
+ .prepare("SELECT id, name FROM tickflare_accounts WHERE name_key = ?")
771
+ .bind(nameKey(name.trim()))
772
+ .first<{ id: string; name: string }>();
773
+ // Deleting it is what uses it: of two requests with the same code, one finds it gone.
774
+ const used = account
775
+ ? await this.#db
776
+ .prepare("DELETE FROM tickflare_recovery WHERE token_hash = ? AND account_id = ? AND kind = 'code'")
777
+ .bind(await sha256(codeKey(code)), account.id)
778
+ .run()
779
+ : null;
780
+ if (!account || !used || used.meta.changes === 0) {
781
+ await this.#recordFailure(keys);
782
+ throw new AccountError(401, "invalid_code", "Wrong name or recovery code.");
783
+ }
784
+ await this.setPassword(account.id, password);
785
+ await this.#db.prepare("DELETE FROM tickflare_sign_in_failures WHERE key = ?").bind(keys[0]).run();
786
+ return { id: account.id, name: account.name, guest: false };
787
+ }
788
+
789
+ /**
790
+ * Makes a password reset token for the account with this name, or for
791
+ * each account with this email address, and returns what to send to whom.
792
+ * Empty if there is no such account or it has no email address. A token
793
+ * replaces the one the account was sent before. `POST /forgot` calls this
794
+ * and hands each result to `sendPasswordReset`.
795
+ */
796
+ async startPasswordReset(who: { name?: string; email?: string }): Promise<PasswordReset[]> {
797
+ await this.migrate();
798
+ const found =
799
+ who.email !== undefined
800
+ ? await this.#db
801
+ .prepare(`SELECT id, name, email FROM tickflare_accounts WHERE lower(email) = lower(?) ORDER BY created_at LIMIT ${MAX_RESETS_PER_EMAIL}`)
802
+ .bind(who.email.trim())
803
+ .all<{ id: string; name: string; email: string | null }>()
804
+ : await this.#db
805
+ .prepare("SELECT id, name, email FROM tickflare_accounts WHERE name_key = ?")
806
+ .bind(nameKey((who.name ?? "").trim()))
807
+ .all<{ id: string; name: string; email: string | null }>();
808
+ const now = Date.now();
809
+ const expiresAt = now + this.#resetTtl * 1000;
810
+ const resets: PasswordReset[] = [];
811
+ const statements = [this.#db.prepare("DELETE FROM tickflare_recovery WHERE expires_at IS NOT NULL AND expires_at <= ?").bind(now)];
812
+ for (const account of found.results) {
813
+ if (!account.email) continue;
814
+ const token = randomToken();
815
+ resets.push({ id: account.id, name: account.name, email: account.email, token, expiresAt });
816
+ statements.push(
817
+ this.#db.prepare("DELETE FROM tickflare_recovery WHERE account_id = ? AND kind = 'reset'").bind(account.id),
818
+ this.#db
819
+ .prepare("INSERT INTO tickflare_recovery (token_hash, account_id, kind, created_at, expires_at) VALUES (?, ?, 'reset', ?, ?)")
820
+ .bind(await sha256(token), account.id, now, expiresAt),
821
+ );
822
+ }
823
+ await this.#db.batch(statements);
824
+ return resets;
825
+ }
826
+
827
+ /** Sets a new password with a token from `startPasswordReset`, once, and ends the account's sessions. */
828
+ async resetPassword(token: string, password: string): Promise<Identity> {
829
+ await this.migrate();
830
+ checkPassword(password);
831
+ const hash = await sha256(token);
832
+ const row = await this.#db
833
+ .prepare(
834
+ `SELECT a.id AS id, a.name AS name FROM tickflare_recovery r JOIN tickflare_accounts a ON a.id = r.account_id
835
+ WHERE r.token_hash = ? AND r.kind = 'reset' AND r.expires_at > ?`,
836
+ )
837
+ .bind(hash, Date.now())
838
+ .first<{ id: string; name: string }>();
839
+ const used = row
840
+ ? await this.#db.prepare("DELETE FROM tickflare_recovery WHERE token_hash = ? AND kind = 'reset'").bind(hash).run()
841
+ : null;
842
+ if (!row || !used || used.meta.changes === 0) {
843
+ throw new AccountError(400, "invalid_token", "That link no longer works. Ask for a new one.");
844
+ }
845
+ await this.setPassword(row.id, password);
846
+ return { id: row.id, name: row.name, guest: false };
847
+ }
848
+
849
+ /** Starts a session for an account and returns its token. Usually done for you by `/login`. */
850
+ async createSession(accountId: string): Promise<string> {
851
+ await this.migrate();
852
+ const token = randomToken();
853
+ const now = Date.now();
854
+ await this.#db
855
+ .prepare("INSERT INTO tickflare_sessions (token_hash, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)")
856
+ .bind(await sha256(token), accountId, now, now + this.#sessionTtl)
857
+ .run();
858
+ return token;
859
+ }
860
+
861
+ /** Deletes an account, its sessions, data and stats. Match records keep the id, but it no longer resolves to a name. */
862
+ async deleteAccount(accountId: string): Promise<void> {
863
+ await this.migrate();
864
+ await this.#db.batch([
865
+ this.#db.prepare("DELETE FROM tickflare_sessions WHERE account_id = ?").bind(accountId),
866
+ this.#db.prepare("DELETE FROM tickflare_recovery WHERE account_id = ?").bind(accountId),
867
+ this.#db.prepare("DELETE FROM tickflare_player_data WHERE player = ?").bind(accountId),
868
+ this.#db.prepare("DELETE FROM tickflare_player_stats WHERE player = ?").bind(accountId),
869
+ this.#db.prepare("DELETE FROM tickflare_accounts WHERE id = ?").bind(accountId),
870
+ ]);
871
+ }
872
+
873
+ /** Everything stored about a player, for them to download. */
874
+ async exportAccount(accountId: string): Promise<Record<string, unknown>> {
875
+ await this.migrate();
876
+ const account = await this.#db
877
+ .prepare("SELECT id, name, email, created_at, password_changed_at FROM tickflare_accounts WHERE id = ?")
878
+ .bind(accountId)
879
+ .first<{ id: string; name: string; email: string | null; created_at: number; password_changed_at: number }>();
880
+ if (!account) throw new AccountError(404, "not_found", "No such account.");
881
+ const sessions = await this.#db
882
+ .prepare("SELECT created_at, expires_at FROM tickflare_sessions WHERE account_id = ? ORDER BY created_at")
883
+ .bind(accountId)
884
+ .all<{ created_at: number; expires_at: number }>();
885
+ let matches: unknown[] = [];
886
+ try {
887
+ const rows = await this.#db
888
+ .prepare(
889
+ "SELECT id, room, ended_at, players, result FROM tickflare_matches WHERE EXISTS (SELECT 1 FROM json_each(players) WHERE value = ?) ORDER BY ended_at",
890
+ )
891
+ .bind(accountId)
892
+ .all<{ id: string; room: string | null; ended_at: number; players: string; result: string }>();
893
+ matches = rows.results.map((row) => ({
894
+ id: row.id,
895
+ room: row.room,
896
+ endedAt: row.ended_at,
897
+ players: JSON.parse(row.players),
898
+ result: JSON.parse(row.result),
899
+ }));
900
+ } catch {
901
+ // No match history in this database.
902
+ }
903
+ return {
904
+ exportedAt: new Date().toISOString(),
905
+ account: {
906
+ id: account.id,
907
+ name: account.name,
908
+ email: account.email,
909
+ createdAt: account.created_at,
910
+ passwordChangedAt: account.password_changed_at,
911
+ recoveryCode: await this.#hasRecoveryCode(accountId),
912
+ },
913
+ sessions: sessions.results.map((session) => ({ createdAt: session.created_at, expiresAt: session.expires_at })),
914
+ data: await this.#allData(accountId),
915
+ stats: await this.stats(accountId),
916
+ matches,
917
+ };
918
+ }
919
+
920
+ // --- Profiles -----------------------------------------------------------------------
921
+
922
+ /** The account as its owner sees it. */
923
+ async ownAccount(accountId: string): Promise<OwnAccount> {
924
+ await this.migrate();
925
+ const account = await this.#db
926
+ .prepare("SELECT id, name, email, created_at FROM tickflare_accounts WHERE id = ?")
927
+ .bind(accountId)
928
+ .first<{ id: string; name: string; email: string | null; created_at: number }>();
929
+ if (!account) throw new AccountError(404, "not_found", "No such account.");
930
+ return {
931
+ id: account.id,
932
+ name: account.name,
933
+ email: account.email,
934
+ createdAt: account.created_at,
935
+ recoveryCode: await this.#hasRecoveryCode(accountId),
936
+ data: await this.#allData(accountId),
937
+ stats: await this.stats(accountId),
938
+ };
939
+ }
940
+
941
+ async #hasRecoveryCode(accountId: string): Promise<boolean> {
942
+ const row = await this.#db
943
+ .prepare("SELECT 1 FROM tickflare_recovery WHERE account_id = ? AND kind = 'code'")
944
+ .bind(accountId)
945
+ .first();
946
+ return row !== null;
947
+ }
948
+
949
+ /** A player's public profile, or null if there is no account with that id. */
950
+ async profile(playerId: string): Promise<PublicProfile | null> {
951
+ await this.migrate();
952
+ const account = await this.#db
953
+ .prepare("SELECT id, name, created_at FROM tickflare_accounts WHERE id = ?")
954
+ .bind(playerId)
955
+ .first<{ id: string; name: string; created_at: number }>();
956
+ if (!account) return null;
957
+ const data = await this.#allData(playerId);
958
+ const visible: Record<string, unknown> = {};
959
+ for (const [key, value] of Object.entries(data)) if (this.#policy(key).read === "public") visible[key] = value;
960
+ return { id: account.id, name: account.name, createdAt: account.created_at, data: visible, stats: await this.stats(playerId) };
961
+ }
962
+
963
+ /** Account names by player id. Guests and deleted accounts are left out. */
964
+ async names(playerIds: readonly string[]): Promise<Map<string, string>> {
965
+ await this.migrate();
966
+ const names = new Map<string, string>();
967
+ // D1 binds at most 100 parameters per statement.
968
+ for (let start = 0; start < playerIds.length; start += 100) {
969
+ const chunk = playerIds.slice(start, start + 100);
970
+ const rows = await this.#db
971
+ .prepare(`SELECT id, name FROM tickflare_accounts WHERE id IN (${chunk.map(() => "?").join(",")})`)
972
+ .bind(...chunk)
973
+ .all<{ id: string; name: string }>();
974
+ for (const row of rows.results) names.set(row.id, row.name);
975
+ }
976
+ return names;
977
+ }
978
+
979
+ // --- Player data ----------------------------------------------------------------------
980
+
981
+ /** The value a player has under `key`, or undefined. Server code reads every key, whatever its policy. */
982
+ async getData(playerId: string, key: string): Promise<unknown> {
983
+ checkKey(key);
984
+ await this.migrate();
985
+ const row = await this.#db
986
+ .prepare("SELECT value FROM tickflare_player_data WHERE player = ? AND key = ?")
987
+ .bind(playerId, key)
988
+ .first<{ value: string }>();
989
+ return row ? JSON.parse(row.value) : undefined;
990
+ }
991
+
992
+ /** Stores a JSON value for a player. Server code may set any key; clients only those with `write: "owner"`. */
993
+ async setData(playerId: string, key: string, value: unknown): Promise<void> {
994
+ checkKey(key);
995
+ await this.migrate();
996
+ const encoded = JSON.stringify(value);
997
+ if (encoded === undefined) throw new AccountError(400, "invalid_value", "The value must be JSON.");
998
+ if (encoder.encode(encoded).length > this.#maxDataBytes) {
999
+ throw new AccountError(413, "value_too_large", `A value can be at most ${this.#maxDataBytes} bytes.`);
1000
+ }
1001
+ const now = Date.now();
1002
+ // Inserting is refused once the player has as many keys as allowed; updating an existing one never is.
1003
+ const result = await this.#db
1004
+ .prepare(
1005
+ `INSERT INTO tickflare_player_data (player, key, value, updated_at)
1006
+ SELECT ?1, ?2, ?3, ?4
1007
+ WHERE EXISTS (SELECT 1 FROM tickflare_player_data WHERE player = ?1 AND key = ?2)
1008
+ OR (SELECT COUNT(*) FROM tickflare_player_data WHERE player = ?1) < ?5
1009
+ ON CONFLICT (player, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
1010
+ )
1011
+ .bind(playerId, key, encoded, now, this.#maxDataKeys)
1012
+ .run();
1013
+ if (result.meta.changes === 0) {
1014
+ throw new AccountError(409, "too_many_keys", `A player can have at most ${this.#maxDataKeys} data keys.`);
1015
+ }
1016
+ }
1017
+
1018
+ /** Removes a player's value under `key`. Does nothing if there is none. */
1019
+ async deleteData(playerId: string, key: string): Promise<void> {
1020
+ checkKey(key);
1021
+ await this.migrate();
1022
+ await this.#db.prepare("DELETE FROM tickflare_player_data WHERE player = ? AND key = ?").bind(playerId, key).run();
1023
+ }
1024
+
1025
+ async #allData(playerId: string): Promise<Record<string, unknown>> {
1026
+ const rows = await this.#db
1027
+ .prepare("SELECT key, value FROM tickflare_player_data WHERE player = ? ORDER BY key")
1028
+ .bind(playerId)
1029
+ .all<{ key: string; value: string }>();
1030
+ return Object.fromEntries(rows.results.map((row) => [row.key, JSON.parse(row.value)]));
1031
+ }
1032
+
1033
+ // --- Stats and leaderboards ----------------------------------------------------------------
1034
+
1035
+ /** Adds to a player's stats: `{ wins: 1, kills: 7 }`. Server only: clients cannot write stats. */
1036
+ async addStats(playerId: string, increments: Record<string, number>): Promise<void> {
1037
+ await this.#writeStats(playerId, increments, "value + excluded.value");
1038
+ }
1039
+
1040
+ /** Sets stats to these values. */
1041
+ async setStats(playerId: string, values: Record<string, number>): Promise<void> {
1042
+ await this.#writeStats(playerId, values, "excluded.value");
1043
+ }
1044
+
1045
+ /** Keeps the higher of the stored and the given value: best scores, longest streaks. */
1046
+ async maxStats(playerId: string, values: Record<string, number>): Promise<void> {
1047
+ await this.#writeStats(playerId, values, "MAX(value, excluded.value)");
1048
+ }
1049
+
1050
+ /**
1051
+ * Writes several players' stats in one go, once per `key`: a match id, say.
1052
+ * Calling it again with the same key changes nothing and returns false, so
1053
+ * code that retries after a failure cannot count a result twice. Either all
1054
+ * of it is written or none of it.
1055
+ */
1056
+ async awardStats(
1057
+ key: string,
1058
+ awards: readonly { player: string; add?: Record<string, number>; set?: Record<string, number>; max?: Record<string, number> }[],
1059
+ ): Promise<boolean> {
1060
+ await this.migrate();
1061
+ if (typeof key !== "string" || key.length === 0 || key.length > 256) throw new AccountError(400, "invalid_key", "An award needs a key.");
1062
+ const now = Date.now();
1063
+ const statements = [this.#db.prepare("INSERT INTO tickflare_stat_awards (key, awarded_at) VALUES (?, ?)").bind(key, now)];
1064
+ for (const award of awards) {
1065
+ for (const [values, update] of [
1066
+ [award.add, "value + excluded.value"],
1067
+ [award.set, "excluded.value"],
1068
+ [award.max, "MAX(value, excluded.value)"],
1069
+ ] as const) {
1070
+ for (const [stat, value] of Object.entries(values ?? {})) statements.push(this.#statStatement(award.player, stat, value, update, now));
1071
+ }
1072
+ }
1073
+ try {
1074
+ await this.#db.batch(statements);
1075
+ return true;
1076
+ } catch (error) {
1077
+ if (String(error).includes("UNIQUE") && String(error).includes("tickflare_stat_awards")) return false;
1078
+ throw error;
1079
+ }
1080
+ }
1081
+
1082
+ /** Every stat a player has. */
1083
+ async stats(playerId: string): Promise<Record<string, number>> {
1084
+ await this.migrate();
1085
+ const rows = await this.#db
1086
+ .prepare("SELECT stat, value FROM tickflare_player_stats WHERE player = ? ORDER BY stat")
1087
+ .bind(playerId)
1088
+ .all<{ stat: string; value: number }>();
1089
+ return Object.fromEntries(rows.results.map((row) => [row.stat, row.value]));
1090
+ }
1091
+
1092
+ /** Several players' stats at once, by player id. `stats` limits it to those stats. Players without any are left out. */
1093
+ async statsOf(playerIds: readonly string[], stats?: readonly string[]): Promise<Map<string, Record<string, number>>> {
1094
+ await this.migrate();
1095
+ stats?.forEach(checkStat);
1096
+ const result = new Map<string, Record<string, number>>();
1097
+ const unique = [...new Set(playerIds)];
1098
+ // D1 binds at most 100 parameters per statement.
1099
+ const room = 100 - (stats?.length ?? 0);
1100
+ for (let start = 0; start < unique.length; start += room) {
1101
+ const chunk = unique.slice(start, start + room);
1102
+ const filter = stats ? ` AND stat IN (${stats.map(() => "?").join(",")})` : "";
1103
+ const rows = await this.#db
1104
+ .prepare(`SELECT player, stat, value FROM tickflare_player_stats WHERE player IN (${chunk.map(() => "?").join(",")})${filter}`)
1105
+ .bind(...chunk, ...(stats ?? []))
1106
+ .all<{ player: string; stat: string; value: number }>();
1107
+ for (const row of rows.results) {
1108
+ let entry = result.get(row.player);
1109
+ if (!entry) result.set(row.player, (entry = {}));
1110
+ entry[row.stat] = row.value;
1111
+ }
1112
+ }
1113
+ return result;
1114
+ }
1115
+
1116
+ /** The players with the highest value of a stat. Players without an account are not listed. */
1117
+ async leaderboard(stat: string, page: { limit?: number; offset?: number } = {}): Promise<LeaderboardPage> {
1118
+ checkStat(stat);
1119
+ await this.migrate();
1120
+ const limit = clamp(page.limit ?? 20, 1, 100);
1121
+ const offset = clamp(page.offset ?? 0, 0, 1_000_000);
1122
+ const [rows, total] = await this.#db.batch([
1123
+ this.#db
1124
+ .prepare(
1125
+ `SELECT s.player AS id, a.name AS name, s.value AS value,
1126
+ (SELECT COUNT(*) FROM tickflare_player_stats o JOIN tickflare_accounts oa ON oa.id = o.player
1127
+ WHERE o.stat = s.stat AND o.value > s.value) + 1 AS rank
1128
+ FROM tickflare_player_stats s JOIN tickflare_accounts a ON a.id = s.player
1129
+ WHERE s.stat = ? ORDER BY s.value DESC, a.name_key LIMIT ? OFFSET ?`,
1130
+ )
1131
+ .bind(stat, limit, offset),
1132
+ this.#db
1133
+ .prepare("SELECT COUNT(*) AS total FROM tickflare_player_stats s JOIN tickflare_accounts a ON a.id = s.player WHERE s.stat = ?")
1134
+ .bind(stat),
1135
+ ]);
1136
+ return {
1137
+ stat,
1138
+ entries: (rows!.results as unknown as LeaderboardEntry[]).map((entry) => ({ ...entry })),
1139
+ total: (total!.results[0] as { total: number } | undefined)?.total ?? 0,
1140
+ };
1141
+ }
1142
+
1143
+ /** A player's place on a leaderboard, or null if they have no value for that stat. */
1144
+ async rank(stat: string, playerId: string): Promise<Pick<LeaderboardEntry, "rank" | "value"> | null> {
1145
+ checkStat(stat);
1146
+ await this.migrate();
1147
+ const row = await this.#db
1148
+ .prepare(
1149
+ `SELECT s.value AS value,
1150
+ (SELECT COUNT(*) FROM tickflare_player_stats o JOIN tickflare_accounts oa ON oa.id = o.player
1151
+ WHERE o.stat = s.stat AND o.value > s.value) + 1 AS rank
1152
+ FROM tickflare_player_stats s WHERE s.stat = ? AND s.player = ?`,
1153
+ )
1154
+ .bind(stat, playerId)
1155
+ .first<{ value: number; rank: number }>();
1156
+ return row ? { rank: row.rank, value: row.value } : null;
1157
+ }
1158
+
1159
+ async #writeStats(playerId: string, values: Record<string, number>, update: string): Promise<void> {
1160
+ await this.migrate();
1161
+ const now = Date.now();
1162
+ const statements = Object.entries(values).map(([stat, value]) => this.#statStatement(playerId, stat, value, update, now));
1163
+ if (statements.length > 0) await this.#db.batch(statements);
1164
+ }
1165
+
1166
+ #statStatement(playerId: string, stat: string, value: number, update: string, now: number): D1PreparedStatement {
1167
+ checkStat(stat);
1168
+ if (!Number.isFinite(value)) throw new AccountError(400, "invalid_value", `${stat} must be a finite number.`);
1169
+ return this.#db
1170
+ .prepare(
1171
+ `INSERT INTO tickflare_player_stats (player, stat, value, updated_at) VALUES (?, ?, ?, ?)
1172
+ ON CONFLICT (player, stat) DO UPDATE SET value = ${update}, updated_at = excluded.updated_at`,
1173
+ )
1174
+ .bind(playerId, stat, value, now);
1175
+ }
1176
+
1177
+ // --- Internals ---------------------------------------------------------------------------
1178
+
1179
+ #policy(key: string): Required<DataPolicy> {
1180
+ const policy = this.#policies[key] ?? {};
1181
+ return { read: policy.read ?? "owner", write: policy.write ?? "server" };
1182
+ }
1183
+
1184
+ #sessionToken(request: Request): string | null {
1185
+ return cookieValue(request.headers.get("Cookie"), this.#cookie) ?? bearerSession(request);
1186
+ }
1187
+
1188
+ async #accountForSession(token: string): Promise<{ id: string; name: string } | null> {
1189
+ await this.migrate();
1190
+ const hash = await sha256(token);
1191
+ const now = Date.now();
1192
+ const row = await this.#db
1193
+ .prepare(
1194
+ `SELECT a.id AS id, a.name AS name, s.expires_at AS expires_at
1195
+ FROM tickflare_sessions s JOIN tickflare_accounts a ON a.id = s.account_id
1196
+ WHERE s.token_hash = ? AND s.expires_at > ?`,
1197
+ )
1198
+ .bind(hash, now)
1199
+ .first<{ id: string; name: string; expires_at: number }>();
1200
+ if (!row) return null;
1201
+ // Sliding expiry, written at most once a day.
1202
+ if (row.expires_at - now < this.#sessionTtl - SESSION_REFRESH_MS) {
1203
+ await this.#db.prepare("UPDATE tickflare_sessions SET expires_at = ? WHERE token_hash = ?").bind(now + this.#sessionTtl, hash).run();
1204
+ }
1205
+ return { id: row.id, name: row.name };
1206
+ }
1207
+
1208
+ async #requireAccount(request: Request): Promise<{ id: string; name: string }> {
1209
+ const token = this.#sessionToken(request);
1210
+ const account = token ? await this.#accountForSession(token) : null;
1211
+ if (!account) throw new AccountError(401, "not_signed_in", "Sign in first.");
1212
+ return account;
1213
+ }
1214
+
1215
+ async #signedIn(request: Request, accountId: string, status: number): Promise<Response> {
1216
+ const token = await this.createSession(accountId);
1217
+ const account = await this.ownAccount(accountId);
1218
+ return json({ account, token }, status, { "Set-Cookie": this.#setCookie(request, token) });
1219
+ }
1220
+
1221
+ async #checkPassword(accountId: string, password: string): Promise<void> {
1222
+ const row = await this.#db
1223
+ .prepare("SELECT password_hash FROM tickflare_accounts WHERE id = ?")
1224
+ .bind(accountId)
1225
+ .first<{ password_hash: string }>();
1226
+ if (!row || !(await this.#verify(accountId, row.password_hash, password))) {
1227
+ throw new AccountError(403, "wrong_password", "That password is not right.");
1228
+ }
1229
+ }
1230
+
1231
+ /** Verifies a password, and upgrades a hash imported from elsewhere once it has been checked. */
1232
+ async #verify(accountId: string, hash: string, password: string): Promise<boolean> {
1233
+ if (hash.startsWith("pbkdf2$")) return verifyPassword(hash, password);
1234
+ if (!this.#verifyImported || !(await this.#verifyImported(hash, password))) return false;
1235
+ await this.#db
1236
+ .prepare("UPDATE tickflare_accounts SET password_hash = ? WHERE id = ?")
1237
+ .bind(await hashPassword(password), accountId)
1238
+ .run();
1239
+ return true;
1240
+ }
1241
+
1242
+ async #checkThrottle(keys: string[]): Promise<void> {
1243
+ const rows = await this.#db
1244
+ .prepare(`SELECT key, failures, window_start FROM tickflare_sign_in_failures WHERE key IN (${keys.map(() => "?").join(",")})`)
1245
+ .bind(...keys)
1246
+ .all<{ key: string; failures: number; window_start: number }>();
1247
+ const now = Date.now();
1248
+ for (const row of rows.results) {
1249
+ if (now - row.window_start >= FAILURE_WINDOW_MS) continue;
1250
+ const limit = row.key.startsWith("forgot:")
1251
+ ? MAX_RESET_REQUESTS
1252
+ : row.key.startsWith("address:") || row.key.startsWith("forgot-address:")
1253
+ ? MAX_FAILURES_PER_ADDRESS
1254
+ : MAX_FAILURES_PER_NAME;
1255
+ if (row.failures >= limit) {
1256
+ throw new AccountError(429, "too_many_attempts", "Too many attempts. Try again in a few minutes.");
1257
+ }
1258
+ }
1259
+ }
1260
+
1261
+ async #recordFailure(keys: string[]): Promise<void> {
1262
+ const now = Date.now();
1263
+ await this.#db.batch(
1264
+ keys.map((key) =>
1265
+ this.#db
1266
+ .prepare(
1267
+ `INSERT INTO tickflare_sign_in_failures (key, failures, window_start) VALUES (?1, 1, ?2)
1268
+ ON CONFLICT (key) DO UPDATE SET
1269
+ failures = CASE WHEN ?2 - window_start >= ?3 THEN 1 ELSE failures + 1 END,
1270
+ window_start = CASE WHEN ?2 - window_start >= ?3 THEN ?2 ELSE window_start END`,
1271
+ )
1272
+ .bind(key, now, FAILURE_WINDOW_MS),
1273
+ ),
1274
+ );
1275
+ }
1276
+
1277
+ /** Whether the request comes from no page at all, a page on the API's own origin, or an allowed one. */
1278
+ #originAllowed(request: Request): boolean {
1279
+ const origin = request.headers.get("Origin");
1280
+ // Requests without an Origin header do not come from another site's page.
1281
+ if (!origin) return true;
1282
+ return origin === new URL(request.url).origin || this.#origins.has(origin);
1283
+ }
1284
+
1285
+ /** Refuses writes from other sites' pages, which would otherwise carry the player's cookie. */
1286
+ #checkOrigin(request: Request): void {
1287
+ if (!this.#originAllowed(request)) {
1288
+ throw new AccountError(403, "origin_not_allowed", "This page is not allowed to use the account service.");
1289
+ }
1290
+ }
1291
+
1292
+ /** CORS headers for an allowed origin other than the API's own, or null. */
1293
+ #corsHeaders(request: Request): Record<string, string> | null {
1294
+ const origin = request.headers.get("Origin");
1295
+ if (!origin || !this.#origins.has(origin)) return null;
1296
+ return { "Access-Control-Allow-Origin": origin, "Access-Control-Allow-Credentials": "true", Vary: "Origin" };
1297
+ }
1298
+
1299
+ async #hasAccount(playerId: string): Promise<boolean> {
1300
+ await this.migrate();
1301
+ return (await this.#db.prepare("SELECT 1 FROM tickflare_accounts WHERE id = ?").bind(playerId).first()) !== null;
1302
+ }
1303
+
1304
+ #setCookie(request: Request, token: string): string {
1305
+ const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
1306
+ // A page on an allowed origin of its own can only use the cookie if it is sent cross-site.
1307
+ const origin = request.headers.get("Origin");
1308
+ const crossSite = secure && origin !== null && this.#origins.has(origin) ? "None" : this.#sameSite;
1309
+ return `${this.#cookie}=${token}; Path=/; HttpOnly; SameSite=${crossSite}; Max-Age=${Math.floor(this.#sessionTtl / 1000)}${secure}`;
1310
+ }
1311
+
1312
+ #clearCookie(request: Request): string {
1313
+ const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
1314
+ return `${this.#cookie}=; Path=/; HttpOnly; SameSite=${this.#sameSite}; Max-Age=0${secure}`;
1315
+ }
1316
+ }
1317
+
1318
+ // --- Passwords -----------------------------------------------------------------------------------
1319
+
1320
+ /** A PBKDF2-SHA256 hash, as `pbkdf2$sha256$<iterations>$<salt>$<hash>` in base64url. */
1321
+ export async function hashPassword(password: string, iterations = PBKDF2_ITERATIONS): Promise<string> {
1322
+ const salt = crypto.getRandomValues(new Uint8Array(16));
1323
+ const hash = await pbkdf2(password, salt, iterations);
1324
+ return `pbkdf2$sha256$${iterations}$${toBase64Url(salt)}$${toBase64Url(hash)}`;
1325
+ }
1326
+
1327
+ /** Whether `password` matches a hash made by `hashPassword`, in constant time. */
1328
+ export async function verifyPassword(stored: string, password: string): Promise<boolean> {
1329
+ const [scheme, digest, iterations, salt, hash] = stored.split("$");
1330
+ if (scheme !== "pbkdf2" || digest !== "sha256" || !iterations || !salt || !hash) return false;
1331
+ const expected = fromBase64Url(hash);
1332
+ const actual = await pbkdf2(password, fromBase64Url(salt), Number(iterations));
1333
+ if (actual.length !== expected.length) return false;
1334
+ let difference = 0;
1335
+ for (let index = 0; index < actual.length; index++) difference |= actual[index]! ^ expected[index]!;
1336
+ return difference === 0;
1337
+ }
1338
+
1339
+ async function pbkdf2(password: string, salt: Uint8Array, iterations: number): Promise<Uint8Array> {
1340
+ const key = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]);
1341
+ const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, key, 256);
1342
+ return new Uint8Array(bits);
1343
+ }
1344
+
1345
+ // --- Small helpers -----------------------------------------------------------------------------------
1346
+
1347
+ function normalizeName(input: string): string {
1348
+ const name = input.normalize("NFKC").trim().replace(/\s+/g, " ");
1349
+ if (!NAME_PATTERN.test(name)) {
1350
+ throw new AccountError(
1351
+ 400,
1352
+ "invalid_name",
1353
+ "A name is 3 to 24 letters, digits, spaces, dots, dashes or underscores, starting and ending with a letter or digit.",
1354
+ );
1355
+ }
1356
+ return name;
1357
+ }
1358
+
1359
+ /** What makes two names the same name: case and look-alike forms do not count. */
1360
+ function nameKey(name: string): string {
1361
+ return name.normalize("NFKC").toLowerCase().replace(/[\s_.-]+/g, "");
1362
+ }
1363
+
1364
+ function normalizeEmail(input: string | null): string | null {
1365
+ if (input === null || input.trim() === "") return null;
1366
+ const email = input.trim();
1367
+ if (email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
1368
+ throw new AccountError(400, "invalid_email", "That email address does not look right.");
1369
+ }
1370
+ return email;
1371
+ }
1372
+
1373
+ function checkPassword(password: string): void {
1374
+ if (typeof password !== "string" || password.length < MIN_PASSWORD || password.length > MAX_PASSWORD) {
1375
+ throw new AccountError(400, "weak_password", `A password is at least ${MIN_PASSWORD} characters.`);
1376
+ }
1377
+ }
1378
+
1379
+ function checkKey(key: string): void {
1380
+ if (!KEY_PATTERN.test(key)) throw new AccountError(400, "invalid_key", "Keys are 1 to 64 letters, digits, dots, dashes or underscores.");
1381
+ }
1382
+
1383
+ function checkStat(stat: string): void {
1384
+ if (!STAT_PATTERN.test(stat)) throw new AccountError(400, "invalid_stat", "Stats are 1 to 64 letters, digits, dots, dashes or underscores.");
1385
+ }
1386
+
1387
+ async function readJson(request: Request): Promise<Record<string, unknown>> {
1388
+ if (!request.headers.get("Content-Type")?.includes("application/json")) {
1389
+ throw new AccountError(415, "json_required", "Send JSON with Content-Type: application/json.");
1390
+ }
1391
+ try {
1392
+ const body = (await request.json()) as unknown;
1393
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new Error("not an object");
1394
+ return body as Record<string, unknown>;
1395
+ } catch {
1396
+ throw new AccountError(400, "invalid_request", "The body is not a JSON object.");
1397
+ }
1398
+ }
1399
+
1400
+ function stringField(body: Record<string, unknown>, field: string): string {
1401
+ const value = body[field];
1402
+ if (typeof value !== "string") throw new AccountError(400, "invalid_request", `Send "${field}" as a string.`);
1403
+ return value;
1404
+ }
1405
+
1406
+ function bearer(request: Request): string | null {
1407
+ return request.headers.get("Authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? null;
1408
+ }
1409
+
1410
+ /** A session token sent as a bearer token. Join tokens are signed ("v1.…"); session tokens are opaque. */
1411
+ function bearerSession(request: Request): string | null {
1412
+ const token = bearer(request);
1413
+ return token && !token.startsWith("v1.") ? token : null;
1414
+ }
1415
+
1416
+ function address(request: Request): string {
1417
+ return request.headers.get("CF-Connecting-IP") ?? "unknown";
1418
+ }
1419
+
1420
+ function cookieValue(header: string | null, name: string): string | null {
1421
+ if (!header) return null;
1422
+ for (const part of header.split(";")) {
1423
+ const [key, ...rest] = part.trim().split("=");
1424
+ if (key === name) return rest.join("=") || null;
1425
+ }
1426
+ return null;
1427
+ }
1428
+
1429
+ function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
1430
+ return new Response(JSON.stringify(body), {
1431
+ status,
1432
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers },
1433
+ });
1434
+ }
1435
+
1436
+ function clamp(value: number, min: number, max: number): number {
1437
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, Math.floor(value))) : min;
1438
+ }
1439
+
1440
+ /** A recovery code: twenty characters, a hundred bits, in four groups to read and type. */
1441
+ function recoveryCode(): string {
1442
+ const bytes = crypto.getRandomValues(new Uint8Array(20));
1443
+ const letters = Array.from(bytes, (byte) => CODE_ALPHABET[byte & 31]).join("");
1444
+ return letters.match(/.{5}/g)!.join("-");
1445
+ }
1446
+
1447
+ /** A recovery code as it is hashed: however it was typed, with the characters people mistake put right. */
1448
+ function codeKey(code: string): string {
1449
+ return code
1450
+ .toUpperCase()
1451
+ .replace(/[^0-9A-Z]/g, "")
1452
+ .replace(/O/g, "0")
1453
+ .replace(/[IL]/g, "1");
1454
+ }
1455
+
1456
+ function randomToken(): string {
1457
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
1458
+ }
1459
+
1460
+ async function sha256(value: string): Promise<string> {
1461
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
1462
+ return [...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1463
+ }
1464
+
1465
+ function toBase64Url(bytes: Uint8Array): string {
1466
+ let binary = "";
1467
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1468
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1469
+ }
1470
+
1471
+ function fromBase64Url(value: string): Uint8Array {
1472
+ const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((value.length + 3) % 4));
1473
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1474
+ }