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