@rebasepro/common 0.9.0 → 0.9.1-canary.0fce67c
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 +1 -1
- package/dist/collections/default-collections.d.ts +4 -0
- package/dist/data/buildRebaseData.d.ts +15 -2
- package/dist/index.es.js +696 -49
- package/dist/index.es.js.map +1 -1
- package/dist/util/auth-default-policies.d.ts +22 -0
- package/dist/util/identity.d.ts +83 -0
- package/dist/util/index.d.ts +3 -0
- package/dist/util/junction-policies.d.ts +108 -0
- package/dist/util/policy/evaluatePolicy.d.ts +8 -1
- package/dist/util/policy/index.d.ts +1 -0
- package/dist/util/policy/sqlToPolicy.d.ts +24 -14
- package/package.json +7 -8
- package/src/collections/default-collections.ts +2 -0
- package/src/data/buildRebaseData.ts +119 -24
- package/src/data/filter-dialect.ts +6 -0
- package/src/util/auth-default-policies.ts +152 -0
- package/src/util/identity.ts +166 -0
- package/src/util/index.ts +3 -0
- package/src/util/junction-policies.ts +353 -0
- package/src/util/policy/evaluatePolicy.ts +20 -4
- package/src/util/policy/index.ts +1 -0
- package/src/util/policy/policyToPostgres.ts +38 -12
- package/src/util/policy/sqlToPolicy.ts +190 -13
- package/dist/index.umd.js +0 -3311
- package/dist/index.umd.js.map +0 -1
package/dist/index.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ALL_WHERE_FILTER_OPS, CANONICAL_TO_REST, DEFAULT_DATA_SOURCE_KEY, EntityReference, EntityRelation, NULL_OPS, REST_TO_CANONICAL, getDataSourceCapabilities, getDeclaredSubcollections, policy, toCanonicalOp } from "@rebasepro/types";
|
|
2
|
-
import { deepClone, generateForeignKeyName, getIn, isDefaultFieldConfigId, mergeDeep, randomString, removeFunctions, toSnakeCase } from "@rebasepro/utils";
|
|
1
|
+
import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, CANONICAL_TO_REST, DEFAULT_DATA_SOURCE_KEY, EntityReference, EntityRelation, NULL_OPS, REST_TO_CANONICAL, getDataSourceCapabilities, getDeclaredSubcollections, isPostgresCollectionConfig, policy, toCanonicalOp } from "@rebasepro/types";
|
|
2
|
+
import { deepClone, generateForeignKeyName, getIn, getPolicyOperations, isDefaultFieldConfigId, mergeDeep, randomString, removeFunctions, toSnakeCase } from "@rebasepro/utils";
|
|
3
3
|
import jsonLogic from "json-logic-js";
|
|
4
4
|
import { deepEqual } from "fast-equals";
|
|
5
5
|
//#region src/util/common.ts
|
|
@@ -249,6 +249,113 @@ function getPrimaryKeys(collection) {
|
|
|
249
249
|
return ["id"];
|
|
250
250
|
}
|
|
251
251
|
//#endregion
|
|
252
|
+
//#region src/util/identity.ts
|
|
253
|
+
/** Separator between the parts of a composite address. */
|
|
254
|
+
var COMPOSITE_ID_SEPARATOR = ":::";
|
|
255
|
+
/**
|
|
256
|
+
* Derive a row's address from its key columns.
|
|
257
|
+
*
|
|
258
|
+
* Single key → the value as a string. Composite → each part joined by
|
|
259
|
+
* {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what
|
|
260
|
+
* {@link parseIdValues} expects to invert.
|
|
261
|
+
*/
|
|
262
|
+
function buildCompositeId(values, primaryKeys) {
|
|
263
|
+
if (primaryKeys.length === 0) return "";
|
|
264
|
+
if (primaryKeys.length === 1) return String(values[primaryKeys[0].fieldName] ?? "");
|
|
265
|
+
return primaryKeys.map((pk) => String(values[pk.fieldName] ?? "")).join(":::");
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Invert {@link buildCompositeId}: turn an address back into key columns, each
|
|
269
|
+
* coerced to the type its column actually round-trips as.
|
|
270
|
+
*
|
|
271
|
+
* This is the boundary where a URL segment becomes a query parameter, so a
|
|
272
|
+
* malformed address must throw rather than silently produce a query that
|
|
273
|
+
* matches the wrong row (or none).
|
|
274
|
+
*/
|
|
275
|
+
function parseIdValues(idValue, primaryKeys) {
|
|
276
|
+
const result = {};
|
|
277
|
+
if (primaryKeys.length === 0) return result;
|
|
278
|
+
if (primaryKeys.length === 1) {
|
|
279
|
+
const pk = primaryKeys[0];
|
|
280
|
+
if (pk.type === "number" && !pk.isUUID) {
|
|
281
|
+
const parsed = typeof idValue === "number" ? idValue : parseInt(String(idValue), 10);
|
|
282
|
+
if (isNaN(parsed)) throw new Error(`Invalid numeric ID: ${idValue}`);
|
|
283
|
+
result[pk.fieldName] = parsed;
|
|
284
|
+
} else result[pk.fieldName] = String(idValue);
|
|
285
|
+
return result;
|
|
286
|
+
}
|
|
287
|
+
const parts = String(idValue).split(":::");
|
|
288
|
+
if (parts.length !== primaryKeys.length) throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);
|
|
289
|
+
for (let i = 0; i < primaryKeys.length; i++) {
|
|
290
|
+
const pk = primaryKeys[i];
|
|
291
|
+
const val = parts[i];
|
|
292
|
+
if (pk.type === "number" && !pk.isUUID) {
|
|
293
|
+
const parsed = parseInt(val, 10);
|
|
294
|
+
if (isNaN(parsed)) throw new Error(`Invalid numeric ID component: ${val}`);
|
|
295
|
+
result[pk.fieldName] = parsed;
|
|
296
|
+
} else result[pk.fieldName] = val;
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The primary keys of a collection, as declared by its properties.
|
|
302
|
+
*
|
|
303
|
+
* This is the only tier both sides can read, because it is the only one written
|
|
304
|
+
* in the config: the postgres driver can also infer keys from the Drizzle
|
|
305
|
+
* schema, which the browser never sees and is never sent — the admin compiles
|
|
306
|
+
* the collection files into its own bundle rather than being served them. A key
|
|
307
|
+
* that lives only in the Drizzle schema is therefore invisible here, and the
|
|
308
|
+
* server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`
|
|
309
|
+
* to add.
|
|
310
|
+
*
|
|
311
|
+
* Returns an empty array when a collection declares none, which callers must
|
|
312
|
+
* treat as "not addressable" rather than defaulting to `id`: guessing a key
|
|
313
|
+
* that is not the real one produces confidently wrong addresses.
|
|
314
|
+
*/
|
|
315
|
+
function getDeclaredPrimaryKeys(collection) {
|
|
316
|
+
const properties = collection.properties;
|
|
317
|
+
if (!properties) return [];
|
|
318
|
+
const keys = [];
|
|
319
|
+
for (const [fieldName, propRaw] of Object.entries(properties)) {
|
|
320
|
+
const prop = propRaw;
|
|
321
|
+
if (!prop || typeof prop !== "object") continue;
|
|
322
|
+
if (!("isId" in prop) || !prop.isId) continue;
|
|
323
|
+
keys.push({
|
|
324
|
+
fieldName,
|
|
325
|
+
type: prop.type === "number" ? "number" : "string",
|
|
326
|
+
isUUID: prop.isId === "uuid"
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
return keys;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* The keys to address a collection's rows with, resolved the way the driver
|
|
333
|
+
* resolves them — minus the tier the browser cannot reach.
|
|
334
|
+
*
|
|
335
|
+
* The postgres driver tries, in order: properties marked `isId`; the primary
|
|
336
|
+
* keys of the Drizzle schema; and finally a column literally named `id`. Only
|
|
337
|
+
* the first and last are visible in a `CollectionConfig`, which is what both
|
|
338
|
+
* sides share.
|
|
339
|
+
*
|
|
340
|
+
* So the two agree except on a collection that declares no `isId` and whose key
|
|
341
|
+
* is known only to Drizzle. There, the driver reads the real key, and this
|
|
342
|
+
* either resolves nothing (reported to the console by the caller) or — if the
|
|
343
|
+
* table happens to have an unrelated `id` property — resolves `id`, which is
|
|
344
|
+
* the wrong key and cannot be detected from here: the addresses look right and
|
|
345
|
+
* route wrong. Only the config can settle it, so the server names both cases
|
|
346
|
+
* at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.
|
|
347
|
+
*/
|
|
348
|
+
function resolvePrimaryKeys(collection) {
|
|
349
|
+
const declared = getDeclaredPrimaryKeys(collection);
|
|
350
|
+
if (declared.length > 0) return declared;
|
|
351
|
+
const idProp = collection.properties?.id;
|
|
352
|
+
if (idProp && typeof idProp === "object") return [{
|
|
353
|
+
fieldName: "id",
|
|
354
|
+
type: idProp.type === "number" ? "number" : "string"
|
|
355
|
+
}];
|
|
356
|
+
return [];
|
|
357
|
+
}
|
|
358
|
+
//#endregion
|
|
252
359
|
//#region src/util/enums.ts
|
|
253
360
|
function enumToObjectEntries(enumValues) {
|
|
254
361
|
if (Array.isArray(enumValues)) return enumValues;
|
|
@@ -682,15 +789,109 @@ function getSubcollections(collection) {
|
|
|
682
789
|
* - `field = 'literal'`
|
|
683
790
|
* - `field != 'literal'`
|
|
684
791
|
* - `field = current_setting('app.user_id')`
|
|
685
|
-
* - `A AND B`
|
|
792
|
+
* - `A AND B`, `A OR B` — only where the keyword is at the top level
|
|
686
793
|
* - `true`
|
|
687
794
|
* - `IN (...)` (as optimistic true)
|
|
688
795
|
*
|
|
689
796
|
* For anything it doesn't understand, it returns a `raw` expression, which
|
|
690
797
|
* the evaluator treats as "unknown" (and usually optimistic true).
|
|
691
|
-
|
|
798
|
+
*
|
|
799
|
+
* **This output also round-trips back into DDL** via `policyToPostgres` (the
|
|
800
|
+
* schema/policy generators), so decomposing a clause the parser only partly
|
|
801
|
+
* understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,
|
|
802
|
+
* prefer `raw`: it is reproduced verbatim.
|
|
803
|
+
*/
|
|
804
|
+
/** True when `keyword` starts at `i` as a standalone word. */
|
|
805
|
+
function isKeywordAt(upper, i, keyword) {
|
|
806
|
+
if (!upper.startsWith(keyword, i)) return false;
|
|
807
|
+
const before = i === 0 ? " " : upper[i - 1];
|
|
808
|
+
const after = upper[i + keyword.length] ?? " ";
|
|
809
|
+
return /[\s()]/.test(before) && /[\s()]/.test(after);
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and
|
|
813
|
+
* outside a string literal. Returns null when it never does, so the caller
|
|
814
|
+
* leaves the clause alone.
|
|
815
|
+
*
|
|
816
|
+
* This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the
|
|
817
|
+
* `AND` inside
|
|
818
|
+
* `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = auth.uid())`
|
|
819
|
+
* split the expression, and re-emitting the halves produced
|
|
820
|
+
* `(EXISTS (...) AND m.user_id = auth.uid())`
|
|
821
|
+
* where `m` is no longer in scope — SQL that Postgres rejects outright with
|
|
822
|
+
* "missing FROM-clause entry for table". Returning null instead keeps such a
|
|
823
|
+
* clause as a `raw` expression, which round-trips verbatim.
|
|
824
|
+
*/
|
|
825
|
+
function splitTopLevel(sql, keyword) {
|
|
826
|
+
const upper = sql.toUpperCase();
|
|
827
|
+
const parts = [];
|
|
828
|
+
let depth = 0;
|
|
829
|
+
let inString = false;
|
|
830
|
+
let start = 0;
|
|
831
|
+
for (let i = 0; i < sql.length; i++) {
|
|
832
|
+
const ch = sql[i];
|
|
833
|
+
if (inString) {
|
|
834
|
+
if (ch === "'") if (sql[i + 1] === "'") i++;
|
|
835
|
+
else inString = false;
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
if (ch === "'") {
|
|
839
|
+
inString = true;
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
if (ch === "(") {
|
|
843
|
+
depth++;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (ch === ")") {
|
|
847
|
+
depth--;
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (depth === 0 && isKeywordAt(upper, i, keyword)) {
|
|
851
|
+
parts.push(sql.slice(start, i));
|
|
852
|
+
i += keyword.length - 1;
|
|
853
|
+
start = i + 1;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (parts.length === 0) return null;
|
|
857
|
+
parts.push(sql.slice(start));
|
|
858
|
+
const trimmedParts = parts.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
859
|
+
return trimmedParts.length > 1 ? trimmedParts : null;
|
|
860
|
+
}
|
|
861
|
+
/** Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`. */
|
|
862
|
+
function stripOuterParens(sql) {
|
|
863
|
+
let s = sql.trim();
|
|
864
|
+
for (;;) {
|
|
865
|
+
if (!s.startsWith("(") || !s.endsWith(")")) return s;
|
|
866
|
+
let depth = 0;
|
|
867
|
+
let inString = false;
|
|
868
|
+
let wraps = true;
|
|
869
|
+
for (let i = 0; i < s.length; i++) {
|
|
870
|
+
const ch = s[i];
|
|
871
|
+
if (inString) {
|
|
872
|
+
if (ch === "'") if (s[i + 1] === "'") i++;
|
|
873
|
+
else inString = false;
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
if (ch === "'") {
|
|
877
|
+
inString = true;
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
if (ch === "(") depth++;
|
|
881
|
+
else if (ch === ")") {
|
|
882
|
+
depth--;
|
|
883
|
+
if (depth === 0 && i < s.length - 1) {
|
|
884
|
+
wraps = false;
|
|
885
|
+
break;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (!wraps) return s;
|
|
890
|
+
s = s.slice(1, -1).trim();
|
|
891
|
+
}
|
|
892
|
+
}
|
|
692
893
|
function sqlToPolicy(sql) {
|
|
693
|
-
const trimmed = sql.trim();
|
|
894
|
+
const trimmed = stripOuterParens(sql.trim());
|
|
694
895
|
if (trimmed.toLowerCase() === "true") return policy.true();
|
|
695
896
|
if (trimmed.toLowerCase() === "false") return policy.false();
|
|
696
897
|
const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\s*\[(.+)\]$/i);
|
|
@@ -703,14 +904,10 @@ function sqlToPolicy(sql) {
|
|
|
703
904
|
const roles = containMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
|
|
704
905
|
return policy.rolesContain(roles);
|
|
705
906
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
if (trimmed.toUpperCase().includes(" AND ")) {
|
|
711
|
-
const parts = trimmed.split(/ AND /i);
|
|
712
|
-
return policy.and(...parts.map(sqlToPolicy));
|
|
713
|
-
}
|
|
907
|
+
const orParts = splitTopLevel(trimmed, "OR");
|
|
908
|
+
if (orParts) return policy.or(...orParts.map(sqlToPolicy));
|
|
909
|
+
const andParts = splitTopLevel(trimmed, "AND");
|
|
910
|
+
if (andParts) return policy.and(...andParts.map(sqlToPolicy));
|
|
714
911
|
const match = trimmed.match(/^(.+?)\s*(!?=)\s*(.+)$/);
|
|
715
912
|
if (match) {
|
|
716
913
|
const [, leftStr, op, rightStr] = match;
|
|
@@ -720,6 +917,77 @@ function sqlToPolicy(sql) {
|
|
|
720
917
|
}
|
|
721
918
|
return policy.raw(sql);
|
|
722
919
|
}
|
|
920
|
+
/**
|
|
921
|
+
* Literals from other BaaS platforms that people compare `auth.uid()` against
|
|
922
|
+
* out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on
|
|
923
|
+
* `pgRoles`, one surface over: the same muscle memory inside a `using:` string
|
|
924
|
+
* is the more dangerous spelling, because it inverts a rule instead of
|
|
925
|
+
* emptying a table.
|
|
926
|
+
*/
|
|
927
|
+
var FOREIGN_CONVENTION_UIDS = {
|
|
928
|
+
anon: "Supabase",
|
|
929
|
+
authenticated: "Supabase",
|
|
930
|
+
service_role: "Supabase"
|
|
931
|
+
};
|
|
932
|
+
/** `auth.uid() IS NOT NULL` in raw SQL, the clause that is always true. */
|
|
933
|
+
var UID_NOT_NULL = /auth\.uid\(\)\s+IS\s+NOT\s+NULL/i;
|
|
934
|
+
/**
|
|
935
|
+
* Find clauses that read as "signed-in users only" but admit anonymous callers.
|
|
936
|
+
*
|
|
937
|
+
* Both spellings come from the same place — Supabase, where `auth.uid()` really
|
|
938
|
+
* is NULL for an anonymous request. Rebase substitutes
|
|
939
|
+
* {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which
|
|
940
|
+
* is how the trusted *server* context is recognised), so:
|
|
941
|
+
*
|
|
942
|
+
* - `auth.uid() IS NOT NULL` is a tautology on the user path, and
|
|
943
|
+
* - `auth.uid() != 'anon'` compares against a string no caller ever has.
|
|
944
|
+
*
|
|
945
|
+
* Either one turns a lockdown into a full grant, and neither looks wrong. No
|
|
946
|
+
* real user id is ever one of these literals, and a user-context request is
|
|
947
|
+
* never NULL, so a match is always a mistake rather than a deliberate check.
|
|
948
|
+
*
|
|
949
|
+
* Structured expressions are checked too, not just parsed SQL: `policy.compare`
|
|
950
|
+
* can spell the same mistake.
|
|
951
|
+
*/
|
|
952
|
+
function findAnonymousGrants(expr) {
|
|
953
|
+
const found = [];
|
|
954
|
+
const visit = (e) => {
|
|
955
|
+
switch (e.kind) {
|
|
956
|
+
case "and":
|
|
957
|
+
case "or":
|
|
958
|
+
e.operands.forEach(visit);
|
|
959
|
+
return;
|
|
960
|
+
case "not":
|
|
961
|
+
visit(e.operand);
|
|
962
|
+
return;
|
|
963
|
+
case "existsIn":
|
|
964
|
+
visit(e.where);
|
|
965
|
+
return;
|
|
966
|
+
case "raw":
|
|
967
|
+
if (UID_NOT_NULL.test(e.sql)) found.push({
|
|
968
|
+
pattern: "uid-not-null",
|
|
969
|
+
detail: e.sql,
|
|
970
|
+
explanation: `\`auth.uid() IS NOT NULL\` is true for every request that came from a client, including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. Use \`condition: policy.authenticated()\` to mean "signed in".`
|
|
971
|
+
});
|
|
972
|
+
return;
|
|
973
|
+
case "compare": {
|
|
974
|
+
const literal = [e.left, e.right].find((o) => o.kind === "literal");
|
|
975
|
+
if (!(e.left.kind === "authUid" || e.right.kind === "authUid") || typeof literal?.value !== "string") return;
|
|
976
|
+
const platform = FOREIGN_CONVENTION_UIDS[literal.value];
|
|
977
|
+
if (!platform) return;
|
|
978
|
+
found.push({
|
|
979
|
+
pattern: "foreign-uid-literal",
|
|
980
|
+
detail: literal.value,
|
|
981
|
+
explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for every caller. Use \`condition: policy.authenticated()\` to mean "signed in".`
|
|
982
|
+
});
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
default: return;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
visit(expr);
|
|
989
|
+
return found;
|
|
990
|
+
}
|
|
723
991
|
function parseOperand(str) {
|
|
724
992
|
if (/current_setting\s*\(\s*'app\.user_id'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) return policy.authUid();
|
|
725
993
|
const stringMatch = str.match(/^'(.+)'$/);
|
|
@@ -796,15 +1064,19 @@ function compile(expr, scope) {
|
|
|
796
1064
|
case "false": return "false";
|
|
797
1065
|
case "and": return expr.operands.length === 0 ? "true" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" AND ");
|
|
798
1066
|
case "or": return expr.operands.length === 0 ? "false" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" OR ");
|
|
799
|
-
case "not":
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
1067
|
+
case "not": return `NOT (${compile(expr.operand, scope)})`;
|
|
1068
|
+
case "compare": {
|
|
1069
|
+
const castForAuthUid = (operand, sqlText, other) => other.kind === "authUid" && (operand.kind === "field" || operand.kind === "outerField") ? `(${sqlText})::text` : sqlText;
|
|
1070
|
+
const leftSql = castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);
|
|
1071
|
+
const rightSql = castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);
|
|
1072
|
+
return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;
|
|
1073
|
+
}
|
|
803
1074
|
case "rolesOverlap": return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
|
|
804
1075
|
case "rolesContain": return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
|
|
805
|
-
case "authenticated": return
|
|
1076
|
+
case "authenticated": return `auth.uid() IS NOT NULL AND auth.uid() <> ${quoteLiteral(ANONYMOUS_USER_ID)}`;
|
|
1077
|
+
case "serverContext": return "auth.uid() IS NULL";
|
|
806
1078
|
case "existsIn": return compileExistsIn(expr, scope);
|
|
807
|
-
case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => col);
|
|
1079
|
+
case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
|
|
808
1080
|
}
|
|
809
1081
|
}
|
|
810
1082
|
/**
|
|
@@ -817,9 +1089,7 @@ function compileExistsIn(expr, scope) {
|
|
|
817
1089
|
const joinTable = join ? getTableName(join) : toSnakeCase(expr.collection);
|
|
818
1090
|
const joinSchema = schemaOf(join) ?? schemaOf(scope.outerCollection) ?? "public";
|
|
819
1091
|
const alias = `_ex${scope.alias.n++}`;
|
|
820
|
-
const
|
|
821
|
-
const outerSchema = schemaOf(scope.outerCollection) ?? "public";
|
|
822
|
-
const outerPrefix = outerTable ? `"${outerSchema}"."${outerTable}".` : "";
|
|
1092
|
+
const outerPrefix = outerQualifier(scope);
|
|
823
1093
|
const innerScope = {
|
|
824
1094
|
fieldCollection: join,
|
|
825
1095
|
fieldPrefix: `"${alias}".`,
|
|
@@ -847,6 +1117,15 @@ function operandToSql(operand, scope) {
|
|
|
847
1117
|
case "authRoles": return "string_to_array(auth.roles(), ',')";
|
|
848
1118
|
}
|
|
849
1119
|
}
|
|
1120
|
+
/**
|
|
1121
|
+
* SQL prefix that qualifies a column of the outer RLS row (`"schema"."table".`),
|
|
1122
|
+
* or `""` when the collection is unknown.
|
|
1123
|
+
*/
|
|
1124
|
+
function outerQualifier(scope) {
|
|
1125
|
+
const table = scope.outerCollection ? getTableName(scope.outerCollection) : void 0;
|
|
1126
|
+
if (!table) return "";
|
|
1127
|
+
return `"${schemaOf(scope.outerCollection) ?? "public"}"."${table}".`;
|
|
1128
|
+
}
|
|
850
1129
|
function schemaOf(collection) {
|
|
851
1130
|
return collection?.schema || void 0;
|
|
852
1131
|
}
|
|
@@ -891,7 +1170,8 @@ function evaluatePolicy(expr, ctx) {
|
|
|
891
1170
|
const userRoles = ctx.roles ?? [];
|
|
892
1171
|
return expr.roles.every((r) => r === "public" || userRoles.includes(r));
|
|
893
1172
|
}
|
|
894
|
-
case "authenticated": return ctx.uid != null;
|
|
1173
|
+
case "authenticated": return ctx.uid != null && ctx.uid !== ANONYMOUS_USER_ID;
|
|
1174
|
+
case "serverContext": return false;
|
|
895
1175
|
case "existsIn": return "unknown";
|
|
896
1176
|
case "raw": return "unknown";
|
|
897
1177
|
}
|
|
@@ -918,7 +1198,7 @@ function resolveOperand(operand, ctx) {
|
|
|
918
1198
|
};
|
|
919
1199
|
case "authUid": return {
|
|
920
1200
|
known: true,
|
|
921
|
-
value: ctx.uid ??
|
|
1201
|
+
value: ctx.uid ?? ANONYMOUS_USER_ID
|
|
922
1202
|
};
|
|
923
1203
|
case "authRoles": return {
|
|
924
1204
|
known: true,
|
|
@@ -1481,6 +1761,323 @@ var buildPropertyCallbacks = (properties) => {
|
|
|
1481
1761
|
return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
|
|
1482
1762
|
};
|
|
1483
1763
|
//#endregion
|
|
1764
|
+
//#region src/util/auth-default-policies.ts
|
|
1765
|
+
/**
|
|
1766
|
+
* Default RLS policies injected by the schema generator.
|
|
1767
|
+
*
|
|
1768
|
+
* Rebase's enforcement model is unified: authenticated (user-context) requests
|
|
1769
|
+
* run under the restricted `rebase_user` role, so Postgres RLS binds *every*
|
|
1770
|
+
* statement — reads and writes. A collection's `securityRules` are the whole
|
|
1771
|
+
* authorization model. The server context (auth flows, migrations,
|
|
1772
|
+
* `dataAsAdmin`) runs as the owner and bypasses RLS.
|
|
1773
|
+
*
|
|
1774
|
+
* Because RLS default-denies, every collection is **locked by default**: with
|
|
1775
|
+
* no rules, only the server context and admins can touch it. The generator
|
|
1776
|
+
* injects that safe baseline:
|
|
1777
|
+
*
|
|
1778
|
+
* **For every collection**
|
|
1779
|
+
* 1. A permissive **server-or-admin SELECT** grant.
|
|
1780
|
+
* 2. A permissive **server-or-admin write** grant (insert/update/delete).
|
|
1781
|
+
*
|
|
1782
|
+
* Author `securityRules` are permissive and OR together, so explicit rules only
|
|
1783
|
+
* *broaden* access from this locked baseline (e.g. "users read/write their own
|
|
1784
|
+
* rows").
|
|
1785
|
+
*
|
|
1786
|
+
* **For auth collections additionally**
|
|
1787
|
+
* 3. A permissive **self SELECT** grant (`id = auth.uid()`), so users can read
|
|
1788
|
+
* their own row (profile, session bootstrap) without every app re-declaring
|
|
1789
|
+
* it.
|
|
1790
|
+
* 4. A **restrictive** admin write gate. Restrictive policies are AND'd with
|
|
1791
|
+
* every other policy, so a write is rejected unless the caller is an admin
|
|
1792
|
+
* (or the server context) — even if the author also wrote a permissive rule
|
|
1793
|
+
* such as "a user may edit their own row". Without this, a permissive owner
|
|
1794
|
+
* rule would let a user change their own `roles`.
|
|
1795
|
+
*
|
|
1796
|
+
* The server context is recognised as `auth.uid() IS NULL` (`policy.serverContext()`)
|
|
1797
|
+
* — the built-in flows that run without a user (signup, migrations) set no user
|
|
1798
|
+
* GUC — which also lets the owner connection satisfy these policies even under
|
|
1799
|
+
* FORCE RLS. A *user* request never reaches that state: an anonymous one carries
|
|
1800
|
+
* `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.
|
|
1801
|
+
*
|
|
1802
|
+
* Opt out with `disableDefaultPolicies: true` to take full responsibility for
|
|
1803
|
+
* the collection's RLS.
|
|
1804
|
+
*/
|
|
1805
|
+
var SERVER_OR_ADMIN_EXPR$1 = policy.or(policy.serverContext(), policy.rolesOverlap(["admin"]));
|
|
1806
|
+
/** Write operations that must be admin-gated by default on auth collections. */
|
|
1807
|
+
var DEFAULT_GUARDED_OPS = [
|
|
1808
|
+
"insert",
|
|
1809
|
+
"update",
|
|
1810
|
+
"delete"
|
|
1811
|
+
];
|
|
1812
|
+
/** Whether a collection is flagged as an authentication collection. */
|
|
1813
|
+
function isAuthCollection(collection) {
|
|
1814
|
+
const auth = collection.auth;
|
|
1815
|
+
return auth === true || typeof auth === "object" && auth?.enabled === true;
|
|
1816
|
+
}
|
|
1817
|
+
/** The property marked as the row id (falls back to `id`). */
|
|
1818
|
+
function getIdPropertyName$1(collection) {
|
|
1819
|
+
for (const [name, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && prop.isId) return name;
|
|
1820
|
+
return "id";
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* Returns the security rules that should be applied to a collection: the
|
|
1824
|
+
* author's explicit `securityRules` plus the framework defaults described in
|
|
1825
|
+
* the module doc (baseline server/admin read for all collections; self-read
|
|
1826
|
+
* and the admin write gate for auth collections).
|
|
1827
|
+
*
|
|
1828
|
+
* Collections that opt out via `disableDefaultPolicies` are returned unchanged.
|
|
1829
|
+
*/
|
|
1830
|
+
function getEffectiveSecurityRules(collection) {
|
|
1831
|
+
const explicit = [...(isPostgresCollectionConfig(collection) ? collection.securityRules : void 0) ?? []];
|
|
1832
|
+
if (collection.disableDefaultPolicies) return explicit;
|
|
1833
|
+
const tableName = getTableName(collection);
|
|
1834
|
+
const injected = [];
|
|
1835
|
+
injected.push({
|
|
1836
|
+
name: `${tableName}_default_admin_read`,
|
|
1837
|
+
operations: ["select"],
|
|
1838
|
+
condition: SERVER_OR_ADMIN_EXPR$1
|
|
1839
|
+
});
|
|
1840
|
+
injected.push({
|
|
1841
|
+
name: `${tableName}_default_admin_write`,
|
|
1842
|
+
operations: [...DEFAULT_GUARDED_OPS],
|
|
1843
|
+
condition: SERVER_OR_ADMIN_EXPR$1,
|
|
1844
|
+
check: SERVER_OR_ADMIN_EXPR$1
|
|
1845
|
+
});
|
|
1846
|
+
if (isAuthCollection(collection)) {
|
|
1847
|
+
injected.push({
|
|
1848
|
+
name: `${tableName}_default_self_read`,
|
|
1849
|
+
operations: ["select"],
|
|
1850
|
+
condition: policy.compare(policy.field(getIdPropertyName$1(collection)), "eq", policy.authUid())
|
|
1851
|
+
});
|
|
1852
|
+
injected.push({
|
|
1853
|
+
name: `${tableName}_require_admin_write`,
|
|
1854
|
+
mode: "restrictive",
|
|
1855
|
+
operations: [...DEFAULT_GUARDED_OPS],
|
|
1856
|
+
condition: SERVER_OR_ADMIN_EXPR$1,
|
|
1857
|
+
check: SERVER_OR_ADMIN_EXPR$1
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
return [...explicit, ...injected];
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* The framework defaults that {@link getEffectiveSecurityRules} would add to a
|
|
1864
|
+
* collection, without the author's own rules.
|
|
1865
|
+
*
|
|
1866
|
+
* These policies appear in the database under names the author never wrote, and
|
|
1867
|
+
* a permissive policy ORs with every other permissive policy — so someone
|
|
1868
|
+
* reading their `securityRules` and then the real ACL sees more access than they
|
|
1869
|
+
* declared. Dropping them by hand does nothing either: `db push` is declarative,
|
|
1870
|
+
* so the next push asserts them again. Callers use this to say, in the generated
|
|
1871
|
+
* DDL, which policies are injected and how to take them off.
|
|
1872
|
+
*/
|
|
1873
|
+
function getInjectedSecurityRules(collection) {
|
|
1874
|
+
if (collection.disableDefaultPolicies) return [];
|
|
1875
|
+
const explicitCount = ((isPostgresCollectionConfig(collection) ? collection.securityRules : void 0) ?? []).length;
|
|
1876
|
+
return getEffectiveSecurityRules(collection).slice(explicitCount);
|
|
1877
|
+
}
|
|
1878
|
+
//#endregion
|
|
1879
|
+
//#region src/util/junction-policies.ts
|
|
1880
|
+
var SERVER_OR_ADMIN_EXPR = policy.or(policy.serverContext(), policy.rolesOverlap(["admin"]));
|
|
1881
|
+
/**
|
|
1882
|
+
* Walk every collection's resolved relations and aggregate the junction tables
|
|
1883
|
+
* they declare. Two collections may declare the same junction from opposite
|
|
1884
|
+
* sides (posts→tags and tags→posts through `posts_tags`); both become
|
|
1885
|
+
* `declaringSides` of one spec, so derived write grants consider both.
|
|
1886
|
+
*/
|
|
1887
|
+
function resolveJunctionSpecs(collections) {
|
|
1888
|
+
const specs = /* @__PURE__ */ new Map();
|
|
1889
|
+
for (const collection of collections) {
|
|
1890
|
+
const resolved = resolveCollectionRelations(collection);
|
|
1891
|
+
for (const relation of Object.values(resolved)) {
|
|
1892
|
+
if (!relation.through) continue;
|
|
1893
|
+
const targetCollection = typeof relation.target === "function" ? relation.target() : void 0;
|
|
1894
|
+
if (!targetCollection) continue;
|
|
1895
|
+
const rawName = relation.through.table;
|
|
1896
|
+
const table = rawName.includes(".") ? rawName.split(".").pop() : rawName;
|
|
1897
|
+
const schema = "public";
|
|
1898
|
+
const source = {
|
|
1899
|
+
collection,
|
|
1900
|
+
junctionColumn: relation.through.sourceColumn,
|
|
1901
|
+
relation
|
|
1902
|
+
};
|
|
1903
|
+
const target = {
|
|
1904
|
+
collection: targetCollection,
|
|
1905
|
+
junctionColumn: relation.through.targetColumn
|
|
1906
|
+
};
|
|
1907
|
+
const existing = specs.get(table);
|
|
1908
|
+
if (!existing) specs.set(table, {
|
|
1909
|
+
table,
|
|
1910
|
+
schema,
|
|
1911
|
+
endpoints: [source, target],
|
|
1912
|
+
declaringSides: [source]
|
|
1913
|
+
});
|
|
1914
|
+
else if (!existing.declaringSides.some((s) => s.collection === collection)) existing.declaringSides.push(source);
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
return specs;
|
|
1918
|
+
}
|
|
1919
|
+
/**
|
|
1920
|
+
* A synthetic CollectionConfig standing in for the junction during policy
|
|
1921
|
+
* compilation and naming. Its two FK columns carry explicit `columnName`s so
|
|
1922
|
+
* `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
|
|
1923
|
+
* whatever their casing.
|
|
1924
|
+
*/
|
|
1925
|
+
function getJunctionCollectionConfig(spec) {
|
|
1926
|
+
const properties = {};
|
|
1927
|
+
for (const endpoint of spec.endpoints) properties[endpoint.junctionColumn] = {
|
|
1928
|
+
type: "string",
|
|
1929
|
+
columnName: endpoint.junctionColumn
|
|
1930
|
+
};
|
|
1931
|
+
return {
|
|
1932
|
+
slug: spec.table,
|
|
1933
|
+
name: spec.table,
|
|
1934
|
+
table: spec.table,
|
|
1935
|
+
schema: spec.schema,
|
|
1936
|
+
properties
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
/** The property marked as the row id (falls back to `id`). */
|
|
1940
|
+
function getIdPropertyName(collection) {
|
|
1941
|
+
for (const [name, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && prop.isId) return name;
|
|
1942
|
+
return "id";
|
|
1943
|
+
}
|
|
1944
|
+
/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
|
|
1945
|
+
function existsEndpoint(endpoint, extra) {
|
|
1946
|
+
const correlation = policy.compare(policy.field(getIdPropertyName(endpoint.collection)), "eq", policy.outerField(endpoint.junctionColumn));
|
|
1947
|
+
return policy.existsIn({
|
|
1948
|
+
collection: endpoint.collection.slug,
|
|
1949
|
+
where: extra ? policy.and(correlation, extra) : correlation
|
|
1950
|
+
});
|
|
1951
|
+
}
|
|
1952
|
+
/**
|
|
1953
|
+
* Whether a parent-rule expression keeps its meaning when moved inside the
|
|
1954
|
+
* junction's `EXISTS` subquery — and the re-scoped copy if it does.
|
|
1955
|
+
*
|
|
1956
|
+
* Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
|
|
1957
|
+
* anywhere (its `{column}` placeholders would bind to the junction), or an
|
|
1958
|
+
* `outerField` inside a nested `existsIn` (it would bind to the junction while
|
|
1959
|
+
* the author meant the parent, and no operand can express "the middle scope").
|
|
1960
|
+
* Top-level `outerField`s are rewritten to `field`, which is what they meant.
|
|
1961
|
+
*/
|
|
1962
|
+
function embedParentExpression(expr, depth = 0) {
|
|
1963
|
+
switch (expr.kind) {
|
|
1964
|
+
case "raw": return null;
|
|
1965
|
+
case "and":
|
|
1966
|
+
case "or": {
|
|
1967
|
+
const parts = [];
|
|
1968
|
+
for (const child of expr.operands) {
|
|
1969
|
+
const embedded = embedParentExpression(child, depth);
|
|
1970
|
+
if (!embedded) return null;
|
|
1971
|
+
parts.push(embedded);
|
|
1972
|
+
}
|
|
1973
|
+
return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
|
|
1974
|
+
}
|
|
1975
|
+
case "not": {
|
|
1976
|
+
const embedded = embedParentExpression(expr.operand, depth);
|
|
1977
|
+
return embedded ? policy.not(embedded) : null;
|
|
1978
|
+
}
|
|
1979
|
+
case "existsIn": {
|
|
1980
|
+
const where = embedParentExpression(expr.where, depth + 1);
|
|
1981
|
+
return where ? policy.existsIn({
|
|
1982
|
+
collection: expr.collection,
|
|
1983
|
+
where
|
|
1984
|
+
}) : null;
|
|
1985
|
+
}
|
|
1986
|
+
case "compare": {
|
|
1987
|
+
const left = embedOperand(expr.left, depth);
|
|
1988
|
+
const right = embedOperand(expr.right, depth);
|
|
1989
|
+
if (!left || !right) return null;
|
|
1990
|
+
return {
|
|
1991
|
+
...expr,
|
|
1992
|
+
left,
|
|
1993
|
+
right
|
|
1994
|
+
};
|
|
1995
|
+
}
|
|
1996
|
+
default: return expr;
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
/** Re-scope an operand, or return `null` if its binding cannot be preserved. */
|
|
2000
|
+
function embedOperand(operand, depth) {
|
|
2001
|
+
if (operand.kind === "outerField") {
|
|
2002
|
+
if (depth === 0) return policy.field(operand.name);
|
|
2003
|
+
return null;
|
|
2004
|
+
}
|
|
2005
|
+
return operand;
|
|
2006
|
+
}
|
|
2007
|
+
/** Does the rule cover the `update` operation? */
|
|
2008
|
+
function coversUpdate(rule) {
|
|
2009
|
+
return getPolicyOperations(rule).some((op) => op === "update" || op === "all");
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* The full derived policy set for a junction table: the locked server/admin
|
|
2013
|
+
* baseline, the endpoint-visibility read grant, inherited write grants, and
|
|
2014
|
+
* inherited restrictive gates. Returns `[]` when every declaring collection set
|
|
2015
|
+
* `disableDefaultPolicies` — the junction is then the author's to police, and
|
|
2016
|
+
* stays locked (RLS is still enabled) until they write policies for it.
|
|
2017
|
+
*/
|
|
2018
|
+
function getJunctionSecurityRules(spec) {
|
|
2019
|
+
if (spec.declaringSides.every((side) => side.collection.disableDefaultPolicies)) return [];
|
|
2020
|
+
const rules = [];
|
|
2021
|
+
rules.push({
|
|
2022
|
+
name: `${spec.table}_default_admin_read`,
|
|
2023
|
+
operations: ["select"],
|
|
2024
|
+
condition: SERVER_OR_ADMIN_EXPR
|
|
2025
|
+
});
|
|
2026
|
+
rules.push({
|
|
2027
|
+
name: `${spec.table}_default_admin_write`,
|
|
2028
|
+
operations: [
|
|
2029
|
+
"insert",
|
|
2030
|
+
"update",
|
|
2031
|
+
"delete"
|
|
2032
|
+
],
|
|
2033
|
+
condition: SERVER_OR_ADMIN_EXPR,
|
|
2034
|
+
check: SERVER_OR_ADMIN_EXPR
|
|
2035
|
+
});
|
|
2036
|
+
rules.push({
|
|
2037
|
+
name: `${spec.table}_default_edge_read`,
|
|
2038
|
+
operations: ["select"],
|
|
2039
|
+
condition: policy.and(existsEndpoint(spec.endpoints[0]), existsEndpoint(spec.endpoints[1]))
|
|
2040
|
+
});
|
|
2041
|
+
const writeGrants = [];
|
|
2042
|
+
for (const side of spec.declaringSides) {
|
|
2043
|
+
const updateRules = ((isPostgresCollectionConfig(side.collection) ? side.collection.securityRules : void 0) ?? []).filter(coversUpdate);
|
|
2044
|
+
const permissive = updateRules.filter((r) => r.mode !== "restrictive");
|
|
2045
|
+
const restrictive = updateRules.filter((r) => r.mode === "restrictive");
|
|
2046
|
+
const embeddedGates = [];
|
|
2047
|
+
let gatesEmbeddable = true;
|
|
2048
|
+
for (const gate of restrictive) {
|
|
2049
|
+
const using = securityRuleToConditions(gate).usingExpr;
|
|
2050
|
+
const embedded = using ? embedParentExpression(using) : null;
|
|
2051
|
+
if (!embedded) {
|
|
2052
|
+
gatesEmbeddable = false;
|
|
2053
|
+
break;
|
|
2054
|
+
}
|
|
2055
|
+
embeddedGates.push(embedded);
|
|
2056
|
+
}
|
|
2057
|
+
if (!gatesEmbeddable) continue;
|
|
2058
|
+
const grants = [];
|
|
2059
|
+
for (const rule of permissive) {
|
|
2060
|
+
const using = securityRuleToConditions(rule).usingExpr;
|
|
2061
|
+
const embedded = using ? embedParentExpression(using) : null;
|
|
2062
|
+
if (embedded) grants.push(embedded);
|
|
2063
|
+
}
|
|
2064
|
+
if (grants.length === 0) continue;
|
|
2065
|
+
const condition = embeddedGates.length > 0 ? policy.and(policy.or(...grants), ...embeddedGates) : policy.or(...grants);
|
|
2066
|
+
writeGrants.push(existsEndpoint(side, condition));
|
|
2067
|
+
}
|
|
2068
|
+
if (writeGrants.length > 0) rules.push({
|
|
2069
|
+
name: `${spec.table}_default_edge_write`,
|
|
2070
|
+
operations: [
|
|
2071
|
+
"insert",
|
|
2072
|
+
"update",
|
|
2073
|
+
"delete"
|
|
2074
|
+
],
|
|
2075
|
+
condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
|
|
2076
|
+
check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
|
|
2077
|
+
});
|
|
2078
|
+
return rules;
|
|
2079
|
+
}
|
|
2080
|
+
//#endregion
|
|
1484
2081
|
//#region src/util/conditions.ts
|
|
1485
2082
|
/**
|
|
1486
2083
|
* Access a nested property from an object via dot notation.
|
|
@@ -2166,6 +2763,7 @@ var defaultUsersCollection = defineCollection({
|
|
|
2166
2763
|
name: "Password Hash",
|
|
2167
2764
|
type: "string",
|
|
2168
2765
|
columnName: "password_hash",
|
|
2766
|
+
excludeFromApi: true,
|
|
2169
2767
|
ui: {
|
|
2170
2768
|
hideFromCollection: true,
|
|
2171
2769
|
disabled: { hidden: true }
|
|
@@ -2185,6 +2783,7 @@ var defaultUsersCollection = defineCollection({
|
|
|
2185
2783
|
name: "Email Verification Token",
|
|
2186
2784
|
type: "string",
|
|
2187
2785
|
columnName: "email_verification_token",
|
|
2786
|
+
excludeFromApi: true,
|
|
2188
2787
|
ui: {
|
|
2189
2788
|
hideFromCollection: true,
|
|
2190
2789
|
disabled: { hidden: true }
|
|
@@ -2369,9 +2968,14 @@ var QueryBuilder = class {
|
|
|
2369
2968
|
/**
|
|
2370
2969
|
* Serialize a JS value to its querystring representation.
|
|
2371
2970
|
* `null` is serialized as the literal string `"null"`.
|
|
2971
|
+
* Relation values (`EntityRelation` instances or `{ __type: "relation", id, path }`
|
|
2972
|
+
* objects) are serialized as their raw id — the wire format only carries the
|
|
2973
|
+
* value to compare against the FK column.
|
|
2372
2974
|
*/
|
|
2373
2975
|
function stringifyValue(value) {
|
|
2374
2976
|
if (value === null) return "null";
|
|
2977
|
+
const relation = normalizeToEntityRelation(value);
|
|
2978
|
+
if (relation) return String(relation.id);
|
|
2375
2979
|
return String(value);
|
|
2376
2980
|
}
|
|
2377
2981
|
/**
|
|
@@ -2608,18 +3212,45 @@ function deserializeLogicalCondition(str) {
|
|
|
2608
3212
|
}
|
|
2609
3213
|
//#endregion
|
|
2610
3214
|
//#region src/data/buildRebaseData.ts
|
|
3215
|
+
function createPrimaryKeyResolver(options) {
|
|
3216
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3217
|
+
const warned = /* @__PURE__ */ new Set();
|
|
3218
|
+
return function primaryKeysFor(slug) {
|
|
3219
|
+
const cached = cache.get(slug);
|
|
3220
|
+
if (cached) return cached;
|
|
3221
|
+
const collection = options?.resolveCollection?.(slug);
|
|
3222
|
+
if (!collection) return [];
|
|
3223
|
+
const keys = resolvePrimaryKeys(collection);
|
|
3224
|
+
if (keys.length > 0) {
|
|
3225
|
+
cache.set(slug, keys);
|
|
3226
|
+
return keys;
|
|
3227
|
+
}
|
|
3228
|
+
if (!warned.has(slug)) {
|
|
3229
|
+
warned.add(slug);
|
|
3230
|
+
console.warn(`[rebase] Collection '${slug}' declares no primary key, so its rows have no address: detail links, caching and relations will not work for it. Mark the key property with \`isId\` in its collection config — the server logs which column to mark at boot, if its schema knows the key.`);
|
|
3231
|
+
}
|
|
3232
|
+
return keys;
|
|
3233
|
+
};
|
|
3234
|
+
}
|
|
2611
3235
|
/**
|
|
2612
|
-
*
|
|
2613
|
-
*
|
|
3236
|
+
* Give a flat row the Entity view-model the admin renders.
|
|
3237
|
+
*
|
|
3238
|
+
* The address is *derived here* — it is not a column, and the row it came from
|
|
3239
|
+
* does not contain one. Rows carry exactly what the table has, with the types
|
|
3240
|
+
* Postgres returned; the id is this layer's invention, and this is the only
|
|
3241
|
+
* place it is minted.
|
|
3242
|
+
*
|
|
3243
|
+
* `primaryKeys` empty falls back to a literal `id` on the row: drivers other
|
|
3244
|
+
* than postgres still serve rows with one, and this keeps them working.
|
|
2614
3245
|
*/
|
|
2615
|
-
function rowToEntity(row, slug) {
|
|
3246
|
+
function rowToEntity(row, slug, primaryKeys = []) {
|
|
2616
3247
|
return {
|
|
2617
|
-
id: row.id,
|
|
3248
|
+
id: primaryKeys.length > 0 ? buildCompositeId(row, primaryKeys) : row.id,
|
|
2618
3249
|
path: slug,
|
|
2619
3250
|
values: row
|
|
2620
3251
|
};
|
|
2621
3252
|
}
|
|
2622
|
-
function createDriverAccessor(driver, slug) {
|
|
3253
|
+
function createDriverAccessor(driver, slug, getPks = () => []) {
|
|
2623
3254
|
const accessor = {
|
|
2624
3255
|
async find(params) {
|
|
2625
3256
|
const filter = params?.where ? deserializeFilter(params.where) : void 0;
|
|
@@ -2652,7 +3283,7 @@ function createDriverAccessor(driver, slug) {
|
|
|
2652
3283
|
hasMore = offset + rows.length < total;
|
|
2653
3284
|
}
|
|
2654
3285
|
return {
|
|
2655
|
-
data: rows.map((row) => rowToEntity(row, slug)),
|
|
3286
|
+
data: rows.map((row) => rowToEntity(row, slug, getPks())),
|
|
2656
3287
|
meta: {
|
|
2657
3288
|
total,
|
|
2658
3289
|
limit,
|
|
@@ -2666,7 +3297,7 @@ function createDriverAccessor(driver, slug) {
|
|
|
2666
3297
|
path: slug,
|
|
2667
3298
|
id
|
|
2668
3299
|
});
|
|
2669
|
-
return row ? rowToEntity(row, slug) : void 0;
|
|
3300
|
+
return row ? rowToEntity(row, slug, getPks()) : void 0;
|
|
2670
3301
|
},
|
|
2671
3302
|
async create(data, id) {
|
|
2672
3303
|
return rowToEntity(await driver.save({
|
|
@@ -2674,15 +3305,22 @@ function createDriverAccessor(driver, slug) {
|
|
|
2674
3305
|
values: data,
|
|
2675
3306
|
id,
|
|
2676
3307
|
status: "new"
|
|
2677
|
-
}), slug);
|
|
3308
|
+
}), slug, getPks());
|
|
2678
3309
|
},
|
|
3310
|
+
createMany: driver.saveMany ? async (data, options) => {
|
|
3311
|
+
return (await driver.saveMany({
|
|
3312
|
+
path: slug,
|
|
3313
|
+
rows: data,
|
|
3314
|
+
upsert: options?.upsert
|
|
3315
|
+
})).map((row) => rowToEntity(row, slug, getPks()));
|
|
3316
|
+
} : void 0,
|
|
2679
3317
|
async update(id, data) {
|
|
2680
3318
|
return rowToEntity(await driver.save({
|
|
2681
3319
|
path: slug,
|
|
2682
3320
|
values: data,
|
|
2683
3321
|
id,
|
|
2684
3322
|
status: "existing"
|
|
2685
|
-
}), slug);
|
|
3323
|
+
}), slug, getPks());
|
|
2686
3324
|
},
|
|
2687
3325
|
async delete(id) {
|
|
2688
3326
|
return driver.delete({ row: {
|
|
@@ -2711,7 +3349,7 @@ function createDriverAccessor(driver, slug) {
|
|
|
2711
3349
|
searchString: params?.searchString,
|
|
2712
3350
|
onUpdate: (entities) => {
|
|
2713
3351
|
onUpdate({
|
|
2714
|
-
data: entities.map((row) => rowToEntity(row, slug)),
|
|
3352
|
+
data: entities.map((row) => rowToEntity(row, slug, getPks())),
|
|
2715
3353
|
meta: {
|
|
2716
3354
|
total: entities.length,
|
|
2717
3355
|
limit,
|
|
@@ -2727,7 +3365,7 @@ function createDriverAccessor(driver, slug) {
|
|
|
2727
3365
|
return driver.listenOne({
|
|
2728
3366
|
path: slug,
|
|
2729
3367
|
id,
|
|
2730
|
-
onUpdate: (entity) => onUpdate(entity ? rowToEntity(entity, slug) : void 0),
|
|
3368
|
+
onUpdate: (entity) => onUpdate(entity ? rowToEntity(entity, slug, getPks()) : void 0),
|
|
2731
3369
|
onError
|
|
2732
3370
|
});
|
|
2733
3371
|
} : void 0,
|
|
@@ -2766,12 +3404,13 @@ function createDriverAccessor(driver, slug) {
|
|
|
2766
3404
|
* await data.products.create({ name: "Camera", price: 299 });
|
|
2767
3405
|
* const { data: items } = await data.products.find({ where: { status: ["==", "published"] } });
|
|
2768
3406
|
*/
|
|
2769
|
-
function buildRebaseData(driver) {
|
|
3407
|
+
function buildRebaseData(driver, options) {
|
|
2770
3408
|
const cache = /* @__PURE__ */ new Map();
|
|
3409
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
2771
3410
|
function getAccessor(slug) {
|
|
2772
3411
|
let accessor = cache.get(slug);
|
|
2773
3412
|
if (!accessor) {
|
|
2774
|
-
accessor = createDriverAccessor(driver, slug);
|
|
3413
|
+
accessor = createDriverAccessor(driver, slug, () => primaryKeysFor(slug));
|
|
2775
3414
|
cache.set(slug, accessor);
|
|
2776
3415
|
}
|
|
2777
3416
|
return accessor;
|
|
@@ -2784,8 +3423,9 @@ function buildRebaseData(driver) {
|
|
|
2784
3423
|
} });
|
|
2785
3424
|
}
|
|
2786
3425
|
/**
|
|
2787
|
-
* Unwrap a Entity into
|
|
2788
|
-
*
|
|
3426
|
+
* Unwrap a Entity back into the flat row it was built from. `rowToEntity` keeps
|
|
3427
|
+
* the row untouched under `.values` and derives `.id` alongside it, so dropping
|
|
3428
|
+
* the wrapper is the whole operation — the address was never part of the row.
|
|
2789
3429
|
*/
|
|
2790
3430
|
function entityToRow(entity) {
|
|
2791
3431
|
return entity.values;
|
|
@@ -2872,6 +3512,12 @@ function toSdkCollectionClient(snap) {
|
|
|
2872
3512
|
async create(data, id) {
|
|
2873
3513
|
return entityToRow(await snap.create(data, id));
|
|
2874
3514
|
},
|
|
3515
|
+
async createMany(data, options) {
|
|
3516
|
+
if (!Array.isArray(data)) throw new TypeError("createMany expects an array of records.");
|
|
3517
|
+
if (data.length === 0) return [];
|
|
3518
|
+
if (!snap.createMany) throw new Error("Bulk writes are not supported by this collection's data source. Fall back to create() per record.");
|
|
3519
|
+
return (await snap.createMany(data, options)).map(entityToRow);
|
|
3520
|
+
},
|
|
2875
3521
|
async update(id, data) {
|
|
2876
3522
|
return entityToRow(await snap.update(id, data));
|
|
2877
3523
|
},
|
|
@@ -2902,36 +3548,36 @@ function toSdkCollectionClient(snap) {
|
|
|
2902
3548
|
* {@link CollectionAccessor}. Every returned row is re-wrapped into the
|
|
2903
3549
|
* `{ id, path, values }` view-model the admin CMS renders.
|
|
2904
3550
|
*/
|
|
2905
|
-
function toEntityAccessor(sdk, slug) {
|
|
3551
|
+
function toEntityAccessor(sdk, slug, getPks = () => []) {
|
|
2906
3552
|
const accessor = {
|
|
2907
3553
|
async find(params) {
|
|
2908
3554
|
const res = await sdk.find(params);
|
|
2909
3555
|
return {
|
|
2910
|
-
data: res.data.map((row) => rowToEntity(row, slug)),
|
|
3556
|
+
data: res.data.map((row) => rowToEntity(row, slug, getPks())),
|
|
2911
3557
|
meta: res.meta
|
|
2912
3558
|
};
|
|
2913
3559
|
},
|
|
2914
3560
|
async findById(id) {
|
|
2915
3561
|
const row = await sdk.findById(id);
|
|
2916
|
-
return row ? rowToEntity(row, slug) : void 0;
|
|
3562
|
+
return row ? rowToEntity(row, slug, getPks()) : void 0;
|
|
2917
3563
|
},
|
|
2918
3564
|
async create(data, id) {
|
|
2919
|
-
return rowToEntity(await sdk.create(data, id), slug);
|
|
3565
|
+
return rowToEntity(await sdk.create(data, id), slug, getPks());
|
|
2920
3566
|
},
|
|
2921
3567
|
async update(id, data) {
|
|
2922
3568
|
const row = await sdk.update(id, data);
|
|
2923
3569
|
if (!row) throw new Error(`Update returned no data for id ${id}`);
|
|
2924
|
-
return rowToEntity(row, slug);
|
|
3570
|
+
return rowToEntity(row, slug, getPks());
|
|
2925
3571
|
},
|
|
2926
3572
|
delete(id) {
|
|
2927
3573
|
return sdk.delete(id);
|
|
2928
3574
|
},
|
|
2929
3575
|
count: sdk.count ? (params) => sdk.count(params) : void 0,
|
|
2930
3576
|
listen: sdk.listen ? (params, onUpdate, onError) => sdk.listen(params, (res) => onUpdate({
|
|
2931
|
-
data: res.data.map((row) => rowToEntity(row, slug)),
|
|
3577
|
+
data: res.data.map((row) => rowToEntity(row, slug, getPks())),
|
|
2932
3578
|
meta: res.meta
|
|
2933
3579
|
}), onError) : void 0,
|
|
2934
|
-
listenById: sdk.listenById ? (id, onUpdate, onError) => sdk.listenById(id, (row) => onUpdate(row ? rowToEntity(row, slug) : void 0), onError) : void 0,
|
|
3580
|
+
listenById: sdk.listenById ? (id, onUpdate, onError) => sdk.listenById(id, (row) => onUpdate(row ? rowToEntity(row, slug, getPks()) : void 0), onError) : void 0,
|
|
2935
3581
|
where(columnOrCondition, operator, value) {
|
|
2936
3582
|
const builder = new QueryBuilder(accessor);
|
|
2937
3583
|
if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
|
|
@@ -2954,12 +3600,13 @@ function toEntityAccessor(sdk, slug) {
|
|
|
2954
3600
|
* CMS `RebaseDataContext` — without it the admin renders rows with only their
|
|
2955
3601
|
* `id`.
|
|
2956
3602
|
*/
|
|
2957
|
-
function wrapAsEntityData(sdkData) {
|
|
3603
|
+
function wrapAsEntityData(sdkData, options) {
|
|
2958
3604
|
const cache = /* @__PURE__ */ new Map();
|
|
3605
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
2959
3606
|
function getAccessor(slug) {
|
|
2960
3607
|
let accessor = cache.get(slug);
|
|
2961
3608
|
if (!accessor) {
|
|
2962
|
-
accessor = toEntityAccessor(sdkData.collection(slug), slug);
|
|
3609
|
+
accessor = toEntityAccessor(sdkData.collection(slug), slug, () => primaryKeysFor(slug));
|
|
2963
3610
|
cache.set(slug, accessor);
|
|
2964
3611
|
}
|
|
2965
3612
|
return accessor;
|
|
@@ -3178,6 +3825,6 @@ async function detectJunctionTables(executeSql) {
|
|
|
3178
3825
|
return junctionTables;
|
|
3179
3826
|
}
|
|
3180
3827
|
//#endregion
|
|
3181
|
-
export { COLLECTION_PATH_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, addInitialSlash, and, applyPropertyConditions, buildCollection, buildConditionContext, buildProperty, buildPropertyCallbacks, buildRebaseData, buildRoutedRebaseData, buildSdkData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, classifyTable, cond, createDataSourceRegistry, createRelationRef, createRelationRefWithData, defaultUsersCollection, defineCollection, deserializeFilter, deserializeLogicalCondition, deserializeOrderBy, detectJunctionTables, enumToObjectEntries, evaluateCondition, evaluatePolicy, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getCollectionBySlugWithin, getCollectionPathsCombinations, getColumnName, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEntityImagePreviewPropertyKey, getEnumVarName, getLabelOrConfigFrom, getLastSegment, getLocalChangesBackup, getNavigationEntriesFromPath, getParentReferencesFromPath, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isHidden, isPropertyBuilder, isReadOnly, isRebaseInternalTable, normalizeToEntityRelation, or, policyToPostgres, registerConditionOperations, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, resolveArrayProperties, resolveCollectionPathIds, resolveCollectionRelations, resolveDataSource, resolveDefaultSelectedView, resolveEnumValues, resolveFilterOperators, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, sanitizeData, sanitizeRelation, securityRuleToConditions, segmentsToStrippedPath, serializeFilter, serializeLogicalCondition, serializeOrderBy, sortProperties, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues, wrapAsEntityData, wrapAsSdkData };
|
|
3828
|
+
export { COLLECTION_PATH_SEPARATOR, COMPOSITE_ID_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, addInitialSlash, and, applyPropertyConditions, buildCollection, buildCompositeId, buildConditionContext, buildProperty, buildPropertyCallbacks, buildRebaseData, buildRoutedRebaseData, buildSdkData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, classifyTable, cond, createDataSourceRegistry, createRelationRef, createRelationRefWithData, defaultUsersCollection, defineCollection, deserializeFilter, deserializeLogicalCondition, deserializeOrderBy, detectJunctionTables, embedParentExpression, enumToObjectEntries, evaluateCondition, evaluatePolicy, findAnonymousGrants, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getCollectionBySlugWithin, getCollectionPathsCombinations, getColumnName, getDeclaredPrimaryKeys, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEffectiveSecurityRules, getEntityImagePreviewPropertyKey, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getLabelOrConfigFrom, getLastSegment, getLocalChangesBackup, getNavigationEntriesFromPath, getParentReferencesFromPath, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isHidden, isPropertyBuilder, isReadOnly, isRebaseInternalTable, normalizeToEntityRelation, or, parseIdValues, policyToPostgres, registerConditionOperations, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, resolveArrayProperties, resolveCollectionPathIds, resolveCollectionRelations, resolveDataSource, resolveDefaultSelectedView, resolveEnumValues, resolveFilterOperators, resolveJunctionSpecs, resolvePrimaryKeys, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, sanitizeData, sanitizeRelation, securityRuleToConditions, segmentsToStrippedPath, serializeFilter, serializeLogicalCondition, serializeOrderBy, sortProperties, sqlToPolicy, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues, wrapAsEntityData, wrapAsSdkData };
|
|
3182
3829
|
|
|
3183
3830
|
//# sourceMappingURL=index.es.js.map
|