@quickback-dev/cli 0.40.0 → 0.46.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.
Files changed (97) hide show
  1. package/dist/commands/claude.d.ts.map +1 -1
  2. package/dist/commands/claude.js +8 -0
  3. package/dist/commands/claude.js.map +1 -1
  4. package/dist/commands/compile.d.ts.map +1 -1
  5. package/dist/commands/compile.js +13 -2
  6. package/dist/commands/compile.js.map +1 -1
  7. package/dist/commands/compile.test.js +26 -21
  8. package/dist/commands/compile.test.js.map +1 -1
  9. package/dist/commands/create.js +6 -9
  10. package/dist/commands/create.js.map +1 -1
  11. package/dist/commands/login.d.ts.map +1 -1
  12. package/dist/commands/login.js +0 -9
  13. package/dist/commands/login.js.map +1 -1
  14. package/dist/commands/start.d.ts.map +1 -1
  15. package/dist/commands/start.js +6 -7
  16. package/dist/commands/start.js.map +1 -1
  17. package/dist/commands/whoami.d.ts.map +1 -1
  18. package/dist/commands/whoami.js +0 -4
  19. package/dist/commands/whoami.js.map +1 -1
  20. package/dist/docs/content.d.ts.map +1 -1
  21. package/dist/docs/content.js +23 -33
  22. package/dist/docs/content.js.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/lib/api-client.d.ts +0 -12
  25. package/dist/lib/api-client.d.ts.map +1 -1
  26. package/dist/lib/api-client.js +0 -10
  27. package/dist/lib/api-client.js.map +1 -1
  28. package/dist/lib/api-client.test.js +13 -8
  29. package/dist/lib/api-client.test.js.map +1 -1
  30. package/dist/lib/auth.d.ts +0 -1
  31. package/dist/lib/auth.d.ts.map +1 -1
  32. package/dist/lib/auth.js.map +1 -1
  33. package/dist/lib/compiler-stubs.d.ts +12 -0
  34. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  35. package/dist/lib/compiler-stubs.js +18 -0
  36. package/dist/lib/compiler-stubs.js.map +1 -1
  37. package/dist/lib/file-loader.d.ts +14 -0
  38. package/dist/lib/file-loader.d.ts.map +1 -1
  39. package/dist/lib/file-loader.js +63 -9
  40. package/dist/lib/file-loader.js.map +1 -1
  41. package/dist/skill/SKILL.md +76 -6
  42. package/dist/skill/docs/changelog.md +253 -0
  43. package/dist/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  44. package/dist/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  45. package/dist/skill/docs/compiler/config/agents.md +49 -1
  46. package/dist/skill/docs/compiler/config/auth.md +20 -5
  47. package/dist/skill/docs/compiler/config/security.md +46 -0
  48. package/dist/skill/docs/compiler/definitions/access.md +1 -1
  49. package/dist/skill/docs/compiler/definitions/actions.md +46 -4
  50. package/dist/skill/docs/compiler/definitions/scopes.md +11 -3
  51. package/dist/skill/docs/compiler/getting-started/full-example.md +5 -3
  52. package/dist/skill/docs/compiler/getting-started/index.md +7 -7
  53. package/dist/skill/docs/compiler/getting-started/patterns.md +39 -5
  54. package/dist/skill/docs/compiler/getting-started/template-blog.md +65 -44
  55. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  56. package/dist/skill/docs/compiler/getting-started/template-empty.md +7 -1
  57. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  59. package/dist/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  60. package/dist/skill/docs/stack/account-ui/hooks.md +24 -1
  61. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  62. package/dist/skill/docs/stack/auth/plugins/index.md +71 -28
  63. package/dist/skill/docs/stack/storage/r2.md +8 -6
  64. package/dist/skill/docs/stack/storage/using-r2.md +58 -33
  65. package/dist/templates/registry.d.ts +0 -12
  66. package/dist/templates/registry.d.ts.map +1 -1
  67. package/dist/templates/registry.js +0 -42
  68. package/dist/templates/registry.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/skill/SKILL.md +76 -6
  71. package/src/skill/docs/changelog.md +253 -0
  72. package/src/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  73. package/src/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  74. package/src/skill/docs/compiler/config/agents.md +49 -1
  75. package/src/skill/docs/compiler/config/auth.md +20 -5
  76. package/src/skill/docs/compiler/config/security.md +46 -0
  77. package/src/skill/docs/compiler/definitions/access.md +1 -1
  78. package/src/skill/docs/compiler/definitions/actions.md +46 -4
  79. package/src/skill/docs/compiler/definitions/scopes.md +11 -3
  80. package/src/skill/docs/compiler/getting-started/full-example.md +5 -3
  81. package/src/skill/docs/compiler/getting-started/index.md +7 -7
  82. package/src/skill/docs/compiler/getting-started/patterns.md +39 -5
  83. package/src/skill/docs/compiler/getting-started/template-blog.md +65 -44
  84. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  85. package/src/skill/docs/compiler/getting-started/template-empty.md +7 -1
  86. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  88. package/src/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  89. package/src/skill/docs/stack/account-ui/hooks.md +24 -1
  90. package/src/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  91. package/src/skill/docs/stack/auth/plugins/index.md +71 -28
  92. package/src/skill/docs/stack/storage/r2.md +8 -6
  93. package/src/skill/docs/stack/storage/using-r2.md +58 -33
  94. package/dist/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  95. package/dist/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
  96. package/src/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  97. package/src/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
