@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,182 @@
|
|
|
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
|
+
import { ApiError, createApi } from "../../admin/panel/api.js";
|
|
9
|
+
import { h, shortAddress } from "../../admin/panel/dom.js";
|
|
10
|
+
import { icon } from "../../admin/panel/icons.js";
|
|
11
|
+
import { qrSvg } from "../../shop/panel/qr.js";
|
|
12
|
+
import { ADMIN_SIGNIN_BASE } from "../types.js";
|
|
13
|
+
/** The wallets, in every list's order: Berry Wallet first. */
|
|
14
|
+
const WALLETS = [
|
|
15
|
+
{ way: "berry", name: "Berry Wallet", mark: "B" },
|
|
16
|
+
{ way: "nautilus", name: "Nautilus", mark: "N" },
|
|
17
|
+
{ way: "nanchat", name: "NanChat", mark: "NC" },
|
|
18
|
+
];
|
|
19
|
+
const nameOf = (way) => WALLETS.find((w) => w.way === way).name;
|
|
20
|
+
/** The admin's words: the starter's. */
|
|
21
|
+
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.";
|
|
22
|
+
/** What NanChat's sign-in says, when it is on: its text cannot say "admin". */
|
|
23
|
+
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.";
|
|
24
|
+
export function adminSigninView(options = {}) {
|
|
25
|
+
const base = options.base ?? ADMIN_SIGNIN_BASE;
|
|
26
|
+
const api = createApi(base, options.fetch ?? ((...a) => fetch(...a)));
|
|
27
|
+
const wallets = WALLETS.filter((w) => w.way !== "nanchat" || options.nanchat === true);
|
|
28
|
+
const touch = () => options.touch ?? (typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches);
|
|
29
|
+
let stopped = false;
|
|
30
|
+
let timer;
|
|
31
|
+
/** The request that is waiting. Back keeps it: the person may have approved it already. */
|
|
32
|
+
let current = null;
|
|
33
|
+
const status = h("p", { class: "n133s-status", role: "status", "aria-live": "polite" });
|
|
34
|
+
const check = h("div", { class: "n133s-check" });
|
|
35
|
+
const area = h("div", { class: "n133s-area" });
|
|
36
|
+
const node = h("div", { class: "n133-signin n133s-view n133-admin-signin" }, h("p", { class: "n133s-lead" }, ADMIN_SIGNIN_INTRO), check, area, status);
|
|
37
|
+
const say = (text) => (status.textContent = text);
|
|
38
|
+
const key = (text, onclick, kind = "plain") => h("button", { class: `n133s-btn n133s-${kind}`, type: "button", onclick }, text);
|
|
39
|
+
const focusFirst = () => (area.querySelector("h3, button:not([disabled])") ?? area).focus?.({ preventScroll: true });
|
|
40
|
+
function stopWaiting() {
|
|
41
|
+
if (timer)
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
timer = undefined;
|
|
44
|
+
}
|
|
45
|
+
function showTiles() {
|
|
46
|
+
stopWaiting();
|
|
47
|
+
const tiles = wallets.map((w) => 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)));
|
|
48
|
+
area.replaceChildren(h("p", { class: "n133s-or" }, "Choose your wallet"), h("div", { class: "n133s-tiles", "data-count": String(tiles.length) }, ...tiles));
|
|
49
|
+
}
|
|
50
|
+
async function choose(way) {
|
|
51
|
+
if (current?.way === way && Date.now() < current.expiresAt)
|
|
52
|
+
return showWallet(current);
|
|
53
|
+
stopWaiting();
|
|
54
|
+
current = null;
|
|
55
|
+
for (const b of Array.from(area.querySelectorAll("button")))
|
|
56
|
+
b.disabled = true;
|
|
57
|
+
say("Starting…");
|
|
58
|
+
try {
|
|
59
|
+
const turnstile = options.personCheck ? await options.personCheck(check) : undefined;
|
|
60
|
+
const s = await api.post("/start", { way, ...(turnstile ? { turnstile } : {}) });
|
|
61
|
+
if (stopped)
|
|
62
|
+
return;
|
|
63
|
+
current = s;
|
|
64
|
+
showWallet(s);
|
|
65
|
+
void poll(s);
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
showTiles();
|
|
69
|
+
say(e instanceof Error && e.message ? e.message : "Sign-in did not start. Try again.");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function showWallet(s) {
|
|
73
|
+
const name = nameOf(s.way);
|
|
74
|
+
const back = h("button", { class: "n133s-back", type: "button", onclick: () => showTiles() }, icon("back", 18), h("span", {}, "Back"));
|
|
75
|
+
area.replaceChildren(back, h("h3", { class: "n133s-step", tabindex: "-1" }, name), ...walletSteps(s, name));
|
|
76
|
+
say(`Waiting for ${name}…`);
|
|
77
|
+
focusFirst();
|
|
78
|
+
}
|
|
79
|
+
/** 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). */
|
|
80
|
+
function qrOf(text, name) {
|
|
81
|
+
try {
|
|
82
|
+
const code = options.qr ? options.qr(text) : qrSvg(text, `QR code to sign in with ${name}`);
|
|
83
|
+
code.setAttribute("aria-label", `QR code to sign in with ${name}`);
|
|
84
|
+
return h("div", { class: "n133s-qr" }, code);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
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`), ".");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** What the person does with the wallet: on a phone, one key; on a computer, a QR code for the phone. */
|
|
91
|
+
function walletSteps(s, name) {
|
|
92
|
+
const open = (text, href, newTab = false) => h("a", { class: "n133s-btn n133s-primary", href, target: newTab ? "_blank" : undefined, rel: newTab ? "noopener" : undefined }, text);
|
|
93
|
+
const only = h("p", { class: "n133s-fine" }, `Only approve a sign-in that you started yourself, on ${location.host}.`);
|
|
94
|
+
const comeBack = h("p", { class: "n133s-fine" }, `Approve the sign-in in ${s.way === "berry" ? "your wallet" : name}, then come back to this page.`);
|
|
95
|
+
if (s.way === "nautilus") {
|
|
96
|
+
const code = h("p", { class: "n133s-text" }, "Check that Nautilus shows the code ", h("strong", { class: "n133s-signcode" }, s.code ?? ""), ".");
|
|
97
|
+
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];
|
|
98
|
+
}
|
|
99
|
+
if (s.way === "nanchat") {
|
|
100
|
+
const note = h("p", { class: "n133s-text n133s-fault" }, ADMIN_NANCHAT_NOTE);
|
|
101
|
+
const here = h("p", { class: "n133s-fine" }, "On this computer: ", h("a", { href: s.link, target: "_blank", rel: "noopener" }, "open NanChat"), ".");
|
|
102
|
+
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];
|
|
103
|
+
}
|
|
104
|
+
const other = h("a", { class: "n133s-btn n133s-plain", href: s.walletLink ?? s.link }, "Another wallet");
|
|
105
|
+
const here = h("p", { class: "n133s-fine" }, "On this computer: ", h("a", { href: s.walletLink ?? s.link }, "open a wallet"), ".");
|
|
106
|
+
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];
|
|
107
|
+
}
|
|
108
|
+
/** The request ended without a sign-in: say why, and offer a new one. */
|
|
109
|
+
function again(s, words) {
|
|
110
|
+
current = null;
|
|
111
|
+
area.replaceChildren(h("div", { class: "n133s-keys" }, key("Try again", () => void choose(s.way), "primary"), key("Choose another wallet", () => showTiles())));
|
|
112
|
+
say(words);
|
|
113
|
+
}
|
|
114
|
+
async function poll(s) {
|
|
115
|
+
if (stopped || current !== s)
|
|
116
|
+
return;
|
|
117
|
+
if (Date.now() > s.expiresAt + 5000)
|
|
118
|
+
return again(s, "This sign-in expired.");
|
|
119
|
+
try {
|
|
120
|
+
const r = await api.post("/check", { id: s.id, way: s.way });
|
|
121
|
+
if (stopped || current !== s)
|
|
122
|
+
return;
|
|
123
|
+
if (r.status === "signedin" && r.address) {
|
|
124
|
+
current = null;
|
|
125
|
+
area.replaceChildren(h("p", { class: "n133s-done" }, icon("check", 22), h("span", {}, `Signed in as ${shortAddress(r.address)}`)));
|
|
126
|
+
say("");
|
|
127
|
+
options.onSignedIn?.(r.address);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (r.status === "elsewhere" || r.status === "used")
|
|
131
|
+
return again(s, "This sign-in was used in another browser. Start again.");
|
|
132
|
+
if (r.status === "not_owner")
|
|
133
|
+
return again(s, "That wallet is not this game's address. Choose the wallet that holds it.");
|
|
134
|
+
if (r.status === "expired")
|
|
135
|
+
return again(s, "This sign-in expired.");
|
|
136
|
+
}
|
|
137
|
+
catch (e) {
|
|
138
|
+
if (e instanceof ApiError && e.status === 429)
|
|
139
|
+
say("Too many checks. Waiting a moment…");
|
|
140
|
+
}
|
|
141
|
+
timer = setTimeout(() => void poll(s), 2000);
|
|
142
|
+
}
|
|
143
|
+
showTiles();
|
|
144
|
+
return {
|
|
145
|
+
node,
|
|
146
|
+
stop() {
|
|
147
|
+
stopped = true;
|
|
148
|
+
stopWaiting();
|
|
149
|
+
},
|
|
150
|
+
reset() {
|
|
151
|
+
stopped = false;
|
|
152
|
+
current = null;
|
|
153
|
+
showTiles();
|
|
154
|
+
say("");
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 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
|
|
160
|
+
* call (the gate shows again) stops the view that was drawn before.
|
|
161
|
+
*
|
|
162
|
+
* mountAdmin(el, { looks, signIn: adminSignIn(), signOut: adminSignOut() });
|
|
163
|
+
*/
|
|
164
|
+
export function adminSignIn(options = {}) {
|
|
165
|
+
let last = null;
|
|
166
|
+
return (into, done) => {
|
|
167
|
+
last?.stop();
|
|
168
|
+
const view = adminSigninView({
|
|
169
|
+
...options,
|
|
170
|
+
onSignedIn(address) {
|
|
171
|
+
options.onSignedIn?.(address);
|
|
172
|
+
done();
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
last = view;
|
|
176
|
+
into.append(view.node);
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** `mountAdmin`'s `signOut`: ends the ADMIN login only (`POST {base}/signout`); the game's own login, another person's perhaps, stays. */
|
|
180
|
+
export function adminSignOut(options = {}) {
|
|
181
|
+
return () => createApi(options.base ?? ADMIN_SIGNIN_BASE, options.fetch ?? ((...a) => fetch(...a))).post("/signout", {});
|
|
182
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { AdminLogin } from "../admin/store.js";
|
|
2
|
+
import type { RequestStoreLike } from "../player-signin/types.js";
|
|
3
|
+
export type { RequestStoreLike, SigninRequest } from "../player-signin/types.js";
|
|
4
|
+
/** The admin's sign-in route, the same in every game: a page, an AI helper and the kit's panel find it here. */
|
|
5
|
+
export declare const ADMIN_SIGNIN_BASE = "/api/admin-signin";
|
|
6
|
+
/** The page the admin signs in to: Berry Wallet signs this page's address ("URI: https://example.com/admin", with NO query). */
|
|
7
|
+
export declare const ADMIN_PAGE = "/admin";
|
|
8
|
+
/**
|
|
9
|
+
* 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
|
|
10
|
+
* (`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
|
|
11
|
+
* text that looks like any sign-in to the game. Berry Wallet and Nautilus sign a text that says "ADMIN".
|
|
12
|
+
*/
|
|
13
|
+
export declare const ADMIN_WAYS: readonly ["berry", "nautilus", "nanchat"];
|
|
14
|
+
export type AdminWay = (typeof ADMIN_WAYS)[number];
|
|
15
|
+
/** What a NanChat start is told while NanChat is off (the default): the starter's words. */
|
|
16
|
+
export declare const NANCHAT_REFUSAL = "NanChat cannot open the admin yet. Use Berry Wallet or Nautilus.";
|
|
17
|
+
/** 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. */
|
|
18
|
+
export declare const ADMIN_REQUEST_MS: number;
|
|
19
|
+
export declare const ADMIN_DELIVER_MS = 60000;
|
|
20
|
+
/** How long a row of the admin's sign-in list is kept: 30 days. */
|
|
21
|
+
export declare const ADMIN_LOGIN_KEEP_MS: number;
|
|
22
|
+
/** How long the starter cookie lives: a wallet's request must be answered within it. */
|
|
23
|
+
export declare const ADMIN_STARTER_MAX_AGE_S: number;
|
|
24
|
+
/** The limits of the routes (calls per window). `signin` uses the game's `limit` hook; the rest count in this process's memory. */
|
|
25
|
+
export declare const ADMIN_SIGNIN_LIMITS: {
|
|
26
|
+
/** An admin sign-in start, per visitor (hook). The key is the player's (`signin|<visitor>`): one count for both, as the starter had. */
|
|
27
|
+
readonly signin: {
|
|
28
|
+
readonly limit: 20;
|
|
29
|
+
readonly windowMs: number;
|
|
30
|
+
};
|
|
31
|
+
/** The browser's checks (every 2 s), per IP address (memory). */
|
|
32
|
+
readonly poll: {
|
|
33
|
+
readonly limit: 90;
|
|
34
|
+
readonly windowMs: 60000;
|
|
35
|
+
};
|
|
36
|
+
/** Berry Wallet's GET and POST and Nautilus's answer, per IP address (memory): the wallet's own phone sends them. */
|
|
37
|
+
readonly wallet: {
|
|
38
|
+
readonly limit: 30;
|
|
39
|
+
readonly windowMs: 60000;
|
|
40
|
+
};
|
|
41
|
+
/** 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). */
|
|
42
|
+
readonly nanchatRoute: {
|
|
43
|
+
readonly limit: 120;
|
|
44
|
+
readonly windowMs: 60000;
|
|
45
|
+
};
|
|
46
|
+
readonly nanchatAll: {
|
|
47
|
+
readonly limit: 600;
|
|
48
|
+
readonly windowMs: number;
|
|
49
|
+
};
|
|
50
|
+
readonly nanchatNonce: {
|
|
51
|
+
readonly limit: 5;
|
|
52
|
+
readonly windowMs: number;
|
|
53
|
+
};
|
|
54
|
+
/** The biggest body the routes read. */
|
|
55
|
+
readonly bodyMax: 8192;
|
|
56
|
+
};
|
|
57
|
+
/** A token, a starter value: 32 random bytes as 64 hex characters. */
|
|
58
|
+
export declare const TOKEN_PATTERN: RegExp;
|
|
59
|
+
/**
|
|
60
|
+
* 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
|
|
61
|
+
* 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
|
|
62
|
+
* sign-in makes; a store returns the word it holds.
|
|
63
|
+
*/
|
|
64
|
+
export type AdminSessionRecord = {
|
|
65
|
+
idHash: string;
|
|
66
|
+
address: string;
|
|
67
|
+
createdAt: number;
|
|
68
|
+
expiresAt: number;
|
|
69
|
+
via: string;
|
|
70
|
+
};
|
|
71
|
+
/** 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. */
|
|
72
|
+
export type AdminSigninSession = {
|
|
73
|
+
address: string;
|
|
74
|
+
createdAt: number;
|
|
75
|
+
via: "wallet" | "nanoterra" | "unknown";
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* 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),
|
|
79
|
+
* 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).
|
|
80
|
+
* Run `adminSigninStoreConformance` on a store you write yourself.
|
|
81
|
+
*/
|
|
82
|
+
export interface AdminSigninStore {
|
|
83
|
+
/** The admin requests of one wallet app. */
|
|
84
|
+
requests(way: AdminWay): RequestStoreLike;
|
|
85
|
+
/**
|
|
86
|
+
* 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,
|
|
87
|
+
* false (and no session written) when it was delivered before, is not signed, is not known or is not the admin's.
|
|
88
|
+
*/
|
|
89
|
+
deliver(way: AdminWay, key: string, session: AdminSessionRecord): Promise<boolean>;
|
|
90
|
+
/** The admin session of a hash while it lasts (`expiresAt` > now), else null. */
|
|
91
|
+
session(idHash: string, now: number): Promise<AdminSessionRecord | null>;
|
|
92
|
+
/** Ends one admin session (this browser's sign-out). */
|
|
93
|
+
endSession(idHash: string): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* "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
|
|
96
|
+
* its time is over, so a request signed a moment ago, or signed later, makes no login). Returns how many sessions went.
|
|
97
|
+
*/
|
|
98
|
+
signOutEverywhere(): Promise<number>;
|
|
99
|
+
/** 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. */
|
|
100
|
+
recordLogin(login: AdminLogin): Promise<void>;
|
|
101
|
+
/** The last sign-ins, newest first, at most `limit`, with only `at`, `country` and `browser`. */
|
|
102
|
+
recentLogins(limit: number): Promise<AdminLogin[]>;
|
|
103
|
+
/** Deletes what nobody needs any more: admin requests 2 hours after they ended, admin sessions that ended, sign-in rows older than 30 days. */
|
|
104
|
+
clean(now: number): Promise<void>;
|
|
105
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
/** The admin's sign-in route, the same in every game: a page, an AI helper and the kit's panel find it here. */
|
|
8
|
+
export const ADMIN_SIGNIN_BASE = "/api/admin-signin";
|
|
9
|
+
/** The page the admin signs in to: Berry Wallet signs this page's address ("URI: https://example.com/admin", with NO query). */
|
|
10
|
+
export const ADMIN_PAGE = "/admin";
|
|
11
|
+
/**
|
|
12
|
+
* 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
|
|
13
|
+
* (`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
|
|
14
|
+
* text that looks like any sign-in to the game. Berry Wallet and Nautilus sign a text that says "ADMIN".
|
|
15
|
+
*/
|
|
16
|
+
export const ADMIN_WAYS = ["berry", "nautilus", "nanchat"];
|
|
17
|
+
/** What a NanChat start is told while NanChat is off (the default): the starter's words. */
|
|
18
|
+
export const NANCHAT_REFUSAL = "NanChat cannot open the admin yet. Use Berry Wallet or Nautilus.";
|
|
19
|
+
/** 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. */
|
|
20
|
+
export const ADMIN_REQUEST_MS = 2 * 60_000;
|
|
21
|
+
export const ADMIN_DELIVER_MS = 60_000;
|
|
22
|
+
/** How long a row of the admin's sign-in list is kept: 30 days. */
|
|
23
|
+
export const ADMIN_LOGIN_KEEP_MS = 30 * 24 * 60 * 60_000;
|
|
24
|
+
/** How long the starter cookie lives: a wallet's request must be answered within it. */
|
|
25
|
+
export const ADMIN_STARTER_MAX_AGE_S = 30 * 60;
|
|
26
|
+
/** The limits of the routes (calls per window). `signin` uses the game's `limit` hook; the rest count in this process's memory. */
|
|
27
|
+
export const ADMIN_SIGNIN_LIMITS = {
|
|
28
|
+
/** An admin sign-in start, per visitor (hook). The key is the player's (`signin|<visitor>`): one count for both, as the starter had. */
|
|
29
|
+
signin: { limit: 20, windowMs: 10 * 60_000 },
|
|
30
|
+
/** The browser's checks (every 2 s), per IP address (memory). */
|
|
31
|
+
poll: { limit: 90, windowMs: 60_000 },
|
|
32
|
+
/** Berry Wallet's GET and POST and Nautilus's answer, per IP address (memory): the wallet's own phone sends them. */
|
|
33
|
+
wallet: { limit: 30, windowMs: 60_000 },
|
|
34
|
+
/** 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). */
|
|
35
|
+
nanchatRoute: { limit: 120, windowMs: 60_000 },
|
|
36
|
+
nanchatAll: { limit: 600, windowMs: 10 * 60_000 },
|
|
37
|
+
nanchatNonce: { limit: 5, windowMs: 10 * 60_000 },
|
|
38
|
+
/** The biggest body the routes read. */
|
|
39
|
+
bodyMax: 8192,
|
|
40
|
+
};
|
|
41
|
+
/** A token, a starter value: 32 random bytes as 64 hex characters. */
|
|
42
|
+
export const TOKEN_PATTERN = /^[0-9a-f]{64}$/;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nano133/nanoterra",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Nanoterra for a creator's game, in one package: the player's sign-in ticket, the player's character (a toon body on the island's skeleton), the looks ladder, the admin, the friends list, an options menu, emotes, the player's sign-in (a passkey or a wallet app) and a shop that sells looks for Nano with no key on the server.",
|
|
3
|
+
"version": "0.11.0",
|
|
4
|
+
"description": "Nanoterra for a creator's game, in one package: the player's sign-in ticket, the player's character (a toon body on the island's skeleton), the looks ladder, the admin and its wallet sign-in, the friends list, an options menu, emotes, the player's sign-in (a passkey or a wallet app) and a shop that sells looks for Nano with no key on the server.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -19,6 +19,13 @@
|
|
|
19
19
|
"./admin/firestore": { "types": "./dist/admin/adapters/firestore.d.ts", "import": "./dist/admin/adapters/firestore.js" },
|
|
20
20
|
"./admin/panel": { "types": "./dist/admin/panel/index.d.ts", "import": "./dist/admin/panel/index.js" },
|
|
21
21
|
"./admin/style.css": "./src/admin/panel/style.css",
|
|
22
|
+
"./admin-signin": { "types": "./dist/admin-signin/index.d.ts", "import": "./dist/admin-signin/index.js" },
|
|
23
|
+
"./admin-signin/conformance": { "types": "./dist/admin-signin/conformance.d.ts", "import": "./dist/admin-signin/conformance.js" },
|
|
24
|
+
"./admin-signin/d1": { "types": "./dist/admin-signin/adapters/d1.d.ts", "import": "./dist/admin-signin/adapters/d1.js" },
|
|
25
|
+
"./admin-signin/d1.sql": "./src/admin-signin/adapters/d1.sql",
|
|
26
|
+
"./admin-signin/firestore": { "types": "./dist/admin-signin/adapters/firestore.d.ts", "import": "./dist/admin-signin/adapters/firestore.js" },
|
|
27
|
+
"./admin-signin/panel": { "types": "./dist/admin-signin/panel/index.d.ts", "import": "./dist/admin-signin/panel/index.js" },
|
|
28
|
+
"./admin-signin/style.css": "./src/player-signin/panel/style.css",
|
|
22
29
|
"./friends": { "types": "./dist/friends/index.d.ts", "import": "./dist/friends/index.js" },
|
|
23
30
|
"./friends/conformance": { "types": "./dist/friends/conformance.d.ts", "import": "./dist/friends/conformance.js" },
|
|
24
31
|
"./friends/d1": { "types": "./dist/friends/adapters/d1.d.ts", "import": "./dist/friends/adapters/d1.js" },
|
package/src/admin/conformance.ts
CHANGED
|
@@ -62,7 +62,14 @@ export type ConformanceHost = {
|
|
|
62
62
|
endLogin?(who: Who): Promise<void>;
|
|
63
63
|
};
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
/**
|
|
66
|
+
* One test case. `timeoutMs`, when set, is the time the case may need on a slow machine (each heavy case sends a few hundred requests to the game):
|
|
67
|
+
* pass it to the runner, `it(c.name, c.run, c.timeoutMs)` (vitest) or `test(c.name, { timeout: c.timeoutMs }, c.run)` (node:test).
|
|
68
|
+
*/
|
|
69
|
+
export type ConformanceCase = { name: string; run: () => Promise<void>; timeoutMs?: number };
|
|
70
|
+
|
|
71
|
+
/** The time a heavy case may take (every visitor, every method, many spellings or origins of one route). */
|
|
72
|
+
export const HEAVY_CASE_MS = 120_000;
|
|
66
73
|
|
|
67
74
|
const REFUSALS: { who: Who; status: number; reason?: string; words: string }[] = [
|
|
68
75
|
{ who: "signed_out", status: 401, words: "a visitor who is signed out" },
|
|
@@ -101,7 +108,7 @@ const DATA_WORDS = /"orders"|"players"|"totals"|"counts"|"character"|"signin"|"f
|
|
|
101
108
|
|
|
102
109
|
export function adminConformance(host: ConformanceHost): ConformanceCase[] {
|
|
103
110
|
const cases: ConformanceCase[] = [];
|
|
104
|
-
const add = (name: string, run: () => Promise<void
|
|
111
|
+
const add = (name: string, run: () => Promise<void>, timeoutMs?: number) => cases.push(timeoutMs ? { name, run, timeoutMs } : { name, run });
|
|
105
112
|
const good = (extra: Record<string, string> = {}) => ({ Origin: host.origin, "Content-Type": "application/json", ...extra });
|
|
106
113
|
const body = (r: { method: string }) => (r.method === "POST" ? "{}" : undefined);
|
|
107
114
|
const NOT_OWNER = REFUSALS.map((r) => r.who);
|
|
@@ -145,7 +152,7 @@ export function adminConformance(host: ConformanceHost): ConformanceCase[] {
|
|
|
145
152
|
}
|
|
146
153
|
}
|
|
147
154
|
}
|
|
148
|
-
});
|
|
155
|
+
}, HEAVY_CASE_MS);
|
|
149
156
|
|
|
150
157
|
add("an unknown path under the base is refused like any admin path (so the routes are not leaked): the same refusal for a visitor, 404 for the owner", async () => {
|
|
151
158
|
const path = `${host.basePath}/no-such-page`;
|
|
@@ -187,12 +194,10 @@ export function adminConformance(host: ConformanceHost): ConformanceCase[] {
|
|
|
187
194
|
];
|
|
188
195
|
};
|
|
189
196
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
for (const path of spellings(route.path)) {
|
|
194
|
-
if (seen.has(path)) continue;
|
|
195
|
-
seen.add(path);
|
|
197
|
+
// One case for each route (not one for all of them): each sends every visitor with every method, so a game with many routes stays inside a runner's time.
|
|
198
|
+
for (const route of host.routes) {
|
|
199
|
+
add(`other spellings of ${route.method} ${route.path} never open anything for a visitor, with any method`, async () => {
|
|
200
|
+
for (const path of new Set(spellings(route.path))) {
|
|
196
201
|
for (const who of NOT_OWNER) {
|
|
197
202
|
for (const method of new Set([route.method, "GET", "POST", "OPTIONS", "HEAD"])) {
|
|
198
203
|
const got = await read(await send(who, { method, path, headers: good(), body: body({ method }) }, false));
|
|
@@ -201,14 +206,14 @@ export function adminConformance(host: ConformanceHost): ConformanceCase[] {
|
|
|
201
206
|
}
|
|
202
207
|
}
|
|
203
208
|
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
209
|
+
}, HEAVY_CASE_MS);
|
|
210
|
+
}
|
|
206
211
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
+
const own = new URL(host.origin);
|
|
213
|
+
const origins = ["https://evil.example", "null", `${own.protocol}//evil.${own.host}`, `${own.protocol}//${own.host.replace(/^[^.]+\./, "sibling.")}`, `${own.protocol}//${own.host}.evil.example`];
|
|
214
|
+
const WHO: Who[] = ["owner", ...NOT_OWNER];
|
|
215
|
+
for (const route of host.routes) {
|
|
216
|
+
add(`a request from another page to ${route.method} ${route.path} never gets a CORS header, and never the data: a foreign Origin (another site, 'null', a sibling subdomain), with every method, for the owner and for every visitor`, async () => {
|
|
212
217
|
for (const origin of origins) {
|
|
213
218
|
for (const who of WHO) {
|
|
214
219
|
for (const method of new Set([route.method, "GET", "OPTIONS", "HEAD"])) {
|
|
@@ -224,8 +229,8 @@ export function adminConformance(host: ConformanceHost): ConformanceCase[] {
|
|
|
224
229
|
const got = await read(await send("owner", { method: route.method, path: route.path, headers: { "Sec-Fetch-Site": site, "Content-Type": "application/json" }, body: body(route) }));
|
|
225
230
|
check(got.status === 403, `${route.method} ${route.path} as owner with Sec-Fetch-Site ${site}: expected 403, got ${got.status}`);
|
|
226
231
|
}
|
|
227
|
-
}
|
|
228
|
-
}
|
|
232
|
+
}, HEAVY_CASE_MS);
|
|
233
|
+
}
|
|
229
234
|
|
|
230
235
|
add("an old login that is still valid in the store is refused EVERY time it is used, not only the first: a game must not renew a login on each read", async () => {
|
|
231
236
|
for (const route of host.routes) {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
-- The admin sign-in tables of "@nano133/nanoterra/admin-signin/d1". Add this file to the game's migrations (for example
|
|
2
|
+
-- migrations/0009_admin_signin.sql) and run `wrangler d1 migrations apply`. The adapter reads and writes only these three tables, and only the
|
|
3
|
+
-- ADMIN rows of the first two (scope = 'admin').
|
|
4
|
+
--
|
|
5
|
+
-- The game starter has all three already (migrations 0001, 0002, 0003, 0005 and 0006): it needs NO migration, and `IF NOT EXISTS` leaves its tables and
|
|
6
|
+
-- rows as they are if it runs this file anyway. A game that has the player sign-in's d1.sql has the first two: this file adds `admin_logins`.
|
|
7
|
+
-- Times are milliseconds since 1970 (Date.now()).
|
|
8
|
+
|
|
9
|
+
-- Wallet sign-in requests (the player's and the admin's: `scope` says whose). An admin request lives 2 minutes; the clean-up deletes it 2 hours after it ends.
|
|
10
|
+
CREATE TABLE IF NOT EXISTS signin_requests (
|
|
11
|
+
id TEXT PRIMARY KEY, -- the store key: the request's id (Berry Wallet, Nautilus) or the SHA-256 of its nonce (NanChat, players only)
|
|
12
|
+
rid TEXT, -- the browser's id for its checks
|
|
13
|
+
way TEXT NOT NULL DEFAULT 'berry', -- berry | nautilus | nanchat
|
|
14
|
+
starter TEXT NOT NULL, -- the SHA-256 of the starting browser's cookie ("admin:" and the cookie for an admin request)
|
|
15
|
+
status TEXT NOT NULL, -- waiting | signedin
|
|
16
|
+
expires_at INTEGER NOT NULL,
|
|
17
|
+
nonce TEXT,
|
|
18
|
+
issued_at INTEGER,
|
|
19
|
+
label TEXT, -- Nautilus: the label it shows and signs; Berry Wallet's admin request: "admin" or "admin:<country>"
|
|
20
|
+
account TEXT, -- the address that signed
|
|
21
|
+
delivered INTEGER NOT NULL DEFAULT 0, -- 1 once a session was made from it (or "Sign out everywhere" ended it)
|
|
22
|
+
scope TEXT NOT NULL DEFAULT 'play' -- 'play' (a player's) or 'admin' (the admin's: the only rows this adapter reads)
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS signin_requests_by_rid ON signin_requests (rid);
|
|
25
|
+
|
|
26
|
+
-- Sessions (the player's and the admin's). Only a hash of the cookie's token is stored: for an admin session the SHA-256 of "admin:" and the token.
|
|
27
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
28
|
+
id_hash TEXT PRIMARY KEY,
|
|
29
|
+
address TEXT NOT NULL,
|
|
30
|
+
created_at INTEGER NOT NULL,
|
|
31
|
+
expires_at INTEGER NOT NULL,
|
|
32
|
+
via TEXT NOT NULL DEFAULT 'wallet', -- wallet | passkey | nanoterra (an admin session: wallet)
|
|
33
|
+
scope TEXT NOT NULL DEFAULT 'play' -- 'play' (a player's) or 'admin' (one day)
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS sessions_by_expiry ON sessions (expires_at);
|
|
36
|
+
|
|
37
|
+
-- The admin's sign-in list (the Sign-ins card of /admin): the time, the rough country and a short browser name. No address, no IP address and no browser
|
|
38
|
+
-- text. A row is kept 30 days.
|
|
39
|
+
CREATE TABLE IF NOT EXISTS admin_logins (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
at INTEGER NOT NULL, -- ms since 1970
|
|
42
|
+
country TEXT, -- two capital letters from the request's country header, or NULL
|
|
43
|
+
browser TEXT NOT NULL -- a short name from fixed lists: "Chrome on macOS"
|
|
44
|
+
);
|
|
45
|
+
CREATE INDEX IF NOT EXISTS admin_logins_by_time ON admin_logins (at);
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// The admin sign-in's store for a game on Cloudflare D1, on the game starter's OWN tables and columns: `signin_requests` and `sessions` (their admin
|
|
2
|
+
// rows, scope = 'admin') and `admin_logins`. A starter moves onto it with no migration, and every creator who is signed in to /admin stays signed in.
|
|
3
|
+
// A new game adds ./d1.sql to its migrations ("@nano133/nanoterra/admin-signin/d1.sql": the same tables, `IF NOT EXISTS`).
|
|
4
|
+
//
|
|
5
|
+
// import { createD1AdminSignin } from "@nano133/nanoterra/admin-signin/d1";
|
|
6
|
+
// const store = createD1AdminSignin(env.DB);
|
|
7
|
+
//
|
|
8
|
+
// It reads and writes ONLY the admin's rows (scope = 'admin'): a game whose players sign in through the same tables (the player sign-in's scope 'play')
|
|
9
|
+
// keeps its rows, and this adapter never reads, delivers, ends or deletes one. D1 has no transaction that reads and then writes, so each change is ONE
|
|
10
|
+
// statement that holds its own check, and a delivery and its session are one batch (the session is written only when the delivery changed a row).
|
|
11
|
+
// "Sign out everywhere" is the same two statements as the admin store's (`createD1Store(db, { logins: true })`): either one may run it.
|
|
12
|
+
|
|
13
|
+
import type { D1Like } from "../../admin/adapters/d1.js";
|
|
14
|
+
import { ADMIN_LOGIN_KEEP_MS, ADMIN_WAYS, type AdminSessionRecord, type AdminSigninStore, type AdminWay, type RequestStoreLike, type SigninRequest } from "../types.js";
|
|
15
|
+
|
|
16
|
+
export type { D1Like, D1StatementLike } from "../../admin/adapters/d1.js";
|
|
17
|
+
|
|
18
|
+
/** The tables' names. Default: the game starter's. A game with other names changes d1.sql to match. */
|
|
19
|
+
export type D1AdminSigninTables = { requests?: string; sessions?: string; logins?: string };
|
|
20
|
+
|
|
21
|
+
type Row = { id: string; rid: string | null; starter: string; status: string; expires_at: number; nonce: string | null; issued_at: number | null; label: string | null; account: string | null };
|
|
22
|
+
|
|
23
|
+
const toRequest = (r: Row): SigninRequest => ({
|
|
24
|
+
id: r.rid ?? r.id,
|
|
25
|
+
starter: r.starter,
|
|
26
|
+
status: r.status === "signedin" ? "signedin" : "waiting",
|
|
27
|
+
expiresAt: Number(r.expires_at),
|
|
28
|
+
...(r.label ? { label: r.label } : {}),
|
|
29
|
+
...(r.nonce ? { nonce: r.nonce } : {}),
|
|
30
|
+
...(r.issued_at ? { issuedAt: Number(r.issued_at) } : {}),
|
|
31
|
+
...(r.account ? { account: r.account } : {}),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
35
|
+
const changes = (res: unknown): number => Number((res as { meta?: { changes?: number } } | undefined)?.meta?.changes ?? 0);
|
|
36
|
+
|
|
37
|
+
export function createD1AdminSignin(db: D1Like, tables: D1AdminSigninTables = {}): AdminSigninStore {
|
|
38
|
+
const T = { requests: tables.requests ?? "signin_requests", sessions: tables.sessions ?? "sessions", logins: tables.logins ?? "admin_logins" };
|
|
39
|
+
for (const n of Object.values(T)) if (!NAME.test(n)) throw new Error(`not a table name: ${n}`);
|
|
40
|
+
const COLS = "id, rid, starter, status, expires_at, nonce, issued_at, label, account";
|
|
41
|
+
|
|
42
|
+
const stores = new Map<AdminWay, RequestStoreLike>();
|
|
43
|
+
for (const way of ADMIN_WAYS) {
|
|
44
|
+
stores.set(way, {
|
|
45
|
+
async create(key, r) {
|
|
46
|
+
// The starter's own insert: `scope` is written when the request is created, so a request started for the admin is the admin's for good.
|
|
47
|
+
await db
|
|
48
|
+
.prepare(`INSERT INTO ${T.requests} (id, rid, way, starter, status, expires_at, nonce, issued_at, label, scope) VALUES (?, ?, ?, ?, 'waiting', ?, ?, ?, ?, 'admin')`)
|
|
49
|
+
.bind(key, r.id, way, r.starter, r.expiresAt, r.nonce ?? null, r.issuedAt ?? null, r.label ?? null)
|
|
50
|
+
.run();
|
|
51
|
+
},
|
|
52
|
+
async get(key) {
|
|
53
|
+
const r = await db.prepare(`SELECT ${COLS} FROM ${T.requests} WHERE id = ? AND way = ? AND scope = 'admin'`).bind(key, way).first<Row>();
|
|
54
|
+
return r ? toRequest(r) : null;
|
|
55
|
+
},
|
|
56
|
+
async find(id) {
|
|
57
|
+
const r = await db.prepare(`SELECT ${COLS} FROM ${T.requests} WHERE rid = ? AND way = ? AND scope = 'admin'`).bind(id, way).first<Row>();
|
|
58
|
+
return r ? { key: r.id, request: toRequest(r) } : null;
|
|
59
|
+
},
|
|
60
|
+
async finish(key, account) {
|
|
61
|
+
return changes(await db.prepare(`UPDATE ${T.requests} SET status = 'signedin', account = ? WHERE id = ? AND way = ? AND status = 'waiting' AND scope = 'admin'`).bind(account, key, way).run()) === 1;
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
requests: (way) => {
|
|
68
|
+
const s = stores.get(way);
|
|
69
|
+
if (!s) throw new Error(`no such way: ${String(way)}`);
|
|
70
|
+
return s;
|
|
71
|
+
},
|
|
72
|
+
async deliver(way, key, s) {
|
|
73
|
+
// The starter's batch: the delivery, and the session only when the delivery changed a row.
|
|
74
|
+
const done = await db.batch([
|
|
75
|
+
db.prepare(`UPDATE ${T.requests} SET delivered = 1 WHERE id = ? AND way = ? AND delivered = 0 AND status = 'signedin' AND scope = 'admin'`).bind(key, way),
|
|
76
|
+
db.prepare(`INSERT INTO ${T.sessions} (id_hash, address, created_at, expires_at, via, scope) SELECT ?, ?, ?, ?, ?, 'admin' WHERE changes() = 1`).bind(s.idHash, s.address, s.createdAt, s.expiresAt, s.via),
|
|
77
|
+
]);
|
|
78
|
+
return changes(done[0]) === 1;
|
|
79
|
+
},
|
|
80
|
+
async session(idHash, now) {
|
|
81
|
+
const r = await db
|
|
82
|
+
.prepare(`SELECT id_hash, address, created_at, expires_at, via FROM ${T.sessions} WHERE id_hash = ? AND expires_at > ? AND scope = 'admin'`)
|
|
83
|
+
.bind(idHash, now)
|
|
84
|
+
.first<{ id_hash: string; address: string; created_at: number; expires_at: number; via: string }>();
|
|
85
|
+
return r ? ({ idHash: r.id_hash, address: r.address, createdAt: Number(r.created_at), expiresAt: Number(r.expires_at), via: String(r.via) } satisfies AdminSessionRecord) : null;
|
|
86
|
+
},
|
|
87
|
+
async endSession(idHash) {
|
|
88
|
+
await db.prepare(`DELETE FROM ${T.sessions} WHERE id_hash = ? AND scope = 'admin'`).bind(idHash).run();
|
|
89
|
+
},
|
|
90
|
+
async signOutEverywhere() {
|
|
91
|
+
const done = await db.batch([
|
|
92
|
+
db.prepare(`DELETE FROM ${T.sessions} WHERE scope = 'admin'`),
|
|
93
|
+
db.prepare(`UPDATE ${T.requests} SET delivered = 1, expires_at = 0 WHERE scope = 'admin' AND delivered = 0`),
|
|
94
|
+
]);
|
|
95
|
+
return changes(done[0]);
|
|
96
|
+
},
|
|
97
|
+
async recordLogin(login) {
|
|
98
|
+
await db.batch([
|
|
99
|
+
db.prepare(`INSERT INTO ${T.logins} (at, country, browser) VALUES (?, ?, ?)`).bind(login.at, login.country, login.browser),
|
|
100
|
+
db.prepare(`DELETE FROM ${T.logins} WHERE at < ?`).bind(login.at - ADMIN_LOGIN_KEEP_MS),
|
|
101
|
+
]);
|
|
102
|
+
},
|
|
103
|
+
async recentLogins(limit) {
|
|
104
|
+
const n = Math.min(Math.max(Math.floor(Number(limit)) || 0, 0), 50);
|
|
105
|
+
const rows = (await db.prepare(`SELECT at, country, browser FROM ${T.logins} ORDER BY at DESC, id DESC LIMIT ?`).bind(n).all<{ at: number; country: string | null; browser: string }>()).results;
|
|
106
|
+
return rows.map((r) => ({ at: Number(r.at), country: r.country, browser: r.browser }));
|
|
107
|
+
},
|
|
108
|
+
async clean(now) {
|
|
109
|
+
// The starter's clean-up of its admin rows (its `cleanUp`, without the game's own `hits`).
|
|
110
|
+
await db.batch([
|
|
111
|
+
db.prepare(`DELETE FROM ${T.requests} WHERE expires_at < ? AND scope = 'admin'`).bind(now - 2 * 3_600_000),
|
|
112
|
+
db.prepare(`DELETE FROM ${T.sessions} WHERE expires_at < ? AND scope = 'admin'`).bind(now),
|
|
113
|
+
db.prepare(`DELETE FROM ${T.logins} WHERE at < ?`).bind(now - ADMIN_LOGIN_KEEP_MS),
|
|
114
|
+
]);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|