Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
"use strict";
// Source-level pins for the activity-log store's at-rest posture and its
// deletion reap (adpanel:activity-log-mode).
//
// The audited hole: nodes.js created .activity-logs and its per-server .log
// files with no mode — they landed at the umask default (world-readable,
// -rw-rw-r-- on this deployment) while holding full actor emails, IPs and
// verbatim console_command payloads; and server deletion never unlinked the
// files, so a deleted server's audit trail persisted forever and stayed
// servable through the reader's canonical/legacy file keys.
//
// Pinned here:
// - nodes.js creates the directory at 0o700 (the SESSION_DIR posture) and
// appends log files at 0o600 (the secret-config posture), with a
// best-effort boot repair chmod'ing the directory and every existing
// *.log (tolerating EPERM with a warn — module init must never crash
// over permissions);
// - index.js's removeServerIndexEntry reaps the deleted server's log files
// for BOTH keys the reader serves (the injective
// utils/activity-log-name key and the pre-fix legacy fallback key) across
// the survivor-guarded doomed-alias set, ENOENT-tolerant and best-effort;
// and the reap also removes the rotation archives the writer leaves
// behind (the `${key}.${timestamp}.log` shape) — matched exactly
// (trailing-dot prefix + digits-only middle segment), so a neighbor
// server's files can never match.
//
// nodes.js IS requireable (several route tests require it), but these pins
// are structural (source windows) like utils/activity-log-name.test.js, so
// requiring the module — and its timers — stays out of the test process.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const NODES_SRC = fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8");
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
function windowBetween(src, startAnchor, endAnchor, label) {
const start = src.indexOf(startAnchor);
assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`);
const end = src.indexOf(endAnchor, start + startAnchor.length);
assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`);
return src.slice(start, end);
}
// ─── 1. nodes.js writer posture ──────────────────────────────────────────────
test("the activity store is created 0o700/0o600, appended with the file mode, and pre-existing files are repaired at boot", () => {
assert.ok(
NODES_SRC.includes("const ACTIVITY_LOG_DIR_MODE = 0o700;") &&
NODES_SRC.includes("const ACTIVITY_LOG_FILE_MODE = 0o600;"),
"the modes must be named constants — the directory is 0o700 (SESSION_DIR posture) and log files 0o600 (secret-config posture)"
);
assert.ok(
NODES_SRC.includes("fs.mkdirSync(ACTIVITY_LOGS_DIR, { recursive: true, mode: ACTIVITY_LOG_DIR_MODE })"),
"the store directory must be created with mode 0o700 — it holds full emails, IPs and verbatim console_command payloads"
);
// Boot repair for EXISTING files (created before the modes existed): chmod
// the directory and every *.log inside, tolerating failures with a warn.
assert.ok(
NODES_SRC.includes("fs.chmodSync(ACTIVITY_LOGS_DIR, ACTIVITY_LOG_DIR_MODE)"),
"the boot repair must chmod the store directory"
);
assert.ok(
NODES_SRC.includes('entry.endsWith(".log")') &&
NODES_SRC.includes("fs.chmodSync(path.join(ACTIVITY_LOGS_DIR, entry), ACTIVITY_LOG_FILE_MODE)"),
"the boot repair must chmod every existing *.log file inside the store"
);
assert.ok(
NODES_SRC.includes('console.warn("[activity-log] Could not tighten permissions on the activity log directory:"'),
"a failed directory chmod must be tolerated with a warn — the repair can never crash module init (EPERM on odd deployments)"
);
// The append must pass the file mode: it applies at CREATION, so every
// fresh log file lands at 0o600 even before any boot repair runs, and an
// append to an existing file never loosens its mode.
const flushWindow = windowBetween(
NODES_SRC,
"async function flushActivityLogs",
"let _webhookDispatcher",
"flushActivityLogs"
);
assert.ok(
flushWindow.includes('{ encoding: "utf8", mode: ACTIVITY_LOG_FILE_MODE }'),
"the log append must carry the 0o600 file mode (creation-time; appends never loosen it)"
);
});
// ─── 2. The deletion reap ────────────────────────────────────────────────────
test("server deletion reaps the deleted server's activity log files for both reader keys over the survivor-guarded alias set", () => {
const reap = windowBetween(
INDEX_SRC,
"async function reapActivityLogFilesForAliases",
"async function removeServerIndexEntry",
"reap helper"
);
// The keys mirror the READER exactly (index.js /api/server/:name/activity):
// the injective activityLogFileKey of the canonical name plus the pre-fix
// legacyActivityLogFileKey fallback — derived for every doomed alias,
// because recordActivity has historically been called with more than one
// alias spelling (name / legacy_id / bot).
assert.ok(
reap.includes("activityLogFileKey(alias)") && reap.includes("legacyActivityLogFileKey(alias)"),
"the reap must unlink BOTH keys the reader serves (injective + pre-fix legacy fallback)"
);
assert.ok(
reap.includes('${key}.log`') && reap.includes('${legacyKey}.log`'),
"the reap must target the exact .log files the reader derives"
);
assert.ok(
reap.includes('if (unlinkErr?.code !== "ENOENT")'),
"the reap must tolerate ENOENT (nothing was ever written under that key)"
);
assert.ok(
reap.includes("console.warn("),
"any other unlink failure is a retention miss (warned), never a deletion failure — the helper cannot throw"
);
// Wiring inside removeServerIndexEntry: the reap runs AFTER the servers-row
// delete (a failed delete aborts before anything is reaped) and receives
// the SURVIVOR-GUARDED alias set, so a survivor's log can never be reaped.
const removeEntry = windowBetween(
INDEX_SRC,
"async function removeServerIndexEntry",
"async function findServer(botName)",
"removeServerIndexEntry"
);
const serversDeleteAt = removeEntry.indexOf("DELETE FROM servers WHERE id IN");
const reapCallAt = removeEntry.indexOf("await reapActivityLogFilesForAliases(childAliases);");
const returnTrueAt = removeEntry.indexOf("return true;");
assert.notStrictEqual(serversDeleteAt, -1, "the id-keyed servers delete is missing");
assert.notStrictEqual(reapCallAt, -1, "the activity-log reap call is missing");
assert.notStrictEqual(returnTrueAt, -1, "the removal success return is missing");
assert.ok(
serversDeleteAt < reapCallAt && reapCallAt < returnTrueAt,
"order must be: servers-row delete -> activity-log reap -> success return — a committed index delete must reap the store, and an aborted one (fail-closed) must reap nothing"
);
assert.ok(
reapCallAt !== -1 && removeEntry.slice(0, reapCallAt).includes("childAliases = childAliases.filter"),
"the reap must receive the survivor-guarded childAliases — an alias still claimed by a surviving server row is excluded, so a survivor's log can never be reaped"
);
});
// ─── 2b. The rotation archives are reaped too ────────────────────────────────
test("the reap also removes the rotation archives and its filter cannot eat a neighbor server's files", () => {
const reap = windowBetween(
INDEX_SRC,
"async function reapActivityLogFilesForAliases",
"async function removeServerIndexEntry",
"reap helper"
);
// nodes.js's rotateActivityLogIfNeeded renames the live file to
// `${key}.${Date.now()}.log` (and pre-fix history lives at
// `${legacyKey}.${ts}.log`) — up to ACTIVITY_LOG_MAX_FILES ×
// ACTIVITY_LOG_MAX_SIZE per server, never served but holding the same
// audit data. A reap that unlinks only the two live keys leaves all of it
// at rest forever, so the archives must be listed with ONE readdir per
// call (per alias set) and unlinked with the same ENOENT-tolerant,
// warn-only posture.
assert.ok(
reap.includes("fsp.readdir(ACTIVITY_LOGS_DIR)"),
"the archive reap must readdir the store once per call (per alias set), not per alias"
);
assert.ok(
reap.includes('readdirErr?.code !== "ENOENT"'),
"a missing store directory must be tolerated silently (ENOENT) like the live-key unlinks — the helper cannot throw"
);
// The filter must match the rotation shape EXACTLY and nothing else — two
// load-bearing discriminators:
// - the prefix is compared WITH its trailing dot (`${prefix}.`): a bare
// prefix match would eat a NEIGHBOR server's files — key "Alpha" vs
// "Alpha2" (the neighbor's live "Alpha2.log" and its own archives
// "Alpha2.${ts}.log" start with "Alpha2", never "Alpha.");
// - the middle segment must be DIGITS-ONLY (the Date.now() stamp): this
// spares the live `${key}.log` itself (middle "log") and any
// non-timestamp shape like "Alpha.notes.log".
assert.ok(
reap.includes("entry.startsWith(`${prefix}.`)"),
"the archive filter must compare the prefix WITH its trailing dot — a bare startsWith(prefix) would delete a neighbor server's files (key 'Alpha' vs 'Alpha2')"
);
assert.ok(
reap.includes("/^\\d+$/.test(middle)"),
"the archive filter must require a digits-only middle segment (the rotation timestamp) — the live '${key}.log' and non-timestamp shapes must not match"
);
// The archive unlinks must run over the FILTERED list only — both
// discriminators above are what keeps neighbor servers' files alive, so a
// delete loop over raw readdir entries would bypass them.
assert.ok(
reap.includes("for (const entry of archiveNames) {"),
"archive unlinks must run over the filtered archive list only — deleting raw readdir entries would bypass the neighbor guards"
);
});