diff --git a/.context/decisions/0044-identity-self-service-reaches-the-cli.md b/.context/decisions/0044-identity-self-service-reaches-the-cli.md new file mode 100644 index 000000000..e313a92bc --- /dev/null +++ b/.context/decisions/0044-identity-self-service-reaches-the-cli.md @@ -0,0 +1,287 @@ +# ADR 0044: Identity self-service reaches the CLI, and ORCID does it through the browser + +**Status:** accepted +**Date:** 2026-09-05 +**Owner:** Seyed Yahya Shirazi + +## Context + +Epic #1250 spent four phases making a NEMAR account something a person is +responsible for. ADR 0040 made upload access a per-account grant, ADR 0041 made +a DOI cite the depositor by real name, ADR 0042 made the person ask for the +grant themselves with their own name and handle on the request, and ADR 0043 +made an email address, a GitHub handle and an ORCID iD each back at most one +live account. + +Every one of those raises the price of a wrong identifier, and the CLI could +not fix a single one of them. `PATCH /auth/profile`, `POST +/auth/email/change/{request,verify}` and the ORCID link routes were all +cookie-only, so an account that signed up through the CLI — which is most of +them — had no in-product way to correct its own email, GitHub handle, username, +name, or ORCID link. Phase 4 shipped `nemar auth profile` as a READ, and its +footer said "not editable yet" for username and name and pointed at Settings +for the rest. + +That is the exact shape ADR 0040 spent a year undoing: a refusal that names a +fix the person cannot reach from where they are. And #1054 had been open since +PR #1053: when an account's sign-in email moves, the address that lost it is +told nothing at all, in an architecture where an emailed code IS the password. + +## Decision + +**Every identifier a person can change in Settings, they can change from the +CLI, through the same handler and the same rules. ORCID stays a browser flow, +initiated by an authenticated POST that mints a signed, account-bound intent. +And a completed email change notifies the address that lost the account.** + +### One handler, two credentials + +`PATCH /auth/profile` and both `/auth/email/change/*` routes now resolve the +acting account through `resolveActingAccount` (backend/src/middleware/auth.ts), +which takes either the CLI's bearer token or the dashboard's `nemar_session` +cookie. `POST /auth/orcid/unlink` does the same. There is no CLI copy of any +rule: the GitHub existence check, the username uniqueness rule and its +post-approval lock, the ORCID-canonical name rule, the non-empty city/country +rule, and every typed refusal are reached identically by both credentials. + +Two asymmetries are deliberate, and both follow from what a credential IS: + +- **The Origin allow-list applies to the cookie path only.** A cookie rides + along with any cross-site request a browser can be tricked into making; a + bearer token does not. Demanding an `Origin` header a terminal has no reason + to send would refuse every CLI. +- **The routes keep `webSessionMiddleware` rather than mounting + `authMiddleware`.** `authMiddleware`'s cookie path refuses a `pending` + account (ADR 0040), and `webSessionMiddleware` admits one. An account that + typed its address wrong at sign-up is `pending` BECAUSE the address is wrong, + and the email change is the one thing it must still be able to do. The token + path uses the standard token rule, which admits only an active account; a + `pending` CLI account has no token to present anyway, since the key is issued + after verification. + +The bearer lookup itself was EXTRACTED, not copied: `resolveBearerUser` is the +same SELECT, the same revoked/expired filter, the same active-account check and +the same `last_used_at` touch `authMiddleware` has always run. A second copy of +that query is how a route ends up honouring a token the middleware would have +refused. + +### ORCID: a browser flow with the account inside the signature + +There is no version of this that types an ORCID password into a terminal, and +no way to render ORCID's consent screen there. So `POST /auth/orcid/cli-start` +mints the intent and returns a URL to open. It takes a bearer token or, under +the same same-origin gate `POST /orcid/start` applies, a session cookie — the +gate is what keeps a cookie caller's intent from being mintable by a page +somewhere else. + +The browser that opens it holds **no NEMAR session** — which is precisely what +the callback used to resolve the user from. So the account travels inside the +state, and **the state is HMAC-signed with `ENCRYPTION_KEY`**, the same +construction as the pending-signup cookie (#832). The callback tries the signed +shape first and falls back to the website's plain `decodeState`. + +**A state minted for user A can never link to user B.** The id is covered by +the signature, and the plain web state — the only shape a forged cookie can +produce — carries no id at all. + +**ADR 0022 survives.** Its rule is that relink intent is never minted on a GET. +It still is not: `cli-start` is an authenticated POST, and a bearer token is a +credential no browser sends on its own, so no link click can arm an identity +swap. The handoff GET mints nothing — it verifies a signature the POST made and +shows it to a person. That is transport, not creation. + +#### Three bounds on a bearer capability + +A signed intent is a bearer capability for the ten minutes it lives, and the +signature alone bounds only WHO it acts for, not who may present it. Left +there, someone could mint an intent for their own account, send the URL to a +victim, and have the victim's iD — the identifier a DOI cites (ADR 0041), and +one ADR 0043 then refuses them on their own account — attached to a stranger's +row, having seen nothing but the ORCID page they expected. That is the standard +OAuth account-linking CSRF, and its consequences here are permanent. Three +things bound it (PR #1269 review): + +1. **The person is shown whose account it is.** `GET /auth/orcid/cli-handoff` + renders one sentence naming the target account — username and masked email, + read from the database by id — and a form they must submit. No script, and + deliberately no auto-submit: a page that submits itself is the redirect it + replaced, with extra steps. `POST /auth/orcid/cli-handoff/continue` re-runs + every check and is same-origin gated, so nothing can post it on the + person's behalf without them seeing the page. +2. **A disagreement is refused, never resolved.** When the browser carries a + session for a DIFFERENT account than the intent names, both handoff steps + and the callback answer `orcid_intent_account_mismatch` and link nothing. + An earlier draft let the signed intent silently outrank the session, which + is correct about whose intent it is and wrong about what to do when the + page says one account and the browser says another. A browser with no + session is the ordinary CLI case and proceeds; a session for the SAME + account proceeds too. +3. **An intent is single-use.** `cli-start` records a nonce in + `orcid_link_intents` (migration 0078) and the callback consumes it before + writing anything, so a URL out of browser history, a referrer or a log is + refused (`orcid_intent_used`) rather than replayed. One browser completion + per intent, whatever its outcome; a failed link means running the CLI + command again, which is what the CLI already tells people to do. The table + is pruned opportunistically at mint time and holds nothing older than one + TTL window. + +What is left after those three is a person who reads a page naming an account +that is not theirs and presses the button anyway, inside ten minutes, on a +single-use link. That is the same residual an emailed confirmation link +carries, and it is the price of ORCID being completable in a browser that +holds no session of ours — the alternative, requiring a web session, is +exactly the dead end this ADR exists to close. + +### The old address is told + +`POST /auth/email/change/verify` mails the PREVIOUS address a notice naming the +new one, MASKED (`a******@lab.org`). Best-effort by construction: it runs after +the write, its failure is logged and reported as `old_address_notified: false`, +and it never fails a change that has already landed. Off production it goes +through `sendEmail`'s existing fence, so a non-allow-listed recipient is +refused before the Resend call — the old address is the one recipient in this +flow that the caller did not choose, and on the dev mirror it is a real +person's. + +Masked and not full: whoever reads the old inbox may no longer be the account +owner, which is the whole case this mail exists for. What they need is that the +address changed and where to report it, not what it changed to. + +## Consequences + +- **`nemar auth profile` grows subcommands** — `set-email` / `verify-email`, + `set-github`, `set-username`, `set-name`, `set-location`, `orcid + link|relink|unlink` — and its footer names a command per identifier instead + of the "not editable yet" line ADR 0043 had to ship. Every subcommand still + says the change can also be made in Settings: the CLI is the second surface, + not a replacement. +- **A refusal has to be readable in a terminal.** These routes answer with a + machine code in `error` and the sentence in `message`, which is right for the + website and useless in a shell. `PROFILE_EDIT_ERROR_CODES` + (shared/contract/user.ts) and `IDENTITY_CONFLICT_CODES` + (shared/contract/identity.ts) declare which strings are codes, and + lib/api/client.ts prefers `message` for them — the same mechanism ADR 0042 + added for the upload-access vocabulary. A code the backend adds and the + contract does not know about prints as a bare token, so **every refusal is + raised through a typed helper and the compiler catches it instead**: + `normalizeProfilePatch`'s codes by `_profileErrorsAreDeclared`, the ten + route-level ones (`username_taken`, `username_locked`, + `name_is_orcid_canonical`, `account_revoked`, `github_unavailable`, + `same_email`, `code_expired`, `code_incorrect`, `orcid_already_have`, + `orcid_unavailable`) by `profileRefusal(code, message)`, whose parameter is + the contract's union — they were bare string literals until the #1269 review + pointed out that the claim was true of a third of them. The identity + refusals (`email_in_use`, `github_in_use`, …) go through `identityRefusal`, + which is typed the same way. No route-level refusal in this vocabulary is + still a literal. +- **`same_email` gained a `message`.** It shipped as a bare code, which the + website could switch on and a terminal could only print as the word + `same_email`. +- **The CLI remembers the pending address** (`pendingEmailChange` in the account + config), so `verify-email ` takes a code and nothing else. Stale is + harmless: the code is bound to both address and account and simply will not + verify. `--email` covers finishing a change started on another machine. +- **The link flow polls.** Nothing pushes the CLI when the browser finishes, so + `orcid link` re-reads `/users/me` every three seconds until the iD appears or + the timeout runs out, and a timeout says "check with `nemar auth profile`" + rather than claiming a failure it cannot see. A relink is judged against the + PREVIOUS iD, since `orcid` stays non-null throughout one. Two poll failures + end the wait early rather than burning it: a 401 (the key was revoked or + regenerated mid-flow) and three consecutive network errors, each with its own + sentence, because "gave up waiting" would send the person to look at their + browser instead of at their credentials. +- **Opening a browser is a convenience, never the mechanism.** The URL is + printed first, always; `NEMAR_NO_BROWSER=1` and `--no-open` suppress the + spawn. The CLI says it is TRYING to open one, never that it did: `spawn` + returns before the child can fail, so a missing `xdg-open` is an async error + that reaches the debug log, not the terminal. A headless or remote machine is + a copy-and-paste, not a dead end. +- **A username change re-keys the local config.** The accounts map is keyed by + username, so `set-username` moves the key as well as the field — otherwise + `nemar auth switch ` cannot find the account it just renamed. It + declines to move onto a key another stored account holds. +- **`/auth/orcid/cli-start`, `/auth/orcid/cli-handoff` (with its `/continue` + step) and `/auth/orcid/unlink` join the strict auth rate bucket** + (10/min/IP): all three are bearer-reachable now, and the token bucket is + 1000/min. The rest of `/auth/orcid/*` deliberately does not: the callback is + a browser landing and moving it would change the web flow's bucket. +- **A change that lands is never reported as a failure.** The local config + writes after an email change happen in their own guarded step, because the + server has already moved the address and spent the code by then; a `conf` + failure prints "the change is live on the server; your local config could + not be updated" rather than "could not confirm the new address". +- **Two surfaces can now race on one field.** Both write through the same + handler and the same constraints, so the loser gets a typed refusal rather + than a corrupt row, but "I changed it in Settings and the terminal still + shows the old value" is a new support question. Every subcommand re-reads + `/users/me` after a successful change to keep the local cache honest. + +## Alternatives considered + +- **Mount `authMiddleware` on the existing routes.** The obvious reading of + "accept a bearer token too", and it silently narrows the cookie path: a + `pending` account would lose the email change, which is the one flow it needs + most. `resolveActingAccount` keeps each credential's own acceptance rule. +- **A parallel set of `/cli/...` routes.** A second copy of the username lock, + the ORCID name rule and the GitHub check, drifting from the website's copy at + the first change to either. The point of this phase is that there is one rule + per field, not one per surface. +- **Put the signed state in ORCID's `state` parameter and skip the handoff.** + Simpler, and it drops both the browser binding and the only place a person + could be shown whose account they are about to link. The handoff costs two + routes and is where the whole defence lives. +- **Keep the handoff a redirect and rely on the signature alone.** What the + first draft did. It makes the flow one hop shorter and leaves the victim of a + handed-over link with nothing to notice: every page they see is one they + expected. The interstitial is the difference between "unforgeable" and + "unusable against someone else". +- **Let the signed intent outrank a session for another account.** Also the + first draft, and defensible on the narrow question of whose intent it is. It + answers the wrong question: when the page names one account and the browser + is signed into another, the disagreement is the signal, and resolving it + silently is how this class of attack stays invisible. +- **Make the intent single-use without a table** (a signed counter, a cookie). + Nothing the client holds can prove it has not been replayed; only a server + row can. It is four columns that live for ten minutes. +- **Carry the account id in the plain state cookie.** The web state cookie is + base64 JSON with no signature, so this would let anyone write a cookie naming + any user id and link an iD to a stranger's account. The signature is the + whole mechanism. +- **A device-code flow (`gh auth login`-style) for ORCID.** Correct in the + abstract and a much larger build: a code table, a polling endpoint, an + expiry sweep, and a second consent surface — to replace a URL the person + opens anyway. Revisit if the printed-link flow proves confusing in practice. +- **Let the CLI complete ORCID itself with a loopback redirect URI.** Requires + registering a second ORCID redirect URI, opening a local port on a + researcher's machine, and a second callback implementation. The registered + redirect stays one, and the browser stays the only place ORCID consent + happens. +- **Tell the old address nothing, as before.** #911 marked it optional; PR + #1053's review argued it should be a real P2 and was right. With passwordless + sign-in the old inbox is the only channel that reaches a legitimate owner + whose address was moved with a stolen session or key, and an audit row is + visible to nobody but an admin. +- **Put the full new address in the notice.** It reads better and it hands the + account's new sign-in address to whoever now reads an inbox the account left. + +## Receipts + +- Issue #1266 (phase 7) and #1054 (the old-address notice), epic #1250. +- Migration `backend/src/db/migrations/0078_orcid_link_intents.sql`. +- Routes `routes/auth-web.ts` (profile PATCH, email change), + `routes/auth-orcid.ts` (`cli-start`, `cli-handoff`, `cli-handoff/continue`, + callback, unlink), + middleware `middleware/auth.ts` (`resolveBearerUser`, + `resolveActingAccount`), service `services/orcid-auth.ts` + (`signCliState` / `verifyCliState`), template + `services/email.ts#sendEmailChangedNoticeEmail`. +- CLI `src/commands/auth.ts` (the `profile` subcommands), + `src/lib/api/auth.ts`, `src/lib/browser.ts`. +- Contract `shared/contract/user.ts` (`profileEditErrorCodeSchema`), + `shared/contract/identity.ts` (`IDENTITY_CONFLICT_CODES`). +- ADR 0022 (relink intent is never minted on a GET) — narrowed to say where + intent is CREATED, not how it is carried. +- ADR 0040, 0041, 0042, 0043 — the four decisions that made a wrong identifier + expensive enough to be worth fixing from wherever the person is. +- ADR 0037 (make versus take) — why `src/lib/browser.ts` is nine lines of + platform table rather than a dependency. diff --git a/.context/decisions/README.md b/.context/decisions/README.md index daa559cba..5e9fd57e8 100644 --- a/.context/decisions/README.md +++ b/.context/decisions/README.md @@ -82,6 +82,7 @@ invisible one — which is why it is checked rather than trusted. - [ADR 0041](0041-dois-cite-the-uploader-by-real-name-or-not-at-all.md) - DOIs cite the uploader by real name, or not at all - [ADR 0042](0042-upload-access-is-requested-once-by-the-person-who-wants-it.md) - Upload access is requested once, by the person who wants it - [ADR 0043](0043-one-person-one-account.md) - One person, one account: ORCID, email and GitHub each back at most one live account +- [ADR 0044](0044-identity-self-service-reaches-the-cli.md) - Identity self-service reaches the CLI, and ORCID does it through the browser ## Backfill note (2026-07-31) diff --git a/AGENTS.md b/AGENTS.md index 5e7246f44..2943f618f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,7 +46,9 @@ Load-bearing ones to know before touching the relevant area: 0034 (`datasets` stays one table under an enforced column budget; derive, don't store), 0040 (`verified` is the base tier; admin approval is the only writer of upload access), 0042 (upload access is requested once, by the person who wants it), -0043 (one person, one account: an ORCID iD, an email or a GitHub handle backs at most one live account). +0043 (one person, one account: an ORCID iD, an email or a GitHub handle backs at most one live account), +0044 (identity self-service reaches the CLI; ORCID links through a browser handoff whose +signed state names the account). --- @@ -533,7 +535,7 @@ and what is historical. The entries worth knowing by name: | Group | Covers | |---|---| -| `nemar auth` | login, signup, status/whoami, profile, request-upload-access, switch, logout, verification, SSH setup, key retrieval and regeneration | +| `nemar auth` | login, signup, status/whoami, profile (plus `set-email`/`verify-email`, `set-github`, `set-username`, `set-name`, `set-location`, `orcid link\|relink\|unlink` — ADR 0044), request-upload-access, switch, logout, verification, SSH setup, key retrieval and regeneration | | `nemar dataset` | validate, upload, download, status (alias: view), list, search, release, update, clone, get, commit, push, drop, ci, manifest | | `nemar dataset publish` | request, status, resend | | `nemar dataset` (access) | request-access, access, invite, collaborators | diff --git a/backend/src/db/migrations/0078_orcid_link_intents.sql b/backend/src/db/migrations/0078_orcid_link_intents.sql new file mode 100644 index 000000000..5965d3311 --- /dev/null +++ b/backend/src/db/migrations/0078_orcid_link_intents.sql @@ -0,0 +1,52 @@ +-- Single-use ORCID link intents for the CLI handoff +-- (ADR 0044, epic #1250 phase #1266; PR #1269 review item A3). +-- +-- WHAT THIS CLOSES. `POST /auth/orcid/cli-start` mints a signed, short-lived +-- intent naming the account it was created for, and the browser that finishes +-- the ORCID flow carries no NEMAR session -- that is the whole point, since it +-- was opened from a terminal. The signature makes the intent unforgeable, but +-- a signature alone does not make it UNREPEATABLE: anyone holding the URL +-- (browser history, a referrer, a shoulder) could complete it again inside the +-- ten-minute window, and the consequence is permanent. ADR 0041 makes a DOI +-- cite the account the iD is attached to, and ADR 0043 then refuses the +-- rightful owner their own iD because it is "already on a live account". +-- +-- So the intent gets a server-side nonce and is CONSUMED at the callback. +-- One browser completion per intent, whatever its outcome; a replay finds +-- `consumed_at` already set and is refused before anything is linked. +-- +-- WHY A TABLE. `auth_codes` is the only comparable short-lived store and it is +-- keyed by email address for a 6-digit secret with an attempt counter -- none +-- of which fits a 256-bit nonce for an account-scoped OAuth intent. Reusing it +-- would mean an `email` column carrying something that is not an email and a +-- `code_hash` carrying something nobody types. This table is four columns and +-- holds nothing for longer than ten minutes. +-- +-- LIFECYCLE. Rows are pruned opportunistically at mint time (every +-- `cli-start` deletes what has expired), so the table needs no cron and +-- cannot grow past the intents minted in one ten-minute window. Nothing here +-- is a secret: the nonce is meaningless without the HMAC-signed state that +-- carries it, and that signature is keyed with ENCRYPTION_KEY. + +CREATE TABLE IF NOT EXISTS orcid_link_intents ( + -- 256 bits of URL-safe randomness, generated by `generateCsrf()`. Primary + -- key rather than a surrogate id: the nonce IS the identity of the intent, + -- and a UNIQUE constraint on it is what makes "consume once" enforceable. + nonce TEXT PRIMARY KEY, + -- The account the intent was minted FOR. Also inside the signed state; kept + -- here so the interstitial can name the account without trusting anything + -- the browser sent, and so a deleted account's intents go with it. + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + -- 'link' or 'relink'. Never 'login': a CLI flow always acts on an account + -- that already exists. + mode TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL, + -- Set by the callback the first time the intent completes. A second + -- completion finds it non-NULL and is refused. + consumed_at TEXT +); + +-- Drives the opportunistic prune and the "is this still usable" read. +CREATE INDEX IF NOT EXISTS idx_orcid_link_intents_expires + ON orcid_link_intents(expires_at); diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index d92cdf910..ae2d54610 100644 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -18,7 +18,12 @@ import { isActiveAccountStatus, } from "../services/account-tier"; import { hashApiKey } from "../services/token"; -import { COOKIE_NAME, hashCookieId, parseCookieHeader } from "../services/web-session"; +import { + COOKIE_NAME, + hashCookieId, + isAllowedOrigin, + parseCookieHeader, +} from "../services/web-session"; import { type AuthUser, type Bindings, @@ -124,41 +129,54 @@ async function resolveCookieUser(c: AuthContext): Promise { } /** - * Middleware to require authentication via either a bearer API token or - * the web-dashboard `nemar_session` cookie (#572). + * What an `Authorization` header resolved to. * - * Resolution order: - * 1. `Authorization: Bearer ` — CLI path, unchanged. - * 2. `Cookie: nemar_session=…` — dashboard path, added for #572. - * 3. Neither resolves -> 401 with the same shape we returned before - * cookies existed. + * `absent` is "no header at all" and is the only outcome a caller may fall + * through on: every other failure is a deliberate answer (a malformed header, + * a dead key, an inactive account) that must reach the client verbatim rather + * than being retried as anonymous. + */ +export type BearerAuthResult = + | { kind: "absent" } + | { kind: "refused"; response: Response } + | { kind: "user"; user: AuthUser }; + +/** + * Resolve `Authorization: Bearer ` to a full AuthUser. * - * Sets `c.var.user` with the resolved AuthUser regardless of which path - * matched, so route handlers don't need to branch. + * Extracted from `authMiddleware` for #1266 so the CLI-facing self-service + * routes in auth-web.ts / auth-orcid.ts accept a token through the SAME + * lookup the rest of the API uses — same key hashing, same revoked/expired + * filter, same active-account rule, same `last_used_at` touch. A second copy + * of this SELECT is how a route ends up honouring a token the middleware + * would have refused. */ -export async function authMiddleware(c: AuthContext, next: Next) { +export async function resolveBearerUser(c: AuthContext): Promise { const authHeader = c.req.header("Authorization"); + if (!authHeader) return { kind: "absent" }; - // ------------------------------------------------------------------- - // Path 1: Authorization: Bearer - // ------------------------------------------------------------------- - if (authHeader) { - if (!authHeader.startsWith("Bearer ")) { - return c.json({ error: "Invalid Authorization header format. Use: Bearer " }, 401); - } + if (!authHeader.startsWith("Bearer ")) { + return { + kind: "refused", + response: c.json( + { error: "Invalid Authorization header format. Use: Bearer " }, + 401, + ), + }; + } - const apiKey = authHeader.substring(7); + const apiKey = authHeader.substring(7); - if (!apiKey || apiKey.length < 32) { - return c.json({ error: "Invalid API key format" }, 401); - } + if (!apiKey || apiKey.length < 32) { + return { kind: "refused", response: c.json({ error: "Invalid API key format" }, 401) }; + } - // Hash the key for lookup - const hashedKey = await hashApiKey(apiKey); + // Hash the key for lookup + const hashedKey = await hashApiKey(apiKey); - // Find token and associated user - const result = await c.env.DB.prepare( - ` + // Find token and associated user + const result = await c.env.DB.prepare( + ` SELECT u.id, u.username, @@ -175,54 +193,79 @@ export async function authMiddleware(c: AuthContext, next: Next) { AND (t.expires_at IS NULL OR t.expires_at > datetime('now')) AND u.deleted_at IS NULL `, - ) - .bind(hashedKey) - .first<{ - id: number; - username: string; - email: string; - github_username: string; - role: string | null; - orcid: string | null; - status: string; - token_id: number; - }>(); + ) + .bind(hashedKey) + .first<{ + id: number; + username: string; + email: string; + github_username: string; + role: string | null; + orcid: string | null; + status: string; + token_id: number; + }>(); - if (!result) { - return c.json({ error: "Invalid or expired API key" }, 401); - } + if (!result) { + return { kind: "refused", response: c.json({ error: "Invalid or expired API key" }, 401) }; + } - // ADR 0040 phase 2: `verified` is the base tier and holds a usable API - // key, so the token is accepted here and the upload gate — not this - // middleware — is what a base-tier account runs into. - if (!isActiveAccountStatus(result.status)) { - return c.json(inactiveAccountBody(result.status), 403); - } + // ADR 0040 phase 2: `verified` is the base tier and holds a usable API + // key, so the token is accepted here and the upload gate — not this + // middleware — is what a base-tier account runs into. + if (!isActiveAccountStatus(result.status)) { + return { kind: "refused", response: c.json(inactiveAccountBody(result.status), 403) }; + } - // Validate role from DB - const role = parseRole(result.role, result.username); - if (role === null) { - return c.json({ error: "Account configuration error. Contact an administrator." }, 500); - } + // Validate role from DB + const role = parseRole(result.role, result.username); + if (role === null) { + return { + kind: "refused", + response: c.json({ error: "Account configuration error. Contact an administrator." }, 500), + }; + } - // Update last_used_at for the token - await c.env.DB.prepare("UPDATE tokens SET last_used_at = datetime('now') WHERE id = ?") - .bind(result.token_id) - .run(); + // Update last_used_at for the token + await c.env.DB.prepare("UPDATE tokens SET last_used_at = datetime('now') WHERE id = ?") + .bind(result.token_id) + .run(); - // Set user in context - const user: AuthUser = { + return { + kind: "user", + user: { id: result.id, username: result.username, email: result.email, github_username: result.github_username, role, orcid: result.orcid || undefined, - }; + }, + }; +} - c.set("user", user); +/** + * Middleware to require authentication via either a bearer API token or + * the web-dashboard `nemar_session` cookie (#572). + * + * Resolution order: + * 1. `Authorization: Bearer ` — CLI path, unchanged. + * 2. `Cookie: nemar_session=…` — dashboard path, added for #572. + * 3. Neither resolves -> 401 with the same shape we returned before + * cookies existed. + * + * Sets `c.var.user` with the resolved AuthUser regardless of which path + * matched, so route handlers don't need to branch. + */ +export async function authMiddleware(c: AuthContext, next: Next) { + // ------------------------------------------------------------------- + // Path 1: Authorization: Bearer + // ------------------------------------------------------------------- + const bearer = await resolveBearerUser(c); + if (bearer.kind === "refused") return bearer.response; + if (bearer.kind === "user") { + c.set("user", bearer.user); c.set("authMethod", "token"); - await next(); return; } @@ -252,6 +295,87 @@ export async function authMiddleware(c: AuthContext, next: Next) { return c.json({ error: "Missing Authorization header" }, 401); } +/** + * The account acting on a self-service route, whichever credential it used. + * + * Only the three fields those routes actually need off the credential: the id + * every write is scoped by, the current address the email change compares + * against, and the current GitHub handle `githubHandleChanged` compares + * against. Everything else is re-read from `users` inside the handler, which + * is what lets ONE handler serve both credentials without caring which one + * arrived (#1266). + */ +export interface ActingAccount { + id: number; + email: string; + github_username: string | null; + via: "cookie" | "token"; +} + +export type ActingAccountResolution = + | { ok: true; actor: ActingAccount } + | { ok: false; response: Response }; + +/** + * Resolve the account acting on a route that accepts EITHER the CLI's bearer + * token or the dashboard's `nemar_session` cookie (#1266, ADR 0044). + * + * Deliberately NOT `authMiddleware` mounted on these routes, for one reason + * that only shows up on the cookie half: `authMiddleware`'s cookie path + * refuses a `pending` account (403, ADR 0040), while `webSessionMiddleware` + * admits it. An account that typed its address wrong at sign-up is `pending` + * BECAUSE the address is wrong, and the email change is the one thing it must + * still be able to do. So the cookie path keeps `webSessionMiddleware`'s + * acceptance byte for byte, and the token path uses the shared + * `resolveBearerUser` above — which, being the standard token rule, admits + * only an active account. A `pending` CLI account has no token to present + * anyway: the key is issued after verification. + * + * The Origin allow-list applies to the COOKIE path only, and that is the whole + * point of it: a cookie rides along with any cross-site request the browser is + * tricked into making, and a bearer token does not. Requiring an Origin header + * a CLI has no reason to send would refuse every terminal. + * + * Bearer wins when both are present, matching `authMiddleware`. + * + * Requires `webSessionMiddleware` to have run for the cookie half. + */ +export async function resolveActingAccount(c: AuthContext): Promise { + const bearer = await resolveBearerUser(c); + if (bearer.kind === "refused") return { ok: false, response: bearer.response }; + if (bearer.kind === "user") { + c.set("user", bearer.user); + c.set("authMethod", "token"); + return { + ok: true, + actor: { + id: bearer.user.id, + email: bearer.user.email, + github_username: bearer.user.github_username || null, + via: "token", + }, + }; + } + + if (!isAllowedOrigin(c.req.header("Origin"))) { + return { ok: false, response: c.json({ error: "Origin not allowed" }, 403) }; + } + const webUser = c.var.webUser; + if (!webUser) { + return { ok: false, response: c.json({ error: "Authentication required" }, 401) }; + } + c.set("authMethod", "cookie"); + return { + ok: true, + actor: { + id: webUser.id, + email: webUser.email, + github_username: webUser.github_username, + via: "cookie", + }, + }; +} + /** * Middleware to require admin role * diff --git a/backend/src/middleware/rateLimit.ts b/backend/src/middleware/rateLimit.ts index 84fd54b85..3089932ab 100644 --- a/backend/src/middleware/rateLimit.ts +++ b/backend/src/middleware/rateLimit.ts @@ -112,6 +112,18 @@ const AUTH_PATHS = [ // entry as a prefix, so "/auth/email/verify" also matches // "/auth/email/verify/request". "/auth/email/verify", + // CLI ORCID surface (#1266, ADR 0044). `cli-start` mints an identity-link + // intent, `cli-handoff` (and its /continue confirm step, covered by the + // prefix match) is the only thing that can turn a leaked one into an ORCID + // redirect, and `unlink` drops an iD outright -- all three are now reachable + // with a bearer token, so without these entries they would sit in the + // 1000/min token bucket instead of the 10/min floor every other identity + // mutation has. A person links or unlinks an iD once. + // The rest of /auth/orcid/* is deliberately NOT here: the callback is a + // browser landing, and moving it would change the web flow's bucket. + "/auth/orcid/cli-start", + "/auth/orcid/cli-handoff", + "/auth/orcid/unlink", // NOT an /auth path, and deliberately in this list anyway (ADR 0042, #1253): // POST /users/me/upload-access/request spends a live GitHub API call on the // shared installation token for every attempt, and a refused one writes diff --git a/backend/src/routes/auth-orcid.ts b/backend/src/routes/auth-orcid.ts index 3eee93ea5..9a3c3f981 100644 --- a/backend/src/routes/auth-orcid.ts +++ b/backend/src/routes/auth-orcid.ts @@ -2,11 +2,29 @@ * ORCID SSO routes (#832), mounted under the same `/auth` prefix as the * passwordless flow in auth-web.ts. * - * GET /auth/orcid/start - set state cookie, 302 to ORCID authorize - * GET /auth/orcid/callback - verify state, exchange code, then either - * sign in / link / hand off to email collection - * POST /auth/orcid/finalize - finish a brand-new ORCID signup with an email - * POST /auth/orcid/unlink - (authed) remove the ORCID link + * GET /auth/orcid/start - set state cookie, 302 to ORCID authorize + * POST /auth/orcid/cli-start - (token or cookie) mint a signed + * link/relink intent + * GET /auth/orcid/cli-handoff - name the account, ask the person + * POST /auth/orcid/cli-handoff/continue - their answer: cookie, then ORCID + * GET /auth/orcid/callback - verify state, exchange code, then + * sign in / link / collect an email + * POST /auth/orcid/finalize - finish a new ORCID signup + * POST /auth/orcid/unlink - (token or cookie) remove the link + * + * CLI parity (#1266, ADR 0044): ORCID stays a browser flow, because a consent + * screen cannot be shown in a terminal. What the CLI gets is `cli-start`, + * which mints the SAME intent the website's POST /orcid/start mints — signed + * this time, and carrying the account id, because the browser that finishes + * the flow holds no NEMAR session for the callback to read. + * + * Three things bound what that signed intent can do, because it is a bearer + * capability for its ten minutes (PR #1269 review): the handoff SHOWS the + * person which account it names before they go to ORCID, a session for a + * DIFFERENT account is refused rather than overridden at both the handoff and + * the callback (`orcid_intent_account_mismatch`), and the intent is single-use + * -- a row in `orcid_link_intents` (migration 0078) the callback consumes. + * Unlink needs no browser at all and takes a bearer token directly. * * Linking is initiated via `GET /auth/orcid/start?mode=link` and completed in * the same callback (the callback links to whichever user the session cookie @@ -40,10 +58,14 @@ import { zValidator } from "@hono/zod-validator"; import { Hono } from "hono"; +import type { Context } from "hono"; import { z } from "zod"; import { auditLogStatement } from "../db/audit-log"; import { timingSafeEqual } from "../lib/constant-time"; +import { escapeHtml } from "../lib/escape"; +import { authMiddleware, resolveActingAccount } from "../middleware/auth"; import { webSessionMiddleware } from "../middleware/webSession"; +import { maskEmail } from "../services/auth-code"; import { issueEmailVerificationCode } from "../services/email-verification"; import { emailFieldSchema, @@ -56,7 +78,10 @@ import { normalizeOrcid, } from "../services/identity"; import { + CLI_STATE_TTL_MS, + type CliOauthState, type OauthMode, + type OauthState, PENDING_COOKIE_NAME, RELINK_DELETE_IDENTITY_SQL, RELINK_INSERT_IDENTITY_SQL, @@ -75,9 +100,12 @@ import { orcidPubBase, relinkParams, safeNextPath, + signCliState, signPending, + verifyCliState, verifyPending, } from "../services/orcid-auth"; +import { profileRefusal } from "../services/profile"; import { buildSessionCookie, isAllowedOrigin, @@ -351,6 +379,374 @@ authOrcidRoutes.post("/orcid/start", webSessionMiddleware, (c) => { return startOrcidFlow(c, mode, safeNextPath(url.searchParams.get("next"))); }); +/** Where the browser lands once a CLI-initiated link finishes. */ +const CLI_LINK_LANDING = "/settings"; + +/** One wording for the two ways this deployment can lack ORCID (no client + * credentials, no signing key). Neither is anything the caller can act on. */ +const ORCID_UNAVAILABLE_MESSAGE = "ORCID linking is unavailable"; + +const cliStartSchema = z.object({ + mode: z.enum(["link", "relink"]).optional(), +}); + +/** + * The account a CLI intent names, as the interstitial shows it. + * + * Read from the DATABASE by id, never from anything the browser sent: the + * point of the page is to let a person recognise (or fail to recognise) the + * account before they hand ORCID their consent. + */ +interface IntentAccount { + id: number; + username: string | null; + email: string; +} + +/** + * Load the account for a CLI intent AND check the nonce is still usable + * (migration 0078). Null when the intent is spent, expired, or names an + * account that is gone or revoked. + * + * Deliberately does NOT consume: the interstitial and its confirm step both + * need to know the intent is live, and burning it before the browser has even + * reached ORCID would make a mistyped password a dead end. + */ +async function loadUsableIntent( + env: Bindings, + state: CliOauthState, +): Promise { + const row = await env.DB.prepare( + `SELECT u.id, u.username, u.email + FROM orcid_link_intents i + JOIN users u ON u.id = i.user_id + WHERE i.nonce = ? + AND i.user_id = ? + AND i.consumed_at IS NULL + AND i.expires_at > datetime('now') + AND u.deleted_at IS NULL + AND u.status != 'revoked' + LIMIT 1`, + ) + .bind(state.nonce, state.userId) + .first(); + return row ?? null; +} + +/** + * Consume a CLI intent, returning false when somebody already did. + * + * The conditional UPDATE is the mutual-exclusion gate: two completions of the + * same URL race here and exactly one sees `changes = 1`. Called once the + * callback knows which account it is acting for and before it writes anything, + * so a refusal downstream still burns the intent -- one browser completion per + * intent, whatever its outcome. The cost is that a failed link means re-running + * the CLI command, which is what the CLI already tells people to do. + */ +async function consumeIntent(env: Bindings, state: CliOauthState): Promise { + const res = await env.DB.prepare( + `UPDATE orcid_link_intents SET consumed_at = datetime('now') + WHERE nonce = ? AND user_id = ? AND consumed_at IS NULL + AND expires_at > datetime('now')`, + ) + .bind(state.nonce, state.userId) + .run(); + return (res.meta?.changes ?? 0) > 0; +} + +/** + * Whether a signed-in browser is signed in as somebody OTHER than the account + * the intent names. + * + * The rule this expresses is "refuse, never override" (PR #1269 review). An + * earlier draft let the signed intent silently win over the session, which is + * correct about WHOSE intent it is and wrong about what to do with the + * disagreement: the person is looking at a page that says one account while + * their browser says another, and guessing between them is how an + * account-linking CSRF stays invisible. A browser with no session is the + * ordinary CLI case and proceeds. + */ +function sessionDisagreesWithIntent( + webUser: { id: number } | undefined, + state: CliOauthState, +): boolean { + return webUser !== undefined && webUser.id !== state.userId; +} + +const INTENT_MISMATCH_MESSAGE = + "This link was created for another NEMAR account; sign out or open it in a browser where you are not signed in."; + +/** Minimal, styleless HTML shell. No script of any kind. */ +function intentPage(title: string, bodyHtml: string, status: 200 | 403 | 410): Response { + return new Response( + ` + + + + + ${escapeHtml(title)} + + +${bodyHtml} + +`, + { + status, + headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }, + }, + ); +} + +/** The typed refusal page both handoff steps and the callback speak. */ +function intentMismatchPage(): Response { + return intentPage( + "Wrong NEMAR account", + `

