@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
@@ -0,0 +1,248 @@
1
+ /**
2
+ * The one place a collection's `search` block becomes SQL.
3
+ *
4
+ * Four things describe a Postgres table in this codebase — the DDL generator,
5
+ * the Drizzle schema generator, the runtime table builder for BaaS mode, and
6
+ * the boot-time schema ensure — and each of them has, at some point, described
7
+ * a column differently from the others. The `varchar(255)` note in
8
+ * `generate-postgres-ddl-logic` is one such scar: the same property produced a
9
+ * capped column down one path and an uncapped one down the other, and nothing
10
+ * failed until a user hit the cap.
11
+ *
12
+ * So the search column is not implemented four times. It is computed once,
13
+ * here, and every generator renders the same {@link SearchColumnSpec}. There is
14
+ * a test asserting exactly that (`search-column-contract.test.ts`); the point of
15
+ * this module is that the test has something to assert *about*.
16
+ *
17
+ * ## Why the expressions look the way they do
18
+ *
19
+ * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and
20
+ * Postgres is stricter here than intuition. Verified against PostgreSQL 18:
21
+ *
22
+ * | expression | immutable |
23
+ * |-----------------------------------------|-----------|
24
+ * | `to_tsvector('spanish', col)` | yes |
25
+ * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |
26
+ * | `array_to_string(col, ' ')` | **no** |
27
+ * | `col::text` on `text[]` | **no** |
28
+ * | `to_jsonb(col)` | **no** |
29
+ * | `unaccent(col)` | **no** — dictionary lookup is STABLE |
30
+ * | `jsonb_to_tsvector('spanish', j, '["string"]')` | yes |
31
+ * | `setweight(...) || setweight(...)` | yes |
32
+ *
33
+ * Three of the four things a real search column needs are therefore unavailable
34
+ * directly, which is why {@link searchHelperFunctions} exists: each wraps a
35
+ * stable built-in in an SQL function declared IMMUTABLE. That declaration is a
36
+ * promise, and it is a true one for these three — array joining, JSON string
37
+ * extraction and accent folding are all deterministic for a given input; the
38
+ * built-ins are marked stable only because they must account for element types
39
+ * and dictionaries in general.
40
+ *
41
+ * The alternative was to skip `unaccent` and text arrays entirely. That is not
42
+ * a real option in an accented language: Postgres stems `auditoría` to
43
+ * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query
44
+ * typed without accents misses every row that carries them.
45
+ */
46
+ import { CollectionConfig, SearchConfig, SearchWeight } from "@rebasepro/types";
47
+ /**
48
+ * Names of the helper functions. Frozen: they are recorded in the stored
49
+ * generation expression of every search column ever created, so renaming one
50
+ * orphans every table that already has a search column.
51
+ */
52
+ export declare const SEARCH_TEXT_FN = "public.rebase_search_text";
53
+ export declare const SEARCH_UNACCENT_FN = "public.rebase_search_unaccent";
54
+ /** How a declared path reaches text, which decides the SQL that extracts it. */
55
+ type FieldKind = "text" | "text_array" | "jsonb";
56
+ /** One resolved field: where it lives, how to read it, what it is worth. */
57
+ export interface ResolvedSearchField {
58
+ /** The path exactly as the author wrote it, for error messages. */
59
+ path: string;
60
+ /** The physical column the path starts at. */
61
+ column: string;
62
+ /** Dotted remainder addressed inside a JSONB column, if any. */
63
+ jsonPath: string[];
64
+ kind: FieldKind;
65
+ weight: SearchWeight;
66
+ /** The `setweight(to_tsvector(…), 'X')` term this field contributes. */
67
+ sql: string;
68
+ /** The plain-text term this field contributes, for the fuzzy column. */
69
+ textSql: string;
70
+ }
71
+ /** Everything the generators need to render one collection's search column. */
72
+ export interface SearchColumnSpec {
73
+ schema: string;
74
+ table: string;
75
+ /** The generated `tsvector` column. */
76
+ column: string;
77
+ language: string;
78
+ unaccent: boolean;
79
+ fields: ResolvedSearchField[];
80
+ /** Body of `GENERATED ALWAYS AS ( … ) STORED` for the tsvector column. */
81
+ expression: string;
82
+ indexName: string;
83
+ /** Extensions that must exist before the column can be created. */
84
+ extensions: string[];
85
+ fuzzy?: {
86
+ column: string;
87
+ expression: string;
88
+ indexName: string;
89
+ threshold: number;
90
+ };
91
+ }
92
+ /** Raised when a `search` block names something that cannot be searched. */
93
+ export declare class SearchConfigError extends Error {
94
+ constructor(message: string);
95
+ }
96
+ /** The `search` block of a collection, or undefined when it has none. */
97
+ export declare const getSearchConfig: (collection: CollectionConfig) => SearchConfig | undefined;
98
+ /**
99
+ * Refuse a `search` block on a collection this engine does not store.
100
+ *
101
+ * The type only permits one on a `PostgresCollectionConfig`, so TypeScript
102
+ * already stops the ordinary case. This catches the rest — a JS config, a cast,
103
+ * a collection whose `engine` was changed after the block was written — because
104
+ * the alternative is the exact failure the block exists to prevent: a developer
105
+ * who declared what to index, saw no error, and got the substring fallback.
106
+ *
107
+ * Called with *every* collection, before the Postgres ones are filtered out.
108
+ */
109
+ export declare const assertSearchIsPostgresOnly: (collections: CollectionConfig[]) => void;
110
+ /**
111
+ * Build the full spec for a collection, or undefined when it has not opted in.
112
+ *
113
+ * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers
114
+ * at boot surface that as a startup failure — a search block that half-works is
115
+ * worse than one that refuses.
116
+ */
117
+ export declare const buildSearchColumnSpec: (collection: CollectionConfig) => SearchColumnSpec | undefined;
118
+ /**
119
+ * The IMMUTABLE wrappers the generated expressions call.
120
+ *
121
+ * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather
122
+ * than an error, and idempotent for the same reason every other boot-time DDL
123
+ * statement here is.
124
+ *
125
+ * The bodies are stable built-ins wrapped in an immutable promise — see the
126
+ * module comment for why that promise is sound. `STRICT` matters: it makes NULL
127
+ * in mean NULL out without executing the body, which is what the `coalesce` at
128
+ * each call site then absorbs.
129
+ */
130
+ export declare const searchHelperFunctions: (spec: SearchColumnSpec) => string[];
131
+ /**
132
+ * `CREATE EXTENSION` statements the spec's expressions depend on.
133
+ *
134
+ * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified
135
+ * `CREATE EXTENSION` installs into the first schema on `search_path`, which
136
+ * defaults to `"$user", public` — and the scaffold's database role is named
137
+ * `rebase`, the same as the schema the generator creates one statement earlier.
138
+ * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the
139
+ * dictionary in `rebase`, and every reference to `public.unaccent` below fails
140
+ * with "text search dictionary does not exist". Observed, not theorised.
141
+ */
142
+ export declare const searchExtensionStatements: (spec: SearchColumnSpec) => string[];
143
+ /** The column definition as it appears inside `CREATE TABLE`. */
144
+ export declare const searchColumnDefinition: (spec: SearchColumnSpec) => string;
145
+ /** The fuzzy column definition, when the spec asks for one. */
146
+ export declare const fuzzyColumnDefinition: (spec: SearchColumnSpec) => string | undefined;
147
+ /**
148
+ * Index statements for the spec.
149
+ *
150
+ * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a
151
+ * SQL file replayed as one unit — a migration, or `search.sql` — where a
152
+ * concurrent build is not allowed. The boot-time ensure path runs statement by
153
+ * statement against tables that are live and populated, and uses the
154
+ * concurrent form instead; see `ensureSearchColumns`.
155
+ */
156
+ export declare const searchIndexStatements: (spec: SearchColumnSpec) => string[];
157
+ /**
158
+ * Marker on the comment of every generated search column this module creates.
159
+ *
160
+ * Versioned because the fingerprint below is only comparable against itself: a
161
+ * future change to how it is computed has to read as "not stamped by this
162
+ * version" rather than as drift on every existing column.
163
+ */
164
+ export declare const SEARCH_STAMP_PREFIX = "rebase:search:v1:";
165
+ /**
166
+ * A stable fingerprint of one generated column's expression.
167
+ *
168
+ * Why a stamp rather than reading the expression back: Postgres stores a
169
+ * generated column's expression *parsed*, and hands it back deparsed — casts
170
+ * made explicit, identifiers requoted, schema qualifications added or dropped
171
+ * according to `search_path`. Comparing that text to the text we generated
172
+ * would report drift on wording, and this comparison decides whether a boot
173
+ * refuses, so a false positive is an outage. The stamp is written by the same
174
+ * code that writes the column, so equality means what it says.
175
+ */
176
+ export declare const searchExpressionFingerprint: (expression: string) => string;
177
+ /** One generated column, with the fingerprint that identifies its expression. */
178
+ export interface SearchColumnStamp {
179
+ column: string;
180
+ /** The expression the column is generated from. */
181
+ expression: string;
182
+ fingerprint: string;
183
+ /** `COMMENT ON COLUMN …`, which is where the fingerprint is recorded. */
184
+ sql: string;
185
+ }
186
+ /**
187
+ * The stamps for a spec's generated columns — one per column, never shared.
188
+ *
189
+ * Per column on purpose: turning `fuzzy` on adds a second column and changes
190
+ * nothing about the first, and a spec-wide fingerprint would report the
191
+ * untouched `tsvector` column as drifted and refuse a boot over a change that
192
+ * is purely additive.
193
+ */
194
+ export declare const searchColumnStamps: (spec: SearchColumnSpec) => SearchColumnStamp[];
195
+ /**
196
+ * The same drift check as the boot ensure, for the SQL file.
197
+ *
198
+ * Needed because {@link searchColumnStamps} would otherwise *launder* drift on
199
+ * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that
200
+ * exists, so a re-generated `search.sql` would stamp a stale column with the
201
+ * new block's fingerprint and the next boot would find them in agreement.
202
+ * Guarding first means the file refuses instead — `rebase db push` is attended,
203
+ * and the operator reading the failure is the person who changed the block.
204
+ */
205
+ export declare const searchStampGuards: (spec: SearchColumnSpec) => string[];
206
+ /**
207
+ * The index names the spec creates.
208
+ *
209
+ * Needed by name, not just by statement, so Atlas can be told to exclude them
210
+ * from its diff — see `searchExcludePatterns`.
211
+ */
212
+ export declare const searchIndexNames: (spec: SearchColumnSpec) => string[];
213
+ /**
214
+ * The generated column names a collection's search block adds, if any.
215
+ *
216
+ * These are physical columns on the table, so `SELECT *` returns them. They are
217
+ * an index in column form — a list of lexeme positions, or a concatenation of
218
+ * every searchable field on the row — and nothing outside the query planner has
219
+ * any use for them. Left in, every list response carries a second, larger copy
220
+ * of the row's text.
221
+ */
222
+ export declare const searchColumnNames: (collection: CollectionConfig) => string[];
223
+ /**
224
+ * True for a column whose type only ever holds a search index.
225
+ *
226
+ * Independent of any collection config on purpose: an introspected database
227
+ * (BaaS mode) can carry a `tsvector` column this framework never created —
228
+ * Pagila's `film.fulltext` is the canonical one — and it should not be returned
229
+ * to callers either. `isDerivedIndexColumn` already keeps such a column out of
230
+ * the *properties*; this keeps it out of the *rows*.
231
+ */
232
+ export declare const isSearchIndexColumn: (column: {
233
+ getSQLType?: () => string;
234
+ }) => boolean;
235
+ /**
236
+ * A drizzle select projection over `table` with the search columns dropped.
237
+ *
238
+ * Returns undefined when nothing needs dropping, so the common case keeps using
239
+ * a plain `select()` and this stays invisible in the generated SQL.
240
+ */
241
+ export declare const visibleColumnProjection: (tableColumns: Record<string, {
242
+ getSQLType?: () => string;
243
+ }> | undefined, collection?: CollectionConfig) => Record<string, unknown> | undefined;
244
+ /** The same exclusion as a drizzle `db.query` `columns` denylist. */
245
+ export declare const hiddenColumnsOption: (tableColumns: Record<string, {
246
+ getSQLType?: () => string;
247
+ }> | undefined, collection?: CollectionConfig) => Record<string, false> | undefined;
248
+ export {};
@@ -14,9 +14,14 @@ import { REBASE_USER_ROLE } from "@rebasepro/common";
14
14
  * are validation/side-effects, not a security boundary.
15
15
  *
16
16
  * - **Server context** — the base (owner) connection: auth flows, migrations,
17
- * background jobs, and the explicit `rebase.dataAsAdmin` accessor. As table
18
- * owner it bypasses RLS. This is the trusted plane, equivalent to
19
- * Supabase's `service_role`.
17
+ * and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted
18
+ * plane, equivalent to Supabase's `service_role`.
19
+ *
20
+ * `rebase.dataAsAdmin` is **not** in it, despite the name. `init.ts` scopes
21
+ * that driver with `withAuth(SERVICE_IDENTITY)`, so it arrives as user
22
+ * context above — `rebase_user`, `app.uid = 'service'`, policies evaluated —
23
+ * and clears the default policies through their admin arm rather than the
24
+ * `auth.uid() IS NULL` one.
20
25
  *
21
26
  * This module provides the three pieces:
22
27
  *
@@ -64,6 +64,18 @@ export declare class FetchService {
64
64
  * and skips rows rather than erroring. The guesses stay, last, for a
65
65
  * caller that hands over no collection to resolve against.
66
66
  */
67
+ /**
68
+ * The ORDER BY target, which may be relevance rather than a column.
69
+ *
70
+ * `_score` is only meaningful for a collection that declared a `search`
71
+ * block *and* for a request that carried a search string — ranking rows
72
+ * against no query ranks them all at zero. Outside those two conditions it
73
+ * is an unknown field and gets the same 400 as any other typo, which is the
74
+ * behaviour that matters: a sort that is silently dropped returns 200 with
75
+ * rows in arbitrary order, and paging over that repeats and skips rows.
76
+ */
77
+ static readonly SCORE_FIELD = "_score";
78
+ private resolveOrderTarget;
67
79
  private resolveOrderByField;
68
80
  /**
69
81
  * Build the `with` config for Drizzle's relational query API.
@@ -132,6 +144,7 @@ export declare class FetchService {
132
144
  offset?: number;
133
145
  startAfter?: Record<string, unknown>;
134
146
  searchString?: string;
147
+ searchExplain?: boolean;
135
148
  databaseId?: string;
136
149
  vectorSearch?: VectorSearchParams;
137
150
  logical?: LogicalCondition;
@@ -177,10 +190,21 @@ export declare class FetchService {
177
190
  */
178
191
  searchRows<M extends Record<string, unknown>>(collectionPath: string, searchString: string, options?: {
179
192
  filter?: FilterValues<Extract<keyof M, string>>;
193
+ /**
194
+ * An `or(...)`/`and(...)` group, applied alongside `filter`.
195
+ *
196
+ * `fetchRowsWithConditions` has always applied one; it was missing
197
+ * from this signature, so a realtime search subscription carrying a
198
+ * group could not pass it on and served every row matching the text
199
+ * that RLS allowed.
200
+ */
201
+ logical?: LogicalCondition;
180
202
  orderBy?: string;
181
203
  order?: "desc" | "asc";
182
204
  limit?: number;
183
205
  databaseId?: string;
206
+ /** Ask each row which declared search field matched. */
207
+ searchExplain?: boolean;
184
208
  }): Promise<Record<string, unknown>[]>;
185
209
  /**
186
210
  * Count rows in a collection
@@ -149,6 +149,36 @@ export declare class RelationService {
149
149
  * Uses a single SQL query with IN clause to avoid N+1.
150
150
  */
151
151
  batchFetchRelatedEntitiesMany(parentCollectionPath: string, parentIds: (string | number)[], _relationKey: string, relation: ResolvedRelation): Promise<Map<string, RelatedRow<Record<string, unknown>>[]>>;
152
+ /**
153
+ * Bring one row's junction links in line with the ids a save carried,
154
+ * by diffing against what is stored rather than replacing the lot.
155
+ *
156
+ * The old shape was `DELETE every link for this parent` followed by
157
+ * `INSERT what the client sent`, which makes a save of the parent a full
158
+ * replacement of the membership set from a list the browser assembled out
159
+ * of a read it did earlier. Three things follow from that, and the diff
160
+ * closes all three:
161
+ *
162
+ * - **Lost update.** Two editors with post 7 open: A adds tag X and saves;
163
+ * B saves any field and the whole set is rewritten from B's older list,
164
+ * dropping X with nothing to show for it. A diff only names the ids that
165
+ * actually changed, so edits to disjoint tags no longer collide.
166
+ * - **Partial read, partial delete.** The read that fills the form runs
167
+ * under RLS, so a user who may edit the parent but cannot *see* some of
168
+ * the linked rows gets a shorter list — and writing it back deleted the
169
+ * links they were never shown. The DELETE now names ids instead of
170
+ * "everything for this parent", and the select that produces them runs
171
+ * in this same transaction under the same policies, so a link the caller
172
+ * cannot read is in neither list and survives the save.
173
+ * - **Junction payload columns.** A junction carrying its own columns
174
+ * (`position`, `role`, `created_at`) lost them on every save, because
175
+ * every row was re-inserted with only the two keys. Untouched links are
176
+ * now left alone.
177
+ *
178
+ * The insert is `ON CONFLICT DO NOTHING` so that two sessions adding the
179
+ * same link concurrently is a no-op rather than a unique violation.
180
+ */
181
+ private syncJunctionLinks;
152
182
  /**
153
183
  * Update many-to-many and junction relations
154
184
  */
@@ -34,6 +34,32 @@ export declare function getColumnMeta(col: AnyPgColumn): DrizzleColumnMeta;
34
34
  */
35
35
  export declare function idCanAddressTable(id: string | number, table: PgTable, idInfoArray: PrimaryKeyInfo[]): boolean;
36
36
  export declare function getCollectionByPath(collectionPath: string, registry: PostgresCollectionRegistry): CollectionConfig;
37
+ /**
38
+ * Reject a write naming something that is not a column of the table.
39
+ *
40
+ * Drizzle builds INSERT from `Object.entries(table[Symbol.Columns])` and UPDATE
41
+ * from `Object.keys(tableColumns)`, so a key the table does not carry is not
42
+ * rejected by anything — it is *left out of the statement*. The insert answers
43
+ * 201 having stored nothing under that name; the update, if the key was the
44
+ * only one, builds `update "posts" set where …` and Postgres raises a syntax
45
+ * error (SQLSTATE 42601), which is neither class 22 nor 23 and so surfaces as a
46
+ * 500 for what is a caller's typo.
47
+ *
48
+ * That makes this the last honest place to check, and the only one every write
49
+ * passes through. `assertKnownWriteFields` in the REST layer checks the same
50
+ * thing against the *config* and is skipped on four paths — `strictWrites:
51
+ * false`, a collection declaring no properties, an auth adapter that owns the
52
+ * body's shape, and a nested route whose target cannot be walked — and it never
53
+ * sees an in-process `rebase.data` write at all.
54
+ *
55
+ * It also gives `strictWrites: false` a truthful implementation. The flag is
56
+ * documented for "a column that really does exist which the config never
57
+ * declared", and skipping the config check alone could not deliver that: the
58
+ * value was dropped a layer later regardless. Skipping the config check and
59
+ * keeping this one does exactly what the flag says — the column must exist,
60
+ * the property need not.
61
+ */
62
+ export declare function assertWritableColumns(values: Record<string, unknown>, table: PgTable, collectionPath: string): void;
37
63
  export declare function getTableForCollection(collection: CollectionConfig, registry: PostgresCollectionRegistry): PgTable<any>;
38
64
  /**
39
65
  * The key columns a collection's rows are addressed by.
@@ -52,10 +52,13 @@ export declare class DataService implements DataRepository {
52
52
  */
53
53
  searchRows<M extends Record<string, unknown>>(collectionPath: string, searchString: string, options?: {
54
54
  filter?: FilterValues<Extract<keyof M, string>>;
55
+ /** An `or(...)`/`and(...)` group, applied alongside `filter`. */
56
+ logical?: LogicalCondition;
55
57
  orderBy?: string;
56
58
  order?: "desc" | "asc";
57
59
  limit?: number;
58
60
  databaseId?: string;
61
+ searchExplain?: boolean;
59
62
  }): Promise<Record<string, unknown>[]>;
60
63
  /**
61
64
  * Count rows in a collection
@@ -14,6 +14,34 @@ export interface SubscriptionAuthContext {
14
14
  uid: string;
15
15
  roles: string[];
16
16
  }
17
+ /** What a channel frame is asking to do. */
18
+ export type ChannelAction = "join" | "broadcast" | "presence" | "history";
19
+ /** Everything an authorizer is told about the frame it is asked to allow. */
20
+ export interface ChannelAuthorizationRequest {
21
+ /** The channel the frame names, exactly as the client wrote it. */
22
+ channel: string;
23
+ action: ChannelAction;
24
+ /** The socket, not the principal — one user may hold several. */
25
+ clientId: string;
26
+ /** The socket's authenticated principal, or the anonymous one. */
27
+ user?: SubscriptionAuthContext;
28
+ }
29
+ /**
30
+ * The extension point for channel access rules.
31
+ *
32
+ * **This is deliberately not a product API yet.** The rule *language* — a
33
+ * config key, a per-pattern DSL, how it composes with `securityRules` — is an
34
+ * open design question (see `docs/channel-authorization.md`), and
35
+ * inventing one here would be inventing the answer. What exists is the single
36
+ * place every channel frame passes through, so that whatever shape the rules
37
+ * eventually take has exactly one seam to plug into and no arm of the switch
38
+ * can be forgotten.
39
+ *
40
+ * Returning `false` — or throwing — refuses the frame. It is consulted *after*
41
+ * the membership floor below, so an authorizer can only ever narrow access,
42
+ * never widen it.
43
+ */
44
+ export type ChannelAuthorizer = (request: ChannelAuthorizationRequest) => boolean | Promise<boolean>;
17
45
  /**
18
46
  * The narrowing a collection subscription was created with, kept so that every
19
47
  * refetch answers the same query the initial fetch did.
@@ -34,6 +62,8 @@ type StoredCollectionRequest = {
34
62
  startAfter?: Record<string, unknown>;
35
63
  databaseId?: string;
36
64
  searchString?: string;
65
+ /** Ask each row which declared search field matched — populates `_matches`. */
66
+ searchExplain?: boolean;
37
67
  };
