153 lines
5.0 KiB
TypeScript
153 lines
5.0 KiB
TypeScript
import { spawn, type SpawnOptions } from "node:child_process";
|
|
import { createReadStream, createWriteStream } from "node:fs";
|
|
import { copyFile } from "node:fs/promises";
|
|
import { pipeline } from "node:stream/promises";
|
|
|
|
export type EncryptionMethod = "age" | "gpg" | "none";
|
|
|
|
export interface EncryptionConfig {
|
|
method: EncryptionMethod;
|
|
/** age public key (recipient) when method=age. */
|
|
recipient?: string;
|
|
/** age identity file when method=age and we're decrypting. */
|
|
identityFile?: string;
|
|
/** gpg key id for method=gpg. */
|
|
gpgRecipient?: string;
|
|
/** Override binary path. */
|
|
binary?: string;
|
|
}
|
|
|
|
export interface EncryptOptions {
|
|
config: EncryptionConfig;
|
|
inputPath: string;
|
|
outputPath: string;
|
|
spawnFn?: typeof spawn;
|
|
}
|
|
|
|
export class EncryptionError extends Error {
|
|
readonly exitCode: number | null;
|
|
readonly stderr: string;
|
|
constructor(message: string, exitCode: number | null, stderr: string) {
|
|
super(message);
|
|
this.name = "EncryptionError";
|
|
this.exitCode = exitCode;
|
|
this.stderr = stderr;
|
|
}
|
|
}
|
|
|
|
export async function encryptFile(opts: EncryptOptions): Promise<{ method: EncryptionMethod; outputPath: string }> {
|
|
const { method } = opts.config;
|
|
if (method === "none") {
|
|
await copyFile(opts.inputPath, opts.outputPath);
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
if (method === "age") {
|
|
if (!opts.config.recipient) {
|
|
throw new EncryptionError("BACKUP_AGE_PUBLIC_KEY is required when BACKUP_ENCRYPTION=age", null, "");
|
|
}
|
|
await runSpawnPipe({
|
|
binary: opts.config.binary ?? "age",
|
|
args: ["-r", opts.config.recipient, "-o", opts.outputPath, opts.inputPath],
|
|
spawnFn: opts.spawnFn,
|
|
});
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
if (method === "gpg") {
|
|
if (!opts.config.gpgRecipient) {
|
|
throw new EncryptionError("BACKUP_GPG_RECIPIENT is required when BACKUP_ENCRYPTION=gpg", null, "");
|
|
}
|
|
await runSpawnPipe({
|
|
binary: opts.config.binary ?? "gpg",
|
|
args: ["--yes", "--encrypt", "--recipient", opts.config.gpgRecipient, "--output", opts.outputPath, opts.inputPath],
|
|
spawnFn: opts.spawnFn,
|
|
});
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
throw new EncryptionError(`Unsupported encryption method: ${String(method)}`, null, "");
|
|
}
|
|
|
|
export interface DecryptOptions {
|
|
config: EncryptionConfig;
|
|
inputPath: string;
|
|
outputPath: string;
|
|
spawnFn?: typeof spawn;
|
|
}
|
|
|
|
export async function decryptFile(opts: DecryptOptions): Promise<{ method: EncryptionMethod; outputPath: string }> {
|
|
const { method } = opts.config;
|
|
if (method === "none") {
|
|
await copyFile(opts.inputPath, opts.outputPath);
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
if (method === "age") {
|
|
if (!opts.config.identityFile) {
|
|
throw new EncryptionError("BACKUP_AGE_IDENTITY_FILE is required to decrypt age backups", null, "");
|
|
}
|
|
await runSpawnPipe({
|
|
binary: opts.config.binary ?? "age",
|
|
args: ["-d", "-i", opts.config.identityFile, "-o", opts.outputPath, opts.inputPath],
|
|
spawnFn: opts.spawnFn,
|
|
});
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
if (method === "gpg") {
|
|
await runSpawnPipe({
|
|
binary: opts.config.binary ?? "gpg",
|
|
args: ["--yes", "--decrypt", "--output", opts.outputPath, opts.inputPath],
|
|
spawnFn: opts.spawnFn,
|
|
});
|
|
return { method, outputPath: opts.outputPath };
|
|
}
|
|
throw new EncryptionError(`Unsupported encryption method: ${String(method)}`, null, "");
|
|
}
|
|
|
|
/**
|
|
* Convenience helper that emulates an in-process encryption when no binary is
|
|
* available — used in unit tests so the round-trip is fully deterministic.
|
|
* Production code paths must use age or gpg via the real binary.
|
|
*/
|
|
export async function trivialXorRoundTrip(inputPath: string, outputPath: string, key: number): Promise<void> {
|
|
const src = createReadStream(inputPath);
|
|
const dst = createWriteStream(outputPath);
|
|
await pipeline(
|
|
src,
|
|
async function* (source) {
|
|
for await (const chunk of source) {
|
|
const buf = chunk as Buffer;
|
|
const out = Buffer.alloc(buf.length);
|
|
for (let i = 0; i < buf.length; i += 1) {
|
|
out[i] = buf[i] ^ key;
|
|
}
|
|
yield out;
|
|
}
|
|
},
|
|
dst,
|
|
);
|
|
}
|
|
|
|
interface RunSpawnPipeOptions {
|
|
binary: string;
|
|
args: readonly string[];
|
|
spawnFn?: typeof spawn;
|
|
}
|
|
|
|
async function runSpawnPipe(opts: RunSpawnPipeOptions): Promise<void> {
|
|
const spawner = opts.spawnFn ?? spawn;
|
|
const spawnOptions: SpawnOptions = { stdio: ["ignore", "pipe", "pipe"] };
|
|
const child = spawner(opts.binary, [...opts.args], spawnOptions);
|
|
const stderrChunks: Buffer[] = [];
|
|
child.stderr?.on("data", (c: Buffer) => stderrChunks.push(c));
|
|
|
|
const exitCode: number | null = await new Promise((resolve, reject) => {
|
|
child.once("error", reject);
|
|
child.once("close", (code: number | null) => resolve(code));
|
|
});
|
|
if (exitCode !== 0) {
|
|
throw new EncryptionError(
|
|
`${opts.binary} exited with code ${exitCode ?? "<null>"}`,
|
|
exitCode,
|
|
Buffer.concat(stderrChunks).toString("utf8"),
|
|
);
|
|
}
|
|
}
|