@hop-top/kit 0.4.0-alpha.1 → 0.4.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @module telemetry/installId
3
+ * @package @hop-top/kit
4
+ *
5
+ * Persisted anonymous installation identifier — the TS mirror of
6
+ * `go/runtime/telemetry/installid.go`.
7
+ *
8
+ * On-disk format: 32 raw bytes from `crypto.randomBytes` stored at
9
+ * `<XDG_STATE_HOME>/kit/telemetry/installation_id`. The surface API
10
+ * returns the lowercase hex SHA-256 of those bytes (64 chars) so the
11
+ * file format stays canonical across polyglot SDKs (Go / Py / TS / Rs /
12
+ * PHP) while the hashed string is what flows through events.
13
+ *
14
+ * Perms: file 0600, parent dir 0700.
15
+ */
16
+
17
+ import { promises as fs } from 'node:fs';
18
+ import { existsSync } from 'node:fs';
19
+ import { randomBytes, createHash } from 'node:crypto';
20
+ import { homedir } from 'node:os';
21
+ import * as path from 'node:path';
22
+
23
+ /** installIDSize is the on-disk byte length. SHA-256 of 32 bytes → 64-char hex. */
24
+ const installIDSize = 32;
25
+ /** File mode. */
26
+ const installIDFilePerm = 0o600;
27
+ /** Parent dir mode. */
28
+ const installIDDirPerm = 0o700;
29
+
30
+ /**
31
+ * xdgStateHome returns `$XDG_STATE_HOME` or `~/.local/state` per the
32
+ * XDG Base Directory Spec.
33
+ */
34
+ function xdgStateHome(): string {
35
+ return process.env.XDG_STATE_HOME ?? path.join(homedir(), '.local', 'state');
36
+ }
37
+
38
+ /**
39
+ * installIdPath returns the canonical on-disk path used by this module.
40
+ * Useful for SDK consumers and compliance checks that need to verify
41
+ * the storage location without invoking the read path.
42
+ */
43
+ export function installIdPath(): string {
44
+ return path.join(xdgStateHome(), 'kit', 'telemetry', 'installation_id');
45
+ }
46
+
47
+ /** sha256Hex returns the lowercase hex SHA-256 of buf. */
48
+ function sha256Hex(buf: Buffer): string {
49
+ return createHash('sha256').update(buf).digest('hex');
50
+ }
51
+
52
+ /** readAndValidate reads the file and validates its byte length. */
53
+ async function readAndValidate(p: string): Promise<Buffer> {
54
+ const data = await fs.readFile(p);
55
+ if (data.length !== installIDSize) {
56
+ throw new Error(
57
+ `install_id: file ${p} has wrong size ${data.length} bytes, expected ${installIDSize}`,
58
+ );
59
+ }
60
+ return data;
61
+ }
62
+
63
+ /**
64
+ * getInstallId returns the persisted anonymous install identifier as
65
+ * lowercase hex SHA-256 of 32 random bytes stored on disk. It generates
66
+ * and persists the bytes on first call. Concurrent first calls across
67
+ * processes are race-safe via a tmp + rename pattern with an
68
+ * existence-precheck: if a peer already wrote a valid file by the time
69
+ * we go to rename, we adopt their bytes.
70
+ *
71
+ * Mirrors `telemetry.InstallationID` in Go.
72
+ */
73
+ export async function getInstallId(): Promise<string> {
74
+ const p = installIdPath();
75
+
76
+ // Fast path: file already exists.
77
+ if (existsSync(p)) {
78
+ const data = await readAndValidate(p);
79
+ return sha256Hex(data);
80
+ }
81
+
82
+ // Slow path: generate + write atomically.
83
+ const parent = path.dirname(p);
84
+ await fs.mkdir(parent, { recursive: true, mode: installIDDirPerm });
85
+ // Re-enforce 0700 in case the dir already existed at a looser mode.
86
+ try {
87
+ await fs.chmod(parent, installIDDirPerm);
88
+ } catch {
89
+ // Non-fatal: a parent we can't chmod (e.g. shared dir) is the
90
+ // operator's problem, not ours.
91
+ }
92
+
93
+ const fresh = randomBytes(installIDSize);
94
+ const tmp = p + '.new';
95
+ await fs.writeFile(tmp, fresh, { mode: installIDFilePerm });
96
+
97
+ // First writer wins. If a peer raced us and a valid file already
98
+ // sits at `p`, drop our tmp and adopt their bytes.
99
+ if (existsSync(p)) {
100
+ try {
101
+ await fs.unlink(tmp);
102
+ } catch {
103
+ // tmp may have already been swept; ignore.
104
+ }
105
+ const data = await readAndValidate(p);
106
+ return sha256Hex(data);
107
+ }
108
+
109
+ await fs.rename(tmp, p);
110
+ return sha256Hex(fresh);
111
+ }
112
+
113
+ /**
114
+ * rotate atomically replaces the persisted bytes with 32 fresh
115
+ * `crypto.randomBytes` and returns the new hex. Used by the
116
+ * `kit consent reset` CLI flow.
117
+ *
118
+ * Mirrors `telemetry.Rotate` in Go.
119
+ */
120
+ export async function rotate(): Promise<string> {
121
+ const p = installIdPath();
122
+ const parent = path.dirname(p);
123
+ await fs.mkdir(parent, { recursive: true, mode: installIDDirPerm });
124
+ try {
125
+ await fs.chmod(parent, installIDDirPerm);
126
+ } catch {
127
+ // See getInstallId — non-fatal.
128
+ }
129
+
130
+ const fresh = randomBytes(installIDSize);
131
+ const tmp = p + '.new';
132
+ await fs.writeFile(tmp, fresh, { mode: installIDFilePerm });
133
+ await fs.rename(tmp, p);
134
+ return sha256Hex(fresh);
135
+ }
136
+
137
+ /**
138
+ * resetForTest deletes the persisted file. Test helper exposed so
139
+ * adopters can drive first-run code paths in their own tests. Never
140
+ * call from production code.
141
+ *
142
+ * Mirrors `telemetry.ResetForTest` in Go.
143
+ */
144
+ export async function resetForTest(): Promise<void> {
145
+ const p = installIdPath();
146
+ try {
147
+ await fs.unlink(p);
148
+ } catch {
149
+ // Missing-file is fine.
150
+ }
151
+ // Also clean up any stale *.new from a crashed writer.
152
+ try {
153
+ await fs.unlink(p + '.new');
154
+ } catch {
155
+ // Missing-file is fine.
156
+ }
157
+ }
@@ -0,0 +1,148 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Mode, parseMode, resolveMode } from './mode';
3
+
4
+ // Helper: build an isolated env map per test. We never mutate
5
+ // process.env directly; resolveMode accepts an injected map so the
6
+ // tests stay hermetic.
7
+ function env(vars: Record<string, string | undefined>): NodeJS.ProcessEnv {
8
+ const out: NodeJS.ProcessEnv = {};
9
+ for (const k of Object.keys(vars)) {
10
+ const v = vars[k];
11
+ if (v !== undefined) {
12
+ out[k] = v;
13
+ }
14
+ }
15
+ return out;
16
+ }
17
+
18
+ // ─── parseMode ──────────────────────────────────────────────────────────────
19
+
20
+ describe('parseMode', () => {
21
+ it('returns [Off, true] for empty / null / undefined', () => {
22
+ expect(parseMode('')).toEqual([Mode.Off, true]);
23
+ expect(parseMode(undefined)).toEqual([Mode.Off, true]);
24
+ expect(parseMode(null)).toEqual([Mode.Off, true]);
25
+ });
26
+
27
+ it('parses "off" case-insensitively', () => {
28
+ expect(parseMode('off')).toEqual([Mode.Off, true]);
29
+ expect(parseMode('OFF')).toEqual([Mode.Off, true]);
30
+ expect(parseMode('Off')).toEqual([Mode.Off, true]);
31
+ });
32
+
33
+ it('parses "anon" case-insensitively', () => {
34
+ expect(parseMode('anon')).toEqual([Mode.Anon, true]);
35
+ expect(parseMode('ANON')).toEqual([Mode.Anon, true]);
36
+ expect(parseMode('Anon')).toEqual([Mode.Anon, true]);
37
+ });
38
+
39
+ it('parses "full" case-insensitively', () => {
40
+ expect(parseMode('full')).toEqual([Mode.Full, true]);
41
+ expect(parseMode('FULL')).toEqual([Mode.Full, true]);
42
+ expect(parseMode('Full')).toEqual([Mode.Full, true]);
43
+ });
44
+
45
+ it('trims surrounding whitespace', () => {
46
+ expect(parseMode(' anon ')).toEqual([Mode.Anon, true]);
47
+ expect(parseMode('\tfull\n')).toEqual([Mode.Full, true]);
48
+ });
49
+
50
+ it('returns [Off, true] for whitespace-only', () => {
51
+ // Mirrors Go: trim → "" → empty branch → [Off, true].
52
+ expect(parseMode(' ')).toEqual([Mode.Off, true]);
53
+ });
54
+
55
+ it('returns [Off, false] for unknown tokens', () => {
56
+ expect(parseMode('garbage')).toEqual([Mode.Off, false]);
57
+ expect(parseMode('verbose')).toEqual([Mode.Off, false]);
58
+ expect(parseMode('on')).toEqual([Mode.Off, false]);
59
+ });
60
+ });
61
+
62
+ // ─── resolveMode ────────────────────────────────────────────────────────────
63
+
64
+ describe('resolveMode', () => {
65
+ it('returns Off when no env vars are set', () => {
66
+ expect(resolveMode(env({}))).toBe(Mode.Off);
67
+ });
68
+
69
+ it('reads KIT_TELEMETRY_MODE when no app prefix is registered', () => {
70
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'anon' }))).toBe(Mode.Anon);
71
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'full' }))).toBe(Mode.Full);
72
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'off' }))).toBe(Mode.Off);
73
+ });
74
+
75
+ it('case-insensitively reads KIT_TELEMETRY_MODE', () => {
76
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'ANON' }))).toBe(Mode.Anon);
77
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'Full' }))).toBe(Mode.Full);
78
+ });
79
+
80
+ it('returns Off when KIT_TELEMETRY_MODE is unparseable', () => {
81
+ expect(resolveMode(env({ KIT_TELEMETRY_MODE: 'garbage' }))).toBe(Mode.Off);
82
+ });
83
+
84
+ it('honors <APP>_TELEMETRY_MODE over KIT_TELEMETRY_MODE when both are set', () => {
85
+ // Canonical precedence example from the user spec.
86
+ const got = resolveMode(
87
+ env({
88
+ KIT_APP_PREFIX: 'spaced',
89
+ SPACED_TELEMETRY_MODE: 'full',
90
+ KIT_TELEMETRY_MODE: 'anon',
91
+ }),
92
+ );
93
+ expect(got).toBe(Mode.Full);
94
+ });
95
+
96
+ it('uppercases KIT_APP_PREFIX before composing the env var name', () => {
97
+ // Lowercase prefix → still resolves to SPACED_TELEMETRY_MODE.
98
+ const got = resolveMode(
99
+ env({
100
+ KIT_APP_PREFIX: 'spaced',
101
+ SPACED_TELEMETRY_MODE: 'anon',
102
+ }),
103
+ );
104
+ expect(got).toBe(Mode.Anon);
105
+ });
106
+
107
+ it('falls back to KIT_TELEMETRY_MODE when the app-specific var is unset', () => {
108
+ const got = resolveMode(
109
+ env({
110
+ KIT_APP_PREFIX: 'spaced',
111
+ KIT_TELEMETRY_MODE: 'anon',
112
+ }),
113
+ );
114
+ expect(got).toBe(Mode.Anon);
115
+ });
116
+
117
+ it('falls back to KIT_TELEMETRY_MODE when the app-specific var is unparseable', () => {
118
+ const got = resolveMode(
119
+ env({
120
+ KIT_APP_PREFIX: 'spaced',
121
+ SPACED_TELEMETRY_MODE: 'garbage',
122
+ KIT_TELEMETRY_MODE: 'full',
123
+ }),
124
+ );
125
+ expect(got).toBe(Mode.Full);
126
+ });
127
+
128
+ it('returns Off when both vars are unparseable', () => {
129
+ const got = resolveMode(
130
+ env({
131
+ KIT_APP_PREFIX: 'spaced',
132
+ SPACED_TELEMETRY_MODE: 'maybe',
133
+ KIT_TELEMETRY_MODE: 'verbose',
134
+ }),
135
+ );
136
+ expect(got).toBe(Mode.Off);
137
+ });
138
+
139
+ it('ignores an empty / whitespace-only KIT_APP_PREFIX', () => {
140
+ const got = resolveMode(
141
+ env({
142
+ KIT_APP_PREFIX: ' ',
143
+ KIT_TELEMETRY_MODE: 'anon',
144
+ }),
145
+ );
146
+ expect(got).toBe(Mode.Anon);
147
+ });
148
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @module telemetry/mode
3
+ * @package @hop-top/kit
4
+ *
5
+ * Telemetry Mode + env-variable precedence — the TS mirror of
6
+ * `go/runtime/telemetry/mode.go`. Three tiers control what an emit
7
+ * call ships:
8
+ *
9
+ * - `Mode.Off`: default; emit is a no-op.
10
+ * - `Mode.Anon`: anonymous payload (installation_id, command_path,
11
+ * exit_code, duration_ms, occurred_at, kit_version, sdk_lang/version).
12
+ * - `Mode.Full`: anon + args + flags, both post-redact.
13
+ *
14
+ * See the event-schema doc at `sdk/docs/telemetry-event-schema.md`
15
+ * for the on-wire shape.
16
+ *
17
+ * The env-precedence rule is intentionally simple:
18
+ *
19
+ * 1. If `KIT_APP_PREFIX=spaced` is set AND `SPACED_TELEMETRY_MODE` has
20
+ * a parseable value, that wins.
21
+ * 2. Otherwise `KIT_TELEMETRY_MODE` is consulted.
22
+ * 3. Anything else (missing, garbage, whitespace) → `Mode.Off`.
23
+ */
24
+
25
+ /**
26
+ * Mode controls how much detail the telemetry emitter ships.
27
+ *
28
+ * Encoded as a string-literal union so the on-disk / on-wire token IS
29
+ * the enum value. Mirrors Go's `Mode.String()` which renders these same
30
+ * three lowercase tokens.
31
+ */
32
+ export const Mode = {
33
+ Off: 'off',
34
+ Anon: 'anon',
35
+ Full: 'full',
36
+ } as const;
37
+
38
+ export type Mode = (typeof Mode)[keyof typeof Mode];
39
+
40
+ /**
41
+ * parseMode maps a string token (case-insensitive: "off", "anon",
42
+ * "full") to a Mode. Empty / null / undefined input returns
43
+ * `[Mode.Off, true]` so an unset env var doesn't masquerade as an
44
+ * error. Unknown tokens return `[Mode.Off, false]` so callers can
45
+ * distinguish "operator typoed the env var" from "operator opted out".
46
+ *
47
+ * Mirrors `telemetry.ParseMode` in `go/runtime/telemetry/mode.go`.
48
+ */
49
+ export function parseMode(s: string | undefined | null): [Mode, boolean] {
50
+ if (s === undefined || s === null || s === '') {
51
+ return [Mode.Off, true];
52
+ }
53
+ const low = s.trim().toLowerCase();
54
+ if (low === '') {
55
+ return [Mode.Off, true];
56
+ }
57
+ for (const m of Object.values(Mode)) {
58
+ if (m === low) {
59
+ return [m, true];
60
+ }
61
+ }
62
+ return [Mode.Off, false];
63
+ }
64
+
65
+ /** resolveAppPrefix normalises KIT_APP_PREFIX to uppercase (matches Go). */
66
+ function resolveAppPrefix(env: NodeJS.ProcessEnv): string {
67
+ return (env.KIT_APP_PREFIX ?? '').trim().toUpperCase();
68
+ }
69
+
70
+ /**
71
+ * resolveMode reads the env vars in canonical precedence order and
72
+ * returns the resolved Mode. Defaults to `Mode.Off`.
73
+ *
74
+ * Precedence (mirrors `telemetry.readEnvMode`):
75
+ *
76
+ * 1. `<APP>_TELEMETRY_MODE` where `<APP>` = uppercased `KIT_APP_PREFIX`.
77
+ * 2. `KIT_TELEMETRY_MODE`.
78
+ * 3. `Mode.Off`.
79
+ *
80
+ * Unparseable values at any tier are skipped (NOT a hard error); the
81
+ * resolver falls through to the next tier and ultimately to Off.
82
+ *
83
+ * @param env Inject a custom env map for testing. Defaults to `process.env`.
84
+ */
85
+ export function resolveMode(env: NodeJS.ProcessEnv = process.env): Mode {
86
+ const app = resolveAppPrefix(env);
87
+ if (app) {
88
+ const v = (env[`${app}_TELEMETRY_MODE`] ?? '').trim();
89
+ if (v) {
90
+ const [m, ok] = parseMode(v);
91
+ if (ok) {
92
+ return m;
93
+ }
94
+ }
95
+ }
96
+ const v = (env.KIT_TELEMETRY_MODE ?? '').trim();
97
+ if (v) {
98
+ const [m, ok] = parseMode(v);
99
+ if (ok) {
100
+ return m;
101
+ }
102
+ }
103
+ return Mode.Off;
104
+ }
@@ -0,0 +1,133 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import * as os from 'node:os';
3
+ import { redact, redactString } from './redact';
4
+
5
+ describe('redactString — single pattern coverage', () => {
6
+ it('redacts emails', () => {
7
+ expect(redactString('contact me at jane.doe+sub@example.co.uk now')).toBe(
8
+ 'contact me at <redacted:email> now',
9
+ );
10
+ });
11
+
12
+ it('redacts IPv4 addresses', () => {
13
+ expect(redactString('host 10.0.0.1 saw 192.168.1.255')).toBe(
14
+ 'host <redacted:ipv4> saw <redacted:ipv4>',
15
+ );
16
+ });
17
+
18
+ it('redacts IPv6 addresses (full 8-group form)', () => {
19
+ expect(
20
+ redactString('peer 2001:db8:1234:5678:abcd:ef01:2345:6789 down'),
21
+ ).toBe('peer <redacted:ipv6> down');
22
+ });
23
+
24
+ it('redacts IPv6 compressed `::` form', () => {
25
+ // Cross-SDK pattern (matches PHP) covers compressed forms.
26
+ expect(redactString('addr 2001:db8::1 here')).toBe(
27
+ 'addr <redacted:ipv6> here',
28
+ );
29
+ });
30
+
31
+ it('redacts IPv6 link-local fe80::', () => {
32
+ expect(redactString('peer fe80::1234:5678:abcd:ef01 up')).toBe(
33
+ 'peer <redacted:ipv6> up',
34
+ );
35
+ });
36
+
37
+ it('does NOT redact bare `::1` loopback (PHP-parity under-match)', () => {
38
+ // The PHP-parity pattern requires at least one hex group BEFORE
39
+ // `::`, so the bare `::1` loopback is intentionally NOT matched.
40
+ // Documented trade-off (parity > drift); see redact.ts header.
41
+ expect(redactString('ping ::1 ok')).toBe('ping ::1 ok');
42
+ });
43
+
44
+ it('IPv4-mapped `::ffff:a.b.c.d` — IPv4 pass mops up the tail', () => {
45
+ // No leading hex group before `::`, so the IPv6 pass skips the
46
+ // `::ffff` prefix; the IPv4 pass then redacts the dotted-quad.
47
+ const out = redactString('hybrid ::ffff:192.168.1.1 here');
48
+ expect(out).not.toContain('192.168.1.1');
49
+ expect(out).toContain('<redacted:ipv4>');
50
+ });
51
+
52
+ it('redacts sk- tokens', () => {
53
+ expect(redactString('OPENAI=sk-AbCdEf12_-ZZ stop')).toBe(
54
+ 'OPENAI=<redacted:token> stop',
55
+ );
56
+ });
57
+
58
+ it('redacts GitHub tokens (ghp/gho/ghu/ghs/ghr)', () => {
59
+ for (const prefix of ['ghp', 'gho', 'ghu', 'ghs', 'ghr']) {
60
+ const token = `${prefix}_${'A'.repeat(20)}`;
61
+ expect(redactString(`token=${token} done`)).toBe(
62
+ 'token=<redacted:token> done',
63
+ );
64
+ }
65
+ });
66
+
67
+ it('redacts xoxb Slack tokens', () => {
68
+ const tok = `xoxb-1-2-${'a'.repeat(30)}`;
69
+ expect(redactString(`slack ${tok}!`)).toBe('slack <redacted:token>!');
70
+ });
71
+
72
+ it('rewrites $HOME prefix to literal $HOME', () => {
73
+ const home = os.homedir();
74
+ expect(redactString(`config at ${home}/.config/kit/x.yaml`)).toBe(
75
+ 'config at $HOME/.config/kit/x.yaml',
76
+ );
77
+ });
78
+
79
+ it('leaves strings without secrets unchanged', () => {
80
+ expect(redactString('all clear, nothing to see')).toBe(
81
+ 'all clear, nothing to see',
82
+ );
83
+ });
84
+ });
85
+
86
+ describe('redact — recursive walks', () => {
87
+ it('walks nested objects', () => {
88
+ const input = {
89
+ user: 'alice@example.com',
90
+ meta: { ip: '127.0.0.1', notes: 'safe' },
91
+ };
92
+ expect(redact(input)).toEqual({
93
+ user: '<redacted:email>',
94
+ meta: { ip: '<redacted:ipv4>', notes: 'safe' },
95
+ });
96
+ });
97
+
98
+ it('walks arrays of mixed types', () => {
99
+ const input = ['user@host.io', 42, true, null, undefined, 'plain'];
100
+ expect(redact(input)).toEqual([
101
+ '<redacted:email>',
102
+ 42,
103
+ true,
104
+ null,
105
+ undefined,
106
+ 'plain',
107
+ ]);
108
+ });
109
+
110
+ it('walks arrays of objects', () => {
111
+ const input = [{ ip: '8.8.8.8' }, { ip: '1.1.1.1' }];
112
+ expect(redact(input)).toEqual([
113
+ { ip: '<redacted:ipv4>' },
114
+ { ip: '<redacted:ipv4>' },
115
+ ]);
116
+ });
117
+
118
+ it('passes non-string scalars through', () => {
119
+ expect(redact(123)).toBe(123);
120
+ expect(redact(0)).toBe(0);
121
+ expect(redact(true)).toBe(true);
122
+ expect(redact(false)).toBe(false);
123
+ expect(redact(null)).toBeNull();
124
+ expect(redact(undefined)).toBeUndefined();
125
+ });
126
+
127
+ it('does not mutate the input object', () => {
128
+ const input = { user: 'bob@example.com', count: 1 };
129
+ const snap = JSON.stringify(input);
130
+ redact(input);
131
+ expect(JSON.stringify(input)).toBe(snap);
132
+ });
133
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @module telemetry/redact
3
+ * @package @hop-top/kit
4
+ *
5
+ * Best-effort PII/secret redactor for telemetry attrs — the TS mirror
6
+ * of `hop_top_kit/telemetry/redact.py`.
7
+ *
8
+ * NOT parity with `go/core/redact`: this is an opinionated regex set
9
+ * covering common leak shapes (emails, IPs, common token prefixes,
10
+ * $HOME paths). The placeholder strings (`<redacted:email>`,
11
+ * `<redacted:ipv4>`, `<redacted:ipv6>`, `<redacted:token>`) MUST match
12
+ * byte-for-byte across the py / ts / rs / php SDKs so the cross-language
13
+ * contract harness can diff outputs without per-language quirks.
14
+ *
15
+ * Callers can layer their own `redactor` callback on `Client`; it runs
16
+ * BEFORE this default pass.
17
+ */
18
+ import * as os from 'node:os';
19
+
20
+ // Pattern order mirrors the py SDK: tokens FIRST (before IP/email) so
21
+ // we don't accidentally eat numeric-looking fragments inside an xoxb
22
+ // token; $HOME LAST so its tail-capture doesn't swallow an embedded
23
+ // email- or ip-shaped substring before the dedicated patterns ran.
24
+ const TOKEN_SK = /\bsk-[A-Za-z0-9_-]{8,}\b/g;
25
+ const TOKEN_GH = /\bgh[pousr]_[A-Za-z0-9_-]{16,}\b/g;
26
+ const TOKEN_XOXB = /\bxoxb-[0-9]+-[0-9]+-[A-Za-z0-9]{24,}\b/g;
27
+ const EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
28
+ // IPv6 regex covers full form (8 groups) AND compressed `::` form
29
+ // (1-7 groups + double colon). Matches PHP SDK behavior for cross-lang
30
+ // parity. May over-match on hex-heavy strings that resemble IPv6 —
31
+ // accepted trade-off (over-redact > leak). The lookbehind/lookahead on
32
+ // `[0-9a-fA-F:]` anchors the match so it can't bleed into adjacent
33
+ // hex tokens (e.g. a UUID fragment touching a colon).
34
+ const IPV6 =
35
+ /(?<![0-9a-fA-F:])(?:(?:[0-9a-fA-F]{1,4}:){1,7}(?::[0-9a-fA-F]{1,4})+|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})(?![0-9a-fA-F:])/g;
36
+ const IPV4 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
37
+
38
+ function escapeRegex(s: string): string {
39
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+ }
41
+
42
+ const HOME = os.homedir();
43
+ // Guard against a missing / unexpanded $HOME (`~`) — emit a pattern
44
+ // that never matches so we don't accidentally rewrite the whole input.
45
+ const HOME_PATTERN: RegExp =
46
+ HOME && HOME !== '~'
47
+ ? new RegExp(escapeRegex(HOME) + '([/\\w.\\-]*)', 'g')
48
+ : /(?!x)x/g;
49
+
50
+ const REPLACEMENTS: ReadonlyArray<readonly [RegExp, string]> = [
51
+ [TOKEN_SK, '<redacted:token>'],
52
+ [TOKEN_GH, '<redacted:token>'],
53
+ [TOKEN_XOXB, '<redacted:token>'],
54
+ [EMAIL, '<redacted:email>'],
55
+ [IPV6, '<redacted:ipv6>'],
56
+ [IPV4, '<redacted:ipv4>'],
57
+ [HOME_PATTERN, '$HOME$1'],
58
+ ];
59
+
60
+ /**
61
+ * redactString applies every pattern in the opinionated set to `s`.
62
+ * Returns a new string; the input is never mutated.
63
+ */
64
+ export function redactString(s: string): string {
65
+ let out = s;
66
+ for (const [pat, repl] of REPLACEMENTS) {
67
+ out = out.replace(pat, repl);
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * redact returns a NEW value with the opinionated regex set applied to
74
+ * every reachable string. Walks plain objects and arrays recursively.
75
+ * Non-string scalars (number, boolean, null, undefined, bigint, symbol)
76
+ * pass through unchanged. Input is never mutated.
77
+ *
78
+ * NOT parity with `go/core/redact`. Use a per-Client redactor callback
79
+ * for stricter or custom rules; this is the default-on backstop.
80
+ */
81
+ export function redact(value: unknown): unknown {
82
+ if (typeof value === 'string') return redactString(value);
83
+ if (Array.isArray(value)) return value.map(redact);
84
+ if (value !== null && typeof value === 'object') {
85
+ const out: Record<string, unknown> = {};
86
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
87
+ out[k] = redact(v);
88
+ }
89
+ return out;
90
+ }
91
+ return value;
92
+ }