38
68
  /**
39
69
  * PostgreSQL-specific realtime service.
@@ -44,6 +74,12 @@ type StoredCollectionRequest = {
44
74
  export declare class RealtimeService extends EventEmitter implements RealtimeProvider {
45
75
  private db;
46
76
  private registry;
77
+ /**
78
+ * Declares to the multi-engine router that channel frames can be handled
79
+ * here. Read by `createRoutedRealtimeService`, which otherwise would have to
80
+ * guess — and guessed "the default provider", whichever engine that is.
81
+ */
82
+ readonly supportsChannels = true;
47
83
  private clients;
48
84
  private channels;
49
85
  private presence;
@@ -90,6 +126,23 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
90
126
  * so a hot channel logs the problem once rather than once per message.
91
127
  */
92
128
  private oversizedBroadcastWarned;
129
+ /**
130
+ * Optional narrowing on top of the membership floor — see
131
+ * {@link ChannelAuthorizer}. Unset by default, which leaves membership as
132
+ * the whole of the rule.
133
+ */
134
+ private channelAuthorizer?;
135
+ /**
136
+ * Whether a notification from another instance has ever arrived.
137
+ *
138
+ * The entity LISTEN handler sees a foreign `sid` on every cross-instance
139
+ * change, which is proof that this deployment runs more than one pod — the
140
+ * one fact needed to tell "the memory bus is fine here" from "broadcast and
141
+ * presence silently reach a fraction of your users".
142
+ */
143
+ private foreignInstanceSeen;
144
+ /** So the multi-pod memory-bus warning is emitted once, not once per join. */
145
+ private memoryBusWarned;
93
146
  private presenceInterval?;
