Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

13.1 KB
Raw Blame
import { describe, it, expect } from 'bun:test';
import os from 'os';
import {
  redactHomeDir,
  redactAbsolutePaths,
  redactUrlQueryStrings,
  redactResidualQueryStrings,
  redactAssignmentSecrets,
  redactSecrets,
  collapseWhitespace,
  redactText,
  scrubMessage,
  scrubStack,
  scrubError,
  extractErrorType,
  messageTemplate,
  REDACTED,
  MESSAGE_MAX_CHARS,
  STACK_MAX_CHARS,
  STACK_MAX_FRAMES,
} from '../../src/services/telemetry/error-scrub';

describe('error-scrub: redactHomeDir', () => {
  it('replaces the home directory with ~', () => {
    const home = os.homedir();
    const input = `Failed to read ${home}/projects/secret/file.ts`;
    const out = redactHomeDir(input);
    expect(out).not.toContain(home);
    expect(out).toContain('~');
  });

  it('is a no-op when home is not present', () => {
    expect(redactHomeDir('plain message')).toBe('plain message');
  });
});

describe('error-scrub: redactAbsolutePaths', () => {
  it('collapses POSIX absolute paths to basename', () => {
    const out = redactAbsolutePaths('cannot open /var/lib/private/data/config.json now');
    expect(out).toContain('config.json');
    expect(out).not.toContain('/var/lib/private');
  });

  it('collapses Windows drive paths to basename', () => {
    const out = redactAbsolutePaths('open C:\\Users\\bob\\secret\\app.log failed');
    expect(out).toContain('app.log');
    expect(out).not.toContain('C:\\Users\\bob');
  });

  it('leaves relative paths and basenames untouched', () => {
    expect(redactAbsolutePaths('error in config.json')).toBe('error in config.json');
  });
});

describe('error-scrub: redactUrlQueryStrings', () => {
  it('strips query strings (keeps host + path)', () => {
    const out = redactUrlQueryStrings('GET https://api.example.com/v1/data?token=secret123&x=1 failed');
    expect(out).toContain('https://api.example.com/v1/data');
    expect(out).not.toContain('token=secret123');
    expect(out).not.toContain('x=1');
  });

  it('strips fragments too', () => {
    const out = redactUrlQueryStrings('see http://host/path#sessionid=abc');
    expect(out).not.toContain('sessionid=abc');
  });

  it('strips http userinfo (username AND password)', () => {
    const out = redactUrlQueryStrings('GET https://alice:[email protected]/path failed');
    expect(out).not.toContain('alice');
    expect(out).not.toContain('s3cr3t');
    expect(out).toContain(REDACTED);
    expect(out).toContain('@10.0.0.5/path');
  });

  it.each([
    ['ECONNREFUSED postgres://u:p@host:5432/db?sslmode=require', ['u:p', 'sslmode=require'], '@host:5432/db'],
    ['redis://admin:hunter2@cache:6379 down', ['admin', 'hunter2'], '@cache:6379'],
    ['mongodb+srv://user:[email protected]/db retrying', ['user:pass'], '@cluster0.mongodb.net/db'],
    ['mysql://root:[email protected]:3306/app failed', ['root:toor'], '@db.internal:3306/app'],
    ['amqp://guest:guest@broker:5672 unreachable', ['guest:guest'], '@broker:5672'],
  ])('redacts connection-string secrets from %s', (input, secrets, kept) => {
    const out = redactUrlQueryStrings(input);
    for (const secret of secrets) expect(out).not.toContain(secret);
    expect(out).toContain(kept);
  });

  it('redacts Slack webhook path secrets (secret is the path, not the query)', () => {
    // Join at runtime so the file does not contain a contiguous webhook URL
    // (GitHub push protection treats the Slack example host+path as a secret).
    const webhook = ['https://hooks.slack.com', 'services', 'T00000000', 'B00000000', 'abcdefghijklmnopqrstuvwx'].join('/');
    const out = redactUrlQueryStrings(`notify ${webhook} failed`);
    expect(out).not.toContain('T00000000');
    expect(out).not.toContain('abcdefghijklmnopqrstuvwx');
    expect(out).toContain(`https://hooks.slack.com/services/${REDACTED}`);
  });
});

describe('error-scrub: redactResidualQueryStrings', () => {
  it('strips leftover query after path collapse destroyed scheme://', () => {
    const out = redactResidualQueryStrings('GET https:/data?token=secret123&x=1 failed');
    expect(out).not.toContain('token=secret123');
    expect(out).toContain('https:/data');
  });
});

describe('error-scrub: redactAssignmentSecrets', () => {
  it('masks token= and api_key= assignments', () => {
    const out = redactAssignmentSecrets('auth failed token=vendorkey_abc123 api_key=short');
    expect(out).not.toContain('vendorkey_abc123');
    expect(out).not.toContain('api_key=short');
    expect(out).toContain(`token=${REDACTED}`);
    expect(out).toContain(`api_key=${REDACTED}`);
  });

  it('does not treat error code= as a secret', () => {
    expect(redactAssignmentSecrets('provider failed with code=12')).toContain('code=12');
  });
});

