@quickback-dev/cli 0.64.0 → 0.64.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.
Files changed (60) hide show
  1. package/dist/codex/AGENTS.md +290 -0
  2. package/dist/commands/codex.d.ts +16 -0
  3. package/dist/commands/codex.d.ts.map +1 -0
  4. package/dist/commands/codex.js +159 -0
  5. package/dist/commands/codex.js.map +1 -0
  6. package/dist/commands/init.d.ts +6 -0
  7. package/dist/commands/init.d.ts.map +1 -0
  8. package/dist/commands/init.js +405 -0
  9. package/dist/commands/init.js.map +1 -0
  10. package/dist/docs/content.d.ts.map +1 -1
  11. package/dist/docs/content.js +94 -159
  12. package/dist/docs/content.js.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/lib/sweep-stale.d.ts +25 -0
  15. package/dist/lib/sweep-stale.d.ts.map +1 -0
  16. package/dist/lib/sweep-stale.js +179 -0
  17. package/dist/lib/sweep-stale.js.map +1 -0
  18. package/dist/lib/sweep-stale.test.d.ts +2 -0
  19. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  20. package/dist/lib/sweep-stale.test.js +130 -0
  21. package/dist/lib/sweep-stale.test.js.map +1 -0
  22. package/dist/skill/docs/configure/auth.md +7 -5
  23. package/dist/skill/docs/configure/index.md +4 -3
  24. package/dist/skill/docs/configure/providers.md +1 -1
  25. package/dist/skill/docs/define/authz-roles.md +52 -0
  26. package/dist/skill/docs/define/changesets.md +8 -3
  27. package/dist/skill/docs/platform/auth/jwt-optimization.md +4 -2
  28. package/dist/skill/docs/platform/auth/plugins/index.md +20 -0
  29. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
  30. package/dist/skill/docs/platform/payments/dev-loop.md +228 -0
  31. package/dist/skill/docs/platform/payments/index.md +158 -0
  32. package/dist/skill/docs/platform/payments/one-off-checkout.md +266 -0
  33. package/dist/skill/docs/platform/realtime/durable-objects.md +1 -1
  34. package/dist/skill/docs/platform/realtime/index.md +1 -1
  35. package/dist/skill/docs/platform/realtime/live-views.md +1 -1
  36. package/dist/skill/docs/platform/realtime/named-invalidations.md +1 -1
  37. package/dist/skill/docs/platform/realtime/using-realtime.md +1 -1
  38. package/dist/skill/docs/platform/webhooks/inbound.md +5 -2
  39. package/dist/skill/docs/tooling/output.md +3 -2
  40. package/dist/skill/docs/ui/admin/connecting.md +1 -1
  41. package/package.json +1 -1
  42. package/src/skill/docs/configure/auth.md +7 -5
  43. package/src/skill/docs/configure/index.md +4 -3
  44. package/src/skill/docs/configure/providers.md +1 -1
  45. package/src/skill/docs/define/authz-roles.md +52 -0
  46. package/src/skill/docs/define/changesets.md +8 -3
  47. package/src/skill/docs/platform/auth/jwt-optimization.md +4 -2
  48. package/src/skill/docs/platform/auth/plugins/index.md +20 -0
  49. package/src/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
  50. package/src/skill/docs/platform/payments/dev-loop.md +228 -0
  51. package/src/skill/docs/platform/payments/index.md +158 -0
  52. package/src/skill/docs/platform/payments/one-off-checkout.md +266 -0
  53. package/src/skill/docs/platform/realtime/durable-objects.md +1 -1
  54. package/src/skill/docs/platform/realtime/index.md +1 -1
  55. package/src/skill/docs/platform/realtime/live-views.md +1 -1
  56. package/src/skill/docs/platform/realtime/named-invalidations.md +1 -1
  57. package/src/skill/docs/platform/realtime/using-realtime.md +1 -1
  58. package/src/skill/docs/platform/webhooks/inbound.md +5 -2
  59. package/src/skill/docs/tooling/output.md +3 -2
  60. package/src/skill/docs/ui/admin/connecting.md +1 -1
@@ -70,14 +70,19 @@ update: { access: { roles: ["member", "admin", "owner"] }, routes: false },
70
70
  One blessed path — **RFC 5789 media-type dispatch** on the routes you already
71
71
  have. No subpath.
72
72
 
