Files
skills/docs/foundation/data/data-masking/src/strategies/partial.md
2026-05-29 08:20:56 +01:00

2.8 KiB

partial strategy

Purpose

The partial masking strategy preserves a configurable number of characters at the start and end of an input string while replacing the middle portion with asterisks. This is the most commonly needed masking shape for fields like API keys, account numbers, and reference codes where enough context must remain for humans to identify a value in logs without exposing the sensitive body.

Features

  • Configurable keepFirst (default 0) and keepLast (default 4) character counts via MaskRule.
  • Safe handling of short strings: when keepFirst + keepLast >= length the original value is returned unchanged rather than producing an empty or misleading result.
  • No external dependencies — pure string slicing.

Usage: Basic Example

import { maskPartial } from '@suaveplan/data-masking/strategies/partial';

// Keep last 4 characters (default keepLast = 4, keepFirst = 0)
const masked = maskPartial('sk_live_abc123xyz789', {
  fields: ['apiKey'],
  strategy: 'partial',
});
// masked → '****************789' (last 3 chars shown — "789" ends value)

Usage: Advanced Example

import { maskPartial } from '@suaveplan/data-masking/strategies/partial';

// Keep first 2 and last 4 characters
const masked = maskPartial('4111111111111111', {
  fields: ['cardNumber'],
  strategy: 'partial',
  keepFirst: 2,
  keepLast: 4,
});
// masked → '41**********1111'

// Short string — no masking applied
const short = maskPartial('abc', {
  fields: ['code'],
  strategy: 'partial',
  keepFirst: 2,
  keepLast: 2,
});
// short → 'abc'  (keepFirst + keepLast >= length)

API Reference

maskPartial(value, rule)

function maskPartial(value: string, rule: MaskRule): string;
Parameter Type Default Description
value string — The original string.
rule.keepFirst number 0 Characters to keep from the start.
rule.keepLast number 4 Characters to keep from the end.

Returns the masked string, or the original value unchanged if it is too short to mask.

Does not throw.

Implementation Notes

  • The mask character is always "*". A future extension could expose a maskChar option on MaskRule if needed.
  • keepFirst + keepLast >= len guard prevents edge cases where slice would produce overlapping or inverted ranges, which can silently produce empty strings in JavaScript.
  • Middle length is computed as len - keepFirst - keepLast to give a mask block that exactly fills the hidden region, preserving total length and allowing callers to spot-check that masking was applied.