Skip to content

Prove embedded Better Auth in one local URLCode site (#843) - #848

Merged
jimhoyd merged 3 commits into
mainfrom
claude/ecosystem-reuse-plan-514fa4
Sep 28, 2026
Merged

jimhoyd merged 3 commits into
mainfrom
claude/ecosystem-reuse-plan-514fa4

Conversation

@jimhoyd

@jimhoyd jimhoyd commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Problem and change

First gate of #841: prove, in one locally runnable URLCode site, that an embedded upstream auth provider can replace URLCode-owned accounts and sessions while URLCode keeps declared routes, admission, sandbox and grant boundaries, and review. Implements the #843 proof; the adopt/narrow/reject decision stays with the maintainer. Recommendation: adopt Better Auth, narrowed (see the end).

proofs/private-requests/ is a site with SQLite and an ordinary frontend. It has two owners (ann, bob), one reviewer (rita), owner-private requests, and one reviewer-only pending → approved transition.

  • Upstream owns auth. Better Auth serves sign-in, sign-out, get/list/revoke sessions and its browser client. Its schema, tables and cookies are its own. Application code never writes the auth database.
  • Operator adapter (operator/better-auth-extension.mjs) mounts Better Auth's native Request/Response handler on /api/auth/*. authorize() turns Better Auth's verified session into URLCode's request principal and refuses cross-origin unsafe methods. The feat(core): generic request-bound capability handoff for extensions (epic #837 Stage B) #840 capability hands routes context.capabilities['better-auth'].identity ({userId}). No cookie or Authorization reaches application code.
  • The application is five ordinary trusted function routes plus page/static routes. Owner scoping, the reviewer permission (an app table keyed by Better Auth's user id, so identity is not authorization), self-approval refusal and the conditional approval are ~60 lines of direct parameterized node:sqlite, per [Request]: Prove an embedded upstream auth provider in one local URLCode application #843's allowance.
  • Operator configuration (host.mjs, operator/auth.mjs) holds the secret, database paths, enabled endpoints and rate limits. app/urlcode.yaml names only better-auth: {version: "1", config: {}}. The app database path reaches functions through an APP_DATABASE binding that the operator policy must grant for the reviewed revision.
  • Core change (small). explain/report now mark an extension mount's handler subpaths: "provider-defined, not enumerated or inspected by URLCode". The acceptance criteria require unknown exposure to be stated honestly, and review previously listed the mount as if nothing below it needed saying. They also list a registration's declared request-bound capabilities on each route it protects (handler receives context.capabilities.better-auth: identity). No new YAML, registration fields or runtime behavior.

What the proof demonstrates

npm run build && npm run test:proof runs the whole flow. It packs this checkout, installs it with [email protected] into a temp copy, then runs the site's own scripts and real HTTP. 11/11 pass:

  • Startup. npm install, npm run build (bundles the upstream client) and npm run setup (forward Better Auth migration, app tables, three synthetic accounts through Better Auth's server API; idempotent). After that, no network service is needed. Telemetry is off, and the adapter refuses otherwise.
  • Explicit approval. validate refuses before the evaluator saves urlcode permissions output as operator/policy.json. Any app edit is refused with revision-pin-mismatch until it is re-approved. The test does that step as the evaluator, and nothing auto-pins.
  • Refusals before serving: missing secret, uninitialized Better Auth schema, SITE_ORIGIN ≠ --origin, a sandbox: true route naming better-auth (capability-in-sandbox), and AWS/Vercel/Cloudflare/static targets (the adapter declares node only; explain shows it).
  • Declarative coverage. urlcode test: 34 cases, including a signed-in steps fixture using the [Request]: let urlcode test fixtures carry a cookie session between steps #811 cookie jar. urlcode audit --expect-routes 8: ready, every route and method covered.
  • HTTP success and denial:
    • Wrong password gives 401. Sign-up over HTTP gives 404 (disabled).
    • Foreign owner read gives 404. Non-reviewer approve or pending gives 403. Reviewer self-approval gives 403. Three concurrent approvals give exactly one 200 and two 409s.
    • Malformed JSON 400, schema violations 422, wrong media type 415, bad uuid 400, cross-origin POST 403.
    • A forged x-urlcode-context-* header is ignored.
    • A cancelled mid-body POST writes nothing.
    • After sign-out, /api/me gives 401. "Revoke sessions" ends a second device's session, and a replayed revoked cookie gives 401.
    • Sign-in is throttled per client address, and spoofed X-Forwarded-For/address headers don't reset it.
  • Browser. Checked by hand in the in-app browser against npm start: sign in, create, reviewer approve, sign out, sign out everywhere. The session survived a server restart. This found and fixed a CSS bug ([hidden] overridden by form {display:grid}).

Adapter findings (why the adapter is 92 lines, not 40)

  1. disabledPaths matches literal paths only. Parametric /callback/:id and /reset-password/:token stay routed (they answer 302s). The adapter forwards only an exact operator allowlist and 404s everything else. npm run inventory probes both layers against the pinned instance.
  2. Rate limiting is off unless NODE_ENV=production. With it on and no client address, all clients share one bucket, so anyone can lock out sign-in for everyone (measured: 429 from the 4th anonymous attempt regardless of client). The adapter refuses a disabled limiter and passes URLCode's admitted clientKey(request.client) in a header it always overwrites. Better Auth is configured to read only that header.
  3. The mount forwards a URL rebuilt from the same path it allowlisted, never the raw target.

None of this is account or session emulation. It stayed under the "stop and reconsider" threshold.

Remaining blockers and gaps

Authoring workflow runs (one agent, one run each; not a benchmark)

The change: owners can filter GET /api/requests by a declared status query enum. That meant 3 YAML lines and 2 function/lib lines, with no auth code touched.

  • CLI-only. Used bootstrap, context, schema route.parameters, explain, diff, validate, review and report, in that order. validate refused the unreviewed revision, then passed after the evaluator re-ran permissions. review returned 0 observations. report flagged both changed files for a person to check. Repairs needed: exporting PROJECT_SHA256 by hand, and a fixture expectation (405 vs extension 403 ordering).
  • Connected MCP. Raw JSON-RPC over stdio (protocol 2025-06-18, 43 tools). Read-only tools succeeded and runners failed on the grant, as above.

Upstream versions, enabled endpoints and footprint

Item Value
better-auth / @better-auth/core 1.7.6 / 1.7.6, MIT, integrity from package-lock.json (printed by npm run inventory)
Driver built-in node:sqlite (DatabaseSync); no native addon
Plugins none
Served endpoints (8) POST /sign-in/email, POST /sign-out, GET|POST /get-session, GET /list-sessions, POST /revoke-session, POST /revoke-sessions, POST /revoke-other-sessions, GET /ok
Disabled or refused sign-up, social/OAuth callback, password reset/change, email verify/change, update/delete user, account linking, tokens, /error (22 more); server-only setPassword
Runtime deps 23 packages, ~32 MiB unpacked: @opentelemetry/semantic-conventions 12 MiB, zod 8 MiB, kysely 3.4 MiB. Unused Mongo/Prisma/Drizzle adapters are hard dependencies.
Build-only esbuild 0.28.2 (10 MiB) for a 33 KiB client bundle (12 KiB gzip)
Startup validate --local with host: ~0.57 s vs 0.35 s without; import('better-auth') ~100 ms

Deletion inventory if adopted (not deleted in this PR)

Subsystem Physical TS lines (src) Notes
packages/auth 17,336 Accounts, sessions, CSRF, passkeys, OIDC, second factor, recovery, API keys, support sessions, backup, CLI, templates. Tests: ~8,500 lines (auth+admin).
packages/admin 1,305 Account and session screens; only dependant of auth
Core auth-specific seams small Route auth: short form (RouteAuthShortForm, 6 files); --passkey-rp-id/passkeyRpId (9 files)
Recipes built on legacy auth 5 recipes authenticated-handlers, authenticated-json-api, fixed-contract-adapter, headless-auth-profile, protected-download
Mail/abuse keep for now Auth is one of two consumers (forms remains). Better Auth covers sign-in throttling itself.

Features without a Better Auth equivalent enabled here (passkeys, OIDC, 2FA, API keys, recovery, admin UI) would each come back only as a Better Auth plugin plus configuration when a current requirement exists, or not at all.

New code by kind (physical lines)

Kind Lines
Reusable adapter (operator/better-auth-extension.mjs) 92
Site operator config (operator/auth.mjs, host.mjs) 71
Operator tooling (scripts/setup.mjs, scripts/inventory.mjs) 70
Application (YAML 70, lib+functions 127, client 65, HTML/CSS 48) ~307
Core (explain.ts, explain-cli.ts) +10
Tests (integration 271, fixtures 18, explain +6) ~295

No migration or compatibility code.

Recommendation: adopt, narrowed

Adopt Better Auth as the embedded identity provider for the #841 program, with these narrowings:

  1. The adapter enforces an exact endpoint allowlist, a mandatory rate limiter keyed on URLCode's admitted address, and telemetry off.
  2. The app starts with email/password and sessions only. Add each plugin (passkey, 2FA, OIDC, admin) only against a current requirement, with its own inventory.
  3. Node target only until another target proves it.
  4. Keep permissions in the application, not in auth's role fields.

Required properties held without bespoke auth machinery. The footprint and the NODE_ENV/disabledPaths sharp edges are real but contained in ~20 adapter lines. Before retiring packages/auth, three things must land: MCP/CLI validation context (#834), a descriptor path that doesn't assume first-party packages (#844), and transition/idempotency (#835).

Verification

  • npm run verify: exit 0 (after npm ci; the worktree's node_modules predated the mail/audit/abuse workspace links). Core npm test: 1,092 pass. Workspace suites and test:addons pass.
  • npm run lint && npm run typecheck && npm run check:docs && npm run check:code && npm run test:package: exit 0 on the final tree.
  • npm run test:proof: 11/11 on Node 26.10.0 / macOS. It needs registry access for better-auth and esbuild, like test:addons, and now runs after it in verify:workspaces and in CI's workspace-integration job (Linux Node 24 on high-impact PRs; Linux/macOS/Windows Node 24 on release and dispatch). Changes under proofs/ or to the test are high-impact. Windows has not been run yet.
  • Manual browser check with the in-app browser, as above.

Compatibility and security

  • No YAML, schema or runtime behavior change. explain JSON gains handler.subpaths on extension mounts and provider.capabilities when declared (additive).

  • Sandbox isolation unchanged: a sandbox: true route naming the provider refuses before serving (tested). Grants stay operator-owned and revision-pinned; nothing auto-approves.

  • Synthetic data only (*@example.test, local demo passwords created by setup). The generated secret lives in the gitignored data/. The proof is not in the npm tarball.

  • This is not an independent security assessment of Better Auth or the adapter.

  • Changes match the documented portable contract; docs/examples are updated where needed.

  • Relevant tests and package checks pass, or limitations are explained above.

  • No credentials, customer data or private project material are included.

  • Runtime/starter changes remain aligned where applicable. (No starter change.)

🤖 Generated with Claude Code

Adds proofs/private-requests: a packed-consumer site where Better Auth
1.7.6 on node:sqlite owns accounts, sessions and its tables, an operator
adapter mounts its native handler and turns its verified session into
the request principal and #840's request-bound `identity` capability,
and ordinary function routes implement owner-private requests and one
reviewer-only approval with parameterized SQL.

The adapter refuses before serving on a missing secret, an uninitialized
schema, an origin or basePath mismatch, telemetry left on, or a disabled
rate limiter; forwards only an exact allowlist of Better Auth paths
(disabledPaths misses parametric routes); and supplies the admitted client
address for throttling in a header it always overwrites.

test/private-requests.integration.ts (npm run test:proof) packs this
checkout, installs it into a copy of the site, and exercises setup,
explicit policy approval, provider/target refusals, declarative fixtures
with audit ready, and the HTTP flow including foreign-owner and reviewer
denial, malformed input, concurrent approval, cancellation, sign-out,
revocation and throttling.

Core: explain/report state that an extension mount's subpaths are
provider-defined and not inspected, and list the capabilities a
registration declares on the routes it protects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
jimhoyd and others added 2 commits September 28, 2026 09:16
…tion

verify:workspaces and the workspace-integration job now run
npm run test:proof after test:addons. The proof packs the already-built
core with --ignore-scripts, like the other packaging tests, so prepare
never rebuilds dist under another test. Changes under proofs/ or to the
proof's test are high-impact, so they select that job on a pull request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t a shell

On Windows the proof's behavior passed but teardown did not: separate
t.after hooks run in registration order, so the temp site was removed
while the served runtime still held its SQLite files (EBUSY), the
server-stop hook never ran, and the live child kept the test process
alive until the job timeout. One unwind stack now attempts every
closer, newest first. npm runs through npm_execpath under this Node, so
Windows needs no shell (DEP0190).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jimhoyd
jimhoyd merged commit 1837202 into main Sep 28, 2026
168 checks passed
@jimhoyd
jimhoyd deleted the claude/ecosystem-reuse-plan-514fa4 branch September 28, 2026 15:57
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