@rebasepro/server-postgres 0.13.1-canary.g18cfeb7 → 0.13.1-canary.g1bf9303

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 (88) hide show
  1. package/dist/PostgresBootstrapper.d.ts +26 -0
  2. package/dist/auth/services.d.ts +21 -0
  3. package/dist/{auth-users-columns-Do9mw5Y5.js → auth-users-columns-BxT6FRyu.js} +819 -68
  4. package/dist/auth-users-columns-BxT6FRyu.js.map +1 -0
  5. package/dist/{backup-service-Bww-Lg0s.js → backup-service-BH0Dzo_h.js} +2 -3
  6. package/dist/{backup-service-Bww-Lg0s.js.map → backup-service-BH0Dzo_h.js.map} +1 -1
  7. package/dist/cli-helpers.d.ts +56 -0
  8. package/dist/cli-output.d.ts +34 -0
  9. package/dist/data-transformer.d.ts +7 -2
  10. package/dist/data_driver-ULAyJEi9.js +193 -0
  11. package/dist/data_driver-ULAyJEi9.js.map +1 -0
  12. package/dist/ensure-collection-policies-CP5_YttS.js +124 -0
  13. package/dist/ensure-collection-policies-CP5_YttS.js.map +1 -0
  14. package/dist/{ensure-collection-tables-DSIxvLLD.js → ensure-collection-tables-DWVISfcC.js} +119 -13
  15. package/dist/ensure-collection-tables-DWVISfcC.js.map +1 -0
  16. package/dist/index.es.js +998 -600
  17. package/dist/index.es.js.map +1 -1
  18. package/dist/{rls-bootstrap-sql-Bpv3nUZo.js → rls-bootstrap-sql-69hYT8nr.js} +2 -2
  19. package/dist/{rls-bootstrap-sql-Bpv3nUZo.js.map → rls-bootstrap-sql-69hYT8nr.js.map} +1 -1
  20. package/dist/rls-enforcement-Ct9ab42o.js +425 -0
  21. package/dist/rls-enforcement-Ct9ab42o.js.map +1 -0
  22. package/dist/schema/auth-schema.d.ts +102 -0
  23. package/dist/schema/doctor-policy-checks.d.ts +28 -0
  24. package/dist/schema/doctor.d.ts +41 -25
  25. package/dist/schema/ensure-collection-policies.d.ts +33 -9
  26. package/dist/schema/ensure-collection-tables.d.ts +60 -6
  27. package/dist/schema/generate-drizzle-schema-logic.d.ts +9 -1
  28. package/dist/schema/generate-postgres-ddl-logic.d.ts +48 -0
  29. package/dist/schema/search-column.d.ts +248 -0
  30. package/dist/security/rls-enforcement.d.ts +8 -3
  31. package/dist/services/FetchService.d.ts +24 -0
  32. package/dist/services/RelationService.d.ts +30 -0
  33. package/dist/services/collection-helpers.d.ts +26 -0
  34. package/dist/services/dataService.d.ts +3 -0
  35. package/dist/services/realtimeService.d.ts +139 -2
  36. package/dist/{src-C_wvdMnl.js → src-DCdn3Val.js} +35 -3
  37. package/dist/src-DCdn3Val.js.map +1 -0
  38. package/dist/utils/drizzle-conditions.d.ts +124 -2
  39. package/dist/{websocket-D0TBU3ia.js → websocket-C8ZqVBiV.js} +75 -18
  40. package/dist/websocket-C8ZqVBiV.js.map +1 -0
  41. package/package.json +6 -6
  42. package/src/PostgresBackendDriver.ts +7 -3
  43. package/src/PostgresBootstrapper.ts +95 -9
  44. package/src/auth/ensure-tables.ts +27 -5
  45. package/src/auth/services.ts +82 -5
  46. package/src/backup/backup-cli.ts +59 -57
  47. package/src/cli-errors.ts +6 -6
  48. package/src/cli-helpers.ts +110 -4
  49. package/src/cli-output.ts +43 -0
  50. package/src/cli.ts +210 -145
  51. package/src/collections/buildRegistry.ts +3 -1
  52. package/src/data-transformer.ts +107 -14
  53. package/src/history/ensure-history-table.ts +2 -2
  54. package/src/schema/auth-schema.ts +17 -1
  55. package/src/schema/doctor-cli.ts +14 -65
  56. package/src/schema/doctor-policy-checks.ts +105 -0
  57. package/src/schema/doctor.ts +149 -72
  58. package/src/schema/ensure-collection-policies.ts +99 -6
  59. package/src/schema/ensure-collection-tables.ts +286 -13
  60. package/src/schema/generate-drizzle-schema-logic.ts +126 -42
  61. package/src/schema/generate-drizzle-schema.ts +11 -10
  62. package/src/schema/generate-postgres-ddl-logic.ts +204 -10
  63. package/src/schema/generate-postgres-ddl.ts +38 -14
  64. package/src/schema/introspect-db-logic.ts +65 -33
  65. package/src/schema/introspect-db.ts +24 -24
  66. package/src/schema/search-column.ts +643 -0
  67. package/src/security/rls-enforcement.ts +9 -4
  68. package/src/services/FetchService.ts +229 -15
  69. package/src/services/PersistService.ts +24 -1
  70. package/src/services/RelationService.ts +119 -69
  71. package/src/services/cdc/trigger-cdc.ts +5 -1
  72. package/src/services/channel-history.ts +9 -3
  73. package/src/services/channel-presence.ts +10 -3
  74. package/src/services/collection-helpers.ts +54 -1
  75. package/src/services/dataService.ts +3 -0
  76. package/src/services/pg-notify-listener.ts +1 -1
  77. package/src/services/realtimeService.ts +347 -86
  78. package/src/utils/drizzle-conditions.ts +365 -23
  79. package/src/utils/pg-error-utils.ts +8 -3
  80. package/src/websocket.ts +113 -16
  81. package/dist/auth-users-columns-Do9mw5Y5.js.map +0 -1
  82. package/dist/ensure-collection-policies-DMUdRQdM.js +0 -57
  83. package/dist/ensure-collection-policies-DMUdRQdM.js.map +0 -1
  84. package/dist/ensure-collection-tables-DSIxvLLD.js.map +0 -1
  85. package/dist/policy-CPkCqVTz.js +0 -105
  86. package/dist/policy-CPkCqVTz.js.map +0 -1
  87. package/dist/src-C_wvdMnl.js.map +0 -1
  88. package/dist/websocket-D0TBU3ia.js.map +0 -1
