export const MASK = "***"; export const MIN_SECRET_LENGTH = 4; const MAX_PENDING = 64 * 1024; /** * Replaces secret values in job output before anyone sees it: the raw value, its base64, base64url and URL-encoded * forms, and each line of a value that spans lines. It masks whole lines, and a form never contains a newline, * so a value split across two chunks is still found. A line longer than 64 KB is masked and sent in parts. */ export class LogMasker { readonly #pattern: RegExp | null; #pending = ""; constructor(secrets: readonly string[]) { const forms = new Set(); for (const secret of secrets) for (const form of formsOf(secret)) if (form.length >= MIN_SECRET_LENGTH) forms.add(form); const sorted = [...forms].sort((a, b) => b.length - a.length).map(escape); this.#pattern = sorted.length ? new RegExp(sorted.join("|"), "g") : null; } push(chunk: string): string { const text = this.#pending + chunk; const cut = text.lastIndexOf("\n") + 1; if (cut === 0 && text.length <= MAX_PENDING) { this.#pending = text; return ""; } const end = cut === 0 ? text.length : cut; this.#pending = text.slice(end); return this.#mask(text.slice(0, end)); } flush(): string { const rest = this.#pending; this.#pending = ""; return this.#mask(rest); } #mask(text: string): string { return this.#pattern ? text.replace(this.#pattern, MASK) : text; } } function formsOf(secret: string): string[] { const values = [secret, ...secret.split(/\r?\n/).map((line) => line.trim())]; return values.flatMap((value) => { if (!value || value.includes("\n")) return []; const base64 = btoa(String.fromCharCode(...new TextEncoder().encode(value))); return [value, base64.replace(/=+$/, ""), base64.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_"), encodeURIComponent(value)]; }); } function escape(text: string): string { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }