@quickback-dev/cli 0.16.5 → 0.17.1

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 (114) hide show
  1. package/README.md +7 -3
  2. package/dist/commands/compile.d.ts.map +1 -1
  3. package/dist/commands/compile.js +12 -48
  4. package/dist/commands/compile.js.map +1 -1
  5. package/dist/commands/create.d.ts +20 -0
  6. package/dist/commands/create.d.ts.map +1 -1
  7. package/dist/commands/create.js +216 -151
  8. package/dist/commands/create.js.map +1 -1
  9. package/dist/commands/login.d.ts +4 -2
  10. package/dist/commands/login.d.ts.map +1 -1
  11. package/dist/commands/login.js +25 -17
  12. package/dist/commands/login.js.map +1 -1
  13. package/dist/commands/start.d.ts +20 -0
  14. package/dist/commands/start.d.ts.map +1 -0
  15. package/dist/commands/start.js +163 -0
  16. package/dist/commands/start.js.map +1 -0
  17. package/dist/commands/whoami.d.ts.map +1 -1
  18. package/dist/commands/whoami.js +5 -4
  19. package/dist/commands/whoami.js.map +1 -1
  20. package/dist/docs/content.js +37 -37
  21. package/dist/docs/content.js.map +1 -1
  22. package/dist/index.js +27 -10
  23. package/dist/index.js.map +1 -1
  24. package/dist/lib/api-client.js +1 -1
  25. package/dist/lib/api-client.js.map +1 -1
  26. package/dist/lib/api-client.test.js +15 -0
  27. package/dist/lib/api-client.test.js.map +1 -1
  28. package/dist/lib/auth.d.ts +39 -3
  29. package/dist/lib/auth.d.ts.map +1 -1
  30. package/dist/lib/auth.js +57 -3
  31. package/dist/lib/auth.js.map +1 -1
  32. package/dist/lib/drizzle-meta-routing.test.js +16 -3
  33. package/dist/lib/drizzle-meta-routing.test.js.map +1 -1
  34. package/dist/lib/file-loader.d.ts +6 -4
  35. package/dist/lib/file-loader.d.ts.map +1 -1
  36. package/dist/lib/file-loader.js +30 -27
  37. package/dist/lib/file-loader.js.map +1 -1
  38. package/dist/lib/file-loader.test.js +16 -7
  39. package/dist/lib/file-loader.test.js.map +1 -1
  40. package/dist/skill/docs/changelog.md +145 -0
  41. package/dist/skill/docs/compiler/config/providers.md +87 -0
  42. package/dist/skill/docs/compiler/config/single-tenant.md +5 -11
  43. package/dist/skill/docs/compiler/definitions/access.md +43 -57
  44. package/dist/skill/docs/compiler/definitions/feature.md +7 -11
  45. package/dist/skill/docs/compiler/definitions/firewall.md +2 -4
  46. package/dist/skill/docs/compiler/definitions/guards.md +16 -18
  47. package/dist/skill/docs/compiler/definitions/index.md +10 -14
  48. package/dist/skill/docs/compiler/definitions/masking.md +6 -6
  49. package/dist/skill/docs/compiler/definitions/read.md +6 -11
  50. package/dist/skill/docs/compiler/definitions/schema.md +18 -18
  51. package/dist/skill/docs/compiler/definitions/views.md +3 -5
  52. package/dist/skill/docs/compiler/getting-started/full-example.md +6 -8
  53. package/dist/skill/docs/compiler/getting-started/hand-crafted.md +3 -5
  54. package/dist/skill/docs/compiler/getting-started/index.md +23 -20
  55. package/dist/skill/docs/compiler/getting-started/patterns.md +19 -31
  56. package/dist/skill/docs/compiler/getting-started/template-blog.md +6 -10
  57. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +3 -5
  58. package/dist/skill/docs/compiler/getting-started/template-empty.md +3 -5
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +29 -23
  60. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +12 -14
  61. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +5 -2
  62. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +5 -7
  63. package/dist/skill/docs/compiler/troubleshooting.md +10 -0
  64. package/dist/skill/docs/stack/auth/security.md +69 -0
  65. package/dist/skill/docs/stack/cms/actions.md +28 -0
  66. package/dist/skill/docs/stack/cms/connecting.md +2 -2
  67. package/dist/skill/docs/stack/cms/index.md +2 -2
  68. package/dist/skill/docs/stack/cms/record-layouts.md +19 -19
  69. package/dist/skill/docs/stack/cms/schema-format.md +33 -3
  70. package/dist/skill/docs/stack/cms/schema-registry.md +22 -2
  71. package/dist/skill/docs/stack/cms/security.md +10 -12
  72. package/dist/skill/docs/stack/cms/table-views.md +1 -1
  73. package/dist/skill/docs/stack/realtime/durable-objects.md +46 -5
  74. package/dist/skill/docs/stack/realtime/index.md +20 -3
  75. package/dist/skill/docs/stack/realtime/using-realtime.md +8 -6
  76. package/dist/skill/docs/stack/vector/embeddings.md +7 -6
  77. package/package.json +1 -1
  78. package/src/skill/docs/changelog.md +145 -0
  79. package/src/skill/docs/compiler/config/providers.md +87 -0
  80. package/src/skill/docs/compiler/config/single-tenant.md +5 -11
  81. package/src/skill/docs/compiler/definitions/access.md +43 -57
  82. package/src/skill/docs/compiler/definitions/feature.md +7 -11
  83. package/src/skill/docs/compiler/definitions/firewall.md +2 -4
  84. package/src/skill/docs/compiler/definitions/guards.md +16 -18
  85. package/src/skill/docs/compiler/definitions/index.md +10 -14
  86. package/src/skill/docs/compiler/definitions/masking.md +6 -6
  87. package/src/skill/docs/compiler/definitions/read.md +6 -11
  88. package/src/skill/docs/compiler/definitions/schema.md +18 -18
  89. package/src/skill/docs/compiler/definitions/views.md +3 -5
  90. package/src/skill/docs/compiler/getting-started/full-example.md +6 -8
  91. package/src/skill/docs/compiler/getting-started/hand-crafted.md +3 -5
  92. package/src/skill/docs/compiler/getting-started/index.md +23 -20
  93. package/src/skill/docs/compiler/getting-started/patterns.md +19 -31
  94. package/src/skill/docs/compiler/getting-started/template-blog.md +6 -10
  95. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +3 -5
  96. package/src/skill/docs/compiler/getting-started/template-empty.md +3 -5
  97. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +29 -23
  98. package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +12 -14
  99. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +5 -2
  100. package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +5 -7
  101. package/src/skill/docs/compiler/troubleshooting.md +10 -0
  102. package/src/skill/docs/stack/auth/security.md +69 -0
  103. package/src/skill/docs/stack/cms/actions.md +28 -0
  104. package/src/skill/docs/stack/cms/connecting.md +2 -2
  105. package/src/skill/docs/stack/cms/index.md +2 -2
  106. package/src/skill/docs/stack/cms/record-layouts.md +19 -19
  107. package/src/skill/docs/stack/cms/schema-format.md +33 -3
  108. package/src/skill/docs/stack/cms/schema-registry.md +22 -2
  109. package/src/skill/docs/stack/cms/security.md +10 -12
  110. package/src/skill/docs/stack/cms/table-views.md +1 -1
  111. package/src/skill/docs/stack/realtime/durable-objects.md +46 -5
  112. package/src/skill/docs/stack/realtime/index.md +20 -3
  113. package/src/skill/docs/stack/realtime/using-realtime.md +8 -6
  114. package/src/skill/docs/stack/vector/embeddings.md +7 -6
