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
99 changes: 99 additions & 0 deletions .context/decisions/0016-cli-device-authorize-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# ADR 0016: The CLI device-authorize page pins its own Origin and always ends in a redirect

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

## Context

Epic #1272 (nemarOrg/nemar-cli#1272) gave the backend a device-authorization grant (RFC 8628; nemar-cli ADR 0047):
`nemar auth login` mints a code,
prints a URL plus a short code,
and polls for a key while a person authorizes the code in a browser they are already signed into.
Phase 2 builds that browser half — `/cli/authorize` —
plus a Settings card for the paste-key fallback
(`GET /auth/keys`, `POST /auth/keys`, `DELETE /auth/keys/:id`).

Two backend behaviors are not obvious from the route list alone
and would otherwise be rediscovered by trial and error:

- `POST /auth/device/{confirm,deny}` sit behind `webSessionMiddleware` (cookie-only —
there is no bearer-token path for a browser confirming or denying a sign-in)
and call `isAllowedOrigin` directly.
`GET/POST/DELETE /auth/keys` go through `resolveActingAccount` instead,
which accepts either the CLI's bearer token or Origin-checks the cookie path the same way.
Either route means the same thing for this page: a bearer token carries no ambient credential
a forged cross-site request could ride along on, so only the cookie path is Origin-gated at all.
A **server-side** GET or POST built by this Worker carries no `Origin` header of its own —
unlike a browser's own fetch — so if this page or the Settings card do not set one explicitly,
every one of these calls 403s with `"Origin not allowed"`,
indistinguishable at first glance from a real refusal.
- `machine_name` on a `device_codes` row is client-supplied text from the CLI's own `POST /device/start` body,
stored and echoed verbatim by `lookup`/`confirm`
(see the header comment on nemar-cli's `backend/src/routes/auth-device.ts`).
The backend does not escape it, because it never renders HTML — that job is this page's.

## Decision

**The page forwards `Astro.url.origin` as the upstream `Origin`, never a hardcoded production host.**
Both the confirm/deny POST and the Settings key list's server-side GET set `Origin: Astro.url.origin`.
This reports the request's real origin rather than a guess,
and it does not depend on the backend's allow-list staying a wildcard:
`isAllowedOrigin` today accepts any `*.nemar.org` host, including `app.nemar.org`,
so a pinned production origin would in fact still pass on staging under the current allow-list —
`forwardAuthMutation` already relies on exactly that fallback elsewhere in this repo.
Forwarding the true origin is correct regardless of how that allow-list is shaped later,
which a pinned value is not.

**The confirm/deny POST always ends in a `Response`:
a 303 redirect on success, or the refused/unavailable view rendered in place on failure —
never a re-render that could re-submit the form.**
`/cli/authorize?code=...&done=authorized|denied&machine=...` is the only success shape;
the following GET reads `done` off its own query string and renders without a second lookup,
so a refresh of the result page is inert rather than re-authorizing or re-denying.

**`machine_name` is rendered exclusively through Astro's default-escaping `{}` interpolation,
never `set:html` or a client script.**
The page ships no `<script>` tag at all — every branch is server-rendered with real form POSTs —
which is what makes "never `set:html`" free to hold —
there is no client-side rendering path for it to leak through.

## Consequences

- Staging (`test.nemar.org`) exercises the real confirm/deny/list calls end-to-end
without any origin-specific branching in the code,
because the Origin sent is always the request's own.
- A person who reloads the done page, or bookmarks it,
sees the same outcome forever with no further backend call —
the code has already been consumed or denied by the time that page renders.
- `machine_name` — attacker-controlled text from the CLI's own request — can appear on this page
only as literal text inside the phishing-aware confirm question
("Did you just run `nemar auth login` on **&lt;machine&gt;**?"), never as markup.

## Alternatives considered

- **Pin `Origin: https://app.nemar.org` unconditionally.**
Under today's wildcard allow-list (`isAllowedOrigin` accepts any `*.nemar.org` host)
this does not actually 403 on staging —
`forwardAuthMutation` relies on exactly that fallback elsewhere in this repo, and it works.
Rejected anyway: forwarding the request's own origin reports the truth instead of a guess,
and stops being correct-by-coincidence the moment the allow-list narrows
to a per-environment exact match.
- **302 the confirm/deny success instead of 303.**
302 does not guarantee the browser turns a POST into a GET on the follow-up request
(some older clients replay the method);
303 is defined by the HTTP spec to do exactly that, which is what post-redirect-get requires.
- **Escape `machine_name` by hand and use `set:html`.**
Adds a hand-rolled escaping routine to audit and a `set:html` sink to explain in every future review,
for a case Astro's own default interpolation already handles correctly and for free.

## Receipts

- nemarOrg/nemar-cli#1272 (epic), nemarOrg/nemar-cli#1282 (this phase's tracking issue), nemarOrg/website#316.
- nemar-cli ADR 0047 (the device-authorization grant);
`backend/src/routes/auth-device.ts` and `backend/src/routes/auth-keys.ts`'s header comments
(Origin allow-list scope, the phishing note on `machine_name`);
`backend/src/middleware/auth.ts`'s `resolveActingAccount`
and `backend/src/services/web-session.ts`'s `isAllowedOrigin`.
- `src/pages/cli/authorize.astro`, `src/lib/device-auth-api.ts`, `src/lib/device-authorize.ts`,
`src/pages/settings.astro`'s CLI-keys card.
1 change: 1 addition & 0 deletions .context/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ Add new entries here as you create ADRs:
- ADR 0013 - [Viewer annotations are two BIDS kinds, stored locally only](0013-viewer-annotations-two-kinds-local-only.md) (accepted)
- ADR 0014 - [The website renders three account tiers, and every one of them has something to do](0014-account-tier-surfaces.md) (accepted)
- ADR 0015 - [Profile gaps come from one module, and their words from a mirrored copy contract](0015-profile-gaps-and-mirrored-copy.md) (accepted)
- ADR 0016 - [The CLI device-authorize page pins its own Origin and always ends in a redirect](0016-cli-device-authorize-page.md) (accepted)
81 changes: 80 additions & 1 deletion .context/handoff.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,85 @@
# Handoff — nemar.org website

**Last session:** 2026-08-03.
**Last session:** 2026-09-07.

## 2026-09-07 — CLI device-authorize page + Settings keys card (epic #1272 phase 2)

Implemented on `feature/issue-316-cli-authorize` (worktree `website-cli-authorize`),
tracking nemarOrg/website#316 and nemar-cli #1282,
against the epic branch's phase-1 backend (nemar-cli ADR 0047, PR #1287).
Pushed as nemarOrg/website#317.
Not yet merged to `staging` — the lead reviews and merges this PR.

- **`/cli/authorize`** — the page a person lands on to authorize `nemar auth login` on a new machine.
Server-rendered, no client script:
a `method="get"` form for a code typed by hand,
a `method="post"` form with `Authorize`/`Deny` buttons once a live code resolves,
and a post-redirect-get (`303`) after either decision so a refresh can never re-submit.
`src/lib/device-auth-api.ts` is the wire client
(never throws; `{ status, body } | { status: "network" }`);
`src/lib/device-authorize.ts` is the pure view model,
mirroring no refusal-code vocabulary (ADR 0005) —
every sentence a person reads comes verbatim off the wire.
`src/lib/device-authorize-dev.ts` stands in for the backend under `astro dev`.
- **`/cli` joined `APP_ROUTE_PREFIXES`** in `src/lib/host.ts` —
otherwise an anonymous first hit on the app host 301s to `nemar.org` first,
costing an extra redirect hop through the marketing host before landing back on `/login`.
- **Settings gained a "CLI keys" card** (`id="cli-keys"`, between `#upload-access` and Appearance):
the list is fetched server-side with `Origin: Astro.url.origin` pinned
(the cookie path 403s `"Origin not allowed"` without one);
create and revoke go through new same-origin routes
(`api/auth/keys.ts`, `api/auth/keys/[id].ts`);
revoke sits behind `ConfirmDialog`.
- **`next` now survives a brand-new ORCID sign-up mid-flow**:
`auth/orcid/complete.astro` reads `?next=` and finishes at `/dashboard?next=...`
instead of `/welcome` when set;
`dashboard.astro` forwards it to `VerifyEmailStep`,
which navigates there on success instead of reloading.
The backend half — appending `?next=` to the `/auth/orcid/complete` redirect —
is phase 3's PR, in the CLI repo;
this side is ready for it and behaves exactly as before until it lands.
- **ADR 0016** records two non-obvious constraints:
Origin must be pinned to `Astro.url.origin` (never a hardcoded production host)
on every cookie-path call this page or the keys card makes,
and the confirm/deny POST always ends in a redirect or an in-place refusal render,
never a plain re-render that could re-submit the form.
- **Build hygiene**: the dev-store seed calls
(`seedDeviceCodes`/`seedApiKeys` in `device-authorize-dev.ts`)
needed `/* @__PURE__ */` annotations —
without them, Rollup kept the calls as bare unassigned statements in the production bundle
(dev-only machine names and codes included),
even though every real call site is behind `import.meta.env.DEV` and gets eliminated.
Confirmed clean: `dist/_worker.js/index.js` carries none of
`dev-laptop`, `dev-desktop`, `dev-headless`, `nmr_dv*`, `seedDeviceCodes`, or `seedApiKeys`
after `bun run build`.

**Review round (same day, before merge)**: four review agents found real gaps, all fixed as
separate commits on the same branch.
`Astro.redirect()` builds a fresh `Response` and does not merge `Astro.response.headers`,
so every redirect on `/cli/authorize` needed its own `no-store`
(a `noStoreRedirect` helper now carries it, plus the bare 403/400 responses).
The Settings key-create handler now parses the response body in its own try/catch
(separate from the fetch itself),
requires a non-empty `api_key` before opening the reveal panel,
and never reports a 2xx-but-unreadable body as a network error.
The dev store's `decideDeviceCodeDev` now gates the account check on `authorize` only —
`deny` is ungated, matching the backend's real `POST /auth/device/deny` route —
and answers `account_revoked` for a `disabled` persona, not just `account_pending` for `pending`.
`decisionView` now validates `ok === true` on a 200 body rather than accepting any object,
and every `unavailable` state carries a `reason` (`network` / `server` / `malformed`)
that is logged, with a machine-aware done-view sentence
("Your terminal on `<machine>` will finish signing in on its own").
ADR 0016's Context and Decision sections had two factual errors,
now corrected rather than left to an Update note since the PR had not yet merged:
confirm/deny are cookie-only via `webSessionMiddleware` and call `isAllowedOrigin` directly
(only `/auth/keys` goes through `resolveActingAccount`),
and the predicted staging 403 from a pinned Origin does not reproduce —
`isAllowedOrigin` accepts any `*.nemar.org` host today, `app.nemar.org` included.

Gates run clean from the worktree: `bun run lint`, `bun run typecheck` (0 errors), `bun run test`,
`bun run build`, and the dev-store-string bundle check.
End-to-end confirm with a real ORCID account needs `api-test.nemar.org`,
which only deploys from nemar-cli `dev` — recorded on #1282 once the epic reaches there.

## 2026-08-03 — funder fix + profile completeness (v0.2.4)

Expand Down
19 changes: 17 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,12 @@ src/
dataset/[id]/collaborators.astro per-dataset collaborator management (app host)
login.astro login/*.astro signup.astro welcome.astro sign-in (ORCID + email code) + onboarding
auth/orcid/{start.ts,callback.ts,complete.astro} ORCID OAuth proxy flow
api/auth/** session-backed proxies: code, email change, profile, unlink, logout
cli/authorize.astro device-auth grant confirm/deny page (epic #1272 phase 2; app host)
api/auth/** session-backed proxies: code, email change, profile, unlink, logout, keys
api/v1/[...path].ts generic authenticated API proxy
dashboard.astro my-datasets list + publish status (app host)
upload.astro upload/success.astro upload flow (dropzone + BIDS pre-check + direct-to-storage PUTs)
settings.astro account: name/email/ORCID/GitHub/profile self-service
settings.astro account: name/email/ORCID/GitHub/profile self-service; CLI keys card
admin/publication-requests.astro admin-only (role=admin; 404s for others)
about.astro support.astro community.astro
og/** robots.txt.ts 404.astro
Expand All @@ -187,6 +188,9 @@ src/
data-api.ts / data-base.ts data.nemar.org client (landing/metadata/manifest/README fetch)
auth.ts auth-dev.ts auth-proxy.ts orcid-proxy.ts session types/helpers, dev mock session, backend proxies
dashboard-api.ts admin-api.ts collaborators-api.ts upload-client.ts authenticated API clients
device-auth-api.ts device-authorization grant client: lookup/confirm/deny, list keys
device-authorize.ts pure view model for /cli/authorize (no mirrored refusal vocabulary)
device-authorize-dev.ts astro-dev stand-in for the device-auth + keys backend (epic #1272 phase 2)
bids-precheck.ts hand-rolled client-side BIDS structural pre-check (upload)
flags.ts feature flags (ORCID_SIGNIN_ENABLED, WEB_SIGNIN_ENABLED, ...)
host.ts two-host route classification + noindex/production host logic
Expand Down Expand Up @@ -339,6 +343,17 @@ branch, so it gets its own custom domain and its own `SESSION_SECRET`.
- **Staging D1 is not synthetic:** `nemar-db-dev` is a partial production
mirror (~722 datasets, ~600 users with real emails, live RESEND key).
Don't run bulk operations against it casually.
- **The CLI device-auth flow points at test.nemar.org on staging, by construction.**
`nemar-cli`'s dev worker sets `APP_BASE_URL=https://test.nemar.org`,
so `POST /auth/device/start`'s `verification_uri`
(and the `verification_uri_complete` the CLI opens in a browser)
already resolve to `/cli/authorize` on THIS repo's staging deploy —
no website-side environment branch needed.
`test.nemar.org` runs in single-host mode (see the Branch ↔ environment map above),
so the `getCrossHostRedirect` concerns ADR 0016 documents for production are inert there;
the page and the Settings CLI-keys card still exercise the real confirm/deny/list calls
end-to-end because both forward `Astro.url.origin`,
which the backend's Origin allow-list accepts for any `*.nemar.org` host.

## Development Workflow

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "nemar-website",
"type": "module",
"version": "0.2.8",
"version": "0.2.9-dev1",
"private": true,
"license": "CC-BY-NC-ND-4.0",
"description": "nemar.org redesign on Astro + Cloudflare Pages",
Expand Down
28 changes: 22 additions & 6 deletions src/components/VerifyEmailStep.astro
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,18 @@ interface Props {
/** What the surface underneath this step is for, so the copy can say what
* verifying unlocks without the component knowing about either page. */
context: "dashboard" | "upload";
/**
* Where to navigate once verification succeeds, instead of reloading the
* mounting page in place (epic #1272 phase 2, nemarOrg/website#316) — the
* return trip for someone who arrived here mid-flow from somewhere else
* (e.g. a brand-new ORCID sign-up bounced through `/dashboard` on its way
* back to `/cli/authorize`). Omitted or `undefined` keeps the original
* behavior: reload the current page so its tier-gated surface re-renders.
*/
next?: string;
}

