fix(db): let the move to Postgres change nothing silently

The move stripped NUL from a plugin's own text, merging keys that were
distinct, and turned a plugin's values into another type (text in a BLOB
column into bytea, numbers in an untyped column into text). Its checksum
was built from the converted values, so both passed as verified.

A plugin's data now moves exactly as the Postgres plugin store would
hand it back, or not at all: a NUL, a value of another storage class
than its column, or an integer past 2^53 refuses the move before
anything is written, listing plugin, table, row and column. A column
left open by SQLite's affinity takes the kind its values need, so text
in a BLOB column stays text.

TREK's own text holding a NUL from an older install is refused by
default too. --drop-nul drops it, lists every changed value in the
summary, and names a unique key that dropping a NUL broke.

Every table's checksum is now built from the values read from SQLite,
so a conversion that changes a value fails the verification.
This commit is contained in:
Maurice
2026-11-17 23:28:01 +01:00
parent 6040b60e86
commit bc6728678b
10 changed files with 655 additions and 97 deletions
@@ -9,9 +9,23 @@ import { createHash } from 'node:crypto';
* SQLite stores a value by what it is, not by the column's declared type, so
* a column may hold text where the schema says integer. The move never
* guesses: a value the Postgres column cannot hold exactly is refused with
* the reason, and the move stops before it commits anything. The one
* exception is a NUL character in text or JSON, which TREK stores on neither
* engine (`db/nul-free.ts`): the move drops it, as every write does.
* the reason, and the move stops before it commits anything.
*
* Two sets of rules decide what "exactly" means ({@link ConvertRules}):
* - TREK's own tables follow TREK's storage model, so a whole number stored
* as text reaches an integer column as that number. A NUL character in text
* or JSON, which TREK has stopped storing on either engine
* (`db/nul-free.ts`), is refused unless the operator asked for it to be
* dropped (`--drop-nul`); each value that loses one is reported.
* - A plugin's own data is the plugin's, so a value must come back from the
* Postgres plugin store as the plugin's SQLite file hands it back today:
* an INTEGER or a REAL as a number, TEXT as a string, a BLOB as a Buffer,
* with the same bytes. Nothing changes its storage class, and a NUL, which
* the Postgres store cannot hold, is refused.
*
* The compared text of a row is built from the value read from SQLite
* ({@link canonicalFromSource}), never from the value sent, so a conversion
* that changed a value fails the verification instead of passing it.
*
* The SQLite side is read with better-sqlite3's safe integers, so an integer
* arrives as a `bigint` and keeps all 64 bits.
@@ -26,13 +40,31 @@ export type SqliteValue = null | bigint | number | string | Uint8Array;
/** A value Postgres takes as a parameter: a decimal string for an integer, a Buffer for bytes. */
export type PostgresValue = null | string | number | Buffer;
type Converted = { ok: true; value: PostgresValue } | { ok: false; reason: string };
/** A converted value, and whether `--drop-nul` removed NUL characters from it. */
type Converted = { ok: true; value: PostgresValue; droppedNul?: true } | { ok: false; reason: string };
/** How strictly a value must arrive; see the header. */
export interface ConvertRules {
/** A plugin's own data: the value keeps its storage class and its bytes, and a NUL is refused. */
exact: boolean;
/** TREK's own data: a NUL in text or JSON is dropped (and reported) instead of refused. */
dropNul: boolean;
}
/** TREK's own tables, without `--drop-nul`. */
const TREK_RULES: ConvertRules = { exact: false, dropNul: false };
/** A plugin's own tables. */
export const PLUGIN_RULES: ConvertRules = { exact: true, dropNul: false };
const INT64_MIN = -(2n ** 63n);
const INT64_MAX = 2n ** 63n - 1n;
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
const DECIMAL_INTEGER = /^[+-]?\d+$/;
const DECIMAL_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
const NUL = '\u0000';
/** Why a value holding a NUL character is refused. */
export const NUL_REASON = 'holds a NUL character (U+0000), which Postgres text cannot hold';
/**
* The kind of a Postgres column, from `information_schema.columns.data_type`.
@@ -102,13 +134,27 @@ function toFloat(value: Exclude<SqliteValue, null>): Converted {
return refuse(`${describe(value)} is not a number`);
}
function toText(value: Exclude<SqliteValue, null>): Converted {
if (typeof value === 'string') return { ok: true, value: stripNul(value) };
function toText(value: Exclude<SqliteValue, null>, dropNul: boolean): Converted {
if (typeof value === 'string') {
if (!value.includes(NUL)) return { ok: true, value };
if (!dropNul) return refuse(`${describe(value)} ${NUL_REASON}`);
return { ok: true, value: stripNul(value), droppedNul: true };
}
if (typeof value === 'bigint' || typeof value === 'number') return { ok: true, value: String(value) };
return refuse(`${describe(value)} is not text`);
}
function toJson(value: Exclude<SqliteValue, null>): Converted {
/** Whether a parsed JSON value holds a NUL in any string, object keys included. */
function jsonHoldsNul(value: unknown): boolean {
if (typeof value === 'string') return value.includes(NUL);
if (Array.isArray(value)) return value.some(jsonHoldsNul);
if (value !== null && typeof value === 'object') {
return Object.entries(value).some(([key, item]) => key.includes(NUL) || jsonHoldsNul(item));
}
return false;
}
function toJson(value: Exclude<SqliteValue, null>, dropNul: boolean): Converted {
if (typeof value === 'bigint' || typeof value === 'number') return { ok: true, value: String(value) };
if (typeof value !== 'string') return refuse(`${describe(value)} is not JSON text`);
let parsed: unknown;
@@ -117,8 +163,10 @@ function toJson(value: Exclude<SqliteValue, null>): Converted {
} catch {
return refuse(`${describe(value)} is not valid JSON`);
}
// Valid JSON holds a NUL only escaped, which jsonb refuses as well: the value is written again without it.
return { ok: true, value: value.includes('\\u0000') ? JSON.stringify(nulFreeJson(parsed)) : value };
// Valid JSON holds a NUL only escaped, which jsonb refuses as well.
if (!jsonHoldsNul(parsed)) return { ok: true, value };
if (!dropNul) return refuse(`${describe(value)} ${NUL_REASON} (escaped as \\u0000)`);
return { ok: true, value: JSON.stringify(nulFreeJson(parsed)), droppedNul: true };
}
function toBytes(value: Exclude<SqliteValue, null>): Converted {
@@ -128,18 +176,71 @@ function toBytes(value: Exclude<SqliteValue, null>): Converted {
return refuse(`${describe(value)} is not a BLOB`);
}
/** `value` as the Postgres column of `kind` takes it, or the reason it cannot hold it exactly. */
export function convertValue(value: SqliteValue, kind: ColumnKind): Converted {
/** What a column of `kind` holds on Postgres, for a refusal. */
const KIND_HOLDS: Record<ColumnKind, string> = {
integer: 'integers (bigint)',
float: 'numbers (double precision)',
text: 'text',
json: 'JSON (jsonb)',
bytes: 'bytes (bytea)',
};
/** The SQLite storage class of a value, for a refusal. */
function storageClass(value: Exclude<SqliteValue, null>): string {
if (value instanceof Uint8Array) return 'a BLOB';
if (typeof value === 'string') return 'TEXT';
return typeof value === 'bigint' ? 'an INTEGER' : 'a REAL';
}
/**
* A plugin's value as its Postgres column takes it, only where the Postgres
* plugin store hands it back to the plugin as the SQLite file did: a `bigint`
* column reads as a number (and one past 2^53 is refused, `parseInt8` in
* `postgres-driver.ts`), `double precision` as a number, `text` as a string
* and `bytea` as a Buffer.
*/
function exactly(value: Exclude<SqliteValue, null>, kind: ColumnKind): Converted {
const changed = () =>
refuse(
`${describe(value)} is stored as ${storageClass(value)}, but the column holds ${KIND_HOLDS[kind]} on Postgres, ` +
'so the plugin would read it back as another type',
);
switch (kind) {
case 'integer':
if (typeof value !== 'bigint') return changed();
if (value > SAFE_MAX || value < -SAFE_MAX) {
return refuse(`${describe(value)} is beyond 2^53, which the Postgres plugin store refuses to read`);
}
return { ok: true, value: value.toString() };
case 'float':
if (typeof value === 'number') return { ok: true, value };
if (typeof value !== 'bigint') return changed();
return value > SAFE_MAX || value < -SAFE_MAX
? refuse(`${describe(value)} has more digits than a double holds`)
: { ok: true, value: Number(value) };
case 'text':
if (typeof value !== 'string') return changed();
return value.includes(NUL) ? refuse(`${describe(value)} ${NUL_REASON}`) : { ok: true, value };
case 'bytes':
return value instanceof Uint8Array ? { ok: true, value: Buffer.from(value) } : changed();
case 'json':
return toJson(value, false);
}
}
/** `value` as the Postgres column of `kind` takes it under `rules`, or the reason it cannot hold it exactly. */
export function convertValue(value: SqliteValue, kind: ColumnKind, rules: ConvertRules = TREK_RULES): Converted {
if (value === null) return { ok: true, value: null };
if (rules.exact) return exactly(value, kind);
switch (kind) {
case 'integer':
return toInteger(value);
case 'float':
return toFloat(value);
case 'text':
return toText(value);
return toText(value, rules.dropNul);
case 'json':
return toJson(value);
return toJson(value, rules.dropNul);
case 'bytes':
return toBytes(value);
}
@@ -168,23 +269,41 @@ export function stableJson(text: string): string {
return JSON.stringify(sort(JSON.parse(text)));
}
/** Bytes as the compared text: their hex digits. */
function hex(bytes: Uint8Array): string {
return Buffer.from(bytes).toString('hex');
}
/**
* The text a value is compared in, from the value the move sent to Postgres.
* `canonicalFromPostgres` must answer the same for what Postgres stored.
* The text a value is compared in, from the value read from the SQLite file
* (not from what the move sent), by the rules it was converted under.
* `canonicalFromPostgres` must answer the same for what Postgres stored, so a
* conversion that changed a value, or a value that changed on the way, fails
* the verification. The one change the rules allow is `--drop-nul` on TREK's
* own text and JSON, which the operator asked for and the summary lists. A
* value of a storage class its kind does not take is refused before it is
* sent; here it answers a marked text that matches nothing Postgres prints.
*/
export function canonicalFromSent(value: PostgresValue, kind: ColumnKind): string | null {
export function canonicalFromSource(
value: SqliteValue,
kind: ColumnKind,
rules: ConvertRules = TREK_RULES,
): string | null {
if (value === null) return null;
if (value instanceof Uint8Array) return kind === 'bytes' ? hex(value) : `blob:${hex(value)}`;
const dropNul = rules.dropNul && !rules.exact;
switch (kind) {
case 'integer':
return BigInt(String(value)).toString();
return typeof value === 'bigint' ? value.toString() : BigInt(String(value).trim()).toString();
case 'float':
return String(Number(value));
return typeof value === 'bigint' ? value.toString() : String(Number(String(value).trim()));
case 'text':
return String(value);
return typeof value === 'string' && dropNul ? stripNul(value) : String(value);
case 'json':
return stableJson(String(value));
if (typeof value !== 'string') return stableJson(String(value));
return stableJson(dropNul ? JSON.stringify(nulFreeJson(JSON.parse(value))) : value);
case 'bytes':
return Buffer.isBuffer(value) ? value.toString('hex') : Buffer.from(String(value), 'utf8').toString('hex');
return typeof value === 'string' ? Buffer.from(value, 'utf8').toString('hex') : `number:${String(value)}`;
}
}