@syncular/server 0.84.0 → 0.85.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/dist/push.js CHANGED
@@ -199,13 +199,9 @@ deleteFloor) {
199
199
  if (stored === undefined) {
200
200
  return errorRecord(opIndex, 'sync.row_missing', 'rescope targets an absent row (§2.2)');
201
201
  }
202
- if (!authorizeWrite(table, stored.scopes, resolved)) {
202
+ if (!authorizeWrite(table, stored.scopes, resolved, true)) {
203
203
  return errorRecord(opIndex, 'sync.forbidden', 'rescope denied by scope authorization (§3.4)');
204
204
  }
205
- const missing = missingScopeVariable(table, stored.scopes);
206
- if (missing !== undefined) {
207
- return errorRecord(opIndex, 'sync.missing_scopes', `stored row lacks scope variable ${JSON.stringify(missing)} (§3.1)`);
208
- }
209
205
  let sparse;
210
206
  try {
211
207
  sparse = decodeSparseRow(wireTable.columns, wireTable.primaryKeyIndex, op.payload);
@@ -244,7 +240,7 @@ deleteFloor) {
244
240
  if ('missing' in extracted) {
245
241
  return errorRecord(opIndex, 'sync.forbidden', `rescope missing scope column value for ${JSON.stringify(extracted.missing)} (§3.4)`);
246
242
  }
247
- if (!authorizeWrite(table, extracted.scopes, resolved)) {
243
+ if (!authorizeWrite(table, extracted.scopes, resolved, true)) {
248
244
  return errorRecord(opIndex, 'sync.forbidden', 'rescope denied by scope authorization of the new scopes (§3.4)');
249
245
  }
250
246
  const deleteReject = await runValidator(validators, table, 'delete', op.rowId, undefined, storedValues, opIndex, tx, partition, actorId, context);
@@ -363,10 +359,6 @@ deleteFloor) {
363
359
  if (!authorizeWrite(table, stored.scopes, resolved)) {
364
360
  return errorRecord(opIndex, 'sync.forbidden', 'delete denied by scope authorization (§3.4)');
365
361
  }
366
- const missing = missingScopeVariable(table, stored.scopes);
367
- if (missing !== undefined) {
368
- return errorRecord(opIndex, 'sync.missing_scopes', `stored row lacks scope variable ${JSON.stringify(missing)} (§3.1)`);
369
- }
370
362
  // §6.7: validate the delete against the stored row (row = undefined,
371
363
  // stored = the row about to be removed). Only reached for an existing
372
364
  // row — an absent-row delete is an idempotent no-op above.
@@ -559,14 +551,13 @@ deleteFloor) {
559
551
  },
560
552
  };
561
553
  }
562
- // Insert path: no stored row (§5.2). The authorization row is the payload
563
- // plus the primary key (§3.4 step 2); a missing or empty scope column value
564
- // ⇒ deny.
554
+ // Insert path: no stored row (§5.2). The owner set authorizes the payload
555
+ // plus the primary key (§3.4 steps 2 and 3).
565
556
  const values = sparse.map((value) => value ?? null);
566
557
  const extracted = storedScopesForRow(table, values);
567
558
  const insert = 'missing' in extracted
568
559
  ? errorRecord(opIndex, 'sync.forbidden', 'insert missing scope column value (§3.4)')
569
- : authorizeWrite(table, extracted.scopes, resolved)
560
+ : authorizeWrite(table, extracted.scopes, resolved, true)
570
561
  ? extracted
571
562
  : errorRecord(opIndex, 'sync.forbidden', 'insert denied by scope authorization (§3.4)');
572
563
  if (op.baseVersion !== undefined && op.baseVersion !== 0) {
@@ -695,14 +686,6 @@ async function checkAndRecordBlobs(tx, table, rowId, values, opIndex, blobCtx) {
695
686
  }
696
687
  return undefined;
697
688
  }
698
- function missingScopeVariable(table, scopes) {
699
- for (const pattern of table.scopePatterns) {
700
- const value = scopes[pattern.variable];
701
- if (value === undefined || value.length === 0)
702
- return pattern.variable;
703
- }
704
- return undefined;
705
- }
706
689
  function commitValidationReader(tx, schema) {
707
690
  const tableFor = (name) => {
708
691
  const table = schema.tables.get(name);
package/dist/schema.d.ts CHANGED
@@ -67,8 +67,9 @@ 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
+ /** Write sets (§3.4): one list of variables, or alternative lists whose
71
+ * first is the owner set. Defaults to one set of every scope variable. */
72
+ readonly writeScopeVariables?: readonly string[] | readonly (readonly string[])[];
72
73
  /** User indexes (optional) — created on the server's relational tables. */
73
74
  readonly indexes?: readonly IndexSchema[];
74
75
  /** Server-only indexes (optional); names share the namespace of `indexes`. */
@@ -111,7 +112,8 @@ export interface CompiledTable {
111
112
  readonly columns: readonly RowColumn[];
112
113
  readonly primaryKeyIndex: number;
113
114
  readonly scopePatterns: readonly CompiledScopePattern[];
114
- readonly writeScopeVariables: readonly string[];
115
+ /** §3.4 write sets; the first is the owner set. */
116
+ readonly writeScopeSets: readonly (readonly string[])[];
115
117
  /** User indexes (validated: unique names, existing columns). */
116
118
  readonly indexes: readonly IndexSchema[];
117
119
  /** Server-only indexes (validated like `indexes`). */
package/dist/schema.js CHANGED
@@ -135,12 +135,21 @@ export function compileSchema(schema) {
135
135
  variables.add(pattern.variable);
136
136
  declaredVariables.add(pattern.variable);
137
137
  }
138
- const writeScopeVariables = table.writeScopeVariables ?? [...variables];
139
- if (!Array.isArray(writeScopeVariables) ||
140
- writeScopeVariables.length === 0 ||
141
- new Set(writeScopeVariables).size !== writeScopeVariables.length ||
142
- writeScopeVariables.some((variable) => !variables.has(variable))) {
143
- throw new Error(`table ${table.name}: writeScopeVariables must contain distinct declared scope variables (§3.4)`);
138
+ // §3.4: one list is one set; a list of lists holds alternative sets.
139
+ const declaredSets = table.writeScopeVariables ?? [[...variables]];
140
+ const flatSet = declaredSets.filter((entry) => typeof entry === 'string');
141
+ const writeScopeSets = flatSet.length > 0
142
+ ? [flatSet]
143
+ : declaredSets.filter((entry) => typeof entry !== 'string');
144
+ const setKeys = new Set(writeScopeSets.map((set) => JSON.stringify([...set].sort())));
145
+ if ((flatSet.length > 0 && flatSet.length !== declaredSets.length) ||
146
+ writeScopeSets.length === 0 ||
147
+ setKeys.size !== writeScopeSets.length ||
148
+ writeScopeSets.some((set) => !Array.isArray(set) ||
149
+ set.length === 0 ||
150
+ new Set(set).size !== set.length ||
151
+ set.some((variable) => !variables.has(variable)))) {
152
+ throw new Error(`table ${table.name}: writeScopeVariables must be one list or distinct lists of distinct declared scope variables (§3.4)`);
144
153
  }
145
154
  const blobRefColumnIndices = [];
146
155
  const crdtColumns = [];
@@ -187,7 +196,7 @@ export function compileSchema(schema) {
187
196
  columns: table.columns,
188
197
  primaryKeyIndex,
189
198
  scopePatterns,
190
- writeScopeVariables,
199
+ writeScopeSets,
191
200
  indexes,
192
201
  serverIndexes,
193
202
  references,
package/dist/scopes.d.ts CHANGED
@@ -31,8 +31,9 @@ export declare function computeEffective(declared: ReadonlySet<string>, requeste
31
31
  /** Render a stored scope column value; `undefined` means missing/empty. */
32
32
  export declare function renderScopeValue(value: RowValue | undefined): string | undefined;
33
33
  /**
34
- * Extract the stored scopes (§3.1) from a decoded row. Returns the missing
35
- * variable name when a declared scope column is absent or empty.
34
+ * Extract the stored scopes (§3.1) from a decoded row. A NULL column outside
35
+ * the owner set leaves its variable without a stored scope. Returns the
36
+ * variable name when a column is empty, or NULL in the owner set.
36
37
  */
37
38
  export declare function storedScopesForRow(table: CompiledTable, values: readonly RowValue[]): {
38
39
  scopes: StoredScopes;
@@ -40,10 +41,11 @@ export declare function storedScopesForRow(table: CompiledTable, values: readonl
40
41
  missing: string;
41
42
  };
42
43
  /**
43
- * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
44
- * the declared write variables must be allowed (or hold `'*'`).
44
+ * Write-path authorization (§3.4 step 3): a write set admits the row when
45
+ * each of its variables has a value the actor is allowed (or `'*'`). An
46
+ * insert and a rescope need the owner set; an existing row needs any set.
45
47
  */
46
- export declare function authorizeWrite(table: CompiledTable, rowScopes: StoredScopes, resolved: ResolvedScopes): boolean;
48
+ export declare function authorizeWrite(table: CompiledTable, rowScopes: StoredScopes, resolved: ResolvedScopes, ownerOnly?: boolean): boolean;
47
49
  /** Does a change's stored scopes match the effective scopes (§3.2)? */
48
50
  export declare function matchesEffective(storedScopes: StoredScopes, effective: ScopeMap): boolean;
49
51
  export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
package/dist/scopes.js CHANGED
@@ -61,13 +61,19 @@ export function renderScopeValue(value) {
61
61
  return rendered.length === 0 ? undefined : rendered;
62
62
  }
63
63
  /**
64
- * Extract the stored scopes (§3.1) from a decoded row. Returns the missing
65
- * variable name when a declared scope column is absent or empty.
64
+ * Extract the stored scopes (§3.1) from a decoded row. A NULL column outside
65
+ * the owner set leaves its variable without a stored scope. Returns the
66
+ * variable name when a column is empty, or NULL in the owner set.
66
67
  */
67
68
  export function storedScopesForRow(table, values) {
68
69
  const scopes = {};
69
70
  for (const pattern of table.scopePatterns) {
70
- const value = renderScopeValue(values[pattern.columnIndex]);
71
+ const raw = values[pattern.columnIndex];
72
+ if ((raw === null || raw === undefined) &&
73
+ !table.writeScopeSets[0].includes(pattern.variable)) {
74
+ continue;
75
+ }
76
+ const value = renderScopeValue(raw);
71
77
  if (value === undefined)
72
78
  return { missing: pattern.variable };
73
79
  scopes[pattern.variable] = value;
@@ -75,29 +81,22 @@ export function storedScopesForRow(table, values) {
75
81
  return { scopes };
76
82
  }
77
83
  /**
78
- * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
79
- * the declared write variables must be allowed (or hold `'*'`).
84
+ * Write-path authorization (§3.4 step 3): a write set admits the row when
85
+ * each of its variables has a value the actor is allowed (or `'*'`). An
86
+ * insert and a rescope need the owner set; an existing row needs any set.
80
87
  */
81
- export function authorizeWrite(table, rowScopes, resolved) {
88
+ export function authorizeWrite(table, rowScopes, resolved, ownerOnly = false) {
82
89
  if (!resolved.ok)
83
90
  return false;
84
- for (const pattern of table.scopePatterns) {
85
- const value = rowScopes[pattern.variable];
86
- if (value === undefined || value.length === 0)
87
- return false;
88
- }
89
- for (const variable of table.writeScopeVariables) {
91
+ const { allowed } = resolved;
92
+ return (ownerOnly ? table.writeScopeSets.slice(0, 1) : table.writeScopeSets).some((set) => set.every((variable) => {
90
93
  const value = rowScopes[variable];
91
- if (value === undefined)
92
- return false;
93
- const allowedValues = resolved.allowed[variable];
94
- if (allowedValues === undefined)
95
- return false;
96
- if (!allowedValues.includes('*') && !allowedValues.includes(value)) {
97
- return false;
98
- }
99
- }
100
- return true;
94
+ const values = allowed[variable];
95
+ return (value !== undefined &&
96
+ value.length > 0 &&
97
+ values !== undefined &&
98
+ (values.includes('*') || values.includes(value)));
99
+ }));
101
100
  }
102
101
  /** Does a change's stored scopes match the effective scopes (§3.2)? */
103
102
  export function matchesEffective(storedScopes, effective) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/server",
3
- "version": "0.84.0",
3
+ "version": "0.85.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.84.0"
71
+ "@syncular/core": "0.85.0"
72
72
  },
73
73
  "devDependencies": {
74
74
  "@electric-sql/pglite": "^0.5.4"
package/src/push.ts CHANGED
@@ -392,21 +392,13 @@ async function applyOperation(
392
392
  'rescope targets an absent row (§2.2)',
393
393
  );
394
394
  }
395
- if (!authorizeWrite(table, stored.scopes, resolved)) {
395
+ if (!authorizeWrite(table, stored.scopes, resolved, true)) {
396
396
  return errorRecord(
397
397
  opIndex,
398
398
  'sync.forbidden',
399
399
  'rescope denied by scope authorization (§3.4)',
400
400
  );
401
401
  }
402
- const missing = missingScopeVariable(table, stored.scopes);
403
- if (missing !== undefined) {
404
- return errorRecord(
405
- opIndex,
406
- 'sync.missing_scopes',
407
- `stored row lacks scope variable ${JSON.stringify(missing)} (§3.1)`,
408
- );
409
- }
410
402
  let sparse: SparseRowValue[];
411
403
  try {
412
404
  sparse = decodeSparseRow(
@@ -473,7 +465,7 @@ async function applyOperation(
473
465
  `rescope missing scope column value for ${JSON.stringify(extracted.missing)} (§3.4)`,
474
466
  );
475
467
  }
476
- if (!authorizeWrite(table, extracted.scopes, resolved)) {
468
+ if (!authorizeWrite(table, extracted.scopes, resolved, true)) {
477
469
  return errorRecord(
478
470
  opIndex,
479
471
  'sync.forbidden',
@@ -633,14 +625,6 @@ async function applyOperation(
633
625
  'delete denied by scope authorization (§3.4)',
634
626
  );
635
627
  }
636
- const missing = missingScopeVariable(table, stored.scopes);
637
- if (missing !== undefined) {
638
- return errorRecord(
639
- opIndex,
640
- 'sync.missing_scopes',
641
- `stored row lacks scope variable ${JSON.stringify(missing)} (§3.1)`,
642
- );
643
- }
644
628
  // §6.7: validate the delete against the stored row (row = undefined,
645
629
  // stored = the row about to be removed). Only reached for an existing
646
630
  // row — an absent-row delete is an idempotent no-op above.
@@ -910,9 +894,8 @@ async function applyOperation(
910
894
  };
911
895
  }
912
896
 
913
- // Insert path: no stored row (§5.2). The authorization row is the payload
914
- // plus the primary key (§3.4 step 2); a missing or empty scope column value
915
- // ⇒ deny.
897
+ // Insert path: no stored row (§5.2). The owner set authorizes the payload
898
+ // plus the primary key (§3.4 steps 2 and 3).
916
899
  const values: RowValue[] = sparse.map((value) => value ?? null);
917
900
  const extracted = storedScopesForRow(table, values);
918
901
  const insert =
@@ -922,7 +905,7 @@ async function applyOperation(
922
905
  'sync.forbidden',
923
906
  'insert missing scope column value (§3.4)',
924
907
  )
925
- : authorizeWrite(table, extracted.scopes, resolved)
908
+ : authorizeWrite(table, extracted.scopes, resolved, true)
926
909
  ? extracted
927
910
  : errorRecord(
928
911
  opIndex,
@@ -1111,17 +1094,6 @@ async function checkAndRecordBlobs(
1111
1094
  return undefined;
1112
1095
  }
1113
1096
 
1114
- function missingScopeVariable(
1115
- table: CompiledTable,
1116
- scopes: Record<string, string>,
1117
- ): string | undefined {
1118
- for (const pattern of table.scopePatterns) {
1119
- const value = scopes[pattern.variable];
1120
- if (value === undefined || value.length === 0) return pattern.variable;
1121
- }
1122
- return undefined;
1123
- }
1124
-
1125
1097
  function commitValidationReader(
1126
1098
  tx: StorageTransaction,
1127
1099
  schema: CompiledSchema,
package/src/schema.ts CHANGED
@@ -75,8 +75,11 @@ 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
+ /** Write sets (§3.4): one list of variables, or alternative lists whose
79
+ * first is the owner set. Defaults to one set of every scope variable. */
80
+ readonly writeScopeVariables?:
81
+ | readonly string[]
82
+ | readonly (readonly string[])[];
80
83
  /** User indexes (optional) — created on the server's relational tables. */
81
84
  readonly indexes?: readonly IndexSchema[];
82
85
  /** Server-only indexes (optional); names share the namespace of `indexes`. */
@@ -122,7 +125,8 @@ export interface CompiledTable {
122
125
  readonly columns: readonly RowColumn[];
123
126
  readonly primaryKeyIndex: number;
124
127
  readonly scopePatterns: readonly CompiledScopePattern[];
125
- readonly writeScopeVariables: readonly string[];
128
+ /** §3.4 write sets; the first is the owner set. */
129
+ readonly writeScopeSets: readonly (readonly string[])[];
126
130
  /** User indexes (validated: unique names, existing columns). */
127
131
  readonly indexes: readonly IndexSchema[];
128
132
  /** Server-only indexes (validated like `indexes`). */
@@ -345,15 +349,33 @@ export function compileSchema(schema: ServerSchema): CompiledSchema {
345
349
  variables.add(pattern.variable);
346
350
  declaredVariables.add(pattern.variable);
347
351
  }
348
- const writeScopeVariables = table.writeScopeVariables ?? [...variables];
352
+ // §3.4: one list is one set; a list of lists holds alternative sets.
353
+ const declaredSets: readonly (string | readonly string[])[] =
354
+ table.writeScopeVariables ?? [[...variables]];
355
+ const flatSet = declaredSets.filter(
356
+ (entry): entry is string => typeof entry === 'string',
357
+ );
358
+ const writeScopeSets =
359
+ flatSet.length > 0
360
+ ? [flatSet]
361
+ : declaredSets.filter((entry) => typeof entry !== 'string');
362
+ const setKeys = new Set(
363
+ writeScopeSets.map((set) => JSON.stringify([...set].sort())),
364
+ );
349
365
  if (
350
- !Array.isArray(writeScopeVariables) ||
351
- writeScopeVariables.length === 0 ||
352
- new Set(writeScopeVariables).size !== writeScopeVariables.length ||
353
- writeScopeVariables.some((variable) => !variables.has(variable))
366
+ (flatSet.length > 0 && flatSet.length !== declaredSets.length) ||
367
+ writeScopeSets.length === 0 ||
368
+ setKeys.size !== writeScopeSets.length ||
369
+ writeScopeSets.some(
370
+ (set) =>
371
+ !Array.isArray(set) ||
372
+ set.length === 0 ||
373
+ new Set(set).size !== set.length ||
374
+ set.some((variable) => !variables.has(variable)),
375
+ )
354
376
  ) {
355
377
  throw new Error(
356
- `table ${table.name}: writeScopeVariables must contain distinct declared scope variables (§3.4)`,
378
+ `table ${table.name}: writeScopeVariables must be one list or distinct lists of distinct declared scope variables (§3.4)`,
357
379
  );
358
380
  }
359
381
  const blobRefColumnIndices: number[] = [];
@@ -410,7 +432,7 @@ export function compileSchema(schema: ServerSchema): CompiledSchema {
410
432
  columns: table.columns,
411
433
  primaryKeyIndex,
412
434
  scopePatterns,
413
- writeScopeVariables,
435
+ writeScopeSets,
414
436
  indexes,
415
437
  serverIndexes,
416
438
  references,
package/src/scopes.ts CHANGED
@@ -80,8 +80,9 @@ export function renderScopeValue(
80
80
  }
81
81
 
82
82
  /**
83
- * Extract the stored scopes (§3.1) from a decoded row. Returns the missing
84
- * variable name when a declared scope column is absent or empty.
83
+ * Extract the stored scopes (§3.1) from a decoded row. A NULL column outside
84
+ * the owner set leaves its variable without a stored scope. Returns the
85
+ * variable name when a column is empty, or NULL in the owner set.
85
86
  */
86
87
  export function storedScopesForRow(
87
88
  table: CompiledTable,
@@ -89,7 +90,14 @@ export function storedScopesForRow(
89
90
  ): { scopes: StoredScopes } | { missing: string } {
90
91
  const scopes: StoredScopes = {};
91
92
  for (const pattern of table.scopePatterns) {
92
- const value = renderScopeValue(values[pattern.columnIndex]);
93
+ const raw = values[pattern.columnIndex];
94
+ if (
95
+ (raw === null || raw === undefined) &&
96
+ !table.writeScopeSets[0]!.includes(pattern.variable)
97
+ ) {
98
+ continue;
99
+ }
100
+ const value = renderScopeValue(raw);
93
101
  if (value === undefined) return { missing: pattern.variable };
94
102
  scopes[pattern.variable] = value;
95
103
  }
@@ -97,29 +105,32 @@ export function storedScopesForRow(
97
105
  }
98
106
 
99
107
  /**
100
- * Write-path authorization (§3.4 steps 2–3): all stored values must exist;
101
- * the declared write variables must be allowed (or hold `'*'`).
108
+ * Write-path authorization (§3.4 step 3): a write set admits the row when
109
+ * each of its variables has a value the actor is allowed (or `'*'`). An
110
+ * insert and a rescope need the owner set; an existing row needs any set.
102
111
  */
103
112
  export function authorizeWrite(
104
113
  table: CompiledTable,
105
114
  rowScopes: StoredScopes,
106
115
  resolved: ResolvedScopes,
116
+ ownerOnly = false,
107
117
  ): boolean {
108
118
  if (!resolved.ok) return false;
109
- for (const pattern of table.scopePatterns) {
110
- const value = rowScopes[pattern.variable];
111
- if (value === undefined || value.length === 0) return false;
112
- }
113
- for (const variable of table.writeScopeVariables) {
114
- const value = rowScopes[variable];
115
- if (value === undefined) return false;
116
- const allowedValues = resolved.allowed[variable];
117
- if (allowedValues === undefined) return false;
118
- if (!allowedValues.includes('*') && !allowedValues.includes(value)) {
119
- return false;
120
- }
121
- }
122
- return true;
119
+ const { allowed } = resolved;
120
+ return (
121
+ ownerOnly ? table.writeScopeSets.slice(0, 1) : table.writeScopeSets
122
+ ).some((set) =>
123
+ set.every((variable) => {
124
+ const value = rowScopes[variable];
125
+ const values = allowed[variable];
126
+ return (
127
+ value !== undefined &&
128
+ value.length > 0 &&
129
+ values !== undefined &&
130
+ (values.includes('*') || values.includes(value))
131
+ );
132
+ }),
133
+ );
123
134
  }
124
135
 
125
136
  /** Does a change's stored scopes match the effective scopes (§3.2)? */