or3-provider-sqlite 0.0.22 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,6 +45,8 @@ wake its ordinary sync pull immediately when the counter changes and use a
45
45
  one-minute safety pull while connected. Last-listener teardown stops the timer;
46
46
  unsupported notification routes retain normal gateway polling.
47
47
 
48
+ Background chat admissions emit the existing thread and user-message create hooks after commit when those rows are newly created. Replayed admissions do not emit them again; hook delivery failures do not fail admission.
49
+
48
50
  ## Atomic webhook registration quotas
49
51
 
50
52
  The webhook store advertises `registrationLimit: 'atomic-v1'`. `createWebhook(input, limit)` checks the user/workspace quota (or instance-wide admin quota) in the same immediate transaction as insertion. Independent connections share the limit; exhaustion throws `WEBHOOK_LIMIT_EXCEEDED`. The optional argument leaves non-quota internal calls unchanged. OR3 Chat requires this capability for registration; ship this provider change before integrating the coordinated host change.
@@ -224,7 +226,8 @@ All tables use snake_case aligned with the sync wire format.
224
226
  - **Snapshot**: captures canonical live rows and current tombstones at one `highWatermark`, then serves immutable, keyset-paginated pages ordered by `(tableName, pk, kind)`. Notification live rows are filtered to the session user.
225
227
  - **Cursor**: forward-only tracking per authenticated user and device within a workspace. Migration 028 changes the unique key so accounts sharing a browser device ID cannot claim each other’s acknowledgements. Legacy unowned rows are never adopted and expire through normal cursor GC.
226
228
  - **Retention safety**: tombstone and `change_log` GC is enabled only under the explicit `snapshot-v1` capability and deletes old revisions acknowledged by every registered device
227
- - **Notifications**: push forces `payload.user_id` to the session user; foreign notification writes are rejected; pull/snapshot omit other users' rows
229
+ - **Notifications**: push forces `payload.user_id` to the session user on puts and deletes; foreign notification writes are rejected. Successful deletes remain visible to the owner's other devices while pull/snapshot omit other users' rows.
230
+ - **Workspace Files/Trash admission**: a client without `workspaceItemCapability: 'v1'` cannot replace or delete a canonical post/project carrying workspace Files/Trash semantics, even if the submitted payload omits those fields. Native write transactions and the D1 atomic batch check canonical state before any operation or version allocation; a rejected batch returns HTTP 426 and leaves sibling writes unchanged.
228
231
 
229
232
  Snapshot continuations are bound to the capturing user and workspace, including
230
233
  backup snapshots. Each user retains at most four copies per workspace across
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
3
  "configKey": "or3-provider-sqlite",
4
- "version": "0.0.22",
4
+ "version": "0.0.23",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -101,12 +101,20 @@ function backgroundHistoryOpId(admission, stage) {
101
101
  const value = hex.join("");
102
102
  return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
103
103
  }
