@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.
@@ -26,6 +26,7 @@ import {
26
26
  FilterCondition,
27
27
  NULL_OPS
28
28
  } from "@rebasepro/types";
29
+ import { normalizeToEntityRelation } from "../util/entities";
29
30
 
30
31
  // ---------------------------------------------------------------------------
31
32
  // Value stringification
@@ -34,9 +35,14 @@ import {
34
35
  /**
35
36
  * Serialize a JS value to its querystring representation.
36
37
  * `null` is serialized as the literal string `"null"`.
38
+ * Relation values (`EntityRelation` instances or `{ __type: "relation", id, path }`
39
+ * objects) are serialized as their raw id — the wire format only carries the
40
+ * value to compare against the FK column.
37
41
  */
38
42
  function stringifyValue(value: unknown): string {
39
43
  if (value === null) return "null";
44
+ const relation = normalizeToEntityRelation(value);
45
+ if (relation) return String(relation.id);
40
46
  return String(value);
41
47
  }
42
48
 
@@ -0,0 +1,152 @@
1
+ import { CollectionConfig, SecurityRule, SecurityOperation, AuthCollectionConfig, PolicyExpression, isPostgresCollectionConfig, policy } from "@rebasepro/types";
2
+ import { getTableName } from "./relations";
3
+
4
+ /**
5
+ * Default RLS policies injected by the schema generator.
6
+ *
7
+ * Rebase's enforcement model is unified: authenticated (user-context) requests
8
+ * run under the restricted `rebase_user` role, so Postgres RLS binds *every*
9
+ * statement — reads and writes. A collection's `securityRules` are the whole
10
+ * authorization model. The server context (auth flows, migrations,
11
+ * `dataAsAdmin`) runs as the owner and bypasses RLS.
12
+ *
13
+ * Because RLS default-denies, every collection is **locked by default**: with
14
+ * no rules, only the server context and admins can touch it. The generator
15
+ * injects that safe baseline:
16
+ *
17
+ * **For every collection**
18
+ * 1. A permissive **server-or-admin SELECT** grant.
19
+ * 2. A permissive **server-or-admin write** grant (insert/update/delete).
20
+ *
21
+ * Author `securityRules` are permissive and OR together, so explicit rules only
22
+ * *broaden* access from this locked baseline (e.g. "users read/write their own
23
+ * rows").
24
+ *
25
+ * **For auth collections additionally**
26
+ * 3. A permissive **self SELECT** grant (`id = auth.uid()`), so users can read
27
+ * their own row (profile, session bootstrap) without every app re-declaring
28
+ * it.
29
+ * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with
30
+ * every other policy, so a write is rejected unless the caller is an admin
31
+ * (or the server context) — even if the author also wrote a permissive rule
32
+ * such as "a user may edit their own row". Without this, a permissive owner
33
+ * rule would let a user change their own `roles`.
34
+ *
35
+ * The server context is recognised as `auth.uid() IS NULL` (`policy.serverContext()`)
36
+ * — the built-in flows that run without a user (signup, migrations) set no user
37
+ * GUC — which also lets the owner connection satisfy these policies even under
38
+ * FORCE RLS. A *user* request never reaches that state: an anonymous one carries
39
+ * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.
40
+ *
41
+ * Opt out with `disableDefaultPolicies: true` to take full responsibility for
42
+ * the collection's RLS.
43
+ */
44
+ // Expressed structurally (not as raw SQL) so the admin UI can evaluate it
45
+ // exactly — the framework's most security-critical policies must be reflected
46
+ // precisely, not left as un-evaluable raw clauses. Compiles to
47
+ // `auth.uid() IS NULL OR (string_to_array(auth.roles(), ',') && ARRAY['admin'])`.
48
+ //
49
+ // `serverContext()`, emphatically not `not(authenticated())`: the server arm of
50
+ // this grant must match the server context and nothing else. Anonymous visitors
51
+ // are not signed in either, so a negated `authenticated()` would hand them the
52
+ // server-or-admin grant on every collection's default policy.
53
+ const SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(
54
+ policy.serverContext(),
55
+ policy.rolesOverlap(["admin"])
56
+ );
57
+
58
+ /** Write operations that must be admin-gated by default on auth collections. */
59
+ const DEFAULT_GUARDED_OPS: SecurityOperation[] = ["insert", "update", "delete"];
60
+
61
+ /** Whether a collection is flagged as an authentication collection. */
62
+ function isAuthCollection(collection: CollectionConfig): boolean {
63
+ const auth = collection.auth;
64
+ return auth === true || (typeof auth === "object" && (auth as AuthCollectionConfig)?.enabled === true);
65
+ }
66
+
67
+ /** The property marked as the row id (falls back to `id`). */
68
+ function getIdPropertyName(collection: CollectionConfig): string {
69
+ for (const [name, prop] of Object.entries(collection.properties ?? {})) {
70
+ if (prop && typeof prop === "object" && "isId" in prop && (prop as { isId?: unknown }).isId) {
71
+ return name;
72
+ }
73
+ }
74
+ return "id";
75
+ }
76
+
77
+ /**
78
+ * Returns the security rules that should be applied to a collection: the
79
+ * author's explicit `securityRules` plus the framework defaults described in
80
+ * the module doc (baseline server/admin read for all collections; self-read
81
+ * and the admin write gate for auth collections).
82
+ *
83
+ * Collections that opt out via `disableDefaultPolicies` are returned unchanged.
84
+ */
85
+ export function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[] {
86
+ const explicit = [...((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? [])];
87
+
88
+ if (collection.disableDefaultPolicies) {
89
+ return explicit;
90
+ }
91
+
92
+ const tableName = getTableName(collection);
93
+ const injected: SecurityRule[] = [];
94
+
95
+ // Baseline read + write: the server context and admins can always operate.
96
+ // RLS default-denies under the user role, so without these a rule-less
97
+ // collection would be locked to everyone — including the admin studio.
98
+ // Author rules are permissive and broaden access from here.
99
+ injected.push({
100
+ name: `${tableName}_default_admin_read`,
101
+ operations: ["select"],
102
+ condition: SERVER_OR_ADMIN_EXPR
103
+ });
104
+ injected.push({
105
+ name: `${tableName}_default_admin_write`,
106
+ operations: [...DEFAULT_GUARDED_OPS],
107
+ condition: SERVER_OR_ADMIN_EXPR,
108
+ check: SERVER_OR_ADMIN_EXPR
109
+ });
110
+
111
+ if (isAuthCollection(collection)) {
112
+ // Self-read: a user can always read their own row.
113
+ injected.push({
114
+ name: `${tableName}_default_self_read`,
115
+ operations: ["select"],
116
+ condition: policy.compare(policy.field(getIdPropertyName(collection)), "eq", policy.authUid())
117
+ });
118
+
119
+ // Restrictive gate: AND'd with all other policies, so no permissive rule
120
+ // (e.g. an owner "edit your own row" rule) can let a non-admin change
121
+ // privileged columns like `roles`.
122
+ injected.push({
123
+ name: `${tableName}_require_admin_write`,
124
+ mode: "restrictive",
125
+ operations: [...DEFAULT_GUARDED_OPS],
126
+ condition: SERVER_OR_ADMIN_EXPR,
127
+ check: SERVER_OR_ADMIN_EXPR
128
+ });
129
+ }
130
+
131
+ return [...explicit, ...injected];
132
+ }
133
+
134
+ /**
135
+ * The framework defaults that {@link getEffectiveSecurityRules} would add to a
136
+ * collection, without the author's own rules.
137
+ *
138
+ * These policies appear in the database under names the author never wrote, and
139
+ * a permissive policy ORs with every other permissive policy — so someone
140
+ * reading their `securityRules` and then the real ACL sees more access than they
141
+ * declared. Dropping them by hand does nothing either: `db push` is declarative,
142
+ * so the next push asserts them again. Callers use this to say, in the generated
143
+ * DDL, which policies are injected and how to take them off.
144
+ */
145
+ export function getInjectedSecurityRules(collection: CollectionConfig): SecurityRule[] {
146
+ if (collection.disableDefaultPolicies) return [];
147
+
148
+ const explicitCount = ((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? []).length;
149
+ // getEffectiveSecurityRules appends the defaults after the author's rules,
150
+ // so everything past the author's count is injected.
151
+ return getEffectiveSecurityRules(collection).slice(explicitCount);
152
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Row identity: the address of a row, and how to derive it.
3
+ *
4
+ * Postgres has no `id`. A row is identified by its primary key — one or more
5
+ * columns, with any names and any types. `id` is something we synthesize on top
6
+ * of that: a single string token, because the admin needs *one* value it can put
7
+ * in a URL (`/products/1:::2`), use as a cache key, and hang a relation ref off.
8
+ *
9
+ * That token is an address, not data. It is derived from the row's columns and
10
+ * never stored in them — a row is exactly its columns, with their real types.
11
+ * Writing the address back into the row is what used to rename primary keys
12
+ * (`sku` → `id`) and restringify them (`42` → `"42"`) on the way out.
13
+ *
14
+ * These live in `common` because both sides need them and must agree exactly:
15
+ * the driver parses an incoming address back into key columns, and the admin
16
+ * derives the address from a row it was served.
17
+ */
18
+
19
+ /**
20
+ * A primary-key column: its name, the type it round-trips as, and whether it is
21
+ * a UUID (which is a string despite sometimes being described as an id "number").
22
+ */
23
+ export interface PrimaryKeyInfo {
24
+ fieldName: string;
25
+ type: "string" | "number";
26
+ isUUID?: boolean;
27
+ }
28
+
29
+ /** Separator between the parts of a composite address. */
30
+ export const COMPOSITE_ID_SEPARATOR = ":::";
31
+
32
+ /**
33
+ * Derive a row's address from its key columns.
34
+ *
35
+ * Single key → the value as a string. Composite → each part joined by
36
+ * {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what
37
+ * {@link parseIdValues} expects to invert.
38
+ */
39
+ export function buildCompositeId(values: Record<string, unknown>, primaryKeys: PrimaryKeyInfo[]): string {
40
+ if (primaryKeys.length === 0) {
41
+ return "";
42
+ }
43
+ if (primaryKeys.length === 1) {
44
+ return String(values[primaryKeys[0].fieldName] ?? "");
45
+ }
46
+ return primaryKeys.map(pk => String(values[pk.fieldName] ?? "")).join(COMPOSITE_ID_SEPARATOR);
47
+ }
48
+
49
+ /**
50
+ * Invert {@link buildCompositeId}: turn an address back into key columns, each
51
+ * coerced to the type its column actually round-trips as.
52
+ *
53
+ * This is the boundary where a URL segment becomes a query parameter, so a
54
+ * malformed address must throw rather than silently produce a query that
55
+ * matches the wrong row (or none).
56
+ */
57
+ export function parseIdValues(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): Record<string, string | number> {
58
+ const result: Record<string, string | number> = {};
59
+
60
+ if (primaryKeys.length === 0) {
61
+ return result;
62
+ }
63
+
64
+ if (primaryKeys.length === 1) {
65
+ const pk = primaryKeys[0];
66
+ if (pk.type === "number" && !pk.isUUID) {
67
+ const parsed = typeof idValue === "number" ? idValue : parseInt(String(idValue), 10);
68
+ if (isNaN(parsed)) {
69
+ throw new Error(`Invalid numeric ID: ${idValue}`);
70
+ }
71
+ result[pk.fieldName] = parsed;
72
+ } else {
73
+ result[pk.fieldName] = String(idValue);
74
+ }
75
+ return result;
76
+ }
77
+
78
+ // Composite key
79
+ const parts = String(idValue).split(COMPOSITE_ID_SEPARATOR);
80
+ if (parts.length !== primaryKeys.length) {
81
+ throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);
82
+ }
83
+
84
+ for (let i = 0; i < primaryKeys.length; i++) {
85
+ const pk = primaryKeys[i];
86
+ const val = parts[i];
87
+ if (pk.type === "number" && !pk.isUUID) {
88
+ const parsed = parseInt(val, 10);
89
+ if (isNaN(parsed)) {
90
+ throw new Error(`Invalid numeric ID component: ${val}`);
91
+ }
92
+ result[pk.fieldName] = parsed;
93
+ } else {
94
+ result[pk.fieldName] = val;
95
+ }
96
+ }
97
+
98
+ return result;
99
+ }
100
+
101
+ /**
102
+ * The primary keys of a collection, as declared by its properties.
103
+ *
104
+ * This is the only tier both sides can read, because it is the only one written
105
+ * in the config: the postgres driver can also infer keys from the Drizzle
106
+ * schema, which the browser never sees and is never sent — the admin compiles
107
+ * the collection files into its own bundle rather than being served them. A key
108
+ * that lives only in the Drizzle schema is therefore invisible here, and the
109
+ * server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`
110
+ * to add.
111
+ *
112
+ * Returns an empty array when a collection declares none, which callers must
113
+ * treat as "not addressable" rather than defaulting to `id`: guessing a key
114
+ * that is not the real one produces confidently wrong addresses.
115
+ */
116
+ export function getDeclaredPrimaryKeys(collection: {
117
+ properties?: Record<string, unknown>;
118
+ }): PrimaryKeyInfo[] {
119
+ const properties = collection.properties;
120
+ if (!properties) return [];
121
+
122
+ const keys: PrimaryKeyInfo[] = [];
123
+ for (const [fieldName, propRaw] of Object.entries(properties)) {
124
+ const prop = propRaw as { type?: string; isId?: unknown } | undefined;
125
+ if (!prop || typeof prop !== "object") continue;
126
+ if (!("isId" in prop) || !prop.isId) continue;
127
+ keys.push({
128
+ fieldName,
129
+ type: prop.type === "number" ? "number" : "string",
130
+ isUUID: prop.isId === "uuid"
131
+ });
132
+ }
133
+ return keys;
134
+ }
135
+
136
+ /**
137
+ * The keys to address a collection's rows with, resolved the way the driver
138
+ * resolves them — minus the tier the browser cannot reach.
139
+ *
140
+ * The postgres driver tries, in order: properties marked `isId`; the primary
141
+ * keys of the Drizzle schema; and finally a column literally named `id`. Only
142
+ * the first and last are visible in a `CollectionConfig`, which is what both
143
+ * sides share.
144
+ *
145
+ * So the two agree except on a collection that declares no `isId` and whose key
146
+ * is known only to Drizzle. There, the driver reads the real key, and this
147
+ * either resolves nothing (reported to the console by the caller) or — if the
148
+ * table happens to have an unrelated `id` property — resolves `id`, which is
149
+ * the wrong key and cannot be detected from here: the addresses look right and
150
+ * route wrong. Only the config can settle it, so the server names both cases
151
+ * at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.
152
+ */
153
+ export function resolvePrimaryKeys(collection: {
154
+ properties?: Record<string, unknown>;
155
+ }): PrimaryKeyInfo[] {
156
+ const declared = getDeclaredPrimaryKeys(collection);
157
+ if (declared.length > 0) return declared;
158
+
159
+ const idProp = collection.properties?.id as { type?: string } | undefined;
160
+ if (idProp && typeof idProp === "object") {
161
+ return [{ fieldName: "id",
162
+ type: idProp.type === "number" ? "number" : "string" }];
163
+ }
164
+
165
+ return [];
166
+ }
package/src/util/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./collections";
2
2
  export * from "./common";
3
3
  export * from "./entities";
4
+ export * from "./identity";
4
5
  export * from "./enums";
5
6
  export * from "./paths";
6
7
  export * from "./resolutions";
@@ -13,6 +14,8 @@ export * from "./builders";
13
14
  export * from "./storage";
14
15
  export * from "./callbacks";
15
16
  export * from "./relations";
17
+ export * from "./auth-default-policies";
18
+ export * from "./junction-policies";
16
19
  export * from "./conditions";
17
20
  export * from "./navigation_utils";
18
21
  export * from "./filter-operator-resolution";