@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.
- package/CHANGELOG.md +30 -0
- package/README.md +110 -7
- package/ai/SPEC.md +30 -2
- package/dist/admin/conformance.d.ts +7 -0
- package/dist/admin/conformance.js +17 -18
- package/dist/admin-signin/adapters/d1.d.ts +10 -0
- package/dist/admin-signin/adapters/d1.js +106 -0
- package/dist/admin-signin/adapters/firestore.d.ts +49 -0
- package/dist/admin-signin/adapters/firestore.js +179 -0
- package/dist/admin-signin/browser.d.ts +4 -0
- package/dist/admin-signin/browser.js +36 -0
- package/dist/admin-signin/conformance.d.ts +11 -0
- package/dist/admin-signin/conformance.js +190 -0
- package/dist/admin-signin/handler.d.ts +62 -0
- package/dist/admin-signin/handler.js +360 -0
- package/dist/admin-signin/index.d.ts +8 -0
- package/dist/admin-signin/index.js +15 -0
- package/dist/admin-signin/memory.d.ts +13 -0
- package/dist/admin-signin/memory.js +101 -0
- package/dist/admin-signin/panel/index.d.ts +3 -0
- package/dist/admin-signin/panel/index.js +5 -0
- package/dist/admin-signin/panel/view.d.ts +40 -0
- package/dist/admin-signin/panel/view.js +182 -0
- package/dist/admin-signin/types.d.ts +105 -0
- package/dist/admin-signin/types.js +42 -0
- package/package.json +9 -2
- package/src/admin/conformance.ts +23 -18
- package/src/admin-signin/adapters/d1.sql +45 -0
- package/src/admin-signin/adapters/d1.ts +117 -0
- package/src/admin-signin/adapters/firestore.ts +207 -0
- package/src/admin-signin/browser.ts +38 -0
- package/src/admin-signin/conformance.ts +212 -0
- package/src/admin-signin/handler.ts +418 -0
- package/src/admin-signin/index.ts +29 -0
- package/src/admin-signin/memory.ts +100 -0
- package/src/admin-signin/panel/index.ts +7 -0
- package/src/admin-signin/panel/view.ts +217 -0
- package/src/admin-signin/types.ts +95 -0
- package/src/player-signin/panel/style.css +7 -1
|
@@ -0,0 +1,360 @@
|
|
|
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
|
+
// `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`
|
|
14
|
+
// 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
|
|
15
|
+
// <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
|
|
16
|
+
// 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
|
|
17
|
+
// 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
|
|
18
|
+
// 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
|
|
19
|
+
// delivered for one more minute, and works once.
|
|
20
|
+
//
|
|
21
|
+
// 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
|
|
22
|
+
// 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,
|
|
23
|
+
// 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
|
|
24
|
+
// 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
|
|
25
|
+
// admin page the creator's.
|
|
26
|
+
import { answerNanchat, answerNanoSignin, answerNautilus, checkNanchat, checkNanoSignin, checkNautilus, nanchatNonce, nanchatReply, NANO_SIGNIN_ACCEPTED, nanoSigninRefusal, nautilusReply, readNanoSignin, startNanchat, startNanoSignin, startNautilus, validAddress, WalletRefused, } from "@nano133/signin";
|
|
27
|
+
import { ADMIN_SESSION_MS } from "../admin/guard.js";
|
|
28
|
+
import { fail, json, memoryLimiter, readLimited, sameOrigin } from "../admin/http.js";
|
|
29
|
+
import { countryOf, shortBrowser } from "./browser.js";
|
|
30
|
+
import { ADMIN_DELIVER_MS, ADMIN_PAGE, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, TOKEN_PATTERN, } from "./types.js";
|
|
31
|
+
/** The address that belongs to nobody (its key is all zeros): Nautilus names it while the game has no address of its own. */
|
|
32
|
+
export const EXAMPLE_ADDRESS = "nano_1111111111111111111111111111111111111111111111111111hifc8npp";
|
|
33
|
+
const hex = (b) => Array.from(b instanceof Uint8Array ? b : new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
34
|
+
const sha256Hex = async (text) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
35
|
+
const randomHex = (bytes) => hex(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
36
|
+
/**
|
|
37
|
+
* 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
|
|
38
|
+
* 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
|
|
39
|
+
* cookie, and a starter value copied from the game's cookie does not finish an admin request.
|
|
40
|
+
*/
|
|
41
|
+
export const adminKey = (value) => sha256Hex(`admin:${value}`);
|
|
42
|
+
/** 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). */
|
|
43
|
+
const trimAscii = (s) => s.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
44
|
+
function cookieValue(req, name) {
|
|
45
|
+
for (const part of (req.headers.get("Cookie") ?? "").split(";")) {
|
|
46
|
+
const i = part.indexOf("=");
|
|
47
|
+
if (i > 0 && trimAscii(part.slice(0, i)) === name) {
|
|
48
|
+
try {
|
|
49
|
+
return decodeURIComponent(trimAscii(part.slice(i + 1)));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Not valid percent-coding: not ours.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
const isHttps = (req) => new URL(req.url).protocol === "https:";
|
|
59
|
+
/** A cookie for this site only: on https it gets the __Host- prefix and Secure (the starter's exact form). */
|
|
60
|
+
function cookieHeader(req, name, value, maxAgeSec) {
|
|
61
|
+
const https = isHttps(req);
|
|
62
|
+
return `${https ? "__Host-" : ""}${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSec}; HttpOnly; SameSite=Lax${https ? "; Secure" : ""}`;
|
|
63
|
+
}
|
|
64
|
+
/** A cookie's value: on https only the `__Host-` name (a sibling subdomain can set the plain one; it cannot set a `__Host-` one). */
|
|
65
|
+
const readCookie = (req, name) => cookieValue(req, isHttps(req) ? `__Host-${name}` : name);
|
|
66
|
+
/** 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. */
|
|
67
|
+
const fallbackLimit = memoryLimiter();
|
|
68
|
+
const memory = memoryLimiter();
|
|
69
|
+
export function createAdminSignin(options) {
|
|
70
|
+
const base = options.base ?? ADMIN_SIGNIN_BASE;
|
|
71
|
+
if (!base.startsWith("/") || base.length < 2 || base.endsWith("/"))
|
|
72
|
+
throw new Error('a path must start with "/" and not end with "/", like "/api/admin-signin"');
|
|
73
|
+
const page = options.page ?? ADMIN_PAGE;
|
|
74
|
+
if (!/^\/[A-Za-z0-9._~\-/]*$/.test(page))
|
|
75
|
+
throw new Error('the admin page is a path with no query, like "/admin"');
|
|
76
|
+
const store = options.store;
|
|
77
|
+
const sessionName = options.cookies?.session ?? "admin";
|
|
78
|
+
const starterName = options.cookies?.starter ?? "starter-admin";
|
|
79
|
+
for (const n of [sessionName, starterName])
|
|
80
|
+
if (!/^[A-Za-z0-9_-]{1,40}$/.test(n))
|
|
81
|
+
throw new Error("a cookie's name is letters, digits, _ and - only");
|
|
82
|
+
if (sessionName === starterName)
|
|
83
|
+
throw new Error("the session cookie and the starter cookie need two names");
|
|
84
|
+
const owner = options.owner;
|
|
85
|
+
const now = options.now ?? (() => Date.now());
|
|
86
|
+
const limit = options.limit ?? fallbackLimit;
|
|
87
|
+
const siteAddress = owner && validAddress(owner) ? owner : EXAMPLE_ADDRESS;
|
|
88
|
+
const nanchatOn = options.nanchat === true;
|
|
89
|
+
const report = (e) => {
|
|
90
|
+
try {
|
|
91
|
+
options.onError?.(e);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// nothing more can be done
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const ipOf = (req) => req.headers.get("CF-Connecting-IP") ?? "anyone";
|
|
98
|
+
const visitorOf = async (req) => (options.visitor ? await options.visitor(req) : ipOf(req));
|
|
99
|
+
const person = async (token, req) => (options.personCheck ? options.personCheck(token, req) : true);
|
|
100
|
+
/**
|
|
101
|
+
* 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
|
|
102
|
+
* 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
|
|
103
|
+
* 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.
|
|
104
|
+
*/
|
|
105
|
+
function wallets(req, at, admin) {
|
|
106
|
+
const url = new URL(req.url);
|
|
107
|
+
const host = options.domain ?? url.host;
|
|
108
|
+
const origin = `${url.protocol}//${host}`;
|
|
109
|
+
const clock = { now: () => at };
|
|
110
|
+
const life = admin ? { ttlMs: ADMIN_REQUEST_MS } : {};
|
|
111
|
+
const started = new Date(at).toISOString().slice(11, 16);
|
|
112
|
+
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.`;
|
|
113
|
+
return {
|
|
114
|
+
host,
|
|
115
|
+
berry: { domain: host, uri: `${origin}${page}`, store: store.requests("berry"), ...life, ...clock },
|
|
116
|
+
nautilus: {
|
|
117
|
+
site: host,
|
|
118
|
+
siteAddress,
|
|
119
|
+
store: store.requests("nautilus"),
|
|
120
|
+
...(admin ? { title: `ADMIN of ${host}`, ...(admin.country ? { note: `from ${admin.country}` } : {}), message: adminLine } : {}),
|
|
121
|
+
...life,
|
|
122
|
+
...clock,
|
|
123
|
+
},
|
|
124
|
+
// NanChat's text is "Login to <host> nonce: <nonce>": it has no place for the admin's name.
|
|
125
|
+
nanchat: { host, store: store.requests("nanchat"), ...life, ...clock },
|
|
126
|
+
nanchatUrl: `${origin}${base}/nanchat`,
|
|
127
|
+
requestUrl: (id) => `${origin}${base}/nano/${id}`,
|
|
128
|
+
nautilusUrl: (id) => `${origin}${base}/nautilus?id=${id}`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** A JSON body of at most 8 KB, or null when it is not one readable object. */
|
|
132
|
+
async function body(req) {
|
|
133
|
+
const text = await readLimited(req, ADMIN_SIGNIN_LIMITS.bodyMax);
|
|
134
|
+
if (text === null)
|
|
135
|
+
return null;
|
|
136
|
+
if (!text)
|
|
137
|
+
return {};
|
|
138
|
+
try {
|
|
139
|
+
const v = JSON.parse(text);
|
|
140
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** 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. */
|
|
147
|
+
const wayOf = (v) => (v === undefined ? "berry" : (ADMIN_WAYS.find((w) => w === v) ?? null));
|
|
148
|
+
async function start(req, b, at) {
|
|
149
|
+
const way = wayOf(b.way);
|
|
150
|
+
if (!way)
|
|
151
|
+
return fail(400, "That wallet is not one of this game's.");
|
|
152
|
+
if (!(await limit(`signin|${await visitorOf(req)}`, ADMIN_SIGNIN_LIMITS.signin.limit, ADMIN_SIGNIN_LIMITS.signin.windowMs, at)))
|
|
153
|
+
return fail(429, "Too many sign-ins. Wait a few minutes.");
|
|
154
|
+
if (!(await person(b.turnstile, req)))
|
|
155
|
+
return fail(403, "The person check failed. Try again.");
|
|
156
|
+
const admin = { country: countryOf(req) };
|
|
157
|
+
// 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
|
|
158
|
+
// the owner who is asked to sign. So it is refused unless the game turned it on.
|
|
159
|
+
if (way === "nanchat" && !nanchatOn)
|
|
160
|
+
return fail(400, NANCHAT_REFUSAL);
|
|
161
|
+
const starter = randomHex(32);
|
|
162
|
+
const hash = await adminKey(starter);
|
|
163
|
+
const w = wallets(req, at, admin);
|
|
164
|
+
let out;
|
|
165
|
+
if (way === "nautilus") {
|
|
166
|
+
const s = await startNautilus(w.nautilus, { starter: hash, answerUrl: w.nautilusUrl });
|
|
167
|
+
out = { way, id: s.id, link: s.link, code: s.code, expiresAt: s.expiresAt };
|
|
168
|
+
}
|
|
169
|
+
else if (way === "nanchat") {
|
|
170
|
+
const s = await startNanchat(w.nanchat, { starter: hash, answerUrl: w.nanchatUrl });
|
|
171
|
+
out = { way, id: s.id, link: s.link, expiresAt: s.expiresAt };
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
// `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.
|
|
175
|
+
const s = await startNanoSignin(w.berry, { starter: hash, requestUrl: w.requestUrl, label: admin.country ? `admin:${admin.country}` : "admin" });
|
|
176
|
+
out = { way, id: s.id, link: s.link, walletLink: s.walletLink, expiresAt: s.expiresAt };
|
|
177
|
+
}
|
|
178
|
+
return json(out, 200, { "Set-Cookie": cookieHeader(req, starterName, starter, ADMIN_STARTER_MAX_AGE_S) });
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 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
|
|
182
|
+
* its cookie is set.
|
|
183
|
+
*/
|
|
184
|
+
async function check(req, b, at) {
|
|
185
|
+
const way = wayOf(b.way);
|
|
186
|
+
if (!way)
|
|
187
|
+
return fail(400, "That wallet is not one of this game's.");
|
|
188
|
+
if (typeof b.id !== "string")
|
|
189
|
+
return fail(400, "no request id");
|
|
190
|
+
const cookie = readCookie(req, starterName);
|
|
191
|
+
// 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.
|
|
192
|
+
const starter = cookie && TOKEN_PATTERN.test(cookie) ? await adminKey(cookie) : undefined;
|
|
193
|
+
// While NanChat is off the admin starts no NanChat request: there is none to deliver.
|
|
194
|
+
if (way === "nanchat" && !nanchatOn)
|
|
195
|
+
return json({ status: "expired" });
|
|
196
|
+
// An admin request is delivered for a minute after it ends.
|
|
197
|
+
const o = { store: store.requests(way), now: () => at, deliverMs: ADMIN_DELIVER_MS };
|
|
198
|
+
const r = way === "nautilus" ? await checkNautilus(o, b.id, starter) : way === "nanchat" ? await checkNanchat(o, b.id, starter) : await checkNanoSignin(o, b.id, starter);
|
|
199
|
+
if (r.status !== "signedin")
|
|
200
|
+
return json({ status: r.status });
|
|
201
|
+
if (!r.mine || !r.account)
|
|
202
|
+
return json({ status: "elsewhere" });
|
|
203
|
+
// 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
|
|
204
|
+
// of its own), and the request stays unused.
|
|
205
|
+
if (r.account !== owner)
|
|
206
|
+
return json({ status: "not_owner", address: r.account });
|
|
207
|
+
// 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
|
|
208
|
+
// written only when the delivery changed the request. So "Sign out everywhere" cannot run between them: it either ends the request first (nothing is
|
|
209
|
+
// delivered, no session) or deletes the session after.
|
|
210
|
+
const token = randomHex(32);
|
|
211
|
+
const record = { idHash: await adminKey(token), address: r.account, createdAt: at, expiresAt: at + ADMIN_SESSION_MS, via: "wallet" };
|
|
212
|
+
if (!(await store.deliver(way, r.key ?? b.id, record)))
|
|
213
|
+
return json({ status: "used" });
|
|
214
|
+
// 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.
|
|
215
|
+
await store.recordLogin({ at, country: countryOf(req), browser: shortBrowser(req.headers.get("User-Agent")) });
|
|
216
|
+
return json({ status: "signedin", address: r.account }, 200, { "Set-Cookie": cookieHeader(req, sessionName, token, ADMIN_SESSION_MS / 1000) });
|
|
217
|
+
}
|
|
218
|
+
/** Berry Wallet's GET and POST. They come from the wallet app, so there is no cookie and no Origin to check. */
|
|
219
|
+
async function berry(req, id, at) {
|
|
220
|
+
const w = wallets(req, at);
|
|
221
|
+
if (req.method === "GET") {
|
|
222
|
+
const request = await readNanoSignin(w.berry, id, w.requestUrl);
|
|
223
|
+
return request ? json(request) : json(nanoSigninRefusal("This sign-in expired."), 404);
|
|
224
|
+
}
|
|
225
|
+
const b = await body(req);
|
|
226
|
+
if (!b)
|
|
227
|
+
return json(nanoSigninRefusal("This answer is not readable."), 401);
|
|
228
|
+
try {
|
|
229
|
+
await answerNanoSignin(w.berry, id, b, w.requestUrl);
|
|
230
|
+
// Berry Wallet shows its success screen only for a 204 with no body.
|
|
231
|
+
return new Response(null, { status: NANO_SIGNIN_ACCEPTED, headers: { "Cache-Control": "no-store" } });
|
|
232
|
+
}
|
|
233
|
+
catch (e) {
|
|
234
|
+
if (e instanceof WalletRefused)
|
|
235
|
+
return json(nanoSigninRefusal(e.message), 401);
|
|
236
|
+
throw e;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** Nautilus's answer. It comes from the app: no cookie, no Origin. Nautilus shows the words only with HTTP 200. */
|
|
240
|
+
async function nautilus(req, at) {
|
|
241
|
+
const w = wallets(req, at);
|
|
242
|
+
const b = await body(req);
|
|
243
|
+
if (!b)
|
|
244
|
+
return json(nautilusReply(w.host, "That answer could not be read."));
|
|
245
|
+
try {
|
|
246
|
+
await answerNautilus(w.nautilus, new URL(req.url).searchParams.get("id") ?? "", b);
|
|
247
|
+
return json(nautilusReply(w.host));
|
|
248
|
+
}
|
|
249
|
+
catch (e) {
|
|
250
|
+
if (e instanceof WalletRefused)
|
|
251
|
+
return json(nautilusReply(w.host, e.message));
|
|
252
|
+
throw e;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** 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. */
|
|
256
|
+
async function nanchat(req, at) {
|
|
257
|
+
const w = wallets(req, at);
|
|
258
|
+
const refuse = (words) => json(nanchatReply(w.host, words));
|
|
259
|
+
if (!memory(`${base}|nanchat`, ADMIN_SIGNIN_LIMITS.nanchatRoute.limit, ADMIN_SIGNIN_LIMITS.nanchatRoute.windowMs, at))
|
|
260
|
+
return refuse("too many sign-ins at once. Wait a minute.");
|
|
261
|
+
const b = await body(req);
|
|
262
|
+
if (!b)
|
|
263
|
+
return refuse("that answer could not be read.");
|
|
264
|
+
const nonce = nanchatNonce(w.host, b.message);
|
|
265
|
+
if (nonce && typeof b.account === "string" && typeof b.signature === "string" && /^[0-9A-Fa-f]{128}$/.test(b.signature)) {
|
|
266
|
+
if (!(await limit("admin-nanchat|all", ADMIN_SIGNIN_LIMITS.nanchatAll.limit, ADMIN_SIGNIN_LIMITS.nanchatAll.windowMs, at)))
|
|
267
|
+
return refuse("too many sign-ins at once. Wait a few minutes.");
|
|
268
|
+
if (!(await limit(`admin-nanchat|${nonce}`, ADMIN_SIGNIN_LIMITS.nanchatNonce.limit, ADMIN_SIGNIN_LIMITS.nanchatNonce.windowMs, at)))
|
|
269
|
+
return refuse(`too many tries for this sign-in. Start again on ${w.host}.`);
|
|
270
|
+
}
|
|
271
|
+
try {
|
|
272
|
+
await answerNanchat(w.nanchat, b);
|
|
273
|
+
return json(nanchatReply(w.host));
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
if (e instanceof WalletRefused)
|
|
277
|
+
return refuse(e.message);
|
|
278
|
+
throw e;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
async function sessionOf(req, at = now()) {
|
|
282
|
+
const token = readCookie(req, sessionName);
|
|
283
|
+
if (!token || !TOKEN_PATTERN.test(token))
|
|
284
|
+
return null;
|
|
285
|
+
// 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.
|
|
286
|
+
const s = await store.session(await adminKey(token), at);
|
|
287
|
+
// Only the two 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).
|
|
288
|
+
return s ? { address: s.address, createdAt: s.createdAt, via: s.via === "wallet" || s.via === "nanoterra" ? s.via : "unknown" } : null;
|
|
289
|
+
}
|
|
290
|
+
async function signOut(req) {
|
|
291
|
+
const token = readCookie(req, sessionName);
|
|
292
|
+
if (token)
|
|
293
|
+
await store.endSession(await adminKey(token));
|
|
294
|
+
return cookieHeader(req, sessionName, "", 0);
|
|
295
|
+
}
|
|
296
|
+
async function handle(req) {
|
|
297
|
+
const url = new URL(req.url);
|
|
298
|
+
const path = url.pathname;
|
|
299
|
+
const berryId = path.startsWith(`${base}/nano/`) ? /^[0-9a-f]{32}$/.exec(path.slice(base.length + 6))?.[0] : undefined;
|
|
300
|
+
const mine = berryId !== undefined || [`${base}/start`, `${base}/check`, `${base}/signout`, `${base}/nautilus`].includes(path) || (nanchatOn && path === `${base}/nanchat`);
|
|
301
|
+
if (!mine)
|
|
302
|
+
return null;
|
|
303
|
+
try {
|
|
304
|
+
if (options.domain && url.host !== options.domain)
|
|
305
|
+
return fail(403, `This sign-in belongs to ${options.domain}.`);
|
|
306
|
+
const at = now();
|
|
307
|
+
const ip = ipOf(req);
|
|
308
|
+
// The wallet apps' routes: no cookie and no Origin (an app posts them, not a browser page).
|
|
309
|
+
if (berryId !== undefined) {
|
|
310
|
+
if (req.method !== "GET" && req.method !== "POST")
|
|
311
|
+
return fail(405, "Not allowed.", {}, { Allow: "GET, POST" });
|
|
312
|
+
if (!memory(`${base}|wallet|${ip}`, ADMIN_SIGNIN_LIMITS.wallet.limit, ADMIN_SIGNIN_LIMITS.wallet.windowMs, at))
|
|
313
|
+
return fail(429, "Too many requests.");
|
|
314
|
+
return await berry(req, berryId, at);
|
|
315
|
+
}
|
|
316
|
+
if (path === `${base}/nautilus`) {
|
|
317
|
+
if (req.method !== "POST")
|
|
318
|
+
return fail(405, "Not allowed.", {}, { Allow: "POST" });
|
|
319
|
+
// Nautilus shows the words of a refusal only with HTTP 200.
|
|
320
|
+
if (!memory(`${base}|wallet|${ip}`, ADMIN_SIGNIN_LIMITS.wallet.limit, ADMIN_SIGNIN_LIMITS.wallet.windowMs, at))
|
|
321
|
+
return json(nautilusReply(wallets(req, at).host, "Too many requests. Wait a minute."));
|
|
322
|
+
return await nautilus(req, at);
|
|
323
|
+
}
|
|
324
|
+
if (path === `${base}/nanchat`) {
|
|
325
|
+
if (req.method !== "POST")
|
|
326
|
+
return fail(405, "Not allowed.", {}, { Allow: "POST" });
|
|
327
|
+
return await nanchat(req, at);
|
|
328
|
+
}
|
|
329
|
+
// The browser's own calls: a POST from the game's own page.
|
|
330
|
+
if (req.method !== "POST")
|
|
331
|
+
return fail(405, "Not allowed.", {}, { Allow: "POST" });
|
|
332
|
+
if (path === `${base}/check` && !memory(`${base}|poll|${ip}`, ADMIN_SIGNIN_LIMITS.poll.limit, ADMIN_SIGNIN_LIMITS.poll.windowMs, at))
|
|
333
|
+
return fail(429, "Too many requests. Wait a minute.");
|
|
334
|
+
if (!sameOrigin(req))
|
|
335
|
+
return fail(403, "This call must come from the game's own page.");
|
|
336
|
+
// A sign-out reads no body.
|
|
337
|
+
if (path === `${base}/signout`)
|
|
338
|
+
return json({ ok: true }, 200, { "Set-Cookie": await signOut(req) });
|
|
339
|
+
const b = await body(req);
|
|
340
|
+
if (!b)
|
|
341
|
+
return fail(400, "That request is not readable.");
|
|
342
|
+
if (path === `${base}/check`)
|
|
343
|
+
return await check(req, b, at);
|
|
344
|
+
return await start(req, b, at);
|
|
345
|
+
}
|
|
346
|
+
catch (e) {
|
|
347
|
+
report(e);
|
|
348
|
+
return fail(500, "Something went wrong. Try again.");
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
base,
|
|
353
|
+
handle,
|
|
354
|
+
session: sessionOf,
|
|
355
|
+
signOut,
|
|
356
|
+
signOutEverywhere: () => store.signOutEverywhere(),
|
|
357
|
+
recentLogins: (n) => store.recentLogins(n),
|
|
358
|
+
clean: (at = now()) => store.clean(at),
|
|
359
|
+
};
|
|
360
|
+
}
|
|
@@ -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_PAGE, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, } from "./types.js";
|
|
7
|
+
export type { AdminSessionRecord, AdminSigninSession, AdminSigninStore, AdminWay, RequestStoreLike, SigninRequest } from "./types.js";
|
|
8
|
+
export { ADMIN_SESSION_MS } from "../admin/guard.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
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); no passkey. The game starter's
|
|
3
|
+
// 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
|
|
4
|
+
// with this package).
|
|
5
|
+
//
|
|
6
|
+
// createAdminSignin the routes (start, the wallets' answers, check, sign-out), `session(request)` for `createAdminHandler`, `signOutEverywhere`,
|
|
7
|
+
// `recentLogins` and `clean`
|
|
8
|
+
// createMemoryAdminSignin a store in memory, for tests
|
|
9
|
+
// (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
|
|
10
|
+
// conformance suite "/admin-signin/conformance", the browser panel "/admin-signin/panel" and its stylesheet "/admin-signin/style.css")
|
|
11
|
+
export { EXAMPLE_ADDRESS, adminKey, createAdminSignin } from "./handler.js";
|
|
12
|
+
export { createMemoryAdminSignin } from "./memory.js";
|
|
13
|
+
export { countryOf, shortBrowser } from "./browser.js";
|
|
14
|
+
export { ADMIN_DELIVER_MS, ADMIN_LOGIN_KEEP_MS, ADMIN_PAGE, ADMIN_REQUEST_MS, ADMIN_SIGNIN_BASE, ADMIN_SIGNIN_LIMITS, ADMIN_STARTER_MAX_AGE_S, ADMIN_WAYS, NANCHAT_REFUSAL, } from "./types.js";
|
|
15
|
+
export { ADMIN_SESSION_MS } from "../admin/guard.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AdminLogin } from "../admin/store.js";
|
|
2
|
+
import { 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 = AdminSigninStore & {
|
|
8
|
+
readonly requestRows: Map<string, RequestRow>;
|
|
9
|
+
readonly sessionRows: Map<string, AdminSessionRecord>;
|
|
10
|
+
readonly loginRows: AdminLogin[];
|
|
11
|
+
};
|
|
12
|
+
export declare function createMemoryAdminSignin(): MemoryAdminSignin;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// The admin sign-in's store in this process's memory: for tests and demos. A game uses a database (./adapters/d1.ts, ./adapters/firestore.ts, or its
|
|
2
|
+
// own store that passes adminSigninStoreConformance).
|
|
3
|
+
import { ADMIN_LOGIN_KEEP_MS, ADMIN_WAYS } from "./types.js";
|
|
4
|
+
const copy = (v) => structuredClone(v);
|
|
5
|
+
export function createMemoryAdminSignin() {
|
|
6
|
+
const requestRows = new Map();
|
|
7
|
+
const sessionRows = new Map();
|
|
8
|
+
const loginRows = [];
|
|
9
|
+
const strip = ({ way: _way, delivered: _delivered, ...r }) => copy(r);
|
|
10
|
+
const stores = new Map();
|
|
11
|
+
for (const way of ADMIN_WAYS) {
|
|
12
|
+
stores.set(way, {
|
|
13
|
+
async create(key, r) {
|
|
14
|
+
if (requestRows.has(key))
|
|
15
|
+
throw new Error("a request with this key exists");
|
|
16
|
+
requestRows.set(key, { ...copy(r), way, delivered: false });
|
|
17
|
+
},
|
|
18
|
+
async get(key) {
|
|
19
|
+
const r = requestRows.get(key);
|
|
20
|
+
return r && r.way === way ? strip(r) : null;
|
|
21
|
+
},
|
|
22
|
+
async find(id) {
|
|
23
|
+
for (const [key, r] of requestRows)
|
|
24
|
+
if (r.way === way && r.id === id)
|
|
25
|
+
return { key, request: strip(r) };
|
|
26
|
+
return null;
|
|
27
|
+
},
|
|
28
|
+
async finish(key, account) {
|
|
29
|
+
const r = requestRows.get(key);
|
|
30
|
+
if (!r || r.way !== way || r.status !== "waiting")
|
|
31
|
+
return false;
|
|
32
|
+
r.status = "signedin";
|
|
33
|
+
r.account = account;
|
|
34
|
+
return true;
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
requestRows,
|
|
40
|
+
sessionRows,
|
|
41
|
+
loginRows,
|
|
42
|
+
requests: (way) => {
|
|
43
|
+
const s = stores.get(way);
|
|
44
|
+
if (!s)
|
|
45
|
+
throw new Error(`no such way: ${String(way)}`);
|
|
46
|
+
return s;
|
|
47
|
+
},
|
|
48
|
+
async deliver(way, key, session) {
|
|
49
|
+
const r = requestRows.get(key);
|
|
50
|
+
if (!r || r.way !== way || r.status !== "signedin" || r.delivered)
|
|
51
|
+
return false;
|
|
52
|
+
r.delivered = true;
|
|
53
|
+
sessionRows.set(session.idHash, copy(session));
|
|
54
|
+
return true;
|
|
55
|
+
},
|
|
56
|
+
async session(idHash, now) {
|
|
57
|
+
const s = sessionRows.get(idHash);
|
|
58
|
+
return s && s.expiresAt > now ? copy(s) : null;
|
|
59
|
+
},
|
|
60
|
+
async endSession(idHash) {
|
|
61
|
+
sessionRows.delete(idHash);
|
|
62
|
+
},
|
|
63
|
+
async signOutEverywhere() {
|
|
64
|
+
const n = sessionRows.size;
|
|
65
|
+
sessionRows.clear();
|
|
66
|
+
for (const r of requestRows.values()) {
|
|
67
|
+
if (r.delivered)
|
|
68
|
+
continue;
|
|
69
|
+
r.delivered = true;
|
|
70
|
+
r.expiresAt = 0;
|
|
71
|
+
}
|
|
72
|
+
return n;
|
|
73
|
+
},
|
|
74
|
+
async recordLogin(login) {
|
|
75
|
+
for (let i = loginRows.length - 1; i >= 0; i--)
|
|
76
|
+
if (loginRows[i].at < login.at - ADMIN_LOGIN_KEEP_MS)
|
|
77
|
+
loginRows.splice(i, 1);
|
|
78
|
+
loginRows.push({ at: login.at, country: login.country, browser: login.browser });
|
|
79
|
+
},
|
|
80
|
+
async recentLogins(limit) {
|
|
81
|
+
const n = Math.min(Math.max(Math.floor(Number(limit)) || 0, 0), 50);
|
|
82
|
+
// Newest first; of two at the same time, the one written last.
|
|
83
|
+
return loginRows
|
|
84
|
+
.map((l, i) => ({ l, i }))
|
|
85
|
+
.sort((a, b) => b.l.at - a.l.at || b.i - a.i)
|
|
86
|
+
.slice(0, n)
|
|
87
|
+
.map(({ l }) => ({ at: l.at, country: l.country, browser: l.browser }));
|
|
88
|
+
},
|
|
89
|
+
async clean(now) {
|
|
90
|
+
for (const [k, r] of requestRows)
|
|
91
|
+
if (r.expiresAt < now - 2 * 3_600_000)
|
|
92
|
+
requestRows.delete(k);
|
|
93
|
+
for (const [k, s] of sessionRows)
|
|
94
|
+
if (s.expiresAt < now)
|
|
95
|
+
sessionRows.delete(k);
|
|
96
|
+
for (let i = loginRows.length - 1; i >= 0; i--)
|
|
97
|
+
if (loginRows[i].at < now - ADMIN_LOGIN_KEEP_MS)
|
|
98
|
+
loginRows.splice(i, 1);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// "@nano133/nanoterra/admin-signin/panel": the ADMIN's sign-in in the browser, for the admin page. `adminSignIn()` fits `mountAdmin`'s `signIn(into, done)`
|
|
2
|
+
// and `adminSignOut()` its `signOut`; `adminSigninView` is the content alone. Add "@nano133/nanoterra/admin-signin/style.css" to the page (the player
|
|
3
|
+
// sheet's stylesheet: the two sign-ins look the same). No package, no Three.js; the server part is "@nano133/nanoterra/admin-signin".
|
|
4
|
+
export { ADMIN_NANCHAT_NOTE, ADMIN_SIGNIN_INTRO, adminSignIn, adminSignOut, adminSigninView } from "./view.js";
|
|
5
|
+
export { ADMIN_SIGNIN_BASE } from "../types.js";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type AdminSigninViewOptions = {
|
|
2
|
+
/** Where the sign-in's routes are. Default "/api/admin-signin" (ADMIN_SIGNIN_BASE). */
|
|
3
|
+
base?: string;
|
|
4
|
+
/**
|
|
5
|
+
* 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
|
|
6
|
+
* admin sign-in from a game sign-in in it: it is off unless the game turns it on on the server and here.
|
|
7
|
+
*/
|
|
8
|
+
nanchat?: boolean;
|
|
9
|
+
/** The person check (Turnstile): fills `box` and gives its token, before a start. No hook: no check. */
|
|
10
|
+
personCheck?: (box: HTMLElement) => Promise<string | null | undefined>;
|
|
11
|
+
/** 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. */
|
|
12
|
+
qr?: (text: string) => HTMLElement | SVGElement;
|
|
13
|
+
/** A touch screen (one key that opens the app) or not (a QR code). Default: `(pointer: coarse)`. */
|
|
14
|
+
touch?: boolean;
|
|
15
|
+
/** The `fetch` to use (default: the page's). */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
/** The owner signed in (the address that signed). */
|
|
18
|
+
onSignedIn?: (address: string) => void;
|
|
19
|
+
};
|
|
20
|
+
export type AdminSigninView = {
|
|
21
|
+
node: HTMLElement;
|
|
22
|
+
/** Ends the waiting (the gate closed). */
|
|
23
|
+
stop(): void;
|
|
24
|
+
/** Starts again at the tiles. */
|
|
25
|
+
reset(): void;
|
|
26
|
+
};
|
|
27
|
+
/** The admin's words: the starter's. */
|
|
28
|
+
export declare 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.";
|
|
29
|
+
/** What NanChat's sign-in says, when it is on: its text cannot say "admin". */
|
|
30
|
+
export declare 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.";
|
|
31
|
+
export declare function adminSigninView(options?: AdminSigninViewOptions): AdminSigninView;
|
|
32
|
+
/**
|
|
33
|
+
* 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
|
|
34
|
+
* call (the gate shows again) stops the view that was drawn before.
|
|
35
|
+
*
|
|
36
|
+
* mountAdmin(el, { looks, signIn: adminSignIn(), signOut: adminSignOut() });
|
|
37
|
+
*/
|
|
38
|
+
export declare function adminSignIn(options?: AdminSigninViewOptions): (into: HTMLElement, done: () => void) => void;
|
|
39
|
+
/** `mountAdmin`'s `signOut`: ends the ADMIN login only (`POST {base}/signout`); the game's own login, another person's perhaps, stays. */
|
|
40
|
+
export declare function adminSignOut(options?: Pick<AdminSigninViewOptions, "base" | "fetch">): () => Promise<unknown>;
|