104
+ function fingerprintPayload(tableName, operation, payload) {
105
+ if (tableName !== "notifications" || operation !== "delete") return payload;
106
+ if (payload == null) return void 0;
107
+ if (typeof payload !== "object" || Array.isArray(payload)) return payload;
108
+ const intent = { ...payload };
109
+ delete intent.user_id;
110
+ return Object.keys(intent).length > 0 ? intent : void 0;
111
+ }
104
112
  function operationFingerprint(op) {
105
113
  return stableJson({
106
114
  tableName: op.tableName,
107
115
  operation: op.operation,
108
116
  pk: op.pk,
109
- payload: op.payload,
117
+ payload: fingerprintPayload(op.tableName, op.operation, op.payload),
110
118
  clock: op.stamp.clock,
111
119
  hlc: op.stamp.hlc,
112
120
  deviceId: op.stamp.deviceId
@@ -117,7 +125,7 @@ function changeLogFingerprint(row) {
117
125
  tableName: row.table_name,
118
126
  operation: row.op,
119
127
  pk: row.pk,
120
- payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
128
+ payload: fingerprintPayload(row.table_name, row.op, row.payload_json ? JSON.parse(row.payload_json) : void 0),
121
129
  clock: row.clock,
122
130
  hlc: row.hlc,
123
131
  deviceId: row.device_id
@@ -140,13 +148,50 @@ function scopeNotificationWrite(op, userId) {
140
148
  if (!userId) {
141
149
  return "Unauthorized: notification writes require a session user";
142
150
  }
143
- if (op.operation !== "put") return op;
144
151
  const payload = op.payload && typeof op.payload === "object" && !Array.isArray(op.payload) ? { ...op.payload } : {};
145
152
  if (payload.user_id !== void 0 && payload.user_id !== userId) {
146
153
  return "Forbidden: notification owner mismatch";
147
154
  }
148
155
  return { ...op, payload: { ...payload, user_id: userId } };
149
156
  }
157
+ const WORKSPACE_ITEM_UPDATE_REQUIRED = "OR3_WORKSPACE_ITEM_UPDATE_REQUIRED";
158
+ function workspaceItemUpdateRequired() {
159
+ return createError({
160
+ statusCode: 426,
161
+ statusMessage: "Update OR3 Chat to use workspace Files and Trash",
162
+ data: { code: WORKSPACE_ITEM_UPDATE_REQUIRED, requiredCapability: WORKSPACE_ITEM_CAPABILITY }
163
+ });
164
+ }
165
+ function workspaceItemCapabilityAssertion(op, workspaceId) {
166
+ const field = op.tableName === "posts" ? "meta" : "data";
167
+ const decoded = `CASE WHEN json_type(data_json, '$.${field}') = 'text'
168
+ THEN CASE WHEN json_valid(json_extract(data_json, '$.${field}'))
169
+ THEN json_extract(data_json, '$.${field}') ELSE 'null' END
170
+ ELSE COALESCE(json_extract(data_json, '$.${field}'), 'null') END`;
171
+ const semantics = op.tableName === "posts" ? `COALESCE(json_extract(data_json, '$.post_type'), json_extract(data_json, '$.postType')) = 'or3:file'
172
+ OR (json_type(metadata) = 'object' AND (
173
+ json_type(metadata, '$."or3.workspace-item"') IS NOT NULL
174
+ OR json_extract(metadata, '$.key') = 'or3.workspace-item'
175
+ ))
176
+ OR (json_type(metadata) = 'array' AND EXISTS (
177
+ SELECT 1 FROM json_each(metadata) AS entry
178
+ WHERE CASE WHEN entry.type = 'object'
179
+ THEN json_extract(entry.value, '$.key') = 'or3.workspace-item' ELSE 0 END
180
+ ))` : `json_type(metadata) = 'array' AND EXISTS (
181
+ SELECT 1 FROM json_each(metadata) AS entry
182
+ WHERE CASE WHEN entry.type = 'object'
183
+ THEN json_extract(entry.value, '$.kind') = 'file' ELSE 0 END
184
+ )`;
185
+ return {
186
+ sql: `SELECT json_extract('{}', CASE WHEN EXISTS (
187
+ SELECT 1 FROM (
188
+ SELECT data_json, ${decoded} AS metadata FROM "${SYNCED_TABLE_MAP[op.tableName]}"
189
+ WHERE workspace_id = ? AND id = ?
190
+ ) WHERE ${semantics}
191
+ ) THEN '${WORKSPACE_ITEM_UPDATE_REQUIRED}' ELSE '$' END)`,
192
+ parameters: [workspaceId, op.pk]
193
+ };
194
+ }
150
195
  const LWW_EXCLUDED_WINS = `(
151
196
  excluded.clock > TARGET.clock
152
197
  OR (excluded.clock = TARGET.clock AND excluded.hlc > TARGET.hlc)
@@ -631,7 +676,8 @@ export class SqliteSyncGatewayAdapter {
631
676
  }
632
677
  const raw = getRawDb();
633
678
  const fingerprint = createHash("sha256").update(stableJson(admission)).digest("hex");
634
- return raw.transaction(() => {
679
+ const hookEmissions = [];
680
+ const result = raw.transaction(() => {
635
681
  this.assertCanonicalActor(actor);
636
682
  const receipt = raw.prepare(
637
683
  `SELECT fingerprint, outcome, server_version
@@ -725,7 +771,8 @@ export class SqliteSyncGatewayAdapter {
725
771
  opId,
726
772
  now
727
773
  );
728
- raw.prepare(
774
+ const existing = raw.prepare(`SELECT 1 FROM ${entry.materialized} WHERE workspace_id = ? AND id = ?`).get(admission.workspaceId, entry.record.id);
775
+ const materialized = raw.prepare(
729
776
  `INSERT INTO ${entry.materialized}
730
777
  (id, workspace_id, data_json, clock, hlc, device_id, op_id,
731
778
  deleted, created_at, updated_at)
@@ -746,6 +793,11 @@ export class SqliteSyncGatewayAdapter {
746
793
  now,
747
794
  now
748
795
  );
796
+ if ((entry.table === "threads" || entry.record.id !== admission.messageId) && !existing && materialized.changes > 0) {
797
+ const op = { tableName: entry.table, operation: "put", pk: entry.record.id, payload };
798
+ const emission = resolveHookEmission({ op, workspaceId: admission.workspaceId, now, userId: actor.userId, wasExisting: false, applied: true });
799
+ if (emission) hookEmissions.push(emission);
800
+ }
749
801
  });
750
802
  const admittedAssistant = raw.prepare(
751
803
  `SELECT data_json, clock, deleted FROM s_messages
@@ -764,6 +816,14 @@ export class SqliteSyncGatewayAdapter {
764
816
  ).run(uid(), admission.workspaceId, admission.generationId, fingerprint, finalVersion, now);
765
817
  return { status: "admitted", replayed: false, serverVersion: finalVersion };
766
818
  }).immediate();
819
+ for (const emission of hookEmissions) {
820
+ try {
821
+ await emitWebhookSystemHook(emission.hookName, emission.payload);
822
+ } catch (error) {
823
+ console.error("[or3-sqlite] Background admission hook failed", error);
824
+ }
825
+ }
826
+ return result;
767
827
  }
768
828
  async finalizeChatGeneration(actor, input) {
769
829
  const admission = parseChatGenerationAdmissionEnvelope(input.admission);
@@ -1229,7 +1289,8 @@ export class SqliteSyncGatewayAdapter {
1229
1289
  uniqueOps,
1230
1290
  resultSlots,
1231
1291
  indicesByOpId,
1232
- userId
1292
+ userId,
1293
+ workspaceItemCapability: input.workspaceItemCapability
1233
1294
  });
1234
1295
  }
1235
1296
  const raw = getRawDb();
@@ -1244,11 +1305,7 @@ export class SqliteSyncGatewayAdapter {
1244
1305
  if (!table || !["posts", "projects"].includes(op.tableName)) continue;
1245
1306
  const canonical = raw.prepare("SELECT data_json FROM " + table + " WHERE id = ? AND workspace_id = ?").get(op.pk, workspaceId);
1246
1307
  if (hasWorkspaceItemSemantics(op.tableName, op.payload) || hasWorkspaceItemSemantics(op.tableName, canonical ? JSON.parse(canonical.data_json) : void 0)) {
1247
- throw createError({
1248
- statusCode: 426,
1249
- statusMessage: "Update OR3 Chat to use workspace Files and Trash",
1250
- data: { code: "OR3_WORKSPACE_ITEM_UPDATE_REQUIRED", requiredCapability: WORKSPACE_ITEM_CAPABILITY }
1251
- });
1308
+ throw workspaceItemUpdateRequired();
1252
1309
  }
1253
1310
  }
1254
1311
  }
@@ -2507,6 +2564,15 @@ export class SqliteSyncGatewayAdapter {
2507
2564
  }
2508
2565
  const now = nowEpoch();
2509
2566
  const statements = [];
2567
+ if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
2568
+ for (const op of uniqueOps) {
2569
+ if (!["posts", "projects"].includes(op.tableName)) continue;
2570
+ if (hasWorkspaceItemSemantics(op.tableName, op.payload)) {
2571
+ throw workspaceItemUpdateRequired();
2572
+ }
2573
+ statements.push(workspaceItemCapabilityAssertion(op, workspaceId));
2574
+ }
2575
+ }
2510
2576
  if (newOps.length > 0) {
2511
2577
  statements.push({
2512
2578
  sql: `INSERT OR IGNORE INTO server_version_counter (workspace_id, value)
@@ -2652,7 +2718,16 @@ export class SqliteSyncGatewayAdapter {
2652
2718
  parameters: [workspaceId]
2653
2719
  });
2654
2720
  }
2655
- const batchResults = statements.length > 0 ? await d1Batch(statements) : [];
2721
+ let batchResults;
2722
+ try {
2723
+ batchResults = statements.length > 0 ? await d1Batch(statements) : [];
2724
+ } catch (error) {
2725
+ const message = error instanceof Error ? error.message : String(error);
2726
+ if (/JSON path/i.test(message) && message.includes(WORKSPACE_ITEM_UPDATE_REQUIRED)) {
2727
+ throw workspaceItemUpdateRequired();
2728
+ }
2729
+ throw error;
2730
+ }
2656
2731
  let finalServerVersion = 0;
2657
2732
  if (finalVersionResultIndex !== void 0) {
2658
2733
  const row = batchResults[finalVersionResultIndex]?.results?.[0];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.22",
3
+ "version": "0.0.23",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"