Skip to content

Phase 7: CLI self-service for identity fields - #1269

Merged
neuromechanist merged 15 commits into
feature/issue-1250-epic-account-tiersfrom
feature/issue-1266-phase7-cli-self-service
Sep 6, 2026
Merged

neuromechanist merged 15 commits into
feature/issue-1250-epic-account-tiersfrom
feature/issue-1266-phase7-cli-self-service

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

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's nemar auth profile was a read whose footer said "not editable yet".

Backend — one handler, two credentials. resolveBearerUser is authMiddleware's own token lookup, extracted rather than copied; resolveActingAccount sits on top and resolves either a bearer token or the nemar_session cookie for PATCH /auth/profile, POST /auth/email/change/{request,verify} and POST /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's email_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 keep webSessionMiddleware rather than moving to authMiddleware, whose cookie path refuses a pending account — 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-handoff verifies 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 through sendEmail'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 profile gains set-email / verify-email, set-github, set-username, set-name, set-location and orcid link|relink|unlink. Refusals print the backend's sentence (the routes put a machine code in error; shared/contract now declares which strings are codes and client.ts prefers message for them). The config is refreshed after each change, the pending address is remembered so verify-email takes 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 so services/email.ts runs 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/profile per 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, pending still admitted).
  • test/auth-profile-self-service-cli.test.ts (19 tests) and test/browser-opener.unit.test.ts: the real CLI entry point against a local backend for every subcommand's success and refusal.
  • 23 mutation checks, one production line at a time, each confirmed to fail the intended test and reverted. One found a real gap: disabling the github_in_use pre-check left the test green because the unique index refuses the same write, so the test now counts GitHub calls (the guard identity-refusals-route.test.ts already 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 needs test/.env.test and 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 profile footer now names commands instead of "not editable yet", upload-access preconditions point at those commands rather than at Settings, and nemar admin duplicates --clear prints its sentence instead of the literal identity_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

`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).
@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1269

Version: 0.9.16-PR1269.abb2129
Commit: abb2129


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review round 1 — all 20 items addressed

5 commits on the same branch (b0d87c5a, 1933cd58, 774b9316, 6dc991cf, 8f3df34b). 16 new mutation checks, one production line at a time, each confirmed failing the intended test and reverted.

A. BLOCKING — the handoff is now bounded three ways

A1 — interstitial. GET /auth/orcid/cli-handoff no longer redirects anywhere. It verifies the intent, reads the target account from D1 by id, and renders one sentence naming it (alovelace (a**@nemar.test)) plus a form posting to POST /auth/orcid/cli-handoff/continue. No script tag of any kind, no auto-submit. The confirm step re-runs every check the GET ran — the page proves nothing about the moment the button is pressed — and is same-origin gated, which is what stops a page elsewhere auto-POSTing it. Test asserts the account name, the masked address, the form action, Location: null, absence of <script/submit(), and that rendering changes nothing.

A2 — refuse, never override. webSessionMiddleware now mounts on both handoff routes (it was already on the callback). A session naming a different account than the intent gets orcid_intent_account_mismatch at the handoff GET (403 page), at /continue (403, no cookie set), and at the callback (?error=orcid_intent_account_mismatch). The old "signed intent outranks the session" line is gone from code and ADR. The test named in the review is rewritten to pin the refusal at all three points with nobody linked and oauth_identities empty; the no-session success case stays, and I added the same-account-session case so the refusal is provably about disagreement, not about a session being present.

A3 — single use. Migration 0078 adds orcid_link_intents(nonce PK, user_id FK cascade, mode, created_at, expires_at, consumed_at). cli-start prunes expired rows, inserts the row, then signs a state carrying the nonce; the callback consumes it with a conditional UPDATE before writing anything, so any outcome burns it. A replay gets orcid_intent_used, and the handoff answers 410 for a spent intent. verifyCliState rejects a nonce-less state outright. Tested end-to-end plus a schema test (orcid-link-intents-migration.test.ts: nonce PK, consume-once changes 1 then 0, expiry, cascade). bun run migrations:d1-check → 80 migrations, 86 objects, 23 tables, OK.

I did not reuse auth_codes: it is keyed by email for a 6-digit secret with an attempt counter, so the reuse would mean an email column holding a non-email and a code_hash holding something nobody types.

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 config

4. renameActiveAccount() in config.ts moves the accounts-map key and activeAccount, called from refreshStoredAccount before the field writes. Declines to overwrite a different stored account's key. Tested end to end: set-username alovelace → the map has exactly ["alovelace"] with the API key intact → a real nemar auth switch alovelace succeeds.

5. Both commands now await the network call in a try that only guards the network call, print success, and then do local writes inside updateLocalConfig(), which reports "The change is live on the server; your local config could not be updated: …". Tested by chmod-ing the config dir to 0500 before verify-email: success line present, warning present, "Could not confirm the new address" absent, exit 0.

C. CLI behaviour

6. Keyed on the API's own not-found signature (status 404 && error === "Not Found" && message), deliberately narrower than "any 404 with a message" — a route that 404s for a missing dataset puts its sentence in error, and appending "does not support this command yet" to that would be wrong. Renders Route PATCH /auth/profile not found. This NEMAR backend does not support this command yet.

7. waitForOrcidLink returns a typed outcome. ApiError 401 → immediate unauthenticated ("your credentials no longer authenticate; run nemar auth login"); three consecutive statusCode 0 → unreachable ("Cannot reach the API: …"); anything else stays transient and resets the counter. Test revokes the key after the pre-flight read with --timeout 120 and asserts the CLI exits in under 30s with the right sentence and without "Gave up waiting".

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 error event and a sync throw go to dlog instead of an empty handler.

9. --timeout is parsed by Commander via parseOrcidTimeout, throwing InvalidArgumentError for non-integer/non-positive input. Tested with 5m, 0, -30, abc: non-zero exit, the message, and nothing minted.

D. Rate limit and tests

10. /auth/orcid/unlink added. Test asserts cli-start, cli-handoff, cli-handoff/continue and unlink are auth-ip with a bearer present, and a separate test asserts /auth/orcid/callback is not — mutation-checked in both directions (dropping the entry, and broadening it to /auth/orcid).
11. Fake GitHub now answers 502 for a nominated login; 503 github_unavailable with the stored handle unchanged, over bearer and cookie.
12. Bearer + another account's cookie on one request → the token's row changes, the cookie's does not.
13. cli-start with no ORCID client → 503 orcid_unavailable, and no intent row written.
14. runCli grew allowBrowser/pathPrefix; a fake open/xdg-open on PATH writes a marker. --no-open: no marker, no "trying to open". Without it: marker present and containing the printed URL.
15. verify-email renders code_incorrect ("4 attempts left", pending address kept) and code_expired; set-username success path is item 4's test.
16. Route-table comment now says "(token or cookie)"; ADR's cli-start paragraph names the same-origin gate; test covers the cookie branch refused with a foreign Origin and accepted with https://nemar.org.

E. Docs and contract

17. Closed structurally: profileRefusal(code: ProfileEditErrorCode, message) in services/profile.ts, and all ten literals now go through it (username_taken ×2, username_locked, name_is_orcid_canonical, account_revoked, github_unavailable, same_email, code_expired, code_incorrect ×2, orcid_already_have, orcid_unavailable). Verified by compiling an undeclared code: TS2345: Argument of type '"username_not_declared"' is not assignable…. No literal remains, so the ADR sentence is now true; ADR and contract comment updated to say which mechanism covers which codes.
18. NEMAR_NO_BROWSER=1 documented in orcid --help-all, along with the interstitial and single-use behaviour and the --timeout rule.
19. Reworded both the doc comment and the footer: "there is nothing to confirm. The only link above goes to NEMAR support, for use if this was not you."

20 — not done, and it is conditional. The item says "if you amend for any other reason"; I did not amend or rebase. feat: ORCID link intent a CLI can hand to a browser is 51 characters against a 50-character guideline, and shortening it means force-pushing over the commits this review already read. Say the word and I will reword it.

Gates

bun run lint clean · bun run typecheck clean · bun run migrations:d1-check OK (80 migrations) · bun test 5066 pass, 97 skip, 50 fail — every failure is live-tier, needing test/.env.test and a deployed backend: test/api.test.ts, test/cli.test.ts, test/iam-removal.test.ts.

`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).
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Re-review gap closed — abb2129b

