# Secret Redaction Logic in `redactSecrets()`: How Munder-Difflin Prevents Credential Leakage

> Discover the secret redaction logic in Munder-Difflin's redactSecrets function. Learn how cascading regex prevents credential leakage before IPC and storage.

- Repository: [Chaitanya Giri/munder-difflin](https://github.com/chaitanyagiri/munder-difflin)
- Tags: internals
- Published: 2026-08-29

---

**The `redactSecrets()` function in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) employs a cascading regex-based pipeline to detect PEM private keys, JWTs, API tokens, and key-value secrets, replacing them with `[redacted]` before they cross the IPC boundary to the renderer or persistent storage.**

Munder-Difflin’s main process implements a defensive security boundary to ensure sensitive credentials never leak into logs, telemetry, or renderer processes. At the core of this safeguard stands `redactSecrets()`, a centralized sanitization routine defined at lines 62-89 of [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) that inspects every string before it leaves the privileged main context.

## How `redactSecrets()` Works

The implementation operates through seven distinct validation and transformation stages. Each stage targets a specific category of secret material using deterministic regular expressions.

### Input Validation and Type Safety

The function first validates that the input is a non-empty string. If the value is `undefined`, `null`, or a number, the function returns the original value unchanged (or an empty string for non-string types). This early exit prevents runtime errors that could expose stack traces containing sensitive data.

### PEM Private Key Detection

A regex pattern identifies standard PEM-encoded private keys by matching `-----BEGIN ... PRIVATE KEY-----` headers through their corresponding `-----END ... PRIVATE KEY-----` footers. This covers RSA, EC, OpenSSH, and PGP formats. The entire block is replaced with the literal string `[redacted]`.

### JSON Web Token (JWT) Redaction

The function detects JWTs by looking for three base64url-encoded segments separated by dots, specifically targeting the characteristic `eyJ` prefix. When found, the complete token string is substituted with `[redacted]`, preventing bearer token leakage in diagnostic output.

### Known Credential Prefix Patterns

The routine enumerates common API key prefixes and replaces any match with `[redacted]`:

- **OpenAI/Anthropic keys**: Patterns like `sk-` and `sk-ant-`
- **Slack tokens**: Prefixes including `xoxb/`, `xoxp/`, `xoxa/`, `xoxr/`, `xoxs-`, and `xapp-`
- **GitHub tokens**: `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, and `github_pat_`
- **AWS access keys**: `AKIA` followed by alphanumeric characters
- **Google API keys**: `AIza` prefix sequences

### Bearer Token Sanitization

Rather than removing the authentication type entirely, the function preserves the word **bearer** (case-insensitive) but strips the subsequent token value. Sequences of 8 or more URL-safe characters following "bearer" are replaced, resulting in `bearer [redacted]`. This maintains log readability while eliminating credential exposure.

### Key-Value Secret Assignments

A broad pattern captures assignment syntax such as `api_key = "value"` or `secret: value`. The regex matches keys containing sensitive identifiers like `api_key`, `secret_access_key`, `token`, and `password`, including optional namespace prefixes like `aws_` or `gcp_` to catch composite names. The implementation preserves the key name and surrounding punctuation while replacing only the value with `[redacted]`.

## Why This Architecture Prevents Leakage

The `redactSecrets()` implementation provides three critical security guarantees that eliminate credential exposure vectors.

**Centralized Deterministic Sanitization**
All outgoing messages—including email subjects, bodies, logs, and telemetry—are funneled through `redactSecrets()` before crossing the IPC boundary. As implemented in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) at lines 1792-1840, this single chokepoint guarantees that no raw credential reaches external services or the renderer process.

**Pattern-Driven Whitelist Approach**
By targeting only documented secret shapes rather than applying broad heuristics, the function avoids over-redaction that would impair debugging while still catching the vast majority of credential formats encountered in production environments.

**Defensive Programming for Edge Cases**
The function's strict input validation ensures that unexpected data types cannot trigger exceptions that might leak secrets in error messages. This defensive design aligns with the test-driven implementation found in `test/voice-messages.test.cjs`, which asserts that each regex pattern successfully strips secrets without damaging benign content.

## Practical Code Examples

The following TypeScript examples demonstrate how `redactSecrets()` handles various secret types according to the source logic:

```typescript
import { redactSecrets } from './src/main/hive';

// PEM private key block
const pem = `
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqh...
-----END PRIVATE KEY-----
`;
console.log(redactSecrets(pem));
// Output: "[redacted]"

// JWT token
const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.abc123.def456';
console.log(redactSecrets(jwt));
// Output: "[redacted]"

// Bearer token in HTTP header
console.log(redactSecrets('Authorization: Bearer ZYX987654321'));
// Output: "Authorization: bearer [redacted]"

// Key-value assignment
console.log(redactSecrets('aws_secret_access_key=ABCD1234EFGH5678IJKL'));
// Output: "aws_secret_access_key=[redacted]"

// Mixed content with multiple secrets
const mixed = `User token: xoxb-1234567890-abcdef
API key: sk-abcdefghijklmnop`;
console.log(redactSecrets(mixed));
// Output: "User token: [redacted]\nAPI key: [redacted]"

```

## Summary

- **`redactSecrets()`** in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) (lines 62-89) serves as the mandatory sanitization gateway for all strings leaving the main process.
- The function employs **seven distinct regex patterns** targeting PEM keys, JWTs, bearer tokens, and key-value assignments.
- **Known credential prefixes** for OpenAI, Anthropic, Slack, GitHub, AWS, and Google are explicitly detected and removed.
- **Input validation** prevents runtime exceptions that could expose sensitive stack traces.
- **Comprehensive test coverage** in `test/voice-messages.test.cjs` ensures the regex battery remains accurate across updates.
- **IPC boundary protection** documented in [`src/renderer/src/realtime/VOICE-MESSAGE-ACCESS.md`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/renderer/src/realtime/VOICE-MESSAGE-ACCESS.md) mandates that redaction occurs exclusively on the main side before transmission.

## Frequently Asked Questions

### Where is the `redactSecrets()` function located in the Munder-Difflin repository?

The `redactSecrets()` function is implemented in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) at lines 62-89. Usage examples showing integration with the IPC layer appear at lines 1792-1840 in the same file, where the function sanitizes message subjects and bodies before renderer transmission.

### What specific secret formats does `redactSecrets()` detect?

The function detects PEM-encoded private keys (RSA, EC, OpenSSH, PGP), JSON Web Tokens (JWTs), bearer tokens, and API keys from major providers including OpenAI (`sk-`), Anthropic (`sk-ant-`), Slack (`xoxb`, `xoxp`), GitHub (`ghp_`, `github_pat_`), AWS (`AKIA`), and Google (`AIza`). It also matches generic key-value patterns for passwords, tokens, and secret access keys with optional namespace prefixes like `aws_` or `gcp_`.

### How does `redactSecrets()` handle non-string inputs?

If the input is not a non-empty string, the function returns the original value unchanged (or an empty string for non-string types such as `undefined` or `null`). This prevents type coercion errors that might leak sensitive data in exception traces or cause runtime failures.

### Is the redaction logic tested for accuracy?

Yes, the test suite in `test/voice-messages.test.cjs` mirrors the complete regex battery and asserts that each pattern successfully strips secrets while preserving benign content. This ensures the secret redaction logic remains reliable and allows lock-step updates when new credential formats are discovered.