Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
fcdad2e
feat: device-flow client error plumbing
neuromechanist Sep 7, 2026
f26ab90
feat: add device auth and named-key API functions
neuromechanist Sep 7, 2026
c92ab19
feat: secure config file and add account-keying helpers
neuromechanist Sep 7, 2026
ee6ef43
feat: guard confirm prompts against non-interactive stdin
neuromechanist Sep 7, 2026
218dcd5
feat: device-flow login (nemar auth login)
neuromechanist Sep 7, 2026
67ce968
feat: revoke this machine's key on logout
neuromechanist Sep 7, 2026
ffe120b
feat: add nemar auth keys group
neuromechanist Sep 7, 2026
5709073
feat: backend touches for CLI signup completion
neuromechanist Sep 7, 2026
c1dd599
feat: signup completion driven by profile_gaps
neuromechanist Sep 7, 2026
d251177
feat: deprecate retrieve-key and regenerate-key
neuromechanist Sep 7, 2026
61cf46f
test: local-tier device-flow CLI coverage
neuromechanist Sep 7, 2026
7e6e1c1
test: live-tier device-flow CLI coverage
neuromechanist Sep 7, 2026
7ac02ac
docs: CLI device sign-in
neuromechanist Sep 7, 2026
51cae3e
fix: keep Welcome back on the paste-key path
neuromechanist Sep 7, 2026
d211dd0
fix: cache sandbox dataset id on login
neuromechanist Sep 7, 2026
a91c83c
fix: classify poll errors and stop after repeats
neuromechanist Sep 7, 2026
74cac07
feat: parse token errors against the contract
neuromechanist Sep 7, 2026
7e392ad
fix: tagged key fields and honest account keys
neuromechanist Sep 7, 2026
4f45e8c
fix: visible failures on revoke and config write
neuromechanist Sep 7, 2026
5dccc1d
docs: drop plan citations, fix help and ADR text
neuromechanist Sep 7, 2026
93dfba1
test: review coverage for device login
neuromechanist Sep 7, 2026
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
Expand Up @@ -93,10 +93,33 @@ 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.
`confirm-key-regeneration` (the existing settings flow `regenerate-key` sends its email link through) is UNCHANGED by phase 3
and still revokes every key on the account, machine-named or not:
it is a password-era flow being retired, not the phase's own key-management surface, and phase 3 does not extend it.
`nemar auth login`'s device flow and `nemar auth logout` are the scoped replacement --
logout's default only ever revokes the ACTIVE machine's own key, and only when that key's `keySource` is `"device"`;
a pasted or password-era key may be shared with other machines and is kept, not silently killed by a different machine's logout.
`retrieve-key` and `regenerate-key` survive this release, each printing a deprecation sentence before its first prompt,
pointing at `nemar auth login` as the replacement for both.

Phase 3's local config keys an account by `accountKeyFor(user) = username?.trim() || email`,
since a brand-new ORCID account's `username` is `null` at collection time (this decision's own point above).
`upsertAccount` merges a re-login into whatever entry it finds by that key OR by email,
so an account that was stored under its email (no username yet) is found and renamed rather than duplicated the moment the server starts reporting a username --
`dismissedNoticeIds`, `profileGaps`, `orcidVerified`, and `serviceAccess` all survive the merge intact.
A re-login on the SAME machine also mints a new device key every time
(the token endpoint keeps no memory of "this machine already has one"),
so phase 3 best-effort revokes the machine's OWN previous key with the newly collected bearer, after the local config write lands --
never a pasted or password-era key, which by definition is not this machine's alone to kill.
The revoke is attempted even when the preflight probe already found the OLD key dead --
a repeat revoke of an already-gone row is harmless and caught the same way any other failure is --
what that foreknowledge skips is only the "(replaced this machine's previous key)" confirmation line,
since nothing was meaningfully replaced by revoking a key that was already dead.
Left unbounded, a script that re-runs `nemar auth login` would otherwise mint a fresh row per invocation until the `MAX_LIVE_API_KEYS` cap (25).