This link is for a different account

+

${escapeHtml(INTENT_MISMATCH_MESSAGE)}

+

Nothing has been changed. (orcid_intent_account_mismatch)

`, + 403, + ); +} + +/** + * Mint an ORCID link intent for the CALLER'S account and hand back a URL to + * open in a browser (#1266, ADR 0044). + * + * ORCID stays a browser flow — there is no way to show a consent screen in a + * terminal, and no version of this should ask for an ORCID password. What the + * CLI gets is the intent, signed and short-lived, in a URL the person opens + * themselves; the link is then completed by the ordinary callback. + * + * ADR 0022 survives intact: relink intent is minted ONLY here, by an + * authenticated POST. A bearer token is a credential the browser never sends + * on its own, so a link click cannot arm an identity swap. A COOKIE caller + * still has to clear the same-origin gate `POST /orcid/start` applies, for + * exactly the reason that route applies it. + */ +authOrcidRoutes.post( + "/orcid/cli-start", + authMiddleware, + zValidator("json", cliStartSchema), + async (c) => { + if (c.get("authMethod") === "cookie" && !isAllowedOrigin(c.req.header("Origin"))) { + return c.json({ error: "Origin not allowed" }, 403); + } + const user = c.get("user"); + if (!c.env.ENCRYPTION_KEY) { + console.error("[auth-orcid] ENCRYPTION_KEY unset; cannot mint a CLI ORCID state"); + return c.json(profileRefusal("orcid_unavailable", ORCID_UNAVAILABLE_MESSAGE), 503); + } + if (!getOrcidConfig(c.env)) { + // Checked at MINT time, not after the browser is open: a missing ORCID + // client turns into "this deployment cannot link ORCID" in the terminal + // rather than a stray error page at the end of a flow. + return c.json(profileRefusal("orcid_unavailable", ORCID_UNAVAILABLE_MESSAGE), 503); + } + + const mode = c.req.valid("json").mode ?? "link"; + if (mode === "link") { + // A plain `link` on an account that already has an iD would spend the + // whole browser round trip only to be refused by the callback with + // `orcid_already_have`. Answer now, and name the command that does what + // they meant. + const mine = await c.env.DB.prepare( + "SELECT provider_subject FROM oauth_identities WHERE user_id = ? AND provider = 'orcid' LIMIT 1", + ) + .bind(user.id) + .first<{ provider_subject: string }>(); + if (mine) { + return c.json( + { + ...profileRefusal( + "orcid_already_have", + `This account is already linked to ORCID iD ${mine.provider_subject}. Replace it with 'nemar auth profile orcid relink', or remove it with 'nemar auth profile orcid unlink'.`, + ), + orcid: mine.provider_subject, + }, + 409, + ); + } + } + + const csrf = generateCsrf(); + const nonce = generateCsrf(); + const expiresAtMs = Date.now() + CLI_STATE_TTL_MS; + + // Opportunistic prune, so the table cannot outgrow one TTL window and + // needs no cron (migration 0078). Best-effort: a failed prune is not a + // reason to refuse somebody their link. + await c.env.DB.prepare("DELETE FROM orcid_link_intents WHERE expires_at < datetime('now')") + .run() + .catch((err) => console.error("[auth-orcid] failed to prune expired link intents", err)); + + // The row is what makes the intent single-use. Written BEFORE the token is + // handed out: an intent the callback cannot find is refused, so a failed + // insert must not produce a URL that would then work. + await c.env.DB.prepare( + `INSERT INTO orcid_link_intents (nonce, user_id, mode, expires_at) + VALUES (?, ?, ?, ?)`, + ) + .bind(nonce, user.id, mode, new Date(expiresAtMs).toISOString()) + .run(); + + const token = await signCliState( + { + csrf, + mode, + userId: user.id, + nonce, + next: CLI_LINK_LANDING, + exp: expiresAtMs, + }, + c.env.ENCRYPTION_KEY, + ); + + return c.json({ + // Our own handoff, not ORCID's authorize URL directly: the handoff is + // what puts the signed state in a cookie, so a leaked URL is not by + // itself enough to finish the link from a different browser. + authorize_url: `${appBase(c.env)}/auth/orcid/cli-handoff?t=${encodeURIComponent(token)}`, + expires_in: Math.floor(CLI_STATE_TTL_MS / 1000), + mode, + }); + }, +); + +/** + * Resolve the `t=` parameter (or form field) both handoff steps take. + * + * Returns the token, the verified state and the account it names, or the page + * to answer with. Shared so the confirm step re-runs EVERY check the + * interstitial ran -- a page that has already been rendered proves nothing + * about the moment the form is submitted. + */ +async function resolveHandoffIntent( + c: Context<{ Bindings: Bindings; Variables: Variables }>, + token: string | null, +): Promise< + | { ok: true; token: string; state: CliOauthState; account: IntentAccount } + | { ok: false; res: Response } +> { + const frontend = appBase(c.env); + if (!c.env.ENCRYPTION_KEY) { + console.error("[auth-orcid] ENCRYPTION_KEY unset; cannot verify a CLI ORCID state"); + return { ok: false, res: redirect(`${frontend}/login?error=orcid_unavailable`) }; + } + const state = await verifyCliState(token, c.env.ENCRYPTION_KEY, Date.now()); + // Expired, tampered with, or simply not one of ours. Either way there is no + // account to act for, so there is nothing to do but say so. + if (!token || !state) return { ok: false, res: redirect(`${frontend}/login?error=orcid_state`) }; + + // Refuse, never override (PR #1269 review): a browser signed in as somebody + // else is a disagreement, not a preference to resolve. + if (sessionDisagreesWithIntent(c.var.webUser, state)) { + return { ok: false, res: intentMismatchPage() }; + } + + const account = await loadUsableIntent(c.env, state); + if (!account) { + // Already completed, expired out of the table, or the account is gone. + // One page for all three: a person who used this link a minute ago and a + // person handed a stale one both need the same next step. + return { + ok: false, + res: intentPage( + "This link is no longer usable", + `

This link has already been used

+

An ORCID link can be opened once. Run nemar auth profile orcid link again to get a fresh one.

+

Nothing has been changed. (orcid_intent_used)

`, + 410, + ), + }; + } + return { ok: true, token, state, account }; +} + +/** + * Show the person WHOSE account is about to be linked, and make them press a + * button (#1266, ADR 0044; PR #1269 review item A1). + * + * This GET mints nothing and, since the review, no longer redirects anywhere + * either. It renders one sentence naming the target account and a form that + * POSTs back. That sentence is the whole defence against the attack the signed + * state cannot stop on its own: a signed intent is a bearer capability for ten + * minutes, so somebody could mint one for THEIR account and send the URL to a + * victim, who would otherwise complete ORCID consent and find their iD -- the + * identifier a DOI cites (ADR 0041), and one that ADR 0043 then refuses them + * on their own account -- attached to a stranger's row, having seen nothing + * but an ORCID page they expected to see. + * + * No script, and deliberately no auto-submit: a page that submits itself is + * the redirect this replaced, with extra steps. + */ +authOrcidRoutes.get("/orcid/cli-handoff", webSessionMiddleware, async (c) => { + const resolved = await resolveHandoffIntent(c, new URL(c.req.url).searchParams.get("t")); + if (!resolved.ok) return resolved.res; + const { token, state, account } = resolved; + + const who = account.username + ? `${escapeHtml(account.username)} (${escapeHtml(maskEmail(account.email))})` + : escapeHtml(maskEmail(account.email)); + const verb = state.mode === "relink" ? "Replace the ORCID iD on" : "Link your ORCID iD to"; + + return intentPage( + "Confirm your NEMAR account", + `

${escapeHtml(verb)} this NEMAR account?

+

${who}

+

You started this from nemar auth profile orcid ${escapeHtml(state.mode)} in a terminal. + Continuing takes you to ORCID to sign in; the iD you sign in with is attached to the account above.

+

+ If this is not your account, close this tab. + Do not continue with a link somebody else sent you: it would attach your ORCID iD to their NEMAR account. +