Unit test (test/config-rename-account.unit.test.ts, real on-disk conf store in an isolated NEMAR_CONFIG_DIR, no mocks): two stored accounts with harlow active, rename it onto alovelace's key. Asserts the refusal, both entries intact with their OWN api keys, alovelace's username and email untouched (not renamed, not merged), activeAccount still harlow, and getConfig().apiKey still the active account's. Plus the success path (key, fields and active pointer all move) and the same-name/blank path, so the refusal is provably about the collision rather than the function doing nothing at all.

CLI counterpart (cheap, so included): a config seeded with two accounts, the server accepting set-username alovelace. Asserts exit 0 and "Username set to alovelace" — the change DID land server-side — plus the warning, and that on disk both accounts survive with their own keys and activeAccount is unmoved.

One deviation, and it is what makes the warning possible. You asked for assert false; the return type is now renamed | unchanged | key_taken instead of a boolean. A boolean cannot separate "the key was already right" (every ordinary refresh) from "somebody else holds it", so the caller could only warn on both or neither. Warning on both would fire after every successful profile edit; warning on neither leaves the real trap silent — the account's stored name and its map key disagree, and nemar auth switch alovelace then selects the OTHER account with nothing having said why. key_taken now prints one line: "This machine already has a different account stored as 'alovelace'." The unit test asserts the exact discriminant in all three cases.

Mutation checks, one line at a time, each reverted:

  • drop the collision guard so the rename clobbers the other account → unit test fails;
  • report the collision as unchanged → unit test AND the CLI test fail;
  • warn on renamed instead of key_taken → CLI test fails.

Gates: bun run lint clean · bun run typecheck clean · bun test 5070 pass, 97 skip, 50 fail — all 50 live-tier (test/api.test.ts, test/cli.test.ts, test/iam-removal.test.ts, needing test/.env.test and a deployed backend). Pushed; ready to merge.

This branch was previously deployed

1 inactive deployment
npm — abb2129b Deployed Sep 6, 2026 by neuromechanist via publish #2324
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant