@nano133/nanoterra 0.10.1 → 0.12.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 (54) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +180 -10
  3. package/ai/SPEC.md +37 -2
  4. package/dist/admin/guard.d.ts +9 -1
  5. package/dist/admin/guard.js +12 -4
  6. package/dist/admin/panel/card.d.ts +5 -0
  7. package/dist/admin/panel/card.js +3 -0
  8. package/dist/admin/panel/icons.d.ts +9 -0
  9. package/dist/admin/panel/icons.js +1 -0
  10. package/dist/admin/panel/index.d.ts +1 -1
  11. package/dist/admin/panel/mount.d.ts +7 -0
  12. package/dist/admin/panel/mount.js +4 -1
  13. package/dist/admin-signin/adapters/d1.d.ts +12 -0
  14. package/dist/admin-signin/adapters/d1.js +161 -0
  15. package/dist/admin-signin/adapters/firestore.d.ts +52 -0
  16. package/dist/admin-signin/adapters/firestore.js +248 -0
  17. package/dist/admin-signin/browser.d.ts +4 -0
  18. package/dist/admin-signin/browser.js +36 -0
  19. package/dist/admin-signin/conformance.d.ts +18 -0
  20. package/dist/admin-signin/conformance.js +275 -0
  21. package/dist/admin-signin/handler.d.ts +69 -0
  22. package/dist/admin-signin/handler.js +488 -0
  23. package/dist/admin-signin/index.d.ts +8 -0
  24. package/dist/admin-signin/index.js +16 -0
  25. package/dist/admin-signin/memory.d.ts +17 -0
  26. package/dist/admin-signin/memory.js +147 -0
  27. package/dist/admin-signin/panel/index.d.ts +6 -0
  28. package/dist/admin-signin/panel/index.js +7 -0
  29. package/dist/admin-signin/panel/passkeys.d.ts +43 -0
  30. package/dist/admin-signin/panel/passkeys.js +202 -0
  31. package/dist/admin-signin/panel/view.d.ts +52 -0
  32. package/dist/admin-signin/panel/view.js +229 -0
  33. package/dist/admin-signin/types.d.ts +155 -0
  34. package/dist/admin-signin/types.js +59 -0
  35. package/package.json +9 -2
  36. package/src/admin/guard.ts +19 -5
  37. package/src/admin/panel/card.ts +5 -0
  38. package/src/admin/panel/icons.ts +1 -0
  39. package/src/admin/panel/index.ts +1 -1
  40. package/src/admin/panel/mount.ts +11 -1
  41. package/src/admin/panel/style.css +44 -0
  42. package/src/admin-signin/adapters/d1.sql +62 -0
  43. package/src/admin-signin/adapters/d1.ts +170 -0
  44. package/src/admin-signin/adapters/firestore.ts +274 -0
  45. package/src/admin-signin/browser.ts +38 -0
  46. package/src/admin-signin/conformance.ts +308 -0
  47. package/src/admin-signin/handler.ts +545 -0
  48. package/src/admin-signin/index.ts +34 -0
  49. package/src/admin-signin/memory.ts +141 -0
  50. package/src/admin-signin/panel/index.ts +11 -0
  51. package/src/admin-signin/panel/passkeys.ts +245 -0
  52. package/src/admin-signin/panel/view.ts +279 -0
  53. package/src/admin-signin/types.ts +146 -0
  54. package/src/player-signin/panel/style.css +8 -1
