Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): refuse a restore whose template names collide without NUL

Yudhi Armyndharis843d9c1b538a
diff --git a/src/modules/infra/table-importers.spec.ts b/src/modules/infra/table-importers.spec.ts
index 4b9f08954..4cdde343c 100644
--- a/src/modules/infra/table-importers.spec.ts
+++ b/src/modules/infra/table-importers.spec.ts
@@ -117,6 +117,34 @@ describe('automationRules table importer', () => {
});
});
+/**
+ * A template name loses its NUL characters on restore, and (sessionId, name) is unique. Two names of
+ * one session that differ only by NUL would collide on insert and roll the restore back, so the
+ * guard refuses the second one up front and names both rows.
+ */
+describe('templates table importer', () => {
+ const templates = TABLE_IMPORTERS.find(importer => importer.key === 'templates');
+ const rows = [
+ { id: 't1', sessionId: 's1', name: 'promo' },
+ { id: 't2', sessionId: 's1', name: 'promo\u0000' },
+ { id: 't3', sessionId: 's2', name: 'promo' },
+ { id: 't4', sessionId: 's1', name: 'other' },
+ ];
+ const skip = (row: Record<string, unknown>) => templates?.skip?.(row as never, rows as never);
+
+ it('refuses a name that matches another template of the same session once NUL is dropped', () => {
+ expect(skip(rows[1])).toBe(
+ 'Skipped template t2: name "promo" without NUL characters collides with template t1 of session s1',
+ );
+ });
+
+ it('accepts the first of the pair, the same name in another session, and a distinct name', () => {
+ expect(skip(rows[0])).toBeNull();
+ expect(skip(rows[2])).toBeNull();
+ expect(skip(rows[3])).toBeNull();
+ });
+});
+
/**
* A restore writes with raw SQL, so the NUL drop the entities apply to their free-text columns never
* runs. PostgreSQL rejects U+0000 in a bound parameter, and an older SQLite backup may hold one, also
diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.ts
index ea06519ab..e1a19543a 100644
--- a/src/modules/infra/table-importers.ts
+++ b/src/modules/infra/table-importers.ts
@@ -34,8 +34,11 @@ export interface TableImporter<K extends keyof MigrationTables = keyof Migration
/** The id interpolated into the failure warning (lid_mappings rows key on lid, not id). */
id: (row: MigrationTables[K][number]) => string;
map: (row: MigrationTables[K][number]) => unknown[];
- /** Per-row veto: returns the warning to record (the row is skipped) or null to import the row. */
- skip?: (row: MigrationTables[K][number]) => string | null;
+ /**
+ * Per-row veto: returns the warning to record (the row is skipped) or null to import the row.
+ * `rows` is the whole archived table, for a guard that weighs a row against its siblings.
+ */
+ skip?: (row: MigrationTables[K][number], rows?: MigrationTables[K]) => string | null;
}
/**
@@ -48,7 +51,7 @@ export interface TableImporter<K extends keyof MigrationTables = keyof Migration
export type AnyTableImporter = Omit<TableImporter, 'id' | 'map' | 'skip'> & {
id: (row: never) => string;
map: (row: never) => unknown[];
- skip?: (row: never) => string | null;
+ skip?: (row: never, rows?: never) => string | null;
};
// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array.
@@ -76,6 +79,22 @@ function nulFree(value: unknown): unknown {
return NulFreeTransformer.to(value);
}
+// (sessionId, NUL-free name) -> id of the first archived template holding it, built once per table.
+const templateNameOwners = new WeakMap<TemplateRow[], Map<string, string>>();
+
+function firstTemplateWithName(rows: TemplateRow[], sessionId: string, name: unknown): string | undefined {
+ let owners = templateNameOwners.get(rows);
+ if (!owners) {
+ owners = new Map();
+ for (const row of rows) {
+ const key = JSON.stringify([row.sessionId, nulFree(row.name)]);
+ if (!owners.has(key)) owners.set(key, row.id);
+ }
+ templateNameOwners.set(rows, owners);
+ }
+ return owners.get(JSON.stringify([sessionId, name]));
+}
+
// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the
// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks
// live on their descriptor entries.
@@ -228,6 +247,15 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [
sql: `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
id: (tpl: TemplateRow) => tpl.id,
+ // (sessionId, name) is unique, and the name loses its NUL characters below. Two names of one
+ // session that differ only by NUL would collide on insert and roll the whole restore back, after
+ // any orphan engines were stopped; refuse the second one here instead, naming both rows.
+ skip: (tpl: TemplateRow, rows: TemplateRow[] = []) => {
+ const name = nulFree(tpl.name);
+ const owner = firstTemplateWithName(rows, tpl.sessionId, name);
+ if (owner === undefined || owner === tpl.id) return null;
+ return `Skipped template ${tpl.id}: name ${JSON.stringify(name)} without NUL characters collides with template ${owner} of session ${tpl.sessionId}`;
+ },
map: (tpl: TemplateRow) => [
tpl.id,
tpl.sessionId,