@rebasepro/server-postgres 0.9.1-canary.73476f2 → 0.9.1-canary.74adfbe

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 (62) hide show
  1. package/README.md +21 -0
  2. package/dist/PostgresBackendDriver.d.ts +43 -2
  3. package/dist/PostgresBootstrapper.d.ts +17 -1
  4. package/dist/auth/services.d.ts +68 -52
  5. package/dist/collections/buildRegistry.d.ts +27 -0
  6. package/dist/connection.d.ts +21 -0
  7. package/dist/data-transformer.d.ts +9 -2
  8. package/dist/index.es.js +2185 -775
  9. package/dist/index.es.js.map +1 -1
  10. package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
  11. package/dist/schema/auth-schema.d.ts +24 -24
  12. package/dist/schema/doctor.d.ts +1 -1
  13. package/dist/schema/introspect-db-logic.d.ts +0 -5
  14. package/dist/schema/introspect-db-naming.d.ts +10 -0
  15. package/dist/security/policy-drift.d.ts +30 -0
  16. package/dist/security/rls-enforcement.d.ts +2 -2
  17. package/dist/services/FetchService.d.ts +4 -24
  18. package/dist/services/PersistService.d.ts +27 -1
  19. package/dist/services/RelationService.d.ts +34 -1
  20. package/dist/services/channel-history.d.ts +118 -0
  21. package/dist/services/collection-helpers.d.ts +79 -14
  22. package/dist/services/dataService.d.ts +3 -1
  23. package/dist/services/index.d.ts +1 -1
  24. package/dist/services/realtimeService.d.ts +76 -2
  25. package/dist/services/row-pipeline.d.ts +63 -0
  26. package/package.json +13 -34
  27. package/src/PostgresBackendDriver.ts +183 -18
  28. package/src/PostgresBootstrapper.ts +80 -26
  29. package/src/auth/ensure-tables.ts +170 -28
  30. package/src/auth/services.ts +181 -150
  31. package/src/cli.ts +60 -0
  32. package/src/collections/buildRegistry.ts +59 -0
  33. package/src/connection.ts +61 -1
  34. package/src/data-transformer.ts +11 -9
  35. package/src/databasePoolManager.ts +2 -0
  36. package/src/schema/auth-bootstrap-sql.ts +7 -1
  37. package/src/schema/auth-schema.ts +13 -13
  38. package/src/schema/doctor.ts +45 -20
  39. package/src/schema/generate-drizzle-schema-logic.ts +24 -29
  40. package/src/schema/generate-postgres-ddl-logic.ts +76 -28
  41. package/src/schema/introspect-db-inference.ts +1 -1
  42. package/src/schema/introspect-db-logic.ts +1 -10
  43. package/src/schema/introspect-db-naming.ts +15 -0
  44. package/src/schema/introspect-db.ts +19 -2
  45. package/src/schema/introspect-runtime.ts +1 -1
  46. package/src/security/policy-drift.test.ts +106 -1
  47. package/src/security/policy-drift.ts +56 -0
  48. package/src/security/rls-enforcement.ts +11 -5
  49. package/src/services/BranchService.ts +42 -10
  50. package/src/services/FetchService.ts +65 -270
  51. package/src/services/PersistService.ts +130 -14
  52. package/src/services/RelationService.ts +153 -94
  53. package/src/services/channel-history.ts +343 -0
  54. package/src/services/collection-helpers.ts +164 -47
  55. package/src/services/dataService.ts +3 -2
  56. package/src/services/index.ts +1 -0
  57. package/src/services/realtimeService.ts +238 -29
  58. package/src/services/row-pipeline.ts +239 -0
  59. package/src/utils/drizzle-conditions.ts +13 -0
  60. package/src/websocket.ts +34 -12
  61. package/dist/schema/auth-default-policies.d.ts +0 -10
  62. package/src/schema/auth-default-policies.ts +0 -132
package/src/websocket.ts CHANGED
@@ -27,7 +27,7 @@ interface WsAuthConfig {
27
27
  * Normalized user identity for WebSocket sessions.
28
28
  */
29
29
  interface WsUserIdentity {
30
- userId: string;
30
+ uid: string;
31
31
  roles: string[];
32
32
  isAdmin: boolean;
33
33
  }
@@ -183,7 +183,7 @@ code } }
183
183
 
184
184
  if (adapterUser) {
185
185
  verifiedUser = {
186
- userId: adapterUser.uid,
186
+ uid: adapterUser.uid,
187
187
  roles: adapterUser.roles,
188
188
  isAdmin: adapterUser.isAdmin
189
189
  };
@@ -195,13 +195,13 @@ code } }
195
195
  // Service key: a static secret, not a JWT. Checked
196
196
  // before verification, mirroring the HTTP middleware —
197
197
  // verifying it as a JWT can only ever fail.
