@nano133/nanoterra 0.8.0 → 0.9.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 (132) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/LICENSE +3 -0
  3. package/README.md +363 -25
  4. package/ai/SPEC.md +65 -3
  5. package/dist/admin/panel/dom.d.ts +2 -0
  6. package/dist/admin/panel/dom.js +6 -0
  7. package/dist/admin/panel/mount.d.ts +3 -0
  8. package/dist/admin/panel/mount.js +4 -2
  9. package/dist/emotes/panel/mount.d.ts +5 -0
  10. package/dist/emotes/panel/mount.js +7 -3
  11. package/dist/friends/panel/mount.d.ts +5 -0
  12. package/dist/friends/panel/mount.js +5 -2
  13. package/dist/options/panel/mount.d.ts +5 -0
  14. package/dist/options/panel/mount.js +5 -3
  15. package/dist/player-signin/adapters/d1.d.ts +10 -0
  16. package/dist/player-signin/adapters/d1.js +108 -0
  17. package/dist/player-signin/adapters/firestore.d.ts +45 -0
  18. package/dist/player-signin/adapters/firestore.js +168 -0
  19. package/dist/player-signin/conformance.d.ts +11 -0
  20. package/dist/player-signin/conformance.js +160 -0
  21. package/dist/player-signin/handler.d.ts +64 -0
  22. package/dist/player-signin/handler.js +364 -0
  23. package/dist/player-signin/host.d.ts +4 -0
  24. package/dist/player-signin/host.js +10 -0
  25. package/dist/player-signin/index.d.ts +9 -0
  26. package/dist/player-signin/index.js +15 -0
  27. package/dist/player-signin/memory.d.ts +15 -0
  28. package/dist/player-signin/memory.js +101 -0
  29. package/dist/player-signin/panel/index.d.ts +9 -0
  30. package/dist/player-signin/panel/index.js +7 -0
  31. package/dist/player-signin/panel/memo.d.ts +12 -0
  32. package/dist/player-signin/panel/memo.js +41 -0
  33. package/dist/player-signin/panel/mount.d.ts +21 -0
  34. package/dist/player-signin/panel/mount.js +105 -0
  35. package/dist/player-signin/panel/view.d.ts +45 -0
  36. package/dist/player-signin/panel/view.js +360 -0
  37. package/dist/player-signin/panel/words.d.ts +8 -0
  38. package/dist/player-signin/panel/words.js +26 -0
  39. package/dist/player-signin/scheme-check.d.ts +3 -0
  40. package/dist/player-signin/scheme-check.js +14 -0
  41. package/dist/player-signin/scheme.d.ts +13 -0
  42. package/dist/player-signin/scheme.js +28 -0
  43. package/dist/player-signin/types.d.ts +116 -0
  44. package/dist/player-signin/types.js +33 -0
  45. package/dist/shop/adapters/d1.d.ts +25 -0
  46. package/dist/shop/adapters/d1.js +200 -0
  47. package/dist/shop/adapters/firestore.d.ts +53 -0
  48. package/dist/shop/adapters/firestore.js +245 -0
  49. package/dist/shop/address.d.ts +14 -0
  50. package/dist/shop/address.js +104 -0
  51. package/dist/shop/amount.d.ts +26 -0
  52. package/dist/shop/amount.js +59 -0
  53. package/dist/shop/conformance.d.ts +13 -0
  54. package/dist/shop/conformance.js +203 -0
  55. package/dist/shop/handler.d.ts +76 -0
  56. package/dist/shop/handler.js +156 -0
  57. package/dist/shop/index.d.ts +19 -0
  58. package/dist/shop/index.js +21 -0
  59. package/dist/shop/match.d.ts +23 -0
  60. package/dist/shop/match.js +58 -0
  61. package/dist/shop/memory.d.ts +13 -0
  62. package/dist/shop/memory.js +106 -0
  63. package/dist/shop/nodes.d.ts +47 -0
  64. package/dist/shop/nodes.js +106 -0
  65. package/dist/shop/orders.d.ts +47 -0
  66. package/dist/shop/orders.js +82 -0
  67. package/dist/shop/panel/index.d.ts +7 -0
  68. package/dist/shop/panel/index.js +11 -0
  69. package/dist/shop/panel/looks.d.ts +30 -0
  70. package/dist/shop/panel/looks.js +61 -0
  71. package/dist/shop/panel/mount.d.ts +52 -0
  72. package/dist/shop/panel/mount.js +194 -0
  73. package/dist/shop/panel/pay.d.ts +24 -0
  74. package/dist/shop/panel/pay.js +115 -0
  75. package/dist/shop/panel/qr.d.ts +9 -0
  76. package/dist/shop/panel/qr.js +281 -0
  77. package/dist/shop/price.d.ts +23 -0
  78. package/dist/shop/price.js +43 -0
  79. package/dist/shop/scan.d.ts +24 -0
  80. package/dist/shop/scan.js +80 -0
  81. package/dist/shop/security.d.ts +10 -0
  82. package/dist/shop/security.js +56 -0
  83. package/dist/shop/store.d.ts +101 -0
  84. package/dist/shop/store.js +4 -0
  85. package/dist/shop/worker.d.ts +43 -0
  86. package/dist/shop/worker.js +76 -0
  87. package/package.json +21 -6
  88. package/src/admin/panel/dom.ts +6 -0
  89. package/src/admin/panel/mount.ts +7 -2
  90. package/src/emotes/panel/mount.ts +9 -2
  91. package/src/friends/panel/mount.ts +8 -2
  92. package/src/options/panel/mount.ts +8 -3
  93. package/src/player-signin/adapters/d1.sql +45 -0
  94. package/src/player-signin/adapters/d1.ts +120 -0
  95. package/src/player-signin/adapters/firestore.ts +194 -0
  96. package/src/player-signin/conformance.ts +184 -0
  97. package/src/player-signin/handler.ts +404 -0
  98. package/src/player-signin/host.ts +12 -0
  99. package/src/player-signin/index.ts +20 -0
  100. package/src/player-signin/memory.ts +94 -0
  101. package/src/player-signin/panel/index.ts +12 -0
  102. package/src/player-signin/panel/memo.ts +49 -0
  103. package/src/player-signin/panel/mount.ts +127 -0
  104. package/src/player-signin/panel/style.css +473 -0
  105. package/src/player-signin/panel/view.ts +428 -0
  106. package/src/player-signin/panel/words.ts +32 -0
  107. package/src/player-signin/scheme-check.ts +14 -0
  108. package/src/player-signin/scheme.ts +32 -0
  109. package/src/player-signin/types.ts +103 -0
  110. package/src/shop/adapters/d1.sql +52 -0
  111. package/src/shop/adapters/d1.ts +245 -0
  112. package/src/shop/adapters/firestore.ts +281 -0
  113. package/src/shop/address.ts +102 -0
  114. package/src/shop/amount.ts +66 -0
  115. package/src/shop/conformance.ts +232 -0
  116. package/src/shop/handler.ts +202 -0
  117. package/src/shop/index.ts +30 -0
  118. package/src/shop/match.ts +63 -0
  119. package/src/shop/memory.ts +102 -0
  120. package/src/shop/nodes.ts +115 -0
  121. package/src/shop/orders.ts +93 -0
  122. package/src/shop/panel/index.ts +15 -0
  123. package/src/shop/panel/looks.ts +106 -0
  124. package/src/shop/panel/mount.ts +241 -0
  125. package/src/shop/panel/pay.ts +171 -0
  126. package/src/shop/panel/qr.ts +256 -0
  127. package/src/shop/panel/style.css +534 -0
  128. package/src/shop/price.ts +52 -0
  129. package/src/shop/scan.ts +90 -0
  130. package/src/shop/security.ts +50 -0
  131. package/src/shop/store.ts +99 -0
  132. package/src/shop/worker.ts +107 -0
