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

Connections on an account: verified identities the person controls, each with its own uses, and a lookup that answers only on opt-in #18120

opened this in answer to

Merged 6h 54m ago, live in production

scout/forge:scout/18108-connections-on-an-account-verified-ident → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18108-connections-on-an-account-verified-ident was merged into main as 314f4eb.

Review

Sign in to review this change.
35 files changed +1430 −199
docs/design/attention-budget.json +3 −3
@@ -115,16 +115,16 @@
115115 },
116116 "settings": {
117117 "390": {
118 "words": 153,
118 "words": 155,
119119 "blocks": 32,
120120 "colours": 1
121121 },
122122 "1280": {
123 "words": 153,
123 "words": 155,
124124 "blocks": 32,
125125 "colours": 1
126126 },
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it; 153 since Settings › Who may do what (#18105), four words: every account sees what it may do and through which grant, so the row is on every account's nav."
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it; 153 since Settings › Who may do what (#18105), four words: every account sees what it may do and through which grant, so the row is on every account's nav. 155 since Settings › Proven emails (#18108), two words: its side-nav entry, so a person finds where their verified addresses are kept."
128128 },
129129 "search": {
130130 "390": {
docs/design/audit.md +1
@@ -196,6 +196,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
196196 - `/settings/teams` — `pages/teams.ts` · the named crew teams, each with a charter, a dial and members · `/settings/crew` · none seen.
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.
199 - `/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.
199200 - `/settings/security` — `pages/security.ts` · the Shield and the evidence an admin needs to act with no AI · `/settings/traffic`, `/settings/backups` · none seen.
200201 - `/settings/security/controls` — `pages/security_controls.ts` · one line per RED-TEAM control and when it was last checked · `/settings/security` · none seen.
201202 - `/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 added +37
@@ -0,0 +1,37 @@
1 ---
2 topic: Every setting, by topic
3 row: Identities on an account: proven emails, each with its own opt-in uses, and the integrations' lookup
4 ---
5 # Identities on an account
6
7 A person keeps a list of proven "yes, I am this" claims (#18108). Today the kind is an
8 email; each is unproven until the code mailed to it (through the forge's mail key) is given
9 back: kept as a hash, spent once, good half an hour, five tries. One address is proven by one
10 account; a second cannot take it. Each proven one has uses, all off by default: `feedback`
11 ("name me on app feedback and crash reports") and `profile`.
12
13 - **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`.
21 - **Reports**: `POST …/reports` with a lookup key and `reporter` (an address) names the
22 reporter only through the `feedback` use. Removing the connection or switching the use off
23 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.
28 - **What it does not reveal**: adding an address another account proved answers as any new address
29 does (201, nothing mailed to its owner; the code never proves, so a member cannot learn whether an
30 address is proven here). Only the mail cap on an address (3 a day) can still differ.
31 - **Mail**: a member's sends are capped by account (20 a day, `connection:<id>` scope of
32 `sendCapped`, so add-then-remove cycles do not evade it), by address and by the forge.
33 - **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.
36
37 `test/identities.test.ts` walks add, prove, opt in, remove; `test/identities-doors.test.ts` the page and the screen.
src/actions/identities.ts added +149
@@ -0,0 +1,149 @@
1 /**
2 * Connections on an account (#18108): add an email, prove it with the code
3 * mailed to it, choose what it is for, remove it; and the lookup a trusted
4 * integration asks. The lookup is a permission check: it answers the forge
5 * user only when a proven connection has that use on, and the same nothing
6 * for unknown, unproven and not opted in. Mail goes through the forge's mail
7 * key (`mailerOf`), never a provider's own API.
8 */
9
10 import type { App } from "../app.ts";
11 import {
12 addEmail, auditLookup, cleanEmail, listConnections, lookup, lookupKeyId, mintLookupKey,
13 proveEmail, removeConnection, revokeLookupKey, setUse, isUse,
14 type Connection,
15 } from "../core/identities.ts";
16 import { getUserById, type User } from "../core/users.ts";
17 import { err, ok, type Result } from "../kernel/result.ts";
18 import { mailerOf } from "./verify.ts";
19 import { sendCapped } from "./mail.ts";
20
21 export type ConnectionError =
22 | "invalid_email" | "limit" | "taken" | "too_soon" | "no_mail" | "capped" | "failed"
23 | "wrong_code" | "not_found" | "invalid_use" | "invalid_name";
24
25 /** What each refusal says, for the API, the settings page and the terminal alike. */
26 export const CONNECTION_WORDS: Record<ConnectionError, string> = {
27 invalid_email: "that is not an email address",
28 limit: "an account keeps at most 10 connections; remove one first",
29 taken: "that address cannot be added to this account",
30 too_soon: "a code was sent a moment ago; wait a minute",
31 no_mail: "this forge sends no mail, so an email cannot be proven here",
32 capped: "the forge's mail limits hold this message; try later",
33 failed: "the code could not be sent",
34 wrong_code: "that code is wrong or has expired",
35 not_found: "no such connection",
36 invalid_use: "use is feedback or profile, and on is true or false",
37 invalid_name: "a key's name is 1 to 60 letters, digits, spaces, dots, dashes or underscores",
38 };
39
40 /** What the settings page says beside the uses: removing or switching off is not retroactive. */
41 export const NOT_RETROACTIVE =
42 "Removing a connection, or switching a use off, stops later reports naming you. Issues already filed are not rewritten.";
43
44 export const connectionsOf = (app: App, user: User): Connection[] => listConnections(app.db, user.id);
45
46 /** Start proving an email: the connection is unproven until the mailed code is given back. */
47 export async function addConnection(
48 app: App, user: User, rawEmail: unknown, now = Date.now(),
49 ): Promise<Result<Connection, ConnectionError>> {
50 const email = cleanEmail(rawEmail);
51 if (email === undefined) return err("invalid_email");
52 const mailer = mailerOf(app, user);
53 if (mailer === undefined) return err("no_mail");
54 const made = addEmail(app.db, user.id, email, now);
55 if (typeof made === "string") return err(made);
56 // Held by another account: the same answer, and no mail to its owner.
57 if (made.held) return ok(made.connection);
58 // The per-account scope caps what one member can have the forge mail in a day, however many
59 // addresses they add and remove; the address and forge-wide caps are `sendCapped`'s own.
60 const sent = await sendCapped(app, mailer, {
61 to: email,
62 subject: "Prove this address on the forge",
63 text: [
64 `Hello ${user.username},`, "",
65 `Your code is ${made.code}. Give it back on the forge to prove this address is yours.`,
66 "It works once, for half an hour.", "",
67 "If you did not ask, ignore this message.",
68 ].join("\n"),
69 }, now, `connection:${user.id}`);
70 if (sent !== "sent") {
71 removeUnproven(app, user, made.connection.id);
72 return err(sent);
73 }
74 return ok(made.connection);
75 }
76
77 const removeUnproven = (app: App, user: User, id: string): void => {
78 const c = listConnections(app.db, user.id).find((x) => x.id === id);
79 if (c && !c.proven) removeConnection(app.db, user.id, id);
80 };
81
82 export function confirmConnection(
83 app: App, user: User, id: string, code: unknown, now = Date.now(),
84 ): Result<Connection, ConnectionError> {
85 if (typeof code !== "string" || code.length > 20) return err("wrong_code");
86 const proved = proveEmail(app.db, user.id, id, code, now);
87 if (proved === "none") return err("not_found");
88 if (proved !== "proven") return err(proved === "taken" ? "taken" : "wrong_code");
89 return ok(listConnections(app.db, user.id).find((c) => c.id === id)!);
90 }
91
92 export function dropConnection(app: App, user: User, id: string): Result<true, ConnectionError> {
93 return removeConnection(app.db, user.id, id) ? ok(true) : err("not_found");
94 }
95
96 export function chooseUse(
97 app: App, user: User, id: string, use: unknown, on: unknown,
98 ): Result<Connection, ConnectionError> {
99 if (!isUse(use) || typeof on !== "boolean") return err("invalid_use");
100 const c = setUse(app.db, user.id, id, use, on);
101 return c ? ok(c) : err("not_found");
102 }
103
104 export type LookupRefusal = "unauthorized" | "rate_limited" | "invalid";
105
106 /**
107 * The integration's question: who, if anyone, chose to be named for this use at this address.
108 * `null` is the one answer for every way of not knowing.
109 */
110 export function findNamed(
111 app: App, presentedKey: string, ident: unknown, use: unknown, now = Date.now(),
112 ): Result<User | null, LookupRefusal> {
113 const keyId = lookupKeyId(app.db, presentedKey);
114 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);
118 if (!auditLookup(app.db, keyId, use, who !== undefined, now)) return err("rate_limited");
119 return ok((who === undefined ? undefined : getUserById(app.db, who)) ?? null);
120 }
121
122 /** `findNamed`, as the API answers it: the username only. */
123 export function askLookup(
124 app: App, presentedKey: string, ident: unknown, use: unknown, now = Date.now(),
125 ): Result<{ username: string } | null, LookupRefusal> {
126 const found = findNamed(app, presentedKey, ident, use, now);
127 return found.ok ? ok(found.value === null ? null : { username: found.value.username }) : found;
128 }
129
130 /**
131 * The reporter a trusted integration may name, for a report it files: the lookup for the feedback
132 * use, or nobody. No key, no lookup: a report without the header touches no table.
133 */
134 export function reporterFor(app: App, presentedKey: string, ident: unknown, now = Date.now()): User | undefined {
135 if (presentedKey === "") return undefined;
136 const found = findNamed(app, presentedKey, ident, "feedback", now);
137 return found.ok ? found.value ?? undefined : undefined;
138 }
139
140 /** An admin makes (and may revoke) the key an integration's lookups carry. */
141 export function makeLookupKey(app: App, admin: User, name: unknown): Result<{ id: string; key: string }, "not_found" | "invalid_name"> {
142 if (!admin.isAdmin) return err("not_found");
143 if (typeof name !== "string" || !/^[\w .-]{1,60}$/.test(name.trim())) return err("invalid_name");
144 return ok(mintLookupKey(app.db, name.trim(), admin.id, Date.now()));
145 }
146
147 export function dropLookupKey(app: App, admin: User, id: string): Result<true, "not_found"> {
148 return admin.isAdmin && revokeLookupKey(app.db, id, Date.now()) ? ok(true) : err("not_found");
149 }
src/actions/reports.ts +6 −1
@@ -104,6 +104,11 @@ export function fileReport(
104104 input: ReportInput,
105105 source: string,
106106 filer?: User,
107 /**
108 * Whom a trusted integration's lookup named for this report (`reporterFor`): only through an
109 * opt-in.
110 */
111 reporter?: User,
107112 ): Result<Report, FileRefusal> {
108113 if (!canRead(app.db, repo, undefined)) return err({ error: "not_found" });
109114 if (reportsClosed(app.db, repo.id)) return err({ error: "closed" });
@@ -135,7 +140,7 @@ export function fileReport(
135140 app.db,
136141 repo.id,
137142 clean.value,
138 filer?.kind === "org" ? null : (filer?.id ?? null),
143 (filer ?? reporter)?.kind === "org" ? null : ((filer ?? reporter)?.id ?? null),
139144 );
140145 app.bus.append({
141146 kind: "report.received",
src/contract/openapi/routes/deleteApiV1ConnectionsId.ts added +15
@@ -0,0 +1,15 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: "/api/v1/connections/{id}",
6 summary: "Remove a connection from the account",
7 auth: true,
8 role: "member",
9 reply: { removed: "boolean", note: "string" },
10 refusals: {
11 not_found: "no such connection on this account (404)",
12 forbidden: "the request is cross-origin, or the token may only read",
13 },
14 refuses: [401, 404],
15 };
src/contract/openapi/routes/deleteApiV1ConnectionsLookupKeysId.ts added +12
@@ -0,0 +1,12 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: "/api/v1/connections/lookup-keys/{id}",
6 summary: "Revoke a lookup key (admin)",
7 auth: true,
8 role: "admin",
9 reply: { revoked: "boolean" },
10 refusals: { not_found: "no such key, or the caller does not administer the forge (404)" },
11 refuses: [401, 404],
12 };
src/contract/openapi/routes/getApiV1Connections.ts added +12
@@ -0,0 +1,12 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/connections",
6 summary: "List the signed-in account's connections and what each is used for",
7 detail: "List the account's connections (an email, proven or not) with the uses chosen for each. A use is opt-in and not retroactive",
8 auth: true,
9 role: "member",
10 reply: { connections: "array", note: "string" },
11 refuses: [401],
12 };
src/contract/openapi/routes/index.ts +8
@@ -6,6 +6,8 @@ export { route as deleteApiV1AdminRunnersId } from "./deleteApiV1AdminRunnersId.
66 export { route as deleteApiV1AgentsUsername } from "./deleteApiV1AgentsUsername.ts";
77 export { route as deleteApiV1BoardsSlug } from "./deleteApiV1BoardsSlug.ts";
88 export { route as deleteApiV1CodesId } from "./deleteApiV1CodesId.ts";
9 export { route as deleteApiV1ConnectionsId } from "./deleteApiV1ConnectionsId.ts";
10 export { route as deleteApiV1ConnectionsLookupKeysId } from "./deleteApiV1ConnectionsLookupKeysId.ts";
911 export { route as deleteApiV1ConversationFilesId } from "./deleteApiV1ConversationFilesId.ts";
1012 export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1ConversationQueueId.ts";
1113 export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts";
@@ -91,6 +93,7 @@ export { route as getApiV1Changelog } from "./getApiV1Changelog.ts";
9193 export { route as getApiV1CloudAccounts } from "./getApiV1CloudAccounts.ts";
9294 export { route as getApiV1Codes } from "./getApiV1Codes.ts";
9395 export { route as getApiV1Config } from "./getApiV1Config.ts";
96 export { route as getApiV1Connections } from "./getApiV1Connections.ts";
9497 export { route as getApiV1Contribute } from "./getApiV1Contribute.ts";
9598 export { route as getApiV1ConversationFilesId } from "./getApiV1ConversationFilesId.ts";
9699 export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns.ts";
@@ -381,6 +384,10 @@ export { route as postApiV1BoardsQuery } from "./postApiV1BoardsQuery.ts";
381384 export { route as postApiV1BrokerOrigins } from "./postApiV1BrokerOrigins.ts";
382385 export { route as postApiV1Builds } from "./postApiV1Builds.ts";
383386 export { route as postApiV1Codes } from "./postApiV1Codes.ts";
387 export { route as postApiV1Connections } from "./postApiV1Connections.ts";
388 export { route as postApiV1ConnectionsIdConfirm } from "./postApiV1ConnectionsIdConfirm.ts";
389 export { route as postApiV1ConnectionsLookup } from "./postApiV1ConnectionsLookup.ts";
390 export { route as postApiV1ConnectionsLookupKeys } from "./postApiV1ConnectionsLookupKeys.ts";
384391 export { route as postApiV1Contribute } from "./postApiV1Contribute.ts";
385392 export { route as postApiV1ConversationAgain } from "./postApiV1ConversationAgain.ts";
386393 export { route as postApiV1ConversationConfirmsId } from "./postApiV1ConversationConfirmsId.ts";
@@ -544,6 +551,7 @@ export { route as putApiV1AdminQuotasKey } from "./putApiV1AdminQuotasKey.ts";
544551 export { route as putApiV1AdminShield } from "./putApiV1AdminShield.ts";
545552 export { route as putApiV1AdminTeamsSlug } from "./putApiV1AdminTeamsSlug.ts";
546553 export { route as putApiV1BoardsSlug } from "./putApiV1BoardsSlug.ts";
554 export { route as putApiV1ConnectionsIdUsesUse } from "./putApiV1ConnectionsIdUsesUse.ts";
547555 export { route as putApiV1FeaturesSlug } from "./putApiV1FeaturesSlug.ts";
548556 export { route as putApiV1ForgeEconomics } from "./putApiV1ForgeEconomics.ts";
549557 export { route as putApiV1ForgesNameCredit } from "./putApiV1ForgesNameCredit.ts";
src/contract/openapi/routes/postApiV1Connections.ts added +24
@@ -0,0 +1,24 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/connections",
6 summary: "Add an email to the account and mail it a code to prove it",
7 detail: "Add an email to the account and mail it a code; send the code to /api/v1/connections/{id}/confirm. An account keeps at most 10 connections",
8 auth: true,
9 role: "member",
10 body: { email: "string" },
11 status: 201,
12 reply: { connection: "object", says: "string" },
13 refusals: {
14 invalid_email: "not an email address (422)",
15 limit: "the account holds 10 connections already (422)",
16 taken: "this account already holds that address, proven (409); an address another account proved answers as a new one",
17 too_soon: "a code was sent a moment ago; Retry-After says how long (429)",
18 capped: "the forge's mail limits hold the message (429)",
19 no_mail: "this forge sends no mail (503)",
20 failed: "the code could not be sent (502)",
21 forbidden: "the request is cross-origin, or the token may only read",
22 },
23 refuses: [401, 422],
24 };
src/contract/openapi/routes/postApiV1ConnectionsIdConfirm.ts added +17
@@ -0,0 +1,17 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/connections/{id}/confirm",
6 summary: "Prove a connection with the code mailed to it",
7 auth: true,
8 role: "member",
9 body: { code: "string" },
10 reply: { connection: "object" },
11 refusals: {
12 wrong_code: "the code is wrong or has expired (422)",
13 not_found: "no such connection on this account (404)",
14 forbidden: "the request is cross-origin, or the token may only read",
15 },
16 refuses: [401, 422],
17 };
src/contract/openapi/routes/postApiV1ConnectionsLookup.ts added +17
@@ -0,0 +1,17 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/connections/lookup",
6 summary: "An integration asks who has proven an email and opted in to a use",
7 detail: "The integrations' question, carrying a lookup key in the X-Forge-Lookup-Key header, never a user token. It answers only for a proven email whose account opted in to the use; every other way of not knowing answers the same 404",
8 auth: false,
9 role: "anonymous",
10 body: { email: "string", use: "string" },
11 reply: { user: "object" },
12 refusals: {
13 invalid: "send {email, use: feedback|profile} (422)",
14 rate_limited: "too many lookups; Retry-After says how long (429)",
15 },
16 refuses: [404],
17 };
src/contract/openapi/routes/postApiV1ConnectionsLookupKeys.ts added +15
@@ -0,0 +1,15 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/connections/lookup-keys",
6 summary: "Make a lookup key for an integration (admin); shown once",
7 detail: "Make a lookup key (a person admin's token, admin scope). The key is shown once; only its hash is kept",
8 auth: true,
9 role: "admin",
10 body: { name: "string" },
11 status: 201,
12 reply: { says: "string" },
13 refusals: { invalid_name: "the name is missing, too long or has odd characters (422)", not_found: "the caller does not administer the forge (404)" },
14 refuses: [401, 422],
15 };
src/contract/openapi/routes/putApiV1ConnectionsIdUsesUse.ts added +18
@@ -0,0 +1,18 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: "/api/v1/connections/{id}/uses/{use}",
6 summary: "Turn one use (feedback or profile) of a connection on or off",
7 detail: "Turn one use of a connection on or off; a use is off until chosen, and turning it on is not retroactive",
8 auth: true,
9 role: "member",
10 body: { on: "boolean" },
11 reply: { connection: "object", note: "string" },
12 refusals: {
13 invalid_use: "use is not feedback or profile, or on is not true or false (422)",
14 not_found: "no such connection on this account (404)",
15 forbidden: "the request is cross-origin, or the token may only read",
16 },
17 refuses: [401, 422],
18 };
src/contract/tags.ts +1
@@ -133,6 +133,7 @@ export const TAG_WORDS: Readonly<Record<string, string>> = {
133133 asks: "Questions the crew asks a person, and their answers",
134134 billing: "Credit, spend, usage and returns",
135135 builds: "Builds of a pull or branch, their screenshots and cart",
136 connections: "Accounts a person has connected and the verified identities they carry",
136137 contract: "This description of the API",
137138 conversations: "Conversations with the crew and the tokens that confirm them",
138139 crew: "The agents of a repository, their fleet and their roster",
src/core/account_purge.ts +2
@@ -54,6 +54,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5454 // them.
5555 "trace_index.owner": DELETE,
5656 "access_link.created_by": FORMER,
57 // The admin who made an integration's lookup key: the key stays, as the former account's.
58 "connection_lookup_key.created_by": FORMER,
5759 // Who asked a game box to run a command: the record keeps it, as the former account.
5860 "game_command.by": FORMER,
5961 // A trace share link is its maker's to give, like a client pack link: it ends with the person.
src/core/identities.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * Connections on an account (#18108): the proven identifiers a person keeps
3 * ("yes, I am this"), each with its own uses, off by default. Pure data in
4 * and out. Only a proven connection ever counts; an email is proven by a
5 * code kept as a hash, spent once, expiring, tried a few times. One
6 * identifier is proven by one account: a second account cannot take it.
7 * `lookup` answers the user only for a proven connection whose use is on,
8 * and `undefined` for everything else, so no answer tells apart an unknown
9 * address from an unproven or an opted-out one.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { sha256 } from "../kernel/hash.ts";
14 import { id as newId, secret } from "../kernel/id.ts";
15
16 export const USES = ["feedback", "profile"] as const;
17 export type Use = (typeof USES)[number];
18 export const isUse = (u: unknown): u is Use => typeof u === "string" && (USES as readonly string[]).includes(u);
19
20 export const CODE_TTL_MS = 30 * 60_000;
21 export const RESEND_MS = 60_000;
22 export const MAX_TRIES = 5;
23 export const PER_ACCOUNT = 10;
24 export const LOOKUPS_PER_MINUTE = 60;
25 export const EMAIL_MAX = 254;
26 /** How long a lookup's audit row is kept: past it, the row goes on the next call of its key. */
27 export const AUDIT_KEEP_MS = 24 * 3_600_000;
28
29 export interface Connection {
30 readonly id: string;
31 readonly kind: "email";
32 readonly ident: string;
33 readonly proven: boolean;
34 readonly uses: Readonly<Record<Use, boolean>>;
35 }
36
37 /**
38 * An email as it is kept: trimmed, lowercased, one `@`, no spaces; undefined when it is not one.
39 */
40 export function cleanEmail(raw: unknown): string | undefined {
41 if (typeof raw !== "string") return undefined;
42 const e = raw.trim().toLowerCase();
43 if (e.length > EMAIL_MAX || !/^[^\s@<>,;"]+@[^\s@<>,;"]+\.[^\s@<>,;"]+$/.test(e)) return undefined;
44 return e.endsWith(".invalid") ? undefined : e;
45 }
46
47 interface Row {
48 id: string; user_id: string; kind: "email"; ident: string; proven_at: string | null;
49 sent_at: string | null; use_feedback: number; use_profile: number;
50 }
51 const shown = (r: Row): Connection => ({
52 id: r.id, kind: r.kind, ident: r.ident, proven: r.proven_at !== null,
53 uses: { feedback: r.use_feedback === 1, profile: r.use_profile === 1 },
54 });
55
56 export function listConnections(db: Database, userId: string): Connection[] {
57 return db.query<Row, [string]>("SELECT * FROM connection WHERE user_id = ?1 ORDER BY created_at, id").all(userId).map(shown);
58 }
59
60 /** Start a connection (unproven) and mint its code, returned once. */
61 export function addEmail(
62 db: Database, userId: string, email: string, now: number,
63 ): { 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);
65 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";
68 } else if (mine.proven_at !== null) return "taken";
69 // Another account proved it: this one still gets a row and a code, but `held` says nothing is
70 // mailed, so the answer never tells whether an address is proven here (it cannot be proven by
71 // this account: `proveEmail` answers "taken" then).
72 const held = db.query("SELECT 1 FROM connection WHERE kind = 'email' AND ident = ?1 AND proven_at IS NOT NULL").get(email) !== null;
73 const id = mine?.id ?? newId();
74 if (mine?.sent_at != null && now - Date.parse(mine.sent_at) < RESEND_MS) return "too_soon";
75 const code = String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, "0");
76 db.query(
77 `INSERT INTO connection (id, user_id, kind, ident, code_hash, expires_at, tries, sent_at, created_at)
78 VALUES (?1, ?2, 'email', ?3, ?4, ?5, 0, ?6, ?6)
79 ON CONFLICT(user_id, kind, ident) DO UPDATE SET code_hash = excluded.code_hash,
80 expires_at = excluded.expires_at, tries = 0, sent_at = excluded.sent_at`,
81 ).run(id, userId, email, sha256(`${id}:${code}`), new Date(now + CODE_TTL_MS).toISOString(), new Date(now).toISOString());
82 return { connection: shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!), code, held };
83 }
84
85 /**
86 * Prove with the code: once, while fresh, a few tries. "taken" when another account proved it
87 * first.
88 */
89 export function proveEmail(
90 db: Database, userId: string, id: string, code: string, now: number,
91 ): "proven" | "wrong" | "taken" | "none" {
92 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",
94 ).get(id, userId);
95 if (row === null) return "none";
96 if (row.code_hash === null || row.expires_at === null || Date.parse(row.expires_at) <= now || row.tries >= MAX_TRIES) return "wrong";
97 db.query("UPDATE connection SET tries = tries + 1 WHERE id = ?1").run(id);
98 if (sha256(`${id}:${code.trim()}`) !== row.code_hash) return "wrong";
99 try {
100 db.query("UPDATE connection SET proven_at = ?2, code_hash = NULL, expires_at = NULL WHERE id = ?1").run(id, new Date(now).toISOString());
101 } catch {
102 return "taken";
103 }
104 return "proven";
105 }
106
107 export function removeConnection(db: Database, userId: string, id: string): boolean {
108 return db.query("DELETE FROM connection WHERE id = ?1 AND user_id = ?2").run(id, userId).changes > 0;
109 }
110
111 /** Switch one use on or off; only a proven connection has uses to choose. */
112 export function setUse(db: Database, userId: string, id: string, use: Use, on: boolean): Connection | undefined {
113 const col = use === "feedback" ? "use_feedback" : "use_profile";
114 const done = db.query(`UPDATE connection SET ${col} = ?3 WHERE id = ?1 AND user_id = ?2 AND proven_at IS NOT NULL`).run(id, userId, on ? 1 : 0);
115 if (done.changes === 0) return undefined;
116 return shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!);
117 }
118
119 /** 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 {
121 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;
125 }
126
127 /** Mint a lookup key for an integration: the secret is returned once, its hash kept. */
128 export function mintLookupKey(db: Database, name: string, by: string, now: number): { id: string; key: string } {
129 const key = `fcl_${secret()}`;
130 const id = newId();
131 db.query("INSERT INTO connection_lookup_key (id, key_hash, name, created_by, created_at) VALUES (?1, ?2, ?3, ?4, ?5)")
132 .run(id, sha256(key), name, by, new Date(now).toISOString());
133 return { id, key };
134 }
135
136 export function revokeLookupKey(db: Database, id: string, now: number): boolean {
137 return db.query("UPDATE connection_lookup_key SET revoked_at = ?2 WHERE id = ?1 AND revoked_at IS NULL").run(id, new Date(now).toISOString()).changes > 0;
138 }
139
140 /** The key's id when it is a live lookup key. */
141 export function lookupKeyId(db: Database, presented: string): string | undefined {
142 if (presented === "") return undefined;
143 return db.query<{ id: string }, [string]>("SELECT id FROM connection_lookup_key WHERE key_hash = ?1 AND revoked_at IS NULL").get(sha256(presented))?.id;
144 }
145
146 /**
147 * Count this call; false when the key is past its minute's calls. Every call is a row: the audit,
148 * kept `AUDIT_KEEP_MS`, pruned here so a key cannot grow the table without limit.
149 */
150 export function auditLookup(db: Database, keyId: string, use: string, answered: boolean, now: number): boolean {
151 const since = new Date(now - 60_000).toISOString();
152 db.query("DELETE FROM connection_lookup_audit WHERE key_id = ?1 AND at < ?2").run(keyId, new Date(now - AUDIT_KEEP_MS).toISOString());
153 const n = db.query<{ n: number }, [string, string]>("SELECT COUNT(*) AS n FROM connection_lookup_audit WHERE key_id = ?1 AND at > ?2").get(keyId, since)?.n ?? 0;
154 if (n >= LOOKUPS_PER_MINUTE) return false;
155 db.query("INSERT INTO connection_lookup_audit (at, key_id, use, answered) VALUES (?1, ?2, ?3, ?4)").run(new Date(now).toISOString(), keyId, use.slice(0, 20), answered ? 1 : 0);
156 return true;
157 }
src/core/migration-pins/20261204060000-connections.pin added +1
@@ -0,0 +1,1 @@
1 65537d89b0374da196f65cd51734342b2f5a3e5b58e80ff7c61faf5983833ccc
src/core/migrations/20261204060000-connections.ts added +42
@@ -0,0 +1,42 @@
1 // Connections on an account (#18108): verified "yes, I am this" claims a person keeps, each with
2 // its own uses, off by default. `ident` is normalized (an email, lowercased). A proof is a code
3 // stored only as a hash (`code_hash`), spent on use, expiring, tried a few times. Only a proven
4 // row counts; the unique index lets one account prove an identifier and no second one. A lookup key
5 // is a credential for the integrations' lookup alone: stored as a hash, revocable. The lookup audit
6 // has one row per call, whatever the answer, and is what the rate limit counts. Additive.
7 export default `
8 CREATE TABLE connection (
9 id TEXT PRIMARY KEY,
10 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
11 kind TEXT NOT NULL CHECK (kind IN ('email')),
12 ident TEXT NOT NULL,
13 proven_at TEXT,
14 code_hash TEXT,
15 expires_at TEXT,
16 tries INTEGER NOT NULL DEFAULT 0,
17 sent_at TEXT,
18 use_feedback INTEGER NOT NULL DEFAULT 0,
19 use_profile INTEGER NOT NULL DEFAULT 0,
20 created_at TEXT NOT NULL
21 ) WITHOUT ROWID;
22 CREATE UNIQUE INDEX connection_one_per_account ON connection(user_id, kind, ident);
23 CREATE UNIQUE INDEX connection_proven_once ON connection(kind, ident) WHERE proven_at IS NOT NULL;
24
25 CREATE TABLE connection_lookup_key (
26 id TEXT PRIMARY KEY,
27 key_hash TEXT NOT NULL UNIQUE,
28 name TEXT NOT NULL,
29 created_by TEXT NOT NULL,
30 created_at TEXT NOT NULL,
31 revoked_at TEXT
32 ) WITHOUT ROWID;
33
34 CREATE TABLE connection_lookup_audit (
35 id INTEGER PRIMARY KEY AUTOINCREMENT,
36 at TEXT NOT NULL,
37 key_id TEXT NOT NULL,
38 use TEXT NOT NULL,
39 answered INTEGER NOT NULL
40 );
41 CREATE INDEX connection_lookup_audit_by_key ON connection_lookup_audit(key_id, at);
42 `;
src/generated/marks.ts +197 −195
@@ -21,201 +21,202 @@ import k16 from "../http/marks/api-v1-changelog.json";
2121 import k17 from "../http/marks/api-v1-cloud.json";
2222 import k18 from "../http/marks/api-v1-codes.json";
2323 import k19 from "../http/marks/api-v1-config.json";
24 import k20 from "../http/marks/api-v1-contribute.json";
25 import k21 from "../http/marks/api-v1-conversation-confirms.json";
26 import k22 from "../http/marks/api-v1-conversation-tokens.json";
27 import k23 from "../http/marks/api-v1-conversation.json";
28 import k24 from "../http/marks/api-v1-conversations.json";
29 import k25 from "../http/marks/api-v1-credit.json";
30 import k26 from "../http/marks/api-v1-crew.json";
31 import k27 from "../http/marks/api-v1-devices.json";
32 import k28 from "../http/marks/api-v1-drills.json";
33 import k29 from "../http/marks/api-v1-explore.json";
34 import k30 from "../http/marks/api-v1-family.json";
35 import k31 from "../http/marks/api-v1-features.json";
36 import k32 from "../http/marks/api-v1-feed.json";
37 import k33 from "../http/marks/api-v1-first-admin.json";
38 import k34 from "../http/marks/api-v1-flags.json";
39 import k35 from "../http/marks/api-v1-fleet.json";
40 import k36 from "../http/marks/api-v1-flow.json";
41 import k37 from "../http/marks/api-v1-forge-templates.json";
42 import k38 from "../http/marks/api-v1-forge.json";
43 import k39 from "../http/marks/api-v1-forges.json";
44 import k40 from "../http/marks/api-v1-forks.json";
45 import k41 from "../http/marks/api-v1-front.json";
46 import k42 from "../http/marks/api-v1-games.json";
47 import k43 from "../http/marks/api-v1-health.json";
48 import k44 from "../http/marks/api-v1-heartbeat.json";
49 import k45 from "../http/marks/api-v1-here.json";
50 import k46 from "../http/marks/api-v1-home.json";
51 import k47 from "../http/marks/api-v1-keeper.json";
52 import k48 from "../http/marks/api-v1-mail-aws.json";
53 import k49 from "../http/marks/api-v1-mail-key.json";
54 import k50 from "../http/marks/api-v1-maintenance.json";
55 import k51 from "../http/marks/api-v1-map.json";
56 import k52 from "../http/marks/api-v1-may.json";
57 import k53 from "../http/marks/api-v1-migrate.json";
58 import k54 from "../http/marks/api-v1-models.json";
59 import k55 from "../http/marks/api-v1-offers.json";
60 import k56 from "../http/marks/api-v1-openapi.json.json";
61 import k57 from "../http/marks/api-v1-orgs.json";
62 import k58 from "../http/marks/api-v1-packs.json";
63 import k59 from "../http/marks/api-v1-passport.json";
64 import k60 from "../http/marks/api-v1-places.json";
65 import k61 from "../http/marks/api-v1-plans.json";
66 import k62 from "../http/marks/api-v1-proof.json";
67 import k63 from "../http/marks/api-v1-reach.json";
68 import k64 from "../http/marks/api-v1-release.json";
69 import k65 from "../http/marks/api-v1-releases.json";
70 import k66 from "../http/marks/api-v1-repos.json";
71 import k67 from "../http/marks/api-v1-returns.json";
72 import k68 from "../http/marks/api-v1-runner.json";
73 import k69 from "../http/marks/api-v1-search.json";
74 import k70 from "../http/marks/api-v1-secrets.json";
75 import k71 from "../http/marks/api-v1-sessions.json";
76 import k72 from "../http/marks/api-v1-share.json";
77 import k73 from "../http/marks/api-v1-slash.json";
78 import k74 from "../http/marks/api-v1-start.json";
79 import k75 from "../http/marks/api-v1-status.json";
80 import k76 from "../http/marks/api-v1-telemetry.json";
81 import k77 from "../http/marks/api-v1-templates.json";
82 import k78 from "../http/marks/api-v1-thoughts.json";
83 import k79 from "../http/marks/api-v1-timers.json";
84 import k80 from "../http/marks/api-v1-tokens.json";
85 import k81 from "../http/marks/api-v1-usage.json";
86 import k82 from "../http/marks/api-v1-user.json";
87 import k83 from "../http/marks/api-v1-users.json";
88 import k84 from "../http/marks/api-v1-version.json";
89 import k85 from "../http/marks/api-v1.json";
90 import k86 from "../http/marks/api.json";
91 import k87 from "../http/marks/apple-touch-icon-precomposed.png.json";
92 import k88 from "../http/marks/apple-touch-icon.png.json";
93 import k89 from "../http/marks/apps.json";
94 import k90 from "../http/marks/archive.json";
95 import k91 from "../http/marks/asked.json";
96 import k92 from "../http/marks/asks.json";
97 import k93 from "../http/marks/assets.json";
98 import k94 from "../http/marks/audit.csv.json";
99 import k95 from "../http/marks/audit.json";
100 import k96 from "../http/marks/big.json";
101 import k97 from "../http/marks/board.json";
102 import k98 from "../http/marks/boards.json";
103 import k99 from "../http/marks/bring.json";
104 import k100 from "../http/marks/broker.json";
105 import k101 from "../http/marks/changelog.atom.json";
106 import k102 from "../http/marks/changelog.json";
107 import k103 from "../http/marks/claim.json";
108 import k104 from "../http/marks/client-clouds.json";
109 import k105 from "../http/marks/cloud.json";
110 import k106 from "../http/marks/cockpit.json";
111 import k107 from "../http/marks/contract.json";
112 import k108 from "../http/marks/contribute.json";
113 import k109 from "../http/marks/csp-report.json";
114 import k110 from "../http/marks/dash.json";
115 import k111 from "../http/marks/data.json";
116 import k112 from "../http/marks/dataset.json";
117 import k113 from "../http/marks/deploy-to.json";
118 import k114 from "../http/marks/design.json";
119 import k115 from "../http/marks/desk.json";
120 import k116 from "../http/marks/displays.json";
121 import k117 from "../http/marks/docs.json";
122 import k118 from "../http/marks/edge.json";
123 import k119 from "../http/marks/edition.json";
124 import k120 from "../http/marks/events.json";
125 import k121 from "../http/marks/explore.atom.json";
126 import k122 from "../http/marks/explore.json";
127 import k123 from "../http/marks/explore.json.json";
128 import k124 from "../http/marks/family.json";
129 import k125 from "../http/marks/favicon.ico.json";
130 import k126 from "../http/marks/feed.json";
131 import k127 from "../http/marks/feed.json.json";
132 import k128 from "../http/marks/first-admin.json";
133 import k129 from "../http/marks/fleet.json";
134 import k130 from "../http/marks/flow.json";
135 import k131 from "../http/marks/forge.json";
136 import k132 from "../http/marks/forges.json";
137 import k133 from "../http/marks/forks.json";
138 import k134 from "../http/marks/front.json";
139 import k135 from "../http/marks/funnel.json";
140 import k136 from "../http/marks/games.json";
141 import k137 from "../http/marks/go.json";
142 import k138 from "../http/marks/health.json";
143 import k139 from "../http/marks/home.json";
144 import k140 from "../http/marks/hooks.json";
145 import k141 from "../http/marks/icons.json";
146 import k142 from "../http/marks/infra.json";
147 import k143 from "../http/marks/join.json";
148 import k144 from "../http/marks/live.json";
149 import k145 from "../http/marks/llms-full.txt.json";
150 import k146 from "../http/marks/llms.txt.json";
151 import k147 from "../http/marks/login.json";
152 import k148 from "../http/marks/logout.json";
153 import k149 from "../http/marks/maintenance-json.json";
154 import k150 from "../http/marks/maintenance.json";
155 import k151 from "../http/marks/manifest.webmanifest.json";
156 import k152 from "../http/marks/map.json";
157 import k153 from "../http/marks/mcp.json";
158 import k154 from "../http/marks/measure.json";
159 import k155 from "../http/marks/metrics.json";
160 import k156 from "../http/marks/migrate.json";
161 import k157 from "../http/marks/new.json";
162 import k158 from "../http/marks/next.json";
163 import k159 from "../http/marks/notes.json";
164 import k160 from "../http/marks/now.json";
165 import k161 from "../http/marks/oauth.json";
166 import k162 from "../http/marks/oembed.json";
167 import k163 from "../http/marks/offers.json";
168 import k164 from "../http/marks/offline.json";
169 import k165 from "../http/marks/og.json";
170 import k166 from "../http/marks/openapi.json.json";
171 import k167 from "../http/marks/opensearch.xml.json";
172 import k168 from "../http/marks/organizations.json";
173 import k169 from "../http/marks/origins.json";
174 import k170 from "../http/marks/owner.atom.json";
175 import k171 from "../http/marks/owner.json";
176 import k172 from "../http/marks/packs.json";
177 import k173 from "../http/marks/peek.json";
178 import k174 from "../http/marks/pinned.json";
179 import k175 from "../http/marks/pipeline.json";
180 import k176 from "../http/marks/plugins.json";
181 import k177 from "../http/marks/pricing.json";
182 import k178 from "../http/marks/privacy.json";
183 import k179 from "../http/marks/r.json";
184 import k180 from "../http/marks/recover.json";
185 import k181 from "../http/marks/releases.json";
186 import k182 from "../http/marks/releases.json.json";
187 import k183 from "../http/marks/repos.json";
188 import k184 from "../http/marks/resilience.json";
189 import k185 from "../http/marks/review.json";
190 import k186 from "../http/marks/robots.txt.json";
191 import k187 from "../http/marks/root.json";
192 import k188 from "../http/marks/runs.json";
193 import k189 from "../http/marks/script-error.json";
194 import k190 from "../http/marks/search.json";
195 import k191 from "../http/marks/security.json";
196 import k192 from "../http/marks/settings.json";
197 import k193 from "../http/marks/sign-in.json";
198 import k194 from "../http/marks/signin.json";
199 import k195 from "../http/marks/signup.json";
200 import k196 from "../http/marks/sitemap.xml.json";
201 import k197 from "../http/marks/status.json";
202 import k198 from "../http/marks/support.json";
203 import k199 from "../http/marks/sw.js.json";
204 import k200 from "../http/marks/system.json";
205 import k201 from "../http/marks/tab.json";
206 import k202 from "../http/marks/tabforge.json";
207 import k203 from "../http/marks/talk.json";
208 import k204 from "../http/marks/tell.json";
209 import k205 from "../http/marks/templates.json";
210 import k206 from "../http/marks/templates.json.json";
211 import k207 from "../http/marks/terms.json";
212 import k208 from "../http/marks/theme.json";
213 import k209 from "../http/marks/toolbar-lab.js.json";
214 import k210 from "../http/marks/toolbar-lab.json";
215 import k211 from "../http/marks/traces.json";
216 import k212 from "../http/marks/verify.json";
217 import k213 from "../http/marks/welcome.json";
218 import k214 from "../http/marks/well-known.json";
24 import k20 from "../http/marks/api-v1-connections.json";
25 import k21 from "../http/marks/api-v1-contribute.json";
26 import k22 from "../http/marks/api-v1-conversation-confirms.json";
27 import k23 from "../http/marks/api-v1-conversation-tokens.json";
28 import k24 from "../http/marks/api-v1-conversation.json";
29 import k25 from "../http/marks/api-v1-conversations.json";
30 import k26 from "../http/marks/api-v1-credit.json";
31 import k27 from "../http/marks/api-v1-crew.json";
32 import k28 from "../http/marks/api-v1-devices.json";
33 import k29 from "../http/marks/api-v1-drills.json";
34 import k30 from "../http/marks/api-v1-explore.json";
35 import k31 from "../http/marks/api-v1-family.json";
36 import k32 from "../http/marks/api-v1-features.json";
37 import k33 from "../http/marks/api-v1-feed.json";
38 import k34 from "../http/marks/api-v1-first-admin.json";
39 import k35 from "../http/marks/api-v1-flags.json";
40 import k36 from "../http/marks/api-v1-fleet.json";
41 import k37 from "../http/marks/api-v1-flow.json";
42 import k38 from "../http/marks/api-v1-forge-templates.json";
43 import k39 from "../http/marks/api-v1-forge.json";
44 import k40 from "../http/marks/api-v1-forges.json";
45 import k41 from "../http/marks/api-v1-forks.json";
46 import k42 from "../http/marks/api-v1-front.json";
47 import k43 from "../http/marks/api-v1-games.json";
48 import k44 from "../http/marks/api-v1-health.json";
49 import k45 from "../http/marks/api-v1-heartbeat.json";
50 import k46 from "../http/marks/api-v1-here.json";
51 import k47 from "../http/marks/api-v1-home.json";
52 import k48 from "../http/marks/api-v1-keeper.json";
53 import k49 from "../http/marks/api-v1-mail-aws.json";
54 import k50 from "../http/marks/api-v1-mail-key.json";
55 import k51 from "../http/marks/api-v1-maintenance.json";
56 import k52 from "../http/marks/api-v1-map.json";
57 import k53 from "../http/marks/api-v1-may.json";
58 import k54 from "../http/marks/api-v1-migrate.json";
59 import k55 from "../http/marks/api-v1-models.json";
60 import k56 from "../http/marks/api-v1-offers.json";
61 import k57 from "../http/marks/api-v1-openapi.json.json";
62 import k58 from "../http/marks/api-v1-orgs.json";
63 import k59 from "../http/marks/api-v1-packs.json";
64 import k60 from "../http/marks/api-v1-passport.json";
65 import k61 from "../http/marks/api-v1-places.json";
66 import k62 from "../http/marks/api-v1-plans.json";
67 import k63 from "../http/marks/api-v1-proof.json";
68 import k64 from "../http/marks/api-v1-reach.json";
69 import k65 from "../http/marks/api-v1-release.json";
70 import k66 from "../http/marks/api-v1-releases.json";
71 import k67 from "../http/marks/api-v1-repos.json";
72 import k68 from "../http/marks/api-v1-returns.json";
73 import k69 from "../http/marks/api-v1-runner.json";
74 import k70 from "../http/marks/api-v1-search.json";
75 import k71 from "../http/marks/api-v1-secrets.json";
76 import k72 from "../http/marks/api-v1-sessions.json";
77 import k73 from "../http/marks/api-v1-share.json";
78 import k74 from "../http/marks/api-v1-slash.json";
79 import k75 from "../http/marks/api-v1-start.json";
80 import k76 from "../http/marks/api-v1-status.json";
81 import k77 from "../http/marks/api-v1-telemetry.json";
82 import k78 from "../http/marks/api-v1-templates.json";
83 import k79 from "../http/marks/api-v1-thoughts.json";
84 import k80 from "../http/marks/api-v1-timers.json";
85 import k81 from "../http/marks/api-v1-tokens.json";
86 import k82 from "../http/marks/api-v1-usage.json";
87 import k83 from "../http/marks/api-v1-user.json";
88 import k84 from "../http/marks/api-v1-users.json";
89 import k85 from "../http/marks/api-v1-version.json";
90 import k86 from "../http/marks/api-v1.json";
91 import k87 from "../http/marks/api.json";
92 import k88 from "../http/marks/apple-touch-icon-precomposed.png.json";
93 import k89 from "../http/marks/apple-touch-icon.png.json";
94 import k90 from "../http/marks/apps.json";
95 import k91 from "../http/marks/archive.json";
96 import k92 from "../http/marks/asked.json";
97 import k93 from "../http/marks/asks.json";
98 import k94 from "../http/marks/assets.json";
99 import k95 from "../http/marks/audit.csv.json";
100 import k96 from "../http/marks/audit.json";
101 import k97 from "../http/marks/big.json";
102 import k98 from "../http/marks/board.json";
103 import k99 from "../http/marks/boards.json";
104 import k100 from "../http/marks/bring.json";
105 import k101 from "../http/marks/broker.json";
106 import k102 from "../http/marks/changelog.atom.json";
107 import k103 from "../http/marks/changelog.json";
108 import k104 from "../http/marks/claim.json";
109 import k105 from "../http/marks/client-clouds.json";
110 import k106 from "../http/marks/cloud.json";
111 import k107 from "../http/marks/cockpit.json";
112 import k108 from "../http/marks/contract.json";
113 import k109 from "../http/marks/contribute.json";
114 import k110 from "../http/marks/csp-report.json";
115 import k111 from "../http/marks/dash.json";
116 import k112 from "../http/marks/data.json";
117 import k113 from "../http/marks/dataset.json";
118 import k114 from "../http/marks/deploy-to.json";
119 import k115 from "../http/marks/design.json";
120 import k116 from "../http/marks/desk.json";
121 import k117 from "../http/marks/displays.json";
122 import k118 from "../http/marks/docs.json";
123 import k119 from "../http/marks/edge.json";
124 import k120 from "../http/marks/edition.json";
125 import k121 from "../http/marks/events.json";
126 import k122 from "../http/marks/explore.atom.json";
127 import k123 from "../http/marks/explore.json";
128 import k124 from "../http/marks/explore.json.json";
129 import k125 from "../http/marks/family.json";
130 import k126 from "../http/marks/favicon.ico.json";
131 import k127 from "../http/marks/feed.json";
132 import k128 from "../http/marks/feed.json.json";
133 import k129 from "../http/marks/first-admin.json";
134 import k130 from "../http/marks/fleet.json";
135 import k131 from "../http/marks/flow.json";
136 import k132 from "../http/marks/forge.json";
137 import k133 from "../http/marks/forges.json";
138 import k134 from "../http/marks/forks.json";
139 import k135 from "../http/marks/front.json";
140 import k136 from "../http/marks/funnel.json";
141 import k137 from "../http/marks/games.json";
142 import k138 from "../http/marks/go.json";
143 import k139 from "../http/marks/health.json";
144 import k140 from "../http/marks/home.json";
145 import k141 from "../http/marks/hooks.json";
146 import k142 from "../http/marks/icons.json";
147 import k143 from "../http/marks/infra.json";
148 import k144 from "../http/marks/join.json";
149 import k145 from "../http/marks/live.json";
150 import k146 from "../http/marks/llms-full.txt.json";
151 import k147 from "../http/marks/llms.txt.json";
152 import k148 from "../http/marks/login.json";
153 import k149 from "../http/marks/logout.json";
154 import k150 from "../http/marks/maintenance-json.json";
155 import k151 from "../http/marks/maintenance.json";
156 import k152 from "../http/marks/manifest.webmanifest.json";
157 import k153 from "../http/marks/map.json";
158 import k154 from "../http/marks/mcp.json";
159 import k155 from "../http/marks/measure.json";
160 import k156 from "../http/marks/metrics.json";
161 import k157 from "../http/marks/migrate.json";
162 import k158 from "../http/marks/new.json";
163 import k159 from "../http/marks/next.json";
164 import k160 from "../http/marks/notes.json";
165 import k161 from "../http/marks/now.json";
166 import k162 from "../http/marks/oauth.json";
167 import k163 from "../http/marks/oembed.json";
168 import k164 from "../http/marks/offers.json";
169 import k165 from "../http/marks/offline.json";
170 import k166 from "../http/marks/og.json";
171 import k167 from "../http/marks/openapi.json.json";
172 import k168 from "../http/marks/opensearch.xml.json";
173 import k169 from "../http/marks/organizations.json";
174 import k170 from "../http/marks/origins.json";
175 import k171 from "../http/marks/owner.atom.json";
176 import k172 from "../http/marks/owner.json";
177 import k173 from "../http/marks/packs.json";
178 import k174 from "../http/marks/peek.json";
179 import k175 from "../http/marks/pinned.json";
180 import k176 from "../http/marks/pipeline.json";
181 import k177 from "../http/marks/plugins.json";
182 import k178 from "../http/marks/pricing.json";
183 import k179 from "../http/marks/privacy.json";
184 import k180 from "../http/marks/r.json";
185 import k181 from "../http/marks/recover.json";
186 import k182 from "../http/marks/releases.json";
187 import k183 from "../http/marks/releases.json.json";
188 import k184 from "../http/marks/repos.json";
189 import k185 from "../http/marks/resilience.json";
190 import k186 from "../http/marks/review.json";
191 import k187 from "../http/marks/robots.txt.json";
192 import k188 from "../http/marks/root.json";
193 import k189 from "../http/marks/runs.json";
194 import k190 from "../http/marks/script-error.json";
195 import k191 from "../http/marks/search.json";
196 import k192 from "../http/marks/security.json";
197 import k193 from "../http/marks/settings.json";
198 import k194 from "../http/marks/sign-in.json";
199 import k195 from "../http/marks/signin.json";
200 import k196 from "../http/marks/signup.json";
201 import k197 from "../http/marks/sitemap.xml.json";
202 import k198 from "../http/marks/status.json";
203 import k199 from "../http/marks/support.json";
204 import k200 from "../http/marks/sw.js.json";
205 import k201 from "../http/marks/system.json";
206 import k202 from "../http/marks/tab.json";
207 import k203 from "../http/marks/tabforge.json";
208 import k204 from "../http/marks/talk.json";
209 import k205 from "../http/marks/tell.json";
210 import k206 from "../http/marks/templates.json";
211 import k207 from "../http/marks/templates.json.json";
212 import k208 from "../http/marks/terms.json";
213 import k209 from "../http/marks/theme.json";
214 import k210 from "../http/marks/toolbar-lab.js.json";
215 import k211 from "../http/marks/toolbar-lab.json";
216 import k212 from "../http/marks/traces.json";
217 import k213 from "../http/marks/verify.json";
218 import k214 from "../http/marks/welcome.json";
219 import k215 from "../http/marks/well-known.json";
219220
220221 /** Each file of `http/marks/`, parsed, in name order. */
221222 export const MARK_FILES: readonly unknown[] = [
@@ -434,4 +435,5 @@ export const MARK_FILES: readonly unknown[] = [
434435 k212,
435436 k213,
436437 k214,
438 k215,
437439 ];
src/http/api.ts +2
@@ -391,6 +391,7 @@ import { promptRoutes } from "./api/prompts.ts";
391391 import { cloudRoutes } from "./api/cloud.ts";
392392 import { secretRoutes } from "./api/secrets.ts";
393393 import { mailKeyRoutes } from "./api/mail_key.ts";
394 import { identityRoutes } from "./api/identities.ts";
394395 import { mailAwsRoutes } from "./api/mail_aws.ts";
395396 import { drillRoutes } from "./api/drills.ts";
396397 import { featureRoutes } from "./api/features.ts";
@@ -3364,6 +3365,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
33643365
33653366 secretRoutes(router);
33663367 mailKeyRoutes(router);
3368 identityRoutes(router);
33673369 mailAwsRoutes(router);
33683370 drillRoutes(router);
33693371 featureRoutes(router);
src/http/api/identities.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * 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
4 * /:id/confirm {code}` proves it; `PUT /:id/uses/:use {on}` chooses a use;
5 * `DELETE /:id` removes. `POST /lookup` is the integrations' question,
6 * carrying a lookup key in `X-Forge-Lookup-Key` (never a user token); an
7 * admin makes keys at `/lookup-keys`. The account itself acts, same-origin.
8 */
9
10 import {
11 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf, askLookup,
12 dropConnection, dropLookupKey, makeLookupKey, type ConnectionError,
13 } from "../../actions/identities.ts";
14 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
15 import type { Handler } from "../context.ts";
16 import { apiError, body, json, notFound, requireAccount, str, tryAgain } from "../respond.ts";
17 import type { Router } from "../router.ts";
18
19 /** The status each refusal answers with, 0 for the ones that wait; the words are the action's. */
20 const STATUS: Record<ConnectionError, number> = {
21 invalid_email: 422, limit: 422, taken: 409, too_soon: 0, no_mail: 0, capped: 0, failed: 502,
22 wrong_code: 422, not_found: 404, invalid_use: 422, invalid_name: 422,
23 };
24 /** Seconds to wait, for the refusals that wait; the rest answer through apiError. */
25 const WAITS: Partial<Record<ConnectionError, number>> = { too_soon: 60, no_mail: 3600, capped: 3600 };
26 const refuse = (e: ConnectionError): Response => {
27 const wait = WAITS[e];
28 if (wait === undefined) return apiError(e, STATUS[e], CONNECTION_WORDS[e]);
29 return e === "no_mail" ? tryAgain(e, 503, CONNECTION_WORDS[e], wait) : tryAgain(e, 429, CONNECTION_WORDS[e], wait);
30 };
31 const noStore = { "cache-control": "private, no-store" };
32
33 export function identityRoutes(router: Router<Handler>): void {
34 router.add("GET", "/api/v1/connections", (ctx) => {
35 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
36 if (!ctx.auth.user) return apiError("unauthorized", 401, "sign in");
37 return json({ connections: connectionsOf(ctx.app, ctx.auth.user), note: NOT_RETROACTIVE }, 200, noStore);
38 });
39
40 router.add("POST", "/api/v1/connections", async (ctx) => {
41 const denied = requireAccount(ctx, { adminToken: true });
42 if (denied) return denied;
43 const input = await body(ctx.request);
44 const made = await addConnection(ctx.app, ctx.auth.user!, input.email);
45 return made.ok ? json({ connection: made.value, says: "A code was mailed; send it to /confirm." }, 201, noStore) : refuse(made.error);
46 });
47
48 router.add("POST", "/api/v1/connections/:id/confirm", async (ctx) => {
49 const denied = requireAccount(ctx, { adminToken: true });
50 if (denied) return denied;
51 const input = await body(ctx.request);
52 const done = confirmConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", input.code);
53 return done.ok ? json({ connection: done.value }, 200, noStore) : refuse(done.error);
54 });
55
56 router.add("PUT", "/api/v1/connections/:id/uses/:use", async (ctx) => {
57 const denied = requireAccount(ctx, { adminToken: true });
58 if (denied) return denied;
59 const input = await body(ctx.request);
60 const done = chooseUse(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", ctx.params["use"], input.on);
61 return done.ok ? json({ connection: done.value, note: NOT_RETROACTIVE }, 200, noStore) : refuse(done.error);
62 });
63
64 router.add("DELETE", "/api/v1/connections/:id", (ctx) => {
65 const denied = requireAccount(ctx, { adminToken: true });
66 if (denied) return denied;
67 const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "");
68 return done.ok ? json({ removed: true, note: NOT_RETROACTIVE }, 200, noStore) : refuse(done.error);
69 });
70
71 // The integrations' lookup: found and not-found answer alike for every way of not knowing.
72 router.add("POST", "/api/v1/connections/lookup", async (ctx) => {
73 const input = await body(ctx.request);
74 const asked = askLookup(ctx.app, ctx.request.headers.get("x-forge-lookup-key") ?? "", input.email, input.use);
75 if (!asked.ok) {
76 if (asked.error === "unauthorized") return notFound();
77 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}");
79 }
80 return json({ user: asked.value }, 200, noStore);
81 });
82
83 router.add("POST", "/api/v1/connections/lookup-keys", async (ctx) => {
84 const denied = requireAccount(ctx, { adminToken: true });
85 if (denied) return denied;
86 const input = await body(ctx.request);
87 const made = makeLookupKey(ctx.app, ctx.auth.user!, str(input.name));
88 if (!made.ok) return made.error === "not_found" ? notFound() : refuse("invalid_name");
89 return json({ ...made.value, says: "Shown once: only its hash is kept." }, 201, noStore);
90 });
91
92 router.add("DELETE", "/api/v1/connections/lookup-keys/:id", (ctx) => {
93 const denied = requireAccount(ctx, { adminToken: true });
94 if (denied) return denied;
95 const done = dropLookupKey(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "");
96 return done.ok ? json({ revoked: true }, 200, noStore) : notFound();
97 });
98 }
src/http/api/reports.ts +4
@@ -23,6 +23,7 @@ import { keyedPage, keyedWindow, loadRepo, originAware, withLabels } from "../ap
2323 import type { Handler } from "../context.ts";
2424 import { holds, weakEtag } from "../etag.ts";
2525 import { clientBucket } from "../peer.ts";
26 import { reporterFor } from "../../actions/identities.ts";
2627 import { proofOf, receiptOf, receiptText, wantsText } from "../report_filer.ts";
2728 import {
2829 apiError,
@@ -67,6 +68,9 @@ export function reportRoutes(router: Router<Handler>): void {
6768 },
6869 clientBucket(ctx.request),
6970 proofOf(ctx),
71 // A trusted integration that names a reporter's address: the report names them only if they
72 // opted in.
73 reporterFor(ctx.app, ctx.request.headers.get("x-forge-lookup-key") ?? "", input.reporter),
7074 );
7175 if (!filed.ok) {
7276 const refusal = filed.error;
src/http/lazy_lists.ts +13
@@ -82,6 +82,11 @@ export const SETTINGS_ROUTES = [
8282 ["POST", "/settings/passkeys/options"],
8383 ["POST", "/settings/passkeys"],
8484 ["POST", "/settings/passkeys/:id/delete"],
85 ["GET", "/settings/identities"],
86 ["POST", "/settings/identities"],
87 ["POST", "/settings/identities/:id/confirm"],
88 ["POST", "/settings/identities/:id/use"],
89 ["POST", "/settings/identities/:id/delete"],
8590 ["GET", "/settings/subscriptions"],
8691 ["POST", "/settings/subscriptions"],
8792 ["POST", "/settings/crew/key"],
@@ -1700,6 +1705,14 @@ export const API_ROUTES = [
17001705 ["GET", "/api/v1/mail-key/:scope"],
17011706 ["PUT", "/api/v1/mail-key/:scope"],
17021707 ["DELETE", "/api/v1/mail-key/:scope"],
1708 ["GET", "/api/v1/connections"],
1709 ["POST", "/api/v1/connections"],
1710 ["POST", "/api/v1/connections/:id/confirm"],
1711 ["PUT", "/api/v1/connections/:id/uses/:use"],
1712 ["DELETE", "/api/v1/connections/:id"],
1713 ["POST", "/api/v1/connections/lookup"],
1714 ["POST", "/api/v1/connections/lookup-keys"],
1715 ["DELETE", "/api/v1/connections/lookup-keys/:id"],
17031716 ["GET", "/api/v1/mail-aws"],
17041717 ["POST", "/api/v1/mail-aws"],
17051718 ["DELETE", "/api/v1/mail-aws"],
src/http/marks/api-v1-connections.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/connections",
3 "mark": "open"
4 }
src/http/marks/settings.json +4
@@ -57,6 +57,10 @@
5757 "/settings/passkeys": "open",
5858 "/settings/passkeys/options": "open",
5959 "/settings/passkeys/:id/delete": "open",
60 "/settings/identities": "open",
61 "/settings/identities/:id/confirm": "open",
62 "/settings/identities/:id/use": "open",
63 "/settings/identities/:id/delete": "open",
6064 "/settings/subscriptions": "admin",
6165 "/settings/crew/key": "admin",
6266 "/settings/crew/budgets": "admin",
src/http/settings_routes.ts +6
@@ -51,6 +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";
5455 import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts";
5556 import { deviceCap, deviceDeclare, deviceGrant, devicesPage, deviceRemove, deviceRevoke } from "../web/settings/devices.ts";
5657 import { mailAwsDo, mailAwsUndo, secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
@@ -231,6 +232,11 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
231232 router.add("POST", "/settings/passkeys/options", passkeyOptions);
232233 router.add("POST", "/settings/passkeys", passkeyAdd);
233234 router.add("POST", "/settings/passkeys/:id/delete", passkeyDelete);
235 router.add("GET", "/settings/identities", identitiesPage);
236 router.add("POST", "/settings/identities", identityAdd);
237 router.add("POST", "/settings/identities/:id/confirm", identityConfirm);
238 router.add("POST", "/settings/identities/:id/use", identityUse);
239 router.add("POST", "/settings/identities/:id/delete", identityRemove);
234240 // The crew: a forge admin's section, hidden from everyone else.
235241 router.add("GET", "/settings/subscriptions", subscriptionsPage);
236242 router.add("POST", "/settings/subscriptions", subscriptionAdd);
src/tui/forge_parts.ts +9
@@ -87,6 +87,7 @@ import { talkBuildScreen } from "./screens/talk_build.ts";
8787 import { talkChatsScreen } from "./screens/talk_chats.ts";
8888 import { sshOn } from "../settings/ssh.ts";
8989 import { sshKeysScreen } from "./screens/sshkeys.ts";
90 import { identitiesScreen } from "./screens/identities.ts";
9091 import { passkeysScreen } from "./screens/passkeys.ts";
9192 import { confirmsScreen } from "./screens/confirms.ts";
9293 import { receiptsScreen } from "./screens/receipts.ts";
@@ -601,6 +602,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
601602 hint: "the passkeys that sign in as you",
602603 run: () => ctx.push(passkeysScreen(session, ctx)),
603604 });
605 // Settings › Proven emails and `/api/v1/connections`: one set of actions (#18108).
606 if (session.signedIn && session.user?.kind !== "agent")
607 commands.push({
608 id: "proven-emails",
609 title: "Proven emails",
610 hint: "the addresses I proved, and what each is for",
611 run: () => ctx.push(identitiesScreen(session, ctx)),
612 });
604613 if (session.signedIn)
605614 commands.push(
606615 {
src/tui/screens/identities.ts added +103
@@ -0,0 +1,103 @@
1 /**
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
4 * off, `d` removes after a y/n. The same actions as the API and the page, so the same gates and
5 * words; the list is the signed-in account's own.
6 */
7
8 import {
9 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf,
10 dropConnection,
11 } from "../../actions/identities.ts";
12 import type { Use } from "../../core/identities.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import { style } from "../term/style.ts";
16 import { truncate } from "../term/width.ts";
17 import type { Session } from "../session.ts";
18 import { fill, len, split } from "../ui/layout.ts";
19 import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts";
20
21 export function identitiesScreen(f: Session, ctx: Ctx): Screen {
22 const state = new ListState();
23 let note = "";
24 const items = () => (f.user === undefined ? [] : connectionsOf(f.app, f.user));
25 const rows = (): ListRow[] =>
26 items().map((c) => ({
27 title: c.ident,
28 meta: c.proven
29 ? `proven · feedback ${c.uses.feedback ? "on" : "off"} · profile ${c.uses.profile ? "on" : "off"}`
30 : "not proven yet: c gives the code",
31 }));
32 const toggle = (use: Use): boolean => {
33 const c = items()[state.index];
34 if (c === undefined || f.user === undefined) return false;
35 const done = chooseUse(f.app, f.user, c.id, use, !c.uses[use]);
36 note = done.ok ? `${use} is ${done.value.uses[use] ? "on" : "off"}. ${NOT_RETROACTIVE}` : CONNECTION_WORDS[done.error];
37 ctx.invalidate();
38 return true;
39 };
40
41 const screen: Screen = {
42 title: "Proven emails",
43 keys: [
44 binding(["j", "k"], "move cursor"), binding(["a"], "add"), binding(["c"], "give the code"),
45 binding(["f"], "feedback on/off"), binding(["p"], "profile on/off"), binding(["d"], "remove"),
46 ],
47 render(area, s) {
48 const c = ctx.theme.c;
49 const [head, body] = split(area, "v", [len(1), fill(1)]);
50 const text = note !== "" ? note : items().length === 0 ? "None yet. a adds an address." : NOT_RETROACTIVE;
51 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
52 drawList(s, body!, c, state, rows());
53 },
54 key(e) {
55 if (state.key(e, items().length)) return true;
56 if (e.ctrl || e.alt || f.user === undefined) return false;
57 const user = f.user;
58 const c = items()[state.index];
59 if (e.key === "a") {
60 ctx.push(promptScreen(ctx, screen, {
61 title: "Add an email", label: "Address", hint: "a code is mailed to it",
62 onSubmit: async (v) => {
63 const made = await addConnection(f.app, user, v);
64 note = made.ok ? "A code was mailed. c gives it back." : CONNECTION_WORDS[made.error];
65 ctx.invalidate();
66 },
67 }));
68 return true;
69 }
70 if (e.key === "f") return toggle("feedback");
71 if (e.key === "p") return toggle("profile");
72 if (c === undefined) return false;
73 if (e.key === "c" && !c.proven) {
74 ctx.push(promptScreen(ctx, screen, {
75 title: `Prove ${c.ident}`, label: "Code", hint: "the code from the mail",
76 onSubmit: (v) => {
77 const done = confirmConnection(f.app, user, c.id, v);
78 note = done.ok ? "Proven. f and p choose its uses." : CONNECTION_WORDS[done.error];
79 ctx.invalidate();
80 return undefined;
81 },
82 }));
83 return true;
84 }
85 if (e.key === "d") {
86 ctx.push(confirmScreen(ctx, screen, {
87 title: "Remove connection", body: [`remove ${c.ident}? y/n`],
88 actions: [{ label: "Remove", variant: "danger" }, { label: "Cancel", variant: "ghost" }],
89 selected: 1, yesNo: true,
90 onChoose: (i) => {
91 if (i !== 0) return;
92 const gone = dropConnection(f.app, user, c.id);
93 note = gone.ok ? `Removed. ${NOT_RETROACTIVE}` : CONNECTION_WORDS[gone.error];
94 ctx.invalidate();
95 },
96 }));
97 return true;
98 }
99 return false;
100 },
101 };
102 return screen;
103 }
src/web/pages/identities.ts added +122
@@ -0,0 +1,122 @@
1 /**
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.
6 */
7
8 import { sshOn } from "../../settings/ssh.ts";
9 import {
10 CONNECTION_WORDS, NOT_RETROACTIVE, addConnection, chooseUse, confirmConnection, connectionsOf,
11 dropConnection,
12 } from "../../actions/identities.ts";
13 import { USES, type Connection, type Use } from "../../core/identities.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
16 import { pageHead, settingsLayout, signInFirst } from "../chrome.ts";
17 import { field, readForm } from "../form.ts";
18 import { html, type Html } from "../html.ts";
19 import { flashTo, page } from "../layout.ts";
20 import { btn, row, rowList } from "../ui.ts";
21 import { accountSections } from "./origins.ts";
22
23 const HERE = "/settings/identities";
24 const USE_WORDS: Record<Use, string> = {
25 feedback: "Name me on app feedback and crash reports",
26 profile: "Use for my profile",
27 };
28
29 const card = (c: Connection): Html => {
30 const act = (path: string, inner: Html) =>
31 html`<form class="row-actions" method="post" action="${HERE}/${c.id}/${path}">${inner}</form>`;
32 const uses = c.proven
33 ? USES.map((u) =>
34 act(
35 "use",
36 html`<input type="hidden" name="use" value="${u}" /><input type="hidden" name="on" value="${c.uses[u] ? "false" : "true"}" />
37 <span class="small">${USE_WORDS[u]}: <strong>${c.uses[u] ? "on" : "off"}</strong></span>
38 ${btn(c.uses[u] ? "Turn off" : "Turn on", { size: "sm", label: `${c.uses[u] ? "Turn off" : "Turn on"} ${u} for ${c.ident}` })}`,
39 ),
40 )
41 : act(
42 "confirm",
43 html`<input class="input mono" type="text" name="code" inputmode="numeric" maxlength="20" autocomplete="off"
44 placeholder="Code from the mail" aria-label="Code mailed to ${c.ident}" required />
45 ${btn("Prove", { variant: "primary", size: "sm", label: `Prove ${c.ident}` })}`,
46 );
47 return row({
48 title: html`<span class="mono">${c.ident}</span>`,
49 meta: html`${c.proven ? "proven" : "not proven yet"}`,
50 trail: act("delete", btn("Remove", { size: "sm", icon: "x", label: `Remove ${c.ident}` })),
51 after: html`${uses}`,
52 });
53 };
54
55 // GET /settings/identities
56 export function identitiesPage(ctx: Ctx): Response {
57 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
58 if (!ctx.auth.user) return signInFirst(ctx);
59 const list = connectionsOf(ctx.app, ctx.auth.user);
60 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 <p class="muted small">${NOT_RETROACTIVE}</p>
65 <form class="edit-row mt" method="post" action="${HERE}">

Non-blocking, principle 1: the page head sub-line and this paragraph both say what the page is for. Drop one.

66 <input class="input" type="email" name="email" placeholder="[email protected]" aria-label="Email address" maxlength="254" autocomplete="off" required />
67 ${btn("Send a code", { variant: "primary", size: "sm", icon: "plus" })}
68 </form>
69 </section>`;
70 const rendering = performance.now();
71 const response = page({
72 ctx,
73 title: "Proven emails",
74 body: html`${pageHead("Proven emails", { sub: "The addresses you proved are yours, and what each is for." })}
75 ${settingsLayout(accountSections("identities", { admin: ctx.auth.user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
76 });
77 notePhase(ctx.request, "render", performance.now() - rendering);
78 return response;
79 }
80
81 const said = (ctx: Ctx, message: string, ok: boolean): Response =>
82 flashTo(ctx, HERE, ok ? { message } : { tone: "danger", message });
83
84 /** Read the form as the signed-in account, same-origin; the acts below share it. */
85 async function acting(ctx: Ctx): Promise<{ form: import("../form.ts").Form } | Response> {
86 if (!ctx.auth.user) return signInFirst(ctx);
87 const form = await readForm(ctx, "admin");
88 return form instanceof Response ? form : { form };
89 }
90
91 // POST /settings/identities
92 export async function identityAdd(ctx: Ctx): Promise<Response> {
93 const got = await acting(ctx);
94 if (got instanceof Response) return got;
95 const made = await addConnection(ctx.app, ctx.auth.user!, field(got.form, "email"));
96 return said(ctx, made.ok ? "A code was mailed. Give it here to prove the address." : CONNECTION_WORDS[made.error], made.ok);
97 }
98
99 // POST /settings/identities/:id/confirm
100 export async function identityConfirm(ctx: Ctx): Promise<Response> {
101 const got = await acting(ctx);
102 if (got instanceof Response) return got;
103 const done = confirmConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", field(got.form, "code"));
104 return said(ctx, done.ok ? "That address is proven. Choose what it is for." : CONNECTION_WORDS[done.error], done.ok);
105 }
106
107 // POST /settings/identities/:id/use
108 export async function identityUse(ctx: Ctx): Promise<Response> {
109 const got = await acting(ctx);
110 if (got instanceof Response) return got;
111 const on = field(got.form, "on");
112 const done = chooseUse(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", field(got.form, "use"), on === "true" ? true : on === "false" ? false : undefined);
113 return said(ctx, done.ok ? "Saved. " + NOT_RETROACTIVE : CONNECTION_WORDS[done.error], done.ok);
114 }
115
116 // POST /settings/identities/:id/delete
117 export async function identityRemove(ctx: Ctx): Promise<Response> {
118 const got = await acting(ctx);
119 if (got instanceof Response) return got;
120 const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "");
121 return said(ctx, done.ok ? "Removed. " + NOT_RETROACTIVE : CONNECTION_WORDS[done.error], done.ok);
122 }
src/web/pages/origins.ts +2
@@ -115,6 +115,7 @@ export type AccountSection =
115115 | "model"
116116 | "passkeys"
117117 | "origins"
118 | "identities"
118119 | "usage"
119120 | "spend"
120121 | "crew"
@@ -178,6 +179,7 @@ const SECTION_ROWS: readonly (readonly [
178179 ["Crew and AI", "Subscriptions", "/settings/subscriptions", "key", (c) => c === "subscriptions", true],
179180 ["Crew and AI", "Usage", "/settings/spend", "activity", (c) => USAGE.has(c), true],
180181 ["Connections", "Connected accounts", "/settings/origins", "globe", (c) => c === "origins", false],
182 ["Connections", "Proven emails", "/settings/identities", "check", (c) => c === "identities", false],
181183 ["Connections", "Cloud", "/settings/cloud", "key", (c) => c === "cloud", true],
182184 ["Connections", "Infrastructure", "/infra", "globe", () => false, true], // what runs there and what it costs
183185 ["Connections", "Secrets", "/settings/secrets", "lock", (c) => c === "secrets", true],
src/web/palette_rows.ts +1
@@ -50,6 +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" },
5354 // The crew's model credentials are the admin's (`/settings/subscriptions` answers anyone else 403).
5455 ...(user.isAdmin
5556 ? [
test/identities-doors.test.ts added +116
@@ -0,0 +1,116 @@
1 /**
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.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { addEmail, listConnections, proveEmail } from "../src/core/identities.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import type { Ctx } from "../src/tui/app/app.ts";
16 import { identitiesScreen } from "../src/tui/screens/identities.ts";
17 import type { Session } from "../src/tui/session.ts";
18 import type { KeyEvent } from "../src/tui/term/input.ts";
19 import { Screen as Surface } from "../src/tui/term/screen.ts";
20 import { theme } from "../src/tui/ui/theme.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24
25 let dir: string;
26 let app: App;
27 let servers: Servers;
28 let tess: User;
29 let cookie: string;
30 const sent: string[] = [];
31
32 beforeAll(async () => {
33 dir = await mkdtemp(join(tmpdir(), "forge-identities-doors-"));
34 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example", mailer: async (m) => (sent.push(m.text), true) });
35 servers = await serve(app);
36 const t = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]" });
37 if (!t.ok) throw new Error("user");
38 tess = t.value;
39 cookie = `forge_session=${createSession(app.db, tess.id).token}`;
40 });
41 afterAll(async () => {
42 servers.stop();
43 app.close();
44 await rm(dir, { recursive: true, force: true });
45 });
46
47 const form = (path: string, fields: Record<string, string>, origin = "https://forge.example", c = cookie) =>
48 fetch(`${servers.url}${path}`, {
49 method: "POST",
50 redirect: "manual",
51 headers: { cookie: c, origin, "content-type": "application/x-www-form-urlencoded" },
52 body: new URLSearchParams(fields).toString(),
53 });
54
55 test("the page needs a signed-in account and a same-origin form", async () => {
56 const anon = await fetch(`${servers.url}/settings/identities`, { redirect: "manual" });
57 expect(anon.status).toBe(303);
58 expect((await form("/settings/identities", { email: "[email protected]" }, "https://forge.example", "")).status).toBe(303);
59 expect((await form("/settings/identities", { email: "[email protected]" }, "https://evil.example")).status).toBe(403);
60 expect(listConnections(app.db, tess.id)).toEqual([]);
61 });
62
63 test("add, prove, choose and remove by the page's forms; the note and the address are escaped", async () => {
64 expect((await form("/settings/identities", { email: "[email protected]" })).status).toBe(303);
65 const c = listConnections(app.db, tess.id)[0]!;
66 expect(c.proven).toBe(false);
67 expect((await form(`/settings/identities/${c.id}/confirm`, { code: "000000" })).status).toBe(303);
68 expect(listConnections(app.db, tess.id)[0]!.proven).toBe(false);
69 const code = /code is (\d{6})/.exec(sent.at(-1)!)![1]!;
70 await form(`/settings/identities/${c.id}/confirm`, { code });
71 expect(listConnections(app.db, tess.id)[0]!.proven).toBe(true);
72 await form(`/settings/identities/${c.id}/use`, { use: "feedback", on: "true" });
73 expect(listConnections(app.db, tess.id)[0]!.uses).toEqual({ feedback: true, profile: false });
74 await form(`/settings/identities/${c.id}/use`, { use: "bogus", on: "true" });
75 expect(listConnections(app.db, tess.id)[0]!.uses.profile).toBe(false);
76 const html = await (await fetch(`${servers.url}/settings/identities`, { headers: { cookie } })).text();
77 expect(html).toContain("[email protected]");
78 expect(html).toContain("Issues already filed are not rewritten");
79 await form(`/settings/identities/${c.id}/delete`, {});
80 expect(listConnections(app.db, tess.id)).toEqual([]);
81 });
82
83 test("another account's connection is not found through the page", async () => {
84 const o = await createUser(app.db, { origin: "seed", trusted: true, username: "otto", email: "[email protected]" });
85 if (!o.ok) throw new Error("user");
86 const made = addEmail(app.db, o.value.id, "[email protected]", Date.now());
87 if (typeof made === "string") throw new Error(made);
88 await form(`/settings/identities/${made.connection.id}/delete`, {});
89 expect(listConnections(app.db, o.value.id)).toHaveLength(1);
90 });
91
92 test("the terminal screen lists the account's own, switches a use and removes", () => {
93 const made = addEmail(app.db, tess.id, "[email protected]", Date.now() + 10 * 60_000);
94 if (typeof made === "string") throw new Error(made);
95 expect(proveEmail(app.db, tess.id, made.connection.id, made.code, Date.now() + 10 * 60_000)).toBe("proven");
96 const pushed: unknown[] = [];
97 const ctx = { theme: theme("dark"), icons: "nerd", invalidate() {}, push: (s: unknown) => pushed.push(s) } as unknown as Ctx;
98 const f = { app, db: app.db, user: tess } as unknown as Session;
99 const screen = identitiesScreen(f, ctx);
100 const draw = () => {
101 const s = new Surface(100, 6);
102 screen.render({ x: 0, y: 0, w: 100, h: 6 }, s);
103 return s.toText();
104 };
105 expect(draw()).toContain("[email protected]");
106 expect(draw()).toContain("feedback off");
107 const key = (k: string): KeyEvent => ({ type: "key", key: k, ctrl: false, alt: false, shift: false });
108 expect(screen.key!(key("f"))).toBe(true);
109 expect(draw()).toContain("feedback on");
110 expect(listConnections(app.db, tess.id)[0]!.uses.feedback).toBe(true);
111 expect(screen.key!(key("d"))).toBe(true);
112 expect(pushed).toHaveLength(1);
113 // Signed out, the screen shows and does nothing.
114 const anon = identitiesScreen({ app, db: app.db, user: undefined } as unknown as Session, ctx);
115 expect(anon.key!(key("f"))).toBe(false);
116 });
test/identities.test.ts added +210
@@ -0,0 +1,210 @@
1 /**
2 * Connections on an account (#18108): an email is added, proven with the
3 * mailed code, and the lookup answers nothing until the feedback use is on,
4 * then the user, then nothing again once the connection is removed. A second
5 * account cannot take a proven address; a report names its reporter only in
6 * the middle step.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { fileReport } from "../src/actions/reports.ts";
14 import { reporterFor } from "../src/actions/identities.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { AUDIT_KEEP_MS, LOOKUPS_PER_MINUTE, auditLookup } from "../src/core/identities.ts";
19 import type { Repo } from "../src/core/repos.ts";
20 import type { Mail } from "../src/kernel/mail.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { seedAdmin } from "./helpers/admin.ts";
23
24 describe("connections on an account", () => {
25 let dataDir: string;
26 let app: App;
27 let servers: Servers;
28 let base: string;
29 let admin: User;
30 let tess: User;
31 let repo: Repo;
32 let adminCookie: string;
33 let tessCookie: string;
34 let otherCookie: string;
35 let key: string;
36 const sent: Mail[] = [];
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-identities-"));
40 app = createApp({ dataDir, port: 0, url: "https://forge.example", mailer: async (m) => (sent.push(m), true) });
41 servers = await serve(app);
42 base = servers.url;
43 const a = await seedAdmin(app, { username: "olive", email: "[email protected]" });
44 if (!a.ok) throw new Error(a.error);
45 admin = a.value;
46 const t = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]" });
47 const o = await createUser(app.db, { origin: "seed", trusted: true, username: "otto", email: "[email protected]" });
48 if (!t.ok || !o.ok) throw new Error("users");
49 tess = t.value;
50 adminCookie = `forge_session=${createSession(app.db, admin.id).token}`;
51 tessCookie = `forge_session=${createSession(app.db, tess.id).token}`;
52 otherCookie = `forge_session=${createSession(app.db, o.value.id).token}`;
53 const r = await createRepo(app, admin, { name: "game", visibility: "public" });
54 if (!r.ok) throw new Error(String(r.error));
55 repo = r.value;
56 });
57 afterAll(async () => {
58 servers.stop();
59 app.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 const call = (method: string, path: string, cookie: string, payload?: unknown, headers: Record<string, string> = {}) =>
64 fetch(`${base}${path}`, {
65 method,
66 headers: { cookie, origin: "https://forge.example", "content-type": "application/json", ...headers },
67 ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
68 });
69 const ask = (email: string, use = "feedback") =>
70 call("POST", "/api/v1/connections/lookup", "", { email, use }, { "x-forge-lookup-key": key }).then((r) => r.json() as Promise<any>);
71 const codeSent = (): string => /code is (\d{6})/.exec(sent.at(-1)!.text)![1]!;
72
73 test("an unproven or unchosen connection is never answered; the lookup needs its key", async () => {
74 const made = await call("POST", "/api/v1/connections/lookup-keys", adminCookie, { name: "bridge" });
75 key = ((await made.json()) as any).key;
76 expect((await call("POST", "/api/v1/connections/lookup-keys", tessCookie, { name: "x" })).status).toBe(403);
77 expect((await call("POST", "/api/v1/connections/lookup", "", { email: "[email protected]", use: "feedback" })).status).toBe(404);
78
79 const added = await call("POST", "/api/v1/connections", tessCookie, { email: "[email protected]" });
80 expect(added.status).toBe(201);
81 const c = ((await added.json()) as any).connection;
82 expect(c).toMatchObject({ ident: "[email protected]", proven: false, uses: { feedback: false, profile: false } });
83 expect(sent.at(-1)!.to).toBe("[email protected]");
84 // Unproven: no use can be chosen and the lookup says nothing.
85 expect((await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, tessCookie, { on: true })).status).toBe(404);
86 expect((await ask("[email protected]")).user).toBeNull();
87 // A wrong code proves nothing; the stored value is a hash, not the code.
88 expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: "000000x" })).status).toBe(422);
89 const stored = app.db.query<{ code_hash: string }, []>("SELECT code_hash FROM connection").get()!;
90 expect(stored.code_hash).not.toContain(codeSent());
91 // Another account cannot prove it with the code mailed to this one.
92 expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, otherCookie, { code: codeSent() })).status).toBe(404);
93 expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: codeSent() })).status).toBe(200);
94 // The code is spent.
95 expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: codeSent() })).status).toBe(404);
96
97 // Proven but every use off: still nothing, and reports do not name her.
98 expect((await ask("[email protected]")).user).toBeNull();
99 const before = fileReport(app, repo, { title: "crash", body: "", page: "" }, "198.51.100.1", undefined,
100 reporterFor(app, key, "[email protected]"));
101 expect(before.ok && before.value.filedBy.how).toBe("anonymous");
102
103 // Feedback on: the user, and only for that use.
104 await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, tessCookie, { on: true });
105 expect((await ask("[email protected]")).user).toEqual({ username: "tess" });
106 expect((await ask("[email protected]", "profile")).user).toBeNull();
107 const during = fileReport(app, repo, { title: "crash 2", body: "", page: "" }, "198.51.100.2", undefined,
108 reporterFor(app, key, "[email protected]"));
109 expect(during.ok && during.value.filedBy).toEqual({ how: "signed", name: "tess" });
110
111 // A second account cannot claim the proven address.
112 // It answers as any new address does, and mails its owner nothing; the code it can never prove.
113 const mailed = sent.length;
114 const twice = await call("POST", "/api/v1/connections", otherCookie, { email: "[email protected]" });
115 const fresh = await call("POST", "/api/v1/connections", otherCookie, { email: "[email protected]" });
116 expect(twice.status).toBe(201);
117 expect(fresh.status).toBe(201);
118 expect(Object.keys(((await twice.json()) as any).connection)).toEqual(Object.keys(((await fresh.json()) as any).connection));
119 expect(sent.length).toBe(mailed + 1);
120 expect(sent.at(-1)!.to).toBe("[email protected]");
121 const ghost = app.db.query<{ id: string }, []>("SELECT id FROM connection WHERE ident = '[email protected]' AND proven_at IS NULL").get()!;
122 expect((await call("POST", `/api/v1/connections/${ghost.id}/confirm`, otherCookie, { code: "123456" })).status).toBe(422);
123 expect((await ask("[email protected]")).user).toEqual({ username: "tess" });
124
125 // Removed (the ghost proves nothing): nothing again; the report already filed keeps its filer.
126 expect((await call("DELETE", `/api/v1/connections/${c.id}`, tessCookie)).status).toBe(200);
127 expect((await ask("[email protected]")).user).toBeNull();
128 const after = fileReport(app, repo, { title: "crash 3", body: "", page: "" }, "198.51.100.3", undefined,
129 reporterFor(app, key, "[email protected]"));
130 expect(after.ok && after.value.filedBy.how).toBe("anonymous");
131 expect(during.ok && during.value.filedBy.name).toBe("tess");
132 const listed = (await (await call("GET", "/api/v1/connections", tessCookie)).json()) as any;
133 expect(listed.connections).toEqual([]);
134 expect(listed.note).toContain("not rewritten");
135 });
136
137 test("a key's name that is wrong says so; one account's mail is capped however many addresses it adds", async () => {
138 const bad = await call("POST", "/api/v1/connections/lookup-keys", adminCookie, { name: "<b>" });
139 expect(bad.status).toBe(422);
140 expect(((await bad.json()) as any).error).toBe("invalid_name");
141 const mailed = sent.length;
142 let last = 201;
143 for (let i = 0; i < 22; i++) {
144 const r = await call("POST", "/api/v1/connections", adminCookie, { email: `n${i}@example.org` });
145 last = r.status;
146 if (r.status === 201) {
147 const id = ((await r.json()) as any).connection.id;
148 await call("DELETE", `/api/v1/connections/${id}`, adminCookie);
149 }
150 }
151 expect(last).toBe(429);
152 expect(sent.length - mailed).toBe(20);
153 });
154
155 test("the audit is pruned on the key's next call; no header and a revoked key touch nothing", () => {
156 const keyId = app.db.query<{ id: string }, []>("SELECT id FROM connection_lookup_key").get()!.id;
157 const now = Date.now();
158 app.db.query("INSERT INTO connection_lookup_audit (at, key_id, use, answered) VALUES (?1, ?2, 'feedback', 0)")
159 .run(new Date(now - AUDIT_KEEP_MS - 1000).toISOString(), keyId);
160 app.db.query("INSERT INTO connection_lookup_audit (at, key_id, use, answered) VALUES (?1, 'other', 'feedback', 0)")
161 .run(new Date(now - AUDIT_KEEP_MS - 1000).toISOString());
162 expect(auditLookup(app.db, keyId, "feedback", false, now + 120_000)).toBe(true);
163 const left = app.db.query<{ key_id: string; at: string }, []>("SELECT key_id, at FROM connection_lookup_audit").all();
164 expect(left.every((r) => r.key_id === "other" || r.at > new Date(now - AUDIT_KEEP_MS).toISOString())).toBe(true);
165 expect(left.filter((r) => r.key_id === keyId).length).toBeGreaterThan(0);
166 const count = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM connection_lookup_audit").get()!.n;
167 const n = count();
168 expect(reporterFor(app, "", "[email protected]")).toBeUndefined();
169 expect(count()).toBe(n);
170 });
171
172 test("the reports route: a revoked key and no header file anonymously", async () => {
173 const mk = await call("POST", "/api/v1/connections/lookup-keys", adminCookie, { name: "second" });
174 const live = ((await mk.json()) as any);
175 const c = ((await (await call("POST", "/api/v1/connections", tessCookie, { email: "[email protected]" })).json()) as any).connection;
176 await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: codeSent() });
177 await call("PUT", `/api/v1/connections/${c.id}/uses/feedback`, tessCookie, { on: true });
178 const file = async (headers: Record<string, string>, title: string) => {
179 const r = await call("POST", `/api/v1/repos/olive/game/reports`, "", { title, reporter: "[email protected]" }, headers);
180 expect(r.status).toBe(202);
181 };
182 await file({ "x-forge-lookup-key": live.key }, "named");
183 await call("DELETE", `/api/v1/connections/lookup-keys/${live.id}`, adminCookie);
184 await file({ "x-forge-lookup-key": live.key }, "revoked");
185 await file({}, "bare");
186 const by = (t: string) => app.db.query<{ user_id: string | null }, [string]>("SELECT filer_id AS user_id FROM report WHERE title = ?1").get(t)?.user_id;
187 expect(by("named")).toBe(tess.id);
188 expect(by("revoked") ?? null).toBeNull();
189 expect(by("bare") ?? null).toBeNull();
190 });
191
192 test("a revoked or foreign key is refused, a cross-origin act is refused, and calls are limited and audited", async () => {
193 expect((await call("POST", "/api/v1/connections/lookup", "", { email: "[email protected]", use: "feedback" }, { "x-forge-lookup-key": "fcl_nope" })).status).toBe(404);
194 const cross = await fetch(`${base}/api/v1/connections`, {
195 method: "POST",
196 headers: { cookie: tessCookie, origin: "https://evil.example", "content-type": "application/json" },
197 body: JSON.stringify({ email: "[email protected]" }),
198 });
199 expect(cross.status).toBe(403);
200 expect((await call("POST", "/api/v1/connections", tessCookie, { email: "not-an-email" })).status).toBe(422);
201 app.db.run("DELETE FROM connection_lookup_audit");
202 let last = 200;
203 for (let i = 0; i < LOOKUPS_PER_MINUTE + 1; i++) last = (await call("POST", "/api/v1/connections/lookup", "", { email: "[email protected]", use: "feedback" }, { "x-forge-lookup-key": key })).status;
204 expect(last).toBe(429);
205 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM connection_lookup_audit").get()!.n).toBe(LOOKUPS_PER_MINUTE);
206 const keyId = app.db.query<{ id: string }, []>("SELECT id FROM connection_lookup_key").get()!.id;
207 expect((await call("DELETE", `/api/v1/connections/lookup-keys/${keyId}`, adminCookie)).status).toBe(200);
208 expect((await call("POST", "/api/v1/connections/lookup", "", { email: "[email protected]", use: "feedback" }, { "x-forge-lookup-key": key })).status).toBe(404);
209 });
210 });
test/palette-roster.test.ts +2
@@ -124,6 +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"],
127128 ["account", "Account settings", undefined],
128129 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
129130 ["sentinel", "Sentinel", "the forge's open faults"],
@@ -478,6 +479,7 @@ test("a member person is offered the signed-in roster without the admin entries"
478479 ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"],
479480 ["fork-flows", "Fork flows", "what I follow, what I offered, what my forks offered me"],
480481 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
482 ["proven-emails", "Proven emails", "the addresses I proved, and what each is for"],
481483 ["account", "Account settings", undefined],
482484 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
483485 ["oauth-grants", "Connected agents", "the agents you let in through OAuth; x revokes one"],

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

Keyboard shortcuts

Docs