198
- verifiedUser = { userId: "service", roles: ["admin"], isAdmin: true };
198
+ verifiedUser = { uid: "service", roles: ["admin"], isAdmin: true };
199
199
  } else {
200
200
  // Standard JWT path
201
201
  const jwtPayload = extractUserFromToken(token);
202
202
  if (jwtPayload) {
203
203
  verifiedUser = {
204
- userId: jwtPayload.userId,
204
+ uid: jwtPayload.uid,
205
205
  roles: jwtPayload.roles ?? [],
206
206
  isAdmin: (jwtPayload.roles ?? []).some((r: string) => r === "admin")
207
207
  };
@@ -218,10 +218,10 @@ code } }
218
218
  ws.send(JSON.stringify({
219
219
  type: "AUTH_SUCCESS",
220
220
  requestId,
221
- payload: { userId: verifiedUser.userId,
221
+ payload: { uid: verifiedUser.uid,
222
222
  roles: verifiedUser.roles }
223
223
  }));
224
- wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.userId}`);
224
+ wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.uid}`);
225
225
  } else {
226
226
  wsDebug(`[WS] replying AUTH_ERROR for requestId ${requestId} (invalid token)`);
227
227
  sendError("AUTH_ERROR", "INVALID_TOKEN", "Invalid or expired token");
@@ -272,7 +272,7 @@ roles: verifiedUser.roles }
272
272
  try {
273
273
  const userForAuth: User = session?.user
274
274
  ? {
275
- uid: session.user.userId,
275
+ uid: session.user.uid,
276
276
  displayName: null,
277
277
  email: null,
278
278
  photoURL: null,
@@ -421,7 +421,7 @@ colors: true }));
421
421
  sql: typeof sql === "string" ? sql.substring(0, 500) : sql,
422
422
  options,
423
423
  resultRows: Array.isArray(result) ? result.length : "unknown",
424
- userId: auditSession?.user?.userId ?? "unknown",
424
+ uid: auditSession?.user?.uid ?? "unknown",
425
425
  roles: auditSession?.user?.roles ?? [],
426
426
  isAdmin: auditSession?.user?.isAdmin ?? false,
427
427
  }));
@@ -476,6 +476,24 @@ colors: true }));
476
476
  }
477
477
  break;
478
478
 
479
+ case "FETCH_APPLICATION_ROLES": {
480
+ wsDebug("👤 [WebSocket Server] Processing FETCH_APPLICATION_ROLES request");
481
+ const delegate = await getScopedDelegate();
482
+ const admin = delegate.admin;
483
+ let roles: string[] = [];
484
+ if (isSQLAdmin(admin) && admin.fetchApplicationRoles) {
485
+ roles = await admin.fetchApplicationRoles();
486
+ }
487
+ wsDebug(`👤 [WebSocket Server] Fetched ${roles.length} application roles.`);
488
+ const response = {
489
+ type: "FETCH_APPLICATION_ROLES_SUCCESS",
490
+ payload: { roles },
491
+ requestId
492
+ };
493
+ ws.send(JSON.stringify(response));
494
+ }
495
+ break;
496
+
479
497
  case "FETCH_CURRENT_DATABASE": {
480
498
  wsDebug("📚 [WebSocket Server] Processing FETCH_CURRENT_DATABASE request");
481
499
  const delegate = await getScopedDelegate();
@@ -594,14 +612,15 @@ colors: true }));
594
612
  case "broadcast":
595
613
  case "presence_track":
596
614
  case "presence_untrack":
597
- case "presence_state": {
615
+ case "presence_state":
616
+ case "channel_history": {
598
617
  wsDebug("🔄 [WebSocket Server] Routing realtime message to RealtimeService:", type);
599
618
  // Attach auth context from the WS session so RLS-aware refetches work
600
619
  const session = clientSessions.get(clientId);
601
620
  const authContext = session?.user
602
- ? { userId: session.user.userId,
621
+ ? { uid: session.user.uid,
603
622
  roles: session.user.roles ?? [] }
604
- : { userId: "anon",
623
+ : { uid: "anon",
605
624
  roles: ["anon"] };
606
625
  // Let RealtimeService handle these messages
607
626
  await realtimeService.handleClientMessage(clientId, {
@@ -620,9 +639,12 @@ roles: ["anon"] };
620
639
  if (error instanceof Error) {
621
640
  logger.error("Stack trace", { detail: error.stack });
622
641
  }
642
+ // Unwrap the cause chain: a Drizzle failure reports itself as
643
+ // "Failed query: <sql> params:", which tells the user nothing and
644
+ // echoes the statement back at them. The reason is in the cause.
623
645
  const errorMessage = process.env.NODE_ENV === "production"
624
646
  ? "An unexpected error occurred"
625
- : (error instanceof Error ? error.message : "An unexpected error occurred");
647
+ : extractErrorMessage(error);
626
648
  const errorResponse = {
627
649
  type: "ERROR",
628
650
  requestId,
@@ -1,10 +0,0 @@
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[];
@@ -1,132 +0,0 @@
1
- import { CollectionConfig, SecurityRule, SecurityOperation, AuthCollectionConfig, PolicyExpression, isPostgresCollectionConfig, policy } from "@rebasepro/types";
2
- import { getTableName } from "@rebasepro/common";
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
- }