@@ -12,7 +12,7 @@
12
12
  // The panel is phone first: a sheet from the bottom on a phone held upright, from the right on a wide or sideways screen; every key is 44 px or more.
13
13
  // `key: false` draws no key, for a game that opens the panel from its own pause menu (`open()`).
14
14
 
15
- import { h } from "../../admin/panel/dom.js";
15
+ import { h, releaseFocus } from "../../admin/panel/dom.js";
16
16
  import { icon } from "../../admin/panel/icons.js";
17
17
  import { keyLabel, type ChoiceDef, type KeyDef, type OptionDef, type OptionsStore, type OptionValue, type RangeDef, type Tab, type ToggleDef } from "../core.js";
18
18
 
@@ -28,6 +28,11 @@ export type OptionsMountOptions = {
28
28
  onRangeDone?: (key: string, value: number) => void;
29
29
  /** Asks the player a yes or no question (default: a question in the panel, with a key for each answer; never a browser dialog). */
30
30
  confirm?: (question: string) => boolean | Promise<boolean>;
31
+ /**
32
+ * Where the keyboard focus goes when the panel closes. "game" (the default): out of the key and the panel, to the page, so Space and the game's
33
+ * other keys reach the game again (a focused key would take Space and open the panel again). "key": back to the key, for a page with no keys of its own.
34
+ */
35
+ focusAfterClose?: "game" | "key";
31
36
  };
32
37
 