describe('error-scrub: redactSecrets', () => {
  const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N';
  const hex = 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef';

  it.each([
    ['contact [email protected] about this', ['[email protected]']],
    ['auth failed for sk-ABCdef1234567890ghij', ['sk-ABCdef1234567890ghij']],
    ['key phc_ABCdef1234567890ghijKLMNOP invalid', ['phc_ABCdef1234567890ghijKLMNOP']],
    [`jwt=${jwt} hash=${hex}`, [jwt, hex]],
    ['creds AKIAIOSFODNN7EXAMPLE rejected', ['AKIAIOSFODNN7EXAMPLE']],
    ['temp key ASIAY34FZKBOKMUTVV7A here', ['ASIAY34FZKBOKMUTVV7A']],
    ['connect failed to 10.0.0.5:5432', ['10.0.0.5']],
  ])('masks secrets in %s', (input, secrets) => {
    const out = redactSecrets(input);
    for (const secret of secrets) expect(out).not.toContain(secret);
    expect(out).toContain(REDACTED);
  });

  it('does NOT mask 3-part version numbers as IPs', () => {
    const out = redactSecrets('claude-mem 13.6.2 ready');
    expect(out).toContain('13.6.2');
  });

  it('still redacts real emails with the BOUNDED regex', () => {
    const out = redactSecrets('contact [email protected] please');
    expect(out).not.toContain('[email protected]');
    expect(out).toContain(REDACTED);
  });
});

describe('error-scrub: collapseWhitespace', () => {
  it('collapses runs of whitespace and trims', () => {
    expect(collapseWhitespace('  a    b\t\tc  ')).toBe('a b c');
  });
});

describe('error-scrub: scrubMessage caps length', () => {
  it('caps message at MESSAGE_MAX_CHARS', () => {
    const out = scrubMessage('x'.repeat(MESSAGE_MAX_CHARS + 200));
    expect(out.length).toBe(MESSAGE_MAX_CHARS);
  });

  it('redacts query tokens on multi-segment URLs (path heuristics must not run first)', () => {
    // Reproducer: collapsing /v1/data?token=… to a basename used to destroy
    // `://`, so URL query redaction never fired and short tokens leaked.
    const out = scrubMessage('GET https://api.example.com/v1/data?token=secret123&x=1 failed');
    expect(out).not.toContain('secret123');
    expect(out).not.toContain('token=');
    expect(out).not.toContain('x=1');
  });

  it('redacts path-like query strings that have no scheme:// prefix', () => {
    const out = scrubMessage('redirect /oauth/callback?access_token=vendorkey_abc123 done');
    expect(out).not.toContain('vendorkey_abc123');
    expect(out).not.toContain('access_token=');
  });

  it('redacts Slack webhook URLs end-to-end', () => {
    const webhook = ['https://hooks.slack.com', 'services', 'T00000000', 'B00000000', 'abcdefghijklmnopqrstuvwx'].join('/');
    const out = scrubMessage(`notify ${webhook} failed`);
    expect(out).not.toContain('T00000000');
    expect(out).not.toContain('abcdefghijklmnopqrstuvwx');
  });
});

describe('error-scrub: scrubStack', () => {
  it('keeps only the top N frames and caps total length', () => {
    const frames = Array.from({ length: 50 }, (_, i) => `    at fn${i} (/abs/path/file${i}.ts:${i}:1)`);
    const stack = ['Error: boom', ...frames].join('\n');
    const out = scrubStack(stack);
    const lineCount = out.split('\n').length;
    // header + at most STACK_MAX_FRAMES frame lines
    expect(lineCount).toBeLessThanOrEqual(STACK_MAX_FRAMES + 1);
    expect(out.length).toBeLessThanOrEqual(STACK_MAX_CHARS);
    expect(out).not.toContain('/abs/path');
  });

  it('returns empty string for non-string input', () => {
    expect(scrubStack(undefined)).toBe('');
    expect(scrubStack(null)).toBe('');
    expect(scrubStack(123 as unknown as string)).toBe('');
  });
});

describe('error-scrub: extractErrorType', () => {
  it('reads the error name/type', () => {
    expect(extractErrorType(new TypeError('x'))).toBe('TypeError');
    expect(extractErrorType(new Error('x'))).toBe('Error');
  });

  it('classifies non-Error throws', () => {
    expect(extractErrorType('boom')).toBe('StringError');
    expect(extractErrorType(null)).toBe('NullError');
    expect(extractErrorType(undefined)).toBe('UndefinedError');
    expect(extractErrorType(42)).toBe('numberError');
    // A plain object's constructor name ('Object') is preferred over the
    // generic fallback; a null-prototype object falls back to 'ObjectError'.
    expect(extractErrorType({})).toBe('Object');
    expect(extractErrorType(Object.create(null))).toBe('ObjectError');
  });
});