@@ -204,3 +204,26 @@ Or enable the in-project browser via the [`docs` config option](#interactive-api
204
204
  }
205
205
  }
206
206
  ```
207
+
208
+ ## Operations manifest
209
+
210
+ Alongside the spec, every compile writes `reports/operations.manifest.json` — a
211
+ stable, machine-readable index of the full route surface (resource, action,
212
+ view, and auth routes):
213
+
214
+ ```json
215
+ [
216
+ { "operationId": "listCustomers", "method": "GET", "path": "/api/v1/customers", "auth": "session", "feature": "customers", "kind": "crud" }
217
+ ]
218
+ ```
219
+
220
+ The manifest is a public contract: entries are sorted by `operationId`, carry
221
+ no timestamps, and the shape is extend-only — new fields may be added, existing
222
+ ones won't change meaning. `operationId`s are stable across compiles for the
223
+ same configuration, which makes the manifest the recommended integration point
224
+ for agent/MCP tooling, route inventories, and diff-based change review.
225
+
226
+ A sibling artifact, `reports/conformance.manifest.json`, enumerates the
227
+ expected authorization outcome for every route × principal class (derived from
228
+ the same compiler model that emits the enforcement code). The compiler's own CI
229
+ executes it against a running build on every change.
@@ -1,6 +1,6 @@
1
1
  # Passwordless Authentication
2
2
 
3
- Account UI supports passwordless authentication via email OTP and magic links.
3
+ Account UI supports passwordless authentication via email OTP.
4
4
 
5
5
  ## Email OTP
6
6
 
@@ -10,17 +10,11 @@ When `ENABLE_EMAIL_OTP=true`:
10
10
  - A one-time password is sent via email
11
11
  - User enters the OTP code to authenticate
12
12
 
13
- ## Magic Links
13
+ The sign-in email contains the six-digit code only — no magic-link companion. Mail-client URL prefetching burns single-use links, so a code the user types is the reliable path.
14
14
 
15
- When `ENABLE_MAGIC_LINK=true`:
15
+ ## What about magic links?
16
16
 
17
- - Users enter their email address
18
- - A login link is sent via email
19
- - Clicking the link authenticates the user
20
-
21
- ## Combo Auth
22
-
23
- When both are enabled, Account UI uses the `@quickback-dev/better-auth-combo-auth` plugin to combine them into a single flow — the email contains both a clickable link and a code.
17
+ Account UI does not offer a magic-link sign-in flow. The `magicLink` Better Auth plugin is still available at the API level (see [Auth Plugins](/stack/auth/plugins#magic-links)) for apps that build their own sign-in UI, but the bundled Account SPA is OTP-only by design.
24
18
 
25
19
  ## Related
26
20
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Quickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.
4
4
 
5
- The classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.
5
+ The classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `403 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.
6
6
 
7
7
  ## Folder layout
