Skip to content

feat: private site session scope and NemarApiRpc entrypoint - #1577

Merged
neuromechanist merged 22 commits into
devfrom
feature/private-site-session-rpc
Sep 30, 2026
Merged

neuromechanist merged 22 commits into
devfrom
feature/private-site-session-rpc

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This adds what the private site (private.nemar.org), which hosts access-controlled features, needs from the API: a session on its own host, and a way to ask who a caller is without reading the API's tables.

The private site's Worker reaches the API through a service binding to a new NemarApiRpc entrypoint (ADR 0078) with three methods: resolvePrincipal, exchangePrivateGrant and revokePrivateSession. The exchange, the per-request check and sign-out are methods, not routes; the public API gains one route, POST /auth/private/grant.

The session is a third web_sessions scope, private, minted by the same one-time-grant handoff the docs gate uses, for any active account, and ended by sign-out, admin revoke and the owner soft delete (ADR 0079). Role demotion and API key revocation deliberately leave it alone, and the ADR says why.

Unlike the docs handoff, this one binds the browser that starts a sign-in to the browser that finishes it. The private site generates a random state, keeps it in a host-only cookie and passes it through the website's authorize page; the grant stores only its hash, and the exchange mints only when the private site presents the same value from its cookie. The private site is a write surface, so without this an attacker could complete their own sign-in in a victim's browser and receive the victim's uploads.

A method for dataset facts was drafted and is left out on purpose: it waits for a caller, so that anonymous-deposit disclosure and archived or deleted rows are settled with that caller, and an additive-only contract should not ship an unsettled method.

It also closes gaps in existing code: an owner revoking a user's key and the key-regeneration link now end that account's docs sessions and grants, and optionalAuthMiddleware no longer accepts an expired API key.

Changes

  • backend/src/worker.ts is the Worker's main: it re-exports the existing default handler and adds NemarApiRpc (backend/src/rpc/), so index.ts never imports cloudflare:workers.
  • resolveApiKeyUser is extracted from resolveBearerUser as the one API-key lookup. The bearer path's SQL and responses are unchanged, and optionalAuthMiddleware now uses it too, which also touches last_used_at for a live key on those routes.
  • Migration 0089 rebuilds web_sessions to allow the private scope, copying every row, column and index behind an exact guard (equal counts and an empty EXCEPT in both directions), and adds private_grants with a required state_hash.
  • services/private-auth.ts holds the grant, mint, consume and revoke statements. routes/auth-private.ts is the grant route: Origin check, 401 without a session, 403 for an inactive account, 400 without a valid state, no-store, and a limit of ten grants a minute per account instead of the shared per-IP bucket (The strict auth rate-limit bucket is shared by every website visitor #1354).
  • shared/contract/private-site.ts is the contract: method and result types, Principal, the rules a caller must follow (fail closed on unknown errors, never cache a principal, never log a presented key, the state requirements), and plain-literal constants for the other repositories, pinned by private-site-contract.test.ts.
  • Maintenance mode is mirrored on the entrypoint through the middleware's own rule: writes are refused in read-only and full, reads in full.
  • The logout, admin revoke and soft-delete batches reach the new scope. revokeDocsCredentials moves to services/docs-auth.ts, is called by every route that revokes keys without ending every session, logs the account id when it fails, and also runs when a by-id revoke loses a race.
  • The deploy workflow now checks, after /health, that an anonymous POST /auth/private/grant answers 401 on both environments.
  • ADRs 0078 and 0079, a dated correction to ADR 0056, and the AGENTS.md revocation-cascade section.

Deploy notes

Merging runs migration 0089 on nemar-db-dev, rebuilding web_sessions. Existing sessions are preserved as asserted by private-sessions-migration.test.ts, which seeds every row shape at 0088 and replays the migration on bun:sqlite and on Miniflare's local D1, and by a seeded replay of all 91 migrations on local D1 during review; bun run migrations:d1-check only proves the schema replays. The live dev schema of web_sessions was compared against the migration-derived one before merge and matches.

The remote apply is not documented to be atomic. The migration's header records what was checked, what the guard does and does not protect, and the recovery path: redeploy the previous Worker version, then restore with D1 Time Travel to the start of the workflow's migration-apply step, or finish the remaining statements by hand. A Time Travel bookmark is recorded right before merge.

After deploy, the new workflow step should report the private grant route answering 401. The website authorize page and the private site deploy after this.

Testing

  • bun run typecheck (root and backend), bun run lint, Biome on changed backend and shared files
  • Full bun test in backend and at root: no new failures against the dev baseline
  • Every commit typechecks and passes the private-site, docs-gate and key tests on its own
  • bun run migrations:d1-check
  • wrangler deploy --dry-run for both environments; the bundle exports NemarApiRpc and the default handler
  • The entrypoint is exercised end to end in workerd through Miniflare, bundled by wrangler deploy --dry-run, with a second Worker holding the service binding
  • New tests were checked by mutating the code they guard
  • Reviewed by three independent review passes (auth and revocation, migration and deploy, contract, tests and docs); every finding addressed

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1577

Version: 0.10.12-PR1577.d5d79cd
Commit: d5d79cd


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review record. Three independent review passes on 5b8580e (authentication and revocation; migration and deploy safety; contract, tests, docs and repository hygiene) found no critical issues. Every finding was addressed in the rewritten history now ending at cbd8eab, and a focused verification pass on that round found no critical or important issues; its moderate items and nits are addressed in 6450364 through d5d79cd.

Main changes from review:

  • The handoff binds the browser that starts a sign-in to the one that finishes it (state hashed on the grant, required at exchange), closing login CSRF for a write surface
  • The grant has a per-account limit instead of the shared per-IP bucket (The strict auth rate-limit bucket is shared by every website visitor #1354)
  • The dataset-facts method is left out until a caller needs it, since the contract is additive-only
  • Revoked accounts are invalid_credential on both credential kinds; Principal mapping is tested across roles, statuses, kinds and verification flags
  • Migration 0089's guard is exact (counts plus EXCEPT both ways) and proven to abort on the D1 engine for a short, altered and padded copy; index, sequence and CHECK regressions are caught by the migration test
  • Optional auth ignores expired keys and never writes
  • Every key-revoke route ends the account's docs sessions, including a lost race, and logs the account id if the cascade fails
  • The deploy workflow smoke-tests the grant route (401 required, 404 fails, maintenance warns)
  • ADRs 0078 and 0079 state the caller rules: fail closed on unknown errors, never cache a principal, never log a presented key, and the state cookie requirements

Kept by design: a sequential retry of an already-revoked key cannot re-run a failed docs cascade (the pre-read filters revoked keys); the exposure is bounded by the 15-minute CLI docs session and the failure is logged with the account id.

@neuromechanist
neuromechanist merged commit 58eb687 into dev Sep 30, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feature/private-site-session-rpc branch September 30, 2026 23:26

This branch was previously deployed

1 inactive deployment
npm — d5d79cde Deployed Sep 30, 2026 by neuromechanist via publish #3025
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