The CLI's config file now always holds a live API key rather than a password hash on every account it stores,
so `getStore()` writes it `configFileMode: 0o600` (honoured by `conf` 13's `atomically` writer regardless of umask)
and migrates an existing file an older build left at `conf`'s default file mode (0o666, unrelated to the conf version) to 0600 on first use, non-Windows only.

## Alternatives considered

Expand Down
16 changes: 12 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,11 @@ Four statuses, fixed meanings, one writer for upload access (**ADR 0040**):
`pending` (email unverified) → `verified` (the base tier, no admin needed) →
`approved` (an admin granted upload) → `revoked`.

1. Sign up (CLI: username, email, password; web: ORCID + an email) → verify the email → `verified`
2. `verified` needs no admin: browse, dashboard, settings, `nemar auth retrieve-key`,
`nemar sandbox`. Upload access is requested ONCE, when it is needed, from Settings
1. Sign up (CLI and web both: ORCID sign-in — the CLI's device flow, ADR 0047, mints the
account through the same browser step web signup uses; `nemar auth signup` is that flow
plus guided completion of whatever `profile_gaps` still names) → verify the email → `verified`
2. `verified` needs no admin: browse, dashboard, settings, `nemar sandbox`.
Upload access is requested ONCE, when it is needed, from Settings
on nemar.org or `nemar auth request-upload-access`
(`POST /users/me/upload-access/request`, **ADR 0042**). The request needs a username,
a real name, a GitHub account that exists, a city and a country, and a sentence about
Expand Down Expand Up @@ -261,6 +263,12 @@ 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`.
The CLI half (epic #1272 phase 3, #1283) is `src/lib/device-login.ts` plus `src/commands/auth.ts`:
`nemar auth login`/`signup` run this flow by default (`login` alone also takes `-k`/`--key`
to paste an existing key instead),
a re-login on the same machine best-effort revokes its own previous device-sourced key,
`nemar auth logout` revokes it back by default (never a pasted or password-era one),
and `nemar auth keys` manages the whole set.

### Dataset deletion

Expand Down Expand Up @@ -576,7 +584,7 @@ and what is historical. The entries worth knowing by name:

| Group | Covers |
|---|---|
| `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 auth` | login (browser device sign-in by default, `-k`/`--key` to paste a key instead — ADR 0047), signup (browser device sign-in, no `-k`/`--key`), status/whoami, keys (list/create/revoke this account's named API keys), 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, deprecated password-era 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 |
Expand Down
46 changes: 27 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,22 @@ gh auth login
## Quick Start

```bash
# 1. Sign up for NEMAR
# 1. Sign up for NEMAR (opens your browser to sign in with ORCID, then a few quick questions)
nemar auth signup

# 2. After admin approval, retrieve your API key
nemar auth retrieve-key

# 3. Login with your API key
nemar auth login

# 4. Complete sandbox training
# 2. Complete sandbox training
nemar sandbox

# 5. Validate your BIDS dataset
# 3. Validate your BIDS dataset
nemar dataset validate /path/to/dataset

# 6. Upload to NEMAR
# 4. Upload to NEMAR
nemar dataset upload /path/to/dataset
```

On another machine, `nemar auth login` signs in the same way (browser by default; `--key <api-key>`
pastes an existing key for a host that cannot open one).

## Architecture Overview

```mermaid
Expand Down Expand Up @@ -277,14 +274,13 @@ sequenceDiagram
### Authentication

```bash
nemar auth signup # Register new account
nemar auth retrieve-key # Retrieve API key after approval
nemar auth login # Login with API key
nemar auth signup # Sign in with your browser; create or continue your account
nemar auth login # Sign in with your browser (-k/--key to paste an existing key)
nemar auth status # Check authentication status
nemar auth switch # Switch between accounts
nemar auth logout # Remove active account (--all for all)
nemar auth setup-ssh # Configure SSH for GitHub
nemar auth regenerate-key # Request new API key
nemar auth keys # List, create, or revoke this account's named API keys
```

### Dataset Management
Expand Down Expand Up @@ -444,8 +440,8 @@ See [the Zenodo testing guide](https://docs.nemar.org/develop/zenodo-testing/) f
### CLI Usage

```bash
NEMAR_API_KEY # API key (alternative to login)
NEMAR_API_URL # Custom API endpoint (default: https://api.nemar.org)
NEMAR_API_KEY # API key (alternative to `nemar auth login -k`)
NEMAR_NO_BROWSER=1 # Never try to open a browser during sign-in (same as --no-open)
NEMAR_NO_COLOR # Disable colored output
```

Expand Down Expand Up @@ -517,9 +513,21 @@ nemar auth logout
nemar auth login
```

**"Account pending approval"**
- Admin must approve your account after signup
- Contact your NEMAR administrator
**Browser doesn't open, or you're on a headless/remote host**
- The printed link is the real mechanism, not the browser: copy it into any
browser, on any machine, and authorize there
- `nemar auth login --no-open` (or `NEMAR_NO_BROWSER=1`) skips the attempt
entirely and just prints the link
- If nothing can open a browser at all, paste an existing key instead:
`nemar auth login -k <api-key>` (create one with `nemar auth keys create`
on a machine that can)

**Upload access is not granted yet**
- Upload access is a separate, one-time admin approval requested with
`nemar auth request-upload-access` (or automatically at the end of
`nemar auth signup`)
- Browsing, downloading, and sandbox training all work without it
- Contact your NEMAR administrator if the request has been pending a while

### Branch Protection

Expand Down
16 changes: 15 additions & 1 deletion backend/src/routes/auth-orcid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -941,7 +941,21 @@ authOrcidRoutes.get("/orcid/callback", webSessionMiddleware, async (c) => {
// Hand off to the email-collection page. It lives under /auth (an app-host
// route) so the Domain=app.nemar.org pending cookie is actually sent to it;
// the public /signup page is not app-scoped. See website#128.
return redirect(`${frontend}/auth/orcid/complete`, [clearState, pendingCookie]);
//
// `next` rides along whenever it names somewhere other than the default
// landing ("/"): a device-flow signup carries `next =
// "/cli/authorize?code=..."` so the browser can return to the CLI
// confirm page once account creation finishes here, and dropping it
// silently was epic #1272 phase 3's one backend fix (nemarOrg/website#316
// reads it in `complete.astro`). Unvalidated like every other `${frontend}
// ${state.next}` interpolation in this handler (see `fail` above) --
// `state.next` is bound to the signed/plain state cookie this callback
// already trusts, not to a query param an attacker controls.
const completeUrl =
state.next !== "/"
? `${frontend}/auth/orcid/complete?next=${encodeURIComponent(state.next)}`
: `${frontend}/auth/orcid/complete`;
return redirect(completeUrl, [clearState, pendingCookie]);
} catch (err) {
console.error("[auth-orcid] callback failed after token exchange", err);
// Carry state.next so an authenticated user who started from Settings
Expand Down
25 changes: 18 additions & 7 deletions backend/src/routes/auth-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1847,17 +1847,28 @@ authWebRoutes.post(
* either way, but a saturated base is an operational fact nobody would
* otherwise see, so it is logged as well as reported.
*
* Cookie-authenticated like the rest of the /auth/profile family, and read-only,
* so it carries no Origin check — same as GET /auth/me.
* Accepts either credential `resolveActingAccount` accepts (#1266, ADR 0044)
* -- the dashboard's `nemar_session` cookie, or the CLI's bearer token, added
* in epic #1272 phase 3 so `nemar auth signup`'s guided completion can offer
* the same default a brand-new ORCID account sees on the website. That
* widens what was "no Origin check, same as GET /auth/me" to the family's
* usual rule: the COOKIE half still requires an allow-listed Origin (a CSRF
* fence a bearer token needs, and has, no part of), while a bearer request
* carries none. `ActingAccount` has no name fields, so this reads them by
* `actor.id` rather than off `c.var.webUser`, which the bearer path never sets.
*/
authWebRoutes.get("/profile/username-suggestion", webSessionMiddleware, async (c) => {
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;

try {
const base = suggestUsername(webUser.given_name, webUser.family_name);
const nameRow = await c.env.DB.prepare(
"SELECT given_name, family_name FROM users WHERE id = ? AND deleted_at IS NULL LIMIT 1",
)
.bind(actor.id)
.first<{ given_name: string | null; family_name: string | null }>();
const base = suggestUsername(nameRow?.given_name ?? null, nameRow?.family_name ?? null);
if (!base) {
return c.json({ suggestion: null, based_on: "unavailable" });
}
Expand Down
2 changes: 1 addition & 1 deletion backend/src/services/device-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ export const DEVICE_POLL_SQL = `UPDATE device_codes SET last_polled_at = datetim
WHERE device_code_hash = ? AND status = 'pending' AND expires_at > datetime('now')
AND (last_polled_at IS NULL OR last_polled_at <= datetime('now', '-${DEVICE_POLL_INTERVAL_SECONDS} seconds'))`;

/** Binds: userId, userCode. The `MAX(expires_at, ...)` grants the decision-6
/** Binds: userId, userCode. The `MAX(expires_at, ...)` grants ADR 0047's
* collection grace: confirming in the closing seconds of the 10-minute
* window extends expiry by {@link DEVICE_CONFIRM_GRACE_SECONDS} rather than
* leaving the very next poll to find it already expired. Safe because the
Expand Down
44 changes: 44 additions & 0 deletions backend/test/device-auth-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,50 @@ describe("device flow reached through a brand-new ORCID sign-in", () => {
// so it is not guaranteed to have landed by the time this request
// returns.
});

test("the /auth/orcid/complete redirect carries the device-flow next", async () => {
// Phase 3's one backend fix (nemarOrg/website#316): a brand-new ORCID
// account started from the CLI's confirm page must not lose its way back
// there. Drives only the callback -- the pending cookie's contents and
// the finalize step are already covered by the test above.
const csrf = "csrf-device-next";
const callbackRes = await app.request(
new Request(`${APP}/auth/orcid/callback?state=${csrf}&code=fake-code`, {
method: "GET",
headers: {
Cookie: `${STATE_COOKIE_NAME}=${encodeState({
csrf,
mode: "login",
next: "/cli/authorize?code=XXXX-XXXX",
})}`,
},
}),
undefined,
env(),
);
expect(callbackRes.status).toBe(302);
expect(callbackRes.headers.get("Location")).toBe(
`${APP}/auth/orcid/complete?next=${encodeURIComponent("/cli/authorize?code=XXXX-XXXX")}`,
);
});

test("an ordinary signup's next ('/') is not appended", async () => {
// The unqualified case (a plain click on the public /signup page) must
// render exactly as it did before this change -- no bare `?next=%2F`.
const csrf = "csrf-device-next-default";
const callbackRes = await app.request(
new Request(`${APP}/auth/orcid/callback?state=${csrf}&code=fake-code`, {
method: "GET",
headers: {
Cookie: `${STATE_COOKIE_NAME}=${encodeState({ csrf, mode: "login", next: "/" })}`,
},
}),
undefined,
env(),
);
expect(callbackRes.status).toBe(302);
expect(callbackRes.headers.get("Location")).toBe(`${APP}/auth/orcid/complete`);
});
});

// --------------------------------------------------------------------------
Expand Down
75 changes: 72 additions & 3 deletions backend/test/profile-username-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import { Hono } from "hono";
import { authWebRoutes } from "../src/routes/auth-web";
import { hashApiKey } from "../src/services/token";
import { isUsernameUniqueViolation } from "../src/services/username";
import { issueSession } from "../src/services/web-session";
import type { Bindings, Variables } from "../src/types/bindings";
Expand Down Expand Up @@ -118,11 +119,29 @@ async function patch(userId: number, body: unknown): Promise<Response> {
async function suggestion(userId: number): Promise<Response> {
return app.request(
"/auth/profile/username-suggestion",
{ headers: { Cookie: await cookieFor(userId) } },
{ headers: { Origin: ORIGIN, Cookie: await cookieFor(userId) } },
env(),
);
}

/** The bearer path: no cookie, no Origin -- the way the CLI calls it. */
function suggestionByKey(apiKey: string): Promise<Response> {
return app.request(
"/auth/profile/username-suggestion",
{ headers: { Authorization: `Bearer ${apiKey}` } },
env(),
);
}

/** Mints a live token row for `userId` and returns the raw key. */
async function issueApiKey(userId: number, apiKey: string): Promise<void> {
db.run("INSERT INTO tokens (user_id, api_key_hash, api_key_prefix) VALUES (?, ?, ?)", [
userId,
await hashApiKey(apiKey),
apiKey.slice(0, 8),
]);
}

function usernameOf(id: number): string | null {
return (
db
Expand Down Expand Up @@ -535,9 +554,25 @@ describe("GET /auth/profile/username-suggestion", () => {
expect(body).toEqual({ suggestion: null, based_on: "exhausted" });
});

test("requires a session", async () => {
const res = await app.request("/auth/profile/username-suggestion", {}, env());
test("an allow-listed Origin with no cookie is unauthenticated", async () => {
const res = await app.request(
"/auth/profile/username-suggestion",
{ headers: { Origin: ORIGIN } },
env(),
);
expect(res.status).toBe(401);
expect((await res.json()).error).toBe("Authentication required");
});

test("no bearer and no allow-listed Origin is refused (epic #1272 phase 3)", async () => {
// `resolveActingAccount`'s CSRF fence, gained when this route widened to
// accept a bearer token alongside the cookie: the docstring used to say
// "no Origin check, same as GET /auth/me", which stopped being true the
// moment the cookie half started sharing a resolver with the routes that
// DO need one.
const res = await app.request("/auth/profile/username-suggestion", {}, env());
expect(res.status).toBe(403);
expect((await res.json()).error).toBe("Origin not allowed");
});

test("suggests, but does not reserve", async () => {
Expand All @@ -550,4 +585,38 @@ describe("GET /auth/profile/username-suggestion", () => {
expect((await (await suggestion(a)).json()).suggestion).toBe("alovelace");
expect((await (await suggestion(b)).json()).suggestion).toBe("alovelace");
});

describe("over a bearer token (epic #1272 phase 3: nemar auth signup)", () => {
test("offers the same default the cookie path would", async () => {
const id = seedUser("cli-suggest@example.org");
await issueApiKey(id, "profile-username-route-key-0123456789ab");

const body = await (await suggestionByKey("profile-username-route-key-0123456789ab")).json();
expect(body).toEqual({ suggestion: "alovelace", based_on: "name" });
});

test("a revoked or unknown key is refused, not treated as anonymous", async () => {
const res = await suggestionByKey("no-such-key-0123456789abcdef0123456789");
expect(res.status).toBe(401);
});

test("bearer wins when a cookie is also present, matching resolveActingAccount", async () => {
const bearerUser = seedUser("cli-wins@example.org", { given_name: "Grace", family_name: "Hopper" });
const cookieUser = seedUser("cookie-loses@example.org");
await issueApiKey(bearerUser, "profile-username-route-key-precedence1");

const res = await app.request(
"/auth/profile/username-suggestion",
{
headers: {
Authorization: "Bearer profile-username-route-key-precedence1",
Origin: ORIGIN,
Cookie: await cookieFor(cookieUser),
},
},
env(),
);
expect(await res.json()).toEqual({ suggestion: "ghopper", based_on: "name" });
});
});
});
Loading
Loading