@@ -15,6 +15,7 @@ interface SchemaRegistry {
15
15
  features: Record<string, string[]>;
16
16
  tables: Record<string, TableMeta>;
17
17
  tablesByFeature: Record<string, string[]>;
18
+ featureActions: Record<string, ActionMeta[]>;
18
19
  pages: Record<string, PageMeta>;
19
20
  pagesByFeature: Record<string, string[]>;
20
21
  }
@@ -29,6 +30,7 @@ interface SchemaRegistry {
29
30
  | `features` | Map of feature name to array of source file names |
30
31
  | `tables` | Map of camelCase table name to full table metadata |
31
32
  | `tablesByFeature` | Map of feature name to array of table names in that feature |
33
+ | `featureActions` | Map of feature name to standalone actions not attached to one table |
32
34
  | `pages` | Map of page slug to full page metadata |
33
35
  | `pagesByFeature` | Map of feature name to array of page slugs in that feature |
34
36
 
@@ -44,6 +46,10 @@ interface TableMeta {
44
46
  columns: ColumnMeta[];
45
47
  firewall: Record<string, unknown>;
46
48
  crud: Record<string, CrudConfig>;
49
+ create?: WriteOperationConfig | false;
50
+ update?: WriteOperationConfig | false;
51
+ delete?: WriteOperationConfig | false;
52
+ upsert?: WriteOperationConfig | false;
47
53
  guards: GuardsConfig;
48
54
  masking: Record<string, MaskingRule>;
49
55
  views: Record<string, ViewConfig>;
@@ -64,12 +70,13 @@ interface TableMeta {
64
70
  | `feature` | Parent feature name (e.g., `"accounting"`) |
65
71
  | `columns` | Ordered array of column metadata |
66
72
  | `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |
67
- | `crud` | Per-operation (create, read, update, delete) access config |
73
+ | `crud` | Legacy normalized write config kept for backwards compatibility |
74
+ | `create` / `update` / `delete` / `upsert` | Flat write-operation aliases mirroring the authored `defineTable(...)` DSL |
68
75
  | `guards` | Field-level create/update/immutable/protected rules |
69
76
  | `masking` | Per-field masking rules keyed by column name |
70
77
  | `views` | Named column projections keyed by view name |
71
78
  | `validation` | Per-field validation rules keyed by column name |
72
- | `actions` | Array of action definitions for this table |
79
+ | `actions` | Array of action definitions scoped to this table |
73
80
  | `displayColumn` | Column used as human-readable label (auto-detected or explicit) |
74
81
  | `defaultSort` | Default sort for CMS table list view (e.g., `{ field: "createdAt", order: "desc" }`) |
75
82
  | `inputHints` | Map of column name to preferred CMS input type (e.g., `"richtext"`, `"select"`, `"textarea"`, `"checkbox"`) |
@@ -114,6 +121,15 @@ interface CrudConfig {
114
121
  mode?: string;
115
122
  }
116
123
 
124
+ interface WriteOperationConfig extends CrudConfig {
125
+ defaults?: Record<string, unknown>;
126
+ computed?: Record<string, unknown>;
127
+ fields?: string[];
128
+ maxBatchSize?: number;
129
+ allowFailFast?: boolean;
130
+ batch?: false | Record<string, unknown>;
131
+ }
132
+
117
133
  interface AccessRule {
118
134
  roles?: string[];
119
135
  or?: Array<{
@@ -130,6 +146,9 @@ interface AccessRule {
130
146
  | `access.or` | Alternative access conditions (any must match) |
131
147
  | `access.record` | Record-level conditions for access |
132
148
  | `mode` | Operation mode (e.g., `"batch"` for bulk create) |
149
+ | `defaults` / `computed` | Create-time defaults and computed field metadata |
150
+ | `maxBatchSize` / `allowFailFast` | Batch-write controls when the config describes a batch operation |
151
+ | `batch` | Nested batch config for the flat `create` / `update` / `delete` / `upsert` aliases |
133
152
 
134
153
  ## GuardsConfig
135
154
 
@@ -179,6 +198,8 @@ interface CmsConfig {
179
198
  destructive?: boolean;
180
199
  category?: string;
181
200
  hidden?: boolean;
201
+ placement?: 'feature' | 'tables';
202
+ tables?: string[];
182
203
  successMessage?: string;
183
204
  onSuccess?: 'refresh' | 'redirect:list' | 'close';
184
205
  order?: number;
@@ -204,7 +225,16 @@ interface ActionInputField {
204
225
  | `method` | HTTP method (defaults to POST) |
205
226
  | `responseType` | `"file"` for download responses |
206
227
  | `sideEffects` | `"sync"` for actions with synchronous side effects |
207
- | `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, successMessage, onSuccess, order) |
228
+ | `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, placement, tables, successMessage, onSuccess, order) |
229
+
230
+ ### CmsConfig placement rules
231
+
232
+ `placement` is only relevant for standalone actions in multi-table features:
233
+
234
+ - `"feature"` shows the action in the toolbar for every table in the feature.
235
+ - `"tables"` shows the action only for the tables listed in `tables`.
236
+
237
+ If the action is already unambiguously table-scoped, the compiler can infer placement and `placement` is optional.
208
238
 
209
239
  ### ActionInputField
210
240
 
@@ -28,6 +28,7 @@ The top-level structure of `schema-registry.json`:
28
28
  "features": { ... },
29
29
  "tables": { ... },
30
30
  "tablesByFeature": { ... },
31
+ "featureActions": { ... },
31
32
  "pages": { ... },
32
33
  "pagesByFeature": { ... }
33
34
  }
@@ -42,6 +43,7 @@ The top-level structure of `schema-registry.json`:
42
43
  | `features` | `Record<string, string[]>` | Feature name to file list mapping |
43
44
  | `tables` | `Record<string, TableMeta>` | Table name to full metadata |
44
45
  | `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |
46
+ | `featureActions` | `Record<string, ActionMeta[]>` | Feature name to standalone actions not owned by one table |
45
47
  | `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |
46
48
  | `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |
47
49
 
@@ -56,7 +58,11 @@ interface TableMeta {
56
58
  feature: string; // Parent feature name
57
59
  columns: ColumnMeta[]; // All columns including audit fields
58
60
  firewall: Record<string, unknown>; // Tenant isolation config
59
- crud: Record<string, CrudConfig>; // Per-operation access rules
61
+ crud: Record<string, CrudConfig>; // Legacy normalized write surface
62
+ create?: WriteOperationConfig | false; // Flat create config
63
+ update?: WriteOperationConfig | false; // Flat update config
64
+ delete?: WriteOperationConfig | false; // Flat delete config
65
+ upsert?: WriteOperationConfig | false; // Flat upsert config
60
66
  guards: {
61
67
  createable: string[]; // Fields allowed on create
62
68
  updatable: string[]; // Fields allowed on update
@@ -66,12 +72,26 @@ interface TableMeta {
66
72
  masking: Record<string, MaskingRule>; // Per-field masking rules
67
73
  views: Record<string, ViewConfig>; // Named column projections
68
74
  validation: Record<string, ValidationRule>; // Per-field validation
69
- actions: ActionMeta[]; // Available actions for this table
75
+ actions: ActionMeta[]; // Table-scoped actions for this table
70
76
  displayColumn?: string; // Human-readable label column
71
77
  internal?: boolean; // Hidden from CMS sidebar when true
72
78
  }
73
79
  ```
74
80
 
81
+ `create`, `update`, `delete`, and `upsert` mirror the preferred flat DSL from `defineTable(...)`. The legacy `crud` block is still emitted for backwards compatibility with older consumers.
82
+
83
+ ## Feature Actions
84
+
85
+ Standalone actions do not always belong to a single table. When an action is attached to a multi-table feature root, the compiler emits it under `featureActions[featureName]` instead of duplicating it across every table.
86
+
87
+ ```typescript
88
+ interface SchemaRegistry {
89
+ featureActions: Record<string, ActionMeta[]>;
90
+ }
91
+ ```
92
+
93
+ The CMS uses `featureActions` for toolbar-style actions that apply to the feature as a whole. Use `cms.placement` on standalone actions to control whether they show for the whole feature or only selected tables.
94
+
75
95
  > **Internal Tables**
76
96
  >
77
97
  > Tables without a `defineTable()` resource config are marked `internal: true` and hidden from the CMS sidebar. These are typically join tables or system tables.
@@ -15,10 +15,10 @@ Under the default `access: "admin"`, the compiler emits server-side gates on eve
15
15
  1. **Account UI** — the "Go to CMS" button is hidden.
16
16
  2. **CMS SPA shell** — the Worker checks `ctx.userRole === "admin"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.
17
17
  3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.
18
- 4. **`custom_view` CRUD** — the CMS-internal saved-views table uses `userRole: ["admin"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.
18
+ 4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: ["admin"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.
19
19
  5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.
20
20
 
21
- Your resource CRUD endpoints keep whatever `crud.access.roles` you defined — they're the app's data API and unaffected by the CMS gate.
21
+ Your resource API endpoints keep whatever `read`, `create`, `update`, `delete`, or `upsert` access rules you defined — they're the app's data API and unaffected by the CMS gate.
22
22
 
23
23
  ## The Four Layers
24
24
 
@@ -27,7 +27,7 @@ Quickback enforces security through four complementary layers:
27
27
  | Layer | Purpose | CMS Behavior |
28
28
  |-------|---------|-------------|
29
29
  | **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |
30
- | **CRUD Access** | Per-operation role requirements | Buttons hidden when role lacks permission |
30
+ | **Operation Access** | Per-operation role requirements | Buttons hidden when role lacks permission |
31
31
  | **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |
32
32
  | **Masking** | Sensitive field redaction | Masked values with lock icons per role |
33
33
 
@@ -36,20 +36,18 @@ Quickback enforces security through four complementary layers:
36
36
  The CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:
37
37
 
38
38
  - **owner** — Full access to all operations and data
39
- - **admin** — Elevated access, typically all CRUD and most actions
39
+ - **admin** — Elevated access, typically all write operations and most actions
40
40
  - **member** — Standard access with restrictions on sensitive data and destructive actions
41
41
 
42
- ### CRUD Button Visibility
42
+ ### Operation Button Visibility
43
43
 
44
- CRUD operation buttons are shown or hidden based on the current role's access:
44
+ Create, edit, and delete buttons are shown or hidden based on the current role's access:
45
45
 
46
46
  ```typescript
47
- crud: {
48
- create: { access: { roles: ['admin', 'owner'] } },
49
- read: { access: { roles: ['member', 'admin', 'owner'] } },
50
- update: { access: { roles: ['admin', 'owner'] } },
51
- delete: { access: { roles: ['owner'] } },
52
- }
47
+ read: { access: { roles: ['member', 'admin', 'owner'] } },
48
+ create: { access: { roles: ['admin', 'owner'] } },
49
+ update: { access: { roles: ['admin', 'owner'] } },
50
+ delete: { access: { roles: ['owner'] } },
53
51
  ```
54
52
 
55
53
  With the config above:
@@ -25,7 +25,7 @@ The three-dot menu on each row provides:
25
25
  | Custom actions | Filtered by role + record state | Run actions like approve, void, post |
26
26
  | Delete | When role has `delete` access | Delete with confirmation |
27
27
 
28
- Actions are filtered by the current role's CRUD permissions and the action's access conditions. For example, an "approve" action that requires `status === "pending"` only appears on pending records.
28
+ Actions are filtered by the current role's write permissions and the action's access conditions. For example, an "approve" action that requires `status === "pending"` only appears on pending records.
29
29
 
30
30
  ## Data Table Mode
31
31
 
@@ -2,6 +2,13 @@
2
2
 
3
3
  Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.
4
4
 
5
+ The targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:
6
+
7
+ - string target: historical `organizationId` shorthand
8
+ - object target: `{ scopeKey?, organizationId?, userId? }`
9
+
10
+ That means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.
11
+
5
12
  ## Enabling Realtime
6
13
 
7
14
  Add `realtime` configuration to individual table definitions:
@@ -35,6 +42,24 @@ export default defineTable(applications, {
35
42
 
36
43
  When any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.
37
44
 
45
+ At the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need relationship-authorized resource tickets:
46
+
47
+ ```typescript
48
+ providers: {
49
+ database: defineDatabase("cloudflare-d1", {
50
+ realtime: {
51
+ wsTicket: {
52
+ role: "attendee",
53
+ requestField: "eventId",
54
+ scopeTable: "events",
55
+ },
56
+ },
57
+ }),
58
+ }
59
+ ```
60
+
61
+ That tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.
62
+
38
63
  ## When auto-broadcast fires (and when you call it manually)
39
64
 
40
65
  Quickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.
@@ -74,6 +99,18 @@ export const execute: ActionExecutor = async ({ db, ctx, input }) => {
74
99
  };
75
100
  ```
76
101
 
102
+ For explicit targeting, pass an object instead of the historical org string:
103
+
104
+ ```typescript
105
+ await realtime.broadcast("event-page-updated", payload, {
106
+ scopeKey: `events:${input.eventId}`,
107
+ });
108
+
109
+ await realtime.broadcast("dm", payload, {
110
+ userId: recipientId,
111
+ });
112
+ ```
113
+
77
114
  ## Event Format
78
115
 
79
116
  Quickback broadcasts events in a structured JSON format for easy client-side handling.
@@ -207,7 +244,7 @@ await realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {
207
244
  });
208
245
  ```
209
246
 
210
- If `targetRoles` is not specified, all authenticated users in the organization receive the broadcast.
247
+ If `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.
211
248
 
212
249
  ## Per-Role Field Masking
213
250
 
@@ -262,13 +299,17 @@ Quickback uses **ticket-based authentication** for WebSocket connections. The cl
262
299
  // 1. Get a ws-ticket from your API (requires session auth)
263
300
  const response = await fetch('/broadcast/v1/ws-ticket', {
264
301
  method: 'POST',
265
- headers: { Authorization: `Bearer ${sessionToken}` },
302
+ headers: {
303
+ Authorization: `Bearer ${sessionToken}`,
304
+ 'Content-Type': 'application/json',
305
+ },
306
+ body: JSON.stringify({ eventId: 'evt_123' }),
266
307
  });
267
308
  const { wsTicket } = await response.json();
268
309
 
269
310
  // 2. Connect with ticket as URL param
270
311
  const ws = new WebSocket(
271
- `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`
312
+ `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`
272
313
  );
273
314
 
274
315
  ws.onopen = () => {
@@ -348,8 +389,8 @@ new_classes = ["Broadcaster"]
348
389
  ```
349
390
 
350
391
  1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.
351
- 2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade — no HTTP round-trip.
352
- 3. **API broadcasts** — After CRUD ops, the API calls the Broadcaster DO directly via its binding (in-process, no network hop).
392
+ 2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.
393
+ 3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.
353
394
 
354
395
  ## Best Practices
355
396
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:
4
4
 
5
- - **`/broadcast/v1/*` — server fan-out.** One DO instance per organization. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this org that something changed." Documented on this page.
5
+ - **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this shared scope that something changed." The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.
6
6
  - **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).
7
7
 
8
8
  Both share the same auth model and ride on the same compiled worker; they solve different problems.
@@ -31,17 +31,18 @@ Both share the same auth model and ride on the same compiled worker; they solve
31
31
  The Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).
32
32
 
33
33
  1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.
34
- 2. **Broadcaster (Durable Object)** — Manages WebSocket connections per organization. One instance per org.
34
+ 2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.
35
35
  3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.
36
36
 
37
37
  ## Key Features
38
38
 
39
39
  | Feature | Description |
40
40
  |---------|-------------|
41
- | Organization-scoped | Each org gets its own Durable Object instance |
41
+ | Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |
42
42
  | Role-based filtering | Only send events to users with matching roles |
43
43
  | Per-role masking | Different users see different field values based on their role |
44
44
  | User-specific targeting | Send events to a specific user within an org |
45
+ | Resource-scoped tickets | Reuse authz relationship roles to mint scope-bound ws tickets |
45
46
  | Custom broadcasts | Arbitrary events beyond CRUD |
46
47
  | Custom namespaces | `defineRealtime()` for type-safe event helpers |
47
48
  | Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |
@@ -66,6 +67,22 @@ export default defineTable(applications, {
66
67
 
67
68
  And enable the realtime binding in your database config. The compiler generates the Durable Object class, helper functions, and wrangler bindings — all within your main worker.
68
69
 
70
+ ```typescript
71
+ providers: {
72
+ database: defineDatabase("cloudflare-d1", {
73
+ realtime: {
74
+ wsTicket: {
75
+ role: "attendee",
76
+ requestField: "eventId",
77
+ scopeTable: "events",
78
+ },
79
+ },
80
+ }),
81
+ }
82
+ ```
83
+
84
+ With that config, `/broadcast/v1/ws-ticket` can authenticate the caller, verify the declared authz relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` channel.
85
+
69
86
  ## Pages
70
87
 
71
88
  - **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces
@@ -28,18 +28,19 @@ const response = await fetch("/broadcast/v1/ws-ticket", {
28
28
  Authorization: `Bearer ${sessionToken}`,
29
29
  "Content-Type": "application/json",
30
30
  },
31
+ body: JSON.stringify({ eventId: "evt_123" }), // optional; used by resource-scoped wsTicket config
31
32
  });
32
33
  const { wsTicket, expiresIn } = await response.json();
33
34
  // expiresIn = 60 (seconds)
34
35
  ```
35
36
 
36
- The ticket is a short-lived (60-second) HMAC-signed token containing your userId, organizationId, and roles.
37
+ The ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.
37
38
 
38
39
  ### Step 2: Connect with Ticket
39
40
 
40
41
  ```typescript
41
42
  const ws = new WebSocket(
42
- `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`
43
+ `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`
43
44
  );
44
45
 
45
46
  ws.onopen = () => {
@@ -148,11 +149,11 @@ Masking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency.
148
149
 
149
150
  ### User-Specific Events
150
151
 
151
- Events can target a specific user within an organization. Only that user receives the broadcast — all other connections in the org are skipped.
152
+ Events can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.
152
153
 
153
- ### Organization Isolation
154
+ ### Scope Isolation
154
155
 
155
- Each organization has its own Durable Object instance. Users can only subscribe to events in organizations they belong to, enforced during authentication.
156
+ Each WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.
156
157
 
157
158
  ## Reconnection
158
159
 
@@ -164,11 +165,12 @@ async function connect() {
164
165
  const res = await fetch("/broadcast/v1/ws-ticket", {
165
166
  method: "POST",
166
167
  headers: { Authorization: `Bearer ${sessionToken}` },
168
+ body: JSON.stringify({ eventId: "evt_123" }),
167
169
  });
168
170
  const { wsTicket } = await res.json();
169
171
 
170
172
  const ws = new WebSocket(
171
- `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`
173
+ `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`
172
174
  );
173
175
 
174
176
  ws.onclose = () => {
@@ -22,10 +22,8 @@ export default defineTable(jobs, {
22
22
  metadata: ['department'], // Metadata for Vectorize index
23
23
  },
24
24
 
25
- crud: {
26
- create: { access: { roles: ['recruiter'] } },
27
- update: { access: { roles: ['recruiter'] } },
28
- },
25
+ create: { access: { roles: ['recruiter'] } },
26
+ update: { access: { roles: ['recruiter'] } },
29
27
  });
30
28
  ```
31
29
 
@@ -94,7 +92,7 @@ onUpdate: ['description', 'title']
94
92
 
95
93
  ## Generic Embeddings API
96
94
 
97
- In addition to automatic embeddings on CRUD operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.
95
+ 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.
98
96
 
99
97
  ### POST /api/v1/embeddings
100
98
 
@@ -290,7 +288,10 @@ export default feature("jobs", {
290
288
  embedding: q.text().optional(),
291
289
  },
292
290
  firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
293
- crud: { list: {}, get: {}, create: {}, update: {}, delete: {} },
291
+ read: {},
292
+ create: {},
293
+ update: {},
294
+ delete: {},
294
295
  });
295
296
  ```
296
297
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.16.5",
3
+ "version": "0.17.1",
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",
@@ -4,6 +4,151 @@ Release notes for the Quickback compiler, CLI, and platform.
4
4
 
5
5
  ---
6
6
 
7
+ ## v0.16.10 — May 14, 2026
8
+
9
+ ### Cloudflare D1 now gets a compiler-native Drizzle safety layer
10
+
11
+ Quickback's `cloudflare-d1` provider no longer treats `drizzle-kit generate` output as deploy-ready SQL by default.
12
+
13
+ **A D1-specific post-generation pass now runs inside the compiler.** After Drizzle emits auth, features, webhooks, or audit migrations, the D1 provider inspects the generated SQL before the compile finishes:
14
+
15
+ - **Better Auth cleanup for retired managed tables** is stripped instead of being shipped as raw `DROP TABLE` statements.
16
+ - **Drop-only cleanup migrations** are reordered child-first when foreign-key dependencies require it.
17
+ - **Every generated D1 migration directory** is replayed against SQLite during compile, so a D1-breaking migration fails before `wrangler d1 migrations apply`.
18
+
19
+ This closes the class of failures where a compile succeeded but the later deploy exploded inside Cloudflare D1 because SQLite foreign-key enforcement rejected Drizzle's destructive cleanup ordering.
20
+
21
+ Pinned by `d1-drizzle-helper.test.ts` plus the existing compile-runner and migration-order regressions.
22
+
23
+ ---
24
+
25
+ ## v0.16.9 — May 13, 2026
26
+
27
+ ### Resource-scoped realtime tickets and a shared broadcast targeting model
28
+
29
+ Quickback's realtime layer no longer assumes every WebSocket subscriber is an org member.
30
+
31
+ **`providers.database.config.realtime` can now be object-shaped.** `realtime: true` still enables the historical org-scoped broadcaster, but projects can now opt into a declarative ws-ticket policy:
32
+
33
+ ```ts
34
+ providers: {
35
+ database: defineDatabase("cloudflare-d1", {
36
+ realtime: {
37
+ wsTicket: {
38
+ role: "attendee",
39
+ requestField: "eventId",
40
+ scopeTable: "events",
41
+ },
42
+ },
43
+ }),
44
+ }
45
+ ```
46
+
47
+ That lets the generated `/broadcast/v1/ws-ticket` route authenticate the caller with Better Auth, evaluate a declared authz relationship role like `attendee` against the request body, and mint a short-lived Quickback websocket ticket for the resolved resource scope. `scopeTable` is the parent resource that defines the broadcast channel; the relationship/junction table remains the proof of access.
48
+
49
+ **Realtime and broadcast now share one targeting model.** The generated helper and Broadcaster both route by `scopeKey || organizationId || userId`. Historical string targets still mean "organizationId shorthand", so existing code like `realtime.insert("claims", record, ctx.activeOrgId!)` keeps working. New explicit targets can scope a broadcast to a resource or a single user:
50
+
51
+ ```ts
52
+ await realtime.broadcast("event-page-updated", payload, {
53
+ scopeKey: "events:evt_123",
54
+ });
55
+
56
+ await realtime.broadcast("dm", payload, {
57
+ userId: recipientId,
58
+ });
59
+ ```
60
+
61
+ **WebSocket tickets are still Quickback-minted, not Better Auth tokens.** The front door remains your normal Better Auth cookie/bearer/JWT auth. After authorization succeeds, Quickback signs its own 60-second ws ticket and the Broadcaster verifies that ticket at upgrade time. Inline and separate broadcast-worker modes now both reuse `BETTER_AUTH_SECRET` for ticket signing so there is no extra secret to configure during beta.
62
+
63
+ Pinned by `realtime-ws-ticket-scope.test.ts`, plus the existing realtime routing and relationship-access regression suites.
64
+
65
+ ---
66
+
67
+ ## v0.16.8 — May 13, 2026
68
+
69
+ ### Auth transport separation, cookie-backed CSRF middleware, and first-class Wrangler observability
70
+
71
+ Three security/runtime hardenings landed together.
72
+
73
+ **Exactly one auth transport per request.** Generated auth middleware now treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as separate auth methods and rejects any mixed request with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted, which removes ambiguous precedence rules from the hot path and keeps machine-to-machine auth explicit.
74
+
75
+ **Cookie-backed mutating requests now get a CSRF gate.** Generated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests when the caller is relying on cookies. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional and origin validation has to carry the load.
76
+
77
+ **Wrangler observability is now a first-class compiler surface.** `providers.runtime.config.observability` no longer stops at `enabled: true`. The compiler now understands top-level Workers Logs sampling plus nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, and emits the matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML. The config validator also rejects ambiguous double-mapping of Workers Logs sampling (`observability.headSamplingRate` plus `observability.logs.headSamplingRate`) and requires explicit per-signal `enabled` flags when trace/log export settings are present.
78
+
79
+ Pinned by `config-wiring.test.ts`, `csrf-middleware.test.ts`, `cookie-security.test.ts`, `auth-api-key-query-param.test.ts`, and the deployed negative-auth regression checks.
80
+
81
+ ---
82
+
83
+ ## v0.16.7 — May 12, 2026
84
+
85
+ ### Bearer wins over cookie, and bearer plugin defaults to `requireSignature: true`
86
+
87
+ Two hardenings to the auth middleware closing a mixed-credential ambiguity and a session-token replay path.
88
+
89
+ **Bearer-vs-cookie precedence.** A request that carries both an `Authorization` header and a session `Cookie` now resolves entirely from the bearer — the cookie is dropped before `getSession()` runs. Previously the api-key and JWT fast-paths already short-circuited above cookie resolution, but session-token bearers fell through to Better Auth's `getSession()` where cookie auth resolved first and the bearer was silently ignored. That meant a request with `Cookie: alice` + `Authorization: Bearer bob-session-token` would resolve as alice, silently dropping bob's explicit credential. The inconsistency between bearer flavors (api-key/JWT bearer-wins, session-bearer cookie-wins) was the bug; making bearer win universally aligns with Better Auth's own framing of the plugin as "intended only for APIs that don't support cookies, or require Bearer tokens for authentication." Cookie remains the resolution path when no `Authorization` header is present, so browser SPA flows are unchanged.
90
+
91
+ **`requireSignature: true` on the bearer plugin.** Better Auth's `bearer` plugin defaults `requireSignature` to `false`, which means the session token emitted in the CORS-exposed `set-auth-token` response header is a literal session secret — anyone who sees it in a proxy access log, a browser dev-tools panel, or a misrouted `Referer` can replay it. Quickback now emits `bearer({ requireSignature: true })` so Better Auth signs the token server-side with `BETTER_AUTH_SECRET` and rejects unsigned bearers on verify. JWT bearers and agent-auth bearers are independently signed and unaffected. Projects that genuinely need unsigned bearers can override by passing `bearer: { requireSignature: false }` in `providers.auth.config.plugins` — user-supplied options merge on top of the secure default.
92
+
93
+ See [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence) for the full threat model and the four credential flavors Quickback supports.
94
+
95
+ Pinned by `agent-auth.test.ts` (asserts the `bearer({ requireSignature: true })` emission shape).
96
+
97
+ ---
98
+
99
+ ## v0.16.5 — May 12, 2026
100
+
101
+ ### Flat write DSL is now the preferred authored shape, with compatibility aliases preserved
102
+
103
+ Quickback's resource DSL had drifted into an awkward split: reads already lived under `read`, while writes still sat under a nested `crud` block that no longer represented the full CRUD surface. That shape was technically supported, but it was teaching the wrong mental model.
104
+
105
+ The preferred authored surface is now flat at the table level:
106
+
107
+ ```ts
108
+ defineTable(customers, {
109
+ read: { ... },
110
+ create: { access: { roles: ["admin"] } },
111
+ update: { access: { roles: ["admin"] } },
112
+ delete: { access: { roles: ["admin"] }, mode: "soft" },
113
+ upsert: { access: { roles: ["admin"] } },
114
+ guards: { ... },
115
+ });
116
+ ```
117
+
118
+ `crud` and top-level `put` still compile in v0.16.5 as deprecated compatibility aliases. The compiler now normalizes the flat shape into the existing internal write surface, rejects mixed usage on the same resource, and warns when legacy aliases are used. Generated outputs that expose authored table policy — including `schema-registry.json` — now emit flat `create` / `update` / `delete` / `upsert` aliases alongside the legacy normalized `crud` block so older consumers keep working during the transition.
119
+
120
+ ### CMS standalone actions now have an explicit placement model for multi-table features
121
+
122
+ Standalone actions were unambiguous for single-table features and for clearly table-scoped paths, but multi-table feature-root actions had no clean place to live in the CMS metadata contract. The API knew what the action was; the CMS had to guess where to render it.
123
+
124
+ The contract is now explicit:
125
+
126
+ - `cms.placement: "feature"` shows the standalone action in the table toolbar for every table in the feature
127
+ - `cms.placement: "tables"` with `cms.tables` shows it only on specific tables
128
+ - `cms.hidden: true` keeps it API-only
129
+
130
+ The compiler now emits feature-root standalone actions under a new `featureActions` bucket in `schema-registry.json` instead of duplicating them across every table entry. The CMS merges those `featureActions` into table toolbars according to placement, while record action bars remain table-scoped by default. Ambiguous multi-table feature-root standalone actions without placement now compile with a warning instead of silently landing in the wrong UI surface.
131
+
132
+ ### `openapi.types` can now keep colocated SPA clients in sync from a single compile
133
+
134
+ `quickback compile` already emitted `openapi.json` and a generated `api-types.gen.ts`, but projects with a colocated SPA often kept a second copy under something like `apps/web/src/lib/api-types.gen.ts`. That second file drifted unless a separate `codegen:api` step was run after every compile.
135
+
136
+ `openapi.types` now accepts a string array as well as `true`, `false`, or a single custom path. One compile can write the same generated types file to multiple locations, for example:
137
+
138
+ ```ts
139
+ openapi: {
140
+ types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],
141
+ }
142
+ ```
143
+
144
+ This keeps the API root artifact and any colocated SPA copy aligned without a second codegen command. The bundled Quickback CMS and Account SPAs do not use `api-types.gen.ts` themselves — CMS is schema-registry driven, and Account uses Better Auth plus hand-written fetch helpers — so this option is aimed at user-authored client apps that live beside the compiled API.
145
+
146
+ ### Generated route files and `schema-registry.json` are now emitted in a stable order
147
+
148
+ Back-to-back `quickback compile` runs could previously regenerate functionally identical route files or `schema-registry.json` with different ordering. The API behavior did not change, but the diff noise was real.
149
+
150
+ The compiler now normalizes discovery order before it builds action bundles, route files, and the schema registry. Identical logical input produces stable emitted artifacts, which means fewer no-op diffs after a recompile and cleaner review when something actually changed.
151
+
7
152
  ## v0.16.4 — May 12, 2026
8
153
 
9
154
  ### Compile didn't emit a migration — v0.16.3 corrupted drizzle snapshots, fixed + self-heal