@rebasepro/server-postgres 0.9.1-canary.f2f61da → 0.9.1-canary.fd3754b

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.
Files changed (53) hide show
  1. package/dist/PostgresBackendDriver.d.ts +2 -25
  2. package/dist/PostgresBootstrapper.d.ts +0 -10
  3. package/dist/auth/services.d.ts +0 -16
  4. package/dist/chunk-DSJWtz9O.js +40 -0
  5. package/dist/connection.d.ts +0 -21
  6. package/dist/data-transformer.d.ts +2 -9
  7. package/dist/index.es.js +2598 -2020
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/schema/auth-default-policies.d.ts +10 -0
  10. package/dist/schema/doctor.d.ts +1 -1
  11. package/dist/security/policy-drift.d.ts +5 -16
  12. package/dist/security/rls-enforcement.d.ts +2 -27
  13. package/dist/services/FetchService.d.ts +24 -4
  14. package/dist/services/PersistService.d.ts +1 -27
  15. package/dist/services/RelationService.d.ts +1 -34
  16. package/dist/services/collection-helpers.d.ts +14 -79
  17. package/dist/services/dataService.d.ts +1 -3
  18. package/dist/services/index.d.ts +1 -1
  19. package/dist/services/realtimeService.d.ts +0 -7
  20. package/dist/src-Eh-CZosp.js +595 -0
  21. package/dist/src-Eh-CZosp.js.map +1 -0
  22. package/package.json +17 -15
  23. package/src/PostgresBackendDriver.ts +13 -127
  24. package/src/PostgresBootstrapper.ts +26 -68
  25. package/src/auth/ensure-tables.ts +11 -73
  26. package/src/auth/services.ts +19 -49
  27. package/src/cli-helpers.ts +20 -2
  28. package/src/connection.ts +1 -61
  29. package/src/data-transformer.ts +9 -11
  30. package/src/databasePoolManager.ts +0 -2
  31. package/src/schema/auth-default-policies.ts +125 -0
  32. package/src/schema/doctor-cli.ts +1 -5
  33. package/src/schema/doctor.ts +20 -45
  34. package/src/schema/generate-drizzle-schema-logic.ts +29 -24
  35. package/src/schema/generate-postgres-ddl-logic.ts +28 -76
  36. package/src/schema/introspect-db.ts +2 -19
  37. package/src/security/policy-drift.test.ts +14 -48
  38. package/src/security/policy-drift.ts +10 -72
  39. package/src/security/rls-enforcement.ts +3 -64
  40. package/src/services/BranchService.ts +10 -42
  41. package/src/services/FetchService.ts +270 -65
  42. package/src/services/PersistService.ts +14 -130
  43. package/src/services/RelationService.ts +94 -153
  44. package/src/services/collection-helpers.ts +47 -164
  45. package/src/services/dataService.ts +2 -3
  46. package/src/services/index.ts +0 -1
  47. package/src/services/realtimeService.ts +19 -40
  48. package/src/utils/drizzle-conditions.ts +0 -13
  49. package/src/websocket.ts +1 -4
  50. package/dist/collections/buildRegistry.d.ts +0 -27
  51. package/dist/services/row-pipeline.d.ts +0 -63
  52. package/src/collections/buildRegistry.ts +0 -59
  53. package/src/services/row-pipeline.ts +0 -239
@@ -0,0 +1,10 @@
1
+ import { CollectionConfig, SecurityRule } from "@rebasepro/types";
2
+ /**
3
+ * Returns the security rules that should be applied to a collection: the
4
+ * author's explicit `securityRules` plus the framework defaults described in
5
+ * the module doc (baseline server/admin read for all collections; self-read
6
+ * and the admin write gate for auth collections).
7
+ *
8
+ * Collections that opt out via `disableDefaultPolicies` are returned unchanged.
9
+ */
10
+ export declare function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[];
@@ -2,7 +2,7 @@ import { CollectionConfig, Property } from "@rebasepro/types";
2
2
  export type IssueSeverity = "error" | "warning" | "info";
