@quickback-dev/cli 0.66.16 → 0.66.18

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 (101) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +26 -20
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/lib/action-harvest.d.ts +3 -2
  6. package/dist/lib/action-harvest.d.ts.map +1 -1
  7. package/dist/lib/action-harvest.js +3 -2
  8. package/dist/lib/action-harvest.js.map +1 -1
  9. package/dist/lib/file-writer.d.ts +9 -0
  10. package/dist/lib/file-writer.d.ts.map +1 -1
  11. package/dist/lib/file-writer.js +30 -5
  12. package/dist/lib/file-writer.js.map +1 -1
  13. package/dist/skill/SKILL.md +2 -2
  14. package/dist/skill/docs/api/actions.md +10 -9
  15. package/dist/skill/docs/api/errors.md +14 -3
  16. package/dist/skill/docs/api/openapi.md +1 -1
  17. package/dist/skill/docs/api/query-params.md +3 -3
  18. package/dist/skill/docs/configure/agents.md +1 -1
  19. package/dist/skill/docs/configure/auth.md +35 -37
  20. package/dist/skill/docs/configure/index.md +1 -1
  21. package/dist/skill/docs/define/access.md +16 -6
  22. package/dist/skill/docs/define/actions/defining.md +8 -1
  23. package/dist/skill/docs/define/actions/scoped-db.md +69 -8
  24. package/dist/skill/docs/define/changesets.md +8 -3
  25. package/dist/skill/docs/define/encryption.md +6 -3
  26. package/dist/skill/docs/define/fga.md +9 -4
  27. package/dist/skill/docs/define/firewall.md +15 -7
  28. package/dist/skill/docs/define/masking.md +1 -1
  29. package/dist/skill/docs/define/relationships.md +6 -3
  30. package/dist/skill/docs/define/schema.md +27 -2
  31. package/dist/skill/docs/define/scopes.md +27 -4
  32. package/dist/skill/docs/define/transitions.md +5 -0
  33. package/dist/skill/docs/define/views.md +9 -0
  34. package/dist/skill/docs/platform/api-contract/index.md +4 -2
  35. package/dist/skill/docs/platform/auth/api-keys.md +10 -1
  36. package/dist/skill/docs/platform/auth/jwt-optimization.md +38 -49
  37. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  38. package/dist/skill/docs/platform/auth/plugins/index.md +7 -15
  39. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  40. package/dist/skill/docs/platform/auth/security.md +2 -2
  41. package/dist/skill/docs/platform/auth/using-auth.md +2 -1
  42. package/dist/skill/docs/platform/database/neon.md +1 -1
  43. package/dist/skill/docs/platform/push/index.md +31 -23
  44. package/dist/skill/docs/platform/storage/r2.md +36 -4
  45. package/dist/skill/docs/platform/vector/embeddings.md +11 -76
  46. package/dist/skill/docs/platform/vector/index.md +1 -1
  47. package/dist/skill/docs/platform/vector/using-embeddings.md +10 -73
  48. package/dist/skill/docs/platform/webhooks/outbound.md +12 -8
  49. package/dist/skill/docs/tooling/cli.md +2 -2
  50. package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  51. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  52. package/dist/skill/docs/tooling/cloud-compiler/index.md +18 -3
  53. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  54. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  55. package/dist/skill/docs/tooling/output.md +6 -2
  56. package/dist/skill/docs/ui/account/hooks.md +2 -2
  57. package/package.json +1 -1
  58. package/src/skill/SKILL.md +2 -2
  59. package/src/skill/docs/api/actions.md +10 -9
  60. package/src/skill/docs/api/errors.md +14 -3
  61. package/src/skill/docs/api/openapi.md +1 -1
  62. package/src/skill/docs/api/query-params.md +3 -3
  63. package/src/skill/docs/configure/agents.md +1 -1
  64. package/src/skill/docs/configure/auth.md +35 -37
  65. package/src/skill/docs/configure/index.md +1 -1
  66. package/src/skill/docs/define/access.md +16 -6
  67. package/src/skill/docs/define/actions/defining.md +8 -1
  68. package/src/skill/docs/define/actions/scoped-db.md +69 -8
  69. package/src/skill/docs/define/changesets.md +8 -3
  70. package/src/skill/docs/define/encryption.md +6 -3
  71. package/src/skill/docs/define/fga.md +9 -4
  72. package/src/skill/docs/define/firewall.md +15 -7
  73. package/src/skill/docs/define/masking.md +1 -1
  74. package/src/skill/docs/define/relationships.md +6 -3
  75. package/src/skill/docs/define/schema.md +27 -2
  76. package/src/skill/docs/define/scopes.md +27 -4
  77. package/src/skill/docs/define/transitions.md +5 -0
  78. package/src/skill/docs/define/views.md +9 -0
  79. package/src/skill/docs/platform/api-contract/index.md +4 -2
  80. package/src/skill/docs/platform/auth/api-keys.md +10 -1
  81. package/src/skill/docs/platform/auth/jwt-optimization.md +38 -49
  82. package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  83. package/src/skill/docs/platform/auth/plugins/index.md +7 -15
  84. package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  85. package/src/skill/docs/platform/auth/security.md +2 -2
  86. package/src/skill/docs/platform/auth/using-auth.md +2 -1
  87. package/src/skill/docs/platform/database/neon.md +1 -1
  88. package/src/skill/docs/platform/push/index.md +31 -23
  89. package/src/skill/docs/platform/storage/r2.md +36 -4
  90. package/src/skill/docs/platform/vector/embeddings.md +11 -76
  91. package/src/skill/docs/platform/vector/index.md +1 -1
  92. package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
  93. package/src/skill/docs/platform/webhooks/outbound.md +12 -8
  94. package/src/skill/docs/tooling/cli.md +2 -2
  95. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  96. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  97. package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
  98. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  99. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  100. package/src/skill/docs/tooling/output.md +6 -2
  101. package/src/skill/docs/ui/account/hooks.md +2 -2
@@ -6,7 +6,7 @@ APNs is planned as a second provider. The helper signature is shared, so most co
6
6
 
7
7
  ## What you get
8
8
 
9
- - **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.
9
+ - **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ organizationId, targetRoles? }`, `{ userIds }`, `{ targetTags }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.
10
10
  - **`sendPush(subscription, payload, vapid)`** — single-recipient delivery. Returns `{ status: 'sent' | 'gone' | 'failed', statusCode, ... }`.
11
11
  - **`sendPushBulk(subscriptions, payload, vapid, opts?)`** — in-request fan-out with a default concurrency cap of 8 (Workers subrequest-budget friendly).
12
12
  - **`vapidFromEnv(env)`** — assembles the `VapidConfig` from `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` / `VAPID_SUBJECT`.
@@ -56,7 +56,7 @@ With `push.defaultSchema: true`, the compiler injects a hardened, owner-scoped `
56
56
  - **INTERNAL-only reads** — the crypto fields (`endpoint`, `p256dh`, `auth`) never leave the worker via any HTTP path. A `views.mine` projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` for "Your devices" UIs.
57
57
  - **Owner firewall** — `owner_id` is auto-stamped on create; user A can never read or delete user B's subscription.
58
58
  - **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender additionally rejects any endpoint whose host resolves to a private, link-local, loopback, `localhost`, or `.internal` address. Together — **https + a non-public-host block** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.
