67 lines
2.5 KiB
TypeScript
67 lines
2.5 KiB
TypeScript
/**
|
|
* Snapshot-event audit log. Spec doesn't mandate a DB-write (the source
|
|
* system's AuditEvent table is reachable but requires Prisma which we keep
|
|
* out of the CLI); instead this module produces a structured, line-oriented
|
|
* audit record that operators redirect to a file or syslog.
|
|
*
|
|
* The `none` profile is the only one that requires the super-admin guardrail
|
|
* at the command layer; the audit entry is always written regardless of
|
|
* profile so that every snapshot leaves a trail.
|
|
*/
|
|
import { appendFile } from "node:fs/promises";
|
|
|
|
export type SnapshotProfile = "full-anonymized" | "minimal-anonymized" | "none";
|
|
|
|
export interface SnapshotAuditEntry {
|
|
readonly event: "TENANT_SNAPSHOT_CREATED";
|
|
readonly snapshotId: string;
|
|
readonly sourceTenantId: string;
|
|
readonly profile: SnapshotProfile;
|
|
readonly actorUserId: string | null;
|
|
readonly host: string | null;
|
|
readonly createdAt: string;
|
|
readonly outputTarget: string;
|
|
/** Whether the super-admin escape hatch was invoked for `none`. */
|
|
readonly superAdminConfirmed: boolean;
|
|
}
|
|
|
|
export interface WriteSnapshotAuditOptions {
|
|
readonly entry: SnapshotAuditEntry;
|
|
/** Optional file path to append the JSON line to. */
|
|
readonly filePath?: string;
|
|
/** Sink for the human-readable line (defaults to process.stdout). */
|
|
readonly stdout?: NodeJS.WritableStream;
|
|
}
|
|
|
|
/**
|
|
* Append a structured audit entry to an optional file and emit a one-line
|
|
* human summary on stdout. Returns the serialized JSON.
|
|
*/
|
|
export async function writeSnapshotAudit(opts: WriteSnapshotAuditOptions): Promise<string> {
|
|
const json = JSON.stringify(opts.entry);
|
|
const line = `[audit] ${opts.entry.event} snapshot=${opts.entry.snapshotId} tenant=${opts.entry.sourceTenantId} profile=${opts.entry.profile} actor=${opts.entry.actorUserId ?? "?"} target=${opts.entry.outputTarget}\n`;
|
|
const out = opts.stdout ?? process.stdout;
|
|
out.write(line);
|
|
if (opts.filePath) {
|
|
await appendFile(opts.filePath, `${json}\n`);
|
|
}
|
|
return json;
|
|
}
|
|
|
|
/**
|
|
* Validate that running the `none` profile is authorized. Throws if not.
|
|
*/
|
|
export function assertSuperAdminForNoneProfile(
|
|
profile: SnapshotProfile,
|
|
confirmed: boolean,
|
|
): void {
|
|
if (profile !== "none") return;
|
|
if (!confirmed) {
|
|
throw new Error(
|
|
"Refusing to run --profile=none without --i-am-the-super-admin. " +
|
|
"Raw exports of tenant data require an explicit super-admin confirmation and leave " +
|
|
"a permanent audit trail. See docs/ops/tenant-snapshot.md.",
|
|
);
|
|
}
|
|
}
|