const { email, context } = Astro.props;
const { email, context, next } = Astro.props;
const masked = maskEmail(email);
const accountDocsUrl = `${resolveDocsBase()}${DOCS_ACCOUNT_SETTINGS_PATH}`;
const unlocks =
Expand All @@ -40,7 +49,12 @@ const unlocks =
: "Verifying unlocks your dashboard, settings, and the ability to request upload access.";
---

<section class="verify-step" data-verify-email-step aria-labelledby="verify-step-title">
<section
class="verify-step"
data-verify-email-step
data-verify-next={next}
aria-labelledby="verify-step-title"
>
<div class="verify-step__rail" aria-hidden="true"></div>

<header class="verify-step__head">
Expand Down Expand Up @@ -310,6 +324,10 @@ const unlocks =
const msg = root.querySelector<HTMLElement>("[data-verify-msg]");
const devChip = root.querySelector<HTMLElement>("[data-verify-devcode]");
const devValue = root.querySelector<HTMLElement>("[data-verify-devcode-value]");
// epic #1272 phase 2: where to go once the account leaves "pending",
// instead of reloading the page this component is mounted on. Absent
// for the ordinary case (dashboard/upload with no return trip pending).
const nextPath = root.dataset.verifyNext;

const setMsg = (text: string, tone: "error" | "success"): void => {
if (!msg) return;
Expand Down Expand Up @@ -340,7 +358,7 @@ const unlocks =
const result = await requestEmailVerificationCode();
if (result.already_verified) {
setMsg("This address is already verified. Reloading…", "success");
setTimeout(() => location.reload(), 700);
setTimeout(() => (nextPath ? (location.href = nextPath) : location.reload()), 700);
return;
}
if (form) form.hidden = false;
Expand Down Expand Up @@ -384,9 +402,7 @@ const unlocks =
try {
await verifyEmailCode(code);
setMsg("Verified. Reloading…", "success");
// The tier changed, so the whole surface re-renders rather than one
// banner being swapped out.
setTimeout(() => location.reload(), 700);
setTimeout(() => (nextPath ? (location.href = nextPath) : location.reload()), 700);
} catch (err) {
const status = err instanceof AccountApiError ? err.status : 0;
const failure = verifyEmailFailure(
Expand Down
Loading
Loading