diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e00adf..3cbbb4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Preflight n8n backup filename collisions, exclude custom backup output from source discovery, and reject output at the repository root or its ancestor. + ## 0.1.0 - Added the first productized CLI: `scan`, `doctor`, and `init`. diff --git a/docs/n8n-safety-backup.md b/docs/n8n-safety-backup.md index b7f87b5..c869e37 100644 --- a/docs/n8n-safety-backup.md +++ b/docs/n8n-safety-backup.md @@ -18,6 +18,8 @@ ark n8n-backup . --backup-dir .agent-reliability/n8n-backup `n8n-backup` writes formatted workflow JSON into a Git-friendly directory and redacts token-like values first. +The resolved output directory is excluded from source discovery, including custom destinations, so repeated runs do not back up their own generated files. Output must not be the source repository root or its ancestor, including directory aliases. Paths are flattened using `__` for compatibility; if two source paths would produce the same backup filename, the command stops before writing any backup files. Names are compared without case on every platform, including the reserved `README.md` and `backup-report.json`, so backups remain portable to case-insensitive filesystems. This also rejects otherwise distinct names differing only in case on a case-sensitive filesystem. Choose distinct source filenames and retry. Previously generated files for the same source may still be refreshed on later runs; unrelated stale files are not deleted. + The command writes: - redacted workflow JSON files diff --git a/src/n8n/backup.ts b/src/n8n/backup.ts index 393294c..b01e740 100644 --- a/src/n8n/backup.ts +++ b/src/n8n/backup.ts @@ -22,16 +22,31 @@ export interface N8nBackupReport { export function backupN8nWorkflows(options: N8nBackupOptions): N8nBackupReport { const root = resolveRoot(options.root); - const backupDir = path.isAbsolute(options.backupDir) ? options.backupDir : path.join(root, options.backupDir); + const backupDir = path.resolve(root, options.backupDir); const files = []; + const physicalRoot = fs.realpathSync(root); + const physicalOutput = resolvePhysicalPath(backupDir); + if (isInside(physicalOutput, physicalRoot)) throw new Error("Backup output must not be the repository root or its ancestor."); + const candidates = []; + // Portable backups must also be safe on case-insensitive macOS volumes. + const destinationKey = (target: string): string => target.toLowerCase(); + const destinations = new Set(["README.md", "backup-report.json"].map((name) => destinationKey(path.join(backupDir, name)))); - fs.mkdirSync(backupDir, { recursive: true }); for (const file of listRepoFiles(root)) { + if (isInside(physicalOutput, path.resolve(physicalRoot, file.relativePath))) continue; const text = readTextFile(file); if (!text || !looksLikeN8nWorkflow(text, file.relativePath)) continue; const redactedText = redactSecretLikeText(text); const parsed = parseJson(redactedText); const target = path.join(backupDir, file.relativePath.replaceAll("/", "__")); + const key = destinationKey(target); + if (destinations.has(key)) throw new Error("Workflow backup filenames collide after path flattening. Rename the source paths and retry."); + destinations.add(key); + candidates.push({ file, text, redactedText, parsed, target }); + } + + fs.mkdirSync(backupDir, { recursive: true }); + for (const { file, text, redactedText, parsed, target } of candidates) { fs.writeFileSync(target, parsed ? `${JSON.stringify(parsed, null, 2)}\n` : redactedText, "utf8"); files.push({ source: file.relativePath, @@ -61,6 +76,18 @@ export function backupN8nWorkflows(options: N8nBackupOptions): N8nBackupReport { return report; } +function isInside(directory: string, candidate: string): boolean { + const relative = path.relative(directory, candidate); + return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); +} + +function resolvePhysicalPath(directory: string): string { + if (fs.existsSync(directory)) return fs.realpathSync(directory); + const parent = path.dirname(directory); + if (parent === directory) throw new Error("Backup destination parent is unavailable."); + return path.join(resolvePhysicalPath(parent), path.basename(directory)); +} + function parseJson(text: string): unknown | null { try { return JSON.parse(text) as unknown; diff --git a/tests/n8nBackup.test.ts b/tests/n8nBackup.test.ts new file mode 100644 index 0000000..eef5354 --- /dev/null +++ b/tests/n8nBackup.test.ts @@ -0,0 +1,83 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { backupN8nWorkflows } from "../src/n8n/backup.js"; + +function rootFixture(): string { + return fs.mkdtempSync(path.join(os.tmpdir(), "ark-backup-paths-")); +} + +function workflow(root: string, relative: string, name = "synthetic-workflow"): void { + const file = path.join(root, relative); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ name, nodes: [{ name: "synthetic-node", type: "n8n-nodes-base.manualTrigger", parameters: {} }] })); +} + +describe("n8n backup destination safety", () => { + it.each([ + ["a/b.json", "A__b.json"], + ["readme.md"], + ["BACKUP-REPORT.JSON"] + ])("rejects portable case-insensitive destination collisions: %s", (...sources) => { + const root = rootFixture(); + for (const source of sources) workflow(root, source); + const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform")!; + try { + // Reproduce the non-Windows path used on case-insensitive macOS volumes. + Object.defineProperty(process, "platform", { ...originalPlatform, value: "darwin" }); + expect(() => backupN8nWorkflows({ root, backupDir: "backups" })).toThrow(/collid/i); + expect(fs.existsSync(path.join(root, "backups"))).toBe(false); + } finally { + Object.defineProperty(process, "platform", originalPlatform); + } + }); + + it.each(["README.md", "backup-report.json"])("rejects a workflow colliding with generated metadata: %s", (name) => { + const root = rootFixture(); + workflow(root, name); + expect(() => backupN8nWorkflows({ root, backupDir: "backups" })).toThrow(/collid/i); + expect(fs.existsSync(path.join(root, "backups"))).toBe(false); + }); + + it("rejects a directory alias pointing at the source root", () => { + const root = rootFixture(); + workflow(root, "example.json"); + fs.symlinkSync(root, path.join(root, "alias"), process.platform === "win32" ? "junction" : "dir"); + expect(() => backupN8nWorkflows({ root, backupDir: "alias" })).toThrow(/root/i); + }); + + it("keeps source folders that merely share the output prefix", () => { + const root = rootFixture(); + workflow(root, "backups-other/example.json"); + const result = backupN8nWorkflows({ root, backupDir: "backups" }); + expect(result.files.map((file) => file.source)).toEqual(["backups-other/example.json"]); + }); + + it("rejects flattened filename collisions before writing backups", () => { + const root = rootFixture(); + workflow(root, "a/b.json", "nested-workflow"); + workflow(root, "a__b.json", "flat-workflow"); + expect(() => backupN8nWorkflows({ root, backupDir: "backups" })).toThrow(/collid/i); + expect(fs.existsSync(path.join(root, "backups"))).toBe(false); + expect(JSON.parse(fs.readFileSync(path.join(root, "a/b.json"), "utf8")).name).toBe("nested-workflow"); + }); + + it("does not read generated custom backup files as new workflows", () => { + const root = rootFixture(); + workflow(root, "workflows/example.json"); + const first = backupN8nWorkflows({ root, backupDir: "backups" }); + const second = backupN8nWorkflows({ root, backupDir: path.join(root, "backups") }); + expect(second.files).toEqual(first.files); + expect(second.files).toHaveLength(1); + expect(fs.readdirSync(path.join(root, "backups")).sort()).toEqual(["README.md", "backup-report.json", "workflows__example.json"]); + }); + + it("rejects the repository root as output without overwriting source metadata", () => { + const root = rootFixture(); + workflow(root, "example.json"); + fs.writeFileSync(path.join(root, "README.md"), "original-readme\n"); + expect(() => backupN8nWorkflows({ root, backupDir: "." })).toThrow(/root/i); + expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("original-readme\n"); + }); +});