Repository navigation
Prove embedded Better Auth in one local URLCode site (#843) - #848
Merged
Merged
Conversation
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]>
This was referenced Sep 28, 2026
…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]>
Merged
4 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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-onlypending → approvedtransition.operator/better-auth-extension.mjs) mounts Better Auth's nativeRequest/Responsehandler 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 routescontext.capabilities['better-auth'].identity({userId}). No cookie orAuthorizationreaches application code.functionroutes pluspage/staticroutes. 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 parameterizednode:sqlite, per [Request]: Prove an embedded upstream auth provider in one local URLCode application #843's allowance.host.mjs,operator/auth.mjs) holds the secret, database paths, enabled endpoints and rate limits.app/urlcode.yamlnames onlybetter-auth: {version: "1", config: {}}. The app database path reaches functions through anAPP_DATABASEbinding that the operator policy must grant for the reviewed revision.explain/reportnow mark an extension mount's handlersubpaths: "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:proofruns 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:npm install,npm run build(bundles the upstream client) andnpm 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.validaterefuses before the evaluator savesurlcode permissionsoutput asoperator/policy.json. Any app edit is refused withrevision-pin-mismatchuntil it is re-approved. The test does that step as the evaluator, and nothing auto-pins.SITE_ORIGIN≠--origin, asandbox: trueroute namingbetter-auth(capability-in-sandbox), and AWS/Vercel/Cloudflare/static targets (the adapter declaresnodeonly;explainshows it).urlcode test: 34 cases, including a signed-instepsfixture 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.x-urlcode-context-*header is ignored./api/megives 401. "Revoke sessions" ends a second device's session, and a replayed revoked cookie gives 401.X-Forwarded-For/address headers don't reset it.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 byform {display:grid}).Adapter findings (why the adapter is 92 lines, not 40)
disabledPathsmatches literal paths only. Parametric/callback/:idand/reset-password/:tokenstay routed (they answer 302s). The adapter forwards only an exact operator allowlist and 404s everything else.npm run inventoryprobes both layers against the pinned instance.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 admittedclientKey(request.client)in a header it always overwrites. Better Auth is configured to read only that header.pathit 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
urlcode mcpdeliberately accepts no--policy, sorun_validate/run_test/run_auditfail withbinding-denied. Read-only tools worked:get_extensionssaw the registration, mount and five protected routes, andsummarize_yaml_change,validateandplan_featureran. I did not change that boundary; details are on [Request]: Make installed authoring validation context executable and discoverable #834.bootstrapcommands omit--policy/--originand suggest copyingoperator//data/(secret, databases) intoapp/to serve them.context/explain/reviewneedPROJECT_SHA256exported by hand. Recorded on [Request]: Make installed authoring validation context executable and discoverable #834.validate(no host) assumes the extension is the first-party@jimhoyd/urlcode-better-authpackage and advisesextensions add(→ [Request]: Support independent provider packages and standard inert artifacts #844).app/lib/requests.mjs;reportdoes list it as changed code.authorize()before the router's 405, so unauthenticated wrong-method requests get 401/403 rather than 405. Noted, not changed.--policyfile answers "Operation failed" without naming it.Authoring workflow runs (one agent, one run each; not a benchmark)
The change: owners can filter
GET /api/requestsby a declaredstatusquery enum. That meant 3 YAML lines and 2 function/lib lines, with no auth code touched.bootstrap,context,schema route.parameters,explain,diff,validate,reviewandreport, in that order.validaterefused the unreviewed revision, then passed after the evaluator re-ranpermissions.reviewreturned 0 observations.reportflagged both changed files for a person to check. Repairs needed: exportingPROJECT_SHA256by hand, and a fixture expectation (405 vs extension 403 ordering).2025-06-18, 43 tools). Read-only tools succeeded and runners failed on the grant, as above.Upstream versions, enabled endpoints and footprint
better-auth/@better-auth/corepackage-lock.json(printed bynpm run inventory)node:sqlite(DatabaseSync); no native addonPOST /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/error(22 more); server-onlysetPassword@opentelemetry/semantic-conventions12 MiB,zod8 MiB,kysely3.4 MiB. Unused Mongo/Prisma/Drizzle adapters are hard dependencies.esbuild0.28.2 (10 MiB) for a 33 KiB client bundle (12 KiB gzip)validate --localwith host: ~0.57 s vs 0.35 s without;import('better-auth')~100 msDeletion inventory if adopted (not deleted in this PR)
packages/authpackages/adminauth:short form (RouteAuthShortForm, 6 files);--passkey-rp-id/passkeyRpId(9 files)authenticated-handlers,authenticated-json-api,fixed-contract-adapter,headless-auth-profile,protected-downloadFeatures 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)
operator/better-auth-extension.mjs)operator/auth.mjs,host.mjs)scripts/setup.mjs,scripts/inventory.mjs)explain.ts,explain-cli.ts)No migration or compatibility code.
Recommendation: adopt, narrowed
Adopt Better Auth as the embedded identity provider for the #841 program, with these narrowings:
Required properties held without bespoke auth machinery. The footprint and the
NODE_ENV/disabledPathssharp edges are real but contained in ~20 adapter lines. Before retiringpackages/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 (afternpm ci; the worktree'snode_modulespredated the mail/audit/abuse workspace links). Corenpm test: 1,092 pass. Workspace suites andtest:addonspass.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 forbetter-authandesbuild, liketest:addons, and now runs after it inverify:workspacesand in CI'sworkspace-integrationjob (Linux Node 24 on high-impact PRs; Linux/macOS/Windows Node 24 on release and dispatch). Changes underproofs/or to the test are high-impact. Windows has not been run yet.Compatibility and security
No YAML, schema or runtime behavior change.
explainJSON gainshandler.subpathson extension mounts andprovider.capabilitieswhen declared (additive).Sandbox isolation unchanged: a
sandbox: trueroute 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 bysetup). The generated secret lives in the gitignoreddata/. 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