Skip to content

A tiny package to secure Token masking with NIST/PCI-DSS/OWASP compliance

License

Notifications You must be signed in to change notification settings

ekaone/mask-token

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

mask-token

Secure token masking with NIST/PCI-DSS/OWASP compliance

npm version License: MIT TypeScript Bundle Size

Token masking library for JavaScript/TypeScript. Masks API keys, secrets, and tokens while preserving context for debugging and compliance.

✨ Features

  • πŸ”’ Security-First: NIST SP 800-122, PCI-DSS, and OWASP A02 compliant
  • 🎯 Smart Detection: Auto-detects 43+ token types (NPM, GitHub, Stripe, AWS, etc.)
  • πŸ›‘οΈ Entropy-Safe: Fixed-length masking prevents length-based attacks
  • ⚠️ Input Validation: Detects and warns about placeholder values and mistakes
  • 🎨 Customizable: 4 built-in presets + full configuration options
  • πŸ“¦ Lightweight: ~5 KB gzipped, zero dependencies
  • πŸ”§ TypeScript: Full type safety with comprehensive IntelliSense
  • 🌳 Tree-Shakeable: ESM exports for optimal bundle size

πŸ“¦ Installation

npm install @ekaone/mask-token
yarn add @ekaone/mask-token
pnpm add @ekaone/mask-token

πŸš€ Quick Start

import { maskToken } from '@ekaone/mask-token';

// Basic usage - auto-detects token type
maskToken('npm_a1b2c3d4e5f6g7h8i9j0');
// β†’ 'npm_β€’β€’β€’β€’β€’β€’β€’β€’i9j0'

// Works with GitHub tokens
maskToken('ghp_abcdefghijklmnopqrstuvwxyz123456');
// β†’ 'ghp_β€’β€’β€’β€’β€’β€’β€’β€’3456'

// Stripe keys
maskToken('sk_test_XXXXXXXXXXXXXXXXXXXX');
// β†’ 'sk_test_β€’β€’β€’β€’β€’β€’β€’β€’XXXX'

// AWS keys
maskToken('AKIAIOSFODNN7EXAMPLE');
// β†’ 'AKIAβ€’β€’β€’β€’β€’β€’β€’β€’MPLE'

πŸ“š Usage Examples

Security Presets

Choose from 4 optimized presets for different use cases:

import { presets } from '@ekaone/mask-token';

const token = 'sk_test_XXXXXXXXXXXXXXXXXXXX';

// Strict - Maximum security (production logs, compliance)
presets.strict(token);
// β†’ 'sk_test_β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’XXXX'

// Balanced - Good for general use
presets.balanced(token);
// β†’ 'sk_test_XXβ€’β€’β€’β€’β€’β€’β€’β€’XXXX'

// Lenient - More visible (development only)
presets.lenient(token);
// β†’ 'sk_test_XXXX******XXXXXX'

// UI - Optimized for user interfaces
presets.ui(token);
// β†’ 'sk_test_XXXXβ€’β€’β€’β€’β€’β€’β€’β€’XXXX'

Custom Configuration

import { maskToken } from '@ekaone/mask-token';

maskToken('secret123', {
  fixedLength: 12,      // Fixed mask length (entropy-safe)
  showHead: 2,          // Show first 2 chars
  showTail: 3,          // Show last 3 chars
  maskChar: 'β–ˆ',        // Custom mask character
});
// β†’ 'seβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ123'

Input Validation

Detect potential mistakes before they become security issues:

import { maskToken } from '@ekaone/mask-token';

// Detects placeholder values
maskToken('undefined', { warnIfPlain: true });
// ⚠️ Console warning: "Looks like a placeholder value"
// β†’ 'β€’β€’β€’β€’β€’β€’β€’β€’ned'

// Detects wrong credential types
maskToken('my_password', { warnIfPlain: true });
// ⚠️ Console warning: "Might be a different credential type"
// β†’ 'β€’β€’β€’β€’β€’β€’β€’β€’word'

