Skip to content

Add automatic credit card masking - #8

Open
alkinbg wants to merge 1 commit into
fuko-php:masterfrom
alkinbg:issue-2-hide-credit-cards
Open

Add automatic credit card masking#8
alkinbg wants to merge 1 commit into
fuko-php:masterfrom
alkinbg:issue-2-hide-credit-cards

Conversation

@alkinbg

@alkinbg alkinbg commented Aug 13, 2026

Copy link
Copy Markdown

Closes #2

What changed

Added automatic credit card number detection to Protect::protect().

Card numbers no longer need to be registered explicitly as sensitive values.
Candidates are detected in scalar values, validated using the Luhn checksum
and then passed through the existing Redact::redact() mechanism.

The implementation supports:

  • 13–19 digit PANs
  • numbers with spaces or hyphens
  • multiple card numbers in the same value
  • card numbers surrounded by other numeric data

I kept the detection separate from the actual redaction logic so existing
custom Redact callbacks continue to work unchanged.

Why the detection is a little more than a regex

A simple regex works for basic cases, but it becomes unreliable when other
numbers are next to the PAN.

For example:

4111 1111 1111 1111 123

or:

Order 123 4111 1111 1111 1111

A greedy match can include the extra digits, fail Luhn validation and leave
the actual card number unprotected.

_redactCreditCardSequence() therefore examines the numeric groups inside the
matched sequence and redacts only the valid PAN range.

False positives

The detector does not redact a value based only on its length.

Candidates must pass Luhn validation, and repeated-digit values such as
0000000000000000 are ignored.

Contiguous values longer than 19 digits are also left untouched, even when
they contain a valid PAN as a prefix.

Backward compatibility

One issue I noticed while implementing this was that running every scalar
through preg_replace_callback() converts non-string values to strings.

The implementation returns the original scalar when no redaction occurred, so
integers, floats and booleans keep their original type.

Tests

Added coverage for:

  • Visa, Mastercard and Amex test numbers
  • 13- and 19-digit boundaries
  • space- and hyphen-formatted PANs
  • PANs next to expiry/CVV/other numeric values
  • multiple and adjacent PANs
  • invalid Luhn values and other false positives
  • preservation of non-string scalar types
  • nested arrays
  • custom Redact callbacks

Full test suite:

128 tests, 179 assertions

@alkinbg
alkinbg force-pushed the issue-2-hide-credit-cards branch from 6a631f2 to b6c70c3 Compare August 13, 2026 13:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Hide credit cards

1 participant