73
- - `PATCH /api/v2/<resource>/:id` with
73
+ Paths below use the default `/api/v1` prefix. Changesets are a contract-v2
74
+ **semantics** feature and v2 is the default, so they are available without
75
+ moving your URLs — set [`contract.routes`](/platform/api-contract#two-axes-semantics-and-routes)
76
+ to `"v2"` only if you also want the `/api/v2` prefix.
77
+
78
+ - `PATCH /api/v1/<resource>/:id` with
74
79
  `Content-Type: application/vnd.quickback.changeset+json` — apply a changeset
75
80
  to an existing root. Plain `application/json` keeps the flat-column PATCH.
76
- - `POST /api/v2/<resource>` with the same media type — create the root and its
81
+ - `POST /api/v1/<resource>` with the same media type — create the root and its
77
82
  children in one changeset.
78
83
 
79
84
  ```jsonc
80
- // PATCH /api/v2/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)
85
+ // PATCH /api/v1/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)
81
86
  {
82
87
  "patch": { "name": "Renamed" }, // sparse ROOT patch (optional)
83
88
  "tasks": {
@@ -49,9 +49,11 @@ auth: {
49
49
  },
50
50
  ```
51
51
 
52
- > **Contract v2 makes this surface opt-in**
52
+ > **This surface is opt-in by default**
53
53
  >
54
- > On `contract: { version: "v2" }`, the custom JWT surface is emitted only when `auth.jwt` is present. Omit it and the generated output has no token endpoint, no `src/lib/jwt.ts`, and no JWT fast-path — cookie and signed session-token bearer auth still work. Contract v1 always emits it. See [Auth & JWT config](/configure/auth).
54
+ > Contract v2 is the default since v0.64.0, and on it the custom JWT surface is emitted only when `auth.jwt` is present. Omit it and the generated output has no token endpoint and no JWT fast-path — cookie and signed session-token bearer auth still work. Pin `contract: { version: "v1" }` to get it unconditionally. See [Auth & JWT config](/configure/auth).
55
+ >
56
+ > `src/lib/jwt.ts` is still emitted when the project declares [`authz.scopes`](/define/scopes): scope tokens are signed JWTs, so the helper is required for minting and verifying them even with no credential lane.
55
57
 
56
58
 
57
59
  ---
@@ -415,6 +415,26 @@ Better Auth's older `better-auth/plugins/mcp` is being deprecated in favour of `
415
415
 
416
416
  Keep `apiKey` enabled alongside it — server-to-server flows (cron, scripts) want a static key; OAuth is for interactive clients.
417
417
 
418
+ ### Subscriptions (Stripe)
419
+
420
+ Subscription tiers, Stripe Checkout, the billing portal, and state sync through the [inbound webhook surface](/platform/webhooks/inbound). Tiers are declared in config — lowest to highest, with a Stripe `priceId` on every paid tier — and the compile fails without them.
421
+
422
+ ```ts
423
+ database: defineDatabase("cloudflare-d1", { webhooksBinding: "WEBHOOKS_DB" }),
424
+ auth: defineAuth("better-auth", {
425
+ plugins: {
426
+ subscriptions: {
427
+ tiers: {
428
+ free: { name: "Free", limits: { projects: 3 } },
429
+ pro: { name: "Pro", priceId: "price_1234", limits: { projects: 100 } },
430
+ },
431
+ },
432
+ },
433
+ }),
434
+ ```
435
+
436
+ Requires `webhooksBinding` — Stripe events are the only thing that renews, downgrades or cancels a subscription. Secrets: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`. See the [Subscriptions plugin page](/platform/auth/plugins/subscriptions) for the endpoint table, webhook wiring, and the org-vs-personal precedence rule.
437
+
418
438
  ### Custom plugins (escape hatch)
419
439
 
420
440
  The named plugins above cover the curated set Quickback ships first-class wiring for. For anything else — third-party packages (`@better-auth-kit/audit`, …), Better Auth built-ins outside the registry, or project-local plugins — use `customPlugins`.
@@ -0,0 +1,297 @@
1
+ # Subscriptions Plugin (Stripe)
2
+
3
+ The subscriptions plugin adds subscription tiers and Stripe billing to Better Auth. The compiler configures it from `quickback.config.ts`, emits it into your project as source, and wires its state-sync handlers onto the [inbound webhook surface](/platform/webhooks/inbound) — so Stripe events reach your database through one verified, deduplicated path.
4
+
5
+ The subscriptions table lives in the auth database, alongside `user` and `session`: entitlements are an access-control concern, not domain data.
6
+
7
+ ## Enable it
8
+
9
+ ```ts
10
+ import { defineAuth, defineConfig, defineDatabase, defineRuntime } from "@quickback/compiler";
11
+
12
+ export default defineConfig({
13
+ name: "my-app",
14
+ providers: {
15
+ runtime: defineRuntime("cloudflare"),
16
+ database: defineDatabase("cloudflare-d1", {
17
+ // REQUIRED: subscription state only ever changes via inbound Stripe events.
18
+ webhooksBinding: "WEBHOOKS_DB",
19
+ }),
20
+ auth: defineAuth("better-auth", {
21
+ emailAndPassword: { enabled: true },
22
+ plugins: {
23
+ subscriptions: {
24
+ tiers: {
25
+ free: { name: "Free", limits: { projects: 3, storage: 1000 } },
26
+ pro: {
27
+ name: "Pro",
28
+ priceId: "price_1234",
29
+ trialDays: 14,
30
+ limits: { projects: 100, storage: 100000 },
31
+ },
32
+ enterprise: {
33
+ name: "Enterprise",
34
+ priceId: "price_5678",
35
+ limits: { projects: -1, storage: -1 },
36
+ },
37
+ },
38
+ },
39
+ },
40
+ }),
41
+ },
42
+ });
43
+ ```
44
+
45
+ ## Tiers are configuration, and the compile fails without them
46
+
47
+ There are no default tiers. A tier with no Stripe price is a tier checkout cannot charge for, so the compiler rejects the config instead of shipping something that looks enabled and cannot take money.
48
+
49
+ **Declaration order is meaningful: lowest → highest.** The first tier is the base tier — what a caller with no subscription row gets — and it is the only one that may omit `priceId`.
50
+
51
+ | Field | Required | Meaning |
52
+ |-------|----------|---------|
53
+ | `priceId` | Yes, except on the first tier | Stripe Price ID. Checkout maps a tier to this; webhooks map it back. |
54
+ | `name` | No (defaults to the tier key) | Display name, returned by `GET /subscriptions/tiers`. |
55
+ | `limits` | No (defaults to `{}`) | Arbitrary numeric entitlements, stored on the subscription row. Use `-1` for unlimited. |
56
+ | `trialDays` | No | Trial length passed to Stripe Checkout. |
57
+
58
+ These are compile errors, not warnings:
59
+
60
+ - the plugin is enabled with no `tiers`
61
+ - any tier after the first has no `priceId`
62
+ - two tiers share a `priceId` (webhooks resolve a tier *by* price, so it would be ambiguous)
63
+ - `webhooksBinding` is not set — see [Webhook wiring](#webhook-wiring)
64
+ - the auth database is not Cloudflare D1 (the table ships in the SQLite dialect)
65
+
66
+ ## Secrets
67
+
68
+ Both are secrets, not vars — set them with `wrangler secret put`:
69
+
70
+ | Secret | Used for |
71
+ |--------|----------|
72
+ | `STRIPE_SECRET_KEY` | Outbound Stripe API calls — creating Checkout and billing-portal sessions. |
73
+ | `STRIPE_WEBHOOK_SECRET` | Verifying the HMAC signature on inbound Stripe events. |
74
+
75
+ ```bash
76
+ npx wrangler secret put STRIPE_SECRET_KEY
77
+ npx wrangler secret put STRIPE_WEBHOOK_SECRET
78
+ ```
79
+
80
+ Use test keys in a dev environment and live keys in production; named environments keep them separate.
81
+
82
+ ## Endpoints
83
+
84
+ All mounted under your auth base path (`/auth/v1` by default).
85
+
86
+ | Method | Path | Access |
87
+ |--------|------|--------|
88
+ | `GET` | `/subscriptions/tiers` | Public — the configured tiers and their limits |
89
+ | `GET` | `/subscriptions/me` | Authenticated — the caller's effective subscription |
90
+ | `POST` | `/subscriptions/checkout` | Authenticated — creates a Stripe Checkout Session |
91
+ | `POST` | `/subscriptions/portal` | Authenticated — creates a Stripe billing-portal session |
92
+ | `GET` | `/subscriptions` | Admin, or org-scoped with `?organizationId=` |
93
+ | `POST` | `/subscriptions` | Admin |
94
+ | `POST` | `/subscriptions/update` | Admin — takes `{ id, ... }` in the body |
95
+ | `POST` | `/subscriptions/delete` | Admin — soft delete, takes `{ id }` in the body |
96
+
97
+ The two admin mutations are `POST` with the id in the **body**, not `PATCH`/`DELETE` on `/subscriptions/:id`. That matches the rest of the Better Auth surface, which is POST-with-body throughout; the generated OpenAPI describes them the same way.
98
+
99
+ `GET /subscriptions/me` returns the base tier with `isDefault: true` when the caller has no subscription row, so clients never have to special-case "not subscribed".
100
+
101
+ Checkout takes the tier name, not a price:
102
+
103
+ ```json
104
+ POST /auth/v1/subscriptions/checkout
105
+ { "tier": "pro" }
106
+ ```
107
+
108
+ Pass `organizationId` to buy on behalf of an organization. That path requires the [organization plugin](/platform/auth/plugins) and checks the caller's membership role (`owner`, `admin` or `member` by default).
109
+
110
+ ## Org vs personal: which subscription applies
111
+
112
+ A caller can have both a personal subscription and membership in a subscribed organization. One rule decides:
113
+
114
+ > **The active organization's subscription wins. Personal is the fallback.**
115
+
116
+ - Active organization set, and that org has a subscription → the **org** subscription applies.
117
+ - Active organization set, but the org has no subscription → the caller's **personal** subscription applies, so switching into an unpaid org never downgrades a paid user.
118
+ - No active organization → the caller's **personal** subscription applies.
119
+
120
+ If a subject somehow has two live rows — the admin create endpoint does not check, and a checkout race can produce one — the winner is decided explicitly, not left to the database: a granting row beats a non-granting one, and among equals the most recently started wins. So starting a new checkout never knocks out the subscription you are currently paying for.
121
+
122
+ It is deliberately not "whichever tier is higher". Setting an active organization is the caller stating which context they are acting in, and a max-tier rule would let one member's personal Pro plan quietly unlock an organization that is on Free.
123
+
124
+ ## Entitlements: gating access on tier
125
+
126
+ Every tier becomes a role string — `pro` becomes `tier_pro` — which the auth middleware stamps into the caller's roles on each request. Access rules then gate on it through the ordinary [`authz.roles`](/define/authz-roles#subscription-tiers) machinery; there is no separate entitlements API to call and nothing to check inside your handlers.
127
+
128
+ ```typescript
129
+ // quickback.config.ts
130
+ export default defineConfig({
131
+ // ...providers, auth plugins as above...
132
+ authz: {
133
+ roles: {
134
+ paid: { roles: ['tier_pro'] },
135
+ },
136
+ },
137
+ });
138
+ ```
139
+
140
+ ```typescript
141
+ // features/reports/actions/forecast.ts
142
+ import { z } from "zod";
143
+ import { defineAction } from "../.quickback/define-action";
144
+
145
+ export default defineAction({
146
+ description: "Generate the revenue forecast. Paid plans only.",
147
+ input: z.object({ months: z.number().int().min(1).max(24) }),
148
+ access: { roles: ['paid'] },
149
+ async execute({ input }) {
150
+ return { months: input.months, forecast: [] };
151
+ },
152
+ });
153
+ ```
154
+
155
+ ### Which statuses grant
156
+
157
+ | Status | Grants |
158
+ |--------|--------|
159
+ | `active` | ✓ |
160
+ | `trialing` | ✓ — a trial is a subscription, so trials reach paid surfaces |
161
+ | `past_due` | ✗ |
162
+ | `cancelled` / `canceled` | ✗ |
163
+ | `incomplete`, `unpaid`, anything else | ✗ |
164
+ | No subscription row at all | ✗ |
165
+
166
+ Everything not on the granting list denies, including states Stripe adds later and a tier name no longer in your config. A failed lookup denies too — a database error must never accidentally grant a paid entitlement.
167
+
168
+ ### Expiry is the second bound
169
+
170
+ Status alone is only ever as current as the last webhook you successfully processed, and there are three ways it can freeze at `active` with nothing left to revoke it: Stripe retries a failing webhook for about three days and then **permanently gives up**; a Stripe status this plugin does not recognise leaves the current one untouched; and a subscription event carrying no period end leaves `expiresAt` unchanged.
171
+
172
+ So a granting status is checked against the row's `expiresAt` as well:
173
+
174
+ | `expiresAt` | Grants |
175
+ |---|---|
176
+ | In the future | ✓ |
177
+ | Up to **48 hours** past | ✓ — the grace window |
178
+ | More than 48 hours past | ✗, whatever the status says |
179
+ | `null` | ✓ — admin-created rows carry no Stripe period |
180
+
181
+ The 48-hour grace window is not slack, it is the renewal boundary: Stripe's `invoice.paid` for the new period lands minutes to hours after the old one ends, and until it does the row still carries the previous `expiresAt`. A strict check would false-deny every paying customer at every renewal. Forty-eight hours absorbs that plus a webhook backlog while still bounding a stuck row.
182
+
183
+ A subscription stuck at `active` with an `expiresAt` three months in the past therefore grants nothing — which is the case this bound exists for.
184
+
185
+ Note the asymmetry with cancellation: `cancel_at_period_end` leaves the row `active`, so a customer who cancels keeps their entitlements until Stripe sends `customer.subscription.deleted`. That is correct — they paid through the period.
186
+
187
+ ### Tier order is the hierarchy
188
+
189
+ A granting subscription stamps its own tier **and every tier below it** in declared order. With `free → pro → enterprise`, an Enterprise subscriber carries `['tier_enterprise', 'tier_pro', 'tier_free']`, so `roles: ['tier_pro']` reads as "pro or better" and you never configure a hierarchy.
190
+
191
+ A caller with **no** subscription gets nothing — not even `tier_free`. The base tier is what checkout sells, not what a signed-up user is. Use `AUTHENTICATED` for "any logged-in user"; reserve `tier_free` for callers who actually hold a free-tier row.
192
+
193
+ ### Which transports carry tier roles
194
+
195
+ | Transport | Tier roles | Freshness |
196
+ |-----------|-----------|-----------|
197
+ | Session cookie | ✓ live lookup | Immediate — a downgrade bites on the next request |
198
+ | JWT bearer | ✓ from the token's `tiers` claim | Stale until the token expires — `auth.jwt.expiresIn` (default 180s), or up to **15 min + one TTL** on a scope-bearing token |
199
+ | API key | ✗ none | — |
200
+ | OAuth bearer | ✗ none | — |
201
+ | Scope-only / anonymous | ✗ none | — |
202
+
203
+ The session path reads the subscriptions table and bakes the result into the JWT it mints, so the fast path costs no database round trip. That is the same tradeoff organization roles already make, and the reason `authMethod: 'session'` exists for callers who need a revocation to be immediate. The lag cuts both ways — a tier *upgrade* is invisible for just as long, so re-authenticate after checkout rather than waiting out the TTL.
204
+
205
+ How long the lag actually is depends on the token:
206
+
207
+ - **A plain bearer** is stale for at most one `auth.jwt.expiresIn` (default 180s).
208
+ - **A scope-bearing token** is stale for up to **`SCOPE_CARRY_FORWARD_MAX_SECONDS` (15 min) plus one TTL** — roughly 18 minutes at the default. The middleware's rolling refresh re-mints such a token on every authenticated call and carries the `tiers` claim forward verbatim, exactly as it carries the scope claim, so tier roles ride the refresh without a fresh subscription lookup.
209
+
210
+ > `auth.jwt.expiresIn` has **no upper bound**. It is the entitlement revocation window as much as the auth one — a 24-hour TTL means a cancelled customer keeps paid access for up to 24 hours on the JWT transport. If you raise it, raise it knowing that.
211
+
212
+
213
+ API keys and OAuth bearers stamp **nothing**, deliberately. A key is an integration credential rather than a person: it may be issued to a user who holds a subscription, but granting a paid entitlement to a long-lived server key is invisible at issue time and revoking the subscription would not revoke the key. A caller that needs tier-gated routes should authenticate with a session, or with a JWT minted from one.
214
+
215
+ Org-vs-personal precedence applies here exactly as it does everywhere else — the active organization's subscription is what gets stamped. See below.
216
+
217
+ ## Webhook wiring
218
+
219
+ The plugin ships **no webhook route of its own**. Stripe events arrive on the standard inbound surface, which verifies the signature and deduplicates on `(provider, externalId)`, then dispatches through `WEBHOOKS_QUEUE`.
220
+
221
+ Delivery is **at-least-once, not exactly-once**: dedup stops Stripe redelivering an event you already accepted, but a handler that throws makes the queue retry the whole message, re-running every handler registered for it. The bundled handlers are idempotent — they upsert on `(userId, organizationId)` or look the row up by `stripeSubscriptionId` — so a replay converges instead of duplicating. Any handler you add for `stripe:*` needs the same property.
222
+
223
+ Point a Stripe webhook endpoint at:
224
+
225
+ ```
226
+ POST https://<your-api-domain>/webhooks/v1/inbound/stripe
227
+ ```
228
+
229
+ and subscribe it to the events the plugin consumes:
230
+
231
+ | Event | Effect on subscription state |
232
+ |-------|------------------------------|
233
+ | `checkout.session.completed` | Creates (or upgrades) the subscription, stamping tier, customer and price |
234
+ | `customer.subscription.updated` | Re-resolves the tier from the price; updates status, period end, cancellation |
235
+ | `customer.subscription.deleted` | Marks cancelled and soft-deletes |
236
+ | `invoice.paid` | Marks active and extends `expiresAt` to the newly paid period — the renewal path |
237
+ | `invoice.payment_failed` | Marks `past_due` |
238
+
239
+ Without these, a subscription is created at checkout and then never renews, downgrades or cancels — which is why `webhooksBinding` is a compile-time requirement rather than a runtime warning.
240
+
241
+ An event whose Stripe price maps to no configured tier is **logged and not granted**. That is deliberate: guessing a tier from an unrecognized price can only guess upward. If subscriptions stop activating after a pricing change, check that every tier's `priceId` matches the live Stripe price.
242
+
243
+ Cancellation is not immediate. `cancel_at_period_end` leaves the subscription `active` — the customer paid through the period — and entitlements end when Stripe sends `customer.subscription.deleted`.
244
+
245
+ State sync runs on the queue, which is correct for entitlement propagation. Anything that must post to a ledger synchronously belongs in an action, not a webhook handler.
246
+
247
+ > An inbound event is recorded and deduplicated **before** it is queued, so if the queue send itself fails, Stripe's redelivery is suppressed for that event ID. Replay it with the inbound retry endpoint (`POST /webhooks/v1/inbound/events/:id/retry`). This is inbound-surface behaviour and applies to every provider, not just Stripe.
248
+
249
+
250
+ ## What the compiler generates
251
+
252
+ 1. `src/plugins/subscriptions/lib/` — the plugin itself, emitted as source. It is **not** an npm dependency; the only package added to your `package.json` is `stripe`.
253
+ 2. `src/plugins/subscriptions/schema.ts` — a re-export of the table in `lib/`, so drizzle-kit, the auth schema barrel and the runtime all resolve to one definition.
254
+ 3. `src/plugins/subscriptions/index.ts` — the plugin with your tiers, auth database and org-membership lookup already bound.
255
+ 4. A migration creating the `subscriptions` table in the auth database.
256
+ 5. Registration of the Stripe handlers into the webhooks queue consumer.
257
+ 6. `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` on the generated `Env` type.
258
+
259
+ Everything under `src/` is generated — change tiers in `quickback.config.ts` and recompile. That includes `lib/`: the plugin ships with the compiler that configured it, so the tier-to-role rule and the auth middleware reading those roles always come from one version. Upgrades arrive by recompiling, not by `npm update`.
260
+
261
+ ## Limits name your own resources
262
+
263
+ `limits` is an open map of numbers — the plugin stores it on the subscription row and returns it from `GET /subscriptions/me`; it never enforces anything itself. The keys are yours, and they are only meaningful if they refer to something real. The tiers above cap `projects`, so the project table is what they are talking about:
264
+
265
+ ```ts
266
+ // features/projects/projects.ts
267
+ import { q, defineTable } from "@quickback/compiler";
268
+
269
+ export const projects = q.table("projects", {
270
+ id: q.uuid("id").primaryKey(),
271
+ owner_id: q.uuid("owner_id").notNull(),
272
+ name: q.text("name").notNull(),
273
+ ...q.audit(),
274
+ ...q.softDelete(),
275
+ });
276
+
277
+ export default defineTable(projects, {
278
+ read: { access: { roles: ["AUTHENTICATED"] } },
279
+ crud: {
280
+ create: { access: { roles: ["AUTHENTICATED"] } },
281
+ update: { access: { roles: ["AUTHENTICATED"] } },
282
+ delete: { access: { roles: ["AUTHENTICATED"] } },
283
+ },
284
+ });
285
+ ```
286
+
287
+ To enforce a limit, read `limits` from `GET /subscriptions/me` (or query the subscriptions table directly in an action) and compare it against a count before creating the row. Enforcement is yours to write until tier-aware access rules land; the plugin's job is to make the caller's current tier and its limits available.
288
+
289
+ ## Local development
290
+
291
+ Forward Stripe events to a local `wrangler dev`:
292
+
293
+ ```bash
294
+ stripe listen --forward-to localhost:8787/webhooks/v1/inbound/stripe
295
+ ```
296
+
297
+ `stripe listen` prints a signing secret for the session — use it as `STRIPE_WEBHOOK_SECRET` in `.dev.vars`.
@@ -0,0 +1,228 @@
1
+ # The Stripe Dev Loop
2
+
3
+ Stripe is the one integration you cannot fully exercise from your own test
4
+ suite: the interesting states — a renewal, a failed card, a cancellation at
5
+ period end — are produced by Stripe's clock, not yours. This page is how to
6
+ drive them.
7
+
8
+ ## Test keys and live keys are the same code
9
+
10
+ Every deployment target runs the **same compiled Worker**. Nothing about test
11
+ mode versus live mode is a compile-time branch — the key you set decides which
12
+ Stripe you are talking to, and both Stripe keys and the webhook signing secret
13
+ are values you never commit.
14
+
15
+ That means there is exactly one thing to get right: which secret value each
16
+ target holds.
17
+
18
+ ### Named environments
19
+
20
+ Declare targets with the top-level `environments` key (see
21
+ [Multi-Domain Architecture](/configure/domains) and
22
+ [D1 environments](/platform/database/d1#named-cloudflare-deployment-environments)).
23
+ Each target deploys as its **own Wrangler Worker script** — a project named
24
+ `storefront` with `dev` and `prod` targets deploys `storefront-dev` and
25
+ `storefront-prod`.
26
+
27
+ That separation is what makes test and live keys safe: Cloudflare scopes secrets
28
+ to a script, and these are two different scripts. It is real isolation, not a
29
+ naming convention.
30
+
31
+ ```bash
32
+ # Test keys on the dev Worker
33
+ npx wrangler secret put STRIPE_SECRET_KEY --env dev # sk_test_…
34
+ npx wrangler secret put STRIPE_WEBHOOK_SECRET --env dev # whsec_… (dev endpoint)
35
+
36
+ # Live keys on the prod Worker
37
+ npx wrangler secret put STRIPE_SECRET_KEY --env prod # sk_live_…
38
+ npx wrangler secret put STRIPE_WEBHOOK_SECRET --env prod # whsec_… (prod endpoint)
39
+ ```
40
+
41
+ Point a **separate Stripe webhook endpoint** at each target's hostname. Each
42
+ endpoint has its own signing secret, so the two `STRIPE_WEBHOOK_SECRET` values
43
+ differ even though the two `sk_` keys differ for a different reason.
44
+
45
+ > A target's `requiredSecrets` list must **equal** the generated runtime secret
46
+ > inventory — the compiler rejects a mismatch. It is a per-target copy of the
47
+ > same list of *names*; it is not a way to require different secrets in dev than
48
+ > in prod. Dev and prod differ only in the **values** you `wrangler secret put`.
49
+
50
+
51
+ Without named environments there is one Worker and one set of secrets, so
52
+ switching to live keys means overwriting the test ones. Add the second target
53
+ before you take real money.
54
+
55
+ ### Local development
56
+
57
+ `wrangler dev` reads **`.dev.vars`**, not `.env`. It is gitignored:
58
+
59
+ ```bash title=".dev.vars"
60
+ STRIPE_SECRET_KEY=sk_test_…
61
+ STRIPE_WEBHOOK_SECRET=whsec_…
62
+ ```
63
+
64
+ Use a **test** key here, always. `.dev.vars` is the file most likely to be read
65
+ aloud in a screenshare.
66
+
67
+ For a project with named environments, the generated `npm run dev` already
68
+ selects the dev target (`wrangler dev --env dev`).
69
+
70
+ ### Getting a legible failure instead of an opaque one
71
+
72
+ Neither Stripe secret is checked by default. A Worker with no `STRIPE_SECRET_KEY`
73
+ starts happily and throws on the first call that reaches `services.stripe`; a
74
+ missing `STRIPE_WEBHOOK_SECRET` makes the inbound route return `500`.
75
+
76
+ Declaring the key under [`bindings.secrets`](/configure/bindings#secrets) with
77
+ `required: true` adds it to the generated env guard:
78
+
79
+ ```ts
80
+ bindings: {
81
+ secrets: [
82
+ { name: "STRIPE_SECRET_KEY", description: "Stripe API key", required: true },
83
+ ],
84
+ }
85
+ ```
86
+
87
+ Be precise about what that buys, because it is less than it sounds:
88
+
89
+ - It is **not** a startup check. The guard runs inside `fetch`, on the **first
90
+ request** the Worker serves, and memoizes the result. A misconfigured Worker
91
+ deploys successfully and looks healthy until someone calls it.
92
+ - What you get is a **legible** failure: `503` with `code: "MISSING_ENV"` and a
93
+ `missing` array naming the variable, instead of an opaque `500` from wherever
94
+ the unset key was first dereferenced. That is a real improvement — it is just
95
+ a diagnostics improvement, not a deployment gate.
96
+ - It wraps **`fetch` only**. The `queue`, `scheduled`, and `email` handlers are
97
+ exported unguarded, so it does **not** cover the queue-dispatched Stripe path
98
+ this page is about. Your fulfilment handler still fails at first use, exactly
99
+ as it would without the declaration.
100
+
101
+ So declare it — a named 503 beats an anonymous 500 — but do not treat a green
102
+ deploy as evidence the key is set. Only a request proves that, and only for the
103
+ `fetch` path.
104
+
105
+ > **Only declare a name the compiler is not already emitting.** There is no
106
+ > deduplication, and a name declared twice lands in the generated `Env`
107
+ > interface twice — the generated project then fails `tsc` with *Duplicate
108
+ > identifier*.
109
+ >
110
+ > - `STRIPE_WEBHOOK_SECRET` is emitted whenever webhooks are on. **Never declare it.**
111
+ > - `STRIPE_SECRET_KEY` is emitted only when the
112
+ > [subscriptions plugin](/platform/auth/plugins/subscriptions) is enabled. Declare
113
+ > it only in a webhooks-only project.
114
+ >
115
+ > Adding a `required: true` secret also grows the runtime inventory, so every
116
+ > named environment's `requiredSecrets` must gain the same name in the same
117
+ > change.
118
+
119
+
120
+ ## Forwarding events to localhost
121
+
122
+ Stripe cannot reach your laptop, so the Stripe CLI relays for it:
123
+
124
+ ```bash
125
+ stripe listen --forward-to localhost:8787/webhooks/v1/inbound/stripe
126
+ ```
127
+
128
+ `8787` is the default `wrangler dev` port; change it if you set `dev.port`. The
129
+ path is the standard inbound route — the same one a dashboard endpoint targets
130
+ in production, so local and deployed exercise identical code.
131
+
132
+ Trigger a specific event without touching the UI:
133
+
134
+ ```bash
135
+ stripe trigger checkout.session.completed
136
+ ```
137
+
138
+ > `stripe trigger` fabricates a *plausible* event, not one of yours — the
139
+ > synthetic Checkout Session carries no `metadata.orderId`, so the
140
+ > [one-off checkout handler](/platform/payments/one-off-checkout) correctly
141
+ > ignores it. That is the handler working, not failing. To exercise the real
142
+ > path, create a session through your own action and pay it with card
143
+ > `4242 4242 4242 4242`.
144
+
145
+
146
+ ### The two `STRIPE_WEBHOOK_SECRET`s
147
+
148
+ This is the single most common way to lose an afternoon.
149
+
150
+ | Source | Scope | Where it belongs |
151
+ |--------|-------|------------------|
152
+ | Printed by `stripe listen` on startup | That CLI session only. New secret each time in some setups; it does **not** match any dashboard endpoint. | `.dev.vars`, while the CLI is running |
153
+ | Shown on a dashboard webhook endpoint | That endpoint, permanently | `wrangler secret put --env <target>` for the Worker that endpoint points at |
154
+
155
+ They are **not interchangeable**. Putting a dashboard endpoint's secret in
156
+ `.dev.vars` while forwarding with `stripe listen` produces `401 Unauthorized` on
157
+ every delivery, from a correctly-signed request — the signature is valid, just
158
+ against a different secret. Restarting `stripe listen` without updating
159
+ `.dev.vars` fails the same way.
160
+
161
+ If local deliveries 401, check that pairing before anything else.
162
+
163
+ ## Test clocks
164
+
165
+ Test clocks are how you test the parts of a subscription that only happen with
166
+ the passage of time — renewal, trial expiry, dunning after a failed payment,
167
+ cancellation at period end. They are **test mode only**.
168
+
169
+ A customer created *on* a clock experiences time as the clock reports it.
170
+ Advancing the clock makes Stripe generate the invoices and events it would have
171
+ generated over that interval, delivered to your webhook endpoint exactly as real
172
+ ones are.
173
+
174
+ ```bash
175
+ # 1. A clock starting now
176
+ stripe test_helpers test_clocks create --frozen-time $(date +%s)
177
+
178
+ # 2. A customer bound to it
179
+ stripe customers create --test-clock clock_… --email dev@example.com
180
+
181
+ # 3. Subscribe them (or run your own checkout flow for that customer),
182
+ # then jump past the period end — 32 days here
183
+ stripe test_helpers test_clocks advance --id clock_… --frozen-time $(( $(date +%s) + 32*86400 ))
184
+ ```
185
+
186
+ With `stripe listen` running, `invoice.paid` and `customer.subscription.updated`
187
+ arrive at your local Worker and the
188
+ [subscriptions plugin's](/platform/auth/plugins/subscriptions#webhook-wiring)
189
+ handlers extend the subscription — the renewal path, which is otherwise
190
+ untestable without waiting a month.
191
+
192
+ Advancing is asynchronous: the clock reports `advancing` before `ready`, and
193
+ events arrive over several seconds. If nothing shows up, confirm the clock
194
+ reached `ready` before concluding the handler is broken.
195
+
196
+ Useful things to drive this way:
197
+
198
+ | Scenario | How |
199
+ |----------|-----|
200
+ | Renewal | Advance past `current_period_end` → `invoice.paid` |
201
+ | Trial ending | Advance past the trial → subscription leaves `trialing` |
202
+ | Failed renewal | Attach card `4000 0000 0000 0341`, then advance → `invoice.payment_failed`, status `past_due` |
203
+ | Cancel at period end | Cancel with `cancel_at_period_end`, advance → `customer.subscription.deleted` |
204
+
205
+ That last row is worth confirming by hand at least once: entitlements are
206
+ supposed to survive until the period actually ends, so a correct system keeps
207
+ the subscriber `active` right up until the `deleted` event.
208
+
209
+ ## A checklist before going live
210
+
211
+ 1. Live `STRIPE_SECRET_KEY` set on the prod target — and it starts `sk_live_`.
212
+ 2. A dashboard webhook endpoint on the **prod** hostname, subscribed to every
213
+ event your handlers register for.
214
+ 3. That endpoint's signing secret set as `STRIPE_WEBHOOK_SECRET` on the prod
215
+ target — not the dev endpoint's, not the CLI's.
216
+ 4. Every tier's `priceId` points at a **live-mode** price. Test-mode price ids do
217
+ not exist in live mode, so checkout fails and, on the inbound side, an
218
+ unrecognized price is
219
+ [logged and not granted](/platform/auth/plugins/subscriptions#webhook-wiring).
220
+ 5. One real transaction, refunded afterwards. There is no test mode for the
221
+ thing you skipped.
222
+
223
+ ## See also
224
+
225
+ - [Payments overview](/platform/payments) — what is native, and what is not.
226
+ - [One-off checkout](/platform/payments/one-off-checkout) — the recipe this loop tests.
227
+ - [Subscriptions Plugin](/platform/auth/plugins/subscriptions) — tiers, portal, renewals.
228
+ - [Inbound Webhooks](/platform/webhooks/inbound) — verification, dedup, retries.