Secure token masking with NIST/PCI-DSS/OWASP compliance
Token masking library for JavaScript/TypeScript. Masks API keys, secrets, and tokens while preserving context for debugging and compliance.
- π 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
npm install @ekaone/mask-tokenyarn add @ekaone/mask-tokenpnpm add @ekaone/mask-tokenimport { 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'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'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'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_-]+$/
}
});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'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 }
// }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'
// ]import { maskToken } from '@ekaone/mask-token';
const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';
maskToken(jwt, { mode: 'jwt' });
// β 'eyJβ’β’β’.eyJβ’β’β’.dozβ’β’β’'Masks a token with intelligent defaults.
Parameters:
token(string): Token to maskoptions(MaskOptions, optional): Configuration options
Returns: string | MaskResult
Example:
maskToken('npm_secret123');
// β 'npm_β’β’β’β’β’β’β’β’t123'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
}Maximum security preset for production environments.
Balanced preset for general use.
Lenient preset for development (NOT for production).
UI-optimized preset for user interfaces.
Register a custom token prefix for auto-detection.
registerPrefix('myapp_', 'MyApp API Key');Detect token type from input string.
const metadata = detectTokenType('npm_abc123');
// {
// type: 'NPM Token',
// prefix: 'npm_',
// confidence: 0.6,
// isLikelyToken: false
// }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
// }Create a custom reusable preset.
const myPreset = definePreset({
name: 'corporate',
fixedLength: 16,
showTail: 6,
maskChar: 'β'
});
myPreset('secret123');
// β ββββββββββββββββret123Prevents 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 leakedPreserves context without exposing secrets:
maskToken('npm_secret123');
// β 'npm_β’β’β’β’β’β’β’β’123'
// β
You know it's an NPM token without seeing the secretCatches 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)- 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
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
import { presets } from '@ekaone/mask-token';
logger.info('User authenticated', {
apiKey: presets.strict(apiKey)
});
// Safe to log, compliant with PCI-DSSimport { 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
}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>
);
}import { maskToken } from '@ekaone/mask-token';
const example = maskToken('sk_test_XXXXXXXXXXXXXXXXXXXX');
// Use in documentation without exposing real keysFull 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);import { presets } from '@ekaone/mask-token';
const maskFn = process.env.NODE_ENV === 'production'
? presets.strict
: presets.lenient;
console.log(maskFn(apiKey));- 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 gzippedimport { 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}`);
}
});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β’β’β’β’'Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
To add support for a new token type, edit src/presets/registry.ts:
{
pattern: 'myservice_',
name: 'MyService API Token',
minLength: 32,
category: 'api',
}MIT Β© 2026
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
- @ekaone/mask-card - Credit card masking library
- @ekaone/mask-email - Email address masking library
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.
- 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
No. Once a token is masked, the original value cannot be recovered. The masking process is one-way and irreversible by design.
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.
β If this library helps you, please consider giving it a star on GitHub!