8
8
 
@@ -25,11 +25,34 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
25
25
  | `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |
26
26
  | `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
27
27
  | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
28
+ | `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
28
29
 
29
30
  `after-admin-user-create.ts` is a **virtual event** — it wires into the same Better Auth `user.create.after` slot as the generic `after-user-create.ts`, but the compiler wraps the call in a runtime filter on the BA context path so it only fires when the row was created via the admin plugin's `POST /admin/create-user` endpoint. Use it for first-time-user provisioning (welcome email, default org assignment) without inspecting `_baCtx?.context?.path` by hand. The generic `after-user-create.ts` still runs for every signup, including admin-created ones.
30
31
 
31
32
  Filenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).
32
33
 
34
+ ## OAuth context resolver
35
+
36
+ First-class MCP OAuth validates the access token and live Better Auth session
37
+ before calling `quickback/hooks/resolve-oauth-context.ts`. Use this trusted
38
+ server hook when tenant selection cannot be derived solely from the session's
39
+ active organization.
40
+
41
+ ```ts title="quickback/hooks/resolve-oauth-context.ts"
42
+ export default async ({ token, session, user, context }, { authDb, authSchema, env }) => {
43
+ return {
44
+ activeOrgId: session.activeOrganizationId ?? null,
45
+ activeTeamId: session.activeTeamId ?? null,
46
+ tenantId: session.activeOrganizationId ?? null,
47
+ roles: context.roles,
48
+ };
49
+ };
50
+ ```
51
+
52
+ The returned object is merged into the standard `AppContext`. The compiler
53
+ always preserves the validated `authenticated`, `userId`, and `user` fields,
54
+ so this hook cannot replace the OAuth identity.
55
+
33
56
  ## ctx shape
34
57
 
35
58
  Every hook receives `(entity, ctx)`:
@@ -24,13 +24,8 @@ The plugin handles 8 email types:
24
24
  | `/ses/send-otp` | One-time password code |
25
25
  | `/ses/send-welcome` | Post-signup welcome email |
26
26
  | `/ses/send-organization-invitation` | Team/org invite with role |
27
- | Combo auth | Magic link + OTP in a single email |
28
27
  | Delete account | Account deletion confirmation |
29
28
 
30
- ### Combo Auth Mode
31
-
32
- When `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.
33
-
34
29
  ## AWS Signature V4
35
30
 
36
31
  The plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.
@@ -122,7 +117,6 @@ const auth = betterAuth({
122
117
  replyTo: env.EMAIL_REPLY_TO,
123
118
  appName: env.APP_NAME || "My App",
124
119
  appUrl: env.APP_URL,
125
- useComboAuthEmail: true, // Optional: combine magic link + OTP
126
120
  }),
127
121
  ],
128
122
  });