@@ -0,0 +1,488 @@
1
+ // The routes of the ADMIN's sign-in, on the Web `Request` and `Response` types (a Worker, Firebase Functions, Node). The game starter's admin sign-in
2
+ // (its src/worker/signin.ts), moved into the package with every check and every signed text as the starter has them; only the paths are new, and the same
3
+ // in every game:
4
+ //
5
+ // POST {base}/start the browser starts an admin request: { way, turnstile? } → { way, id, link, walletLink?, code?, expiresAt } and the starter cookie
6
+ // GET {base}/nano/:id Berry Wallet reads the request (no cookie, no Origin)
7
+ // POST {base}/nano/:id Berry Wallet posts its signature: 204 with no body when accepted, 401 and the words when refused
8
+ // POST {base}/nautilus?id= Nautilus posts its signature: always 200 (Nautilus shows only a 200's words)
9
+ // POST {base}/nanchat NanChat's relay server posts the signature (only with `nanchat: true`): always 200, a refusal starts "NOT signed in"
10
+ // POST {base}/check the browser asks every 2 seconds: { id, way } → { status: "waiting" | "expired" | "elsewhere" | "used" | "not_owner" | "signedin", address? }
11
+ // POST {base}/signout ends this browser's admin login only: { ok: true }
12
+ //
13
+ // With `passkeys: true` (since 0.12.0), the owner's linked passkeys (a passkey is only a key to /admin; the money stays in the owner's wallet):
14
+ //
15
+ // POST {base}/passkey/link { address, at, signature }: ONLY with a live WALLET admin session of the owner, and the passkey's own signature of
16
+ // "Link this passkey to the ADMIN of <host>: sign in as <address> at <ms>": both sides prove their key → { ok, passkeys }
17
+ // POST {base}/passkey/unlink { address }: only with a live wallet admin session of the owner; the passkey's admin sessions end too → { ok, removed, passkeys }
18
+ // POST {base}/passkeys the list, for any session the guard accepts → { passkeys, limit, via, canChange, you }
19
+ // POST {base}/passkey { address, at, signature, turnstile? }: the passkey's signature of "ADMIN of <host>: sign in as <address> at <ms>" (never
20
+ // the host alone, which a player's passkey signs), refused unless the passkey is linked to the owner → a NEW admin session
21
+ // { via: "passkey" } of one day and the admin cookie
22
+ //
23
+ // Each passkey signature counts once (the admin's own table) and within 5 minutes. A passkey session opens /admin only while its link to the CURRENT owner
24
+ // exists: `session(request)` reads the link on every request, so a removed link or a new owner address ends it at the next request.
25
+ //
26
+ // `base` is "/api/admin-signin" (ADMIN_SIGNIN_BASE). Berry Wallet and Nautilus sign a text that names the ADMIN: Berry signs the page `${origin}/admin`
27
+ // with NO query (Berry refused "/admin?from=US" with "Sign-in requires a public HTTPS website", device test 2026-10-27), Nautilus signs the label "ADMIN of
28
+ // <host> sign-in ABCD-EFGH from <country>" and shows "Sign in to the ADMIN of <host>. Started <time> UTC from <country>. If you did not start this, do not
29
+ // sign." NanChat is OFF by default and refused with the starter's words: its text must start "Login to <host>" and CANNOT name the ADMIN, so the owner
30
+ // who is asked to sign sees what looks like any sign-in to the game. A game may turn it on (`nanchat: true`); it then signs "Login to <host>" as a
31
+ // player's NanChat sign-in does, and the admin's own checks (the starter cookie, the owner, once) are the same. A request lives 2 minutes, is
32
+ // delivered for one more minute, and works once.
33
+ //
34
+ // Two logins, two cookies: the game's (`session`, the player sign-in's) and the admin's (`admin`; `__Host-admin` on https, HttpOnly, SameSite=Lax, one
35
+ // day), so the game and /admin can have different people signed in at once. The database keeps `adminKey(token)`, the SHA-256 of "admin:" and the token,
36
+ // and a player's session keeps the plain hash: a player's token put in the admin cookie opens nothing, and a starter value copied from the player's cookie
37
+ // finishes no admin request. Only the game's own address (`owner`) makes an admin login. DO NOT CHANGE the checks in this file: they are what makes the
38
+ // admin page the creator's.
39
+ import { answerNanchat, answerNanoSignin, answerNautilus, checkNanchat, checkSignatureSignin, checkNanoSignin, checkNautilus, nanchatNonce, nanchatReply, NANO_SIGNIN_ACCEPTED, nanoSigninRefusal, nautilusReply, readNanoSignin, SigninError, startNanchat, startNanoSignin, startNautilus, validAddress, WalletRefused, } from "@nano133/signin";
40
+ import { ADMIN_SESSION_MS, adminAccess } from "../admin/guard.js";
41
+ import { fail, json, memoryLimiter, readLimited, sameOrigin } from "../admin/http.js";
42
+ import { countryOf, shortBrowser } from "./browser.js";
43
+ import { ADMIN_DELIVER_MS, ADMIN_ONCE_MS, ADMIN_PAGE, ADMIN_PASSKEY_LIMIT, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, TOKEN_PATTERN, adminLinkDomain, adminPasskeyDomain, } from "./types.js";
44
+ /** The address that belongs to nobody (its key is all zeros): Nautilus names it while the game has no address of its own. */
45
+ export const EXAMPLE_ADDRESS = "nano_1111111111111111111111111111111111111111111111111111hifc8npp";
46
+ const hex = (b) => Array.from(b instanceof Uint8Array ? b : new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
47
+ const sha256Hex = async (text) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
48
+ const randomHex = (bytes) => hex(crypto.getRandomValues(new Uint8Array(bytes)));
49
+ /**
50
+ * What the database keeps of an admin session or of an admin request's starter: the hash of the value with a prefix. So the SERVER (not only the cookie's
51
+ * name) keeps the two scopes apart: a token made for the game (the player sign-in keeps its plain hash) does not open /admin even if it is put in the admin
52
+ * cookie, and a starter value copied from the game's cookie does not finish an admin request.
53
+ */
54
+ export const adminKey = (value) => sha256Hex(`admin:${value}`);
55
+ /** Only a space or a tab around a cookie's name or value is dropped (JS trim() also drops Unicode spaces, which would let another name pass for ours). */
56
+ const trimAscii = (s) => s.replace(/^[ \t]+|[ \t]+$/g, "");
57
+ function cookieValue(req, name) {
58
+ for (const part of (req.headers.get("Cookie") ?? "").split(";")) {
59
+ const i = part.indexOf("=");
60
+ if (i > 0 && trimAscii(part.slice(0, i)) === name) {
61
+ try {
62
+ return decodeURIComponent(trimAscii(part.slice(i + 1)));
63
+ }
64
+ catch {
65
+ // Not valid percent-coding: not ours.
66
+ }
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ const isHttps = (req) => new URL(req.url).protocol === "https:";
72
+ /** A cookie for this site only: on https it gets the __Host- prefix and Secure (the starter's exact form). */
73
+ function cookieHeader(req, name, value, maxAgeSec) {
74
+ const https = isHttps(req);
75
+ return `${https ? "__Host-" : ""}${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSec}; HttpOnly; SameSite=Lax${https ? "; Secure" : ""}`;
76
+ }
77
+ /** A cookie's value: on https only the `__Host-` name (a sibling subdomain can set the plain one; it cannot set a `__Host-` one). */
78
+ const readCookie = (req, name) => cookieValue(req, isHttps(req) ? `__Host-${name}` : name);
79
+ /** What the owner reads for a refused passkey signature. */
80
+ function passkeyWords(e) {
81
+ if (e.status === 409)
82
+ return "That passkey signature was used already. Try again.";
83
+ if (e.status === 401)
84
+ return "The passkey's signature does not match. Try again.";
85
+ if (/too old/.test(e.message))
86
+ return "That signature is too old. Check the clock of this device, then try again.";
87
+ return "That passkey signature could not be read. Try again.";
88
+ }
89
+ /** The limiters live at module level: a Worker makes the sign-in for each request, and a limiter made inside it would forget every call. */
90
+ const fallbackLimit = memoryLimiter();
91
+ const memory = memoryLimiter();
92
+ export function createAdminSignin(options) {
93
+ const base = options.base ?? ADMIN_SIGNIN_BASE;
94
+ if (!base.startsWith("/") || base.length < 2 || base.endsWith("/"))
95
+ throw new Error('a path must start with "/" and not end with "/", like "/api/admin-signin"');
96
+ const page = options.page ?? ADMIN_PAGE;
97
+ if (!/^\/[A-Za-z0-9._~\-/]*$/.test(page))
98
+ throw new Error('the admin page is a path with no query, like "/admin"');
99
+ const store = options.store;
100
+ const sessionName = options.cookies?.session ?? "admin";
101
+ const starterName = options.cookies?.starter ?? "starter-admin";
102
+ for (const n of [sessionName, starterName])
103
+ if (!/^[A-Za-z0-9_-]{1,40}$/.test(n))
104
+ throw new Error("a cookie's name is letters, digits, _ and - only");
105
+ if (sessionName === starterName)
106
+ throw new Error("the session cookie and the starter cookie need two names");
107
+ const owner = options.owner;
108
+ const now = options.now ?? (() => Date.now());
109
+ const limit = options.limit ?? fallbackLimit;
110
+ const siteAddress = owner && validAddress(owner) ? owner : EXAMPLE_ADDRESS;
111
+ const nanchatOn = options.nanchat === true;
112
+ const passkeysOn = options.passkeys === true;
113
+ const pk = store;
114
+ if (passkeysOn) {
115
+ for (const m of ["createSession", "linkPasskey", "unlinkPasskey", "passkeys", "linked", "useOnce"]) {
116
+ if (typeof store[m] !== "function")
117
+ throw new Error(`passkeys: true needs a store with ${m}() (the package's stores have it)`);
118
+ }
119
+ }
120
+ const report = (e) => {
121
+ try {
122
+ options.onError?.(e);
123
+ }
124
+ catch {
125
+ // nothing more can be done
126
+ }
127
+ };
128
+ const ipOf = (req) => req.headers.get("CF-Connecting-IP") ?? "anyone";
129
+ const visitorOf = async (req) => (options.visitor ? await options.visitor(req) : ipOf(req));
130
+ const person = async (token, req) => (options.personCheck ? options.personCheck(token, req) : true);
131
+ /**
132
+ * The sign-in options of each wallet app for this request's site: the domain and page come from the address the owner opened (or `domain`). `admin` is
133
+ * given for a START: the request's life is 2 minutes, and Nautilus's label and line name the admin and the place the request started. Berry Wallet's text
134
+ * names the admin through its page, for every call (each request this sign-in holds is an admin request), so the wallet's GET and POST get the same text.
135
+ */
136
+ function wallets(req, at, admin) {
137
+ const url = new URL(req.url);
138
+ const host = options.domain ?? url.host;
139
+ const origin = `${url.protocol}//${host}`;
140
+ const clock = { now: () => at };
141
+ const life = admin ? { ttlMs: ADMIN_REQUEST_MS } : {};
142
+ const started = new Date(at).toISOString().slice(11, 16);
143
+ const adminLine = `Sign in to the ADMIN of ${host}. Started ${started} UTC from ${admin?.country ?? "an unknown country"}. If you did not start this, do not sign.`;
144
+ return {
145
+ host,
146
+ berry: { domain: host, uri: `${origin}${page}`, store: store.requests("berry"), ...life, ...clock },
147
+ nautilus: {
148
+ site: host,
149
+ siteAddress,
150
+ store: store.requests("nautilus"),
151
+ ...(admin ? { title: `ADMIN of ${host}`, ...(admin.country ? { note: `from ${admin.country}` } : {}), message: adminLine } : {}),
152
+ ...life,
153
+ ...clock,
154
+ },
155
+ // NanChat's text is "Login to <host> nonce: <nonce>": it has no place for the admin's name.
156
+ nanchat: { host, store: store.requests("nanchat"), ...life, ...clock },
157
+ nanchatUrl: `${origin}${base}/nanchat`,
158
+ requestUrl: (id) => `${origin}${base}/nano/${id}`,
159
+ nautilusUrl: (id) => `${origin}${base}/nautilus?id=${id}`,
160
+ };
161
+ }
162
+ /** A JSON body of at most 8 KB, or null when it is not one readable object. */
163
+ async function body(req) {
164
+ const text = await readLimited(req, ADMIN_SIGNIN_LIMITS.bodyMax);
165
+ if (text === null)
166
+ return null;
167
+ if (!text)
168
+ return {};
169
+ try {
170
+ const v = JSON.parse(text);
171
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ }
177
+ /** The way a call names; Berry Wallet when it names none. Null for anything else. NanChat is a way even when it is off, so that it is refused with its own words. */
178
+ const wayOf = (v) => (v === undefined ? "berry" : (ADMIN_WAYS.find((w) => w === v) ?? null));
179
+ async function start(req, b, at) {
180
+ const way = wayOf(b.way);
181
+ if (!way)
182
+ return fail(400, "That wallet is not one of this game's.");
183
+ if (!(await limit(`signin|${await visitorOf(req)}`, ADMIN_SIGNIN_LIMITS.signin.limit, ADMIN_SIGNIN_LIMITS.signin.windowMs, at)))
184
+ return fail(429, "Too many sign-ins. Wait a few minutes.");
185
+ if (!(await person(b.turnstile, req)))
186
+ return fail(403, "The person check failed. Try again.");
187
+ const admin = { country: countryOf(req) };
188
+ // NanChat cannot name the admin in what it signs (its text must start "Login to <host>"): an admin request through it would look like any sign-in to
189
+ // the owner who is asked to sign. So it is refused unless the game turned it on.
190
+ if (way === "nanchat" && !nanchatOn)
191
+ return fail(400, NANCHAT_REFUSAL);
192
+ const starter = randomHex(32);
193
+ const hash = await adminKey(starter);
194
+ const w = wallets(req, at, admin);
195
+ let out;
196
+ if (way === "nautilus") {
197
+ const s = await startNautilus(w.nautilus, { starter: hash, answerUrl: w.nautilusUrl });
198
+ out = { way, id: s.id, link: s.link, code: s.code, expiresAt: s.expiresAt };
199
+ }
200
+ else if (way === "nanchat") {
201
+ const s = await startNanchat(w.nanchat, { starter: hash, answerUrl: w.nanchatUrl });
202
+ out = { way, id: s.id, link: s.link, expiresAt: s.expiresAt };
203
+ }
204
+ else {
205
+ // `label` keeps where the request started ("admin:US"), as the starter wrote it: a starter that reads these rows sees an admin request it knows.
206
+ const s = await startNanoSignin(w.berry, { starter: hash, requestUrl: w.requestUrl, label: admin.country ? `admin:${admin.country}` : "admin" });
207
+ out = { way, id: s.id, link: s.link, walletLink: s.walletLink, expiresAt: s.expiresAt };
208
+ }
209
+ return json(out, 200, { "Set-Cookie": cookieHeader(req, starterName, starter, ADMIN_STARTER_MAX_AGE_S) });
210
+ }
211
+ /**
212
+ * The browser's check of an admin request. When it is signed and this browser started it ("mine"), a NEW admin session is made, once per request, and
213
+ * its cookie is set.
214
+ */
215
+ async function check(req, b, at) {
216
+ const way = wayOf(b.way);
217
+ if (!way)
218
+ return fail(400, "That wallet is not one of this game's.");
219
+ if (typeof b.id !== "string")
220
+ return fail(400, "no request id");
221
+ const cookie = readCookie(req, starterName);
222
+ // The starter cookie is what this sign-in made: 32 random bytes as 64 hex characters. A value of any other shape (one with a prefix of the other scope's hashing, for example) is no starter.
223
+ const starter = cookie && TOKEN_PATTERN.test(cookie) ? await adminKey(cookie) : undefined;
224
+ // While NanChat is off the admin starts no NanChat request: there is none to deliver.
225
+ if (way === "nanchat" && !nanchatOn)
226
+ return json({ status: "expired" });
227
+ // An admin request is delivered for a minute after it ends.
228
+ const o = { store: store.requests(way), now: () => at, deliverMs: ADMIN_DELIVER_MS };
229
+ const r = way === "nautilus" ? await checkNautilus(o, b.id, starter) : way === "nanchat" ? await checkNanchat(o, b.id, starter) : await checkNanoSignin(o, b.id, starter);
230
+ if (r.status !== "signedin")
231
+ return json({ status: r.status });
232
+ if (!r.mine || !r.account)
233
+ return json({ status: "elsewhere" });
234
+ // An admin login is for the game's own address only. A wallet that is not it makes no admin login (and does not end the owner's, which is in a cookie
235
+ // of its own), and the request stays unused.
236
+ if (r.account !== owner)
237
+ return json({ status: "not_owner", address: r.account });
238
+ // Deliver once: a second check of the same request makes no second session. The delivery and the session are ONE step of the store, and the session is
239
+ // written only when the delivery changed the request. So "Sign out everywhere" cannot run between them: it either ends the request first (nothing is
240
+ // delivered, no session) or deletes the session after.
241
+ const token = randomHex(32);
242
+ const record = { idHash: await adminKey(token), address: r.account, createdAt: at, expiresAt: at + ADMIN_SESSION_MS, via: "wallet" };
243
+ if (!(await store.deliver(way, r.key ?? b.id, record)))
244
+ return json({ status: "used" });
245
+ // The admin's sign-in list: the time, the rough country and a short browser name of THIS browser (the one that started the request and now gets the login). Nothing else.
246
+ await store.recordLogin({ at, country: countryOf(req), browser: shortBrowser(req.headers.get("User-Agent")) });
247
+ return json({ status: "signedin", address: r.account }, 200, { "Set-Cookie": cookieHeader(req, sessionName, token, ADMIN_SESSION_MS / 1000) });
248
+ }
249
+ /** Berry Wallet's GET and POST. They come from the wallet app, so there is no cookie and no Origin to check. */
250
+ async function berry(req, id, at) {
251
+ const w = wallets(req, at);
252
+ if (req.method === "GET") {
253
+ const request = await readNanoSignin(w.berry, id, w.requestUrl);
254
+ return request ? json(request) : json(nanoSigninRefusal("This sign-in expired."), 404);
255
+ }
256
+ const b = await body(req);
257
+ if (!b)
258
+ return json(nanoSigninRefusal("This answer is not readable."), 401);
259
+ try {
260
+ await answerNanoSignin(w.berry, id, b, w.requestUrl);
261
+ // Berry Wallet shows its success screen only for a 204 with no body.
262
+ return new Response(null, { status: NANO_SIGNIN_ACCEPTED, headers: { "Cache-Control": "no-store" } });
263
+ }
264
+ catch (e) {
265
+ if (e instanceof WalletRefused)
266
+ return json(nanoSigninRefusal(e.message), 401);
267
+ throw e;
268
+ }
269
+ }
270
+ /** Nautilus's answer. It comes from the app: no cookie, no Origin. Nautilus shows the words only with HTTP 200. */
271
+ async function nautilus(req, at) {
272
+ const w = wallets(req, at);
273
+ const b = await body(req);
274
+ if (!b)
275
+ return json(nautilusReply(w.host, "That answer could not be read."));
276
+ try {
277
+ await answerNautilus(w.nautilus, new URL(req.url).searchParams.get("id") ?? "", b);
278
+ return json(nautilusReply(w.host));
279
+ }
280
+ catch (e) {
281
+ if (e instanceof WalletRefused)
282
+ return json(nautilusReply(w.host, e.message));
283
+ throw e;
284
+ }
285
+ }
286
+ /** NanChat's answer (only while it is on): its relay server posts every one, so the limits are totals and per nonce, never per visitor. Always 200: NanChat shows the words. */
287
+ async function nanchat(req, at) {
288
+ const w = wallets(req, at);
289
+ const refuse = (words) => json(nanchatReply(w.host, words));
290
+ if (!memory(`${base}|nanchat`, ADMIN_SIGNIN_LIMITS.nanchatRoute.limit, ADMIN_SIGNIN_LIMITS.nanchatRoute.windowMs, at))
291
+ return refuse("too many sign-ins at once. Wait a minute.");
292
+ const b = await body(req);
293
+ if (!b)
294
+ return refuse("that answer could not be read.");
295
+ const nonce = nanchatNonce(w.host, b.message);
296
+ if (nonce && typeof b.account === "string" && typeof b.signature === "string" && /^[0-9A-Fa-f]{128}$/.test(b.signature)) {
297
+ if (!(await limit("admin-nanchat|all", ADMIN_SIGNIN_LIMITS.nanchatAll.limit, ADMIN_SIGNIN_LIMITS.nanchatAll.windowMs, at)))
298
+ return refuse("too many sign-ins at once. Wait a few minutes.");
299
+ if (!(await limit(`admin-nanchat|${nonce}`, ADMIN_SIGNIN_LIMITS.nanchatNonce.limit, ADMIN_SIGNIN_LIMITS.nanchatNonce.windowMs, at)))
300
+ return refuse(`too many tries for this sign-in. Start again on ${w.host}.`);
301
+ }
302
+ try {
303
+ await answerNanchat(w.nanchat, b);
304
+ return json(nanchatReply(w.host));
305
+ }
306
+ catch (e) {
307
+ if (e instanceof WalletRefused)
308
+ return refuse(e.message);
309
+ throw e;
310
+ }
311
+ }
312
+ async function sessionOf(req, at = now()) {
313
+ const token = readCookie(req, sessionName);
314
+ if (!token || !TOKEN_PATTERN.test(token))
315
+ return null;
316
+ // The scope is in the store's row (the adapter reads only admin rows) as well as in the hash: the two scopes stay apart in two ways.
317
+ const s = await store.session(await adminKey(token), at);
318
+ if (!s)
319
+ return null;
320
+ if (s.via === "passkey") {
321
+ // A passkey's login counts only while its link to the CURRENT owner exists: read now, on every request. A removed link, a new owner address, or the
322
+ // passkeys turned off: no session at all (the page asks for a sign-in). `linkedTo` is set here only, and only after this check.
323
+ if (!passkeysOn || typeof owner !== "string" || !validAddress(owner))
324
+ return null;
325
+ return (await pk.linked(owner, s.address)) ? { address: s.address, createdAt: s.createdAt, via: "passkey", linkedTo: owner } : null;
326
+ }
327
+ // Only the words a login can carry are read; any other is "unknown", never a wallet login (a fail-open map would turn a stray value into a login that opens /admin).
328
+ return { address: s.address, createdAt: s.createdAt, via: s.via === "wallet" || s.via === "nanoterra" ? s.via : "unknown" };
329
+ }
330
+ // ---- the owner's passkeys ----
331
+ /** The host every passkey text names: `domain`, or this request's host. */
332
+ const hostOf = (req) => options.domain ?? new URL(req.url).host;
333
+ /** The session the guard accepts now, or the refusal to send. `wallet`: only a wallet session of the owner (a link and a removal). */
334
+ async function ownerSession(req, at, wallet) {
335
+ const session = await sessionOf(req, at);
336
+ const access = adminAccess({ owner, session, now: at });
337
+ if (!access.ok)
338
+ return { ok: false, res: fail(access.status, access.error, access.reason ? { reason: access.reason } : {}) };
339
+ if (wallet && session.via !== "wallet")
340
+ return { ok: false, res: fail(403, "Only a wallet sign-in can add or remove a passkey. Sign in with your wallet.", { reason: "wallet_only" }) };
341
+ return { ok: true, session: session };
342
+ }
343
+ /** A passkey's signature of `domain`'s text, checked once: its address, or the refusal to send. */
344
+ async function passkeySignature(b, domain, label, at) {
345
+ try {
346
+ const address = await checkSignatureSignin({ domain, useOnce: (k, ttl) => pk.useOnce(k, Math.max(ttl, ADMIN_ONCE_MS)), now: () => at, onceLabel: label }, { address: b.address, at: Number(b.at), signature: b.signature });
347
+ return { ok: true, address };
348
+ }
349
+ catch (e) {
350
+ if (e instanceof SigninError)
351
+ return { ok: false, res: fail(e.status, passkeyWords(e)) };
352
+ throw e;
353
+ }
354
+ }
355
+ async function passkeyList(session) {
356
+ return { passkeys: await pk.passkeys(owner), limit: ADMIN_PASSKEY_LIMIT, via: session.via, canChange: session.via === "wallet", you: session.address };
357
+ }
358
+ async function link(req, b, at) {
359
+ const o = await ownerSession(req, at, true);
360
+ if (!o.ok)
361
+ return o.res;
362
+ if (!(await limit(`signin|${await visitorOf(req)}`, ADMIN_SIGNIN_LIMITS.signin.limit, ADMIN_SIGNIN_LIMITS.signin.windowMs, at)))
363
+ return fail(429, "Too many tries. Wait a few minutes.");
364
+ const sig = await passkeySignature(b, adminLinkDomain(hostOf(req)), "nanoterra admin passkey link v1", at);
365
+ if (!sig.ok)
366
+ return sig.res;
367
+ const r = await pk.linkPasskey(owner, sig.address, at);
368
+ if (r === "full")
369
+ return fail(409, `You have ${ADMIN_PASSKEY_LIMIT} passkeys. Remove one first.`, { reason: "full" });
370
+ if (r === "exists")
371
+ return fail(409, "This passkey is linked already.", { reason: "exists" });
372
+ return json({ ok: true, address: sig.address, ...(await passkeyList(o.session)) });
373
+ }
374
+ async function unlink(req, b, at) {
375
+ const o = await ownerSession(req, at, true);
376
+ if (!o.ok)
377
+ return o.res;
378
+ if (typeof b.address !== "string" || !validAddress(b.address))
379
+ return fail(400, "That is not a passkey's address.");
380
+ const removed = await pk.unlinkPasskey(owner, b.address);
381
+ return json({ ok: true, removed, ...(await passkeyList(o.session)) });
382
+ }
383
+ async function list(req, at) {
384
+ const o = await ownerSession(req, at, false);
385
+ if (!o.ok)
386
+ return o.res;
387
+ return json(await passkeyList(o.session));
388
+ }
389
+ async function passkeySignin(req, b, at) {
390
+ if (!(await limit(`signin|${await visitorOf(req)}`, ADMIN_SIGNIN_LIMITS.signin.limit, ADMIN_SIGNIN_LIMITS.signin.windowMs, at)))
391
+ return fail(429, "Too many sign-ins. Wait a few minutes.");
392
+ if (!(await person(b.turnstile, req)))
393
+ return fail(403, "The person check failed. Try again.");
394
+ if (typeof owner !== "string" || !validAddress(owner))
395
+ return fail(403, "Set the game's own Nano address first. Only that address can open this page.", { reason: "no_address" });
396
+ const sig = await passkeySignature(b, adminPasskeyDomain(hostOf(req)), "nanoterra admin passkey signin v1", at);
397
+ if (!sig.ok)
398
+ return sig.res;
399
+ // The signature is checked first, so a stranger learns nothing of which passkeys are linked.
400
+ if (!(await pk.linked(owner, sig.address)))
401
+ return fail(403, "This passkey is not linked to the game's address. Sign in with your wallet, then add this passkey in Settings.", { reason: "not_linked" });
402
+ const token = randomHex(32);
403
+ await pk.createSession({ idHash: await adminKey(token), address: sig.address, createdAt: at, expiresAt: at + ADMIN_SESSION_MS, via: "passkey" });
404
+ await store.recordLogin({ at, country: countryOf(req), browser: shortBrowser(req.headers.get("User-Agent")) });
405
+ return json({ status: "signedin", address: sig.address, linkedTo: owner }, 200, { "Set-Cookie": cookieHeader(req, sessionName, token, ADMIN_SESSION_MS / 1000) });
406
+ }
407
+ async function signOut(req) {
408
+ const token = readCookie(req, sessionName);
409
+ if (token)
410
+ await store.endSession(await adminKey(token));
411
+ return cookieHeader(req, sessionName, "", 0);
412
+ }
413
+ async function handle(req) {
414
+ const url = new URL(req.url);
415
+ const path = url.pathname;
416
+ const berryId = path.startsWith(`${base}/nano/`) ? /^[0-9a-f]{32}$/.exec(path.slice(base.length + 6))?.[0] : undefined;
417
+ const passkeyPaths = [`${base}/passkey`, `${base}/passkey/link`, `${base}/passkey/unlink`, `${base}/passkeys`];
418
+ const mine = berryId !== undefined || [`${base}/start`, `${base}/check`, `${base}/signout`, `${base}/nautilus`].includes(path) || (nanchatOn && path === `${base}/nanchat`) || (passkeysOn && passkeyPaths.includes(path));
419
+ if (!mine)
420
+ return null;
421
+ try {
422
+ if (options.domain && url.host !== options.domain)
423
+ return fail(403, `This sign-in belongs to ${options.domain}.`);
424
+ const at = now();
425
+ const ip = ipOf(req);
426
+ // The wallet apps' routes: no cookie and no Origin (an app posts them, not a browser page).
427
+ if (berryId !== undefined) {
428
+ if (req.method !== "GET" && req.method !== "POST")
429
+ return fail(405, "Not allowed.", {}, { Allow: "GET, POST" });
430
+ if (!memory(`${base}|wallet|${ip}`, ADMIN_SIGNIN_LIMITS.wallet.limit, ADMIN_SIGNIN_LIMITS.wallet.windowMs, at))
431
+ return fail(429, "Too many requests.");
432
+ return await berry(req, berryId, at);
433
+ }
434
+ if (path === `${base}/nautilus`) {
435
+ if (req.method !== "POST")
436
+ return fail(405, "Not allowed.", {}, { Allow: "POST" });
437
+ // Nautilus shows the words of a refusal only with HTTP 200.
438
+ if (!memory(`${base}|wallet|${ip}`, ADMIN_SIGNIN_LIMITS.wallet.limit, ADMIN_SIGNIN_LIMITS.wallet.windowMs, at))
439
+ return json(nautilusReply(wallets(req, at).host, "Too many requests. Wait a minute."));
440
+ return await nautilus(req, at);
441
+ }
442
+ if (path === `${base}/nanchat`) {
443
+ if (req.method !== "POST")
444
+ return fail(405, "Not allowed.", {}, { Allow: "POST" });
445
+ return await nanchat(req, at);
446
+ }
447
+ // The browser's own calls: a POST from the game's own page.
448
+ if (req.method !== "POST")
449
+ return fail(405, "Not allowed.", {}, { Allow: "POST" });
450
+ if (path === `${base}/check` && !memory(`${base}|poll|${ip}`, ADMIN_SIGNIN_LIMITS.poll.limit, ADMIN_SIGNIN_LIMITS.poll.windowMs, at))
451
+ return fail(429, "Too many requests. Wait a minute.");
452
+ if (passkeyPaths.includes(path) && path !== `${base}/passkey` && !memory(`${base}|passkeys|${ip}`, ADMIN_SIGNIN_LIMITS.passkeys.limit, ADMIN_SIGNIN_LIMITS.passkeys.windowMs, at))
453
+ return fail(429, "Too many requests. Wait a minute.");
454
+ if (!sameOrigin(req))
455
+ return fail(403, "This call must come from the game's own page.");
456
+ // A sign-out reads no body.
457
+ if (path === `${base}/signout`)
458
+ return json({ ok: true }, 200, { "Set-Cookie": await signOut(req) });
459
+ const b = await body(req);
460
+ if (!b)
461
+ return fail(400, "That request is not readable.");
462
+ if (path === `${base}/check`)
463
+ return await check(req, b, at);
464
+ if (path === `${base}/passkey`)
465
+ return await passkeySignin(req, b, at);
466
+ if (path === `${base}/passkey/link`)
467
+ return await link(req, b, at);
468
+ if (path === `${base}/passkey/unlink`)
469
+ return await unlink(req, b, at);
470
+ if (path === `${base}/passkeys`)
471
+ return await list(req, at);
472
+ return await start(req, b, at);
473
+ }
474
+ catch (e) {
475
+ report(e);
476
+ return fail(500, "Something went wrong. Try again.");
477
+ }
478
+ }
479
+ return {
480
+ base,
481
+ handle,
482
+ session: sessionOf,
483
+ signOut,
484
+ signOutEverywhere: () => store.signOutEverywhere(),
485
+ recentLogins: (n) => store.recentLogins(n),
486
+ clean: (at = now()) => store.clean(at),
487
+ };
488
+ }
@@ -0,0 +1,8 @@
1
+ export { EXAMPLE_ADDRESS, adminKey, createAdminSignin } from "./handler.js";
2
+ export type { AdminSignin, AdminSigninOptions } from "./handler.js";
3
+ export { createMemoryAdminSignin } from "./memory.js";
4
+ export type { MemoryAdminSignin } from "./memory.js";
5
+ export { countryOf, shortBrowser } from "./browser.js";
6
+ export { ADMIN_DELIVER_MS, ADMIN_LOGIN_KEEP_MS, ADMIN_ONCE_MS, ADMIN_PAGE, ADMIN_PASSKEY_LIMIT, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, adminLinkDomain, adminPasskeyDomain, } from "./types.js";
7
+ export type { AdminLinkResult, AdminPasskey, AdminSessionRecord, AdminSigninSession, AdminSigninStore, AdminWay, RequestStoreLike, SigninRequest } from "./types.js";
8
+ export { ADMIN_SESSION_MS } from "../admin/guard.js";
@@ -0,0 +1,16 @@
1
+ // "@nano133/nanoterra/admin-signin": the ADMIN's sign-in of a game (/admin), on ONE fixed route, "/api/admin-signin", in every game. Berry Wallet or
2
+ // Nautilus signs a text that names the ADMIN; NanChat is off unless the game turns it on (its text cannot name the admin); the owner's linked passkeys
3
+ // only with `passkeys: true` (since 0.12.0; a wallet session of the owner links them, each with its own signature). The game starter's
4
+ // admin sign-in, moved into the package with every check and every signed text unchanged. The checks are @nano133/signin's (an optional peer: install it
5
+ // with this package).
6
+ //
7
+ // createAdminSignin the routes (start, the wallets' answers, check, sign-out), `session(request)` for `createAdminHandler`, `signOutEverywhere`,
8
+ // `recentLogins` and `clean`
9
+ // createMemoryAdminSignin a store in memory, for tests
10
+ // (the adapters are "/admin-signin/d1" (on the starter's own tables; a new game adds "/admin-signin/d1.sql") and "/admin-signin/firestore", the store's
11
+ // conformance suite "/admin-signin/conformance", the browser panel "/admin-signin/panel" and its stylesheet "/admin-signin/style.css")
12
+ export { EXAMPLE_ADDRESS, adminKey, createAdminSignin } from "./handler.js";
13
+ export { createMemoryAdminSignin } from "./memory.js";
14
+ export { countryOf, shortBrowser } from "./browser.js";
15
+ export { ADMIN_DELIVER_MS, ADMIN_LOGIN_KEEP_MS, ADMIN_ONCE_MS, ADMIN_PAGE, ADMIN_PASSKEY_LIMIT, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, adminLinkDomain, adminPasskeyDomain, } from "./types.js";
16
+ export { ADMIN_SESSION_MS } from "../admin/guard.js";
@@ -0,0 +1,17 @@
1
+ import type { AdminLogin } from "../admin/store.js";
2
+ import { type AdminPasskey, type AdminSessionRecord, type AdminSigninStore, type AdminWay, type SigninRequest } from "./types.js";
3
+ type RequestRow = SigninRequest & {
4
+ way: AdminWay;
5
+ delivered: boolean;
6
+ };
7
+ export type MemoryAdminSignin = Required<AdminSigninStore> & {
8
+ readonly requestRows: Map<string, RequestRow>;
9
+ readonly sessionRows: Map<string, AdminSessionRecord>;
10
+ readonly loginRows: AdminLogin[];
11
+ /** The owner's passkeys: owner → the links, oldest first. */
12
+ readonly passkeyRows: Map<string, AdminPasskey[]>;
13
+ /** The used passkey signatures: key → until (ms). */
14
+ readonly onceRows: Map<string, number>;
15
+ };
16
+ export declare function createMemoryAdminSignin(): MemoryAdminSignin;
17
+ export {};