@quickback-dev/cli 0.70.45 → 0.72.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/build.d.ts.map +1 -1
- package/dist/commands/build.js +10 -1
- package/dist/commands/build.js.map +1 -1
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +7 -1
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/mcp.d.ts.map +1 -1
- package/dist/commands/mcp.js +6 -5
- package/dist/commands/mcp.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/access-manifest-diff.d.ts +6 -0
- package/dist/lib/access-manifest-diff.d.ts.map +1 -1
- package/dist/lib/access-manifest-diff.js +10 -0
- package/dist/lib/access-manifest-diff.js.map +1 -1
- package/dist/lib/action-harvest.d.ts.map +1 -1
- package/dist/lib/action-harvest.js +36 -0
- package/dist/lib/action-harvest.js.map +1 -1
- package/dist/lib/api-client.d.ts +8 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/deployment-target.d.ts +13 -0
- package/dist/lib/deployment-target.d.ts.map +1 -1
- package/dist/lib/deployment-target.js +4 -0
- package/dist/lib/deployment-target.js.map +1 -1
- package/dist/lib/file-loader.d.ts +22 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +80 -18
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/file-writer.js +9 -0
- package/dist/lib/file-writer.js.map +1 -1
- package/dist/lib/harness.d.ts +10 -0
- package/dist/lib/harness.d.ts.map +1 -1
- package/dist/lib/harness.js +31 -0
- package/dist/lib/harness.js.map +1 -1
- package/dist/lib/migrations/executor.js +5 -1
- package/dist/lib/migrations/executor.js.map +1 -1
- package/dist/lib/migrations/plan.js +3 -0
- package/dist/lib/migrations/plan.js.map +1 -1
- package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
- package/dist/lib/migrations/postprocessors/index.js +23 -2
- package/dist/lib/migrations/postprocessors/index.js.map +1 -1
- package/dist/lib/migrations/postprocessors/tenant-bundle.d.ts +30 -0
- package/dist/lib/migrations/postprocessors/tenant-bundle.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/tenant-bundle.js +109 -0
- package/dist/lib/migrations/postprocessors/tenant-bundle.js.map +1 -0
- package/dist/lib/migrations/prior-state.d.ts +13 -1
- package/dist/lib/migrations/prior-state.d.ts.map +1 -1
- package/dist/lib/migrations/prior-state.js +33 -2
- package/dist/lib/migrations/prior-state.js.map +1 -1
- package/dist/lib/migrations/types.d.ts +2 -2
- package/dist/lib/migrations/types.d.ts.map +1 -1
- package/dist/lib/migrations/types.js +3 -0
- package/dist/lib/migrations/types.js.map +1 -1
- package/dist/lib/wrangler-resources.d.ts +14 -1
- package/dist/lib/wrangler-resources.d.ts.map +1 -1
- package/dist/lib/wrangler-resources.js +29 -7
- package/dist/lib/wrangler-resources.js.map +1 -1
- package/dist/skill/docs/api/actions.md +73 -2
- package/dist/skill/docs/api/batch-operations.md +2 -0
- package/dist/skill/docs/api/caching.md +2 -2
- package/dist/skill/docs/api/crud.md +13 -0
- package/dist/skill/docs/api/errors.md +111 -10
- package/dist/skill/docs/api/index.md +24 -0
- package/dist/skill/docs/api/openapi.md +8 -0
- package/dist/skill/docs/api/query-params.md +6 -0
- package/dist/skill/docs/configure/agents.md +73 -1
- package/dist/skill/docs/configure/auth.md +7 -1
- package/dist/skill/docs/configure/bindings.md +55 -0
- package/dist/skill/docs/configure/cloudflare-access.md +191 -0
- package/dist/skill/docs/configure/domains.md +1 -1
- package/dist/skill/docs/configure/index.md +4 -2
- package/dist/skill/docs/configure/providers.md +2 -1
- package/dist/skill/docs/configure/tenancy.md +3 -0
- package/dist/skill/docs/configure/tenant-databases.md +2407 -0
- package/dist/skill/docs/define/access.md +33 -1
- package/dist/skill/docs/define/actions/defining.md +118 -1
- package/dist/skill/docs/define/actions/scoped-db.md +32 -8
- package/dist/skill/docs/define/areas.md +145 -2
- package/dist/skill/docs/define/diagnostics.md +160 -21
- package/dist/skill/docs/define/encryption.md +13 -2
- package/dist/skill/docs/define/fga.md +320 -42
- package/dist/skill/docs/define/firewall.md +4 -0
- package/dist/skill/docs/define/index.md +1 -0
- package/dist/skill/docs/define/read.md +39 -0
- package/dist/skill/docs/define/relationships.md +30 -12
- package/dist/skill/docs/define/schema.md +2 -0
- package/dist/skill/docs/define/scopes.md +393 -9
- package/dist/skill/docs/define/sealed-protocol.md +67 -12
- package/dist/skill/docs/define/transitions.md +4 -1
- package/dist/skill/docs/define/triggers.md +55 -1
- package/dist/skill/docs/platform/api-contract/index.md +4 -2
- package/dist/skill/docs/platform/auth/jwt-optimization.md +13 -1
- package/dist/skill/docs/platform/auth/using-auth.md +1 -1
- package/dist/skill/docs/platform/database/d1.md +112 -3
- package/dist/skill/docs/platform/database/data-migrations.md +3 -1
- package/dist/skill/docs/platform/database/neon.md +10 -2
- package/dist/skill/docs/platform/queues/handlers.md +48 -16
- package/dist/skill/docs/platform/queues/using-queues.md +16 -0
- package/dist/skill/docs/platform/realtime/durable-objects.md +285 -17
- package/dist/skill/docs/platform/realtime/index.md +9 -6
- package/dist/skill/docs/platform/realtime/named-invalidations.md +3 -1
- package/dist/skill/docs/platform/realtime/using-realtime.md +28 -3
- package/dist/skill/docs/platform/schedules/index.md +1 -1
- package/dist/skill/docs/platform/storage/r2.md +10 -1
- package/dist/skill/docs/platform/storage/using-r2.md +42 -1
- package/dist/skill/docs/tooling/output.md +9 -2
- package/dist/skill/docs/ui/account/features/admin.md +5 -3
- package/dist/skill/docs/ui/account/hooks.md +9 -2
- package/dist/skill/docs/ui/admin/index.md +1 -1
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +73 -2
- package/src/skill/docs/api/batch-operations.md +2 -0
- package/src/skill/docs/api/caching.md +2 -2
- package/src/skill/docs/api/crud.md +13 -0
- package/src/skill/docs/api/errors.md +111 -10
- package/src/skill/docs/api/index.md +24 -0
- package/src/skill/docs/api/openapi.md +8 -0
- package/src/skill/docs/api/query-params.md +6 -0
- package/src/skill/docs/configure/agents.md +73 -1
- package/src/skill/docs/configure/auth.md +7 -1
- package/src/skill/docs/configure/bindings.md +55 -0
- package/src/skill/docs/configure/cloudflare-access.md +191 -0
- package/src/skill/docs/configure/domains.md +1 -1
- package/src/skill/docs/configure/index.md +4 -2
- package/src/skill/docs/configure/providers.md +2 -1
- package/src/skill/docs/configure/tenancy.md +3 -0
- package/src/skill/docs/configure/tenant-databases.md +2407 -0
- package/src/skill/docs/define/access.md +33 -1
- package/src/skill/docs/define/actions/defining.md +118 -1
- package/src/skill/docs/define/actions/scoped-db.md +32 -8
- package/src/skill/docs/define/areas.md +145 -2
- package/src/skill/docs/define/diagnostics.md +160 -21
- package/src/skill/docs/define/encryption.md +13 -2
- package/src/skill/docs/define/fga.md +320 -42
- package/src/skill/docs/define/firewall.md +4 -0
- package/src/skill/docs/define/index.md +1 -0
- package/src/skill/docs/define/read.md +39 -0
- package/src/skill/docs/define/relationships.md +30 -12
- package/src/skill/docs/define/schema.md +2 -0
- package/src/skill/docs/define/scopes.md +393 -9
- package/src/skill/docs/define/sealed-protocol.md +67 -12
- package/src/skill/docs/define/transitions.md +4 -1
- package/src/skill/docs/define/triggers.md +55 -1
- package/src/skill/docs/platform/api-contract/index.md +4 -2
- package/src/skill/docs/platform/auth/jwt-optimization.md +13 -1
- package/src/skill/docs/platform/auth/using-auth.md +1 -1
- package/src/skill/docs/platform/database/d1.md +112 -3
- package/src/skill/docs/platform/database/data-migrations.md +3 -1
- package/src/skill/docs/platform/database/neon.md +10 -2
- package/src/skill/docs/platform/queues/handlers.md +48 -16
- package/src/skill/docs/platform/queues/using-queues.md +16 -0
- package/src/skill/docs/platform/realtime/durable-objects.md +285 -17
- package/src/skill/docs/platform/realtime/index.md +9 -6
- package/src/skill/docs/platform/realtime/named-invalidations.md +3 -1
- package/src/skill/docs/platform/realtime/using-realtime.md +28 -3
- package/src/skill/docs/platform/schedules/index.md +1 -1
- package/src/skill/docs/platform/storage/r2.md +10 -1
- package/src/skill/docs/platform/storage/using-r2.md +42 -1
- package/src/skill/docs/tooling/output.md +9 -2
- package/src/skill/docs/ui/account/features/admin.md +5 -3
- package/src/skill/docs/ui/account/hooks.md +9 -2
- package/src/skill/docs/ui/admin/index.md +1 -1
- package/dist/codex/AGENTS.md +0 -290
- package/dist/commands/build.test.d.ts.map +0 -1
- package/dist/commands/codex.d.ts +0 -16
- package/dist/commands/codex.d.ts.map +0 -1
- package/dist/commands/codex.js +0 -159
- package/dist/commands/codex.js.map +0 -1
- package/dist/commands/compile.d.ts +0 -62
- package/dist/commands/compile.d.ts.map +0 -1
- package/dist/commands/compile.js +0 -830
- package/dist/commands/compile.js.map +0 -1
- package/dist/commands/compile.test.d.ts.map +0 -1
- package/dist/commands/init.d.ts +0 -6
- package/dist/commands/init.d.ts.map +0 -1
- package/dist/commands/init.js +0 -405
- package/dist/commands/init.js.map +0 -1
- package/dist/commands/migrate.test.d.ts.map +0 -1
- package/dist/commands/migrations.test.d.ts.map +0 -1
- package/dist/commands/push.test.d.ts.map +0 -1
- package/dist/commands/schema.test.d.ts.map +0 -1
- package/dist/docs/content.d.ts +0 -7
- package/dist/docs/content.d.ts.map +0 -1
- package/dist/docs/content.js +0 -672
- package/dist/docs/content.js.map +0 -1
- package/dist/docs/index.test.d.ts.map +0 -1
- package/dist/lib/action-harvest.test.d.ts.map +0 -1
- package/dist/lib/api-client.test.d.ts.map +0 -1
- package/dist/lib/artifact-routing.test.d.ts.map +0 -1
- package/dist/lib/auth.test.d.ts.map +0 -1
- package/dist/lib/compile-next-steps.test.d.ts.map +0 -1
- package/dist/lib/compiler-floor.test.d.ts.map +0 -1
- package/dist/lib/config-id-splice.test.d.ts.map +0 -1
- package/dist/lib/config-sync.test.d.ts.map +0 -1
- package/dist/lib/copy-public-assets.test.d.ts.map +0 -1
- package/dist/lib/copy-source-apps.test.d.ts.map +0 -1
- package/dist/lib/drizzle-meta-routing.test.d.ts.map +0 -1
- package/dist/lib/file-loader-typescript-fallback.test.d.ts.map +0 -1
- package/dist/lib/file-loader.test.d.ts.map +0 -1
- package/dist/lib/file-writer.test.d.ts.map +0 -1
- package/dist/lib/helpers.d.ts +0 -39
- package/dist/lib/helpers.d.ts.map +0 -1
- package/dist/lib/helpers.js +0 -299
- package/dist/lib/helpers.js.map +0 -1
- package/dist/lib/migrations/drizzle-prompts.test.d.ts.map +0 -1
- package/dist/lib/migrations/drizzle.test.d.ts.map +0 -1
- package/dist/lib/migrations/executor.test.d.ts.map +0 -1
- package/dist/lib/migrations/inventory.test.d.ts.map +0 -1
- package/dist/lib/migrations/lock.test.d.ts.map +0 -1
- package/dist/lib/migrations/paths.test.d.ts.map +0 -1
- package/dist/lib/migrations/plan.test.d.ts.map +0 -1
- package/dist/lib/migrations/postprocessors/index.test.d.ts.map +0 -1
- package/dist/lib/migrations/prompt-runner.test.d.ts.map +0 -1
- package/dist/lib/migrations/staging.test.d.ts.map +0 -1
- package/dist/lib/neon-canary.test.d.ts.map +0 -1
- package/dist/lib/neon-target.test.d.ts.map +0 -1
- package/dist/lib/neon.test.d.ts.map +0 -1
- package/dist/lib/prepare-output.test.d.ts.map +0 -1
- package/dist/lib/prepare-state-output.test.d.ts.map +0 -1
- package/dist/lib/schema-sync/index.test.d.ts.map +0 -1
- package/dist/lib/shell.test.d.ts.map +0 -1
- package/dist/lib/sweep-stale.d.ts +0 -25
- package/dist/lib/sweep-stale.d.ts.map +0 -1
- package/dist/lib/sweep-stale.js +0 -179
- package/dist/lib/sweep-stale.js.map +0 -1
- package/dist/lib/sweep-stale.test.d.ts.map +0 -1
- package/dist/lib/wrangler-resources.test.d.ts.map +0 -1
|
@@ -51,6 +51,11 @@ authz: {
|
|
|
51
51
|
|
|
52
52
|
### 2. Enter the scope
|
|
53
53
|
|
|
54
|
+
> **Deprecated**
|
|
55
|
+
>
|
|
56
|
+
> Scope-token minting through `POST /scope/v1/enter` is deprecated in favour of [instance-bound OAuth tokens](#instance-bound-oauth-tokens). It keeps working, and the compiler warns where a project uses it. Removal is a later major. See [Migrating to instance-bound OAuth tokens](#migrating-to-instance-bound-oauth-tokens).
|
|
57
|
+
|
|
58
|
+
|
|
54
59
|
```http
|
|
55
60
|
POST /scope/v1/enter (session OR existing JWT auth)
|
|
56
61
|
{ "eventId": "evt_123" }
|
|
@@ -118,11 +123,14 @@ export default feature('guests', {
|
|
|
118
123
|
| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/define/firewall) |
|
|
119
124
|
| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |
|
|
120
125
|
| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |
|
|
126
|
+
| **Realtime** (sockets) | `realtime.access.roles`, `emit.target.targetRoles` and `show.roles` over the socket name `scope:event:<role>` — matched against the ws-ticket's `scopeRoles` — see [Realtime → Role-Based Filtering](/platform/realtime/using-realtime#role-based-filtering) |
|
|
121
127
|
|
|
122
128
|
## The org / scope split (security)
|
|
123
129
|
|
|
124
130
|
**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.
|
|
125
131
|
|
|
132
|
+
The split holds on the socket too. A ws-ticket carries the proven scope roles kind-qualified in `scopeRoles`, separate from `roles`; the Broadcaster matches `scope:*` audiences and show-roles only against `scopeRoles`, and a bare show-role never reveals to a scope ticket.
|
|
133
|
+
|
|
126
134
|
## Sub-keys (row slicing)
|
|
127
135
|
|
|
128
136
|
A role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:
|
|
@@ -230,7 +238,7 @@ resolver records which `via:` lane opened the gate (first-match-wins) and stamps
|
|
|
230
238
|
request.
|
|
231
239
|
|
|
232
240
|
- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.
|
|
233
|
-
- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.
|
|
241
|
+
- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role. On a [claimed table](/define/areas#claimed-tables-are-pinned-to-the-url-instance) the instance pin still confines that caller to the instance in the URL.
|
|
234
242
|
|
|
235
243
|
The refresh described so far is in-memory and single-request. To also hand the
|
|
236
244
|
caller a **persisted** scope token, opt the namespace into `mintScope` — see
|
|
@@ -287,6 +295,11 @@ scope token. Without a standalone action under the prefix, none of that fires.
|
|
|
287
295
|
|
|
288
296
|
## `mintScope` — mint the scope token from the namespace resolver
|
|
289
297
|
|
|
298
|
+
> **Deprecated**
|
|
299
|
+
>
|
|
300
|
+
> `mintScope: true` is deprecated in favour of [instance-bound OAuth tokens](#instance-bound-oauth-tokens). It keeps working, and the compiler warns where a project uses it. Removal is a later major. See [Migrating to instance-bound OAuth tokens](#migrating-to-instance-bound-oauth-tokens).
|
|
301
|
+
|
|
302
|
+
|
|
290
303
|
A scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.
|
|
291
304
|
Setting **`mintScope: true`** on a namespace folds that mint into the
|
|
292
305
|
namespace resolver: on a successful relationship probe the resolver MINTS a
|
|
@@ -347,7 +360,7 @@ so it can only ever carry the role the caller actually proved this request.
|
|
|
347
360
|
|
|
348
361
|
- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.
|
|
349
362
|
- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
|
|
350
|
-
- **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`.
|
|
363
|
+
- **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`. The namespace resolver never derives `ctx.activeOrgId` from a proven row in the first place — an org firewall arm means org membership — so a relationship caller has no tenant to persist.
|
|
351
364
|
- **`/scope/v1/enter` drops the org claims for a foreign-tenant instance.** When the relationship's `from` table carries an organization column, the enter route reads it off the proven row (the same row the probe already fetched — no extra query) and compares it with `ctx.activeOrgId`. A mismatch — an org-B member entering an org-A event — mints the token **without** `orgId` / `role`: a relationship-only principal, exactly the state the namespace resolver gives the same caller. The caller keeps their org seat for org-B requests by using their session or a plain `/api/v1/token`; the scope token is for the scope. A `from` table with no organization column (a global reference relationship) leaves the claim untouched.
|
|
352
365
|
- **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is `authz.scopes.<kind>.instance` when declared (`instance: 'events'`), else the target of the relationship's `resource.column` foreign key, else the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). Several such tables is a compile error naming them — set `instance`. If nothing resolves, the compiler warns: set `instance` (or declare the FK) so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding. When the namespace gate already hydrated the instance table by the same path param, the resolver takes the instance's organization from `ctx.<exposeAs>` instead of reading it again — that row passed the table's full firewall, and any row the full firewall admits, the tenant-stripped one admits too.
|
|
353
366
|
|
|
@@ -359,11 +372,11 @@ hydrates a shared resource whose table carries an organization column (the
|
|
|
359
372
|
belongs to `ctx.activeOrgId` *before* honouring a `{ roles }` / `{ team }`
|
|
360
373
|
lane. If it does not — an org-B admin entering an org-A event — the lane does
|
|
361
374
|
not apply: the caller is re-evaluated through the relationship lanes as a
|
|
362
|
-
**relationship-only principal**, with `ctx.roles = []` and
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
fails for them,
|
|
366
|
-
|
|
375
|
+
**relationship-only principal**, with `ctx.roles = []` and no active
|
|
376
|
+
organization (exactly the state a caller with no org seat gets). No
|
|
377
|
+
relationship → `403`. Any `ctx.roles`-based check or org-only firewall arm in
|
|
378
|
+
the action then fails for them, and the namespace re-mint carries no org
|
|
379
|
+
claim.
|
|
367
380
|
|
|
368
381
|
The check and the hydration are one read for a caller in their own org: the
|
|
369
382
|
resolver loads the row by id, `ctx.activeOrgId`, and the table's firewall, and
|
|
@@ -546,6 +559,11 @@ request, use the unwrapped `db` (`createDb`) directly, as before.
|
|
|
546
559
|
|
|
547
560
|
## Sessionless scope mint — `ctx.mintScope`
|
|
548
561
|
|
|
562
|
+
> **Deprecated**
|
|
563
|
+
>
|
|
564
|
+
> `ctx.mintScope` is deprecated in favour of [instance-bound OAuth tokens](#instance-bound-oauth-tokens). It keeps working, and the compiler warns where a project uses it. Removal is a later major. See [Migrating to instance-bound OAuth tokens](#migrating-to-instance-bound-oauth-tokens).
|
|
565
|
+
|
|
566
|
+
|
|
549
567
|
`POST /scope/v1/enter` and the namespace resolver both prove the relationship by
|
|
550
568
|
**`ctx.userId`** — so they require a Better Auth account. But a legitimate
|
|
551
569
|
principal often has none: an **event attendee who arrives by email + invite
|
|
@@ -655,8 +673,8 @@ serve a scope principal actual rows, use `scope:<kind>:<role>` gates +
|
|
|
655
673
|
a tier).
|
|
656
674
|
|
|
657
675
|
Everything downstream — REST firewall, masking, scoped-role access, the realtime
|
|
658
|
-
ws-ticket — then treats the sessionless
|
|
659
|
-
user-proven one. There is no new enforcement surface; the principal is just
|
|
676
|
+
ws-ticket and the Broadcaster's `scope:` audiences — then treats the sessionless
|
|
677
|
+
attendee **identically** to a user-proven one. There is no new enforcement surface; the principal is just
|
|
660
678
|
`scope:event:attendee`.
|
|
661
679
|
|
|
662
680
|
### `subjectId` — scoping to the person, not just the instance
|
|
@@ -760,6 +778,367 @@ same per-event rooms (and per-attendee rooms keyed on `subjectId`) as a
|
|
|
760
778
|
user-attendee, carrying the same scope role on the ticket. So the REST gate and
|
|
761
779
|
the socket gate stay identical for accountless principals too.
|
|
762
780
|
|
|
781
|
+
## Instance-bound OAuth tokens
|
|
782
|
+
|
|
783
|
+
Set `oauth` on a scope kind to issue OAuth access tokens bound to **one instance** of that kind. The holder reaches that instance's namespace routes and nothing else: no other instance, no org seat, no user-level routes. Use it for principals who should never hold a full session — an event guest, a vendor contact, a client contact.
|
|
784
|
+
|
|
785
|
+
```typescript
|
|
786
|
+
// quickback.config.ts
|
|
787
|
+
authz: {
|
|
788
|
+
relationships: {
|
|
789
|
+
attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
|
|
790
|
+
},
|
|
791
|
+
scopes: {
|
|
792
|
+
event: {
|
|
793
|
+
requestField: 'eventId',
|
|
794
|
+
roles: { attendee: { via: 'attendeeOf' } },
|
|
795
|
+
oauth: {}, // resource: BETTER_AUTH_URL + '/event', 180s access tokens
|
|
796
|
+
},
|
|
797
|
+
},
|
|
798
|
+
namespaces: {
|
|
799
|
+
eventScope: { prefix: '/event/:eventId', via: ['attendeeOf'] },
|
|
800
|
+
},
|
|
801
|
+
}
|
|
802
|
+
```
|
|
803
|
+
|
|
804
|
+
The mechanism is per kind. `event`, `vendor`, and `client` are three kinds with three resources; nothing in it is specific to events.
|
|
805
|
+
|
|
806
|
+
### Requirements (compile errors)
|
|
807
|
+
|
|
808
|
+
- The project runs on the Cloudflare runtime with `cloudflare-d1`. Postgres providers and the Bun/Node runtimes are refused until they are proven.
|
|
809
|
+
- The auth provider has `oauth: { enabled: true }`.
|
|
810
|
+
- At least one role of the kind is user-provable (`subject: 'user' | 'both'`). Admission is that role's relationship, proven for the signed-in user.
|
|
811
|
+
- A kind with two or more user-provable roles declares [`precedence`](#subject-precedence), listing each of them exactly once (`SCOPE_OAUTH_PRECEDENCE_REQUIRED`, `SCOPE_OAUTH_PRECEDENCE_INVALID`). The kind's namespace `via` lanes list their relationships in the same order (`SCOPE_PRECEDENCE_LANE_CONFLICT`). `precedence` on a kind without `oauth` is an error.
|
|
812
|
+
- A namespace's prefix has the kind's `requestField` as its **first** parameter (`/event/:eventId`). Those prefixes are the only paths a bound token reaches.
|
|
813
|
+
- `accessTokenTtl` is 1–180 seconds (default 180) — the same ceiling as every other token that carries a scope claim. A JWT access token can't be revoked before it expires.
|
|
814
|
+
- `resource`, when set, is an absolute `http(s)` URL with no fragment, unique across kinds, and not an ordinary OAuth audience: not the origin, `/mcp`, a named MCP server's path, or an `oauth.audiences` entry. A kind named `mcp` is refused for the same reason.
|
|
815
|
+
- No two OAuth kinds share a `requestField`.
|
|
816
|
+
- No route outside the kind's namespaces mounts under their prefixes. That covers feature and table mounts, root standalone actions, and built-in routes such as `/api/v1/system/…` and `/api/v1/schema`. A feature named `event` mounts CRUD at `/api/v1/event/:id`, inside `/event/:eventId`, so it is an error next to an `event` kind with `oauth`.
|
|
817
|
+
- Every namespace whose first parameter is the kind's `requestField` gates on at least one of the kind's relationships in its `via`. A namespace on `:eventId` that only admits `{ roles: [...] }` is an error, because bound tokens would reach it.
|
|
818
|
+
- `plugins.oauthProvider.postLogin`, `customAccessTokenClaims`, `resources`, and `resourceSeedMode` are generated; setting them is an error. `refreshTokenReuseInterval` defaults to `30` and must stay above `0`. A DPoP-bound grant (the client sent a `DPoP` proof when it redeemed or authorized) is the exception: after each rotation the old refresh token stays replayable until it expires, so a native app that lost a rotation answer can resend it later and get the same answer, instead of revoking every grant the user holds. The proof must come from the bound key, and revocation deletes the rows, so there is nothing left to replay.
|
|
819
|
+
- With [`tenancy.isolation: 'durable-object'`](/configure/tenant-databases#tenant-backed-scope-kinds), a kind whose relationship tables and instance table all live in one organization object is **tenant-backed**: authorize, code exchange, refresh, `issueScopeGrant`, its namespace routes and its ws-tickets all admit inside that object (`qb.admitScope` / `admitLocal`), and none of them reads the platform D1. Grants pin the tenant and its authorization epoch (`qb2:` references, `qb_scope` with `v: 2`, `tenantId`, `epoch`, `provingTable`), and `ctx.oauth.boundTo` carries `tenantId` and `epoch`. The kind's namespace runs in the tenant Worker, routed by the tenant the token pins ([Tenant namespaces](/configure/tenant-databases#tenant-namespaces)). It needs `tenancy.lookups.<kind>` on the instance table's primary key, `subject: 'user'` roles only, no `self`, no relationship `hops`, and no `mintScope` / `acceptScope` on its namespace — each refused permanently for tenant tables, under its own code. It has no `POST /scope/v1/enter`. A kind that reads a tenant table but can't be tenant-backed fails the build with the [missing requirements](/configure/tenant-databases#which-kinds-can-be-tenant-backed). Every other scope kind, and relationship-backed access on platform features, must keep its tables on the platform (`TENANCY_ADMISSION_DEPENDENCY`).
|
|
820
|
+
|
|
821
|
+
### Request a token
|
|
822
|
+
|
|
823
|
+
Only **trusted clients** get bound tokens: clients an admin created with `skip_consent: true`. Dynamic client registration can't set `skip_consent` (Better Auth rejects it), so an MCP connector that registered itself gets `unauthorized_client`. Register the guest app once from server code, signed in as an admin:
|
|
824
|
+
|
|
825
|
+
```typescript
|
|
826
|
+
await createAuth(env).api.adminCreateOAuthClient({
|
|
827
|
+
headers, // an admin's session
|
|
828
|
+
body: {
|
|
829
|
+
client_name: 'Guest app',
|
|
830
|
+
redirect_uris: ['https://guest.example.com/callback'],
|
|
831
|
+
token_endpoint_auth_method: 'none', // public client, PKCE
|
|
832
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
833
|
+
response_types: ['code'],
|
|
834
|
+
skip_consent: true,
|
|
835
|
+
scope: 'offline_access',
|
|
836
|
+
},
|
|
837
|
+
});
|
|
838
|
+
```
|
|
839
|
+
|
|
840
|
+
The client sends the kind's resource and the instance in RFC 9396 `authorization_details`:
|
|
841
|
+
|
|
842
|
+
```http
|
|
843
|
+
GET /auth/v1/oauth2/authorize?response_type=code&client_id=<id>&redirect_uri=<uri>
|
|
844
|
+
&code_challenge=<S256>&code_challenge_method=S256&state=<state>
|
|
845
|
+
&scope=offline_access
|
|
846
|
+
&resource=https://api.example.com/event
|
|
847
|
+
&authorization_details=[{"type":"event","id":"evt_123"}]
|
|
848
|
+
```
|
|
849
|
+
|
|
850
|
+
A caller without a session is sent to the login page first; `authorization_details` rides the signed query and is checked when authorize resumes. Then `POST /auth/v1/oauth2/token` exchanges the code as usual. Request `offline_access` to get a refresh token.
|
|
851
|
+
|
|
852
|
+
Issuance fails closed:
|
|
853
|
+
|
|
854
|
+
| Request | Result |
|
|
855
|
+
|---|---|
|
|
856
|
+
| No `authorization_details`, malformed JSON, more than one entry, wrong `type`, empty `id` | `invalid_request` |
|
|
857
|
+
| `authorization_details` without a kind resource | `invalid_request` |
|
|
858
|
+
| A kind resource plus any other resource | `invalid_target` |
|
|
859
|
+
| `openid` in `scope` (it adds the userinfo audience) | `invalid_scope` |
|
|
860
|
+
| An instance id outside `A-Z a-z 0-9 . _ ~ -` | `invalid_request` |
|
|
861
|
+
| A client that is not admin-created with `skip_consent` | `unauthorized_client` |
|
|
862
|
+
| A banned user, or no relationship to the instance | `access_denied`, no code |
|
|
863
|
+
|
|
864
|
+
The relationship and the ban state are re-checked at the code exchange and at **every refresh**: removing the guest row or banning the user fails the next refresh with `invalid_grant`. Admission uses the same probe as `/scope/v1/enter`, including [instance tenant binding](#per-matched-lane-minting-forging-safety).
|
|
865
|
+
|
|
866
|
+
The access token carries the proven entry in a `qb_scope` claim, beside the standard OAuth claims:
|
|
867
|
+
|
|
868
|
+
```jsonc
|
|
869
|
+
{ "aud": "https://api.example.com/event", "sub": "<user id>",
|
|
870
|
+
"qb_scope": { "kind": "event", "id": "evt_123", "roles": ["attendee"], "subjectId": "gst_42" } }
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
**A sign-in session created for this authorization is deleted** when the code is exchanged. A session counts as created for it when that request created the session (its `createdAt` is no earlier than the request, and the response sets its cookie) and the request carries the bound authorization: the signed `oauth_query` (email OTP, password, passkey), a social callback's server context, or, on `/magic-link/verify` and `/verify-email` (its auto sign-in), a `callbackURL` that is the bound authorize URL. The guest holds only the bound access and refresh tokens. A session the user already had (staff signed in to the CMS or Account) is never deleted, and neither are its ordinary OAuth tokens: verifying an email while signed in, or a `callbackURL` on any other endpoint (`/get-session`, `/update-user`, `/update-session`), marks nothing, and re-setting the cookie of an existing session never marks it.
|
|
874
|
+
|
|
875
|
+
### Subject precedence
|
|
876
|
+
|
|
877
|
+
A user can hold several roles on one instance through different rows: a crew member who is also a confirmed guest. A token binds **one** subject, so a kind with two or more user-provable roles declares which row wins:
|
|
878
|
+
|
|
879
|
+
```typescript
|
|
880
|
+
// quickback.config.ts
|
|
881
|
+
authz: {
|
|
882
|
+
relationships: {
|
|
883
|
+
crewOf: { from: 'event_roles', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'crew' } },
|
|
884
|
+
attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
|
|
885
|
+
},
|
|
886
|
+
scopes: {
|
|
887
|
+
event: {
|
|
888
|
+
requestField: 'eventId',
|
|
889
|
+
roles: { crew: { via: 'crewOf' }, attendee: { via: 'attendeeOf' } },
|
|
890
|
+
precedence: ['crew', 'attendee'], // most authoritative first
|
|
891
|
+
oauth: {},
|
|
892
|
+
},
|
|
893
|
+
},
|
|
894
|
+
namespaces: {
|
|
895
|
+
eventScope: { prefix: '/event/:eventId', via: ['crewOf', 'attendeeOf'] }, // same order
|
|
896
|
+
},
|
|
897
|
+
}
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
At authorize, exchange and refresh, admission walks the user-provable roles in this order:
|
|
901
|
+
|
|
902
|
+
1. The first role with any matching row chooses the subject. If that role matches **two** rows (two confirmed guest rows for the same user and event), admission is refused. Neither row is picked at random.
|
|
903
|
+
2. Every later role is checked against that same row only: same table, same id. Duplicate rows on a later role are ignored. They can't add roles to the chosen row, so they don't refuse anything.
|
|
904
|
+
3. The token carries only the roles that same row proves, and its sub-keys. It never unions roles from different rows.
|
|
905
|
+
|
|
906
|
+
A refresh can pick a different row if the first one was removed, but only for the same instance. An exact `issueScopeGrant` ceiling never does: that grant stays on its own row and roles. The rule is the same for every OAuth kind, including one with a single role.
|
|
907
|
+
|
|
908
|
+
A kind with one user-provable role needs no `precedence`. `subject: 'supplied'` roles are never admitted by OAuth, so they are not listed.
|
|
909
|
+
|
|
910
|
+
> Breaking: before `precedence`, a user who matched several roles was admitted with all of them, under whichever row matched last. Kinds with two or more user-provable roles now fail to compile until they declare the order. Also new, and fail-closed for every OAuth kind: when the role that chooses the subject matches two rows for one user and instance, the user used to be admitted with whichever row the database returned first. Now nobody is admitted until the duplicate row is removed.
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
### What the token reaches
|
|
914
|
+
|
|
915
|
+
The auth middleware owns any bearer whose `aud` names a kind resource. It verifies it against the JWKS locally, with no session lookup and no `sid` check: once the session row is gone, refreshed tokens carry `sid: null`. Then:
|
|
916
|
+
|
|
917
|
+
- `aud` must be **exactly** the kind's resource. An array audience is `401`.
|
|
918
|
+
- `qb_scope` must name that kind and an instance id. A bad signature, expiry, or a missing claim is `401` — never a fall-through to another lane.
|
|
919
|
+
- The request path must be under one of the kind's namespace prefixes **for the same instance** (`/api/v1/event/evt_123/…`). `evt_456`, `evt_1234`, an encoded segment, `/api/v1/me`, CRUD routes, `/scope/v1/enter`, `/mcp`, and the operator endpoints are `403`.
|
|
920
|
+
- One exception: `POST /broadcast/v1/ws-ticket`, when the realtime ticket's `requestField` is the kind's. The mint then issues a ticket for this instance only, intersecting the token's currently proven roles with the configured ticket gate's relationship lanes. The ticket identifies only the exact scope subject, without account-wide user identity ([details](/platform/realtime/durable-objects#instance-bound-oauth-tokens)). Every other broadcast path is `403`.
|
|
921
|
+
- The kind's prefixes are every namespace whose first parameter is its `requestField`. Each namespace gate checks again that a bound token names its own kind and its own `:param`, and returns `403` otherwise.
|
|
922
|
+
- Issuance reads `resource`, `authorization_details`, and `client_id` from the request Better Auth is authorizing (the GET query, the POST form body, or the verified `oauth_query` on resume), never from other parts of the raw request. A non-string `oauth_query` is `invalid_request`.
|
|
923
|
+
- With `auth.jwt.revocationCheck: 'kv'`, the user-level revocation key applies, so a ban or sign-out-everywhere stamp rejects the token before it expires.
|
|
924
|
+
|
|
925
|
+
The verifier caches the JWKS per isolate, refetches only for an unknown `kid`, and accepts only asymmetric algorithms.
|
|
926
|
+
|
|
927
|
+
The request then runs as a relationship-only principal:
|
|
928
|
+
|
|
929
|
+
```typescript
|
|
930
|
+
{
|
|
931
|
+
authenticated: true,
|
|
932
|
+
authMethod: 'oauth',
|
|
933
|
+
userId: '<sub>',
|
|
934
|
+
activeOrgId: undefined,
|
|
935
|
+
roles: [], // no org roles
|
|
936
|
+
scope: { event: { id: 'evt_123', roles: ['attendee'], subjectId: 'gst_42' } },
|
|
937
|
+
oauth: { clientId, scopes, resource, boundTo: { kind: 'event', id: 'evt_123' } },
|
|
938
|
+
}
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
The namespace gate re-proves the relationship on every request, as it does for any signed-in caller, so a removed guest loses access immediately on namespace routes. The project's [`resolve-oauth-context.ts` hook](/ui/account/hooks#oauth-context-resolver) does not run for bound tokens, and a namespace with `mintScope: true` never mints a scope JWT for one — that token would carry the user past the instance.
|
|
942
|
+
|
|
943
|
+
> Confinement is per route and instance, for every lane. A table the namespace claims is [pinned to the URL instance](/define/areas#claimed-tables-are-pinned-to-the-url-instance): the gate stamps the instance id, and the table's firewall ANDs `<instance column> = <id>` for bound tokens, relationship lanes and org members alike. The exception is a claimed table with no instance arm (only an owner arm, say): it serves the user's own rows from **other** instances through this instance's routes, and the compile warns `CLAIMED_TABLE_UNPINNED`. Give every claimed table one instance-scoped firewall arm, such as `{ field: 'eventId', equals: 'ctx.scope.event' }`.
|
|
944
|
+
>
|
|
945
|
+
> A claimed table's [legacy forward](/define/areas#keeping-the-old-url-legacy) does not widen this: it refuses an instance-bound token and every caller without an active organization (`403 LEGACY_ORG_REQUIRED`), and it only forwards into an instance of the caller's own organization.
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
Ordinary OAuth tokens (MCP clients, audience = origin or `/mcp`) are unchanged: they still need a live session and get the user's full context.
|
|
949
|
+
|
|
950
|
+
### Revoke one instance
|
|
951
|
+
|
|
952
|
+
Delete that grant's refresh rows, or remove the relationship. Both stop the next refresh; the access token in flight dies within its TTL. Other instances keep refreshing.
|
|
953
|
+
|
|
954
|
+
Bound refresh tokens outlive sessions by design, so user-wide revocation drops them explicitly. These delete every bound refresh token the user holds:
|
|
955
|
+
|
|
956
|
+
- `/revoke-sessions` and `/revoke-other-sessions` (the Account devices page)
|
|
957
|
+
- `/change-password` with `revokeOtherSessions: true`
|
|
958
|
+
- `/reset-password`, `/email-otp/reset-password`, `/phone-number/reset-password`, over HTTP or from server code (`auth.api.resetPassword`)
|
|
959
|
+
- `/admin/ban-user`, `/admin/revoke-user-sessions`, `/admin/remove-user`, `/admin/set-user-password`
|
|
960
|
+
|
|
961
|
+
Revoking **one** session (`/revoke-session`, `/admin/revoke-user-session`) leaves bound grants alone. They don't depend on any session, and the session that started a flow is already deleted after the exchange.
|
|
962
|
+
|
|
963
|
+
```typescript
|
|
964
|
+
import { createAuth } from '../lib/auth';
|
|
965
|
+
import { revokeScopeGrant } from '../lib/scope-oauth';
|
|
966
|
+
|
|
967
|
+
await revokeScopeGrant(createAuth(env), { userId, kind: 'event', instanceId: 'evt_123' });
|
|
968
|
+
```
|
|
969
|
+
|
|
970
|
+
For a [tenant-backed kind](/configure/tenant-databases#tenant-backed-scope-kinds), pass the organization the grant pins as well: `{ userId, kind, instanceId, tenantId }`. It is required for those kinds and refused for others.
|
|
971
|
+
|
|
972
|
+
> Never call `/oauth2/revoke` for a bound refresh token. Better Auth treats any later use of a revoked refresh token — an app retry, two tabs racing a rotation — as replay and deletes **every** refresh token that user holds for the client, signing them out of all instances.
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
### Server-issued grants (`issueScopeGrant`)
|
|
976
|
+
|
|
977
|
+
Some principals prove themselves with a credential Better Auth does not know: a handout code staff give at the door, or a one-time exchange of a legacy event pass. Don't turn that credential into a Better Auth session. A one-time token transfers a full session, and creating a session row or verifying an email from server code writes auth tables and can link rows across organizations. Issue a bound grant instead.
|
|
978
|
+
|
|
979
|
+
The credential stays your application's own row. The compiler models no credential table; your action proves the credential and consumes it.
|
|
980
|
+
|
|
981
|
+
#### Declare the ceiling (`oauth.serverGrant`)
|
|
982
|
+
|
|
983
|
+
```typescript
|
|
984
|
+
// quickback.config.ts (excerpt)
|
|
985
|
+
scopes: {
|
|
986
|
+
event: {
|
|
987
|
+
requestField: 'eventId',
|
|
988
|
+
instance: 'events',
|
|
989
|
+
roles: { attendee: { via: 'attendeeOf' }, invitee: { via: 'inviteeOf' }, applicant: { via: 'applicantOf' } },
|
|
990
|
+
precedence: ['attendee', 'invitee', 'applicant'],
|
|
991
|
+
oauth: {
|
|
992
|
+
serverGrant: {
|
|
993
|
+
roles: ['attendee', 'invitee', 'applicant'], // the exact ceiling
|
|
994
|
+
project: {
|
|
995
|
+
subject: { email: 'emailAtInvite', name: 'nameAtInvite' }, // identity, for resolving the user
|
|
996
|
+
instance: ['status'], // optional read-only instance columns
|
|
997
|
+
},
|
|
998
|
+
},
|
|
999
|
+
},
|
|
1000
|
+
},
|
|
1001
|
+
},
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
`serverGrant` is for [tenant-backed kinds](/configure/tenant-databases#tenant-backed-scope-kinds) (`tenancy.isolation: 'durable-object'`). The build fails with `SCOPE_SERVER_GRANT_INVALID` unless:
|
|
1005
|
+
|
|
1006
|
+
- the kind is tenant-backed, so its instance and proving tables live in the organization object, unpartitioned, with the tenant column and server-generated ids;
|
|
1007
|
+
- every ceiling role is a user-provable role of the kind, and their relationships share one proving table, one user column (`equals: 'ctx.userId'`) and one resource column, with literal `where` values only. The subject is *admittable* when it matches any ceiling role's `where` (their OR);
|
|
1008
|
+
- the proving and instance tables soft-delete, so a hard-deleted and re-added row can never reuse an id a credential names;
|
|
1009
|
+
- every projected column exists and is a text column;
|
|
1010
|
+
- the project has the security audit database (any `PUBLIC`, `unsafe` or hard-deleting route gives it one): every link writes an audit row.
|
|
1011
|
+
|
|
1012
|
+
A kind with `serverGrant` also refuses `SCOPE_SERVER_GRANT_NAMESPACE_LEAK`: every table a namespace of the kind claims, and every table owned by a feature with a standalone action under that namespace, must pin its rows to the instance (an arm on `ctx.scope.<kind>`, `ctx.scope.<kind>.id` or `ctx.scope.<kind>.subjectId`) or to organization members (an arm on `ctx.activeOrgId`). A server-granted token keeps the linked account's `userId`, so an owner-only table under the namespace would serve that account's rows of other instances. An organization arm is safe: an instance-bound token never carries an active organization or organization roles, even when its user is a member, so an organization-only table simply refuses it. Every branch of an `any:` group must be pinned, and an `all:` group is as pinned as its safest arm: `any: [owner, instance]` is refused, `any: [{ all: [owner, org] }, instance]` passes. An organization arm marked `optional: true` pins nothing (it is dropped when the claim is absent), so `all: [owner, { …org, optional: true }]` is refused. Since `serverGrant` needs a tenant-backed kind, the check only ever fires with `tenancy.isolation: 'durable-object'`.
|
|
1013
|
+
|
|
1014
|
+
#### Issue before consume
|
|
1015
|
+
|
|
1016
|
+
A handout code yields exactly one thing: a grant for its own event, with the exact subject row and the declared ceiling. Never a session, a cookie, a pass, or a link to any account but the subject's own. The action runs these steps in order:
|
|
1017
|
+
|
|
1018
|
+
| # | Step | Writes | A failure here |
|
|
1019
|
+
|---|---|---|---|
|
|
1020
|
+
| 1 | **Precheck** the credential (your platform row: not revoked, not expired, the right subject). | none | invalid |
|
|
1021
|
+
| 2 | **`readScopeGrantSubject`**: the live instance, the live admittable subject, its identity columns and current link, read in the tenant. | none | denied / unavailable |
|
|
1022
|
+
| 3 | **Resolve the subject's user** with vanilla Better Auth: the current link if that user exists; else by email, applying the squatting guard; else `auth.api.createUser` (no password, no session). | maybe a passwordless unverified user | conflict / unavailable |
|
|
1023
|
+
| 4 | **`linkScopeGrantSubject`**: one tenant transaction re-checks the subject, writes the link only if it is unlinked (or still names the one user step 3 proved gone), exactly one row, plus an audit row. | link + audit | conflict / denied / unavailable |
|
|
1024
|
+
| 5 | **`issueScopeGrant`**: fresh exact admission, a hashed 120 s grant row. The code is not returned yet. | grant row | denied / unavailable |
|
|
1025
|
+
| 6 | **Consume** your credential with one conditional write (`UPDATE … WHERE id = ? AND revoked_at IS NULL AND expires_at > ? … RETURNING id`). | credential spent | lost |
|
|
1026
|
+
| 7 | **Return** the grant code only if step 6 returned exactly one row. Otherwise `discardScopeGrant(auth, code)` and answer the uniform invalid error. | grant row deleted | — |
|
|
1027
|
+
|
|
1028
|
+
Nothing before step 6 spends the credential, so any failure there (a held tenant, a transient error, a revocation, a declined guest) leaves it redeemable. Two redeemers racing one code both reach step 6; one consume wins and returns its grant, the other discards its own. If the consume's outcome is unknown (the D1 call threw), discard the grant and answer 503: a retry then finds the code spent, the same "burned, staff reissue" outcome as a crash after the consume.
|
|
1029
|
+
|
|
1030
|
+
```typescript
|
|
1031
|
+
import { createAuth } from '../lib/auth';
|
|
1032
|
+
import { readScopeGrantSubject, linkScopeGrantSubject, issueScopeGrant, discardScopeGrant } from '../lib/scope-oauth';
|
|
1033
|
+
|
|
1034
|
+
// Inside the handout action, AFTER step 1 proved the code row `cred`.
|
|
1035
|
+
const ids = { kind: 'event', instanceId: cred.eventId, subjectId: cred.guestId, tenantHint: cred.organizationId };
|
|
1036
|
+
const read = await readScopeGrantSubject(env, ids); // { status: 'ok', tenantId, epoch, subject, instance } | denied | unavailable
|
|
1037
|
+
// …step 3 resolves userId (and `replaces`, the observed link, when that user is gone)…
|
|
1038
|
+
const link = await linkScopeGrantSubject(auth, { env, ...ids, epoch: read.epoch, userId, replaces });
|
|
1039
|
+
const { code, expiresIn } = await issueScopeGrant(auth, {
|
|
1040
|
+
env, userId, kind: 'event', instanceId: cred.eventId, subjectId: cred.guestId, tenantHint: cred.organizationId,
|
|
1041
|
+
roles: ['attendee', 'invitee', 'applicant'], // exactly the declared serverGrant ceiling
|
|
1042
|
+
clientId, codeChallenge, codeChallengeMethod: 'S256', redirectUri,
|
|
1043
|
+
});
|
|
1044
|
+
// …step 6: consume `cred` with one conditional write; `won` = the rows it returned…
|
|
1045
|
+
if (won.length !== 1) { await discardScopeGrant(auth, code); /* uniform invalid */ }
|
|
1046
|
+
c.header('Cache-Control', 'no-store');
|
|
1047
|
+
return { code, expiresIn };
|
|
1048
|
+
```
|
|
1049
|
+
|
|
1050
|
+
**The caller's account is never an input.** `userId` comes only from the tenant read: the subject's own link or identity columns. The handout action must not read `ctx.userId`, cookies or a bearer, and no request field names a user. A caller signed in as some other account gets exactly what an anonymous caller gets, and is never linked. Call `auth.api.createUser` with no headers, so no session is consulted.
|
|
1051
|
+
|
|
1052
|
+
**Squatting guard.** An account found by the subject's email that is unverified and has a self-set credential (a password or a passkey) is refused (`409 AUTH_EMAIL_UNPROVEN_ACCOUNT`) unless the auth database proves it (a verified email, or a `member` row), or the tenant read shows the subject already linked to exactly that user. Apply the guard to the winner of a lost create race too. The user clears it by verifying their email.
|
|
1053
|
+
|
|
1054
|
+
Because the code row usually belongs to an anonymous caller, the scoped `db` (which stamps the caller as the writer) refuses its writes. Declare `unsafe: { reason, crossTenant: false }` and consume through the features handle directly (`createDb(env.DB)`); see [Scoped database](/define/actions/scoped-db#credential-doors-server-grants).
|
|
1055
|
+
|
|
1056
|
+
#### The four functions
|
|
1057
|
+
|
|
1058
|
+
| Function | Does | Returns |
|
|
1059
|
+
|---|---|---|
|
|
1060
|
+
| `readScopeGrantSubject(env, { kind, instanceId, subjectId, tenantHint? })` | Tenant read (`qb.scopeGrantRead`). Writes nothing. | `{ status: 'ok', tenantId, epoch, subject: { email, name, linkedUserId, matchedRoles }, instance }`, or `denied` / `unavailable` with a code |
|
|
1061
|
+
| `linkScopeGrantSubject(auth, { env, kind, instanceId, subjectId, tenantHint?, epoch, userId, replaces?, requestId? })` | Tenant link (`qb.scopeGrantLink`) in one transaction, with an audit row (`event_kind: 'scope_grant_link'`, metadata `{ actorType: 'credential-mediated', userId, purpose: 'scope-grant-link', kind, instanceId, subjectId, requestId }`, never a code or email). `replaces` is accepted only when that user no longer exists in the auth database. `epoch` is the read's: a restore in between denies. | `linked`, `conflict`, `denied` or `unavailable` |
|
|
1062
|
+
| `issueScopeGrant(auth, { … })` | Admits and stores a single-use grant code (below). | `{ code, expiresIn }`; throws on refusal |
|
|
1063
|
+
| `discardScopeGrant(auth, code)` | Consumes an unreturned code. A code already redeemed or expired is ignored. | — |
|
|
1064
|
+
|
|
1065
|
+
Routing: the tenant comes from the kind's lookup. `tenantHint` (the organization your action read from the credential row) is used only while the lookup has no row; a lookup that disagrees (`SCOPE_GRANT_TENANT_MISMATCH`) or is ambiguous (`SCOPE_GRANT_TENANT_AMBIGUOUS`) refuses. The tenant object checks that its own tenant, the instance row's and the subject row's all agree, so a wrong hint admits nobody. None of these functions is an HTTP endpoint.
|
|
1066
|
+
|
|
1067
|
+
Map the outcomes onto the action's response, disclosing `conflict` and `denied` only after step 1 proved the credential:
|
|
1068
|
+
|
|
1069
|
+
| Class | Meaning | Response | Credential |
|
|
1070
|
+
|---|---|---|---|
|
|
1071
|
+
| invalid | unknown, expired or revoked credential; consume lost | `404` (uniform) | not spent, or already spent |
|
|
1072
|
+
| conflict | email collision, unproven account, subject linked to another live user | `409` | not spent |
|
|
1073
|
+
| denied | subject or instance not admittable or deleted, admission refused | `403` / `409` | not spent |
|
|
1074
|
+
| unavailable | tenant held, restoring, moving; transient RPC / auth / D1 error; unknown consume outcome | `503` + `Retry-After` | not spent (unknown consume: see above) |
|
|
1075
|
+
|
|
1076
|
+
Set `Cache-Control: no-store` on every grant response. The [Idempotency-Key middleware](/platform/api-contract#idempotency-key) never stores a `no-store` body, for any caller, so a retried key re-runs the action instead of replaying a grant code. Never log the credential, the grant code, the verifier or emails, and key rate limits on a hash of the code.
|
|
1077
|
+
|
|
1078
|
+
#### `issueScopeGrant`
|
|
1079
|
+
|
|
1080
|
+
`issueScopeGrant` refuses (throws) unless all of these hold:
|
|
1081
|
+
|
|
1082
|
+
- The kind declares `oauth`, and `resource` (if given) is the kind's resource.
|
|
1083
|
+
- The client is admin-created with `skip_consent`, lists `urn:quickback:params:oauth:grant-type:scope-grant` in its `grant_types`, and has `redirectUri` among its redirect URIs.
|
|
1084
|
+
- The scopes are at most `['offline_access']` (the default): a bound grant carries no API scopes, so `openid` and anything an action forwards (such as `admin`) are refused. If the client registered scopes, they must include the requested ones.
|
|
1085
|
+
- The user exists, is not banned, and passes the kind's admission probe for `instanceId`.
|
|
1086
|
+
- For a tenant-backed kind: the kind declares `oauth.serverGrant` and `roles` is exactly its ceiling; the tenant resolves from the kind's lookup, or from `tenantHint` while the lookup has no row (a disagreeing hint refuses, and `tenantHint` on any other kind refuses); and the grant names the table `subjectId` lives in (`provingTable`, filled in from the ceiling).
|
|
1087
|
+
|
|
1088
|
+
`roles` and `subjectId` are mandatory server-authorized limits, proved by the action's credential check. Never forward them from client input. The role list is an allowed set, not a snapshot: an invitee or applicant may become an attendee after RSVP or staff approval, but cannot acquire an organizer role outside that set. Admission probes only those roles and the exact subject row before issuing, redeeming, or refreshing. The code and every rotated refresh grant retain this ceiling; replacing or cancelling the guest row cannot fall back to another relationship held by the same user. Bound REST and realtime requests also restrict rechecks to the token's current roles and subject. Refresh after an authorized role transition to receive the new role.
|
|
1089
|
+
|
|
1090
|
+
The app redeems the code at the token endpoint with its PKCE verifier:
|
|
1091
|
+
|
|
1092
|
+
```http
|
|
1093
|
+
POST /auth/v1/oauth2/token
|
|
1094
|
+
grant_type=urn:quickback:params:oauth:grant-type:scope-grant
|
|
1095
|
+
&code=<code>&code_verifier=<verifier>&client_id=<id>&redirect_uri=<uri>
|
|
1096
|
+
```
|
|
1097
|
+
|
|
1098
|
+
It gets the same bound access and refresh tokens as the [authorize flow](#request-a-token), with the same `qb_scope` claim and confinement. Refreshes re-run admission as usual.
|
|
1099
|
+
|
|
1100
|
+
Redemption checks everything before it spends the code: it finds the code without consuming it, checks the client, its trust, the redirect URI, the PKCE verifier, the user and the ban, runs exact admission for the stored reference (`503 temporarily_unavailable` with the code intact when the tenant cannot answer, `invalid_grant` when it denies), and only then consumes exactly the row it checked (Better Auth's `consumeVerificationValue`: of concurrent redeemers, one wins). The token is issued after that, and its claims re-run admission once more. A revocation that lands between the two admissions burns the code and issues nothing (a window of milliseconds, fail closed).
|
|
1101
|
+
|
|
1102
|
+
The code:
|
|
1103
|
+
|
|
1104
|
+
- is single-use; a failed redemption (wrong verifier, redirect or client, admission refused or unavailable) does **not** consume it, so the correct request can still redeem it until it expires;
|
|
1105
|
+
- expires after 120 seconds;
|
|
1106
|
+
- is stored only as a SHA-256 hash, in the `verification` table;
|
|
1107
|
+
- redeems only with the same `client_id` and `redirect_uri` and a `code_verifier` matching the challenge;
|
|
1108
|
+
- is refused with `unauthorized_client` if, between issuance and redemption, the client lost `skip_consent` or dropped the grant type.
|
|
1109
|
+
|
|
1110
|
+
No Better Auth session is created and `emailVerified` is never touched.
|
|
1111
|
+
|
|
1112
|
+
It is not an `authorization_code` because oauthProvider redeems those only against the live session that authorized them, and this path must not create one. The grant goes through oauthProvider's own extension-grant dispatch and `issueTokens`, so token format, refresh rotation, and revocation are unchanged.
|
|
1113
|
+
|
|
1114
|
+
> `issueScopeGrant` is a server-side primitive; there is no HTTP endpoint for it. The calling action proves the credential, and that proof is the whole security boundary. Make the credential single-use or short-lived, compare it in constant time, and give the action its own `rateLimit` (for example `rateLimit: { limit: 5, period: 60 }`) so a handout code cannot be guessed. The bucket is keyed on the caller's `userId`, or on the verified scope subject for a scope-only principal. Only a caller with neither, which is the usual case for a `PUBLIC` handout action, is keyed on `cf-connecting-ip`, falling back to one shared `anon` bucket when that header is absent. See [how requests are keyed](/define/rate-limit#how-requests-are-keyed). An IP bucket does not stop a distributed guesser, so keep handout codes long and single-use as well. A `PUBLIC` action without one is flagged by `ACTION_PUBLIC_WITHOUT_RATELIMIT`.
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
## Migrating to instance-bound OAuth tokens
|
|
1118
|
+
|
|
1119
|
+
Scope tokens (`POST /scope/v1/enter`, namespace `mintScope: true`, and `ctx.mintScope`) are deprecated. Instance-bound OAuth tokens replace them: Better Auth issues and refreshes them, the relationship is re-proved at every refresh, and the namespace gate re-proves it on every request. Scope roles, relationships, namespaces, and every pillar that reads `ctx.scope.<kind>` stay as they are. Only how the token is obtained changes.
|
|
1120
|
+
|
|
1121
|
+
The compiler warns, without failing, when a project still relies on scope tokens:
|
|
1122
|
+
|
|
1123
|
+
| Warning names | Means |
|
|
1124
|
+
|---|---|
|
|
1125
|
+
| a scope kind with no `oauth` | its instances are entered only with `POST /scope/v1/enter` tokens |
|
|
1126
|
+
| `subject: 'supplied' \| 'both'` roles | `ctx.mintScope` is emitted for them |
|
|
1127
|
+
| a namespace with `mintScope: true` | the resolver mints a scope token |
|
|
1128
|
+
|
|
1129
|
+
`POST /scope/v1/enter` responses also carry `Deprecation: true` and a `Link` header pointing here, so clients can find the calls.
|
|
1130
|
+
|
|
1131
|
+
Steps, per kind:
|
|
1132
|
+
|
|
1133
|
+
1. Add `oauth: {}` to the kind, and enable `oauth: { enabled: true }` on the auth provider. Check the [requirements](#requirements-compile-errors): a namespace whose first parameter is the kind's `requestField` (`/event/:eventId`), and no other route mounted under it.
|
|
1134
|
+
2. Register the client app once as a trusted client (`adminCreateOAuthClient` with `skip_consent: true`), as in [Request a token](#request-a-token).
|
|
1135
|
+
3. In the client, replace `POST /scope/v1/enter { eventId }` with the authorization-code flow: `resource=<kind resource>` and `authorization_details=[{"type":"event","id":"<eventId>"}]`, plus `offline_access` for a refresh token. Send the access token as `Authorization: Bearer …` on the instance's namespace routes. Refresh with the refresh token instead of re-entering.
|
|
1136
|
+
4. Move every call the scoped principal makes under the kind's namespace prefix. A bound token reaches only `/api/v1/<prefix>/<instance>/…`; CRUD routes and `/scope/v1/enter` itself answer `403`. Realtime works through [`POST /broadcast/v1/ws-ticket`](/platform/realtime/durable-objects) for the bound instance.
|
|
1137
|
+
5. Drop `mintScope: true` from namespaces once no client reads its `set-auth-token`.
|
|
1138
|
+
6. For accountless principals using `ctx.mintScope`, give them a Better Auth user (for example email OTP, created by your invite action) so they can sign in once and authorize. The bound token then confines them exactly as the scope token did. Remove `subject: 'supplied'` from the role when the last `ctx.mintScope` call is gone.
|
|
1139
|
+
|
|
1140
|
+
Revocation moves with it. A bound grant ends when its refresh rows are deleted or the relationship is removed ([Revoke one instance](#revoke-one-instance)). The `qbrev:scope` KV markers only deny scope tokens and retire with them; see [JWT optimization](/platform/auth/jwt-optimization#revocation--revocationcheck-kv).
|
|
1141
|
+
|
|
763
1142
|
## Revocation & TTL
|
|
764
1143
|
|
|
765
1144
|
The scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:
|
|
@@ -794,6 +1173,10 @@ ctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [
|
|
|
794
1173
|
recheck?: Record<string, string | number | boolean | null | Array<string | number>>;
|
|
795
1174
|
};
|
|
796
1175
|
}>;
|
|
1176
|
+
oauth?: { // instance-bound OAuth tokens
|
|
1177
|
+
resource?: string; // default BETTER_AUTH_URL + '/<kind>'
|
|
1178
|
+
accessTokenTtl?: number; // 1–180, default 180
|
|
1179
|
+
};
|
|
797
1180
|
}
|
|
798
1181
|
|
|
799
1182
|
// ctx.self — present in actions when any scoped role declares `self`
|
|
@@ -813,3 +1196,4 @@ ctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):
|
|
|
813
1196
|
- `subjectId` is the conferring row's primary key, populated on **both** proof paths — scope self-data on `ctx.scope.<kind>.subjectId`.
|
|
814
1197
|
- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.
|
|
815
1198
|
- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared).
|
|
1199
|
+
- `oauth` on a kind registers its OAuth resource and emits `src/lib/scope-oauth.ts` (admission, claims, `revokeScopeGrant`). See [Instance-bound OAuth tokens](#instance-bound-oauth-tokens).
|