94
147
  private static readonly PRESENCE_TIMEOUT_MS;
95
148
  /** How often stale roster rows from other instances are reaped. */
@@ -194,7 +247,39 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
194
247
  */
195
248
  notifyUpdate(path: string, id: string, row: Record<string, unknown> | null, databaseId?: string, broadcast?: boolean, origin?: "app" | "cdc"): Promise<void>;
196
249
  /**
197
- * Notify subscriptions for a specific path
250
+ * Notify subscriptions for a specific path.
251
+ *
252
+ * **A subscriber only ever receives rows re-read under its own scope.**
253
+ * `row` is used to decide *that* something changed, never to say *what* —
254
+ * every delivery below goes through a refetch that binds the subscription's
255
+ * own auth context.
256
+ *
257
+ * It used to be conditional. The CDC path already did the right thing: it
258
+ * discards the captured tuple and emits `{_rebase_invalidated: true}`, and
259
+ * that marker selected the refetch branch. But the marker is produced in
260
+ * exactly two places, and the *other* side of each branch here shipped the
261
+ * row it was handed straight to the socket. Two of the three entry paths
262
+ * took that side — every API mutation (`PostgresBackendDriver.save` passes
263
+ * the row it just wrote, read under the **writer's** scope) and the legacy
264
+ * cross-instance LISTEN handler (which re-reads on the owner connection,
265
+ * bypassing RLS altogether). Path matching was the only filter applied: the
266
+ * subscription's own `filter`/`logical` was never evaluated, and any
267
+ * `afterRead` redaction was the writer's rather than the reader's.
268
+ *
269
+ * A single-row subscription was the sharpest case. `subscribe_one` on a row
270
+ * RLS denies is accepted and answered `null`; the next update then pushed
271
+ * the full row with no later correction. The collection variant was merely
272
+ * papered over ~300 ms later by the debounced refetch — after the bytes had
273
+ * already reached the browser.
274
+ *
275
+ * The same defect was found and fixed on the Mongo driver in `065e2b615`
276
+ * (see `packages/server-mongo/test/realtime-authorization.test.ts`); this is
277
+ * the Postgres half, stated as one rule rather than three patched branches.
278
+ *
279
+ * The cost is the instant row-level patch that used to precede the refetch:
280
+ * cross-tab feedback now waits for the debounce. That is the price of not
281
+ * being able to know, without asking the database as this subscriber,
282
+ * whether this subscriber may see the row at all.
198
283
  */
199
284
  private notifyPathUpdate;
200
285
  /**
@@ -235,7 +320,6 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
235
320
  * columns and no address. The SDK holds no collection config to derive one
236
321
  * from, so this is the only place the mapping can come from.
237
322
  */
238
- private sendCollectionPatch;
239
323
  /** The key columns of the collection at `path`, if they can be resolved. */
240
324
  private primaryKeysForPath;
241
325
  private sendError;
@@ -245,8 +329,61 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
245
329
  * Returns ["posts", "posts/70"] for the example above
246
330
  */
247
331
  private getParentPaths;
332
+ /**
333
+ * Install a channel authorizer — see {@link ChannelAuthorizer}.
334
+ *
335
+ * Nothing in the framework calls this yet: it is the seam a rules API will
336
+ * be built on, kept deliberately separate from the membership floor so the
337
+ * floor holds whether or not anyone uses it.
338
+ */
339
+ setChannelAuthorizer(authorizer: ChannelAuthorizer | undefined): void;
340
+ /** Which action each channel frame is asking to perform. */
341
+ private static readonly CHANNEL_ACTIONS;
342
+ /**
343
+ * The one door every channel frame comes through.
344
+ *
345
+ * Returns synchronously — and so dispatches synchronously — unless an
346
+ * authorizer is installed. That matters: a client sends `join_channel`,
347
+ * `presence_state` and `channel_history` back to back on connect, and the
348
+ * socket's message handler processes each frame up to its first `await`,
349
+ * so a gate that always yielded would let the reads overtake the join that
350
+ * is about to authorize them.
351
+ */
352
+ private handleChannelMessage;
353
+ /** Perform an already-authorized channel frame. */
354
+ private dispatchChannelMessage;
355
+ /**
356
+ * Decide whether a client may perform an action on a channel.
357
+ *
358
+ * **Membership is the floor.** Reading a channel's presence roster, replaying
359
+ * its retained history and broadcasting into it all require that this client
360
+ * has joined it. That is a low bar — joining is open to anyone who can name
361
+ * the channel — but it is not the bar that was there before, which was none
362
+ * at all: `channel_history` and `presence_state` answered any socket about
363
+ * any channel, and a broadcast fanned out to members the sender had never
364
+ * joined. Two internal tables (`rebase.channel_presence`,
365
+ * `rebase.channel_messages`) are held outside RLS on the strength of this
366
+ * check, so it fails closed: an authorizer that throws refuses the frame.
367
+ *
368
+ * Anything richer than membership belongs in a {@link ChannelAuthorizer};
369
+ * this method is where it is consulted, and the only place.
370
+ */
371
+ private authorizeChannelAction;
372
+ /** Tell the client why its channel frame went nowhere, and say so in the log. */
373
+ private denyChannelAction;
248
374
  /** Join a broadcast channel */
