aboutsummaryrefslogtreecommitdiffhomepage
path: root/lib/util/sanitize.ts
blob: 1fadb386194199863daff2e981238463520ec854 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import is from '@sindresorhus/is';
import { toBase64 } from './string';

const globalSecrets = new Set<string>();
const repoSecrets = new Set<string>();

export const redactedFields = [
  'authorization',
  'token',
  'githubAppKey',
  'npmToken',
  'npmrc',
  'privateKey',
  'privateKeyOld',
  'gitPrivateKey',
  'forkToken',
  'password',
  'httpsCertificate',
  'httpsPrivateKey',
  'httpsCertificateAuthority',
];

// TODO: returns null or undefined only when input is null or undefined.
export function sanitize(input: string): string;
export function sanitize(
  input: string | null | undefined,
): string | null | undefined;
export function sanitize(
  input: string | null | undefined,
): string | null | undefined {
  if (!input) {
    return input;
  }
  let output: string = input;
  [globalSecrets, repoSecrets].forEach((secrets) => {
    secrets.forEach((secret) => {
      while (output.includes(secret)) {
        output = output.replace(secret, '**redacted**');
      }
    });
  });
  return output;
}

const GITHUB_APP_TOKEN_PREFIX = 'x-access-token:';

export function addSecretForSanitizing(
  secret: string | undefined,
  type = 'repo',
): void {
  if (!is.nonEmptyString(secret)) {
    return;
  }
  const secrets = type === 'repo' ? repoSecrets : globalSecrets;
  secrets.add(secret);
  secrets.add(toBase64(secret));
  if (secret.startsWith(GITHUB_APP_TOKEN_PREFIX)) {
    const trimmedSecret = secret.replace(GITHUB_APP_TOKEN_PREFIX, '');
    secrets.add(trimmedSecret);
    secrets.add(toBase64(trimmedSecret));
  }
}

export function clearRepoSanitizedSecretsList(): void {
  repoSecrets.clear();
}

export function clearGlobalSanitizedSecretsList(): void {
  globalSecrets.clear();
}