Open push preview database read-only

push:preview opened the database through getDatabase(), which creates
the file, sets WAL journal mode, and runs schema setup. Preview now
opens the existing notify.sqlite with readonly and fileMustExist, sets
query_only, and closes the connection before returning.

A missing database or a missing fcm_registrations table fails with an
error and is not repaired. The service connection and push:test are
unchanged.

Tests check that preview reads without writing, migrating, or changing
journal mode, that a missing database creates nothing, and that the
CLI exits 1 with no Firebase output.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Jose Olarte III
2026-11-20 16:46:33 +08:00
co-authored by Cursor
parent 6c17111055
commit 89d4b4ec11
5 changed files with 279 additions and 19 deletions
+12
View File
@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto";
import type BetterSqlite from "better-sqlite3";
import { getDatabase } from "./sqlite.js";
/**
@@ -53,6 +54,17 @@ function testModeToDb(testMode: boolean | undefined): number | null {
const ROW_COLUMNS =
"id, user_id, device_id, fcm_token, platform, test_mode, created_at, updated_at, last_notified_at";
/** Read registrations from a connection the caller opened. Does not open or migrate one. */
export function readRegistrationsByUserId(
connection: BetterSqlite.Database,
userId: string
): StoredRow[] {
const rows = connection
.prepare(`SELECT ${ROW_COLUMNS} FROM fcm_registrations WHERE user_id = ?`)
.all(userId) as DbRow[];
return rows.map(toStoredRow);
}
export const db = {
async upsert(row: {
userId: string;
+30 -1
View File
@@ -525,6 +525,35 @@ function ensureSchema(connection: Database.Database): void {
addDeviceSendKindColumn(connection);
}
/** The notify.sqlite path the service and the read-only tools share. */
export function notifyDatabasePath(): string {
return path.join(dataDirPath(), "notify.sqlite");
}
/**
* Open an existing database without creating it, migrating it, or changing
* its journal mode. The caller closes the connection. This is not the service
* connection: getDatabase() remains read-write and still initializes schema.
*/
export function openReadonlyDatabase(dbPath: string): Database.Database {
let connection: Database.Database;
try {
connection = new Database(dbPath, { readonly: true, fileMustExist: true });
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
throw new Error(
`Cannot open ${dbPath} read-only (${detail}). This command does not create a database. Nothing was sent.`
);
}
try {
connection.pragma("query_only = ON");
} catch (err) {
connection.close();
throw err;
}
return connection;
}
/**
* Returns a singleton SQLite connection with schema initialized.
* SQLite is the service's storage backend.
@@ -533,7 +562,7 @@ export function getDatabase(): Database.Database {
if (database === null) {
const dataDir = dataDirPath();
mkdirSync(dataDir, { recursive: true });
database = new Database(path.join(dataDir, "notify.sqlite"));
database = new Database(notifyDatabasePath());
database.pragma("journal_mode = WAL");
ensureSchema(database);
}
+59 -13
View File
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { alertPushDeviceSendsDb, type AlertPushDeviceSendInput } from "../db/alertPushDeviceSendsSqlite.js";
import { db, type StoredRow } from "../db/fcmTokensSqlite.js";
import { listRegisteredDevices } from "../alertSearch/notify.js";
import { db, readRegistrationsByUserId, type StoredRow } from "../db/fcmTokensSqlite.js";
import { notifyDatabasePath, openReadonlyDatabase } from "../db/sqlite.js";
import {
FCM_MESSAGE_ID_MAX_CHARS,
fcmFailureParts,
@@ -102,8 +102,61 @@ export type PushPreview = {
};
/**
* Describe the diagnostic notification for one DID. Does not send, and does
* not initialize Firebase. Eligible devices are the ones an AlertSearch send
* One row per distinct token, first row wins, then drop a blank token.
* The same rule as an AlertSearch send. Sorting is only for the preview text.
*/
function eligiblePreviewDevices(
rows: readonly StoredRow[]
): Array<{ deviceId: string; platform: string; fcmToken: string }> {
const seen = new Set<string>();
const devices: Array<{ deviceId: string; platform: string; fcmToken: string }> = [];
for (const row of rows) {
if (seen.has(row.fcmToken)) continue;
seen.add(row.fcmToken);
if (row.fcmToken.trim().length === 0) continue;
devices.push({ deviceId: row.deviceId, platform: row.platform, fcmToken: row.fcmToken });
}
devices.sort((a, b) => (a.deviceId < b.deviceId ? -1 : a.deviceId > b.deviceId ? 1 : 0));
return devices;
}
/**
* Read one DID's registrations from the existing database. The connection is
* read-only and query-only, and it is closed before this returns. A missing
* file or a missing fcm_registrations table is an error. Nothing is created
* or migrated, and journal mode is left alone.
*/
function readPreviewRegistrations(userId: string): StoredRow[] {
const dbPath = notifyDatabasePath();
const connection = openReadonlyDatabase(dbPath);
try {
const present = connection
.prepare(
`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'fcm_registrations'`
)
.get();
if (present === undefined) {
throw new Error(
`${dbPath} has no fcm_registrations table. push:preview does not create or migrate the schema. Nothing was sent.`
);
}
try {
return readRegistrationsByUserId(connection, userId);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
throw new Error(
`Cannot read fcm_registrations in ${dbPath} (${detail}). push:preview does not migrate the schema. Nothing was sent.`
);
}
} finally {
connection.close();
}
}
/**
* Describe the diagnostic notification for one DID. Does not send and does
* not initialize Firebase. The database is opened read-only and closed
* before this returns. Eligible devices are the ones an AlertSearch send
* would attempt: one row per distinct non-empty token.
*/
export async function previewDiagnosticPush(input: {
@@ -111,17 +164,10 @@ export async function previewDiagnosticPush(input: {
now?: Date;
env?: NodeJS.ProcessEnv;
}): Promise<PushPreview> {
const registrations = readPreviewRegistrations(input.userId);
const now = input.now ?? new Date();
const environment = resolveDiagnosticEnvironment(input.env);
const registrations = await db.getByUserId(input.userId);
const eligible = (await listRegisteredDevices(input.userId))
.filter((device) => device.token.trim().length > 0)
.map((device) => ({
deviceId: device.deviceId,
platform: device.platform,
fcmToken: device.token,
}))
.sort((a, b) => (a.deviceId < b.deviceId ? -1 : a.deviceId > b.deviceId ? 1 : 0));
const eligible = eligiblePreviewDevices(registrations);
const content = buildPushDiagnosticContent({
id: randomUUID(),
at: now.toISOString(),
+7 -1
View File
@@ -1,6 +1,7 @@
/**
* Show the diagnostic notification that would be sent to a DID.
* Does not send, does not initialize Firebase, and does not write the database.
* Does not send and does not initialize Firebase. Opens the existing
* database read-only, does not create it, and does not migrate it.
*
* pnpm push:preview -- --did <DID>
*/
@@ -14,6 +15,11 @@ if (did === undefined) {
process.exit(1);
}
try {
const preview = await previewDiagnosticPush({ userId: did });
console.log(preview.report);
} catch (err) {
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
process.exit(0);
+169 -2
View File
@@ -1,14 +1,15 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { chmodSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
import { mkdtemp, rm } from "node:fs/promises";
import Database from "better-sqlite3";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, it } from "node:test";
import { alertPushSendsDb } from "../../src/db/alertPushSendsSqlite.js";
import { db } from "../../src/db/fcmTokensSqlite.js";
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
import { closeDatabase, getDatabase, notifyDatabasePath, openReadonlyDatabase } from "../../src/db/sqlite.js";
import {
decideDiagnosticRegistration,
maskRegistrationToken,
@@ -69,6 +70,31 @@ function row(partial: Partial<StoredRow> & Pick<StoredRow, "userId" | "deviceId"
};
}
function inspectDatabase(dbPath: string): {
journal: string;
master: unknown[];
registrations: unknown[];
cursorColumns: string[];
attemptColumns: string[];
} {
const connection = new Database(dbPath, { readonly: true, fileMustExist: true });
try {
const names = (table: string) =>
(connection.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map(
(column) => column.name
);
return {
journal: String(connection.pragma("journal_mode", { simple: true })),
master: connection.prepare(`SELECT type, name, sql FROM sqlite_master ORDER BY name`).all(),
registrations: connection.prepare(`SELECT * FROM fcm_registrations ORDER BY id`).all(),
cursorColumns: names("alert_search_cursors"),
attemptColumns: names("alert_push_device_sends"),
};
} finally {
connection.close();
}
}
function assertNoSecrets(text: string): void {
assert.equal(text.includes(TOKEN), false);
assert.equal(text.includes("UNIQUESECRET"), false);
@@ -277,6 +303,7 @@ describe("diagnostic preview and send", () => {
await register(DID, "phone-2", "zzzzUNIQUESECRET9876yyyy", "ios");
const sendsBefore = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
const attemptsBefore = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_device_sends`).get() as { n: number };
const journalBefore = getDatabase().pragma("journal_mode", { simple: true });
const calls: unknown[] = [];
delete process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED;
const preview = await previewDiagnosticPush({ userId: DID, now: NOW });
@@ -304,12 +331,139 @@ describe("diagnostic preview and send", () => {
const attemptsAfter = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_device_sends`).get() as { n: number };
assert.equal(sendsAfter.n, sendsBefore.n);
assert.equal(attemptsAfter.n, attemptsBefore.n);
assert.equal(getDatabase().pragma("journal_mode", { simple: true }), journalBefore);
const empty = await previewDiagnosticPush({ userId: "did:example:nobody", now: NOW });
assert.match(empty.report, /Eligible devices: 0/);
assert.match(empty.report, /No eligible FCM registration for this DID/);
});
it("reads an existing database without writing, migrating, or changing journal mode", async () => {
closeDatabase();
const dbPath = notifyDatabasePath();
const created = new Database(dbPath);
created.exec(`
CREATE TABLE fcm_registrations (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
device_id TEXT NOT NULL,
fcm_token TEXT NOT NULL,
platform TEXT NOT NULL,
test_mode INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
last_notified_at INTEGER
);
CREATE TABLE alert_search_cursors (
user_id TEXT NOT NULL,
endorser_after_id TEXT
);
CREATE TABLE alert_push_device_sends (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
device_id TEXT NOT NULL,
attempted_at TEXT NOT NULL,
outcome TEXT NOT NULL
);
INSERT INTO fcm_registrations (
id, user_id, device_id, fcm_token, platform, test_mode, created_at, updated_at, last_notified_at
) VALUES
('reg-1', '${DID}', '${DEVICE}', '${TOKEN}', 'android', 0, '${NOW.toISOString()}', '${NOW.toISOString()}', NULL),
('reg-2', '${DID}', 'phone-2', '${TOKEN}', 'ios', 0, '${NOW.toISOString()}', '${NOW.toISOString()}', NULL),
('reg-3', '${DID}', 'phone-blank', ' ', 'android', 0, '${NOW.toISOString()}', '${NOW.toISOString()}', NULL);
INSERT INTO alert_search_cursors (user_id, endorser_after_id) VALUES ('${DID}', 'old-id-cursor');
`);
created.pragma("journal_mode = DELETE");
created.close();
const readonly = openReadonlyDatabase(dbPath);
assert.throws(() => readonly.prepare(`INSERT INTO alert_search_cursors (user_id) VALUES ('x')`).run());
assert.throws(() => readonly.exec(`CREATE TABLE preview_should_not_create (id TEXT)`));
assert.throws(() => readonly.pragma("journal_mode = WAL"));
readonly.close();
const before = inspectDatabase(dbPath);
assert.equal(before.journal, "delete");
chmodSync(dbPath, 0o444);
chmodSync(dir, 0o555);
const mtime = statSync(dbPath).mtimeMs;
const logs: string[] = [];
const originalLog = console.log;
const originalError = console.error;
console.log = (...args: unknown[]) => {
logs.push(args.map(String).join(" "));
};
console.error = (...args: unknown[]) => {
logs.push(args.map(String).join(" "));
};
try {
const preview = await previewDiagnosticPush({ userId: DID, now: NOW });
assert.equal(preview.eligible.length, 1);
assert.equal(preview.eligible[0]?.deviceId, DEVICE);
assert.equal(preview.registrationCount, 3);
assert.match(preview.report, /Eligible devices: 1/);
assert.match(preview.report, /Registrations: 3/);
assert.match(preview.report, /2 registrations not eligible/);
assert.match(preview.report, /Preview only\. No FCM message was sent\./);
assertNoSecrets(preview.report);
assert.equal(logs.some((line) => line.includes("[Firebase]")), false);
} finally {
console.log = originalLog;
console.error = originalError;
chmodSync(dir, 0o755);
chmodSync(dbPath, 0o644);
}
assert.equal(statSync(dbPath).mtimeMs, mtime);
assert.deepEqual(inspectDatabase(dbPath), before);
});
it("fails when the database or the registration table is missing and creates nothing", async () => {
closeDatabase();
const missingDir = path.join(dir, "no-database");
mkdirSync(missingDir);
process.env.NOTIFY_DATA_DIR = missingDir;
await assert.rejects(
() => previewDiagnosticPush({ userId: DID, now: NOW }),
/does not create a database/
);
assert.deepEqual(readdirSync(missingDir), []);
process.env.NOTIFY_DATA_DIR = dir;
const dbPath = notifyDatabasePath();
const empty = new Database(dbPath);
const journalBefore = String(empty.pragma("journal_mode", { simple: true }));
empty.close();
await assert.rejects(
() => previewDiagnosticPush({ userId: DID, now: NOW }),
/no fcm_registrations table/
);
const afterEmpty = new Database(dbPath, { readonly: true, fileMustExist: true });
try {
assert.equal(String(afterEmpty.pragma("journal_mode", { simple: true })), journalBefore);
const tables = afterEmpty
.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`)
.all() as Array<{ name: string }>;
assert.deepEqual(tables, []);
} finally {
afterEmpty.close();
}
const partial = new Database(dbPath);
partial.exec(`CREATE TABLE fcm_registrations (id TEXT)`);
partial.close();
await assert.rejects(
() => previewDiagnosticPush({ userId: DID, now: NOW }),
/does not migrate the schema/
);
const afterPartial = new Database(dbPath, { readonly: true, fileMustExist: true });
try {
const columns = afterPartial.prepare(`PRAGMA table_info(fcm_registrations)`).all() as Array<{ name: string }>;
assert.deepEqual(columns.map((column) => column.name), ["id"]);
} finally {
afterPartial.close();
}
});
it("sends to exactly one registration and records a diagnostic attempt without touching the cap", async () => {
await register(DID, DEVICE);
await register(DID, "phone-2", "zzzzUNIQUESECRET9876yyyy", "ios");
@@ -647,6 +801,19 @@ describe("push preview and test commands", () => {
const tool = readFileSync(path.join(root, "src/tools/pushPreview.ts"), "utf8");
assert.equal(tool.includes("firebase"), false);
assert.equal(tool.includes("messaging"), false);
const missingDir = path.join(dir, "no-database");
mkdirSync(missingDir);
const missingDatabase = run("src/tools/pushPreview.ts", ["--did", DID], {
...previewEnv,
NOTIFY_DATA_DIR: missingDir,
});
assert.equal(missingDatabase.status, 1, missingDatabase.stderr);
assert.match(missingDatabase.stderr, /does not create a database/);
assert.match(missingDatabase.stderr, /Nothing was sent/);
assert.equal(missingDatabase.stdout, "");
assert.equal(missingDatabase.stderr.includes("[Firebase]"), false);
assert.deepEqual(readdirSync(missingDir), []);
});
it("requires both a DID and a device id before a test send", () => {