3
3
  export interface DoctorIssue {
4
4
  severity: IssueSeverity;
5
- category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale" | "sdk_not_generated";
5
+ category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
6
6
  table?: string;
7
7
  column?: string;
8
8
  expected?: string;
@@ -22,10 +22,6 @@ export interface PolicyRef {
22
22
  roles: string[];
23
23
  /** SELECT / INSERT / UPDATE / DELETE / ALL. */
24
24
  command: string;
25
- /** Whether a USING clause is present at all (not what it says). */
26
- hasUsing: boolean;
27
- /** Whether a WITH CHECK clause is present at all (not what it says). */
28
- hasWithCheck: boolean;
29
25
  }
30
26
  export interface PolicyDrift {
31
27
  /** Described by the collections, absent from the database. */
@@ -49,18 +45,11 @@ export declare function parseExpectedPolicies(ddl: string): PolicyRef[];
49
45
  /**
50
46
  * Diff expected against live.
51
47
  *
52
- * Compares names, roles, command, and whether each clause exists — all exact
53
- * values. Policy expression *text* is deliberately not compared: Postgres
54
- * rewrites `qual`/`with_check` when storing them (parenthesising, casting,
55
- * schema-qualifying), so text comparison reports drift that does not exist, and
56
- * a check that cries wolf gets ignored.
57
- *
58
- * Presence is not text, though. A NULL `qual` is not a rewrite of an
59
- * expression, it is the absence of one, and absence has no false-positive risk:
60
- * either the generator emitted a clause or it did not. That distinction is worth
61
- * the extra comparison — a production database was found with a SELECT policy
62
- * whose `qual` was NULL, matching on every field this checked and denying 100%
63
- * of reads. The same blindness would hide a policy that fails open.
48
+ * Compares names, roles and command only — all exact values. Policy
49
+ * *expressions* are deliberately not compared: Postgres rewrites `qual`/
50
+ * `with_check` when storing them (parenthesising, casting, schema-qualifying),
51
+ * so text comparison reports drift that does not exist, and a check that cries
52
+ * wolf gets ignored. Roles alone catch the failure this exists for.
64
53
  */
65
54
  export declare function checkPolicyDrift(client: Queryable, collections: CollectionConfig[]): Promise<PolicyDrift>;
66
55
  export declare const hasDrift: (d: PolicyDrift) => boolean;
@@ -1,5 +1,4 @@
1
1
  import { SQL } from "drizzle-orm";
2
- import { SecurityRule } from "@rebasepro/types";
3
2
  /**
4
3
  * Unified RLS enforcement — the "user context vs server context" model.
5
4
  *
@@ -95,34 +94,10 @@ export declare function ensureAppRole(run: RawSqlRunner, schemas: string[]): Pro
95
94
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
96
95
  * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
97
96
  * be read as NULL and silently escalate a user request to server privileges.
98
- * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
99
- * rather than trusting every caller (e.g. realtime subscription auth) to do it.
100
- * That sentinel is exported from `@rebasepro/types` because it leaks into rule
101
- * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
97
+ * Coerce empty/blank ids to a sentinel here, at the single chokepoint, rather
98
+ * than trusting every caller (e.g. realtime subscription auth) to do it.
102
99
  */
103
100
  export declare function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void>;
104
- /**
105
- * Warn about rules that read as "signed-in users only" but admit anonymous
106
- * callers — `auth.uid() IS NOT NULL`, or a comparison against another
107
- * platform's magic user id such as `'anon'`.
108
- *
109
- * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
110
- * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
111
- * the table reads empty — loud, and that guard throws. These do the opposite:
112
- * the rule compiles to a grant, and nothing looks wrong until the data is
113
- * already public.
114
- *
115
- * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
116
- * serving traffic today: refusing to boot would take an app offline to report a
117
- * problem it already has, and on the read path it would take it offline
118
- * *because* its data was exposed. Rewriting the author's SQL is not an option
119
- * either — this is the escape hatch whose whole promise is that it means what it
120
- * says. So: say so, loudly, and leave the rule alone.
121
- */
122
- export declare function warnOnAnonymousGrants(collections: {
123
- slug?: string;
124
- securityRules?: readonly SecurityRule[];
125
- }[]): void;
126
101
  /**
127
102
  * Reject `pgRoles` that this server can never satisfy.
128
103
  *
@@ -40,22 +40,44 @@ export declare class FetchService {
40
40
  * the target relation so actual row data is returned.
41
41
  */
42
42
  private buildWithConfig;
43
+ /**
44
+ * Detect if a many-to-many relation uses a junction table in the Drizzle schema.
45
+ */
46
+ private isJunctionRelation;
43
47
  /**
44
48
  * Get the Drizzle relation name on the junction table that points to the actual target row.
45
49
  * For example, for posts_tags junction, this returns "tag_id" (the relation pointing to tags).
46
50
  */
47
51
  private getJunctionTargetRelationName;
52
+ /**
53
+ * Convert a db.query result row (with nested relation objects) to a flat row.
54
+ * Handles:
55
+ * - Placing `id` at the top level as a string
56
+ * - Type normalization (dates, numbers, NaN) via normalizeDbValues
57
+ * - Converting nested relation objects to { id, path, __type: "relation" } for CMS
58
+ * - Flattening junction-table many-to-many results
59
+ */
60
+ private drizzleResultToRow;
48
61
  /**
49
62
  * Post-fetch joinPath relations for a single flat row.
50
63
  * joinPath relations cannot be expressed via Drizzle's `with` config,
51
64
  * so they must be loaded separately after the primary query.
52
65
  */
53
66
  private resolveJoinPathRelations;
67
+ /**
68
+ * Post-fetch joinPath relations for a batch of flat rows.
69
+ * Uses batch fetching to avoid N+1 queries for list views.
70
+ */
71
+ private resolveJoinPathRelationsBatch;
54
72
  /**
55
73
  * Resolves joinPath relations for raw REST rows and directly injects them.
56
74
  * Uses RelationService to query the database and maps results back to the flattened objects.
57
75
  */
58
76
  private resolveJoinPathRelationsBatchRest;
77
+ /**
78
+ * Convert a db.query result row to a flat REST-style object with populated relations.
79
+ */
80
+ private drizzleResultToRestRow;
59
81
  /**
60
82
  * Build db.query-compatible options from standard fetch options.
61
83
  * Handles filter, search, orderBy, limit, and cursor-based pagination.
@@ -86,10 +108,8 @@ export declare class FetchService {
86
108
  }): Promise<Record<string, unknown>[]>;
87
109
  /**
88
110
  * Fallback path used when db.query is unavailable.
89
- *
90
- * The primary path runs the results through `toCmsRow`, which maps
91
- * relations from what drizzle already nested — no query per row. This one
92
- * has no nesting to read, so it resolves relations itself, in batches.
111
+ * The primary path uses drizzleResultToRow which handles relation
112
+ * mapping without N+1 queries.
93
113
  *
94
114
  * Process raw database results into flat rows with relations.
95
115
  */
@@ -12,24 +12,6 @@ export declare class PersistService {
12
12
  private relationService;
13
13
  private fetchService;
14
14
  constructor(db: DrizzleClient, registry: PostgresCollectionRegistry);
15
- /**
16
- * Explain a write that matched no rows.
17
- *
18
- * Row-level security filters UPDATE and DELETE through the policy's USING
19
- * clause instead of raising: a denied write is reported by Postgres exactly
20
- * like a successful one that happened to match nothing. Left unchecked, a
21
- * caller cannot tell "denied" from "done" — the write returns 200/204 and
22
- * the row is untouched.
23
- *
24
- * Re-reading the target over the *same* RLS-scoped handle separates the two
25
- * cases. A visible row means the policy rejected the write (403); an
26
- * invisible one means there is nothing there to write for this caller (404,
27
- * matching what a GET would say). The re-read is bound by the caller's own
28
- * policies, so it discloses nothing a plain read wouldn't.
29
- *
30
- * Only reached when zero rows matched, so the happy path pays nothing.
31
- */
32
- private explainZeroRowWrite;
33
15
  /**
34
16
  * Delete an row by ID
35
17
  */
@@ -40,16 +22,8 @@ export declare class PersistService {
40
22
  deleteAll(collectionPath: string, _databaseId?: string): Promise<void>;
41
23
  /**
42
24
  * Save an row (create or update)
43
- *
44
- * With `options.upsert`, the row is written with INSERT ... ON CONFLICT DO
45
- * UPDATE against the primary key rather than a plain UPDATE. That is one
46
- * statement, so it cannot lose a race the way a read-then-write can, and it
47
- * does not care whether the row already exists — which is what a re-runnable
48
- * import needs.
49
25
  */
50
- save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string, options?: {
51
- upsert?: boolean;
52
- }): Promise<Record<string, unknown>>;
26
+ save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string): Promise<Record<string, unknown>>;
53
27
  /**
54
28
  * Get the RelationService instance for external use
55
29
  */
@@ -20,40 +20,6 @@ export declare class RelationService {
20
20
  private db;
21
21
  private registry;
22
22
  constructor(db: DrizzleClient, registry: PostgresCollectionRegistry);
23
- /**
24
- * One target row, as the {@link RelatedRow} everything here returns.
25
- *
26
- * Eight sites built this by hand, which is how the address came to be the
27
- * target's first key column in all eight — one edit, eight places to miss.
28
- *
29
- * `resolveNested` is the one thing they did not agree on, and the
30
- * disagreement was invisible: the single-parent fetches pass `db` and
31
- * `registry` to `parseDataFromServer`, so the target's *own* relations get
32
- * resolved too, while the batch paths deliberately do not — a query per
33
- * target row is the N+1 the batching exists to avoid. Naming the parameter
34
- * makes that a decision rather than a difference between two call sites
35
- * nobody was comparing.
36
- */
37
- private toRelatedRow;
38
- /**
39
- * A WHERE matching any of `parentIds`, by the whole key.
40
- *
41
- * A single key is an `IN (…)`. A composite one cannot be: matching
42
- * `tenant_id IN (1, 1)` collects every row of tenant 1, so two parents that
43
- * share their first column each receive the other's relations. It becomes
44
- * an OR of ANDs — one exact address per parent — which Postgres indexes the
45
- * same way it would a multi-column key lookup.
46
- */
47
- private parentKeyCondition;
48
- /**
49
- * Reject a relation that cannot express a composite-keyed parent.
50
- *
51
- * `localKey` and `foreignKeyOnTarget` are single column names: one column
52
- * cannot reference a two-column key, so such a relation has no correct
53
- * reading. Left alone it would silently match on the first key column and
54
- * hand a tenant's rows to its neighbour — say so instead.
55
- */
56
- private assertSingleKeyAddressable;
57
23
  /**
58
24
  * Fetch rows related to a parent row through a specific relation
59
25
  */
@@ -106,6 +72,7 @@ export declare class RelationService {
106
72
  relationKey: string;
107
73
  relation: Relation;
108
74
  newValue: unknown;
75
+ currentId?: string | number;
109
76
  }>): Promise<void>;
110
77
  /**
111
78
  * Handle inverse relations with joinPath
@@ -1,9 +1,6 @@
1
1
  import { PgTable, AnyPgColumn } from "drizzle-orm/pg-core";
2
2
  import { CollectionConfig } from "@rebasepro/types";
3
3
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
4
- export { buildCompositeId, parseIdValues, COMPOSITE_ID_SEPARATOR } from "@rebasepro/common";
5
- export type { PrimaryKeyInfo } from "@rebasepro/common";
6
- import type { PrimaryKeyInfo } from "@rebasepro/common";
7
4
  /**
8
5
  * Shared helper functions for row operations.
9
6
  * These are used by FetchService, PersistService, and RelationService.
@@ -24,80 +21,18 @@ export interface DrizzleColumnMeta {
24
21
  export declare function getColumnMeta(col: AnyPgColumn): DrizzleColumnMeta;
25
22
  export declare function getCollectionByPath(collectionPath: string, registry: PostgresCollectionRegistry): CollectionConfig;
26
23
  export declare function getTableForCollection(collection: CollectionConfig, registry: PostgresCollectionRegistry): PgTable<any>;
27
- /**
28
- * The key columns a collection's rows are addressed by.
29
- *
30
- * Three tiers, in order: properties marked `isId`, the primary keys of the
31
- * drizzle schema, and finally a column literally named `id`. Only the first is
32
- * visible to the browser, which is why a key known only to drizzle is reported
33
- * at boot — see {@link warnOnKeysTheAdminCannotResolve}.
34
- *
35
- * Returns `[]` when nothing resolves, rather than throwing. It used to open by
36
- * resolving the table, which throws when there is none — so the `isId` tier,
37
- * which needs no table at all, was unreachable for exactly the collections
38
- * most likely to have no table registered. Every caller that wanted "no keys"
39
- * to mean "no keys" had to spell that out in a try/catch.
40
- *
41
- * Callers that cannot proceed without a key must say so themselves, naming the
42
- * collection: an empty array here means "this collection has no address", which
43
- * is a different answer in a notification (broadcast a wildcard) than in a save
44
- * (fail).
45
- */
46
- export declare function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
47
- /**
48
- * The key columns, for callers that cannot do their job without one.
49
- *
50
- * {@link getPrimaryKeys} answers "what keys, if any" and returns `[]` for a
51
- * collection with no address. Most of this driver, though, is building a WHERE
52
- * clause and has no meaning without a key — for those, an empty array is not an
53
- * answer, and indexing `[0]` into it produces `Cannot read properties of
54
- * undefined` three frames from where the real problem is. This says what is
55
- * wrong and which collection it is wrong about.
56
- */
57
- export declare function requirePrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
58
- /**
59
- * Collections whose key the *browser* cannot resolve, and what it will do
60
- * instead.
61
- *
62
- * The two sides resolve keys from different evidence. This driver reads, in
63
- * order: properties marked `isId`, the primary keys of the Drizzle schema, then
64
- * a column literally named `id`. The admin shares the `CollectionConfig` — it
65
- * compiles the same collection files into its bundle — but never the Drizzle
66
- * schema, so the middle tier is invisible to it.
67
- *
68
- * Nothing can normalize this at runtime: the server does not serve the admin
69
- * its collections, so a key resolved here cannot be handed over there. The
70
- * config files are the only thing both sides read, so the fix is an edit to
71
- * them, and the most this can do is say exactly which edit.
72
- *
73
- * Two shapes, and the second is the dangerous one:
74
- *
75
- * - No `isId`, no `id` property → the admin resolves no address, warns in the
76
- * console, and rows cannot be opened or linked.
77
- * - No `isId`, but an `id` property that is *not* the key → the admin addresses
78
- * rows by `id` while this driver reads the address as the real key. Nothing
79
- * errors: the addresses look right and route wrong.
80
- */
81
- export declare function findUnresolvableKeyCollections(collections: CollectionConfig[], registry: PostgresCollectionRegistry): {
82
- collection: CollectionConfig;
83
- keys: PrimaryKeyInfo[];
84
- shadowedByIdProperty: boolean;
24
+ export declare function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): {
25
+ fieldName: string;
26
+ type: "string" | "number";
27
+ isUUID?: boolean;
85
28
  }[];
86
- /**
87
- * Report the collections from {@link findUnresolvableKeyCollections} at boot,
88
- * with the edit that fixes each one.
89
- *
90
- * Grouped by failure, not by collection: the shadowed case is a routing bug and
91
- * the silent case is a missing feature, and they deserve different urgency.
92
- */
93
- export declare function warnOnKeysTheAdminCannotResolve(collections: CollectionConfig[], registry: PostgresCollectionRegistry): void;
94
- /**
95
- * The address of a row: derived from the collection's primary keys, because a
96
- * row does not carry one — it is exactly its columns.
97
- *
98
- * Falls back to a literal `id` column, for a row that reached us from somewhere
99
- * other than this driver. Returns `""` when there is no key and no `id` —
100
- * callers decide what that means, since "unaddressable" is a different answer
101
- * in a notification (broadcast a wildcard) than in a save (fail).
102
- */
103
- export declare function deriveRowAddress(row: Record<string, unknown>, collection: CollectionConfig, registry: PostgresCollectionRegistry): string;
29
+ export declare function parseIdValues(idValue: string | number, primaryKeys: {
30
+ fieldName: string;
31
+ type: "string" | "number";
32
+ isUUID?: boolean;
33
+ }[]): Record<string, string | number>;
34
+ export declare function buildCompositeId(values: Record<string, unknown>, primaryKeys: {
35
+ fieldName: string;
36
+ type: "string" | "number";
37
+ isUUID?: boolean;
38
+ }[]): string;
@@ -82,9 +82,7 @@ export declare class DataService implements DataRepository {
82
82
  /**
83
83
  * Save an row (create or update)
84
84
  */
85
- save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string, options?: {
86
- upsert?: boolean;
87
- }): Promise<Record<string, unknown>>;
85
+ save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string): Promise<Record<string, unknown>>;
88
86
  /**
89
87
  * Delete an row by ID
90
88
  */
@@ -1,4 +1,4 @@
1
1
  export { FetchService } from "./FetchService";
2
2
  export { PersistService } from "./PersistService";
3
3
  export { RelationService } from "./RelationService";
4
- export { getCollectionByPath, getTableForCollection, getPrimaryKeys, deriveRowAddress, parseIdValues, buildCompositeId } from "./collection-helpers";
4
+ export { getCollectionByPath, getTableForCollection, getPrimaryKeys, parseIdValues, buildCompositeId } from "./collection-helpers";
@@ -177,15 +177,8 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
177
177
  /**
178
178
  * Send a lightweight row-level patch to a collection subscriber.
179
179
  * The client can merge this into its cached data for instant feedback.
180
- *
181
- * The key columns ride along: the patch names a row by address, and the
182
- * client has to find that row among the ones it cached — which carry
183
- * columns and no address. The SDK holds no collection config to derive one
184
- * from, so this is the only place the mapping can come from.
185
180
  */
186
181
  private sendCollectionPatch;
187
- /** The key columns of the collection at `path`, if they can be resolved. */
188
- private primaryKeysForPath;
189
182
  private sendError;
190
183
  private sendMessage;
191
184
  /**