+
+ + +
`, + 200, + ); +}); + +/** + * The confirm step of the interstitial: set the state cookie and go to ORCID. + * + * Every check the GET ran is run again here, because the GET proves nothing + * about this moment -- the intent may have been consumed in another tab, and + * the session may have changed. The same-origin gate is what keeps this from + * being the redirect it replaced: without it, a page anywhere could auto-POST + * a crafted intent and the person would never see whose account it names. + */ +authOrcidRoutes.post("/orcid/cli-handoff/continue", webSessionMiddleware, async (c) => { + if (!isAllowedOrigin(c.req.header("Origin"))) { + return c.json({ error: "Origin not allowed" }, 403); + } + const form = await c.req.formData().catch(() => null); + const submitted = form?.get("t"); + const resolved = await resolveHandoffIntent( + c, + typeof submitted === "string" && submitted.length > 0 ? submitted : null, + ); + if (!resolved.ok) return resolved.res; + const { token, state } = resolved; + + const frontend = appBase(c.env); + const config = getOrcidConfig(c.env); + if (!config) return redirect(`${frontend}/login?error=orcid_unavailable`); + + const stateCookie = buildCookie(STATE_COOKIE_NAME, token, { + domain: cookieDomain(c.env), + maxAgeSeconds: Math.floor(CLI_STATE_TTL_MS / 1000), + }); + const authorizeUrl = buildAuthorizeUrl({ + config, + redirectUri: `${frontend}/auth/orcid/callback`, + state: state.csrf, + }); + return redirect(authorizeUrl, [stateCookie]); +}); + authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => { const frontend = appBase(c.env); const domain = cookieDomain(c.env); @@ -364,7 +760,20 @@ authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => { if (url.searchParams.get("error")) return fail("orcid_denied"); - const state = decodeState(parseCookieHeader(c.req.header("Cookie"), STATE_COOKIE_NAME)); + // Two state shapes reach this cookie, and the SIGNED one is tried first + // (#1266, ADR 0044). A CLI-minted state names the account it was minted for + // inside an HMAC the browser cannot forge; the website's plain state cookie + // names no account at all and never can, which is what keeps a forged + // cookie from linking an iD to somebody else's row. Everything downstream — + // the csrf compare, the mode, the landing path — reads the same three + // fields either way. + const stateCookieRaw = parseCookieHeader(c.req.header("Cookie"), STATE_COOKIE_NAME); + const cliState = c.env.ENCRYPTION_KEY + ? await verifyCliState(stateCookieRaw, c.env.ENCRYPTION_KEY, Date.now()) + : null; + const state: OauthState | null = cliState + ? { csrf: cliState.csrf, mode: cliState.mode, next: cliState.next } + : decodeState(stateCookieRaw); const stateParam = url.searchParams.get("state"); if (!state || !stateParam || !timingSafeEqual(stateParam, state.csrf)) { return fail("orcid_state"); @@ -395,18 +804,46 @@ authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => { .bind(orcid) .first<{ user_id: number }>(); - const webUser = c.var.webUser; + // WHICH account the finished iD attaches to. + // + // A CLI-minted state answers it on its own (#1266): the browser that + // finishes the flow was opened from a terminal and carries no NEMAR + // session, so the id inside the signed state is the only account in play. + // `loadActiveUser` re-checks the row is still live and not revoked, since + // the intent was minted up to ten minutes ago. + // + // A session for a DIFFERENT account is refused rather than overridden (PR + // #1269 review). The handoff already refused it once; this is the same + // rule at the other end, because the two steps are minutes apart and a + // browser can sign in between them. + let actingUserId: number | null = null; + if (cliState) { + if (sessionDisagreesWithIntent(c.var.webUser, cliState)) { + return fail("orcid_intent_account_mismatch", state.next); + } + const cliUser = await loadActiveUser(c.env, cliState.userId); + if (!cliUser) return fail("orcid_account", state.next); + // Consume before anything is written: one browser completion per intent, + // whatever its outcome. A replay of the same URL loses this race and is + // refused here, with nothing linked. + if (!(await consumeIntent(c.env, cliState))) { + return fail("orcid_intent_used", state.next); + } + actingUserId = cliUser.id; + } else if (c.var.webUser) { + actingUserId = c.var.webUser.id; + } - // An already-authenticated session => link to that user (regardless of the - // start mode, so a logged-in user can never accidentally spawn a duplicate - // account). The default landing is the carried `next` (the onboarding gate - // passes /welcome). - if (webUser) { - const outcome = decideLinkOutcome(ident?.user_id ?? null, webUser.id); + // An already-authenticated session (or a CLI intent) => link to that user + // (regardless of the start mode, so a logged-in user can never + // accidentally spawn a duplicate account). The default landing is the + // carried `next` (the onboarding gate passes /welcome). + if (actingUserId !== null) { + const outcome = decideLinkOutcome(ident?.user_id ?? null, actingUserId); if (outcome === "conflict") return fail("orcid_linked_other", state.next); if (outcome === "already_linked") { await touchIdentityLogin(c.env, orcid); - afterResponse(c, refreshUserName(c.env, webUser.id, orcid)); + afterResponse(c, refreshUserName(c.env, actingUserId, orcid)); return redirect(`${frontend}${state.next}`, [clearState]); } // link_new says only that no oauth_identities row claims the iD. That @@ -416,7 +853,7 @@ authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => { // how one person ends up backing two accounts (production rows 42/43). // Checked here rather than inside the relink branch so it covers both a // first link and an explicit relink -- both write `users.orcid`. - const orcidHolder = await findOrcidHolder(c.env.DB, orcid, webUser.id); + const orcidHolder = await findOrcidHolder(c.env.DB, orcid, actingUserId); if (orcidHolder) return fail("orcid_in_use", state.next); // If this account already has a *different* iD, only an explicit relink @@ -424,28 +861,28 @@ authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => { const mine = await c.env.DB.prepare( "SELECT provider_subject FROM oauth_identities WHERE user_id = ? AND provider = 'orcid' LIMIT 1", ) - .bind(webUser.id) + .bind(actingUserId) .first<{ provider_subject: string }>(); if (mine && mine.provider_subject !== orcid) { if (decideSecondOrcidOutcome(state.mode) === "refuse") { return fail("orcid_already_have", state.next); } try { - await relinkIdentity(c.env, webUser.id, mine.provider_subject, orcid, name); + await relinkIdentity(c.env, actingUserId, mine.provider_subject, orcid, name); } catch (err) { if (claimedByAnother(err)) return fail("orcid_in_use", state.next); throw err; } - afterResponse(c, refreshUserName(c.env, webUser.id, orcid)); + afterResponse(c, refreshUserName(c.env, actingUserId, orcid)); return redirect(`${frontend}${state.next}`, [clearState]); } try { - await linkIdentity(c.env, webUser.id, orcid, name); + await linkIdentity(c.env, actingUserId, orcid, name); } catch (err) { if (claimedByAnother(err)) return fail("orcid_in_use", state.next); throw err; } - afterResponse(c, refreshUserName(c.env, webUser.id, orcid)); + afterResponse(c, refreshUserName(c.env, actingUserId, orcid)); return redirect(`${frontend}${state.next}`, [clearState]); } @@ -715,11 +1152,13 @@ authOrcidRoutes.post("/orcid/finalize", zValidator("json", finalizeSchema), asyn }); authOrcidRoutes.post("/orcid/unlink", webSessionMiddleware, async (c) => { - if (!isAllowedOrigin(c.req.header("Origin"))) { - return c.json({ error: "Origin not allowed" }, 403); - } - const webUser = c.var.webUser; - if (!webUser) return c.json({ error: "Authentication required" }, 401); + // Cookie or bearer token (#1266, ADR 0044). Unlink is the one ORCID + // operation with no browser step in it -- nothing to consent to, nothing to + // redirect through -- so the CLI calls it directly. The same-origin gate + // still applies to the cookie half; see `resolveActingAccount`. + const resolved = await resolveActingAccount(c); + if (!resolved.ok) return resolved.response; + const actor = resolved.actor; // Drop the link COMPLETELY: the identity row, `orcid_verified`, AND // `users.orcid` (#1254, ADR 0043). @@ -745,9 +1184,9 @@ authOrcidRoutes.post("/orcid/unlink", webSessionMiddleware, async (c) => { await c.env.DB.batch([ c.env.DB.prepare( "DELETE FROM oauth_identities WHERE user_id = ? AND provider = 'orcid'", - ).bind(webUser.id), + ).bind(actor.id), c.env.DB.prepare("UPDATE users SET orcid = NULL, orcid_verified = 0 WHERE id = ?").bind( - webUser.id, + actor.id, ), ]); } catch (err) { diff --git a/backend/src/routes/auth-web.ts b/backend/src/routes/auth-web.ts index 03afaab63..554d218be 100644 --- a/backend/src/routes/auth-web.ts +++ b/backend/src/routes/auth-web.ts @@ -48,6 +48,7 @@ import { Hono } from "hono"; import { z } from "zod"; import { auditLogStatement } from "../db/audit-log"; import { timingSafeEqual } from "../lib/constant-time"; +import { resolveActingAccount } from "../middleware/auth"; import { webSessionMiddleware } from "../middleware/webSession"; import { CODE_TTL_MINUTES, @@ -65,6 +66,7 @@ import { import { resolveEmailConfig, sendEmailChangeCodeEmail, + sendEmailChangedNoticeEmail, sendPasswordlessCodeEmail, } from "../services/email"; import { @@ -84,6 +86,7 @@ import { type ProfilePatchInput, githubHandleChanged, normalizeProfilePatch, + profileRefusal, } from "../services/profile"; import { isUsernameUniqueViolation, @@ -670,6 +673,12 @@ export const _profilePatchShapesAgree: MutuallyAssignable< * subset of github_username / city / country / affiliation / username / * given_name / family_name — see profile.ts for the per-field rules. * + * Two credentials, ONE handler (#1266, ADR 0044): the dashboard's + * `nemar_session` cookie or the CLI's bearer token, resolved by + * `resolveActingAccount`. Every rule and every refusal below is reached + * identically by both, which is the point — a forked CLI copy is how the two + * surfaces drift on what "your username is locked" means. + * * A changed GitHub handle gets the same three checks as CLI signup: direct * dup (COLLATE NOCASE, 409 even when the handle no longer resolves), live * existence against the GitHub API, and a canonical-login re-dedup when @@ -699,13 +708,9 @@ authWebRoutes.patch( webSessionMiddleware, zValidator("json", profilePatchSchema), async (c) => { - if (!isAllowedOrigin(c.req.header("Origin"))) { - return c.json({ error: "Origin not allowed" }, 403); - } - const webUser = c.var.webUser; - if (!webUser) { - return c.json({ error: "Authentication required" }, 401); - } + const resolved = await resolveActingAccount(c); + if (!resolved.ok) return resolved.response; + const actor = resolved.actor; const normalized = normalizeProfilePatch(c.req.valid("json")); if (!normalized.ok) { @@ -721,15 +726,15 @@ authWebRoutes.patch( patch.family_name !== undefined ) { // One read for both rules, and only when one of them is in the patch: - // a plain city/country save must not pay for it. `webUser` carries - // status and orcid_verified already but NOT username, and reading them - // from one statement keeps the three decisions consistent with each - // other rather than with two different moments. + // a plain city/country save must not pay for it. The credential — + // cookie or token — carries neither `username` nor `orcid_verified`, + // and reading them from one statement keeps the three decisions + // consistent with each other rather than with two different moments. const account = await db .prepare( "SELECT username, status, orcid, orcid_verified FROM users WHERE id = ? AND deleted_at IS NULL", ) - .bind(webUser.id) + .bind(actor.id) .first<{ username: string | null; status: string; @@ -757,10 +762,7 @@ authWebRoutes.patch( // and because it says out loud that revocation is not a state // profile edits happen in. return c.json( - { - error: "account_revoked", - message: "This account is revoked; contact an admin", - }, + profileRefusal("account_revoked", "This account is revoked; contact an admin"), 409, ); } else if (current !== "" && account.status === "approved") { @@ -772,11 +774,10 @@ authWebRoutes.patch( // A first assignment is not a change, so it is allowed at any // status. return c.json( - { - error: "username_locked", - message: - "Your username is fixed once an admin has approved your account; contact an admin to change it", - }, + profileRefusal( + "username_locked", + "Your username is fixed once an admin has approved your account; contact an admin to change it", + ), 409, ); } else { @@ -786,11 +787,11 @@ authWebRoutes.patch( WHERE username = ? COLLATE NOCASE AND id != ? AND deleted_at IS NULL LIMIT 1`, ) - .bind(patch.username, webUser.id) + .bind(patch.username, actor.id) .first<{ id: number }>(); if (taken) { return c.json( - { error: "username_taken", message: "That username is already taken" }, + profileRefusal("username_taken", "That username is already taken"), 409, ); } @@ -803,11 +804,10 @@ authWebRoutes.patch( (account.orcid ?? "").trim() !== "" ) { return c.json( - { - error: "name_is_orcid_canonical", - message: - "Your name comes from your ORCID record and is refreshed on every sign-in. Update it at orcid.org and sign in again.", - }, + profileRefusal( + "name_is_orcid_canonical", + "Your name comes from your ORCID record and is refreshed on every sign-in. Update it at orcid.org and sign in again.", + ), 409, ); } @@ -815,7 +815,7 @@ authWebRoutes.patch( if ( typeof patch.github_username === "string" && - githubHandleChanged(patch.github_username, webUser.github_username) + githubHandleChanged(patch.github_username, actor.github_username) ) { const dup = await db .prepare( @@ -823,7 +823,7 @@ authWebRoutes.patch( WHERE github_username = ? COLLATE NOCASE AND id != ? AND deleted_at IS NULL LIMIT 1`, ) - .bind(patch.github_username, webUser.id) + .bind(patch.github_username, actor.id) .first<{ id: number }>(); if (dup) { return c.json({ error: "github_in_use", ...identityRefusal("github_in_use") }, 409); @@ -840,10 +840,10 @@ authWebRoutes.patch( if (githubLookup.status === "unavailable") { console.error(`[auth-web] /profile GitHub lookup unavailable: ${githubLookup.detail}`); return c.json( - { - error: "github_unavailable", - message: "GitHub could not be reached; try again in a few minutes", - }, + profileRefusal( + "github_unavailable", + "GitHub could not be reached; try again in a few minutes", + ), 503, ); } @@ -867,7 +867,7 @@ authWebRoutes.patch( WHERE github_username = ? COLLATE NOCASE AND id != ? AND deleted_at IS NULL LIMIT 1`, ) - .bind(githubUser.login, webUser.id) + .bind(githubUser.login, actor.id) .first<{ id: number }>(); if (canonicalDup) { return c.json({ error: "github_in_use", ...identityRefusal("github_in_use") }, 409); @@ -911,7 +911,7 @@ authWebRoutes.patch( // here is re-submitting your own current username). Answer with the // current row rather than building `UPDATE users SET WHERE ...`. if (sets.length === 0) { - const unchanged = await fetchPublicUserById(db, webUser.id); + const unchanged = await fetchPublicUserById(db, actor.id); if (!unchanged) return c.json({ error: "Account not found" }, 403); return c.json({ ok: true, user: unchanged }); } @@ -922,19 +922,19 @@ authWebRoutes.patch( await db.batch([ db .prepare(`UPDATE users SET ${sets.join(", ")} WHERE id = ? AND deleted_at IS NULL`) - .bind(...binds, webUser.id), + .bind(...binds, actor.id), auditLogStatement(db, { - userId: webUser.id, + userId: actor.id, action: "profile_updated", resourceType: "user", - resourceId: String(webUser.id), + resourceId: String(actor.id), details: JSON.stringify(patch), }), ]); // Re-read so the response reflects what actually landed (the website // also re-reads /auth/me on reload; this keeps both in agreement). - const user = await fetchPublicUserById(db, webUser.id); + const user = await fetchPublicUserById(db, actor.id); if (!user) { // Session resolved but the row is gone (tombstoned mid-request). return c.json({ error: "Account not found" }, 403); @@ -961,7 +961,7 @@ authWebRoutes.patch( // case-VARIANT race (`Ada` and `ada` arriving together) slips past both // and is what Phase 4's case-insensitive unique index closes. if (isUsernameUniqueViolation(err)) { - return c.json({ error: "username_taken", message: "That username is already taken" }, 409); + return c.json(profileRefusal("username_taken", "That username is already taken"), 409); } console.error("[auth-web] /profile PATCH failed", err); return c.json({ error: "Failed to update profile" }, 500); @@ -1045,10 +1045,62 @@ async function restoreConsumedCode(db: D1Database, codeId: number, email: string * account the code belongs to. `POST /auth/code/verify`, which is * unauthenticated, keeps its single collapsed answer for exactly that reason. */ -const CODE_EXPIRED_BODY = { - error: "code_expired", - message: "That code has expired or has already been used. Request a new one.", -} as const; +const CODE_EXPIRED_BODY = profileRefusal( + "code_expired", + "That code has expired or has already been used. Request a new one.", +); + +/** + * The `same_email` refusal, with a sentence. + * + * It shipped as a bare `{ error: "same_email" }`, which the website could + * switch on and a terminal could only print as the word "same_email" (#1266). + * `error` keeps the code the website already reads; `message` is additive. + */ +const SAME_EMAIL_REFUSAL = profileRefusal( + "same_email", + "That is already the address on this account.", +); + +/** + * Tell the PREVIOUS address that the account's sign-in email moved (#1054). + * + * Never throws and never blocks: the change has already committed when this + * runs, so the only question left is whether the old inbox heard about it. + * Returns that answer so the route can report `old_address_notified` rather + * than leaving the caller to assume a send that may have been fenced (a + * non-production worker refuses any recipient off DEV_EMAIL_ALLOWLIST) or + * refused by Resend. + * + * The new address is MASKED in the notice: whoever reads the old inbox may no + * longer be the account owner -- that is precisely the case this mail exists + * for -- and they need to know the address changed, not what it changed to. + */ +async function notifyOldAddressOfEmailChange( + c: { env: Bindings }, + oldEmail: string, + newEmail: string, +): Promise { + try { + const { fromEmail, replyTo, isDev } = resolveEmailConfig(c.env); + await sendEmailChangedNoticeEmail( + oldEmail, + maskEmail(newEmail), + c.env.RESEND_API_KEY, + fromEmail, + replyTo, + isDev, + c.env, + ); + return true; + } catch (err) { + console.error( + "[auth-web] /email/change/verify: could not notify the previous address (the change DID land)", + err, + ); + return false; + } +} /** Re-read a user by id and shape the dashboard payload (same SELECT the * /code/verify path runs by email). Null when the row is gone/tombstoned. */ @@ -1116,6 +1168,11 @@ async function fetchPublicUserById( * auth_codes table and the /code/request mechanics (atomic rate-limited * insert, rotation, rollback-on-send-failure, dev_code echo rules). * + * Cookie OR bearer token since #1266 (ADR 0044) — the same handler either + * way. What the credential decides is only WHOSE account is acting; the code + * still goes to the new address and is still bound to that account, so a + * token can no more redeem someone else's code than a session can. + * * Purpose-mixing with sign-in codes is structurally impossible, twice over: * a change code is only ever issued for an address with NO users row * (collisions are refused here), while /code/verify requires a users row for @@ -1128,19 +1185,15 @@ authWebRoutes.post( webSessionMiddleware, zValidator("json", emailSchema), async (c) => { - if (!isAllowedOrigin(c.req.header("Origin"))) { - return c.json({ error: "Origin not allowed" }, 403); - } - const webUser = c.var.webUser; - if (!webUser) { - return c.json({ error: "Authentication required" }, 401); - } + const resolved = await resolveActingAccount(c); + if (!resolved.ok) return resolved.response; + const actor = resolved.actor; const { email } = c.req.valid("json"); const db = c.env.DB; try { - if (email === webUser.email.toLowerCase()) { - return c.json({ error: "same_email" }, 409); + if (email === actor.email.toLowerCase()) { + return c.json(SAME_EMAIL_REFUSAL, 409); } // Deliberate, bounded enumeration tradeoff (PR #1053 review): unlike // /code/request's #595 silent skip, this DOES tell the caller whether @@ -1183,12 +1236,12 @@ authWebRoutes.post( email, codeHash, expiresAt, - webUser.id, + actor.id, email, PER_MINUTE_LIMIT, email, PER_HOUR_LIMIT, - webUser.id, + actor.id, PER_HOUR_LIMIT, ) .run(); @@ -1205,7 +1258,7 @@ authWebRoutes.post( `UPDATE auth_codes SET used_at = datetime('now') WHERE email = ? AND user_id = ? AND used_at IS NULL AND id != ?`, ) - .bind(email, webUser.id, newCodeId) + .bind(email, actor.id, newCodeId) .run(); // #1008 + #957: same echo-skips-the-send reasoning as /code/request @@ -1267,26 +1320,27 @@ authWebRoutes.post( * new address (same compare/attempts/consume semantics as /code/verify), * then moves users.email in the same D1 batch as the audit row. The session * cookie is NOT rotated: web_sessions reference the user id, not the email, - * so every existing session stays valid across the change. + * so every existing session stays valid across the change. Nor is the API + * token: `tokens` references the user id too, so a CLI that changed its + * address keeps working with the key it already has. + * + * On success the PREVIOUS address is told (#1054) — best-effort, reported as + * `old_address_notified`, never a reason to fail a change that has landed. */ authWebRoutes.post( "/email/change/verify", webSessionMiddleware, zValidator("json", emailChangeVerifySchema), async (c) => { - if (!isAllowedOrigin(c.req.header("Origin"))) { - return c.json({ error: "Origin not allowed" }, 403); - } - const webUser = c.var.webUser; - if (!webUser) { - return c.json({ error: "Authentication required" }, 401); - } + const resolved = await resolveActingAccount(c); + if (!resolved.ok) return resolved.response; + const actor = resolved.actor; const { email, code } = c.req.valid("json"); const db = c.env.DB; try { - if (email === webUser.email.toLowerCase()) { - return c.json({ error: "same_email" }, 409); + if (email === actor.email.toLowerCase()) { + return c.json(SAME_EMAIL_REFUSAL, 409); } // Re-check the collision: an account for this address may have been // created between request and verify. Case-insensitive (ADR 0043), and @@ -1300,7 +1354,7 @@ authWebRoutes.post( const row = await db .prepare(USER_BOUND_CODE_LOOKUP_SQL) - .bind(email, webUser.id) + .bind(email, actor.id) .first<{ id: number; code_hash: string; attempts: number }>(); if (!row) { return c.json(CODE_EXPIRED_BODY, 401); @@ -1311,11 +1365,12 @@ authWebRoutes.post( const attemptsRemaining = await recordFailedAttempt(db, row); return c.json( { - error: "code_incorrect", - message: + ...profileRefusal( + "code_incorrect", attemptsRemaining > 0 ? `That code did not match. ${attemptsRemaining} attempt${attemptsRemaining === 1 ? "" : "s"} left before it is invalidated.` : "That code did not match and has now been invalidated. Request a new one.", + ), attempts_remaining: attemptsRemaining, }, 401, @@ -1341,13 +1396,13 @@ authWebRoutes.post( await db.batch([ db .prepare("UPDATE users SET email = ?, email_verified = 1 WHERE id = ?") - .bind(email, webUser.id), + .bind(email, actor.id), auditLogStatement(db, { - userId: webUser.id, + userId: actor.id, action: "email_changed", resourceType: "user", - resourceId: String(webUser.id), - details: JSON.stringify({ from: webUser.email, to: email }), + resourceId: String(actor.id), + details: JSON.stringify({ from: actor.email, to: email }), }), ]); } catch (writeErr) { @@ -1364,11 +1419,26 @@ authWebRoutes.post( throw writeErr; } - const user = await fetchPublicUserById(db, webUser.id); + // Tell the address that just LOST the account (#1054). In a + // passwordless architecture the old inbox is the only channel that can + // reach a legitimate owner whose sign-in address moved out from under + // them (a stolen session cookie, a stolen API token), and the audit row + // this route already writes is visible to nobody but an admin. + // + // Best-effort, and deliberately AFTER the write: the change has landed + // and is not reversible by a failed send, so a failure is logged and + // reported (`old_address_notified`) rather than 500ed. Off production + // `sendEmail`'s own fence refuses any recipient that is not on + // DEV_EMAIL_ALLOWLIST -- the old address is a REAL one on the dev + // mirror's ~609 rows, and this is the one send in the flow whose + // target the caller did not choose. + const oldAddressNotified = await notifyOldAddressOfEmailChange(c, actor.email, email); + + const user = await fetchPublicUserById(db, actor.id); if (!user) { return c.json({ error: "Account not found" }, 403); } - return c.json({ ok: true, user }); + return c.json({ ok: true, user, old_address_notified: oldAddressNotified }); } catch (err) { console.error("[auth-web] /email/change/verify failed", err); return c.json({ error: "Verification failed" }, 500); @@ -1492,11 +1562,12 @@ authWebRoutes.post( const attemptsRemaining = await recordFailedAttempt(db, row); return c.json( { - error: "code_incorrect", - message: + ...profileRefusal( + "code_incorrect", attemptsRemaining > 0 ? `That code did not match. ${attemptsRemaining} attempt${attemptsRemaining === 1 ? "" : "s"} left before it is invalidated.` : "That code did not match and has now been invalidated. Request a new one.", + ), attempts_remaining: attemptsRemaining, }, 401, diff --git a/backend/src/services/email.ts b/backend/src/services/email.ts index 774eb660a..a783e478b 100644 --- a/backend/src/services/email.ts +++ b/backend/src/services/email.ts @@ -1580,6 +1580,72 @@ export async function sendEmailChangeCodeEmail( ); } +/** + * Tell the PREVIOUS address that an account's sign-in email was changed + * (#1054; ADR 0044). + * + * NEMAR sign-in is passwordless for the dashboard and token-based for the + * CLI, so the old inbox is the only channel that can reach a legitimate owner + * whose address was moved out from under them with a stolen session or key. + * The change itself has already happened by the time this is sent -- this is + * a notice, not a confirmation step, so there is nothing to confirm and the + * only link worth following is the support one, and only if this was not you. + * + * `maskedNewEmail` is deliberately masked by the caller (`maskEmail`): the + * person reading the old inbox may no longer be the account owner, which is + * the whole reason for the mail, and what they need is that the address + * changed rather than what it changed to. + */ +export async function sendEmailChangedNoticeEmail( + to: string, + maskedNewEmail: string, + resendApiKey: string, + fromEmail: string, + replyTo?: string, + isDev?: boolean, + deliveryEnv?: EmailDeliveryEnv, +): Promise { + const html = ` + + + + + + + +

Your NEMAR account email was changed

+ +

The sign-in email for your NEMAR account was changed from this address to ${escapeHtml(maskedNewEmail)}.

+ +

This address can no longer be used to sign in to the account, and future NEMAR mail goes to the new one.

+ +

+ If this was not you, contact NEMAR support at + nemar.org/support right away and say which address this notice reached. +

+ +
+ +

+ NEMAR - Neuroelectromagnetic Data Archive and Tools Resource
+ This is a security notice: there is nothing to confirm. The only link above goes to NEMAR support, for use if this was not you. +

+ + + `; + + await sendEmail( + to, + "Your NEMAR account email was changed", + html, + resendApiKey, + fromEmail, + replyTo, + isDev, + deliveryEnv, + ); +} + /** * Warn a dataset owner that their private, unpublished dataset is approaching * the 90-day inactivity deadline and will be removed unless they act (#662). diff --git a/backend/src/services/orcid-auth.ts b/backend/src/services/orcid-auth.ts index 80aeea0a6..1e8ad6eb4 100644 --- a/backend/src/services/orcid-auth.ts +++ b/backend/src/services/orcid-auth.ts @@ -422,3 +422,103 @@ export async function verifyPending( return null; } } + +// --------------------------------------------------------------------- +// CLI-initiated link state (#1266, ADR 0044) +// --------------------------------------------------------------------- +// +// ORCID is a browser flow and stays one: the CLI cannot show a consent +// screen, and nobody should type an ORCID password into a terminal. So +// `POST /auth/orcid/cli-start` mints the intent for the TOKEN'S account and +// hands back a URL to open; the browser that opens it has no NEMAR session, +// which is exactly what the callback used to resolve the user from. +// +// The account therefore travels INSIDE the state, and the state is HMAC +// signed with ENCRYPTION_KEY (the same key and the same construction as the +// pending-signup cookie above). Two properties follow, and both are +// load-bearing: +// +// - a state minted for user A can never link to user B, because the id is +// covered by the signature and nothing else in the callback supplies one +// for this path; and +// - a state cannot be MADE at all without a live API token for the account +// it names, so the ADR 0022 rule survives: relink intent is still minted +// only by an authenticated POST, never by following a link. +// +// The token is short-lived (10 minutes, the same TTL as the website's state +// cookie) and is carried to ORCID in the state COOKIE rather than in the +// `state` query parameter, so a leaked authorize URL is not on its own enough +// to finish a link from another browser -- see `/auth/orcid/cli-handoff`. + +/** How long a CLI-minted ORCID link intent stays usable. */ +export const CLI_STATE_TTL_MS = 10 * 60 * 1000; + +export interface CliOauthState { + csrf: string; + /** Never "login": a CLI flow always acts on an existing account. */ + mode: "link" | "relink"; + /** The account the intent was minted FOR. Covered by the signature. */ + userId: number; + /** + * Server-side handle for this intent (`orcid_link_intents.nonce`, migration + * 0078). The signature makes an intent unforgeable; this makes it + * UNREPEATABLE -- the callback consumes the row, so a second completion with + * the same URL is refused. Covered by the signature like the rest, so a + * replay cannot swap in a fresh nonce. + */ + nonce: string; + /** Same-origin relative path to land the browser on afterwards. */ + next: string; + /** Epoch ms after which the state is rejected. */ + exp: number; +} + +export async function signCliState(s: CliOauthState, secret: string): Promise { + const payload = b64urlEncode(JSON.stringify(s)); + const sig = await hmacHex(secret, payload); + return `${payload}.${sig}`; +} + +/** + * Verify and decode a CLI state, or null for anything that is not one: a + * missing value, a web flow's plain state cookie, a bad signature, an expired + * intent, or a payload whose fields are not the shape above. + * + * `null` is not an error here -- the callback tries this FIRST and falls back + * to the web `decodeState`, so "this is not a CLI state" is the normal answer + * for every dashboard sign-in. + */ +export async function verifyCliState( + token: string | null | undefined, + secret: string, + nowMs: number, +): Promise { + if (!token) return null; + const dot = token.indexOf("."); + if (dot < 1) return null; + const payload = token.slice(0, dot); + const sig = token.slice(dot + 1); + const expected = await hmacHex(secret, payload); + if (!timingSafeEqual(sig, expected)) return null; + try { + const p = JSON.parse(b64urlDecode(payload)) as Partial; + if (typeof p.csrf !== "string" || p.csrf.length === 0) return null; + if (p.mode !== "link" && p.mode !== "relink") return null; + if (typeof p.userId !== "number" || !Number.isInteger(p.userId) || p.userId <= 0) return null; + // A state with no nonce cannot be consumed, so it cannot be single-use. + // Rejected outright rather than treated as "no replay protection": the + // only states without one predate migration 0078 and expired long ago. + if (typeof p.nonce !== "string" || p.nonce.length === 0) return null; + if (typeof p.exp !== "number" || nowMs > p.exp) return null; + return { + csrf: p.csrf, + mode: p.mode, + userId: p.userId, + nonce: p.nonce, + next: safeNextPath(typeof p.next === "string" ? p.next : "/"), + exp: p.exp, + }; + } catch { + return null; + } +} diff --git a/backend/src/services/profile.ts b/backend/src/services/profile.ts index f81976465..9a9219dc4 100644 --- a/backend/src/services/profile.ts +++ b/backend/src/services/profile.ts @@ -28,6 +28,7 @@ * answers 409 `name_is_orcid_canonical` for the rest. */ +import type { ProfileEditErrorCode } from "../../../shared/contract/user.js"; import { normalizeGithubHandle } from "./identity"; import { type UsernameFormatError, validateUsernameFormat } from "./username"; @@ -78,6 +79,43 @@ export type NormalizeResult = | { ok: true; patch: ProfilePatch } | { ok: false; error: ProfilePatchError; message: string }; +/** + * Compile-time proof that every refusal this module can raise is in the + * shared vocabulary the CLI renders from (#1266, ADR 0044). + * + * The CLI prints `error` for an ordinary failure and `message` for a body + * whose `error` is a machine code; it decides which by membership in + * `PROFILE_EDIT_ERROR_CODES`. A code added here and not there does not fail + * anywhere — it just prints the word `city_required` at a person — so the + * alias below resolves to `never` and the assignment stops compiling instead. + */ +type AllDeclared = [A] extends [B] ? true : never; +export const _profileErrorsAreDeclared: AllDeclared = true; + +/** + * The body of a route-level self-service refusal, with the code CHECKED. + * + * The alias above only covers the codes `normalizeProfilePatch` returns. The + * ten raised by the routes themselves -- `username_taken`, `username_locked`, + * `name_is_orcid_canonical`, `account_revoked`, `github_unavailable`, + * `same_email`, `code_expired`, `code_incorrect`, `orcid_already_have`, + * `orcid_unavailable` -- were bare string literals in `c.json({ error: "..." })` + * calls, so the ADR's claim that a missing code "fails to compile" was true of + * a third of them (PR #1269 review item 17). Going through this function makes + * it true of all of them: the parameter is `ProfileEditErrorCode`, so a typo or + * an undeclared code is a compile error at the call site rather than a bare + * token printed at a person. + * + * `error` carries the code because that is where the browser-facing routes + * have always put it (ADR 0043); extra fields are spread in by the caller. + */ +export function profileRefusal( + code: ProfileEditErrorCode, + message: string, +): { error: ProfileEditErrorCode; message: string } { + return { error: code, message }; +} + /** * Normalize a raw PATCH body into a sparse, validated update. Keys absent * from the input stay absent from the patch (true PATCH semantics); the diff --git a/backend/test/cli-self-service-routes.test.ts b/backend/test/cli-self-service-routes.test.ts new file mode 100644 index 000000000..d2e9807ee --- /dev/null +++ b/backend/test/cli-self-service-routes.test.ts @@ -0,0 +1,1148 @@ +/** + * Token-authenticated self-service identity routes (#1266, epic #1250; ADR + * 0044), plus the old-address notification #1054 asks for. + * + * The claim under test is parity: the SAME handler, reached with the CLI's + * bearer token instead of the dashboard's session cookie, applies the same + * rules and raises the same refusals. So every case here drives the HTTP route + * with an `Authorization: Bearer` header and asserts on what landed in the + * database or in the mail. + * + * Real engine throughout: bun:sqlite behind `realD1` with every migration + * applied, real Hono dispatch, real zod validation, real HMAC code hashing via + * the production `hashAuthCode`, real API-key hashing via `hashApiKey`, real + * session issuance via `issueSession`, real ORCID state signing via + * `signCliState`. The two external boundaries -- ORCID and GitHub -- are a + * local `Bun.serve()` reached through the bindings production already uses to + * point at a mirror, and Resend is redirected to another local server by + * `withFakeResend`, so services/email.ts runs unchanged including its + * non-production delivery fence. No mocks. + */ + +import type { Database } from "bun:sqlite"; +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import type { Server } from "bun"; +import { Hono } from "hono"; +import { authOrcidRoutes } from "../src/routes/auth-orcid"; +import { authWebRoutes } from "../src/routes/auth-web"; +import { hashAuthCode } from "../src/services/auth-code"; +import { STATE_COOKIE_NAME, signCliState } from "../src/services/orcid-auth"; +import { hashApiKey } from "../src/services/token"; +import { issueSession } from "../src/services/web-session"; +import type { Bindings, Variables } from "../src/types/bindings"; +import { freshDb, realD1 } from "./helpers/d1"; +import { type CapturedEmail, asSend, sendsTo, withFakeResend } from "./helpers/resend"; + +const APP = "https://app.nemar.org"; +const ENCRYPTION_KEY = "cli-self-service-test-encryption-key-0123"; + +/** Keys are >= 32 chars: `resolveBearerUser` refuses anything shorter. */ +const ADA_KEY = "cli-self-service-ada-key-0123456789abcdef"; +const BOB_KEY = "cli-self-service-bob-key-0123456789abcdef"; + +const ADA_ORCID = "0000-0002-1825-0097"; +const BOB_ORCID = "0000-0002-1974-1293"; + +let db: Database; +let app: Hono<{ Bindings: Bindings; Variables: Variables }>; +let external: Server; +let externalBase: string; +/** Which iD the local ORCID token endpoint hands back for the next callback. */ +let tokenOrcid = ADA_ORCID; +/** GitHub logins the local mirror should answer 404 for. */ +let missingGithubLogins = new Set(); +/** GitHub logins the local mirror should answer 502 for -- an OUTAGE, which + * is a different answer from "this account does not exist" (#1052). */ +let failingGithubLogins = new Set(); +/** + * `/users/:login` hits since the last reset. + * + * What makes the duplicate-handle refusal falsifiable at all. `idx_users_github` + * (COLLATE NOCASE, migration 0012) would reject the same write at the UPDATE + * and the route's catch maps it to the same 409 body, so a status-and-body + * assertion passes whether or not the PRE-CHECK exists. The pre-check runs + * before `validateGitHubUsername`, so the observable difference is that a + * refused save spends no GitHub call -- which is also why it is ordered that + * way: a duplicate must not cost a rate-limited request on a shared token. + */ +let githubCalls = 0; + +beforeAll(() => { + external = Bun.serve({ + port: 0, + fetch(req) { + const url = new URL(req.url); + if (url.pathname === "/oauth/token") { + return Response.json({ orcid: tokenOrcid, name: "Ada Lovelace", access_token: "unused" }); + } + if (url.pathname.endsWith("/personal-details")) { + return Response.json({ + name: { "given-names": { value: "Ada" }, "family-name": { value: "Lovelace" } }, + }); + } + const gh = url.pathname.match(/^\/users\/(.+)$/); + if (gh) { + githubCalls += 1; + if (failingGithubLogins.has(gh[1])) return new Response("upstream boom", { status: 502 }); + if (missingGithubLogins.has(gh[1])) return new Response("not found", { status: 404 }); + return Response.json({ login: gh[1], id: 4242 }); + } + return new Response("not found", { status: 404 }); + }, + }); + externalBase = `http://localhost:${external.port}`; + (globalThis as { NEMAR_GITHUB_API_URL?: string }).NEMAR_GITHUB_API_URL = externalBase; +}); + +afterAll(() => { + (globalThis as { NEMAR_GITHUB_API_URL?: string }).NEMAR_GITHUB_API_URL = undefined; + external.stop(true); +}); + +/** + * `DEV_EMAIL_ALLOWLIST` defaults to the synthetic test domain so the mail this + * suite asserts on is actually delivered. Individual tests pass "" to exercise + * the fence, which is the state the dev worker is really in for a real user's + * address (AGENTS.md: ~609 real addresses behind a live Resend key). + */ +function env(allowlist = "@nemar.test"): Bindings { + return { + DB: realD1(db), + ENVIRONMENT: "test", + ENCRYPTION_KEY, + RESEND_API_KEY: "test-resend-key", + FROM_EMAIL: "NEMAR ", + DEV_EMAIL_ALLOWLIST: allowlist, + ORCID_CLIENT_ID: "APP-TEST", + ORCID_CLIENT_SECRET: "test-secret", + ORCID_API_BASE: externalBase, + ORCID_PUB_API_BASE: externalBase, + APP_BASE_URL: APP, + WEB_SESSION_COOKIE_DOMAIN: "", + GITHUB_ADMIN_PAT: "test-pat-not-used-against-a-real-host", + API_BASE_URL: "http://localhost:8787", + } as unknown as Bindings; +} + +interface SeedOpts { + username?: string | null; + status?: string; + github?: string | null; + orcid?: string | null; + orcidVerified?: boolean; + identityBacked?: boolean; + givenName?: string | null; + familyName?: string | null; +} + +async function seedUser(email: string, apiKey: string | null, opts: SeedOpts = {}): Promise { + db.run( + `INSERT INTO users (username, email, password_hash, status, role, signup_source, + email_verified, orcid, orcid_verified, github_username, + given_name, family_name) + VALUES (?, ?, 'x', ?, 'member', 'cli', 1, ?, ?, ?, ?, ?)`, + [ + opts.username ?? null, + email, + opts.status ?? "verified", + opts.orcid ?? null, + opts.orcidVerified ? 1 : 0, + opts.github ?? null, + opts.givenName ?? null, + opts.familyName ?? null, + ], + ); + const row = db.query<{ id: number }, [string]>("SELECT id FROM users WHERE email = ?").get(email); + if (!row) throw new Error(`seed failed for ${email}`); + if (apiKey) { + db.run("INSERT INTO tokens (user_id, api_key_hash, api_key_prefix) VALUES (?, ?, ?)", [ + row.id, + await hashApiKey(apiKey), + apiKey.slice(0, 8), + ]); + } + if (opts.identityBacked && opts.orcid) { + db.run( + "INSERT INTO oauth_identities (user_id, provider, provider_subject) VALUES (?, 'orcid', ?)", + [row.id, opts.orcid], + ); + } + return row.id; +} + +function userRow(id: number) { + return db + .query< + { + id: number; + email: string; + username: string | null; + github_username: string | null; + given_name: string | null; + family_name: string | null; + city: string | null; + country: string | null; + orcid: string | null; + orcid_verified: number; + email_verified: number; + }, + [number] + >( + `SELECT id, email, username, github_username, given_name, family_name, city, country, + orcid, orcid_verified, email_verified FROM users WHERE id = ?`, + ) + .get(id); +} + +/** A bearer-authenticated JSON call, the way the CLI makes it: no Origin. */ +function withToken( + path: string, + apiKey: string, + body: unknown, + method = "POST", + bindings: Bindings = env(), +): Promise { + return app.request( + path, + { + method, + headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify(body), + }, + bindings, + ); +} + +beforeEach(() => { + db = freshDb(); + tokenOrcid = ADA_ORCID; + missingGithubLogins = new Set(); + failingGithubLogins = new Set(); + githubCalls = 0; + app = new Hono<{ Bindings: Bindings; Variables: Variables }>(); + app.route("/auth", authOrcidRoutes); + app.route("/auth", authWebRoutes); +}); + +// --------------------------------------------------------------------------- +// Email change over a bearer token +// --------------------------------------------------------------------------- + +/** Run the whole two-step change and hand back the captured mail. */ +async function changeEmail( + apiKey: string, + newAddress: string, + bindings: Bindings, +): Promise<{ request: Response; verify: Response; mail: CapturedEmail[] }> { + return withFakeResend(async (calls) => { + const request = await withToken( + "/auth/email/change/request", + apiKey, + { email: newAddress }, + "POST", + bindings, + ); + const requestBody = (await request.clone().json()) as { dev_code?: string }; + const verify = await withToken( + "/auth/email/change/verify", + apiKey, + { email: newAddress, code: requestBody.dev_code ?? "000000" }, + "POST", + bindings, + ); + return { request, verify, mail: calls }; + }); +} + +describe("POST /auth/email/change/* with a bearer token", () => { + test("changes the address end to end and tells the OLD one", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + + const { request, verify, mail } = await changeEmail(ADA_KEY, "ada-new@nemar.test", env()); + + expect(request.status).toBe(200); + expect(verify.status).toBe(200); + const body = (await verify.json()) as { ok: boolean; old_address_notified: boolean }; + expect(body.ok).toBe(true); + expect(body.old_address_notified).toBe(true); + + const row = userRow(ada); + expect(row?.email).toBe("ada-new@nemar.test"); + // The new inbox was just proved, so the flag follows the address. + expect(row?.email_verified).toBe(1); + + // The notice goes to the address that LOST the account -- that is its + // entire job (#1054), and sending it to the new one would tell the person + // who just typed the code something they already know. + const notices = sendsTo(mail, "ada@nemar.test"); + expect(notices.length).toBe(1); + expect(notices[0].subject).toBe("Your NEMAR account email was changed"); + // Masked, because whoever reads the old inbox may not be the owner. + expect(notices[0].html).toContain("a******@nemar.test"); + expect(notices[0].html).not.toContain("ada-new@nemar.test"); + expect(notices[0].html).toContain("If this was not you"); + expect(notices[0].html).toContain("nemar.org/support"); + }); + + test("a failed notice does not fail the change", async () => { + // The change has already committed by the time the notice is attempted; + // rolling it back over an undeliverable email would be the worse outcome. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + + const result = await withFakeResend( + async (calls) => { + const request = await withToken("/auth/email/change/request", ADA_KEY, { + email: "ada-new@nemar.test", + }); + const { dev_code } = (await request.json()) as { dev_code: string }; + const verify = await withToken("/auth/email/change/verify", ADA_KEY, { + email: "ada-new@nemar.test", + code: dev_code, + }); + return { verify, calls }; + }, + // Resend refuses every send, exactly as a real outage does. + { status: 500 }, + ); + + expect(result.verify.status).toBe(200); + const body = (await result.verify.json()) as { ok: boolean; old_address_notified: boolean }; + expect(body.ok).toBe(true); + // Reported rather than hidden: the caller can say the notice did not land. + expect(body.old_address_notified).toBe(false); + expect(userRow(ada)?.email).toBe("ada-new@nemar.test"); + }); + + test("off production the notice is fenced to allow-listed addresses", async () => { + // The dev D1 carries ~609 real addresses and the dev worker holds a live + // Resend key (AGENTS.md). The old address is the one recipient in this + // flow that the caller did not choose, so the fence has to cover it. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + + const { verify, mail } = await changeEmail(ADA_KEY, "ada-new@nemar.test", env("")); + + expect(verify.status).toBe(200); + expect((await verify.json()) as { old_address_notified: boolean }).toMatchObject({ + old_address_notified: false, + }); + expect(sendsTo(mail, "ada@nemar.test")).toEqual([]); + // The change still happened; only the mail was withheld. + expect(userRow(ada)?.email).toBe("ada-new@nemar.test"); + }); + + test("refuses an address another live account holds", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + await seedUser("taken@nemar.test", null); + + const res = await withToken("/auth/email/change/request", ADA_KEY, { + email: "TAKEN@nemar.test", + }); + + expect(res.status).toBe(409); + const body = (await res.json()) as { error: string; code: string; message: string }; + expect(body.error).toBe("email_in_use"); + expect(body.code).toBe("email_in_use"); + expect(body.message).toContain("nemar.org/settings"); + // Nothing was mailed and no code exists for the target. + expect( + db + .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM auth_codes WHERE email = ?") + .get("taken@nemar.test")?.n, + ).toBe(0); + }); + + test("a code issued for one account cannot be redeemed by another's token", async () => { + // The whole point of the 0066 user_id binding, now reachable from two + // credentials: a second person holding the same inbox (or the same code) + // must not be able to attach the address to THEIR account. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const bob = await seedUser("bob@nemar.test", BOB_KEY); + + const request = await withToken("/auth/email/change/request", ADA_KEY, { + email: "shared@nemar.test", + }); + const { dev_code } = (await request.json()) as { dev_code: string }; + + const stolen = await withToken("/auth/email/change/verify", BOB_KEY, { + email: "shared@nemar.test", + code: dev_code, + }); + + expect(stolen.status).toBe(401); + expect((await stolen.json()) as { error: string }).toMatchObject({ error: "code_expired" }); + expect(userRow(bob)?.email).toBe("bob@nemar.test"); + expect(userRow(ada)?.email).toBe("ada@nemar.test"); + + // And the rightful owner's code still works afterwards. + const mine = await withFakeResend(() => + withToken("/auth/email/change/verify", ADA_KEY, { + email: "shared@nemar.test", + code: dev_code, + }), + ); + expect(mine.status).toBe(200); + expect(userRow(ada)?.email).toBe("shared@nemar.test"); + }); + + test("a wrong code is refused and the address does not move", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + await withToken("/auth/email/change/request", ADA_KEY, { email: "ada-new@nemar.test" }); + + const res = await withToken("/auth/email/change/verify", ADA_KEY, { + email: "ada-new@nemar.test", + code: "000000", + }); + + // 000000 is a valid draw, so pin the assertion to the account instead of + // to the status alone. + expect(userRow(ada)?.email).toBe("ada@nemar.test"); + if (res.status !== 200) { + expect((await res.json()) as { error: string }).toMatchObject({ error: "code_incorrect" }); + } + }); + + test("the current address is refused with a sentence, not a bare code", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + const res = await withToken("/auth/email/change/request", ADA_KEY, { email: "ada@nemar.test" }); + expect(res.status).toBe(409); + const body = (await res.json()) as { error: string; message: string }; + expect(body.error).toBe("same_email"); + expect(body.message).toContain("already the address"); + }); + + test("an unknown token is refused before anything is mailed", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + const res = await withToken("/auth/email/change/request", `${ADA_KEY}-wrong`, { + email: "ada-new@nemar.test", + }); + expect(res.status).toBe(401); + expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM auth_codes").get()?.n).toBe(0); + }); +}); + +// --------------------------------------------------------------------------- +// PATCH /auth/profile over a bearer token +// --------------------------------------------------------------------------- + +describe("PATCH /auth/profile with a bearer token", () => { + test("sets the GitHub handle, checked against GitHub", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const res = await withToken("/auth/profile", ADA_KEY, { github_username: "@octocat" }, "PATCH"); + expect(res.status).toBe(200); + // The leading "@" people paste is stripped by the shared normaliser. + expect(userRow(ada)?.github_username).toBe("octocat"); + // A changed handle IS looked up: existence is checked before it is stored. + expect(githubCalls).toBe(1); + }); + + test("refuses a GitHub handle that does not exist", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + missingGithubLogins.add("ghost-handle"); + const res = await withToken( + "/auth/profile", + ADA_KEY, + { github_username: "ghost-handle" }, + "PATCH", + ); + expect(res.status).toBe(400); + expect((await res.json()) as { error: string }).toMatchObject({ + error: "invalid_github_username", + }); + expect(userRow(ada)?.github_username).toBeNull(); + }); + + test("refuses a GitHub handle another live account holds", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + await seedUser("other@nemar.test", null, { github: "Octocat" }); + const res = await withToken("/auth/profile", ADA_KEY, { github_username: "octocat" }, "PATCH"); + expect(res.status).toBe(409); + expect((await res.json()) as { code: string }).toMatchObject({ code: "github_in_use" }); + expect(userRow(ada)?.github_username).toBeNull(); + // Refused by the pre-check, not by the index at UPDATE time: no GitHub + // call was spent. Without this the assertions above pass either way. + expect(githubCalls).toBe(0); + }); + + test("a GitHub OUTAGE is a 503, and the stored handle is untouched", async () => { + // #1052's tri-state, over both credentials. Reporting an outage as + // `invalid_github_username` tells someone their own correct handle does + // not exist and leaves them editing a field that is already right. + const ada = await seedUser("ada@nemar.test", ADA_KEY, { github: "old-handle" }); + failingGithubLogins.add("octocat"); + + const viaToken = await withToken( + "/auth/profile", + ADA_KEY, + { github_username: "octocat" }, + "PATCH", + ); + expect(viaToken.status).toBe(503); + const body = (await viaToken.json()) as { error: string; message: string }; + expect(body.error).toBe("github_unavailable"); + expect(body.message).toContain("try again"); + expect(userRow(ada)?.github_username).toBe("old-handle"); + + const { cookieIdRaw } = await issueSession(env(), ada, false, null, null, "email_code"); + const viaCookie = await app.request( + "/auth/profile", + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://nemar.org", + }, + body: JSON.stringify({ github_username: "octocat" }), + }, + env(), + ); + expect(viaCookie.status).toBe(503); + expect((await viaCookie.json()) as { error: string }).toMatchObject({ + error: "github_unavailable", + }); + expect(userRow(ada)?.github_username).toBe("old-handle"); + }); + + test("a bearer token wins when a cookie for another account is also sent", async () => { + // `resolveActingAccount` documents this order; nothing exercised it. A + // request carrying both must act for the TOKEN's account, because that is + // the credential the caller chose deliberately. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const bob = await seedUser("bob@nemar.test", BOB_KEY); + const { cookieIdRaw } = await issueSession(env(), bob, false, null, null, "email_code"); + + const res = await app.request( + "/auth/profile", + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${ADA_KEY}`, + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://nemar.org", + }, + body: JSON.stringify({ username: "alovelace" }), + }, + env(), + ); + + expect(res.status).toBe(200); + expect(userRow(ada)?.username).toBe("alovelace"); + expect(userRow(bob)?.username).toBeNull(); + }); + + test("sets a username while it is empty, and refuses one that is taken", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + await seedUser("other@nemar.test", null, { username: "Taken" }); + + const ok = await withToken("/auth/profile", ADA_KEY, { username: "alovelace" }, "PATCH"); + expect(ok.status).toBe(200); + expect(userRow(ada)?.username).toBe("alovelace"); + + const clash = await withToken("/auth/profile", ADA_KEY, { username: "taken" }, "PATCH"); + expect(clash.status).toBe(409); + expect((await clash.json()) as { error: string }).toMatchObject({ error: "username_taken" }); + expect(userRow(ada)?.username).toBe("alovelace"); + }); + + test("refuses a rename once an admin has approved the account", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY, { + username: "alovelace", + status: "approved", + }); + const res = await withToken("/auth/profile", ADA_KEY, { username: "adal" }, "PATCH"); + expect(res.status).toBe(409); + const body = (await res.json()) as { error: string; message: string }; + expect(body.error).toBe("username_locked"); + expect(body.message).toContain("contact an admin"); + expect(userRow(ada)?.username).toBe("alovelace"); + }); + + test("sets the name when no verified ORCID speaks for the account", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const res = await withToken( + "/auth/profile", + ADA_KEY, + { given_name: "Ada", family_name: "Lovelace" }, + "PATCH", + ); + expect(res.status).toBe(200); + const row = userRow(ada); + expect(row?.given_name).toBe("Ada"); + expect(row?.family_name).toBe("Lovelace"); + }); + + test("refuses a name edit while a verified ORCID iD is linked", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY, { + orcid: ADA_ORCID, + orcidVerified: true, + givenName: "Ada", + familyName: "Lovelace", + }); + const res = await withToken("/auth/profile", ADA_KEY, { given_name: "Augusta" }, "PATCH"); + expect(res.status).toBe(409); + const body = (await res.json()) as { error: string; message: string }; + expect(body.error).toBe("name_is_orcid_canonical"); + expect(body.message).toContain("orcid.org"); + expect(userRow(ada)?.given_name).toBe("Ada"); + }); + + test("sets city and country, and refuses a blank one", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const ok = await withToken( + "/auth/profile", + ADA_KEY, + { city: " San Diego ", country: "USA" }, + "PATCH", + ); + expect(ok.status).toBe(200); + const row = userRow(ada); + expect(row?.city).toBe("San Diego"); + expect(row?.country).toBe("USA"); + + const blank = await withToken("/auth/profile", ADA_KEY, { city: " " }, "PATCH"); + expect(blank.status).toBe(400); + expect((await blank.json()) as { error: string }).toMatchObject({ error: "city_required" }); + expect(userRow(ada)?.city).toBe("San Diego"); + }); + + test("a token still cannot edit somebody else's row", async () => { + // The patch is scoped by the credential, never by anything in the body. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const bob = await seedUser("bob@nemar.test", BOB_KEY); + const res = await withToken( + "/auth/profile", + BOB_KEY, + { username: "bobby", id: ada, user_id: ada }, + "PATCH", + ); + expect(res.status).toBe(200); + expect(userRow(bob)?.username).toBe("bobby"); + expect(userRow(ada)?.username).toBeNull(); + }); + + test("no credential at all is still refused", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + const res = await app.request( + "/auth/profile", + { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username: "nobody" }), + }, + env(), + ); + // No bearer and no allowed Origin: the cookie half's CSRF gate answers + // first, exactly as it did before tokens were accepted here. + expect(res.status).toBe(403); + }); +}); + +// --------------------------------------------------------------------------- +// ORCID: cli-start -> cli-handoff -> callback +// --------------------------------------------------------------------------- + +/** The `t=` token out of a cli-start response. */ +function handoffToken(authorizeUrl: string): string { + const t = new URL(authorizeUrl).searchParams.get("t"); + if (!t) throw new Error(`no state token in ${authorizeUrl}`); + return t; +} + +/** GET the interstitial, with an optional browser session cookie. */ +function openHandoff(token: string, sessionCookie?: string): Promise { + return app.request( + `/auth/orcid/cli-handoff?t=${encodeURIComponent(token)}`, + sessionCookie ? { headers: { Cookie: sessionCookie } } : {}, + env(), + ); +} + +/** POST the interstitial's confirm form, the way its own page does. */ +function continueHandoff(token: string, sessionCookie?: string): Promise { + const headers: Record = { + "Content-Type": "application/x-www-form-urlencoded", + Origin: "https://nemar.org", + }; + if (sessionCookie) headers.Cookie = sessionCookie; + return app.request( + "/auth/orcid/cli-handoff/continue", + { method: "POST", headers, body: `t=${encodeURIComponent(token)}` }, + env(), + ); +} + +/** + * Walk BOTH handoff steps the way a person does -- read the page, press the + * button -- and hand back the state cookie and the csrf. + * + * The interstitial is not a formality to skip in tests: it is the step that + * makes the intent's target account visible before ORCID sees anything, so a + * helper that jumped straight to the redirect would be testing a flow nobody + * can perform. + */ +async function walkHandoff( + token: string, + sessionCookie?: string, +): Promise<{ cookie: string; csrf: string }> { + const page = await openHandoff(token, sessionCookie); + expect(page.status).toBe(200); + const res = await continueHandoff(token, sessionCookie); + expect(res.status).toBe(302); + const setCookie = res.headers.get("Set-Cookie") ?? ""; + const cookie = setCookie.split(";")[0]; + expect(cookie.startsWith(`${STATE_COOKIE_NAME}=`)).toBe(true); + const csrf = new URL(res.headers.get("Location") ?? "https://x/").searchParams.get("state"); + if (!csrf) throw new Error("handoff redirect carried no state"); + return { cookie, csrf }; +} + +function callback(csrf: string, cookies: string[]): Promise { + return app.request( + `/auth/orcid/callback?code=orcid-code&state=${encodeURIComponent(csrf)}`, + { headers: { Cookie: cookies.join("; ") } }, + env(), + ); +} + +describe("POST /auth/orcid/cli-start", () => { + test("mints a handoff a browser with no session can complete", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + tokenOrcid = ADA_ORCID; + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + expect(started.status).toBe(200); + const body = (await started.json()) as { + authorize_url: string; + expires_in: number; + mode: string; + }; + expect(body.mode).toBe("link"); + expect(body.expires_in).toBe(600); + expect(body.authorize_url.startsWith(`${APP}/auth/orcid/cli-handoff?t=`)).toBe(true); + + const { cookie, csrf } = await walkHandoff(handoffToken(body.authorize_url)); + // No `nemar_session` cookie anywhere: this is a browser opened from a + // terminal, which is the whole reason the account rides in the state. + const res = await callback(csrf, [cookie]); + + expect(res.status).toBe(302); + expect(res.headers.get("Location")).toBe(`${APP}/settings`); + const row = userRow(ada); + expect(row?.orcid).toBe(ADA_ORCID); + expect(row?.orcid_verified).toBe(1); + expect( + db + .query<{ n: number }, [number]>( + "SELECT COUNT(*) AS n FROM oauth_identities WHERE user_id = ?", + ) + .get(ada)?.n, + ).toBe(1); + }); + + test("the interstitial names the account and does not submit itself", async () => { + // The page IS the defence a signed state cannot provide on its own: a + // bearer capability that a victim could be handed. What stops that is a + // person reading whose account it names before ORCID sees anything. + const ada = await seedUser("ada@nemar.test", ADA_KEY, { username: "alovelace" }); + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const page = await openHandoff(handoffToken(authorize_url)); + + expect(page.status).toBe(200); + expect(page.headers.get("Content-Type")).toContain("text/html"); + // NOT a redirect: nothing reaches ORCID until the person presses the + // button. + expect(page.headers.get("Location")).toBeNull(); + const html = await page.text(); + expect(html).toContain("alovelace"); + // The address is masked, like every other place NEMAR shows one back. + expect(html).toContain("a**@nemar.test"); + expect(html).not.toContain("ada@nemar.test"); + expect(html).toContain("If this is not your account, close this tab"); + expect(html).toContain('action="/auth/orcid/cli-handoff/continue"'); + // No script at all, and in particular nothing that could auto-submit the + // form and turn this page back into the redirect it replaced. + expect(html).not.toContain(" { + // Both ends of the flow, because they are minutes apart and a browser can + // sign in between them. An earlier draft let the signed intent silently + // win, which is correct about whose intent it is and wrong about what to + // do with the disagreement. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const bob = await seedUser("bob@nemar.test", BOB_KEY); + tokenOrcid = ADA_ORCID; + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const token = handoffToken(authorize_url); + const { cookieIdRaw } = await issueSession(env(), bob, false, null, null, "email_code"); + const bobSession = `nemar_session=${cookieIdRaw}`; + + const page = await openHandoff(token, bobSession); + expect(page.status).toBe(403); + const html = await page.text(); + expect(html).toContain("orcid_intent_account_mismatch"); + expect(html).toContain("sign out or open it in a browser where you are not signed in"); + + // The confirm step refuses on its own, not merely because the page did. + const posted = await continueHandoff(token, bobSession); + expect(posted.status).toBe(403); + expect(posted.headers.get("Set-Cookie")).toBeNull(); + + // And so does the callback, for a session that appeared after a clean + // handoff. + const { cookie, csrf } = await walkHandoff(token); + const res = await callback(csrf, [cookie, bobSession]); + expect(res.headers.get("Location")).toContain("error=orcid_intent_account_mismatch"); + + expect(userRow(ada)?.orcid).toBeNull(); + expect(userRow(bob)?.orcid).toBeNull(); + expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM oauth_identities").get()?.n).toBe( + 0, + ); + }); + + test("the same browser signed in as the intent's own account proceeds", async () => { + // The refusal above must be about DISAGREEMENT, not about the presence of + // a session: someone who happens to be signed in on the same account is + // exactly who the intent is for. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + tokenOrcid = ADA_ORCID; + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const { cookieIdRaw } = await issueSession(env(), ada, false, null, null, "email_code"); + const session = `nemar_session=${cookieIdRaw}`; + + const { cookie, csrf } = await walkHandoff(handoffToken(authorize_url), session); + const res = await callback(csrf, [cookie, session]); + + expect(res.status).toBe(302); + expect(userRow(ada)?.orcid).toBe(ADA_ORCID); + }); + + test("an intent is single-use: a replay links nothing", async () => { + // A signed URL sits in browser history, in a referrer, in a log. The + // signature makes it unforgeable; the nonce row (migration 0078) makes it + // unrepeatable. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + tokenOrcid = ADA_ORCID; + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const token = handoffToken(authorize_url); + const { cookie, csrf } = await walkHandoff(token); + expect((await callback(csrf, [cookie])).status).toBe(302); + expect(userRow(ada)?.orcid).toBe(ADA_ORCID); + + // Same URL, same cookie, second time. The iD would be re-linkable to this + // very account, so the assertion that bites is the refusal itself. + const replay = await callback(csrf, [cookie]); + expect(replay.headers.get("Location")).toContain("error=orcid_intent_used"); + + // And the handoff will not re-issue a cookie for a spent intent either. + const page = await openHandoff(token); + expect(page.status).toBe(410); + expect(await page.text()).toContain("orcid_intent_used"); + expect((await continueHandoff(token)).status).toBe(410); + }); + + test("cli-start accepts a session under the same-origin gate", async () => { + // The route takes either credential (authMiddleware). A cookie caller + // still has to clear the gate `POST /orcid/start` applies, and the ADR + // says so -- but nothing exercised the branch, so "it accepts a cookie" + // was an unverified claim in a comment. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const { cookieIdRaw } = await issueSession(env(), ada, false, null, null, "email_code"); + + const refused = await app.request( + "/auth/orcid/cli-start", + { + method: "POST", + headers: { + "Content-Type": "application/json", + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://evil.example.com", + }, + body: JSON.stringify({ mode: "link" }), + }, + env(), + ); + expect(refused.status).toBe(403); + + const allowed = await app.request( + "/auth/orcid/cli-start", + { + method: "POST", + headers: { + "Content-Type": "application/json", + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://nemar.org", + }, + body: JSON.stringify({ mode: "link" }), + }, + env(), + ); + expect(allowed.status).toBe(200); + const { authorize_url } = (await allowed.json()) as { authorize_url: string }; + expect(authorize_url).toContain("/auth/orcid/cli-handoff?t="); + }); + + test("503s when this deployment has no ORCID client", async () => { + // Checked at MINT time so the terminal says "unavailable" instead of the + // person discovering it at the end of a browser round trip. + await seedUser("ada@nemar.test", ADA_KEY); + const withoutOrcid = { ...env(), ORCID_CLIENT_ID: "", ORCID_CLIENT_SECRET: "" } as Bindings; + const res = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }, "POST", withoutOrcid); + expect(res.status).toBe(503); + const body = (await res.json()) as { error: string; message: string }; + expect(body.error).toBe("orcid_unavailable"); + expect(body.message).toContain("unavailable"); + // Nothing was recorded for an intent that can never be used. + expect(db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM orcid_link_intents").get()?.n).toBe( + 0, + ); + }); + + test("a tampered state links nothing", async () => { + // The user id is covered by the signature, so editing it is not an + // account swap -- it is an unreadable state. + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const bob = await seedUser("bob@nemar.test", BOB_KEY); + + const forged = await signCliState( + { csrf: "forged-csrf", mode: "link", userId: bob, next: "/settings", exp: Date.now() + 60000 }, + "not-the-worker-key", + ); + const handoff = await app.request( + `/auth/orcid/cli-handoff?t=${encodeURIComponent(forged)}`, + {}, + env(), + ); + expect(handoff.status).toBe(302); + expect(handoff.headers.get("Location")).toBe(`${APP}/login?error=orcid_state`); + expect(handoff.headers.get("Set-Cookie")).toBeNull(); + + // And presenting it straight at the callback fails the csrf compare too. + const res = await callback("forged-csrf", [`${STATE_COOKIE_NAME}=${forged}`]); + expect(res.headers.get("Location")).toContain("error=orcid_state"); + expect(userRow(ada)?.orcid).toBeNull(); + expect(userRow(bob)?.orcid).toBeNull(); + }); + + test("an expired intent is refused at the handoff", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + const stale = await signCliState( + { csrf: "stale", mode: "link", userId: 1, next: "/settings", exp: Date.now() - 1000 }, + ENCRYPTION_KEY, + ); + const res = await app.request( + `/auth/orcid/cli-handoff?t=${encodeURIComponent(stale)}`, + {}, + env(), + ); + expect(res.headers.get("Location")).toBe(`${APP}/login?error=orcid_state`); + }); + + test("relink swaps the iD; a plain link on a linked account is refused early", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY, { + orcid: ADA_ORCID, + orcidVerified: true, + identityBacked: true, + }); + + const refused = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + expect(refused.status).toBe(409); + const refusal = (await refused.json()) as { error: string; message: string }; + expect(refusal.error).toBe("orcid_already_have"); + expect(refusal.message).toContain("orcid relink"); + + tokenOrcid = BOB_ORCID; + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "relink" }); + expect(started.status).toBe(200); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const { cookie, csrf } = await walkHandoff(handoffToken(authorize_url)); + const res = await callback(csrf, [cookie]); + + expect(res.status).toBe(302); + expect(userRow(ada)?.orcid).toBe(BOB_ORCID); + const subjects = db + .query<{ provider_subject: string }, [number]>( + "SELECT provider_subject FROM oauth_identities WHERE user_id = ?", + ) + .all(ada) + .map((r) => r.provider_subject); + expect(subjects).toEqual([BOB_ORCID]); + }); + + test("refuses an iD another live account already holds", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + await seedUser("holder@nemar.test", null, { orcid: BOB_ORCID }); + tokenOrcid = BOB_ORCID; + + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const { cookie, csrf } = await walkHandoff(handoffToken(authorize_url)); + const res = await callback(csrf, [cookie]); + + expect(res.headers.get("Location")).toContain("error=orcid_in_use"); + expect(userRow(ada)?.orcid).toBeNull(); + }); + + test("an intent for a revoked account links nothing", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const started = await withToken("/auth/orcid/cli-start", ADA_KEY, { mode: "link" }); + const { authorize_url } = (await started.json()) as { authorize_url: string }; + const { cookie, csrf } = await walkHandoff(handoffToken(authorize_url)); + // Revoked between minting and finishing -- up to ten minutes apart. + db.run("UPDATE users SET status = 'revoked' WHERE id = ?", [ada]); + + const res = await callback(csrf, [cookie]); + + expect(res.headers.get("Location")).toContain("error=orcid_account"); + expect(userRow(ada)?.orcid).toBeNull(); + }); + + test("needs a credential", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + const res = await app.request( + "/auth/orcid/cli-start", + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ mode: "relink" }), + }, + env(), + ); + expect(res.status).toBe(401); + }); +}); + +describe("POST /auth/orcid/unlink with a bearer token", () => { + test("drops the identity row and the claim on the iD", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY, { + orcid: ADA_ORCID, + orcidVerified: true, + identityBacked: true, + }); + + const res = await withToken("/auth/orcid/unlink", ADA_KEY, {}); + + expect(res.status).toBe(200); + const row = userRow(ada); + expect(row?.orcid).toBeNull(); + expect(row?.orcid_verified).toBe(0); + expect( + db + .query<{ n: number }, [number]>( + "SELECT COUNT(*) AS n FROM oauth_identities WHERE user_id = ?", + ) + .get(ada)?.n, + ).toBe(0); + }); + + test("unlinks only the acting account", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY, { + orcid: ADA_ORCID, + orcidVerified: true, + identityBacked: true, + }); + await seedUser("bob@nemar.test", BOB_KEY, { + orcid: BOB_ORCID, + orcidVerified: true, + identityBacked: true, + }); + + const res = await withToken("/auth/orcid/unlink", BOB_KEY, {}); + + expect(res.status).toBe(200); + expect(userRow(ada)?.orcid).toBe(ADA_ORCID); + }); +}); + +// --------------------------------------------------------------------------- +// The cookie half is unchanged +// --------------------------------------------------------------------------- + +describe("the session path keeps its own rules", () => { + test("a cookie without an allowed Origin is still refused", async () => { + const ada = await seedUser("ada@nemar.test", ADA_KEY); + const { cookieIdRaw } = await issueSession(env(), ada, false, null, null, "email_code"); + + const res = await app.request( + "/auth/profile", + { + method: "PATCH", + headers: { + "Content-Type": "application/json", + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://evil.example.com", + }, + body: JSON.stringify({ username: "alovelace" }), + }, + env(), + ); + + expect(res.status).toBe(403); + expect(userRow(ada)?.username).toBeNull(); + }); + + test("a pending account can still change the address it typed wrong", async () => { + // `authMiddleware`'s cookie path refuses `pending` (ADR 0040); this route + // must not, because an unverified inbox is exactly what a wrong address + // produces and the change is the only way out of it. + const ada = await seedUser("ada@nemar.test", null, { status: "pending" }); + db.run("UPDATE users SET email_verified = 0 WHERE id = ?", [ada]); + const { cookieIdRaw } = await issueSession(env(), ada, false, null, null, "email_code"); + + const res = await app.request( + "/auth/email/change/request", + { + method: "POST", + headers: { + "Content-Type": "application/json", + Cookie: `nemar_session=${cookieIdRaw}`, + Origin: "https://nemar.org", + }, + body: JSON.stringify({ email: "ada-fixed@nemar.test" }), + }, + env(), + ); + + expect(res.status).toBe(200); + expect((await res.json()) as { ok: boolean }).toMatchObject({ ok: true }); + }); +}); + +// --------------------------------------------------------------------------- +// One assertion that the mail helper is really seeing sends +// --------------------------------------------------------------------------- + +describe("the change code itself", () => { + test("goes to the NEW address and nowhere else", async () => { + await seedUser("ada@nemar.test", ADA_KEY); + // Echo-eligible targets skip the send (the echo IS the delivery off + // production), so a non-synthetic target is what proves the recipient. + const mail = await withFakeResend(async (calls) => { + await withToken( + "/auth/email/change/request", + ADA_KEY, + { email: "ada-new@nemar.test" }, + "POST", + env(), + ); + return calls; + }); + // `@nemar.test` is echo-eligible, so nothing is mailed for the CODE at + // all -- which is the fence working, and is asserted so a change that + // starts mailing dev targets fails here. + expect(mail.filter((c) => c.path === "/emails").map((c) => asSend(c).subject)).toEqual([]); + }); +}); diff --git a/backend/test/orcid-link-intents-migration.test.ts b/backend/test/orcid-link-intents-migration.test.ts new file mode 100644 index 000000000..56c9e9a67 --- /dev/null +++ b/backend/test/orcid-link-intents-migration.test.ts @@ -0,0 +1,100 @@ +/** + * Migration 0078: `orcid_link_intents` (ADR 0044, PR #1269 review item A3). + * + * The route tests drive the behaviour end to end -- an intent is minted, + * walked through the interstitial, consumed by the callback, and refused on + * replay. What they cannot show is that the SCHEMA is what makes that + * enforceable rather than the application being careful: two writers racing + * the same nonce, and rows outliving the account they belong to. + * + * Real bun:sqlite with every migration applied. No mocks. + */ + +import type { Database } from "bun:sqlite"; +import { beforeEach, describe, expect, test } from "bun:test"; +import { freshDb } from "./helpers/d1"; + +let db: Database; + +function seedUser(email: string): number { + db.run( + `INSERT INTO users (username, email, password_hash, status, role, signup_source, email_verified) + VALUES (?, ?, 'x', 'verified', 'member', 'cli', 1)`, + [email.split("@")[0], email], + ); + const row = db.query<{ id: number }, [string]>("SELECT id FROM users WHERE email = ?").get(email); + if (!row) throw new Error("seed failed"); + return row.id; +} + +function insertIntent(nonce: string, userId: number): void { + db.run( + `INSERT INTO orcid_link_intents (nonce, user_id, mode, expires_at) + VALUES (?, ?, 'link', datetime('now', '+10 minutes'))`, + [nonce, userId], + ); +} + +beforeEach(() => { + db = freshDb(); +}); + +describe("orcid_link_intents", () => { + test("the nonce is a primary key, so an intent cannot be duplicated", () => { + // Consume-once is a conditional UPDATE on this key. If two rows could + // carry the same nonce, the second would still be unconsumed after the + // first was spent -- and the replay the callback refuses would work. + const ada = seedUser("ada@nemar.test"); + insertIntent("nonce-one", ada); + expect(() => insertIntent("nonce-one", ada)).toThrow(); + expect( + db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM orcid_link_intents").get()?.n, + ).toBe(1); + }); + + test("a consumed intent stays consumed for a second UPDATE", () => { + // The exact statement the callback runs: `changes` is what decides the + // race, so the second attempt must report zero rather than re-stamping. + const ada = seedUser("ada@nemar.test"); + insertIntent("nonce-two", ada); + const sql = `UPDATE orcid_link_intents SET consumed_at = datetime('now') + WHERE nonce = ? AND user_id = ? AND consumed_at IS NULL + AND expires_at > datetime('now')`; + expect(db.run(sql, ["nonce-two", ada]).changes).toBe(1); + expect(db.run(sql, ["nonce-two", ada]).changes).toBe(0); + }); + + test("an expired intent is not consumable and prunes away", () => { + const ada = seedUser("ada@nemar.test"); + db.run( + `INSERT INTO orcid_link_intents (nonce, user_id, mode, expires_at) + VALUES ('stale', ?, 'link', datetime('now', '-1 minute'))`, + [ada], + ); + const consumed = db.run( + `UPDATE orcid_link_intents SET consumed_at = datetime('now') + WHERE nonce = 'stale' AND consumed_at IS NULL AND expires_at > datetime('now')`, + ); + expect(consumed.changes).toBe(0); + // The prune `cli-start` runs on every mint, which is why this table needs + // no cron. + db.run("DELETE FROM orcid_link_intents WHERE expires_at < datetime('now')"); + expect( + db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM orcid_link_intents").get()?.n, + ).toBe(0); + }); + + test("intents go with the account they belong to", () => { + // ON DELETE CASCADE, so a deleted account leaves no live intent naming an + // id that no longer resolves. Foreign keys are off by default in SQLite, + // so this asserts the DECLARATION does its job when they are on -- which + // is how D1 runs. + const ada = seedUser("ada@nemar.test"); + db.run("PRAGMA foreign_keys = ON"); + insertIntent("nonce-three", ada); + db.run("DELETE FROM users WHERE id = ?", [ada]); + expect( + db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM orcid_link_intents").get()?.n, + ).toBe(0); + }); +}); diff --git a/backend/test/rate-limit-buckets.test.ts b/backend/test/rate-limit-buckets.test.ts index 0d4225965..588bf9210 100644 --- a/backend/test/rate-limit-buckets.test.ts +++ b/backend/test/rate-limit-buckets.test.ts @@ -159,6 +159,33 @@ describe("__selectBucket", () => { } }); + test("the CLI ORCID surface is in the strict bucket; the callback is not", () => { + // #1266, ADR 0044. All three are bearer-reachable now, so without their + // AUTH_PATHS entries a token would put them in the 1000/min bucket -- on + // an identity-link mint, on the step that turns a leaked intent into an + // ORCID redirect, and on the unlink. /continue is asserted separately + // because it relies on the matcher's prefix behaviour. + for (const path of [ + "/auth/orcid/cli-start", + "/auth/orcid/cli-handoff", + "/auth/orcid/cli-handoff/continue", + "/auth/orcid/unlink", + ]) { + const sel = __selectBucket(path, `Bearer ${VALID_TOKEN}`, "10.0.0.1"); + expect(sel.keyKind).toBe("auth-ip"); + expect(sel.rawKey).toBe("10.0.0.1"); + expect(sel.maxRequests).toBe(__limits.AUTH_MAX_REQUESTS); + } + }); + + test("the ORCID callback stays OUT of the strict bucket", () => { + // A browser landing on a shared egress IP, and the one ORCID path a + // careless prefix entry ("/auth/orcid") would drag to 10/min -- which + // would rate-limit the website's own sign-in flow, not the CLI's. + const sel = __selectBucket("/auth/orcid/callback?code=x&state=y", undefined, "10.0.0.1"); + expect(sel.keyKind).not.toBe("auth-ip"); + }); + test("the rest of /users keeps the ordinary token bucket", () => { // The AUTH_PATHS matcher is a prefix match, so an over-broad entry // ("/users") would drag the dashboard's own polling into a 10/min cap. diff --git a/shared/contract/identity.ts b/shared/contract/identity.ts index 8f8f7beb2..570b81190 100644 --- a/shared/contract/identity.ts +++ b/shared/contract/identity.ts @@ -49,6 +49,11 @@ export const identityConflictCodeSchema = z.enum([ ]); export type IdentityConflictCode = z.infer; +/** The refusal codes as a plain array, for a runtime membership test. The CLI + * client uses it to decide whether a body's `error` is a machine code whose + * human half rides in `message` (#1266, ADR 0044). */ +export const IDENTITY_CONFLICT_CODES: readonly string[] = identityConflictCodeSchema.options; + /** Where a person changes each identifier once they are signed in. */ export const IDENTITY_SETTINGS_URL = "https://nemar.org/settings"; diff --git a/shared/contract/user.ts b/shared/contract/user.ts index 3dc8522f9..75269da63 100644 --- a/shared/contract/user.ts +++ b/shared/contract/user.ts @@ -227,6 +227,61 @@ export type UploadAccessErrorCode = z.infer; * client uses it to decide whether a body leads with `message`). */ export const UPLOAD_ACCESS_ERROR_CODES: readonly string[] = uploadAccessErrorCodeSchema.options; +/** + * Why a self-service identity edit was refused (#1266, ADR 0044). + * + * `PATCH /auth/profile`, `POST /auth/email/change/{request,verify}` and + * `POST /auth/orcid/cli-start` all answer a refusal with a machine CODE in + * `error` and the sentence in `message` — the shape the website's Settings + * form has always switched on. That shape is unreadable in a terminal, where + * `error` is what the CLI prints, so the client needs to know which strings + * are codes rather than sentences. Declaring the set here means the routes + * and the renderer cannot drift; the same reason + * {@link uploadAccessErrorCodeSchema} lives here. + * + * The identity-uniqueness codes (`email_in_use`, `github_in_use`, + * `orcid_in_use`, ...) are NOT repeated here — they are declared once in + * shared/contract/identity.ts and the CLI checks both sets. + * + * Enforced on the backend side, not merely documented: every refusal in this + * vocabulary is built by `profileRefusal(code, message)` (backend + * services/profile.ts), whose parameter is this union, so an undeclared code + * is a compile error at the call site rather than a bare token printed at a + * person. The codes `normalizeProfilePatch` returns are additionally pinned by + * `_profileErrorsAreDeclared` in the same module. + */ +export const profileEditErrorCodeSchema = z.enum([ + // normalizeProfilePatch (services/profile.ts) + "invalid_github_username", + "city_required", + "country_required", + "empty_patch", + "username_too_short", + "username_too_long", + "username_charset", + "given_name_required", + "family_name_required", + // PATCH /auth/profile, decided against the account rather than the value + "username_taken", + "username_locked", + "name_is_orcid_canonical", + "account_revoked", + "github_unavailable", + // email change + "same_email", + "code_expired", + "code_incorrect", + // ORCID link intent + "orcid_already_have", + "orcid_unavailable", +]); +export type ProfileEditErrorCode = z.infer; + +/** The profile-edit refusal codes as a plain array, for a runtime membership + * test (the CLI client uses it to decide whether a body leads with + * `message`). */ +export const PROFILE_EDIT_ERROR_CODES: readonly string[] = profileEditErrorCodeSchema.options; + /** * Bounds on the upload request's why text (ADR 0042, #1253). * diff --git a/src/commands/auth.ts b/src/commands/auth.ts index 4abd35cef..b5bdfebae 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -17,7 +17,7 @@ */ import chalk from "chalk"; -import { Command } from "commander"; +import { Command, InvalidArgumentError } from "commander"; import inquirer from "inquirer"; import ora from "ora"; import { @@ -26,28 +26,37 @@ import { } from "../../shared/contract/user.js"; import { type OrcidNameResponse, + type ProfilePatchRequest, type UploadAccessRequestResponse, checkGitHubUsername, checkOrcidName, checkUsername, getCurrentUser, login, + requestEmailChange, requestKeyRegeneration, requestUploadAccess, resendVerification, retrieveKey, signup, + startOrcidCliLink, + unlinkOrcid, + updateProfile, + verifyEmailChange, } from "../lib/api/auth.js"; import { ApiError, MaintenanceError, errorDetail } from "../lib/api/errors.js"; +import { openInBrowser } from "../lib/browser.js"; import { printStepFailure } from "../lib/cli-output.js"; import { DEFAULT_API_URL, clearAllConfig, clearConfig, + deleteConfig, getAccounts, getConfig, getConfigPath, isAuthenticated, + renameActiveAccount, setConfig, storeAccount, switchAccount, @@ -1281,12 +1290,14 @@ Examples: */ const UPLOAD_ACCESS_FIX: Record = { email_verified: "run 'nemar auth resend-verification' and click the link in your inbox", - username: "set it in Settings on nemar.org", - given_name: "comes from your ORCID record; make it public at orcid.org, or set it in Settings", - family_name: "comes from your ORCID record; make it public at orcid.org, or set it in Settings", - github_username: "set it in Settings on nemar.org", - city: "set it in Settings on nemar.org", - country: "set it in Settings on nemar.org", + username: "run 'nemar auth profile set-username '", + given_name: + "comes from your ORCID record when one is linked; otherwise 'nemar auth profile set-name --given '", + family_name: + "comes from your ORCID record when one is linked; otherwise 'nemar auth profile set-name --family '", + github_username: "run 'nemar auth profile set-github '", + city: "run 'nemar auth profile set-location --city '", + country: "run 'nemar auth profile set-location --country '", why: "pass a longer --why, or answer the prompt", }; @@ -1454,9 +1465,9 @@ function verifiedMark(flag: boolean | undefined): string { * The footer is the load-bearing half. Identity uniqueness means a duplicate * account is refused rather than created (ADR 0043), so the message a person * hits is "that iD already belongs to an account" -- and the only useful next - * sentence is where to go and change it. Email, GitHub and ORCID are all - * self-service in Settings today; username and name are not, and saying so is - * better than leaving someone hunting for a field that does not exist. + * sentence is where to go and change it. Since #1266 every one of them is + * self-service from here as well as from Settings, so the footer names the + * command rather than a page the person then has to find. */ export async function profileAction(): Promise { if (!isAuthenticated()) { @@ -1515,14 +1526,24 @@ export async function profileAction(): Promise { console.log(); console.log(chalk.bold("Where to change each")); + console.log(` Email ${chalk.cyan("nemar auth profile set-email
")}`); + console.log(` Username ${chalk.cyan("nemar auth profile set-username ")}`); console.log( - ` Email, GitHub, ORCID ${chalk.cyan("https://nemar.org/settings")} ${chalk.dim( - "(sign in, then Settings)", - )}`, + ` Name ${chalk.cyan("nemar auth profile set-name --given --family ")}`, ); - console.log(` Username, name ${chalk.dim("not editable yet (nemarOrg/website#301)")}`); + console.log(` GitHub ${chalk.cyan("nemar auth profile set-github ")}`); + console.log(` ORCID ${chalk.cyan("nemar auth profile orcid link|relink|unlink")}`); console.log( - ` Upload access ${chalk.dim("one-time admin approval; see https://nemar.org/support")}`, + ` Location ${chalk.cyan("nemar auth profile set-location --city --country ")}`, + ); + console.log( + ` Upload access ${chalk.dim("one-time admin approval; nemar auth request-upload-access")}`, + ); + console.log(); + console.log( + chalk.dim( + " Every one of these is also in Settings on https://nemar.org/settings — same rules, same checks.", + ), ); console.log(); console.log( @@ -1554,6 +1575,651 @@ Description: than creating a duplicate; the fix is to change the identifier on the account that already holds it. +Subcommands (the same changes Settings on nemar.org makes): + set-email
mail a code to a new address, then verify-email + verify-email finish the change + set-username set your NEMAR handle (locked once approved) + set-name --given / --family (ORCID wins when a verified iD is linked) + set-github set the GitHub username (checked against GitHub) + set-location --city / --country + orcid link|relink|unlink opens a browser for ORCID's consent screen + +Examples: + $ nemar auth profile + $ nemar auth profile set-email ada@lab.example.org + $ nemar auth profile orcid link`, +); + +// ============================================================================ +// Profile self-service subcommands (#1266, epic #1250; ADR 0044) +// ============================================================================ +// +// The identifiers a person can fix themselves, from the terminal, with the +// same verification the website does: an email change is still proved by a +// code mailed to the NEW address, an ORCID link is still an ORCID consent +// screen in a browser, and every rule and refusal is the backend's, not a +// second copy living here. + +/** Where the same change can be made in a browser. Printed by every + * subcommand, because the CLI is the second surface, not the only one. */ +const SETTINGS_HINT = "Also changeable in Settings on https://nemar.org/settings"; + +/** + * Guard every subcommand: an action must not print a spinner for a request + * that was never going to be sent, and must exit non-zero (`nemar auth + * profile` itself is a query and exits 0). + */ +function requireAuthenticatedForChange(): boolean { + if (isAuthenticated()) return true; + console.log(chalk.yellow("Not authenticated")); + console.log(); + console.log(" Run 'nemar auth login' to authenticate"); + process.exitCode = 1; + return false; +} + +/** + * Re-read the account from the server and update the local config cache. + * + * Called after every successful change so `nemar auth status` stops showing + * the value that was just replaced. A failure here is NOT a failure of the + * change -- the change has landed on the server -- so it is reported as a + * dim note and the command still exits 0. + */ +async function refreshStoredAccount(): Promise { + try { + const user = await getCurrentUser(); + // The accounts map is KEYED by username, so a rename has to move the key + // as well as the field, or `nemar auth switch ` cannot find the + // account it just renamed (#1266 review). Done first: the writes below + // target the active account, and this is what decides which one that is. + // + // It declines to overwrite a DIFFERENT stored account holding that key, + // which leaves this machine with an account whose stored name and lookup + // key disagree. Silence there is the trap: `nemar auth switch ` + // would then select the other account, and nothing would have said why. + if (user.username && renameActiveAccount(user.username) === "key_taken") { + console.log( + chalk.yellow( + ` This machine already has a different account stored as '${user.username}'.`, + ), + ); + console.log( + chalk.dim( + " Your credentials stay under the old name; 'nemar auth switch' still selects that one.", + ), + ); + } + setConfig("username", user.username ?? undefined); + setConfig("email", user.email); + setConfig("githubUsername", user.github_username ?? undefined); + if (user.service_access !== undefined) setConfig("serviceAccess", user.service_access); + setConfig("role", user.role); + } catch (error) { + console.log( + chalk.dim( + ` (local copy not refreshed: ${errorDetail(error)} — run 'nemar auth status --refresh')`, + ), + ); + } +} + +/** + * Apply a local config write that must not be mistaken for the network call + * that preceded it (#1266 review item 5). + * + * The server has already changed something by the time these run -- the email + * has moved and the code is spent -- so a failed `conf` write is a stale local + * copy, not a failed change. Inside the request's own try/catch it printed + * "Could not confirm the new address" for a change that had in fact landed, + * which is the one sentence that sends a person to re-request a code they no + * longer need. + */ +function updateLocalConfig(apply: () => void): void { + try { + apply(); + } catch (error) { + console.log( + chalk.yellow( + ` The change is live on the server; your local config could not be updated: ${errorDetail(error)}`, + ), + ); + console.log(chalk.dim(" Run 'nemar auth status --refresh' once the problem is fixed.")); + } +} + +/** + * Fail a subcommand with the backend's own sentence. + * + * Every refusal these routes raise carries a machine code in `error` and the + * actionable sentence in `message`, and lib/api/client.ts already prefers the + * sentence for the declared code vocabularies (shared/contract). So there is + * nothing to map here: printing `error.message` IS printing the backend's + * wording, which is the point -- a second copy in the CLI is how the two + * surfaces start telling people different things. + */ +function failWithApiError(spinner: ReturnType, error: unknown, fallback: string): void { + if (error instanceof ApiError || error instanceof MaintenanceError) { + spinner.fail(error.message); + } else { + spinner.fail(fallback); + console.log(chalk.dim(` ${errorDetail(error)}`)); + } + process.exitCode = 1; +} + +/** Apply a `PATCH /auth/profile` patch and report it uniformly. */ +async function applyProfilePatch( + patch: ProfilePatchRequest, + pending: string, + succeeded: string, +): Promise { + if (!requireAuthenticatedForChange()) return; + const spinner = ora(pending).start(); + try { + await updateProfile(patch); + spinner.succeed(succeeded); + await refreshStoredAccount(); + console.log(chalk.dim(` ${SETTINGS_HINT}`)); + } catch (error) { + failWithApiError(spinner, error, "Could not update your profile"); + } +} + +// ---------------------------------------------------------------- set-email + +const profileSetEmailCmd = profileCmd + .command("set-email
") + .description("Start an email change: mails a confirmation code to the new address") + .action(async (address: string) => { + if (!requireAuthenticatedForChange()) return; + const spinner = ora(`Sending a confirmation code to ${address}...`).start(); + let result: Awaited>; + try { + result = await requestEmailChange(address); + } catch (error) { + failWithApiError(spinner, error, "Could not send the confirmation code"); + return; + } + + // Past this point the code IS in the person's inbox, so nothing below may + // report a failure of the request. The local write gets its own guarded + // step for exactly that reason (#1266 review). + spinner.succeed(`Code sent to ${result.masked_email}`); + updateLocalConfig(() => setConfig("pendingEmailChange", address)); + + console.log(); + console.log(" The address is not changed until you confirm the code:"); + console.log(` ${chalk.cyan("nemar auth profile verify-email ")}`); + console.log(chalk.dim(" The code expires in 10 minutes.")); + if (result.dev_code) { + console.log(chalk.dim(` (development backend echoed the code: ${result.dev_code})`)); + } + if (result.dev_skip) { + console.log( + chalk.yellow( + " This backend is non-production and did not mail anything (delivery allow-list).", + ), + ); + } + console.log(chalk.dim(` ${SETTINGS_HINT}`)); + }); + +addVerboseHelp( + profileSetEmailCmd, + ` +Description: + Step one of changing the email address your NEMAR account signs in with. + A 6-digit code goes to the NEW address; nothing changes until you enter it + with 'nemar auth profile verify-email'. The old address is told once the + change lands, so a change you did not make is visible to you. + + An address that already belongs to a NEMAR account is refused: one person, + one account. Change it on the account that holds it instead. + + Your API key keeps working across the change -- it is tied to the account, + not to the address. + +Examples: + $ nemar auth profile set-email ada@lab.example.org + $ nemar auth profile verify-email 123456`, +); + +// ------------------------------------------------------------- verify-email + +const profileVerifyEmailCmd = profileCmd + .command("verify-email ") + .description("Finish an email change with the code sent to the new address") + .option("--email
", "The address the code was sent to (defaults to the last requested)") + .action(async (code: string, options: { email?: string }) => { + if (!requireAuthenticatedForChange()) return; + const address = (options.email ?? getConfig().pendingEmailChange ?? "").trim(); + if (!address) { + // No stored request: a code alone cannot say which address it proves. + console.log(chalk.yellow("No pending email change on this machine")); + console.log(); + console.log(" Run 'nemar auth profile set-email
' first,"); + console.log(" or pass the address with --email
."); + process.exitCode = 1; + return; + } + + const spinner = ora(`Confirming ${address}...`).start(); + let result: Awaited>; + try { + result = await verifyEmailChange(address, code); + } catch (error) { + failWithApiError(spinner, error, "Could not confirm the new address"); + return; + } + + // The address HAS moved and the code is spent, so success is reported + // before anything local is touched: a `conf` write failure here used to + // print "Could not confirm the new address" for a change that had landed + // (#1266 review). + spinner.succeed(`Account email is now ${address}`); + // Written from the address we just proved rather than from the refresh + // below: a refresh that fails must not leave the old address cached as if + // nothing had happened. + updateLocalConfig(() => { + setConfig("email", address); + deleteConfig("pendingEmailChange"); + }); + if (result.old_address_notified === false) { + console.log( + chalk.yellow(" The previous address could not be notified; the change still applied."), + ); + } + await refreshStoredAccount(); + console.log(chalk.dim(" Sign-in codes and NEMAR mail now go to the new address.")); + }); + +addVerboseHelp( + profileVerifyEmailCmd, + ` +Description: + Step two of an email change. The code is bound to BOTH the new address and + your account, so a code from someone else's request cannot be redeemed here, + and five wrong guesses invalidate it -- request a new one with + 'nemar auth profile set-email'. + + The address is remembered from the set-email step; pass --email if you are + finishing a change started on another machine. + +Examples: + $ nemar auth profile verify-email 123456 + $ nemar auth profile verify-email 123456 --email ada@lab.example.org`, +); + +// -------------------------------------------------------------- set-github + +const profileSetGithubCmd = profileCmd + .command("set-github ") + .description("Set the GitHub username on your account") + .action(async (handle: string) => { + await applyProfilePatch( + { github_username: handle }, + `Checking GitHub for ${handle}...`, + `GitHub username set to ${handle}`, + ); + }); + +addVerboseHelp( + profileSetGithubCmd, + ` +Description: + Sets the GitHub username your dataset repositories are shared with. The + handle must EXIST on GitHub -- it is looked up before it is stored -- and it + may back only one NEMAR account. + + Ownership is not proved here: what matters for a review is that the account + an admin will add as a collaborator resolves. + +Examples: + $ nemar auth profile set-github octocat`, +); + +// ------------------------------------------------------------ set-username + +const profileSetUsernameCmd = profileCmd + .command("set-username ") + .description("Set your NEMAR username (locked once an admin approves the account)") + .action(async (name: string) => { + await applyProfilePatch( + { username: name }, + `Setting your username to ${name}...`, + `Username set to ${name}`, + ); + }); + +addVerboseHelp( + profileSetUsernameCmd, + ` +Description: + Your NEMAR handle: what 'nemar admin approve ' addresses and what + the dataset repositories you own are attributed to. + + It can be set while it is empty at any time, and CHANGED until an admin + approves your account -- after that a rename needs an admin, because other + records already point at it. + +Examples: + $ nemar auth profile set-username alovelace`, +); + +// ---------------------------------------------------------------- set-name + +const profileSetNameCmd = profileCmd + .command("set-name") + .description("Set the given and family name your DOIs cite") + .option("--given ", "Given (first) name") + .option("--family ", "Family (last) name") + .action(async (options: { given?: string; family?: string }) => { + if (options.given === undefined && options.family === undefined) { + console.log(chalk.yellow("Nothing to set")); + console.log(); + console.log(" Pass --given and/or --family, e.g."); + console.log(" nemar auth profile set-name --given Ada --family Lovelace"); + process.exitCode = 1; + return; + } + const patch: ProfilePatchRequest = {}; + if (options.given !== undefined) patch.given_name = options.given; + if (options.family !== undefined) patch.family_name = options.family; + await applyProfilePatch(patch, "Setting your name...", "Name updated"); + }); + +addVerboseHelp( + profileSetNameCmd, + ` +Description: + The name a DOI cites you by. Both halves are required before a dataset can + be published, which is why this is settable at all. + + It is refused while a VERIFIED ORCID iD is linked: ORCID is canonical there + and its record is re-read on every sign-in, so an edit here would be + silently overwritten. Change it at orcid.org and sign in again, or unlink + the iD first. + +Examples: + $ nemar auth profile set-name --given Ada --family Lovelace`, +); + +// ------------------------------------------------------------ set-location + +const profileSetLocationCmd = profileCmd + .command("set-location") + .description("Set the city and country on your account") + .option("--city ", "City") + .option("--country ", "Country") + .action(async (options: { city?: string; country?: string }) => { + if (options.city === undefined && options.country === undefined) { + console.log(chalk.yellow("Nothing to set")); + console.log(); + console.log(" Pass --city and/or --country, e.g."); + console.log(" nemar auth profile set-location --city 'San Diego' --country USA"); + process.exitCode = 1; + return; + } + const patch: ProfilePatchRequest = {}; + if (options.city !== undefined) patch.city = options.city; + if (options.country !== undefined) patch.country = options.country; + await applyProfilePatch(patch, "Setting your location...", "Location updated"); + }); + +addVerboseHelp( + profileSetLocationCmd, + ` +Description: + City and country are required for the export-control screening an admin + does before granting upload access, so an upload-access request is refused + without them. Neither may be blank. + +Examples: + $ nemar auth profile set-location --city "San Diego" --country USA`, +); + +// ------------------------------------------------------------------- orcid + +/** How often the link flow re-checks whether the iD has landed. */ +const ORCID_POLL_INTERVAL_MS = 3000; + +/** + * Wait for a browser-side ORCID link to finish, or give up. + * + * The link is completed by the ORCID callback in the browser, so there is + * nothing for the CLI to await except the account itself changing. Polling + * `/users/me` is that: for a link, an iD appearing; for a relink, a DIFFERENT + * iD appearing, which is why the previous value is passed in rather than + * re-read (a relink to the same account keeps `orcid` non-null throughout, + * so "non-null" would report success the instant it started). + * + * A transient failure mid-wait is ignored on purpose -- the browser flow is + * unaffected by our polling, and the timeout is the only thing that ends the + * wait unhappily. + */ +/** + * Consecutive unreachable polls before the wait is abandoned. Three at the + * three-second interval is roughly ten seconds of silence -- long enough to + * ride out one dropped request, short enough not to spend five minutes + * pretending to wait for a browser flow that cannot report back. + */ +const ORCID_POLL_MAX_NETWORK_FAILURES = 3; + +/** + * Why a wait ended. `timeout` is the ordinary "they walked away" case; the + * other two are conditions that will not improve by waiting longer, and each + * has a different thing for the person to do (#1266 review item 7). + */ +type OrcidWaitOutcome = + | { kind: "linked"; orcid: string } + | { kind: "timeout" } + | { kind: "unauthenticated" } + | { kind: "unreachable"; detail: string }; + +async function waitForOrcidLink( + previousOrcid: string | null, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + let networkFailures = 0; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, ORCID_POLL_INTERVAL_MS)); + try { + const user = await getCurrentUser(); + networkFailures = 0; + const current = user.orcid ?? null; + if (current && current !== previousOrcid) return { kind: "linked", orcid: current }; + } catch (error) { + // A 401 is not a transient poll failure: the key this command is holding + // has been revoked or regenerated, and no amount of waiting fixes it. + // Burning the full timeout on it ends in "gave up waiting", which sends + // the person to look at their browser rather than at their credentials. + if (error instanceof ApiError && error.statusCode === 401) { + return { kind: "unauthenticated" }; + } + // statusCode 0 is this codebase's convention for a network-layer + // failure (lib/api/client.ts). One is noise; several in a row means the + // API is not reachable from here, and the browser flow's result is + // unknowable until it is. + if (error instanceof ApiError && error.statusCode === 0) { + networkFailures += 1; + if (networkFailures >= ORCID_POLL_MAX_NETWORK_FAILURES) { + return { kind: "unreachable", detail: errorDetail(error) }; + } + } else { + // Anything else (a 5xx, a contract drift) is treated as transient: + // it says nothing about the browser flow, which is what we are + // actually waiting on. + networkFailures = 0; + } + } + } + return { kind: "timeout" }; +} + +/** + * Parse `--timeout` at the ARGUMENT boundary, so a bad value is a usage error + * (#1266 review item 9). + * + * It used to fall back to 300 silently, which is the worst of both: a typo + * (`--timeout 5m`) was accepted and then ignored, and the person watched a + * five-minute wait they thought they had shortened. Commander turns an + * InvalidArgumentError into its own usage failure with a non-zero exit. + */ +export function parseOrcidTimeout(raw: string): number { + const seconds = Number(raw); + if (!Number.isFinite(seconds) || !Number.isInteger(seconds) || seconds <= 0) { + throw new InvalidArgumentError("--timeout must be a whole number of seconds greater than 0"); + } + return seconds; +} + +const profileOrcidCmd = profileCmd + .command("orcid ") + .description("Link, re-link, or unlink your ORCID iD (link opens a browser)") + .option("--no-open", "Print the URL instead of opening a browser") + .option( + "--timeout ", + "How long to wait for the browser flow to finish", + parseOrcidTimeout, + 300, + ) + .option("-y, --yes", "Skip the confirmation prompt (unlink)") + .option("-n, --no", "Decline the confirmation prompt (unlink)") + .action( + async ( + action: string, + options: { open?: boolean; timeout?: number; yes?: boolean; no?: boolean }, + ) => { + if (action !== "link" && action !== "relink" && action !== "unlink") { + console.log(chalk.yellow(`Unknown action '${action}'`)); + console.log(); + console.log(" Use one of: link, relink, unlink"); + process.exitCode = 1; + return; + } + if (!requireAuthenticatedForChange()) return; + + if (action === "unlink") { + const result = await confirm( + "Unlink your ORCID iD from this NEMAR account?", + { yes: options.yes, no: options.no }, + false, + ); + if (result !== "confirmed") { + console.log(result === "declined" ? "Declined" : "Cancelled"); + return; + } + const spinner = ora("Unlinking your ORCID iD...").start(); + try { + await unlinkOrcid(); + spinner.succeed("ORCID iD unlinked"); + console.log( + chalk.dim( + " Your account no longer claims that iD. Link it again any time with 'nemar auth profile orcid link'.", + ), + ); + await refreshStoredAccount(); + } catch (error) { + failWithApiError(spinner, error, "Could not unlink your ORCID iD"); + } + return; + } + + // link / relink: ORCID's consent screen is a browser page, so the CLI's + // job is to get the person in front of it and then wait for the account + // to change. + const spinner = ora("Preparing the ORCID sign-in link...").start(); + let authorizeUrl: string; + let previousOrcid: string | null = null; + try { + // Read the current iD FIRST: a relink is only observable as a change + // from this value. + previousOrcid = (await getCurrentUser()).orcid ?? null; + const started = await startOrcidCliLink(action); + authorizeUrl = started.authorize_url; + spinner.stop(); + } catch (error) { + failWithApiError(spinner, error, "Could not start the ORCID flow"); + return; + } + + console.log(); + console.log(" Open this link and sign in with ORCID:"); + console.log(` ${chalk.cyan(authorizeUrl)}`); + console.log(chalk.dim(" The link is good for 10 minutes and works only for this account.")); + if (options.open !== false && openInBrowser(authorizeUrl)) { + // "Trying", not "opened": the spawn returns before the child can fail, + // so this is a claim about what was attempted (#1266 review item 8). + console.log(chalk.dim(" (trying to open your browser; use the link above if it doesn't)")); + } + console.log(); + + // Already validated by parseOrcidTimeout at the argument boundary. + const timeoutSeconds = options.timeout ?? 300; + const waitSpinner = ora("Waiting for you to finish in the browser...").start(); + const outcome = await waitForOrcidLink(previousOrcid, timeoutSeconds * 1000); + if (outcome.kind === "linked") { + waitSpinner.succeed(`ORCID iD ${outcome.orcid} is linked to your account`); + await refreshStoredAccount(); + console.log(chalk.dim(` ${SETTINGS_HINT}`)); + return; + } + if (outcome.kind === "unauthenticated") { + waitSpinner.fail("Your credentials no longer authenticate"); + console.log(); + console.log(" Run 'nemar auth login' with a current API key, then try again."); + console.log( + chalk.dim(" If you finished the browser step, the link may still have been made."), + ); + process.exitCode = 1; + return; + } + if (outcome.kind === "unreachable") { + waitSpinner.fail(`Cannot reach the API: ${outcome.detail}`); + console.log(); + console.log(" The browser step may still have worked; check with 'nemar auth profile'."); + process.exitCode = 1; + return; + } + waitSpinner.warn("Gave up waiting for the browser flow"); + console.log(); + console.log(" If you finished it, check with 'nemar auth profile'."); + console.log(" If the browser showed an error, run this command again."); + process.exitCode = 1; + }, + ); + +addVerboseHelp( + profileOrcidCmd, + ` +Description: + ORCID stays a browser flow: the consent screen is ORCID's, and no NEMAR + command should ever ask for an ORCID password. This mints a short-lived link + for THIS account, opens it if it can, and then waits for the iD to appear. + + link attach an ORCID iD to an account that has none + relink replace the linked iD with a different one + unlink remove the link (and the iD this account claims) + + An iD backs at most one NEMAR account. If it is already linked elsewhere, + unlink it there first. + + The link URL is printed whether or not a browser opens, so a headless or + remote machine is a copy-and-paste rather than a dead end. Pass --no-open, + or set NEMAR_NO_BROWSER=1, to stop the CLI reaching for a browser at all. + + Opening the link shows a NEMAR page naming the account it will link to + before it sends you to ORCID. If that account is not yours, close the tab: + the link was made by somebody else and would attach YOUR iD to THEIR + account. A link can only be used once. + + --timeout is a whole number of seconds (default 300); the wait stops early + if your credentials stop working or the API becomes unreachable. + Examples: - $ nemar auth profile`, + $ nemar auth profile orcid link + $ nemar auth profile orcid relink --no-open + $ nemar auth profile orcid unlink --yes`, ); diff --git a/src/lib/api/auth.ts b/src/lib/api/auth.ts index 00c68fa4e..5f8ae1bb3 100644 --- a/src/lib/api/auth.ts +++ b/src/lib/api/auth.ts @@ -303,3 +303,120 @@ export async function requestUploadAccess(why: string): Promise { + return request( + "/auth/email/change/request", + { + method: "POST", + body: JSON.stringify({ email }), + }, + true, + ); +} + +export interface EmailChangeVerifyResponse { + ok: true; + /** + * Whether the PREVIOUS address was told the account email moved (#1054). + * `false` is not a failure of the change -- the change has landed either + * way -- but it is worth saying out loud, because the notice is the only + * thing that would reach a legitimate owner if this were not them. + * Optional: a backend deployed before #1266 does not send it. + */ + old_address_notified?: boolean; +} + +/** Step 2: redeem the code and move `users.email`. */ +export async function verifyEmailChange( + email: string, + code: string, +): Promise { + return request( + "/auth/email/change/verify", + { + method: "POST", + body: JSON.stringify({ email, code }), + }, + true, + ); +} + +/** Any subset of the self-editable profile fields; absent keys are untouched. */ +export interface ProfilePatchRequest { + github_username?: string; + username?: string; + given_name?: string; + family_name?: string; + city?: string; + country?: string; + affiliation?: string; +} + +export interface ProfileUpdateResponse { + ok: true; +} + +/** Edit the account's own profile fields (`PATCH /auth/profile`). */ +export async function updateProfile(patch: ProfilePatchRequest): Promise { + return request( + "/auth/profile", + { + method: "PATCH", + body: JSON.stringify(patch), + }, + true, + ); +} + +export interface OrcidCliStartResponse { + /** Open this in a browser; it sets the state cookie and bounces to ORCID. */ + authorize_url: string; + /** Seconds the intent stays usable. */ + expires_in: number; + mode: "link" | "relink"; +} + +/** + * Mint a browser-openable ORCID link (or relink) intent for this account. + * ORCID cannot be completed in a terminal — this is the handoff, and the + * callback finishes the link for the account the intent names. + */ +export async function startOrcidCliLink(mode: "link" | "relink"): Promise { + return request( + "/auth/orcid/cli-start", + { + method: "POST", + body: JSON.stringify({ mode }), + }, + true, + ); +} + +/** Remove the ORCID link (identity row, `users.orcid`, `orcid_verified`). */ +export async function unlinkOrcid(): Promise<{ ok: true }> { + return request<{ ok: true }>("/auth/orcid/unlink", { method: "POST" }, true); +} diff --git a/src/lib/api/client.ts b/src/lib/api/client.ts index 813f251da..bcab0b005 100644 --- a/src/lib/api/client.ts +++ b/src/lib/api/client.ts @@ -12,7 +12,11 @@ */ import type { ZodType } from "zod"; -import { UPLOAD_ACCESS_ERROR_CODES } from "../../../shared/contract/user.js"; +import { IDENTITY_CONFLICT_CODES } from "../../../shared/contract/identity.js"; +import { + PROFILE_EDIT_ERROR_CODES, + UPLOAD_ACCESS_ERROR_CODES, +} from "../../../shared/contract/user.js"; import { getConfig } from "../config.js"; import { isDebugEnabled, recordHttpExchange } from "../debug-log.js"; import { printMaintenanceBanner } from "../maintenance-banner.js"; @@ -185,14 +189,44 @@ export async function request( // imported from shared/contract so the client and the route cannot drift // on which codes those are. Every other endpoint still leads with `error`, // which is where its human sentence lives. + // The third family (#1266, ADR 0044): the self-service identity edits. + // `PATCH /auth/profile`, the email change and the ORCID link intent all + // answer with a code in `error` and the sentence in `message`, and unlike + // the upload-access arm above there is no `missing` array to key on — so + // membership in the declared vocabulary IS the test. Both sets are + // imported from shared/contract rather than spelled out here, so a code + // the backend adds and the CLI has not been taught about prints as a bare + // token exactly once, in review. + const isProfileEditCode = + typeof data.error === "string" && + (PROFILE_EDIT_ERROR_CODES.includes(data.error) || + IDENTITY_CONFLICT_CODES.includes(data.error)); const prefersMessage = hasBlockReason || + isProfileEditCode || (missing !== undefined && typeof data.error === "string" && UPLOAD_ACCESS_ERROR_CODES.includes(data.error)); - const primary = prefersMessage + let primary = prefersMessage ? (data.message as string) || (data.error as string) : (data.error as string) || (data.message as string); + + // A route this CLI knows about and the backend does not (#1266 review). + // The API's 404 body is `{ error: "Not Found", message: "Route PATCH + // /auth/profile not found" }`, and leading with `error` renders the whole + // thing as the words "Not Found" -- which reads as "your dataset is + // missing", not "this deployment predates the command you just ran". The + // message names the route, and the added line names the cause. + // + // Keyed on the API's own not-found SIGNATURE (`error === "Not Found"` plus + // a message, backend/src/index.ts) rather than on the status alone: a + // route that answers 404 for a missing DATASET says so in `error`, and + // "this backend does not support this command" would be a wrong and + // confusing thing to append to it. + if (response.status === 404 && data.error === "Not Found" && typeof data.message === "string") { + primary = `${data.message}. This NEMAR backend does not support this command yet.`; + } + throw new ApiError( response.status, primary || "Request failed", diff --git a/src/lib/browser.ts b/src/lib/browser.ts new file mode 100644 index 000000000..f5ef1b2f4 --- /dev/null +++ b/src/lib/browser.ts @@ -0,0 +1,81 @@ +/** + * Open a URL in the user's browser (#1266, epic #1250; ADR 0044). + * + * Used by the ORCID link/relink handoff, which cannot happen in a terminal: + * the consent screen is ORCID's, and the CLI's job is to get the person in + * front of it. Opening is a CONVENIENCE and never the mechanism — the URL is + * always printed first, so a headless box, an SSH session, or a machine with + * no opener is a copy-and-paste rather than a dead end. + * + * No dependency for this (ADR 0037's make-versus-take test): the whole + * platform table is three commands, none of them moving, and `open`'s value + * over that is handling cases a scientific CLI does not meet. + */ + +import { spawn } from "node:child_process"; +import { dlog } from "./debug-log.js"; + +export interface BrowserOpener { + command: string; + args: string[]; +} + +/** + * The opener for a platform, or null when we do not know one. + * + * Pure so the table is testable without spawning anything. Windows goes + * through `cmd /c start` with an empty title argument: `start` treats a first + * quoted argument as the window title, so omitting it breaks any URL that + * needs quoting. + */ +export function browserOpenerFor(platform: NodeJS.Platform, url: string): BrowserOpener | null { + if (platform === "darwin") return { command: "open", args: [url] }; + if (platform === "win32") return { command: "cmd", args: ["/c", "start", "", url] }; + if (platform === "linux") return { command: "xdg-open", args: [url] }; + return null; +} + +/** + * Try to open `url`. The return value is whether an opener was LAUNCHED, and + * deliberately not whether it worked. + * + * That distinction is the reason the caller says "trying to open your browser" + * rather than "opened" (#1266 review): `spawn` returns before the child can + * fail, so a missing `xdg-open` on a minimal container produces an async + * `error` event long after this function has answered. Claiming success there + * would leave someone waiting for a window that is never coming, next to a URL + * they were supposed to click. + * + * `false` means "there was nothing to try" — no opener for the platform, or + * `NEMAR_NO_BROWSER=1`, which exists for CI, for tests, and for anyone who + * does not want a CLI reaching for their browser. Never throws; the URL is + * printed by the caller either way. + * + * The async failure goes to the debug log rather than the terminal: it is + * diagnostic detail for `--debug`, and printing it under a URL the person can + * already click would be noise. + */ +export function openInBrowser(url: string): boolean { + if (process.env.NEMAR_NO_BROWSER === "1") return false; + const opener = browserOpenerFor(process.platform, url); + if (!opener) return false; + try { + const child = spawn(opener.command, opener.args, { + stdio: "ignore", + detached: true, + }); + // Recorded, not discarded, and never rethrown: an unhandled 'error' event + // on a detached child would take the CLI down over a browser that did not + // open. + child.on("error", (err) => { + dlog(`openInBrowser: ${opener.command} failed: ${err instanceof Error ? err.message : err}`); + }); + child.unref(); + return true; + } catch (err) { + dlog( + `openInBrowser: could not spawn ${opener.command}: ${err instanceof Error ? err.message : err}`, + ); + return false; + } +} diff --git a/src/lib/config.ts b/src/lib/config.ts index 01b387ad2..bf20f4bea 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -101,6 +101,14 @@ const accountSchema = z.object({ * report a role without an extra network call. */ role: z.string().optional(), + /** + * The address `nemar auth profile set-email` last sent a code to (#1266). + * Remembered so `verify-email ` needs only the code, the way the + * website's Settings form remembers it across the two steps. Cleared on a + * successful verification; harmless if stale, since the code is bound to + * both the address and the account and simply will not verify. + */ + pendingEmailChange: z.string().email().optional(), }); export type Config = z.infer; @@ -482,6 +490,52 @@ export function storeAccount(username: string, accountConfig: Config): void { config.store = { ...config.store, accounts, activeAccount: username }; } +/** + * What {@link renameActiveAccount} did. + * + * Three outcomes rather than a boolean, because the caller has to tell the two + * "did nothing" cases apart: `unchanged` is the ordinary path (the key was + * already right, or there is nothing to rename) and says nothing to the user, + * while `key_taken` leaves this machine holding two accounts whose stored name + * and map key disagree — which is worth one line of warning, since + * `nemar auth switch ` will then select the OTHER one. + */ +export type RenameAccountResult = "renamed" | "unchanged" | "key_taken"; + +/** + * Re-key the ACTIVE account after its username changed on the server (#1266). + * + * The accounts map is keyed by username and `switchAccount` looks an account + * up by that key, so writing the new username into the account's fields and + * leaving the key alone produces an account that `nemar auth switch ` + * cannot find and `nemar auth switch ` finds under a name that no longer + * exists. `nemar auth profile set-username` is the first thing that can change + * a username from the CLI, so it is the first thing that has to move the key. + * + * Never clobbers a DIFFERENT stored account to do it. Two accounts on one + * machine can legitimately end up here — sign in as `harlow`, sign in as + * `alovelace`, then rename `harlow` to `alovelace` on the server — and + * overwriting the second entry would delete a working API key to fix a name. + * The account keeps its old key and still works; only the lookup name is + * stale, and the caller says so. + */ +export function renameActiveAccount(newUsername: string): RenameAccountResult { + const name = newUsername.trim(); + if (!name) return "unchanged"; + const config = getStore(); + const active = getActiveAccountName(); + if (!active || active === name) return "unchanged"; + const accounts = getAccountsMap(); + const current = accounts[active]; + if (!current) return "unchanged"; + if (accounts[name]) return "key_taken"; + + delete accounts[active]; + accounts[name] = { ...current, username: name }; + config.store = { ...config.store, accounts, activeAccount: name }; + return "renamed"; +} + /** * Switch to a different stored account by NEMAR username or GitHub username. * Returns the account that was switched to, or null if not found. diff --git a/test/admin-duplicates-cli.test.ts b/test/admin-duplicates-cli.test.ts index 2ce170ec0..600aaa8ad 100644 --- a/test/admin-duplicates-cli.test.ts +++ b/test/admin-duplicates-cli.test.ts @@ -230,7 +230,12 @@ describe("nemar admin duplicates", () => { const result = await runCli(["admin", "duplicates", "--clear", "42"], server.url); expect(result.exitCode).toBe(1); expect(`${result.stdout}${result.stderr}`).toContain("Still colliding"); - expect(`${result.stdout}${result.stderr}`).toContain("identity_conflict_remains"); + // The SENTENCE, not the code. Until #1266 taught the client which + // strings in `error` are machine codes (shared/contract), this line + // printed the literal `identity_conflict_remains` at an operator. + expect(`${result.stdout}${result.stderr}`).toContain( + "Resolve it on the other account first", + ); } finally { server.stop(); } diff --git a/test/api-export-surface.unit.test.ts b/test/api-export-surface.unit.test.ts index e48524154..92c977087 100644 --- a/test/api-export-surface.unit.test.ts +++ b/test/api-export-surface.unit.test.ts @@ -42,12 +42,17 @@ const MODULE_EXPORTS: Record = { "getSandboxStatus", "login", "registerSSHKey", + "requestEmailChange", "requestKeyRegeneration", "requestUploadAccess", "resendVerification", "resetSandbox", "retrieveKey", "signup", + "startOrcidCliLink", + "unlinkOrcid", + "updateProfile", + "verifyEmailChange", ], datasets: [ "ORCID_REGEX", @@ -182,6 +187,11 @@ const POST_SPLIT_ADDITIONS = [ "getFacets", // #1149, epic #1144 phase 5b: GET /datasets/facets for shell completion "getUserDuplicates", // #1254, ADR 0043: GET /admin/users/duplicates "publishZarrCatalog", // #1062, epic #1181 phase 2: POST /admin/zarr-catalog/publish + "requestEmailChange", // #1266, ADR 0044: POST /auth/email/change/request + "startOrcidCliLink", // #1266, ADR 0044: POST /auth/orcid/cli-start + "unlinkOrcid", // #1266, ADR 0044: POST /auth/orcid/unlink + "updateProfile", // #1266, ADR 0044: PATCH /auth/profile + "verifyEmailChange", // #1266, ADR 0044: POST /auth/email/change/verify "requestUploadAccess", // #1253, epic #1250: POST /users/me/upload-access/request "recordingStatsSweep", // #1194, CLI wrapper for POST /admin/datasets/recording-stats-sweep "recordingStatsSweepReset", // #1194, CLI wrapper for the recording-stats sweep reset diff --git a/test/auth-profile-cli.test.ts b/test/auth-profile-cli.test.ts index dccb8786a..a7dbda0f5 100644 --- a/test/auth-profile-cli.test.ts +++ b/test/auth-profile-cli.test.ts @@ -190,18 +190,23 @@ describe("nemar auth profile", () => { } }); - test("the footer says where each identifier is changed", async () => { + test("the footer names the command that changes each identifier", async () => { seedAuthenticatedConfig(); const server = startMeServer(meUser()); try { const result = await runCli(["auth", "profile"], server.url); expect(result.stdout).toContain("Where to change each"); - expect(result.stdout).toContain("Email, GitHub, ORCID"); + // Since #1266 every identifier is self-service from the CLI, so the + // footer names the command rather than a page the person then has to + // find. Username and name used to read "not editable yet" here. + expect(result.stdout).toContain("nemar auth profile set-email
"); + expect(result.stdout).toContain("nemar auth profile set-username "); + expect(result.stdout).toContain("nemar auth profile set-name --given --family "); + expect(result.stdout).toContain("nemar auth profile set-github "); + expect(result.stdout).toContain("nemar auth profile orcid link|relink|unlink"); + expect(result.stdout).not.toContain("not editable yet"); + // The website is still the other half of the same rules, not a rival. expect(result.stdout).toContain("https://nemar.org/settings"); - // Username and name are NOT self-service yet, and saying so beats - // leaving someone hunting for a field that does not exist. - expect(result.stdout).toContain("Username, name"); - expect(result.stdout).toContain("not editable yet"); expect(result.stdout).toContain("at most one NEMAR account"); } finally { server.stop(); diff --git a/test/auth-profile-self-service-cli.test.ts b/test/auth-profile-self-service-cli.test.ts new file mode 100644 index 000000000..a9aa26bf4 --- /dev/null +++ b/test/auth-profile-self-service-cli.test.ts @@ -0,0 +1,932 @@ +/** + * CLI `nemar auth profile set-*` / `orcid` (#1266, epic #1250; ADR 0044), + * driven through the real entry point (`bun run src/index.ts auth profile ...`). + * + * What these commands add over a curl one-liner is entirely in what reaches + * the terminal and what lands in the local config, so that is what is pinned: + * + * - a refusal prints the backend's SENTENCE, never the machine code that + * rides in `error` (lib/api/client.ts decides that from the shared + * contract's code vocabularies, so a code the CLI does not know about would + * print as a bare token); + * - the two-step email change remembers its address, so `verify-email ` + * is a code and nothing else; and + * - the stored account is refreshed after a change, so `nemar auth status` + * stops showing the value that was just replaced. + * + * Harness mirrors test/auth-request-upload-access-cli.test.ts: a real + * subprocess CLI run against a real local HTTP server via TEST_API_URL, an + * isolated NEMAR_CONFIG_DIR, and the real on-disk config store. No mocks. + * `NEMAR_NO_BROWSER=1` keeps the ORCID cases from reaching for a browser. + */ + +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawn } from "bun"; + +const CLI_ENTRY = join(import.meta.dir, "..", "src", "index.ts"); +const REPO_ROOT = join(import.meta.dir, ".."); + +const ORCID = "0000-0002-1825-0097"; + +interface Reply { + status: number; + body: unknown; +} + +interface Recorded { + path: string; + method: string; + body: unknown; +} + +interface FakeBackend { + url: string; + calls: Recorded[]; + stop: () => void; +} + +/** The `/users/me` envelope, as the real backend shapes it. */ +function meUser(overrides: Record = {}) { + return { + id: 7, + username: "harlow", + email: "harlow@example.org", + github_username: "harlow-gh", + role: "member", + orcid: null, + status: "verified", + email_verified: true, + orcid_verified: false, + given_name: "Ada", + family_name: "Lovelace", + created_at: "2026-05-01T00:00:00Z", + approved_at: null, + dataset_count: 0, + sandbox_completed: false, + sandbox_completed_at: null, + sandbox_dataset_id: null, + service_access: false, + ...overrides, + }; +} + +interface BackendOptions { + /** Keyed by path; the default is 200 `{ ok: true }`. */ + replies?: Record; + /** The user `/users/me` returns; a function is called per request so a test + * can make the ORCID iD appear part-way through a poll. */ + user?: Record | ((callIndex: number) => Record); +} + +function startBackend(options: BackendOptions = {}): FakeBackend { + const calls: Recorded[] = []; + let meCalls = 0; + const server = Bun.serve({ + port: 0, + async fetch(req) { + const url = new URL(req.url); + if (url.pathname === "/notices") return Response.json({ notices: [] }); + if (url.pathname === "/datasets/facets") return Response.json({}); + if (url.pathname === "/users/me") { + const user = + typeof options.user === "function" + ? options.user(meCalls++) + : (options.user ?? meUser()); + // The sentinel a test uses to revoke the key part-way through a poll. + if ((user as { unauthorized?: boolean }).unauthorized) { + return Response.json({ error: "Invalid or expired API key" }, { status: 401 }); + } + return Response.json({ user, token: null }); + } + calls.push({ + path: url.pathname, + method: req.method, + body: await req.json().catch(() => null), + }); + const reply = options.replies?.[url.pathname]; + if (!reply) return Response.json({ ok: true }); + return Response.json(reply.body, { status: reply.status }); + }, + }); + return { url: `http://localhost:${server.port}`, calls, stop: () => server.stop(true) }; +} + +let configDir: string; + +function seedAuthenticatedConfig(extra: Record = {}): void { + writeFileSync( + join(configDir, "config.json"), + JSON.stringify({ + activeAccount: "harlow", + accounts: { + harlow: { apiKey: "test-user-key-0123456789", username: "harlow", ...extra }, + }, + }), + ); +} + +function storedAccount(): Record { + const raw = JSON.parse(readFileSync(join(configDir, "config.json"), "utf8")); + return raw.accounts.harlow; +} + +beforeEach(() => { + configDir = mkdtempSync(join(tmpdir(), "nemar-profile-selfservice-")); +}); + +afterEach(() => { + rmSync(configDir, { recursive: true, force: true }); +}); + +interface RunOptions { + /** Let the CLI actually try to open a browser, with `pathPrefix` supplying + * a fake opener. Every other test keeps NEMAR_NO_BROWSER=1: a test suite + * may not open real browser windows. */ + allowBrowser?: boolean; + /** Prepended to PATH, so a fake `open` / `xdg-open` is found first. */ + pathPrefix?: string; +} + +async function runCli(args: string[], apiUrl: string, options: RunOptions = {}) { + const env: Record = { + ...process.env, + NEMAR_CONFIG_DIR: configDir, + TEST_API_URL: apiUrl, + NEMAR_NO_UPDATE_CHECK: "1", + NEMAR_NO_BROWSER: options.allowBrowser ? undefined : "1", + NO_COLOR: "1", + }; + if (options.pathPrefix) env.PATH = `${options.pathPrefix}:${process.env.PATH ?? ""}`; + env.FORCE_COLOR = undefined; + env.CLICOLOR_FORCE = undefined; + const proc = spawn({ + cmd: ["bun", "run", CLI_ENTRY, ...args], + cwd: REPO_ROOT, + env, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }); + const stdout = await new Response(proc.stdout).text(); + const stderr = await new Response(proc.stderr).text(); + const exitCode = await proc.exited; + // ora writes its spinner lines to stderr, so assertions that cover a + // succeed/fail line read both streams. + return { stdout, stderr, out: `${stdout}${stderr}`, exitCode }; +} + +// --------------------------------------------------------------------------- +// Email change +// --------------------------------------------------------------------------- + +describe("nemar auth profile set-email", () => { + test("sends the code and says what the second step is", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/email/change/request": { + status: 200, + body: { ok: true, masked_email: "a**@lab.example.org" }, + }, + }, + }); + try { + const result = await runCli( + ["auth", "profile", "set-email", "ada@lab.example.org"], + backend.url, + ); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("Code sent to a**@lab.example.org"); + expect(result.out).toContain("nemar auth profile verify-email "); + expect(backend.calls).toEqual([ + { + path: "/auth/email/change/request", + method: "POST", + body: { email: "ada@lab.example.org" }, + }, + ]); + // Remembered so the second step needs only the code. + expect(storedAccount().pendingEmailChange).toBe("ada@lab.example.org"); + // Nothing has changed yet -- the address moves at verify time. + expect(storedAccount().email).toBeUndefined(); + } finally { + backend.stop(); + } + }); + + test("prints the backend's sentence for a taken address, not the code", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/email/change/request": { + status: 409, + body: { + error: "email_in_use", + code: "email_in_use", + message: + "That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, https://nemar.org/settings).", + }, + }, + }, + }); + try { + const result = await runCli( + ["auth", "profile", "set-email", "taken@lab.example.org"], + backend.url, + ); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("already belongs to a NEMAR account"); + expect(result.out).toContain("nemar.org/settings"); + // The machine code must not be what a person reads. + expect(result.out).not.toContain("email_in_use"); + expect(storedAccount().pendingEmailChange).toBeUndefined(); + } finally { + backend.stop(); + } + }); +}); + +describe("nemar auth profile verify-email", () => { + test("uses the remembered address and updates the stored account", async () => { + seedAuthenticatedConfig({ email: "old@example.org", pendingEmailChange: "ada@lab.example.org" }); + const backend = startBackend({ + replies: { + "/auth/email/change/verify": { status: 200, body: { ok: true, old_address_notified: true } }, + }, + user: meUser({ email: "ada@lab.example.org" }), + }); + try { + const result = await runCli(["auth", "profile", "verify-email", "123456"], backend.url); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("Account email is now ada@lab.example.org"); + expect(backend.calls[0]).toEqual({ + path: "/auth/email/change/verify", + method: "POST", + body: { email: "ada@lab.example.org", code: "123456" }, + }); + const account = storedAccount(); + expect(account.email).toBe("ada@lab.example.org"); + expect(account.pendingEmailChange).toBeUndefined(); + } finally { + backend.stop(); + } + }); + + test("says so when the old address could not be told", async () => { + seedAuthenticatedConfig({ pendingEmailChange: "ada@lab.example.org" }); + const backend = startBackend({ + replies: { + "/auth/email/change/verify": { + status: 200, + body: { ok: true, old_address_notified: false }, + }, + }, + user: meUser({ email: "ada@lab.example.org" }), + }); + try { + const result = await runCli(["auth", "profile", "verify-email", "123456"], backend.url); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("previous address could not be notified"); + expect(result.out).toContain("the change still applied"); + } finally { + backend.stop(); + } + }); + + test("with nothing pending it explains rather than guessing an address", async () => { + seedAuthenticatedConfig(); + const backend = startBackend(); + try { + const result = await runCli(["auth", "profile", "verify-email", "123456"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("No pending email change"); + expect(result.out).toContain("set-email"); + // Nothing was sent: a code alone cannot say which address it proves. + expect(backend.calls).toEqual([]); + } finally { + backend.stop(); + } + }); + + test("a wrong code prints the attempts left, not the code name", async () => { + seedAuthenticatedConfig({ pendingEmailChange: "ada@lab.example.org" }); + const backend = startBackend({ + replies: { + "/auth/email/change/verify": { + status: 401, + body: { + error: "code_incorrect", + message: "That code did not match. 4 attempts left before it is invalidated.", + attempts_remaining: 4, + }, + }, + }, + }); + try { + const result = await runCli(["auth", "profile", "verify-email", "000000"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("4 attempts left"); + expect(result.out).not.toContain("code_incorrect"); + // The pending address survives a wrong guess: the next attempt is the + // same two-step flow, not a new one. + expect(storedAccount().pendingEmailChange).toBe("ada@lab.example.org"); + expect(storedAccount().email).toBeUndefined(); + } finally { + backend.stop(); + } + }); + + test("an expired code says to request a new one", async () => { + seedAuthenticatedConfig({ pendingEmailChange: "ada@lab.example.org" }); + const backend = startBackend({ + replies: { + "/auth/email/change/verify": { + status: 401, + body: { + error: "code_expired", + message: "That code has expired or has already been used. Request a new one.", + }, + }, + }, + }); + try { + const result = await runCli(["auth", "profile", "verify-email", "123456"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("Request a new one"); + expect(result.out).not.toContain("code_expired"); + } finally { + backend.stop(); + } + }); + + test("a config write that fails does not report the change as failed", async () => { + // The server has already moved the address and spent the code by the time + // the local write runs, so a `conf` failure is a stale local copy, not a + // failed change. Inside the request's try/catch it printed "Could not + // confirm the new address", which sends a person to request a code they + // no longer need (#1266 review item 5). + seedAuthenticatedConfig({ pendingEmailChange: "ada@lab.example.org" }); + const backend = startBackend({ + replies: { + "/auth/email/change/verify": { status: 200, body: { ok: true, old_address_notified: true } }, + }, + user: meUser({ email: "ada@lab.example.org" }), + }); + // Readable, not writable: the store loads and every write fails. + chmodSync(configDir, 0o500); + try { + const result = await runCli(["auth", "profile", "verify-email", "123456"], backend.url); + expect(result.out).toContain("Account email is now ada@lab.example.org"); + expect(result.out).toContain("The change is live on the server"); + expect(result.out).toContain("local config could not be updated"); + expect(result.out).not.toContain("Could not confirm the new address"); + expect(result.exitCode).toBe(0); + } finally { + chmodSync(configDir, 0o700); + backend.stop(); + } + }); + + test("--email finishes a change started on another machine", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser({ email: "ada@lab.example.org" }) }); + try { + const result = await runCli( + ["auth", "profile", "verify-email", "123456", "--email", "ada@lab.example.org"], + backend.url, + ); + expect(result.exitCode).toBe(0); + expect(backend.calls[0].body).toEqual({ email: "ada@lab.example.org", code: "123456" }); + } finally { + backend.stop(); + } + }); +}); + +// --------------------------------------------------------------------------- +// Profile fields +// --------------------------------------------------------------------------- + +describe("nemar auth profile set-github / set-username / set-name / set-location", () => { + test("set-github sends the handle and refreshes the stored account", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser({ github_username: "octocat" }) }); + try { + const result = await runCli(["auth", "profile", "set-github", "octocat"], backend.url); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("GitHub username set to octocat"); + expect(backend.calls[0]).toEqual({ + path: "/auth/profile", + method: "PATCH", + body: { github_username: "octocat" }, + }); + expect(storedAccount().githubUsername).toBe("octocat"); + // Every subcommand says where else the change can be made. + expect(result.out).toContain("https://nemar.org/settings"); + } finally { + backend.stop(); + } + }); + + test("set-github prints the refusal for a handle another account holds", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/profile": { + status: 409, + body: { + error: "github_in_use", + code: "github_in_use", + message: + "That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, https://nemar.org/settings).", + }, + }, + }, + }); + try { + const result = await runCli(["auth", "profile", "set-github", "octocat"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("already linked to a NEMAR account"); + expect(result.out).not.toContain("github_in_use"); + } finally { + backend.stop(); + } + }); + + test("set-username prints the post-approval lock in the backend's words", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/profile": { + status: 409, + body: { + error: "username_locked", + message: + "Your username is fixed once an admin has approved your account; contact an admin to change it", + }, + }, + }, + }); + try { + const result = await runCli(["auth", "profile", "set-username", "adal"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("fixed once an admin has approved"); + expect(result.out).not.toContain("username_locked"); + } finally { + backend.stop(); + } + }); + + test("set-username re-keys the stored account, so `auth switch` finds it", async () => { + // The accounts map is keyed by username. Writing the new name into the + // account's fields and leaving the key alone produced an account that + // `nemar auth switch ` could not find (#1266 review item 4). + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser({ username: "alovelace" }) }); + try { + const result = await runCli(["auth", "profile", "set-username", "alovelace"], backend.url); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("Username set to alovelace"); + expect(backend.calls[0].body).toEqual({ username: "alovelace" }); + + const config = JSON.parse(readFileSync(join(configDir, "config.json"), "utf8")); + expect(Object.keys(config.accounts)).toEqual(["alovelace"]); + expect(config.activeAccount).toBe("alovelace"); + // The credentials moved with the key, rather than being left behind. + expect(config.accounts.alovelace.apiKey).toBe("test-user-key-0123456789"); + + // The actual thing that was broken: switching by the new name. + const switched = await runCli(["auth", "switch", "alovelace"], backend.url); + expect(switched.exitCode).toBe(0); + expect(switched.out).toContain("alovelace"); + expect(switched.out).not.toContain("not found"); + } finally { + backend.stop(); + } + }); + + test("a name another stored account holds is kept, and said out loud", async () => { + // Two accounts on one machine, and the server accepts a rename onto the + // OTHER one's key -- sign in as harlow, sign in as alovelace, then rename + // harlow to alovelace. The re-key declines rather than deleting a working + // API key to fix a display name, and the warning is the point: without it + // `nemar auth switch alovelace` silently selects the other account. + writeFileSync( + join(configDir, "config.json"), + JSON.stringify({ + activeAccount: "harlow", + accounts: { + harlow: { apiKey: "test-user-key-0123456789", username: "harlow" }, + alovelace: { apiKey: "someone-elses-key", username: "alovelace" }, + }, + }), + ); + const backend = startBackend({ user: meUser({ username: "alovelace" }) }); + try { + const result = await runCli(["auth", "profile", "set-username", "alovelace"], backend.url); + // The change DID land on the server; only the local re-key was skipped. + expect(result.exitCode).toBe(0); + expect(result.out).toContain("Username set to alovelace"); + expect(result.out).toContain("already has a different account stored as 'alovelace'"); + expect(result.out).toContain("stay under the old name"); + + const config = JSON.parse(readFileSync(join(configDir, "config.json"), "utf8")); + expect(Object.keys(config.accounts).sort()).toEqual(["alovelace", "harlow"]); + expect(config.activeAccount).toBe("harlow"); + // Neither account's credentials were clobbered by the other's. + expect(config.accounts.harlow.apiKey).toBe("test-user-key-0123456789"); + expect(config.accounts.alovelace.apiKey).toBe("someone-elses-key"); + } finally { + backend.stop(); + } + }); + + test("set-name sends both halves, and refuses to send an empty patch", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser() }); + try { + const ok = await runCli( + ["auth", "profile", "set-name", "--given", "Ada", "--family", "Lovelace"], + backend.url, + ); + expect(ok.exitCode).toBe(0); + expect(backend.calls[0].body).toEqual({ given_name: "Ada", family_name: "Lovelace" }); + + const empty = await runCli(["auth", "profile", "set-name"], backend.url); + expect(empty.exitCode).toBe(1); + expect(empty.out).toContain("Nothing to set"); + // Still one call: the empty invocation sent nothing. + expect(backend.calls.length).toBe(1); + } finally { + backend.stop(); + } + }); + + test("set-name prints the ORCID-canonical refusal", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/profile": { + status: 409, + body: { + error: "name_is_orcid_canonical", + message: + "Your name comes from your ORCID record and is refreshed on every sign-in. Update it at orcid.org and sign in again.", + }, + }, + }, + }); + try { + const result = await runCli( + ["auth", "profile", "set-name", "--given", "Augusta"], + backend.url, + ); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("comes from your ORCID record"); + expect(result.out).not.toContain("name_is_orcid_canonical"); + } finally { + backend.stop(); + } + }); + + test("set-location sends city and country together", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser() }); + try { + const result = await runCli( + ["auth", "profile", "set-location", "--city", "San Diego", "--country", "USA"], + backend.url, + ); + expect(result.exitCode).toBe(0); + expect(result.out).toContain("Location updated"); + expect(backend.calls[0].body).toEqual({ city: "San Diego", country: "USA" }); + } finally { + backend.stop(); + } + }); + + test("an older backend that lacks the route says so, in its own words", async () => { + // The API's 404 body names the route; leading with `error` rendered the + // whole thing as the words "Not Found", which reads as "your account is + // missing" rather than "this deployment predates the command you ran" + // (#1266 review item 6). + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/profile": { + status: 404, + body: { error: "Not Found", message: "Route PATCH /auth/profile not found" }, + }, + }, + }); + try { + const result = await runCli(["auth", "profile", "set-github", "octocat"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("Route PATCH /auth/profile not found"); + expect(result.out).toContain("does not support this command yet"); + expect(result.out).not.toContain("Could not update your profile"); + } finally { + backend.stop(); + } + }); + + test("an unauthenticated config exits non-zero without calling the API", async () => { + const backend = startBackend(); + try { + const result = await runCli(["auth", "profile", "set-github", "octocat"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("Not authenticated"); + expect(backend.calls).toEqual([]); + } finally { + backend.stop(); + } + }); +}); + +// --------------------------------------------------------------------------- +// ORCID +// --------------------------------------------------------------------------- + +describe("nemar auth profile orcid", () => { + test("link prints the URL and waits for the iD to appear", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 200, + body: { + authorize_url: "https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state", + expires_in: 600, + mode: "link", + }, + }, + }, + // Call 0 is the "what is linked now" read before the flow starts; the + // browser finishes between then and the first poll. + user: (n) => meUser(n === 0 ? { orcid: null } : { orcid: ORCID, orcid_verified: true }), + }); + try { + const result = await runCli( + ["auth", "profile", "orcid", "link", "--timeout", "20"], + backend.url, + ); + expect(result.exitCode).toBe(0); + // The URL is always printed, whether or not a browser opened -- that is + // what makes a headless machine a copy-and-paste rather than a dead end. + expect(result.out).toContain("https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state"); + expect(result.out).toContain(`ORCID iD ${ORCID} is linked`); + expect(backend.calls[0]).toEqual({ + path: "/auth/orcid/cli-start", + method: "POST", + body: { mode: "link" }, + }); + } finally { + backend.stop(); + } + }, 30000); + + test("link gives up rather than claiming success it cannot see", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 200, + body: { + authorize_url: "https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state", + expires_in: 600, + mode: "link", + }, + }, + }, + // Nobody ever finishes in the browser. + user: meUser({ orcid: null }), + }); + try { + const result = await runCli( + ["auth", "profile", "orcid", "link", "--timeout", "1"], + backend.url, + ); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("Gave up waiting"); + expect(result.out).toContain("nemar auth profile"); + } finally { + backend.stop(); + } + }, 30000); + + test("relink waits for a DIFFERENT iD, not merely for a non-empty one", async () => { + // A relink starts and ends with `orcid` set, so "an iD is present" would + // report success the instant the command started, before the person had + // touched the browser. The previous value is what the wait is measured + // against. + const OTHER = "0000-0002-1974-1293"; + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 200, + body: { + authorize_url: "https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state", + expires_in: 600, + mode: "relink", + }, + }, + }, + // The OLD iD is still on the account for the first poll. + user: (n) => meUser({ orcid: n < 2 ? ORCID : OTHER, orcid_verified: true }), + }); + try { + const result = await runCli( + ["auth", "profile", "orcid", "relink", "--timeout", "20"], + backend.url, + ); + expect(result.exitCode).toBe(0); + expect(result.out).toContain(`ORCID iD ${OTHER} is linked`); + expect(result.out).not.toContain(`ORCID iD ${ORCID} is linked`); + expect(backend.calls[0].body).toEqual({ mode: "relink" }); + } finally { + backend.stop(); + } + }, 30000); + + test("link prints the refusal when an iD is already linked", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 409, + body: { + error: "orcid_already_have", + message: + "This account is already linked to ORCID iD 0000-0002-1825-0097. Replace it with 'nemar auth profile orcid relink', or remove it with 'nemar auth profile orcid unlink'.", + }, + }, + }, + user: meUser({ orcid: ORCID, orcid_verified: true }), + }); + try { + const result = await runCli(["auth", "profile", "orcid", "link"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("already linked to ORCID iD"); + expect(result.out).toContain("orcid relink"); + expect(result.out).not.toContain("orcid_already_have"); + } finally { + backend.stop(); + } + }); + + test("unlink asks first, and --yes goes through", async () => { + seedAuthenticatedConfig(); + const backend = startBackend({ user: meUser() }); + try { + const declined = await runCli(["auth", "profile", "orcid", "unlink", "--no"], backend.url); + expect(declined.exitCode).toBe(0); + expect(declined.out).toContain("Declined"); + expect(backend.calls).toEqual([]); + + const done = await runCli(["auth", "profile", "orcid", "unlink", "--yes"], backend.url); + expect(done.exitCode).toBe(0); + expect(done.out).toContain("ORCID iD unlinked"); + expect(backend.calls[0].path).toBe("/auth/orcid/unlink"); + } finally { + backend.stop(); + } + }); + + test("--timeout rejects a value it would otherwise silently ignore", async () => { + // It used to fall back to 300 on anything unparseable, so `--timeout 5m` + // was accepted and then ignored -- and the person watched a five-minute + // wait they thought they had shortened (#1266 review item 9). + seedAuthenticatedConfig(); + const backend = startBackend(); + try { + for (const bad of ["5m", "0", "-30", "abc"]) { + const result = await runCli( + ["auth", "profile", "orcid", "link", "--timeout", bad], + backend.url, + ); + expect(result.exitCode).not.toBe(0); + expect(result.out).toContain("--timeout must be a whole number of seconds"); + // Refused at the argument boundary: nothing was minted. + expect(backend.calls).toEqual([]); + } + } finally { + backend.stop(); + } + }); + + test("a poll that stops authenticating gives up early and says why", async () => { + // Burning the full timeout on a revoked key ends in "gave up waiting", + // which sends the person to look at their browser rather than at their + // credentials (#1266 review item 7). + seedAuthenticatedConfig(); + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 200, + body: { + authorize_url: "https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state", + expires_in: 600, + mode: "link", + }, + }, + }, + // The pre-flight read succeeds; the key is revoked before the first poll. + user: (n) => (n === 0 ? meUser({ orcid: null }) : { unauthorized: true }), + }); + try { + const started = Date.now(); + const result = await runCli( + ["auth", "profile", "orcid", "link", "--timeout", "120"], + backend.url, + ); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("no longer authenticate"); + expect(result.out).toContain("nemar auth login"); + expect(result.out).not.toContain("Gave up waiting"); + // The point of the change: it did not wait out the two minutes. + expect(Date.now() - started).toBeLessThan(30_000); + } finally { + backend.stop(); + } + }, 40000); + + test("--no-open suppresses the opener; without it the opener runs", async () => { + // NEMAR_NO_BROWSER=1 is set for every other test in this file, which made + // --no-open untestable (#1266 review item 14). Here the flag is the only + // difference, and a fake `open` / `xdg-open` first on PATH records + // whether the CLI reached for a browser at all. + seedAuthenticatedConfig(); + const binDir = mkdtempSync(join(tmpdir(), "nemar-fake-opener-")); + const marker = join(binDir, "opened.txt"); + // Both names, so the test does not depend on which platform runs it. + for (const name of ["open", "xdg-open"]) { + writeFileSync(join(binDir, name), `#!/bin/sh +echo "$1" >> "${marker}" +`); + chmodSync(join(binDir, name), 0o755); + } + const backend = startBackend({ + replies: { + "/auth/orcid/cli-start": { + status: 200, + body: { + authorize_url: "https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state", + expires_in: 600, + mode: "link", + }, + }, + }, + user: meUser({ orcid: null }), + }); + + /** The spawn is detached, so the marker can land after the CLI exits. */ + async function markerAppears(): Promise { + for (let i = 0; i < 20; i++) { + if (existsSync(marker)) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return false; + } + + try { + const suppressed = await runCli( + ["auth", "profile", "orcid", "link", "--no-open", "--timeout", "1"], + backend.url, + { allowBrowser: true, pathPrefix: binDir }, + ); + expect(suppressed.out).toContain("https://app.nemar.org/auth/orcid/cli-handoff?t=signed-state"); + expect(suppressed.out).not.toContain("trying to open your browser"); + expect(await markerAppears()).toBe(false); + + const opened = await runCli( + ["auth", "profile", "orcid", "link", "--timeout", "1"], + backend.url, + { allowBrowser: true, pathPrefix: binDir }, + ); + expect(opened.out).toContain("trying to open your browser"); + expect(await markerAppears()).toBe(true); + // It opened the URL it printed, not something else. + expect(readFileSync(marker, "utf8")).toContain("cli-handoff?t=signed-state"); + } finally { + backend.stop(); + rmSync(binDir, { recursive: true, force: true }); + } + }, 40000); + + test("an unknown action is named rather than silently ignored", async () => { + seedAuthenticatedConfig(); + const backend = startBackend(); + try { + const result = await runCli(["auth", "profile", "orcid", "connect"], backend.url); + expect(result.exitCode).toBe(1); + expect(result.out).toContain("Unknown action 'connect'"); + expect(backend.calls).toEqual([]); + } finally { + backend.stop(); + } + }); +}); diff --git a/test/auth-request-upload-access-cli.test.ts b/test/auth-request-upload-access-cli.test.ts index c105cda5e..a75766d64 100644 --- a/test/auth-request-upload-access-cli.test.ts +++ b/test/auth-request-upload-access-cli.test.ts @@ -194,10 +194,14 @@ describe("nemar auth request-upload-access", () => { for (const field of ["username", "city", "country"]) { expect(out).toContain(field); } - // Not just the field names: where to go. For these three that is - // Settings on nemar.org, because that is where the fields live - // (nemarOrg/website#301) -- not because of anything about the CLI. - expect(out).toContain("Settings on nemar.org"); + // Not just the field names: where to go. Since #1266 every one of these + // fields is settable from the CLI, so the fix names the command -- + // sending someone to a browser for a field they can set from the shell + // they are already in is the dead end ADR 0042 was left with. + expect(out).toContain("nemar auth profile set-username "); + expect(out).toContain("nemar auth profile set-location --city "); + expect(out).toContain("nemar auth profile set-location --country "); + // The website is still the other half of the same rules. expect(out).toContain("https://nemar.org/settings"); } finally { server.stop(); diff --git a/test/browser-opener.unit.test.ts b/test/browser-opener.unit.test.ts new file mode 100644 index 000000000..d7e9e6e71 --- /dev/null +++ b/test/browser-opener.unit.test.ts @@ -0,0 +1,42 @@ +/** + * The platform table behind `openInBrowser` (#1266, ADR 0044). + * + * A supplement to the CLI tests, not their replacement: those run the real + * `nemar auth profile orcid link` with `NEMAR_NO_BROWSER=1`, which is the only + * honest way to drive that command in a test suite (spawning a real browser is + * not a thing a test may do). What is left uncovered by that is the table + * itself, which is exactly where a silent regression would live -- an opener + * that never runs looks identical to one that runs and fails. + */ + +import { describe, expect, test } from "bun:test"; +import { browserOpenerFor } from "../src/lib/browser.js"; + +describe("browserOpenerFor", () => { + test("uses each platform's own opener", () => { + expect(browserOpenerFor("darwin", "https://example.org")).toEqual({ + command: "open", + args: ["https://example.org"], + }); + expect(browserOpenerFor("linux", "https://example.org")).toEqual({ + command: "xdg-open", + args: ["https://example.org"], + }); + }); + + test("windows keeps the empty title argument", () => { + // `start` reads a first quoted argument as the window TITLE, so dropping + // the empty string breaks every URL that needs quoting -- and it breaks it + // by opening a window called "https://..." rather than by erroring. + expect(browserOpenerFor("win32", "https://example.org?a=1&b=2")).toEqual({ + command: "cmd", + args: ["/c", "start", "", "https://example.org?a=1&b=2"], + }); + }); + + test("an unknown platform has no opener, rather than a wrong one", () => { + // The caller prints the URL and moves on; guessing `open` on AIX would + // spawn something unrelated. + expect(browserOpenerFor("aix", "https://example.org")).toBeNull(); + }); +}); diff --git a/test/config-rename-account.unit.test.ts b/test/config-rename-account.unit.test.ts new file mode 100644 index 000000000..cc04fe27b --- /dev/null +++ b/test/config-rename-account.unit.test.ts @@ -0,0 +1,113 @@ +/** + * `renameActiveAccount` — the accounts map is keyed by username (#1266, ADR + * 0044; PR #1269 review). + * + * `nemar auth profile set-username` is the first thing that can change a + * username from the CLI, so it is the first thing that has to move the KEY as + * well as the field: `switchAccount` looks an account up by that key, and a + * renamed account whose key stayed behind is one `nemar auth switch ` + * cannot find. + * + * The case this file exists for is the one the CLI test cannot reach cheaply: + * a machine with TWO stored accounts, where the new name is already somebody + * else's key. Overwriting it would delete a working API key to fix a display + * name, so the rename declines — and declining is only safe if it is total, + * which is what the assertions below pin. + * + * Real on-disk store through the production `conf` instance, in an isolated + * NEMAR_CONFIG_DIR. No mocks. + */ + +import { afterAll, beforeEach, describe, expect, test } from "bun:test"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + __resetStoreCacheForTesting, + getAccounts, + getConfig, + renameActiveAccount, +} from "../src/lib/config.js"; + +const testDir = join(tmpdir(), `nemar-cfg-rename-${Date.now()}-${process.pid}`); +const configPath = join(testDir, "config.json"); + +/** Two stored accounts, `harlow` active — the shape `nemar auth switch` makes. */ +function seedTwoAccounts(): void { + writeFileSync( + configPath, + JSON.stringify({ + activeAccount: "harlow", + accounts: { + harlow: { apiKey: "harlow-key", username: "harlow", email: "harlow@example.org" }, + alovelace: { apiKey: "ada-key", username: "alovelace", email: "ada@example.org" }, + }, + }), + ); + __resetStoreCacheForTesting(); +} + +function onDisk(): { + activeAccount?: string; + accounts: Record; +} { + return JSON.parse(readFileSync(configPath, "utf8")); +} + +beforeEach(() => { + mkdirSync(testDir, { recursive: true }); + process.env.NEMAR_CONFIG_DIR = testDir; + seedTwoAccounts(); +}); + +afterAll(() => { + process.env.NEMAR_CONFIG_DIR = undefined; + __resetStoreCacheForTesting(); + rmSync(testDir, { recursive: true, force: true }); +}); + +describe("renameActiveAccount", () => { + test("refuses to take a key another stored account already holds", () => { + // The collision path, and the reason it is a no-op rather than an + // overwrite: `alovelace` is a real account with a real API key, and + // renaming `harlow` onto it would destroy that key to fix a name. + expect(renameActiveAccount("alovelace")).toBe("key_taken"); + + const stored = onDisk(); + // BOTH entries intact, each with its own credentials. + expect(Object.keys(stored.accounts).sort()).toEqual(["alovelace", "harlow"]); + expect(stored.accounts.harlow.apiKey).toBe("harlow-key"); + expect(stored.accounts.alovelace.apiKey).toBe("ada-key"); + // The other account's identity is untouched -- not renamed, not merged. + expect(stored.accounts.alovelace.username).toBe("alovelace"); + expect(stored.accounts.alovelace.email).toBe("ada@example.org"); + // And the caller is still acting as the account it was acting as. + expect(stored.activeAccount).toBe("harlow"); + expect(getConfig().apiKey).toBe("harlow-key"); + }); + + test("moves the key, the fields and the active pointer when the name is free", () => { + // The success path, so the refusal above is provably about the COLLISION + // and not about the function doing nothing at all. + expect(renameActiveAccount("hgrant")).toBe("renamed"); + + const stored = onDisk(); + expect(Object.keys(stored.accounts).sort()).toEqual(["alovelace", "hgrant"]); + expect(stored.accounts.hgrant.apiKey).toBe("harlow-key"); + expect(stored.accounts.hgrant.username).toBe("hgrant"); + // The credentials moved with the key rather than being left behind. + expect(stored.accounts.hgrant.email).toBe("harlow@example.org"); + expect(stored.activeAccount).toBe("hgrant"); + expect(getAccounts().find((a) => a.active)?.username).toBe("hgrant"); + }); + + test("re-submitting the current name is `unchanged`, not a collision", () => { + // The ordinary case on every refresh: the account's own key is "taken" by + // the account itself. Reporting `key_taken` here would print a warning + // after every successful profile edit. + expect(renameActiveAccount("harlow")).toBe("unchanged"); + expect(renameActiveAccount(" ")).toBe("unchanged"); + expect(onDisk().activeAccount).toBe("harlow"); + expect(Object.keys(onDisk().accounts).sort()).toEqual(["alovelace", "harlow"]); + }); +});