Files
OmniRoute/tests/unit/cli-storage-key-bootstrap.test.ts
diegosouzapw 04d8884e09 fix(cli): persist STORAGE_ENCRYPTION_KEY in DATA_DIR + guard against destructive regen (#1622)
The CLI key bootstrap wrote to ~/.omniroute/.env ignoring DATA_DIR, so users with a
custom DATA_DIR (incl. Docker-style setups) lost the key across restarts. It also
regenerated a fresh key whenever STORAGE_ENCRYPTION_KEY was unset — even when an encrypted
storage.sqlite already existed — locking users out. Now writes to DATA_DIR and refuses to
auto-generate when a database is already present (mirrors server bootstrapEnv guard).
Reported by Daniel Nach; original key persistence by @Chewji9875.
2026-05-21 22:17:22 -03:00

63 lines
2.2 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const BIN = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"..",
"bin",
"omniroute.mjs"
);
function runCli(dataDir: string): { code: number | null; stderr: string } {
const res = spawnSync("node", [BIN, "--help"], {
env: { ...process.env, DATA_DIR: dataDir, NO_UPDATE_NOTIFIER: "1" },
timeout: 60_000,
encoding: "utf-8",
});
return { code: res.status, stderr: res.stderr ?? "" };
}
// #1622 follow-up (reported by Daniel Nach; original persistence by @Chewji9875):
// the CLI must persist the key into DATA_DIR (not just ~/.omniroute) so Docker/custom-DATA_DIR
// users keep it across restarts, and must NEVER auto-generate a fresh key when a database
// already exists (a new key can't decrypt prior data → user locked out).
test("CLI generates STORAGE_ENCRYPTION_KEY into DATA_DIR on first run (#1622)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-key-a-"));
try {
runCli(dir);
const envPath = path.join(dir, ".env");
assert.ok(fs.existsSync(envPath), "DATA_DIR/.env must be created");
const content = fs.readFileSync(envPath, "utf-8");
assert.match(
content,
/STORAGE_ENCRYPTION_KEY=[0-9a-f]{64}/,
"key persisted into DATA_DIR/.env"
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("CLI refuses to auto-generate a key when a database already exists (#1622)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-key-b-"));
try {
fs.writeFileSync(path.join(dir, "storage.sqlite"), "fake-db");
const { stderr } = runCli(dir);
const envPath = path.join(dir, ".env");
const hasKey =
fs.existsSync(envPath) &&
fs.readFileSync(envPath, "utf-8").includes("STORAGE_ENCRYPTION_KEY=");
assert.equal(hasKey, false, "must NOT generate a key when a DB already exists");
assert.match(stderr, /already exists/i, "must warn that a database already exists");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});