@quickback-dev/cli 0.64.1 → 0.65.0
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/action-harvest.d.ts.map +1 -1
- package/dist/lib/action-harvest.js +6 -1
- package/dist/lib/action-harvest.js.map +1 -1
- package/dist/lib/action-harvest.test.js +19 -0
- package/dist/lib/action-harvest.test.js.map +1 -1
- package/dist/lib/compiler-stubs.d.ts +10 -0
- package/dist/lib/compiler-stubs.d.ts.map +1 -1
- package/dist/lib/compiler-stubs.js +16 -0
- package/dist/lib/compiler-stubs.js.map +1 -1
- package/dist/lib/file-writer.js +23 -0
- package/dist/lib/file-writer.js.map +1 -1
- package/dist/lib/file-writer.test.js +25 -0
- package/dist/lib/file-writer.test.js.map +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/api/actions.md +6 -20
- package/dist/skill/docs/changelog/index.md +23 -2
- package/dist/skill/docs/configure/bindings.md +1 -1
- package/dist/skill/docs/configure/domains.md +4 -2
- package/dist/skill/docs/configure/variables.md +2 -2
- package/dist/skill/docs/define/actions/defining.md +12 -0
- package/dist/skill/docs/define/authz-roles.md +52 -0
- package/dist/skill/docs/platform/auth/plugins/aws-ses.md +6 -18
- package/dist/skill/docs/platform/auth/plugins/aws-sns.md +4 -4
- package/dist/skill/docs/platform/auth/plugins/index.md +21 -1
- 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/index.md +2 -1
- package/dist/skill/docs/platform/realtime/using-realtime.md +7 -5
- package/dist/skill/docs/platform/storage/r2.md +12 -0
- package/dist/skill/docs/platform/webhooks/inbound.md +5 -2
- package/dist/skill/docs/start/template-cloudflare.md +1 -1
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +6 -20
- package/src/skill/docs/changelog/index.md +23 -2
- package/src/skill/docs/configure/bindings.md +1 -1
- package/src/skill/docs/configure/domains.md +4 -2
- package/src/skill/docs/configure/variables.md +2 -2
- package/src/skill/docs/define/actions/defining.md +12 -0
- package/src/skill/docs/define/authz-roles.md +52 -0
- package/src/skill/docs/platform/auth/plugins/aws-ses.md +6 -18
- package/src/skill/docs/platform/auth/plugins/aws-sns.md +4 -4
- package/src/skill/docs/platform/auth/plugins/index.md +21 -1
- 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/index.md +2 -1
- package/src/skill/docs/platform/realtime/using-realtime.md +7 -5
- package/src/skill/docs/platform/storage/r2.md +12 -0
- package/src/skill/docs/platform/webhooks/inbound.md +5 -2
- package/src/skill/docs/start/template-cloudflare.md +1 -1
|
@@ -145,6 +145,18 @@ evaluated for real, so a derivation in that file happens to work. Whether it
|
|
|
145
145
|
works depends on unrelated content in the table file — declare the shape
|
|
146
146
|
instead.
|
|
147
147
|
|
|
148
|
+
**`output` describes the success path only.** Error responses never pass
|
|
149
|
+
through it: throw
|
|
150
|
+
[`ActionError`](/api/actions#error-handling) and the route returns
|
|
151
|
+
`{ error, code, details }` with your status code — that error envelope is part
|
|
152
|
+
of the generated contract already, so do not fold error variants into
|
|
153
|
+
`output`. The one exception is an endpoint whose *success* body is
|
|
154
|
+
deliberately a status report (a webhook receiver acknowledging
|
|
155
|
+
`{ received: false, reason }`, say) — that is a union of success shapes, and
|
|
156
|
+
declaring it as `z.discriminatedUnion(...)` in `output` is correct. Do not
|
|
157
|
+
return an error object (or a `Response`) from `execute` to signal failure —
|
|
158
|
+
see [Error Handling](/api/actions#error-handling) for what actually happens.
|
|
159
|
+
|
|
148
160
|
Parameterized standalone paths use Hono's `:param` syntax in authored source,
|
|
149
161
|
for example `path: "/events/:eventId/check-in"`. The harvest planner converts
|
|
150
162
|
those segments to the OpenAPI `{param}` form before applying the schema, so
|
|
@@ -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
|
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
# AWS SES Plugin
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Quickback's AWS SES plugin sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).
|
|
4
4
|
|
|
5
5
|
> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/configure#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
npm install @quickback-dev/better-auth-aws-ses
|
|
11
|
-
```
|
|
9
|
+
None. The compiler bundles the plugin source and emits it into your project at `src/plugins/aws-ses/` — it is **not** an npm dependency, and upgrades arrive by recompiling, not by `npm update`.
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
The plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.
|
|
14
12
|
|
|
15
13
|
## Email Types
|
|
16
14
|
|
|
@@ -95,16 +93,16 @@ Recognized keys:
|
|
|
95
93
|
| `'forget-password'` | Password reset request — and admin-bootstrap if `welcome` isn't set |
|
|
96
94
|
| `'welcome'` | **Synthetic** — routed when `forget-password` fires for a user with no credential row yet (the admin-plugin → bootstrap flow). Without it, those sends fall through to `forget-password`. |
|
|
97
95
|
|
|
98
|
-
Missing keys fall through to the built-in defaults from
|
|
96
|
+
Missing keys fall through to the built-in defaults from the vendored plugin (`src/plugins/aws-ses/`). The compiler stages each referenced file into `src/email-templates/<name>.ts` and wires the default import in `src/lib/auth.ts` — the template function is called inline from `sendVerificationOTP`, so it has access to whatever modules the file imports.
|
|
99
97
|
|
|
100
98
|
> **Provider scope.** Overrides are only honored when `email.provider: 'aws-ses'`. The Cloudflare Email path uses the helper's own template pipeline and ignores `plugins.emailOtp.templates`.
|
|
101
99
|
|
|
102
100
|
## Configuration
|
|
103
101
|
|
|
104
|
-
|
|
102
|
+
The compiler wires the plugin into `src/lib/auth.ts` automatically. The generated `getSESConfig(env)` maps environment to the vendored plugin's options:
|
|
105
103
|
|
|
106
104
|
```typescript
|
|
107
|
-
import { awsSESPlugin } from "
|
|
105
|
+
import { awsSESPlugin } from "../plugins/aws-ses";
|
|
108
106
|
|
|
109
107
|
const auth = betterAuth({
|
|
110
108
|
plugins: [
|
|
@@ -122,16 +120,6 @@ const auth = betterAuth({
|
|
|
122
120
|
});
|
|
123
121
|
```
|
|
124
122
|
|
|
125
|
-
### Client Plugin
|
|
126
|
-
|
|
127
|
-
```typescript
|
|
128
|
-
import { awsSESClientPlugin } from "@quickback-dev/better-auth-aws-ses/client";
|
|
129
|
-
|
|
130
|
-
const authClient = createAuthClient({
|
|
131
|
-
plugins: [awsSESClientPlugin()],
|
|
132
|
-
});
|
|
133
|
-
```
|
|
134
|
-
|
|
135
123
|
## Required Environment Variables
|
|
136
124
|
|
|
137
125
|
| Variable | Description |
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# AWS SNS Plugin (SMS OTP)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The AWS SNS transport is what Quickback wires into Better Auth's built-in `phoneNumber` plugin when you opt in to SMS OTP. The compiler emits its source into your project at `src/plugins/aws-sns/` — it is not an npm dependency. It signs SNS `Publish` requests with AWS Signature V4 using the Web Crypto API — zero AWS SDK dependency, runs on Cloudflare Workers.
|
|
4
4
|
|
|
5
5
|
> **Why SMS?** Corporate email gateways aggressively filter or rewrite transactional auth emails (link previews, click-tracking, MITM scanners). For some user bases SMS is the most reliable channel for a six-digit code that has to land in under a minute.
|
|
6
6
|
|
|
7
7
|
## What it provides
|
|
8
8
|
|
|
9
|
-
The
|
|
9
|
+
The transport itself does **not** register a Better Auth plugin. Better Auth's builtin [`phoneNumber`](https://www.better-auth.com/docs/plugins/phone-number) plugin owns the endpoints (`/auth/v1/phone-number/send-otp`, `/verify`, `/sign-in/phone-number`, password reset). This package fills the `sendOTP` / `sendPasswordResetOTP` callbacks and the `phoneNumberValidator` hook.
|
|
10
10
|
|
|
11
11
|
| Export | Purpose |
|
|
12
12
|
|--------|---------|
|
|
@@ -40,7 +40,7 @@ export default defineConfig({
|
|
|
40
40
|
|
|
41
41
|
The compiler:
|
|
42
42
|
|
|
43
|
-
1.
|
|
43
|
+
1. Emits the plugin source into `src/plugins/aws-sns/` — vendored, not an npm dependency; upgrades arrive by recompiling.
|
|
44
44
|
2. Emits a `getSNSConfig(env)` helper in `src/lib/auth.ts`.
|
|
45
45
|
3. Wires the `phoneNumber` plugin with `sendOTP`, `sendPasswordResetOTP`, and `phoneNumberValidator: isValidE164`.
|
|
46
46
|
4. Drops `AWS_SNS_REGION` / `APP_NAME` (and `SMS_SENDER_ID` / `SMS_TYPE` when set) into `[vars]` in `wrangler.toml`.
|
|
@@ -116,7 +116,7 @@ Your <AppName> code is 123456. Expires in 5 min. Don't share it.
|
|
|
116
116
|
After compile, check the generated `src/lib/auth.ts`:
|
|
117
117
|
|
|
118
118
|
```ts
|
|
119
|
-
import { sendSMSWithSNS, smsTemplates, isValidE164 } from "
|
|
119
|
+
import { sendSMSWithSNS, smsTemplates, isValidE164 } from "../plugins/aws-sns";
|
|
120
120
|
|
|
121
121
|
function getSNSConfig(env: CloudflareBindings | undefined): SNSConfig { /* ... */ }
|
|
122
122
|
|
|
@@ -76,7 +76,7 @@ auth: defineAuth("better-auth", {
|
|
|
76
76
|
|
|
77
77
|
### SMS OTP (with AWS SNS)
|
|
78
78
|
|
|
79
|
-
When `phoneNumber` is enabled, the compiler wires Better Auth's built-in `phoneNumber` plugin to AWS SNS for SMS delivery via [
|
|
79
|
+
When `phoneNumber` is enabled, the compiler wires Better Auth's built-in `phoneNumber` plugin to AWS SNS for SMS delivery via the vendored [AWS SNS transport](/platform/auth/plugins/aws-sns) (emitted into `src/plugins/aws-sns/`, not installed from npm). The plugin adds `phoneNumber` / `phoneNumberVerified` columns to the user table, handles OTP generation + storage + verify-attempt limits, and exposes endpoints for phone-only sign-in, phone+password sign-in, and password reset via SMS.
|
|
80
80
|
|
|
81
81
|
**Enable in config:**
|
|
82
82
|
|
|
@@ -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`.
|