@rebasepro/server-postgres 0.9.1-canary.a57c262 → 0.9.1-canary.a639738
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 +10 -0
- package/dist/auth/services.d.ts +16 -0
- package/dist/connection.d.ts +21 -0
- package/dist/index.es.js +208 -37
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/security/policy-drift.d.ts +30 -0
- package/dist/services/row-pipeline.d.ts +5 -2
- package/package.json +7 -6
- package/src/PostgresBackendDriver.ts +18 -5
- package/src/PostgresBootstrapper.ts +51 -2
- package/src/auth/ensure-tables.ts +73 -11
- package/src/auth/services.ts +49 -19
- package/src/cli.ts +60 -0
- package/src/connection.ts +61 -1
- package/src/databasePoolManager.ts +2 -0
- package/src/schema/doctor.ts +45 -20
- package/src/schema/introspect-db.ts +11 -1
- package/src/security/policy-drift.test.ts +106 -1
- package/src/security/policy-drift.ts +56 -0
- package/src/services/PersistService.ts +9 -2
- package/src/services/row-pipeline.ts +70 -7
- package/src/utils/drizzle-conditions.ts +13 -0
|
@@ -2,6 +2,7 @@ import { Pool } from "pg";
|
|
|
2
2
|
import { drizzle } from "drizzle-orm/node-postgres";
|
|
3
3
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
4
4
|
import { logger } from "@rebasepro/server";
|
|
5
|
+
import { guardPoolAgainstDirtyRelease } from "./connection";
|
|
5
6
|
|
|
6
7
|
export class DatabasePoolManager {
|
|
7
8
|
private pools: Map<string, Pool> = new Map();
|
|
@@ -50,6 +51,7 @@ export class DatabasePoolManager {
|
|
|
50
51
|
pool.on("error", (err) => {
|
|
51
52
|
logger.error(`[DatabasePoolManager] Unexpected error on idle client for db ${databaseName}`, { error: err });
|
|
52
53
|
});
|
|
54
|
+
guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);
|
|
53
55
|
|
|
54
56
|
this.pools.set(databaseName, pool);
|
|
55
57
|
return pool;
|
package/src/schema/doctor.ts
CHANGED
|
@@ -37,7 +37,7 @@ export type IssueSeverity = "error" | "warning" | "info";
|
|
|
37
37
|
|
|
38
38
|
export interface DoctorIssue {
|
|
39
39
|
severity: IssueSeverity;
|
|
40
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
|
|
40
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale" | "sdk_not_generated";
|
|
41
41
|
table?: string;
|
|
42
42
|
column?: string;
|
|
43
43
|
expected?: string;
|
|
@@ -61,19 +61,29 @@ export function getExpectedColumnType(prop: Property): string | null {
|
|
|
61
61
|
const sp = prop as StringProperty;
|
|
62
62
|
if (sp.enum) return "USER-DEFINED"; // pgEnum → USER-DEFINED in information_schema
|
|
63
63
|
if ("isId" in sp && sp.isId === "uuid") return "uuid";
|
|
64
|
-
if (sp.columnType === "
|
|
64
|
+
if (sp.columnType === "uuid") return "uuid";
|
|
65
|
+
// A markdown/multiline string compiles to `text`, not varchar — the
|
|
66
|
+
// generator treats those UI hints as column-type signals, so the
|
|
67
|
+
// expectation here must too or every such column reads as drift.
|
|
68
|
+
if (sp.columnType === "text" || sp.ui?.markdown || sp.ui?.multiline) return "text";
|
|
65
69
|
if (sp.columnType === "char") return "character";
|
|
66
70
|
return "character varying";
|
|
67
71
|
}
|
|
68
72
|
case "number": {
|
|
69
73
|
const np = prop as NumberProperty;
|
|
70
|
-
if (np.columnType
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
if (np.columnType) {
|
|
75
|
+
// The generator passes any columnType straight through to drizzle,
|
|
76
|
+
// so mirror that rather than enumerating a subset (which reported
|
|
77
|
+
// drift for anything unlisted, e.g. smallint). Serial types are
|
|
78
|
+
// integers with a sequence default; information_schema reports the
|
|
79
|
+
// underlying width.
|
|
80
|
+
const serialWidths: Record<string, string> = {
|
|
81
|
+
serial: "integer",
|
|
82
|
+
bigserial: "bigint",
|
|
83
|
+
smallserial: "smallint"
|
|
84
|
+
};
|
|
85
|
+
return serialWidths[np.columnType] ?? np.columnType;
|
|
86
|
+
}
|
|
77
87
|
if (np.validation?.integer || ("isId" in np && np.isId)) return "integer";
|
|
78
88
|
return "numeric";
|
|
79
89
|
}
|
|
@@ -201,15 +211,18 @@ export async function checkCollectionsVsSdk(
|
|
|
201
211
|
): Promise<{ passed: boolean; issues: DoctorIssue[] }> {
|
|
202
212
|
const issues: DoctorIssue[] = [];
|
|
203
213
|
|
|
204
|
-
//
|
|
214
|
+
// The typed SDK is opt-in — nothing in a scaffolded project imports it until
|
|
215
|
+
// you choose to. A project that never generated one isn't drifting, so report
|
|
216
|
+
// it as information rather than a warning; otherwise `doctor` can never come
|
|
217
|
+
// back clean on a fresh project and users learn to ignore its output.
|
|
205
218
|
if (!fs.existsSync(sdkFilePath)) {
|
|
206
219
|
issues.push({
|
|
207
|
-
severity: "
|
|
208
|
-
category: "
|
|
209
|
-
message:
|
|
210
|
-
fix: "Run `rebase generate-sdk`"
|
|
220
|
+
severity: "info",
|
|
221
|
+
category: "sdk_not_generated",
|
|
222
|
+
message: "Typed SDK not generated (optional).",
|
|
223
|
+
fix: "Run `rebase generate-sdk` if you want typed collection access"
|
|
211
224
|
});
|
|
212
|
-
return { passed:
|
|
225
|
+
return { passed: true,
|
|
213
226
|
issues };
|
|
214
227
|
}
|
|
215
228
|
|
|
@@ -631,11 +644,15 @@ export function renderReport(report: DoctorReport): void {
|
|
|
631
644
|
}
|
|
632
645
|
|
|
633
646
|
function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): void {
|
|
634
|
-
|
|
647
|
+
const errorCount = issues.filter((i) => i.severity === "error").length;
|
|
648
|
+
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
649
|
+
const infoIssues = issues.filter((i) => i.severity === "info");
|
|
650
|
+
|
|
651
|
+
// Informational notes don't make a phase unhealthy, so key the header off
|
|
652
|
+
// real problems rather than `passed` alone.
|
|
653
|
+
if (errorCount === 0 && warnCount === 0) {
|
|
635
654
|
logger.info(` ${chalk.green("✅")} ${label}: ${chalk.green("In sync")}`);
|
|
636
655
|
} else {
|
|
637
|
-
const errorCount = issues.filter((i) => i.severity === "error").length;
|
|
638
|
-
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
639
656
|
const parts: string[] = [];
|
|
640
657
|
if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? "s" : ""}`);
|
|
641
658
|
if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? "s" : ""}`);
|
|
@@ -643,7 +660,14 @@ function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): voi
|
|
|
643
660
|
}
|
|
644
661
|
logger.info("");
|
|
645
662
|
|
|
646
|
-
|
|
663
|
+
// Notes render as a quiet one-liner, not a full drift box.
|
|
664
|
+
for (const issue of infoIssues) {
|
|
665
|
+
const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : "";
|
|
666
|
+
logger.info(` ${chalk.gray("ℹ")} ${chalk.gray(issue.message)}${fixPart}`);
|
|
667
|
+
logger.info("");
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
for (const issue of issues.filter((i) => i.severity !== "info")) {
|
|
647
671
|
const severityIcon = issue.severity === "error" ? chalk.red("✗") : chalk.yellow("⚠");
|
|
648
672
|
const categoryLabel = formatCategory(issue.category);
|
|
649
673
|
logger.info(` ${chalk.gray("┌─")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray("─".repeat(Math.max(0, 42 - categoryLabel.length)))}`);
|
|
@@ -674,7 +698,8 @@ function formatCategory(cat: DoctorIssue["category"]): string {
|
|
|
674
698
|
missing_enum: "Missing Enum",
|
|
675
699
|
enum_value_mismatch: "Enum Value Mismatch",
|
|
676
700
|
missing_foreign_key: "Missing Foreign Key",
|
|
677
|
-
sdk_stale: "Stale SDK Types"
|
|
701
|
+
sdk_stale: "Stale SDK Types",
|
|
702
|
+
sdk_not_generated: "SDK Types Not Generated"
|
|
678
703
|
};
|
|
679
704
|
return labels[cat];
|
|
680
705
|
}
|
|
@@ -243,7 +243,17 @@ async function main() {
|
|
|
243
243
|
const merged = mergeIndexContent(existing, generatedFiles);
|
|
244
244
|
fs.writeFileSync(indexPath, merged, "utf-8");
|
|
245
245
|
} else {
|
|
246
|
-
|
|
246
|
+
// --force replaces collections derived from the database, but the
|
|
247
|
+
// directory can also hold hand-written ones with no table in the
|
|
248
|
+
// introspected schema (the auth users collection lives in
|
|
249
|
+
// "rebase"). The backend discovers the whole directory, so an
|
|
250
|
+
// index listing only introspected tables would silently drop them
|
|
251
|
+
// from the admin UI while the API still served them.
|
|
252
|
+
const siblings = fs.readdirSync(outDir)
|
|
253
|
+
.filter(f => f.endsWith(".ts") && f !== "index.ts")
|
|
254
|
+
.map(f => f.replace(/\.ts$/, ""));
|
|
255
|
+
const allFiles = [...new Set([...generatedFiles, ...siblings])];
|
|
256
|
+
const indexContent = generateIndexContent(allFiles);
|
|
247
257
|
fs.writeFileSync(indexPath, indexContent, "utf-8");
|
|
248
258
|
}
|
|
249
259
|
logger.info(chalk.green(` ✓ ${indexPath}`));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from "@jest/globals";
|
|
2
2
|
import type { CollectionConfig } from "@rebasepro/types";
|
|
3
3
|
|
|
4
|
-
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, type PolicyRef, type Queryable } from "./policy-drift";
|
|
4
|
+
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, dropOrphanedPolicies, isGeneratedPolicyName, type PolicyRef, type Queryable } from "./policy-drift";
|
|
5
5
|
import { generatePostgresPoliciesDdl } from "../schema/generate-postgres-ddl-logic";
|
|
6
6
|
|
|
7
7
|
function collection(slug: string): CollectionConfig {
|
|
@@ -154,3 +154,108 @@ describe("checkPolicyDrift", () => {
|
|
|
154
154
|
expect(drift.missing.length).toBeGreaterThan(0);
|
|
155
155
|
});
|
|
156
156
|
});
|
|
157
|
+
|
|
158
|
+
describe("isGeneratedPolicyName", () => {
|
|
159
|
+
it("recognises the generator's own shape", () => {
|
|
160
|
+
expect(isGeneratedPolicyName("documents_insert_a1b2c3d", "documents")).toBe(true);
|
|
161
|
+
// One rule spanning several operations appends the operation index.
|
|
162
|
+
expect(isGeneratedPolicyName("documents_update_a1b2c3d_1", "documents")).toBe(true);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("does not claim names a human could have written", () => {
|
|
166
|
+
expect(isGeneratedPolicyName("owner_access", "documents")).toBe(false);
|
|
167
|
+
expect(isGeneratedPolicyName("documents_default_admin_read", "documents")).toBe(false);
|
|
168
|
+
// Right shape, wrong table — belongs to something else.
|
|
169
|
+
expect(isGeneratedPolicyName("teams_insert_a1b2c3d", "documents")).toBe(false);
|
|
170
|
+
// A digest is 7 lowercase hex characters, nothing else.
|
|
171
|
+
expect(isGeneratedPolicyName("documents_insert_notahex", "documents")).toBe(false);
|
|
172
|
+
expect(isGeneratedPolicyName("documents_grant_a1b2c3d", "documents")).toBe(false);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("dropOrphanedPolicies", () => {
|
|
177
|
+
/** Records the DDL issued so the test can assert on what was dropped. */
|
|
178
|
+
function recordingDb(rows: Record<string, unknown>[]) {
|
|
179
|
+
const executed: string[] = [];
|
|
180
|
+
const db: Queryable = {
|
|
181
|
+
query: async (text: string) => {
|
|
182
|
+
if (!/^SELECT/i.test(text)) executed.push(text);
|
|
183
|
+
return { rows: rows as never[] };
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
return { db, executed };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
it("drops the policy a rule edit superseded", async () => {
|
|
190
|
+
// The reported failure: tightening a rule renames its policy, and the
|
|
191
|
+
// permissive original stays live and keeps ORing itself back in.
|
|
192
|
+
const cols = [collection("documents")];
|
|
193
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
194
|
+
const stale = {
|
|
195
|
+
schemaname: "public", tablename: "documents", policyname: "documents_insert_dead1ee",
|
|
196
|
+
roles: ["public"], cmd: "INSERT", qual: null, with_check: "true"
|
|
197
|
+
};
|
|
198
|
+
const live = [...expected.map((p) => liveRow(p)), stale];
|
|
199
|
+
|
|
200
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
201
|
+
const { db, executed } = recordingDb(live);
|
|
202
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
203
|
+
|
|
204
|
+
expect(dropped).toHaveLength(1);
|
|
205
|
+
expect(dropped[0].name).toBe("documents_insert_dead1ee");
|
|
206
|
+
expect(kept).toHaveLength(0);
|
|
207
|
+
expect(executed).toEqual([
|
|
208
|
+
'DROP POLICY IF EXISTS "documents_insert_dead1ee" ON "public"."documents"'
|
|
209
|
+
]);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("leaves a hand-written policy alone and reports it instead", async () => {
|
|
213
|
+
const cols = [collection("documents")];
|
|
214
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
215
|
+
const live = [
|
|
216
|
+
...expected.map((p) => liveRow(p)),
|
|
217
|
+
{ schemaname: "public", tablename: "documents", policyname: "ops_break_glass", roles: ["public"], cmd: "ALL", qual: "true", with_check: null }
|
|
218
|
+
];
|
|
219
|
+
|
|
220
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
221
|
+
const { db, executed } = recordingDb(live);
|
|
222
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
223
|
+
|
|
224
|
+
expect(dropped).toHaveLength(0);
|
|
225
|
+
expect(kept.map((p) => p.name)).toEqual(["ops_break_glass"]);
|
|
226
|
+
expect(executed).toEqual([]);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("never touches a table the collections do not describe", async () => {
|
|
230
|
+
// Another application sharing the schema owns this table; a
|
|
231
|
+
// generator-shaped name there is coincidence, not our leftover.
|
|
232
|
+
const cols = [collection("documents")];
|
|
233
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
234
|
+
const live = [
|
|
235
|
+
...expected.map((p) => liveRow(p)),
|
|
236
|
+
{ schemaname: "public", tablename: "legacy", policyname: "legacy_select_a1b2c3d", roles: ["public"], cmd: "SELECT", qual: "true", with_check: null }
|
|
237
|
+
];
|
|
238
|
+
|
|
239
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
240
|
+
const { db, executed } = recordingDb(live);
|
|
241
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
242
|
+
|
|
243
|
+
expect(dropped).toHaveLength(0);
|
|
244
|
+
expect(kept.map((p) => p.name)).toEqual(["legacy_select_a1b2c3d"]);
|
|
245
|
+
expect(executed).toEqual([]);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("does nothing when the database already matches", async () => {
|
|
249
|
+
const cols = [collection("documents")];
|
|
250
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
251
|
+
const live = expected.map((p) => liveRow(p));
|
|
252
|
+
|
|
253
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
254
|
+
const { db, executed } = recordingDb(live);
|
|
255
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
256
|
+
|
|
257
|
+
expect(dropped).toHaveLength(0);
|
|
258
|
+
expect(kept).toHaveLength(0);
|
|
259
|
+
expect(executed).toEqual([]);
|
|
260
|
+
});
|
|
261
|
+
});
|
|
@@ -192,6 +192,62 @@ export async function checkPolicyDrift(
|
|
|
192
192
|
return drift;
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
+
/**
|
|
196
|
+
* Does this name look like one the generator produced for this table?
|
|
197
|
+
*
|
|
198
|
+
* Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one
|
|
199
|
+
* rule spans several operations), and the hash covers the rule's semantics — so
|
|
200
|
+
* *editing* a rule renames its policy. The policy under the old name is left
|
|
201
|
+
* behind by `db push`, which only DROPs the names it is about to CREATE, and
|
|
202
|
+
* Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps
|
|
203
|
+
* granting everything no matter how tight its replacement is.
|
|
204
|
+
*
|
|
205
|
+
* Matching the shape is what makes dropping them safe. A hand-written policy
|
|
206
|
+
* would have to collide with a 7-hex digest to be mistaken for generated one;
|
|
207
|
+
* a policy named anything else is left alone and merely reported, because a
|
|
208
|
+
* custom name is indistinguishable from one someone wrote in SQL on purpose.
|
|
209
|
+
*/
|
|
210
|
+
export function isGeneratedPolicyName(name: string, table: string): boolean {
|
|
211
|
+
return new RegExp(`^${table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\d+)?$`)
|
|
212
|
+
.test(name);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface OrphanCleanup {
|
|
216
|
+
/** Superseded generated policies that were dropped. */
|
|
217
|
+
dropped: PolicyRef[];
|
|
218
|
+
/** Orphans left in place because their names are not generator-shaped. */
|
|
219
|
+
kept: PolicyRef[];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Drop the policies an earlier push superseded but never removed.
|
|
224
|
+
*
|
|
225
|
+
* Only touches tables the collections describe — a table with no expected
|
|
226
|
+
* policy is not ours to reconcile, and scanning by schema alone would sweep up
|
|
227
|
+
* policies belonging to something else sharing the database.
|
|
228
|
+
*/
|
|
229
|
+
export async function dropOrphanedPolicies(
|
|
230
|
+
client: Queryable,
|
|
231
|
+
drift: PolicyDrift,
|
|
232
|
+
collections: CollectionConfig[]
|
|
233
|
+
): Promise<OrphanCleanup> {
|
|
234
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
|
|
235
|
+
const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));
|
|
236
|
+
|
|
237
|
+
const cleanup: OrphanCleanup = { dropped: [], kept: [] };
|
|
238
|
+
for (const p of drift.orphaned) {
|
|
239
|
+
if (!managed.has(`${p.schema}.${p.table}`) || !isGeneratedPolicyName(p.name, p.table)) {
|
|
240
|
+
cleanup.kept.push(p);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
// Identifiers are quoted, and the name came from pg_policies rather than
|
|
244
|
+
// from user input, so it is already a valid identifier.
|
|
245
|
+
await client.query(`DROP POLICY IF EXISTS "${p.name}" ON "${p.schema}"."${p.table}"`);
|
|
246
|
+
cleanup.dropped.push(p);
|
|
247
|
+
}
|
|
248
|
+
return cleanup;
|
|
249
|
+
}
|
|
250
|
+
|
|
195
251
|
export const hasDrift = (d: PolicyDrift): boolean =>
|
|
196
252
|
d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
|
|
197
253
|
|
|
@@ -383,8 +383,15 @@ export class PersistService {
|
|
|
383
383
|
throw this.toUserFriendlyError(error, collection.slug);
|
|
384
384
|
}
|
|
385
385
|
|
|
386
|
-
// Fetch the
|
|
387
|
-
|
|
386
|
+
// Fetch the saved row back through the same walk `GET /:id` serves, so a
|
|
387
|
+
// write's answer is the read that follows it. This used to be `fetchOne`
|
|
388
|
+
// — the admin view-model walk — whose `__type: "relation"` refs then
|
|
389
|
+
// leaked into REST responses, afterSave callbacks, history records and
|
|
390
|
+
// app-level realtime payloads, none of which see that shape from any
|
|
391
|
+
// read path. The admin does not need them here either: its rows arrive
|
|
392
|
+
// over the realtime subscription refetch, which still serves the
|
|
393
|
+
// view-model walk.
|
|
394
|
+
const finalEntity = await this.fetchService.fetchOneForRest(collection.slug, savedId, undefined, databaseId);
|
|
388
395
|
if (!finalEntity) throw new Error("Could not fetch row after save.");
|
|
389
396
|
return finalEntity;
|
|
390
397
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CollectionConfig, Relation } from "@rebasepro/types";
|
|
1
|
+
import { CollectionConfig, Property, Relation } from "@rebasepro/types";
|
|
2
2
|
import { resolveCollectionRelations, findRelation, createRelationRefWithData } from "@rebasepro/common";
|
|
3
3
|
import { normalizeDbValues } from "../data-transformer";
|
|
4
4
|
import { deriveRowAddress } from "./collection-helpers";
|
|
@@ -54,7 +54,67 @@ function unwrapJunctionRow(item: Record<string, unknown>): Record<string, unknow
|
|
|
54
54
|
return nestedKey ? item[nestedKey] as Record<string, unknown> : item;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Give back the number a `number` property was declared to be.
|
|
59
|
+
*
|
|
60
|
+
* Postgres returns NUMERIC as a string and drizzle keeps it that way, since a
|
|
61
|
+
* numeric can hold more precision than a double. But the collection declared
|
|
62
|
+
* this property `number` and the OpenAPI spec this server publishes says
|
|
63
|
+
* `type: number`, so serving `"9.99"` breaks its own contract — and breaks it
|
|
64
|
+
* asymmetrically, because a create answers with the number and the read that
|
|
65
|
+
* follows answers with the string. Any client that multiplies a price works
|
|
66
|
+
* until the first refresh.
|
|
67
|
+
*
|
|
68
|
+
* Declaring a property `number` already accepts double precision — that is what
|
|
69
|
+
* the admin has always parsed it to. Columns REST serves that no property
|
|
70
|
+
* declares are left exactly as the database returned them.
|
|
71
|
+
*/
|
|
72
|
+
function coerceDeclaredNumber(value: unknown, property: Property | undefined): unknown {
|
|
73
|
+
if (property?.type !== "number" || typeof value !== "string") return value;
|
|
74
|
+
const parsed = parseFloat(value);
|
|
75
|
+
return isNaN(parsed) ? null : parsed;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Apply {@link coerceDeclaredNumber} across a row, leaving every other column alone. */
|
|
79
|
+
function coerceDeclaredNumbers(
|
|
80
|
+
row: Record<string, unknown>,
|
|
81
|
+
collection: CollectionConfig
|
|
82
|
+
): Record<string, unknown> {
|
|
83
|
+
const properties = collection.properties;
|
|
84
|
+
if (!properties) return row;
|
|
85
|
+
|
|
86
|
+
const out: Record<string, unknown> = {};
|
|
87
|
+
for (const [key, value] of Object.entries(row)) {
|
|
88
|
+
out[key] = coerceDeclaredNumber(value, properties[key] as Property | undefined);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
57
93
|
/** Render one target row in the requested style. */
|
|
94
|
+
/**
|
|
95
|
+
* Drop every column the collection marked `excludeFromApi`.
|
|
96
|
+
*
|
|
97
|
+
* Password hashes and verification tokens have to be readable server-side but
|
|
98
|
+
* must never reach a client — and "never" has to mean every exit from this
|
|
99
|
+
* pipeline, including relation targets, or a secret leaks through whichever
|
|
100
|
+
* path was overlooked. Keyed by both the property name and its column name,
|
|
101
|
+
* since a row can arrive keyed either way depending on the caller.
|
|
102
|
+
*/
|
|
103
|
+
function stripExcluded(
|
|
104
|
+
row: Record<string, unknown>,
|
|
105
|
+
collection: CollectionConfig
|
|
106
|
+
): Record<string, unknown> {
|
|
107
|
+
const properties = collection.properties as Record<string, Property> | undefined;
|
|
108
|
+
if (!properties) return row;
|
|
109
|
+
|
|
110
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
111
|
+
if (!property?.excludeFromApi) continue;
|
|
112
|
+
delete row[key];
|
|
113
|
+
if (property.columnName) delete row[property.columnName];
|
|
114
|
+
}
|
|
115
|
+
return row;
|
|
116
|
+
}
|
|
117
|
+
|
|
58
118
|
function renderTarget(
|
|
59
119
|
targetRow: Record<string, unknown>,
|
|
60
120
|
targetCollection: CollectionConfig,
|
|
@@ -64,7 +124,7 @@ function renderTarget(
|
|
|
64
124
|
if (style === "inline") {
|
|
65
125
|
// The target's columns, and only those: its address is the consumer's
|
|
66
126
|
// to derive, and merging one in overwrites a real `id` column.
|
|
67
|
-
return { ...targetRow };
|
|
127
|
+
return stripExcluded(coerceDeclaredNumbers({ ...targetRow }, targetCollection), targetCollection);
|
|
68
128
|
}
|
|
69
129
|
|
|
70
130
|
const address = relationTargetAddress(targetRow, targetCollection, registry);
|
|
@@ -132,15 +192,18 @@ export function toCmsRow(
|
|
|
132
192
|
}
|
|
133
193
|
}
|
|
134
194
|
|
|
135
|
-
return normalized;
|
|
195
|
+
return stripExcluded(normalized, collection);
|
|
136
196
|
}
|
|
137
197
|
|
|
138
198
|
/**
|
|
139
199
|
* The row REST serves: every column under its own name, with the value Postgres
|
|
140
200
|
* returned, and relations inlined as the target's columns.
|
|
141
201
|
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
202
|
+
* Values are the ones the database returned, except where that contradicts the
|
|
203
|
+
* declared type: a `number` property is served as a number (see
|
|
204
|
+
* {@link coerceDeclaredNumber}). Dates stay as the database returned them —
|
|
205
|
+
* JSON has its own opinions about dates that the admin's view-model does not
|
|
206
|
+
* share.
|
|
144
207
|
*
|
|
145
208
|
* Keyed by the row rather than by the relation list — a REST fetch only loads
|
|
146
209
|
* the relations `include` asked for, so the row is the authority on which are
|
|
@@ -168,9 +231,9 @@ export function toRestRow(
|
|
|
168
231
|
} else if (relation && typeof value === "object" && value !== null) {
|
|
169
232
|
flat[key] = renderTarget(value as Record<string, unknown>, relation.target(), "inline", registry);
|
|
170
233
|
} else {
|
|
171
|
-
flat[key] = value;
|
|
234
|
+
flat[key] = coerceDeclaredNumber(value, collection.properties?.[key] as Property | undefined);
|
|
172
235
|
}
|
|
173
236
|
}
|
|
174
237
|
|
|
175
|
-
return flat;
|
|
238
|
+
return stripExcluded(flat, collection);
|
|
176
239
|
}
|
|
@@ -1126,6 +1126,19 @@ export class DrizzleConditionBuilder {
|
|
|
1126
1126
|
throw new Error(`Vector column '${vectorSearch.property}' not found in table`);
|
|
1127
1127
|
}
|
|
1128
1128
|
|
|
1129
|
+
// The vector is interpolated as a raw SQL literal below (pgvector has no
|
|
1130
|
+
// bind form for the `::vector` cast), so every element must be a finite
|
|
1131
|
+
// number. The REST query parser already enforces this, but this builder
|
|
1132
|
+
// is a shared entry point — validate here too so no future caller can
|
|
1133
|
+
// turn an unchecked value into SQL injection.
|
|
1134
|
+
if (
|
|
1135
|
+
!Array.isArray(vectorSearch.vector) ||
|
|
1136
|
+
vectorSearch.vector.length === 0 ||
|
|
1137
|
+
!vectorSearch.vector.every((n) => typeof n === "number" && Number.isFinite(n))
|
|
1138
|
+
) {
|
|
1139
|
+
throw new Error("Vector search requires a non-empty array of finite numbers");
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1129
1142
|
const vectorLiteral = `'[${vectorSearch.vector.join(",")}]'::vector`;
|
|
1130
1143
|
const distanceFn = vectorSearch.distance || "cosine";
|
|
1131
1144
|
|