@nano133/nanoterra 0.10.0 → 0.11.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 (39) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +110 -7
  3. package/ai/SPEC.md +30 -2
  4. package/dist/admin/conformance.d.ts +7 -0
  5. package/dist/admin/conformance.js +17 -18
  6. package/dist/admin-signin/adapters/d1.d.ts +10 -0
  7. package/dist/admin-signin/adapters/d1.js +106 -0
  8. package/dist/admin-signin/adapters/firestore.d.ts +49 -0
  9. package/dist/admin-signin/adapters/firestore.js +179 -0
  10. package/dist/admin-signin/browser.d.ts +4 -0
  11. package/dist/admin-signin/browser.js +36 -0
  12. package/dist/admin-signin/conformance.d.ts +11 -0
  13. package/dist/admin-signin/conformance.js +190 -0
  14. package/dist/admin-signin/handler.d.ts +62 -0
  15. package/dist/admin-signin/handler.js +360 -0
  16. package/dist/admin-signin/index.d.ts +8 -0
  17. package/dist/admin-signin/index.js +15 -0
  18. package/dist/admin-signin/memory.d.ts +13 -0
  19. package/dist/admin-signin/memory.js +101 -0
  20. package/dist/admin-signin/panel/index.d.ts +3 -0
  21. package/dist/admin-signin/panel/index.js +5 -0
  22. package/dist/admin-signin/panel/view.d.ts +40 -0
  23. package/dist/admin-signin/panel/view.js +182 -0
  24. package/dist/admin-signin/types.d.ts +105 -0
  25. package/dist/admin-signin/types.js +42 -0
  26. package/package.json +9 -2
  27. package/src/admin/conformance.ts +23 -18
  28. package/src/admin-signin/adapters/d1.sql +45 -0
  29. package/src/admin-signin/adapters/d1.ts +117 -0
  30. package/src/admin-signin/adapters/firestore.ts +207 -0
  31. package/src/admin-signin/browser.ts +38 -0
  32. package/src/admin-signin/conformance.ts +212 -0
  33. package/src/admin-signin/handler.ts +418 -0
  34. package/src/admin-signin/index.ts +29 -0
  35. package/src/admin-signin/memory.ts +100 -0
  36. package/src/admin-signin/panel/index.ts +7 -0
  37. package/src/admin-signin/panel/view.ts +217 -0
  38. package/src/admin-signin/types.ts +95 -0
  39. package/src/player-signin/panel/style.css +7 -1
