@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.
- package/dist/PostgresBootstrapper.d.ts +26 -0
- package/dist/auth/services.d.ts +21 -0
- package/dist/{auth-users-columns-Do9mw5Y5.js → auth-users-columns-BxT6FRyu.js} +819 -68
- package/dist/auth-users-columns-BxT6FRyu.js.map +1 -0
- package/dist/{backup-service-Bww-Lg0s.js → backup-service-BH0Dzo_h.js} +2 -3
- package/dist/{backup-service-Bww-Lg0s.js.map → backup-service-BH0Dzo_h.js.map} +1 -1
- package/dist/cli-helpers.d.ts +56 -0
- package/dist/cli-output.d.ts +34 -0
- package/dist/data-transformer.d.ts +7 -2
- package/dist/data_driver-ULAyJEi9.js +193 -0
- package/dist/data_driver-ULAyJEi9.js.map +1 -0
- package/dist/ensure-collection-policies-CP5_YttS.js +124 -0
- package/dist/ensure-collection-policies-CP5_YttS.js.map +1 -0
- package/dist/{ensure-collection-tables-DSIxvLLD.js → ensure-collection-tables-DWVISfcC.js} +119 -13
- package/dist/ensure-collection-tables-DWVISfcC.js.map +1 -0
- package/dist/index.es.js +998 -600
- package/dist/index.es.js.map +1 -1
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js → rls-bootstrap-sql-69hYT8nr.js} +2 -2
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js.map → rls-bootstrap-sql-69hYT8nr.js.map} +1 -1
- package/dist/rls-enforcement-Ct9ab42o.js +425 -0
- package/dist/rls-enforcement-Ct9ab42o.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +102 -0
- package/dist/schema/doctor-policy-checks.d.ts +28 -0
- package/dist/schema/doctor.d.ts +41 -25
- package/dist/schema/ensure-collection-policies.d.ts +33 -9
- package/dist/schema/ensure-collection-tables.d.ts +60 -6
- package/dist/schema/generate-drizzle-schema-logic.d.ts +9 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +48 -0
- package/dist/schema/search-column.d.ts +248 -0
- package/dist/security/rls-enforcement.d.ts +8 -3
- package/dist/services/FetchService.d.ts +24 -0
- package/dist/services/RelationService.d.ts +30 -0
- package/dist/services/collection-helpers.d.ts +26 -0
- package/dist/services/dataService.d.ts +3 -0
- package/dist/services/realtimeService.d.ts +139 -2
- package/dist/{src-C_wvdMnl.js → src-DCdn3Val.js} +35 -3
- package/dist/src-DCdn3Val.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +124 -2
- package/dist/{websocket-D0TBU3ia.js → websocket-C8ZqVBiV.js} +75 -18
- package/dist/websocket-C8ZqVBiV.js.map +1 -0
- package/package.json +6 -6
- package/src/PostgresBackendDriver.ts +7 -3
- package/src/PostgresBootstrapper.ts +95 -9
- package/src/auth/ensure-tables.ts +27 -5
- package/src/auth/services.ts +82 -5
- package/src/backup/backup-cli.ts +59 -57
- package/src/cli-errors.ts +6 -6
- package/src/cli-helpers.ts +110 -4
- package/src/cli-output.ts +43 -0
- package/src/cli.ts +210 -145
- package/src/collections/buildRegistry.ts +3 -1
- package/src/data-transformer.ts +107 -14
- package/src/history/ensure-history-table.ts +2 -2
- package/src/schema/auth-schema.ts +17 -1
- package/src/schema/doctor-cli.ts +14 -65
- package/src/schema/doctor-policy-checks.ts +105 -0
- package/src/schema/doctor.ts +149 -72
- package/src/schema/ensure-collection-policies.ts +99 -6
- package/src/schema/ensure-collection-tables.ts +286 -13
- package/src/schema/generate-drizzle-schema-logic.ts +126 -42
- package/src/schema/generate-drizzle-schema.ts +11 -10
- package/src/schema/generate-postgres-ddl-logic.ts +204 -10
- package/src/schema/generate-postgres-ddl.ts +38 -14
- package/src/schema/introspect-db-logic.ts +65 -33
- package/src/schema/introspect-db.ts +24 -24
- package/src/schema/search-column.ts +643 -0
- package/src/security/rls-enforcement.ts +9 -4
- package/src/services/FetchService.ts +229 -15
- package/src/services/PersistService.ts +24 -1
- package/src/services/RelationService.ts +119 -69
- package/src/services/cdc/trigger-cdc.ts +5 -1
- package/src/services/channel-history.ts +9 -3
- package/src/services/channel-presence.ts +10 -3
- package/src/services/collection-helpers.ts +54 -1
- package/src/services/dataService.ts +3 -0
- package/src/services/pg-notify-listener.ts +1 -1
- package/src/services/realtimeService.ts +347 -86
- package/src/utils/drizzle-conditions.ts +365 -23
- package/src/utils/pg-error-utils.ts +8 -3
- package/src/websocket.ts +113 -16
- package/dist/auth-users-columns-Do9mw5Y5.js.map +0 -1
- package/dist/ensure-collection-policies-DMUdRQdM.js +0 -57
- package/dist/ensure-collection-policies-DMUdRQdM.js.map +0 -1
- package/dist/ensure-collection-tables-DSIxvLLD.js.map +0 -1
- package/dist/policy-CPkCqVTz.js +0 -105
- package/dist/policy-CPkCqVTz.js.map +0 -1
- package/dist/src-C_wvdMnl.js.map +0 -1
- package/dist/websocket-D0TBU3ia.js.map +0 -1
|
@@ -34,7 +34,9 @@ export function buildCollectionRegistry(schema: RegistrySchema): PostgresCollect
|
|
|
34
34
|
|
|
35
35
|
if (schema.collections) {
|
|
36
36
|
registry.registerMultiple(schema.collections);
|
|
37
|
-
|
|
37
|
+
// `Auto-discovered collections` already reports the count and the
|
|
38
|
+
// directory they came from; this is the same fact with the names.
|
|
39
|
+
logger.debug(
|
|
38
40
|
`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: ` +
|
|
39
41
|
`[${registry.getCollections().map(c => c.slug).join(", ")}]`
|
|
40
42
|
);
|
package/src/data-transformer.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { isPrototypePollutingKey } from "@rebasepro/utils";
|
|
|
7
7
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
8
8
|
import { DrizzleConditionBuilder } from "./utils/drizzle-conditions";
|
|
9
9
|
import { getPrimaryKeys, buildCompositeId } from "./services/collection-helpers";
|
|
10
|
-
import { logger } from "@rebasepro/server";
|
|
10
|
+
import { ApiError, logger } from "@rebasepro/server";
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Data transformation utilities for converting between frontend and database formats.
|
|
@@ -136,6 +136,17 @@ joinPathRelationUpdates: [] };
|
|
|
136
136
|
// Same reasoning as `sanitizeAndConvertDates`: these keys come from the
|
|
137
137
|
// request body, and no column answers to them.
|
|
138
138
|
if (isPrototypePollutingKey(key)) continue;
|
|
139
|
+
|
|
140
|
+
// `{ subtitle: undefined }` means "I have no value for this", not "set
|
|
141
|
+
// this column to NULL" — it is what spreading an optional field
|
|
142
|
+
// produces, and what Drizzle itself skips. The key used to survive with
|
|
143
|
+
// `undefined` and `sanitizeAndConvertDates` then turned it into `null`,
|
|
144
|
+
// so `update(id, { title, subtitle: payload.subtitle })` wiped
|
|
145
|
+
// `subtitle` whenever the payload happened not to carry one. Unreachable
|
|
146
|
+
// over HTTP (JSON has no `undefined`); the in-process data API passes
|
|
147
|
+
// the caller's object straight through, so it is reachable there.
|
|
148
|
+
if (value === undefined) continue;
|
|
149
|
+
|
|
139
150
|
const property = properties[key as keyof M] as Property;
|
|
140
151
|
|
|
141
152
|
// Coerce empty strings to null for any field that acts as a foreign key
|
|
@@ -153,7 +164,7 @@ joinPathRelationUpdates: [] };
|
|
|
153
164
|
if (relation) {
|
|
154
165
|
if (relation.kind === "belongsTo") {
|
|
155
166
|
// Owning relation: Map relation object to FK column on current table
|
|
156
|
-
const serializedValue = serializePropertyToServer(effectiveValue, property);
|
|
167
|
+
const serializedValue = serializePropertyToServer(effectiveValue, property, key);
|
|
157
168
|
if (serializedValue !== undefined) {
|
|
158
169
|
result[relation.localKey] = serializedValue;
|
|
159
170
|
}
|
|
@@ -161,7 +172,7 @@ joinPathRelationUpdates: [] };
|
|
|
161
172
|
continue;
|
|
162
173
|
} else if (hasForeignKeyOnTarget(relation)) {
|
|
163
174
|
// Inverse relation: Need to update the target table's FK
|
|
164
|
-
const serializedValue = serializePropertyToServer(effectiveValue, property);
|
|
175
|
+
const serializedValue = serializePropertyToServer(effectiveValue, property, key);
|
|
165
176
|
inverseRelationUpdates.push({
|
|
166
177
|
relationKey: key,
|
|
167
178
|
relation,
|
|
@@ -175,7 +186,7 @@ joinPathRelationUpdates: [] };
|
|
|
175
186
|
// There used to be two arms here — "owning" and "inverse"
|
|
176
187
|
// joinPath — but a join chain has no owning side, so they
|
|
177
188
|
// only ever differed by which list they pushed to.
|
|
178
|
-
const serializedValue = serializePropertyToServer(effectiveValue, property);
|
|
189
|
+
const serializedValue = serializePropertyToServer(effectiveValue, property, key);
|
|
179
190
|
if (relation.cardinality === "one") {
|
|
180
191
|
// Ordering matters: PersistService applies these BEFORE
|
|
181
192
|
// the main UPDATE, so the mapping reads the pre-update
|
|
@@ -197,7 +208,7 @@ joinPathRelationUpdates: [] };
|
|
|
197
208
|
}
|
|
198
209
|
}
|
|
199
210
|
|
|
200
|
-
result[key] = serializePropertyToServer(effectiveValue, property);
|
|
211
|
+
result[key] = serializePropertyToServer(effectiveValue, property, key);
|
|
201
212
|
}
|
|
202
213
|
|
|
203
214
|
return {
|
|
@@ -208,19 +219,41 @@ joinPathRelationUpdates: [] };
|
|
|
208
219
|
}
|
|
209
220
|
|
|
210
221
|
/**
|
|
211
|
-
*
|
|
222
|
+
* How to name a rejected value in an error, without quoting it back.
|
|
223
|
+
*
|
|
224
|
+
* The value may be anything the caller sent, including a secret in the wrong
|
|
225
|
+
* field, so the message describes its shape rather than echoing it — an echoed
|
|
226
|
+
* value ends up in logs and in error-reporting services.
|
|
212
227
|
*/
|
|
213
|
-
|
|
228
|
+
function describeValue(value: unknown): string {
|
|
229
|
+
if (value === null) return "null";
|
|
230
|
+
if (Array.isArray(value)) return "an array";
|
|
231
|
+
if (value instanceof Date) return "a date";
|
|
232
|
+
const type = typeof value;
|
|
233
|
+
return type === "object" ? "an object" : `a ${type}`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Serialize a single property value for database storage.
|
|
238
|
+
*
|
|
239
|
+
* `propertyKey` is only ever used to phrase errors and warnings. Without it the
|
|
240
|
+
* one trace a bad value left was `Expected array value for array property, got
|
|
241
|
+
* string` — no collection, no property, no value, which in the log of a
|
|
242
|
+
* thousand-row import names nothing at all.
|
|
243
|
+
*/
|
|
244
|
+
export function serializePropertyToServer(value: unknown, property: Property, propertyKey?: string): unknown {
|
|
214
245
|
if (value === null || value === undefined) {
|
|
215
246
|
return value;
|
|
216
247
|
}
|
|
217
248
|
|
|
249
|
+
const fieldLabel = propertyKey ? `'${propertyKey}'` : `a '${property.type}' field`;
|
|
250
|
+
|
|
218
251
|
const propertyType = property.type;
|
|
219
252
|
|
|
220
253
|
switch (propertyType) {
|
|
221
254
|
case "relation":
|
|
222
255
|
if (Array.isArray(value)) {
|
|
223
|
-
return value.map(v => serializePropertyToServer(v, property));
|
|
256
|
+
return value.map(v => serializePropertyToServer(v, property, propertyKey));
|
|
224
257
|
} else if (typeof value === "object" && value !== null && "id" in value) {
|
|
225
258
|
return (value as Record<string, unknown>).id;
|
|
226
259
|
}
|
|
@@ -230,7 +263,7 @@ export function serializePropertyToServer(value: unknown, property: Property): u
|
|
|
230
263
|
case "array":
|
|
231
264
|
if (Array.isArray(value)) {
|
|
232
265
|
if (property.of) {
|
|
233
|
-
return value.map(item => serializePropertyToServer(item, property.of as Property));
|
|
266
|
+
return value.map(item => serializePropertyToServer(item, property.of as Property, propertyKey));
|
|
234
267
|
} else if (property.oneOf) {
|
|
235
268
|
const typeField = property.oneOf.typeField ?? DEFAULT_ONE_OF_TYPE;
|
|
236
269
|
const valueField = property.oneOf.valueField ?? DEFAULT_ONE_OF_VALUE;
|
|
@@ -243,15 +276,50 @@ export function serializePropertyToServer(value: unknown, property: Property): u
|
|
|
243
276
|
if (!type || !childProperty) return e;
|
|
244
277
|
return {
|
|
245
278
|
[typeField]: type,
|
|
246
|
-
[valueField]: serializePropertyToServer(rec[valueField], childProperty)
|
|
279
|
+
[valueField]: serializePropertyToServer(rec[valueField], childProperty, propertyKey)
|
|
247
280
|
};
|
|
248
281
|
});
|
|
249
282
|
}
|
|
250
283
|
return value;
|
|
251
284
|
}
|
|
252
|
-
//
|
|
253
|
-
|
|
254
|
-
|
|
285
|
+
// A non-array value used to become `[]` here — the caller's value
|
|
286
|
+
// destroyed, answered 200/201, and the row reading back as an empty
|
|
287
|
+
// list on every later fetch. `POST /posts {"tags":"news"}` from a
|
|
288
|
+
// client that sent a single tag as a scalar, or a CSV import that
|
|
289
|
+
// did not split a column, was unrecoverable data loss on a `text[]`
|
|
290
|
+
// column. The stated reason for coercing — "avoid .map() crashes
|
|
291
|
+
// downstream" — is better served by refusing the value at the
|
|
292
|
+
// boundary, which is what a 400 does.
|
|
293
|
+
//
|
|
294
|
+
// The read-side twin (`parsePropertyFromServer`) still coerces, and
|
|
295
|
+
// should: a row already in the database is not this caller's fault.
|
|
296
|
+
throw ApiError.badRequest(
|
|
297
|
+
`${fieldLabel} expects an array, but received ${describeValue(value)}.`,
|
|
298
|
+
"VALIDATION_INVALID_VALUE"
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
case "geopoint": {
|
|
302
|
+
// Stored as `jsonb`, in the `{ latitude, longitude }` shape the
|
|
303
|
+
// OpenAPI schema and the generated TS type both promise. Nothing
|
|
304
|
+
// used to handle `geopoint` on either side, which is why the type
|
|
305
|
+
// was documented, code-generated, admin-editable — and dropped.
|
|
306
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
307
|
+
throw ApiError.badRequest(
|
|
308
|
+
`${fieldLabel} expects a geopoint object with \`latitude\` and \`longitude\`, ` +
|
|
309
|
+
`but received ${describeValue(value)}.`,
|
|
310
|
+
"VALIDATION_INVALID_VALUE"
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
const point = value as Record<string, unknown>;
|
|
314
|
+
if (typeof point.latitude !== "number" || typeof point.longitude !== "number") {
|
|
315
|
+
throw ApiError.badRequest(
|
|
316
|
+
`${fieldLabel} expects a geopoint object with numeric \`latitude\` and \`longitude\`.`,
|
|
317
|
+
"VALIDATION_INVALID_VALUE"
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
return { latitude: point.latitude,
|
|
321
|
+
longitude: point.longitude };
|
|
322
|
+
}
|
|
255
323
|
|
|
256
324
|
|
|
257
325
|
case "map":
|
|
@@ -260,7 +328,7 @@ export function serializePropertyToServer(value: unknown, property: Property): u
|
|
|
260
328
|
for (const [subKey, subValue] of Object.entries(value)) {
|
|
261
329
|
const subProperty = (property.properties as Properties)[subKey];
|
|
262
330
|
if (subProperty) {
|
|
263
|
-
result[subKey] = serializePropertyToServer(subValue, subProperty);
|
|
331
|
+
result[subKey] = serializePropertyToServer(subValue, subProperty, propertyKey ? `${propertyKey}.${subKey}` : subKey);
|
|
264
332
|
} else {
|
|
265
333
|
result[subKey] = subValue;
|
|
266
334
|
}
|
|
@@ -626,6 +694,13 @@ export function parsePropertyFromServer(value: unknown, property: Property, coll
|
|
|
626
694
|
}
|
|
627
695
|
return value;
|
|
628
696
|
|
|
697
|
+
case "geopoint":
|
|
698
|
+
// A `jsonb` column, so node-postgres hands back the object already.
|
|
699
|
+
// Named explicitly rather than left to `default:`, which would run
|
|
700
|
+
// it past the Buffer probe — and because a type with a write
|
|
701
|
+
// serializer and no read counterpart is how this one went missing.
|
|
702
|
+
return value;
|
|
703
|
+
|
|
629
704
|
case "vector": {
|
|
630
705
|
let nums: number[] = [];
|
|
631
706
|
if (typeof value === "string") {
|
|
@@ -685,6 +760,15 @@ export function parsePropertyFromServer(value: unknown, property: Property, coll
|
|
|
685
760
|
* from the result (used by `normalizeDbValues` where
|
|
686
761
|
* Drizzle's relational API already hydrates them).
|
|
687
762
|
*/
|
|
763
|
+
/**
|
|
764
|
+
* Keys a query computes and attaches to a row, rather than reads from a column.
|
|
765
|
+
*
|
|
766
|
+
* An explicit set rather than a `_` prefix rule: a user's column may perfectly
|
|
767
|
+
* well be called `_internal`, and passing it through here would put a value on
|
|
768
|
+
* the row that no property describes and nothing downstream knows how to type.
|
|
769
|
+
*/
|
|
770
|
+
const QUERY_METADATA_KEYS = new Set(["_score", "_distance", "_matches"]);
|
|
771
|
+
|
|
688
772
|
function normalizeScalarValues<M extends Record<string, unknown>>(
|
|
689
773
|
data: M,
|
|
690
774
|
properties: Properties,
|
|
@@ -709,6 +793,15 @@ function normalizeScalarValues<M extends Record<string, unknown>>(
|
|
|
709
793
|
continue;
|
|
710
794
|
}
|
|
711
795
|
|
|
796
|
+
// Query-computed metadata, which by definition is not a column and so
|
|
797
|
+
// has no property to be found. Dropped here until now — which meant
|
|
798
|
+
// `_distance` was computed for every vector search on this path and
|
|
799
|
+
// then discarded before the caller ever saw it.
|
|
800
|
+
if (QUERY_METADATA_KEYS.has(key)) {
|
|
801
|
+
result[key] = value;
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
|
|
712
805
|
const property = properties[key as keyof M] as Property;
|
|
713
806
|
if (!property) continue; // Skip DB columns not defined in properties
|
|
714
807
|
|
|
@@ -9,7 +9,7 @@ import { revokeInternalTableSql } from "@rebasepro/common";
|
|
|
9
9
|
* pattern as `ensureAuthTablesExist`.
|
|
10
10
|
*/
|
|
11
11
|
export async function ensureHistoryTableExists(db: NodePgDatabase): Promise<void> {
|
|
12
|
-
logger.
|
|
12
|
+
logger.debug("🔍 Checking row history table...");
|
|
13
13
|
|
|
14
14
|
try {
|
|
15
15
|
// Create the rebase schema (idempotent — may already exist from auth init)
|
|
@@ -45,7 +45,7 @@ export async function ensureHistoryTableExists(db: NodePgDatabase): Promise<void
|
|
|
45
45
|
// (created here, after that grant ran), so take it back.
|
|
46
46
|
await db.execute(sql.raw(revokeInternalTableSql("rebase", "entity_history")));
|
|
47
47
|
|
|
48
|
-
logger.
|
|
48
|
+
logger.debug("✅ Entity history table ready");
|
|
49
49
|
} catch (error) {
|
|
50
50
|
logger.error("❌ Failed to create row history table", { error: error });
|
|
51
51
|
logger.warn("⚠️ Continuing without creating history table.");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { pgSchema, pgTable, uuid, timestamp, boolean, jsonb, text, unique, index } from "drizzle-orm/pg-core";
|
|
1
|
+
import { pgSchema, pgTable, uuid, timestamp, boolean, jsonb, text, unique, index, integer, bigint } from "drizzle-orm/pg-core";
|
|
2
2
|
import { relations } from "drizzle-orm";
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -87,6 +87,13 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
87
87
|
* that rotates immediately after it.
|
|
88
88
|
*/
|
|
89
89
|
sessionStartedAt: timestamp("session_started_at").defaultNow().notNull(),
|
|
90
|
+
/**
|
|
91
|
+
* The assurance level the sign-in was established at — `aal2` only
|
|
92
|
+
* where a second factor was actually presented. Carried across
|
|
93
|
+
* rotations, because refresh is not a new authentication and has
|
|
94
|
+
* nothing else to read the level from.
|
|
95
|
+
*/
|
|
96
|
+
aal: text("aal"),
|
|
90
97
|
userAgent: text("user_agent"),
|
|
91
98
|
ipAddress: text("ip_address"),
|
|
92
99
|
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
@@ -140,6 +147,13 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
140
147
|
secretEncrypted: text("secret_encrypted").notNull(),
|
|
141
148
|
friendlyName: text("friendly_name"),
|
|
142
149
|
verified: boolean("verified").default(false).notNull(),
|
|
150
|
+
/**
|
|
151
|
+
* The highest TOTP time step ever accepted for this factor. RFC 6238
|
|
152
|
+
* §5.2 forbids accepting an OTP twice, and the ±1 step window that
|
|
153
|
+
* exists for clock drift is also a 90-second replay window: without
|
|
154
|
+
* this, one observed code buys a fresh session for a minute and a half.
|
|
155
|
+
*/
|
|
156
|
+
lastUsedCounter: bigint("last_used_counter", { mode: "number" }),
|
|
143
157
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
144
158
|
updatedAt: timestamp("updated_at").defaultNow().notNull()
|
|
145
159
|
});
|
|
@@ -153,6 +167,8 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
153
167
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
154
168
|
verifiedAt: timestamp("verified_at"),
|
|
155
169
|
ipAddress: text("ip_address"),
|
|
170
|
+
/** Failed guesses recorded against this challenge; bounded by the route. */
|
|
171
|
+
attempts: integer("attempts").default(0).notNull(),
|
|
156
172
|
expiresAt: timestamp("expires_at").notNull()
|
|
157
173
|
});
|
|
158
174
|
|
package/src/schema/doctor-cli.ts
CHANGED
|
@@ -5,62 +5,8 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import path from "path";
|
|
7
7
|
import chalk from "chalk";
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import { checkPolicyDrift, formatPolicyDrift, hasDrift } from "../security/policy-drift";
|
|
11
|
-
import { validatePolicyPgRoles, warnOnAnonymousGrants } from "../security/rls-enforcement";
|
|
12
|
-
import { logger } from "@rebasepro/server";
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* The RLS half of the doctor: policies actually deployed vs the ones the
|
|
16
|
-
* collections describe, plus policy roles this server could never satisfy.
|
|
17
|
-
*
|
|
18
|
-
* Returns true when something is wrong, so callers can set the exit code.
|
|
19
|
-
*/
|
|
20
|
-
async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<boolean> {
|
|
21
|
-
if (!databaseUrl) {
|
|
22
|
-
logger.warn(chalk.yellow(" ⚠ No DATABASE_URL — skipping RLS policy checks"));
|
|
23
|
-
return false;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
let problems = false;
|
|
27
|
-
const { Pool } = await import("pg");
|
|
28
|
-
const pool = new Pool({ connectionString: databaseUrl });
|
|
29
|
-
try {
|
|
30
|
-
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
31
|
-
const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];
|
|
32
|
-
|
|
33
|
-
// A policy naming a role the server never runs as filters every row, so
|
|
34
|
-
// the collection reads as empty. Report it without booting a server.
|
|
35
|
-
try {
|
|
36
|
-
await validatePolicyPgRoles(runSql, collections as never);
|
|
37
|
-
logger.info(chalk.green(" ✓ Policy roles are usable by this server"));
|
|
38
|
-
} catch (err) {
|
|
39
|
-
problems = true;
|
|
40
|
-
logger.info("");
|
|
41
|
-
logger.error(chalk.red(err instanceof Error ? err.message : String(err)));
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// A rule that reads as a lockdown but is true for every caller compiles
|
|
45
|
-
// to a grant. Report it without booting a server.
|
|
46
|
-
warnOnAnonymousGrants(collections as never);
|
|
47
|
-
|
|
48
|
-
const drift = await checkPolicyDrift(pool as never, collections);
|
|
49
|
-
logger.info("");
|
|
50
|
-
if (hasDrift(drift)) {
|
|
51
|
-
problems = true;
|
|
52
|
-
logger.info(chalk.yellow(" RLS policies: database does not match your collections"));
|
|
53
|
-
logger.info(formatPolicyDrift(drift));
|
|
54
|
-
} else {
|
|
55
|
-
logger.info(chalk.green(" ✓ RLS policies match your collections"));
|
|
56
|
-
}
|
|
57
|
-
} catch (err) {
|
|
58
|
-
logger.warn(chalk.yellow(" ⚠ Could not check RLS policies"), { error: err });
|
|
59
|
-
} finally {
|
|
60
|
-
await pool.end();
|
|
61
|
-
}
|
|
62
|
-
return problems;
|
|
63
|
-
}
|
|
8
|
+
import { runDoctor } from "./doctor";
|
|
9
|
+
import { exitCodeForPolicyGate, runPolicyChecks } from "./doctor-policy-checks";
|
|
64
10
|
|
|
65
11
|
async function main() {
|
|
66
12
|
const collectionsArg = process.argv.find((a) => a.startsWith("--collections="));
|
|
@@ -80,9 +26,9 @@ async function main() {
|
|
|
80
26
|
const dotenv = await import("dotenv");
|
|
81
27
|
const envPath = process.env.DOTENV_CONFIG_PATH;
|
|
82
28
|
if (envPath) {
|
|
83
|
-
dotenv.config({ path: envPath });
|
|
29
|
+
dotenv.config({ path: envPath, quiet: true });
|
|
84
30
|
} else {
|
|
85
|
-
dotenv.config();
|
|
31
|
+
dotenv.config({ quiet: true });
|
|
86
32
|
}
|
|
87
33
|
} catch {
|
|
88
34
|
// dotenv may not be installed
|
|
@@ -91,9 +37,9 @@ async function main() {
|
|
|
91
37
|
const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
|
|
92
38
|
|
|
93
39
|
if (policiesOnly) {
|
|
94
|
-
// Non-zero so this can gate CI — the whole point of the flag
|
|
95
|
-
|
|
96
|
-
|
|
40
|
+
// Non-zero so this can gate CI — the whole point of the flag, and a
|
|
41
|
+
// check that could not run has not passed. See exitCodeForPolicyGate.
|
|
42
|
+
process.exit(exitCodeForPolicyGate(await runPolicyChecks(collectionsPath, databaseUrl)));
|
|
97
43
|
}
|
|
98
44
|
|
|
99
45
|
const report = await runDoctor({
|
|
@@ -103,15 +49,18 @@ async function main() {
|
|
|
103
49
|
databaseUrl: databaseUrl ?? undefined
|
|
104
50
|
});
|
|
105
51
|
|
|
106
|
-
const
|
|
52
|
+
const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);
|
|
107
53
|
|
|
108
|
-
// Exit
|
|
109
|
-
|
|
54
|
+
// Exit non-zero if there are errors. A policy run that could not happen is
|
|
55
|
+
// reported loudly above but does not fail the interactive command — the
|
|
56
|
+
// same treatment the skipped database phase gets. `--policies` is the gate,
|
|
57
|
+
// and that one fails closed.
|
|
58
|
+
if (report.summary.errors > 0 || policyStatus === "problems") {
|
|
110
59
|
process.exit(1);
|
|
111
60
|
}
|
|
112
61
|
}
|
|
113
62
|
|
|
114
63
|
main().catch((err) => {
|
|
115
|
-
|
|
64
|
+
console.error(chalk.red(" ✗ Doctor failed"), err instanceof Error ? (err.stack ?? err.message) : String(err));
|
|
116
65
|
process.exit(1);
|
|
117
66
|
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.
|
|
3
|
+
*
|
|
4
|
+
* Lives beside `doctor-cli.ts` rather than inside it because that file runs
|
|
5
|
+
* `main()` on import: a gate whose failure modes cannot be unit-tested is how
|
|
6
|
+
* this one shipped reporting success for work it never did.
|
|
7
|
+
*/
|
|
8
|
+
import path from "path";
|
|
9
|
+
import chalk from "chalk";
|
|
10
|
+
import { CollectionConfig } from "@rebasepro/types";
|
|
11
|
+
import { loadCollections } from "./doctor";
|
|
12
|
+
import { checkPolicyDrift, formatPolicyDrift, hasDrift } from "../security/policy-drift";
|
|
13
|
+
import { validatePolicyPgRoles, warnOnAnonymousGrants } from "../security/rls-enforcement";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What the RLS checks concluded.
|
|
17
|
+
*
|
|
18
|
+
* `unchecked` exists because "we could not look" and "we looked and it is fine"
|
|
19
|
+
* used to be reported identically: a collections path that did not resolve made
|
|
20
|
+
* the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`
|
|
21
|
+
* early-returned an empty diff, and the gate printed
|
|
22
|
+
* `✓ RLS policies match your collections` having compared zero policies against
|
|
23
|
+
* zero collections. Any exception at all — a collection file that throws on
|
|
24
|
+
* import, a `pg_policies` read the CI role is not granted, a connection reset —
|
|
25
|
+
* did the same thing through a `warn`, and exited 0.
|
|
26
|
+
*/
|
|
27
|
+
export type PolicyCheckStatus = "ok" | "problems" | "unchecked";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The exit code for `rebase doctor --policies`.
|
|
31
|
+
*
|
|
32
|
+
* A gate that could not run has not passed. Only a completed, clean check
|
|
33
|
+
* exits 0 — anything else, including "we never opened a connection", is a
|
|
34
|
+
* failure, or the flag certifies a database nobody looked at.
|
|
35
|
+
*/
|
|
36
|
+
export function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {
|
|
37
|
+
return status === "ok" ? 0 : 1;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Policies actually deployed vs the ones the collections describe, plus policy
|
|
42
|
+
* roles this server could never satisfy.
|
|
43
|
+
*
|
|
44
|
+
* Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.
|
|
45
|
+
*/
|
|
46
|
+
export async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {
|
|
47
|
+
if (!databaseUrl) {
|
|
48
|
+
console.error(chalk.yellow(" ⚠ No DATABASE_URL — RLS policies were NOT checked"));
|
|
49
|
+
return "unchecked";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const resolvedPath = path.resolve(process.cwd(), collectionsPath);
|
|
53
|
+
let problems = false;
|
|
54
|
+
const { Pool } = await import("pg");
|
|
55
|
+
const pool = new Pool({ connectionString: databaseUrl });
|
|
56
|
+
try {
|
|
57
|
+
const collections: CollectionConfig[] = await loadCollections(resolvedPath);
|
|
58
|
+
|
|
59
|
+
// Zero collections is not "no drift", it is nothing to compare. The
|
|
60
|
+
// loader returns `[]` for a path that does not exist, so the commonest
|
|
61
|
+
// way to get here is a `--collections` path resolved against the wrong
|
|
62
|
+
// directory — which used to render as a green tick.
|
|
63
|
+
if (collections.length === 0) {
|
|
64
|
+
console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));
|
|
65
|
+
console.error(chalk.gray(" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere."));
|
|
66
|
+
return "unchecked";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];
|
|
70
|
+
|
|
71
|
+
// A policy naming a role the server never runs as filters every row, so
|
|
72
|
+
// the collection reads as empty. Report it without booting a server.
|
|
73
|
+
try {
|
|
74
|
+
await validatePolicyPgRoles(runSql, collections as never);
|
|
75
|
+
console.log(chalk.green(" ✓ Policy roles are usable by this server"));
|
|
76
|
+
} catch (err) {
|
|
77
|
+
problems = true;
|
|
78
|
+
console.log("");
|
|
79
|
+
console.error(chalk.red(err instanceof Error ? err.message : String(err)));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// A rule that reads as a lockdown but is true for every caller compiles
|
|
83
|
+
// to a grant. Report it without booting a server.
|
|
84
|
+
warnOnAnonymousGrants(collections as never);
|
|
85
|
+
|
|
86
|
+
const drift = await checkPolicyDrift(pool as never, collections);
|
|
87
|
+
console.log("");
|
|
88
|
+
if (hasDrift(drift)) {
|
|
89
|
+
problems = true;
|
|
90
|
+
console.log(chalk.yellow(" RLS policies: database does not match your collections"));
|
|
91
|
+
console.log(formatPolicyDrift(drift));
|
|
92
|
+
} else {
|
|
93
|
+
console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));
|
|
94
|
+
}
|
|
95
|
+
} catch (err) {
|
|
96
|
+
// Fail closed. This catch covers every query and every collection import
|
|
97
|
+
// above, so returning the pre-catch verdict made the documented CI gate
|
|
98
|
+
// green on exactly the runs it exists to catch.
|
|
99
|
+
console.error(chalk.red(" ✗ Could not check RLS policies:"), err instanceof Error ? err.message : String(err));
|
|
100
|
+
return "unchecked";
|
|
101
|
+
} finally {
|
|
102
|
+
await pool.end();
|
|
103
|
+
}
|
|
104
|
+
return problems ? "problems" : "ok";
|
|
105
|
+
}
|