@syncular/server 0.49.2 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -286,13 +286,23 @@ Whole-commit validation checks a client-proposed commit; it does not grant
286
286
  authority. Privileged operations such as connecting facilities still belong in
287
287
  explicit server-authoritative commands.
288
288
 
289
+ For a whole-commit authority refusal, throw `CommitAuthorizationRejection`
290
+ with the operation index and a static message. The server returns
291
+ `sync.forbidden` and rolls back the commit. An absent-row delete is normally an
292
+ idempotent no-op; a validator that denies it can use the message
293
+ `delete denied by scope authorization (§3.4)` to match the refusal for a
294
+ stored row outside the actor's scopes. Do not put row data or identifiers in
295
+ the message.
296
+
289
297
  ## Push idempotency and retry contract
290
298
 
291
299
  The idempotency key for a push commit is the triple
292
300
  **(`partition`, `clientId`, `clientCommitId`)**. The server persists the full
293
301
  commit result in the same transaction as the writes, and a replay of the same
294
- key returns that result byte-equivalent: an applied commit replays as `cached`,
295
- a rejected commit replays as `rejected` (§2.3, §6.3).
302
+ key returns that result: an applied commit replays as `cached`, and a rejected
303
+ commit replays as `rejected` (§2.3, §6.3). The server reauthorizes a cached
304
+ conflict snapshot against current write scopes before returning its row. A
305
+ denied replay returns `sync.forbidden` and leaves the cached result intact.
296
306
 
297
307
  The key contains the commit ID and nothing about the operations. Host
298
308
  authentication, request-envelope validation, and the §1.5 clientId-actor
@@ -301,8 +311,8 @@ binding run before the lookup.
301
311
  not proof of an authenticated device. When a retained result exists for the
302
312
  key, the server skips `buildOperations`, the commit and write validators, and
303
313
  the apply transaction: a retry that reuses the key with different operations
304
- returns the persisted result, and those operations are never built, validated,
305
- or applied. `packages/server/test/push.test.ts` pins this.
314
+ returns the persisted result subject to conflict reauthorization, and those
315
+ operations are never built, validated, or applied. `packages/server/test/push.test.ts` pins this.
306
316
 
307
317
  A client MUST NOT reuse a `clientCommitId` for changed intent, including after
308
318
  the persisted result has been pruned. One ID identifies one logical commit
@@ -376,6 +376,9 @@ function serializePushResult(result) {
376
376
  ...(result.cacheIdentity !== undefined
377
377
  ? { cacheIdentity: result.cacheIdentity }
378
378
  : {}),
379
+ ...(result.conflictAuthorization !== undefined
380
+ ? { conflictAuthorization: result.conflictAuthorization }
381
+ : {}),
379
382
  results: result.results.map((record) => {
380
383
  if (record.status === 'conflict') {
381
384
  return {
@@ -437,6 +440,9 @@ function deserializePushResult(value) {
437
440
  ...(parsed.cacheIdentity !== undefined
438
441
  ? { cacheIdentity: parsed.cacheIdentity }
439
442
  : {}),
443
+ ...(parsed.conflictAuthorization !== undefined
444
+ ? { conflictAuthorization: parsed.conflictAuthorization }
445
+ : {}),
440
446
  results,
441
447
  };
442
448
  }
package/dist/push.js CHANGED
@@ -29,7 +29,7 @@ import { readCandidateRows, serveGateRefusal } from './storage.js';
29
29
  import { StorageConstraintError } from './storage-errors.js';
30
30
  import { transactionQuery } from './storage-query.js';
31
31
  import { serveNotReadyError } from './readiness.js';
32
- import { CommitValidationRejection, toValidateRow, ValidationRejection, } from './validate.js';
32
+ import { CommitAuthorizationRejection, CommitValidationRejection, toValidateRow, ValidationRejection, } from './validate.js';
33
33
  /**
34
34
  * Extract the blobIds a decoded row references through its `blob_ref`
35
35
  * columns (§5.9.4), skipping NULLs. Malformed BlobRefs already failed at
@@ -730,6 +730,12 @@ async function runCommitValidator(validator, onError, tx, schema, clientId, clie
730
730
  });
731
731
  }
732
732
  catch (error) {
733
+ if (error instanceof CommitAuthorizationRejection) {
734
+ if (error.opIndex >= operations.length) {
735
+ return errorRecord(0, 'sync.constraint_violation', 'commit authorization rejection names an unavailable operation');
736
+ }
737
+ return errorRecord(error.opIndex, error.code, error.message, false);
738
+ }
733
739
  if (error instanceof CommitValidationRejection) {
734
740
  if (error.opIndex >= operations.length) {
735
741
  return errorRecord(0, 'sync.constraint_violation', `commit validator rejection names unavailable opIndex ${error.opIndex}`);
@@ -795,7 +801,7 @@ function referenceRejection(opIndex, message, details) {
795
801
  * operation count) and emit ordinary changes carrying the child's stored
796
802
  * scopes; a rejection attributes to the originating client delete.
797
803
  */
798
- async function enforceReferences(tx, schema, staged, clientOpCount, cascadeLimit, validators, partition, actorId) {
804
+ async function enforceReferences(tx, schema, resolved, staged, clientOpCount, cascadeLimit, validators, partition, actorId) {
799
805
  const changes = [];
800
806
  const operations = [];
801
807
  const originByIndex = [];
@@ -922,6 +928,9 @@ async function enforceReferences(tx, schema, staged, clientOpCount, cascadeLimit
922
928
  throw new Error(`unreachable: reference child table ${reference.table} is not compiled`);
923
929
  }
924
930
  for (const childRow of children) {
931
+ if (!authorizeWrite(child, childRow.scopes, resolved)) {
932
+ return errorRecord(item.originOpIndex, 'sync.forbidden', 'cascade denied by scope authorization (§3.4)');
933
+ }
925
934
  if (reference.onDelete === 'CASCADE') {
926
935
  if (!schedule(child, childRow.rowId, item.originOpIndex, scheduled, queue)) {
927
936
  continue;
@@ -1143,6 +1152,28 @@ export async function processPushOperationsWithTrace(ctx, schema, resolved, clie
1143
1152
  throw serveNotReadyError(refusal);
1144
1153
  }
1145
1154
  if (prepared.persisted !== undefined) {
1155
+ const conflict = prepared.persisted.results.find((result) => result.status === 'conflict');
1156
+ const authorization = prepared.persisted.conflictAuthorization;
1157
+ const table = authorization && schema.tables.get(authorization.table);
1158
+ if (conflict !== undefined &&
1159
+ (authorization === undefined ||
1160
+ authorization.schemaVersion !== schema.version ||
1161
+ table === undefined ||
1162
+ !authorizeWrite(table, authorization.scopes, resolved))) {
1163
+ await tx.rollback();
1164
+ return processedPushCommit(clientCommitId, {
1165
+ ...prepared.persisted,
1166
+ results: [
1167
+ {
1168
+ opIndex: conflict.opIndex,
1169
+ status: 'error',
1170
+ code: 'sync.forbidden',
1171
+ message: 'conflict replay denied by scope authorization (§3.4)',
1172
+ retryable: false,
1173
+ },
1174
+ ],
1175
+ }, true);
1176
+ }
1146
1177
  await tx.rollback();
1147
1178
  return processedPushCommit(clientCommitId, prepared.persisted, true);
1148
1179
  }
@@ -1184,7 +1215,7 @@ export async function processPushOperationsWithTrace(ctx, schema, resolved, clie
1184
1215
  // and before whole-commit validation.
1185
1216
  let appendedOrigin = [];
1186
1217
  if (terminated === undefined) {
1187
- const referencePass = await enforceReferences(tx, schema, stagedWrites, operations.length, limitsOf(ctx).maxCascadeOperationsPerCommit, validators, partition, ctx.actorId);
1218
+ const referencePass = await enforceReferences(tx, schema, resolved, stagedWrites, operations.length, limitsOf(ctx).maxCascadeOperationsPerCommit, validators, partition, ctx.actorId);
1188
1219
  if (referencePass.kind === 'terminate') {
1189
1220
  terminated = referencePass.record;
1190
1221
  }
@@ -1223,8 +1254,27 @@ export async function processPushOperationsWithTrace(ctx, schema, resolved, clie
1223
1254
  if (terminated !== undefined) {
1224
1255
  // §6.3 rejected: only the terminating operation's record; §6.4:
1225
1256
  // every write of the commit rolls back.
1257
+ const conflictOperation = terminated.status === 'conflict'
1258
+ ? operations[terminated.opIndex]
1259
+ : undefined;
1260
+ const conflictRow = conflictOperation === undefined
1261
+ ? undefined
1262
+ : await tx.getRow(conflictOperation.table, conflictOperation.rowId);
1263
+ if (terminated.status === 'conflict' &&
1264
+ (conflictOperation === undefined || conflictRow === undefined)) {
1265
+ throw new Error('conflict snapshot has no authorization row');
1266
+ }
1226
1267
  const stored = newStoredPushResult(createdAtMs, {
1227
1268
  status: 'rejected',
1269
+ ...(conflictOperation !== undefined && conflictRow !== undefined
1270
+ ? {
1271
+ conflictAuthorization: {
1272
+ table: conflictOperation.table,
1273
+ schemaVersion: schema.version,
1274
+ scopes: conflictRow.scopes,
1275
+ },
1276
+ }
1277
+ : {}),
1228
1278
  results: [terminated],
1229
1279
  });
1230
1280
  // Discard candidates and persist the rejection while retaining the same
package/dist/schema.d.ts CHANGED
@@ -67,6 +67,8 @@ export interface TableSchema {
67
67
  readonly primaryKey: string;
68
68
  /** Scope patterns (§3.1). Every synced table declares at least one. */
69
69
  readonly scopes: readonly ScopePatternSpec[];
70
+ /** Variables required together for writes; defaults to every scope variable. */
71
+ readonly writeScopeVariables?: readonly string[];
70
72
  /** User indexes (optional) — created on the server's relational tables. */
71
73
  readonly indexes?: readonly IndexSchema[];
72
74
  /** Server-only indexes (optional); names share the namespace of `indexes`. */
@@ -109,6 +111,7 @@ export interface CompiledTable {
109
111
  readonly columns: readonly RowColumn[];
110
112
  readonly primaryKeyIndex: number;
111
113
  readonly scopePatterns: readonly CompiledScopePattern[];
114
+ readonly writeScopeVariables: readonly string[];
112
115
  /** User indexes (validated: unique names, existing columns). */
113
116
  readonly indexes: readonly IndexSchema[];
114
117
  /** Server-only indexes (validated like `indexes`). */
package/dist/schema.js CHANGED
@@ -117,6 +117,13 @@ export function compileSchema(schema) {
117
117
  variables.add(pattern.variable);
118
118
  declaredVariables.add(pattern.variable);
119
119
  }
120
+ const writeScopeVariables = table.writeScopeVariables ?? [...variables];
121
+ if (!Array.isArray(writeScopeVariables) ||
122
+ writeScopeVariables.length === 0 ||
123
+ new Set(writeScopeVariables).size !== writeScopeVariables.length ||
124
+ writeScopeVariables.some((variable) => !variables.has(variable))) {
125
+ throw new Error(`table ${table.name}: writeScopeVariables must contain distinct declared scope variables (§3.4)`);
126
+ }
120
127
  const blobRefColumnIndices = [];
121
128
  const crdtColumns = [];
122
129
  const encryptedColumnIndices = [];
@@ -162,6 +169,7 @@ export function compileSchema(schema) {
162
169
  columns: table.columns,
163
170
  primaryKeyIndex,
164
171
  scopePatterns,
172
+ writeScopeVariables,
165
173
  indexes,
166
174
  serverIndexes,
167
175
  references,
package/dist/scopes.d.ts CHANGED
@@ -36,9 +36,8 @@ export declare function storedScopesForRow(table: CompiledTable, values: readonl
36
36
  missing: string;
37
37
  };
38
38
  /**
39
- * Write-path authorization (§3.4 steps 2–3): every declared variable's
40
- * stored value must be present and allowed (or the allowed list holds
41
- * `'*'`). All declared keys are required — there is no partial pass.
39
+ * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
40
+ * the declared write variables must be allowed (or hold `'*'`).
42
41
  */
43
42
  export declare function authorizeWrite(table: CompiledTable, rowScopes: StoredScopes, resolved: ResolvedScopes): boolean;
44
43
  /** Does a change's stored scopes match the effective scopes (§3.2)? */
package/dist/scopes.js CHANGED
@@ -57,9 +57,8 @@ export function storedScopesForRow(table, values) {
57
57
  return { scopes };
58
58
  }
59
59
  /**
60
- * Write-path authorization (§3.4 steps 2–3): every declared variable's
61
- * stored value must be present and allowed (or the allowed list holds
62
- * `'*'`). All declared keys are required — there is no partial pass.
60
+ * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
61
+ * the declared write variables must be allowed (or hold `'*'`).
63
62
  */
64
63
  export function authorizeWrite(table, rowScopes, resolved) {
65
64
  if (!resolved.ok)
@@ -68,7 +67,12 @@ export function authorizeWrite(table, rowScopes, resolved) {
68
67
  const value = rowScopes[pattern.variable];
69
68
  if (value === undefined || value.length === 0)
70
69
  return false;
71
- const allowedValues = resolved.allowed[pattern.variable];
70
+ }
71
+ for (const variable of table.writeScopeVariables) {
72
+ const value = rowScopes[variable];
73
+ if (value === undefined)
74
+ return false;
75
+ const allowedValues = resolved.allowed[variable];
72
76
  if (allowedValues === undefined)
73
77
  return false;
74
78
  if (!allowedValues.includes('*') && !allowedValues.includes(value)) {
@@ -197,6 +197,9 @@ export function serializePushResult(result) {
197
197
  ...(result.cacheIdentity !== undefined
198
198
  ? { cacheIdentity: result.cacheIdentity }
199
199
  : {}),
200
+ ...(result.conflictAuthorization !== undefined
201
+ ? { conflictAuthorization: result.conflictAuthorization }
202
+ : {}),
200
203
  results: result.results.map((record) => {
201
204
  if (record.status === 'conflict') {
202
205
  return {
@@ -258,6 +261,9 @@ export function deserializePushResult(text) {
258
261
  ...(parsed.cacheIdentity !== undefined
259
262
  ? { cacheIdentity: parsed.cacheIdentity }
260
263
  : {}),
264
+ ...(parsed.conflictAuthorization !== undefined
265
+ ? { conflictAuthorization: parsed.conflictAuthorization }
266
+ : {}),
261
267
  results,
262
268
  };
263
269
  }
package/dist/storage.d.ts CHANGED
@@ -234,6 +234,12 @@ export interface StoredPushResult {
234
234
  readonly recordedAtMs?: number;
235
235
  /** Privacy-safe identity used to distinguish this stored outcome from a race. */
236
236
  readonly cacheIdentity?: string;
237
+ /** The scope of a persisted conflict snapshot, for replay authorization. */
238
+ readonly conflictAuthorization?: {
239
+ readonly table: string;
240
+ readonly schemaVersion: number;
241
+ readonly scopes: Readonly<Record<string, string>>;
242
+ };
237
243
  readonly results: readonly PushOperationResult[];
238
244
  }
239
245
  export interface ClientSubscription {
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { type RejectionDetails, type RowColumn, type RowValue, type ScopeMap } from '@syncular/core';
17
17
  import type { AuthoritativeQueryRequest, AuthoritativeQueryResult } from './storage.js';
18
+ import { SyncError } from './errors.js';
18
19
  /**
19
20
  * §6.7 reserved code prefixes. A host validator code MUST NOT start with
20
21
  * any of these: they namespace the protocol's own error families (§10.2)
@@ -210,5 +211,10 @@ export declare class CommitValidationRejection extends ValidationRejection {
210
211
  readonly opIndex: number;
211
212
  constructor(opIndex: number, code: string, message?: string, details?: RejectionDetails);
212
213
  }
214
+ /** A whole-commit authority refusal attributed to one operation (§6.8). */
215
+ export declare class CommitAuthorizationRejection extends SyncError {
216
+ readonly opIndex: number;
217
+ constructor(opIndex: number, message: string);
218
+ }
213
219
  /** Build the column-keyed row object a validator inspects (§6.7). */
214
220
  export declare function toValidateRow(columns: readonly RowColumn[], values: readonly RowValue[]): ValidateRow;
package/dist/validate.js CHANGED
@@ -14,6 +14,7 @@
14
14
  * object — zero cost, the events-seam discipline.
15
15
  */
16
16
  import { normalizeRejectionDetails, } from '@syncular/core';
17
+ import { SyncError } from './errors.js';
17
18
  /**
18
19
  * §6.7 reserved code prefixes. A host validator code MUST NOT start with
19
20
  * any of these: they namespace the protocol's own error families (§10.2)
@@ -73,6 +74,17 @@ export class CommitValidationRejection extends ValidationRejection {
73
74
  }
74
75
  }
75
76
  }
77
+ /** A whole-commit authority refusal attributed to one operation (§6.8). */
78
+ export class CommitAuthorizationRejection extends SyncError {
79
+ opIndex;
80
+ constructor(opIndex, message) {
81
+ super('sync.forbidden', message);
82
+ this.opIndex = opIndex;
83
+ if (!Number.isSafeInteger(opIndex) || opIndex < 0) {
84
+ throw new Error('CommitAuthorizationRejection opIndex must be a non-negative safe integer');
85
+ }
86
+ }
87
+ }
76
88
  /** Build the column-keyed row object a validator inspects (§6.7). */
77
89
  export function toValidateRow(columns, values) {
78
90
  const row = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/server",
3
- "version": "0.49.2",
3
+ "version": "0.51.0",
4
4
  "description": "Syncular server: handleSyncRequest + storage/auth interfaces for the sync protocol",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -68,7 +68,7 @@
68
68
  "verify:node": "cd ../.. && bun build ./packages/server/test/sqlite-runtime/verify-node.mjs --target=node --conditions=bun --outfile=./packages/server/.verify-node.built.mjs && node ./packages/server/.verify-node.built.mjs"
69
69
  },
70
70
  "dependencies": {
71
- "@syncular/core": "0.49.2"
71
+ "@syncular/core": "0.51.0"
72
72
  },
73
73
  "devDependencies": {
74
74
  "@electric-sql/pglite": "^0.5.4"
@@ -678,6 +678,9 @@ function serializePushResult(result: StoredPushResult): unknown {
678
678
  ...(result.cacheIdentity !== undefined
679
679
  ? { cacheIdentity: result.cacheIdentity }
680
680
  : {}),
681
+ ...(result.conflictAuthorization !== undefined
682
+ ? { conflictAuthorization: result.conflictAuthorization }
683
+ : {}),
681
684
  results: result.results.map((record) => {
682
685
  if (record.status === 'conflict') {
683
686
  return {
@@ -711,6 +714,7 @@ function deserializePushResult(value: unknown): StoredPushResult {
711
714
  commitSeq?: number;
712
715
  recordedAtMs?: number;
713
716
  cacheIdentity?: string;
717
+ conflictAuthorization?: StoredPushResult['conflictAuthorization'];
714
718
  results: SerializedResult[];
715
719
  };
716
720
  const results: PushOperationResult[] = parsed.results.map((record) => {
@@ -746,6 +750,9 @@ function deserializePushResult(value: unknown): StoredPushResult {
746
750
  ...(parsed.cacheIdentity !== undefined
747
751
  ? { cacheIdentity: parsed.cacheIdentity }
748
752
  : {}),
753
+ ...(parsed.conflictAuthorization !== undefined
754
+ ? { conflictAuthorization: parsed.conflictAuthorization }
755
+ : {}),
749
756
  results,
750
757
  };
751
758
  }
package/src/push.ts CHANGED
@@ -67,6 +67,7 @@ import type {
67
67
  ValidatorRegistry,
68
68
  } from './validate';
69
69
  import {
70
+ CommitAuthorizationRejection,
70
71
  CommitValidationRejection,
71
72
  toValidateRow,
72
73
  ValidationRejection,
@@ -1164,6 +1165,16 @@ async function runCommitValidator(
1164
1165
  read: commitValidationReader(tx, schema),
1165
1166
  });
1166
1167
  } catch (error) {
1168
+ if (error instanceof CommitAuthorizationRejection) {
1169
+ if (error.opIndex >= operations.length) {
1170
+ return errorRecord(
1171
+ 0,
1172
+ 'sync.constraint_violation',
1173
+ 'commit authorization rejection names an unavailable operation',
1174
+ );
1175
+ }
1176
+ return errorRecord(error.opIndex, error.code, error.message, false);
1177
+ }
1167
1178
  if (error instanceof CommitValidationRejection) {
1168
1179
  if (error.opIndex >= operations.length) {
1169
1180
  return errorRecord(
@@ -1263,6 +1274,7 @@ function referenceRejection(
1263
1274
  async function enforceReferences(
1264
1275
  tx: StorageTransaction,
1265
1276
  schema: CompiledSchema,
1277
+ resolved: ResolvedScopes,
1266
1278
  staged: readonly StagedWrite[],
1267
1279
  clientOpCount: number,
1268
1280
  cascadeLimit: number,
@@ -1432,6 +1444,13 @@ async function enforceReferences(
1432
1444
  );
1433
1445
  }
1434
1446
  for (const childRow of children) {
1447
+ if (!authorizeWrite(child, childRow.scopes, resolved)) {
1448
+ return errorRecord(
1449
+ item.originOpIndex,
1450
+ 'sync.forbidden',
1451
+ 'cascade denied by scope authorization (§3.4)',
1452
+ );
1453
+ }
1435
1454
  if (reference.onDelete === 'CASCADE') {
1436
1455
  if (
1437
1456
  !schedule(
@@ -1772,6 +1791,36 @@ export async function processPushOperationsWithTrace(
1772
1791
  throw serveNotReadyError(refusal);
1773
1792
  }
1774
1793
  if (prepared.persisted !== undefined) {
1794
+ const conflict = prepared.persisted.results.find(
1795
+ (result) => result.status === 'conflict',
1796
+ );
1797
+ const authorization = prepared.persisted.conflictAuthorization;
1798
+ const table = authorization && schema.tables.get(authorization.table);
1799
+ if (
1800
+ conflict !== undefined &&
1801
+ (authorization === undefined ||
1802
+ authorization.schemaVersion !== schema.version ||
1803
+ table === undefined ||
1804
+ !authorizeWrite(table, authorization.scopes, resolved))
1805
+ ) {
1806
+ await tx.rollback();
1807
+ return processedPushCommit(
1808
+ clientCommitId,
1809
+ {
1810
+ ...prepared.persisted,
1811
+ results: [
1812
+ {
1813
+ opIndex: conflict.opIndex,
1814
+ status: 'error',
1815
+ code: 'sync.forbidden',
1816
+ message: 'conflict replay denied by scope authorization (§3.4)',
1817
+ retryable: false,
1818
+ },
1819
+ ],
1820
+ },
1821
+ true,
1822
+ );
1823
+ }
1775
1824
  await tx.rollback();
1776
1825
  return processedPushCommit(clientCommitId, prepared.persisted, true);
1777
1826
  }
@@ -1829,6 +1878,7 @@ export async function processPushOperationsWithTrace(
1829
1878
  const referencePass = await enforceReferences(
1830
1879
  tx,
1831
1880
  schema,
1881
+ resolved,
1832
1882
  stagedWrites,
1833
1883
  operations.length,
1834
1884
  limitsOf(ctx).maxCascadeOperationsPerCommit,
@@ -1887,8 +1937,31 @@ export async function processPushOperationsWithTrace(
1887
1937
  if (terminated !== undefined) {
1888
1938
  // §6.3 rejected: only the terminating operation's record; §6.4:
1889
1939
  // every write of the commit rolls back.
1940
+ const conflictOperation =
1941
+ terminated.status === 'conflict'
1942
+ ? operations[terminated.opIndex]
1943
+ : undefined;
1944
+ const conflictRow =
1945
+ conflictOperation === undefined
1946
+ ? undefined
1947
+ : await tx.getRow(conflictOperation.table, conflictOperation.rowId);
1948
+ if (
1949
+ terminated.status === 'conflict' &&
1950
+ (conflictOperation === undefined || conflictRow === undefined)
1951
+ ) {
1952
+ throw new Error('conflict snapshot has no authorization row');
1953
+ }
1890
1954
  const stored = newStoredPushResult(createdAtMs, {
1891
1955
  status: 'rejected',
1956
+ ...(conflictOperation !== undefined && conflictRow !== undefined
1957
+ ? {
1958
+ conflictAuthorization: {
1959
+ table: conflictOperation.table,
1960
+ schemaVersion: schema.version,
1961
+ scopes: conflictRow.scopes,
1962
+ },
1963
+ }
1964
+ : {}),
1892
1965
  results: [terminated],
1893
1966
  });
1894
1967
  // Discard candidates and persist the rejection while retaining the same
package/src/schema.ts CHANGED
@@ -75,6 +75,8 @@ export interface TableSchema {
75
75
  readonly primaryKey: string;
76
76
  /** Scope patterns (§3.1). Every synced table declares at least one. */
77
77
  readonly scopes: readonly ScopePatternSpec[];
78
+ /** Variables required together for writes; defaults to every scope variable. */
79
+ readonly writeScopeVariables?: readonly string[];
78
80
  /** User indexes (optional) — created on the server's relational tables. */
79
81
  readonly indexes?: readonly IndexSchema[];
80
82
  /** Server-only indexes (optional); names share the namespace of `indexes`. */
@@ -120,6 +122,7 @@ export interface CompiledTable {
120
122
  readonly columns: readonly RowColumn[];
121
123
  readonly primaryKeyIndex: number;
122
124
  readonly scopePatterns: readonly CompiledScopePattern[];
125
+ readonly writeScopeVariables: readonly string[];
123
126
  /** User indexes (validated: unique names, existing columns). */
124
127
  readonly indexes: readonly IndexSchema[];
125
128
  /** Server-only indexes (validated like `indexes`). */
@@ -318,6 +321,17 @@ export function compileSchema(schema: ServerSchema): CompiledSchema {
318
321
  variables.add(pattern.variable);
319
322
  declaredVariables.add(pattern.variable);
320
323
  }
324
+ const writeScopeVariables = table.writeScopeVariables ?? [...variables];
325
+ if (
326
+ !Array.isArray(writeScopeVariables) ||
327
+ writeScopeVariables.length === 0 ||
328
+ new Set(writeScopeVariables).size !== writeScopeVariables.length ||
329
+ writeScopeVariables.some((variable) => !variables.has(variable))
330
+ ) {
331
+ throw new Error(
332
+ `table ${table.name}: writeScopeVariables must contain distinct declared scope variables (§3.4)`,
333
+ );
334
+ }
321
335
  const blobRefColumnIndices: number[] = [];
322
336
  const crdtColumns: { index: number; crdtType: string }[] = [];
323
337
  const encryptedColumnIndices: number[] = [];
@@ -372,6 +386,7 @@ export function compileSchema(schema: ServerSchema): CompiledSchema {
372
386
  columns: table.columns,
373
387
  primaryKeyIndex,
374
388
  scopePatterns,
389
+ writeScopeVariables,
375
390
  indexes,
376
391
  serverIndexes,
377
392
  references,
package/src/scopes.ts CHANGED
@@ -77,9 +77,8 @@ export function storedScopesForRow(
77
77
  }
78
78
 
79
79
  /**
80
- * Write-path authorization (§3.4 steps 2–3): every declared variable's
81
- * stored value must be present and allowed (or the allowed list holds
82
- * `'*'`). All declared keys are required — there is no partial pass.
80
+ * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
81
+ * the declared write variables must be allowed (or hold `'*'`).
83
82
  */
84
83
  export function authorizeWrite(
85
84
  table: CompiledTable,
@@ -90,7 +89,11 @@ export function authorizeWrite(
90
89
  for (const pattern of table.scopePatterns) {
91
90
  const value = rowScopes[pattern.variable];
92
91
  if (value === undefined || value.length === 0) return false;
93
- const allowedValues = resolved.allowed[pattern.variable];
92
+ }
93
+ for (const variable of table.writeScopeVariables) {
94
+ const value = rowScopes[variable];
95
+ if (value === undefined) return false;
96
+ const allowedValues = resolved.allowed[variable];
94
97
  if (allowedValues === undefined) return false;
95
98
  if (!allowedValues.includes('*') && !allowedValues.includes(value)) {
96
99
  return false;
@@ -247,6 +247,9 @@ export function serializePushResult(result: StoredPushResult): string {
247
247
  ...(result.cacheIdentity !== undefined
248
248
  ? { cacheIdentity: result.cacheIdentity }
249
249
  : {}),
250
+ ...(result.conflictAuthorization !== undefined
251
+ ? { conflictAuthorization: result.conflictAuthorization }
252
+ : {}),
250
253
  results: result.results.map((record) => {
251
254
  if (record.status === 'conflict') {
252
255
  return {
@@ -280,6 +283,7 @@ export function deserializePushResult(text: string): StoredPushResult {
280
283
  commitSeq?: number;
281
284
  recordedAtMs?: number;
282
285
  cacheIdentity?: string;
286
+ conflictAuthorization?: StoredPushResult['conflictAuthorization'];
283
287
  results: SerializedResult[];
284
288
  };
285
289
  const results: PushOperationResult[] = parsed.results.map((record) => {
@@ -315,6 +319,9 @@ export function deserializePushResult(text: string): StoredPushResult {
315
319
  ...(parsed.cacheIdentity !== undefined
316
320
  ? { cacheIdentity: parsed.cacheIdentity }
317
321
  : {}),
322
+ ...(parsed.conflictAuthorization !== undefined
323
+ ? { conflictAuthorization: parsed.conflictAuthorization }
324
+ : {}),
318
325
  results,
319
326
  };
320
327
  }
package/src/storage.ts CHANGED
@@ -323,6 +323,12 @@ export interface StoredPushResult {
323
323
  readonly recordedAtMs?: number;
324
324
  /** Privacy-safe identity used to distinguish this stored outcome from a race. */
325
325
  readonly cacheIdentity?: string;
326
+ /** The scope of a persisted conflict snapshot, for replay authorization. */
327
+ readonly conflictAuthorization?: {
328
+ readonly table: string;
329
+ readonly schemaVersion: number;
330
+ readonly scopes: Readonly<Record<string, string>>;
331
+ };
326
332
  readonly results: readonly PushOperationResult[];
327
333
  }
328
334
 
package/src/validate.ts CHANGED
@@ -24,6 +24,7 @@ import type {
24
24
  AuthoritativeQueryRequest,
25
25
  AuthoritativeQueryResult,
26
26
  } from './storage';
27
+ import { SyncError } from './errors';
27
28
 
28
29
  /**
29
30
  * §6.7 reserved code prefixes. A host validator code MUST NOT start with
@@ -284,6 +285,21 @@ export class CommitValidationRejection extends ValidationRejection {
284
285
  }
285
286
  }
286
287
 
288
+ /** A whole-commit authority refusal attributed to one operation (§6.8). */
289
+ export class CommitAuthorizationRejection extends SyncError {
290
+ constructor(
291
+ readonly opIndex: number,
292
+ message: string,
293
+ ) {
294
+ super('sync.forbidden', message);
295
+ if (!Number.isSafeInteger(opIndex) || opIndex < 0) {
296
+ throw new Error(
297
+ 'CommitAuthorizationRejection opIndex must be a non-negative safe integer',
298
+ );
299
+ }
300
+ }
301
+ }
302
+
287
303
  /** Build the column-keyed row object a validator inspects (§6.7). */
288
304
  export function toValidateRow(
289
305
  columns: readonly RowColumn[],