59
- - **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx` (`user:<id>`, `role:<name>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>`, the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. A normal session-cookie subscribe therefore stamps `user:` and `role:` but no `scope:` tag; see [Targeting](#targeting).
59
+ - **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx`: `user:<id>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>` plus one `scope:<kind>:<instance>#<role>` per scope role the verified claim grants (the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. **Org roles are never stamped** — a device is user-owned, and org audiences are resolved from live membership at send time; see [Targeting](#targeting).
60
60
  - **Rate limit + cap** — creates are limited to 10/minute per caller, and only the newest 10 live subscriptions per user are kept (older rows are soft-deleted, so a user's new device always works).
61
61
 
62
62
  This create-time hardening (endpoint/key validation, server-side tag stamping, the per-user cap) runs in JS before/after-insert hooks that fire **only on audit-wrapped writes** — the REST create path and actions. The normal browser subscribe is REST, so it's fully covered; but raw-SQL writes, queue/cron inserts, or direct INTERNAL-context inserts into `push_subscriptions` bypass all of it. Don't hand-insert subscription rows expecting the guards to apply.
@@ -181,22 +181,27 @@ export default defineAction({
181
181
  description: "Publish an event and notify admins.",
182
182
  input: z.object({}),
183
183
  access: { roles: ["owner", "admin"] },
184
- async execute({ record, env, effects }) {
184
+ async execute({ record, ctx, env, effects }) {
185
185
  // ...your committed write happens here...
186
186
 
187
- // After-commit: notify every subscribed admin.
188
- effects.enqueue("push:eventPublished", () =>
189
- enqueuePushFanout(
190
- env.PUSH_FANOUT_QUEUE!,
191
- { targetRoles: ["admin"] },
192
- {
193
- title: record.name,
194
- body: "Event published — tap to review",
195
- url: `https://app.example.com/events/${record.id}`,
196
- tag: `event-${record.id}`,
197
- },
198
- ),
199
- );
187
+ // After-commit: notify this organization's admins (owners too, via
188
+ // auth.roleHierarchy). The scope is on the send — resolved from
189
+ // membership when the queue consumer runs, never from the device.
190
+ const organizationId = ctx.activeOrgId;
191
+ if (organizationId) {
192
+ effects.enqueue("push:eventPublished", () =>
193
+ enqueuePushFanout(
194
+ env.PUSH_FANOUT_QUEUE!,
195
+ { organizationId, targetRoles: ["admin"] },
196
+ {
197
+ title: record.name,
198
+ body: "Event published — tap to review",
199
+ url: `https://app.example.com/events/${record.id}`,
200
+ tag: `event-${record.id}`,
201
+ },
202
+ ),
203
+ );
204
+ }
200
205
 
201
206
  return { published: true };
202
207
  },
@@ -205,24 +210,27 @@ export default defineAction({
205
210
 
206
211
  The declarative form enqueues **one small message**; the generated queue consumer resolves the audience against `push_subscriptions` inside the server-internal trust zone and fans out delivery chunks. Subscription crypto never enters your action code.
207
212
 
208
- Target by `{ targetRoles }` or `{ userIds }` — these match the `role:<name>` and `user:<id>` tags that **every** subscription carries, because they're stamped from `ctx` on a normal session-cookie subscribe. `{ targetTags: ['scope:events:e9'] }` only matches subscriptions created inside a scoped context (see the note under [Targeting](#targeting)); against ordinary session-created rows it selects nobody.
213
+ Target an organization with `{ organizationId, targetRoles? }` or specific people with `{ userIds }` — both work for every subscription, because they resolve against the row's owner rather than a stamped claim.
209
214
 
210
215
  ### Targeting
211
216
 
212
- `enqueuePushFanout` speaks the same identity-tag dialect as [realtime targeting](/platform/realtime/durable-objects). For the common browser subscribe flow, reach for `{ targetRoles }` or `{ userIds }` first — those tags are stamped on every session-created subscription:
217
+ A declarative target names **exactly one** audience:
213
218
 
214
219
  | Target | Selects |
215
220
  |---|---|
216
- | `{ targetRoles: ['admin'] }` | Rows whose tags include `role:admin` (any listed role) |
221
+ | `{ organizationId: 'org_1' }` | Devices of every current member of that organization |
222
+ | `{ organizationId: 'org_1', targetRoles: ['admin'] }` | Devices of that org's members holding a listed role — `auth.roleHierarchy`-expanded, so an `owner` satisfies `'admin'` |
223
+ | `{ organizationId: 'org_1', targetRoles: [...], userIds: [...] }` | The same, narrowed to those users |
217
224
  | `{ userIds: ['u1', 'u2'] }` | Subscriptions owned by those users |
225
+ | `{ targetTags: ['scope:event:e9#attendee'] }` | Rows whose stamped tags include ANY listed tag — **`scope:*` tags exist only on scoped-token subscribes** (see note below) |
218
226
  | `{ all: true }` | Every live subscription — broadcast must be this explicit |
219
- | `{ targetTags: ['scope:events:e9'] }` | Rows whose stamped tags include ANY listed tag — **but `scope:*` tags exist only on scoped-token subscribes** (see note below); against session-created rows this selects nobody |
220
- | `{ targetTags: [...], targetRoles: [...] }` | Rows matching BOTH arms (AND across arms, union within) |
221
227
  | `{ subscriptions: [...] }` | An explicit list you already hold |
222
228
 
223
- Selection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), and a target with no arms at all throws — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.
229
+ **Org audiences are resolved at send time.** The queue consumer reads the organization's Better Auth membership when it resolves the fan-out (one query; on D1 through the `AUTH_DB` binding), filters by role, and delivers to those members' devices. A member who is demoted or removed stops receiving on the very next send, and one organization's roles never reach another organization's members — a user who is an admin in one org and a member in another is an admin only for the first. `targetRoles` is **only** valid beside `organizationId`: a role without an organization has no tenant, so `{ targetRoles }` alone is a type error and throws at runtime. The `organizationId` arm needs the Better Auth `organization` plugin; without it the target throws.
224
230
 
225
- > **`scope:<kind>:<subject>` tags need a scoped token.** `ctx.scope` is populated *only* from a verified scoped-JWT claim — the same relationship-derived scope the [realtime pillar](/platform/realtime/durable-objects) uses. A normal browser subscribe authenticated with a session cookie stamps only `user:<id>` and `role:<name>`; it **never** stamps a `scope:*` tag. Because targeting is fail-closed, a `{ targetTags: ['scope:events:e9'] }` fan-out over session-created subscriptions silently delivers to **nobody**. Scope targeting works only if your app subscribes users from within a scoped context; otherwise select by role or user id.
231
+ Selection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), a target with no arm throws, and arms do not combine (`{ userIds, targetTags }` throws) — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.
232
+
233
+ > **`scope:*` tags need a scoped token.** `ctx.scope` is populated *only* from a verified scoped-JWT claim — the same relationship-derived scope the [realtime pillar](/platform/realtime/durable-objects) uses. A normal browser subscribe authenticated with a session cookie stamps only `user:<id>`; it **never** stamps a `scope:*` tag. Because targeting is fail-closed, a `{ targetTags: ['scope:event:e9#attendee'] }` fan-out over session-created subscriptions delivers to **nobody**. Scope tags — identity and role alike — are frozen at subscribe (re-subscribing refreshes them), so a scope role revoked afterwards keeps matching until then; org roles have no such window because they are never stamped.
226
234
 
227
235
 
228
236
  With an explicit `{ subscriptions }` list, passing `opts.vapid` (via `vapidFromEnv(env)`) lets lists at or under `push.fanout.threshold` (default 500) deliver **inline** with per-recipient results; larger lists chunk onto the queue.
@@ -155,7 +155,7 @@ export default {
155
155
 
156
156
  | Method | Endpoint | Description |
157
157
  |--------|----------|-------------|
158
- | POST | `/bucket` | Create a bucket |
158
+ | POST | `/bucket` | Create a bucket (`allowedMimeTypes` must be a subset of `allowedTypes`) |
159
159
  | GET | `/bucket` | List buckets |
160
160
  | GET | `/bucket/:name` | Get bucket info |
161
161
  | DELETE | `/bucket/:name` | Delete bucket (must be empty) |
@@ -201,6 +201,14 @@ POST /storage/v1/bucket
201
201
  `readScope: "public"` is the default for listing photos and avatars. Switch to
202
202
  `organization` or `user` only when a signed-in session must gate the GET.
203
203
 
204
+ A bucket can also set `fileSizeLimit` and `allowedMimeTypes`. Both **narrow**
205
+ the project-wide `maxFileSize` / `allowedTypes`; neither can widen them.
206
+ `allowedMimeTypes` entries outside the project's `allowedTypes` are rejected
207
+ with `400` `VALIDATION_INVALID_INPUT`, listing the offenders in
208
+ `details.disallowed`. Bucket rows written before that check existed are
209
+ intersected with `allowedTypes` at upload and presign time, so a widened list
210
+ has no effect.
211
+
204
212
  ### Scope Options
205
213
 
206
214
  | Scope | Read Behavior | Write Behavior |
@@ -317,8 +325,9 @@ curl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \
317
325
  > The `size` and `contentType` from step 1 are **bound into the signature** as
318
326
  > `Content-Length` and `Content-Type` — the client MUST replay the returned
319
327
  > `headers` verbatim on the PUT, or R2 rejects it. That is what makes
320
- > `maxFileSize` and `allowedTypes` real limits on the object that lands, not
321
- > just on the request that asked for a URL.
328
+ > `maxFileSize` and `allowedTypes` (and a bucket's narrower `fileSizeLimit` /
329
+ > `allowedMimeTypes`) real limits on the object that lands, not just on the
330
+ > request that asked for a URL.
322
331
 
323
332
 
324
333
  ### Required secrets
@@ -424,6 +433,25 @@ The files worker:
424
433
  > trusted as minted.
425
434
 
426
435
 
436
+ ### Response headers
437
+
438
+ Uploaded bytes are attacker-controlled, and the API origin shares cookies with
439
+ the CMS and Account apps. So every stored object — from `GET`/`HEAD
440
+ /storage/v1/object/...` and from the files worker alike — is served with one
441
+ header policy:
442
+
443
+ | Header | Value |
444
+ |--------|-------|
445
+ | `X-Content-Type-Options` | `nosniff` |
446
+ | `Content-Security-Policy` | `default-src 'none'; sandbox` |
447
+ | `Content-Disposition` | `inline` for `image/jpeg`, `image/png`, `image/gif`, `image/webp`, `image/avif`; otherwise `attachment; filename="…"; filename*=UTF-8''…` |
448
+
449
+ An SVG, HTML, XML, or PDF upload therefore **downloads** when opened directly
450
+ instead of rendering on your domain. `<img src>` embedding is unaffected —
451
+ subresource loads ignore `Content-Disposition` and the document CSP. The
452
+ filename is the last segment of the object key, RFC 6266-encoded. If you need
453
+ to display PDFs inline, render them from a separate, cookie-less origin.
454
+
427
455
  ## Generated Files
428
456
 
429
457
  When file storage is configured, the compiler generates:
@@ -432,6 +460,7 @@ When file storage is configured, the compiler generates:
432
460
  |------|---------|
433
461
  | `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |
434
462
  | `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |
463
+ | `src/lib/object-headers.ts` | `objectHeaders()` — the serving-header policy shared by the storage routes and the files worker |
435
464
  | `src/files/schema.ts` | Files metadata schema (buckets, objects) — `sqliteTable` on D1, a `files` Postgres schema otherwise |
436
465
  | `src/files/index.ts` | `createFilesDb` — the D1 binding handle, or the Postgres service-lane handle |
437
466
  | `drizzle.files.config.ts` | Second migration target — **D1 only** |
@@ -536,7 +565,7 @@ cd cloudflare-workers/files && npx wrangler deploy --env dev
536
565
  | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
537
566
  | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode, `cloudflare-d1` only — Postgres uses the `files` schema of the single database and emits no binding) |
538
567
  | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
539
- | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
568
+ | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode). The ceiling for every bucket: a bucket's `allowedMimeTypes` must be a subset. |
540
569
  | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
541
570
 
542
571
  ### How the size limit is enforced
@@ -564,5 +593,8 @@ Both paths answer `413` with the actual and permitted byte counts.
564
593
  read scope never implies a public write.
565
594
  - **Serve security**: Public prefix = URL is the capability. Session-gated
566
595
  paths re-check membership on every GET. Signed GET expires.
596
+ - **Content safety**: Every served object carries `nosniff` and a sandboxing
597
+ CSP; only raster images are `inline`, everything else is an `attachment`
598
+ ([Response headers](#response-headers)).
567
599
  - **Soft deletes**: Files are marked deleted in metadata but retained in R2
568
600
  - **Tenant isolation**: All files are prefixed with organization ID
@@ -100,82 +100,18 @@ onUpdate: ['description', 'title']
100
100
  - The queue consumer is an internal process that executes pre-validated jobs
101
101
  - If a user can't create a job posting, they can't trigger an embedding job
102
102
 
103
- ## Generic Embeddings API
103
+ ## Re-embedding a Row
104
104
 
105
- In addition to automatic embeddings on standard resource operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.
105
+ There is no separate embeddings endpoint. To re-embed a row, **PATCH it**: the
106
+ generated `PATCH /api/v1/<resource>/:id` (and `PATCH /batch`) enqueues a fresh job
107
+ after the write passes auth, firewall, and guards. With `onUpdate: [...fields]`,
108
+ the PATCH must include one of the watched fields — resending the current value is
109
+ enough; with the default `onUpdate`, any PATCH re-embeds. The job always uses the
110
+ table's configured `model` and `embeddingColumn`; clients never choose either.
106
111
 
107
- ### POST /api/v1/embeddings
108
-
109
- Generate an embedding for any text content:
110
-
111
- ```bash
112
- curl -X POST https://your-api.workers.dev/api/v1/embeddings \
113
- -H "Content-Type: application/json" \
114
- -H "Cookie: better-auth.session_token=..." \
115
- -d '{
116
- "content": "Text to embed",
117
- "model": "@cf/baai/bge-base-en-v1.5",
118
- "table": "jobs",
119
- "id": "job_123"
120
- }'
121
- ```
122
-
123
- #### Request Body
124
-
125
- | Field | Type | Required | Description |
126
- |-------|------|----------|-------------|
127
- | `content` | `string` | Yes | Text to generate embedding for |
128
- | `model` | `string` | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |
129
- | `table` | `string` | No | Table to store embedding back to |
130
- | `id` | `string` | Conditional | Record ID to update (required if `table` is specified) |
131
-
132
- #### Response
133
-
134
- ```json
135
- {
136
- "queued": true,
137
- "jobId": "550e8400-e29b-41d4-a716-446655440000",
138
- "table": "jobs",
139
- "id": "job_123",
140
- "model": "@cf/baai/bge-base-en-v1.5"
141
- }
142
- ```
143
-
144
- ### GET /api/v1/embeddings/tables
145
-
146
- List tables that have embeddings configured:
147
-
148
- ```bash
149
- curl https://your-api.workers.dev/api/v1/embeddings/tables \
150
- -H "Cookie: better-auth.session_token=..."
151
- ```
152
-
153
- Response:
154
-
155
- ```json
156
- {
157
- "tables": [
158
- {
159
- "name": "jobs",
160
- "embeddingColumn": "embedding",
161
- "model": "@cf/baai/bge-base-en-v1.5"
162
- }
163
- ]
164
- }
165
- ```
166
-
167
- ### Authentication & Authorization
168
-
169
- The generic embeddings API requires authentication and uses the `activeOrgId` from the user's context to enforce organization-level isolation. Embedding jobs are scoped to the user's current organization.
170
-
171
- ### Use Cases
172
-
173
- The generic embeddings API is useful for:
174
-
175
- - **Batch embedding**: Embed content without going through CRUD routes
176
- - **Re-embedding**: Force re-generation of embeddings for existing records
177
- - **Preview embeddings**: Test embedding generation before persisting
178
- - **External content**: Embed content that doesn't fit your defined schemas
112
+ For content that doesn't live in a table (previews, external text), call the
113
+ search service's [`embed()`](/platform/vector/embeddings#generate-embeddings-directly)
114
+ from an action — it runs under that action's own access rules.
179
115
 
180
116
  ## Generated Files
181
117
 
@@ -184,10 +120,9 @@ When embeddings are configured, the compiler generates:
184
120
  | File | Purpose |
185
121
  |------|---------|
186
122
  | `src/queue-consumer.ts` | Queue consumer handler for processing embedding jobs |
187
- | `src/routes/embeddings.ts` | Generic embeddings API routes |
188
123
  | `wrangler.toml` | Queue producer/consumer bindings, AI binding |
189
124
  | `src/env.d.ts` | `EMBEDDINGS_QUEUE`, `AI` types |
190
- | `src/index.ts` | Exports `queue` handler, mounts `/api/v1/embeddings` |
125
+ | `src/index.ts` | Exports the `queue` handler |
191
126
 
192
127
  ### wrangler.toml additions
193
128
 
@@ -41,4 +41,4 @@ The default embedding model is `@cf/baai/bge-base-en-v1.5` (768 dimensions). You
41
41
  ## Pages
42
42
 
43
43
  - **[Automatic Embeddings](/platform/vector/embeddings)** — `defineTable()` embeddings config, queue consumer, Vectorize integration, and `defineEmbedding()` search service
44
- - **[Using Embeddings](/platform/vector/using-embeddings)** — Embeddings API endpoints, semantic search, and practical usage
44
+ - **[Using Embeddings](/platform/vector/using-embeddings)** — Re-embedding rows, semantic search, and practical usage
@@ -1,76 +1,14 @@
1
1
  # Using Embeddings
2
2
 
3
- This page covers the runtime API for working with embeddings — the generated endpoints, the search service, and practical usage patterns.
3
+ This page covers the runtime API for working with embeddings — re-embedding rows, the search service, and practical usage patterns.
4
4
 
5
- ## Embeddings API
5
+ ## Re-embedding Rows
6
6
 
7
- When any feature has embeddings configured, the compiler generates these endpoints:
8
-
9
- ### Generate Embedding
10
-
11
- ```
12
- POST /api/v1/embeddings
13
- ```
14
-
15
- Enqueue an embedding job for arbitrary content:
16
-
17
- ```bash
18
- curl -X POST https://api.example.com/api/v1/embeddings \
19
- -H "Content-Type: application/json" \
20
- -H "Cookie: better-auth.session_token=..." \
21
- -d '{
22
- "content": "Text to generate an embedding for",
23
- "model": "@cf/baai/bge-base-en-v1.5",
24
- "table": "jobs",
25
- "id": "job_123"
26
- }'
27
- ```
28
-
29
- **Request body:**
30
-
31
- | Field | Type | Required | Description |
32
- |-------|------|----------|-------------|
33
- | `content` | string | Yes | Text to embed |
34
- | `model` | string | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |
35
- | `table` | string | No | Table to store the embedding in |
36
- | `id` | string | Conditional | Record ID (required when `table` is provided) |
37
-
38
- **Response:**
39
-
40
- ```json
41
- {
42
- "queued": true,
43
- "jobId": "550e8400-e29b-41d4-a716-446655440000",
44
- "table": "jobs",
45
- "id": "job_123",
46
- "model": "@cf/baai/bge-base-en-v1.5"
47
- }
48
- ```
49
-
50
- This endpoint is useful for:
51
- - Re-embedding existing records
52
- - Embedding content that doesn't go through CRUD routes
53
- - Batch embedding via scripts
54
-
55
- ### List Embedding Tables
56
-
57
- ```
58
- GET /api/v1/embeddings/tables
59
- ```
60
-
61
- List tables that have embeddings configured:
62
-
63
- ```json
64
- {
65
- "tables": [
66
- {
67
- "name": "jobs",
68
- "embeddingColumn": "embedding",
69
- "model": "@cf/baai/bge-base-en-v1.5"
70
- }
71
- ]
72
- }
73
- ```
7
+ Embeddings have no endpoint of their own. Rows are embedded on INSERT and
8
+ re-embedded on UPDATE by the generated CRUD routes, after auth, firewall, and
9
+ guards pass — so **PATCH the row to re-embed** (with `onUpdate: [...fields]`,
10
+ include a watched field; resending its current value is enough). The job uses the
11
+ table's configured `model` and `embeddingColumn`.
74
12
 
75
13
  ## Search Service
76
14
 
@@ -162,14 +100,13 @@ The `metadata` fields in your `defineTable` embeddings config are automatically
162
100
  |---------|-----|----------|
163
101
  | Auto (INSERT) | Compiler enqueues after successful create | Default behavior |
164
102
  | Auto (UPDATE) | Compiler enqueues when watched fields change | Keeps embeddings fresh |
165
- | Manual (API) | `POST /api/v1/embeddings` | Re-embedding, batch jobs |
103
+ | Re-embed | `PATCH` the row (or `PATCH /batch`) | Re-embedding existing records |
166
104
  | Manual (Queue) | `env.EMBEDDINGS_QUEUE.send(...)` | Custom pipelines |
167
105
 
168
106
  ## Security
169
107
 
170
- - The embeddings API requires authentication
171
- - Jobs are scoped to the user's `activeOrgId`
172
- - Embedding jobs are only enqueued after all security checks pass (auth, firewall, guards)
108
+ - Embedding jobs are only enqueued by the generated write routes, after all security checks pass (auth, firewall, guards) — there is no client-facing embeddings endpoint
109
+ - Jobs are scoped to the writer's `activeOrgId`
173
110
  - The queue consumer is an internal process — it trusts pre-validated jobs
174
111
 
175
112
  ## Supported Models
@@ -22,12 +22,16 @@ import { emitWebhookEvent } from '../lib/webhooks/emit';
22
22
  // After creating a user
23
23
  const newUser = await db.insert(users).values(data).returning();
24
24
 
25
- await emitWebhookEvent(
26
- "user.created",
27
- newUser[0],
28
- { organizationId: ctx.activeOrgId },
29
- env
30
- );
25
+ // ctx.activeOrgId is `string | undefined` — narrow it first. Passing it
26
+ // unguarded is a type error, and an unscoped emit throws at runtime.
27
+ if (ctx.activeOrgId) {
28
+ await emitWebhookEvent(
29
+ "user.created",
30
+ newUser[0],
31
+ { organizationId: ctx.activeOrgId },
32
+ env
33
+ );
34
+ }
31
35
  ```
32
36
 
33
37
  **Parameters:**
@@ -36,7 +40,7 @@ await emitWebhookEvent(
36
40
  |-----------|------|-------------|
37
41
  | `eventType` | `string` | Event name (e.g., `user.created`) |
38
42
  | `payload` | `unknown` | Event data (auto-wrapped with metadata) |
39
- | `options` | `object` | `{ organizationId?, userId? }` — scope for endpoint matching |
43
+ | `options` | `{ organizationId: string } \| { userId: string }` | **Required.** Exactly one scope — only endpoints registered to that org or user receive the event. Neither or both throws. |
40
44
  | `env` | `CloudflareBindings` | Cloudflare environment bindings |
41
45
 
42
46
  **Note:** The compiler does NOT auto-emit events after CRUD operations. You must call `emitWebhookEvent()` explicitly where you want webhooks triggered.
@@ -166,7 +170,7 @@ Endpoints subscribe to events using patterns:
166
170
 
167
171
  ### Access Control
168
172
 
169
- Endpoints are scoped by `userId` or `organizationId`. Users can only manage their own endpoints. When emitting events, only endpoints matching the event's scope receive deliveries.
173
+ Endpoints are scoped by `userId` or `organizationId`. Users can only manage their own endpoints. When emitting events, only endpoints matching the event's scope receive deliveries. Every emit must name exactly one scope: an unscoped emit (`{}`, or an `organizationId` that is `undefined` at runtime) throws instead of reaching every tenant's endpoints — there is no global broadcast.
170
174
 
171
175
  ### URL Validation (anti-SSRF)
172
176
 
@@ -102,7 +102,7 @@ Every file under `src/` carries a `Generated by quickback.dev` header and is own
102
102
 
103
103
  1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).
104
104
  2. Wipes `src/` entirely.
105
- 3. Writes the fresh manifest from the compiler.
105
+ 3. Writes the fresh manifest from the compiler. Every path is checked first: an absolute path, a `.` / `..` segment, or anything resolving outside the output directory fails the build before a single file is written — the CLI never trusts the compiler's response to stay inside your project.
106
106
 
107
107
  This prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.
108
108
 
@@ -376,7 +376,7 @@ The CLI parses your feature files with the TypeScript compiler API, and falls ba
376
376
 
377
377
  `typescript` is an optional peer dependency, supported at **`>=5.0.0 <7`** — both 5.x and 6.x expose the classic compiler API. TypeScript 7 (the native port) resolves its main entry to a module exporting only `version` — parsing moved to the explicitly-unstable `typescript/unstable/*` subpaths — so it cannot drive the AST parser, and the CLI says so by name rather than degrading quietly.
378
378
 
379
- Compiled projects pin TypeScript 7 for `tsc`, which typechecks generated output correctly. Add a 6.x devDependency alongside it if you want `quickback schema sync` in that project.
379
+ Compiled projects pin `typescript` to 6.x for exactly this reason: `quickback build` runs schema sync before every compile, and a project on TypeScript 7 cannot build. Don't bump it to 7 by hand.
380
380
 
381
381
  Set `QUICKBACK_STRICT_PARSE=1` in CI so a regex-parsed build fails the pipeline instead of shipping:
382
382
 
@@ -28,7 +28,7 @@ The API key takes precedence over stored credentials from `quickback login`.
28
28
 
29
29
  ## How Tokens Are Validated
30
30
 
31
- The compiler-cloud worker validates authentication by forwarding your token to the Quickback API's `/internal/validate` endpoint via a [Cloudflare service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/). This resolves both session tokens (from `quickback login`) and API keys (from `QUICKBACK_API_KEY`).
31
+ The compiler-cloud worker validates authentication by forwarding your credentials to the Quickback API's Better Auth `GET /auth/v1/get-session` endpoint via a [Cloudflare service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/). This resolves both session tokens (from `quickback login`) and API keys (from `QUICKBACK_API_KEY`, sent as `x-api-key` — `get-session` is the only Better Auth endpoint that accepts a key in place of a session).
32
32
 
33
33
  ## Credential Storage
34
34
 
@@ -35,9 +35,10 @@ The `/compile` endpoint requires either a session token (from `quickback login`)
35
35
 
36
36
  The map uses project-root-relative paths and follows the same layout `quickback build` reads from disk: `quickback/quickback.config.ts`, `quickback/features/**`, `quickback/services/**`, `quickback/{lib,hooks,plugins,middlewares,email-templates}/**`, plus `quickback/drizzle/**/meta/**` and `wrangler.toml` for incremental builds.
37
37
 
38
- Two constraints, both fail-closed:
38
+ Three constraints, all fail-closed:
39
39
 
40
40
  - **The config must be fully static.** The compiler parses `quickback.config.ts` with a literals-only evaluator — it never executes user code. Object/array/string/number/boolean literals, substitution-free template literals, and the `define*` helper calls all work; variables, computed values, and imports-as-values are rejected with a 400 that names the offending construct and line.
41
+ - **Table files must be declarative.** Everything above `export default defineTable(...)` is checked before it reaches the generated schema that migration tooling loads — only `drizzle-orm` / `@quickback/compiler` / table-file imports and inert expressions pass ([rules](/define/schema#table-files-are-declarative)); anything else fails the compile naming the file and line.
41
42
  - **Action input schemas are contract-sensitive.** For v1, raw-files requests may omit `actionInputSchemas` and use the compiler's lower-fidelity static parser. V2 requires one usable client-harvested `z.toJSONSchema(action.input)` entry for every authored action. The CLI reports each missing action with its local bundle or evaluation error; the API independently reports missing or invalid action keys.
42
43
 
43
44
  Raw-files requests work with both `?complete=true` and `?complete=false`
@@ -51,9 +51,24 @@ without changing their definitions or generated output.
51
51
 
52
52
  ## Processing, analytics, and AI use
53
53
 
54
- - Compile payloads are processed for the request. Full compiles use an isolated
55
- temporary work directory that is deleted in a `finally` cleanup on success or
56
- failure; validation compiles run in memory.
54
+ - Compile payloads are processed for the request. Full compiles use a
55
+ per-request temporary work directory that is deleted in a `finally` cleanup
56
+ on success or failure; validation compiles run in memory.
57
+ - Compiles share a warm container, so the compiler limits what project source
58
+ can execute at all: table files must be
59
+ [declarative](/define/schema#table-files-are-declarative), Better Auth schema
60
+ generation does not load your auth hooks, email templates, or project-local
61
+ custom plugins, `existingFiles` may carry only migration state
62
+ (`quickback/drizzle/**/*.sql|json` and `wrangler.toml`), and a project file
63
+ (`quickback/lib/`, hooks, plugins) that lands on a generated path or under
64
+ `node_modules` fails the compile.
65
+ - The tools a full compile runs (drizzle-kit, the Better Auth CLI, wrangler's
66
+ dry-run bundle) run as a fresh operating-system user for each compile, with
67
+ no capabilities, and never reused. That user owns only its own work
68
+ directory (mode `0700`) while its command runs. It cannot read another
69
+ compile's directory, the compiler server's environment or memory, or write
70
+ anything a later compile loads. The hosted container has no outbound network
71
+ access.
57
72
  - Quickback does not retain request source or generated output as a project
58
73
  artifact on the compiler service.
59
74
  - The hosted edge records operational analytics: user/organization identifiers,
@@ -84,12 +84,15 @@ curl http://localhost:3000/health
84
84
 
85
85
  The Docker image includes:
86
86
  - Pre-installed dependencies for compiled projects (`/deps/node_modules`)
87
- - CMS and Account SPA source code (`/spa/cms/`, `/spa/account/`)
88
- - Pre-installed SPA dependencies (`/spa-deps/cms/`, `/spa-deps/account/`)
87
+ - Generic prebuilt CMS and Account SPA bundles (`/spa-prebuilt/cms/`, `/spa-prebuilt/account/`), built once at image build
89
88
 
90
- When compiling a project with `cms: true` or `account: true`, the compiler builds the SPAs from source inside the container with the correct Vite environment variables (e.g., `VITE_QUICKBACK_API_URL`, `VITE_QUICKBACK_ACCOUNT_URL`). This ensures each project gets properly configured SPA assets without manual intervention.
89
+ When compiling a project with `cms: true` or `account: true`, the compiler copies those prebuilt bundles into the project's `src/apps/` — it never runs Vite per compile. The generated worker injects the per-project values (API URLs, feature flags) into every served SPA shell as `window.__QUICKBACK_RUNTIME`, and the SPAs read that runtime blob, so one generic bundle serves every project.
91
90
 
92
- The generated worker additionally injects the same per-project values into every served SPA shell as `window.__QUICKBACK_RUNTIME`, and the SPAs prefer that runtime blob over the baked env — so the served behavior is identical even with a generic (no-`.env`) SPA build.
91
+ ### Security boundary
92
+
93
+ - **Loopback only.** Local mode skips authentication, so the launcher publishes the port on `127.0.0.1` only.
94
+ - **No browser-driven compiles.** In local mode, a request carrying an `Origin` header whose hostname is not `localhost`, `127.0.0.1`, or `[::1]` gets `403` — checked before CORS, so a web page you visit cannot POST a compile to your machine. The CLI and `curl` send no `Origin` and are unaffected.
95
+ - **Unprivileged user.** The server runs as the image's `bun` user (uid 1000). `/app`, `/deps`, and `/spa-prebuilt` are root-owned and not writable by it, and each compile works in its own `0700` directory under `/tmp/quickback`, so code that runs during one compile cannot plant files a later compile loads.
93
96
 
94
97
  ## Deploying to Cloud
95
98
 
@@ -11,7 +11,7 @@ quickback login
11
11
 
12
12
  ## Compilation timeout
13
13
 
14
- Large projects may take longer to compile. The cloud compiler uses [Cloudflare Containers](https://developers.cloudflare.com/containers/) to run compilation in isolated environments. If you hit timeouts, try [running the compiler locally](/tooling/cloud-compiler/local-compiler).
14
+ Large projects may take longer to compile. The cloud compiler runs in [Cloudflare Containers](https://developers.cloudflare.com/containers/). If you hit timeouts, try [running the compiler locally](/tooling/cloud-compiler/local-compiler).
15
15
 
16
16
  ## Compiler stays on loading
17
17
 
@@ -32,6 +32,9 @@ src/
32
32
  │ └── {feature}.ts # Mount re-export consumed by src/index.ts
33
33
  ├── lib/
34
34
  │ ├── auth.ts # Better Auth instance & config
35
+ │ ├── auth.schema-gen.ts # Copy of auth.ts with hooks/email templates stubbed — what `better-auth generate` reads
36
+ │ ├── firewall-registry.ts # Table → generated firewall builder for the action `db` (when used)
37
+ │ ├── scoped-db.ts # The action `db` — applies each table's firewall (when used)
35
38
  │ ├── access.ts # Access control helpers
36
39
  │ ├── types.ts # Runtime type definitions
37
40
  │ ├── masks.ts # Field masking utilities
@@ -281,11 +284,12 @@ When any feature has `embeddings` configured:
281
284
  src/
282
285
  ├── lib/
283
286
  │ └── embeddings.ts # Embedding helpers
284
- ├── routes/
285
- │ └── embeddings.ts # POST /api/{v1|v2}/embeddings endpoint
286
287
  └── queue-consumer.ts # Queue handler for async embedding jobs
287
288
  ```
288
289
 
290
+ There is no embeddings route: jobs are enqueued only by the generated write
291
+ routes, after auth, firewall, and guards pass.
292
+
289
293
  ### File Storage (R2)
290
294
 
291
295
  When `fileStorage` is configured, presign-only mode emits just the signer:
@@ -236,7 +236,7 @@ make project and Better Auth tables explicit.
236
236
 
237
237
  ## Writing hooks: use built-ins where possible
238
238
 
239
- Hook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a "module not found" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.
239
+ Hooks run in the deployed Worker, never at compile time: Better Auth schema generation reads `src/lib/auth.schema-gen.ts`, a copy of `src/lib/auth.ts` with every auth hook and email template replaced by an inert stub. The generated `package.json` does not pick up a hook's imports, though, so a hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package is undeclared: it fails to resolve when the Worker is bundled (and the local `auth:schema` script, which still loads `src/lib/auth.ts`) with a "module not found" error.
240
240
 
241
241
  Stick to runtime built-ins for ID generation, hashing, and similar primitives:
242
242
 
@@ -247,7 +247,7 @@ Stick to runtime built-ins for ID generation, hashing, and similar primitives:
247
247
  | Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |
248
248
  | Time | `Date.now()`, `new Date().toISOString()` |
249
249
 
250
- `drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.
250
+ `drizzle-orm` is always a dependency of the generated project, so `eq`, `and`, `inArray`, etc. are safe to import.
251
251
 
252
252
  ## Throw semantics
253
253
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.16",
3
+ "version": "0.66.18",
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",