Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion configs/platform/system/pii/patterns/dateOfBirth.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ description: >-
locale-independently by the regex below, textual forms ("born on March 28,
1998", "geboren am 12. März 1980", "1998年9月28日生") composed from each
enabled locale's date-of-birth vocabulary. A year-plausibility gate
(1900..current+1) rejects phone numbers and random digit runs.
(1900..current+1) rejects phone numbers and random digit runs. A numeric
date with a two-digit year (12.03.80) counts only right after one of the
enabled locales' date-of-birth keywords ("DOB: 12.03.80", "Geburtsdatum:
12.03.80"); on its own it passes, like a version or section number.
replacement: '[DATE_OF_BIRTH]'
impl: native
regex:
Expand Down
2 changes: 1 addition & 1 deletion docs/de/platform/admin/governance/guardrails.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Der PII-Schutz erkennt konfigurierte Muster wie E-Mail-Adressen, Telefonnummern

Maskieren entfernt erkannte Werte aus dem weitergegebenen Text. Im Chat speichert und zeigt Tale auch den maskierten Text als Nachricht; der ursprüngliche Wortlaut bleibt nicht erhalten. Blockieren lehnt einen Treffer ab. Tokenisierung ersetzt die Werte für das Modell durch nummerierte Tokens und stellt sie in der Antwort wieder her. Sie kann die Verarbeitung mit weniger offengelegten Daten unterstützen, verspricht aber keine Antwort ohne personenbezogene Daten.

Eine eingebaute Kennung, die nur aus Ziffern besteht, etwa eine schwedische Passnummer oder eine ukrainische Steuernummer, wird nur neben einem Wort erkannt, das sie benennt, zum Beispiel `passnummer` oder `ІПН`. Bestellnummern, kompakte Datumsangaben und Build-Nummern bleiben unverändert. Jede Erkennung unter **Aktuelle Ereignisse** nennt das ausgelöste Muster, etwa `se-passport`.
Eine eingebaute Kennung, die nur aus Ziffern besteht, etwa eine schwedische Passnummer oder eine ukrainische Steuernummer, wird nur neben einem Wort erkannt, das sie benennt, zum Beispiel `passnummer` oder `ІПН`. Bestellnummern, kompakte Datumsangaben und Build-Nummern bleiben unverändert. Ebenso wird ein Geburtsdatum mit zweistelliger Jahreszahl wie `15.03.87` nur direkt nach einem Wort erkannt, das es benennt, zum Beispiel `DOB` oder `Geburtsdatum`; mit vierstelliger Jahreszahl auch ohne ein solches Wort. Jede Erkennung unter **Aktuelle Ereignisse** nennt das ausgelöste Muster, etwa `se-passport`.

Teste die tatsächlich verwendeten Formate mit erfundenen Werten. Muster können ungewöhnliche Formate übersehen oder normalen Text fälschlich markieren. Prüfe Eingabe und Ausgabe getrennt.

Expand Down
2 changes: 1 addition & 1 deletion docs/en/platform/admin/governance/guardrails.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ When several categories match, block takes precedence over mask, then flag. Word

Masking removes matched values from the text sent onward. In a chat, the masked text is also what Tale stores and shows as the message; the original wording is not kept. Blocking refuses a match. Tokenization replaces detected values with indexed tokens for the model and restores them in its reply. Tokenization is therefore useful for processing with reduced exposure, but it is not a promise that the final reply will contain no personal data.

A built-in identifier that is digits only, such as a Swedish passport number or a Ukrainian tax ID, is recognized only next to a word that names it, for example `passnummer` or `ІПН`. Order numbers, compact dates, and build numbers pass through. Each detection in **Recent events** names the pattern that fired, such as `se-passport`.
A built-in identifier that is digits only, such as a Swedish passport number or a Ukrainian tax ID, is recognized only next to a word that names it, for example `passnummer` or `ІПН`. Order numbers, compact dates, and build numbers pass through. Likewise, a date of birth with a two-digit year, such as `15.03.87`, is recognized only right after a word that names it, for example `DOB` or `Geburtsdatum`; with a four-digit year, it is recognized without such a word. Each detection in **Recent events** names the pattern that fired, such as `se-passport`.

Test the formats you actually use with synthetic values. Pattern detection can miss unusual formats and can flag ordinary text. Check input and output separately.

Expand Down
2 changes: 1 addition & 1 deletion docs/fr/platform/admin/governance/guardrails.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ La protection PII détecte des formats configurés, comme les adresses e-mail, n

Le masquage retire les valeurs détectées du texte transmis. Dans un chat, Tale enregistre et affiche aussi le texte masqué comme message ; la formulation d’origine n’est pas conservée. Le blocage refuse une correspondance. La tokenisation remplace les valeurs par des tokens numérotés pour le modèle, puis les restaure dans sa réponse. Elle réduit l’exposition pendant le traitement, sans garantir une réponse finale dépourvue de données personnelles.

Un identifiant intégré composé uniquement de chiffres, comme un numéro de passeport suédois ou un identifiant fiscal ukrainien, n’est reconnu qu’à côté d’un mot qui le nomme, par exemple `passnummer` ou `ІПН`. Les numéros de commande, les dates compactes et les numéros de build passent tels quels. Chaque détection dans **Événements récents** nomme le motif déclenché, par exemple `se-passport`.
Un identifiant intégré composé uniquement de chiffres, comme un numéro de passeport suédois ou un identifiant fiscal ukrainien, n’est reconnu qu’à côté d’un mot qui le nomme, par exemple `passnummer` ou `ІПН`. Les numéros de commande, les dates compactes et les numéros de build passent tels quels. De même, une date de naissance avec une année à deux chiffres, comme `15.03.87`, n’est reconnue que directement après un mot qui la nomme, par exemple `DOB` ou `Geburtsdatum` ; avec une année à quatre chiffres, elle est reconnue même sans ce mot. Chaque détection dans **Événements récents** nomme le motif déclenché, par exemple `se-passport`.

Teste tes formats réels avec des valeurs fictives. La détection peut manquer des formats inhabituels et signaler à tort du texte ordinaire. Vérifie séparément l’entrée et la sortie.

Expand Down
96 changes: 84 additions & 12 deletions services/platform/lib/pii/patterns/date-of-birth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,19 @@
* orderings `DAY (de|of) MONTH (de) YEAR` and `MONTH DAY, YEAR`, with
* optional context prefix and day ordinals (`28th`, `1er`, `28.`);
* - one CJK regex (`YYYY年MM月DD日` with optional context word before or
* after) from the union of the year/month/day markers.
* after) from the union of the year/month/day markers;
* - one keyword-gated regex for a numeric date with a two-digit year
* (`DOB: 15/03/87`) from the union of the context keywords. On its own
* `15.03.87` reads as well as a version or a section number, so only a
* keyword right before it makes it a date of birth.
*
* Locales without a `dateOfBirth` block contribute nothing.
*
* Every match passes a plausibility validator: the year must fall in
* 1900..currentYear+1 (the +1 absorbs New-Year clock skew), the day/month
* groups must be calendar-plausible — that is what keeps phone numbers and
* card issue dates from reading as DOBs. Keywords are escaped and
* 1900..currentYear+1 (the +1 absorbs New-Year clock skew; a two-digit
* year after a keyword may be any), the day/month groups must be
* calendar-plausible — that is what keeps phone numbers and card issue
* dates from reading as DOBs. Keywords are escaped and
* longest-first ordered by the shared composer; all quantifiers are
* bounded, and the composed regexes run under the engine's exec budget
* like any other.
Expand All @@ -43,19 +48,35 @@ const CURRENT_YEAR = new Date().getUTCFullYear();
const MIN_YEAR = 1900;
const MAX_YEAR = CURRENT_YEAR + 1;

