Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# ADR 0047: CLI sign-in is the device authorization grant

**Status:** accepted
**Date:** 2026-09-06
**Owner:** Seyed Yahya Shirazi

## Context

Epic #1272 makes ORCID the single identity root for NEMAR.
After epic #1250 the web already creates accounts only through ORCID OAuth,
but the CLI still creates them with a password and a typed, unverified ORCID iD.
Two creation paths with two different identity roots produced the null-username and duplicate-account problems that epic #1250 cleaned up.

A terminal cannot receive an OAuth redirect,
and nobody should type an ORCID password into a CLI prompt.
`nemar auth login` therefore needs a way to authenticate that starts in the terminal and finishes in a browser the person already trusts.
`gh auth login` solves the identical problem with the device authorization grant (RFC 8628), a pattern built for exactly this shape:
a CLI mints a short code, a person authorizes it in a browser,
and the CLI polls for the credential once authorization lands.

Phase 1 (#1281) builds the backend half of this flow.
It never talks to ORCID itself:
`lookup`/`confirm`/`deny` sit behind the existing web session and ORCID routes,
so every ORCID lesson already in the tree (ADR 0022, 0043, 0044) applies unchanged.

## Decision

CLI sign-in is the device authorization grant,
layered on top of the existing web ORCID session rather than a new identity path.
The API key is minted only when the CLI collects it at `/auth/device/token`,
never when the browser confirms at `/auth/device/confirm`:
confirm records `user_id` and `status = 'confirmed'` only,
so no plaintext key is ever at rest between the two steps.
Every key is a named row for one machine (`tokens.name` holds the machine name the CLI or the paste-key form supplied),
and a new sign-in never revokes another machine's key --
a laptop and a compute cluster can both hold a live key for the same account at the same time.
The polling secret itself is never stored in the clear:
`device_codes.device_code_hash` holds only its SHA-256 hash, the same function `tokens.api_key_hash` uses,
so a read of the table cannot be turned into a working code.

## Consequences

`POST /auth/device/token` sits OUTSIDE the strict per-IP auth bucket (`AUTH_PATHS`, 10 requests/minute) and rides the generic bucket instead --
in practice `ip` (500/min), since the CLI holds no bearer until it has collected a key --
because the CLI polls it roughly every 5 seconds while waiting, up to ~120 polls across one 10-minute code.
At that cadence 10 polls fit inside the strict bucket's 60-second window and the 11th would trip it, about 50 seconds in.
The route gets its own per-row floor instead:
a poll sooner than 5 seconds after the last STAMPED poll answers `slow_down` without resetting the timer,
so a jittery client is never starved and can never restart its own countdown.

`verification_uri_complete` pre-fills the user code in the URL.
This is the RFC 8628 section 5.4 phishing trade-off, accepted deliberately:
NEMAR's users are researchers, not security engineers,
and the easiest, most reliable flow wins (the epic's guiding principle).
The mitigation is that phase 2's confirm page names the account and the machine before asking anyone to press Authorize --
a person who did not just run `nemar auth login` sees exactly that, and closes the tab.

Confirm extends a near-expiry code by 120 seconds (`expires_at = MAX(expires_at, datetime('now', '+120 seconds'))`),
so a person who authorizes in the closing seconds of the 10-minute window is not told "expired" by the CLI's very next poll.
This is safe because the code is already bound to one account by that point,
and the CLI still has to hold the device secret to collect the key.

`account_revoked` is unreachable at `lookup`/`confirm`/`deny`:
`findSessionByCookieId` already filters revoked accounts out of session resolution,
so a revoked person carries no web session and gets a 401, never this refusal.
It IS reachable at `/auth/device/token`,
for the case where an admin revokes the account between confirm and collect.

`POST /auth/device/deny` records no `user_id` on the `device_codes` row itself:
any signed-in account may deny a pending code,
and the denier is named only on the audit row, not on the table a later confirm/token read would see.

A brand-new ORCID account's `username` is `null` in `/auth/device/token`'s success response:
`refreshNameThenAssignUsername` runs after finalize, behind the response, not before it,
so a CLI collecting a key moments after sign-up may see the field still unset.
Phase 3 must not key config or first-run behavior on `username` alone.

`identity_conflict` refuses a NEW sign-in -- device confirm and the paste-key mint (`POST /auth/keys`) both check it --
while a key minted before the flag was set keeps authenticating.
The account has to clear the conflict (Settings) before it can add another key,
but nothing already issued stops working the moment the flag is set.

The polling endpoint's error body carries two different fields for "why":
`error` is the RFC 8628 code the CLI's retry loop switches on (`authorization_pending`, `slow_down`, `expired_token`, `access_denied`, `invalid_grant`),
and `reason` -- present only on a terminal answer, never on the two "keep polling" ones --
is the more specific refusal code (`account_pending`, `too_many_keys`, ...) a person-facing message reads from.
They disagree on purpose, which is why `reason` is not spelled `code` like every other refusal on this wire.

Every device-flow timestamp is written and compared in SQL (`datetime('now', '+N seconds')`, `julianday` for `expires_in`),
never in JavaScript.
A JS `toISOString()` value compares greater than a same-day SQL `datetime('now')` value at index 10 (`'T' > ' '`),
so mixing the two silently breaks expiry.
This is a pre-existing bug in `auth_codes`, `web_sessions`, and `orcid_link_intents`;
fixing those is out of scope here and gets its own issue after this phase lands.

`confirm-key-regeneration` (the existing settings flow) still revokes every key on the account, machine-named or not.
Phase 3 decides whether that survives once keys are per-machine --
revoking a laptop's key to regenerate a compute cluster's is not obviously right,
but that call belongs to the phase that builds the CLI-facing key management UX, not to this one.

## Alternatives considered

- **Mint the key at confirm, encrypted at rest.**
An encrypted key is plaintext-equivalent the moment it needs to be read back for the CLI to collect,
and it adds a second secret (the encryption key) to rotate and protect.
Minting at collect removes the "at rest between steps" window entirely rather than encrypting it.
- **HMAC-signed device state, no table.**
Works for the ORCID CLI-link intent (migration 0078) because that flow is single-use and needs no server-side rate floor.
The device grant needs both: single use (confirm must not be replayable)
and a per-code poll floor (`slow_down`),
neither of which a stateless signed token can enforce on its own.
0078 chose a table for the same reason this phase does.
- **Keep password login for the CLI.**
Rejected by the epic itself:
two identity roots (password + typed ORCID iD vs. verified ORCID OAuth)
is the problem epic #1250 already cleaned up once.

## Receipts

- Epic #1272, issue #1281 (phase 1 backend).
- RFC 8628 (OAuth 2.0 Device Authorization Grant), section 3.5 (error codes)
and section 5.4 (phishing considerations).
- ADR 0022 -- ORCID relink intent is minted only by an authenticated same-origin POST.
- ADR 0040 -- admin approval is the single writer of upload access;
`verified` is the base tier.
- ADR 0043 -- one person, one account.
- ADR 0044 -- identity self-service reaches the CLI, and ORCID does it through the browser.
- Migration 0078 (`orcid_link_intents`) -- the precedent for a short-lived,
single-use table over a stateless signed token.
- Migration 0081 (`device_codes`).
1 change: 1 addition & 0 deletions .context/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ invisible one — which is why it is checked rather than trusted.
- [ADR 0044](0044-identity-self-service-reaches-the-cli.md) - Identity self-service reaches the CLI, and ORCID does it through the browser
- [ADR 0045](0045-the-cli-and-the-web-say-one-thing-about-an-account.md) - The CLI and the web say one thing about an account: one matrix, one copy table, one gap function
- [ADR 0046](0046-cross-repo-parity-compares-pre-release-branches.md) - Cross-repo parity compares pre-release branches, never `main`
- [ADR 0047](0047-cli-sign-in-is-the-device-authorization-grant.md) - CLI sign-in is the device authorization grant, layered on the web ORCID session

## Backfill note (2026-07-31)

Expand Down
29 changes: 29 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,35 @@ with `username`/`github_username`/`password_hash` NULL until admin onboarding fi
Endpoints are defined in `backend/src/routes/auth-web.ts` (with `auth.ts` for the CLI path
and `auth-orcid.ts` for ORCID); read those rather than trusting this summary.

### CLI sign-in: device authorization (#1281, ADR 0047)

`nemar auth login` obtains its API key through the device authorization grant (RFC 8628),
the pattern `gh auth login` uses,
because a terminal cannot receive an OAuth redirect.
Five routes: `POST /auth/device/start` (CLI mints a device code + user code),
`POST /auth/device/token` (CLI polls for the key),
and `GET /auth/device/lookup`, `POST /auth/device/confirm`, `POST /auth/device/deny`
(the browser, behind the existing web session).
`lookup`/`confirm`/`deny` never talk to ORCID directly —
they sit behind the same web session and identity checks every other cookie-authenticated route does (ADR 0022, 0043, 0044).
**The key is minted only when the CLI collects it at `/token`, never when the browser confirms at `/confirm`** (ADR 0047):
confirm records `user_id` and `status='confirmed'` only,
so no plaintext key is ever at rest between the two steps.
Every key is a named row for one machine (`tokens.name`),
and a new sign-in never revokes another machine's key.
`POST /auth/device/token` is the one route in this family deliberately OUTSIDE the strict `AUTH_PATHS` bucket:
at a 5-second poll cadence,
10 polls fit inside the strict bucket's 60-second window and the 11th trips it, about 50 seconds in,
so the route rides the generic bucket instead — in practice `ip` (500/min),
since the CLI holds no bearer until it has collected a key —
plus its own per-row 5-second floor (`slow_down`).
Every timestamp this flow writes or compares is SQL-side (`datetime('now', ...)`, `julianday`),
never a JS `toISOString()` value,
because the two compare unequally on the same day and silently break expiry.
Named API keys (list/mint/revoke, plus the device flow's paste-key fallback) live alongside it at `GET/POST /auth/keys` and `DELETE /auth/keys/:id`.
Three files: `backend/src/routes/auth-device.ts`, `backend/src/routes/auth-keys.ts`,
and the shared SQL/helpers in `backend/src/services/device-auth.ts`.

### Dataset deletion

`DELETE /admin/datasets/:id` or `nemar admin delete-dataset <id>`.
Expand Down
77 changes: 77 additions & 0 deletions backend/src/db/migrations/0081_device_codes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
-- Device authorization grant codes (RFC 8628; epic #1272 phase 1, #1281;
-- ADR 0047).
--
-- WHAT THIS CLOSES. `nemar auth login` cannot receive an OAuth redirect on
-- a headless host, so CLI sign-in mints a device code here
-- (`POST /auth/device/start`), a person authorizes it in a browser they are
-- already signed into (`GET /auth/device/lookup`,
-- `POST /auth/device/{confirm,deny}`), and the CLI collects an API key by
-- polling `POST /auth/device/token`.
--
-- LIFECYCLE. pending -> confirmed -> consumed (a key was minted), or
-- pending -> denied, or any non-terminal status -> expired once something
-- observes `expires_at` has passed (no cron: the first poll, lookup, confirm
-- or deny past expiry stamps it). Rows older than 24 hours past expiry are
-- pruned opportunistically at `start` -- the same opportunistic-prune-
-- instead-of-cron IDEA as `orcid_link_intents` (migration 0078), but not
-- the same retention: that table deletes a row the moment it expires
-- (nothing there is useful once its ten minutes are up), while a device
-- code stays around for 24 hours past expiry so one more `token` poll can
-- still answer `expired_token` with a sentence instead of "unknown code".
--
-- NOTHING SECRET LIVES HERE. `device_code_hash` is the SHA-256 hash of the
-- polling secret the CLI holds (`hashApiKey`, same function `tokens
-- .api_key_hash` uses) -- a read of this table cannot be turned into a
-- working device code. `user_code` is the short code a person types or has
-- pre-filled into a link; it identifies the row for the browser half of the
-- flow but authorizes nothing by itself; the CLI's poll requires the
-- device_code_hash's preimage.
--
-- The key itself is never written here. Confirm stamps `status='confirmed'`
-- and `user_id` only; the token endpoint mints the `tokens` row and
-- consumes this row's `status -> 'consumed'` in one batch, so a confirmed
-- code yields at most one key and no plaintext key is ever at rest.

CREATE TABLE IF NOT EXISTS device_codes (
-- SHA-256 hash of the 256-bit polling secret the CLI holds. Primary key:
-- the hash IS the identity of the row for the token endpoint's lookup,
-- same pattern as `orcid_link_intents.nonce`.
device_code_hash TEXT PRIMARY KEY,
-- The short code shown in the terminal and typed/pre-filled in the
-- browser. Globally UNIQUE so a lookup by code is never ambiguous; `start`
-- retries on a collision (services/device-auth.ts).
user_code TEXT NOT NULL UNIQUE,
-- Client-supplied text (RFC 8628 section 5.4), shown back to the person
-- authorizing so they can recognise "did I just run this". The website
-- (phase 2) must escape and frame it; this table stores it verbatim.
machine_name TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'confirmed', 'denied', 'consumed', 'expired')),
-- Set by confirm. NULL until then; NEVER set by deny (the denier is
-- recorded on the audit row, not on this table -- ADR 0047).
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
-- Set by the token endpoint's mint, once. Lets an admin trace which
-- device-auth row produced a given tokens row.
token_id INTEGER REFERENCES tokens(id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
-- Poll floor bookkeeping (ADR 0047): a poll sooner than 5 seconds after
-- the previous one is answered `slow_down` without resetting the timer.
last_polled_at TEXT,
poll_count INTEGER NOT NULL DEFAULT 0,
confirmed_at TEXT,
consumed_at TEXT,
-- A row cannot claim to be confirmed or consumed without naming the
-- account it was confirmed for -- the same shape `orcid_link_intents`
-- guarantees with NOT NULL, expressed as a CHECK here because `user_id`
-- is NULL through 'pending' and 'denied'.
CHECK (status NOT IN ('confirmed', 'consumed') OR user_id IS NOT NULL)
);

-- Drives ONLY the opportunistic prune's scan (`DELETE ... WHERE expires_at
-- < ...`, the one statement here that has to search by `expires_at` rather
-- than look a single row up). The observed-expiry stamp and every row read
-- go through the primary key (`device_code_hash`) or the `user_code` unique
-- index instead -- `expires_at` is a filter on those lookups, not the path
-- to the row.
CREATE INDEX IF NOT EXISTS idx_device_codes_expires ON device_codes(expires_at);
9 changes: 9 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { maintenanceMode } from "./middleware/maintenance";
import { rateLimiter } from "./middleware/rateLimit";
import { adminRoutes } from "./routes/admin";
import { authRoutes } from "./routes/auth";
import { authDeviceRoutes } from "./routes/auth-device";
import { authKeysRoutes } from "./routes/auth-keys";
import { authOrcidRoutes } from "./routes/auth-orcid";
import { authWebRoutes } from "./routes/auth-web";
import { catalogIndexResponse, dataRoutes } from "./routes/data";
Expand Down Expand Up @@ -152,6 +154,13 @@ api.route("/auth", authRoutes);
api.route("/auth", authWebRoutes);
// ORCID SSO (#832). Same /auth prefix; new paths under /auth/orcid/*.
api.route("/auth", authOrcidRoutes);
// Device authorization grant (RFC 8628; epic #1272 phase 1, #1281; ADR
// 0047). Same /auth prefix; new paths under /auth/device/*.
api.route("/auth", authDeviceRoutes);
// Named API key routes (#1281, ADR 0047): list/mint/revoke, plus the
// device flow's paste-key fallback. Same /auth prefix; new paths under
// /auth/keys*.
api.route("/auth", authKeysRoutes);
api.route("/users", userRoutes);
api.route("/admin", adminRoutes);
api.route("/datasets", datasetRoutes);
Expand Down
27 changes: 27 additions & 0 deletions backend/src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
* stricter 10/60s cap and stay keyed by IP — those run pre-auth so
* a token isn't available, and they need to resist password
* guessing across IPs without any single bucket being unbounded.
* - The device authorization grant (#1281, ADR 0047) is the one
* exception INSIDE its own family: `start`/`lookup`/`confirm`/`deny`
* and `/auth/keys` sit in the strict bucket, but `/auth/device/token`
* does not -- a CLI polling every 5s fits 10 polls in the strict
* bucket's 60s window and trips it on the 11th, about 50 seconds in,
* so it rides the generic bucket plus its own per-row floor instead.
* See the `AUTH_PATHS` comment for the detail.
*/

import type { Context, Next } from "hono";
Expand Down Expand Up @@ -124,6 +131,26 @@ const AUTH_PATHS = [
"/auth/orcid/cli-start",
"/auth/orcid/cli-handoff",
"/auth/orcid/unlink",
// Device authorization grant (RFC 8628; epic #1272 phase 1, #1281; ADR
// 0047). A person starts, looks up, confirms, or denies a sign-in a
// handful of times, not in a loop, so all four -- plus /auth/keys, the
// named-key routes the prefix match also covers (/auth/keys/:id) -- sit
// in the strict floor like every other identity mutation above.
// `/auth/device/token` is DELIBERATELY ABSENT: the CLI polls it roughly
// every 5 seconds while waiting (up to ~120 polls for one 10-minute
// code). At that cadence 10 polls fit inside the strict bucket's 60s
// window and the 11th trips it, about 50 seconds in -- not the "third
// poll" a looser count might suggest. In practice this route lands in
// the plain `ip` bucket (500/min), not `token`: the CLI has not
// collected a key yet while it is polling, so it holds no bearer to
// authenticate a request with. Its own per-row 5-second floor
// (`DEVICE_POLL_SQL`) answers `slow_down` to anything faster than that
// without ever 429ing the loop.
"/auth/device/start",
"/auth/device/lookup",
"/auth/device/confirm",
"/auth/device/deny",
"/auth/keys",
// 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
Expand Down
Loading
Loading