249
375
  joinChannel(clientId: string, channel: string): void;
376
+ /**
377
+ * Say something the first time channels are used on a deployment that is
378
+ * demonstrably multi-pod while the bus is still the in-memory default.
379
+ *
380
+ * Every other warning in this subsystem covers a *configured* bus failing —
381
+ * the case where the operator already knew a bus mattered. The common
382
+ * misconfiguration is the opposite one: scaled to two replicas, never
383
+ * touched `realtime.bus`, and broadcast and presence quietly serve a
384
+ * fraction of the room. The evidence is already in the process, so use it.
385
+ */
386
+ private warnIfMemoryBusOnMultiplePods;
250
387
  /** Leave a broadcast channel */
251
388
  leaveChannel(clientId: string, channel: string): void;
252
389
  /**
@@ -2,6 +2,25 @@ import { createRequire as __createRequire } from "module";
2
2
  import "process";
3
3
  __createRequire(import.meta.url);
4
4
  //#region ../types/src/types/filter-operators.ts
5
+ /** Maps canonical operators to their REST short-code equivalents. */
6
+ var CANONICAL_TO_REST = {
7
+ "==": "eq",
8
+ "!=": "neq",
9
+ ">": "gt",
10
+ ">=": "gte",
11
+ "<": "lt",
12
+ "<=": "lte",
13
+ "in": "in",
14
+ "not-in": "nin",
15
+ "array-contains": "cs",
16
+ "array-contains-any": "csa",
17
+ "like": "like",
18
+ "ilike": "ilike",
19
+ "not-like": "nlike",
20
+ "not-ilike": "nilike",
21
+ "is-null": "isnull",
22
+ "is-not-null": "notnull"
23
+ };
5
24
  /** Maps REST short-code operators to their canonical equivalents. */
