Public: anyone can read this; the crew can change it.
A person downloads everything the forge holds about them as one JSON file, with no secret in it #15678
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15617-a-person-downloads-everything-the-forge → main 0 commits fork 7 threads · 7 unresolved
docs/features/account-help.md +16
| @@ -15,3 +15,19 @@ The terminal (both doors): it has no account-settings screen, so there are no fi | ||
| 15 | 15 | `src/tui` edits no profile, password, token or notify URL. Nothing changes there. |
| 16 | 16 | |
| 17 | 17 | Pinned by `test/account-help.test.ts`; design note in `docs/design/areas/settings.md`. |
| 18 | ||
| 19 | ## Download my data | |
| 20 | ||
| 21 | **Your data › Download** on `/settings/payments` saves one JSON file of what the forge holds about you (#15617): | |
| 22 | profile (email and which address commits use), SSH key names and fingerprints, token names and scopes, signed-in | |
| 23 | devices, the repositories you own or write by team (name, visibility, clone URL), the forges you claimed and their | |
| 24 | payments. It sits there, beside the payments it also holds, so the settings page's first view stays inside its | |
| 25 | attention budget. `src/core/account_export.ts` builds it from an allow-list: every column of the account's tables is | |
| 26 | named there as exported or withheld, so a column added later stays out until someone decides. Never in it: the | |
| 27 | password hash, a token, a session id, a key's blob, a session's network address, a repository you only read. Over the | |
| 28 | API it is `GET /api/v1/user/export` (a session from the forge's own page, the password, or an admin token). | |
| 29 | ||
| 30 | The terminal (both doors): `ssh <forge> export > me.json` writes the same file, built by the same | |
| 31 | `accountExportFor`, to your own machine as the account the key belongs to (`serveExport` in `src/core/account_export.ts`). The profile | |
| 32 | screen counts what it holds and `x` shows that command, word for word from the forge's own address, or says the | |
| 33 | terminal is off. The screen writes no file itself: one written there would land on the forge's disk, not yours. |
docs/guide-backups-moving.md +1
| @@ -14,6 +14,7 @@ Recovery is a printable guide, with two routes: the restore command, or the obje | ||
| 14 | 14 | |
| 15 | 15 | - **To your machine**: `forge sync` clones the apps you pin (or, with none pinned, the ones you own), and work continues offline. See [](ON-YOUR-MACHINE.md). |
| 16 | 16 | - **Between forges**: connect another forge as an origin at `/settings/origins`, bring an app in, and send changes back. See [](ORIGINS.md). |
| 17 | - **Your own data**: **Download** under Your data at `/settings/payments` saves one JSON file of what the forge holds about you, no secret in it; the terminal writes the same file ([](features/account-help.md)). | |
| 17 | 18 | - **To a new owner**: transfer an app from its Danger zone. Old links keep working ([](features/repo-transfer.md)). |
| 18 | 19 | |
| 19 | 20 | To keep your repositories mirrored on your machine, so you can work offline, run this after `forge login`: |
src/actions/forge_bill.ts +37
| @@ -16,6 +16,10 @@ import { getRepo } from "../core/repos.ts"; | ||
| 16 | 16 | import type { User } from "../core/users.ts"; |
| 17 | 17 | import { emailVerified } from "../core/verify.ts"; |
| 18 | 18 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 19 | import { listPayments, type Payment } from "../billing/payments.ts"; | |
| 20 | import { getStored } from "../billing/store.ts"; | |
| 21 | import { getPlan } from "../settings/plans.ts"; | |
| 22 | import { servedNow } from "../spawn/clients.ts"; | |
| 19 | 23 | import { loadOrCreateHostKey } from "../ssh/keys.ts"; |
| 20 | 24 | import { childPerson } from "../spawn/child_db.ts"; |
| 21 | 25 | import { billTo } from "../spawn/person_activity.ts"; |
| @@ -64,3 +68,36 @@ export async function readBill( | ||
| 64 | 68 | }); |
| 65 | 69 | return ok({ file: `${child.name}-${asked}.bill.jsonl`, month: asked, text }); |
| 66 | 70 | } |
| 71 | ||
| 72 | /** | |
| 73 | * The forges a person claimed and the payments recorded for them (#12276, #13093), as plain rows: | |
| 74 | * the settings page's bills block, /settings/payments, the terminal's bills screen and the account | |
| 75 | * export (#15617) all read them here, so the API never imports a page. | |
| 76 | */ | |
| 77 | /** The forges this person claimed that are finished; their names. */ | |
| 78 | export const billNames = (app: App, user: User): string[] => | |
| 79 | servedNow(app) | |
| 80 | .filter((r) => r.made && claimsBill(app.db, user, r.billTo)) | |
| 81 | .map((r) => r.name); | |
| 82 | ||
| 83 | export interface PaymentLine extends Payment { | |
| 84 | /** The forge's plan now: the store keeps no plan per payment. */ | |
| 85 | readonly plan: string; | |
| 86 | } | |
| 87 | ||
| 88 | /** The most rows listed; a person with more is told so. */ | |
| 89 | export const PAYMENTS_CAP = 100; | |
| 90 | ||
| 91 | /** This person's payments, newest first: those of every forge they claimed, once each. */ | |
| 92 | export function paymentsFor(app: App, user: User | undefined): { rows: PaymentLine[]; more: boolean } { | |
| 93 | if (user === undefined) return { rows: [], more: false }; | |
| 94 | const seen = new Map<string, PaymentLine>(); | |
| 95 | for (const forge of billNames(app, user)) { | |
| 96 | const e = getStored(app.db, forge); | |
| 97 | if (e === undefined || e.customerId === "") continue; | |
| 98 | const plan = getPlan(app.db, e.plan)?.name ?? e.plan; | |
| 99 | for (const p of listPayments(app.db, e.customerId, PAYMENTS_CAP + 1)) if (!seen.has(p.id)) seen.set(p.id, { ...p, plan }); | |
| 100 | } | |
| 101 | const all = [...seen.values()].sort((a, b) => (a.at === b.at ? (a.id < b.id ? 1 : -1) : a.at < b.at ? 1 : -1)); | |
| 102 | return { rows: all.slice(0, PAYMENTS_CAP), more: all.length > PAYMENTS_CAP }; | |
| 103 | } |
src/contract/openapi/routes/getApiV1UserExport.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/user/export", | |
| 6 | summary: "Download everything the forge holds about you", | |
| 7 | detail: | |
| 8 | "One JSON file (#15617): profile, SSH key names and fingerprints, token names and scopes, signed-in devices, the repositories you own or write, your forges and payments; never a password, token, session id or secret. A session from the forge's own page, the password, or an admin token", | |
| 9 | auth: true, | |
| 10 | role: "member", | |
| 11 | refuses: [401], | |
| 12 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -231,6 +231,7 @@ export { route as getApiV1Tokens } from "./getApiV1Tokens.ts"; | ||
| 231 | 231 | export { route as getApiV1Usage } from "./getApiV1Usage.ts"; |
| 232 | 232 | export { route as getApiV1User } from "./getApiV1User.ts"; |
| 233 | 233 | export { route as getApiV1UserAssigned } from "./getApiV1UserAssigned.ts"; |
| 234 | export { route as getApiV1UserExport } from "./getApiV1UserExport.ts"; | |
| 234 | 235 | export { route as getApiV1UserKeys } from "./getApiV1UserKeys.ts"; |
| 235 | 236 | export { route as getApiV1UserNextSteps } from "./getApiV1UserNextSteps.ts"; |
| 236 | 237 | export { route as getApiV1UserNotify } from "./getApiV1UserNotify.ts"; |
src/core/account_export.ts added +154
| @@ -0,0 +1,154 @@ | ||
| 1 | /** | |
| 2 | * Everything the forge holds about one person, as one plain document (#15617): | |
| 3 | * `GET /api/v1/user/export` answers it, the account page links it. Leaving must | |
| 4 | * be possible, and the file says what it holds. | |
| 5 | * | |
| 6 | * Built from an allow-list, never `SELECT *`: each table a person's rows live | |
| 7 | * in names every column in `COLUMNS`, as either exported or withheld (and | |
| 8 | * why), and `test/account-export.test.ts` fails on a column it does not name, | |
| 9 | * so a field added later is held out until someone decides. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import type { App } from "../app.ts"; | |
| 14 | import { billNames, paymentsFor } from "../actions/forge_bill.ts"; | |
| 15 | import type { User } from "./users.ts"; | |
| 16 | ||
| 17 | /** Where the file is, over HTTP. */ | |
| 18 | export const EXPORT_PATH = "/api/v1/user/export"; | |
| 19 | ||
| 20 | /** The one sentence every door says about the file. */ | |
| 21 | export const EXPORT_WORDS = "One JSON file of what the forge holds about you. No secrets."; | |
| 22 | ||
| 23 | /** The exec word that writes the same file to a terminal's standard output. */ | |
| 24 | export const EXPORT_EXEC = "export"; | |
| 25 | ||
| 26 | /** The download's file name: the username with anything outside `[A-Za-z0-9_.-]` made `_`. */ | |
| 27 | export const exportFileName = (username: string): string => `${username.replace(/[^A-Za-z0-9_.-]/g, "_")}-forge-export.json`; | |
| 28 | ||
| 29 | /** Every column of the person's tables, sorted into what leaves and what stays. */ | |
| 30 | export const COLUMNS: Record<string, { exported: readonly string[]; withheld: Record<string, string> }> = { | |
| 31 | user: { | |
| 32 | exported: ["username", "email", "display_name", "is_admin", "created_at", "kind", "commit_email"], | |
| 33 | withheld: { | |
| 34 | id: "an internal key", | |
| 35 | password_hash: "a secret", | |
| 36 | is_agent: "said by kind", | |
| 37 | suspended_at: "a moderator's record", | |
| 38 | removed_at: "a moderator's record", | |
| 39 | waiting_at: "a moderator's record", | |
| 40 | }, | |
| 41 | }, | |
| 42 | user_key: { | |
| 43 | exported: ["name", "algo", "fingerprint", "created_at", "last_used_at"], | |
| 44 | withheld: { id: "an internal key", user_id: "the person", blob: "the fingerprint names the key" }, | |
| 45 | }, | |
| 46 | token: { | |
| 47 | exported: ["name", "scope", "created_at", "last_used_at", "expires_at"], | |
| 48 | withheld: { id: "an internal key", token_hash: "a secret", user_id: "the person" }, | |
| 49 | }, | |
| 50 | session: { | |
| 51 | exported: ["browser", "created_at", "last_seen_at", "expires_at"], | |
| 52 | withheld: { token_hash: "a secret", id: "a session id", user_id: "the person", address: "network detail, not asked for" }, | |
| 53 | }, | |
| 54 | }; | |
| 55 | ||
| 56 | /** | |
| 57 | * What the caller adds that lives outside these tables: the forges' names and their payment rows. | |
| 58 | */ | |
| 59 | export interface ExportExtras { | |
| 60 | origin: string; | |
| 61 | forges: readonly string[]; | |
| 62 | payments: readonly { amountMinor: number; currency: string; status: string; at: string; plan: string }[]; | |
| 63 | } | |
| 64 | ||
| 65 | const cols = (table: string, prefix = ""): string => COLUMNS[table]!.exported.map((c) => `${prefix}${c}`).join(", "); | |
| 66 | ||
| 67 | /** | |
| 68 | * The repositories this person owns or may write by team; never the forge-wide | |
| 69 | * reach an admin has, and never one they only read. | |
| 70 | */ | |
| 71 | const WRITES = `repo.owner_id = ?1 | |
| 72 | OR repo.owner_id IN (SELECT team.org_id FROM team JOIN team_member ON team_member.team_id = team.id | |
| 73 | WHERE team_member.user_id = ?1 AND team.permission IN ('write','admin'))`; | |
| 74 | ||
| 75 | /** What the file holds, counted with three small queries (the terminal's profile row). */ | |
| 76 | export function exportCounts(db: Database, userId: string): { keys: number; tokens: number; repositories: number } { | |
| 77 | const count = (sql: string): number => db.query<{ n: number }, [string]>(sql).get(userId)?.n ?? 0; | |
| 78 | return { | |
| 79 | keys: count("SELECT count(*) AS n FROM user_key WHERE user_id = ?1"), | |
| 80 | tokens: count("SELECT count(*) AS n FROM token WHERE user_id = ?1"), | |
| 81 | repositories: count(`SELECT count(*) AS n FROM repo WHERE ${WRITES}`), | |
| 82 | }; | |
| 83 | } | |
| 84 | ||
| 85 | /** The document for a signed-in person, with their forges and payments: every door calls this. */ | |
| 86 | export const accountExportFor = (app: App, user: User, origin: string) => | |
outdated
If commit_email equals email, the address is listed twice. Dedupe (new Set). Also |
||
| 87 | accountExport(app.db, user.id, { origin, forges: billNames(app, user), payments: paymentsFor(app, user).rows }); | |
| 88 | ||
| 89 | /** The document, or undefined when no such person is here. */ | |
| 90 | export function accountExport(db: Database, userId: string, extras: ExportExtras) { | |
| 91 | const profile = db.query<Record<string, unknown>, [string]>(`SELECT ${cols("user")} FROM user WHERE id = ?1`).get(userId); | |
| 92 | if (profile === null) return undefined; | |
| 93 | const rows = (table: string) => | |
| 94 | db.query<Record<string, unknown>, [string]>(`SELECT ${cols(table)} FROM ${table} WHERE user_id = ?1 ORDER BY created_at`).all(userId); | |
| 95 | const origin = extras.origin.replace(/\/+$/, ""); | |
| 96 | const repositories = db | |
| 97 | .query<{ owner: string; name: string; visibility: string; owns: number }, [string]>( | |
| 98 | `SELECT owner.username AS owner, repo.name, repo.visibility, repo.owner_id = ?1 AS owns | |
| 99 | FROM repo JOIN user AS owner ON owner.id = repo.owner_id | |
| 100 | WHERE ${WRITES} ORDER BY owner.username, repo.name`, | |
| 101 | ) | |
| 102 | .all(userId) | |
| 103 | .map((r) => ({ | |
| 104 | name: `${r.owner}/${r.name}`, | |
| 105 | visibility: r.visibility, | |
| 106 | role: r.owns ? "owner" : "writer", | |
| 107 | cloneUrl: `${origin}/${r.owner}/${r.name}.git`, | |
| 108 | })); | |
| 109 | return { | |
| 110 | about: | |
| 111 | "Everything this forge holds about you: profile (with your email and which address your commits use), SSH key names and fingerprints, token names and scopes, " + | |
| 112 | "signed-in devices, the repositories you own or write, your forges and payments. No password, token, session id or secret is in it.", | |
| 113 | exportedAt: new Date().toISOString(), | |
| 114 | profile, | |
| 115 | sshKeys: rows("user_key"), | |
| 116 | tokens: rows("token"), | |
| 117 | sessions: rows("session"), | |
| 118 | repositories, | |
| 119 | forges: [...extras.forges], | |
| 120 | payments: extras.payments.map((p) => ({ amountMinor: p.amountMinor, currency: p.currency, status: p.status, at: p.at, plan: p.plan })), | |
| 121 | }; | |
| 122 | } | |
| 123 | ||
| 124 | /** | |
| 125 | * `ssh <forge> export > me.json` (#15617): the terminal's door to the same one-file export | |
| 126 | * `GET /api/v1/user/export` answers, built by the same `accountExportFor`, as the account the | |
| 127 | * presented key belongs to. The JSON goes to standard output and lands on the person's own | |
| 128 | * machine; nothing is written on the forge's. A key the forge does not know is refused. | |
| 129 | */ | |
| 130 | ||
| 131 | /** The part of an ssh session the export writes to. */ | |
| 132 | export interface ExportSession { | |
| 133 | write(text: string): void; | |
| 134 | writeStderr(text: string): void; | |
| 135 | exit(code: number): void; | |
| 136 | } | |
| 137 | ||
| 138 | /** What an unknown key, or an agent, is told. */ | |
| 139 | export const EXPORT_ACCOUNT_WORDS = "export needs a person's account: add this key under Settings › Keys"; | |
| 140 | ||
| 141 | /** True when the exec is the export, and nothing more. */ | |
| 142 | export const isExportCommand = (command: string | undefined): boolean => command?.trim() === EXPORT_EXEC; | |
| 143 | ||
| 144 | /** Write the person's export to the session's standard output, then exit. */ | |
| 145 | export function serveExport(app: App, session: ExportSession, user: User | undefined): void { | |
| 146 | const doc = user === undefined || user.kind !== "user" ? undefined : accountExportFor(app, user, (app.config.url ?? "").replace(/\/+$/, "")); | |
| 147 | if (doc === undefined) { | |
| 148 | session.writeStderr(`forge: ${EXPORT_ACCOUNT_WORDS}\r\n`); | |
| 149 | session.exit(1); | |
| 150 | return; | |
| 151 | } | |
| 152 | session.write(`${JSON.stringify(doc, null, 2)}\n`); | |
| 153 | session.exit(0); | |
| 154 | } |
src/http/api/user.ts +16
| @@ -17,6 +17,7 @@ import { NOTIFY_ERRORS, notifyHost, notifyUrlOf, setNotifyUrl } from "../../crew | ||
| 17 | 17 | import { listAssignedTo } from "../../core/issues.ts"; |
| 18 | 18 | import { nextStepsFor } from "../../core/next-steps.ts"; |
| 19 | 19 | import { listKeys, publicKey } from "../../core/keys.ts"; |
| 20 | import { accountExportFor, exportFileName } from "../../core/account_export.ts"; | |
| 20 | 21 | import { listOrgsForUser } from "../../core/orgs.ts"; |
| 21 | 22 | import { canRead, getRepo, getReposByIds, readableRepoIds } from "../../core/repos.ts"; |
outdated
Layering: src/http/api imports from src/web/pages (billNames, paymentsFor). The API now depends on page modules. Move those two into src/core (the page can import them from there) and import from core here. |
||
| 22 | 23 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| @@ -200,6 +201,21 @@ export function userRoutes(router: Router<Handler>): void { | ||
| 200 | 201 | return timePhase(ctx.request, "render", () => json(keyedPage(orgs, (o) => o.username, window))); |
| 201 | 202 | }); |
| 202 | 203 | |
| 204 | // Everything held about the caller, as one file to take away (#15617): | |
| 205 | // a session from our own page, the password, or an admin token. | |
| 206 | router.add("GET", "/api/v1/user/export", (ctx) => { | |
| 207 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 208 | const denied = requireAccount(ctx, { adminToken: true }); | |
| 209 | if (denied) return denied; | |
| 210 | const user = ctx.auth.user!; | |
| 211 | const doc = accountExportFor(ctx.app, user, ctx.url.origin); | |
| 212 | if (doc === undefined) return notFound(); | |
| 213 | return json(doc, 200, { | |
| 214 | "cache-control": "private, no-store", | |
| 215 | "content-disposition": `attachment; filename="${exportFileName(user.username)}"`, | |
| 216 | }); | |
| 217 | }); | |
| 218 | ||
| 203 | 219 | // SSH keys — what the SSH listener authenticates against. Public keys are |
| 204 | 220 | // public, so the list returns them whole. |
| 205 | 221 | router.add("GET", "/api/v1/user/keys", (ctx) => { |
src/tui/screens/bills.ts +1 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | import { readBill } from "../../actions/forge_bill.ts"; |
| 9 | 9 | import { verifyBill } from "../../core/ledger_bill.ts"; |
| 10 | import { billNames } from "../../web/pages/bills.ts"; | |
| 10 | import { billNames } from "../../actions/forge_bill.ts"; | |
| 11 | 11 | import type { Ctx, Screen } from "../app/app.ts"; |
| 12 | 12 | import { binding } from "../app/keys.ts"; |
| 13 | 13 | import { style } from "../term/style.ts"; |
src/tui/screens/payments.ts +2 −1
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | * nothing. Status word first, then date, amount and the forge's plan now. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { amountWords, paymentsFor, PAYMENTS_CAP } from "../../web/pages/payments.ts"; | |
| 7 | import { paymentsFor, PAYMENTS_CAP } from "../../actions/forge_bill.ts"; | |
| 8 | import { amountWords } from "../../web/pages/payments.ts"; | |
| 8 | 9 | import type { Ctx, Screen } from "../app/app.ts"; |
| 9 | 10 | import { binding } from "../app/keys.ts"; |
| 10 | 11 | import { style } from "../term/style.ts"; |
src/tui/screens/profile.ts +31 −4
| @@ -2,20 +2,41 @@ | ||
| 2 | 2 | * Your profile, in the terminal: username, display name and email, with `n` |
| 3 | 3 | * and `e` to change the last two through `updateProfile` — the action behind |
| 4 | 4 | * Settings › Account, refusing in the same words. A new email starts |
| 5 | * verification exactly as it does on the web. | |
| 5 | * verification exactly as it does on the web. The last row counts the one-file | |
| 6 | * export of the account (#15617), and `x` says the exec that writes it to the | |
| 7 | * person's own machine (`ssh … export > file`, `serveExport` in `src/core/account_export.ts`): a | |
| 8 | * file written here would land on the forge's disk, not theirs. | |
| 6 | 9 | */ |
| 7 | 10 | |
| 8 | 11 | import { emailSavedWords, PROFILE_FALLBACK, PROFILE_REFUSALS } from "../../actions/profile_words.ts"; |
| 9 | 12 | import { updateProfile } from "../../actions/users.ts"; |
| 10 | import { isStandInEmail } from "../../core/users.ts"; | |
| 13 | import { EXPORT_EXEC, EXPORT_PATH, EXPORT_WORDS, exportCounts, exportFileName } from "../../core/account_export.ts"; | |
| 14 | import { sshCommand } from "../../ssh/command.ts"; | |
| 15 | import type { Database } from "bun:sqlite"; | |
| 16 | import { isStandInEmail, type User } from "../../core/users.ts"; | |
| 11 | 17 | import type { Ctx, Screen } from "../app/app.ts"; |
| 12 | 18 | import { binding } from "../app/keys.ts"; |
| 13 | 19 | import type { Session } from "../session.ts"; |
| 14 | 20 | import { style } from "../term/style.ts"; |
| 15 | 21 | import { truncate } from "../term/width.ts"; |
| 16 | import { promptScreen } from "./common.ts"; | |
| 22 | import { confirmScreen, promptScreen } from "./common.ts"; | |
| 17 | 23 | import type { PaletteEntry } from "./entries.ts"; |
| 18 | 24 | |
outdated
This builds the whole export (keys, tokens, sessions, repos) just to count, on every screen construction. Count with the core function that has a small query, or expose counts from account_export.ts. Also the 'Download my data on /settings' wording is hard-coded in the TUI; keep one source. |
||
| 25 | /** What the export holds, counted with small queries (#15617). */ | |
| 26 | export function exportWords(db: Database, user: User | undefined): string { | |
| 27 | if (user === undefined) return "none"; | |
| 28 | const c = exportCounts(db, user.id); | |
| 29 | const n = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`; | |
| 30 | return `${n(c.keys, "key")}, ${n(c.tokens, "token")}, ${n(c.repositories, "repository", "repositories")}; x to take it`; | |
| 31 | } | |
| 32 | ||
| 33 | /** How this terminal takes the file: the exec that prints it, or why there is none. */ | |
| 34 | export function exportHow(app: Session["app"], user: User): string[] { | |
| 35 | const ssh = sshCommand(app); | |
| 36 | if (ssh === undefined) return [EXPORT_WORDS, "", `The terminal is off on this forge; download it on the web at ${EXPORT_PATH}.`]; | |
| 37 | return [EXPORT_WORDS, "", "Run this on your own machine, with this key:", "", `${ssh} ${EXPORT_EXEC} > ${exportFileName(user.username)}`]; | |
| 38 | } | |
| 39 | ||
| 19 | 40 | export function profileScreen(f: Session, ctx: Ctx): Screen { |
| 20 | 41 | const save = (patch: { displayName: string } | { email: string }): string | undefined => { |
| 21 | 42 | const r = updateProfile(f.app, f.user, patch); |
| @@ -31,9 +52,10 @@ export function profileScreen(f: Session, ctx: Ctx): Screen { | ||
| 31 | 52 | return undefined; |
| 32 | 53 | }; |
| 33 | 54 | |
| 55 | const held = exportWords(f.app.db, f.user); | |
| 34 | 56 | const screen: Screen = { |
| 35 | 57 | title: "Your profile", |
| 36 | keys: [binding(["n"], "set display name"), binding(["e"], "set email")], | |
| 58 | keys: [binding(["n"], "set display name"), binding(["e"], "set email"), binding(["x"], "take my data")], | |
| 37 | 59 | render(area, s) { |
outdated
Both doors: the terminal cannot take the file; it only tells the person to leave the terminal and use a browser. Give the screen a key (e.g. |
||
| 38 | 60 | const c = ctx.theme.c; |
| 39 | 61 | const u = f.user; |
| @@ -43,6 +65,7 @@ export function profileScreen(f: Session, ctx: Ctx): Screen { | ||
| 43 | 65 | ["Username", u.username], |
| 44 | 66 | ["Display name", u.displayName], |
| 45 | 67 | ["Email", email], |
| 68 | ["Your data", held], | |
| 46 | 69 | ]; |
| 47 | 70 | rows.forEach(([k, v], i) => { |
| 48 | 71 | const y = area.y + i; |
| @@ -63,6 +86,10 @@ export function profileScreen(f: Session, ctx: Ctx): Screen { | ||
| 63 | 86 | ); |
| 64 | 87 | return true; |
| 65 | 88 | } |
| 89 | if (e.key === "x") { | |
| 90 | ctx.push(confirmScreen(ctx, screen, { title: "Your data", body: exportHow(f.app, f.user), actions: [{ label: "Close" }], onChoose: () => ctx.invalidate(), width: 76 })); | |
| 91 | return true; | |
| 92 | } | |
| 66 | 93 | if (e.key === "e") { |
| 67 | 94 | ctx.push( |
| 68 | 95 | promptScreen(ctx, screen, { |
src/tui/ssh.ts +6
| @@ -35,6 +35,7 @@ import type { Terminal } from "./term/terminal.ts"; | ||
| 35 | 35 | import type { createForgeApp as CreateForgeApp } from "./forge.ts"; |
| 36 | 36 | import type { TuiIdentity } from "./session.ts"; |
| 37 | 37 | import { GUEST_RATE_WORDS, GuestRate } from "./ssh-guest-rate.ts"; |
| 38 | import { isExportCommand, serveExport } from "../core/account_export.ts"; | |
| 38 | 39 | import { parseTalkAgain, parseTalkCommand, serveTalk, serveTalkAgain } from "./ssh-talk.ts"; |
| 39 | 40 | import { fullSentence, isFull } from "../kernel/full_disk.ts"; |
| 40 | 41 | import { parseTellCommand, serveTell } from "./ssh-tell.ts"; |
| @@ -313,6 +314,11 @@ export function forgeSshSession( | ||
| 313 | 314 | ); |
| 314 | 315 | return; |
| 315 | 316 | } |
| 317 | // `export`: everything held about the person, as JSON on standard output (#15617). | |
| 318 | if (door === undefined && isExportCommand(session.command)) { | |
| 319 | serveExport(forge, session, identity.user); | |
| 320 | return; | |
| 321 | } | |
| 316 | 322 | // `talk <words>`: the forge's own agent, as the person. |
| 317 | 323 | const talked = parseTalkCommand(session.command); |
| 318 | 324 | if (talked !== undefined && door === undefined) { |
src/web/pages/bills.ts +1 −8
| @@ -4,9 +4,8 @@ | ||
| 4 | 4 | * or not. Read from the rows the last pass kept in memory; it reads no child. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { claimsBill } from "../../actions/forge_bill.ts"; | |
| 7 | import { billNames } from "../../actions/forge_bill.ts"; | |
| 8 | 8 | import type { User } from "../../core/users.ts"; |
| 9 | import { servedNow } from "../../spawn/clients.ts"; | |
| 10 | 9 | import type { App } from "../../app.ts"; |
| 11 | 10 | import { html, type Html } from "../html.ts"; |
| 12 | 11 | import { row } from "../ui.ts"; |
| @@ -19,12 +18,6 @@ export const billRow = (name: string): Html => | ||
| 19 | 18 | data: { bill: "" }, |
| 20 | 19 | }); |
| 21 | 20 | |
| 22 | /** The forges this person claimed that are finished; their names. */ | |
| 23 | export const billNames = (app: App, user: User): string[] => | |
| 24 | servedNow(app) | |
| 25 | .filter((r) => r.made && claimsBill(app.db, user, r.billTo)) | |
| 26 | .map((r) => r.name); | |
| 27 | ||
| 28 | 21 | /** |
| 29 | 22 | * A block for the settings page: each claimed forge's bill, and for everyone the way to payments. |
| 30 | 23 | */ |
src/web/pages/payments.ts +12 −30
| @@ -4,17 +4,13 @@ | ||
| 4 | 4 | * stored integer minor units shown in its currency; nothing is recomputed or rewritten. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import type { App } from "../../app.ts"; | |
| 8 | import type { User } from "../../core/users.ts"; | |
| 9 | import { listPayments, type Payment } from "../../billing/payments.ts"; | |
| 10 | import { getStored } from "../../billing/store.ts"; | |
| 11 | import { getPlan } from "../../settings/plans.ts"; | |
| 12 | 7 | import type { Ctx } from "../../http/context.ts"; |
| 13 | 8 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 14 | 9 | import { signInFirst } from "../chrome.ts"; |
| 15 | 10 | import { html, type Html } from "../html.ts"; |
| 16 | 11 | import { page } from "../layout.ts"; |
| 17 | import { billNames } from "./bills.ts"; | |
| 12 | import { EXPORT_PATH, EXPORT_WORDS } from "../../core/account_export.ts"; | |
| 13 | import { paymentsFor, PAYMENTS_CAP, type PaymentLine } from "../../actions/forge_bill.ts"; | |
| 18 | 14 | |
| 19 | 15 | const STATUS_WORDS = { paid: "Paid", refunded: "Refunded", failed: "Failed" } as const; |
| 20 | 16 | |
| @@ -32,31 +28,17 @@ export function amountWords(minor: number, currency: string): string { | ||
| 32 | 28 | } |
| 33 | 29 | } |
| 34 | 30 | |
| 35 | interface Line extends Payment { | |
| 36 | /** The forge's plan now: the store keeps no plan per payment. */ | |
| 37 | readonly plan: string; | |
| 38 | } | |
| 39 | ||
| 40 | /** The most rows listed; a person with more is told so. */ | |
| 41 | export const PAYMENTS_CAP = 100; | |
| 42 | ||
| 43 | /** This person's payments, newest first: those of every forge they claimed, once each. */ | |
| 44 | export function paymentsFor(app: App, user: User | undefined): { rows: Line[]; more: boolean } { | |
| 45 | if (user === undefined) return { rows: [], more: false }; | |
| 46 | const seen = new Map<string, Line>(); | |
| 47 | for (const forge of billNames(app, user)) { | |
| 48 | const e = getStored(app.db, forge); | |
| 49 | if (e === undefined || e.customerId === "") continue; | |
| 50 | const plan = getPlan(app.db, e.plan)?.name ?? e.plan; | |
| 51 | for (const p of listPayments(app.db, e.customerId, PAYMENTS_CAP + 1)) if (!seen.has(p.id)) seen.set(p.id, { ...p, plan }); | |
| 52 | } | |
| 53 | const all = [...seen.values()].sort((a, b) => (a.at === b.at ? (a.id < b.id ? 1 : -1) : a.at < b.at ? 1 : -1)); | |
| 54 | return { rows: all.slice(0, PAYMENTS_CAP), more: all.length > PAYMENTS_CAP }; | |
| 55 | } | |
| 56 | ||
| 57 | const line = (p: Line): Html => | |
| 31 | const line = (p: PaymentLine): Html => | |
| 58 | 32 | html`<tr data-payment="${p.status}"><td>${STATUS_WORDS[p.status]}</td><td><time datetime="${p.at}">${p.at.slice(0, 10)}</time></td><td>${amountWords(p.amountMinor, p.currency)}</td><td>${p.plan}</td></tr>`; |
| 59 | 33 | |
| 34 | /** | |
| 35 | * Leaving is possible (#15617): a settings row, beside the payments it also holds, for the one | |
| 36 | * file of everything the forge keeps about this person. Here, not on /settings, so that page's | |
| 37 | * first view stays inside its attention budget. | |
| 38 | */ | |
| 39 | export const exportRow = (): Html => | |
| 40 | html`<dl class="status-rows"><div class="status-row"><dt>Your data</dt><dd><a class="btn" href="${EXPORT_PATH}" download>Download</a> ${EXPORT_WORDS}</dd></div></dl>`; | |
| 41 | ||
| 60 | 42 | // GET /settings/payments |
| 61 | 43 | export function paymentsPage(ctx: Ctx): Response { |
| 62 | 44 | if (ctx.auth.user === undefined) return signInFirst(ctx); |
| @@ -74,7 +56,7 @@ export function paymentsPage(ctx: Ctx): Response { | ||
| 74 | 56 | // A lean shell: a person comes here from Settings and goes back to it, so the bar holds that |
| 75 | 57 | // one link. |
| 76 | 58 | tools: html`<a class="small" href="/settings">Settings</a>`, |
| 77 | body: html`<div class="page-head"><h1>Payments</h1></div><p>What was charged for the forges you claimed, newest first. Plan now is the forge's plan today.</p>${body}`, | |
| 59 | body: html`<div class="page-head"><h1>Payments</h1></div><p>What was charged for the forges you claimed, newest first. Plan now is the forge's plan today.</p>${body}${exportRow()}`, | |
| 78 | 60 | }); |
| 79 | 61 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 80 | 62 | return res; |
test/account-export.test.ts added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | // GET /api/v1/user/export: one JSON file of what the forge holds about a person, no secret in it | |
| 2 | // (#15617). | |
| 3 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp } from "../src/app.ts"; | |
| 8 | import { accountExport, COLUMNS, EXPORT_WORDS, exportFileName } from "../src/core/account_export.ts"; | |
| 9 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 10 | import { serveExport, EXPORT_ACCOUNT_WORDS, type ExportSession } from "../src/core/account_export.ts"; | |
| 11 | import { getUserById } from "../src/core/users.ts"; | |
| 12 | import { addKey, parseAuthorizedKey } from "../src/core/keys.ts"; | |
| 13 | import { createRepo } from "../src/core/repos.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser } from "../src/core/users.ts"; | |
| 17 | import { serve } from "../src/http/server.ts"; | |
| 18 | ||
| 19 | let dir = "", app: ReturnType<typeof createApp>, servers: Awaited<ReturnType<typeof serve>>; | |
| 20 | let cookie = "", sessionToken = "", apiToken = "", aliceId = "", rootId = ""; | |
| 21 | const KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl laptop"; | |
| 22 | ||
| 23 | beforeAll(async () => { | |
| 24 | dir = await mkdtemp(join(process.env.TMPDIR ?? tmpdir(), "account-export-")); | |
| 25 | app = createApp({ dataDir: dir, port: 0 }); | |
| 26 | // Alice and Bob are people; Carol is the admin who must not read Alice's export. | |
| 27 | const [alice, bob, carol] = await Promise.all( | |
| 28 | (["alice", "bob", "carol"] as const).map((username) => | |
| 29 | createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@private.example`, password: "a-good-passphrase", isAdmin: username === "carol" }).then((r) => { | |
| 30 | if (!r.ok) throw new Error(r.error); | |
| 31 | return r.value; | |
| 32 | }), | |
| 33 | ), | |
| 34 | ); | |
| 35 | if (alice === undefined || bob === undefined || carol === undefined) throw new Error("no people"); | |
| 36 | aliceId = alice.id; | |
| 37 | sessionToken = createSession(app.db, alice.id).token; | |
| 38 | cookie = `forge_session=${sessionToken}`; | |
| 39 | const tok = createToken(app.db, alice.id, "deploy", "rw"); | |
| 40 | apiToken = tok.token; | |
| 41 | const parsed = parseAuthorizedKey(KEY); | |
| 42 | if (!parsed.ok) throw new Error(parsed.error); | |
| 43 | const key = addKey(app.db, alice.id, "laptop", parsed.value); | |
| 44 | if (!key.ok) throw new Error(String(key.error)); | |
| 45 | for (const [owner, name, visibility] of [[alice.id, "mine", "private"], [bob.id, "bobs-secret", "private"], [bob.id, "bobs-open", "public"]] as const) { | |
| 46 | const r = await createRepo(app.db, app.reposRoot, { ownerId: owner, name, visibility }); | |
| 47 | if (!r.ok) throw new Error(String(r.error)); | |
| 48 | } | |
| 49 | // Alice writes one org's repository by team and only reads another's. | |
| 50 | for (const [org, team, permission, repo] of [["writers-org", "devs", "write", "shared"], ["readers-org", "viewers", "read", "looked-at"]] as const) { | |
| 51 | const o = createOrg(app.db, org, bob.id); | |
| 52 | if (!o.ok) throw new Error(String(o.error)); | |
| 53 | const t = createTeam(app.db, o.value.id, team, permission); | |
| 54 | if (!t.ok) throw new Error(String(t.error)); | |
| 55 | if (!addTeamMember(app.db, t.value, alice.id)) throw new Error("no member"); | |
| 56 | const r = await createRepo(app.db, app.reposRoot, { ownerId: o.value.id, name: repo, visibility: "private" }); | |
| 57 | if (!r.ok) throw new Error(String(r.error)); | |
| 58 | } | |
| 59 | rootId = carol.id; | |
| 60 | servers = await serve(app); | |
| 61 | }); | |
| 62 | afterAll(async () => { | |
| 63 | servers.stop(); | |
| 64 | app.close(); | |
| 65 | await rm(dir, { recursive: true, force: true }); | |
| 66 | }); | |
| 67 | ||
| 68 | const get = (headers: Record<string, string> = {}) => fetch(`${servers.url}/api/v1/user/export`, { headers }); | |
| 69 | ||
| 70 | test("an anonymous caller gets 401", async () => { | |
| 71 | expect((await get()).status).toBe(401); | |
| 72 | }); | |
| 73 | ||
| 74 | test("the document holds the person's own rows and none of their secrets", async () => { | |
| 75 | const res = await get({ cookie, "sec-fetch-site": "same-origin" }); | |
| 76 | expect(res.status).toBe(200); | |
| 77 | expect(res.headers.get("content-disposition")).toContain("alice-forge-export.json"); | |
| 78 | expect(res.headers.get("cache-control")).toContain("no-store"); | |
| 79 | const text = await res.text(); | |
| 80 | const doc = JSON.parse(text); | |
| 81 | expect(doc.profile.username).toBe("alice"); | |
| 82 | expect(doc.profile.email).toBe("[email protected]"); | |
| 83 | expect(text.split("[email protected]").length - 1).toBe(1); | |
| 84 | expect(doc.emails).toBeUndefined(); | |
| 85 | expect(doc.sshKeys.map((k: { name: string }) => k.name)).toEqual(["laptop"]); | |
| 86 | expect(doc.sshKeys[0].fingerprint).toMatch(/^SHA256:/); | |
| 87 | expect(doc.tokens.map((t: { name: string; scope: string }) => `${t.name}:${t.scope}`)).toEqual(["deploy:rw"]); | |
| 88 | expect(doc.sessions.length).toBe(1); | |
| 89 | expect(doc.repositories.map((r: { name: string; role: string }) => `${r.name}:${r.role}`)).toEqual(["alice/mine:owner", "writers-org/shared:writer"]); | |
| 90 | expect(doc.repositories[0].cloneUrl).toBe(`${servers.url}/alice/mine.git`); | |
| 91 | ||
| 92 | const hash = app.db.query<{ password_hash: string }, [string]>("SELECT password_hash FROM user WHERE id = ?1").get(aliceId)!.password_hash; | |
| 93 | const sessionRow = app.db.query<{ id: string | null; token_hash: string }, [string]>("SELECT id, token_hash FROM session WHERE user_id = ?1").get(aliceId)!; | |
| 94 | const tokenHash = app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM token WHERE user_id = ?1").get(aliceId)!.token_hash; | |
| 95 | for (const secret of [hash, sessionToken, sessionRow.token_hash, apiToken, tokenHash, aliceId, "[email protected]", "bobs-secret", "looked-at", "AAAAC3NzaC1lZDI1NTE5"]) | |
| 96 | expect(text).not.toContain(secret); | |
| 97 | if (sessionRow.id) expect(text).not.toContain(sessionRow.id); | |
| 98 | const keys: string[] = []; | |
| 99 | JSON.stringify(doc, (k, v) => (keys.push(k), v)); | |
| 100 | expect(keys.filter((k) => /password|hash|blob|address|^id$|user_id/i.test(k))).toEqual([]); | |
| 101 | }); | |
| 102 | ||
| 103 | test("a cross-site page cannot read it with the person's cookie", async () => { | |
| 104 | expect((await get({ cookie, "sec-fetch-site": "cross-site" })).status).toBe(403); | |
| 105 | }); | |
| 106 | ||
| 107 | test("a read-write token is not enough", async () => { | |
| 108 | expect((await get({ authorization: `Bearer ${apiToken}` })).status).toBe(403); | |
| 109 | }); | |
| 110 | ||
| 111 | test("every column of the person's tables is named, so a new one fails here until someone decides", () => { | |
| 112 | for (const [table, { exported, withheld }] of Object.entries(COLUMNS)) { | |
| 113 | const actual = app.db.query<{ name: string }, []>(`PRAGMA table_info(${table})`).all().map((c) => c.name).sort(); | |
| 114 | expect({ table, columns: actual }).toEqual({ table, columns: [...exported, ...Object.keys(withheld)].sort() }); | |
| 115 | } | |
| 116 | }); | |
| 117 | ||
| 118 | test("a site admin's file holds only their own repositories, not the forge-wide reach", () => { | |
| 119 | expect(accountExport(app.db, rootId, { origin: "", forges: [], payments: [] })!.repositories).toEqual([]); | |
| 120 | }); | |
| 121 | ||
| 122 | test("forges and payments pass through with only their named fields", () => { | |
| 123 | const payment = { id: "pay_internal", customerId: "cus_secret", amountMinor: 1999, currency: "usd", status: "paid", at: "2026-11-01T00:00:00Z", plan: "Small" }; | |
| 124 | const doc = accountExport(app.db, aliceId, { origin: "", forges: ["alices-forge"], payments: [payment] })!; | |
| 125 | expect(doc.forges).toEqual(["alices-forge"]); | |
| 126 | expect(doc.payments).toEqual([{ amountMinor: 1999, currency: "usd", status: "paid", at: "2026-11-01T00:00:00Z", plan: "Small" }]); | |
| 127 | expect(JSON.stringify(doc)).not.toContain("cus_secret"); | |
| 128 | }); | |
| 129 | ||
| 130 | test("the file name keeps only safe characters of the username", () => { | |
| 131 | expect(exportFileName("alice")).toBe("alice-forge-export.json"); | |
| 132 | expect(exportFileName('a"b/c\\d\r\n é')).toBe("a_b_c_d____-forge-export.json"); | |
| 133 | expect(exportFileName("x.y_z-1")).toBe("x.y_z-1-forge-export.json"); | |
| 134 | }); | |
| 135 | ||
| 136 | test("the payments page offers it as a settings row, in one sentence", async () => { | |
| 137 | const html = await (await fetch(`${servers.url}/settings/payments`, { headers: { cookie } })).text(); | |
| 138 | expect(html).toContain('<dt>Your data</dt><dd><a class="btn" href="/api/v1/user/export" download>Download</a>'); | |
| 139 | expect(html).toContain(EXPORT_WORDS); | |
| 140 | expect(html).not.toContain("data-export"); | |
| 141 | }); | |
| 142 | ||
| 143 | function fakeSession() { | |
| 144 | const said = { out: "", err: "", code: undefined as number | undefined }; | |
| 145 | const session: ExportSession = { | |
| 146 | write: (d) => void (said.out += d), | |
| 147 | writeStderr: (d) => void (said.err += d), | |
| 148 | exit: (c) => void (said.code ??= c), | |
| 149 | }; | |
| 150 | return { session, said }; | |
| 151 | } | |
| 152 | ||
| 153 | test("ssh … export writes the same document to standard output, and refuses an unknown key", () => { | |
| 154 | const { session, said } = fakeSession(); | |
| 155 | serveExport(app, session, getUserById(app.db, aliceId)); | |
| 156 | expect(said.code).toBe(0); | |
| 157 | const doc = JSON.parse(said.out); | |
| 158 | expect(doc.profile.username).toBe("alice"); | |
| 159 | expect(doc.repositories.map((r: { name: string }) => r.name)).toEqual(["alice/mine", "writers-org/shared"]); | |
| 160 | expect(said.out).not.toContain(apiToken); | |
| 161 | const guest = fakeSession(); | |
| 162 | serveExport(app, guest.session, undefined); | |
| 163 | expect(guest.said.code).toBe(1); | |
| 164 | expect(guest.said.out).toBe(""); | |
| 165 | expect(guest.said.err).toContain(EXPORT_ACCOUNT_WORDS); | |
| 166 | }); | |
| 167 | ||
| 168 | test("the terminal's profile screen counts what the export holds, and x says how to take it", async () => { | |
| 169 | const { exportWords, exportHow } = await import("../src/tui/screens/profile.ts"); | |
| 170 | const alice = getUserById(app.db, aliceId)!; | |
| 171 | expect(exportWords(app.db, alice)).toBe("1 key, 1 token, 2 repositories; x to take it"); | |
| 172 | const how = exportHow(app, alice).join("\n"); | |
| 173 | expect(how).toContain(EXPORT_WORDS); | |
| 174 | expect(how.includes("export > alice-forge-export.json") || how.includes("The terminal is off")).toBe(true); | |
| 175 | }); |
This includes owner-or-team-write and nothing else. Add tests that a team writer's repo is listed with role writer, a read-only team's repo is not, and an admin sees no one else's repo. None of these branches is tested; deleting the OR clause would leave the suite green.