package/src/websocket.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { RealtimeService } from "./services/realtimeService";
2
2
  import { PostgresBackendDriver } from "./PostgresBackendDriver";
3
3
  import type { DataDriver, DeleteProps, FetchCollectionProps, FetchOneProps, SaveProps, TableMetadata, BranchInfo, AuthAdapter } from "@rebasepro/types";
4
- import { ANONYMOUS_USER_ID, isSQLAdmin, isSchemaAdmin } from "@rebasepro/types";
4
+ import { ANONYMOUS_USER_ID, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, ListLimitError } from "@rebasepro/types";
5
5
  import type { User } from "@rebasepro/types";
6
6
 
7
7
  import { WebSocketServer, WebSocket } from "ws";
@@ -39,6 +39,9 @@ interface ClientSession {
39
39
  /** Sliding window message counter for rate limiting */
40
40
  messageCount: number;
41
41
  messageWindowStart: number;
42
+ /** The same window, counted separately for channel frames. */
43
+ channelMessageCount: number;
44
+ channelWindowStart: number;
42
45
  }
43
46
 
44
47
 
@@ -47,6 +50,33 @@ const WS_RATE_LIMIT = 2000;
47
50
  /** Rate limit window in milliseconds (60 seconds) */
48
51
  const WS_RATE_WINDOW_MS = 60_000;
49
52
 
53
+ /**
54
+ * Channel frames get their own budget, because they are a different workload.
55
+ *
56
+ * 2000/minute is 33/second, which is generous for queries and subscriptions and
57
+ * an order of magnitude below what the documented channel idiom asks for: the
58
+ * capacity note in `docs/backend/realtime.md` uses 60 fps cursor movement as
59
+ * its worked example, and the presence idiom re-`track()`s on every move, so
60
+ * one client sustaining that sends ~120 frames/second — 7200 a minute. Sharing
61
+ * one counter meant the cursor stream ate the query budget and then froze for
62
+ * the rest of the window.
63
+ *
64
+ * The number is sized to that documented workload and nothing more; it is not
65
+ * a considered product limit (see `docs/channel-authorization.md`).
66
+ */
67
+ const WS_CHANNEL_RATE_LIMIT = 7200;
68
+
69
+ /** Frames counted against the channel budget rather than the general one. */
70
+ const CHANNEL_MESSAGE_TYPES = new Set([
71
+ "join_channel",
72
+ "leave_channel",
73
+ "broadcast",
74
+ "presence_track",
75
+ "presence_untrack",
76
+ "presence_state",
77
+ "channel_history"
78
+ ]);
79
+
50
80
  /** Admin-only WebSocket message types */
51
81
  const ADMIN_ONLY_TYPES = new Set([
52
82
  "EXECUTE_SQL",
@@ -139,7 +169,9 @@ export function createPostgresWebSocket(
139
169
  clientSessions.set(clientId, { ws,
140
170
  authenticated: !requireAuth,
141
171
  messageCount: 0,
142
- messageWindowStart: Date.now() });
172
+ messageWindowStart: Date.now(),
173
+ channelMessageCount: 0,
174
+ channelWindowStart: Date.now() });
143
175
  realtimeService.addClient(clientId, ws);
144
176
 
145
177
  ws.on("close", () => {
@@ -247,19 +279,34 @@ roles: verifiedUser.roles }
247
279
  }
248
280
  }
249
281
 
250
- // Rate limiting: reject if client exceeds message limit
282
+ // Rate limiting: reject if client exceeds message limit.
283
+ // Channel frames are counted against their own budget — see
284
+ // WS_CHANNEL_RATE_LIMIT for why one shared counter starved them.
251
285
  {
252
286
  const session = clientSessions.get(clientId);
253
287
  if (session) {
254
288
  const now = Date.now();
255
- if (now - session.messageWindowStart > WS_RATE_WINDOW_MS) {
256
- session.messageCount = 0;
257
- session.messageWindowStart = now;
258
- }
259
- session.messageCount++;
260
- if (session.messageCount > WS_RATE_LIMIT) {
261
- sendError("ERROR", "RATE_LIMITED", "Too many requests. Please slow down.");
262
- return;
289
+ const isChannelFrame = CHANNEL_MESSAGE_TYPES.has(type);
290
+ if (isChannelFrame) {
291
+ if (now - session.channelWindowStart > WS_RATE_WINDOW_MS) {
292
+ session.channelMessageCount = 0;
293
+ session.channelWindowStart = now;
294
+ }
295
+ session.channelMessageCount++;
296
+ if (session.channelMessageCount > WS_CHANNEL_RATE_LIMIT) {
297
+ sendError("ERROR", "RATE_LIMITED", "Too many channel messages. Please slow down.");
298
+ return;
299
+ }
300
+ } else {
301
+ if (now - session.messageWindowStart > WS_RATE_WINDOW_MS) {
302
+ session.messageCount = 0;
303
+ session.messageWindowStart = now;
304
+ }
305
+ session.messageCount++;
306
+ if (session.messageCount > WS_RATE_LIMIT) {
307
+ sendError("ERROR", "RATE_LIMITED", "Too many requests. Please slow down.");
308
+ return;
309
+ }
263
310
  }
264
311
  }
265
312
  }
@@ -312,7 +359,19 @@ roles: verifiedUser.roles }
312
359
  wsDebug("📋 [WebSocket Server] Processing FETCH_COLLECTION request");
313
360
  const request: FetchCollectionProps = payload;
314
361
  const delegate = await getScopedDelegate();
315
- const rows = await delegate.fetchCollection(request);
362
+ // Bound the client-supplied limit with the SAME guarantee
363
+ // the REST ingress and `subscribe_collection` apply
364
+ // (`resolveClientListLimit`). Without it an absent limit
365
+ // reached the driver as `undefined`, which emits no LIMIT
366
+ // clause — one socket frame streamed the whole table, on
367
+ // the one transport that skipped the ceiling every other
368
+ // read path enforces.
369
+ const rows = await delegate.fetchCollection({
370
+ ...request,
371
+ limit: resolveClientListLimit(request.limit, {
372
+ vectorSearch: !!request.vectorSearch
373
+ })
374
+ });
316
375
  wsDebug("📋 [WebSocket Server] FETCH_COLLECTION result - rows count:", rows.length);
317
376
  const response = {
318
377
  type: "FETCH_COLLECTION_SUCCESS",
@@ -400,6 +459,12 @@ colors: true }));
400
459
 
401
460
 
402
461
  case "COUNT": {
462
+ // Deliberately NOT routed through `resolveClientListLimit`:
463
+ // this answers with a scalar, and the driver drops `limit`
464
+ // on the way to `SELECT count(*)`. Clamping here could only
465
+ // ever make `total` describe fewer rows than the collection
466
+ // holds — the page size is the caller's business, the total
467
+ // is not.
403
468
  const request: FetchCollectionProps = payload;
404
469
  const delegate = await getScopedDelegate();
405
470
  const count = await delegate.count!(request);
@@ -426,14 +491,29 @@ colors: true }));
426
491
  wsDebug(`⚡ [WebSocket Server] SQL executed. Returned ${Array.isArray(result) ? result.length : "non-array"} rows.`);
427
492
  }
428
493
  const auditSession = clientSessions.get(clientId);
429
- console.log("[SQL Audit] WebSocket SQL execution", JSON.stringify({
430
- sql: typeof sql === "string" ? sql.substring(0, 500) : sql,
431
- options,
494
+ // Through `logger`, not `console.log`: this line is
495
+ // emitted in production, and a bare console call
496
+ // has no severity, no timestamp, no JSON envelope
497
+ // and no LOG_LEVEL gate, so it lands in Cloud
498
+ // Logging as unstructured text the queries written
499
+ // for every other line cannot match.
500
+ //
501
+ // The bound values are counted, never written — the
502
+ // statement is the audit signal, the parameters are
503
+ // whatever row the operator was touching. (stdout is
504
+ // not an audit sink either; a real trail belongs in
505
+ // a table with an actor and a retention policy.)
506
+ logger.info("[SQL Audit] WebSocket SQL execution", {
507
+ sql: typeof sql === "string" ? sql.substring(0, 500) : String(sql),
508
+ database: options?.database,
509
+ role: options?.role,
510
+ paramCount: Array.isArray(options?.params) ? options.params.length : 0,
432
511
  resultRows: Array.isArray(result) ? result.length : "unknown",
433
512
  uid: auditSession?.user?.uid ?? "unknown",
434
513
  roles: auditSession?.user?.roles ?? [],
435
514
  isAdmin: auditSession?.user?.isAdmin ?? false,
436
- }));
515
+ requestId
516
+ });
437
517
  const response = {
438
518
  type: "EXECUTE_SQL_SUCCESS",
439
519
  payload: { result },
@@ -644,6 +724,23 @@ roles: ["anon"] };
644
724
  logger.error("❌ [WebSocket Server] Unknown message type", { detail: type });
645
725
  }
646
726
  } catch (error: unknown) {
727
+ // A refused `limit` is the caller's mistake, not a server fault.
728
+ // Left to the generic branch below it answers INTERNAL_ERROR
729
+ // with the message suppressed in production — so the one thing
730
+ // that would tell the caller what to send instead is exactly
731
+ // what gets dropped. Answered here the way
732
+ // `subscribe_collection` already answers it: INVALID_LIMIT,
733
+ // message intact. The text names the ceiling and nothing else.
734
+ if (error instanceof ListLimitError) {
735
+ logger.warn(`[WebSocket Server] Refused a list read: ${error.message}`);
736
+ ws.send(JSON.stringify({
737
+ type: "ERROR",
738
+ requestId,
739
+ payload: { error: { message: error.message,
740
+ code: "INVALID_LIMIT" } }
741
+ }));
742
+ return;
743
+ }
647
744
  logger.error("💥 [WebSocket Server] Error handling message", { error: error });
648
745
  if (error instanceof Error) {
649
746
  logger.error("Stack trace", { detail: error.stack });