// Custom validation rules
maskToken(input, {
  warnIfPlain: true,
  validators: {
    minLength: 20,
    noSpaces: true,
    pattern: /^[A-Za-z0-9_-]+$/
  }
});

Custom Token Prefixes

Register your own token formats:

import { registerPrefix, maskToken } from '@ekaone/mask-token';

// Register custom prefix
registerPrefix('myapp_', 'MyApp API Key');

// Now it's auto-detected
maskToken('myapp_secret123456789');
// β†’ 'myapp_β€’β€’β€’β€’β€’β€’β€’β€’6789'

Get Token Metadata

import { maskToken } from '@ekaone/mask-token';

const result = maskToken('npm_secret123', { 
  includeMetadata: true 
});

console.log(result);
// {
//   masked: 'npm_β€’β€’β€’β€’β€’β€’β€’β€’t123',
//   metadata: {
//     type: 'NPM Token',
//     prefix: 'npm_',
//     confidence: 0.6,
//     isLikelyToken: false
//   },
//   validation: { valid: true, warnings: [], riskScore: 0 },
//   original: { length: 13, hasPrefix: true }
// }

Batch Processing

import { maskToken } from '@ekaone/mask-token';

const tokens = [
  'npm_abc123',
  'ghp_xyz789',
  'sk_test_secret'
];

const masked = tokens.map(t => maskToken(t));
// [
//   'npm_β€’β€’β€’β€’β€’β€’β€’β€’123',
//   'ghp_β€’β€’β€’β€’β€’β€’β€’β€’789',
//   'sk_test_β€’β€’β€’β€’β€’β€’ret'
// ]

JWT Tokens

import { maskToken } from '@ekaone/mask-token';

const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';

maskToken(jwt, { mode: 'jwt' });
// β†’ 'eyJβ€’β€’β€’.eyJβ€’β€’β€’.dozβ€’β€’β€’'

🎯 API Reference

Main Function

maskToken(token, options?)

Masks a token with intelligent defaults.

Parameters:

  • token (string): Token to mask
  • options (MaskOptions, optional): Configuration options

Returns: string | MaskResult

Example:

maskToken('npm_secret123');
// β†’ 'npm_β€’β€’β€’β€’β€’β€’β€’β€’t123'

Options

interface MaskOptions {
  // Masking behavior
  fixedLength?: number | boolean;  // Fixed mask length (default: 8)
  showTail?: number;               // Chars to show from end (default: 4)
  showHead?: number;               // Chars to show from start (default: 0)
  maskChar?: string;               // Masking character (default: 'β€’')
  
  // Prefix handling
  preservePrefix?: boolean | string[];  // Auto-detect prefixes (default: true)
  customPrefixes?: Record<string, string>;  // Custom prefix definitions
  
  // Security & validation
  warnIfPlain?: boolean;           // Warn about suspicious inputs (default: false)
  validators?: ValidationRules;    // Custom validation rules
  onWarning?: (result: ValidationResult) => void;  // Warning callback
  
  // Advanced
  mode?: 'auto' | 'jwt' | 'custom';  // Masking mode (default: 'auto')
  segments?: SegmentConfig;        // Segment configuration
  includeMetadata?: boolean;       // Return full result (default: false)
  preset?: 'strict' | 'balanced' | 'lenient' | 'ui';  // Use preset
}

Presets

presets.strict(token)

Maximum security preset for production environments.

presets.balanced(token)

Balanced preset for general use.

presets.lenient(token)

Lenient preset for development (NOT for production).

presets.ui(token)

UI-optimized preset for user interfaces.

Utilities

registerPrefix(prefix, description)

Register a custom token prefix for auto-detection.

registerPrefix('myapp_', 'MyApp API Key');

detectTokenType(input)

Detect token type from input string.