6
25
  var REST_TO_CANONICAL = {
7
26
  "eq": "==",
@@ -53,6 +72,19 @@ var ALL_WHERE_FILTER_OPS = [
53
72
  /** All canonical operator strings for runtime validation. */
54
73
  var CANONICAL_OPS = new Set(ALL_WHERE_FILTER_OPS);
55
74
  /**
75
+ * The REST table as a `Map`, because the key `toCanonicalOp` is handed comes
76
+ * off the wire.
77
+ *
78
+ * Indexed as a plain object, every `Object.prototype` member answered:
79
+ * `toCanonicalOp("valueOf")` returned the inherited *function* as though it
80
+ * were a `WhereFilterOp`, and every caller here treats a defined result as
81
+ * "known operator". Same defect the REST codec's own lookup tables were
82
+ * converted away from in `filter-dialect.ts`; this is the copy that survived
83
+ * one package over, and it now sits under the operator validation the REST
84
+ * parser does, which would otherwise have admitted `["constructor", x]`.
85
+ */
86
+ var REST_OP_LOOKUP = new Map(Object.entries(REST_TO_CANONICAL));
87
+ /**
56
88
  * Resolve any operator string (canonical or REST short-code) to its
57
89
  * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.
58
90
  *
@@ -64,7 +96,7 @@ var CANONICAL_OPS = new Set(ALL_WHERE_FILTER_OPS);
64
96
  */
65
97
  function toCanonicalOp(op) {
66
98
  if (CANONICAL_OPS.has(op)) return op;
67
- return REST_TO_CANONICAL[op];
99
+ return REST_OP_LOOKUP.get(op);
68
100
  }
69
101
  //#endregion
70
102
  //#region ../types/src/types/data_source.ts
@@ -320,6 +352,6 @@ function usesLegacyRlsFunctions(sql) {
320
352
  return /\bauth\.(uid|jwt|roles)\s*\(\s*\)/i.test(sql);
321
353
  }
322
354
  //#endregion
323
- export { rewriteLegacyRlsFunctions as a, isPostgresCollectionConfig as c, getDataSourceCapabilities as d, NULL_OPS as f, RLS_UID_SQL as i, isRelationalCollectionConfig as l, toCanonicalOp as m, REBASE_SCHEMA as n, usesLegacyRlsFunctions as o, REST_TO_CANONICAL as p, RLS_ROLES_SQL as r, getDeclaredSubcollections as s, LEGACY_RLS_SCHEMA as t, DEFAULT_DATA_SOURCE_KEY as u };
355
+ export { rewriteLegacyRlsFunctions as a, isPostgresCollectionConfig as c, getDataSourceCapabilities as d, ALL_WHERE_FILTER_OPS as f, toCanonicalOp as g, REST_TO_CANONICAL as h, RLS_UID_SQL as i, isRelationalCollectionConfig as l, NULL_OPS as m, REBASE_SCHEMA as n, usesLegacyRlsFunctions as o, CANONICAL_TO_REST as p, RLS_ROLES_SQL as r, getDeclaredSubcollections as s, LEGACY_RLS_SCHEMA as t, DEFAULT_DATA_SOURCE_KEY as u };
324
356
 
325
- //# sourceMappingURL=src-C_wvdMnl.js.map
357
+ //# sourceMappingURL=src-DCdn3Val.js.map