55 lines · 1.9 KBRaw
| 1 | export const MASK = "***"; |
| 2 | export const MIN_SECRET_LENGTH = 4; |
| 3 | const MAX_PENDING = 64 * 1024; |
| 4 | |
| 5 | /** |
| 6 | * Replaces secret values in job output before anyone sees it: the raw value, its base64, base64url and URL-encoded |
| 7 | * forms, and each line of a value that spans lines. It masks whole lines, and a form never contains a newline, |
| 8 | * so a value split across two chunks is still found. A line longer than 64 KB is masked and sent in parts. |
| 9 | */ |
| 10 | export class LogMasker { |
| 11 | readonly #pattern: RegExp | null; |
| 12 | #pending = ""; |
| 13 | |
| 14 | constructor(secrets: readonly string[]) { |
| 15 | const forms = new Set<string>(); |
| 16 | for (const secret of secrets) for (const form of formsOf(secret)) if (form.length >= MIN_SECRET_LENGTH) forms.add(form); |
| 17 | const sorted = [...forms].sort((a, b) => b.length - a.length).map(escape); |
| 18 | this.#pattern = sorted.length ? new RegExp(sorted.join("|"), "g") : null; |
| 19 | } |
| 20 | |
| 21 | push(chunk: string): string { |
| 22 | const text = this.#pending + chunk; |
| 23 | const cut = text.lastIndexOf("\n") + 1; |
| 24 | if (cut === 0 && text.length <= MAX_PENDING) { |
| 25 | this.#pending = text; |
| 26 | return ""; |
| 27 | } |
| 28 | const end = cut === 0 ? text.length : cut; |
| 29 | this.#pending = text.slice(end); |
| 30 | return this.#mask(text.slice(0, end)); |
| 31 | } |
| 32 | |
| 33 | flush(): string { |
| 34 | const rest = this.#pending; |
| 35 | this.#pending = ""; |
| 36 | return this.#mask(rest); |
| 37 | } |
| 38 | |
| 39 | #mask(text: string): string { |
| 40 | return this.#pattern ? text.replace(this.#pattern, MASK) : text; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | function formsOf(secret: string): string[] { |
| 45 | const values = [secret, ...secret.split(/\r?\n/).map((line) => line.trim())]; |
| 46 | return values.flatMap((value) => { |
| 47 | if (!value || value.includes("\n")) return []; |
| 48 | const base64 = btoa(String.fromCharCode(...new TextEncoder().encode(value))); |
| 49 | return [value, base64.replace(/=+$/, ""), base64.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_"), encodeURIComponent(value)]; |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | function escape(text: string): string { |
| 54 | return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 55 | } |