"use strict"; const crypto = require("crypto"); // Per-server activity log files are named after the server name. Server names // legally contain characters outside [A-Za-z0-9_-] (sanitizeServerToken in // utils/server-name.js keeps [A-Za-z0-9\-_.]), so the historical filename // transform `name.replace(/[^a-zA-Z0-9_-]/g, "_")` was NOT injective: it // collapsed "shop.bot" and "shop_bot" (and any pair differing only outside // [A-Za-z0-9_-]) onto ONE file while the access check still authorized the // raw requested name — a cross-tenant information disclosure (one tenant could // read the other's full audit trail: console commands, paths, actor emails, // IPs). // // activityLogFileKey replaces that transform with an INJECTIVE filesystem-safe // encoding so distinct server names can never share a log file again, while // keeping the key charset identical to the old one ([A-Za-z0-9_-]) so nothing // else about the filename scheme (extension, rotation suffix, pruning) changes. // // Encoding, per code unit of the trimmed input: // "_" -> "__" (literal underscores are DOUBLED) // [A-Za-z0-9-] -> unchanged // anything else -> "__" // e.g. "." -> "_2e_", "@" -> "_40_", " " -> "_20_" // // INJECTIVITY ARGUMENT. The encoding is a per-character code whose codewords // are: (a) the passthrough chars [A-Za-z0-9-] (never containing "_"), (b) "__" // and (c) "_" + hex digits + "_". Codeword (b) starts with "__" while every // (c) codeword has at least one HEX DIGIT between its underscores (a code unit // is at least 1 hex digit wide), so no codeword is a prefix of another — the // code is prefix-free, hence uniquely decodable, hence two distinct inputs can // never produce the same key. Concretely: the only way "__" appears in an // output is a literal "_" in the input, because a hex escape always keeps a // hex digit between its two underscores and cannot melt into a neighboring // escape (parsing is left-to-right and each escape is consumed whole). // // LENGTH CAP. Worst case every input char expands ~6x, so a long name could // exceed comfortable filename limits. Keys longer than 240 chars are replaced // by their first 160 chars plus "-" and the first 12 hex chars of the SHA-256 // of the FULL encoding: the hash covers the part cut off, so two long names // sharing a >160-char prefix (the truncation boundary) still get different // keys. The suffix is appended after a "-" separator, which a passthrough char // can also produce — an engineered (not derivable) collision between a crafted // short name and one specific truncated key remains theoretically possible; // it requires deliberately registering a ~173-char-encoded lookalike name and // is documented as a residual risk, unlike the old collapse which collided on // everyday names like "shop.bot"/"shop_bot". function activityLogFileKey(raw) { const name = String(raw || "").trim(); if (!name) return ""; // Order matters and is what the injectivity proof above relies on: decide // the underscore escape FIRST (against the ORIGINAL characters), then escape // the remaining non-safe characters. A single sequential pass per code unit // of the input — not two whole-string replaces — so the "__" produced for a // literal underscore is never re-escaped as "_5f_": it survives verbatim and // stays distinguishable from every hex escape. let encoded = ""; for (const ch of name) { if (ch === "_") { encoded += "__"; } else if (/[A-Za-z0-9-]/.test(ch)) { encoded += ch; } else { // The input is iterated by code point (`for..of`), so astral characters // (emoji) arrive as a surrogate PAIR; escaping each half separately via // charCodeAt would emit two escapes. Escaping the whole code point once // (codePointAt) keeps one escape per visible character and stays just // as injective (code points map to distinct hex strings). encoded += "_" + ch.codePointAt(0).toString(16) + "_"; } } if (encoded.length <= 240) return encoded; const digest = crypto.createHash("sha256").update(encoded, "utf8").digest("hex"); return encoded.slice(0, 160) + "-" + digest.slice(0, 12); } // The PRE-FIX filename transform, kept verbatim (plus the trim the writer's // callers always applied via sanitizeServerToken) for the read-only legacy // fallback in index.js: activity logs written before the injective-key fix // live under `${legacyKey}.log` / `${legacyKey}.${timestamp}.log` and must // stay reachable for unambiguous names so history is not lost. This function // is deliberately NOT injective — that was the bug — so the reader must never // use it for writes or as a primary key, only behind an ambiguity check. function legacyActivityLogFileKey(raw) { return String(raw || "").trim().replace(/[^a-zA-Z0-9_-]/g, "_"); } module.exports = { activityLogFileKey, legacyActivityLogFileKey, };