@@ -0,0 +1,217 @@
1
+ // The ADMIN's sign-in in the browser (/admin), with Berry Wallet or Nautilus (and NanChat only when the game turned it on). The game starter's
2
+ // src/client/ui/signin.ts, moved into the package: first the wallets as tiles (Berry Wallet first); then, for the chosen one, one key that opens it (a
3
+ // phone) or a QR code to scan with it (a computer). The page asks the game every 2 seconds until the wallet has signed. It makes the ADMIN login (its
4
+ // own cookie, on the fixed route "/api/admin-signin"), so the game and /admin can have different people signed in at once.
5
+ //
6
+ // Plain DOM, no framework, no package. The tiles show letters, not logos: no wallet's licence clearly allows its logo. Phone first: text 16 px, every
7
+ // key and tile 48 px or more each way. It uses the player sheet's stylesheet ("@nano133/nanoterra/admin-signin/style.css" is the same file).
8
+
9
+ import { ApiError, createApi } from "../../admin/panel/api.js";
10
+ import { h, shortAddress } from "../../admin/panel/dom.js";
11
+ import { icon } from "../../admin/panel/icons.js";
12
+ import { qrSvg } from "../../shop/panel/qr.js";
13
+ import { ADMIN_SIGNIN_BASE, type AdminWay } from "../types.js";
14
+
15
+ export type AdminSigninViewOptions = {
16
+ /** Where the sign-in's routes are. Default "/api/admin-signin" (ADMIN_SIGNIN_BASE). */
17
+ base?: string;
18
+ /**
19
+ * Offer NanChat too (the server's `nanchat: true`). Default false. NanChat's text cannot name the ADMIN ("Login to <host>"), so the owner cannot tell an
20
+ * admin sign-in from a game sign-in in it: it is off unless the game turns it on on the server and here.
21
+ */
22
+ nanchat?: boolean;
23
+ /** The person check (Turnstile): fills `box` and gives its token, before a start. No hook: no check. */
24
+ personCheck?: (box: HTMLElement) => Promise<string | null | undefined>;
25
+ /** Draws a QR code of `text` (a wallet's link), for a screen with a mouse. Default: the package's own QR code; a link too long for it is shown as a link. */
26
+ qr?: (text: string) => HTMLElement | SVGElement;
27
+ /** A touch screen (one key that opens the app) or not (a QR code). Default: `(pointer: coarse)`. */
28
+ touch?: boolean;
29
+ /** The `fetch` to use (default: the page's). */
30
+ fetch?: typeof fetch;
31
+ /** The owner signed in (the address that signed). */
32
+ onSignedIn?: (address: string) => void;
33
+ };
34
+
35
+ export type AdminSigninView = {
36
+ node: HTMLElement;
37
+ /** Ends the waiting (the gate closed). */
38
+ stop(): void;
39
+ /** Starts again at the tiles. */
40
+ reset(): void;
41
+ };
42
+
43
+ type Start = { way: AdminWay; id: string; link: string; walletLink?: string; code?: string; expiresAt: number };
44
+
45
+ /** The wallets, in every list's order: Berry Wallet first. */
46
+ const WALLETS: { way: AdminWay; name: string; mark: string }[] = [
47
+ { way: "berry", name: "Berry Wallet", mark: "B" },
48
+ { way: "nautilus", name: "Nautilus", mark: "N" },
49
+ { way: "nanchat", name: "NanChat", mark: "NC" },
50
+ ];
51
+ const nameOf = (way: AdminWay) => WALLETS.find((w) => w.way === way)!.name;
52
+
53
+ /** The admin's words: the starter's. */
54
+ export const ADMIN_SIGNIN_INTRO = "No password and no payment. This signs in to the ADMIN of this game: your wallet signs a short message that says so. If you did not start this yourself, do not sign.";
55
+ /** What NanChat's sign-in says, when it is on: its text cannot say "admin". */
56
+ export const ADMIN_NANCHAT_NOTE = "NanChat shows a plain sign-in to this game: its text cannot say ADMIN. Sign only a request that you started here, just now.";
57
+
58
+ export function adminSigninView(options: AdminSigninViewOptions = {}): AdminSigninView {
59
+ const base = options.base ?? ADMIN_SIGNIN_BASE;
60
+ const api = createApi(base, options.fetch ?? ((...a) => fetch(...a)));
61
+ const wallets = WALLETS.filter((w) => w.way !== "nanchat" || options.nanchat === true);
62
+ const touch = () => options.touch ?? (typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches);
63
+ let stopped = false;
64
+ let timer: ReturnType<typeof setTimeout> | undefined;
65
+ /** The request that is waiting. Back keeps it: the person may have approved it already. */
66
+ let current: Start | null = null;
67
+
68
+ const status = h("p", { class: "n133s-status", role: "status", "aria-live": "polite" });
69
+ const check = h("div", { class: "n133s-check" });
70
+ const area = h("div", { class: "n133s-area" });
71
+ const node = h("div", { class: "n133-signin n133s-view n133-admin-signin" }, h("p", { class: "n133s-lead" }, ADMIN_SIGNIN_INTRO), check, area, status);
72
+
73
+ const say = (text: string) => (status.textContent = text);
74
+ const key = (text: string, onclick: () => void, kind: "primary" | "plain" = "plain") => h("button", { class: `n133s-btn n133s-${kind}`, type: "button", onclick }, text);
75
+ const focusFirst = () => (area.querySelector<HTMLElement>("h3, button:not([disabled])") ?? area).focus?.({ preventScroll: true });
76
+
77
+ function stopWaiting() {
78
+ if (timer) clearTimeout(timer);
79
+ timer = undefined;
80
+ }
81
+
82
+ function showTiles() {
83
+ stopWaiting();
84
+ const tiles = wallets.map((w) =>
85
+ h("button", { class: "n133s-tile", type: "button", "data-way": w.way, onclick: () => void choose(w.way) }, h("span", { class: "n133s-mark", "aria-hidden": "true" }, w.mark), h("span", { class: "n133s-name" }, w.name)),
86
+ );
87
+ area.replaceChildren(h("p", { class: "n133s-or" }, "Choose your wallet"), h("div", { class: "n133s-tiles", "data-count": String(tiles.length) }, ...tiles));
88
+ }
89
+
90
+ async function choose(way: AdminWay) {
91
+ if (current?.way === way && Date.now() < current.expiresAt) return showWallet(current);
92
+ stopWaiting();
93
+ current = null;
94
+ for (const b of Array.from(area.querySelectorAll("button"))) b.disabled = true;
95
+ say("Starting…");
96
+ try {
97
+ const turnstile = options.personCheck ? await options.personCheck(check) : undefined;
98
+ const s = await api.post<Start>("/start", { way, ...(turnstile ? { turnstile } : {}) });
99
+ if (stopped) return;
100
+ current = s;
101
+ showWallet(s);
102
+ void poll(s);
103
+ } catch (e) {
104
+ showTiles();
105
+ say(e instanceof Error && e.message ? e.message : "Sign-in did not start. Try again.");
106
+ }
107
+ }
108
+
109
+ function showWallet(s: Start) {
110
+ const name = nameOf(s.way);
111
+ const back = h("button", { class: "n133s-back", type: "button", onclick: () => showTiles() }, icon("back", 18), h("span", {}, "Back"));
112
+ area.replaceChildren(back, h("h3", { class: "n133s-step", tabindex: "-1" }, name), ...walletSteps(s, name));
113
+ say(`Waiting for ${name}…`);
114
+ focusFirst();
115
+ }
116
+
117
+ /** A QR code of the link, or the link alone when the code cannot hold it (Nautilus's link is longer than the package's QR code holds). */
118
+ function qrOf(text: string, name: string): HTMLElement {
119
+ try {
120
+ const code = options.qr ? options.qr(text) : qrSvg(text, `QR code to sign in with ${name}`);
121
+ code.setAttribute("aria-label", `QR code to sign in with ${name}`);
122
+ return h("div", { class: "n133s-qr" }, code);
123
+ } catch {
124
+ return h("p", { class: "n133s-fine" }, `Open this page on your phone to sign in with ${name}, or `, h("a", { href: text }, `open ${name} on this computer`), ".");
125
+ }
126
+ }
127
+
128
+ /** What the person does with the wallet: on a phone, one key; on a computer, a QR code for the phone. */
129
+ function walletSteps(s: Start, name: string): Node[] {
130
+ const open = (text: string, href: string, newTab = false) => h("a", { class: "n133s-btn n133s-primary", href, target: newTab ? "_blank" : undefined, rel: newTab ? "noopener" : undefined }, text);
131
+ const only = h("p", { class: "n133s-fine" }, `Only approve a sign-in that you started yourself, on ${location.host}.`);
132
+ const comeBack = h("p", { class: "n133s-fine" }, `Approve the sign-in in ${s.way === "berry" ? "your wallet" : name}, then come back to this page.`);
133
+ if (s.way === "nautilus") {
134
+ const code = h("p", { class: "n133s-text" }, "Check that Nautilus shows the code ", h("strong", { class: "n133s-signcode" }, s.code ?? ""), ".");
135
+ return touch() ? [code, open("Open Nautilus", s.link), comeBack] : [qrOf(s.link, name), h("p", { class: "n133s-text" }, "Scan this with Nautilus on your phone, then approve the sign-in."), code, only];
136
+ }
137
+ if (s.way === "nanchat") {
138
+ const note = h("p", { class: "n133s-text n133s-fault" }, ADMIN_NANCHAT_NOTE);
139
+ const here = h("p", { class: "n133s-fine" }, "On this computer: ", h("a", { href: s.link, target: "_blank", rel: "noopener" }, "open NanChat"), ".");
140
+ return touch() ? [note, open("Open NanChat", s.link, true), comeBack, only] : [note, qrOf(s.link, name), h("p", { class: "n133s-text" }, "Scan this with your phone's camera, then approve the sign-in in NanChat."), only, here];
141
+ }
142
+ const other = h("a", { class: "n133s-btn n133s-plain", href: s.walletLink ?? s.link }, "Another wallet");
143
+ const here = h("p", { class: "n133s-fine" }, "On this computer: ", h("a", { href: s.walletLink ?? s.link }, "open a wallet"), ".");
144
+ return touch() ? [open("Open Berry Wallet", s.link), other, comeBack] : [qrOf(s.link, name), h("p", { class: "n133s-text" }, "Scan this with Berry Wallet on your phone, then approve the sign-in."), only, here];
145
+ }
146
+
147
+ /** The request ended without a sign-in: say why, and offer a new one. */
148
+ function again(s: Start, words: string) {
149
+ current = null;
150
+ area.replaceChildren(h("div", { class: "n133s-keys" }, key("Try again", () => void choose(s.way), "primary"), key("Choose another wallet", () => showTiles())));
151
+ say(words);
152
+ }
153
+
154
+ async function poll(s: Start) {
155
+ if (stopped || current !== s) return;
156
+ if (Date.now() > s.expiresAt + 5000) return again(s, "This sign-in expired.");
157
+ try {
158
+ const r = await api.post<{ status: string; address?: string }>("/check", { id: s.id, way: s.way });
159
+ if (stopped || current !== s) return;
160
+ if (r.status === "signedin" && r.address) {
161
+ current = null;
162
+ area.replaceChildren(h("p", { class: "n133s-done" }, icon("check", 22), h("span", {}, `Signed in as ${shortAddress(r.address)}`)));
163
+ say("");
164
+ options.onSignedIn?.(r.address);
165
+ return;
166
+ }
167
+ if (r.status === "elsewhere" || r.status === "used") return again(s, "This sign-in was used in another browser. Start again.");
168
+ if (r.status === "not_owner") return again(s, "That wallet is not this game's address. Choose the wallet that holds it.");
169
+ if (r.status === "expired") return again(s, "This sign-in expired.");
170
+ } catch (e) {
171
+ if (e instanceof ApiError && e.status === 429) say("Too many checks. Waiting a moment…");
172
+ }
173
+ timer = setTimeout(() => void poll(s), 2000);
174
+ }
175
+
176
+ showTiles();
177
+ return {
178
+ node,
179
+ stop() {
180
+ stopped = true;
181
+ stopWaiting();
182
+ },
183
+ reset() {
184
+ stopped = false;
185
+ current = null;
186
+ showTiles();
187
+ say("");
188
+ },
189
+ };
190
+ }
191
+
192
+ /**
193
+ * The admin's sign-in for `mountAdmin`'s `signIn(into, done)` hook: it draws the view into `into` and calls `done()` once the owner has signed in. A new
194
+ * call (the gate shows again) stops the view that was drawn before.
195
+ *
196
+ * mountAdmin(el, { looks, signIn: adminSignIn(), signOut: adminSignOut() });
197
+ */
198
+ export function adminSignIn(options: AdminSigninViewOptions = {}): (into: HTMLElement, done: () => void) => void {
199
+ let last: AdminSigninView | null = null;
200
+ return (into, done) => {
201
+ last?.stop();
202
+ const view = adminSigninView({
203
+ ...options,
204
+ onSignedIn(address) {
205
+ options.onSignedIn?.(address);
206
+ done();
207
+ },
208
+ });
209
+ last = view;
210
+ into.append(view.node);
211
+ };
212
+ }
213
+
214
+ /** `mountAdmin`'s `signOut`: ends the ADMIN login only (`POST {base}/signout`); the game's own login, another person's perhaps, stays. */
215
+ export function adminSignOut(options: Pick<AdminSigninViewOptions, "base" | "fetch"> = {}): () => Promise<unknown> {
216
+ return () => createApi(options.base ?? ADMIN_SIGNIN_BASE, options.fetch ?? ((...a) => fetch(...a))).post("/signout", {});
217
+ }
@@ -0,0 +1,95 @@
1
+ // The ADMIN's sign-in of a game: the fixed route, the times, the limits and the store contract. (The player's sign-in is another thing:
2
+ // "@nano133/nanoterra/player-signin".) No package and no DOM: the stores, the adapters and the browser panel read this file.
3
+ //
4
+ // The admin signs in with a wallet app only: Berry Wallet or Nautilus (and NanChat only when the game turns it on: its text cannot name the ADMIN). No
5
+ // passkey. What Berry Wallet and Nautilus sign names the ADMIN, so a link that a stranger sends to the owner does not look like any sign-in. Only the game's own address makes an admin login, and only from a request that was started
6
+ // on the admin's route; the guard (`adminAccess`) decides again on every call of /admin.
7
+
8
+ import type { AdminLogin } from "../admin/store.js";
9
+ import type { RequestStoreLike } from "../player-signin/types.js";
10
+
11
+ export type { RequestStoreLike, SigninRequest } from "../player-signin/types.js";
12
+
13
+ /** The admin's sign-in route, the same in every game: a page, an AI helper and the kit's panel find it here. */
14
+ export const ADMIN_SIGNIN_BASE = "/api/admin-signin";
15
+
16
+ /** The page the admin signs in to: Berry Wallet signs this page's address ("URI: https://example.com/admin", with NO query). */
17
+ export const ADMIN_PAGE = "/admin";
18
+
19
+ /**
20
+ * The wallet apps a store keeps admin requests for, in every list's order: Berry Wallet first. NanChat is OFF unless the game turns it on
21
+ * (`createAdminSignin({ nanchat: true })`): its text must start "Login to <host>" and cannot name the ADMIN, so the owner who is asked to sign sees a
22
+ * text that looks like any sign-in to the game. Berry Wallet and Nautilus sign a text that says "ADMIN".
23
+ */
24
+ export const ADMIN_WAYS = ["berry", "nautilus", "nanchat"] as const;
25
+ export type AdminWay = (typeof ADMIN_WAYS)[number];
26
+
27
+ /** What a NanChat start is told while NanChat is off (the default): the starter's words. */
28
+ export const NANCHAT_REFUSAL = "NanChat cannot open the admin yet. Use Berry Wallet or Nautilus.";
29
+
30
+ /** An admin sign-in REQUEST lives 2 minutes (a player's lives 5), and a signature is delivered for one more minute after it ends. It works once. */
31
+ export const ADMIN_REQUEST_MS = 2 * 60_000;
32
+ export const ADMIN_DELIVER_MS = 60_000;
33
+ /** How long a row of the admin's sign-in list is kept: 30 days. */
34
+ export const ADMIN_LOGIN_KEEP_MS = 30 * 24 * 60 * 60_000;
35
+ /** How long the starter cookie lives: a wallet's request must be answered within it. */
36
+ export const ADMIN_STARTER_MAX_AGE_S = 30 * 60;
37
+
38
+ /** The limits of the routes (calls per window). `signin` uses the game's `limit` hook; the rest count in this process's memory. */
39
+ export const ADMIN_SIGNIN_LIMITS = {
40
+ /** An admin sign-in start, per visitor (hook). The key is the player's (`signin|<visitor>`): one count for both, as the starter had. */
41
+ signin: { limit: 20, windowMs: 10 * 60_000 },
42
+ /** The browser's checks (every 2 s), per IP address (memory). */
43
+ poll: { limit: 90, windowMs: 60_000 },
44
+ /** Berry Wallet's GET and POST and Nautilus's answer, per IP address (memory): the wallet's own phone sends them. */
45
+ wallet: { limit: 30, windowMs: 60_000 },
46
+ /** NanChat's answers (when it is on) all come from its one relay server: the whole route (memory), the answers of the right shape (hook) and each nonce (hook). */
47
+ nanchatRoute: { limit: 120, windowMs: 60_000 },
48
+ nanchatAll: { limit: 600, windowMs: 10 * 60_000 },
49
+ nanchatNonce: { limit: 5, windowMs: 10 * 60_000 },
50
+ /** The biggest body the routes read. */
51
+ bodyMax: 8192,
52
+ } as const;
53
+
54
+ /** A token, a starter value: 32 random bytes as 64 hex characters. */
55
+ export const TOKEN_PATTERN = /^[0-9a-f]{64}$/;
56
+
57
+ /**
58
+ * An admin session as a store keeps it. `idHash` is the SHA-256 (hex) of "admin:" and the cookie's token (`adminKey`): never the token, and never the
59
+ * plain hash a player's session has, so the SERVER keeps the two scopes apart and not only the cookies' names. `via` is "wallet" for every session this
60
+ * sign-in makes; a store returns the word it holds.
61
+ */
62
+ export type AdminSessionRecord = { idHash: string; address: string; createdAt: number; expiresAt: number; via: string };
63
+
64
+ /** The admin session as the game reads it (`createAdminHandler`'s `session` hook). `via` is "unknown" for a stored word other than "wallet" and "nanoterra": the guard refuses it. */
65
+ export type AdminSigninSession = { address: string; createdAt: number; via: "wallet" | "nanoterra" | "unknown" };
66
+
67
+ /**
68
+ * The game's database for the admin's sign-in. An adapter reads and writes ONLY its three tables or collections (requests, sessions, the sign-in list),
69
+ * and only the ADMIN's rows of the first two (a game whose players sign in through the same tables keeps its rows apart: the `scope` column).
70
+ * Run `adminSigninStoreConformance` on a store you write yourself.
71
+ */
72
+ export interface AdminSigninStore {
73
+ /** The admin requests of one wallet app. */
74
+ requests(way: AdminWay): RequestStoreLike;
75
+ /**
76
+ * Delivers a signed admin request to the browser that started it, ONCE, and writes its session in the same step: true when this call delivered it,
77
+ * false (and no session written) when it was delivered before, is not signed, is not known or is not the admin's.
78
+ */
79
+ deliver(way: AdminWay, key: string, session: AdminSessionRecord): Promise<boolean>;
80
+ /** The admin session of a hash while it lasts (`expiresAt` > now), else null. */
81
+ session(idHash: string, now: number): Promise<AdminSessionRecord | null>;
82
+ /** Ends one admin session (this browser's sign-out). */
83
+ endSession(idHash: string): Promise<void>;
84
+ /**
85
+ * "Sign out everywhere": deletes EVERY admin session and no player's, and ends every admin request that was not delivered (it is marked delivered and
86
+ * its time is over, so a request signed a moment ago, or signed later, makes no login). Returns how many sessions went.
87
+ */
88
+ signOutEverywhere(): Promise<number>;
89
+ /** Writes one row of the sign-in list (the time, the country, a short browser name: nothing else) and deletes the rows older than ADMIN_LOGIN_KEEP_MS before it. */
90
+ recordLogin(login: AdminLogin): Promise<void>;
91
+ /** The last sign-ins, newest first, at most `limit`, with only `at`, `country` and `browser`. */
92
+ recentLogins(limit: number): Promise<AdminLogin[]>;
93
+ /** Deletes what nobody needs any more: admin requests 2 hours after they ended, admin sessions that ended, sign-in rows older than 30 days. */
94
+ clean(now: number): Promise<void>;
95
+ }
@@ -1,4 +1,5 @@
1
- /* The player's sign-in sheet (mountPlayerSignin in ./mount.ts) and its content (signInView in ./view.ts). Every rule is under .n133-signin, so nothing
1
+ /* The player's sign-in sheet (mountPlayerSignin in ./mount.ts) and its content (signInView in ./view.ts), and the admin's sign-in (adminSigninView in
2
+ ../../admin-signin/panel/view.ts: "@nano133/nanoterra/admin-signin/style.css" is this file). Every rule is under .n133-signin, so nothing
2
3
  leaks into the game's page.
3
4
  Phone first: text is 16 px, and every key, tile, link, close key and back key is 48 px or more each way. On a phone held upright the sheet comes from the bottom; on a wide or sideways screen it
4
5
  is a card in the middle. A scrim covers the game while it is open.
@@ -261,6 +262,11 @@
261
262
  gap: 10px;
262
263
  }
263
264
 
265
+ /* Two wallets (the admin's sign-in: Berry Wallet and Nautilus) fill the row in two halves. */
266
+ .n133-signin .n133s-tiles[data-count="2"] {
267
+ grid-template-columns: repeat(2, minmax(0, 1fr));
268
+ }
269
+
264
270
  .n133-signin .n133s-tile {
265
271
  position: relative;
266
272
  display: flex;