// Both textual forms carry exactly one 4-digit group — the year — so the
// first 4-digit run in a match is always it.
// A four-digit-year match, numeric or textual, carries exactly one 4-digit
// group — the year — so the first 4-digit run in a match is always it. A
// bare numeric match without one (`15.03.87`) fails here on purpose: only
// the keyword-gated pass takes a two-digit year.
const YEAR_EXTRACT_RE = /\d{4}/;
const NUMERIC_PARTS_RE = /(\d{1,4})[./\-–—](\d{1,2})[./\-–—](\d{1,4})/;
const LEADING_DAY_RE = /\d{1,2}/;

/** Separators between a context keyword and the date it names: whitespace,
* a colon (ASCII or full-width), a dot, a comma, an equals sign or a dash —
* "DOB: 15/03/87", "geb. 15.03.87", "dob=15/03/87". */
const KEYWORD_GAP = '[\\s::.,=\\-–—]{0,12}';
/** A numeric date with a two-digit year at either end (`15.03.87`,
* `87.03.15`), never the head of a longer run (`15.03.87.12`, `15.03.879`). */
const TWO_DIGIT_YEAR_DATE =
'\\d{1,2}[./—–-]\\d{1,2}[./—–-]\\d{2}(?![\\p{L}\\p{M}\\p{N}]|[./—–-]\\p{N})';

function yearLooksPlausible(matchedText: string): boolean {
const m = matchedText.match(YEAR_EXTRACT_RE);
if (!m) return false;
const year = Number(m[0]);
return year >= MIN_YEAR && year <= MAX_YEAR;
}

/** A day and a month that can form a calendar date. */
function dayMonthLooksPlausible(day: number, month: number): boolean {
return month >= 1 && month <= 12 && day >= 1 && day <= 31;
}

/**
* Numeric-date plausibility: plausible year, then plausible day/month.
* A leading 4-digit group reads as YMD; otherwise DMY and MDY are both
Expand All @@ -72,12 +93,28 @@ function numericDateLooksPlausible(matchedText: string): boolean {
const g2 = Number(parts[2]);
const g3 = Number(parts[3]);

if (g1 >= 1000) {
return g2 >= 1 && g2 <= 12 && g3 >= 1 && g3 <= 31;
}
const dmyOk = g2 >= 1 && g2 <= 12 && g1 >= 1 && g1 <= 31;
const mdyOk = g1 >= 1 && g1 <= 12 && g2 >= 1 && g2 <= 31;
return dmyOk || mdyOk;
if (g1 >= 1000) return dayMonthLooksPlausible(g3, g2);
return dayMonthLooksPlausible(g1, g2) || dayMonthLooksPlausible(g2, g1);
}

/**
* Two-digit-year plausibility: any year — the keyword before the match is
* what says it is a date of birth — and a real day/month in DMY, MDY or
* YMD order (`15.03.87`, `03/15/87`, `87.03.15`).
*/
function twoDigitYearDateLooksPlausible(matchedText: string): boolean {
const parts = matchedText.match(NUMERIC_PARTS_RE);
if (!parts) return false;

const g1 = Number(parts[1]);
const g2 = Number(parts[2]);
const g3 = Number(parts[3]);

return (
dayMonthLooksPlausible(g1, g2) ||
dayMonthLooksPlausible(g2, g1) ||
dayMonthLooksPlausible(g3, g2)
);
}

/** Latin textual plausibility: plausible year plus a 1–31 leading day. */
Expand All @@ -91,6 +128,7 @@ function latinTextualLooksPlausible(matchedText: string): boolean {
}

interface ComposedDob {
twoDigitYear: PiiPatternRegex | null;
latin: PiiPatternRegex | null;
cjk: PiiPatternRegex | null;
}
Expand Down Expand Up @@ -125,6 +163,38 @@ function partitionLocales(locales: ReadonlyArray<LocaleConfig>): {
return { latinish, cjk };
}

/**
* A numeric date with a two-digit year right after a date-of-birth context
* keyword of any enabled locale (`DOB: 15/03/87`, `Geburtsdatum: 15.03.87`).
* The keyword is matched the way the phone and national-ID keywords are
* (word-bounded, case-insensitive) but in a lookbehind, so it stays outside
* the span and the mask keeps it: `DOB: [DATE_OF_BIRTH]`, as with a
* four-digit year.
*/
function buildTwoDigitYearPattern(
locales: ReadonlyArray<LocaleConfig>,
name: string,
replacement: string,
): PiiPatternRegex | null {
const contextAlt = composeKeywordAlternation(
locales.map((l) => l.dateOfBirth?.contextKeywords ?? []),
);
if (contextAlt === '(?!)') return null;

const keyword = `(?<![\\p{L}\\p{M}])(?:${contextAlt})(?![\\p{L}\\p{M}])`;
const regex = new RegExp(
`(?<=${keyword}${KEYWORD_GAP})${TWO_DIGIT_YEAR_DATE}`,
'giu',
);

return {
name,
regex,
replacement,
validate: twoDigitYearDateLooksPlausible,
};
}

function buildLatinTextualPattern(
locales: ReadonlyArray<LocaleConfig>,
name: string,
Expand Down Expand Up @@ -230,6 +300,7 @@ function composeFromLocales(

const { latinish, cjk } = partitionLocales(locales);
const composed: ComposedDob = {
twoDigitYear: buildTwoDigitYearPattern(locales, name, replacement),
latin:
latinish.length > 0
? buildLatinTextualPattern(latinish, name, replacement)
Expand All @@ -255,6 +326,7 @@ export const buildDateOfBirthPattern: NativePatternBuilder = (file) => {
const out: PiiPattern[] = [];
if (numericPattern) out.push(numericPattern);
const composed = composeFromLocales(locales, file.name, file.replacement);
if (composed.twoDigitYear) out.push(composed.twoDigitYear);
if (composed.latin) out.push(composed.latin);
if (composed.cjk) out.push(composed.cjk);
return out;
Expand Down
28 changes: 27 additions & 1 deletion services/platform/tests/pii/smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,33 @@ describe('createScrubber — mask mode', () => {
const o = scrubber.scrub('DOB: 15/03/1987');
expect(o.kind).toBe('modified');
if (o.kind !== 'modified') return;
expect(o.text).toContain('[DATE_OF_BIRTH]');
expect(o.text).toBe('DOB: [DATE_OF_BIRTH]');
});

// A two-digit year counts only right after a word that names a date of
// birth: on its own, `15.03.87` reads as well as a version or a section.
it.each([
['DOB: 15/03/87', 'DOB: [DATE_OF_BIRTH]'],
['Geburtsdatum: 15.03.87', 'Geburtsdatum: [DATE_OF_BIRTH]'],
['date de naissance : 15/03/87', 'date de naissance : [DATE_OF_BIRTH]'],
['생년월일: 87.03.15', '생년월일: [DATE_OF_BIRTH]'],
])(
'masks a two-digit-year date of birth after its keyword: %s',
(input, expected) => {
const o = scrubber.scrub(input);
expect(o.kind).toBe('modified');
if (o.kind !== 'modified') return;
expect(o.text).toBe(expected);
expect(o.categoryIds).toEqual(['dateOfBirth']);
},
);

it('leaves a two-digit-year date without a keyword alone', () => {
expect(scrubber.scrub('15.03.87').kind).toBe('pass');
});

it('leaves an impossible two-digit-year date after a keyword alone', () => {
expect(scrubber.scrub('DOB: 45/13/87').kind).toBe('pass');
});
});

Expand Down
Loading