Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Add Google and GitHub sign-in with permanent Kiln accounts (#146)

Matthew Kissinger8d14d0e0ca89
diff --git a/docs/plans/2026-10-05-v1-publication-plan.md b/docs/plans/2026-10-05-v1-publication-plan.md
index 0fdbd407..820a447f 100644
--- a/docs/plans/2026-10-05-v1-publication-plan.md
+++ b/docs/plans/2026-10-05-v1-publication-plan.md
@@ -1026,11 +1026,14 @@ Sources: [Better Auth account linking](https://better-auth.com/docs/concepts/use
#### Remaining security and user-flow gates
-The current gateway follows the upstream library's consent/PKCE pattern, strips
-credentials before private dispatch and tests tenant separation. It lacks Google,
-an internal account registry, account settings/linking/deletion, production public
-endpoint quotas and the branded end-user flow. The current bare consent form is
-an implementation fixture, not the approved launch presentation.
+The gateway follows the upstream library's consent/PKCE pattern, strips credentials
+before private dispatch and tests tenant separation. On 6 October the separate
+`codex/v1-hosted-identity` branch connected Google and GitHub adapters to permanent
+D1 Kiln accounts, atomic upstream login guards and current account/epoch checks;
+90 local hosted tests pass. See the [execution record](../reviews/2026-10-06-v1-execution.md#hosted-identity-integration).
+Account settings/linking/deletion, individual connection revocation, production
+public-endpoint quotas and the branded end-user flow remain open. The current bare
+consent form is an implementation fixture, not the approved launch presentation.
The provider documents a same-browser concurrent replay window because KV cannot
atomically consume a consent/upstream handle. KV also propagates changes across
diff --git a/docs/plans/2026-10-06-hosting-economics.md b/docs/plans/2026-10-06-hosting-economics.md
index 51749cfd..9c71c5b7 100644
--- a/docs/plans/2026-10-06-hosting-economics.md
+++ b/docs/plans/2026-10-06-hosting-economics.md
@@ -54,8 +54,10 @@ nothing from user input at job time. Serve the web viewer with Workers static as
Implementation refinement: tenant ownership and quota transactions now use the
tenant Durable Object's own SQLite database. This keeps the authoritative record
with the tenant routing boundary; it does not need a second D1 copy of those records.
-D1 remains optional for a demonstrated shared-metadata need, not a resource to
-provision merely because it appeared in the initial diagram.
+D1 now has a specific shared-metadata role: permanent Kiln accounts, verified
+Google/GitHub identity mappings and atomic login intents. Those adapters are
+implemented locally; no live D1 resource has been provisioned. Tenant asset and
+quota records stay in the tenant Durable Object rather than being duplicated.
Native execution does not require hardware GPU rendering. CPU geometry previews
already exist in Kiln. Textured/material previews would use the repo's existing
@@ -73,13 +75,17 @@ not an isolation boundary. Keep OAuth tokens, R2 credentials and other users' fi
in the trusted Worker. Apply outbound network restrictions outside the sandbox.
The Worker remains authoritative for ownership, quotas and permitted output handling.
-The critical spike is whether Kiln's current `setpriv`/`bwrap`/namespace restrictions
-work inside the actual Container. Native binary support alone does not prove this.
-If they do not, qualify an explicit per-job sandbox adapter; do not silently weaken
-the current evaluator. Test filesystem escape, network denial, CPU/native-memory
-limits, cancellation and tenant separation along with rendering. Treat Container
-outputs as untrusted inputs at the host boundary. A successful local Docker run or
-existing software-renderer CI job is insufficient to accept hosted isolation.
+The restricted Docker preflight has now demonstrated that its outer environment
+denies nested namespace creation. The [isolation review](../reviews/2026-10-06-hosted-isolation-review.md)
+therefore selects an explicit per-job Cloudflare microVM adapter as the next
+implementation to qualify, using the existing evaluator protocol. Keep credentials,
+ownership and quotas outside that VM; start from the pinned image without job
+snapshots and destroy the whole instance on completion, cancellation or failure.
+Preserve the existing Bubblewrap adapter and its fail-closed checks for compatible
+Linux hosts. Do not weaken them or claim a process username isolates a managed VM.
+Test network denial, cross-job access, CPU/native-memory limits, output limits and
+crash/cleanup recovery on Cloudflare itself. Local Docker or software-renderer CI
+does not establish the provider boundary or hosted launch acceptance.
Start with `standard-2` as a conservative test fixture, then measure a custom
one-vCPU/3-GiB configuration if RSS and image size permit. Current
diff --git a/docs/reviews/2026-10-06-hosted-isolation-review.md b/docs/reviews/2026-10-06-hosted-isolation-review.md
new file mode 100644
index 00000000..21bf0aa7
--- /dev/null
+++ b/docs/reviews/2026-10-06-hosted-isolation-review.md
@@ -0,0 +1,130 @@
+# Hosted evaluation: isolation review
+
+Research date: 6 October 2026. This records findings and the next implementation
+contract, not Cloudflare qualification or deployment acceptance. Companion to the
+[hosting plan](../plans/2026-10-06-hosting-economics.md) and
+[execution record](2026-10-06-v1-execution.md).
+
+## What failed
+
+PR #145's [native preflight run 37466581995](https://github.com/instruktlabs/kiln/actions/runs/37466581995)
+built its Linux image but failed before evaluating source. Both a minimal
+`unshare --user --map-root-user` command and Bubblewrap were denied namespace
+creation. The receipt is `isolation / wrapper-launch`; the independent trusted
+software-renderer fixture passed all six views. The retained diagnostics are under
+`.cache/native-hosting-run-37466581995/receipts/`.
+
+The outer Docker process was non-root, with all capabilities dropped, no new
+privileges and the default seccomp profile. Ubuntu also reported its AppArmor
+unprivileged-user-namespace restriction enabled. These observations establish
+denial, but do not identify one exclusive denying layer. Docker documents namespace
+syscall restrictions in its [default seccomp profile](https://docs.docker.com/engine/security/seccomp/).
+This is a CI environment compatibility failure, not evidence of a broken renderer
+or a requirement for the owner to approve a Windows Docker setting.
+
+The original preflight combined two distinct questions: whether this restricted
+Docker configuration permits Kiln's inner Linux sandbox, and whether the intended
+managed hosting boundary can safely execute Kiln. A Docker result cannot answer
+the second question.
+
+## Recommended Cloudflare boundary
+
+Cloudflare describes Containers as Linux images inside Firecracker microVMs with
+their own kernels. Native libraries and subprocesses make Containers the relevant
+environment for the existing Kiln engine. Workers remain the control plane.
+Source: [choose a sandbox environment](https://developers.cloudflare.com/sandbox/concepts/).
+
+The provider's [security guidance](https://developers.cloudflare.com/sandbox/concepts/security/)
+treats the entire sandbox as one trust unit. Processes share files and localhost;
+Linux usernames do not isolate them. Secrets and other users' data should stay
+outside. Output needs validation before storage or use.
+
+Our resulting design is **one fresh microVM per admitted evaluation job**:
+
+1. The authenticated Worker verifies ownership, reserves quotas and generates an
+ unguessable execution ID. Client-supplied names cannot select an existing job.
+2. A dedicated execution Durable Object starts a pinned image with Internet access
+ disabled. It receives only the bounded source and resources authorized for that
+ job. No OAuth credentials, account database, bucket mount, broad storage token,
+ previous job files or user-created snapshot enters the VM.
+3. Run the installed engine through its versioned evaluator protocol. Keep the
+ source restrictions, input limits and registry definitions. Arbitrary code
+ execution inside this VM must not become control-plane authority.
+4. The external supervisor enforces startup and total job deadlines, cancellation,
+ instance limits and bounded output. It destroys the VM on every terminal path.
+ A cleanup failure is a failed execution requiring reconciliation, not success.
+5. Validate the response version, request ID, byte limits and artifact structure
+ outside the VM before tenant storage. Never use a returned path, tenant ID,
+ quota count or claimed QA result as authorization. A compromised evaluator can
+ forge its own report; quality claims require their separately defined evidence.
+6. Persist accepted artifacts through the trusted tenant service. Another job
+ starts from the pinned image, including jobs belonging to the same user.
+
+The current [Durable Object Container API](https://developers.cloudflare.com/containers/api/durable-object-container/)
+is the recommended interface for new applications. `ctx.container` exposes image
+identity, startup, direct-argument execution and destruction. An execution signal
+kills its direct process, not all descendants; request cancellation alone does not
+stop execution. Use whole-instance destruction and await it. Do not substitute
+an inactivity timeout for a hard job deadline. Durable alarms must recover cleanup
+after a supervisor interruption. The new scheduling policy remains public beta;
+actual account availability and behavior need the provider probe.
+
+Use the existing `EvaluatorTransportV2` / `createEvaluatorPortV2` seam in
+`src/evaluator/protocol.ts`. Add the Cloudflare adapter in private `hosting/`, with
+its own explicit readiness contract. Do not relabel the Bubblewrap readiness check
+as passed or bypass `loadNativeMcpRuntime`'s current fail-closed path. The existing
+local Linux adapter remains available on a compatible host. Node's
+[`vm` module](https://nodejs.org/api/vm.html) is not an execution security boundary.
+
+## How HOL Guard helps
+
+Reviewed the owner's fork at
+[`dfc2b844`](https://github.com/matthew-kissinger/hol-guard/tree/dfc2b844de26a5fd79124bb2ce5f8e262d59eab6)
+without installing or executing it. It contains both policy/scanning facilities and
+execution adapters. Its older 3.0 baseline documents are not a complete inventory:
+the source also contains an
+[isolation-provider contract](https://github.com/matthew-kissinger/hol-guard/blob/dfc2b844de26a5fd79124bb2ce5f8e262d59eab6/src/codex_plugin_scanner/guard/runtime/isolation_provider.py),
+OCI plan validation and a
+[gVisor reference runner](https://github.com/matthew-kissinger/hol-guard/blob/dfc2b844de26a5fd79124bb2ce5f8e262d59eab6/src/codex_plugin_scanner/guard/runtime/gvisor_reference_runtime.py).
+Useful patterns include pinned provider identity, bounded execution, explicit
+capabilities, forbidden mounts and cleanup evidence. Reading them does not qualify
+their guarantees or establish compatibility with Kiln's native renderer.
+
+Current upstream's
+[containment CI at `2755b3cd`](https://github.com/hashgraph-online/hol-guard/blob/2755b3cd3cd372ec8a08a962de2cc4213d73d49a/.github/workflows/containment-ci.yml)
+deliberately provisions its test hosts. One job grants Bubblewrap user-namespace
+access through an executable-specific AppArmor profile. A separate nested-container
+job adds an outer capability and relaxes outer filters so it can test its inner
+sandbox. Those are distinct test environments, not proof that a default restricted
+Docker container supports nesting. They are useful reference configurations, not
+settings to copy into a public Kiln runtime or onto the owner's PC automatically.
+
+Recommendation: use these contracts and tests as reference material now; evaluate
+optional Kiln plugin compatibility/scanning separately. Do not add the full Python
+runtime, a nested gVisor runtime or a new mandatory end-user dependency to v1 without
+a demonstrated benefit and qualification. No HOL Guard changes or contribution PR
+were made. The owner subsequently explicitly deferred HOL Guard contribution and
+integration work until after a polished Kiln v1. Proceed with the appropriate
+current platform techniques without making HOL Guard a release dependency.
+
+## Qualification sequence
+
+| Gate | Required evidence |
+| --- | --- |
+| Local Linux adapter | Dedicated compatible runner; existing source-denial and isolation corpus; clearly labeled as Linux/Bubblewrap evidence |
+| Private Cloudflare adapter | Tests for fixed image selection, ownership, no Internet, single job, bounded protocol, timeout, abort, output flood, cleanup failure and supervisor recovery |
+| Real provider probe | Exact Worker/image/package identities; network denial, cross-job filesystem/process denial, memory exhaustion, child-process cleanup, deadline and restart recovery |
+| Native execution/rendering | Installed package produces bounded GLB and CPU views; software Vulkan fidelity separately identified; startup, elapsed time and memory measured |
+| Hosted integration | Authenticated MCP invokes the qualified adapter; private save/download/retention and two-user denial tests; admission and accounting cannot trust sandbox claims |
+
+Keep the existing failed receipt as evidence. Changing a test to check a different
+boundary requires a new named receipt, not reinterpreting the old failure as a pass.
+Cloudflare qualification is still a hosted-launch blocker. Package publication has
+its own exact-main archive gates and can progress independently.
+
+No workstation reconfiguration or Docker permission approval is needed now.
+Prepare the private provider probe's reviewed source, resources, access controls,
+cost estimate and teardown before requesting its remaining deployment approval.
+Cloudflare's [Workers Builds path](https://developers.cloudflare.com/containers/guides/deploy/)
+can build images remotely; verify CLI/build support and image identity before
+choosing this over a local Docker dependency.
diff --git a/docs/reviews/2026-10-06-v1-execution.md b/docs/reviews/2026-10-06-v1-execution.md
index 8e46c574..2eae4bf7 100644
--- a/docs/reviews/2026-10-06-v1-execution.md
+++ b/docs/reviews/2026-10-06-v1-execution.md
@@ -21,7 +21,7 @@ published yet.
| P4 | Clean installs and workspace upgrades | In progress: RC package passed all platform CI jobs; official 0.10.0-to-RC upgrades pass for Claude/Codex workspaces with conflict refusal, reapplied customizations and byte-exact old assets; final-version harness checks remain open |
| P5 | Release automation and npm publication | In progress: manual exact-archive workflow and owner runbook; GitHub npm-release environment created with sole owner review, no admin bypass and protected branches; live npm trust, staging approval, registry provenance and fresh registry install remain open |
| H1 | Native Cloudflare qualification | In progress: Linux image built, Trixie software renderer passes six textured views; Docker namespace probe fails closed, Bubblewrap launch-argument defect corrected; real Cloudflare isolation/execution, RSS, startup and measured cost remain pending |
-| H2 | Authenticated MCP and tenant boundary | In progress: Google and GitHub selected with one Kiln account; existing GitHub-only OAuth and native HTTP pass local two-user, storage and reconnect checks; provider-neutral account storage, Google/linking, branded real sign-in, container dispatch and evaluator isolation remain open |
+| H2 | Authenticated MCP and tenant boundary | In progress: Google/GitHub adapters, permanent D1 account IDs, atomic upstream login guards and current account/epoch checks pass 90 local hosted tests; linking, individual connection revocation, branded real sign-in, container dispatch and evaluator isolation remain open |
| H3 | Artifact lifecycle | In progress: tenant SQLite/R2 bytes, ProgramStore and native AssetLibrary, atomic quotas/revision pins, material closures, authenticated downloads, deletion and seven-day unsaved retention pass local workerd and actual-engine checks; standalone MaterialLibrary, native dispatch, browser tickets, account deletion and deployed lifecycle proof remain open |
| H4 | Capacity and operations | In progress: local native request admission, body/response/deadline bounds and cancellation pass; global operational quotas, process cleanup, load/cost measurements, alerts, deployed health/build identity and rollback remain open |
| H5 | Production deployment | Pending: approved deployment at `kiln.instruktlabs.com`; live authenticated create/edit/render/save/download/reconnect flow |
@@ -1127,6 +1127,130 @@ fresh registry/plugin installation precede final 1.0 qualification. Apply the
saved source/document changes selectively after the RC step, then regenerate plugin
metadata and runtime bundles; never restore its stale generated build files.
+### Independent multi-provider account foundation
+
+The tested stdio correction was committed and pushed as
+`6a89d790ba2d786ad641bdab777a40535ef3c19c` on `codex/v1-publication`;
+[CI 37466581875](https://github.com/instruktlabs/kiln/actions/runs/37466581875)
+passed all twelve jobs, including Intel macOS shutdown, coverage and installed
+software Vulkan. Hosted gateway checks 37466581806 and Website 37466582044 also
+passed at the same commit; native preflight 37466581995 still fails isolation.
+PR 145 is ready for review, with approval to merge this exact RC requested through
+the question tool. No merge, npm stage or deployment has occurred.
+Hosting implementation continues on the local
+`codex/v1-hosted-identity` branch based on that commit, preserving the PR 145
+candidate while its release checks and owner handoffs proceed.
+
+The first account-directory contract and D1 migration are implemented independently
+of the OAuth gateway. Canonical verified issuer/subject pairs map to random Kiln
+account IDs; contact data and upstream credentials are not persisted. Atomic D1
+batches and uniqueness constraints prevent duplicate owners and orphan accounts.
+Every lookup starts a new `first-primary` session. Disabled/deleting records are
+returned by state lookup but cannot sign in or create a replacement account.
+
+Six focused tests failed against the initial unimplemented contract and pass with
+the D1 adapter. They include 24 concurrent first sign-ins, distinct issuers with
+matching emails/subjects and a trigger-induced identity failure proving transaction
+rollback. Full hosted suite: 75 passed, no failures; both typechecks and all five
+existing production builds pass. Receipts: `.cache/v1-accounts-before.log`,
+`.cache/v1-accounts-after.log`, `.cache/v1-accounts-full.log`.
+No live D1 database was created. The adapter is not yet wired to authorization or
+tenant selection; Google, linking, epoch enforcement and account lifecycle remain
+open. Simulated primary reads do not prove deployed cross-region revocation.
+
+## Hosted identity integration
+
+The owner-selected Google and GitHub flow is now connected to the D1 account
+directory on `codex/v1-hosted-identity`, separately from the frozen npm RC. Google
+uses pinned `[email protected]`; signatures, both documented Google issuers,
+audience/authorized-party, nonce, expiry, state and exact callback checks are
+exercised with locally generated signing keys. It requests `openid profile` and
+discards upstream credentials. GitHub continues to request no repository scopes.
+Only a permanent Kiln account ID enters a grant or tenant-routing hash.
+
+`0002_login_intents.sql` and its D1 adapter close the upstream same-browser KV
+replay window with atomic, origin/state/provider/purpose-bound claims, after the
+OAuth library verifies its browser cookie. Tests include 24 simultaneous consent
+claims and callback consumes, stale-KV replay, provider swaps, expiry and bounded
+input. No raw state or upstream credentials are stored in these D1 tables.
+Every protected access, code exchange and refresh also reads current primary
+account state and epoch. Disabled/deleting accounts, old epochs and missing
+authority fail closed. Re-enabling after an epoch increment does not restore old
+credentials. These checks use public provider hooks, with no vendor internals
+modified and no custom JWT decoder.
+
+The Google tests first failed against their stub, and a single-audience foreign
+`azp` fixture exposed an additional check now enforced. The login-intent stub
+failed all four contract tests; the new routing contract failed before wiring.
+Full hosted result: **90 passed, no failures**; both hosting typechecks, all five
+production builds and root lint (933 files) pass. Receipts:
+`.cache/v1-google-before.log`, `.cache/v1-google-after.log`,
+`.cache/v1-login-intents-before.log`, `.cache/v1-login-intents-after.log`,
+`.cache/v1-provider-routing-before.log`, `.cache/v1-hosted-identity-full.log`.
+
+This is local implementation evidence, not hosted launch acceptance. No provider
+app, live D1 resource or hosted deployment was created. Explicit account linking,
+browser account sessions, individual connection revocation, deletion orchestration,
+public-endpoint admission limits, completed branding/privacy/support pages and
+actual deployed provider/client and cross-region checks remain open. Native
+provider isolation and dispatch remain independent blockers. PR #145's npm RC
+head was unchanged during this work; its subsequent merge is recorded below.
+
+## RC merge and npm authentication handoff
+
+The owner explicitly approved merging PR #145 at reviewed head
+`6a89d790ba2d786ad641bdab777a40535ef3c19c`. Its complete check set was **15 passed,
+one failed**: all 12 engine/package jobs, both hosted gateway platform jobs and the
+website build passed. The native-hosting preflight remained failed. Its downloaded
+receipt reports `isolation / wrapper-launch`; diagnostics show `unshare` denied
+with `Operation not permitted` and Bubblewrap unable to create a namespace. The
+separate software-renderer receipt passed six views. This is an unresolved hosted
+launch blocker, not an all-green PR and not Cloudflare provider qualification.
+
+GitHub's required linear-history rule rejected a merge commit. A normal squash
+merge of the exact approved head succeeded, with no admin bypass or protection
+change, on 6 October at 13:31 UTC. Main commit:
+`ce640ccae0c621177aad176a03b5a214ae57d266`. The hosting identity branch was rebased
+onto that main commit without changing its implementation. Exact main CI, archive
+review and verify-mode release preparation are now required before staging.
+
+The owner also completed a fresh npm CLI browser sign-in in external Chrome. The
+CLI reported success and an independent `npm whoami` returned `matthew-kissinger`.
+No password, security-key response, recovery code or npm token was read into chat.
+Login and merge published no package and deployed no hosted service.
+
+## Isolation review and exact-main qualification
+
+The owner requested current-practice research on the Docker namespace failure and
+offered their HOL Guard fork as a possible reference. The
+[hosted isolation review](2026-10-06-hosted-isolation-review.md) records the actual
+CI denial, current Cloudflare microVM controls, the fork's local/OCI/gVisor code,
+and upstream's separately provisioned containment test environments. No HOL Guard
+code was installed or run. The owner explicitly deferred its contribution and
+integration work until after a polished v1.
+
+The next hosted implementation is an explicit adapter for a fresh Cloudflare
+microVM per evaluation job, with external network, lifetime and output controls.
+This does not weaken or bypass the existing Linux Bubblewrap readiness contract.
+Cloudflare deployment and adversarial qualification remain open; no workstation
+Docker change is required from the owner at this stage.
+
+All 12 engine/package jobs passed on exact merged main
+`ce640ccae0c621177aad176a03b5a214ae57d266` in
+[CI run 37471433457](https://github.com/instruktlabs/kiln/actions/runs/37471433457).
+Downloaded `node-package-candidate` without repacking: the RC archive is 9,154,941
+bytes, SHA-256
+`f2de7eb69f6e16dd618c77249b1f46eda1b5d032789f5b0d9048b2b2a08ea8c2`.
+Its SDK receipt agrees with that digest. Dispatched
+[release verification 37473250032](https://github.com/instruktlabs/kiln/actions/runs/37473250032)
+from the same main commit, in **verify** mode with no npm staging permission.
+Verification passed. Downloaded `npm-release-review`, inspected `review.json` and
+independently matched its archive digest. The stage job was skipped as intended.
+All 15 checks on hosted identity PR #146 at `255df6a` also passed; that PR remains
+unmerged and does not change this npm candidate. The owner staging/access-setup
+question is now pending because first-time npm staging creates a public placeholder.
+No npm package has been staged or published, and no hosted service has been deployed.
+
## Owner handoffs
Cloudflare CLI consent is complete. After the earlier consent expired, the owner
@@ -1146,8 +1270,7 @@ usable disconnect/deletion controls and actual deployed consent, cancellation,
expiry/revocation and cross-user denial checks. Local fixtures do not establish
those results. No identity app or secret has been provisioned yet.
-The CLI's read-only `npm whoami` check reports that this machine is not signed in.
-A browser login was opened in external Chrome and the owner's password/security-key
-step was surfaced through the question tool. Login does not stage or publish a
-package. Publisher verification and final external approvals remain separate;
-missing human steps do not block independent package work.
+The initial npm browser login did not complete and its terminal-password fallback
+was cancelled. The fresh owner-attended attempt succeeded, as recorded above.
+Trusted publishing configuration, exact-archive staging and owner promotion remain
+separate steps. No package has been staged or published yet.
diff --git a/hosting/README.md b/hosting/README.md
index 4fcae52a..e797c309 100644
--- a/hosting/README.md
+++ b/hosting/README.md
@@ -21,8 +21,8 @@ npm run build
The tests execute the Worker in workerd through the pinned Miniflare package.
Its 5.x API is currently alpha; the exported v4 option converter supplies the
-documented simulation bindings. Tests replace GitHub network responses with fixed
-identities. Routing tests use a recording backend; storage tests use the production
+documented simulation bindings. Tests replace GitHub responses with fixed identities
+and Google responses with locally signed OIDC fixtures. Routing tests use a recording backend; storage tests use the production
tenant Worker with real simulated SQLite and R2 bindings. A combined test connects
both production Workers and verifies authenticated two-user downloads and reconnects.
Separate test-only fault injection covers late upload acknowledgement and failed
@@ -38,6 +38,29 @@ with input/hash/import receipts, are written to
`../.cache/hosted-worker/`. `build` performs no upload, resource provisioning or
deployment. `Hosted gateway checks` runs the same checks on Linux and Windows.
+## Provider-neutral accounts
+
+`src/accounts.ts` defines a provider-neutral account lookup contract and a D1
+adapter. `migrations/0001_accounts.sql` owns the identity index. Verified canonical
+issuer/subject pairs map to random permanent Kiln IDs; email, provider tokens and
+profile names are not stored or used to merge accounts. Registering an identity
+and its new account is one transaction. Each operation starts a primary-backed
+session, independent of caller bookmarks. Disabled/deleting accounts cannot obtain
+a replacement account through ordinary sign-in.
+
+The workerd tests exercise concurrent first sign-ins, unique issuer/subject pairs,
+rollback after an injected identity-write failure and current account-state reads.
+They do not establish cross-region deployment behavior. Both provider adapters now
+resolve this directory before issuing Kiln grants. Every protected-resource token
+validation, authorization-code exchange and refresh checks the current primary
+account state and authorization epoch. Missing/disabled/deleting accounts and old
+epochs fail closed; database outages return unavailable rather than permitting
+cached access. Account lifecycle mutations must increment the epoch atomically.
+Explicit identity linking, browser sessions, connection controls and completed
+asset deletion remain required before launch.
+Only verified server-side provider adapters may call this contract. The JSON
+interface under `test/` exists solely for local tests and is not a public API.
+
## Native HTTP adapter
`src/native-mcp.ts` serves the installed engine's registry through the MCP SDK's
@@ -83,16 +106,22 @@ before deployment.
The owner selected Google and GitHub sign-in for free hosted v1 access, private
saved assets and personal quotas; email can follow. The local package needs no
-Kiln account. The current adapter implements GitHub only. It requests no repository scopes, uses upstream S256 PKCE,
-and resolves the current GitHub user for every login. Only `github-<immutable id>`
-becomes a subject. Login names and email addresses are not tenant identifiers.
-Upstream tokens are used only for the identity lookup and are not stored or passed
-to the backend. This needs a dedicated Instrukt Labs OAuth app; no app or secret
-has been provisioned by this implementation.
-
-Before launch, replace this direct provider subject with a permanent Kiln account
-id resolved from verified `(issuer, subject)` bindings. Google, account storage,
-explicit linking and recovery/account controls are not implemented yet. See the
+Kiln account. GitHub requests no repository scopes, uses upstream S256 PKCE and
+resolves the immutable user ID for every login. Google uses `[email protected]`
+for discovery, code exchange, nonce/issuer/audience/expiry checks and application-level
+signature verification. It requests `openid profile`, uses S256 PKCE, rejects a
+foreign `azp`, and canonicalizes Google's two documented issuer spellings. Network
+responses are bounded and redirects/foreign endpoint origins are refused. Upstream
+access/ID tokens are discarded at the adapter boundary; only verified issuer/subject
+pairs enter the account directory. Login names and email never select a tenant.
+
+The gateway needs `ACCOUNTS` bound to D1 with both migrations applied, plus
+`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID` and
+`GITHUB_CLIENT_SECRET`. Register exact `/oauth/google/callback` and
+`/oauth/github/callback` URLs under the configured `PUBLIC_ORIGIN`, using separate
+test and production provider apps. No live database, provider app or secret has
+been provisioned by this implementation. Existing prototype provider-derived grants
+are deliberately invalid; no deployed user migration is being claimed. See the
[authentication architecture review](../docs/plans/2026-10-05-v1-publication-plan.md#authentication-architecture-review-6-october)
for the selected provider-independent boundary, library comparison, KV consistency
limits and required deployed checks. Equal email addresses never imply permission
@@ -100,24 +129,34 @@ to merge accounts or libraries.
Launch requires a clearly branded Kiln / Instrukt Labs connection page, a verified
service domain, a plain explanation of the granted access, privacy/support links
-and usable disconnect/deletion controls. Verify actual provider consent, denied
+and usable disconnect/deletion controls. The current minimal consent page is not
+the accepted launch design. Verify actual provider consent, denied
and cancelled sign-in, token expiry/revocation and cross-user access on the deployed
service. Local fixtures are not acceptance of that end-user experience or its
-deployed security. Keep GitHub credentials only in the gateway's secret bindings;
+deployed security. Keep provider credentials only in the gateway's secret bindings;
never send them to an evaluator, log them or store them with artifacts.
Consent names the requesting client, verified domain when available, callback
host, scopes and loopback warning. The library binds consent and upstream state
to HttpOnly, Secure browser cookies; the form additionally checks its exact
origin. Client-supplied strings are escaped. The page forbids scripts and framing.
+`src/login-intents.ts` adds atomic D1 claims after the library's browser validation:
+one consent choice per handle, and one callback per origin/state/provider/purpose
+intent. The database stores hashes, not raw state, verifier or nonce. Consent claims
+last one day (longer than the library's ten-minute transaction); upstream intents
+last ten minutes. Indexed cleanup removes at most 128 expired rows per write.
+Replayed stale KV snapshots and concurrent D1 claims are exercised locally.
The `kiln:use` scope permits the engine's asset lifecycle, including deletion;
`offline_access` permits a renewable connection with a fixed 30-day lifetime.
Access tokens expire after 15 minutes. Revocation uses the advertised endpoint.
Production KV propagation means the local revocation test does not promise
instant global revocation; this needs explicit operational qualification.
-Verified OAuth subjects alone select a Durable Object, using a versioned hash of
-issuer and subject. Reconnecting through another client selects the same tenant.
+Verified permanent Kiln account IDs alone select a Durable Object, using a versioned
+hash of the configured Kiln origin and account ID. Reconnecting through another
+client selects the same tenant. Different provider identities are separate until
+an explicit linking flow is implemented; matching email or subject strings do not
+merge their accounts.
Bearer tokens, cookies, session ids, caller tenant headers and program references
cannot choose the object. Only bounded MCP transport headers and request bodies
cross the private binding. The tenant backend must still authorize all references
diff --git a/hosting/migrations/0001_accounts.sql b/hosting/migrations/0001_accounts.sql
new file mode 100644
index 00000000..f4398c8c
--- /dev/null
+++ b/hosting/migrations/0001_accounts.sql
@@ -0,0 +1,16 @@
+CREATE TABLE kiln_accounts (
+ id TEXT PRIMARY KEY NOT NULL,
+ state TEXT NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'disabled', 'deleting')),
+ authorization_epoch INTEGER NOT NULL DEFAULT 1 CHECK (authorization_epoch > 0),
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE kiln_identities (
+ issuer TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY (issuer, subject)
+);
+
+CREATE INDEX kiln_identities_by_account ON kiln_identities(account_id);
diff --git a/hosting/migrations/0002_login_intents.sql b/hosting/migrations/0002_login_intents.sql
new file mode 100644
index 00000000..b496a5fb
--- /dev/null
+++ b/hosting/migrations/0002_login_intents.sql
@@ -0,0 +1,14 @@
+CREATE TABLE kiln_consent_claims (
+ handle_hash TEXT PRIMARY KEY,
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX kiln_consent_expiry ON kiln_consent_claims(expires_at);
+
+CREATE TABLE kiln_login_intents (
+ id TEXT PRIMARY KEY,
+ state_hash TEXT NOT NULL UNIQUE,
+ provider TEXT NOT NULL CHECK(provider IN ('google', 'github')),
+ purpose TEXT NOT NULL CHECK(purpose = 'sign-in'),
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX kiln_login_expiry ON kiln_login_intents(expires_at);
diff --git a/hosting/package-lock.json b/hosting/package-lock.json
index 735d4383..7b114890 100644
--- a/hosting/package-lock.json
+++ b/hosting/package-lock.json
@@ -9,7 +9,8 @@
"version": "1.0.0-rc.1",
"dependencies": {
"@cloudflare/workers-oauth-provider": "1.2.1",
- "@modelcontextprotocol/server": "2.3.0"
+ "@modelcontextprotocol/server": "2.3.0",
+ "oauth4webapi": "3.8.8"
},
"devDependencies": {
"@cloudflare/workers-types": "5.20261006.1",
@@ -1703,6 +1704,15 @@
"node": ">=22.0.0"
}
},
+ "node_modules/oauth4webapi": {
+ "version": "3.8.8",
+ "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
+ "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
diff --git a/hosting/package.json b/hosting/package.json
index bc9a0c48..6cf69659 100644
--- a/hosting/package.json
+++ b/hosting/package.json
@@ -10,7 +10,8 @@
},
"dependencies": {
"@cloudflare/workers-oauth-provider": "1.2.1",
- "@modelcontextprotocol/server": "2.3.0"
+ "@modelcontextprotocol/server": "2.3.0",
+ "oauth4webapi": "3.8.8"
},
"devDependencies": {
"@cloudflare/workers-types": "5.20261006.1",
diff --git a/hosting/src/accounts.ts b/hosting/src/accounts.ts
new file mode 100644
index 00000000..ad68c788
--- /dev/null
+++ b/hosting/src/accounts.ts
@@ -0,0 +1,105 @@
+import { HttpFailure } from './http';
+
+export const IDENTITY_ISSUERS = {
+ google: 'https://accounts.google.com',
+ github: 'https://github.com',
+} as const;
+
+/** Identity inputs may only come from a successfully verified provider adapter. */
+export interface VerifiedIdentity {
+ issuer: string;
+ subject: string;
+}
+
+export interface KilnAccount {
+ id: string;
+ state: 'active' | 'disabled' | 'deleting';
+ authorizationEpoch: number;
+}
+
+export interface AccountDirectory {
+ /** Reuses a binding or atomically creates it; never links existing accounts. */
+ resolveIdentity(identity: VerifiedIdentity): Promise<KilnAccount>;
+ /** Reads current primary state, including disabled/deleting and revocation epoch. */
+ getAccount(id: string): Promise<KilnAccount | null>;
+}
+
+/** A grant can outlive sign-in, but never the account's current authorization epoch. */
+export async function isCurrentAccountGrant(
+ database: D1Database,
+ userId: unknown,
+ props: unknown,
+): Promise<boolean> {
+ if (
+ typeof userId !== 'string' ||
+ !/^ka_[a-f0-9]{32}$/.test(userId) ||
+ !props ||
+ typeof props !== 'object'
+ )
+ return false;
+ const grant = props as Record<string, unknown>;
+ if (
+ grant.userId !== userId ||
+ !Number.isSafeInteger(grant.accountEpoch) ||
+ Number(grant.accountEpoch) < 1
+ )
+ return false;
+ const account = await new D1AccountDirectory(database).getAccount(userId);
+ return account?.state === 'active' && account.authorizationEpoch === grant.accountEpoch;
+}
+
+const accountColumns = 'id, state, authorization_epoch AS authorizationEpoch';
+
+export class D1AccountDirectory implements AccountDirectory {
+ constructor(private readonly database: D1Database) {}
+
+ async resolveIdentity(identity: VerifiedIdentity): Promise<KilnAccount> {
+ if (
+ !identity ||
+ !Object.values(IDENTITY_ISSUERS).some((issuer) => issuer === identity.issuer) ||
+ typeof identity.subject !== 'string' ||
+ !/^[\x21-\x7e]{1,255}$/.test(identity.subject)
+ ) {
+ throw new HttpFailure(400, 'Invalid sign-in identity');
+ }
+ const { issuer, subject } = identity;
+ const id = `ka_${crypto.randomUUID().replace(/-/g, '')}`;
+ const created = Date.now();
+ // A fresh primary-backed session per operation, never a client bookmark.
+ const session = this.database.withSession('first-primary');
+ // D1 batches are transactions. Registration cannot leave an orphan account
+ // when binding fails, or allocate several owners under concurrent callbacks.
+ const results = await session.batch<KilnAccount>([
+ session
+ .prepare(`INSERT INTO kiln_accounts (id, created_at)
+ SELECT ?, ? WHERE NOT EXISTS (
+ SELECT 1 FROM kiln_identities WHERE issuer=? AND subject=?
+ )`)
+ .bind(id, created, issuer, subject),
+ session
+ .prepare(`INSERT INTO kiln_identities (issuer, subject, account_id, created_at)
+ SELECT ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM kiln_accounts WHERE id=?)
+ ON CONFLICT (issuer, subject) DO NOTHING`)
+ .bind(issuer, subject, id, created, id),
+ session
+ .prepare(`SELECT ${accountColumns} FROM kiln_accounts WHERE id=(
+ SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?
+ )`)
+ .bind(issuer, subject),
+ ]);
+ const account = results[2]?.results[0];
+ if (!account) throw new Error('Account registration failed');
+ if (account.state !== 'active') throw new HttpFailure(403, 'Account unavailable');
+ return account;
+ }
+
+ async getAccount(id: string): Promise<KilnAccount | null> {
+ if (typeof id !== 'string' || !/^ka_[a-f0-9]{32}$/.test(id))
+ throw new HttpFailure(400, 'Invalid account');
+ return this.database
+ .withSession('first-primary')
+ .prepare(`SELECT ${accountColumns} FROM kiln_accounts WHERE id=?`)
+ .bind(id)
+ .first<KilnAccount>();
+ }
+}
diff --git a/hosting/src/artifact-store.ts b/hosting/src/artifact-store.ts
index 9c9ef329..cb0a2b16 100644
--- a/hosting/src/artifact-store.ts
+++ b/hosting/src/artifact-store.ts
@@ -187,6 +187,7 @@ export class ArtifactStore {
// Schedule recovery before reserving storage or starting an external write.
await this.schedule(this.now() + UPLOAD_GRACE);
const id = crypto.randomUUID().replace(/-/g, '');
+ const createdAt = this.now();
const row: ArtifactRow = {
id,
object_key: this.prefix + id,
@@ -194,8 +195,8 @@ export class ArtifactStore {
bytes,
filename,
media_type: mediaType,
- created_at: this.now(),
- expires_at: this.now() + 7 * DAY,
+ created_at: createdAt,
+ expires_at: createdAt + 7 * DAY,
state: 'uploading',
};
this.ctx.storage.transactionSync(() => {
diff --git a/hosting/src/auth.ts b/hosting/src/auth.ts
index 7638eb3c..eb716fdb 100644
--- a/hosting/src/auth.ts
+++ b/hosting/src/auth.ts
@@ -5,11 +5,22 @@ import {
type OAuthHelpers,
} from '@cloudflare/workers-oauth-provider';
import { HttpFailure, readBounded, sha256 } from './http';
+import { D1AccountDirectory, IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
+import { googleAuthorizationUrl, type GoogleEnv, googleIdentity } from './google';
+import { D1LoginIntents, type SignInProvider } from './login-intents';
export const SCOPES = ['kiln:use', 'offline_access'];
-export interface SignInEnv {
+export interface SignInEnv extends GoogleEnv {
GITHUB_CLIENT_ID: string;
GITHUB_CLIENT_SECRET: string;
+ ACCOUNTS: D1Database;
+}
+interface SignInTransaction {
+ intentId: string;
+ provider: SignInProvider;
+ purpose: 'sign-in';
+ verifier: string;
+ nonce: string;
}
const escapeHtml = (value: string) =>
value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
@@ -26,9 +37,11 @@ function consentPage(details: ConsentDescription, handle: string): string {
<p>Access will be returned to <strong>${escapeHtml(details.redirectHost)}</strong>.</p>
${details.redirectIsLoopback ? '<p>This connects an app on your computer. Continue only if you started that connection.</p>' : ''}
<ul>${details.scope.map((scope) => `<li>${escapeHtml(descriptions[scope] ?? scope)}</li>`).join('')}</ul>
-<p>Sign in with GitHub to identify your Kiln account. Kiln requests no repository access.</p>
+<p>Hosted access is free within your quota. Sign in to keep saved assets private. Kiln requests no GitHub repository access or Google Drive access.</p>
+<p>Use the same sign-in method when returning to your library.</p>
<form method="post" action="/authorize"><input type="hidden" name="handle" value="${escapeHtml(handle)}">
-<button name="decision" value="approve">Continue with GitHub</button>
+<button name="decision" value="google">Continue with Google</button>
+<button name="decision" value="github">Continue with GitHub</button>
<button name="decision" value="deny">Cancel</button></form></main></html>`;
}
@@ -55,7 +68,7 @@ async function githubIdentity(
verifier: string,
origin: string,
env: SignInEnv,
-): Promise<string> {
+): Promise<VerifiedIdentity> {
const token = await upstreamJson('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
@@ -88,8 +101,8 @@ async function githubIdentity(
throw new HttpFailure(502, 'Invalid sign-in identity');
}
// Immutable provider id, never a mutable login or email. Upstream tokens are
- // discarded here; only this subject is retained by Kiln's OAuth grants.
- return `github-${user.id}`;
+ // discarded here; the account directory owns the provider-neutral subject.
+ return { issuer: IDENTITY_ISSUERS.github, subject: String(user.id) };
}
export async function authorize(
@@ -99,6 +112,7 @@ export async function authorize(
env: SignInEnv,
): Promise<Response> {
const url = new URL(request.url);
+ const intents = new D1LoginIntents(env.ACCOUNTS, origin);
if (url.pathname === '/authorize' && request.method === 'GET') {
const auth = await oauth.parseAuthRequest(request);
if (
@@ -131,19 +145,49 @@ export async function authorize(
throw new HttpFailure(415, 'Expected form data');
}
const form = await request.formData();
+ if (form.getAll('handle').length !== 1 || form.getAll('decision').length !== 1)
+ throw new HttpFailure(400, 'Invalid sign-in form');
const handle = String(form.get('handle') ?? '');
const decision = form.get('decision');
if (decision === 'deny') {
const result = await oauth.denyConsent(request, handle);
+ await intents.claimConsent(handle);
return new Response(null, { status: 302, headers: result.headers });
}
- if (decision !== 'approve') throw new HttpFailure(400, 'Choose whether to connect');
+ if (decision !== 'google' && decision !== 'github')
+ throw new HttpFailure(400, 'Choose how to connect');
const approved = await oauth.approveConsent(request, handle);
+ await intents.claimConsent(handle);
const verifier = crypto.randomUUID().replace(/-/g, '') + crypto.randomUUID().replace(/-/g, '');
+ const data: SignInTransaction = {
+ intentId: crypto.randomUUID(),
+ provider: decision,
+ purpose: 'sign-in',
+ verifier,
+ nonce: crypto.randomUUID().replace(/-/g, ''),
+ };
const upstream = await oauth.beginUpstream(approved.request, {
- data: { verifier },
+ data,
headers: approved.headers,
});
+ await intents.create({
+ id: data.intentId,
+ state: upstream.state,
+ provider: data.provider,
+ purpose: data.purpose,
+ });
+ if (decision === 'google') {
+ upstream.headers.set(
+ 'location',
+ await googleAuthorizationUrl(
+ origin,
+ { state: upstream.state, verifier, nonce: data.nonce },
+ env,
+ request.signal,
+ ),
+ );
+ return new Response(null, { status: 302, headers: upstream.headers });
+ }
const target = new URL('https://github.com/login/oauth/authorize');
target.search = new URLSearchParams({
client_id: env.GITHUB_CLIENT_ID,
@@ -156,8 +200,31 @@ export async function authorize(
upstream.headers.set('location', target.href);
return new Response(null, { status: 302, headers: upstream.headers });
}
- if (url.pathname === '/oauth/github/callback' && request.method === 'GET') {
- const resumed = await oauth.finishUpstream<{ verifier: string }>(request);
+ const callbackProvider =
+ url.pathname === '/oauth/google/callback'
+ ? 'google'
+ : url.pathname === '/oauth/github/callback'
+ ? 'github'
+ : null;
+ if (callbackProvider && request.method === 'GET') {
+ if (url.searchParams.getAll('state').length !== 1)
+ throw new HttpFailure(400, 'Invalid sign-in state');
+ const resumed = await oauth.finishUpstream<SignInTransaction>(request);
+ if (
+ !resumed.data ||
+ resumed.data.provider !== callbackProvider ||
+ resumed.data.purpose !== 'sign-in'
+ )
+ throw new HttpFailure(400, 'Invalid sign-in provider');
+ const state = url.searchParams.get('state') ?? '';
+ // The library validates this state against its browser-bound transaction;
+ // D1 additionally compares its server-retained hash and atomically consumes it.
+ await intents.consume({
+ id: resumed.data.intentId,
+ state,
+ provider: callbackProvider,
+ purpose: resumed.data.purpose,
+ });
if (url.searchParams.has('error')) {
resumed.headers.set('location', authorizationErrorRedirect(resumed.request, 'access_denied'));
return new Response(null, { status: 302, headers: resumed.headers });
@@ -165,13 +232,23 @@ export async function authorize(
const code = url.searchParams.get('code');
if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1)
throw new HttpFailure(400, 'Missing sign-in code');
- const userId = await githubIdentity(code, resumed.data.verifier, origin, env);
+ const identity =
+ callbackProvider === 'google'
+ ? await googleIdentity(
+ request,
+ origin,
+ { state, verifier: resumed.data.verifier, nonce: resumed.data.nonce },
+ env,
+ )
+ : await githubIdentity(code, resumed.data.verifier, origin, env);
+ const account = await new D1AccountDirectory(env.ACCOUNTS).resolveIdentity(identity);
+ const userId = account.id;
const { redirectTo } = await oauth.completeAuthorization({
request: resumed.request,
userId,
metadata: {},
scope: resumed.request.scope,
- props: { userId },
+ props: { userId, accountEpoch: account.authorizationEpoch },
});
resumed.headers.set('location', redirectTo);
return new Response(null, { status: 302, headers: resumed.headers });
diff --git a/hosting/src/gateway.ts b/hosting/src/gateway.ts
index 4a92faf8..3e066b7e 100644
--- a/hosting/src/gateway.ts
+++ b/hosting/src/gateway.ts
@@ -13,8 +13,7 @@ export async function forwardTenant(
): Promise<Response> {
if (!ctx.auth.scope.includes('kiln:use')) return insufficientScope(ctx.auth, ['kiln:use']);
const userId = ctx.auth.userId;
- if (!userId || !/^[A-Za-z0-9_-]{1,256}$/.test(userId))
- throw new HttpFailure(401, 'Invalid identity');
+ if (!userId || !/^ka_[a-f0-9]{32}$/.test(userId)) throw new HttpFailure(401, 'Invalid identity');
const url = new URL(request.url);
const isMcp = url.pathname === '/mcp';
const isArtifact = /^\/mcp\/artifacts\/[A-Za-z0-9_-]{16,128}$/.test(url.pathname);
diff --git a/hosting/src/google.ts b/hosting/src/google.ts
new file mode 100644
index 00000000..9297f6d0
--- /dev/null
+++ b/hosting/src/google.ts
@@ -0,0 +1,175 @@
+import * as oauth from 'oauth4webapi';
+import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';
+import { HttpFailure, readBounded } from './http';
+
+export interface GoogleEnv {
+ GOOGLE_CLIENT_ID: string;
+ GOOGLE_CLIENT_SECRET: string;
+}
+
+/** Values retained server-side for one browser-bound, single-use login intent. */
+export interface GoogleFlow {
+ state: string;
+ verifier: string;
+ nonce: string;
+}
+
+const issuer = new URL(IDENTITY_ISSUERS.google);
+const unavailable = () =>
+ new HttpFailure(502, 'Google sign-in provider unavailable; restart sign-in');
+const failed = () => new HttpFailure(400, 'Google sign-in failed; restart sign-in');
+
+function configuration(origin: string, flow: GoogleFlow, env: GoogleEnv): oauth.Client {
+ if (
+ new URL(origin).protocol !== 'https:' ||
+ new URL(origin).origin !== origin ||
+ !env.GOOGLE_CLIENT_ID ||
+ env.GOOGLE_CLIENT_ID.length > 512 ||
+ !env.GOOGLE_CLIENT_SECRET ||
+ env.GOOGLE_CLIENT_SECRET.length > 4096
+ )
+ throw new HttpFailure(503, 'Google sign-in is not configured');
+ if (
+ !flow.state ||
+ flow.state.length > 4096 ||
+ !/^[A-Za-z0-9._~-]{43,128}$/.test(flow.verifier) ||
+ !/^[A-Za-z0-9_-]{32,128}$/.test(flow.nonce)
+ )
+ throw failed();
+ return { client_id: env.GOOGLE_CLIENT_ID, id_token_signed_response_alg: 'RS256' };
+}
+
+function endpoint(value: unknown, origin: string): string {
+ if (typeof value !== 'string') throw unavailable();
+ const url = new URL(value);
+ if (url.origin !== origin || url.username || url.password || url.hash) throw unavailable();
+ return url.href;
+}
+
+type GoogleHttpOptions = oauth.HttpRequestOptions<'GET' | 'POST', URLSearchParams | undefined>;
+
+function network(signal?: AbortSignal): GoogleHttpOptions {
+ const deadline = AbortSignal.timeout(10_000);
+ const execution = signal ? AbortSignal.any([signal, deadline]) : deadline;
+ return {
+ signal: execution,
+ [oauth.customFetch]: async (url, options) => {
+ try {
+ const target = new URL(url);
+ // The discovery document and provider endpoints are selected by this
+ // adapter, never by callback input. Refuse redirects and non-Google I/O.
+ if (
+ ![
+ 'https://accounts.google.com',
+ 'https://oauth2.googleapis.com',
+ 'https://www.googleapis.com',
+ ].includes(target.origin)
+ )
+ throw unavailable();
+ const response = await fetch(url, { ...options, redirect: 'manual', signal: execution });
+ if ((response.status >= 300 && response.status < 400) || response.status >= 500) {
+ void response.body?.cancel().catch(() => {});
+ throw unavailable();
+ }
+ const bytes = await readBounded(response.body, 65_536, execution);
+ return new Response(bytes, { status: response.status, headers: response.headers });
+ } catch {
+ throw unavailable();
+ }
+ },
+ };
+}
+
+async function metadata(options: GoogleHttpOptions): Promise<oauth.AuthorizationServer> {
+ try {
+ const response = await oauth.discoveryRequest(issuer, options);
+ const server = await oauth.processDiscoveryResponse(issuer, response);
+ endpoint(server.authorization_endpoint, 'https://accounts.google.com');
+ endpoint(server.token_endpoint, 'https://oauth2.googleapis.com');
+ endpoint(server.jwks_uri, 'https://www.googleapis.com');
+ return server;
+ } catch {
+ throw unavailable();
+ }
+}
+
+export async function googleAuthorizationUrl(
+ origin: string,
+ flow: GoogleFlow,
+ env: GoogleEnv,
+ signal?: AbortSignal,
+): Promise<string> {
+ const client = configuration(origin, flow, env);
+ const server = await metadata(network(signal));
+ const target = new URL(server.authorization_endpoint!);
+ target.search = new URLSearchParams({
+ client_id: client.client_id,
+ response_type: 'code',
+ redirect_uri: `${origin}/oauth/google/callback`,
+ scope: 'openid profile',
+ state: flow.state,
+ nonce: flow.nonce,
+ code_challenge: await oauth.calculatePKCECodeChallenge(flow.verifier),
+ code_challenge_method: 'S256',
+ }).toString();
+ return target.href;
+}
+
+export async function googleIdentity(
+ request: Request,
+ origin: string,
+ flow: GoogleFlow,
+ env: GoogleEnv,
+): Promise<VerifiedIdentity> {
+ const client = configuration(origin, flow, env);
+ const callback = new URL(request.url);
+ if (
+ request.method !== 'GET' ||
+ callback.origin !== origin ||
+ callback.pathname !== '/oauth/google/callback'
+ )
+ throw failed();
+ const options = network(request.signal);
+ const server = await metadata(options);
+ try {
+ const parameters = oauth.validateAuthResponse(server, client, callback, flow.state);
+ const response = await oauth.authorizationCodeGrantRequest(
+ server,
+ client,
+ oauth.ClientSecretPost(env.GOOGLE_CLIENT_SECRET),
+ parameters,
+ `${origin}/oauth/google/callback`,
+ flow.verifier,
+ options,
+ );
+ // Google documents both issuer spellings. Each goes through the complete
+ // library validator; no JWT is decoded or modified by Kiln. The resulting
+ // account key is always the canonical HTTPS issuer.
+ let verified: oauth.TokenEndpointResponse | undefined;
+ for (const acceptedIssuer of [server.issuer, 'accounts.google.com']) {
+ const attempt = response.clone();
+ const acceptedServer = { ...server, issuer: acceptedIssuer };
+ try {
+ verified = await oauth.processAuthorizationCodeResponse(acceptedServer, client, attempt, {
+ expectedNonce: flow.nonce,
+ requireIdToken: true,
+ });
+ } catch (error) {
+ if (acceptedIssuer === server.issuer) continue;
+ throw error;
+ }
+ await oauth.validateApplicationLevelSignature(acceptedServer, attempt, options);
+ break;
+ }
+ const claims = verified && oauth.getValidatedIdTokenClaims(verified);
+ if (!claims || !/^[\x21-\x7e]{1,255}$/.test(claims.sub)) throw failed();
+ // This client has no cross-client/hybrid sign-in. The library requires azp
+ // for multiple audiences; also reject a foreign azp with a single audience.
+ if (claims.azp !== undefined && claims.azp !== client.client_id) throw failed();
+ // Upstream access/ID tokens are intentionally discarded at this boundary.
+ return { issuer: IDENTITY_ISSUERS.google, subject: claims.sub };
+ } catch (error) {
+ if (error instanceof HttpFailure) throw error;
+ throw failed();
+ }
+}
diff --git a/hosting/src/login-intents.ts b/hosting/src/login-intents.ts
new file mode 100644
index 00000000..3372a59e
--- /dev/null
+++ b/hosting/src/login-intents.ts
@@ -0,0 +1,95 @@
+import { HttpFailure, sha256 } from './http';
+
+export type SignInProvider = 'google' | 'github';
+export interface LoginIntent {
+ id: string;
+ state: string;
+ provider: SignInProvider;
+ purpose: 'sign-in';
+}
+
+/** Complements browser validation in the OAuth library with atomic replay guards. */
+export class D1LoginIntents {
+ constructor(
+ private readonly database: D1Database,
+ private readonly origin: string,
+ ) {}
+ async claimConsent(handle: string): Promise<void> {
+ bounded(handle);
+ const now = Date.now();
+ const session = this.database.withSession('first-primary');
+ const results = await session.batch([
+ session
+ .prepare(
+ 'DELETE FROM kiln_consent_claims WHERE handle_hash IN (SELECT handle_hash FROM kiln_consent_claims WHERE expires_at<? LIMIT 128)',
+ )
+ .bind(now),
+ session
+ .prepare(
+ 'INSERT INTO kiln_consent_claims(handle_hash, expires_at) VALUES (?, ?) ON CONFLICT DO NOTHING RETURNING handle_hash',
+ )
+ .bind(await sha256(JSON.stringify([this.origin, handle])), now + 86_400_000),
+ ]);
+ // Retain the claim much longer than the library's ten-minute transaction.
+ // Call only after its browser-cookie validation, so a stranger cannot burn it.
+ if (results[1]?.results.length !== 1) throw expired();
+ }
+ async create(intent: LoginIntent): Promise<void> {
+ validate(intent);
+ const now = Date.now();
+ const session = this.database.withSession('first-primary');
+ await session.batch([
+ session
+ .prepare(
+ 'DELETE FROM kiln_login_intents WHERE id IN (SELECT id FROM kiln_login_intents WHERE expires_at<? LIMIT 128)',
+ )
+ .bind(now),
+ session
+ .prepare(
+ 'INSERT INTO kiln_login_intents(id, state_hash, provider, purpose, expires_at) VALUES (?, ?, ?, ?, ?)',
+ )
+ .bind(
+ intent.id,
+ await this.stateHash(intent.state),
+ intent.provider,
+ intent.purpose,
+ now + 600_000,
+ ),
+ ]);
+ }
+ async consume(intent: LoginIntent): Promise<void> {
+ validate(intent);
+ const row = await this.database
+ .withSession('first-primary')
+ .prepare(
+ 'DELETE FROM kiln_login_intents WHERE id=? AND state_hash=? AND provider=? AND purpose=? AND expires_at>? RETURNING id',
+ )
+ .bind(
+ intent.id,
+ await this.stateHash(intent.state),
+ intent.provider,
+ intent.purpose,
+ Date.now(),
+ )
+ .first();
+ if (!row) throw expired();
+ }
+ private stateHash(state: string): Promise<string> {
+ return sha256(JSON.stringify([this.origin, state]));
+ }
+}
+
+const expired = () => new HttpFailure(400, 'Invalid or expired sign-in; restart sign-in');
+function bounded(value: unknown): asserts value is string {
+ if (typeof value !== 'string' || !value || value.length > 4096) throw expired();
+}
+function validate(intent: LoginIntent): void {
+ if (
+ !intent ||
+ !/^[a-f0-9-]{36}$/.test(intent.id) ||
+ !['google', 'github'].includes(intent.provider) ||
+ intent.purpose !== 'sign-in'
+ )
+ throw expired();
+ bounded(intent.state);
+}
diff --git a/hosting/src/worker.ts b/hosting/src/worker.ts
index f640abf1..f936e190 100644
--- a/hosting/src/worker.ts
+++ b/hosting/src/worker.ts
@@ -1,4 +1,9 @@
-import { OAuthAuthorizationServer, OAuthResourceServer } from '@cloudflare/workers-oauth-provider';
+import {
+ OAuthAuthorizationServer,
+ OAuthError,
+ OAuthResourceServer,
+} from '@cloudflare/workers-oauth-provider';
+import { isCurrentAccountGrant } from './accounts';
import { authorize, authorizationFailure, SCOPES, type SignInEnv } from './auth';
import { forwardTenant, type TenantEnv } from './gateway';
import { boundedRequest, HttpFailure, privateResponse } from './http';
@@ -29,14 +34,27 @@ export default {
scopesSupported: SCOPES,
accessTokenTTL: 900,
refreshTokenTTL: 30 * 24 * 60 * 60,
+ tokenExchangeCallback: async ({ env: bindings, userId, props }) => {
+ if (!(await isCurrentAccountGrant(bindings.ACCOUNTS, userId, props)))
+ throw new OAuthError('invalid_grant', {
+ description: 'Account authorization changed; sign in again',
+ });
+ },
// Deliberately do not log request data or provider error descriptions.
onError: () => {},
});
const protectedResource = new OAuthResourceServer<Env>({
resourceMetadata: { resource, authorization_servers: [origin] },
requiredScopes: ['kiln:use'],
- validateToken: (bindings) => (audience, token) =>
- auth.validateToken(audience, token, bindings),
+ validateToken: (bindings) => async (audience, token) => {
+ const verified = await auth.validateToken(audience, token, bindings);
+ if (!verified) return null;
+ if (!(await isCurrentAccountGrant(bindings.ACCOUNTS, verified.userId, verified.props)))
+ throw new OAuthError('invalid_token', {
+ description: 'Account authorization changed; sign in again',
+ });
+ return verified;
+ },
handler: {
fetch: (incoming, bindings, context) =>
forwardTenant(incoming, bindings, context, origin),
@@ -54,8 +72,18 @@ export default {
if (url.search)
throw new HttpFailure(400, 'Query parameters are not supported on resource endpoints');
response = await protectedResource.fetch(request, env, ctx);
- } else if (url.pathname === '/authorize' || url.pathname === '/oauth/github/callback') {
- if (!env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET)
+ } else if (
+ url.pathname === '/authorize' ||
+ url.pathname === '/oauth/github/callback' ||
+ url.pathname === '/oauth/google/callback'
+ ) {
+ if (
+ !env.GITHUB_CLIENT_ID ||
+ !env.GITHUB_CLIENT_SECRET ||
+ !env.GOOGLE_CLIENT_ID ||
+ !env.GOOGLE_CLIENT_SECRET ||
+ !env.ACCOUNTS
+ )
throw new HttpFailure(503, 'Sign-in is not configured');
response = await authorize(
await boundedRequest(request, 16_384),
diff --git a/hosting/test/accounts-worker.ts b/hosting/test/accounts-worker.ts
new file mode 100644
index 00000000..99d80c01
--- /dev/null
+++ b/hosting/test/accounts-worker.ts
@@ -0,0 +1,18 @@
+import { D1AccountDirectory } from '../src/accounts';
+import { serviceFailure } from '../src/http';
+
+// Test-only interface to the directory. Production must only accept identities
+// from verified sign-in adapters, never request bodies or caller headers.
+export default {
+ async fetch(request: Request, env: { ACCOUNTS: D1Database }): Promise<Response> {
+ try {
+ const directory = new D1AccountDirectory(env.ACCOUNTS);
+ const url = new URL(request.url);
+ if (request.method === 'POST')
+ return Response.json(await directory.resolveIdentity(await request.json()));
+ return Response.json(await directory.getAccount(url.pathname.slice(1)));
+ } catch (error) {
+ return serviceFailure(error);
+ }
+ },
+} satisfies ExportedHandler<{ ACCOUNTS: D1Database }>;
diff --git a/hosting/test/accounts.test.mjs b/hosting/test/accounts.test.mjs
new file mode 100644
index 00000000..0bbde174
--- /dev/null
+++ b/hosting/test/accounts.test.mjs
@@ -0,0 +1,159 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import { after, before, test } from 'node:test';
+import { build } from 'esbuild';
+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
+
+let runtime;
+let database;
+const google = 'https://accounts.google.com';
+const github = 'https://github.com';
+before(async () => {
+ const bundle = await build({
+ entryPoints: [fileURLToPath(new URL('./accounts-worker.ts', import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'browser',
+ });
+ runtime = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: bundle.outputFiles[0].text,
+ compatibilityDate: '2026-10-06',
+ d1Databases: ['ACCOUNTS'],
+ outboundService: async () => {
+ throw new Error('Accounts must not fetch');
+ },
+ }),
+ );
+ database = await runtime.getD1Database('ACCOUNTS');
+ const schema = await readFile(
+ new URL('../migrations/0001_accounts.sql', import.meta.url),
+ 'utf8',
+ );
+ await database.batch(
+ schema
+ .split(';')
+ .filter((sql) => sql.trim())
+ .map((sql) => database.prepare(sql)),
+ );
+});
+after(async () => runtime?.dispose());
+
+const resolve = (issuer, subject, extra = {}) =>
+ runtime.dispatchFetch('https://accounts.test/', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ issuer, subject, ...extra }),
+ });
+const count = async () =>
+ (await database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n;
+
+test('verified identities get stable independent Kiln IDs without storing contact data or tokens', async () => {
+ const response = await resolve(github, '1001', {
+ email: '[email protected]',
+ access_token: 'fixture-only',
+ });
+ assert.equal(response.status, 200);
+ const account = await response.json();
+ assert.match(account.id, /^ka_[a-f0-9]{32}$/);
+ assert.equal(account.state, 'active');
+ assert.equal(account.authorizationEpoch, 1);
+ assert.deepEqual(
+ await (await resolve(github, '1001', { email: '[email protected]' })).json(),
+ account,
+ );
+ assert.deepEqual(
+ await (await runtime.dispatchFetch(`https://accounts.test/${account.id}`)).json(),
+ account,
+ );
+ const identity = await database
+ .prepare('SELECT * FROM kiln_identities WHERE issuer=? AND subject=?')
+ .bind(github, '1001')
+ .first();
+ assert.deepEqual(Object.keys(identity).sort(), ['account_id', 'created_at', 'issuer', 'subject']);
+ assert.equal(identity.account_id, account.id);
+});
+
+test('the same email or subject at different issuers never automatically merges accounts', async () => {
+ const a = await (await resolve(github, '2002', { email: '[email protected]' })).json();
+ const b = await (await resolve(google, '2002', { email: '[email protected]' })).json();
+ assert.notEqual(a.id, b.id);
+});
+
+test('concurrent first sign-ins create exactly one identity and one account with no orphan rows', async () => {
+ const before = await count();
+ const responses = await Promise.all(
+ Array.from({ length: 24 }, () => resolve(google, 'concurrent-subject')),
+ );
+ const accounts = await Promise.all(
+ responses.map(async (response) => {
+ assert.equal(response.status, 200);
+ return response.json();
+ }),
+ );
+ assert.equal(new Set(accounts.map((account) => account.id)).size, 1);
+ assert.equal(await count(), before + 1);
+ const identities = await database
+ .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE issuer=? AND subject=?')
+ .bind(google, 'concurrent-subject')
+ .first();
+ assert.equal(identities.n, 1);
+});
+
+test('identity-write failure rolls back its new account as one transaction', async () => {
+ await database
+ .prepare(`CREATE TRIGGER reject_fixture_identity BEFORE INSERT ON kiln_identities
+ WHEN NEW.subject = 'rollback-subject' BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)
+ .run();
+ const before = await count();
+ assert.equal((await resolve(google, 'rollback-subject')).status, 503);
+ assert.equal(await count(), before);
+ await database.prepare('DROP TRIGGER reject_fixture_identity').run();
+ assert.equal((await resolve(google, 'rollback-subject')).status, 200);
+ assert.equal(await count(), before + 1);
+});
+
+test('disabled and deleting accounts cannot sign in or acquire a replacement account', async () => {
+ for (const state of ['disabled', 'deleting']) {
+ const account = await (await resolve(google, `state-${state}`)).json();
+ await database
+ .prepare('UPDATE kiln_accounts SET state=?, authorization_epoch=2 WHERE id=?')
+ .bind(state, account.id)
+ .run();
+ const before = await count();
+ assert.equal((await resolve(google, `state-${state}`)).status, 403);
+ assert.equal(await count(), before);
+ assert.deepEqual(
+ await (await runtime.dispatchFetch(`https://accounts.test/${account.id}`)).json(),
+ { ...account, state, authorizationEpoch: 2 },
+ );
+ }
+});
+
+test('identity keys are bounded, exact and restricted to configured issuers', async () => {
+ const before = await count();
+ for (const [issuer, subject] of [
+ [google, ''],
+ [google, 'a'.repeat(256)],
+ [google, 'bad\nsubject'],
+ [google, 123],
+ ['https://foreign.example', '1001'],
+ [`${google}/`, '1001'],
+ ]) {
+ assert.equal((await resolve(issuer, subject)).status, 400);
+ }
+ assert.equal(await count(), before);
+ const a = await (await resolve(google, 'CaseSensitive')).json();
+ const b = await (await resolve(google, 'casesensitive')).json();
+ assert.notEqual(a.id, b.id);
+ assert.equal((await runtime.dispatchFetch('https://accounts.test/not-an-account')).status, 400);
+ assert.equal(
+ await (
+ await runtime.dispatchFetch('https://accounts.test/ka_00000000000000000000000000000000')
+ ).json(),
+ null,
+ );
+});
diff --git a/hosting/test/auth.test.mjs b/hosting/test/auth.test.mjs
index 1915f548..17948b0d 100644
--- a/hosting/test/auth.test.mjs
+++ b/hosting/test/auth.test.mjs
@@ -1,13 +1,19 @@
import assert from 'node:assert/strict';
-import { createHash, randomBytes } from 'node:crypto';
+import { createHash, generateKeyPairSync, randomBytes, sign } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { after, before, test } from 'node:test';
import { build } from 'esbuild';
import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
+import { migrateAccounts } from './database.mjs';
const origin = 'https://kiln.example.com';
let runtime;
+let database;
let outboundCalls = 0;
+const googleIssuer = 'https://accounts.google.com';
+const googleKeys = generateKeyPairSync('rsa', { modulusLength: 2048 });
+const googleCodes = new Map();
+const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
const digest = (value) => createHash('sha256').update(value).digest('base64url');
const cookies = (response) =>
response.headers
@@ -30,14 +36,56 @@ before(async () => {
compatibilityDate: '2026-10-06',
compatibilityFlags: ['global_fetch_strictly_public'],
kvNamespaces: ['OAUTH_KV'],
+ d1Databases: ['ACCOUNTS'],
durableObjects: { TENANTS: 'TestTenant' },
bindings: {
PUBLIC_ORIGIN: origin,
GITHUB_CLIENT_ID: 'fixture-client',
GITHUB_CLIENT_SECRET: 'fixture-secret-not-a-real-credential',
+ GOOGLE_CLIENT_ID: 'fixture-google-client',
+ GOOGLE_CLIENT_SECRET: 'fixture-google-secret',
},
outboundService: async (request) => {
outboundCalls++;
+ if (request.url === `${googleIssuer}/.well-known/openid-configuration`) {
+ return Response.json({
+ issuer: googleIssuer,
+ authorization_endpoint: `${googleIssuer}/o/oauth2/v2/auth`,
+ token_endpoint: 'https://oauth2.googleapis.com/token',
+ jwks_uri: 'https://www.googleapis.com/oauth2/v3/certs',
+ id_token_signing_alg_values_supported: ['RS256'],
+ code_challenge_methods_supported: ['S256'],
+ });
+ }
+ if (request.url === 'https://www.googleapis.com/oauth2/v3/certs') {
+ return Response.json({
+ keys: [
+ {
+ ...googleKeys.publicKey.export({ format: 'jwk' }),
+ kid: 'test',
+ alg: 'RS256',
+ use: 'sig',
+ },
+ ],
+ });
+ }
+ if (request.url === 'https://oauth2.googleapis.com/token') {
+ const form = new URLSearchParams(await request.text());
+ const flow = googleCodes.get(form.get('code'));
+ assert.ok(flow);
+ assert.equal(digest(form.get('code_verifier')), flow.challenge);
+ assert.equal(form.get('client_id'), 'fixture-google-client');
+ assert.equal(form.get('client_secret'), 'fixture-google-secret');
+ assert.equal(form.get('redirect_uri'), `${origin}/oauth/google/callback`);
+ const now = Math.floor(Date.now() / 1000);
+ const input = `${encode({ alg: 'RS256', kid: 'test' })}.${encode({ iss: googleIssuer, sub: flow.user === 'alice' ? '1001' : '1002', aud: 'fixture-google-client', exp: now + 300, iat: now, nonce: flow.nonce })}`;
+ return Response.json({
+ access_token: 'fixture-google-token',
+ token_type: 'Bearer',
+ expires_in: 300,
+ id_token: `${input}.${sign('RSA-SHA256', Buffer.from(input), googleKeys.privateKey).toString('base64url')}`,
+ });
+ }
if (
[
'https://client.example/metadata.json',
@@ -87,6 +135,8 @@ before(async () => {
},
}),
);
+ database = await runtime.getD1Database('ACCOUNTS');
+ await migrateAccounts(database);
});
after(async () => runtime?.dispose());
@@ -149,7 +199,7 @@ async function consent({
};
}
-async function approve(start, { cookie = start.cookie, decision = 'approve' } = {}) {
+async function approve(start, { cookie = start.cookie, decision = 'github' } = {}) {
return start.server.dispatchFetch(`${origin}/authorize`, {
method: 'POST',
redirect: 'manual',
@@ -158,16 +208,24 @@ async function approve(start, { cookie = start.cookie, decision = 'approve' } =
});
}
-async function grant(user = 'alice', options) {
+async function grant(user = 'alice', options = {}) {
const start = await consent(options);
assert.equal(start.response.status, 200);
- const approved = await approve(start);
+ const provider = options.provider ?? 'github';
+ const approved = await approve(start, { decision: provider });
assert.equal(approved.status, 302);
const upstream = new URL(approved.headers.get('location'));
- assert.equal(upstream.origin, 'https://github.com');
+ assert.equal(upstream.origin, provider === 'github' ? 'https://github.com' : googleIssuer);
assert.equal(upstream.searchParams.get('code_challenge_method'), 'S256');
- assert.equal(upstream.searchParams.get('scope'), '');
- const callback = `${origin}/oauth/github/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code: user })}`;
+ assert.equal(upstream.searchParams.get('scope'), provider === 'github' ? '' : 'openid profile');
+ const code = provider === 'github' ? user : randomBytes(24).toString('base64url');
+ if (provider === 'google')
+ googleCodes.set(code, {
+ user,
+ nonce: upstream.searchParams.get('nonce'),
+ challenge: upstream.searchParams.get('code_challenge'),
+ });
+ const callback = `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`;
const response = await start.server.dispatchFetch(callback, {
headers: { cookie: cookies(approved) },
redirect: 'manual',
@@ -351,6 +409,141 @@ test('same user reconnects to one tenant; another user and forged headers cannot
assert.equal(other.headers['mcp-session-id'], 'session-alice'); // Session IDs never route a tenant.
});
+test('both sign-in choices resolve permanent Kiln accounts, with no cross-provider auto-link', async () => {
+ const page = (await consent()).page;
+ assert.match(page, /Continue with Google/);
+ assert.match(page, /Continue with GitHub/);
+ const first = await token('alice', { provider: 'google' });
+ const again = await token('alice', { provider: 'google' });
+ const github = await token('alice');
+ const googleTenant = (await (await mcp(first)).json()).tenant;
+ assert.equal((await (await mcp(again)).json()).tenant, googleTenant);
+ assert.notEqual((await (await mcp(github)).json()).tenant, googleTenant);
+ const rows = await database
+ .prepare('SELECT issuer, account_id FROM kiln_identities WHERE subject=?')
+ .bind('1001')
+ .all();
+ assert.equal(rows.results.length, 2);
+ for (const row of rows.results) assert.match(row.account_id, /^ka_[a-f0-9]{32}$/);
+});
+
+const refreshToken = (credential) =>
+ runtime.dispatchFetch(`${origin}/oauth/token`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'refresh_token',
+ refresh_token: credential.refresh_token,
+ client_id: credential.clientId,
+ resource: `${origin}/mcp`,
+ }),
+ });
+
+test('current account state and epoch gate tools, downloads, code exchange and refresh', async () => {
+ for (const mutation of ['disable', 'delete', 'epoch']) {
+ const credential = await token('bob');
+ const pendingCode = await grant('bob');
+ const identity = await database
+ .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')
+ .bind('https://github.com', '1002')
+ .first();
+ const state =
+ mutation === 'disable' ? 'disabled' : mutation === 'delete' ? 'deleting' : 'active';
+ await database
+ .prepare(
+ 'UPDATE kiln_accounts SET state=?, authorization_epoch=authorization_epoch+? WHERE id=?',
+ )
+ .bind(state, mutation === 'epoch' ? 1 : 0, identity.account_id)
+ .run();
+ assert.equal((await mcp(credential)).status, 401);
+ assert.equal(
+ (
+ await runtime.dispatchFetch(`${origin}/mcp/artifacts/${'a'.repeat(32)}`, {
+ headers: { authorization: `Bearer ${credential.access_token}` },
+ })
+ ).status,
+ 401,
+ );
+ assert.equal((await exchange(pendingCode)).status, 400);
+ const refused = await refreshToken(credential);
+ assert.equal(refused.status, 400);
+ assert.equal((await refused.json()).error, 'invalid_grant');
+ await database
+ .prepare(
+ 'UPDATE kiln_accounts SET state=?, authorization_epoch=authorization_epoch+1 WHERE id=?',
+ )
+ .bind('active', identity.account_id)
+ .run();
+ // Re-enabling never revives old credentials; an explicit new login is required.
+ assert.equal((await mcp(credential)).status, 401);
+ assert.equal((await mcp(await token('bob'))).status, 200);
+ }
+});
+
+test('an unavailable account authority fails closed for access and refresh', async () => {
+ const credential = await token('alice');
+ await database.prepare('ALTER TABLE kiln_accounts RENAME TO fixture_unavailable_accounts').run();
+ try {
+ const access = await mcp(credential);
+ assert.equal(access.status, 503);
+ assert.ok(!(await access.text()).includes('kiln_accounts'));
+ assert.equal((await refreshToken(credential)).status, 503);
+ } finally {
+ await database
+ .prepare('ALTER TABLE fixture_unavailable_accounts RENAME TO kiln_accounts')
+ .run();
+ }
+ assert.equal((await mcp(credential)).status, 200);
+});
+
+test('a provider callback cannot be swapped onto the other provider route', async () => {
+ for (const provider of ['github', 'google']) {
+ const start = await consent();
+ const approved = await approve(start, { decision: provider });
+ assert.equal(approved.status, 302);
+ const state = new URL(approved.headers.get('location')).searchParams.get('state');
+ const count = outboundCalls;
+ const other = provider === 'google' ? 'github' : 'google';
+ const response = await runtime.dispatchFetch(
+ `${origin}/oauth/${other}/callback?${new URLSearchParams({ state, code: 'alice' })}`,
+ { headers: { cookie: cookies(approved) }, redirect: 'manual' },
+ );
+ assert.equal(response.status, 400);
+ assert.equal(outboundCalls, count);
+ }
+});
+
+test('stale upstream KV cannot replay consent or a completed sign-in', async () => {
+ const kv = await runtime.getKVNamespace('OAUTH_KV');
+ const snapshot = async () => {
+ const { keys } = await kv.list();
+ return Promise.all(keys.map(async ({ name }) => [name, await kv.get(name)]));
+ };
+ const restore = async (records) => {
+ for (const [name, value] of records) if (value !== null) await kv.put(name, value);
+ };
+ const start = await consent();
+ const beforeConsent = await snapshot();
+ const approved = await approve(start);
+ assert.equal(approved.status, 302);
+ await restore(beforeConsent);
+ const count = outboundCalls;
+ assert.equal((await approve(start)).status, 400);
+ assert.equal(outboundCalls, count);
+ const beforeCallback = await snapshot();
+ const state = new URL(approved.headers.get('location')).searchParams.get('state');
+ const callback = () =>
+ runtime.dispatchFetch(
+ `${origin}/oauth/github/callback?${new URLSearchParams({ state, code: 'alice' })}`,
+ { headers: { cookie: cookies(approved) }, redirect: 'manual' },
+ );
+ assert.equal((await callback()).status, 302);
+ await restore(beforeCallback);
+ const afterFirst = outboundCalls;
+ assert.equal((await callback()).status, 400);
+ assert.equal(outboundCalls, afterFirst);
+});
+
test('MCP refuses a foreign browser Origin even with a valid token', async () => {
const credential = await token('alice');
assert.equal(
@@ -501,6 +694,7 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', as
compatibilityDate: '2026-10-06',
compatibilityFlags: ['global_fetch_strictly_public'],
kvNamespaces: ['OAUTH_KV'],
+ d1Databases: ['ACCOUNTS'],
durableObjects: {
TENANTS: { className: 'KilnTenant', scriptName: 'tenant', useSQLite: true },
},
@@ -508,6 +702,8 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', as
PUBLIC_ORIGIN: origin,
GITHUB_CLIENT_ID: 'fixture-client',
GITHUB_CLIENT_SECRET: 'fixture-only-secret',
+ GOOGLE_CLIENT_ID: 'fixture-google-client',
+ GOOGLE_CLIENT_SECRET: 'fixture-google-secret',
},
outboundService: async (request) => {
if (request.url === 'https://github.com/login/oauth/access_token') {
@@ -545,11 +741,17 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', as
}),
);
try {
+ const accounts = await server.getD1Database('ACCOUNTS', 'gateway');
+ await migrateAccounts(accounts);
const alice = await token('alice', { server });
const bob = await token('bob', { server });
const reconnected = await token('alice', { server });
const namespace = await server.getDurableObjectNamespace('TENANTS', 'tenant');
- const name = digest(JSON.stringify(['kiln-tenant-v1', origin, 'github-1001']));
+ const identity = await accounts
+ .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')
+ .bind('https://github.com', '1001')
+ .first();
+ const name = digest(JSON.stringify(['kiln-tenant-v1', origin, identity.account_id]));
const tenant = namespace.get(namespace.idFromName(name));
// Seed bytes through the same private binding used by the future native host.
const bytes = Buffer.from('private retained source');
diff --git a/hosting/test/database.mjs b/hosting/test/database.mjs
new file mode 100644
index 00000000..997f0b86
--- /dev/null
+++ b/hosting/test/database.mjs
@@ -0,0 +1,13 @@
+import { readFile } from 'node:fs/promises';
+
+export async function migrateAccounts(database) {
+ for (const file of ['0001_accounts.sql', '0002_login_intents.sql']) {
+ const source = await readFile(new URL(`../migrations/${file}`, import.meta.url), 'utf8');
+ await database.batch(
+ source
+ .split(';')
+ .filter((sql) => sql.trim())
+ .map((sql) => database.prepare(sql)),
+ );
+ }
+}
diff --git a/hosting/test/google-worker.ts b/hosting/test/google-worker.ts
new file mode 100644
index 00000000..8ea7bdb1
--- /dev/null
+++ b/hosting/test/google-worker.ts
@@ -0,0 +1,20 @@
+import { googleAuthorizationUrl, googleIdentity, type GoogleEnv } from '../src/google';
+import { serviceFailure } from '../src/http';
+
+// Fixtures have no production entry or credentials. The real gateway must load
+// these values from its consumed browser-bound login intent, never from a caller.
+const flow = { state: 's'.repeat(43), verifier: 'v'.repeat(43), nonce: 'n'.repeat(43) };
+export default {
+ async fetch(request: Request, env: GoogleEnv): Promise<Response> {
+ try {
+ const origin = 'https://kiln.example.com';
+ if (new URL(request.url).pathname === '/start')
+ return Response.json({
+ url: await googleAuthorizationUrl(origin, flow, env, request.signal),
+ });
+ return Response.json(await googleIdentity(request, origin, flow, env));
+ } catch (error) {
+ return serviceFailure(error);
+ }
+ },
+} satisfies ExportedHandler<GoogleEnv>;
diff --git a/hosting/test/google.test.mjs b/hosting/test/google.test.mjs
new file mode 100644
index 00000000..fb4329c5
--- /dev/null
+++ b/hosting/test/google.test.mjs
@@ -0,0 +1,224 @@
+import assert from 'node:assert/strict';
+import { createHash, generateKeyPairSync, sign } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { after, before, test } from 'node:test';
+import { build } from 'esbuild';
+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
+
+const origin = 'https://kiln.example.com';
+const issuer = 'https://accounts.google.com';
+const clientId = 'fixture-google-client';
+const state = 's'.repeat(43),
+ verifier = 'v'.repeat(43),
+ nonce = 'n'.repeat(43);
+const keys = generateKeyPairSync('rsa', { modulusLength: 2048 });
+const wrongKeys = generateKeyPairSync('rsa', { modulusLength: 2048 });
+const jwk = {
+ ...keys.publicKey.export({ format: 'jwk' }),
+ kid: 'fixture-key',
+ alg: 'RS256',
+ use: 'sig',
+};
+let runtime;
+let tokenCalls = 0;
+let metadataPatch = {};
+let jwksUnavailable = false;
+const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
+function idToken(mode) {
+ const now = Math.floor(Date.now() / 1000);
+ const claims = {
+ iss: issuer,
+ sub: 'immutable-google-subject',
+ aud: clientId,
+ iat: now,
+ exp: now + 300,
+ nonce,
+ };
+ if (mode === 'legacy-issuer') claims.iss = 'accounts.google.com';
+ if (mode === 'wrong-issuer') claims.iss = 'https://foreign.example';
+ if (mode === 'wrong-audience') claims.aud = 'another-client';
+ if (mode === 'wrong-azp') claims.azp = 'another-client';
+ if (mode === 'expired') claims.exp = now - 600;
+ if (mode === 'wrong-nonce') claims.nonce = 'foreign-nonce';
+ if (mode === 'missing-nonce') delete claims.nonce;
+ if (mode === 'missing-subject') delete claims.sub;
+ const header = { alg: mode === 'unsigned' ? 'none' : 'RS256', kid: 'fixture-key' };
+ const input = `${encode(header)}.${encode(claims)}`;
+ const signature =
+ mode === 'unsigned'
+ ? ''
+ : sign(
+ 'RSA-SHA256',
+ Buffer.from(input),
+ mode === 'wrong-signature' ? wrongKeys.privateKey : keys.privateKey,
+ ).toString('base64url');
+ return `${input}.${signature}`;
+}
+
+before(async () => {
+ const bundle = await build({
+ entryPoints: [fileURLToPath(new URL('./google-worker.ts', import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'browser',
+ });
+ runtime = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: bundle.outputFiles[0].text,
+ compatibilityDate: '2026-10-06',
+ bindings: {
+ GOOGLE_CLIENT_ID: clientId,
+ GOOGLE_CLIENT_SECRET: 'fixture-secret-not-a-credential',
+ },
+ outboundService: async (request) => {
+ if (request.url === `${issuer}/.well-known/openid-configuration`) {
+ assert.equal(request.method, 'GET');
+ assert.equal(request.headers.get('authorization'), null);
+ return Response.json({
+ issuer,
+ authorization_endpoint: `${issuer}/o/oauth2/v2/auth`,
+ token_endpoint: 'https://oauth2.googleapis.com/token',
+ jwks_uri: 'https://www.googleapis.com/oauth2/v3/certs',
+ id_token_signing_alg_values_supported: ['RS256'],
+ code_challenge_methods_supported: ['S256'],
+ ...metadataPatch,
+ });
+ }
+ if (request.url === 'https://oauth2.googleapis.com/token') {
+ tokenCalls++;
+ assert.equal(request.method, 'POST');
+ const form = new URLSearchParams(await request.text());
+ assert.equal(form.get('client_id'), clientId);
+ assert.equal(form.get('client_secret'), 'fixture-secret-not-a-credential');
+ assert.equal(form.get('code_verifier'), verifier);
+ assert.equal(form.get('redirect_uri'), `${origin}/oauth/google/callback`);
+ assert.equal(form.get('grant_type'), 'authorization_code');
+ const mode = form.get('code');
+ if (mode === 'outage')
+ return new Response('private provider diagnostic', { status: 503 });
+ if (mode === 'redirect')
+ return new Response(null, {
+ status: 302,
+ headers: { location: 'https://foreign.example/steal' },
+ });
+ if (mode === 'oversize')
+ return new Response('x'.repeat(70_000), {
+ headers: { 'content-type': 'application/json' },
+ });
+ return Response.json({
+ access_token: 'fixture-access-token',
+ token_type: 'Bearer',
+ expires_in: 300,
+ ...(mode === 'missing-token' ? {} : { id_token: idToken(mode) }),
+ });
+ }
+ if (request.url === 'https://www.googleapis.com/oauth2/v3/certs') {
+ assert.equal(request.method, 'GET');
+ assert.equal(request.headers.get('authorization'), null);
+ return jwksUnavailable
+ ? new Response('private JWKS diagnostic', { status: 503 })
+ : Response.json({ keys: [jwk] });
+ }
+ throw new Error('Unexpected Google fixture request');
+ },
+ }),
+ );
+});
+after(async () => runtime?.dispose());
+const callback = (code = 'valid', extra = '') =>
+ runtime.dispatchFetch(`${origin}/oauth/google/callback?code=${code}&state=${state}${extra}`);
+
+test('Google authorization uses minimal scopes, exact callback, state, nonce and S256', async () => {
+ const response = await runtime.dispatchFetch(`${origin}/start`);
+ assert.equal(response.status, 200);
+ const url = new URL((await response.json()).url);
+ assert.equal(url.origin + url.pathname, `${issuer}/o/oauth2/v2/auth`);
+ assert.equal(url.searchParams.get('client_id'), clientId);
+ assert.equal(url.searchParams.get('scope'), 'openid profile');
+ assert.equal(url.searchParams.get('redirect_uri'), `${origin}/oauth/google/callback`);
+ assert.equal(url.searchParams.get('response_type'), 'code');
+ assert.equal(url.searchParams.get('state'), state);
+ assert.equal(url.searchParams.get('nonce'), nonce);
+ assert.equal(url.searchParams.get('code_challenge_method'), 'S256');
+ assert.equal(
+ url.searchParams.get('code_challenge'),
+ createHash('sha256').update(verifier).digest('base64url'),
+ );
+ assert.equal(url.searchParams.has('client_secret'), false);
+ assert.equal(url.searchParams.has('access_type'), false);
+});
+
+test('both documented Google issuer spellings verify and produce one canonical identity without tokens', async () => {
+ for (const code of ['valid', 'legacy-issuer']) {
+ const response = await callback(code);
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), { issuer, subject: 'immutable-google-subject' });
+ }
+});
+
+test('invalid ID tokens fail issuer, audience, authorized-party, expiry, nonce and signature checks', async () => {
+ for (const mode of [
+ 'wrong-issuer',
+ 'wrong-audience',
+ 'wrong-azp',
+ 'expired',
+ 'wrong-nonce',
+ 'missing-nonce',
+ 'missing-subject',
+ 'wrong-signature',
+ 'unsigned',
+ 'missing-token',
+ ]) {
+ const response = await callback(mode);
+ assert.equal(response.status, 400, mode);
+ assert.equal(await response.text(), 'Google sign-in failed; restart sign-in');
+ }
+});
+
+test('state errors, duplicate codes, a foreign callback and provider denial stop before token exchange', async () => {
+ const before = tokenCalls;
+ for (const url of [
+ `${origin}/oauth/google/callback?code=valid&state=foreign`,
+ `${origin}/oauth/google/callback?code=valid`,
+ `${origin}/oauth/google/callback?code=valid&code=other&state=${state}`,
+ `${origin}/oauth/google/callback?error=access_denied&state=${state}`,
+ `${origin}/oauth/github/callback?code=valid&state=${state}`,
+ `https://foreign.example/oauth/google/callback?code=valid&state=${state}`,
+ ])
+ assert.equal((await runtime.dispatchFetch(url)).status, 400);
+ assert.equal(tokenCalls, before);
+});
+
+test('discovery cannot redirect credentials or JWKS requests to a different service', async () => {
+ const before = tokenCalls;
+ try {
+ for (const patch of [
+ { issuer: 'https://foreign.example' },
+ { token_endpoint: 'https://foreign.example/token' },
+ { jwks_uri: 'http://127.0.0.1/keys' },
+ { authorization_endpoint: 'https://foreign.example/authorize' },
+ ]) {
+ metadataPatch = patch;
+ assert.equal((await callback()).status, 502);
+ }
+ } finally {
+ metadataPatch = {};
+ }
+ assert.equal(tokenCalls, before);
+});
+
+test('provider outages, redirects and oversized responses fail without exposing diagnostic bodies', async () => {
+ for (const mode of ['outage', 'redirect', 'oversize']) {
+ const response = await callback(mode);
+ assert.equal(response.status, 502, mode);
+ assert.equal(await response.text(), 'Google sign-in provider unavailable; restart sign-in');
+ }
+ jwksUnavailable = true;
+ try {
+ assert.equal((await callback()).status, 502);
+ } finally {
+ jwksUnavailable = false;
+ }
+});
diff --git a/hosting/test/login-intents-worker.ts b/hosting/test/login-intents-worker.ts
new file mode 100644
index 00000000..9923bc27
--- /dev/null
+++ b/hosting/test/login-intents-worker.ts
@@ -0,0 +1,27 @@
+import { authorizationFailure } from '../src/auth';
+import { D1LoginIntents, type LoginIntent } from '../src/login-intents';
+
+export default {
+ async fetch(request: Request, env: { ACCOUNTS: D1Database }): Promise<Response> {
+ try {
+ const input = (await request.json()) as LoginIntent & { handle: string };
+ const store = new D1LoginIntents(env.ACCOUNTS, new URL(request.url).origin);
+ switch (new URL(request.url).pathname) {
+ case '/consent':
+ await store.claimConsent(input.handle);
+ break;
+ case '/create':
+ await store.create(input);
+ break;
+ case '/consume':
+ await store.consume(input);
+ break;
+ default:
+ return new Response(null, { status: 404 });
+ }
+ return new Response(null, { status: 204 });
+ } catch (error) {
+ return authorizationFailure(error);
+ }
+ },
+};
diff --git a/hosting/test/login-intents.test.mjs b/hosting/test/login-intents.test.mjs
new file mode 100644
index 00000000..94db085e
--- /dev/null
+++ b/hosting/test/login-intents.test.mjs
@@ -0,0 +1,94 @@
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { after, before, test } from 'node:test';
+import { build } from 'esbuild';
+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';
+import { migrateAccounts } from './database.mjs';
+
+let runtime, database;
+before(async () => {
+ const bundle = await build({
+ entryPoints: [fileURLToPath(new URL('./login-intents-worker.ts', import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'browser',
+ external: ['cloudflare:workers'],
+ });
+ runtime = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ script: bundle.outputFiles[0].text,
+ compatibilityDate: '2026-10-06',
+ d1Databases: ['ACCOUNTS'],
+ }),
+ );
+ database = await runtime.getD1Database('ACCOUNTS');
+ await migrateAccounts(database);
+});
+after(async () => runtime?.dispose());
+const intent = () => ({
+ id: randomUUID(),
+ state: randomUUID(),
+ provider: 'google',
+ purpose: 'sign-in',
+});
+const call = (action, input, origin = 'https://kiln.test') =>
+ runtime.dispatchFetch(`${origin}/${action}`, { method: 'POST', body: JSON.stringify(input) });
+
+test('only one simultaneous use of a browser-validated consent handle succeeds', async () => {
+ const input = { handle: randomUUID() };
+ const results = await Promise.all(Array.from({ length: 24 }, () => call('consent', input)));
+ assert.equal(results.filter((r) => r.status === 204).length, 1);
+ assert.equal(results.filter((r) => r.status === 400).length, 23);
+ assert.equal((await call('consent', input, 'https://other.test')).status, 204);
+});
+
+test('only one simultaneous callback can consume an intent, even with stale upstream KV', async () => {
+ const input = intent();
+ assert.equal((await call('create', input)).status, 204);
+ const stored = await database
+ .prepare('SELECT * FROM kiln_login_intents WHERE id=?')
+ .bind(input.id)
+ .first();
+ assert.ok(!JSON.stringify(stored).includes(input.state));
+ const results = await Promise.all(Array.from({ length: 24 }, () => call('consume', input)));
+ assert.equal(results.filter((r) => r.status === 204).length, 1);
+ assert.equal(results.filter((r) => r.status === 400).length, 23);
+});
+
+test('provider, purpose, origin and state must all match without burning the valid intent', async () => {
+ const input = intent();
+ assert.equal((await call('create', input)).status, 204);
+ for (const patch of [
+ { provider: 'github' },
+ { purpose: 'link' },
+ { state: randomUUID() },
+ { id: randomUUID() },
+ ]) {
+ assert.equal((await call('consume', { ...input, ...patch })).status, 400);
+ }
+ assert.equal((await call('consume', input, 'https://other.test')).status, 400);
+ assert.equal((await call('consume', input)).status, 204);
+});
+
+test('expired intents fail closed; malformed input cannot reach storage', async () => {
+ const input = intent();
+ assert.equal((await call('create', input)).status, 204);
+ await database
+ .prepare('UPDATE kiln_login_intents SET expires_at=0 WHERE id=?')
+ .bind(input.id)
+ .run();
+ assert.equal((await call('consume', input)).status, 400);
+ for (const patch of [
+ { id: '' },
+ { state: '' },
+ { state: 'x'.repeat(4097) },
+ { provider: 'foreign' },
+ { purpose: 'link' },
+ ]) {
+ assert.equal((await call('create', { ...intent(), ...patch })).status, 400);
+ }
+ assert.equal((await call('consent', { handle: '' })).status, 400);
+});
diff --git a/hosting/test/storage-fault-worker.ts b/hosting/test/storage-fault-worker.ts
index 661cb7c3..45180b46 100644
--- a/hosting/test/storage-fault-worker.ts
+++ b/hosting/test/storage-fault-worker.ts
@@ -28,11 +28,13 @@ export class StorageFaultFixture extends DurableObject<{ ARTIFACTS: R2Bucket }>
return typeof value === 'function' ? value.bind(target) : value;
},
});
+ let fixtureClock = Date.now();
this.artifacts = new ArtifactStore(
ctx,
bucket,
{ maxBytes: 1024 * 1024, maxObjects: 32, maxGroups: 8 },
- () => Date.now() + (fault('aged') ? 16 * 60 * 1000 : 0),
+ () =>
+ fault('ticking-clock') ? ++fixtureClock : Date.now() + (fault('aged') ? 16 * 60 * 1000 : 0),
500,
);
}
diff --git a/hosting/test/storage-fault.test.mjs b/hosting/test/storage-fault.test.mjs
index e1d3cb7b..3ad4290c 100644
--- a/hosting/test/storage-fault.test.mjs
+++ b/hosting/test/storage-fault.test.mjs
@@ -55,6 +55,15 @@ const upload = (owner, path = '/upload') =>
});
const prefix = (owner) => `tenants/${namespace.idFromName(owner)}/artifacts/`;
+test('unsaved retention uses one creation instant even when the clock advances', async () => {
+ const db = await database('retention-clock');
+ await db.exec("INSERT INTO faults VALUES ('ticking-clock')");
+ const result = await upload('retention-clock');
+ assert.equal(result.status, 201);
+ const record = await result.json();
+ assert.equal(record.expiresAt - record.createdAt, 7 * 24 * 60 * 60 * 1000);
+});
+
test('upload deadline includes R2 acknowledgement and retains failed-cleanup quota for retry', async () => {
const db = await database('deadline');
await db.exec("INSERT INTO faults VALUES ('slow-ack'), ('delete-failure')");