Repository navigation
Phase 7: CLI self-service for identity fields - #1269
neuromechanist merged 15 commits into
Conversation
`resolveBearerUser` is authMiddleware's own token lookup, extracted so the self-service identity routes can accept a CLI key through the SAME query, revoked/expired filter, active-account rule and last_used_at touch. A second copy is how a route ends up honouring a token the middleware would refuse. `resolveActingAccount` sits on top for the routes that take either credential: bearer wins when both are present, and the Origin allow-list applies to the cookie half only, since a token is not a credential a browser sends on its own. Part of #1266 (epic #1250, ADR 0044).
PATCH /auth/profile and both /auth/email/change routes now resolve the acting account from a bearer token as well as the session cookie, through one handler: every rule and every typed refusal is reached identically by both. They keep webSessionMiddleware rather than moving to authMiddleware because the latter refuses a `pending` account, and a wrong address is exactly what makes an account pending. A completed change now mails the PREVIOUS address a notice naming the new one, masked (#1054). Best-effort by construction: after the write, reported as `old_address_notified`, and off production it goes through sendEmail's existing allow-list fence -- the old address is the one recipient the caller did not choose. `same_email` gained a `message`, so a terminal has a sentence to print. Closes #1054. Part of #1266 (epic #1250, ADR 0044).
ORCID stays a browser flow -- there is no consent screen in a terminal -- so POST /auth/orcid/cli-start (bearer) mints a signed, account-bound intent and returns a URL to open. The browser that opens it holds no NEMAR session, which is what the callback used to resolve the user from, so the account rides inside an HMAC-signed state; the callback tries that shape first and falls back to the website's plain cookie. A state minted for user A can never link to user B: the id is covered by the signature, and the plain shape carries no id at all. GET /auth/orcid/cli-handoff mints nothing -- it verifies the POST's signature, puts it in the state cookie, and redirects -- so ADR 0022 holds: intent is still created only by an authenticated POST. Unlink takes a bearer token directly. Both new paths join the strict auth rate bucket. Part of #1266 (epic #1250, ADR 0044).
The identity routes answer a refusal with a code in `error` and the sentence in `message` -- right for the website's Settings form, and unreadable in a shell, where the CLI prints `error`. `profileEditErrorCodeSchema` and IDENTITY_CONFLICT_CODES declare the vocabularies, and client.ts prefers `message` for them, the same mechanism ADR 0042 added for upload access. `_profileErrorsAreDeclared` fails to compile if normalizeProfilePatch raises a code the contract does not know about, since the failure mode otherwise is a bare token printed at a person. Part of #1266 (epic #1250, ADR 0044).
Every identifier a person can change in Settings, they can now change from the CLI: set-email/verify-email, set-github, set-username, set-name, set-location, and orcid link|relink|unlink. Each prints the backend's own sentence on a refusal, re-reads /users/me afterwards so the local cache stops showing the value that was just replaced, and says the change can also be made in Settings. The email change remembers its address so verify-email takes a code and nothing else. `orcid link` prints the URL first and only then tries to open a browser, so a headless machine is a copy-and-paste; it then polls until the iD appears or the timeout runs out, and a timeout says to check rather than claiming a failure it cannot see. Part of #1266 (epic #1250, ADR 0044).
Backend: the two-step email change over a bearer token end to end, including the old-address notice (content, best-effort on a Resend failure, withheld off production for a non-allow-listed address), the email_in_use refusal, a code issued for one account refused for another's token, PATCH /auth/profile per field and per refusal, the CLI ORCID state proved account-bound (A's intent presented with B's session still links to A; a tampered one links nothing), and unlink. Real routes on bun:sqlite, real Resend redirected locally, no mocks. CLI: the real entry point against a local backend for each subcommand's success and refusal, asserting the sentence reaches the terminal and never the code. Three existing tests updated for behaviour this phase changes: the profile footer now names commands, upload-access preconditions point at those commands, and `admin duplicates --clear` prints its sentence instead of its code. Part of #1266 (epic #1250, ADR 0044).
Records the decision this phase makes and the reasoning it has to survive: one handler per field with two credentials, the two deliberate asymmetries between them, why ORCID's account rides inside a signature rather than a session, why ADR 0022 is unbroken by a GET that only transports an already-signed intent, the residual leaked-intent risk stated plainly, and why the old-address notice masks the new address. Part of #1266 (epic #1250).
Mutation check: disabling the github_in_use PRE-check left the test green, because idx_users_github refuses the same write at the UPDATE and the catch maps it to the same 409 body. The pre-check runs before the GitHub lookup, so a refused save spending no GitHub call is the observable difference -- the same guard identity-refusals-route.test.ts carries for CLI signup. Part of #1266 (epic #1250, ADR 0044).
A signed intent is a bearer capability for ten minutes, and the signature bounds only WHO it acts for, not who may present it. Someone could mint one for their own account, send the URL to a victim, and have the victim's iD -- what a DOI cites (ADR 0041), and what ADR 0043 then refuses them on their own account -- attached to a stranger's row, having seen nothing they did not expect. Three changes, per PR #1269's review: The handoff GET no longer redirects. It renders one sentence naming the target account (username and masked email, read from D1 by id) and a form the person submits; /cli-handoff/continue re-runs every check behind the same-origin gate. No script, and deliberately no auto-submit. A session for a DIFFERENT account is refused at both handoff steps and at the callback (orcid_intent_account_mismatch) rather than overridden. No session is the ordinary CLI case; the same account proceeds. An intent is single-use: cli-start records a nonce (migration 0078) and the callback consumes it before writing anything, so a URL out of history or a log is refused rather than replayed. cli-handoff and unlink join the strict rate bucket with cli-start, since all three are bearer-reachable. Part of #1266 (epic #1250, ADR 0044).
The ADR claimed a missing code "fails to compile"; that was true of the codes normalizeProfilePatch returns and false of the ten the routes raise themselves, which were bare string literals in c.json calls. They now go through profileRefusal(code, message), whose parameter is the contract union, so a typo or an undeclared code is a compile error at the call site. No route-level refusal in this vocabulary is still a literal. Also: the old-address notice claimed "no link to click" while shipping two. Part of #1266 (epic #1250, ADR 0044).
set-username re-keys the stored account: the accounts map is keyed by username, so writing the field and leaving the key left an account `nemar auth switch <new>` could not find. The local config writes after an email change moved out of the try that guards the network call. The server has already moved the address and spent the code by then, so a `conf` failure printed "Could not confirm the new address" for a change that had landed; it now says the change is live and the local copy is not. A 404 from a backend without these routes rendered as the words "Not Found"; the API's own not-found body names the route, and the CLI adds that this deployment does not support the command yet. The ORCID poll no longer burns its whole timeout on a revoked key (401) or an unreachable API (three consecutive network errors), each with its own sentence. --timeout is parsed by Commander, so a non-numeric or non-positive value is a usage error instead of a silent fallback to 300. openInBrowser reports what it ATTEMPTED, since spawn returns before the child can fail, and routes the spawn error to the debug log rather than discarding it. Part of #1266 (epic #1250, ADR 0044).
Backend: the interstitial (names the account, no script, no redirect), the account mismatch refused at both handoff steps AND the callback, the same account proceeding, the single-use replay, cli-start over a cookie with and without an allowed Origin, the ORCID-unconfigured 503, the GitHub-outage 503 for both credentials, bearer winning over a cookie for another account, and migration 0078's own guarantees (nonce PK, consume-once, expiry, cascade). CLI: verify-email's wrong-code and expired-code rendering, set-username re-keying the config followed by a real `nemar auth switch`, a config write that fails after the server already changed the address, the 404 line, the poll giving up on a 401 inside 30s rather than 120, --timeout rejecting four bad values before minting anything, and --no-open against a fake opener on PATH (the only test in the file that lets the CLI reach for a browser). Part of #1266 (epic #1250, ADR 0044).
The residual-risk paragraph now describes what an intent can actually do: it is shown to the person with its account named, refuses a browser signed in as somebody else, and is single-use. Adds the alternatives the review rejected (redirect-only handoff, intent-outranks-session, a nonce without a table), the compile-checked refusal vocabulary, and the CLI consequences. Part of #1266 (epic #1250).
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR1269Version: 🤖 Updated on each push. |
Review round 1 — all 20 items addressed5 commits on the same branch ( A. BLOCKING — the handoff is now bounded three waysA1 — interstitial. A2 — refuse, never override. A3 — single use. Migration 0078 adds I did not reuse ADR residual-risk paragraph replaced by "Three bounds on a bearer capability", ending with what is actually left: someone who reads a page naming an account that is not theirs and presses the button anyway, inside ten minutes, on a single-use link. B. CLI config4. 5. Both commands now C. CLI behaviour6. Keyed on the API's own not-found signature ( 7. 8. Return value re-documented as "an opener was launched", the caller prints "(trying to open your browser; use the link above if it doesn't)", and both the async 9. D. Rate limit and tests10. E. Docs and contract17. Closed structurally: 20 — not done, and it is conditional. The item says "if you amend for any other reason"; I did not amend or rebase. Gates
|
`renameActiveAccount` declined to overwrite a different stored account's key and nothing tested it, which is exactly the shape of no-op that quietly stops being a no-op. Unit test: two stored accounts, rename the active one onto the other's key -- refused, both entries intact with their own credentials, the active pointer unmoved. Plus the success and same-name paths, so the refusal is provably about the collision. The return type is now `renamed | unchanged | key_taken` rather than a boolean, because the caller has to tell the two "did nothing" answers apart: the collision leaves this machine with an account whose stored name and lookup key disagree, and `nemar auth switch <name>` would then select the OTHER account with nothing having said why. That case now prints one line. Covered end to end through the CLI as well. Part of #1266 (epic #1250, ADR 0044).
Re-review gap closed —
|
92ae5db
into
feature/issue-1250-epic-account-tiers
Closes #1266
Closes #1054
Part of #1250
What this does
Epic #1250 spent four phases making an account something a person is responsible for, and the CLI could not fix a single identifier on it:
PATCH /auth/profile, both/auth/email/change/*routes and the ORCID link surface were cookie-only, so a CLI-created account had no in-product way to correct its own email, GitHub handle, username, name or ORCID link. Phase 4'snemar auth profilewas a read whose footer said "not editable yet".Backend — one handler, two credentials.
resolveBearerUserisauthMiddleware's own token lookup, extracted rather than copied;resolveActingAccountsits on top and resolves either a bearer token or thenemar_sessioncookie forPATCH /auth/profile,POST /auth/email/change/{request,verify}andPOST /auth/orcid/unlink. Every rule and every typed refusal (GitHub existence, username uniqueness and the post-approval lock, the ORCID-canonical name rule, non-empty city/country, Phase 4'semail_in_use/github_in_use) is reached identically by both. Two asymmetries are deliberate and documented in the ADR: the Origin allow-list applies to the cookie path only, and the routes keepwebSessionMiddlewarerather than moving toauthMiddleware, whose cookie path refuses apendingaccount — the one account that most needs the email change.ORCID stays a browser flow.
POST /auth/orcid/cli-start(bearer) mints a short-lived HMAC-signed intent naming the token's account and returns a URL;GET /auth/orcid/cli-handoffverifies that signature, puts it in the state cookie and bounces to ORCID; the existing callback reads the account out of the signed state, because the browser that finishes the flow holds no NEMAR session. A state minted for user A can never link to user B — the id is covered by the signature, the website's plain state carries no id at all, and a CLI state outranks any session the browser happens to hold. ADR 0022 is intact: the GET mints nothing, it transports an intent an authenticated POST already signed.The old address is told (#1054). A completed change mails the previous address a notice naming the new one, masked. Best-effort by construction: after the write, reported as
old_address_notified, and off production it goes throughsendEmail's existing allow-list fence — the old address is the one recipient in the flow the caller did not choose, and on the dev mirror it is a real person's.CLI.
nemar auth profilegainsset-email/verify-email,set-github,set-username,set-name,set-locationandorcid link|relink|unlink. Refusals print the backend's sentence (the routes put a machine code inerror;shared/contractnow declares which strings are codes andclient.tsprefersmessagefor them). The config is refreshed after each change, the pending address is remembered soverify-emailtakes only a code, and the ORCID link prints its URL before trying to open a browser, then polls until the iD appears or the timeout runs out.Tested
backend/test/cli-self-service-routes.test.ts(31 tests): real routes on bun:sqlite with every migration, real Hono dispatch, real HMAC code and key hashing, real ORCID state signing, real Resend redirected to a local server soservices/email.tsruns unchanged including its fence, ORCID and GitHub served from a local mirror through the existing bindings. Covers: the email change end to end over a bearer token with the old-address notice (content, masked address, best-effort on a Resend failure, withheld for a non-allow-listed address off production),email_in_use, a code issued for account A refused for B's token,PATCH /auth/profileper field and per refusal,cli-start->cli-handoff-> callback with no session, A's intent presented alongside B's session still linking to A, a tampered and an expired intent linking nothing,unlink, and the unchanged cookie rules (Origin gate,pendingstill admitted).test/auth-profile-self-service-cli.test.ts(19 tests) andtest/browser-opener.unit.test.ts: the real CLI entry point against a local backend for every subcommand's success and refusal.github_in_usepre-check left the test green because the unique index refuses the same write, so the test now counts GitHub calls (the guardidentity-refusals-route.test.tsalready carries for signup).bun run lint,bun run typecheck,bun run migrations:d1-check(no migration added) all clean.bun test: 5045 pass, 97 skip, 50 fail — all 50 are the live tier, which needstest/.env.testand a deployed backend (test/api.test.ts,test/cli.test.ts,test/iam-removal.test.ts).Three existing tests changed for behaviour this phase changes: the
nemar auth profilefooter now names commands instead of "not editable yet", upload-access preconditions point at those commands rather than at Settings, andnemar admin duplicates --clearprints its sentence instead of the literalidentity_conflict_remains.ADR 0044 records the decision, both asymmetries, why ADR 0022 survives, and the residual risk that a leaked intent is a bearer capability for ten minutes.
🤖 Generated with Claude Code