@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.
- package/dist/codex/AGENTS.md +290 -0
- package/dist/commands/codex.d.ts +16 -0
- package/dist/commands/codex.d.ts.map +1 -0
- package/dist/commands/codex.js +159 -0
- package/dist/commands/codex.js.map +1 -0
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +405 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +94 -159
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/sweep-stale.d.ts +25 -0
- package/dist/lib/sweep-stale.d.ts.map +1 -0
- package/dist/lib/sweep-stale.js +179 -0
- package/dist/lib/sweep-stale.js.map +1 -0
- package/dist/lib/sweep-stale.test.d.ts +2 -0
- package/dist/lib/sweep-stale.test.d.ts.map +1 -0
- package/dist/lib/sweep-stale.test.js +130 -0
- package/dist/lib/sweep-stale.test.js.map +1 -0
- package/dist/skill/docs/configure/auth.md +7 -5
- package/dist/skill/docs/configure/index.md +4 -3
- package/dist/skill/docs/configure/providers.md +1 -1
- package/dist/skill/docs/define/authz-roles.md +52 -0
- package/dist/skill/docs/define/changesets.md +8 -3
- package/dist/skill/docs/platform/auth/jwt-optimization.md +4 -2
- package/dist/skill/docs/platform/auth/plugins/index.md +20 -0
- package/dist/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
- package/dist/skill/docs/platform/payments/dev-loop.md +228 -0
- package/dist/skill/docs/platform/payments/index.md +158 -0
- package/dist/skill/docs/platform/payments/one-off-checkout.md +266 -0
- package/dist/skill/docs/platform/realtime/durable-objects.md +1 -1
- package/dist/skill/docs/platform/realtime/index.md +1 -1
- package/dist/skill/docs/platform/realtime/live-views.md +1 -1
- package/dist/skill/docs/platform/realtime/named-invalidations.md +1 -1
- package/dist/skill/docs/platform/realtime/using-realtime.md +1 -1
- package/dist/skill/docs/platform/webhooks/inbound.md +5 -2
- package/dist/skill/docs/tooling/output.md +3 -2
- package/dist/skill/docs/ui/admin/connecting.md +1 -1
- package/package.json +1 -1
- package/src/skill/docs/configure/auth.md +7 -5
- package/src/skill/docs/configure/index.md +4 -3
- package/src/skill/docs/configure/providers.md +1 -1
- package/src/skill/docs/define/authz-roles.md +52 -0
- package/src/skill/docs/define/changesets.md +8 -3
- package/src/skill/docs/platform/auth/jwt-optimization.md +4 -2
- package/src/skill/docs/platform/auth/plugins/index.md +20 -0
- package/src/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
- package/src/skill/docs/platform/payments/dev-loop.md +228 -0
- package/src/skill/docs/platform/payments/index.md +158 -0
- package/src/skill/docs/platform/payments/one-off-checkout.md +266 -0
- package/src/skill/docs/platform/realtime/durable-objects.md +1 -1
- package/src/skill/docs/platform/realtime/index.md +1 -1
- package/src/skill/docs/platform/realtime/live-views.md +1 -1
- package/src/skill/docs/platform/realtime/named-invalidations.md +1 -1
- package/src/skill/docs/platform/realtime/using-realtime.md +1 -1
- package/src/skill/docs/platform/webhooks/inbound.md +5 -2
- package/src/skill/docs/tooling/output.md +3 -2
- package/src/skill/docs/ui/admin/connecting.md +1 -1
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Payments
|
|
2
|
+
|
|
3
|
+
There is no payments *pillar*. Payments are not a security boundary and not a
|
|
4
|
+
schema concern, so Quickback ships three concrete pieces rather than an
|
|
5
|
+
abstraction over billing:
|
|
6
|
+
|
|
7
|
+
| Piece | What it is | Where |
|
|
8
|
+
|-------|------------|-------|
|
|
9
|
+
| Subscriptions plugin | Tiers, Checkout, the billing portal, and subscription state kept in sync by Stripe | [Subscriptions Plugin](/platform/auth/plugins/subscriptions) |
|
|
10
|
+
| `services.stripe` | A configured Stripe client on the services layer, reachable from any action | This page |
|
|
11
|
+
| `stripe:*` inbound webhooks | Signature-verified, deduplicated Stripe events dispatched to your handlers | [Inbound Webhooks](/platform/webhooks/inbound) |
|
|
12
|
+
|
|
13
|
+
Everything else — one-off charges, marketplaces, usage billing — is composed
|
|
14
|
+
from those three. The [one-off checkout recipe](/platform/payments/one-off-checkout)
|
|
15
|
+
shows the composition end to end.
|
|
16
|
+
|
|
17
|
+
## `services.stripe`
|
|
18
|
+
|
|
19
|
+
Actions already receive a `services` object ([Executor Parameters](/define/actions/scoped-db#executor-parameters)).
|
|
20
|
+
When a project needs Stripe, a configured client appears on it:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
async execute({ services, record }) {
|
|
24
|
+
const session = await services.stripe.checkout.sessions.create({ /* … */ });
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
No import, no client construction, no key plumbing.
|
|
29
|
+
|
|
30
|
+
### When it is emitted
|
|
31
|
+
|
|
32
|
+
The client appears when **either** of these is true:
|
|
33
|
+
|
|
34
|
+
1. the [subscriptions plugin](/platform/auth/plugins/subscriptions) is enabled, or
|
|
35
|
+
2. the webhooks subsystem is on — that is, `providers.database` declares a
|
|
36
|
+
`webhooksBinding`.
|
|
37
|
+
|
|
38
|
+
Condition 2 is broader than it may look, and deliberately so. There is no
|
|
39
|
+
per-provider inbound webhook configuration surface: the inbound route registers
|
|
40
|
+
exactly one provider, Stripe, so *any* project that turned webhooks on is a
|
|
41
|
+
project that can receive Stripe events. The same condition adds `stripe` to the
|
|
42
|
+
generated `package.json` (pinned at `^22.5.0`), so the dependency and the client
|
|
43
|
+
can never disagree about whether Stripe is in play.
|
|
44
|
+
|
|
45
|
+
> **Accepted over-trigger.** A project that only *receives* Stripe webhooks and
|
|
46
|
+
> never calls the API still gets the SDK in its bundle — roughly 130 KB gzipped
|
|
47
|
+
> — because inbound signature verification is hand-rolled on `crypto.subtle` and
|
|
48
|
+
> does not need the SDK at all. This was taken deliberately: projects receiving
|
|
49
|
+
> Stripe events almost always call Stripe from their handlers, and the one-off
|
|
50
|
+
> checkout recipe depends on the client being there. If a real project hits
|
|
51
|
+
> Worker bundle limits because of it, that is the trigger to narrow the
|
|
52
|
+
> condition.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
### Cloudflare only, and it fails at compile time
|
|
56
|
+
|
|
57
|
+
Both triggers are Cloudflare-only surfaces, and the non-Cloudflare
|
|
58
|
+
`createServices()` takes no environment to read a key from. So a project that
|
|
59
|
+
wants Stripe on another runtime is a **compile error**, not a silently missing
|
|
60
|
+
client. The error names which of the two triggers pulled Stripe in.
|
|
61
|
+
|
|
62
|
+
### Lazy, memoized, and fail-closed on the secret
|
|
63
|
+
|
|
64
|
+
The client is built on first access and reused for the rest of the request. A
|
|
65
|
+
request that never touches Stripe pays nothing; one that touches it repeatedly
|
|
66
|
+
builds the client once.
|
|
67
|
+
|
|
68
|
+
If `STRIPE_SECRET_KEY` is unset, the **first access throws** — it never yields a
|
|
69
|
+
half-configured client that fails later at the network boundary:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
services.stripe requires the STRIPE_SECRET_KEY secret, which is not set.
|
|
73
|
+
Set it with `wrangler secret put STRIPE_SECRET_KEY` for a deployed Worker,
|
|
74
|
+
or add STRIPE_SECRET_KEY to .dev.vars for local development.
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Nothing checks the key before that. The Worker starts fine without it and fails
|
|
78
|
+
on the first call that reaches Stripe — including one made from a queue handler,
|
|
79
|
+
where the failure surfaces as a retried message rather than an HTTP response. See
|
|
80
|
+
[the dev loop](/platform/payments/dev-loop#getting-a-legible-failure-instead-of-an-opaque-one)
|
|
81
|
+
for how much of that is worth improving, and how little the env guard covers.
|
|
82
|
+
|
|
83
|
+
> `STRIPE_SECRET_KEY` is added to the generated `Env` type only when the
|
|
84
|
+
> **subscriptions plugin** is enabled. A webhooks-only project gets
|
|
85
|
+
> `services.stripe` but no `Env` entry for the key — the client reads it off the
|
|
86
|
+
> environment regardless. Do not "fix" this by redeclaring the name under
|
|
87
|
+
> `bindings.secrets` when the plugin is on: the compiler does not deduplicate,
|
|
88
|
+
> and the generated project fails `tsc` with *Duplicate identifier
|
|
89
|
+
> 'STRIPE_SECRET_KEY'*.
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
### The client's configuration
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
new Stripe(secretKey, { maxNetworkRetries: 3, timeout: 30_000 })
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Two things are notable by their absence:
|
|
99
|
+
|
|
100
|
+
- **No `httpClient`.** On Workers the `workerd` export condition resolves to
|
|
101
|
+
stripe-node's fetch/`SubtleCrypto` build, so `Stripe.createFetchHttpClient()`
|
|
102
|
+
is not needed. Passing it is not an improvement.
|
|
103
|
+
- **No `apiVersion`.** stripe-node types `apiVersion` as an exact string literal
|
|
104
|
+
matching the SDK's own pinned version, so hardcoding one breaks `tsc` the next
|
|
105
|
+
time the pin moves. Omitting it uses the SDK's pinned version — the same
|
|
106
|
+
choice Stripe's own Workers template makes. Pin the *SDK*, not the API version
|
|
107
|
+
string.
|
|
108
|
+
|
|
109
|
+
### Reaching Stripe outside an action
|
|
110
|
+
|
|
111
|
+
`services` is an action-executor parameter. Queue-dispatched webhook handlers
|
|
112
|
+
get a raw `env` instead, and the generated `Env` **is** `CloudflareBindings` —
|
|
113
|
+
so `createServices` takes it directly:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { createServices } from "../../../lib/services";
|
|
117
|
+
|
|
118
|
+
onWebhookEvent("stripe:invoice.paid", async (ctx) => {
|
|
119
|
+
const { stripe } = createServices(ctx.env);
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
You rarely need this on the inbound path: the surface has already verified the
|
|
124
|
+
signature and handed you the parsed envelope. Reach for it when a handler must
|
|
125
|
+
call *back* into Stripe — fetching line items an event omits, say.
|
|
126
|
+
|
|
127
|
+
> If you ever verify a Stripe signature yourself, note that on Workers it is
|
|
128
|
+
> async-only: `await stripe.webhooks.constructEventAsync(...)`. The synchronous
|
|
129
|
+
> `constructEvent` has no Web Crypto path and throws. The inbound surface
|
|
130
|
+
> already does this for you.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
## What is not native
|
|
134
|
+
|
|
135
|
+
| Not built | Why, and what to do instead |
|
|
136
|
+
|-----------|------------------------------|
|
|
137
|
+
| **Stripe Connect** | Nothing to build. The inbound envelope already preserves the top-level `account` (`acct_…`) — read it via `ctx.event.account` and route on it yourself. See [Stripe Connect](/platform/webhooks/inbound#stripe-connect). |
|
|
138
|
+
| **Invoicing** | Stripe's own invoicing API is a better invoicing product than a wrapper over it would be. Call it through `services.stripe`. |
|
|
139
|
+
| **A generic payments pillar** | A provider-neutral payments abstraction over one provider is a guess about the second one. There is deliberately no `providers.payments` category; it gets revisited if a second payments provider actually lands. |
|
|
140
|
+
| **A one-off payment primitive** | Deliberately a [recipe](/platform/payments/one-off-checkout), not a define surface, until the recipe proves to have a hole in real use. |
|
|
141
|
+
|
|
142
|
+
## The escape hatch
|
|
143
|
+
|
|
144
|
+
`services.stripe` is a plain, fully-typed `Stripe` instance. Anything the Stripe
|
|
145
|
+
Node SDK can do, an action can do — payment intents, refunds, transfers, Connect
|
|
146
|
+
account links, tax calculations — with no Quickback surface in between and no
|
|
147
|
+
feature request required.
|
|
148
|
+
|
|
149
|
+
The rule that constrains it is not about Stripe. It is about *where* money
|
|
150
|
+
moves: anything that must post to a ledger synchronously belongs in an action,
|
|
151
|
+
where the caller sees the failure, and never in an async queue handler. The
|
|
152
|
+
[recipe](/platform/payments/one-off-checkout#the-money-rule) spells this out.
|
|
153
|
+
|
|
154
|
+
## Next
|
|
155
|
+
|
|
156
|
+
- [One-off checkout](/platform/payments/one-off-checkout) — charge for a record, then fulfil it.
|
|
157
|
+
- [The Stripe dev loop](/platform/payments/dev-loop) — test keys, `stripe listen`, test clocks.
|
|
158
|
+
- [Subscriptions Plugin](/platform/auth/plugins/subscriptions) — recurring billing, already built.
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# One-off Checkout
|
|
2
|
+
|
|
3
|
+
Charging once for one row — an order, a ticket, a report — is a **recipe**, not a
|
|
4
|
+
Quickback primitive. It is two halves that already exist:
|
|
5
|
+
|
|
6
|
+
1. An **action** creates a Stripe Checkout Session via
|
|
7
|
+
[`services.stripe`](/platform/payments#servicesstripe), carrying the record's
|
|
8
|
+
id in `metadata`.
|
|
9
|
+
2. A **`stripe:checkout.session.completed` handler** on the
|
|
10
|
+
[inbound webhook surface](/platform/webhooks/inbound) reads that id back and
|
|
11
|
+
marks the record paid.
|
|
12
|
+
|
|
13
|
+
`metadata` is the whole link between them. Stripe returns it verbatim on the
|
|
14
|
+
event, so the handler never has to guess which row a payment belongs to.
|
|
15
|
+
|
|
16
|
+
There is deliberately no `definePayment()`. If this recipe turns out to have a
|
|
17
|
+
hole in real use, that is the trigger to build one.
|
|
18
|
+
|
|
19
|
+
## Configuration
|
|
20
|
+
|
|
21
|
+
`webhooksBinding` is what turns on the inbound surface — and with it,
|
|
22
|
+
`services.stripe`:
|
|
23
|
+
|
|
24
|
+
```ts title="quickback/quickback.config.ts"
|
|
25
|
+
import { defineAuth, defineConfig, defineDatabase, defineRuntime } from "@quickback/compiler";
|
|
26
|
+
|
|
27
|
+
export default defineConfig({
|
|
28
|
+
name: "storefront",
|
|
29
|
+
providers: {
|
|
30
|
+
runtime: defineRuntime("cloudflare"),
|
|
31
|
+
database: defineDatabase("cloudflare-d1", {
|
|
32
|
+
binding: "DB",
|
|
33
|
+
// Turns on inbound webhooks — and emits services.stripe.
|
|
34
|
+
webhooksBinding: "WEBHOOKS_DB",
|
|
35
|
+
}),
|
|
36
|
+
auth: defineAuth("better-auth", {
|
|
37
|
+
emailAndPassword: { enabled: true },
|
|
38
|
+
}),
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Set both secrets — see [the dev loop](/platform/payments/dev-loop) for test vs
|
|
44
|
+
live values:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx wrangler secret put STRIPE_SECRET_KEY
|
|
48
|
+
npx wrangler secret put STRIPE_WEBHOOK_SECRET
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## The record
|
|
52
|
+
|
|
53
|
+
Nothing about this table is payment machinery — it is your domain row plus three
|
|
54
|
+
columns recording what Stripe did to it.
|
|
55
|
+
|
|
56
|
+
```ts title="quickback/features/orders/orders.ts"
|
|
57
|
+
import { q, defineTable } from "@quickback/compiler";
|
|
58
|
+
|
|
59
|
+
export const orders = q.table("orders", {
|
|
60
|
+
id: q.id(),
|
|
61
|
+
description: q.text().required(),
|
|
62
|
+
amountCents: q.int().required(),
|
|
63
|
+
currency: q.text().default("usd").required(),
|
|
64
|
+
status: q.text().default("unpaid").required(),
|
|
65
|
+
stripeSessionId: q.text().optional(),
|
|
66
|
+
paidAt: q.timestamp().optional(),
|
|
67
|
+
organizationId: q.scope("organization"),
|
|
68
|
+
...q.audit(),
|
|
69
|
+
...q.softDelete(),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
export default defineTable(orders, {
|
|
73
|
+
read: { access: { roles: ["AUTHENTICATED"] } },
|
|
74
|
+
crud: {
|
|
75
|
+
create: { access: { roles: ["AUTHENTICATED"] } },
|
|
76
|
+
// Stripe is the only writer of `status: "paid"`. Clients never mark
|
|
77
|
+
// their own orders paid, so ordinary update/delete stay admin-only.
|
|
78
|
+
update: { access: { roles: ["admin"] } },
|
|
79
|
+
delete: { access: { roles: ["admin"] } },
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`status` starts at `unpaid` and only the webhook handler moves it. That is the
|
|
85
|
+
entire trust model: the client is told where to pay, and Stripe — not the
|
|
86
|
+
client — reports back that it happened.
|
|
87
|
+
|
|
88
|
+
## The action and the handler
|
|
89
|
+
|
|
90
|
+
Both halves live in one action file. The handler is registered at **module
|
|
91
|
+
scope**, which is what puts it on the queue consumer's module graph: feature
|
|
92
|
+
action files are imported by the feature's routes, the routes are imported by
|
|
93
|
+
the worker entry, and that same entry exports the `queue()` consumer.
|
|
94
|
+
|
|
95
|
+
```ts title="quickback/features/orders/actions/startCheckout.ts"
|
|
96
|
+
import { z } from "zod";
|
|
97
|
+
import { and, eq } from "drizzle-orm";
|
|
98
|
+
import { drizzle } from "drizzle-orm/d1";
|
|
99
|
+
import { defineAction, orders } from "../.quickback/define-action";
|
|
100
|
+
import { onWebhookEvent } from "../../../lib/webhooks";
|
|
101
|
+
|
|
102
|
+
export default defineAction({
|
|
103
|
+
description: "Create a Stripe Checkout Session for this order.",
|
|
104
|
+
input: z.object({
|
|
105
|
+
successUrl: z.string().url(),
|
|
106
|
+
cancelUrl: z.string().url(),
|
|
107
|
+
}),
|
|
108
|
+
access: { roles: ["AUTHENTICATED"] },
|
|
109
|
+
async execute({ services, record, input }) {
|
|
110
|
+
if (record.status === "paid") {
|
|
111
|
+
throw new Error("Order is already paid");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const session = await services.stripe.checkout.sessions.create(
|
|
115
|
+
{
|
|
116
|
+
mode: "payment",
|
|
117
|
+
success_url: input.successUrl,
|
|
118
|
+
cancel_url: input.cancelUrl,
|
|
119
|
+
line_items: [
|
|
120
|
+
{
|
|
121
|
+
quantity: 1,
|
|
122
|
+
price_data: {
|
|
123
|
+
currency: record.currency,
|
|
124
|
+
unit_amount: record.amountCents,
|
|
125
|
+
product_data: { name: record.description },
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
// The only link back to the row. Stripe returns it verbatim.
|
|
130
|
+
metadata: { orderId: record.id },
|
|
131
|
+
},
|
|
132
|
+
// A retried click reuses the session instead of opening a second one.
|
|
133
|
+
{ idempotencyKey: `order-checkout-${record.id}` },
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
return { checkoutUrl: session.url };
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// ── Fulfilment ────────────────────────────────────────────────────────────
|
|
141
|
+
onWebhookEvent("stripe:checkout.session.completed", async (ctx) => {
|
|
142
|
+
// Through `unknown`: ctx.data is a Record<string, unknown>, which does not
|
|
143
|
+
// sufficiently overlap a Stripe resource type for a one-step cast.
|
|
144
|
+
const session = ctx.data as unknown as import("stripe").Stripe.Checkout.Session;
|
|
145
|
+
const orderId = session.metadata?.orderId;
|
|
146
|
+
|
|
147
|
+
// A Checkout Session this recipe did not create. Not an error.
|
|
148
|
+
if (!orderId) return;
|
|
149
|
+
|
|
150
|
+
// `completed` is not `paid`: delayed-notification methods complete the
|
|
151
|
+
// session unpaid and settle later on async_payment_succeeded.
|
|
152
|
+
if (session.payment_status !== "paid") return;
|
|
153
|
+
|
|
154
|
+
const db = drizzle(ctx.env.DB);
|
|
155
|
+
const marked = await db
|
|
156
|
+
.update(orders)
|
|
157
|
+
// `q.timestamp()` is a text column on D1/SQLite — write the ISO string.
|
|
158
|
+
.set({
|
|
159
|
+
status: "paid",
|
|
160
|
+
stripeSessionId: session.id,
|
|
161
|
+
paidAt: new Date().toISOString(),
|
|
162
|
+
})
|
|
163
|
+
.where(and(eq(orders.id, orderId), eq(orders.status, "unpaid")))
|
|
164
|
+
.returning({ id: orders.id });
|
|
165
|
+
|
|
166
|
+
if (marked.length === 0) {
|
|
167
|
+
console.warn(
|
|
168
|
+
`stripe: no unpaid order ${orderId} for session ${session.id} — ignoring`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The action returns a URL; redirect the browser to it. Everything after that
|
|
175
|
+
happens on Stripe's domain, and the next thing your Worker hears is the webhook.
|
|
176
|
+
|
|
177
|
+
> **A webhook handler has no caller, so it has no scoped `db`.** Actions get a
|
|
178
|
+
> security-filtered handle that applies the org/owner firewall from the request
|
|
179
|
+
> principal ([Scoped DB](/define/actions/scoped-db)). A queued event has no
|
|
180
|
+
> principal to scope to, so the handler builds a plain Drizzle client off
|
|
181
|
+
> `ctx.env` instead — exactly as the bundled subscription handlers do. That
|
|
182
|
+
> client is **unfiltered**: the `where` clause is the only thing keeping the
|
|
183
|
+
> write on one row, which is why it matches on the id Stripe echoed back and on
|
|
184
|
+
> `status = "unpaid"`.
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
## Idempotency is not optional
|
|
188
|
+
|
|
189
|
+
Inbound delivery is **at-least-once**. Deduplication on `(provider, externalId)`
|
|
190
|
+
stops Stripe redelivering an event you already accepted, but it does not stop a
|
|
191
|
+
*retry*: if any handler registered for a message throws, the queue retries the
|
|
192
|
+
whole message and **every** handler for that event runs again.
|
|
193
|
+
|
|
194
|
+
So the handler must converge, not accumulate. Two properties do it here:
|
|
195
|
+
|
|
196
|
+
| Property | What it buys |
|
|
197
|
+
|----------|--------------|
|
|
198
|
+
| `where status = "unpaid"` | The second run updates zero rows. Marking paid twice is a no-op, not a double state change. |
|
|
199
|
+
| `.returning()` + a zero-row check | The no-op is *observable*, so "already handled" is distinguishable from "never matched". |
|
|
200
|
+
|
|
201
|
+
Write the same way for any handler you add: match on the id the provider echoed
|
|
202
|
+
back, guard the transition on the state you expect to leave, and make a re-run
|
|
203
|
+
land on nothing.
|
|
204
|
+
|
|
205
|
+
The `idempotencyKey` on the outbound side is the mirror image — it stops a
|
|
206
|
+
double-clicked action from opening two Checkout Sessions for one order.
|
|
207
|
+
|
|
208
|
+
## The money rule
|
|
209
|
+
|
|
210
|
+
**The queue handler does state marking. It does not move money.**
|
|
211
|
+
|
|
212
|
+
Marking an order paid is *state propagation*: Stripe already took the money, and
|
|
213
|
+
the handler is recording a fact that is true whether or not the Worker is
|
|
214
|
+
healthy. Async, retried, eventually-consistent — all correct.
|
|
215
|
+
|
|
216
|
+
Posting to a ledger is not that. A general-ledger entry must succeed or fail
|
|
217
|
+
with the operation that caused it, in a transaction the caller can see the
|
|
218
|
+
result of. A queue handler has no caller, no shared transaction, and a retry
|
|
219
|
+
policy that will happily run your posting logic a second time.
|
|
220
|
+
|
|
221
|
+
| Belongs in the handler | Belongs in an action |
|
|
222
|
+
|------------------------|----------------------|
|
|
223
|
+
| `status → "paid"`, `paidAt`, `stripeSessionId` | Posting double-entry GL rows |
|
|
224
|
+
| Enqueuing a receipt email | Debiting a wallet or credit balance |
|
|
225
|
+
| Invalidating a cache | Anything whose failure must fail the caller's request |
|
|
226
|
+
|
|
227
|
+
If fulfilment must post to a ledger, the handler marks the record paid and the
|
|
228
|
+
ledger posting happens in an action — invoked by the operation that needs it,
|
|
229
|
+
synchronously, where a failure is somebody's 500 rather than a silent retry.
|
|
230
|
+
|
|
231
|
+
## Failure modes
|
|
232
|
+
|
|
233
|
+
Handle these explicitly; none of them should be a guess.
|
|
234
|
+
|
|
235
|
+
| Situation | Correct response |
|
|
236
|
+
|-----------|------------------|
|
|
237
|
+
| No `metadata.orderId` | Return quietly. The endpoint receives every Stripe event for the account, including ones this recipe never created. |
|
|
238
|
+
| `orderId` present, no matching row | **Log loudly and stop.** Never fall back to matching on amount, email, or customer — that is how one customer's payment marks another customer's order paid. |
|
|
239
|
+
| Row already `paid` | Zero rows updated. Log at most; this is the retry path working. |
|
|
240
|
+
| `payment_status !== "paid"` | Return. Subscribe to `checkout.session.async_payment_succeeded` if you accept delayed-notification methods. |
|
|
241
|
+
| Genuinely transient failure (D1 unavailable) | **Throw.** That is what earns a retry. |
|
|
242
|
+
|
|
243
|
+
The distinction in the last two rows is the one to get right: throw only when a
|
|
244
|
+
retry could plausibly succeed. Throwing on an unknown order id buys three
|
|
245
|
+
pointless retries and then a `failed` row, when the honest outcome was "this
|
|
246
|
+
event is not mine".
|
|
247
|
+
|
|
248
|
+
> An inbound event is recorded and deduplicated **before** it is queued, so if
|
|
249
|
+
> the queue send itself fails, Stripe's redelivery is suppressed for that event
|
|
250
|
+
> id. Replay it with `POST /webhooks/v1/inbound/events/:id/retry`. This applies
|
|
251
|
+
> to every provider, not just Stripe.
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
## What this recipe does not cover
|
|
255
|
+
|
|
256
|
+
- **Refunds.** `services.stripe.refunds.create(...)` from an action, plus a
|
|
257
|
+
`stripe:charge.refunded` handler, following the same shape.
|
|
258
|
+
- **Recurring billing.** Use the
|
|
259
|
+
[subscriptions plugin](/platform/auth/plugins/subscriptions) — it already owns
|
|
260
|
+
tiers, the portal, renewals and cancellation.
|
|
261
|
+
- **Marketplaces.** Read `ctx.event.account` to route a connected account's
|
|
262
|
+
event; see [Stripe Connect](/platform/webhooks/inbound#stripe-connect).
|
|
263
|
+
|
|
264
|
+
## Next
|
|
265
|
+
|
|
266
|
+
- [The Stripe dev loop](/platform/payments/dev-loop) — run this locally before you ship it.
|
|
@@ -79,7 +79,7 @@ providers: {
|
|
|
79
79
|
}
|
|
80
80
|
```
|
|
81
81
|
|
|
82
|
-
That tells `/broadcast/v1/ws-ticket` (the broadcast surface tracks `contract.
|
|
82
|
+
That tells `/broadcast/v1/ws-ticket` (the broadcast surface tracks `contract.routes`, so `/broadcast/v2/ws-ticket` when that is `"v2"`) to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/platform/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).
|
|
83
83
|
|
|
84
84
|
### Namespace-backed tickets (per-matched-lane)
|
|
85
85
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:
|
|
4
4
|
|
|
5
|
-
- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this shared scope that something changed." The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. The `/broadcast/v1` version segment tracks `contract.
|
|
5
|
+
- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this shared scope that something changed." The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. The `/broadcast/v1` version segment tracks `contract.routes` — set it to `"v2"` and the same surface mounts at `/broadcast/v2` (no hidden v1 alias). `contract.version` selects the frame FORMAT, not the path: on v2 semantics (the default) frames are [CloudEvents 1.0](/platform/api-contract#contract-version-matrix) envelopes regardless of which prefix you serve them on. Documented on this page. For **typed, targeted "this changed — refresh" signals** fired from an action after commit (with optional per-recipient narrowing), see [Named invalidations](/platform/realtime/named-invalidations).
|
|
6
6
|
- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/platform/realtime/partyserver-rooms).
|
|
7
7
|
|
|
8
8
|
Both share the same auth model and ride on the same compiled worker; they solve different problems.
|
|
@@ -157,7 +157,7 @@ function PersonDetail({ personId }: { personId: string }) {
|
|
|
157
157
|
Under the hood `useView` uses a **subscribe-then-snapshot** flow so no change
|
|
158
158
|
slips through the gap between reading the surface and the socket going live:
|
|
159
159
|
|
|
160
|
-
1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` — `/broadcast/v2/ws-ticket`
|
|
160
|
+
1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` — `/broadcast/v2/ws-ticket` when `contract.routes` is `"v2"` — with
|
|
161
161
|
`{ view, rootId }`) — gated by exactly the same `read.access` + firewall
|
|
162
162
|
checks as the read endpoint — and opens a WebSocket scoped to
|
|
163
163
|
`view:<view>:<rootId>`.
|
|
@@ -125,7 +125,7 @@ Each `invalidate.<binding>.<variant>(payload)` call queues **one** after-commit
|
|
|
125
125
|
|
|
126
126
|
## The wire frame
|
|
127
127
|
|
|
128
|
-
Clients receive a broadcast frame on `/broadcast/v{n}` (the
|
|
128
|
+
Clients receive a broadcast frame on `/broadcast/v{n}` (the segment tracks `contract.routes`):
|
|
129
129
|
|
|
130
130
|
```jsonc
|
|
131
131
|
{
|
|
@@ -8,7 +8,7 @@ Open a WebSocket connection to the realtime worker:
|
|
|
8
8
|
|
|
9
9
|
```typescript
|
|
10
10
|
const ws = new WebSocket("wss://api.yourdomain.com/broadcast/v1/websocket");
|
|
11
|
-
// Note: /broadcast/v1 tracks contract.
|
|
11
|
+
// Note: /broadcast/v1 tracks contract.routes — use /broadcast/v2 when that is "v2".
|
|
12
12
|
```
|
|
13
13
|
|
|
14
14
|
## Authentication
|
|
@@ -82,10 +82,13 @@ onWebhookEvent("stripe:invoice.paid", async (ctx) => {
|
|
|
82
82
|
});
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
`data.object` is an open record. Cast it when you need inner-field typing
|
|
85
|
+
`data.object` is an open record. Cast it when you need inner-field typing — and
|
|
86
|
+
route the cast **through `unknown`**. `ctx.data` is a `Record<string, unknown>`,
|
|
87
|
+
which does not sufficiently overlap a Stripe resource interface, so the direct
|
|
88
|
+
one-step form is a `TS2352` error:
|
|
86
89
|
|
|
87
90
|
```typescript
|
|
88
|
-
const session = ctx.data as import("stripe").Stripe.Checkout.Session;
|
|
91
|
+
const session = ctx.data as unknown as import("stripe").Stripe.Checkout.Session;
|
|
89
92
|
```
|
|
90
93
|
|
|
91
94
|
**Execution order:**
|
|
@@ -377,8 +377,9 @@ For each feature, the compiler generates a routes file at `src/features/{name}/r
|
|
|
377
377
|
| `POST /:id/{action}` | Record-based actions defined |
|
|
378
378
|
| `POST /{action}` | Standalone actions defined |
|
|
379
379
|
|
|
380
|
-
Routes are mounted under `/api/v1/{feature}`
|
|
381
|
-
`/api/v2/{feature}` when `contract: {
|
|
380
|
+
Routes are mounted under `/api/v1/{feature}` by default, or
|
|
381
|
+
`/api/v2/{feature}` when `contract: { routes: "v2" }` is set. `contract.version`
|
|
382
|
+
selects semantics and leaves these paths alone.
|
|
382
383
|
|
|
383
384
|
## Migrations
|
|
384
385
|
|
|
@@ -105,7 +105,7 @@ interface ListResult {
|
|
|
105
105
|
The client is constructed once from the resolved `apiUrl` and provided via React
|
|
106
106
|
context (`ApiClientContext`), available throughout the component tree. It reads
|
|
107
107
|
the Better Auth session cookie and calls the standard REST endpoints
|
|
108
|
-
(`/api/v1/{table}`, or `/api/v2/…`
|
|
108
|
+
(`/api/v1/{table}`, or `/api/v2/…` when `contract.routes` is `"v2"`).
|
|
109
109
|
|
|
110
110
|
## Embedded Mode (Recommended)
|
|
111
111
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.64.
|
|
3
|
+
"version": "0.64.2",
|
|
4
4
|
"description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
|
|
5
5
|
"author": "Kardoe Incorporated <paul@kardoe.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -24,12 +24,14 @@ Lowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to m
|
|
|
24
24
|
|
|
25
25
|
Quickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.
|
|
26
26
|
|
|
27
|
-
> **
|
|
27
|
+
> **This JWT surface is opt-in by default**
|
|
28
28
|
>
|
|
29
|
-
>
|
|
30
|
-
> when `auth.jwt` is present. If it is omitted, generated output
|
|
31
|
-
> `/api/
|
|
32
|
-
>
|
|
29
|
+
> Contract v2 is the default since v0.64.0, and on it Quickback emits this custom
|
|
30
|
+
> JWT surface only when `auth.jwt` is present. If it is omitted, generated output
|
|
31
|
+
> has no generic `/api/v1/token` endpoint, no JWT middleware verify/mint
|
|
32
|
+
> fast-path, and no Quickback JWT imports. (`src/lib/jwt.ts` is still emitted when
|
|
33
|
+
> the project declares [`authz.scopes`](/define/scopes) — scope tokens are signed
|
|
34
|
+
> JWTs.) Pin `contract: { version: "v1" }` to emit it unconditionally. Generated `llms.txt` and RFC 8414 discovery metadata
|
|
33
35
|
> also omit Bearer-JWT instructions, token endpoints, and JWT scopes that do not
|
|
34
36
|
> exist. Better Auth cookie and signed session-token bearer authentication remain
|
|
35
37
|
> available.
|
|
@@ -499,12 +499,13 @@ A modern Quickback project runs on **one Cloudflare Worker** that serves multipl
|
|
|
499
499
|
|
|
500
500
|
When any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:
|
|
501
501
|
|
|
502
|
-
- `/api/v1/*` and `/auth/v1/*`
|
|
503
|
-
|
|
502
|
+
- `/api/v1/*` and `/auth/v1/*` by default, or `/api/v2/*` and `/auth/v2/*`
|
|
503
|
+
when `contract.routes` is `"v2"` (the URL axis — `contract.version` does
|
|
504
|
+
not move these)
|
|
504
505
|
- `/storage/*` — R2 file storage
|
|
505
506
|
- `/health`, `/openapi.json` — monitoring/discovery
|
|
506
507
|
- `/account/*`, `/cms/*` — bundled SPAs (when enabled)
|
|
507
|
-
- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.
|
|
508
|
+
- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.routes: 'v2'`), `/mcp` (MCP), etc.
|
|
508
509
|
|
|
509
510
|
The unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.
|
|
510
511
|
|
|
@@ -215,7 +215,7 @@ providers: {
|
|
|
215
215
|
}
|
|
216
216
|
```
|
|
217
217
|
|
|
218
|
-
> The broadcast surface mounts at `/broadcast/v1` by default and `/broadcast/v2` under `contract.
|
|
218
|
+
> The broadcast surface mounts at `/broadcast/v1` by default and `/broadcast/v2` under `contract.routes: "v2"`. It tracks the URL axis, not `contract.version`.
|
|
219
219
|
|
|
220
220
|
`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:
|
|
221
221
|
|
|
@@ -157,6 +157,58 @@ Inside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned — writ
|
|
|
157
157
|
A `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.
|
|
158
158
|
|
|
159
159
|
|
|
160
|
+
## Subscription tiers
|
|
161
|
+
|
|
162
|
+
When the [subscriptions plugin](/platform/auth/plugins/subscriptions) is enabled, every tier you declare becomes an ordinary role string — `pro` becomes `tier_pro` — and the auth middleware stamps it into the caller's roles alongside their organization roles. There is no new access key and no new syntax: tiers compose in `authz.roles` exactly like everything else on this page.
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
// quickback.config.ts
|
|
166
|
+
export default defineConfig({
|
|
167
|
+
// ...providers, with plugins: { subscriptions: { tiers: { free: {...}, pro: {...} } } }
|
|
168
|
+
authz: {
|
|
169
|
+
roles: {
|
|
170
|
+
// `tier_pro` is stamped by the middleware — you never declare it.
|
|
171
|
+
paid: { roles: ['tier_pro'] },
|
|
172
|
+
// Compose it like any other name:
|
|
173
|
+
paidStaff: { and: [{ roles: ['paid'] }, { roles: ['admin', 'owner'] }] },
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
// any feature
|
|
181
|
+
import { q, defineTable } from '@quickback/compiler';
|
|
182
|
+
|
|
183
|
+
export const reports = q.table('reports', {
|
|
184
|
+
id: q.id(),
|
|
185
|
+
title: q.text().required(),
|
|
186
|
+
organizationId: q.scope('organization'),
|
|
187
|
+
...q.audit(),
|
|
188
|
+
...q.softDelete(),
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
export default defineTable(reports, {
|
|
192
|
+
read: {
|
|
193
|
+
access: { roles: ['owner', 'admin', 'member'] },
|
|
194
|
+
views: {
|
|
195
|
+
// Pro and Enterprise subscribers; nobody else.
|
|
196
|
+
forecast: { fields: ['id', 'title'], access: { roles: ['paid'] } },
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
**`tier_pro` means "pro or better".** A granting subscription stamps its own tier *and every tier below it* in your declared order, so an Enterprise subscriber carries `['tier_enterprise', 'tier_pro', 'tier_free']`. Gate on the lowest tier that should get in and higher tiers follow automatically — there is no hierarchy to configure, because tier order is already the order you declared them in.
|
|
203
|
+
|
|
204
|
+
**A caller with no subscription gets no tier roles at all** — not even `tier_free`. The base tier describes what checkout sells, not what a signed-up user is; only an actual subscription row with a granting status stamps anything. So `roles: ['tier_free']` means "someone who holds a free-tier subscription", and "any logged-in user" is still `AUTHENTICATED`.
|
|
205
|
+
|
|
206
|
+
Tier names are reserved. Declaring `authz.roles.tier_pro` is a compile error — it would shadow the stamped role rather than gate on it — and so is a tier whose derived name collides with a pseudo-role, a provider role, or an `auth.roleHierarchy` entry. Give the gate its own name, as `paid` does above.
|
|
207
|
+
|
|
208
|
+
Two independent bounds decide whether a subscription grants: its **status** (only `active` and `trialing` do) and its **expiry**. A row whose `expiresAt` passed more than 48 hours ago stops granting whatever its status claims — that grace window absorbs the normal renewal lag, while still bounding a row whose status froze because a webhook never arrived. A row with no `expiresAt` at all (admin-created, no Stripe period) keeps granting.
|
|
209
|
+
|
|
210
|
+
A downgrade is immediate on session auth. On a JWT it lasts until the token expires — one `auth.jwt.expiresIn` for a plain bearer, up to 15 minutes plus one TTL for a scope-bearing one, and `expiresIn` has no upper bound. For which statuses grant, which transports carry tier roles, and the full staleness picture, see [Entitlements](/platform/auth/plugins/subscriptions#entitlements-gating-access-on-tier).
|
|
211
|
+
|
|
160
212
|
## Outgrown this?
|
|
161
213
|
|
|
162
214
|
If the answer depends on a row in one of *your* domain tables ("is this caller a
|