Public: anyone can read this; the crew can change it.

Connections: a Minecraft name is a second kind of proven connection beside email #18227

opened this

Merged 5h 5m ago, live in production

mason/forge:mason/18221-connections-a-minecraft-name-is-a-second → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18221-connections-a-minecraft-name-is-a-second was merged into main as 5948687.

Review

Sign in to review this change.
20 files changed +355 −82
docs/design/audit.md +1 −1
@@ -197,7 +197,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
197197 - `/settings/devices` — `settings/devices.ts` · LAN printers the owner declares, with model, state and supplies · `/settings/origins` (the same account sections) · none seen.
198198 - `/settings/origins` — `pages/origins.ts` (1,497 lines) · other forges this one reads and mirrors from · `/migrate` · none seen.
199199 - `/settings/bring` — `pages/visitor_bring.ts` · what a visitor made on this device, picked and brought to the account, and the receipts with a day's undo · the forge button's "Keep these on my account" on an app · none seen.
200 - `/settings/identities` — `pages/identities.ts` · the verified addresses connected to your account, each with its state and the one that is in use · `/settings/origins` (the same account sections) · none seen.
200 - `/settings/identities` — `pages/identities.ts` · the verified addresses and Minecraft names connected to your account, each with its state and the one that is in use · `/settings/origins` (the same account sections) · none seen.
201201 - `/settings/security` — `pages/security.ts` · the Shield and the evidence an admin needs to act with no AI · `/settings/traffic`, `/settings/backups` · none seen.
202202 - `/settings/security/controls` — `pages/security_controls.ts` · one line per RED-TEAM control and when it was last checked · `/settings/security` · none seen.
203203 - `/settings/traffic` — `pages/traffic.ts` · who used the answering time in the last 15 minutes · `/settings/usage`, `/settings/telemetry` · none seen.
docs/features/account-identities.md +28 −15
@@ -1,6 +1,6 @@
11 ---
22 topic: Every setting, by topic
3 row: Identities on an account: proven emails, each with its own opt-in uses, and the integrations' lookup
3 row: Identities on an account: proven emails and Minecraft names, each with its own opt-in uses, and the integrations' lookup
44 ---
55 # Identities on an account
66
@@ -10,28 +10,41 @@ back: kept as a hash, spent once, good half an hour, five tries. One address is
1010 account; a second cannot take it. Each proven one has uses, all off by default: `feedback`
1111 ("name me on app feedback and crash reports") and `profile`.
1212
13 A **Minecraft name** is the second kind (#18221): kept lowercased (3 to 16 letters, digits or
14 underscores), with no code. It is shown "not proven yet" until the game door links that player
15 to the account: Settings › Link your Minecraft name gives a code, and `!forge link <code>` typed
16 in game proves the connection by that name, the same link that lets the player command the box

This describes a proof that outlives its game link. Change it once unlinking unproves, and wrap the long API and Lookup bullets nearby.