33
38
  export type MountedOptions = {
@@ -318,8 +323,8 @@ export function mountOptions(root: HTMLElement, store: OptionsStore, options: Op
318
323
  panel.dataset.open = scrim.dataset.open = "false";
319
324
  key?.setAttribute("aria-expanded", "false");
320
325
  options.onClose?.();
321
- const back = key ?? (returnTo?.isConnected ? returnTo : null);
322
- back?.focus();
326
+ if (options.focusAfterClose === "key") (key ?? (returnTo?.isConnected ? returnTo : null))?.focus();
327
+ else releaseFocus(wrap);
323
328
  };
324
329
  key?.addEventListener("click", () => (isOpen ? close() : open()));
325
330
  closeKey.addEventListener("click", close);
@@ -0,0 +1,45 @@
1
+ -- The player sign-in tables of "@nano133/nanoterra/player-signin/d1". Add this file to the game's migrations (for example
2
+ -- migrations/0008_player_signin.sql) and run `wrangler d1 migrations apply`. The adapter reads and writes only these three tables, and only their
3
+ -- PLAYER rows (scope = 'play').
4
+ --
5
+ -- The game starter has the first two tables already (migrations 0001, 0002, 0003 and 0006): `IF NOT EXISTS` leaves them and their rows as they are,
6
+ -- so every player who is signed in stays signed in. For the starter this file adds `signin_once` and three indexes, nothing else.
7
+ -- Times are milliseconds since 1970 (Date.now()).
8
+
9
+ -- Wallet sign-in requests (Berry Wallet, Nautilus, NanChat). They live 5 minutes; the clean-up deletes them 2 hours after they end.
10
+ CREATE TABLE IF NOT EXISTS signin_requests (
11
+ id TEXT PRIMARY KEY, -- the store key: the request's id (Berry Wallet, Nautilus) or the SHA-256 of its nonce (NanChat)
12
+ rid TEXT, -- the browser's id for its checks
13
+ way TEXT NOT NULL DEFAULT 'berry', -- berry | nautilus | nanchat
14
+ starter TEXT NOT NULL, -- the SHA-256 of the starting browser's cookie
15
+ status TEXT NOT NULL, -- waiting | signedin
16
+ expires_at INTEGER NOT NULL,
17
+ nonce TEXT,
18
+ issued_at INTEGER,
19
+ label TEXT, -- Nautilus: the label it shows and signs
20
+ account TEXT, -- the address that signed
21
+ delivered INTEGER NOT NULL DEFAULT 0, -- 1 once a session was made from it
22
+ scope TEXT NOT NULL DEFAULT 'play' -- 'play' (a player's) or 'admin' (the game's own admin sign-in, which this adapter never reads)
23
+ );
24
+ CREATE INDEX IF NOT EXISTS signin_requests_by_rid ON signin_requests (rid);
25
+ CREATE INDEX IF NOT EXISTS signin_requests_by_account ON signin_requests (account);
26
+
27
+ -- Sessions. Only the SHA-256 of the cookie's token is stored.
28
+ CREATE TABLE IF NOT EXISTS sessions (
29
+ id_hash TEXT PRIMARY KEY,
30
+ address TEXT NOT NULL,
31
+ created_at INTEGER NOT NULL,
32
+ expires_at INTEGER NOT NULL,
33
+ via TEXT NOT NULL DEFAULT 'wallet', -- wallet | passkey | nanoterra
34
+ scope TEXT NOT NULL DEFAULT 'play' -- 'play' (a player's) or 'admin' (never read by this adapter)
35
+ );
36
+ CREATE INDEX IF NOT EXISTS sessions_by_expiry ON sessions (expires_at);
37
+ CREATE INDEX IF NOT EXISTS sessions_by_address ON sessions (address);
38
+
39
+ -- The passkey sign-in's once-only keys: the hash of each signed message, so one signature signs in once.
40
+ CREATE TABLE IF NOT EXISTS signin_once (
41
+ key TEXT PRIMARY KEY,
42
+ address TEXT NOT NULL,
43
+ until INTEGER NOT NULL
44
+ );
45
+ CREATE INDEX IF NOT EXISTS signin_once_by_address ON signin_once (address);
@@ -0,0 +1,120 @@
1
+ // The player sign-in's store for a game on Cloudflare D1. The tables are in ./d1.sql (the package ships it: "@nano133/nanoterra/player-signin/d1.sql");
2
+ // add it to the game's migrations. They are the game starter's own `signin_requests` and `sessions` (so a starter's data carries over: every
3
+ // player stays signed in) and one more, `signin_once`.
4
+ //
5
+ // import { createD1PlayerSignin } from "@nano133/nanoterra/player-signin/d1";
6
+ // const store = createD1PlayerSignin(env.DB);
7
+ //
8
+ // It reads and writes ONLY the player's rows (scope = 'play'): a game whose admin signs in through the same tables (the starter's scope 'admin')
9
+ // keeps its admin rows, and this adapter never reads, delivers, ends or deletes one. D1 has no transaction that reads and then writes, so each change
10
+ // is ONE statement that holds its own check, and a delivery and its session are one batch (the session is written only when the delivery changed a row).
11
+
12
+ import type { D1Like } from "../../admin/adapters/d1.js";
13
+ import { WAYS, type PlayerSigninStore, type RequestStoreLike, type SessionRecord, type SigninRequest, type Way } from "../types.js";
14
+
15
+ export type { D1Like, D1StatementLike } from "../../admin/adapters/d1.js";
16
+
17
+ /** The tables' names. Default: the game starter's. A game with other names changes d1.sql to match. */
18
+ export type D1PlayerSigninTables = { requests?: string; sessions?: string; once?: string };
19
+
20
+ type Row = { id: string; rid: string | null; starter: string; status: string; expires_at: number; nonce: string | null; issued_at: number | null; label: string | null; account: string | null };
21
+
22
+ const toRequest = (r: Row): SigninRequest => ({
23
+ id: r.rid ?? r.id,
24
+ starter: r.starter,
25
+ status: r.status === "signedin" ? "signedin" : "waiting",
26
+ expiresAt: Number(r.expires_at),
27
+ ...(r.label ? { label: r.label } : {}),
28
+ ...(r.nonce ? { nonce: r.nonce } : {}),
29
+ ...(r.issued_at ? { issuedAt: Number(r.issued_at) } : {}),
30
+ ...(r.account ? { account: r.account } : {}),
31
+ });
32
+
33
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
34
+ const changes = (res: unknown): number => Number((res as { meta?: { changes?: number } } | undefined)?.meta?.changes ?? 0);
35
+
36
+ export function createD1PlayerSignin(db: D1Like, tables: D1PlayerSigninTables = {}): PlayerSigninStore {
37
+ const T = { requests: tables.requests ?? "signin_requests", sessions: tables.sessions ?? "sessions", once: tables.once ?? "signin_once" };
38
+ for (const n of Object.values(T)) if (!NAME.test(n)) throw new Error(`not a table name: ${n}`);
39
+ const COLS = "id, rid, starter, status, expires_at, nonce, issued_at, label, account";
40
+
41
+ const stores = new Map<Way, RequestStoreLike>();
42
+ for (const way of WAYS) {
43
+ stores.set(way, {
44
+ async create(key, r) {
45
+ await db
46
+ .prepare(`INSERT INTO ${T.requests} (id, rid, way, starter, status, expires_at, nonce, issued_at, label, scope) VALUES (?, ?, ?, ?, 'waiting', ?, ?, ?, ?, 'play')`)
47
+ .bind(key, r.id, way, r.starter, r.expiresAt, r.nonce ?? null, r.issuedAt ?? null, r.label ?? null)
48
+ .run();
49
+ },
50
+ async get(key) {
51
+ const r = await db.prepare(`SELECT ${COLS} FROM ${T.requests} WHERE id = ? AND way = ? AND scope = 'play'`).bind(key, way).first<Row>();
52
+ return r ? toRequest(r) : null;
53
+ },
54
+ async find(id) {
55
+ const r = await db.prepare(`SELECT ${COLS} FROM ${T.requests} WHERE rid = ? AND way = ? AND scope = 'play'`).bind(id, way).first<Row>();
56
+ return r ? { key: r.id, request: toRequest(r) } : null;
57
+ },
58
+ async finish(key, account) {
59
+ return changes(await db.prepare(`UPDATE ${T.requests} SET status = 'signedin', account = ? WHERE id = ? AND way = ? AND status = 'waiting' AND scope = 'play'`).bind(account, key, way).run()) === 1;
60
+ },
61
+ });
62
+ }
63
+
64
+ const insertSession = (s: SessionRecord, afterChange: boolean) => {
65
+ const cols = `INSERT INTO ${T.sessions} (id_hash, address, created_at, expires_at, via, scope)`;
66
+ return db.prepare(afterChange ? `${cols} SELECT ?, ?, ?, ?, ?, 'play' WHERE changes() = 1` : `${cols} VALUES (?, ?, ?, ?, ?, 'play')`).bind(s.idHash, s.address, s.createdAt, s.expiresAt, s.via);
67
+ };
68
+
69
+ return {
70
+ requests: (way) => {
71
+ const s = stores.get(way);
72
+ if (!s) throw new Error(`no such way: ${String(way)}`);
73
+ return s;
74
+ },
75
+ async deliver(way, key, session) {
76
+ const done = await db.batch([
77
+ db.prepare(`UPDATE ${T.requests} SET delivered = 1 WHERE id = ? AND way = ? AND delivered = 0 AND status = 'signedin' AND scope = 'play'`).bind(key, way),
78
+ insertSession(session, true),
79
+ ]);
80
+ return changes(done[0]) === 1;
81
+ },
82
+ async createSession(session) {
83
+ await insertSession(session, false).run();
84
+ },
85
+ async session(idHash, now) {
86
+ const r = await db
87
+ .prepare(`SELECT id_hash, address, created_at, expires_at, via FROM ${T.sessions} WHERE id_hash = ? AND expires_at > ? AND scope = 'play'`)
88
+ .bind(idHash, now)
89
+ .first<{ id_hash: string; address: string; created_at: number; expires_at: number; via: string }>();
90
+ return r ? { idHash: r.id_hash, address: r.address, createdAt: Number(r.created_at), expiresAt: Number(r.expires_at), via: r.via as SessionRecord["via"] } : null;
91
+ },
92
+ async endSession(idHash) {
93
+ await db.prepare(`DELETE FROM ${T.sessions} WHERE id_hash = ? AND scope = 'play'`).bind(idHash).run();
94
+ },
95
+ async useOnce(key, ttlMs, address) {
96
+ const now = Date.now();
97
+ // A row past its time may be taken again (its signature's 5 minutes are long over); a live one may not.
98
+ const res = await db
99
+ .prepare(`INSERT INTO ${T.once} (key, address, until) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET address = excluded.address, until = excluded.until WHERE ${T.once}.until <= ?`)
100
+ .bind(key, address, now + ttlMs, now)
101
+ .run();
102
+ return changes(res) === 1;
103
+ },
104
+ async forget(address) {
105
+ const done = await db.batch([
106
+ db.prepare(`DELETE FROM ${T.sessions} WHERE address = ? AND scope = 'play'`).bind(address),
107
+ db.prepare(`DELETE FROM ${T.requests} WHERE account = ? AND scope = 'play'`).bind(address),
108
+ db.prepare(`DELETE FROM ${T.once} WHERE address = ?`).bind(address),
109
+ ]);
110
+ return done.reduce<number>((n, r) => n + changes(r), 0);
111
+ },
112
+ async clean(now) {
113
+ await db.batch([
114
+ db.prepare(`DELETE FROM ${T.requests} WHERE expires_at < ? AND scope = 'play'`).bind(now - 2 * 3_600_000),
115
+ db.prepare(`DELETE FROM ${T.sessions} WHERE expires_at <= ? AND scope = 'play'`).bind(now),
116
+ db.prepare(`DELETE FROM ${T.once} WHERE until <= ?`).bind(now),
117
+ ]);
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,194 @@
1
+ // The player sign-in's store for a game on Firestore (the Admin SDK). The package has no Firebase dependency: the adapter uses the small interface
2
+ // below, which the Admin SDK's `Firestore` fits. It reads and writes ONLY its three collections, and only the player's documents (scope "play").
3
+ //
4
+ // import { createFirestorePlayerSignin } from "@nano133/nanoterra/player-signin/firestore";
5
+ // const store = createFirestorePlayerSignin(getFirestore());
6
+ //
7
+ // The data model (the three collection names can be changed):
8
+ // signin_requests/{key} { id, way, starter, status, expiresAt, nonce?, issuedAt?, label?, account?, delivered, scope: "play", deleteAt }
9
+ // sessions/{idHash} { address, createdAt, expiresAt, via, scope: "play", deleteAt }
10
+ // signin_once/{key} { address, until, deleteAt }
11
+ // Times are ms numbers; `deleteAt` is a Date (a Timestamp in Firestore): set a TTL policy on `deleteAt` for each collection. `{key}` is the request's
12
+ // id (Berry Wallet, Nautilus) or the SHA-256 of its nonce (NanChat); `{idHash}` the SHA-256 of the session's token. Every change that reads first is a
13
+ // transaction. Indexes: Firestore's own single-field indexes are enough (`id`, `address`, `account`, `expiresAt`, `until`).
14
+
15
+ import { WAYS, type PlayerSigninStore, type RequestStoreLike, type SessionRecord, type SigninRequest, type Way } from "../types.js";
16
+
17
+ export type PlayerSigninDocSnap = { exists: boolean; data(): Record<string, unknown> | undefined };
18
+ export interface PlayerSigninDocRef {
19
+ get(): Promise<PlayerSigninDocSnap>;
20
+ }
21
+ export type PlayerSigninQuerySnap = { docs: { id: string; ref: PlayerSigninDocRef; data(): Record<string, unknown> }[] };
22
+ export interface PlayerSigninQuery {
23
+ where(field: string, op: "==" | "<" | "<=", value: unknown): PlayerSigninQuery;
24
+ limit(n: number): PlayerSigninQuery;
25
+ get(): Promise<PlayerSigninQuerySnap>;
26
+ }
27
+ export interface PlayerSigninCollection extends PlayerSigninQuery {
28
+ doc(id: string): PlayerSigninDocRef;
29
+ }
30
+ /** A transaction: every read before the first write, as Firestore asks. */
31
+ export interface PlayerSigninTransaction {
32
+ get(ref: PlayerSigninDocRef): Promise<PlayerSigninDocSnap>;
33
+ set(ref: PlayerSigninDocRef, data: Record<string, unknown>, options?: { merge?: boolean }): unknown;
34
+ delete(ref: PlayerSigninDocRef): unknown;
35
+ }
36
+ export interface PlayerSigninBatch {
37
+ delete(ref: PlayerSigninDocRef): unknown;
38
+ commit(): Promise<unknown>;
39
+ }
40
+ export interface FirestorePlayerSigninLike {
41
+ collection(name: string): PlayerSigninCollection;
42
+ runTransaction<T>(fn: (tx: PlayerSigninTransaction) => Promise<T>): Promise<T>;
43
+ batch(): PlayerSigninBatch;
44
+ }
45
+
46
+ const DAY = 86_400_000;
47
+ /** At most this many documents go in one batch (Firestore's limit is 500). */
48
+ const BATCH = 400;
49
+
50
+ const text = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
51
+ const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
52
+
53
+ function requestOf(d: Record<string, unknown> | undefined, key: string, way: Way): SigninRequest | null {
54
+ if (!d || d.scope !== "play" || d.way !== way || typeof d.starter !== "string" || num(d.expiresAt) === undefined) return null;
55
+ const nonce = text(d.nonce);
56
+ const issuedAt = num(d.issuedAt);
57
+ const label = text(d.label);
58
+ const account = text(d.account);
59
+ return {
60
+ id: text(d.id) ?? key,
61
+ starter: d.starter,
62
+ status: d.status === "signedin" ? "signedin" : "waiting",
63
+ expiresAt: num(d.expiresAt)!,
64
+ ...(label !== undefined ? { label } : {}),
65
+ ...(nonce !== undefined ? { nonce } : {}),
66
+ ...(issuedAt !== undefined ? { issuedAt } : {}),
67
+ ...(account !== undefined ? { account } : {}),
68
+ };
69
+ }
70
+
71
+ export function createFirestorePlayerSignin(db: FirestorePlayerSigninLike, collections: { requests?: string; sessions?: string; once?: string } = {}): PlayerSigninStore {
72
+ const requestsCol = () => db.collection(collections.requests ?? "signin_requests");
73
+ const sessionsCol = () => db.collection(collections.sessions ?? "sessions");
74
+ const onceCol = () => db.collection(collections.once ?? "signin_once");
75
+
76
+ const sessionData = (s: SessionRecord) => ({ address: s.address, createdAt: s.createdAt, expiresAt: s.expiresAt, via: s.via, scope: "play", deleteAt: new Date(s.expiresAt) });
77
+
78
+ const stores = new Map<Way, RequestStoreLike>();
79
+ for (const way of WAYS) {
80
+ stores.set(way, {
81
+ async create(key, r) {
82
+ const ref = requestsCol().doc(key);
83
+ await db.runTransaction(async (tx) => {
84
+ if ((await tx.get(ref)).exists) throw new Error("a request with this key exists");
85
+ tx.set(ref, {
86
+ id: r.id,
87
+ way,
88
+ starter: r.starter,
89
+ status: "waiting",
90
+ expiresAt: r.expiresAt,
91
+ ...(r.nonce !== undefined ? { nonce: r.nonce } : {}),
92
+ ...(r.issuedAt !== undefined ? { issuedAt: r.issuedAt } : {}),
93
+ ...(r.label !== undefined ? { label: r.label } : {}),
94
+ delivered: false,
95
+ scope: "play",
96
+ deleteAt: new Date(r.expiresAt + DAY),
97
+ });
98
+ });
99
+ },
100
+ async get(key) {
101
+ return requestOf((await requestsCol().doc(key).get()).data(), key, way);
102
+ },
103
+ async find(id) {
104
+ for (const d of (await requestsCol().where("id", "==", id).limit(10).get()).docs) {
105
+ const request = requestOf(d.data(), d.id, way);
106
+ if (request) return { key: d.id, request };
107
+ }
108
+ return null;
109
+ },
110
+ async finish(key, account) {
111
+ const ref = requestsCol().doc(key);
112
+ return db.runTransaction(async (tx) => {
113
+ const cur = requestOf((await tx.get(ref)).data(), key, way);
114
+ if (!cur || cur.status !== "waiting") return false;
115
+ tx.set(ref, { status: "signedin", account }, { merge: true });
116
+ return true;
117
+ });
118
+ },
119
+ });
120
+ }
121
+
122
+ async function deleteAll(docs: { ref: PlayerSigninDocRef }[]): Promise<number> {
123
+ for (let i = 0; i < docs.length; i += BATCH) {
124
+ const b = db.batch();
125
+ for (const d of docs.slice(i, i + BATCH)) b.delete(d.ref);
126
+ await b.commit();
127
+ }
128
+ return docs.length;
129
+ }
130
+
131
+ return {
132
+ requests: (way) => {
133
+ const s = stores.get(way);
134
+ if (!s) throw new Error(`no such way: ${String(way)}`);
135
+ return s;
136
+ },
137
+ async deliver(way, key, session) {
138
+ const ref = requestsCol().doc(key);
139
+ const sref = sessionsCol().doc(session.idHash);
140
+ return db.runTransaction(async (tx) => {
141
+ const raw = (await tx.get(ref)).data();
142
+ const cur = requestOf(raw, key, way);
143
+ await tx.get(sref);
144
+ if (!cur || cur.status !== "signedin" || raw?.delivered === true) return false;
145
+ tx.set(ref, { delivered: true }, { merge: true });
146
+ tx.set(sref, sessionData(session));
147
+ return true;
148
+ });
149
+ },
150
+ async createSession(session) {
151
+ const ref = sessionsCol().doc(session.idHash);
152
+ await db.runTransaction(async (tx) => {
153
+ if ((await tx.get(ref)).exists) throw new Error("a session with this id exists");
154
+ tx.set(ref, sessionData(session));
155
+ });
156
+ },
157
+ async session(idHash, now) {
158
+ const d = (await sessionsCol().doc(idHash).get()).data();
159
+ if (!d || d.scope !== "play" || typeof d.address !== "string") return null;
160
+ const expiresAt = num(d.expiresAt);
161
+ if (expiresAt === undefined || expiresAt <= now) return null;
162
+ return { idHash, address: d.address, createdAt: num(d.createdAt) ?? 0, expiresAt, via: d.via as SessionRecord["via"] };
163
+ },
164
+ async endSession(idHash) {
165
+ const ref = sessionsCol().doc(idHash);
166
+ await db.runTransaction(async (tx) => {
167
+ const d = (await tx.get(ref)).data();
168
+ if (d && d.scope === "play") tx.delete(ref);
169
+ });
170
+ },
171
+ async useOnce(key, ttlMs, address) {
172
+ const ref = onceCol().doc(key);
173
+ return db.runTransaction(async (tx) => {
174
+ const now = Date.now();
175
+ const d = (await tx.get(ref)).data();
176
+ if (d && (num(d.until) ?? Infinity) > now) return false;
177
+ tx.set(ref, { address, until: now + ttlMs, deleteAt: new Date(now + ttlMs) });
178
+ return true;
179
+ });
180
+ },
181
+ async forget(address) {
182
+ const sessions = (await sessionsCol().where("address", "==", address).get()).docs.filter((d) => d.data().scope === "play");
183
+ const requests = (await requestsCol().where("account", "==", address).get()).docs.filter((d) => d.data().scope === "play");
184
+ const once = (await onceCol().where("address", "==", address).get()).docs;
185
+ return deleteAll([...sessions, ...requests, ...once]);
186
+ },
187
+ async clean(now) {
188
+ const old = (await requestsCol().where("expiresAt", "<", now - 2 * 3_600_000).limit(BATCH).get()).docs.filter((d) => d.data().scope === "play");
189
+ const ended = (await sessionsCol().where("expiresAt", "<=", now).limit(BATCH).get()).docs.filter((d) => d.data().scope === "play");
190
+ const used = (await onceCol().where("until", "<=", now).limit(BATCH).get()).docs;
191
+ await deleteAll([...old, ...ended, ...used]);
192
+ },
193
+ };
194
+ }
@@ -0,0 +1,184 @@
1
+ // The conformance suite of the player sign-in's store: a game that writes its own store (another database) runs it, and so proves that its store
2
+ // keeps every rule the package's adapters keep. The package runs it on the memory store, D1 (on SQLite) and Firestore (a fake, and the emulator).
3
+ //
4
+ // import { playerSigninStoreConformance } from "@nano133/nanoterra/player-signin/conformance";
5
+ // for (const c of playerSigninStoreConformance(async () => ({ store: myStore(), dump: () => allMyRowsAsText() }))) it(c.name, c.run);
6
+ //
7
+ // Each case gets a NEW, empty store from `make`. The rules: a request is finished once and delivered once, and a delivery writes its session in the
8
+ // same step; the ways stay apart; a session lasts until its time; a once-only key counts once; "forget" leaves nothing of the player's.
9
+
10
+ import type { PlayerSigninStore, SessionRecord, SigninRequest, Way } from "./types.js";
11
+
12
+ export type PlayerSigninHarness = {
13
+ store: PlayerSigninStore;
14
+ /** Every row the store keeps (requests, sessions, once-only keys) as one text. `forget` must leave none that holds the player's address. */
15
+ dump(): Promise<string>;
16
+ };
17
+
18
+ export type PlayerSigninConformanceCase = { name: string; run: () => Promise<void> };
19
+
20
+ function check(ok: boolean, message: string): void {
21
+ if (!ok) throw new Error(message);
22
+ }
23
+
24
+ /** An address the suite can find in any text (a store does not check addresses: the handler does). */
25
+ const who = (n: string) => `nano_3${n}${"x".repeat(59 - n.length)}`;
26
+ const ANN = who("ann");
27
+ const BOB = who("bob");
28
+ const hex = (n: number, len = 64) => n.toString(16).padStart(len, "0");
29
+
30
+ let serial = 0;
31
+ /** A request as a wallet's start makes it: a fresh id each time. */
32
+ function request(at: number, extra: Partial<SigninRequest> = {}): { key: string; r: SigninRequest } {
33
+ serial += 1;
34
+ const id = hex(Date.now() * 1000 + serial, 32).slice(-32);
35
+ return { key: id, r: { id, starter: hex(serial + 7), status: "waiting", expiresAt: at + 5 * 60_000, nonce: hex(serial + 99), issuedAt: at, ...extra } };
36
+ }
37
+ const session = (address: string, at: number, n: number, via: SessionRecord["via"] = "wallet"): SessionRecord => ({ idHash: hex(1_000_000 + n + serial++), address, createdAt: at, expiresAt: at + 30 * 86_400_000, via });
38
+
39
+ export function playerSigninStoreConformance(make: () => Promise<PlayerSigninHarness>): PlayerSigninConformanceCase[] {
40
+ const cases: PlayerSigninConformanceCase[] = [];
41
+ const add = (name: string, run: (h: PlayerSigninHarness, now: number) => Promise<void>) => cases.push({ name, run: async () => run(await make(), Date.now()) });
42
+
43
+ add("a request reads back as it was made, by its key and by its browser id, and only for its own way", async ({ store }, now) => {
44
+ const { key, r } = request(now, { label: "game.test sign-in ABCD-EFGH" });
45
+ await store.requests("nautilus").create(key, r);
46
+ const back = await store.requests("nautilus").get(key);
47
+ check(back !== null && back.id === r.id && back.starter === r.starter && back.status === "waiting" && back.expiresAt === r.expiresAt && back.label === r.label && back.nonce === r.nonce && back.issuedAt === r.issuedAt && back.account === undefined, `read back: ${JSON.stringify(back)}`);
48
+ const found = await store.requests("nautilus").find(r.id);
49
+ check(found?.key === key && found.request.id === r.id, `find: ${JSON.stringify(found)}`);
50
+ for (const other of ["berry", "nanchat"] as Way[]) {
51
+ check((await store.requests(other).get(key)) === null, `${other} does not see a nautilus request`);
52
+ check((await store.requests(other).find(r.id)) === null, `${other} does not find a nautilus request`);
53
+ }
54
+ check((await store.requests("nautilus").get(hex(12345, 32))) === null, "an unknown key is null");
55
+ });
56
+
57
+ add("NanChat's request is kept under the hash of its nonce and found by the browser's id", async ({ store }, now) => {
58
+ const { r } = request(now);
59
+ const key = hex(424242);
60
+ await store.requests("nanchat").create(key, { ...r, id: "AbCdEfGhIjKlMnOpQrStUvWx" });
61
+ check((await store.requests("nanchat").find("AbCdEfGhIjKlMnOpQrStUvWx"))?.key === key, "found by the browser's id");
62
+ });
63
+
64
+ add("a second request with the same key is refused", async ({ store }, now) => {
65
+ const { key, r } = request(now);
66
+ await store.requests("berry").create(key, r);
67
+ let threw = false;
68
+ try {
69
+ await store.requests("berry").create(key, { ...r, starter: hex(1) });
70
+ } catch {
71
+ threw = true;
72
+ }
73
+ check(threw, "the second create throws");
74
+ check((await store.requests("berry").get(key))?.starter === r.starter, "the first request is unchanged");
75
+ });
76
+
77
+ add("finish signs a waiting request in once, with its account; a second finish, or one on an unknown key, is false", async ({ store }, now) => {
78
+ const { key, r } = request(now);
79
+ await store.requests("berry").create(key, r);
80
+ check(await store.requests("berry").finish(key, ANN), "the first finish");
81
+ check(!(await store.requests("berry").finish(key, BOB)), "a second finish is false");
82
+ const back = await store.requests("berry").get(key);
83
+ check(back?.status === "signedin" && back.account === ANN, `the account stays the first: ${JSON.stringify(back)}`);
84
+ check(!(await store.requests("berry").finish(hex(777, 32), ANN)), "an unknown key");
85
+ check(!(await store.requests("nautilus").finish(key, ANN)), "another way cannot finish it");
86
+ });
87
+
88
+ add("two finishes at the same moment: exactly one is true", async ({ store }, now) => {
89
+ const { key, r } = request(now);
90
+ await store.requests("berry").create(key, r);
91
+ const both = await Promise.all([store.requests("berry").finish(key, ANN), store.requests("berry").finish(key, BOB)]);
92
+ check(both.filter(Boolean).length === 1, `results: ${JSON.stringify(both)}`);
93
+ });
94
+
95
+ add("deliver: false while waiting; then once, with its session; a second delivery writes no session", async ({ store }, now) => {
96
+ const { key, r } = request(now);
97
+ await store.requests("berry").create(key, r);
98
+ const early = session(ANN, now, 1);
99
+ check(!(await store.deliver("berry", key, early)), "a waiting request is not delivered");
100
+ check((await store.session(early.idHash, now)) === null, "and no session was written");
101
+ await store.requests("berry").finish(key, ANN);
102
+ const s1 = session(ANN, now, 2);
103
+ check(await store.deliver("berry", key, s1), "the first delivery");
104
+ const read = await store.session(s1.idHash, now);
105
+ check(read?.address === ANN && read.via === "wallet" && read.expiresAt === s1.expiresAt && read.createdAt === s1.createdAt, `the session: ${JSON.stringify(read)}`);
106
+ const s2 = session(ANN, now, 3);
107
+ check(!(await store.deliver("berry", key, s2)), "a second delivery is false");
108
+ check((await store.session(s2.idHash, now)) === null, "and wrote no session");
109
+ check(!(await store.deliver("nautilus", key, session(ANN, now, 4))), "another way cannot deliver it");
110
+ check(!(await store.deliver("berry", hex(888, 32), session(ANN, now, 5))), "an unknown key");
111
+ });
112
+
113
+ add("two deliveries at the same moment: one is true, and one session is written", async ({ store, dump }, now) => {
114
+ const { key, r } = request(now);
115
+ await store.requests("nautilus").create(key, r);
116
+ await store.requests("nautilus").finish(key, ANN);
117
+ const a = session(ANN, now, 10);
118
+ const b = session(ANN, now, 11);
119
+ const both = await Promise.all([store.deliver("nautilus", key, a), store.deliver("nautilus", key, b)]);
120
+ check(both.filter(Boolean).length === 1, `results: ${JSON.stringify(both)}`);
121
+ const live = [await store.session(a.idHash, now), await store.session(b.idHash, now)].filter(Boolean);
122
+ check(live.length === 1, `sessions written: ${live.length} (${(await dump()).slice(0, 300)})`);
123
+ });
124
+
125
+ add("a session reads while it lasts, with its `via`, and not from its end; ending it removes it", async ({ store }, now) => {
126
+ const s = session(BOB, now, 20, "passkey");
127
+ await store.createSession(s);
128
+ const read = await store.session(s.idHash, now);
129
+ check(read?.address === BOB && read.via === "passkey" && read.idHash === s.idHash, `read: ${JSON.stringify(read)}`);
130
+ check((await store.session(s.idHash, s.expiresAt)) === null, "not at its end");
131
+ check((await store.session(s.idHash, s.expiresAt + 1)) === null, "not after it");
132
+ check((await store.session(hex(999), now)) === null, "an unknown id");
133
+ await store.endSession(s.idHash);
134
+ check((await store.session(s.idHash, now)) === null, "ended");
135
+ await store.endSession(s.idHash);
136
+ });
137
+
138
+ add("a once-only key counts once; another key counts; two at the same moment: one", async ({ store }, now) => {
139
+ const k = hex(now);
140
+ check(await store.useOnce(k, 600_000, ANN), "the first use");
141
+ check(!(await store.useOnce(k, 600_000, BOB)), "the second use");
142
+ check(await store.useOnce(hex(now + 1), 600_000, ANN), "another key");
143
+ const k2 = hex(now + 2);
144
+ const both = await Promise.all([store.useOnce(k2, 600_000, ANN), store.useOnce(k2, 600_000, ANN)]);
145
+ check(both.filter(Boolean).length === 1, `two at once: ${JSON.stringify(both)}`);
146
+ });
147
+
148
+ add("forget leaves nothing of the player's (sessions, signed requests, once-only keys) and every row of another player", async ({ store, dump }, now) => {
149
+ for (const [address, n] of [[ANN, 30], [BOB, 40]] as const) {
150
+ await store.createSession(session(address, now, n, "passkey"));
151
+ const { key, r } = request(now);
152
+ await store.requests("berry").create(key, r);
153
+ await store.requests("berry").finish(key, address);
154
+ await store.deliver("berry", key, session(address, now, n + 1));
155
+ await store.useOnce(hex(now + n), 600_000, address);
156
+ }
157
+ const before = await dump();
158
+ check(before.includes(ANN) && before.includes(BOB), "both players are in the store");
159
+ const gone = await store.forget(ANN);
160
+ check(gone >= 4, `rows that went: ${gone}`);
161
+ const after = await dump();
162
+ check(!after.includes(ANN), `the player is left in the store: ${after.slice(0, 400)}`);
163
+ check(after.split(BOB).length - 1 >= 4, "the other player's rows stay");
164
+ check((await store.forget(ANN)) === 0, "a second forget finds nothing");
165
+ });
166
+
167
+ add("clean deletes ended sessions and requests 2 hours after they ended, and keeps the rest", async ({ store }, now) => {
168
+ const ended = { ...session(ANN, now - 40 * 86_400_000, 50), expiresAt: now - 1 };
169
+ const live = session(ANN, now, 51);
170
+ await store.createSession(ended);
171
+ await store.createSession(live);
172
+ const old = request(now - 3 * 3_600_000);
173
+ const fresh = request(now);
174
+ await store.requests("berry").create(old.key, old.r);
175
+ await store.requests("berry").create(fresh.key, fresh.r);
176
+ await store.clean(now);
177
+ check((await store.session(live.idHash, now)) !== null, "the live session stays");
178
+ check((await store.session(ended.idHash, now - 2)) === null, "the ended session went");
179
+ check((await store.requests("berry").get(old.key)) === null, "the old request went");
180
+ check((await store.requests("berry").get(fresh.key)) !== null, "the fresh request stays");
181
+ });
182
+
183
+ return cases;
184
+ }