@@ -183,5 +177,4 @@ awsSESPlugin({
183
177
 
184
178
  ## See Also
185
179
 
186
- - [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication
187
180
  - [Auth Configuration](/compiler/config/providers) — Configuring auth plugins
@@ -6,7 +6,7 @@ Quickback ships with a curated set of Better Auth plugins and helper wiring so y
6
6
 
7
7
  ### Email OTP (with AWS SES)
8
8
 
9
- Quickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).
9
+ Quickback wires the Better Auth Email OTP flow to your email provider. When `emailOtp` is enabled, the compiler emits an OTP-only sign-in email — a six-digit code, no magic-link companion.
10
10
 
11
11
  **Enable in config:**
12
12
 
@@ -46,23 +46,32 @@ Use this to show UI warnings when SES isn't configured.
46
46
  - `GET /api/v1/system/email-status`
47
47
  - Response: `{ "emailConfigured": true|false }`
48
48
 
49
- ### Upgrade Anonymous
49
+ **Disabling sign-up via OTP:**
50
50
 
51
- Adds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.
51
+ By default the Email OTP plugin **auto-creates an account** when a code is
52
+ verified for an unknown email — verifying an OTP doubles as registration. This
53
+ is a separate code path from `emailAndPassword.disableSignUp` (which only gates
54
+ `POST /auth/v1/sign-up/email`), so disabling password sign-up alone does *not*
55
+ close the OTP path.
52
56
 
53
- **Enable in config:**
57
+ To make OTP sign-in only (existing users can sign in; unknown emails are
58
+ rejected instead of registered), use the object form:
54
59
 
55
60
  ```ts
56
61
  auth: defineAuth("better-auth", {
57
62
  emailAndPassword: { enabled: true },
58
- plugins: ["anonymous", "upgradeAnonymous"],
63
+ plugins: {
64
+ emailOtp: { disableSignUp: true },
65
+ },
59
66
  }),
60
67
  ```
61
68
 
62
- **Endpoint:**
63
- - `POST /auth/v1/upgrade-anonymous`
69
+ > `emailOtp.disableSignUp` **inherits the global signup gate**: when
70
+ > `account.auth.signup: false` (i.e. `emailAndPassword.disableSignUp: true`) is
71
+ > set, the OTP plugin is gated automatically so it can't be used to bypass it. Set
72
+ > `emailOtp: { disableSignUp: false }` explicitly to opt the OTP path back open
73
+ > while password sign-up stays closed.
64
74
 
65
- **Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.
66
75
 
67
76
  ### SMS OTP (with AWS SNS)
68
77
 
@@ -129,6 +138,25 @@ auth: defineAuth("better-auth", {
129
138
  - `POST /auth/v1/magic-link/send` - Send magic link email
130
139
  - `GET /auth/v1/magic-link/verify` - Verify magic link token
131
140
 
141
+ **Disabling sign-up via magic link:**
142
+
143
+ Like Email OTP, the magic-link plugin **auto-creates an account** when a link is
144
+ verified for an unknown email, on a code path independent of
145
+ `emailAndPassword.disableSignUp`. Gate it with the object form:
146
+
147
+ ```ts
148
+ auth: defineAuth("better-auth", {
149
+ emailAndPassword: { enabled: true },
150
+ plugins: {
151
+ magicLink: { disableSignUp: true }, // sign-in only; unknown emails rejected
152
+ },
153
+ }),
154
+ ```
155
+
156
+ It inherits the global signup gate the same way `emailOtp.disableSignUp` does:
157
+ `account.auth.signup: false` gates the magic-link path automatically; set
158
+ `magicLink: { disableSignUp: false }` to opt it back open.
159
+
132
160
  **Email customization:**
133
161
 
134
162
  Magic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:
@@ -285,13 +313,36 @@ Turns your Quickback worker into a standards-compliant OAuth 2.1 + OIDC authoriz
285
313
 
286
314
  ```ts
287
315
  auth: defineAuth("better-auth", {
288
- plugins: ["oauthProvider"],
316
+ oauth: {
317
+ enabled: true,
318
+ issuerUrl: {
319
+ env: "OAUTH_ISSUER_URL",
320
+ fallback: "http://localhost:8787/auth/v1",
321
+ },
322
+ loginPage: {
323
+ env: "OAUTH_LOGIN_URL",
324
+ fallback: "http://localhost:8787/account/login",
325
+ },
326
+ consentPage: {
327
+ env: "OAUTH_CONSENT_URL",
328
+ fallback: "http://localhost:8787/account/consent",
329
+ },
330
+ scopes: ["openid", "profile", "email", "offline_access"],
331
+ audiences: [
332
+ { env: "OAUTH_API_AUDIENCE", fallback: "http://localhost:8787" },
333
+ { env: "OAUTH_MCP_AUDIENCE", fallback: "http://localhost:8787/mcp" },
334
+ ],
335
+ allowDynamicClientRegistration: true,
336
+ },
289
337
  }),
290
338
  ```
291
339
 
292
- The compiler auto-includes Better Auth's `jwt` plugin alongside `oauthProvider` — `@better-auth/oauth-provider` delegates access-token signing to it, and schema generation fails without it.
340
+ The compiler auto-includes Better Auth's `oauthProvider`, `jwt`, and bearer
341
+ plugins, protects `POST /mcp`, emits RFC 8414 and RFC 9728 discovery, and
342
+ accepts the provider's JWKS-signed access tokens in the standard Quickback
343
+ auth middleware.
293
344
 
294
- **Custom configuration** (object form):
345
+ The legacy plugin object remains available for provider-specific options:
295
346
 
296
347
  ```ts
297
348
  auth: defineAuth("better-auth", {
@@ -312,6 +363,7 @@ auth: defineAuth("better-auth", {
312
363
 
313
364
  Discovery (public, no auth):
314
365
  - `GET /.well-known/oauth-authorization-server` — RFC 8414 metadata
366
+ - `GET /.well-known/oauth-authorization-server/auth/v1` — RFC 8414 path-insert discovery
315
367
  - `GET /.well-known/oauth-protected-resource` — MCP resource metadata
316
368
  - `GET /.well-known/openid-configuration` — OIDC discovery
317
369
 
@@ -337,25 +389,16 @@ Consent management:
337
389
 
338
390
  The compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.
339
391
 
340
- **Verifying tokens in your own Workers / route handlers:**
392
+ **Token and tenant context:**
341
393
 
342
- Issued tokens are JWTs by default — verify them locally without a DB hit:
394
+ Generated middleware validates the provider JWKS, canonical issuer, configured
395
+ audience, expiration, subject, and backing Better Auth session. It then builds
396
+ the same `AppContext` used by session and Quickback JWT authentication.
397
+ Organization membership and role hierarchy are resolved automatically.
343
398
 
344
- ```ts
345
- import { createAuthClient } from "better-auth/client";
346
- import { oauthProviderResourceClient } from "@better-auth/oauth-provider/resource-client";
347
- import { auth } from "./auth";
348
-
349
- const serverClient = createAuthClient({
350
- plugins: [oauthProviderResourceClient(auth)],
351
- });
352
-
353
- const token = req.headers.get("authorization")?.replace("Bearer ", "");
354
- const payload = await serverClient.verifyAccessToken(token, {
355
- verifyOptions: { issuer: env.BETTER_AUTH_URL, audience: env.BETTER_AUTH_URL },
356
- });
357
- // payload.sub → userId, payload.scope → granted scopes
358
- ```
399
+ For application-specific tenant selection, add
400
+ `quickback/hooks/resolve-oauth-context.ts`; see
401
+ [Auth Hooks](/stack/account-ui/hooks#oauth-context-resolver).
359
402
 
360
403
  **Why this and not the deprecated `mcp` plugin?**
361
404
 
@@ -355,12 +355,14 @@ After compiling:
355
355
 
356
356
  | Option | Type | Default | Description |
357
357
  |--------|------|---------|-------------|
358
- | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |
359
- | `bucketName` | `string` | Required | R2 bucket name |
360
- | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |
361
- | `maxFileSize` | `number` | 10MB | Max upload size in bytes |
362
- | `allowedTypes` | `string[]` | Images only | Allowed MIME types |
363
- | `publicDomain` | `string` | - | Custom domain for files worker |
358
+ | `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |
359
+ | `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |
360
+ | `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |
361
+ | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
362
+ | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |
363
+ | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
364
+ | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
365
+ | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
364
366
 
365
367
  ## Security Model
366
368
 
@@ -2,53 +2,78 @@
2
2
 
3
3
  Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.
4
4
 
5
- ## Upload Flow
5
+ By default `defineFileStorage("cloudflare-r2")` is **presign-only**: you get the
6
+ `ctx.storage` signer and nothing else. The `/storage/v1/*` endpoints shown
7
+ further down only exist in the [managed subsystem](/stack/storage/r2#two-modes)
8
+ (`managed: true`).
9
+
10
+ ## Upload Flow (default — `ctx.storage`)
11
+
12
+ Write a normal `defineAction` that signs a presigned URL and stores the key in
13
+ **your own table**. Bytes go directly to R2 — the Worker only signs.
14
+
15
+ ```ts
16
+ export default defineAction({
17
+ path: "/media/sign-upload",
18
+ method: "POST",
19
+ input: z.object({ filename: z.string(), contentType: z.string() }),
20
+ access: { roles: ["member"] },
21
+ async execute({ input, ctx, db, storage }) {
22
+ const key = `org/${ctx.activeOrgId}/${crypto.randomUUID()}-${input.filename}`;
23
+ const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });
24
+ await db.insert(media).values({ key /* … */ });
25
+ return { uploadUrl: upload.url, key, headers: upload.headers };
26
+ },
27
+ });
28
+ ```
29
+
30
+ ```bash
31
+ # 1. Ask your action for a signed URL (your auth/roles run here)
32
+ curl -X POST https://api.example.com/api/v1/media/sign-upload \
33
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
34
+ -d '{ "filename": "report.pdf", "contentType": "application/pdf" }'
35
+ # → { "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...", "key": "...", "headers": { "Content-Type": "application/pdf" } }
36
+
37
+ # 2. Upload the bytes straight to R2 (replay the returned headers)
38
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
39
+ ```
40
+
41
+ `storage.signPutUrl(key, { contentType?, expiresIn?, bucket? })` returns
42
+ `{ url, method, headers, key, expiresAt }`; `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })`
43
+ returns a presigned GET URL. Pass `bucket` to target a bucket other than the
44
+ configured default.
45
+
46
+ Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
47
+ and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
6
48
 
7
- The generated API provides a two-step **presigned** upload — the file bytes go
8
- directly to R2 and never stream through your Worker:
49
+ ## Upload Flow (managed mode — `/storage/v1/*`)
9
50
 
10
- 1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the
11
- Worker runs auth + bucket + role checks and returns a time-limited URL
12
- 2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)
13
- 3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag
51
+ With `managed: true`, the generated API also exposes turnkey presigned
52
+ endpoints backed by the FILES_DB metadata system:
14
53
 
15
54
  ```bash
16
55
  # 1. Request a presigned upload URL
17
56
  curl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \
18
- -H "Authorization: Bearer <token>" \
19
- -H "Content-Type: application/json" \
57
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
20
58
  -d '{ "contentType": "application/pdf", "size": 248000 }'
59
+ # → { "id": "obj_abc", "key": "...", "uploadUrl": "...", "headers": {...}, "expiresAt": "..." }
60
+
61
+ # 2. Upload directly to R2
62
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
21
63
 
22
- # Response:
23
- # {
24
- # "id": "obj_abc123",
25
- # "key": "org_abc/documents/report.pdf",
26
- # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
27
- # "method": "PUT",
28
- # "headers": { "Content-Type": "application/pdf" },
29
- # "expiresAt": "2026-06-02T12:10:00.000Z"
30
- # }
31
-
32
- # 2. Upload directly to R2 using the presigned URL (replay the returned headers)
33
- curl -X PUT "<uploadUrl>" \
34
- -H "Content-Type: application/pdf" \
35
- --data-binary @report.pdf
36
-
37
- # 3. Confirm the upload
64
+ # 3. Confirm (reconciles size + etag)
38
65
  curl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \
39
66
  -H "Authorization: Bearer <token>"
40
67
  ```
41
68
 
42
- Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
43
- and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
44
-
45
- For uploads that should land in **your own table** (with your own access rules),
46
- sign the URL from inside a `defineAction` via `ctx.storage` — see
47
- [Signing from your own action](/stack/storage/r2#signing-from-your-own-action).
48
-
49
69
  ## Download Flow
50
70
 
51
- Files are served through your Worker with security checks applied:
71
+ In **presign-only** mode, mint a short-lived download URL with
72
+ `storage.signGetUrl(key, { downloadFilename })` from your action and hand it to
73
+ the client — the bytes come straight from R2.
74
+
75
+ In **managed** mode, files are also served through the worker with security
76
+ checks applied:
52
77
 
53
78
  ```bash
54
79
  # Download a file (auth + firewall enforced)
@@ -1,74 +0,0 @@
1
- # Combo Auth Plugin
2
-
3
- `@quickback-dev/better-auth-combo-auth` provides a combined authentication flow that sends both a magic link and an OTP code in a single email. Users can click the link (one-click) or enter the 6-digit OTP code — whichever is more convenient.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install @quickback-dev/better-auth-combo-auth
9
- ```
10
-
11
- ## Server Setup
12
-
13
- Add the plugin to your Better Auth configuration:
14
-
15
- ```typescript
16
- import { betterAuth } from "better-auth";
17
- import { comboAuth } from "@quickback-dev/better-auth-combo-auth";
18
-
19
- export const auth = betterAuth({
20
- plugins: [
21
- comboAuth({
22
- sendComboAuth: async ({ email, otp, url }) => {
23
- // Send email with both the magic link (url) and OTP code (otp)
24
- await sendEmail({
25
- to: email,
26
- subject: "Sign in to My App",
27
- html: `
28
- <p>Click the link below to sign in:</p>
29
- <a href="${url}">Sign in to My App</a>
30
- <p>Or enter this code: <strong>${otp}</strong></p>
31
- `,
32
- });
33
- },
34
- }),
35
- ],
36
- });
37
- ```
38
-
39
- ## Client Usage
40
-
41
- ```typescript
42
- import { createAuthClient } from "better-auth/client";
43
- import { comboAuthClient } from "@quickback-dev/better-auth-combo-auth/client";
44
-
45
- const authClient = createAuthClient({
46
- plugins: [comboAuthClient()],
47
- });
48
-
49
- // Request authentication — sends email with link + OTP
50
- await authClient.signIn.comboAuth({
51
- email: "user@example.com",
52
- });
53
-
54
- // Verify with OTP code (if user enters it manually)
55
- await authClient.signIn.comboAuth({
56
- email: "user@example.com",
57
- otp: "123456",
58
- });
59
- ```
60
-
61
- ## How It Works
62
-
63
- 1. User enters their email and requests sign-in
64
- 2. A single email is sent containing both a magic link and a 6-digit OTP
65
- 3. **Option A:** User clicks the magic link — authenticated immediately
66
- 4. **Option B:** User enters the OTP code — authenticated after verification
67
-
68
- This provides the best of both worlds: convenience of magic links with the reliability of OTP codes (useful when magic links don't work well, e.g., opening email on a different device).
69
-
70
- ## See Also
71
-
72
- - [Auth Plugins](/stack/auth/plugins) — All authentication plugin options
73
- - [Upgrade Anonymous](/stack/auth/plugins/upgrade-anonymous) — Convert anonymous sessions to full accounts
74
- - [AWS SES](/stack/auth/plugins/aws-ses) — Email delivery for auth flows
@@ -1,155 +0,0 @@
1
- # Upgrade Anonymous Plugin
2
-
3
- `@quickback-dev/better-auth-upgrade-anonymous` provides a single endpoint to convert anonymous users into full authenticated users. It flips the `isAnonymous` flag, optionally updates email and name, and refreshes the session — no re-authentication required.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install @quickback-dev/better-auth-upgrade-anonymous
9
- ```
10
-
11
- ## Configuration
12
-
13
- Enable both the `anonymous` and `upgradeAnonymous` plugins:
14
-
15
- ```typescript
16
- auth: defineAuth("better-auth", {
17
- plugins: ["anonymous", "upgradeAnonymous"],
18
- })
19
- ```
20
-
21
- The plugin accepts optional configuration:
22
-
23
- ```typescript
24
- import { upgradeAnonymous } from "@quickback-dev/better-auth-upgrade-anonymous";
25
-
26
- upgradeAnonymous({
27
- emailConfigured: true, // Whether email delivery is available
28
- requireEmailVerification: true, // Whether to require email verification
29
- })
30
- ```
31
-
32
- | Option | Default | Description |
33
- |--------|---------|-------------|
34
- | `emailConfigured` | `false` | When `true` and an email is provided, `emailVerified` is set based on `requireEmailVerification` |
35
- | `requireEmailVerification` | `true` | When `true`, provided emails are marked unverified (requiring OTP). When `false`, emails are marked verified immediately |
36
-
37
- > **Quickback Compiler**
38
- >
39
- > When using the Quickback compiler, these options are set automatically based on your SES environment variables. You don't need to configure them manually.
40
-
41
-
42
- ## Endpoint
43
-
44
- ```
45
- POST /auth/v1/upgrade-anonymous
46
- ```
47
-
48
- ### Flow
49
-
50
- 1. Validates the user's session (returns `401` if not authenticated)
51
- 2. Checks if the user is already upgraded (returns success immediately if so)
52
- 3. If an email is provided, checks for duplicates (returns `400` if email is taken)
53
- 4. Updates `isAnonymous` to `false`, plus optional `email`, `name`, and `emailVerified` fields
54
- 5. Refreshes the session cookie with the updated user object
55
- 6. Returns the updated user, session, and `verificationRequired` flag
56
-
57
- ### Request
58
-
59
- The body is optional. When provided, it accepts:
60
-
61
- | Field | Type | Description |
62
- |-------|------|-------------|
63
- | `email` | `string` (email) | Optional. Real email to replace the anonymous placeholder |
64
- | `name` | `string` | Optional. User's display name |
65
-
66
- ```bash
67
- # Minimal — just upgrade, no email/name
68
- curl -X POST https://api.example.com/auth/v1/upgrade-anonymous \
69
- -H "Cookie: better-auth.session_token=..."
70
-
71
- # With email and name
72
- curl -X POST https://api.example.com/auth/v1/upgrade-anonymous \
73
- -H "Cookie: better-auth.session_token=..." \
74
- -H "Content-Type: application/json" \
75
- -d '{"email": "jane@example.com", "name": "Jane"}'
76
- ```
77
-
78
- ### Response
79
-
80
- ```json
81
- {
82
- "success": true,
83
- "verificationRequired": true,
84
- "user": {
85
- "id": "usr_abc123",
86
- "email": "jane@example.com",
87
- "isAnonymous": false
88
- },
89
- "session": {
90
- "id": "sess_xyz",
91
- "userId": "usr_abc123"
92
- }
93
- }
94
- ```
95
-
96
- The `verificationRequired` field is `true` when all three conditions are met:
97
- - An email was provided in the request body
98
- - `emailConfigured` is `true` in plugin config
99
- - `requireEmailVerification` is `true` in plugin config
100
-
101
- When `verificationRequired` is `true`, the frontend should send a verification OTP and redirect the user to verify their email.
102
-
103
- ## How It Works
104
-
105
- The plugin is designed to be flexible:
106
-
107
- - **Minimal by default** — With no body, only changes `isAnonymous` from `true` to `false`
108
- - **Optional email/name** — Can update email and name in the same request
109
- - **Duplicate protection** — Rejects emails already associated with another account
110
- - **Verification-aware** — Returns `verificationRequired` so the frontend knows whether to trigger OTP
111
- - **Session preserved** — Same session ID, no re-authentication needed
112
- - **Idempotent** — Calling on an already-upgraded user returns success immediately
113
-
114
- ## Typical Flows
115
-
116
- ### Passkey Signup (no email)
117
-
118
- 1. User creates anonymous session
119
- 2. User registers a passkey
120
- 3. App calls `POST /auth/v1/upgrade-anonymous` with no body
121
- 4. User is now a full user with passkey auth — no email on file
122
-
123
- ### Passkey Signup (with email)
124
-
125
- 1. User creates anonymous session
126
- 2. User registers a passkey
127
- 3. User optionally enters email/name on the email collection step
128
- 4. App calls `POST /auth/v1/upgrade-anonymous` with `{ email, name }`
129
- 5. If `verificationRequired`: app sends OTP, user verifies, then redirects to dashboard
130
- 6. Otherwise: user goes straight to dashboard
131
-
132
- ### Email Signup
133
-
134
- 1. User starts as anonymous (created via Better Auth's `anonymous` plugin)
135
- 2. User provides email/password through your UI (via combo auth or signup)
136
- 3. Your app calls `POST /auth/v1/upgrade-anonymous`
137
- 4. User is now a full user with the same ID and all their data intact
138
-
139
- ### Client Plugin
140
-
141
- ```typescript
142
- import { upgradeAnonymousClient } from "@quickback-dev/better-auth-upgrade-anonymous/client";
143
-
144
- const authClient = createAuthClient({
145
- plugins: [upgradeAnonymousClient()],
146
- });
147
-
148
- // Upgrade the current anonymous user
149
- await authClient.upgradeAnonymous();
150
- ```
151
-
152
- ## See Also
153
-
154
- - [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP for collecting credentials
155
- - [Auth Configuration](/compiler/config/providers) — Configuring auth plugins