@nano133/nanoterra 0.11.0 → 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.
- package/CHANGELOG.md +26 -0
- package/README.md +84 -11
- package/ai/SPEC.md +11 -4
- package/dist/admin/guard.d.ts +9 -1
- package/dist/admin/guard.js +12 -4
- package/dist/admin/panel/card.d.ts +5 -0
- package/dist/admin/panel/card.js +3 -0
- package/dist/admin/panel/icons.d.ts +9 -0
- package/dist/admin/panel/icons.js +1 -0
- package/dist/admin/panel/index.d.ts +1 -1
- package/dist/admin/panel/mount.d.ts +7 -0
- package/dist/admin/panel/mount.js +4 -1
- package/dist/admin-signin/adapters/d1.d.ts +3 -1
- package/dist/admin-signin/adapters/d1.js +58 -3
- package/dist/admin-signin/adapters/firestore.d.ts +5 -2
- package/dist/admin-signin/adapters/firestore.js +74 -5
- package/dist/admin-signin/conformance.d.ts +8 -1
- package/dist/admin-signin/conformance.js +88 -3
- package/dist/admin-signin/handler.d.ts +7 -0
- package/dist/admin-signin/handler.js +134 -6
- package/dist/admin-signin/index.d.ts +2 -2
- package/dist/admin-signin/index.js +3 -2
- package/dist/admin-signin/memory.d.ts +6 -2
- package/dist/admin-signin/memory.js +47 -1
- package/dist/admin-signin/panel/index.d.ts +3 -0
- package/dist/admin-signin/panel/index.js +4 -2
- package/dist/admin-signin/panel/passkeys.d.ts +43 -0
- package/dist/admin-signin/panel/passkeys.js +202 -0
- package/dist/admin-signin/panel/view.d.ts +12 -0
- package/dist/admin-signin/panel/view.js +48 -1
- package/dist/admin-signin/types.d.ts +57 -7
- package/dist/admin-signin/types.js +20 -3
- package/package.json +1 -1
- package/src/admin/guard.ts +19 -5
- package/src/admin/panel/card.ts +5 -0
- package/src/admin/panel/icons.ts +1 -0
- package/src/admin/panel/index.ts +1 -1
- package/src/admin/panel/mount.ts +11 -1
- package/src/admin/panel/style.css +44 -0
- package/src/admin-signin/adapters/d1.sql +20 -3
- package/src/admin-signin/adapters/d1.ts +58 -5
- package/src/admin-signin/adapters/firestore.ts +73 -6
- package/src/admin-signin/conformance.ts +99 -3
- package/src/admin-signin/handler.ts +131 -4
- package/src/admin-signin/index.ts +7 -2
- package/src/admin-signin/memory.ts +43 -2
- package/src/admin-signin/panel/index.ts +6 -2
- package/src/admin-signin/panel/passkeys.ts +245 -0
- package/src/admin-signin/panel/view.ts +63 -1
- package/src/admin-signin/types.ts +62 -11
- package/src/player-signin/panel/style.css +3 -2
|
@@ -2,14 +2,18 @@
|
|
|
2
2
|
// own store that passes adminSigninStoreConformance).
|
|
3
3
|
|
|
4
4
|
import type { AdminLogin } from "../admin/store.js";
|
|
5
|
-
import { ADMIN_LOGIN_KEEP_MS, ADMIN_WAYS, type AdminSessionRecord, type AdminSigninStore, type AdminWay, type RequestStoreLike, type SigninRequest } from "./types.js";
|
|
5
|
+
import { ADMIN_LOGIN_KEEP_MS, ADMIN_PASSKEY_LIMIT, ADMIN_WAYS, type AdminPasskey, type AdminSessionRecord, type AdminSigninStore, type AdminWay, type RequestStoreLike, type SigninRequest } from "./types.js";
|
|
6
6
|
|
|
7
7
|
type RequestRow = SigninRequest & { way: AdminWay; delivered: boolean };
|
|
8
8
|
|
|
9
|
-
export type MemoryAdminSignin = AdminSigninStore & {
|
|
9
|
+
export type MemoryAdminSignin = Required<AdminSigninStore> & {
|
|
10
10
|
readonly requestRows: Map<string, RequestRow>;
|
|
11
11
|
readonly sessionRows: Map<string, AdminSessionRecord>;
|
|
12
12
|
readonly loginRows: AdminLogin[];
|
|
13
|
+
/** The owner's passkeys: owner → the links, oldest first. */
|
|
14
|
+
readonly passkeyRows: Map<string, AdminPasskey[]>;
|
|
15
|
+
/** The used passkey signatures: key → until (ms). */
|
|
16
|
+
readonly onceRows: Map<string, number>;
|
|
13
17
|
};
|
|
14
18
|
|
|
15
19
|
const copy = <T>(v: T): T => structuredClone(v);
|
|
@@ -18,6 +22,8 @@ export function createMemoryAdminSignin(): MemoryAdminSignin {
|
|
|
18
22
|
const requestRows = new Map<string, RequestRow>();
|
|
19
23
|
const sessionRows = new Map<string, AdminSessionRecord>();
|
|
20
24
|
const loginRows: AdminLogin[] = [];
|
|
25
|
+
const passkeyRows = new Map<string, AdminPasskey[]>();
|
|
26
|
+
const onceRows = new Map<string, number>();
|
|
21
27
|
const strip = ({ way: _way, delivered: _delivered, ...r }: RequestRow): SigninRequest => copy(r);
|
|
22
28
|
|
|
23
29
|
const stores = new Map<AdminWay, RequestStoreLike>();
|
|
@@ -49,6 +55,8 @@ export function createMemoryAdminSignin(): MemoryAdminSignin {
|
|
|
49
55
|
requestRows,
|
|
50
56
|
sessionRows,
|
|
51
57
|
loginRows,
|
|
58
|
+
passkeyRows,
|
|
59
|
+
onceRows,
|
|
52
60
|
requests: (way) => {
|
|
53
61
|
const s = stores.get(way);
|
|
54
62
|
if (!s) throw new Error(`no such way: ${String(way)}`);
|
|
@@ -95,6 +103,39 @@ export function createMemoryAdminSignin(): MemoryAdminSignin {
|
|
|
95
103
|
for (const [k, r] of requestRows) if (r.expiresAt < now - 2 * 3_600_000) requestRows.delete(k);
|
|
96
104
|
for (const [k, s] of sessionRows) if (s.expiresAt < now) sessionRows.delete(k);
|
|
97
105
|
for (let i = loginRows.length - 1; i >= 0; i--) if (loginRows[i].at < now - ADMIN_LOGIN_KEEP_MS) loginRows.splice(i, 1);
|
|
106
|
+
for (const [k, until] of onceRows) if (until <= now) onceRows.delete(k);
|
|
107
|
+
},
|
|
108
|
+
async createSession(session) {
|
|
109
|
+
if (sessionRows.has(session.idHash)) throw new Error("a session with this id exists");
|
|
110
|
+
sessionRows.set(session.idHash, copy(session));
|
|
111
|
+
},
|
|
112
|
+
async linkPasskey(owner, address, at) {
|
|
113
|
+
const list = passkeyRows.get(owner) ?? [];
|
|
114
|
+
if (list.some((p) => p.address === address)) return "exists";
|
|
115
|
+
if (list.length >= ADMIN_PASSKEY_LIMIT) return "full";
|
|
116
|
+
passkeyRows.set(owner, [...list, { address, createdAt: at }]);
|
|
117
|
+
return "linked";
|
|
118
|
+
},
|
|
119
|
+
async unlinkPasskey(owner, address) {
|
|
120
|
+
const list = passkeyRows.get(owner) ?? [];
|
|
121
|
+
const had = list.some((p) => p.address === address);
|
|
122
|
+
if (had) passkeyRows.set(owner, list.filter((p) => p.address !== address));
|
|
123
|
+
// The passkey's admin sessions end with its link.
|
|
124
|
+
for (const [k, s] of sessionRows) if (s.via === "passkey" && s.address === address) sessionRows.delete(k);
|
|
125
|
+
return had;
|
|
126
|
+
},
|
|
127
|
+
async passkeys(owner) {
|
|
128
|
+
return copy(passkeyRows.get(owner) ?? []);
|
|
129
|
+
},
|
|
130
|
+
async linked(owner, address) {
|
|
131
|
+
return (passkeyRows.get(owner) ?? []).some((p) => p.address === address);
|
|
132
|
+
},
|
|
133
|
+
async useOnce(key, ttlMs) {
|
|
134
|
+
const now = Date.now();
|
|
135
|
+
const until = onceRows.get(key);
|
|
136
|
+
if (until !== undefined && until > now) return false;
|
|
137
|
+
onceRows.set(key, now + ttlMs);
|
|
138
|
+
return true;
|
|
98
139
|
},
|
|
99
140
|
};
|
|
100
141
|
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
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
|
|
3
|
-
// sheet's stylesheet: the two sign-ins look the same). No
|
|
2
|
+
// and `adminSignOut()` its `signOut`; `adminSigninView` is the content alone; `ownerPasskeys()` is the "Owner passkeys" card for `mountAdmin`'s `cards`
|
|
3
|
+
// (since 0.12.0). Add "@nano133/nanoterra/admin-signin/style.css" to the page (the player sheet's stylesheet: the two sign-ins look the same). No Three.js;
|
|
4
|
+
// the passkey code (@nano133/signin/passkey and /purse) is loaded only when a passkey is used; the server part is "@nano133/nanoterra/admin-signin".
|
|
4
5
|
|
|
5
6
|
export { ADMIN_NANCHAT_NOTE, ADMIN_SIGNIN_INTRO, adminSignIn, adminSignOut, adminSigninView } from "./view.js";
|
|
7
|
+
export { ownerPasskeys, passkeyAdminSignIn, passkeyFaultText } from "./passkeys.js";
|
|
8
|
+
export type { AdminPasskeyOptions, PasskeyList } from "./passkeys.js";
|
|
9
|
+
export type { AdminCard } from "../../admin/panel/card.js";
|
|
6
10
|
export type { AdminSigninView, AdminSigninViewOptions } from "./view.js";
|
|
7
11
|
export { ADMIN_SIGNIN_BASE } from "../types.js";
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// The owner's passkeys in the browser (since 0.12.0): the "Passkey" way of the admin's sign-in, and the "Owner passkeys" card for /admin (`ownerPasskeys()`,
|
|
2
|
+
// a card for `mountAdmin`'s `cards`). A passkey is only a key to /admin: the money stays in the owner's wallet.
|
|
3
|
+
//
|
|
4
|
+
// - Sign in: the passkey purse (the game's FROZEN scheme, the player sheet's) signs "ADMIN of <host>: sign in as <address> at <ms>"; the server lets it in
|
|
5
|
+
// only while the passkey is linked to the game's address.
|
|
6
|
+
// - Add: only with a WALLET admin session. A new passkey is made (or one the owner has is used), and it signs "Link this passkey to the ADMIN of <host>:
|
|
7
|
+
// ...": the server writes the link only with both proofs, the wallet session and this signature.
|
|
8
|
+
// - Remove: only with a wallet admin session; the passkey's admin sessions end too.
|
|
9
|
+
//
|
|
10
|
+
// The passkey code (@nano133/signin/passkey) and the purse's signing code (@nano133/signin/purse) are loaded only when a passkey is used: a game without
|
|
11
|
+
// passkeys never loads them. The seed lives in local variables of one press only: never in storage, a log, an error text or an address.
|
|
12
|
+
|
|
13
|
+
import type { NewPasskey, PasskeyScheme, PasskeySetup } from "@nano133/signin/passkey";
|
|
14
|
+
import { ApiError, createApi, type Api } from "../../admin/panel/api.js";
|
|
15
|
+
import { h, shortAddress } from "../../admin/panel/dom.js";
|
|
16
|
+
import { icon } from "../../admin/panel/icons.js";
|
|
17
|
+
import type { AdminCard } from "../../admin/panel/card.js";
|
|
18
|
+
import { checkScheme } from "../../player-signin/scheme-check.js";
|
|
19
|
+
import { ADMIN_SIGNIN_BASE, adminLinkDomain, adminPasskeyDomain, type AdminPasskey } from "../types.js";
|
|
20
|
+
|
|
21
|
+
export type AdminPasskeyOptions = {
|
|
22
|
+
/** The game's FROZEN passkey scheme: the same one the player sheet takes (see "/player-signin": checkScheme, schemeVector). */
|
|
23
|
+
scheme: PasskeyScheme;
|
|
24
|
+
/** The game's name: the device shows it next to a new passkey ("Coin Bees admin · 1 Nov 2026"). */
|
|
25
|
+
name: string;
|
|
26
|
+
/** The passkeys' relying party id: the game's domain. Default: the page's host name. */
|
|
27
|
+
rpId?: string;
|
|
28
|
+
/** Where the admin sign-in's routes are. Default "/api/admin-signin" (ADMIN_SIGNIN_BASE). */
|
|
29
|
+
base?: string;
|
|
30
|
+
/** The `fetch` to use (default: the page's). */
|
|
31
|
+
fetch?: typeof fetch;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** The answer of `POST {base}/passkeys` (and of a link or a removal). */
|
|
35
|
+
export type PasskeyList = { passkeys: AdminPasskey[]; limit: number; via: string; canChange: boolean; you: string };
|
|
36
|
+
|
|
37
|
+
/** What the owner reads when a passkey prompt fails, by the fault's code (@nano133/signin/passkey's PasskeyFault). */
|
|
38
|
+
export function passkeyFaultText(e: unknown): string {
|
|
39
|
+
const code = (e as { code?: unknown } | null)?.code;
|
|
40
|
+
const name = (e as { name?: unknown } | null)?.name;
|
|
41
|
+
const c = typeof code === "string" ? code : name === "NotAllowedError" || name === "AbortError" ? "cancelled" : name === "SecurityError" ? "wrong-host" : name === "NotSupportedError" ? "unsupported" : name === "InvalidStateError" ? "exists" : "failed";
|
|
42
|
+
if (c === "cancelled") return "The passkey was closed. Try again.";
|
|
43
|
+
if (c === "no-prf" || c === "other-form" || c === "unsupported") return "This browser or device cannot use a passkey here. Use your wallet.";
|
|
44
|
+
if (c === "not-a-purse") return "That passkey is not one of this game's. Choose another one.";
|
|
45
|
+
if (c === "wrong-host") return "A passkey works only on the game's own address.";
|
|
46
|
+
if (c === "exists") return "This device has a passkey for this game already. Press Use a passkey I have.";
|
|
47
|
+
return "The passkey did not work. Try again.";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const dayText = (ms: number) => new Date(ms).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
|
|
51
|
+
|
|
52
|
+
function setupOf(o: AdminPasskeyOptions): PasskeySetup {
|
|
53
|
+
return { rpId: o.rpId ?? location.hostname, rpName: o.name, scheme: o.scheme, userName: `${o.name} admin · ${dayText(Date.now())}`, exclude: [] };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const apiOf = (o: Pick<AdminPasskeyOptions, "base" | "fetch">): Api => createApi(o.base ?? ADMIN_SIGNIN_BASE, o.fetch ?? ((...a) => fetch(...a)));
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Signs in to /admin with a linked passkey: the device asks for the passkey, the purse signs the ADMIN text, the server checks the link. Resolves with the
|
|
60
|
+
* passkey's address; throws an ApiError (the server's words) or a passkey fault (`passkeyFaultText`).
|
|
61
|
+
*/
|
|
62
|
+
export async function passkeyAdminSignIn(o: AdminPasskeyOptions & { turnstile?: string | null; signal?: AbortSignal }): Promise<{ address: string; linkedTo: string }> {
|
|
63
|
+
checkScheme(o.scheme);
|
|
64
|
+
const { openPasskey } = await import("@nano133/signin/passkey");
|
|
65
|
+
const p = await openPasskey(setupOf(o), o.signal);
|
|
66
|
+
const { signinBody } = await import("@nano133/signin/purse");
|
|
67
|
+
return apiOf(o).post<{ address: string; linkedTo: string }>("/passkey", { ...signinBody(adminPasskeyDomain(location.host), p.seed), ...(o.turnstile ? { turnstile: o.turnstile } : {}) });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The "Owner passkeys" card for /admin: the passkeys linked to the game's address, "Add a passkey" and Remove (both only with a wallet sign-in). Give it to
|
|
72
|
+
* `mountAdmin`'s `cards`; it reads the list each time the owner signs in.
|
|
73
|
+
*
|
|
74
|
+
* mountAdmin(el, { looks, signIn: adminSignIn({ passkeys: true, scheme, name }), signOut: adminSignOut(), cards: [ownerPasskeys({ scheme, name })] });
|
|
75
|
+
*/
|
|
76
|
+
export function ownerPasskeys(options: AdminPasskeyOptions): AdminCard {
|
|
77
|
+
checkScheme(options.scheme);
|
|
78
|
+
const api = apiOf(options);
|
|
79
|
+
let list: PasskeyList | null = null;
|
|
80
|
+
let prompt: AbortController | null = null;
|
|
81
|
+
|
|
82
|
+
const status = h("p", { class: "fine passkey-status", role: "status", "aria-live": "polite" });
|
|
83
|
+
const items = h("ul", { class: "signin-list passkey-list" });
|
|
84
|
+
const note = h("p", { class: "fine" });
|
|
85
|
+
const add = h("div", { class: "passkey-add" });
|
|
86
|
+
const el = h(
|
|
87
|
+
"section",
|
|
88
|
+
{ class: "admin-card owner-passkeys", "aria-labelledby": "n133-passkeys-title" },
|
|
89
|
+
h("h2", { id: "n133-passkeys-title" }, "Owner passkeys"),
|
|
90
|
+
h("p", { class: "fine" }, "A passkey opens this admin page with Face ID, Touch ID or your device PIN, without your wallet. It cannot move money: your money stays in your wallet."),
|
|
91
|
+
items,
|
|
92
|
+
note,
|
|
93
|
+
add,
|
|
94
|
+
status,
|
|
95
|
+
);
|
|
96
|
+
el.hidden = true;
|
|
97
|
+
|
|
98
|
+
const say = (text: string) => (status.textContent = text);
|
|
99
|
+
const key = (text: string, onclick: () => void, kind: "primary" | "plain" = "plain") => h("button", { class: `btn${kind === "primary" ? " btn-primary" : ""}`, type: "button", onclick }, text);
|
|
100
|
+
const busy = (on: boolean) => {
|
|
101
|
+
for (const b of Array.from(el.querySelectorAll("button"))) b.disabled = on;
|
|
102
|
+
el.toggleAttribute("aria-busy", on);
|
|
103
|
+
};
|
|
104
|
+
const words = (e: unknown, fallback: string) => (e instanceof ApiError ? e.message : e && typeof e === "object" && ("code" in e || "name" in e) ? passkeyFaultText(e) : fallback);
|
|
105
|
+
|
|
106
|
+
function draw() {
|
|
107
|
+
if (!list) return;
|
|
108
|
+
const l = list;
|
|
109
|
+
items.replaceChildren(
|
|
110
|
+
...l.passkeys.map((p) => {
|
|
111
|
+
const row = h("li", { class: "passkey-row" });
|
|
112
|
+
const what = h("span", { class: "passkey-what" }, icon("key", 18), h("strong", {}, h("code", { title: p.address }, shortAddress(p.address))), h("span", {}, ` · added ${dayText(p.createdAt)}`), p.address === l.you && l.via === "passkey" ? h("span", { class: "chip" }, "This passkey") : null);
|
|
113
|
+
row.append(what);
|
|
114
|
+
if (l.canChange) row.append(key("Remove", () => confirmRemove(row, p.address)));
|
|
115
|
+
return row;
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
if (!l.passkeys.length) items.append(h("li", { class: "fine" }, "No passkey is linked yet."));
|
|
119
|
+
note.textContent = l.canChange ? `You can link up to ${l.limit} passkeys. Each one proves its key when you add it.` : "You signed in with a passkey. Sign in with your wallet to add or remove a passkey.";
|
|
120
|
+
showAdd();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function showAdd() {
|
|
124
|
+
if (!list?.canChange) return add.replaceChildren();
|
|
125
|
+
const full = list.passkeys.length >= list.limit;
|
|
126
|
+
const b = key("Add a passkey", () => chooseAdd(), "primary");
|
|
127
|
+
b.disabled = full;
|
|
128
|
+
add.replaceChildren(b, full ? h("p", { class: "fine" }, `You have ${list.limit} passkeys. Remove one to add another.`) : "");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function chooseAdd() {
|
|
132
|
+
say("");
|
|
133
|
+
add.replaceChildren(
|
|
134
|
+
h("p", {}, "Make a new passkey on this device, or use a passkey you have for this game."),
|
|
135
|
+
h("div", { class: "passkey-keys" }, key("Make a new passkey", () => void makeNew(), "primary"), key("Use a passkey I have", () => void useMine()), key("Cancel", () => showAdd())),
|
|
136
|
+
);
|
|
137
|
+
add.querySelector("button")?.focus({ preventScroll: true });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Links the passkey of `seed`: it signs the LINK text, and the server writes the link with this wallet session. */
|
|
141
|
+
async function linkSeed(seed: string) {
|
|
142
|
+
const { signinBody } = await import("@nano133/signin/purse");
|
|
143
|
+
list = await api.post<PasskeyList>("/passkey/link", signinBody(adminLinkDomain(location.host), seed));
|
|
144
|
+
draw();
|
|
145
|
+
say("Passkey added. It opens this admin page from now on.");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function makeNew() {
|
|
149
|
+
busy(true);
|
|
150
|
+
say("Making a passkey… Follow your device.");
|
|
151
|
+
prompt = new AbortController();
|
|
152
|
+
try {
|
|
153
|
+
const pk = await import("@nano133/signin/passkey");
|
|
154
|
+
const made = await pk.makePasskey(setupOf(options), prompt.signal);
|
|
155
|
+
await firstOpen(made, false);
|
|
156
|
+
} catch (e) {
|
|
157
|
+
busy(false);
|
|
158
|
+
showAdd();
|
|
159
|
+
say(words(e, "The passkey was not added. Try again."));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The first use of a new passkey gives its seed. Where the browser allows one prompt per press, one more key finishes it. */
|
|
164
|
+
async function firstOpen(made: NewPasskey, pick: boolean): Promise<void> {
|
|
165
|
+
busy(true);
|
|
166
|
+
say("Opening the new passkey…");
|
|
167
|
+
prompt = new AbortController();
|
|
168
|
+
const pk = await import("@nano133/signin/passkey");
|
|
169
|
+
try {
|
|
170
|
+
const p = await pk.firstUse(setupOf(options), made, prompt.signal, pick);
|
|
171
|
+
await linkSeed(p.seed);
|
|
172
|
+
busy(false);
|
|
173
|
+
} catch (e) {
|
|
174
|
+
busy(false);
|
|
175
|
+
const code = (e as { code?: unknown } | null)?.code;
|
|
176
|
+
if (code !== "cancelled" && code !== "failed") throw e;
|
|
177
|
+
add.replaceChildren(h("p", {}, "Your passkey is made. Open it once to add it."), h("div", { class: "passkey-keys" }, key("Open the new passkey", () => void firstOpen(made, true).catch(fault), "primary"), key("Cancel", () => showAdd())));
|
|
178
|
+
say("");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function fault(e: unknown) {
|
|
183
|
+
busy(false);
|
|
184
|
+
showAdd();
|
|
185
|
+
say(words(e, "The passkey was not added. Try again."));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function useMine() {
|
|
189
|
+
busy(true);
|
|
190
|
+
say("Waiting for your passkey…");
|
|
191
|
+
prompt = new AbortController();
|
|
192
|
+
try {
|
|
193
|
+
const pk = await import("@nano133/signin/passkey");
|
|
194
|
+
const p = await pk.openPasskey(setupOf(options), prompt.signal);
|
|
195
|
+
await linkSeed(p.seed);
|
|
196
|
+
busy(false);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
fault(e);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function confirmRemove(row: HTMLElement, address: string) {
|
|
203
|
+
const keys = h(
|
|
204
|
+
"div",
|
|
205
|
+
{ class: "passkey-confirm" },
|
|
206
|
+
h("p", {}, "Remove this passkey? It cannot open this page any more, and its sign-ins end now."),
|
|
207
|
+
key("Yes, remove", () => void remove(address), "primary"),
|
|
208
|
+
key("Cancel", () => draw()),
|
|
209
|
+
);
|
|
210
|
+
row.replaceChildren(row.firstChild!, keys);
|
|
211
|
+
keys.querySelector("button")?.focus({ preventScroll: true });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function remove(address: string) {
|
|
215
|
+
busy(true);
|
|
216
|
+
say("Removing…");
|
|
217
|
+
try {
|
|
218
|
+
list = await api.post<PasskeyList>("/passkey/unlink", { address });
|
|
219
|
+
busy(false);
|
|
220
|
+
draw();
|
|
221
|
+
say("Passkey removed.");
|
|
222
|
+
} catch (e) {
|
|
223
|
+
busy(false);
|
|
224
|
+
draw();
|
|
225
|
+
say(words(e, "The game's server did not answer. Nothing was changed."));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function refresh(): Promise<void> {
|
|
230
|
+
prompt?.abort();
|
|
231
|
+
prompt = null;
|
|
232
|
+
try {
|
|
233
|
+
list = await api.post<PasskeyList>("/passkeys");
|
|
234
|
+
el.hidden = false;
|
|
235
|
+
say("");
|
|
236
|
+
draw();
|
|
237
|
+
} catch {
|
|
238
|
+
// No passkeys on this game (the route is off), or no session that may read them: the card does not show.
|
|
239
|
+
list = null;
|
|
240
|
+
el.hidden = true;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return { el, refresh };
|
|
245
|
+
}
|
|
@@ -5,12 +5,18 @@
|
|
|
5
5
|
//
|
|
6
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
7
|
// key and tile 48 px or more each way. It uses the player sheet's stylesheet ("@nano133/nanoterra/admin-signin/style.css" is the same file).
|
|
8
|
+
//
|
|
9
|
+
// With `passkeys: true` (and the game's frozen `scheme` and `name`), a "Passkey" tile comes after the wallets: a passkey that the owner linked in Settings
|
|
10
|
+
// ("Owner passkeys", ./passkeys.ts) opens /admin. A passkey that is not linked is refused by the server.
|
|
8
11
|
|
|
12
|
+
import type { PasskeyScheme } from "@nano133/signin/passkey";
|
|
9
13
|
import { ApiError, createApi } from "../../admin/panel/api.js";
|
|
10
14
|
import { h, shortAddress } from "../../admin/panel/dom.js";
|
|
11
15
|
import { icon } from "../../admin/panel/icons.js";
|
|
16
|
+
import { checkScheme } from "../../player-signin/scheme-check.js";
|
|
12
17
|
import { qrSvg } from "../../shop/panel/qr.js";
|
|
13
18
|
import { ADMIN_SIGNIN_BASE, type AdminWay } from "../types.js";
|
|
19
|
+
import { passkeyAdminSignIn, passkeyFaultText } from "./passkeys.js";
|
|
14
20
|
|
|
15
21
|
export type AdminSigninViewOptions = {
|
|
16
22
|
/** Where the sign-in's routes are. Default "/api/admin-signin" (ADMIN_SIGNIN_BASE). */
|
|
@@ -20,6 +26,17 @@ export type AdminSigninViewOptions = {
|
|
|
20
26
|
* admin sign-in from a game sign-in in it: it is off unless the game turns it on on the server and here.
|
|
21
27
|
*/
|
|
22
28
|
nanchat?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Offer the owner's linked passkeys (the server's `passkeys: true`): a "Passkey" tile after the wallets. Default false. Needs `scheme` and `name`. Only a
|
|
31
|
+
* passkey that the owner linked in Settings while signed in with the wallet opens /admin.
|
|
32
|
+
*/
|
|
33
|
+
passkeys?: boolean;
|
|
34
|
+
/** The game's FROZEN passkey scheme: the same one the player sheet takes. Needed with `passkeys`. */
|
|
35
|
+
scheme?: PasskeyScheme;
|
|
36
|
+
/** The game's name (the device shows it with the passkey). Needed with `passkeys`. */
|
|
37
|
+
name?: string;
|
|
38
|
+
/** The passkeys' relying party id: the game's domain. Default: the page's host name. */
|
|
39
|
+
rpId?: string;
|
|
23
40
|
/** The person check (Turnstile): fills `box` and gives its token, before a start. No hook: no check. */
|
|
24
41
|
personCheck?: (box: HTMLElement) => Promise<string | null | undefined>;
|
|
25
42
|
/** 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. */
|
|
@@ -59,6 +76,12 @@ export function adminSigninView(options: AdminSigninViewOptions = {}): AdminSign
|
|
|
59
76
|
const base = options.base ?? ADMIN_SIGNIN_BASE;
|
|
60
77
|
const api = createApi(base, options.fetch ?? ((...a) => fetch(...a)));
|
|
61
78
|
const wallets = WALLETS.filter((w) => w.way !== "nanchat" || options.nanchat === true);
|
|
79
|
+
const passkeysOn = options.passkeys === true;
|
|
80
|
+
if (passkeysOn) {
|
|
81
|
+
checkScheme(options.scheme as PasskeyScheme);
|
|
82
|
+
if (typeof options.name !== "string" || !options.name.trim()) throw new Error("passkeys: true needs the game's name");
|
|
83
|
+
}
|
|
84
|
+
let prompt: AbortController | null = null;
|
|
62
85
|
const touch = () => options.touch ?? (typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches);
|
|
63
86
|
let stopped = false;
|
|
64
87
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -77,6 +100,8 @@ export function adminSigninView(options: AdminSigninViewOptions = {}): AdminSign
|
|
|
77
100
|
function stopWaiting() {
|
|
78
101
|
if (timer) clearTimeout(timer);
|
|
79
102
|
timer = undefined;
|
|
103
|
+
prompt?.abort();
|
|
104
|
+
prompt = null;
|
|
80
105
|
}
|
|
81
106
|
|
|
82
107
|
function showTiles() {
|
|
@@ -84,7 +109,44 @@ export function adminSigninView(options: AdminSigninViewOptions = {}): AdminSign
|
|
|
84
109
|
const tiles = wallets.map((w) =>
|
|
85
110
|
h("button", { class: "n133s-tile", type: "button", "data-way": w.way, onclick: () => void choose(w.way) }, h("span", { class: "n133s-mark", "aria-hidden": "true" }, w.mark), h("span", { class: "n133s-name" }, w.name)),
|
|
86
111
|
);
|
|
87
|
-
|
|
112
|
+
// The owner's linked passkey comes after the wallets: a wallet makes the first admin login, and only it links a passkey.
|
|
113
|
+
if (passkeysOn) tiles.push(h("button", { class: "n133s-tile", type: "button", "data-way": "passkey", onclick: () => showPasskey() }, h("span", { class: "n133s-mark", "aria-hidden": "true" }, icon("key", 24)), h("span", { class: "n133s-name" }, "Passkey")));
|
|
114
|
+
area.replaceChildren(h("p", { class: "n133s-or" }, passkeysOn ? "Choose your wallet or your passkey" : "Choose your wallet"), h("div", { class: "n133s-tiles", "data-count": String(tiles.length) }, ...tiles));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ---- the owner's linked passkey ----
|
|
118
|
+
|
|
119
|
+
function showPasskey(words = "") {
|
|
120
|
+
stopWaiting();
|
|
121
|
+
current = null;
|
|
122
|
+
const back = h("button", { class: "n133s-back", type: "button", onclick: () => showTiles() }, icon("back", 18), h("span", {}, "Back"));
|
|
123
|
+
area.replaceChildren(
|
|
124
|
+
back,
|
|
125
|
+
h("h3", { class: "n133s-step", tabindex: "-1" }, "Passkey"),
|
|
126
|
+
h("p", { class: "n133s-text" }, "Use a passkey that you linked to the game's address in Settings. Your device asks for Face ID, Touch ID or its PIN."),
|
|
127
|
+
h("div", { class: "n133s-keys" }, key("Use my passkey", () => void usePasskey(), "primary")),
|
|
128
|
+
h("p", { class: "n133s-fine" }, "No passkey yet? Sign in with your wallet, then add one in Settings, Owner passkeys."),
|
|
129
|
+
);
|
|
130
|
+
say(words);
|
|
131
|
+
focusFirst();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function usePasskey() {
|
|
135
|
+
stopWaiting();
|
|
136
|
+
for (const b of Array.from(area.querySelectorAll("button"))) b.disabled = true;
|
|
137
|
+
say("Waiting for your passkey…");
|
|
138
|
+
prompt = new AbortController();
|
|
139
|
+
try {
|
|
140
|
+
const turnstile = options.personCheck ? await options.personCheck(check) : undefined;
|
|
141
|
+
const r = await passkeyAdminSignIn({ scheme: options.scheme!, name: options.name!, rpId: options.rpId, base, fetch: options.fetch, turnstile, signal: prompt.signal });
|
|
142
|
+
if (stopped) return;
|
|
143
|
+
area.replaceChildren(h("p", { class: "n133s-done" }, icon("check", 22), h("span", {}, `Signed in with your passkey ${shortAddress(r.address)}`)));
|
|
144
|
+
say("");
|
|
145
|
+
options.onSignedIn?.(r.address);
|
|
146
|
+
} catch (e) {
|
|
147
|
+
if (stopped) return;
|
|
148
|
+
showPasskey(e instanceof ApiError ? e.message : passkeyFaultText(e));
|
|
149
|
+
}
|
|
88
150
|
}
|
|
89
151
|
|
|
90
152
|
async function choose(way: AdminWay) {
|
|
@@ -1,9 +1,13 @@
|
|
|
1
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
2
|
// "@nano133/nanoterra/player-signin".) No package and no DOM: the stores, the adapters and the browser panel read this file.
|
|
3
3
|
//
|
|
4
|
-
// The admin signs in with a wallet app
|
|
5
|
-
//
|
|
6
|
-
// on the admin's route; the guard (`adminAccess`) decides again on every call of /admin.
|
|
4
|
+
// The admin signs in with a wallet app: Berry Wallet or Nautilus (and NanChat only when the game turns it on: its text cannot name the ADMIN). What Berry
|
|
5
|
+
// 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 a
|
|
6
|
+
// wallet admin login, and only from a request that was started on the admin's route; the guard (`adminAccess`) decides again on every call of /admin.
|
|
7
|
+
//
|
|
8
|
+
// Since 0.12.0, with `passkeys: true`, the owner may also LINK passkeys (at most 10): a passkey is only a key to /admin, the money stays in the owner's
|
|
9
|
+
// wallet. A link is written only from a live WALLET admin session of the owner and with the passkey's own signature (both sides prove their key), and a
|
|
10
|
+
// passkey's admin login counts only while its link to the CURRENT owner exists (read again on every request).
|
|
7
11
|
|
|
8
12
|
import type { AdminLogin } from "../admin/store.js";
|
|
9
13
|
import type { RequestStoreLike } from "../player-signin/types.js";
|
|
@@ -47,27 +51,56 @@ export const ADMIN_SIGNIN_LIMITS = {
|
|
|
47
51
|
nanchatRoute: { limit: 120, windowMs: 60_000 },
|
|
48
52
|
nanchatAll: { limit: 600, windowMs: 10 * 60_000 },
|
|
49
53
|
nanchatNonce: { limit: 5, windowMs: 10 * 60_000 },
|
|
54
|
+
/** The owner's passkeys: the list, a link and a removal, per IP address (memory). A passkey's sign-in counts with the starts (`signin`, hook). */
|
|
55
|
+
passkeys: { limit: 30, windowMs: 60_000 },
|
|
50
56
|
/** The biggest body the routes read. */
|
|
51
57
|
bodyMax: 8192,
|
|
52
58
|
} as const;
|
|
53
59
|
|
|
60
|
+
/** The most passkeys one owner may link. */
|
|
61
|
+
export const ADMIN_PASSKEY_LIMIT = 10;
|
|
62
|
+
/** How long a passkey's signature is kept as used (its 5-minute window, both ways, and some more). */
|
|
63
|
+
export const ADMIN_ONCE_MS = 10 * 60_000;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* What a passkey signs to OPEN /admin: `signinMessage(adminPasskeyDomain(host), address, at)`, "ADMIN of <host>: sign in as nano_... at <ms>". Never the
|
|
67
|
+
* host alone: a player's passkey signature names only the host, and it must never open /admin.
|
|
68
|
+
*/
|
|
69
|
+
export const adminPasskeyDomain = (host: string) => `ADMIN of ${host}`;
|
|
70
|
+
/** What a passkey signs to be LINKED to the owner: "Link this passkey to the ADMIN of <host>: sign in as nano_... at <ms>". It opens nothing. */
|
|
71
|
+
export const adminLinkDomain = (host: string) => `Link this passkey to the ADMIN of ${host}`;
|
|
72
|
+
|
|
73
|
+
/** One passkey linked to the owner: the passkey purse's address and when it was linked (ms). */
|
|
74
|
+
export type AdminPasskey = { address: string; createdAt: number };
|
|
75
|
+
/** What a link gives: "linked", "exists" (it was linked already: nothing changed) or "full" (the owner has ADMIN_PASSKEY_LIMIT already). */
|
|
76
|
+
export type AdminLinkResult = "linked" | "exists" | "full";
|
|
77
|
+
|
|
54
78
|
/** A token, a starter value: 32 random bytes as 64 hex characters. */
|
|
55
79
|
export const TOKEN_PATTERN = /^[0-9a-f]{64}$/;
|
|
56
80
|
|
|
57
81
|
/**
|
|
58
82
|
* An admin session as a store keeps it. `idHash` is the SHA-256 (hex) of "admin:" and the cookie's token (`adminKey`): never the token, and never the
|
|
59
|
-
* plain hash a player's session has, so the SERVER keeps the two scopes apart and not only the cookies' names. `via` is "wallet" for
|
|
60
|
-
*
|
|
83
|
+
* 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 a wallet's session
|
|
84
|
+
* and "passkey" for a linked passkey's (its `address` is the PASSKEY's, never the owner's); a store returns the word it holds.
|
|
61
85
|
*/
|
|
62
86
|
export type AdminSessionRecord = { idHash: string; address: string; createdAt: number; expiresAt: number; via: string };
|
|
63
87
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
88
|
+
/**
|
|
89
|
+
* The admin session as the game reads it (`createAdminHandler`'s `session` hook). `via` is "unknown" for a stored word other than "wallet", "nanoterra" and
|
|
90
|
+
* "passkey": the guard refuses it. A "passkey" session carries `linkedTo`, the owner's address, only while its link to the CURRENT owner exists (read on this
|
|
91
|
+
* request); without the link the sign-in gives no session at all.
|
|
92
|
+
*/
|
|
93
|
+
export type AdminSigninSession =
|
|
94
|
+
| { address: string; createdAt: number; via: "wallet" | "nanoterra" | "unknown" }
|
|
95
|
+
| { address: string; createdAt: number; via: "passkey"; linkedTo: string };
|
|
66
96
|
|
|
67
97
|
/**
|
|
68
|
-
* The game's database for the admin's sign-in. An adapter reads and writes ONLY its
|
|
69
|
-
* and only the ADMIN's rows of the first two (a game whose players sign in through the same tables
|
|
70
|
-
* Run `adminSigninStoreConformance` on a store you write yourself.
|
|
98
|
+
* The game's database for the admin's sign-in. An adapter reads and writes ONLY its tables or collections (requests, sessions, the sign-in list, and for
|
|
99
|
+
* the owner's passkeys the links and the used signatures), and only the ADMIN's rows of the first two (a game whose players sign in through the same tables
|
|
100
|
+
* keeps its rows apart: the `scope` column). Run `adminSigninStoreConformance` on a store you write yourself.
|
|
101
|
+
*
|
|
102
|
+
* The passkey methods (`createSession` to `useOnce`) are optional: a store without them works for wallets, and `createAdminSignin({ passkeys: true })`
|
|
103
|
+
* refuses it.
|
|
71
104
|
*/
|
|
72
105
|
export interface AdminSigninStore {
|
|
73
106
|
/** The admin requests of one wallet app. */
|
|
@@ -90,6 +123,24 @@ export interface AdminSigninStore {
|
|
|
90
123
|
recordLogin(login: AdminLogin): Promise<void>;
|
|
91
124
|
/** The last sign-ins, newest first, at most `limit`, with only `at`, `country` and `browser`. */
|
|
92
125
|
recentLogins(limit: number): Promise<AdminLogin[]>;
|
|
93
|
-
/** Deletes what nobody needs any more: admin requests 2 hours after they ended, admin sessions that ended, sign-in rows older than 30 days. */
|
|
126
|
+
/** Deletes what nobody needs any more: admin requests 2 hours after they ended, admin sessions that ended, sign-in rows older than 30 days, used passkey signatures past their time. */
|
|
94
127
|
clean(now: number): Promise<void>;
|
|
128
|
+
|
|
129
|
+
// ---- the owner's passkeys (since 0.12.0) ----
|
|
130
|
+
|
|
131
|
+
/** Writes an admin session (a linked passkey's sign-in). Throws when a session with this hash exists. */
|
|
132
|
+
createSession?(session: AdminSessionRecord): Promise<void>;
|
|
133
|
+
/**
|
|
134
|
+
* Links the passkey `address` to `owner`, in ONE step that holds the limit: "linked"; "exists" when it is linked already (nothing changes); "full" when
|
|
135
|
+
* `owner` has ADMIN_PASSKEY_LIMIT links (nothing is written). Two calls at once never make more than the limit.
|
|
136
|
+
*/
|
|
137
|
+
linkPasskey?(owner: string, address: string, at: number): Promise<AdminLinkResult>;
|
|
138
|
+
/** Removes the link and ends every admin session of that passkey ("passkey" sessions of `address`). True when a link was there. */
|
|
139
|
+
unlinkPasskey?(owner: string, address: string): Promise<boolean>;
|
|
140
|
+
/** The passkeys linked to `owner`, oldest first. */
|
|
141
|
+
passkeys?(owner: string): Promise<AdminPasskey[]>;
|
|
142
|
+
/** True only when `address` is linked to `owner` NOW (the exact texts). */
|
|
143
|
+
linked?(owner: string, address: string): Promise<boolean>;
|
|
144
|
+
/** Records `key` (a used passkey signature) and answers true; false when it is there and its time is not over. The admin's own table, not the player's. */
|
|
145
|
+
useOnce?(key: string, ttlMs: number): Promise<boolean>;
|
|
95
146
|
}
|
|
@@ -262,8 +262,9 @@
|
|
|
262
262
|
gap: 10px;
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
-
/* Two wallets (the admin's sign-in: Berry Wallet and Nautilus) fill the row in two halves. */
|
|
266
|
-
.n133-signin .n133s-tiles[data-count="2"]
|
|
265
|
+
/* Two wallets (the admin's sign-in: Berry Wallet and Nautilus) fill the row in two halves; four tiles (the admin's with NanChat and a passkey) make two rows of two. */
|
|
266
|
+
.n133-signin .n133s-tiles[data-count="2"],
|
|
267
|
+
.n133-signin .n133s-tiles[data-count="4"] {
|
|
267
268
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
268
269
|
}
|
|
269
270
|
|