BBizKit

redact.token

v0.1.0 latest

Redact a token or API key with configurable head/tail preservation, per PCI DSS data security principles.

redacttokenapi-keysecretpci-dssmaskingsecurity

Redact a token or API key with configurable head/tail preservation, per PCI DSS data security principles.

Signature

function token(v: string, opt?: TokenRedactOptions): string

Type Definitions:

Problem

API keys, session tokens, and secrets appear in logs, error messages, and configuration dumps. Full exposure compromises security; full masking prevents identification of which key caused an issue. Configurable partial masking is needed to balance security and debuggability.

How It Works

Without options, returns the fixed-length mask '***' to prevent length inference. With keepHead/keepTail, preserves the specified leading and trailing characters and replaces the middle with '' characters. If keepHead + keepTail >= value length, returns the value unchanged (nothing to mask).

Boundaries

  • Does not validate token format or structure.
  • Without options, always returns '****' regardless of input length — prevents length inference.
  • Returns the value unchanged if keepHead + keepTail >= value.length.

Replaces

Common boilerplate this function replaces:

v.slice(0, keepHead) + '*'.repeat(v.length - keepHead - keepTail) + v.slice(-keepTail)

Examples

redact.token("sk_live_abc123xyz");  // "****"
redact.token("sk_live_abc123xyz", { keepHead: 7 });  // "sk_live************"
redact.token("sk_live_abc123xyz", { keepHead: 3, keepTail: 3 });  // "sk_*************xyz"
redact.token("ab", { keepHead: 1, keepTail: 1 });  // "ab"

Standards

Caveats

  • No-options mode always returns exactly '****' (4 asterisks) — this is intentional to prevent length inference.
  • keepHead and keepTail values of 0 are treated the same as omitted — triggering the fixed-length mask.

FAQ

How to safely log API keys in JavaScript?

redact.token('sk_live_abc123') returns '****' — a fixed-length mask that prevents length inference.

How to show the beginning of a token for debugging?

Use keepHead: redact.token('sk_live_abc123', { keepHead: 7 }) returns 'sk_live******' — preserves the prefix for identification.

How to mask secrets while keeping head and tail visible?

Use both keepHead and keepTail: redact.token('key_abc123xyz', { keepHead: 4, keepTail: 3 }) preserves 'key_' and 'xyz', masking the middle.

Why does token redaction without options return a fixed-length string?

Returning a fixed '****' prevents attackers from inferring the original token length from the masked output.

What happens if keepHead + keepTail exceeds the token length?

The value is returned unchanged — there are no characters left to mask.