peppa/packages/core/src/connection-mask.ts
peppa-bot 9b2b233e95
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 34с
peppa/test test: success за 1426с
peppa-ci / ci (pull_request) Successful in 25m45s
PEP-258: маскировка всех форм ключа и в шлюзе баз/SSH/S3/почты (PEP-251); память в пределе
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:18:42 +00:00

101 lines
4.4 KiB
TypeScript

// PEP-258: every recognisable form of a connection key, and masking of them in what reaches the agent.
// A service may echo the key back encoded (base64 of «login:password», URL-encoded query key, hex,
// JSON-escaped, line-wrapped base64) or cut at the 256 KB boundary — none of it may reach the agent.
import type { CatalogAuth } from "./connection-catalog.ts";
import { MASK } from "./secrets.ts";
/** Shorter fragments (base64 cores of short keys) are not masked on their own: false positives. */
const CORE_MIN = 8;
/** Forms at least this long are also looked for with line breaks inside (MIME/PEM wrapping). */
const WRAP_MIN = 16;
/** A truncated answer ending with this many first characters of a form gets its tail masked. */
const TAIL_MIN = 4;
const urlSafe = (b64: string) => b64.replace(/\+/g, "-").replace(/\//g, "_");
/**
* base64 of the value as it appears inside a longer base64 stream at byte offset 0, 1 and 2:
* characters that depend on neighbouring bytes are dropped. Plus the whole value with and without padding.
*/
function base64Forms(value: string): string[] {
const bytes = Buffer.from(value, "utf8");
const out: string[] = [];
const full = bytes.toString("base64");
out.push(full, full.replace(/=+$/, ""));
for (let k = 0; k < 3; k++) {
const enc = Buffer.concat([Buffer.alloc(k), bytes]).toString("base64").replace(/=+$/, "");
const head = k === 0 ? 0 : 4; // the first group mixes the prefix bytes
const tail = (k + bytes.length) % 3 === 0 ? 0 : (((k + bytes.length) % 3) + 1); // the last partial group depends on what follows
const core = enc.slice(head, enc.length - tail);
if (core.length >= CORE_MIN) out.push(core);
}
return [...out, ...out.map(urlSafe)];
}
function textForms(value: string): string[] {
const uri = encodeURIComponent(value);
const hex = Buffer.from(value, "utf8").toString("hex");
const json = JSON.stringify(value).slice(1, -1);
const uEsc = [...value].map((ch) => (ch.codePointAt(0)! > 0xffff ? JSON.stringify(ch).slice(1, -1) : `\\u${ch.codePointAt(0)!.toString(16).padStart(4, "0")}`)).join("");
return [
value,
uri,
uri.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()),
uri.replace(/%20/g, "+"),
encodeURI(value),
escape(value),
hex,
hex.toUpperCase(),
json,
json.replace(/\//g, "\\/"),
uEsc,
uEsc.toUpperCase().replace(/\\U/g, "\\u"),
...base64Forms(value),
];
}
/**
* All forms of a connection key the gateway masks, longest first. For basic the password alone is a
* secret too (the login is not: it is often public — an email).
*/
export function connectionKeyForms(secret: string, authKind?: CatalogAuth | string | null): string[] {
const values = [secret];
// An SSH private key spans lines (PEP-251): each long line is a secret on its own.
if (/[\r\n]/.test(secret)) values.push(...secret.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length >= CORE_MIN && !/^-----/.test(l)));
if (authKind === "basic") {
const i = secret.indexOf(":");
const password = i >= 0 ? secret.slice(i + 1) : "";
if (password.length >= TAIL_MIN) values.push(password);
}
const forms = new Set<string>();
for (const v of values) for (const f of textForms(v)) if (f.length >= TAIL_MIN) forms.add(f);
return [...forms].sort((a, b) => b.length - a.length);
}
const reEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/** The form with an optional line break between any two characters. */
const wrapped = (form: string) => new RegExp([...form].map(reEscape).join("(?:\\r?\\n)?"), "g");
/**
* Replaces every form of the key with «••••». `truncated`: the answer was cut, so its very end may hold
* the beginning of a form — masked too.
*/
export function maskConnectionKey(text: string, forms: string[], o: { truncated?: boolean } = {}): string {
if (!forms.length || !text) return text;
let out = text;
for (const f of forms) if (out.includes(f)) out = out.split(f).join(MASK);
if (/[\r\n]/.test(out)) for (const f of forms) if (f.length >= WRAP_MIN) out = out.replace(wrapped(f), MASK);
if (o.truncated) {
const maxCut = Math.max(...forms.map((f) => f.length)) - 1;
for (let n = Math.min(maxCut, out.length); n >= TAIL_MIN; n--) {
const tail = out.slice(-n);
if (forms.some((f) => f.length > n && f.startsWith(tail))) {
out = out.slice(0, -n) + MASK;
break;
}
}
}
return out;
}