17 (`src/games/chat.ts`). A name the account already linked in game is proven as soon as it is
18 added. One name is proven by one account: a second may keep it, but the link never proves it
19 there. Its uses are off by default, as an email's. The proof lasts as long as the link: once
20 the account's last game link for that player is gone (unlinked on Settings › Minecraft, or
21 dropped because another player now has the name), the connection is not proven again and its
22 uses are off, so the lookup no longer answers this account for a name someone else may hold.
23
1324 - **API**: `GET /api/v1/connections` lists; `POST` `{email}` mails a code; `POST /:id/confirm`
14 `{code}` proves; `PUT /:id/uses/:use` `{on}` chooses; `DELETE /:id` removes. The account
15 itself, same-origin.
16 - **Lookup** (`POST /api/v1/connections/lookup`, `{email, use}`, header `X-Forge-Lookup-Key`):
17 answers `{user: {username}}` only for a proven address whose use is on; unknown, unproven and
18 not opted in all answer `{user: null}`. A forge admin makes keys (`POST …/lookup-keys
19 {name}`, shown once) and revokes them (`DELETE …/lookup-keys/:id`). 60 calls a minute per
20 key; each call is a row in `connection_lookup_audit`.
25 `{code}` proves (an email); `POST` `{minecraft}` keeps a Minecraft name; `PUT /:id/uses/:use`
26 `{on}` chooses; `DELETE /:id` removes. The account itself, same-origin.
27 - **Lookup** (`POST /api/v1/connections/lookup`, `{email, use}` or `{minecraft, use}`, header
28 `X-Forge-Lookup-Key`): answers `{user: {username}}` only for a proven address or name whose
29 use is on; unknown, unproven and not opted in all answer `{user: null}`. A forge admin makes
30 keys (`POST …/lookup-keys {name}`, shown once) and revokes them (`DELETE …/lookup-keys/:id`).
31 60 calls a minute per key; each call is a row in `connection_lookup_audit`.
2132 - **Reports**: `POST …/reports` with a lookup key and `reporter` (an address) names the
2233 reporter only through the `feedback` use. Removing the connection or switching the use off
2334 stops later reports naming them; issues already filed are not rewritten.
24 - **Doors**: Settings › Proven emails (`src/web/pages/identities.ts`, same-origin forms, the
25 signed-in account only) and the terminal's "Proven emails" screen (`src/tui/screens/identities.ts`:
26 `a` add, `c` code, `f`/`p` switch a use, `d` remove) call the same actions as the API, and say
27 the same words beside the uses: removing or switching off is not retroactive.
35 - **Doors**: Settings › Proven identities (`src/web/pages/identities.ts`, same-origin forms, the
36 signed-in account only; "Add the name" posts to `/settings/identities/minecraft`) and the
37 terminal's "Proven identities" screen (`src/tui/screens/identities.ts`: `a` add an email,
38 `m` add a Minecraft name, `c` code, `f`/`p` switch a use, `d` remove) call the same actions as
39 the API, and say the same words beside the uses: removing or switching off is not retroactive.
2840 - **What it does not reveal**: adding an address another account proved answers as any new address
2941 does (201, nothing mailed to its owner; the code never proves, so a member cannot learn whether an
3042 address is proven here). Only the mail cap on an address (3 a day) can still differ.
3143 - **Mail**: a member's sends are capped by account (20 a day, `connection:<id>` scope of
3244 `sendCapped`, so add-then-remove cycles do not evade it), by address and by the forge.
3345 - **Audit**: a key's rows older than a day are deleted on its next call.
34 - **Not yet**: the Apple app; the Minecraft link and the account's proven email stay where they
35 are, not in this list.
46 - **Not yet**: the Apple app; the account's proven email stays where it is, not in this list; the
47 game links themselves (one per box) stay on Settings › Minecraft.
3648
37 `test/identities.test.ts` walks add, prove, opt in, remove; `test/identities-doors.test.ts` the page and the screen.
49 `test/identities.test.ts` walks add, prove, opt in, unlink, remove;
50 `test/identities-doors.test.ts` the page and the screen.
src/actions/identities.ts +39 −13
@@ -4,27 +4,31 @@
44 * integration asks. The lookup is a permission check: it answers the forge
55 * user only when a proven connection has that use on, and the same nothing
66 * for unknown, unproven and not opted in. Mail goes through the forge's mail
7 * key (`mailerOf`), never a provider's own API.
7 * key (`mailerOf`), never a provider's own API. A Minecraft name (#18221) is
8 * kept unproven and proven by the game door's own link (`!forge link <code>`,
9 * `games/chat.ts`), or at once when the account already linked that player.
810 */
911
1012 import type { App } from "../app.ts";
1113 import {
12 addEmail, auditLookup, cleanEmail, listConnections, lookup, lookupKeyId, mintLookupKey,
13 proveEmail, removeConnection, revokeLookupKey, setUse, isUse,
14 type Connection,
14 addEmail, addMinecraft, auditLookup, cleanEmail, cleanMinecraft, listConnections, lookup, lookupKeyId, mintLookupKey,
15 proveEmail, proveMinecraft, removeConnection, revokeLookupKey, setUse, isUse,
16 type Connection, type Kind,
1517 } from "../core/identities.ts";
18 import { linksOf } from "../games/chat.ts";
1619 import { getUserById, type User } from "../core/users.ts";
1720 import { err, ok, type Result } from "../kernel/result.ts";
1821 import { mailerOf } from "./verify.ts";
1922 import { sendCapped } from "./mail.ts";
2023
2124 export type ConnectionError =
22 | "invalid_email" | "limit" | "taken" | "too_soon" | "no_mail" | "capped" | "failed"
25 | "invalid_email" | "invalid_minecraft" | "limit" | "taken" | "too_soon" | "no_mail" | "capped" | "failed"
2326 | "wrong_code" | "not_found" | "invalid_use" | "invalid_name";
2427
2528 /** What each refusal says, for the API, the settings page and the terminal alike. */
2629 export const CONNECTION_WORDS: Record<ConnectionError, string> = {
2730 invalid_email: "that is not an email address",
31 invalid_minecraft: "a Minecraft name is 3 to 16 letters, digits or underscores",
2832 limit: "an account keeps at most 10 connections; remove one first",
2933 taken: "that address cannot be added to this account",
3034 too_soon: "a code was sent a moment ago; wait a minute",
@@ -41,6 +45,10 @@ export const CONNECTION_WORDS: Record<ConnectionError, string> = {
4145 export const NOT_RETROACTIVE =
4246 "Removing a connection, or switching a use off, stops later reports naming you. Issues already filed are not rewritten.";
4347
48 /** How a Minecraft name is proven, said by the API, the settings page and the terminal alike. */
49 export const MINECRAFT_PROOF =
50 "Not proven until you link this player in game: Settings › Link your Minecraft name gives a code to type there as !forge link <code>.";
51
4452 export const connectionsOf = (app: App, user: User): Connection[] => listConnections(app.db, user.id);
4553
4654 /** Start proving an email: the connection is unproven until the mailed code is given back. */
@@ -74,6 +82,22 @@ export async function addConnection(
7482 return ok(made.connection);
7583 }
7684
85 /**
86 * Keep a Minecraft name, unproven until the game door links that player to this account. A player
87 * this account already linked on a box is proven now, by that same link.
88 */
89 export function addMinecraftConnection(
90 app: App, user: User, rawName: unknown, now = Date.now(),
91 ): Result<Connection, ConnectionError> {
92 const name = cleanMinecraft(rawName);
93 if (name === undefined) return err("invalid_minecraft");
94 const made = addMinecraft(app.db, user.id, name, now);
95 if (made === "limit") return err(made);
96 if (made.proven || !linksOf(app, user.id).some((l) => l.player.toLowerCase() === name)) return ok(made);
97 proveMinecraft(app.db, user.id, name, now);
98 return ok(listConnections(app.db, user.id).find((c) => c.id === made.id)!);
99 }
100
77101 const removeUnproven = (app: App, user: User, id: string): void => {
78102 const c = listConnections(app.db, user.id).find((x) => x.id === id);
79103 if (c && !c.proven) removeConnection(app.db, user.id, id);
@@ -108,22 +132,24 @@ export type LookupRefusal = "unauthorized" | "rate_limited" | "invalid";
108132 * `null` is the one answer for every way of not knowing.
109133 */
110134 export function findNamed(
111 app: App, presentedKey: string, ident: unknown, use: unknown, now = Date.now(),
135 app: App, presentedKey: string, kind: Kind, ident: unknown, use: unknown, now = Date.now(),
112136 ): Result<User | null, LookupRefusal> {
113137 const keyId = lookupKeyId(app.db, presentedKey);
114138 if (keyId === undefined) return err("unauthorized");
115 const email = cleanEmail(ident);
116 if (!isUse(use) || email === undefined) return err("invalid");
117 const who = lookup(app.db, email, use);
139 const clean = kind === "email" ? cleanEmail(ident) : cleanMinecraft(ident);
140 if (!isUse(use) || clean === undefined) return err("invalid");
141 const who = lookup(app.db, kind, clean, use);
118142 if (!auditLookup(app.db, keyId, use, who !== undefined, now)) return err("rate_limited");
119143 return ok((who === undefined ? undefined : getUserById(app.db, who)) ?? null);
120144 }
121145
122 /** `findNamed`, as the API answers it: the username only. */
146 /** `findNamed`, as the API answers it: the username only, for `{email}` or `{minecraft}`. */
123147 export function askLookup(
124 app: App, presentedKey: string, ident: unknown, use: unknown, now = Date.now(),
148 app: App, presentedKey: string, asked: { email?: unknown; minecraft?: unknown }, use: unknown, now = Date.now(),
125149 ): Result<{ username: string } | null, LookupRefusal> {
126 const found = findNamed(app, presentedKey, ident, use, now);
150 const found = asked.minecraft === undefined
151 ? findNamed(app, presentedKey, "email", asked.email, use, now)
152 : findNamed(app, presentedKey, "minecraft", asked.minecraft, use, now);
127153 return found.ok ? ok(found.value === null ? null : { username: found.value.username }) : found;
128154 }
129155
@@ -133,7 +159,7 @@ export function askLookup(
133159 */
134160 export function reporterFor(app: App, presentedKey: string, ident: unknown, now = Date.now()): User | undefined {
135161 if (presentedKey === "") return undefined;
136 const found = findNamed(app, presentedKey, ident, "feedback", now);
162 const found = findNamed(app, presentedKey, "email", ident, "feedback", now);
137163 return found.ok ? found.value ?? undefined : undefined;
138164 }
139165
src/core/identities.ts +74 −11
@@ -6,7 +6,9 @@
66 * identifier is proven by one account: a second account cannot take it.
77 * `lookup` answers the user only for a proven connection whose use is on,
88 * and `undefined` for everything else, so no answer tells apart an unknown
9 * address from an unproven or an opted-out one.
9 * address from an unproven or an opted-out one. A Minecraft name (#18221) is
10 * the second kind: no code, it is proven when the game door links that player
11 * to the account (`proveMinecraft`), and the same one-account rule holds.
1012 */
1113
1214 import type { Database } from "bun:sqlite";
@@ -26,9 +28,11 @@ export const EMAIL_MAX = 254;
2628 /** How long a lookup's audit row is kept: past it, the row goes on the next call of its key. */
2729 export const AUDIT_KEEP_MS = 24 * 3_600_000;
2830
31 export type Kind = "email" | "minecraft";
32
2933 export interface Connection {
3034 readonly id: string;
31 readonly kind: "email";
35 readonly kind: Kind;
3236 readonly ident: string;
3337 readonly proven: boolean;
3438 readonly uses: Readonly<Record<Use, boolean>>;
@@ -44,8 +48,18 @@ export function cleanEmail(raw: unknown): string | undefined {
4448 return e.endsWith(".invalid") ? undefined : e;
4549 }
4650
51 /**
52 * A Minecraft name as it is kept: trimmed and lowercased (the game treats names without case), 3 to
53 * 16 letters, digits or underscores; undefined when it is not one.
54 */
55 export function cleanMinecraft(raw: unknown): string | undefined {
56 if (typeof raw !== "string") return undefined;
57 const n = raw.trim().toLowerCase();
58 return /^[a-z0-9_]{3,16}$/.test(n) ? n : undefined;
59 }
60
4761 interface Row {
48 id: string; user_id: string; kind: "email"; ident: string; proven_at: string | null;
62 id: string; user_id: string; kind: Kind; ident: string; proven_at: string | null;
4963 sent_at: string | null; use_feedback: number; use_profile: number;
5064 }
5165 const shown = (r: Row): Connection => ({
@@ -61,10 +75,9 @@ export function listConnections(db: Database, userId: string): Connection[] {
6175 export function addEmail(
6276 db: Database, userId: string, email: string, now: number,
6377 ): { connection: Connection; code: string; held: boolean } | "limit" | "taken" | "too_soon" {
64 const mine = db.query<Row, [string, string]>("SELECT * FROM connection WHERE user_id = ?1 AND ident = ?2").get(userId, email);
78 const mine = db.query<Row, [string, string]>("SELECT * FROM connection WHERE user_id = ?1 AND kind = 'email' AND ident = ?2").get(userId, email);
6579 if (mine === null) {
66 const n = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM connection WHERE user_id = ?1").get(userId)?.n ?? 0;
67 if (n >= PER_ACCOUNT) return "limit";
80 if (full(db, userId)) return "limit";
6881 } else if (mine.proven_at !== null) return "taken";
6982 // Another account proved it: this one still gets a row and a code, but `held` says nothing is
7083 // mailed, so the answer never tells whether an address is proven here (it cannot be proven by
@@ -82,6 +95,56 @@ export function addEmail(
8295 return { connection: shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!), code, held };
8396 }
8497
98 const full = (db: Database, userId: string): boolean =>
99 (db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM connection WHERE user_id = ?1").get(userId)?.n ?? 0) >= PER_ACCOUNT;
100
101 /**
102 * Keep a Minecraft name on the account, unproven until the game proves it (`proveMinecraft`).
103 * Adding it again returns the one kept. A name another account proved still gets a row that can
104 * never be proven, so the answer does not tell whether it is proven elsewhere.
105 */
106 export function addMinecraft(db: Database, userId: string, name: string, now: number): Connection | "limit" {
107 const mine = db.query<Row, [string, string]>("SELECT * FROM connection WHERE user_id = ?1 AND kind = 'minecraft' AND ident = ?2").get(userId, name);
108 if (mine !== null) return shown(mine);
109 if (full(db, userId)) return "limit";
110 const id = newId();
111 db.query("INSERT INTO connection (id, user_id, kind, ident, created_at) VALUES (?1, ?2, 'minecraft', ?3, ?4)")
112 .run(id, userId, name, new Date(now).toISOString());
113 return shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!);
114 }
115
116 /**
117 * The game door linked `player` to this account: its Minecraft connection by that name, if kept
118 * and not yet proven, is proven now. False when there is none, or another account proved it first.
119 */
120 export function proveMinecraft(db: Database, userId: string, player: string, now: number): boolean {
121 const name = cleanMinecraft(player);
122 if (name === undefined) return false;
123 try {
124 return db.query("UPDATE connection SET proven_at = ?3 WHERE user_id = ?1 AND kind = 'minecraft' AND ident = ?2 AND proven_at IS NULL")
125 .run(userId, name, new Date(now).toISOString()).changes > 0;
126 } catch {
127 return false;
128 }
129 }
130
131 /**
132 * A game link for `player` was removed: the account's Minecraft connection by that name is
133 * unproven, its uses off, unless another box still links that player to this account. The name can
134 * pass to someone else, so the proof never outlives its link. True when a connection was unproven.
135 */
136 export function unproveMinecraft(db: Database, userId: string, player: string): boolean {
137 const name = cleanMinecraft(player);
138 if (name === undefined) return false;
139 const stillLinked = db
140 .query<{ n: number }, [string, string]>("SELECT COUNT(*) AS n FROM game_link WHERE user_id = ?1 AND lower(player) = ?2")
141 .get(userId, name);
142 if ((stillLinked?.n ?? 0) > 0) return false;
143 return db.query(
144 "UPDATE connection SET proven_at = NULL, use_feedback = 0, use_profile = 0 WHERE user_id = ?1 AND kind = 'minecraft' AND ident = ?2 AND proven_at IS NOT NULL",
145 ).run(userId, name).changes > 0;
146 }
147
85148 /**
86149 * Prove with the code: once, while fresh, a few tries. "taken" when another account proved it
87150 * first.
@@ -90,7 +153,7 @@ export function proveEmail(
90153 db: Database, userId: string, id: string, code: string, now: number,
91154 ): "proven" | "wrong" | "taken" | "none" {
92155 const row = db.query<Row & { code_hash: string | null; expires_at: string | null; tries: number }, [string, string]>(
93 "SELECT * FROM connection WHERE id = ?1 AND user_id = ?2 AND proven_at IS NULL",
156 "SELECT * FROM connection WHERE id = ?1 AND user_id = ?2 AND kind = 'email' AND proven_at IS NULL",
94157 ).get(id, userId);
95158 if (row === null) return "none";
96159 if (row.code_hash === null || row.expires_at === null || Date.parse(row.expires_at) <= now || row.tries >= MAX_TRIES) return "wrong";
@@ -117,11 +180,11 @@ export function setUse(db: Database, userId: string, id: string, use: Use, on: b
117180 }
118181
119182 /** The user a proven identifier belongs to, if that user switched this use on; nothing else. */
120 export function lookup(db: Database, ident: string, use: Use): string | undefined {
183 export function lookup(db: Database, kind: Kind, ident: string, use: Use): string | undefined {
121184 const col = use === "feedback" ? "use_feedback" : "use_profile";
122 return db.query<{ user_id: string }, [string]>(
123 `SELECT user_id FROM connection WHERE kind = 'email' AND ident = ?1 AND proven_at IS NOT NULL AND ${col} = 1`,
124 ).get(ident)?.user_id;
185 return db.query<{ user_id: string }, [Kind, string]>(
186 `SELECT user_id FROM connection WHERE kind = ?1 AND ident = ?2 AND proven_at IS NOT NULL AND ${col} = 1`,
187 ).get(kind, ident)?.user_id;
125188 }
126189
127190 /** Mint a lookup key for an integration: the secret is returned once, its hash kept. */
src/core/migration-pins/20261204120000-connection-minecraft.pin added +1
@@ -0,0 +1,1 @@
1 ecf45627aac9a231890d62c128672bff669ee23ed7c6abff594e1d58a3b4b095
src/core/migrations/20261204120000-connection-minecraft.ts added +25
@@ -0,0 +1,25 @@
1 // A Minecraft name is a second kind of connection beside email (#18221): `ident` is the name
2 // lowercased, proven when the game door links that player to the account (`!forge link <code>`).
3 // SQLite cannot widen a CHECK in place, so the table is copied into a new one and its indexes made
4 // again; nothing refers to it.
5 export default `
6 CREATE TABLE connection_next (
7 id TEXT PRIMARY KEY,
8 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
9 kind TEXT NOT NULL CHECK (kind IN ('email', 'minecraft')),
10 ident TEXT NOT NULL,
11 proven_at TEXT,
12 code_hash TEXT,
13 expires_at TEXT,
14 tries INTEGER NOT NULL DEFAULT 0,
15 sent_at TEXT,
16 use_feedback INTEGER NOT NULL DEFAULT 0,
17 use_profile INTEGER NOT NULL DEFAULT 0,
18 created_at TEXT NOT NULL
19 ) WITHOUT ROWID;
20 INSERT INTO connection_next SELECT * FROM connection;
21 DROP TABLE connection;
22 ALTER TABLE connection_next RENAME TO connection;
23 CREATE UNIQUE INDEX connection_one_per_account ON connection(user_id, kind, ident);
24 CREATE UNIQUE INDEX connection_proven_once ON connection(kind, ident) WHERE proven_at IS NOT NULL;
25 `;
src/games/chat.ts +11 −4
@@ -28,6 +28,7 @@ import type { App } from "../app.ts";
2828 import { waitingConfirms } from "../actions/conversation_confirms.ts";
2929 import { talk } from "../actions/talk.ts";
3030 import { createConversation, listTurns } from "../core/conversations.ts";
31 import { proveMinecraft, unproveMinecraft } from "../core/identities.ts";
3132 import { readReceipt } from "../crew/receipt.ts";
3233 import { publicOrigin } from "../core/public_origin.ts";
3334 import { getUserById, isActive, type User } from "../core/users.ts";
@@ -185,10 +186,12 @@ export const playersOn = (app: App, boxId: string): { player: string; username:
185186 /** Forget one of a person's linked names, kept in the audit as theirs. */
186187 export function unlink(app: App, userId: string, boxId: string, player: string): void {
187188 const gone = app.db.query("DELETE FROM game_link WHERE user_id = ?1 AND box_id = ?2 AND player = ?3").run(userId, boxId, player);
188 if (gone.changes > 0)
189 app.db
190 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at) VALUES (?1, '', ?2, ?3, 'unlink', '', 'unlinked on the forge', ?4)")
191 .run(boxId, player, userId, new Date().toISOString());
189 if (gone.changes === 0) return;
190 // The link was the proof of the Minecraft connection by this name (#18221).
191 unproveMinecraft(app.db, userId, player);
192 app.db
193 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at) VALUES (?1, '', ?2, ?3, 'unlink', '', 'unlinked on the forge', ?4)")
194 .run(boxId, player, userId, new Date().toISOString());
192195 }
193196
194197 /** The latest commands said in a box's chat, newest first: who, what, and what came of it. */
@@ -407,6 +410,9 @@ function one(
407410 uuid,
408411 new Date(now).toISOString(),
409412 );
413 // The same link proves the account's Minecraft connection by this name, if it keeps one
outdated

High: the link proves the connection, but nothing unproves it when the link is removed (Settings > Minecraft). The name can later belong to someone else, and the lookup keeps answering this user for it. Add an unproveMinecraft that clears proven_at and the uses, call it where the game_link row is deleted, and test it.

414 // (#18221).
415 proveMinecraft(db, code.user_id, player, now);
410416 const who = getUserById(db, code.user_id);
411417 audit(app, box, at, code.user_id, "link", "link ****", "linked", now);
412418 return say(
@@ -431,6 +437,7 @@ function one(
431437 if (uuid === "") return refuse(user.id, "not seen online", `The forge does not see ${player} on ${service} yet: try again in a minute.`);
432438 if (uuid !== linked.uuid) {
433439 db.query("DELETE FROM game_link WHERE box_id = ?1 AND player = ?2").run(box.id, player);
440 unproveMinecraft(db, user.id, player);
434441 audit(app, box, at, user.id, "refused", shown, "another player has the name: link dropped", now);
435442 return say(db, box, at, [`${player} was linked as another player, so that link is gone.`, ...howToLink], "", "red");
436443 }
src/http/api/identities.ts +10 −4
@@ -1,6 +1,7 @@
11 /**
22 * Connections on an account over the API (#18108): `GET /api/v1/connections`
3 * lists the caller's; `POST` adds an email and mails a code; `POST
3 * lists the caller's; `POST` adds an email and mails a code, or `{minecraft}`
4 * keeps a Minecraft name the game door proves (#18221); `POST
45 * /:id/confirm {code}` proves it; `PUT /:id/uses/:use {on}` chooses a use;
56 * `DELETE /:id` removes. `POST /lookup` is the integrations' question,
67 * carrying a lookup key in `X-Forge-Lookup-Key` (never a user token); an
@@ -9,6 +10,7 @@
910
1011 import {
1112 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf, askLookup,
13 addMinecraftConnection, MINECRAFT_PROOF,
1214 dropConnection, dropLookupKey, makeLookupKey, type ConnectionError,
1315 } from "../../actions/identities.ts";
1416 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -18,7 +20,7 @@ import type { Router } from "../router.ts";
1820
1921 /** The status each refusal answers with, 0 for the ones that wait; the words are the action's. */
2022 const STATUS: Record<ConnectionError, number> = {
21 invalid_email: 422, limit: 422, taken: 409, too_soon: 0, no_mail: 0, capped: 0, failed: 502,
23 invalid_email: 422, invalid_minecraft: 422, limit: 422, taken: 409, too_soon: 0, no_mail: 0, capped: 0, failed: 502,
2224 wrong_code: 422, not_found: 404, invalid_use: 422, invalid_name: 422,
2325 };
2426 /** Seconds to wait, for the refusals that wait; the rest answer through apiError. */
@@ -41,6 +43,10 @@ export function identityRoutes(router: Router<Handler>): void {
4143 const denied = requireAccount(ctx, { adminToken: true });
4244 if (denied) return denied;
4345 const input = await body(ctx.request);
46 if (input.minecraft !== undefined) {
47 const kept = addMinecraftConnection(ctx.app, ctx.auth.user!, input.minecraft);
48 return kept.ok ? json({ connection: kept.value, says: MINECRAFT_PROOF }, 201, noStore) : refuse(kept.error);
49 }
4450 const made = await addConnection(ctx.app, ctx.auth.user!, input.email);
4551 return made.ok ? json({ connection: made.value, says: "A code was mailed; send it to /confirm." }, 201, noStore) : refuse(made.error);
4652 });
@@ -71,11 +77,11 @@ export function identityRoutes(router: Router<Handler>): void {
7177 // The integrations' lookup: found and not-found answer alike for every way of not knowing.
7278 router.add("POST", "/api/v1/connections/lookup", async (ctx) => {
7379 const input = await body(ctx.request);
74 const asked = askLookup(ctx.app, ctx.request.headers.get("x-forge-lookup-key") ?? "", input.email, input.use);
80 const asked = askLookup(ctx.app, ctx.request.headers.get("x-forge-lookup-key") ?? "", { email: input.email, minecraft: input.minecraft }, input.use);
7581 if (!asked.ok) {
7682 if (asked.error === "unauthorized") return notFound();
7783 if (asked.error === "rate_limited") return tryAgain("rate_limited", 429, "too many lookups; wait a minute", 60);
78 return apiError("invalid", 422, "send {email, use: feedback|profile}");
84 return apiError("invalid", 422, "send {email, use: feedback|profile} or {minecraft, use}");
7985 }
8086 return json({ user: asked.value }, 200, noStore);
8187 });
src/http/lazy_lists.ts +1
@@ -84,6 +84,7 @@ export const SETTINGS_ROUTES = [
8484 ["POST", "/settings/passkeys/:id/delete"],
8585 ["GET", "/settings/identities"],
8686 ["POST", "/settings/identities"],
87 ["POST", "/settings/identities/minecraft"],
8788 ["POST", "/settings/identities/:id/confirm"],
8889 ["POST", "/settings/identities/:id/use"],
8990 ["POST", "/settings/identities/:id/delete"],
src/http/marks/settings.json +1
@@ -58,6 +58,7 @@
5858 "/settings/passkeys/options": "open",
5959 "/settings/passkeys/:id/delete": "open",
6060 "/settings/identities": "open",
61 "/settings/identities/minecraft": "open",
6162 "/settings/identities/:id/confirm": "open",
6263 "/settings/identities/:id/use": "open",
6364 "/settings/identities/:id/delete": "open",
src/http/settings_routes.ts +2 −1
@@ -51,7 +51,7 @@ import { confirmsList, confirmYes } from "../web/pages/confirms.ts";
5151 import { captainAct, captainPage } from "../web/pages/captain.ts";
5252 import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-settings.ts";
5353 import { featureAccept, featurePage, featureRun, featureSave, featuresPage, featureSwitch } from "../web/pages/features.ts";
54 import { identityAdd, identityConfirm, identityRemove, identitiesPage, identityUse } from "../web/pages/identities.ts";
54 import { identityAdd, identityAddMinecraft, identityConfirm, identityRemove, identitiesPage, identityUse } from "../web/pages/identities.ts";
5555 import { visitorBringPage, visitorBringSubmit, visitorBringUndo } from "../web/pages/visitor_bring.ts";
5656 import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts";
5757 import { deviceCap, deviceDeclare, deviceGrant, devicesPage, deviceRemove, deviceRevoke } from "../web/settings/devices.ts";
@@ -235,6 +235,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
235235 router.add("POST", "/settings/passkeys/:id/delete", passkeyDelete);
236236 router.add("GET", "/settings/identities", identitiesPage);
237237 router.add("POST", "/settings/identities", identityAdd);
238 router.add("POST", "/settings/identities/minecraft", identityAddMinecraft);
238239 router.add("POST", "/settings/identities/:id/confirm", identityConfirm);
239240 router.add("POST", "/settings/identities/:id/use", identityUse);
240241 router.add("POST", "/settings/identities/:id/delete", identityRemove);
src/tui/forge_parts.ts +3 −3
@@ -603,12 +603,12 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
603603 hint: "the passkeys that sign in as you",
604604 run: () => ctx.push(passkeysScreen(session, ctx)),
605605 });
606 // Settings › Proven emails and `/api/v1/connections`: one set of actions (#18108).
606 // Settings › Proven identities and `/api/v1/connections`: one set of actions (#18108).
607607 if (session.signedIn && session.user?.kind !== "agent")
608608 commands.push({
609609 id: "proven-emails",
610 title: "Proven emails",
611 hint: "the addresses I proved, and what each is for",
610 title: "Proven identities",
611 hint: "the emails and Minecraft names I proved, and what each is for",
612612 run: () => ctx.push(identitiesScreen(session, ctx)),
613613 });
614614 // Settings › Brought in: the receipts, and undo (#18113).
src/tui/screens/identities.ts +23 −9
@@ -1,13 +1,14 @@
11 /**
2 * Proven emails in the terminal (#18108), as Settings › Proven emails: `a` adds an address and
3 * mails a code, `c` gives the code back, `f` and `p` switch the feedback and profile uses on or
2 * Proven identities in the terminal (#18108), as Settings › Proven identities: `a` adds an address
3 * and mails a code, `c` gives the code back, `m` keeps a Minecraft name the game door proves
4 * (#18221), `f` and `p` switch the feedback and profile uses on or
45 * off, `d` removes after a y/n. The same actions as the API and the page, so the same gates and
56 * words; the list is the signed-in account's own.
67 */
78
89 import {
9 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf,
10 dropConnection,
10 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse,
11 confirmConnection, connectionsOf, dropConnection,
1112 } from "../../actions/identities.ts";
1213 import type { Use } from "../../core/identities.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
@@ -24,10 +25,10 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen {
2425 const items = () => (f.user === undefined ? [] : connectionsOf(f.app, f.user));
2526 const rows = (): ListRow[] =>
2627 items().map((c) => ({
27 title: c.ident,
28 title: c.kind === "minecraft" ? `${c.ident} (Minecraft)` : c.ident,
2829 meta: c.proven
2930 ? `proven · feedback ${c.uses.feedback ? "on" : "off"} · profile ${c.uses.profile ? "on" : "off"}`
30 : "not proven yet: c gives the code",
31 : c.kind === "minecraft" ? "not proven yet: link it in game" : "not proven yet: c gives the code",
3132 }));
3233 const toggle = (use: Use): boolean => {
3334 const c = items()[state.index];
@@ -39,9 +40,10 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen {
3940 };
4041
4142 const screen: Screen = {
42 title: "Proven emails",
43 title: "Proven identities",
4344 keys: [
44 binding(["j", "k"], "move cursor"), binding(["a"], "add"), binding(["c"], "give the code"),
45 binding(["j", "k"], "move cursor"), binding(["a"], "add"), binding(["m"], "add a Minecraft name"),
46 binding(["c"], "give the code"),
4547 binding(["f"], "feedback on/off"), binding(["p"], "profile on/off"), binding(["d"], "remove"),
4648 ],
4749 render(area, s) {
@@ -67,10 +69,22 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen {
6769 }));
6870 return true;
6971 }
72 if (e.key === "m") {
73 ctx.push(promptScreen(ctx, screen, {
74 title: "Add a Minecraft name", label: "Name", hint: "proven when you link it in game",
75 onSubmit: (v) => {
76 const kept = addMinecraftConnection(f.app, user, v);
77 note = !kept.ok ? CONNECTION_WORDS[kept.error] : kept.value.proven ? "Added, and proven by your link in game." : MINECRAFT_PROOF;
78 ctx.invalidate();
79 return undefined;
80 },
81 }));
82 return true;
83 }
7084 if (e.key === "f") return toggle("feedback");
7185 if (e.key === "p") return toggle("profile");
7286 if (c === undefined) return false;
73 if (e.key === "c" && !c.proven) {
87 if (e.key === "c" && c.kind === "email" && !c.proven) {
7488 ctx.push(promptScreen(ctx, screen, {
7589 title: `Prove ${c.ident}`, label: "Code", hint: "the code from the mail",
7690 onSubmit: (v) => {
src/web/pages/identities.ts +29 −12
@@ -1,14 +1,15 @@
11 /**
2 * Settings › Proven emails (#18108): the addresses an account proved, each with its own uses, all
3 * off until chosen. Server-rendered; every act is a same-origin form (`readForm`), by the signed-in
4 * account alone, through the actions the API and the terminal use. The note beside the uses says
5 * what switching off does not undo.
2 * Settings › Proven identities (#18108): the addresses an account proved, and its Minecraft names
3 * (#18221, proven by the game door's link), each with its own uses, all off until chosen.
4 * Server-rendered; every act is a same-origin form (`readForm`), by the signed-in account alone,
5 * through the actions the API and the terminal use. The note beside the uses says what switching
6 * off does not undo.
67 */
78
89 import { sshOn } from "../../settings/ssh.ts";
910 import {
10 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf,
11 dropConnection,
11 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse,
12 confirmConnection, connectionsOf, dropConnection,
1213 } from "../../actions/identities.ts";
1314 import { USES, type Connection, type Use } from "../../core/identities.ts";
1415 import type { Ctx } from "../../http/context.ts";
@@ -38,6 +39,8 @@ const card = (c: Connection): Html => {
3839 ${btn(c.uses[u] ? "Turn off" : "Turn on", { size: "sm", label: `${c.uses[u] ? "Turn off" : "Turn on"} ${u} for ${c.ident}` })}`,
3940 ),
4041 )
42 : c.kind === "minecraft"
43 ? html`<p class="muted small">${MINECRAFT_PROOF}</p>`
4144 : act(
4245 "confirm",
4346 html`<input class="input mono" type="text" name="code" inputmode="numeric" maxlength="20" autocomplete="off"
@@ -46,7 +49,7 @@ const card = (c: Connection): Html => {
4649 );
4750 return row({
4851 title: html`<span class="mono">${c.ident}</span>`,
49 meta: html`${c.proven ? "proven" : "not proven yet"}`,
52 meta: html`${c.kind === "minecraft" ? "Minecraft · " : ""}${c.proven ? "proven" : "not proven yet"}`,
5053 trail: act("delete", btn("Remove", { size: "sm", icon: "x", label: `Remove ${c.ident}` })),
5154 after: html`${uses}`,
5255 });
@@ -58,20 +61,25 @@ export function identitiesPage(ctx: Ctx): Response {
5861 if (!ctx.auth.user) return signInFirst(ctx);
5962 const list = connectionsOf(ctx.app, ctx.auth.user);
6063 const body = html`<section class="settings-block">
61 <h2>Proven emails</h2>
62 <p class="muted small">An address you prove is yours, and what it may be used for. Every use is off until you turn it on.</p>
63 ${list.length === 0 ? html`<p class="muted">None yet.</p>` : rowList(list.map(card), { bare: true, label: "Proven emails" })}
64 <h2>Proven identities</h2>
65 <p class="muted small">An address or Minecraft name you prove is yours, and what it may be used for. Every use is off until you turn it on.</p>
66 ${list.length === 0 ? html`<p class="muted">None yet.</p>` : rowList(list.map(card), { bare: true, label: "Proven identities" })}
6467 <p class="muted small">${NOT_RETROACTIVE}</p>
6568 <form class="edit-row mt" method="post" action="${HERE}">
6669 <input class="input" type="email" name="email" placeholder="[email protected]" aria-label="Email address" maxlength="254" autocomplete="off" required />
6770 ${btn("Send a code", { variant: "primary", size: "sm", icon: "plus" })}
6871 </form>
72 <form class="edit-row mt" method="post" action="${HERE}/minecraft">
73 <input class="input mono" type="text" name="minecraft" placeholder="Minecraft name" aria-label="Minecraft name" maxlength="16"
74 pattern="[A-Za-z0-9_]{3,16}" autocomplete="off" required />
75 ${btn("Add the name", { size: "sm", icon: "plus" })}
76 </form>
6977 </section>`;
7078 const rendering = performance.now();
7179 const response = page({
7280 ctx,
73 title: "Proven emails",
74 body: html`${pageHead("Proven emails", { sub: "The addresses you proved are yours, and what each is for." })}
81 title: "Proven identities",
82 body: html`${pageHead("Proven identities", { sub: "The addresses and Minecraft names you proved are yours, and what each is for." })}
7583 ${settingsLayout(accountSections("identities", { admin: ctx.auth.user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
7684 });
7785 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -96,6 +104,15 @@ export async function identityAdd(ctx: Ctx): Promise<Response> {
96104 return said(ctx, made.ok ? "A code was mailed. Give it here to prove the address." : CONNECTION_WORDS[made.error], made.ok);
97105 }
98106
107 // POST /settings/identities/minecraft
108 export async function identityAddMinecraft(ctx: Ctx): Promise<Response> {
109 const got = await acting(ctx);
110 if (got instanceof Response) return got;
111 const kept = addMinecraftConnection(ctx.app, ctx.auth.user!, field(got.form, "minecraft"));
112 if (!kept.ok) return said(ctx, CONNECTION_WORDS[kept.error], false);
113 return said(ctx, kept.value.proven ? "Added, and proven by the link you already made in game." : `Added. ${MINECRAFT_PROOF}`, true);
114 }
115
99116 // POST /settings/identities/:id/confirm
100117 export async function identityConfirm(ctx: Ctx): Promise<Response> {
101118 const got = await acting(ctx);
src/web/pages/origins.ts +1 −1
@@ -181,7 +181,7 @@ const SECTION_ROWS: readonly (readonly [
181181 ["Crew and AI", "Subscriptions", "/settings/subscriptions", "key", (c) => c === "subscriptions", true],
182182 ["Crew and AI", "Usage", "/settings/spend", "activity", (c) => USAGE.has(c), true],
183183 ["Connections", "Connected accounts", "/settings/origins", "globe", (c) => c === "origins", false],
184 ["Connections", "Proven emails", "/settings/identities", "check", (c) => c === "identities", false],
184 ["Connections", "Proven identities", "/settings/identities", "check", (c) => c === "identities", false],
185185 ["Connections", "Cloud", "/settings/cloud", "key", (c) => c === "cloud", true],
186186 ["Connections", "Infrastructure", "/infra", "globe", () => false, true], // what runs there and what it costs
187187 ["Connections", "Secrets", "/settings/secrets", "lock", (c) => c === "secrets", true],
src/web/palette_rows.ts +1 −1
@@ -50,7 +50,7 @@ export function settingsRows(user: User | undefined): PaletteRow[] {
5050 { t: "Appearance", h: "/settings/appearance", c: "Settings" },
5151 { t: "Password", h: "/settings/password", c: "Settings" },
5252 { t: "Passkeys", h: "/settings/passkeys", c: "Settings" },
53 { t: "Proven emails", h: "/settings/identities", c: "Settings" },
53 { t: "Proven identities", h: "/settings/identities", c: "Settings" },
5454 // The crew's model credentials are the admin's (`/settings/subscriptions` answers anyone else 403).
5555 ...(user.isAdmin
5656 ? [
test/identities-doors.test.ts +23 −3
@@ -1,7 +1,7 @@
11 /**
2 * The two doors of connections on an account (#18108): Settings › Proven emails and the terminal
3 * screen. Both gate on the signed-in account, answer a form only same-origin, escape what they
4 * show, and act through the same actions as the API.
2 * The two doors of connections on an account (#18108): Settings › Proven identities and the
3 * terminal screen. Both gate on the signed-in account, answer a form only same-origin, escape what
4 * they show, and act through the same actions as the API.
55 */
66 import { afterAll, beforeAll, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
@@ -114,3 +114,23 @@ test("the terminal screen lists the account's own, switches a use and removes",
114114 const anon = identitiesScreen({ app, db: app.db, user: undefined } as unknown as Session, ctx);
115115 expect(anon.key!(key("f"))).toBe(false);
116116 });
117
118 test("a Minecraft name is added by the page's form and the terminal's m, shown unproven with how to prove it", async () => {
119 expect((await form("/settings/identities/minecraft", { minecraft: "Tess_<b>" }, "https://evil.example")).status).toBe(403);
120 expect((await form("/settings/identities/minecraft", { minecraft: "Tess_<b>" })).status).toBe(303);
121 expect(listConnections(app.db, tess.id).some((c) => c.kind === "minecraft")).toBe(false);
122 expect((await form("/settings/identities/minecraft", { minecraft: "Tess_MC" })).status).toBe(303);
123 const c = listConnections(app.db, tess.id).find((x) => x.kind === "minecraft")!;
124 expect(c).toMatchObject({ ident: "tess_mc", proven: false });
125 const html = await (await fetch(`${servers.url}/settings/identities`, { headers: { cookie } })).text();
126 expect(html).toContain("tess_mc");
127 expect(html).toContain("Minecraft · not proven yet");
128 expect(html).toContain("!forge link &lt;code&gt;");
129 await form(`/settings/identities/${c.id}/delete`, {});
130
131 const pushed: { key?: (e: KeyEvent) => boolean }[] = [];
132 const ctx = { theme: theme("dark"), icons: "nerd", invalidate() {}, push: (s: never) => pushed.push(s) } as unknown as Ctx;
133 const screen = identitiesScreen({ app, db: app.db, user: tess } as unknown as Session, ctx);
134 expect(screen.key!({ type: "key", key: "m", ctrl: false, alt: false, shift: false })).toBe(true);
135 expect(pushed).toHaveLength(1);
136 });
test/identities.test.ts +79 −2
@@ -3,7 +3,9 @@
33 * mailed code, and the lookup answers nothing until the feedback use is on,
44 * then the user, then nothing again once the connection is removed. A second
55 * account cannot take a proven address; a report names its reporter only in
6 * the middle step.
6 * the middle step. A Minecraft name (#18221) is added unproven, proven by the
7 * game door's link, and likewise taken by one account only; unlinking it in
8 * game unproves it.
79 */
810 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
911 import { mkdtemp, rm } from "node:fs/promises";
@@ -14,8 +16,9 @@ import { fileReport } from "../src/actions/reports.ts";
1416 import { reporterFor } from "../src/actions/identities.ts";
1517 import { createApp, type App } from "../src/app.ts";
1618 import { createSession } from "../src/core/sessions.ts";
19 import { unlink } from "../src/games/chat.ts";
1720 import { createUser, type User } from "../src/core/users.ts";
18 import { AUDIT_KEEP_MS, LOOKUPS_PER_MINUTE, auditLookup } from "../src/core/identities.ts";
21 import { AUDIT_KEEP_MS, LOOKUPS_PER_MINUTE, auditLookup, proveMinecraft } from "../src/core/identities.ts";
1922 import type { Repo } from "../src/core/repos.ts";
2023 import type { Mail } from "../src/kernel/mail.ts";
2124 import { serve, type Servers } from "../src/http/server.ts";
@@ -134,6 +137,80 @@ describe("connections on an account", () => {
134137 expect(listed.note).toContain("not rewritten");
135138 });
136139
140 test("a Minecraft name is added unproven, proven by the game's link, and a second account cannot take it", async () => {
141 const added = await call("POST", "/api/v1/connections", tessCookie, { minecraft: " Tess_Plays " });
142 expect(added.status).toBe(201);
143 const c = ((await added.json()) as any).connection;
144 expect(c).toMatchObject({ kind: "minecraft", ident: "tess_plays", proven: false, uses: { feedback: false, profile: false } });
145 expect((await call("POST", "/api/v1/connections", tessCookie, { minecraft: "no spaces!" })).status).toBe(422);
146 // Listed beside email, unproven: no code proves it, no use can be chosen, the lookup says
147 // nothing.
148 const listed = (await (await call("GET", "/api/v1/connections", tessCookie)).json()) as any;
149 expect(listed.connections.find((x: any) => x.id === c.id)).toMatchObject({ kind: "minecraft", proven: false });
150 expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: "123456" })).status).toBe(404);
151 expect((await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, tessCookie, { on: true })).status).toBe(404);
152 expect((await ask("x", "feedback")).error).toBe("invalid");
153 const askMc = (name: string) =>
154 call("POST", "/api/v1/connections/lookup", "", { minecraft: name, use: "feedback" }, { "x-forge-lookup-key": key }).then((r) => r.json() as Promise<any>);
155 expect((await askMc("tess_plays")).user).toBeNull();
156
157 // The game door's link proves it (games/chat.ts calls this once the player is linked).
158 expect(proveMinecraft(app.db, tess.id, "Tess_Plays", Date.now())).toBe(true);
159 await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, tessCookie, { on: true });
160 expect((await askMc("TESS_PLAYS")).user).toEqual({ username: "tess" });
161 expect((await ask("[email protected]")).user).toBeNull();
162
163 // A second account may keep the name, but the game's link never proves it there.
164 const otto = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'otto'").get()!.id;
165 const twice = await call("POST", "/api/v1/connections", otherCookie, { minecraft: "tess_plays" });
166 expect(twice.status).toBe(201);
167 expect(proveMinecraft(app.db, otto, "tess_plays", Date.now())).toBe(false);
168 expect(((await twice.json()) as any).connection.proven).toBe(false);
169 expect((await askMc("tess_plays")).user).toEqual({ username: "tess" });
170
171 // Removed: nothing again.
172 expect((await call("DELETE", `/api/v1/connections/${c.id}`, tessCookie)).status).toBe(200);
173 expect((await askMc("tess_plays")).user).toBeNull();
174 const after = (await (await call("GET", "/api/v1/connections", tessCookie)).json()) as any;
175 expect(after.connections.some((x: any) => x.kind === "minecraft")).toBe(false);
176 });
177
178 test("a Minecraft name the account already linked in game is proven when it is added", async () => {
179 app.db.query("INSERT INTO game_link (box_id, player, user_id, uuid, created_at) VALUES ('box1', 'Olive_MC', ?1, 'u-1', ?2)")
180 .run(admin.id, new Date().toISOString());
181 const added = await call("POST", "/api/v1/connections", adminCookie, { minecraft: "olive_mc" });
182 expect(((await added.json()) as any).connection).toMatchObject({ kind: "minecraft", ident: "olive_mc", proven: true });
183 const other = await call("POST", "/api/v1/connections", adminCookie, { minecraft: "olive_alt" });
184 expect(((await other.json()) as any).connection.proven).toBe(false);
185 for (const c of ((await (await call("GET", "/api/v1/connections", adminCookie)).json()) as any).connections)
186 await call("DELETE", `/api/v1/connections/${c.id}`, adminCookie);
187 });
188
189 test("unlinking the game link that proved a Minecraft name unproves it, so the lookup answers null", async () => {
190 const link = (box: string) =>
191 app.db.query("INSERT INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'Ivy_MC', ?2, 'u-ivy', ?3)")
192 .run(box, admin.id, new Date().toISOString());
193 link("box-a");
194 link("box-b");
195 const c = ((await (await call("POST", "/api/v1/connections", adminCookie, { minecraft: "ivy_mc" })).json()) as any).connection;
196 expect(c.proven).toBe(true);
197 await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, adminCookie, { on: true });
198 const askMc = () =>
199 call("POST", "/api/v1/connections/lookup", "", { minecraft: "ivy_mc", use: "feedback" }, { "x-forge-lookup-key": key }).then((r) => r.json() as Promise<any>);
200 expect((await askMc()).user).toEqual({ username: admin.username });
201
202 // Still linked on another box: still proven.
203 unlink(app, admin.id, "box-a", "Ivy_MC");
204 expect((await askMc()).user).toEqual({ username: admin.username });
205
206 // The last link gone: unproven, its uses off, and the lookup says nothing.
207 unlink(app, admin.id, "box-b", "Ivy_MC");
208 expect((await askMc()).user).toBeNull();
209 const after = ((await (await call("GET", "/api/v1/connections", adminCookie)).json()) as any).connections.find((x: any) => x.id === c.id);
210 expect(after).toMatchObject({ proven: false, uses: { feedback: false, profile: false } });
211 await call("DELETE", `/api/v1/connections/${c.id}`, adminCookie);
212 });
213
137214 test("a key's name that is wrong says so; one account's mail is capped however many addresses it adds", async () => {
138215 const bad = await call("POST", "/api/v1/connections/lookup-keys", adminCookie, { name: "<b>" });
139216 expect(bad.status).toBe(422);
test/palette-roster.test.ts +2 −2
@@ -124,7 +124,7 @@ test("a site-admin person is offered the whole roster", () => {
124124 ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"],
125125 ["fork-flows", "Fork flows", "what I follow, what I offered, what my forks offered me"],
126126 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
127 ["proven-emails", "Proven emails", "the addresses I proved, and what each is for"],
127 ["proven-emails", "Proven identities", "the emails and Minecraft names I proved, and what each is for"],
128128 ["visitor-bring", "Brought in", "what I made before signing in; u undoes"],
129129 ["account", "Account settings", undefined],
130130 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
@@ -481,7 +481,7 @@ test("a member person is offered the signed-in roster without the admin entries"
481481 ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"],
482482 ["fork-flows", "Fork flows", "what I follow, what I offered, what my forks offered me"],
483483 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
484 ["proven-emails", "Proven emails", "the addresses I proved, and what each is for"],
484 ["proven-emails", "Proven identities", "the emails and Minecraft names I proved, and what each is for"],
485485 ["visitor-bring", "Brought in", "what I made before signing in; u undoes"],
486486 ["account", "Account settings", undefined],
487487 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
test/schema-additive.test.ts +1
@@ -187,6 +187,7 @@ const REBUILT: Record<string, string> = {
187187 "20261104100000-conversation-run-stopped-state": "conversation_run widens its state CHECK to admit stopped (#8972); same columns, same rows, the stopped column kept",
188188 "20261114000000-estimate-done": "issue_estimate widens its event CHECK to admit done (#11955); same columns, same rows, the indexes made again; the release before never writes or reads a done row",
189189 "20261110170000-fork-follow-dont-follow": "fork_follow widens its mode CHECK to admit dont-follow (#608); same columns, same rows; the release before reads dont-follow as not take-updates",
190 "20261204120000-connection-minecraft": "connection widens its kind CHECK to admit minecraft (#18221); same columns, same rows, both unique indexes made again; the release before lists a minecraft row as it lists an email, its lookup asks kind = 'email' only, and nothing refers to the table",
190191 "20261114010000-machine-sample-hourly": "machine_sample widens its step CHECK to admit 3600 (#12007); same columns, same rows; the release before reads by step 15 or 300 and deletes past 30 days what an hourly row would hold",
191192 };
192193

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs