Skip to content

PII Redactor — Go source

Paste text and automatically detect and mask personal data — emails, phone numbers, IP addresses, SSNs, credit card numbers, and dates.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package piiredactor ports src/lib/pii-redactor.ts (dual source: the web lib
// is TypeScript, the CLI lib is Go — kept in lock-step). Pure + deterministic,
// never panics. The table-driven tests in pii_redactor_test.go share vectors
// with src/lib/pii-redactor.test.ts so the two implementations are held to the
// same contract.
//
// Detection mirrors the TS lib exactly: one global candidate regex per type,
// each candidate passing a structural validator (octet ranges, Luhn checksum,
// month/day bounds, E.164 digit budget), then overlap resolution by type
// priority — unambiguous types claim their span before the fuzzy phone
// pattern.
//
// Go's regexp (RE2) has no lookbehind/lookahead, so the anchored TS patterns
// are ported as their greedy bodies plus explicit boundary checks on the bytes
// adjacent to each match (see the boundary funcs in detectors).
package piiredactor

import (
	"regexp"
	"sort"
	"strconv"
	"strings"
)

// PiiType is one of the seven personal-data types the detector knows.
type PiiType string

// The seven PII types, mirroring PiiType in the TS lib.
const (
	TypeEmail      PiiType = "email"
	TypePhone      PiiType = "phone"
	TypeIpv4       PiiType = "ipv4"
	TypeIpv6       PiiType = "ipv6"
	TypeSsn        PiiType = "ssn"
	TypeCreditCard PiiType = "credit-card"
	TypeDate       PiiType = "date"
)

// PiiTypes lists all PII types in display order (PII_TYPES in the TS lib).
var PiiTypes = []PiiType{TypeEmail, TypePhone, TypeIpv4, TypeIpv6, TypeSsn, TypeCreditCard, TypeDate}

// PiiMatch is one detected personal-data item: where it is and what it was.
type PiiMatch struct {
	Type     PiiType
	Start    int // index of the first byte in the input
	End      int // index one past the last byte
	Original string
}

// IsValidLuhn checks the Luhn checksum. digits must be a non-empty string of
// 0-9 (any separator makes it invalid — strip them first). It mirrors
// isValidLuhn in the TS lib.
func IsValidLuhn(digits string) bool {
	if !regexp.MustCompile(`^\d+$`).MatchString(digits) {
		return false
	}
	sum := 0
	double := false
	for i := len(digits) - 1; i >= 0; i-- {
		d := int(digits[i] - '0')
		if double {
			d *= 2
			if d > 9 {
				d -= 9
			}
		}
		sum += d
		double = !double
	}
	return sum%10 == 0
}

// --- Per-type structural validators (regex candidates pass through these) ---

var hexGroupRe = regexp.MustCompile(`^[A-Fa-f0-9]{1,4}$`)

// isValidIpv4 accepts octets 0-255 each; the regex already bounds the shape
// to a dotted quad.
func isValidIpv4(candidate string) bool {
	for _, o := range strings.Split(candidate, ".") {
		n, err := strconv.Atoi(o)
		if err != nil || n > 255 {
			return false
		}
	}
	return true
}

// isValidIpv6 accepts the full 8-group form, or a compressed "::" form
// expanding to at most 8 groups.
func isValidIpv6(candidate string) bool {
	// Lone ":" / "::" (URL scheme separators like https://) carry no hex digits.
	if !strings.ContainsAny(candidate, "0123456789abcdefABCDEF") {
		return false
	}
	groups := strings.Split(candidate, ":")
	hasEmpty := false
	for _, g := range groups {
		if g == "" {
			hasEmpty = true
			break
		}
	}
	if hasEmpty {
		// Compressed: at most one "::", its sides together hold < 8 groups.
		parts := strings.Split(candidate, "::")
		if len(parts) > 2 {
			return false
		}
		var left, right []string
		if parts[0] != "" {
			left = strings.Split(parts[0], ":")
		}
		if len(parts) > 1 && parts[1] != "" {
			right = strings.Split(parts[1], ":")
		}
		if len(left)+len(right) > 7 {
			return false
		}
		return allHexGroups(append(left, right...))
	}
	return len(groups) == 8 && allHexGroups(groups)
}

func allHexGroups(groups []string) bool {
	for _, g := range groups {
		if !hexGroupRe.MatchString(g) {
			return false
		}
	}
	return true
}

var (
	fullDateRe   = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`)
	nonDigitRe   = regexp.MustCompile(`[^0-9]`)
	ipv4ShapeRe  = regexp.MustCompile(`^\d{1,3}(?:\.\d{1,3}){3}$`)
	dateShapeRe  = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
)

// isValidDate checks ISO calendar plausibility: month 01-12, day 01-31.
func isValidDate(candidate string) bool {
	m := fullDateRe.FindStringSubmatch(candidate)
	if m == nil {
		return false
	}
	mm, _ := strconv.Atoi(m[2])
	dd, _ := strconv.Atoi(m[3])
	return mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31
}

// isValidPhone checks the E.164 digit budget (7-15) and structural guards for
// the fuzzy phone shape.
func isValidPhone(candidate string) bool {
	digits := nonDigitRe.ReplaceAllString(candidate, "")
	if len(digits) < 7 || len(digits) > 15 {
		return false
	}
	// A dotted quad is IP-shaped: if it were a valid IP it was already claimed
	// by the ipv4 detector; an invalid one (999.x) is likelier a version string.
	if ipv4ShapeRe.MatchString(candidate) {
		return false
	}
	// YYYY-MM-DD shaped (even an impossible date) is never a phone number.
	if dateShapeRe.MatchString(candidate) {
		return false
	}
	return true
}

// isValidCard accepts 13-19 digits with optional space/dash grouping, plus a
// Luhn checksum.
func isValidCard(candidate string) bool {
	digits := nonDigitRe.ReplaceAllString(candidate, "")
	return len(digits) >= 13 && len(digits) <= 19 && IsValidLuhn(digits)
}

// --- Detectors: a global candidate regex + optional validator + boundary ---

// boundary verifies the bytes adjacent to a candidate match, replacing the
// lookbehind/lookahead assertions of the TS regexes (RE2 has none).
type boundary func(s string, start, end int) bool

func isWordByte(c byte) bool {
	return c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}

func isDigitByte(c byte) bool { return c >= '0' && c <= '9' }

// prevIs reports whether the byte before start satisfies pred; true at start
// of text (nothing precedes — every lookbehind passes).
func prevIs(s string, start int, pred func(byte) bool) bool {
	return start == 0 || pred(s[start-1])
}

// nextIs reports whether the byte at end satisfies pred; true at end of text.
func nextIs(s string, end int, pred func(byte) bool) bool {
	return end >= len(s) || pred(s[end])
}

// ipv6Boundary: TS `(?<![:\w]) ... (?![:\w])`.
func ipv6Boundary(s string, start, end int) bool {
	notColonWord := func(c byte) bool { return c != ':' && !isWordByte(c) }
	return prevIs(s, start, notColonWord) && nextIs(s, end, notColonWord)
}

// ipv4Boundary: TS `(?<![\w.]) ... (?!\.?\d)(?!\w)`.
func ipv4Boundary(s string, start, end int) bool {
	if !prevIs(s, start, func(c byte) bool { return !isWordByte(c) && c != '.' }) {
		return false
	}
	// (?!\.?\d): not a dot followed by a digit; (?!\w): not a word byte.
	if nextIs(s, end, isWordByte) {
		return false
	}
	if end < len(s) && s[end] == '.' && end+1 < len(s) && isDigitByte(s[end+1]) {
		return false
	}
	return true
}

// dateBoundary: TS `(?<!\d) \d{4}-\d{2}-\d{2} (?!\d)`.
func dateBoundary(s string, start, end int) bool {
	return prevIs(s, start, func(c byte) bool { return !isDigitByte(c) }) &&
		nextIs(s, end, func(c byte) bool { return !isDigitByte(c) })
}

// phoneBoundary: TS `(?<![\d(]) ... (?!\d)`.
func phoneBoundary(s string, start, end int) bool {
	return prevIs(s, start, func(c byte) bool { return !isDigitByte(c) && c != '(' }) &&
		nextIs(s, end, func(c byte) bool { return !isDigitByte(c) })
}

type detector struct {
	typ      PiiType
	re       *regexp.Regexp
	validate func(string) bool
	boundary boundary
}

// detectors mirrors DETECTORS in the TS lib (same order; resolution uses the
// priority map below). The regexes are the TS sources minus their
// lookbehind/lookahead, which the boundary funcs re-implement.
var detectors = []detector{
	{
		// RFC 5322 simplified: local@domain.tld (letters-only TLD, 2+ chars).
		typ: TypeEmail,
		re:  regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`),
	},
	{
		// A maximal run of 12+ digits with single spaces/dashes as separators;
		// isValidCard then enforces 13-19 digits + Luhn on the whole run.
		typ:      TypeCreditCard,
		re:       regexp.MustCompile(`\d(?:[ -]?\d){11,}`),
		validate: isValidCard,
	},
	{
		typ: TypeSsn,
		re:  regexp.MustCompile(`\b\d{3}-\d{2}-\d{4}\b`),
	},
	{
		// Hex groups joined by colons (>=2 colons); isValidIpv6 rejects prose
		// like "10:30:45" (only 3 groups, no "::").
		typ:      TypeIpv6,
		re:       regexp.MustCompile(`[A-Fa-f0-9]{0,4}(?::[A-Fa-f0-9]{0,4}){1,7}`),
		validate: isValidIpv6,
		boundary: ipv6Boundary,
	},
	{
		// Dotted quad; boundary guards keep it out of versions ("v1.2.3.4") and
		// longer quintets ("1.2.3.4.5") while allowing sentence-final periods.
		typ:      TypeIpv4,
		re:       regexp.MustCompile(`(?:\d{1,3}\.){3}\d{1,3}`),
		validate: isValidIpv4,
		boundary: ipv4Boundary,
	},
	{
		typ:      TypeDate,
		re:       regexp.MustCompile(`\d{4}-\d{2}-\d{2}`),
		validate: isValidDate,
		boundary: dateBoundary,
	},
	{
		// Optional +country, optional (area), then 1-4 groups of 2-4 digits
		// separated by spaces, dashes, or dots. Fuzziest pattern — lowest
		// priority.
		typ:      TypePhone,
		re:       regexp.MustCompile(`(?:\+\d{1,3}[ .-]?)?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?\d{2,4}){1,4}`),
		validate: isValidPhone,
		boundary: phoneBoundary,
	},
}

// priority resolves overlaps: when two candidates cover the same span, the
// more specific type wins. Phone is deliberately last — a date, SSN, IP, or
// card number can all masquerade as one.
var priority = map[PiiType]int{
	TypeEmail:      0,
	TypeCreditCard: 1,
	TypeSsn:        2,
	TypeIpv6:       3,
	TypeIpv4:       4,
	TypeDate:       5,
	TypePhone:      6,
}

// DetectPii detects personal data in text. Pass types to scan for a subset
// (the per-type toggles); pass nil to scan for everything. Returns matches in
// document order, non-overlapping, with exact Start/End byte indices. It is
// the Go twin of detectPii() in src/lib/pii-redactor.ts.
func DetectPii(text string, types []PiiType) []PiiMatch {
	var active map[PiiType]bool
	if types != nil {
		active = make(map[PiiType]bool, len(types))
		for _, t := range types {
			active[t] = true
		}
	}
	var candidates []PiiMatch

	for _, det := range detectors {
		if active != nil && !active[det.typ] {
			continue
		}
		for _, loc := range det.re.FindAllStringIndex(text, -1) {
			start, end := loc[0], loc[1]
			if start == end {
				continue // zero-length safety; none of the patterns can
			}
			if det.boundary != nil && !det.boundary(text, start, end) {
				continue
			}
			if det.validate == nil || det.validate(text[start:end]) {
				candidates = append(candidates, PiiMatch{Type: det.typ, Start: start, End: end, Original: text[start:end]})
			}
		}
	}

	// Highest-priority (lowest number) candidates claim their span first.
	sort.SliceStable(candidates, func(i, j int) bool {
		if priority[candidates[i].Type] != priority[candidates[j].Type] {
			return priority[candidates[i].Type] < priority[candidates[j].Type]
		}
		return candidates[i].Start < candidates[j].Start
	})
	kept := []PiiMatch{}
	for _, c := range candidates {
		overlaps := false
		for _, k := range kept {
			if c.Start < k.End && k.Start < c.End {
				overlaps = true
				break
			}
		}
		if !overlaps {
			kept = append(kept, c)
		}
	}
	sort.SliceStable(kept, func(i, j int) bool { return kept[i].Start < kept[j].Start })
	return kept
}

// RedactOptions configures RedactPii. The zero value (RedactOptions{})
// matches the TS default call redactPii(text): the default [REDACTED] mask
// and every type scanned.
//
// Mask is a *string so the zero value means "default mask" while a non-nil
// empty string still means "erase the span" — exactly like the TS lib's
// distinction between omitted and ''.
type RedactOptions struct {
	Mask  *string   // nil → "[REDACTED]" (default); non-nil, including "", used verbatim
	Types []PiiType // nil → scan every type
}

// RedactPii redacts personal data from text, replacing every detected span
// with mask (default [REDACTED]). It accepts the same types subset as
// DetectPii and mirrors redactPii() in src/lib/pii-redactor.ts.
func RedactPii(text string, opts RedactOptions) string {
	mask := "[REDACTED]"
	if opts.Mask != nil {
		mask = *opts.Mask
	}
	matches := DetectPii(text, opts.Types)
	out := text
	// Replace right-to-left so earlier indices stay valid.
	for i := len(matches) - 1; i >= 0; i-- {
		m := matches[i]
		out = out[:m.Start] + mask + out[m.End:]
	}
	return out
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →