@pgxsinkit/contracts 0.2.4 → 0.2.6
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/event-stream.d.ts +158 -0
- package/dist/event-stream.d.ts.map +1 -0
- package/dist/events.d.ts +158 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +588 -69
- package/dist/index.js.map +11 -7
- package/dist/projection.d.ts +2 -2
- package/dist/projection.d.ts.map +1 -1
- package/dist/registry-diff.d.ts +57 -4
- package/dist/registry-diff.d.ts.map +1 -1
- package/dist/registry-invariant.d.ts +110 -0
- package/dist/registry-invariant.d.ts.map +1 -0
- package/dist/registry.d.ts +144 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/runtime.d.ts +4 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/sql-role-guard.d.ts +21 -0
- package/dist/sql-role-guard.d.ts.map +1 -0
- package/dist/supabase-rls.d.ts +113 -8
- package/dist/supabase-rls.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/registry-authoring/SKILL.md +280 -222
- package/src/event-stream.ts +214 -0
- package/src/events.ts +154 -0
- package/src/index.ts +4 -0
- package/src/projection.ts +7 -2
- package/src/registry-diff.ts +235 -7
- package/src/registry-invariant.ts +218 -0
- package/src/registry.ts +413 -3
- package/src/runtime.ts +4 -3
- package/src/sql-role-guard.ts +33 -0
- package/src/supabase-rls.ts +336 -48
package/dist/index.js
CHANGED
|
@@ -181,8 +181,62 @@ import {
|
|
|
181
181
|
} from "drizzle-orm/pg-core";
|
|
182
182
|
import { varchar } from "drizzle-orm/pg-core";
|
|
183
183
|
import { getColumns } from "drizzle-orm/utils";
|
|
184
|
+
|
|
185
|
+
// packages/contracts/src/event-stream.ts
|
|
186
|
+
var EVENT_STREAM_QUEUE_PREFIX = "pgxsinkit_events_";
|
|
187
|
+
var EVENT_STREAM_NAME_MAX_LENGTH = 47 - EVENT_STREAM_QUEUE_PREFIX.length;
|
|
188
|
+
var EVENT_STREAM_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
189
|
+
function defineEventStream(input) {
|
|
190
|
+
return {
|
|
191
|
+
payload: input.payload,
|
|
192
|
+
identity: input.identity,
|
|
193
|
+
...input.revision != null ? { revision: input.revision } : {}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function isZodSchema(value) {
|
|
197
|
+
return typeof value === "object" && value !== null && typeof value.safeParse === "function" && typeof value.parse === "function";
|
|
198
|
+
}
|
|
199
|
+
function zodDefOf(schema) {
|
|
200
|
+
const def = schema?._zod?.def;
|
|
201
|
+
return def != null && typeof def === "object" ? def : undefined;
|
|
202
|
+
}
|
|
203
|
+
function hasNonStrictObjectRoot(schema) {
|
|
204
|
+
const seen = new Set;
|
|
205
|
+
const walk = (candidate) => {
|
|
206
|
+
if (candidate == null || seen.has(candidate)) {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
seen.add(candidate);
|
|
210
|
+
const def = zodDefOf(candidate);
|
|
211
|
+
if (!def) {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
if (def.type === "object") {
|
|
215
|
+
return zodDefOf(def.catchall)?.type !== "never";
|
|
216
|
+
}
|
|
217
|
+
if (def.type === "union" && Array.isArray(def.options)) {
|
|
218
|
+
return def.options.some(walk);
|
|
219
|
+
}
|
|
220
|
+
return false;
|
|
221
|
+
};
|
|
222
|
+
return walk(schema);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// packages/contracts/src/registry.ts
|
|
184
226
|
var syncRegistrySchemaSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistrySchema");
|
|
185
227
|
var syncRegistryStorageSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryStorage");
|
|
228
|
+
var syncRegistryRowClassesSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryRowClasses");
|
|
229
|
+
var syncRegistryStreamsSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryStreams");
|
|
230
|
+
function isManagedFieldGuarded(field, operation) {
|
|
231
|
+
switch (operation) {
|
|
232
|
+
case "create":
|
|
233
|
+
return field.applyOn.includes("create");
|
|
234
|
+
case "update":
|
|
235
|
+
return true;
|
|
236
|
+
case "delete":
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
186
240
|
function viewColumnsForProjection(columns, omittedColumns) {
|
|
187
241
|
if (omittedColumns.length === 0) {
|
|
188
242
|
return columns;
|
|
@@ -356,11 +410,13 @@ function defineReadProjection(owner, opts) {
|
|
|
356
410
|
electricTable: physicalTable,
|
|
357
411
|
...rowFilter != null ? { rowFilter } : {}
|
|
358
412
|
};
|
|
413
|
+
const rowClass = opts.rowClass ?? owner.rowClass;
|
|
359
414
|
const projection = {
|
|
360
415
|
...built,
|
|
361
416
|
table: owner.table,
|
|
362
417
|
shape,
|
|
363
418
|
readProjection: true,
|
|
419
|
+
...rowClass != null ? { rowClass } : {},
|
|
364
420
|
...serverProjection != null ? { serverProjection } : {}
|
|
365
421
|
};
|
|
366
422
|
return projection;
|
|
@@ -373,7 +429,9 @@ function defineSyncRegistry(input) {
|
|
|
373
429
|
validateRegistryTableUniqueness(input.tables);
|
|
374
430
|
validateRegistryLifecycleGroups(input.tables);
|
|
375
431
|
validateStorageDeclaration(input.storage);
|
|
376
|
-
|
|
432
|
+
validateRowClassification(input.tables, input.rowClasses);
|
|
433
|
+
validateEventStreams(input.streams);
|
|
434
|
+
return attachSyncRegistryStreams(attachSyncRegistryRowClasses(attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage), input.rowClasses), input.streams);
|
|
377
435
|
}
|
|
378
436
|
for (const entry of getRegistryEntries(input)) {
|
|
379
437
|
validateSyncTableEntry(entry);
|
|
@@ -550,6 +608,144 @@ function getSyncRegistryStorage(registry) {
|
|
|
550
608
|
const storage = Reflect.get(registry, syncRegistryStorageSymbol);
|
|
551
609
|
return storage != null && typeof storage === "object" ? storage : undefined;
|
|
552
610
|
}
|
|
611
|
+
function attachSyncRegistryRowClasses(registry, rowClasses) {
|
|
612
|
+
if (rowClasses == null) {
|
|
613
|
+
return registry;
|
|
614
|
+
}
|
|
615
|
+
const existing = getSyncRegistryRowClasses(registry);
|
|
616
|
+
if (existing != null) {
|
|
617
|
+
if (existing.length !== rowClasses.length || existing.some((value, index) => value !== rowClasses[index])) {
|
|
618
|
+
throw new Error(`conflicting rowClasses declaration for registry: already [${existing.join(", ")}], cannot re-declare ` + `[${rowClasses.join(", ")}]`);
|
|
619
|
+
}
|
|
620
|
+
return registry;
|
|
621
|
+
}
|
|
622
|
+
Object.defineProperty(registry, syncRegistryRowClassesSymbol, {
|
|
623
|
+
value: Object.freeze([...rowClasses]),
|
|
624
|
+
enumerable: false,
|
|
625
|
+
configurable: false,
|
|
626
|
+
writable: false
|
|
627
|
+
});
|
|
628
|
+
return registry;
|
|
629
|
+
}
|
|
630
|
+
function getSyncRegistryRowClasses(registry) {
|
|
631
|
+
const rowClasses = Reflect.get(registry, syncRegistryRowClassesSymbol);
|
|
632
|
+
return Array.isArray(rowClasses) ? rowClasses : undefined;
|
|
633
|
+
}
|
|
634
|
+
function attachSyncRegistryStreams(registry, streams) {
|
|
635
|
+
if (streams == null) {
|
|
636
|
+
return registry;
|
|
637
|
+
}
|
|
638
|
+
const existing = getSyncRegistryStreams(registry);
|
|
639
|
+
if (existing != null) {
|
|
640
|
+
const existingNames = Object.keys(existing).sort();
|
|
641
|
+
const nextNames = Object.keys(streams).sort();
|
|
642
|
+
const same = existingNames.length === nextNames.length && existingNames.every((name, index) => name === nextNames[index] && existing[name] === streams[name]);
|
|
643
|
+
if (!same) {
|
|
644
|
+
throw new Error(`conflicting streams declaration for registry: already [${existingNames.join(", ")}], cannot re-declare ` + `[${nextNames.join(", ")}]`);
|
|
645
|
+
}
|
|
646
|
+
return registry;
|
|
647
|
+
}
|
|
648
|
+
Object.defineProperty(registry, syncRegistryStreamsSymbol, {
|
|
649
|
+
value: Object.freeze({ ...streams }),
|
|
650
|
+
enumerable: false,
|
|
651
|
+
configurable: false,
|
|
652
|
+
writable: false
|
|
653
|
+
});
|
|
654
|
+
return registry;
|
|
655
|
+
}
|
|
656
|
+
function getSyncRegistryStreams(registry) {
|
|
657
|
+
const streams = Reflect.get(registry, syncRegistryStreamsSymbol);
|
|
658
|
+
return streams != null && typeof streams === "object" ? streams : undefined;
|
|
659
|
+
}
|
|
660
|
+
function validateEventStreams(streams) {
|
|
661
|
+
if (streams == null) {
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
const problems = [];
|
|
665
|
+
for (const [name, entry] of Object.entries(streams)) {
|
|
666
|
+
if (!EVENT_STREAM_NAME_PATTERN.test(name)) {
|
|
667
|
+
problems.push(`"${name}": invalid Event-stream name \u2014 must match ${EVENT_STREAM_NAME_PATTERN.source} ` + `(lowercase letters, digits and underscores, starting with a letter)`);
|
|
668
|
+
} else if (name.length > EVENT_STREAM_NAME_MAX_LENGTH) {
|
|
669
|
+
problems.push(`"${name}": Event-stream name is ${name.length} characters \u2014 at most ${EVENT_STREAM_NAME_MAX_LENGTH} ` + `are allowed, because each stream is provisioned as the pgmq queue ` + `"${EVENT_STREAM_QUEUE_PREFIX}${name}" and pgmq's queue-name limit is 47 characters, of which the ` + `"${EVENT_STREAM_QUEUE_PREFIX}" prefix consumes ${EVENT_STREAM_QUEUE_PREFIX.length}`);
|
|
670
|
+
}
|
|
671
|
+
if (entry == null || typeof entry !== "object") {
|
|
672
|
+
problems.push(`"${name}": not an Event-stream entry \u2014 declare it with defineEventStream({ payload, identity })`);
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (!isZodSchema(entry.payload)) {
|
|
676
|
+
problems.push(`"${name}": payload is not a zod schema \u2014 declare a strict zod schema for the event payload`);
|
|
677
|
+
} else if (hasNonStrictObjectRoot(entry.payload)) {
|
|
678
|
+
problems.push(`"${name}": the payload's object schema is not strict \u2014 declare it with \`.strict()\` or ` + `\`z.strictObject()\` (every object inside a union payload too), so an unknown key is REJECTED at ` + `\`appendEvent\` instead of being silently stripped on the way to the consumer`);
|
|
679
|
+
}
|
|
680
|
+
if (entry.revision != null && (!Number.isInteger(entry.revision) || entry.revision <= 0)) {
|
|
681
|
+
problems.push(`"${name}": revision must be a positive integer (it is the opaque counter you bump when acceptance ` + `logic the JSON-Schema hash cannot see \u2014 a refinement threshold, a transform \u2014 changes)`);
|
|
682
|
+
}
|
|
683
|
+
if (entry.identity == null || typeof entry.identity !== "object") {
|
|
684
|
+
problems.push(`"${name}": identity must be a record of field name -> { claimPath }`);
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
for (const [field, spec] of Object.entries(entry.identity)) {
|
|
688
|
+
if (field.trim().length === 0) {
|
|
689
|
+
problems.push(`"${name}": an identity field name is empty`);
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
const claimPath = spec?.claimPath;
|
|
693
|
+
if (!Array.isArray(claimPath) || claimPath.length === 0) {
|
|
694
|
+
problems.push(`"${name}".identity.${field}: claimPath must be a non-empty JSON path into the verified claims ` + `(e.g. ["sub"] or ["app_metadata", "person_id"])`);
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
if (claimPath.some((segment) => typeof segment !== "string" || segment.trim().length === 0)) {
|
|
698
|
+
problems.push(`"${name}".identity.${field}: every claimPath segment must be a non-empty string`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
if (problems.length === 0) {
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
throw new Error(`invalid Event-stream registration (ADR-0053). The record key IS the Event-stream name, and each entry ` + `must be a defineEventStream({ payload, identity }) \u2014 ${problems.join("; ")}.`);
|
|
706
|
+
}
|
|
707
|
+
function validateRowClassification(registry, rowClasses) {
|
|
708
|
+
if (rowClasses == null) {
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (rowClasses.length === 0) {
|
|
712
|
+
throw new Error(`rowClasses is declared but empty: a declared vocabulary makes classification mandatory, so an empty ` + `set can never be satisfied. Declare the classes this registry uses, or omit rowClasses entirely.`);
|
|
713
|
+
}
|
|
714
|
+
const seen = new Set;
|
|
715
|
+
const duplicates = new Set;
|
|
716
|
+
for (const rowClass of rowClasses) {
|
|
717
|
+
if (typeof rowClass !== "string" || rowClass.length === 0) {
|
|
718
|
+
throw new Error(`rowClasses contains an invalid value ${JSON.stringify(rowClass)}: each class must be a non-empty string`);
|
|
719
|
+
}
|
|
720
|
+
if (seen.has(rowClass)) {
|
|
721
|
+
duplicates.add(rowClass);
|
|
722
|
+
}
|
|
723
|
+
seen.add(rowClass);
|
|
724
|
+
}
|
|
725
|
+
if (duplicates.size > 0) {
|
|
726
|
+
throw new Error(`rowClasses declares duplicate classes: ${[...duplicates].join(", ")}`);
|
|
727
|
+
}
|
|
728
|
+
const unclassified = [];
|
|
729
|
+
const unknown = [];
|
|
730
|
+
for (const [key, entry] of Object.entries(registry)) {
|
|
731
|
+
const rowClass = entry.rowClass;
|
|
732
|
+
if (rowClass == null) {
|
|
733
|
+
unclassified.push(key);
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
if (!seen.has(rowClass)) {
|
|
737
|
+
unknown.push(`${key} (rowClass "${rowClass}")`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (unclassified.length === 0 && unknown.length === 0) {
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const problems = [
|
|
744
|
+
...unclassified.length > 0 ? [`unclassified entries: ${unclassified.join(", ")}`] : [],
|
|
745
|
+
...unknown.length > 0 ? [`entries with an undeclared class: ${unknown.join(", ")}`] : []
|
|
746
|
+
];
|
|
747
|
+
throw new Error(`row classification is incomplete (ADR-0052). This registry declares rowClasses ` + `[${rowClasses.join(", ")}], so every entry must carry a rowClass from that set \u2014 ${problems.join("; ")}. ` + `Classify each entry (or widen rowClasses if a genuinely new kind of row has arrived).`);
|
|
748
|
+
}
|
|
553
749
|
function validateStorageDeclaration(storage) {
|
|
554
750
|
if (storage == null) {
|
|
555
751
|
return;
|
|
@@ -859,6 +1055,43 @@ var CONVERGENCE_EVENTS = [
|
|
|
859
1055
|
effect: "subscription reset + re-stream; affected entity state re-derives from the fresh synced rows"
|
|
860
1056
|
}
|
|
861
1057
|
];
|
|
1058
|
+
// packages/contracts/src/events.ts
|
|
1059
|
+
import { z as z3 } from "zod";
|
|
1060
|
+
var MAX_EVENTS_PER_BATCH = 1000;
|
|
1061
|
+
var MAX_EVENT_PAYLOAD_BYTES = 64 * 1024;
|
|
1062
|
+
var MAX_EVENT_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
1063
|
+
var batchEventPaths = ["/api/events"];
|
|
1064
|
+
var eventEnvelopeSchema = z3.object({
|
|
1065
|
+
stream: z3.string().trim().min(1),
|
|
1066
|
+
eventId: z3.uuid(),
|
|
1067
|
+
occurredAtUs: unixMicrosecondsSchema,
|
|
1068
|
+
payload: z3.unknown()
|
|
1069
|
+
}).strict();
|
|
1070
|
+
var batchEventRequestSchema = z3.object({
|
|
1071
|
+
events: z3.array(eventEnvelopeSchema).min(1).max(MAX_EVENTS_PER_BATCH)
|
|
1072
|
+
}).strict();
|
|
1073
|
+
var eventAckStatusSchema = z3.enum(["acked", "refused", "rejected", "deferred"]);
|
|
1074
|
+
var eventAckSchema = z3.object({
|
|
1075
|
+
eventId: z3.uuid(),
|
|
1076
|
+
status: eventAckStatusSchema,
|
|
1077
|
+
reason: z3.string().trim().min(1).optional()
|
|
1078
|
+
}).strict();
|
|
1079
|
+
var batchEventAckSchema = z3.object({
|
|
1080
|
+
acks: z3.array(eventAckSchema)
|
|
1081
|
+
}).strict();
|
|
1082
|
+
var batchEventErrorSchema = z3.object({
|
|
1083
|
+
message: z3.string().optional()
|
|
1084
|
+
});
|
|
1085
|
+
var stampedEventSchema = z3.object({
|
|
1086
|
+
eventId: z3.uuid(),
|
|
1087
|
+
occurredAtUs: unixMicrosecondsSchema,
|
|
1088
|
+
identity: z3.record(z3.string().trim().min(1), z3.string()),
|
|
1089
|
+
payload: z3.unknown()
|
|
1090
|
+
}).strict();
|
|
1091
|
+
var eventQueueMessageSchema = z3.object({
|
|
1092
|
+
stream: z3.string().trim().min(1),
|
|
1093
|
+
events: z3.array(stampedEventSchema).min(1)
|
|
1094
|
+
}).strict();
|
|
862
1095
|
// packages/contracts/src/fingerprint.ts
|
|
863
1096
|
import { getTableConfig as getTableConfig3 } from "drizzle-orm/pg-core";
|
|
864
1097
|
var byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
@@ -972,12 +1205,60 @@ function hashString(input) {
|
|
|
972
1205
|
return high.toString(16).padStart(8, "0") + low.toString(16).padStart(8, "0");
|
|
973
1206
|
}
|
|
974
1207
|
// packages/contracts/src/registry-diff.ts
|
|
1208
|
+
import { z as z4 } from "zod";
|
|
1209
|
+
var asString2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
1210
|
+
function registryRowClasses(registry) {
|
|
1211
|
+
const classes = {};
|
|
1212
|
+
for (const key of Object.keys(registry).sort()) {
|
|
1213
|
+
classes[key] = registry[key]?.rowClass ?? null;
|
|
1214
|
+
}
|
|
1215
|
+
return classes;
|
|
1216
|
+
}
|
|
1217
|
+
function stableStringify(value) {
|
|
1218
|
+
if (Array.isArray(value)) {
|
|
1219
|
+
return `[${value.map(stableStringify).join(",")}]`;
|
|
1220
|
+
}
|
|
1221
|
+
if (value !== null && typeof value === "object") {
|
|
1222
|
+
const entries = Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => asString2(a, b)).map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);
|
|
1223
|
+
return `{${entries.join(",")}}`;
|
|
1224
|
+
}
|
|
1225
|
+
return JSON.stringify(value) ?? "null";
|
|
1226
|
+
}
|
|
1227
|
+
function canonicalEventStreamString(entry) {
|
|
1228
|
+
let payload;
|
|
1229
|
+
try {
|
|
1230
|
+
payload = stableStringify(z4.toJSONSchema(entry.payload, { io: "input", unrepresentable: "any" }));
|
|
1231
|
+
} catch {
|
|
1232
|
+
payload = '"<unrepresentable>"';
|
|
1233
|
+
}
|
|
1234
|
+
const identity = Object.keys(entry.identity ?? {}).sort(asString2).map((field) => [field, [...entry.identity[field]?.claimPath ?? []]]);
|
|
1235
|
+
return stableStringify({ payload, identity, revision: entry.revision ?? 0 });
|
|
1236
|
+
}
|
|
1237
|
+
function registryEventStreams(registry) {
|
|
1238
|
+
const streams = getSyncRegistryStreams(registry);
|
|
1239
|
+
const hashes = {};
|
|
1240
|
+
if (!streams) {
|
|
1241
|
+
return hashes;
|
|
1242
|
+
}
|
|
1243
|
+
for (const name of Object.keys(streams).sort(asString2)) {
|
|
1244
|
+
const entry = streams[name];
|
|
1245
|
+
if (entry) {
|
|
1246
|
+
hashes[name] = hashString(canonicalEventStreamString(entry));
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return hashes;
|
|
1250
|
+
}
|
|
975
1251
|
var SEVERITY_RANK = { compatible: 0, risky: 1, breaking: 2 };
|
|
976
1252
|
function maxSeverity(changes) {
|
|
977
1253
|
return changes.reduce((worst, change) => SEVERITY_RANK[change.severity] > SEVERITY_RANK[worst] ? change.severity : worst, "compatible");
|
|
978
1254
|
}
|
|
979
1255
|
function buildRegistryLock(registry) {
|
|
980
|
-
return {
|
|
1256
|
+
return {
|
|
1257
|
+
version: fingerprintRegistry(registry),
|
|
1258
|
+
tables: canonicalizeRegistry(registry),
|
|
1259
|
+
rowClasses: registryRowClasses(registry),
|
|
1260
|
+
streams: registryEventStreams(registry)
|
|
1261
|
+
};
|
|
981
1262
|
}
|
|
982
1263
|
function diffTable(table, previous, next, changes) {
|
|
983
1264
|
const prevColumns = new Map(previous.columns.map((column) => [column.name, column]));
|
|
@@ -1053,10 +1334,59 @@ function diffShape(table, previous, next, changes) {
|
|
|
1053
1334
|
changes.push({ severity: "risky", table, detail: "row filter changed (re-sync required)" });
|
|
1054
1335
|
}
|
|
1055
1336
|
}
|
|
1056
|
-
function
|
|
1337
|
+
function diffRowClass(table, previous, next, changes) {
|
|
1338
|
+
if (previous === next) {
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
if (previous == null) {
|
|
1342
|
+
changes.push({ severity: "compatible", table, detail: `row class declared: ${next}` });
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
if (next == null) {
|
|
1346
|
+
changes.push({
|
|
1347
|
+
severity: "risky",
|
|
1348
|
+
table,
|
|
1349
|
+
detail: `row class removed: ${previous} (un-enrols from registry invariants)`
|
|
1350
|
+
});
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
changes.push({
|
|
1354
|
+
severity: "risky",
|
|
1355
|
+
table,
|
|
1356
|
+
detail: `row class changed: ${previous} -> ${next} (review invariant enrollment)`
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
function diffEventStreams(previous, next, changes) {
|
|
1360
|
+
for (const name of Object.keys(previous).sort(asString2)) {
|
|
1361
|
+
const nextHash = next[name];
|
|
1362
|
+
if (nextHash === undefined) {
|
|
1363
|
+
changes.push({
|
|
1364
|
+
severity: "breaking",
|
|
1365
|
+
table: name,
|
|
1366
|
+
detail: `event stream removed: ${name} (in-flight client events will be deferred/refused)`
|
|
1367
|
+
});
|
|
1368
|
+
continue;
|
|
1369
|
+
}
|
|
1370
|
+
if (previous[name] !== nextHash) {
|
|
1371
|
+
changes.push({
|
|
1372
|
+
severity: "risky",
|
|
1373
|
+
table: name,
|
|
1374
|
+
detail: `event stream ${name} payload/identity changed (must remain backward-compatible; ` + `incompatible change requires a new Event-stream name)`
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
for (const name of Object.keys(next).sort(asString2)) {
|
|
1379
|
+
if (!(name in previous)) {
|
|
1380
|
+
changes.push({ severity: "compatible", table: name, detail: `event stream added: ${name}` });
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
function diffCanonicalRegistries(previous, next, rowClasses, streams) {
|
|
1057
1385
|
const changes = [];
|
|
1058
1386
|
const prevByKey = new Map(previous.map((table) => [table.key, table]));
|
|
1059
1387
|
const nextByKey = new Map(next.map((table) => [table.key, table]));
|
|
1388
|
+
const prevClasses = rowClasses?.previous ?? {};
|
|
1389
|
+
const nextClasses = rowClasses?.next ?? {};
|
|
1060
1390
|
for (const [key, prevTable] of prevByKey) {
|
|
1061
1391
|
const nextTable = nextByKey.get(key);
|
|
1062
1392
|
if (!nextTable) {
|
|
@@ -1064,19 +1394,21 @@ function diffCanonicalRegistries(previous, next) {
|
|
|
1064
1394
|
continue;
|
|
1065
1395
|
}
|
|
1066
1396
|
diffTable(key, prevTable, nextTable, changes);
|
|
1397
|
+
diffRowClass(key, prevClasses[key] ?? null, nextClasses[key] ?? null, changes);
|
|
1067
1398
|
}
|
|
1068
1399
|
for (const key of nextByKey.keys()) {
|
|
1069
1400
|
if (!prevByKey.has(key)) {
|
|
1070
1401
|
changes.push({ severity: "compatible", table: key, detail: "table added" });
|
|
1071
1402
|
}
|
|
1072
1403
|
}
|
|
1404
|
+
diffEventStreams(streams?.previous ?? {}, streams?.next ?? {}, changes);
|
|
1073
1405
|
return { changes, severity: maxSeverity(changes) };
|
|
1074
1406
|
}
|
|
1075
1407
|
function compareRegistries(previous, next) {
|
|
1076
|
-
return diffCanonicalRegistries(canonicalizeRegistry(previous), canonicalizeRegistry(next));
|
|
1408
|
+
return diffCanonicalRegistries(canonicalizeRegistry(previous), canonicalizeRegistry(next), { previous: registryRowClasses(previous), next: registryRowClasses(next) }, { previous: registryEventStreams(previous), next: registryEventStreams(next) });
|
|
1077
1409
|
}
|
|
1078
1410
|
function diffRegistryAgainstLock(registry, lock) {
|
|
1079
|
-
return diffCanonicalRegistries(lock.tables, canonicalizeRegistry(registry));
|
|
1411
|
+
return diffCanonicalRegistries(lock.tables, canonicalizeRegistry(registry), { previous: lock.rowClasses, next: registryRowClasses(registry) }, { previous: lock.streams, next: registryEventStreams(registry) });
|
|
1080
1412
|
}
|
|
1081
1413
|
function runRegistryCheck(input) {
|
|
1082
1414
|
const diff = diffRegistryAgainstLock(input.registry, input.lock);
|
|
@@ -1089,10 +1421,78 @@ function summarizeRegistryDiff(diff) {
|
|
|
1089
1421
|
return diff.changes.map((change) => `[${change.severity}] ${change.table}: ${change.detail}`).join(`
|
|
1090
1422
|
`);
|
|
1091
1423
|
}
|
|
1424
|
+
// packages/contracts/src/registry-invariant.ts
|
|
1425
|
+
import { getTableConfig as getTableConfig4, PgDialect as PgDialect2 } from "drizzle-orm/pg-core";
|
|
1426
|
+
var policyDialect = new PgDialect2;
|
|
1427
|
+
function renderPolicyPredicate(fragment) {
|
|
1428
|
+
return fragment == null ? null : policyDialect.sqlToQuery(fragment.inlineParams()).sql;
|
|
1429
|
+
}
|
|
1430
|
+
function renderPolicies(entry) {
|
|
1431
|
+
return getTableConfig4(entry.table).policies.map((policy) => ({
|
|
1432
|
+
name: policy.name,
|
|
1433
|
+
command: policy.for ?? "all",
|
|
1434
|
+
using: renderPolicyPredicate(policy.using),
|
|
1435
|
+
withCheck: renderPolicyPredicate(policy.withCheck)
|
|
1436
|
+
}));
|
|
1437
|
+
}
|
|
1438
|
+
function renderWhere(entry, claims) {
|
|
1439
|
+
const rowFilter = entry.shape?.rowFilter;
|
|
1440
|
+
return rowFilter == null ? null : buildRowFilterShape(rowFilter, claims);
|
|
1441
|
+
}
|
|
1442
|
+
function boundEntries(registry, appliesTo) {
|
|
1443
|
+
const entries = Object.entries(registry);
|
|
1444
|
+
if (typeof appliesTo === "function") {
|
|
1445
|
+
return entries.filter(([key, entry]) => appliesTo(entry, key));
|
|
1446
|
+
}
|
|
1447
|
+
const classes = new Set(appliesTo);
|
|
1448
|
+
return entries.filter(([, entry]) => entry.rowClass != null && classes.has(entry.rowClass));
|
|
1449
|
+
}
|
|
1450
|
+
function assertRegistryInvariant(registry, spec) {
|
|
1451
|
+
const declaredClasses = getSyncRegistryRowClasses(registry);
|
|
1452
|
+
if (Array.isArray(spec.appliesTo) && declaredClasses != null) {
|
|
1453
|
+
const unknown = spec.appliesTo.filter((rowClass) => !declaredClasses.includes(rowClass));
|
|
1454
|
+
if (unknown.length > 0) {
|
|
1455
|
+
throw new Error(`registry invariant "${spec.name}" applies to unknown row class(es): ${unknown.join(", ")}. This ` + `registry declares [${declaredClasses.join(", ")}] \u2014 a misspelled class would bind no entries and ` + `pass vacuously, so it is rejected here.`);
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
const bound = boundEntries(registry, spec.appliesTo);
|
|
1459
|
+
if (bound.length === 0) {
|
|
1460
|
+
const binding = Array.isArray(spec.appliesTo) ? `row class(es) ${spec.appliesTo.join(", ")}` : "its predicate";
|
|
1461
|
+
throw new Error(`registry invariant "${spec.name}" binds no entries (${binding}). An invariant that checks nothing ` + `passes vacuously, which defeats the point \u2014 check the class name(s) against the entries' rowClass, ` + `or drop the invariant if its rows are gone.`);
|
|
1462
|
+
}
|
|
1463
|
+
const fixtures = Object.entries(spec.claimsFixtures);
|
|
1464
|
+
if (fixtures.length === 0) {
|
|
1465
|
+
throw new Error(`registry invariant "${spec.name}" declares no claims fixtures: the invariant is evaluated per persona, ` + `so with none it checks nothing. Declare at least one (e.g. { anonymous: {} }).`);
|
|
1466
|
+
}
|
|
1467
|
+
const violations = [];
|
|
1468
|
+
for (const [key, entry] of bound) {
|
|
1469
|
+
const renderedPolicies = renderPolicies(entry);
|
|
1470
|
+
for (const [fixtureName, claims] of fixtures) {
|
|
1471
|
+
const verdict = spec.holds({
|
|
1472
|
+
key,
|
|
1473
|
+
entry,
|
|
1474
|
+
rowClass: entry.rowClass,
|
|
1475
|
+
fixtureName,
|
|
1476
|
+
claims,
|
|
1477
|
+
renderedWhere: renderWhere(entry, claims),
|
|
1478
|
+
renderedPolicies
|
|
1479
|
+
});
|
|
1480
|
+
if (verdict === true) {
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
violations.push(`${key} (${fixtureName}): ${typeof verdict === "string" ? verdict : "invariant does not hold"}`);
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
if (violations.length > 0) {
|
|
1487
|
+
throw new Error(`registry invariant "${spec.name}" is violated by ${violations.length} of ${bound.length * fixtures.length} ` + `checked cells:
|
|
1488
|
+
${violations.join(`
|
|
1489
|
+
`)}`);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1092
1492
|
// packages/contracts/src/mutation.ts
|
|
1093
|
-
import { z as
|
|
1094
|
-
var mutationKindSchema =
|
|
1095
|
-
var mutationStatusSchema =
|
|
1493
|
+
import { z as z5 } from "zod";
|
|
1494
|
+
var mutationKindSchema = z5.enum(["create", "update", "delete"]);
|
|
1495
|
+
var mutationStatusSchema = z5.enum([
|
|
1096
1496
|
"pending",
|
|
1097
1497
|
"sending",
|
|
1098
1498
|
"acked",
|
|
@@ -1101,48 +1501,48 @@ var mutationStatusSchema = z3.enum([
|
|
|
1101
1501
|
"conflicted",
|
|
1102
1502
|
"rejected"
|
|
1103
1503
|
]);
|
|
1104
|
-
var mutationAckStatusSchema =
|
|
1105
|
-
var entityKeySchema =
|
|
1106
|
-
var mutationEnvelopeSchema =
|
|
1107
|
-
tableName:
|
|
1504
|
+
var mutationAckStatusSchema = z5.enum(["acked", "failed", "conflicted", "rejected"]);
|
|
1505
|
+
var entityKeySchema = z5.record(z5.string().trim().min(1), z5.string().trim().min(1));
|
|
1506
|
+
var mutationEnvelopeSchema = z5.object({
|
|
1507
|
+
tableName: z5.string().trim().min(1),
|
|
1108
1508
|
entityKey: entityKeySchema,
|
|
1109
|
-
mutationId:
|
|
1110
|
-
mutationSeq:
|
|
1509
|
+
mutationId: z5.uuid(),
|
|
1510
|
+
mutationSeq: z5.number().int().nonnegative(),
|
|
1111
1511
|
kind: mutationKindSchema,
|
|
1112
|
-
payload:
|
|
1512
|
+
payload: z5.unknown(),
|
|
1113
1513
|
clientTimestampUs: unixMicrosecondsSchema,
|
|
1114
1514
|
baseServerVersion: unixMicrosecondsSchema.optional()
|
|
1115
1515
|
}).strict();
|
|
1116
|
-
var mutationAckSchema =
|
|
1117
|
-
tableName:
|
|
1516
|
+
var mutationAckSchema = z5.object({
|
|
1517
|
+
tableName: z5.string().trim().min(1),
|
|
1118
1518
|
entityKey: entityKeySchema,
|
|
1119
|
-
mutationId:
|
|
1120
|
-
mutationSeq:
|
|
1519
|
+
mutationId: z5.uuid(),
|
|
1520
|
+
mutationSeq: z5.number().int().nonnegative(),
|
|
1121
1521
|
status: mutationAckStatusSchema,
|
|
1122
1522
|
serverUpdatedAtUs: unixMicrosecondsSchema.optional(),
|
|
1123
|
-
conflictReason:
|
|
1124
|
-
rejectionReason:
|
|
1125
|
-
httpStatus:
|
|
1523
|
+
conflictReason: z5.string().trim().min(1).optional(),
|
|
1524
|
+
rejectionReason: z5.string().trim().min(1).optional(),
|
|
1525
|
+
httpStatus: z5.number().int().min(100).max(599).optional()
|
|
1126
1526
|
}).strict();
|
|
1127
|
-
var batchMutationRequestSchema =
|
|
1128
|
-
mutations:
|
|
1527
|
+
var batchMutationRequestSchema = z5.object({
|
|
1528
|
+
mutations: z5.array(mutationEnvelopeSchema).min(1)
|
|
1129
1529
|
}).strict();
|
|
1130
|
-
var authoritativeWriteRequestSchema =
|
|
1131
|
-
writeUnit:
|
|
1132
|
-
mutations:
|
|
1530
|
+
var authoritativeWriteRequestSchema = z5.object({
|
|
1531
|
+
writeUnit: z5.string().trim().min(1).optional(),
|
|
1532
|
+
mutations: z5.array(mutationEnvelopeSchema).min(1)
|
|
1133
1533
|
}).strict();
|
|
1134
|
-
var batchMutationAckSchema =
|
|
1135
|
-
acks:
|
|
1534
|
+
var batchMutationAckSchema = z5.object({
|
|
1535
|
+
acks: z5.array(mutationAckSchema)
|
|
1136
1536
|
}).strict();
|
|
1137
|
-
var mutationRejectionSchema =
|
|
1138
|
-
tableName:
|
|
1139
|
-
mutationId:
|
|
1140
|
-
mutationSeq:
|
|
1141
|
-
reason:
|
|
1537
|
+
var mutationRejectionSchema = z5.object({
|
|
1538
|
+
tableName: z5.string().trim().min(1),
|
|
1539
|
+
mutationId: z5.uuid(),
|
|
1540
|
+
mutationSeq: z5.number().int().nonnegative(),
|
|
1541
|
+
reason: z5.string().trim().min(1)
|
|
1142
1542
|
}).strict();
|
|
1143
|
-
var batchMutationErrorSchema =
|
|
1144
|
-
message:
|
|
1145
|
-
rejections:
|
|
1543
|
+
var batchMutationErrorSchema = z5.object({
|
|
1544
|
+
message: z5.string().optional(),
|
|
1545
|
+
rejections: z5.array(mutationRejectionSchema).optional()
|
|
1146
1546
|
});
|
|
1147
1547
|
// packages/contracts/src/projection.ts
|
|
1148
1548
|
function asReadonly(entry) {
|
|
@@ -1158,6 +1558,7 @@ function asReadonly(entry) {
|
|
|
1158
1558
|
mode: "readonly",
|
|
1159
1559
|
primaryKey: entry.primaryKey,
|
|
1160
1560
|
applyMode: entry.applyMode,
|
|
1561
|
+
...entry.rowClass != null ? { rowClass: entry.rowClass } : {},
|
|
1161
1562
|
...entry.shape != null ? { shape: entry.shape } : {},
|
|
1162
1563
|
...readonlyProjection != null ? { clientProjection: readonlyProjection } : {},
|
|
1163
1564
|
...entry.serverProjection != null ? { serverProjection: entry.serverProjection } : {},
|
|
@@ -1196,18 +1597,46 @@ import { sql as sql2 } from "drizzle-orm";
|
|
|
1196
1597
|
var NOW_MICROSECONDS_SQL_TEXT = "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)";
|
|
1197
1598
|
var CLOCK_US_CALL_SQL_TEXT = "public.pgxsinkit_clock_us()";
|
|
1198
1599
|
var clockMicrosecondsSql = sql2.raw(CLOCK_US_CALL_SQL_TEXT);
|
|
1600
|
+
// packages/contracts/src/sql-role-guard.ts
|
|
1601
|
+
function buildRoleGuardedStatement(roleName, statementSql) {
|
|
1602
|
+
return [
|
|
1603
|
+
"DO $$",
|
|
1604
|
+
"BEGIN",
|
|
1605
|
+
` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${escapeSqlLiteral(roleName)}') THEN`,
|
|
1606
|
+
` EXECUTE '${escapeSqlLiteral(statementSql)}';`,
|
|
1607
|
+
" END IF;",
|
|
1608
|
+
"END;",
|
|
1609
|
+
"$$;"
|
|
1610
|
+
].join(`
|
|
1611
|
+
`);
|
|
1612
|
+
}
|
|
1199
1613
|
// packages/contracts/src/supabase-rls.ts
|
|
1200
1614
|
import { and, eq, getTableName, or, sql as sql3 } from "drizzle-orm";
|
|
1201
|
-
import { PgDialect as
|
|
1202
|
-
var textDialect = new
|
|
1615
|
+
import { PgDialect as PgDialect3, pgPolicy } from "drizzle-orm/pg-core";
|
|
1616
|
+
var textDialect = new PgDialect3;
|
|
1203
1617
|
function renderInlineSql(fragment) {
|
|
1204
1618
|
return textDialect.sqlToQuery(fragment.inlineParams()).sql;
|
|
1205
1619
|
}
|
|
1620
|
+
function readClaimsPath(claims, path) {
|
|
1621
|
+
let current = claims;
|
|
1622
|
+
for (const segment of path) {
|
|
1623
|
+
if (typeof current !== "object" || current === null || Array.isArray(current)) {
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
current = current[segment];
|
|
1627
|
+
}
|
|
1628
|
+
return current;
|
|
1629
|
+
}
|
|
1630
|
+
function readSubjectClaim(claims) {
|
|
1631
|
+
const subject = readClaimsPath(claims, ["sub"]);
|
|
1632
|
+
return typeof subject === "string" && subject.length > 0 ? subject : null;
|
|
1633
|
+
}
|
|
1206
1634
|
var defaultOwnerSqlColumn = "owner_id";
|
|
1207
1635
|
var defaultOwnerPropertyKey = "ownerId";
|
|
1208
1636
|
var defaultAuthenticatedRoleName = "authenticated";
|
|
1209
1637
|
var defaultAdminRoleName = "admin";
|
|
1210
1638
|
var defaultSubjectCastType = "uuid";
|
|
1639
|
+
var adminRolesClaimPath = ["app_metadata", "roles"];
|
|
1211
1640
|
var ownerOrAdminPolicyShapes = [
|
|
1212
1641
|
{
|
|
1213
1642
|
command: "select",
|
|
@@ -1260,19 +1689,30 @@ function buildSubjectSqlText(subjectCastType) {
|
|
|
1260
1689
|
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
|
|
1261
1690
|
)::${subjectCastType}`;
|
|
1262
1691
|
}
|
|
1263
|
-
function
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1692
|
+
function resolveAdminRolesClaimPath(path) {
|
|
1693
|
+
const segments = path && path.length > 0 ? [...path] : [...adminRolesClaimPath];
|
|
1694
|
+
for (const segment of segments) {
|
|
1695
|
+
assertIdentifier(segment, "adminRolesClaimPath segment");
|
|
1696
|
+
}
|
|
1697
|
+
return segments;
|
|
1698
|
+
}
|
|
1699
|
+
function buildClaimPathChainSql(path) {
|
|
1700
|
+
return sql3.join(path.map((segment) => sql3` -> ${segment}`), sql3``);
|
|
1701
|
+
}
|
|
1702
|
+
function buildClaimArraySqlText(claimSqlText) {
|
|
1703
|
+
return `case jsonb_typeof(${claimSqlText}) when 'array' then ${claimSqlText} else '[]'::jsonb end`;
|
|
1704
|
+
}
|
|
1705
|
+
function buildAdminRoleExistsSqlText(adminRoleName, claimPath) {
|
|
1706
|
+
const rolesClaim = renderInlineSql(sql3`(
|
|
1269
1707
|
coalesce(
|
|
1270
1708
|
nullif(current_setting('request.jwt.claim', true), ''),
|
|
1271
1709
|
nullif(current_setting('request.jwt.claims', true), '')
|
|
1272
|
-
)::jsonb
|
|
1273
|
-
)
|
|
1274
|
-
|
|
1275
|
-
|
|
1710
|
+
)::jsonb${buildClaimPathChainSql(claimPath)}
|
|
1711
|
+
)`);
|
|
1712
|
+
return renderInlineSql(sql3`EXISTS (
|
|
1713
|
+
SELECT 1
|
|
1714
|
+
FROM jsonb_array_elements_text(
|
|
1715
|
+
${sql3.raw(buildClaimArraySqlText(rolesClaim))}
|
|
1276
1716
|
) AS assigned_role(role_name_value)
|
|
1277
1717
|
WHERE assigned_role.role_name_value = ${adminRoleName}
|
|
1278
1718
|
)`);
|
|
@@ -1286,20 +1726,21 @@ function normalizePredicateOptions(options = {}) {
|
|
|
1286
1726
|
return {
|
|
1287
1727
|
ownerSqlColumn,
|
|
1288
1728
|
adminRoleName,
|
|
1289
|
-
subjectCastType
|
|
1729
|
+
subjectCastType,
|
|
1730
|
+
claimPath: resolveAdminRolesClaimPath(options.adminRolesClaimPath)
|
|
1290
1731
|
};
|
|
1291
1732
|
}
|
|
1292
1733
|
function buildSupabaseOwnerOrAdminPredicateSqlText(options = {}) {
|
|
1293
1734
|
const normalized = normalizePredicateOptions(options);
|
|
1294
1735
|
return `
|
|
1295
1736
|
${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}
|
|
1296
|
-
OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName)}
|
|
1737
|
+
OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName, normalized.claimPath)}
|
|
1297
1738
|
`;
|
|
1298
1739
|
}
|
|
1299
1740
|
function buildSupabaseOwnerOrAdminNativePolicies(options) {
|
|
1300
1741
|
const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
|
|
1301
1742
|
const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);
|
|
1302
|
-
const adminExists = sql3.raw(buildAdminRoleExistsSqlText(adminRoleName));
|
|
1743
|
+
const adminExists = sql3.raw(buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)));
|
|
1303
1744
|
const predicate = or(eq(options.ownerColumn, subject), adminExists);
|
|
1304
1745
|
const tableName = tableNameForColumn(options.ownerColumn, "ownerColumn");
|
|
1305
1746
|
return ownerOrAdminPolicyShapes.map((shape) => pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {
|
|
@@ -1317,6 +1758,16 @@ var supabaseOwnerOrAdminDefaults = {
|
|
|
1317
1758
|
adminRoleName: defaultAdminRoleName,
|
|
1318
1759
|
subjectCastType: defaultSubjectCastType
|
|
1319
1760
|
};
|
|
1761
|
+
function resolveOwnerOrAdminAccess(claims, options = {}) {
|
|
1762
|
+
const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
|
|
1763
|
+
const roles = readClaimsPath(claims, resolveAdminRolesClaimPath(options.adminRolesClaimPath));
|
|
1764
|
+
const admin = Array.isArray(roles) && roles.some((role) => typeof role === "string" && role === adminRoleName);
|
|
1765
|
+
return { admin, subject: readSubjectClaim(claims) };
|
|
1766
|
+
}
|
|
1767
|
+
function buildOwnerOrAdminShapeWhere(ownerColumn, claims, options = {}) {
|
|
1768
|
+
const access = resolveOwnerOrAdminAccess(claims, options);
|
|
1769
|
+
return access.admin ? null : buildOwnershipShapeWhere(ownerColumn, access.subject);
|
|
1770
|
+
}
|
|
1320
1771
|
var defaultManagerRoleValue = "manager";
|
|
1321
1772
|
var membershipPolicyShapes = [
|
|
1322
1773
|
{ command: "select", using: true, withCheck: false },
|
|
@@ -1383,8 +1834,16 @@ function buildSupabaseMembershipNativePolicies(options) {
|
|
|
1383
1834
|
});
|
|
1384
1835
|
});
|
|
1385
1836
|
}
|
|
1837
|
+
function buildMembershipShapeWhere(columns, claims) {
|
|
1838
|
+
const subject = readSubjectClaim(claims);
|
|
1839
|
+
if (subject === null) {
|
|
1840
|
+
return DENY_ALL;
|
|
1841
|
+
}
|
|
1842
|
+
return sql3`${c(columns.containerColumn)} in (select ${c(columns.membershipContainerColumn)} from ${columns.membershipTable} where ${c(columns.membershipSubjectColumn)} = ${subject})`;
|
|
1843
|
+
}
|
|
1386
1844
|
var defaultGrantsClaimPath = ["app_metadata", "authorization", "grants"];
|
|
1387
1845
|
var defaultGrantScopeCastType = "uuid";
|
|
1846
|
+
var defaultBypassScopeKind = "platform";
|
|
1388
1847
|
var grantScopePolicyShapes = [
|
|
1389
1848
|
{ command: "select", using: true, withCheck: false },
|
|
1390
1849
|
{ command: "insert", using: false, withCheck: true },
|
|
@@ -1399,15 +1858,12 @@ function resolveGrantsClaimPath(path) {
|
|
|
1399
1858
|
return segments;
|
|
1400
1859
|
}
|
|
1401
1860
|
function buildGrantsArraySqlText(path) {
|
|
1402
|
-
return `
|
|
1403
|
-
(
|
|
1861
|
+
return buildClaimArraySqlText(`(
|
|
1404
1862
|
coalesce(
|
|
1405
1863
|
nullif(current_setting('request.jwt.claim', true), ''),
|
|
1406
1864
|
nullif(current_setting('request.jwt.claims', true), '')
|
|
1407
1865
|
)::jsonb #> '{${path.join(",")}}'
|
|
1408
|
-
)
|
|
1409
|
-
'[]'::jsonb
|
|
1410
|
-
)`;
|
|
1866
|
+
)`);
|
|
1411
1867
|
}
|
|
1412
1868
|
function buildRoleInListSqlText(roleValues) {
|
|
1413
1869
|
if (roleValues.length === 0) {
|
|
@@ -1421,7 +1877,7 @@ function resolveGrantScopeIdField(options) {
|
|
|
1421
1877
|
return field;
|
|
1422
1878
|
}
|
|
1423
1879
|
function buildBypassExistsSqlText(bypass, grantsText) {
|
|
1424
|
-
const scopeKind = bypass.scopeKind ??
|
|
1880
|
+
const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;
|
|
1425
1881
|
return `exists (
|
|
1426
1882
|
select 1
|
|
1427
1883
|
from jsonb_array_elements(${grantsText}) as bypass_grant
|
|
@@ -1457,16 +1913,6 @@ function buildSupabaseGrantScopeNativePolicies(options) {
|
|
|
1457
1913
|
...shape.withCheck ? { withCheck: predicate } : {}
|
|
1458
1914
|
}));
|
|
1459
1915
|
}
|
|
1460
|
-
function readClaimsPath(claims, path) {
|
|
1461
|
-
let current = claims;
|
|
1462
|
-
for (const segment of path) {
|
|
1463
|
-
if (typeof current !== "object" || current === null || Array.isArray(current)) {
|
|
1464
|
-
return;
|
|
1465
|
-
}
|
|
1466
|
-
current = current[segment];
|
|
1467
|
-
}
|
|
1468
|
-
return current;
|
|
1469
|
-
}
|
|
1470
1916
|
function resolveGrantScopeIds(claims, options) {
|
|
1471
1917
|
const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));
|
|
1472
1918
|
if (!Array.isArray(grants)) {
|
|
@@ -1504,17 +1950,63 @@ function buildGrantScopeShapeWhere(scopeColumn, ids) {
|
|
|
1504
1950
|
}
|
|
1505
1951
|
return sql3`${c(scopeColumn)} in (${sql3.join(ids.map((id) => sql3`${id}`), sql3`, `)})`;
|
|
1506
1952
|
}
|
|
1953
|
+
function hasGrantScopeBypass(claims, options) {
|
|
1954
|
+
const bypass = options.bypass;
|
|
1955
|
+
if (!bypass) {
|
|
1956
|
+
return false;
|
|
1957
|
+
}
|
|
1958
|
+
const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));
|
|
1959
|
+
if (!Array.isArray(grants)) {
|
|
1960
|
+
return false;
|
|
1961
|
+
}
|
|
1962
|
+
const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;
|
|
1963
|
+
const roleValues = new Set(bypass.roleValues);
|
|
1964
|
+
for (const grant of grants) {
|
|
1965
|
+
if (typeof grant !== "object" || grant === null) {
|
|
1966
|
+
continue;
|
|
1967
|
+
}
|
|
1968
|
+
const record = grant;
|
|
1969
|
+
if (!roleValues.has(String(record["role"]))) {
|
|
1970
|
+
continue;
|
|
1971
|
+
}
|
|
1972
|
+
const scope = record["scope"];
|
|
1973
|
+
if (typeof scope !== "object" || scope === null) {
|
|
1974
|
+
continue;
|
|
1975
|
+
}
|
|
1976
|
+
if (scope["kind"] === scopeKind) {
|
|
1977
|
+
return true;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
return false;
|
|
1981
|
+
}
|
|
1982
|
+
function resolveGrantScopeAccess(claims, options) {
|
|
1983
|
+
return {
|
|
1984
|
+
bypass: hasGrantScopeBypass(claims, options),
|
|
1985
|
+
ids: resolveGrantScopeIds(claims, options)
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
function buildGrantScopeAccessShapeWhere(scopeColumn, claims, options) {
|
|
1989
|
+
const access = resolveGrantScopeAccess(claims, options);
|
|
1990
|
+
return access.bypass ? null : buildGrantScopeShapeWhere(scopeColumn, access.ids);
|
|
1991
|
+
}
|
|
1507
1992
|
export {
|
|
1508
1993
|
withRetention,
|
|
1509
1994
|
unixMicrosecondsSchema,
|
|
1995
|
+
syncRegistryStreamsSymbol,
|
|
1510
1996
|
syncRegistryStorageSymbol,
|
|
1511
1997
|
syncRegistrySchemaSymbol,
|
|
1998
|
+
syncRegistryRowClassesSymbol,
|
|
1512
1999
|
supabaseOwnerOrAdminDefaults,
|
|
1513
2000
|
summarizeRegistryDiff,
|
|
2001
|
+
stampedEventSchema,
|
|
1514
2002
|
runRegistryCheck,
|
|
1515
2003
|
resolveStorageDeclaration,
|
|
1516
2004
|
resolveServerVersionColumnName,
|
|
2005
|
+
resolveOwnerOrAdminAccess,
|
|
1517
2006
|
resolveGrantScopeIds,
|
|
2007
|
+
resolveGrantScopeAccess,
|
|
2008
|
+
registryRowClasses,
|
|
2009
|
+
registryEventStreams,
|
|
1518
2010
|
quoteSqlLiteral,
|
|
1519
2011
|
quoteIdentifier,
|
|
1520
2012
|
normalizeCastPositionType,
|
|
@@ -1526,16 +2018,21 @@ export {
|
|
|
1526
2018
|
mutationAckSchema,
|
|
1527
2019
|
maybeQuoteIdentifier,
|
|
1528
2020
|
jwtClaimsSchema,
|
|
2021
|
+
isZodSchema,
|
|
1529
2022
|
isWriteMode,
|
|
1530
2023
|
isSubscriptionTiming,
|
|
1531
2024
|
isStorageDurability,
|
|
1532
2025
|
isStorageBackend,
|
|
1533
2026
|
isRetention,
|
|
2027
|
+
isManagedFieldGuarded,
|
|
1534
2028
|
isConflictPolicy,
|
|
1535
2029
|
isClaimsDependentRowFilter,
|
|
1536
2030
|
hashString,
|
|
2031
|
+
hasNonStrictObjectRoot,
|
|
2032
|
+
getSyncRegistryStreams,
|
|
1537
2033
|
getSyncRegistryStorage,
|
|
1538
2034
|
getSyncRegistrySchema,
|
|
2035
|
+
getSyncRegistryRowClasses,
|
|
1539
2036
|
getProjectedColumns,
|
|
1540
2037
|
getProjectedColumnNames,
|
|
1541
2038
|
getOmittedProjectedColumns,
|
|
@@ -1545,6 +2042,10 @@ export {
|
|
|
1545
2042
|
getLocalSyncPrimaryKey,
|
|
1546
2043
|
fingerprintRegistry,
|
|
1547
2044
|
fingerprintReadContract,
|
|
2045
|
+
eventQueueMessageSchema,
|
|
2046
|
+
eventEnvelopeSchema,
|
|
2047
|
+
eventAckStatusSchema,
|
|
2048
|
+
eventAckSchema,
|
|
1548
2049
|
escapeSqlLiteral,
|
|
1549
2050
|
entityKeySchema,
|
|
1550
2051
|
diffRegistryAgainstLock,
|
|
@@ -1553,6 +2054,7 @@ export {
|
|
|
1553
2054
|
defineSyncTable,
|
|
1554
2055
|
defineSyncRegistry,
|
|
1555
2056
|
defineReadProjection,
|
|
2057
|
+
defineEventStream,
|
|
1556
2058
|
compareRegistries,
|
|
1557
2059
|
clockMicrosecondsSql,
|
|
1558
2060
|
classifyTableApplyStrategy,
|
|
@@ -1568,17 +2070,28 @@ export {
|
|
|
1568
2070
|
buildSupabaseMembershipNativePolicies,
|
|
1569
2071
|
buildSupabaseGrantScopeNativePolicies,
|
|
1570
2072
|
buildRowFilterShape,
|
|
2073
|
+
buildRoleGuardedStatement,
|
|
1571
2074
|
buildRegistryLock,
|
|
1572
2075
|
buildOwnershipShapeWhere,
|
|
2076
|
+
buildOwnerOrAdminShapeWhere,
|
|
1573
2077
|
buildOverlayResolutionBarrier,
|
|
2078
|
+
buildMembershipShapeWhere,
|
|
1574
2079
|
buildGrantScopeShapeWhere,
|
|
2080
|
+
buildGrantScopeAccessShapeWhere,
|
|
1575
2081
|
batchMutationRequestSchema,
|
|
1576
2082
|
batchMutationErrorSchema,
|
|
1577
2083
|
batchMutationAckSchema,
|
|
2084
|
+
batchEventRequestSchema,
|
|
2085
|
+
batchEventPaths,
|
|
2086
|
+
batchEventErrorSchema,
|
|
2087
|
+
batchEventAckSchema,
|
|
1578
2088
|
authoritativeWriteRequestSchema,
|
|
2089
|
+
attachSyncRegistryStreams,
|
|
1579
2090
|
attachSyncRegistryStorage,
|
|
1580
2091
|
attachSyncRegistrySchema,
|
|
2092
|
+
attachSyncRegistryRowClasses,
|
|
1581
2093
|
assertStorageDeclarationCompatible,
|
|
2094
|
+
assertRegistryInvariant,
|
|
1582
2095
|
assertReadContractPreserved,
|
|
1583
2096
|
asReadonly,
|
|
1584
2097
|
asEphemeral,
|
|
@@ -1589,10 +2102,16 @@ export {
|
|
|
1589
2102
|
STORAGE_BACKENDS,
|
|
1590
2103
|
RETENTIONS,
|
|
1591
2104
|
NOW_MICROSECONDS_SQL_TEXT,
|
|
2105
|
+
MAX_EVENT_REQUEST_BYTES,
|
|
2106
|
+
MAX_EVENT_PAYLOAD_BYTES,
|
|
2107
|
+
MAX_EVENTS_PER_BATCH,
|
|
2108
|
+
EVENT_STREAM_QUEUE_PREFIX,
|
|
2109
|
+
EVENT_STREAM_NAME_PATTERN,
|
|
2110
|
+
EVENT_STREAM_NAME_MAX_LENGTH,
|
|
1592
2111
|
DENY_ALL,
|
|
1593
2112
|
CONVERGENCE_EVENTS,
|
|
1594
2113
|
CONFLICT_POLICIES,
|
|
1595
2114
|
CLOCK_US_CALL_SQL_TEXT
|
|
1596
2115
|
};
|
|
1597
2116
|
|
|
1598
|
-
//# debugId=
|
|
2117
|
+
//# debugId=7B2607AF400BBBC364756E2164756E21
|