describe('error-scrub: scrubError never throws on hostile input', () => {
  it('handles null / undefined / primitives', () => {
    expect(() => scrubError(null)).not.toThrow();
    expect(() => scrubError(undefined)).not.toThrow();
    expect(() => scrubError(42)).not.toThrow();
    expect(() => scrubError('a string error')).not.toThrow();
    const r = scrubError('a string error');
    expect(r.type).toBe('StringError');
    expect(r.message).toBe('a string error');
  });

  it('handles objects with throwing getters', () => {
    const hostile: Record<string, unknown> = {};
    Object.defineProperty(hostile, 'message', {
      enumerable: true,
      get() {
        throw new Error('gotcha');
      },
    });
    Object.defineProperty(hostile, 'stack', {
      enumerable: true,
      get() {
        throw new Error('gotcha2');
      },
    });
    expect(() => scrubError(hostile)).not.toThrow();
    const r = scrubError(hostile);
    expect(typeof r.type).toBe('string');
    expect(typeof r.message).toBe('string');
    expect(typeof r.stack).toBe('string');
  });

  it('handles circular references', () => {
    const circular: Record<string, unknown> = { name: 'X' };
    circular.self = circular;
    expect(() => scrubError(circular)).not.toThrow();
  });

  it('redacts a real Error end to end', () => {
    const home = os.homedir();
    const err = new Error(`open ${home}/repo/secret.ts for user [email protected] token sk-ABCdef1234567890ghij`);
    const out = scrubError(err);
    expect(out.type).toBe('Error');
    expect(out.message).not.toContain(home);
    expect(out.message).not.toContain('[email protected]');
    expect(out.message).not.toContain('sk-ABCdef1234567890ghij');
  });
});

describe('error-scrub: messageTemplate collapses varying ids', () => {
  it('collapses numbers and quoted values to a stable template', () => {
    const a = messageTemplate('User 12 not found in "repo-alpha"');
    const b = messageTemplate('User 9999 not found in "repo-beta"');
    expect(a).toBe(b);
  });

  it('never throws on non-string', () => {
    expect(() => messageTemplate(null)).not.toThrow();
    expect(messageTemplate(null)).toBe('');
  });
});

describe('error-scrub: redactText handles non-strings', () => {
  it('returns empty for null/undefined', () => {
    expect(redactText(null)).toBe('');
    expect(redactText(undefined)).toBe('');
  });
});

describe('error-scrub: ReDoS / CPU-DoS bound (perf)', () => {
  // These inputs drove the email/JWT/generic-token regexes O(n²) before the
  // MAX_RAW_INPUT_CHARS cap + bounded quantifiers. Pre-fix, scrubbing a 200KB
  // hostile string took seconds (measured 200KB → ~32s). Post-fix it must be
  // well under 100ms because no regex ever sees more than ~8KB.
  const BUDGET_MS = 100;

  it('scrubs a 200KB email-local-part run (no @) well under 100ms', () => {
    const hostile = 'a.b-c_d%e+f'.repeat(20000); // ~220KB of local-part chars, no '@'
    const t0 = performance.now();
    const out = scrubMessage(hostile);
    const elapsed = performance.now() - t0;
    expect(typeof out).toBe('string');
    expect(out.length).toBeLessThanOrEqual(MESSAGE_MAX_CHARS);
    expect(elapsed).toBeLessThan(BUDGET_MS);
  });

  it('scrubs a 100KB base64 blob well under 100ms', () => {
    const blob = 'A1b2C3d4E5f6G7h8'.repeat(7000); // ~112KB base64url-ish, digit-laden
    const t0 = performance.now();
    const out = scrubMessage(blob);
    const elapsed = performance.now() - t0;
    expect(typeof out).toBe('string');
    expect(elapsed).toBeLessThan(BUDGET_MS);
  });

  it('scrubs a 200KB hostile stack well under 100ms', () => {
    const hostile = 'x.y-z_w%v+u'.repeat(20000);
    const t0 = performance.now();
    const out = scrubStack(`Error: boom\n    at fn (${hostile})`);
    const elapsed = performance.now() - t0;
    expect(typeof out).toBe('string');
    expect(out.length).toBeLessThanOrEqual(STACK_MAX_CHARS);
    expect(elapsed).toBeLessThan(BUDGET_MS);
  });

  it('scrubError end-to-end on a 200KB hostile message is bounded', () => {
    const hostile = 'a.b-c_d%e+f'.repeat(20000);
    const t0 = performance.now();
    const out = scrubError(new Error(hostile));
    const elapsed = performance.now() - t0;
    expect(out.message.length).toBeLessThanOrEqual(MESSAGE_MAX_CHARS);
    expect(elapsed).toBeLessThan(BUDGET_MS);
  });
});