const metadata = detectTokenType('npm_abc123');
// {
//   type: 'NPM Token',
//   prefix: 'npm_',
//   confidence: 0.6,
//   isLikelyToken: false
// }

validateToken(input, rules?)

Validate input for token-like characteristics.

const result = validateToken('undefined', {
  minLength: 20,
  noSpaces: true
});
// {
//   valid: false,
//   warnings: [
//     'Input too short (9 < 20)',
//     'Looks like an undefined or null value'
//   ],
//   suggestions: [
//     'Ensure you are passing the full token string',
//     'Replace placeholder with actual token value'
//   ],
//   riskScore: 80
// }

definePreset(config)

Create a custom reusable preset.

const myPreset = definePreset({
  name: 'corporate',
  fixedLength: 16,
  showTail: 6,
  maskChar: 'β–ˆ'
});

myPreset('secret123');
// β†’ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆret123

πŸ”’ Security Features

1. Entropy-Safe Fixed-Length Masking

Prevents length-based enumeration attacks by using a fixed-length mask:

// Without fixed length (INSECURE - reveals length)
maskToken('short', { fixedLength: false });      // β†’ 'β€’hort'
maskToken('verylongtoken', { fixedLength: false }); // β†’ 'β€’β€’β€’β€’β€’β€’β€’β€’β€’oken'
// ❌ Attacker knows one token is longer

// With fixed length (SECURE - hides length)
maskToken('short');           // β†’ 'β€’β€’β€’β€’β€’β€’β€’β€’hort'
maskToken('verylongtoken');   // β†’ 'β€’β€’β€’β€’β€’β€’β€’β€’oken'
// βœ… Same mask length, no information leaked

2. Automated Prefix Preservation

Preserves context without exposing secrets:

maskToken('npm_secret123');
// β†’ 'npm_β€’β€’β€’β€’β€’β€’β€’β€’123'
// βœ… You know it's an NPM token without seeing the secret

3. Input Validation (Leaked Token Detection)

Catches common mistakes before they become security issues:

maskToken('undefined', { warnIfPlain: true });
// ⚠️ Warning: Looks like a placeholder value

maskToken('my password', { warnIfPlain: true });
// ⚠️ Warning: Contains whitespace (tokens typically do not)

4. Compliance

  • NIST SP 800-122: Context retention through prefix preservation
  • PCI-DSS: Head/tail identification (show last 4 digits)
  • OWASP A02: Entropy hiding via fixed-length masking

🎨 Supported Token Types

mask-token automatically detects 43+ token formats including:

Version Control & CI/CD

  • NPM (npm_)
  • GitHub (ghp_, gho_, ghu_, ghs_, ghr_)
  • GitLab (glpat-, gldt-)
  • Docker Hub (dckr_pat_)

Payment & Commerce

  • Stripe (sk_test_, sk_live_, pk_test_, pk_live_)
  • Shopify (shpat_, shpca_, shpss_)

Communication

  • Slack (xoxb-, xoxp-, xoxa-, xoxr-)
  • Twilio (SK*, AC*)
  • SendGrid (SG.)

Cloud Providers

  • AWS (AKIA, ASIA)
  • Google Cloud (AIza)
  • DigitalOcean (dop_v1_)

AI/ML Services

  • OpenAI (sk-, sk-proj-)
  • Anthropic (sk-ant-)

And many more! View full list

🎯 Use Cases

Production Logs

import { presets } from '@ekaone/mask-token';

logger.info('User authenticated', {
  apiKey: presets.strict(apiKey)
});
// Safe to log, compliant with PCI-DSS

Error Messages

import { maskToken } from '@ekaone/mask-token';

