add push preview and diagnostic test push commands
Add two separate CLI commands. push:preview shows the notification and eligible devices for a DID without sending. push:test sends one diagnostic notification to exactly one registration, selected by both DID and device id, and fails closed on a missing, inactive, other-DID, or ambiguous registration.
This commit is contained in:
@@ -31,6 +31,12 @@
|
||||
# "production" everywhere. Unset or blank appends nothing.
|
||||
# MESSAGE_ENV_LABEL=test
|
||||
|
||||
# Diagnostic test push (pnpm push:test) sends only when MESSAGE_ENV_LABEL is
|
||||
# exactly "test" and this value equals the project_id inside
|
||||
# FIREBASE_SERVICE_ACCOUNT_JSON. There is no production override. Leave unset
|
||||
# in production.
|
||||
# PUSH_TEST_FIREBASE_PROJECT_ID=
|
||||
|
||||
# --- SMS notifications (/notify-sms) ---
|
||||
|
||||
# Master switch. While false, every /notify-sms route returns 503 SMS_DISABLED
|
||||
|
||||
+3
-1
@@ -16,7 +16,9 @@
|
||||
"sms:blocks": "tsx scripts/sms-blocks.ts",
|
||||
"alert-search:tap": "tsx scripts/alert-search-tap.ts",
|
||||
"sms:watch": "tsx src/tools/smsWatch.ts",
|
||||
"push:watch": "tsx src/tools/pushWatch.ts"
|
||||
"push:watch": "tsx src/tools/pushWatch.ts",
|
||||
"push:preview": "tsx src/tools/pushPreview.ts",
|
||||
"push:test": "tsx src/tools/pushTest.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-ecc": "^2.7.0",
|
||||
|
||||
@@ -25,6 +25,12 @@ export type AlertPushDeviceSendInput = {
|
||||
fcmMessageId: string | null;
|
||||
fcmErrorCode: string | null;
|
||||
errorDetail: string | null;
|
||||
/**
|
||||
* `alert_search` is a normal digest attempt. `push_watch_test` is one
|
||||
* diagnostic send. Omitted means `alert_search`, including every caller
|
||||
* that predates the column.
|
||||
*/
|
||||
kind?: "alert_search" | "push_watch_test";
|
||||
};
|
||||
|
||||
function storedText(value: string | null, maxChars: number): string | null {
|
||||
@@ -56,8 +62,8 @@ export const alertPushDeviceSendsDb = {
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO alert_push_device_sends (
|
||||
id, user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail, kind
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
for (const row of rows) {
|
||||
const outcome = row.outcome === "sent" ? "sent" : "failed";
|
||||
@@ -71,7 +77,8 @@ export const alertPushDeviceSendsDb = {
|
||||
outcome,
|
||||
outcome === "sent" ? storedText(row.fcmMessageId, FCM_MESSAGE_ID_MAX_CHARS) : null,
|
||||
outcome === "failed" ? storedText(row.fcmErrorCode, FCM_ERROR_CODE_MAX_CHARS) : null,
|
||||
outcome === "failed" ? storedText(row.errorDetail, FCM_ERROR_DETAIL_MAX_CHARS) : null
|
||||
outcome === "failed" ? storedText(row.errorDetail, FCM_ERROR_DETAIL_MAX_CHARS) : null,
|
||||
row.kind === "push_watch_test" ? "push_watch_test" : "alert_search"
|
||||
);
|
||||
}
|
||||
const prune = db.prepare(
|
||||
|
||||
@@ -163,6 +163,16 @@ export const db = {
|
||||
return rows.map(toStoredRow);
|
||||
},
|
||||
|
||||
/** Every registration stored under this device id, whichever DID owns it. */
|
||||
async listByDeviceId(deviceId: string): Promise<StoredRow[]> {
|
||||
const rows = getDatabase()
|
||||
.prepare(
|
||||
`SELECT ${ROW_COLUMNS} FROM fcm_registrations WHERE device_id = ?`
|
||||
)
|
||||
.all(deviceId) as DbRow[];
|
||||
return rows.map(toStoredRow);
|
||||
},
|
||||
|
||||
async getByDeviceId(
|
||||
userId: string,
|
||||
deviceId: string
|
||||
|
||||
+22
-3
@@ -339,8 +339,11 @@ CREATE INDEX IF NOT EXISTS idx_alert_push_sends_user_sent
|
||||
-- rejected it. Neither means the device displayed the notification.
|
||||
-- push_send_id matches alert_push_sends when that DID-level row exists
|
||||
-- (at least one device was accepted). It is null when every device failed,
|
||||
-- because no DID-level row is written in that case. The daily cap does not
|
||||
-- read this table. Tokens, JWTs, and notification bodies are not stored.
|
||||
-- because no DID-level row is written in that case. It is also null for a
|
||||
-- diagnostic test push, which never writes alert_push_sends. The daily cap
|
||||
-- does not read this table. Tokens, JWTs, and notification bodies are not stored.
|
||||
-- kind is alert_search for a normal digest attempt and push_watch_test for a
|
||||
-- diagnostic send. Existing rows default to alert_search.
|
||||
CREATE TABLE IF NOT EXISTS alert_push_device_sends (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
@@ -351,7 +354,8 @@ CREATE TABLE IF NOT EXISTS alert_push_device_sends (
|
||||
outcome TEXT NOT NULL,
|
||||
fcm_message_id TEXT,
|
||||
fcm_error_code TEXT,
|
||||
error_detail TEXT
|
||||
error_detail TEXT,
|
||||
kind TEXT NOT NULL DEFAULT 'alert_search'
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_alert_push_device_sends_user_attempted
|
||||
@@ -486,6 +490,20 @@ const BATCH_TABLES = [
|
||||
"sms_alert_authorization_batches",
|
||||
];
|
||||
|
||||
/** Device-attempt rows from before diagnostic sends have no kind column. */
|
||||
function addDeviceSendKindColumn(connection: Database.Database): void {
|
||||
const columns = connection
|
||||
.prepare(`PRAGMA table_info(alert_push_device_sends)`)
|
||||
.all() as Array<{ name: string }>;
|
||||
if (columns.length === 0) return;
|
||||
if (!columns.some((column) => column.name === "kind")) {
|
||||
connection.exec(
|
||||
`ALTER TABLE alert_push_device_sends
|
||||
ADD COLUMN kind TEXT NOT NULL DEFAULT 'alert_search'`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function addRenewalRemindedColumn(connection: Database.Database): void {
|
||||
for (const table of BATCH_TABLES) {
|
||||
const columns = connection
|
||||
@@ -504,6 +522,7 @@ function ensureSchema(connection: Database.Database): void {
|
||||
connection.exec(SCHEMA_SQL);
|
||||
addCursorSearchInputColumns(connection);
|
||||
addRenewalRemindedColumn(connection);
|
||||
addDeviceSendKindColumn(connection);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
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 {
|
||||
FCM_MESSAGE_ID_MAX_CHARS,
|
||||
fcmFailureParts,
|
||||
sanitizeFcmDiagnostic,
|
||||
type FcmSendResult,
|
||||
} from "../util/fcmOutcome.js";
|
||||
import { maskToken } from "../util/maskToken.js";
|
||||
import { log } from "../util/log.js";
|
||||
import {
|
||||
formatDiagnosticEnvironment,
|
||||
resolveDiagnosticEnvironment,
|
||||
type DiagnosticEnvironmentResult,
|
||||
} from "./pushDiagnosticEnv.js";
|
||||
import {
|
||||
buildPushDiagnosticContent,
|
||||
buildPushDiagnosticMessage,
|
||||
formatPushDiagnosticPayload,
|
||||
type PushDiagnosticContent,
|
||||
type PushDiagnosticMessage,
|
||||
} from "./pushDiagnosticPayload.js";
|
||||
|
||||
/** Same shape as pushWatch's maskFcmToken: a short prefix and suffix, never the middle. */
|
||||
export function maskRegistrationToken(token: string): string {
|
||||
if (token.length === 0) return "(empty)";
|
||||
const prefix = 4;
|
||||
const suffix = 4;
|
||||
if (token.length < prefix + suffix + 8) return "********";
|
||||
const stars = "*".repeat(Math.min(token.length - prefix - suffix, 12));
|
||||
return `${token.slice(0, prefix)}${stars}${token.slice(-suffix)}`;
|
||||
}
|
||||
|
||||
export type DiagnosticRegistrationDecision =
|
||||
| { ok: true; row: StoredRow }
|
||||
| { ok: false; reason: "missing" | "inactive" | "ambiguous" | "other_did"; detail: string };
|
||||
|
||||
/**
|
||||
* Choose the one registration named by both the DID and the device id.
|
||||
* A device id owned by someone else is not a match. More than one row for
|
||||
* the pair is ambiguous. A blank token cannot be sent to.
|
||||
*/
|
||||
export function decideDiagnosticRegistration(
|
||||
userId: string,
|
||||
deviceId: string,
|
||||
rows: readonly StoredRow[]
|
||||
): DiagnosticRegistrationDecision {
|
||||
const owned = rows.filter((row) => row.userId === userId && row.deviceId === deviceId);
|
||||
if (owned.length > 1) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "ambiguous",
|
||||
detail: `Found ${owned.length} registrations for this DID and device id. Nothing was sent.`,
|
||||
};
|
||||
}
|
||||
if (owned.length === 0) {
|
||||
if (rows.length > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "other_did",
|
||||
detail: "That device id is registered to a different DID. Nothing was sent.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
reason: "missing",
|
||||
detail: "No registration exists for this DID and device id. Nothing was sent.",
|
||||
};
|
||||
}
|
||||
const row = owned[0];
|
||||
if (row.fcmToken.trim().length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "inactive",
|
||||
detail: "The registration has no FCM token. Nothing was sent.",
|
||||
};
|
||||
}
|
||||
return { ok: true, row };
|
||||
}
|
||||
|
||||
export async function selectDiagnosticRegistration(
|
||||
userId: string,
|
||||
deviceId: string
|
||||
): Promise<DiagnosticRegistrationDecision> {
|
||||
const rows = await db.listByDeviceId(deviceId);
|
||||
return decideDiagnosticRegistration(userId, deviceId, rows);
|
||||
}
|
||||
|
||||
export type PushPreview = {
|
||||
userId: string;
|
||||
registrationCount: number;
|
||||
eligible: Array<{ deviceId: string; platform: string; fcmToken: string }>;
|
||||
content: PushDiagnosticContent;
|
||||
environment: DiagnosticEnvironmentResult;
|
||||
report: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe the diagnostic notification for one DID. Does not send, and does
|
||||
* not initialize Firebase. Eligible devices are the ones an AlertSearch send
|
||||
* would attempt: one row per distinct non-empty token.
|
||||
*/
|
||||
export async function previewDiagnosticPush(input: {
|
||||
userId: string;
|
||||
now?: Date;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): Promise<PushPreview> {
|
||||
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 content = buildPushDiagnosticContent({
|
||||
id: randomUUID(),
|
||||
at: now.toISOString(),
|
||||
});
|
||||
const skipped = registrations.length - eligible.length;
|
||||
const lines = [
|
||||
"Preview only. No FCM message was sent.",
|
||||
...formatDiagnosticEnvironment(environment),
|
||||
`DID: ${input.userId}`,
|
||||
`Registrations: ${registrations.length}`,
|
||||
`Eligible devices: ${eligible.length}`,
|
||||
];
|
||||
if (eligible.length === 0) {
|
||||
lines.push("No eligible FCM registration for this DID.");
|
||||
}
|
||||
for (const device of eligible) {
|
||||
lines.push(
|
||||
` ${device.deviceId} ${device.platform} token ${maskRegistrationToken(device.fcmToken)}`
|
||||
);
|
||||
}
|
||||
if (skipped > 0) {
|
||||
lines.push(
|
||||
`${skipped} registration${skipped === 1 ? "" : "s"} not eligible (empty token, or a token already listed).`
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
"Diagnostic notification that would be sent:",
|
||||
...formatPushDiagnosticPayload(content),
|
||||
"data.id and data.at are assigned when the message is built. A later send builds its own.",
|
||||
"This is not an alert_search message. Tapping it does not open New Activity."
|
||||
);
|
||||
return {
|
||||
userId: input.userId,
|
||||
registrationCount: registrations.length,
|
||||
eligible,
|
||||
content,
|
||||
environment,
|
||||
report: lines.join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
export type DiagnosticSendOutcome =
|
||||
| {
|
||||
ok: false;
|
||||
stage: "environment" | "registration";
|
||||
report: string;
|
||||
}
|
||||
| {
|
||||
ok: true;
|
||||
status: "sent" | "failed";
|
||||
report: string;
|
||||
diagnosticId: string;
|
||||
attemptedAt: string;
|
||||
history: "recorded" | "failed";
|
||||
message: PushDiagnosticMessage;
|
||||
};
|
||||
|
||||
async function defaultSend(message: PushDiagnosticMessage): Promise<string> {
|
||||
const { messaging } = await import("./firebase.js");
|
||||
return String(await messaging.send(message));
|
||||
}
|
||||
|
||||
function failureCode(err: unknown): string {
|
||||
const code = fcmFailureParts(err).errorCode;
|
||||
return code ?? "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Send one diagnostic notification to the registration named by DID and
|
||||
* device id. Refuses unless the environment check passes. A history-write
|
||||
* failure is logged and does not send again.
|
||||
*/
|
||||
export async function runDiagnosticSend(input: {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
now?: Date;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
send?: (message: PushDiagnosticMessage) => Promise<string>;
|
||||
record?: (row: AlertPushDeviceSendInput) => Promise<void>;
|
||||
onBeforeSend?: (info: {
|
||||
environment: Extract<DiagnosticEnvironmentResult, { ok: true }>;
|
||||
content: PushDiagnosticContent;
|
||||
row: StoredRow;
|
||||
}) => void;
|
||||
}): Promise<DiagnosticSendOutcome> {
|
||||
const environment = resolveDiagnosticEnvironment(input.env);
|
||||
if (!environment.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
stage: "environment",
|
||||
report: formatDiagnosticEnvironment(environment).join("\n"),
|
||||
};
|
||||
}
|
||||
const selected = await selectDiagnosticRegistration(input.userId, input.deviceId);
|
||||
if (!selected.ok) {
|
||||
return { ok: false, stage: "registration", report: selected.detail };
|
||||
}
|
||||
|
||||
const now = input.now ?? new Date();
|
||||
const content = buildPushDiagnosticContent({
|
||||
id: randomUUID(),
|
||||
at: now.toISOString(),
|
||||
});
|
||||
const message = buildPushDiagnosticMessage(selected.row.fcmToken, content);
|
||||
input.onBeforeSend?.({ environment, content, row: selected.row });
|
||||
|
||||
const sender = input.send ?? defaultSend;
|
||||
let outcome: FcmSendResult;
|
||||
const suffix = maskToken(selected.row.fcmToken);
|
||||
log.info("[PushDiagnostic] Send attempt, token suffix:", suffix);
|
||||
try {
|
||||
const rawId = await sender(message);
|
||||
const messageId = sanitizeFcmDiagnostic(String(rawId), selected.row.fcmToken, FCM_MESSAGE_ID_MAX_CHARS);
|
||||
outcome = messageId.length === 0 ? { status: "sent" } : { status: "sent", messageId };
|
||||
log.info("[PushDiagnostic] Send completed, token suffix:", suffix);
|
||||
} catch (err) {
|
||||
outcome = { status: "failed", ...fcmFailureParts(err, selected.row.fcmToken) };
|
||||
// The code only. The exception text can carry the token, a JWT, or a URL.
|
||||
log.error(
|
||||
"[PushDiagnostic] Send failed, token suffix:",
|
||||
suffix + ":",
|
||||
outcome.errorCode ?? "unknown"
|
||||
);
|
||||
}
|
||||
|
||||
const record = input.record ?? ((row) => alertPushDeviceSendsDb.appendMany([row]));
|
||||
let history: "recorded" | "failed" = "recorded";
|
||||
try {
|
||||
await record({
|
||||
userId: selected.row.userId,
|
||||
deviceId: selected.row.deviceId,
|
||||
platform: selected.row.platform,
|
||||
pushSendId: null,
|
||||
attemptedAt: content.data.at,
|
||||
outcome: outcome.status,
|
||||
fcmMessageId: outcome.messageId ?? null,
|
||||
fcmErrorCode: outcome.errorCode ?? null,
|
||||
// The FCM message text is not stored. It can contain a token or a credential.
|
||||
errorDetail: null,
|
||||
kind: "push_watch_test",
|
||||
});
|
||||
} catch (err) {
|
||||
history = "failed";
|
||||
log.error("[PushDiagnostic] History write failed:", failureCode(err));
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`Outcome: ${outcome.status === "sent" ? "accepted by FCM" : "rejected by FCM"}`,
|
||||
`DID: ${selected.row.userId}`,
|
||||
`Device: ${selected.row.deviceId}`,
|
||||
`Platform: ${selected.row.platform}`,
|
||||
`Token: ${maskRegistrationToken(selected.row.fcmToken)}`,
|
||||
`FCM message id: ${outcome.messageId ?? "-"}`,
|
||||
`FCM error code: ${outcome.errorCode ?? "-"}`,
|
||||
...formatPushDiagnosticPayload(content),
|
||||
history === "recorded"
|
||||
? "Device-attempt history: recorded as a diagnostic test. alert_push_sends was not written."
|
||||
: "Device-attempt history was not recorded. The FCM result stands; nothing was sent again.",
|
||||
];
|
||||
return {
|
||||
ok: true,
|
||||
status: outcome.status,
|
||||
report: lines.join("\n"),
|
||||
diagnosticId: content.data.id,
|
||||
attemptedAt: content.data.at,
|
||||
history,
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
/** `--name value` or `--name=value`. An empty value is treated as absent. */
|
||||
export function readFlag(argv: readonly string[], name: string): string | undefined {
|
||||
const prefix = `${name}=`;
|
||||
const inline = argv.find((arg) => arg.startsWith(prefix));
|
||||
if (inline !== undefined) {
|
||||
const value = inline.slice(prefix.length).trim();
|
||||
return value.length > 0 ? value : undefined;
|
||||
}
|
||||
const index = argv.indexOf(name);
|
||||
if (index === -1) return undefined;
|
||||
const value = argv[index + 1]?.trim();
|
||||
if (value === undefined || value.length === 0 || value.startsWith("--")) return undefined;
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Whether this process may send a diagnostic test push.
|
||||
*
|
||||
* A label by itself is not enough: MESSAGE_ENV_LABEL is typed by the operator,
|
||||
* and NODE_ENV is `production` on every Docker server. The send is allowed
|
||||
* only when that label is exactly `test` and the Firebase service-account
|
||||
* project id equals PUSH_TEST_FIREBASE_PROJECT_ID. Anything else is refused.
|
||||
* This does not change the process environment or the Firebase app.
|
||||
*/
|
||||
|
||||
export const PUSH_DIAGNOSTIC_TEST_LABEL = "test";
|
||||
export const PUSH_TEST_FIREBASE_PROJECT_ENV = "PUSH_TEST_FIREBASE_PROJECT_ID";
|
||||
|
||||
const PRODUCTION_LABELS = new Set(["production", "prod"]);
|
||||
|
||||
export type DiagnosticCredentialSource =
|
||||
| "FIREBASE_SERVICE_ACCOUNT_JSON"
|
||||
| "application_default"
|
||||
| "missing"
|
||||
| "unreadable";
|
||||
|
||||
export type DiagnosticEnvironmentObserved = {
|
||||
label: string | null;
|
||||
firebaseProjectId: string | null;
|
||||
expectedProjectId: string | null;
|
||||
credential: DiagnosticCredentialSource;
|
||||
};
|
||||
|
||||
export type DiagnosticEnvironmentOk = {
|
||||
ok: true;
|
||||
label: typeof PUSH_DIAGNOSTIC_TEST_LABEL;
|
||||
firebaseProjectId: string;
|
||||
credential: "FIREBASE_SERVICE_ACCOUNT_JSON";
|
||||
};
|
||||
|
||||
export type DiagnosticEnvironmentRefusal = {
|
||||
ok: false;
|
||||
/** production: the deployment is the production one. unknown: a fact is missing. ambiguous: the facts disagree. */
|
||||
classification: "production" | "unknown" | "ambiguous";
|
||||
reason: string;
|
||||
observed: DiagnosticEnvironmentObserved;
|
||||
};
|
||||
|
||||
export type DiagnosticEnvironmentResult = DiagnosticEnvironmentOk | DiagnosticEnvironmentRefusal;
|
||||
|
||||
function trimmed(value: string | undefined): string | null {
|
||||
if (value === undefined) return null;
|
||||
const text = value.trim();
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
function projectIdFromAccount(account: unknown): string | null {
|
||||
if (typeof account !== "object" || account === null) return null;
|
||||
const record = account as { project_id?: unknown; projectId?: unknown };
|
||||
if (typeof record.project_id === "string" && record.project_id.trim().length > 0) {
|
||||
return record.project_id.trim();
|
||||
}
|
||||
if (typeof record.projectId === "string" && record.projectId.trim().length > 0) {
|
||||
return record.projectId.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readCredential(env: NodeJS.ProcessEnv): {
|
||||
credential: DiagnosticCredentialSource;
|
||||
firebaseProjectId: string | null;
|
||||
} {
|
||||
const json = env.FIREBASE_SERVICE_ACCOUNT_JSON;
|
||||
if (json === undefined || json.trim().length === 0) {
|
||||
return {
|
||||
credential: env.GOOGLE_APPLICATION_CREDENTIALS ? "application_default" : "missing",
|
||||
firebaseProjectId: null,
|
||||
};
|
||||
}
|
||||
try {
|
||||
return {
|
||||
credential: "FIREBASE_SERVICE_ACCOUNT_JSON",
|
||||
firebaseProjectId: projectIdFromAccount(JSON.parse(json)),
|
||||
};
|
||||
} catch {
|
||||
return { credential: "unreadable", firebaseProjectId: null };
|
||||
}
|
||||
}
|
||||
|
||||
function refuse(
|
||||
classification: DiagnosticEnvironmentRefusal["classification"],
|
||||
reason: string,
|
||||
observed: DiagnosticEnvironmentObserved
|
||||
): DiagnosticEnvironmentRefusal {
|
||||
return { ok: false, classification, reason, observed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the label and the Firebase project. Does not initialize Firebase and
|
||||
* does not include the service-account key in the result.
|
||||
*/
|
||||
export function resolveDiagnosticEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): DiagnosticEnvironmentResult {
|
||||
const label = trimmed(env.MESSAGE_ENV_LABEL);
|
||||
const expectedProjectId = trimmed(env[PUSH_TEST_FIREBASE_PROJECT_ENV]);
|
||||
const credential = readCredential(env);
|
||||
const observed: DiagnosticEnvironmentObserved = {
|
||||
label,
|
||||
firebaseProjectId: credential.firebaseProjectId,
|
||||
expectedProjectId,
|
||||
credential: credential.credential,
|
||||
};
|
||||
|
||||
if (label === null) {
|
||||
return refuse(
|
||||
"production",
|
||||
"MESSAGE_ENV_LABEL is unset. Production leaves it unset, so a diagnostic send is refused.",
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (PRODUCTION_LABELS.has(label.toLowerCase())) {
|
||||
return refuse(
|
||||
"production",
|
||||
`MESSAGE_ENV_LABEL is "${label}", which is a production label.`,
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (label !== PUSH_DIAGNOSTIC_TEST_LABEL) {
|
||||
return refuse(
|
||||
"ambiguous",
|
||||
`MESSAGE_ENV_LABEL is "${label}". A diagnostic send requires it to be exactly "${PUSH_DIAGNOSTIC_TEST_LABEL}".`,
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (credential.credential === "missing" || credential.credential === "application_default") {
|
||||
return refuse(
|
||||
"unknown",
|
||||
"FIREBASE_SERVICE_ACCOUNT_JSON is unset, so the Firebase project cannot be verified. Application Default Credentials are not accepted for a diagnostic send.",
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (credential.credential === "unreadable") {
|
||||
return refuse(
|
||||
"unknown",
|
||||
"FIREBASE_SERVICE_ACCOUNT_JSON is not valid JSON, so the Firebase project cannot be verified.",
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (credential.firebaseProjectId === null) {
|
||||
return refuse(
|
||||
"unknown",
|
||||
"The Firebase service account has no project_id, so the project cannot be verified.",
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (expectedProjectId === null) {
|
||||
return refuse(
|
||||
"unknown",
|
||||
`${PUSH_TEST_FIREBASE_PROJECT_ENV} is unset, so the service-account project cannot be checked against the test project.`,
|
||||
observed
|
||||
);
|
||||
}
|
||||
if (credential.firebaseProjectId !== expectedProjectId) {
|
||||
return refuse(
|
||||
"ambiguous",
|
||||
`Firebase project "${credential.firebaseProjectId}" does not match ${PUSH_TEST_FIREBASE_PROJECT_ENV} "${expectedProjectId}".`,
|
||||
observed
|
||||
);
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
label: PUSH_DIAGNOSTIC_TEST_LABEL,
|
||||
firebaseProjectId: credential.firebaseProjectId,
|
||||
credential: "FIREBASE_SERVICE_ACCOUNT_JSON",
|
||||
};
|
||||
}
|
||||
|
||||
export function formatDiagnosticEnvironment(result: DiagnosticEnvironmentResult): string[] {
|
||||
if (result.ok) {
|
||||
return [
|
||||
"Environment: test",
|
||||
`Firebase project: ${result.firebaseProjectId}`,
|
||||
"Credential: FIREBASE_SERVICE_ACCOUNT_JSON",
|
||||
];
|
||||
}
|
||||
const observed = result.observed;
|
||||
return [
|
||||
`Diagnostic send refused (${result.classification}): ${result.reason}`,
|
||||
`Observed label: ${observed.label ?? "(unset)"}`,
|
||||
`Observed Firebase project: ${observed.firebaseProjectId ?? "(unverified)"}`,
|
||||
`Expected test project: ${observed.expectedProjectId ?? "(unset)"}`,
|
||||
`Credential source: ${observed.credential}`,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { withEnvLabel } from "../env.js";
|
||||
|
||||
/**
|
||||
* Data type for a diagnostic test notification. The app opens New Activity
|
||||
* only when `data.type` is `alert_search`, so this type is displayed and
|
||||
* otherwise ignored.
|
||||
*/
|
||||
export const PUSH_WATCH_TEST_TYPE = "push_watch_test";
|
||||
|
||||
export const PUSH_DIAGNOSTIC_TITLE = "TimeSafari Push Test";
|
||||
export const PUSH_DIAGNOSTIC_BODY = "This is a diagnostic notification.";
|
||||
|
||||
export type PushDiagnosticContent = {
|
||||
title: string;
|
||||
body: string;
|
||||
data: {
|
||||
type: typeof PUSH_WATCH_TEST_TYPE;
|
||||
id: string;
|
||||
at: string;
|
||||
};
|
||||
};
|
||||
|
||||
/** Notification plus data, without a device token. Preview and send both use this. */
|
||||
export function buildPushDiagnosticContent(input: {
|
||||
id: string;
|
||||
at: string;
|
||||
}): PushDiagnosticContent {
|
||||
return {
|
||||
title: PUSH_DIAGNOSTIC_TITLE,
|
||||
body: withEnvLabel(PUSH_DIAGNOSTIC_BODY),
|
||||
data: {
|
||||
type: PUSH_WATCH_TEST_TYPE,
|
||||
id: input.id,
|
||||
at: input.at,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The Firebase Admin message for one device. `data.type` is never `alert_search`. */
|
||||
export type PushDiagnosticMessage = {
|
||||
token: string;
|
||||
notification: { title: string; body: string };
|
||||
data: PushDiagnosticContent["data"];
|
||||
};
|
||||
|
||||
export function buildPushDiagnosticMessage(
|
||||
token: string,
|
||||
content: PushDiagnosticContent
|
||||
): PushDiagnosticMessage {
|
||||
return {
|
||||
token,
|
||||
notification: { title: content.title, body: content.body },
|
||||
data: content.data,
|
||||
};
|
||||
}
|
||||
|
||||
/** The payload fields safe to print. The device token is not one of them. */
|
||||
export function formatPushDiagnosticPayload(content: PushDiagnosticContent): string[] {
|
||||
return [
|
||||
`Title: ${content.title}`,
|
||||
`Body: ${content.body}`,
|
||||
`Data type: ${content.data.type}`,
|
||||
`Data id: ${content.data.id}`,
|
||||
`Data at: ${content.data.at}`,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Show the diagnostic notification that would be sent to a DID.
|
||||
* Does not send, does not initialize Firebase, and does not write the database.
|
||||
*
|
||||
* pnpm push:preview -- --did <DID>
|
||||
*/
|
||||
import "../env.js";
|
||||
import { previewDiagnosticPush, readFlag } from "../services/pushDiagnostic.js";
|
||||
|
||||
const did = readFlag(process.argv.slice(2), "--did");
|
||||
if (did === undefined) {
|
||||
console.error("Usage: pnpm push:preview -- --did <DID>");
|
||||
console.error("A DID is required. Nothing was sent.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const preview = await previewDiagnosticPush({ userId: did });
|
||||
console.log(preview.report);
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Send one diagnostic notification to one registration of one DID.
|
||||
* Refuses unless MESSAGE_ENV_LABEL is exactly `test` and the Firebase
|
||||
* service-account project id equals PUSH_TEST_FIREBASE_PROJECT_ID.
|
||||
* Does not write alert_push_sends and does not change the daily cap.
|
||||
*
|
||||
* pnpm push:test -- --did <DID> --device-id <DEVICE_ID>
|
||||
*/
|
||||
import "../env.js";
|
||||
import { maskRegistrationToken, readFlag, runDiagnosticSend } from "../services/pushDiagnostic.js";
|
||||
import { formatDiagnosticEnvironment } from "../services/pushDiagnosticEnv.js";
|
||||
import { formatPushDiagnosticPayload } from "../services/pushDiagnosticPayload.js";
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const did = readFlag(argv, "--did");
|
||||
const deviceId = readFlag(argv, "--device-id");
|
||||
if (did === undefined || deviceId === undefined) {
|
||||
console.error("Usage: pnpm push:test -- --did <DID> --device-id <DEVICE_ID>");
|
||||
console.error("Both a DID and a device id are required. Nothing was sent.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const outcome = await runDiagnosticSend({
|
||||
userId: did,
|
||||
deviceId,
|
||||
onBeforeSend(info) {
|
||||
console.log(
|
||||
[
|
||||
...formatDiagnosticEnvironment(info.environment),
|
||||
`DID: ${info.row.userId}`,
|
||||
`Device: ${info.row.deviceId}`,
|
||||
`Platform: ${info.row.platform}`,
|
||||
`Token: ${maskRegistrationToken(info.row.fcmToken)}`,
|
||||
...formatPushDiagnosticPayload(info.content),
|
||||
"Sending one diagnostic notification to this device.",
|
||||
].join("\n")
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
if (!outcome.ok || outcome.status !== "sent") {
|
||||
console.error(outcome.report);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(outcome.report);
|
||||
process.exit(0);
|
||||
+35
-2
@@ -9,7 +9,9 @@
|
||||
* notification was displayed. alert_push_device_sends is one row per device
|
||||
* Firebase accepted or rejected. Accepted means Firebase took the message,
|
||||
* not that the device received, displayed, or opened it. Those rows are not
|
||||
* the daily cap. last_notified_at is raw stored metadata and is not a
|
||||
* the daily cap. A diagnostic test push is the same table with kind
|
||||
* push_watch_test, a null push_send_id, and no alert_push_sends row.
|
||||
* last_notified_at is raw stored metadata and is not a
|
||||
* delivery indicator. A registration quiet for 30 days is a warning, not
|
||||
* proof that Firebase invalidated the token.
|
||||
*
|
||||
@@ -63,7 +65,7 @@ const WEEK_MS = 7 * DAY_MS;
|
||||
const SEND_LIMITATION =
|
||||
"alert_push_sends is a DID-level record written when a push reached at least one device. It does not record which device, FCM errors, or that the notification was displayed.";
|
||||
const DEVICE_ATTEMPT_LIMITATION =
|
||||
"alert_push_device_sends is one row per registered device included in an AlertSearch FCM send. Accepted means Firebase took the message. It does not mean the device received, displayed, or opened it. These rows are not the daily-cap record; alert_push_sends is.";
|
||||
"alert_push_device_sends is one row per registered device included in an AlertSearch FCM send, or one diagnostic test push. Accepted means Firebase took the message. It does not mean the device received, displayed, or opened it. These rows are not the daily-cap record; alert_push_sends is. A diagnostic row does not write that table.";
|
||||
const SCHEDULER_LIMITATION =
|
||||
"Scheduler history lists only users listPendingForDay returned (an unused JWT for the day). A user without one is not a candidate and has no row; see Authorizations. fcm_accepted means Firebase accepted at least one device, not that it was displayed. Rows are kept 30 days.";
|
||||
const STALE_LIMITATION =
|
||||
@@ -368,15 +370,28 @@ export type DeviceAttemptInput = {
|
||||
fcmMessageId: string | null;
|
||||
fcmErrorCode: string | null;
|
||||
errorDetail: string | null;
|
||||
/** Absent or anything other than push_watch_test is an AlertSearch attempt. */
|
||||
kind?: string | null;
|
||||
};
|
||||
|
||||
export type DeviceAttemptSummary = {
|
||||
total: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
alertSearch: number;
|
||||
diagnostic: number;
|
||||
mostRecentAt?: string;
|
||||
};
|
||||
|
||||
/** Diagnostic rows are marked push_watch_test. Every other value is an AlertSearch attempt. */
|
||||
export function deviceAttemptKind(row: { kind?: string | null }): "alert_search" | "push_watch_test" {
|
||||
return row.kind === "push_watch_test" ? "push_watch_test" : "alert_search";
|
||||
}
|
||||
|
||||
export function deviceAttemptKindLabel(row: { kind?: string | null }): string {
|
||||
return deviceAttemptKind(row) === "push_watch_test" ? "diagnostic test" : "AlertSearch";
|
||||
}
|
||||
|
||||
/** One FCM scheduler pass. Counts and safe codes only; no user content. */
|
||||
export type SchedulerPassRow = {
|
||||
id: string;
|
||||
@@ -787,14 +802,20 @@ export function summarizeDeviceAttempts(
|
||||
): DeviceAttemptSummary {
|
||||
let succeeded = 0;
|
||||
let failed = 0;
|
||||
let alertSearch = 0;
|
||||
let diagnostic = 0;
|
||||
for (const row of rows) {
|
||||
if (row.outcome === "sent") succeeded += 1;
|
||||
else if (row.outcome === "failed") failed += 1;
|
||||
if (deviceAttemptKind(row) === "push_watch_test") diagnostic += 1;
|
||||
else alertSearch += 1;
|
||||
}
|
||||
return {
|
||||
total: rows.length,
|
||||
succeeded,
|
||||
failed,
|
||||
alertSearch,
|
||||
diagnostic,
|
||||
mostRecentAt: latestParsedIso(
|
||||
rows.map((row) => row.attemptedAt),
|
||||
now.getTime()
|
||||
@@ -1292,6 +1313,8 @@ function deviceAttemptSummaryLines(rows: readonly DeviceAttemptInput[], now: Dat
|
||||
`Device attempts: ${summary.total}`,
|
||||
`Device attempts accepted by FCM: ${summary.succeeded}`,
|
||||
`Device attempts rejected by FCM: ${summary.failed}`,
|
||||
`AlertSearch attempts: ${summary.alertSearch}`,
|
||||
`Diagnostic test attempts: ${summary.diagnostic}`,
|
||||
`Most recent device attempt: ${summary.mostRecentAt ?? "none"}`,
|
||||
DEVICE_ATTEMPT_LIMITATION,
|
||||
];
|
||||
@@ -1308,6 +1331,7 @@ export function deviceAttemptLine(row: DeviceAttemptInput): string {
|
||||
stamp(row.attemptedAt),
|
||||
abbreviateMiddle(row.userId),
|
||||
abbreviateMiddle(row.deviceId, 8, 4),
|
||||
deviceAttemptKindLabel(row),
|
||||
row.platform ?? "-",
|
||||
`fcm=${fcmOutcomeLabel(row.outcome)}`,
|
||||
row.fcmMessageId ? `id=${row.fcmMessageId}` : "id=-",
|
||||
@@ -1326,6 +1350,7 @@ export function deviceAttemptDetail(row: DeviceAttemptInput): string[] {
|
||||
`attempted_at: ${row.attemptedAt}`,
|
||||
`DID: ${show(row.userId)}`,
|
||||
`Device ID: ${show(row.deviceId)}`,
|
||||
`Attempt kind: ${deviceAttemptKindLabel(row)}`,
|
||||
`Platform: ${row.platform ?? "-"}`,
|
||||
`FCM outcome: ${label}`,
|
||||
`FCM message ID: ${row.fcmMessageId ?? "-"}`,
|
||||
@@ -1766,6 +1791,7 @@ type DeviceAttemptDb = {
|
||||
fcm_message_id: string | null;
|
||||
fcm_error_code: string | null;
|
||||
error_detail: string | null;
|
||||
kind?: string | null;
|
||||
};
|
||||
|
||||
type SchedulerPassDb = {
|
||||
@@ -2013,11 +2039,16 @@ export function loadSnapshot(
|
||||
sentAt: row.sent_at,
|
||||
}));
|
||||
|
||||
const deviceAttemptColumns = db
|
||||
.prepare(`PRAGMA table_info(alert_push_device_sends)`)
|
||||
.all() as { name: string }[];
|
||||
const deviceAttemptKindColumn = deviceAttemptColumns.some((column) => column.name === "kind");
|
||||
const deviceAttempts = (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail
|
||||
${deviceAttemptKindColumn ? ", kind" : ""}
|
||||
FROM alert_push_device_sends`
|
||||
)
|
||||
.all() as DeviceAttemptDb[]
|
||||
@@ -2031,6 +2062,8 @@ export function loadSnapshot(
|
||||
fcmMessageId: row.fcm_message_id,
|
||||
fcmErrorCode: row.fcm_error_code,
|
||||
errorDetail: row.error_detail,
|
||||
// A database from before this column has only AlertSearch attempts.
|
||||
kind: deviceAttemptKindColumn ? row.kind ?? "alert_search" : "alert_search",
|
||||
}));
|
||||
|
||||
// With --did, that DID's rows across the newest passes. Otherwise the users
|
||||
|
||||
@@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, it } from "node:test";
|
||||
import Database from "better-sqlite3";
|
||||
import { alertPushDeviceSendsDb } from "../../src/db/alertPushDeviceSendsSqlite.js";
|
||||
import { ALERT_PUSH_SEND_RETENTION_DAYS, alertPushSendsDb } from "../../src/db/alertPushSendsSqlite.js";
|
||||
import { closeDatabase, getDatabase } from "../../src/db/sqlite.js";
|
||||
@@ -42,6 +43,7 @@ describe("alert_push_device_sends", () => {
|
||||
"fcm_message_id",
|
||||
"fcm_error_code",
|
||||
"error_detail",
|
||||
"kind",
|
||||
]
|
||||
);
|
||||
assert.equal(columns.some((column) => column.name === "fcm_token"), false);
|
||||
@@ -128,6 +130,46 @@ describe("alert_push_device_sends", () => {
|
||||
assert.equal(rows[1].error_detail, null);
|
||||
const capRows = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
|
||||
assert.equal(capRows.n, 0);
|
||||
const kinds = getDatabase()
|
||||
.prepare(`SELECT device_id, kind FROM alert_push_device_sends ORDER BY device_id`)
|
||||
.all() as { device_id: string; kind: string }[];
|
||||
assert.deepEqual(kinds, [
|
||||
{ device_id: "phone-bad", kind: "alert_search" },
|
||||
{ device_id: "phone-ok", kind: "alert_search" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies rows written before the kind column as AlertSearch attempts", async () => {
|
||||
closeDatabase();
|
||||
const file = path.join(dir, "notify.sqlite");
|
||||
const raw = new Database(file);
|
||||
raw.exec(`
|
||||
CREATE TABLE alert_push_device_sends (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
device_id TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
push_send_id TEXT,
|
||||
attempted_at TEXT NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
fcm_message_id TEXT,
|
||||
fcm_error_code TEXT,
|
||||
error_detail TEXT
|
||||
);
|
||||
`);
|
||||
raw.prepare(
|
||||
`INSERT INTO alert_push_device_sends (
|
||||
id, user_id, device_id, platform, push_send_id, attempted_at, outcome,
|
||||
fcm_message_id, fcm_error_code, error_detail
|
||||
) VALUES ('old', 'did:example:old', 'phone', 'ios', 'send-1', ?, 'sent', 'msg', NULL, NULL)`
|
||||
).run("2026-11-01T00:00:00.000Z");
|
||||
raw.close();
|
||||
|
||||
const row = getDatabase()
|
||||
.prepare(`SELECT kind, push_send_id FROM alert_push_device_sends WHERE id = 'old'`)
|
||||
.get() as { kind: string; push_send_id: string };
|
||||
assert.equal(row.kind, "alert_search");
|
||||
assert.equal(row.push_send_id, "send-1");
|
||||
});
|
||||
|
||||
it("drops this identity's device rows past the retention window", async () => {
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
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 {
|
||||
decideDiagnosticRegistration,
|
||||
maskRegistrationToken,
|
||||
previewDiagnosticPush,
|
||||
runDiagnosticSend,
|
||||
} from "../../src/services/pushDiagnostic.js";
|
||||
import { resolveDiagnosticEnvironment } from "../../src/services/pushDiagnosticEnv.js";
|
||||
import {
|
||||
PUSH_DIAGNOSTIC_BODY,
|
||||
PUSH_DIAGNOSTIC_TITLE,
|
||||
PUSH_WATCH_TEST_TYPE,
|
||||
buildPushDiagnosticContent,
|
||||
buildPushDiagnosticMessage,
|
||||
} from "../../src/services/pushDiagnosticPayload.js";
|
||||
import { maskFcmToken } from "../../src/tools/pushWatch.js";
|
||||
import type { StoredRow } from "../../src/db/fcmTokensSqlite.js";
|
||||
|
||||
const DID = "did:example:preview";
|
||||
const OTHER = "did:example:other";
|
||||
const DEVICE = "phone-1";
|
||||
const TOKEN = "abcdUNIQUESECRET9876wxyz";
|
||||
const PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----SENTINELPRIVATEKEY";
|
||||
const JWT = "eyJhbGciOiJIUzI1NiJ9.UNIQUEJWTSECRET.signaturevalue";
|
||||
const NOW = new Date("2026-11-16T08:00:00.000Z");
|
||||
const PROJECT = "timesafari-test";
|
||||
|
||||
const ENV_KEYS = [
|
||||
"MESSAGE_ENV_LABEL",
|
||||
"PUSH_TEST_FIREBASE_PROJECT_ID",
|
||||
"FIREBASE_SERVICE_ACCOUNT_JSON",
|
||||
"GOOGLE_APPLICATION_CREDENTIALS",
|
||||
"NOTIFY_DATA_DIR",
|
||||
] as const;
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const tsx = path.join(root, "node_modules/.bin/tsx");
|
||||
|
||||
function serviceAccount(projectId: string): string {
|
||||
return JSON.stringify({
|
||||
type: "service_account",
|
||||
project_id: projectId,
|
||||
private_key: PRIVATE_KEY,
|
||||
client_email: "push-test@timesafari-test.iam.gserviceaccount.com",
|
||||
});
|
||||
}
|
||||
|
||||
function row(partial: Partial<StoredRow> & Pick<StoredRow, "userId" | "deviceId">): StoredRow {
|
||||
return {
|
||||
id: "reg-1",
|
||||
fcmToken: TOKEN,
|
||||
platform: "android",
|
||||
createdAt: NOW.toISOString(),
|
||||
updatedAt: NOW.toISOString(),
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
function assertNoSecrets(text: string): void {
|
||||
assert.equal(text.includes(TOKEN), false);
|
||||
assert.equal(text.includes("UNIQUESECRET"), false);
|
||||
assert.equal(text.includes(PRIVATE_KEY), false);
|
||||
assert.equal(text.includes("SENTINELPRIVATEKEY"), false);
|
||||
assert.equal(text.includes(JWT), false);
|
||||
assert.equal(text.includes("UNIQUEJWTSECRET"), false);
|
||||
}
|
||||
|
||||
describe("diagnostic environment", () => {
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
for (const key of ENV_KEYS) {
|
||||
saved[key] = process.env[key];
|
||||
delete process.env[key];
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of ENV_KEYS) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
});
|
||||
|
||||
function allowTest(projectId = PROJECT): void {
|
||||
process.env.MESSAGE_ENV_LABEL = "test";
|
||||
process.env.PUSH_TEST_FIREBASE_PROJECT_ID = projectId;
|
||||
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = serviceAccount(projectId);
|
||||
}
|
||||
|
||||
it("accepts a test label only when it matches the service-account project", () => {
|
||||
allowTest();
|
||||
const result = resolveDiagnosticEnvironment();
|
||||
assert.equal(result.ok, true);
|
||||
if (result.ok) {
|
||||
assert.equal(result.firebaseProjectId, PROJECT);
|
||||
assert.equal(result.label, "test");
|
||||
}
|
||||
const text = JSON.stringify(result);
|
||||
assertNoSecrets(text);
|
||||
});
|
||||
|
||||
it("refuses production, unknown, and ambiguous configurations", () => {
|
||||
const cases: Array<{ name: string; setup: () => void; classification: string }> = [
|
||||
{
|
||||
name: "unset label",
|
||||
setup: () => allowTest(),
|
||||
classification: "production",
|
||||
},
|
||||
{
|
||||
name: "production label",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.MESSAGE_ENV_LABEL = "production";
|
||||
},
|
||||
classification: "production",
|
||||
},
|
||||
{
|
||||
name: "prod label",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.MESSAGE_ENV_LABEL = "prod";
|
||||
},
|
||||
classification: "production",
|
||||
},
|
||||
{
|
||||
name: "no service account",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
delete process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
|
||||
process.env.GOOGLE_APPLICATION_CREDENTIALS = "/tmp/adc.json";
|
||||
},
|
||||
classification: "unknown",
|
||||
},
|
||||
{
|
||||
name: "unreadable service account",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = "not-json";
|
||||
},
|
||||
classification: "unknown",
|
||||
},
|
||||
{
|
||||
name: "service account without a project",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = JSON.stringify({ type: "service_account", private_key: PRIVATE_KEY });
|
||||
},
|
||||
classification: "unknown",
|
||||
},
|
||||
{
|
||||
name: "expected project unset",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
delete process.env.PUSH_TEST_FIREBASE_PROJECT_ID;
|
||||
},
|
||||
classification: "unknown",
|
||||
},
|
||||
{
|
||||
name: "label is not test",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.MESSAGE_ENV_LABEL = "staging";
|
||||
},
|
||||
classification: "ambiguous",
|
||||
},
|
||||
{
|
||||
name: "project ids differ",
|
||||
setup: () => {
|
||||
allowTest();
|
||||
process.env.PUSH_TEST_FIREBASE_PROJECT_ID = "some-other-project";
|
||||
},
|
||||
classification: "ambiguous",
|
||||
},
|
||||
];
|
||||
|
||||
for (const entry of cases) {
|
||||
for (const key of ENV_KEYS) delete process.env[key];
|
||||
entry.setup();
|
||||
if (entry.name === "unset label") delete process.env.MESSAGE_ENV_LABEL;
|
||||
const result = resolveDiagnosticEnvironment();
|
||||
assert.equal(result.ok, false, entry.name);
|
||||
if (!result.ok) assert.equal(result.classification, entry.classification, entry.name);
|
||||
assertNoSecrets(JSON.stringify(result));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("diagnostic registration selection", () => {
|
||||
it("rejects a missing registration, an inactive token, another DID, and an ambiguous pair", () => {
|
||||
const missing = decideDiagnosticRegistration(DID, DEVICE, []);
|
||||
assert.equal(missing.ok, false);
|
||||
if (!missing.ok) assert.equal(missing.reason, "missing");
|
||||
|
||||
const blank = decideDiagnosticRegistration(DID, DEVICE, [row({ userId: DID, deviceId: DEVICE, fcmToken: " " })]);
|
||||
assert.equal(blank.ok, false);
|
||||
if (!blank.ok) assert.equal(blank.reason, "inactive");
|
||||
|
||||
const other = decideDiagnosticRegistration(DID, DEVICE, [row({ userId: OTHER, deviceId: DEVICE })]);
|
||||
assert.equal(other.ok, false);
|
||||
if (!other.ok) {
|
||||
assert.equal(other.reason, "other_did");
|
||||
assertNoSecrets(other.detail);
|
||||
}
|
||||
|
||||
const ambiguous = decideDiagnosticRegistration(DID, DEVICE, [
|
||||
row({ userId: DID, deviceId: DEVICE, id: "a" }),
|
||||
row({ userId: DID, deviceId: DEVICE, id: "b", fcmToken: "zzzzUNIQUESECRET9876yyyy" }),
|
||||
]);
|
||||
assert.equal(ambiguous.ok, false);
|
||||
if (!ambiguous.ok) {
|
||||
assert.equal(ambiguous.reason, "ambiguous");
|
||||
assertNoSecrets(ambiguous.detail);
|
||||
}
|
||||
|
||||
const selected = decideDiagnosticRegistration(DID, DEVICE, [
|
||||
row({ userId: OTHER, deviceId: DEVICE, fcmToken: "other-token-UNIQUESECRET-value" }),
|
||||
row({ userId: DID, deviceId: DEVICE }),
|
||||
]);
|
||||
assert.equal(selected.ok, true);
|
||||
if (selected.ok) assert.equal(selected.row.fcmToken, TOKEN);
|
||||
});
|
||||
|
||||
it("masks a registration token the same way push:watch does", () => {
|
||||
assert.equal(maskRegistrationToken(TOKEN), maskFcmToken(TOKEN));
|
||||
assert.equal(maskRegistrationToken(TOKEN).includes("UNIQUESECRET"), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("diagnostic preview and send", () => {
|
||||
let dir: string;
|
||||
let previous: Record<string, string | undefined>;
|
||||
|
||||
beforeEach(async () => {
|
||||
previous = {};
|
||||
for (const key of ENV_KEYS) previous[key] = process.env[key];
|
||||
dir = await mkdtemp(path.join(tmpdir(), "push-diagnostic-"));
|
||||
process.env.NOTIFY_DATA_DIR = dir;
|
||||
process.env.MESSAGE_ENV_LABEL = "test";
|
||||
process.env.PUSH_TEST_FIREBASE_PROJECT_ID = PROJECT;
|
||||
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = serviceAccount(PROJECT);
|
||||
delete process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
closeDatabase();
|
||||
for (const key of ENV_KEYS) {
|
||||
if (previous[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = previous[key];
|
||||
}
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function register(userId: string, deviceId: string, fcmToken = TOKEN, platform = "android"): Promise<void> {
|
||||
await db.upsert({ userId, deviceId, fcmToken, platform, updatedAt: NOW });
|
||||
}
|
||||
|
||||
it("previews the shared payload and does not send or write", async () => {
|
||||
await register(DID, DEVICE);
|
||||
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 calls: unknown[] = [];
|
||||
const preview = await previewDiagnosticPush({ userId: DID, now: NOW });
|
||||
assert.equal(calls.length, 0);
|
||||
assert.equal(preview.eligible.length, 2);
|
||||
assert.match(preview.report, /Preview only\. No FCM message was sent\./);
|
||||
assert.match(preview.report, /Eligible devices: 2/);
|
||||
assert.match(preview.report, /Environment: test/);
|
||||
assert.match(preview.report, new RegExp(PROJECT));
|
||||
assert.match(preview.report, /phone-1/);
|
||||
assert.match(preview.report, /android/);
|
||||
assert.match(preview.report, new RegExp(PUSH_DIAGNOSTIC_TITLE));
|
||||
assert.match(preview.report, /This is a diagnostic notification\. \(test\)/);
|
||||
assert.match(preview.report, new RegExp(`Data type: ${PUSH_WATCH_TEST_TYPE}`));
|
||||
assert.doesNotMatch(preview.report, /Data type: alert_search/);
|
||||
assertNoSecrets(preview.report);
|
||||
const message = buildPushDiagnosticMessage(TOKEN, preview.content);
|
||||
assert.deepEqual(message.notification, { title: preview.content.title, body: preview.content.body });
|
||||
assert.deepEqual(message.data, preview.content.data);
|
||||
assert.equal(message.data.type, PUSH_WATCH_TEST_TYPE);
|
||||
assert.notEqual(message.data.type, "alert_search");
|
||||
const sendsAfter = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
|
||||
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);
|
||||
|
||||
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("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");
|
||||
await register(OTHER, DEVICE, "otherUNIQUESECRET9876token", "android");
|
||||
await alertPushSendsDb.append({ userId: DID, batchId: "batch-1", sentAt: "2026-11-16T01:00:00.000Z" });
|
||||
const capBefore = await alertPushSendsDb.countSince(DID, "2026-11-16T00:00:00.000Z");
|
||||
|
||||
const sent: unknown[] = [];
|
||||
const logs: string[] = [];
|
||||
const originalError = console.error;
|
||||
const originalLog = console.log;
|
||||
console.error = (...args: unknown[]) => {
|
||||
logs.push(args.map(String).join(" "));
|
||||
};
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map(String).join(" "));
|
||||
};
|
||||
let outcome;
|
||||
try {
|
||||
outcome = await runDiagnosticSend({
|
||||
userId: DID,
|
||||
deviceId: DEVICE,
|
||||
now: NOW,
|
||||
send: async (message) => {
|
||||
sent.push(message);
|
||||
if (sent.length > 1) throw new Error("resent");
|
||||
return "projects/timesafari-test/messages/msg-1";
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
console.log = originalLog;
|
||||
}
|
||||
|
||||
assert.equal(outcome.ok, true);
|
||||
if (!outcome.ok) return;
|
||||
assert.equal(outcome.status, "sent");
|
||||
assert.equal(sent.length, 1);
|
||||
const expected = buildPushDiagnosticMessage(
|
||||
TOKEN,
|
||||
buildPushDiagnosticContent({ id: outcome.diagnosticId, at: outcome.attemptedAt })
|
||||
);
|
||||
assert.deepEqual(sent[0], expected);
|
||||
assert.equal(expected.data.type, PUSH_WATCH_TEST_TYPE);
|
||||
assert.equal(expected.notification.title, PUSH_DIAGNOSTIC_TITLE);
|
||||
assert.equal(expected.notification.body, `${PUSH_DIAGNOSTIC_BODY} (test)`);
|
||||
assert.equal(outcome.history, "recorded");
|
||||
assertNoSecrets(outcome.report);
|
||||
assertNoSecrets(logs.join("\n"));
|
||||
|
||||
const attempts = getDatabase()
|
||||
.prepare(
|
||||
`SELECT user_id, device_id, platform, push_send_id, outcome, fcm_message_id, kind
|
||||
FROM alert_push_device_sends`
|
||||
)
|
||||
.all() as Array<Record<string, unknown>>;
|
||||
assert.deepEqual(attempts, [
|
||||
{
|
||||
user_id: DID,
|
||||
device_id: DEVICE,
|
||||
platform: "android",
|
||||
push_send_id: null,
|
||||
outcome: "sent",
|
||||
fcm_message_id: "projects/timesafari-test/messages/msg-1",
|
||||
kind: "push_watch_test",
|
||||
},
|
||||
]);
|
||||
const capAfter = await alertPushSendsDb.countSince(DID, "2026-11-16T00:00:00.000Z");
|
||||
assert.equal(capBefore, 1);
|
||||
assert.equal(capAfter, 1);
|
||||
const sendRows = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
|
||||
assert.equal(sendRows.n, 1);
|
||||
});
|
||||
|
||||
it("does not send when the environment or the registration is refused", async () => {
|
||||
await register(OTHER, DEVICE);
|
||||
const sent: unknown[] = [];
|
||||
const send = async (message: unknown) => {
|
||||
sent.push(message);
|
||||
return "msg";
|
||||
};
|
||||
|
||||
const otherDid = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
|
||||
assert.equal(otherDid.ok, false);
|
||||
if (!otherDid.ok) assert.equal(otherDid.stage, "registration");
|
||||
|
||||
const missing = await runDiagnosticSend({ userId: DID, deviceId: "missing-phone", now: NOW, send });
|
||||
assert.equal(missing.ok, false);
|
||||
|
||||
process.env.MESSAGE_ENV_LABEL = "production";
|
||||
const production = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
|
||||
assert.equal(production.ok, false);
|
||||
if (!production.ok) {
|
||||
assert.equal(production.stage, "environment");
|
||||
assert.match(production.report, /production/);
|
||||
assertNoSecrets(production.report);
|
||||
}
|
||||
|
||||
process.env.MESSAGE_ENV_LABEL = "test";
|
||||
process.env.PUSH_TEST_FIREBASE_PROJECT_ID = "production-project";
|
||||
const ambiguous = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
|
||||
assert.equal(ambiguous.ok, false);
|
||||
if (!ambiguous.ok) assert.match(ambiguous.report, /ambiguous/);
|
||||
|
||||
delete process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
|
||||
const unknown = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
|
||||
assert.equal(unknown.ok, false);
|
||||
if (!unknown.ok) assert.match(unknown.report, /unknown/);
|
||||
assert.equal(sent.length, 0);
|
||||
});
|
||||
|
||||
it("records a failure without the token and does not resend when history writing throws", async () => {
|
||||
await register(DID, DEVICE);
|
||||
let calls = 0;
|
||||
const logs: string[] = [];
|
||||
const originalError = console.error;
|
||||
console.error = (...args: unknown[]) => {
|
||||
logs.push(args.map(String).join(" "));
|
||||
};
|
||||
let outcome;
|
||||
try {
|
||||
outcome = await runDiagnosticSend({
|
||||
userId: DID,
|
||||
deviceId: DEVICE,
|
||||
now: NOW,
|
||||
send: async () => {
|
||||
calls += 1;
|
||||
throw Object.assign(new Error(`token ${TOKEN} jwt ${JWT} rejected`), {
|
||||
code: "messaging/invalid-argument",
|
||||
});
|
||||
},
|
||||
record: async () => {
|
||||
throw Object.assign(new Error(`disk full ${TOKEN}`), { code: "SQLITE_FULL" });
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
}
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(outcome.ok, true);
|
||||
if (!outcome.ok) return;
|
||||
assert.equal(outcome.status, "failed");
|
||||
assert.equal(outcome.history, "failed");
|
||||
assert.match(outcome.report, /messaging\/invalid-argument/);
|
||||
assert.match(outcome.report, /nothing was sent again/);
|
||||
assertNoSecrets(outcome.report);
|
||||
assertNoSecrets(logs.join("\n"));
|
||||
assert.match(logs.join("\n"), /messaging\/invalid-argument/);
|
||||
assert.match(logs.join("\n"), /SQLITE_FULL/);
|
||||
const attempts = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_device_sends`).get() as { n: number };
|
||||
const sends = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
|
||||
assert.equal(attempts.n, 0);
|
||||
assert.equal(sends.n, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("push preview and test commands", () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "push-diagnostic-cli-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
closeDatabase();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function run(script: string, args: string[], env: NodeJS.ProcessEnv): { status: number | null; stdout: string; stderr: string } {
|
||||
const result = spawnSync(tsx, [path.join(root, script), ...args], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
timeout: 20000,
|
||||
env,
|
||||
});
|
||||
return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
||||
}
|
||||
|
||||
it("requires a DID for preview and does not initialize Firebase", async () => {
|
||||
const missing = run("src/tools/pushPreview.ts", [], { ...process.env, NOTIFY_DATA_DIR: dir });
|
||||
assert.equal(missing.status, 1);
|
||||
assert.match(missing.stderr, /--did/);
|
||||
assert.match(missing.stderr, /Nothing was sent/);
|
||||
|
||||
const databaseDir = path.join(dir, "db");
|
||||
process.env.NOTIFY_DATA_DIR = databaseDir;
|
||||
closeDatabase();
|
||||
await db.upsert({
|
||||
userId: DID,
|
||||
deviceId: DEVICE,
|
||||
fcmToken: TOKEN,
|
||||
platform: "android",
|
||||
updatedAt: NOW,
|
||||
});
|
||||
closeDatabase();
|
||||
delete process.env.NOTIFY_DATA_DIR;
|
||||
|
||||
const preview = run("src/tools/pushPreview.ts", ["--did", DID], {
|
||||
...process.env,
|
||||
NOTIFY_DATA_DIR: databaseDir,
|
||||
MESSAGE_ENV_LABEL: "test",
|
||||
PUSH_TEST_FIREBASE_PROJECT_ID: PROJECT,
|
||||
// A credential Firebase could not initialize. Preview must not load it.
|
||||
FIREBASE_SERVICE_ACCOUNT_JSON: JSON.stringify({ project_id: PROJECT }),
|
||||
});
|
||||
assert.equal(preview.status, 0, preview.stderr);
|
||||
assert.match(preview.stdout, /Preview only\. No FCM message was sent\./);
|
||||
assert.match(preview.stdout, new RegExp(`Data type: ${PUSH_WATCH_TEST_TYPE}`));
|
||||
assert.match(preview.stdout, new RegExp(PUSH_DIAGNOSTIC_TITLE));
|
||||
assert.equal(preview.stdout.includes(TOKEN), false);
|
||||
assert.equal(preview.stderr.includes("[Firebase]"), false);
|
||||
assert.doesNotMatch(preview.stdout, /Data type: alert_search/);
|
||||
|
||||
const tool = readFileSync(path.join(root, "src/tools/pushPreview.ts"), "utf8");
|
||||
assert.equal(tool.includes("firebase"), false);
|
||||
assert.equal(tool.includes("messaging"), false);
|
||||
});
|
||||
|
||||
it("requires both a DID and a device id before a test send", () => {
|
||||
const env = { ...process.env, NOTIFY_DATA_DIR: dir, MESSAGE_ENV_LABEL: "production" };
|
||||
const noDid = run("src/tools/pushTest.ts", ["--device-id", DEVICE], env);
|
||||
assert.equal(noDid.status, 1);
|
||||
assert.match(noDid.stderr, /--did/);
|
||||
assert.match(noDid.stderr, /--device-id/);
|
||||
assert.match(noDid.stderr, /Nothing was sent/);
|
||||
const noDevice = run("src/tools/pushTest.ts", ["--did", DID], env);
|
||||
assert.equal(noDevice.status, 1);
|
||||
assert.match(noDevice.stderr, /Nothing was sent/);
|
||||
assert.equal(noDid.stdout.includes(TOKEN), false);
|
||||
assert.equal(noDevice.stderr.includes("[Firebase]"), false);
|
||||
});
|
||||
});
|
||||
@@ -719,6 +719,27 @@ describe("push:watch CLI", () => {
|
||||
assert.equal(logicalDump(dbPath), before);
|
||||
assert.equal(hashFile(dbPath), hash);
|
||||
});
|
||||
|
||||
it("labels AlertSearch attempts and diagnostic test pushes separately", () => {
|
||||
const dbPath = createDatabase((db) => {
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO alert_push_device_sends (
|
||||
id, user_id, device_id, platform, push_send_id, attempted_at,
|
||||
outcome, fcm_message_id, fcm_error_code, error_detail, kind
|
||||
) VALUES (?, 'did:example:kind', ?, 'android', ?, ?, ?, NULL, NULL, NULL, ?)`
|
||||
);
|
||||
insert.run("alert-row", "phone-a", "send-1", "2026-11-12T14:00:00.000Z", "sent", "alert_search");
|
||||
insert.run("test-row", "phone-b", null, "2026-11-12T15:00:00.000Z", "sent", "push_watch_test");
|
||||
});
|
||||
const before = logicalDump(dbPath);
|
||||
const result = run(["--once", "--db", dbPath, "--did", "did:example:kind"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /AlertSearch attempts: 1/);
|
||||
assert.match(result.stdout, /Diagnostic test attempts: 1/);
|
||||
assert.match(result.stdout, /Attempt kind: AlertSearch/);
|
||||
assert.match(result.stdout, /Attempt kind: diagnostic test/);
|
||||
assert.equal(logicalDump(dbPath), before);
|
||||
});
|
||||
});
|
||||
|
||||
const SCHEMA = `
|
||||
@@ -781,7 +802,8 @@ CREATE TABLE alert_push_device_sends (
|
||||
outcome TEXT NOT NULL,
|
||||
fcm_message_id TEXT,
|
||||
fcm_error_code TEXT,
|
||||
error_detail TEXT
|
||||
error_detail TEXT,
|
||||
kind TEXT NOT NULL DEFAULT 'alert_search'
|
||||
);
|
||||
CREATE TABLE alert_search_scheduler_passes (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
|
||||
Reference in New Issue
Block a user