// archive.org's S3 KEYS for Save Page Now (release 37 S5), kept the way the // Claude API key is (lib/llm/anthropic.ts readApiKey): the environment first // (ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, both), else a mode-600 // file whose PATH is the setting `archiveOrg.s3KeyFile` (two lines // `ARCHIVE_ORG_S3_ACCESS=…`, `ARCHIVE_ORG_S3_SECRET=…`). A file the group or // others can read is refused. The keys are never a setting, never logged, // never in an error, a job record or a result. import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../archiveOrgTorrent"; import { spnOffSentence, type SpnKeys } from "./savePageNow"; export type SpnKeysRead = { ok: true; keys: SpnKeys; from: "env" | "file" } | { ok: false; reason: string }; const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p); const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim(); export function readSpnKeys(o: { keyFile?: string; env?: Readonly>; }): SpnKeysRead { const env = o.env ?? process.env; const keyFile = o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE; const envAccess = (env.ARCHIVE_ORG_S3_ACCESS ?? "").trim(); const envSecret = (env.ARCHIVE_ORG_S3_SECRET ?? "").trim(); if (envAccess && envSecret) return { ok: true, keys: { access: envAccess, secret: envSecret }, from: "env" }; const file = expandHome(keyFile); let mode: number; try { mode = statSync(file).mode; } catch { return { ok: false, reason: spnOffSentence(keyFile) }; } if (mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; Save Page Now is off until then.` }; let text: string; try { text = readFileSync(file, "utf8"); } catch { return { ok: false, reason: `${keyFile} could not be read; Save Page Now is off.` }; } let access = ""; let secret = ""; for (const raw of text.split("\n")) { const line = raw.trim().replace(/^export\s+/, ""); if (line.startsWith("ARCHIVE_ORG_S3_ACCESS=")) access = unquote(line.slice("ARCHIVE_ORG_S3_ACCESS=".length)); if (line.startsWith("ARCHIVE_ORG_S3_SECRET=")) secret = unquote(line.slice("ARCHIVE_ORG_S3_SECRET=".length)); } if (!access || !secret) { return { ok: false, reason: `${keyFile} has no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines; Save Page Now is off.` }; } return { ok: true, keys: { access, secret }, from: "file" }; } // Replace the keys wherever they appear in a text: the last line of defence // for a message that leaves the module. export function redactSpnKeys(text: string, keys: SpnKeys | undefined): string { if (!keys) return text; let out = text; for (const k of [keys.secret, keys.access]) if (k && k.length >= 4) out = out.split(k).join("[redacted]"); return out; }