try {
  await fetch(url, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
} catch (error) {
  throw new Error(`Request failed with token ${maskToken(token)}`);
  // Error message is safe to display/log
}

Settings Pages

import { presets } from '@ekaone/mask-token';

function ApiKeyDisplay({ apiKey }) {
  return (
    <div>
      <label>Your API Key</label>
      <input 
        type="text" 
        value={presets.ui(apiKey)} 
        readOnly 
      />
    </div>
  );
}

Documentation

import { maskToken } from '@ekaone/mask-token';

const example = maskToken('sk_test_XXXXXXXXXXXXXXXXXXXX');
// Use in documentation without exposing real keys

βš™οΈ Configuration

TypeScript

Full TypeScript support with comprehensive types:

import { maskToken, MaskOptions, MaskResult } from '@ekaone/mask-token';

const options: MaskOptions = {
  fixedLength: 8,
  showTail: 4,
  maskChar: 'β€’'
};

const result: string = maskToken('secret', options);

Environment-Specific Presets

import { presets } from '@ekaone/mask-token';

const maskFn = process.env.NODE_ENV === 'production'
  ? presets.strict
  : presets.lenient;

console.log(maskFn(apiKey));

πŸ“Š Performance

  • Bundle size: ~5 KB gzipped (full package)
  • Tree-shakeable: Import only what you need
  • Zero dependencies: No supply chain vulnerabilities
  • Fast: Constant-time operations
// Only bundles what you use
import { maskToken } from '@ekaone/mask-token';
// β†’ ~3.8 KB gzipped

import { presets } from '@ekaone/mask-token';
// β†’ ~4.5 KB gzipped

πŸ”§ Advanced Usage

Custom Validation

import { maskToken } from '@ekaone/mask-token';

maskToken(token, {
  warnIfPlain: true,
  validators: {
    minLength: 32,
    pattern: /^sk_/,
    customCheck: (input) => !input.includes('test')
  },
  onWarning: (result) => {
    // Send to error tracking
    Sentry.captureMessage(`Invalid token: ${result.warnings}`);
  }
});

Custom Segment Masking

import { maskToken } from '@ekaone/mask-token';

// Mask UUID-like tokens
maskToken('550e8400-e29b-41d4-a716-446655440000', {
  mode: 'custom',
  segments: {
    delimiter: '-',
    showCharsPerSegment: 2
  }
});
// β†’ '55β€’β€’β€’β€’-e2β€’β€’β€’β€’-41β€’β€’β€’β€’-a7β€’β€’β€’β€’-44β€’β€’β€’β€’'

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Adding New Token Prefixes

To add support for a new token type, edit src/presets/registry.ts:

{
  pattern: 'myservice_',
  name: 'MyService API Token',
  minLength: 32,
  category: 'api',
}

πŸ“ License

MIT Β© 2026

πŸ™ Acknowledgments

This library follows security best practices from:

  • NIST SP 800-122 - Guide to Protecting the Confidentiality of PII
  • PCI-DSS - Payment Card Industry Data Security Standard
  • OWASP Top 10 - A02:2021 – Cryptographic Failures

πŸ”— Links

Related Packages

πŸ’‘ FAQ

Why mask tokens?

Even though tokens are unique and secure, they can be accidentally exposed through:

  • Screenshots shared in Slack/Teams
  • Error messages in logs
  • Customer support tickets
  • Documentation examples
  • Public repositories

Masking tokens prevents these accidental exposures while preserving enough context for debugging.

When should I use which preset?

  • strict: Production logs, compliance requirements, audit trails
  • balanced: General application use, internal tools, developer dashboards
  • lenient: Local development, debugging (never use in production!)
  • ui: Settings pages, user interfaces, mobile apps

Is the masked output reversible?

No. Once a token is masked, the original value cannot be recovered. The masking process is one-way and irreversible by design.

Does this replace proper secret management?

No. This library is for displaying tokens safely, not for storing them. Always use proper secret management solutions (environment variables, secret managers, encrypted storage) for storing tokens.

Related Packages


⭐ If this library helps you, please consider giving it a star on GitHub!

About

A tiny package to secure Token masking with NIST/PCI-DSS/OWASP compliance

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published