@maskera/core 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # @maskera/core
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7662737: Initial release: Swedish-first PII detectors (personnummer, samordningsnummer,
8
+ organisationsnummer, phone, email, postnummer, bankgiro/plusgiro, IBAN, credit
9
+ card, IP, URL) with checksum validation, plus a redact/restore engine with
10
+ stable placeholders and deterministic overlap resolution.
11
+ - 385f4e9: Add opt-in `@maskera/ner` package: a Transformers.js NER layer for free-text
12
+ names/places, with `createNerRecognizer()` and
13
+ a `redactWithNer()` hybrid. Core gains `redactFromDetections()` so external
14
+ detection sources reuse the stable-placeholder / overlap engine.
15
+
16
+ ### Patch Changes
17
+
18
+ - d127450: `@maskera/ner`: maskera's own Swedish model (`joelhagvall/maskera-sv-ner`,
19
+ MIT, 40 MB q4) is now the default. Span reconstruction is rebuilt piece by
20
+ piece, fixing silent drops of hyphenated names ("Karl-Gustav"), ampersand orgs
21
+ ("H&M") and title-attached subwords ("dr Svensson").
22
+
23
+ `@maskera/core`: the plusgiro detector now tolerates space-grouped numbers
24
+ ("90 19 50-6") and validates the mod-10 check digit, so partial matches no
25
+ longer leak and look-alikes no longer fire.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joel Hägvall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # @maskera/core
2
+
3
+ Swedish-first, **zero-dependency** PII detection & redaction. Runs in the
4
+ browser, Node, and edge runtimes. Part of [maskera](https://github.com/joelhagvall/maskera).
5
+
6
+ ```bash
7
+ pnpm add @maskera/core
8
+ ```
9
+
10
+ ```ts
11
+ import { redact } from "@maskera/core"
12
+
13
+ const { text, restore } = redact("Personnummer 19900101-0017, tel 070-123 45 67.")
14
+ text // "Personnummer [PERSONNUMMER_1], tel [PHONE_1]."
15
+ ```
16
+
17
+ ## Highlights
18
+
19
+ - **Swedish-first**: personnummer, samordningsnummer, organisationsnummer —
20
+ date- and Luhn-validated, so `123456-0000` is *not* mistaken for a person.
21
+ - **Stable placeholders**: the same value reuses its token within a call.
22
+ - **Restore map**: map LLM output back to real values, locally.
23
+ - **Zero dependencies**, tree-shakeable, ESM + CJS + types.
24
+
25
+ ## Built-in detectors
26
+
27
+ All exported individually and as `defaultDetectors`. Checksum-validated where
28
+ a checksum exists, so look-alikes (year ranges, reference numbers) don't fire.
29
+
30
+ | Label | Matches | Validation |
31
+ | ---------------------- | -------------------------------------- | --------------------- |
32
+ | `PERSONNUMMER` | `19900101-0017`, `900101-0017` | date + Luhn |
33
+ | `SAMORDNINGSNUMMER` | day + 60 variant | date + Luhn |
34
+ | `ORGANISATIONSNUMMER` | `556016-0680` | Luhn, third digit ≥ 2 |
35
+ | `EMAIL` | `anna@example.se` | pattern |
36
+ | `PHONE` | `070-123 45 67`, `+46 8 123 456` | Swedish mobile + landline |
37
+ | `POSTNUMMER` | `114 55` | pattern |
38
+ | `BANKGIRO` | `5050-1055` | Luhn check digit |
39
+ | `PLUSGIRO` | `90 19 50-6` (spaces tolerated) | Luhn check digit |
40
+ | `IBAN` | `SE45 5000 0000 0583 9825 7466` | SE pattern |
41
+ | `CREDIT_CARD` | 13-19 digits, spaces/dashes tolerated | Luhn |
42
+ | `IP_ADDRESS` / `URL` | IPv4 / http(s) | pattern |
43
+
44
+ Add your own with `regexDetector` (below); mix and match via
45
+ `options.detectors`.
46
+
47
+ ## API
48
+
49
+ ### `redact(input, options?) => RedactResult`
50
+
51
+ ```ts
52
+ interface RedactOptions {
53
+ detectors?: Detector[] // default: defaultDetectors
54
+ placeholder?: (label: string, index: number) => string // default: `[LABEL_n]`
55
+ }
56
+
57
+ interface RedactResult {
58
+ text: string
59
+ redactions: Redaction[] // { start, end, value, label, replacement }
60
+ map: Record<string, string> // token -> original value
61
+ restore: (text: string) => string // bound to this call's map
62
+ }
63
+ ```
64
+
65
+ ### `restore(text, map) => string`
66
+
67
+ Re-inserts originals into any string containing the placeholder tokens — safe on
68
+ LLM output that reorders or quotes them.
69
+
70
+ ### `regexDetector(label, globalRegex, validate?) => Detector`
71
+
72
+ Build a detector. If the regex has a capture group, group 1 is treated as the
73
+ value to redact. `validate` can reject false positives (e.g. failing a checksum).
74
+
75
+ ### Validators
76
+
77
+ `luhnValid`, `isPersonnummer`, `isSamordningsnummer`, `isOrganisationsnummer`.
78
+
79
+ ## License
80
+
81
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+
3
+ // src/validators.ts
4
+ function luhnValid(digits) {
5
+ const only = digits.replace(/\D/g, "");
6
+ if (only.length === 0) return false;
7
+ let sum = 0;
8
+ let double = false;
9
+ for (let i = only.length - 1; i >= 0; i--) {
10
+ let d = only.charCodeAt(i) - 48;
11
+ if (double) {
12
+ d *= 2;
13
+ if (d > 9) d -= 9;
14
+ }
15
+ sum += d;
16
+ double = !double;
17
+ }
18
+ return sum % 10 === 0;
19
+ }
20
+ function isPersonnummer(value) {
21
+ const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
22
+ if (!m) return false;
23
+ const month = Number(m[3]);
24
+ const day = Number(m[4]);
25
+ if (month < 1 || month > 12) return false;
26
+ if (day < 1 || day > 31) return false;
27
+ const core = value.replace(/[-+]/g, "").slice(-10);
28
+ return luhnValid(core);
29
+ }
30
+ function isSamordningsnummer(value) {
31
+ const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
32
+ if (!m) return false;
33
+ const month = Number(m[3]);
34
+ const day = Number(m[4]);
35
+ if (month < 1 || month > 12) return false;
36
+ if (day < 61 || day > 91) return false;
37
+ const core = value.replace(/[-+]/g, "").slice(-10);
38
+ return luhnValid(core);
39
+ }
40
+ function isOrganisationsnummer(value) {
41
+ const only = value.replace(/\D/g, "");
42
+ const core = only.length === 12 ? only.slice(2) : only;
43
+ if (core.length !== 10) return false;
44
+ if (Number(core[2]) < 2) return false;
45
+ return luhnValid(core);
46
+ }
47
+
48
+ // src/detectors/index.ts
49
+ function regexDetector(label, regex, validate) {
50
+ if (!regex.global) {
51
+ throw new Error(`Detector "${label}" requires a global ("g") regex`);
52
+ }
53
+ return {
54
+ label,
55
+ detect(input) {
56
+ const out = [];
57
+ regex.lastIndex = 0;
58
+ for (const m of input.matchAll(regex)) {
59
+ if (m.index === void 0) continue;
60
+ const value = m[1] ?? m[0];
61
+ if (value.length === 0) continue;
62
+ const start = m.index + m[0].indexOf(value);
63
+ if (validate && !validate(value)) continue;
64
+ out.push({ start, end: start + value.length, value });
65
+ }
66
+ return out;
67
+ }
68
+ };
69
+ }
70
+ var personnummer = regexDetector(
71
+ "PERSONNUMMER",
72
+ /\b(?:19|20)?\d{6}[-+]?\d{4}\b/g,
73
+ isPersonnummer
74
+ );
75
+ var samordningsnummer = regexDetector(
76
+ "SAMORDNINGSNUMMER",
77
+ /\b(?:19|20)?\d{6}[-+]?\d{4}\b/g,
78
+ isSamordningsnummer
79
+ );
80
+ var organisationsnummer = regexDetector(
81
+ "ORGANISATIONSNUMMER",
82
+ /\b\d{6}[-]?\d{4}\b/g,
83
+ isOrganisationsnummer
84
+ );
85
+ var email = regexDetector("EMAIL", /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi);
86
+ var phone = regexDetector(
87
+ "PHONE",
88
+ /(?:\+46[\s-]?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8}\b/g
89
+ );
90
+ var postnummer = regexDetector("POSTNUMMER", /\b\d{3}\s?\d{2}\b/g);
91
+ var bankgiro = regexDetector(
92
+ "BANKGIRO",
93
+ /\b\d{3,4}-\d{4}\b/g,
94
+ (v) => luhnValid(v.replace(/\D/g, ""))
95
+ );
96
+ var plusgiro = regexDetector(
97
+ "PLUSGIRO",
98
+ /\b\d(?:\s?\d){0,6}-\d\b/g,
99
+ (v) => luhnValid(v.replace(/\D/g, ""))
100
+ );
101
+ var iban = regexDetector("IBAN", /\bSE\d{2}(?:\s?\d){20}\b/gi);
102
+ var creditCard = regexDetector("CREDIT_CARD", /\b\d(?:[ -]?\d){12,18}\b/g, (v) => {
103
+ const digits = v.replace(/\D/g, "");
104
+ return digits.length >= 13 && digits.length <= 19 && luhnValid(digits);
105
+ });
106
+ var ipAddress = regexDetector(
107
+ "IP_ADDRESS",
108
+ /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g
109
+ );
110
+ var url = regexDetector("URL", /\bhttps?:\/\/[^\s<>")]+/gi);
111
+ var defaultDetectors = [
112
+ email,
113
+ url,
114
+ personnummer,
115
+ samordningsnummer,
116
+ organisationsnummer,
117
+ iban,
118
+ creditCard,
119
+ bankgiro,
120
+ plusgiro,
121
+ phone,
122
+ postnummer,
123
+ ipAddress
124
+ ];
125
+
126
+ // src/redact.ts
127
+ function defaultPlaceholder(label, index) {
128
+ return `[${label}_${index}]`;
129
+ }
130
+ function resolveOverlaps(detections) {
131
+ const sorted = [...detections].sort((a, b) => {
132
+ if (a.start !== b.start) return a.start - b.start;
133
+ if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start);
134
+ return a.label.localeCompare(b.label);
135
+ });
136
+ const kept = [];
137
+ let cursor = -1;
138
+ for (const d of sorted) {
139
+ if (d.start >= cursor) {
140
+ kept.push(d);
141
+ cursor = d.end;
142
+ }
143
+ }
144
+ return kept;
145
+ }
146
+ function redact(input, options = {}) {
147
+ const detectors = options.detectors ?? defaultDetectors;
148
+ const all = [];
149
+ for (const detector of detectors) {
150
+ for (const m of detector.detect(input)) {
151
+ all.push({ ...m, label: detector.label });
152
+ }
153
+ }
154
+ return redactFromDetections(input, all, options);
155
+ }
156
+ function redactFromDetections(input, detections, options = {}) {
157
+ const placeholder = options.placeholder ?? defaultPlaceholder;
158
+ const resolved = resolveOverlaps(detections);
159
+ const counters = /* @__PURE__ */ new Map();
160
+ const tokenByKey = /* @__PURE__ */ new Map();
161
+ const map = {};
162
+ const redactions = [];
163
+ for (const d of resolved) {
164
+ const key = `${d.label}::${d.value}`;
165
+ let token = tokenByKey.get(key);
166
+ if (!token) {
167
+ const next = (counters.get(d.label) ?? 0) + 1;
168
+ counters.set(d.label, next);
169
+ token = placeholder(d.label, next);
170
+ tokenByKey.set(key, token);
171
+ map[token] = d.value;
172
+ }
173
+ redactions.push({ ...d, replacement: token });
174
+ }
175
+ let text = "";
176
+ let last = 0;
177
+ for (const r of redactions) {
178
+ text += input.slice(last, r.start);
179
+ text += r.replacement;
180
+ last = r.end;
181
+ }
182
+ text += input.slice(last);
183
+ return {
184
+ text,
185
+ redactions,
186
+ map,
187
+ restore: (s) => restore(s, map)
188
+ };
189
+ }
190
+ function restore(text, map) {
191
+ let out = text;
192
+ const tokens = Object.keys(map).sort((a, b) => b.length - a.length);
193
+ for (const token of tokens) {
194
+ out = out.split(token).join(map[token]);
195
+ }
196
+ return out;
197
+ }
198
+
199
+ exports.bankgiro = bankgiro;
200
+ exports.creditCard = creditCard;
201
+ exports.defaultDetectors = defaultDetectors;
202
+ exports.email = email;
203
+ exports.iban = iban;
204
+ exports.ipAddress = ipAddress;
205
+ exports.isOrganisationsnummer = isOrganisationsnummer;
206
+ exports.isPersonnummer = isPersonnummer;
207
+ exports.isSamordningsnummer = isSamordningsnummer;
208
+ exports.luhnValid = luhnValid;
209
+ exports.organisationsnummer = organisationsnummer;
210
+ exports.personnummer = personnummer;
211
+ exports.phone = phone;
212
+ exports.plusgiro = plusgiro;
213
+ exports.postnummer = postnummer;
214
+ exports.redact = redact;
215
+ exports.redactFromDetections = redactFromDetections;
216
+ exports.regexDetector = regexDetector;
217
+ exports.restore = restore;
218
+ exports.samordningsnummer = samordningsnummer;
219
+ exports.url = url;
220
+ //# sourceMappingURL=index.cjs.map
221
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IA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A,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer) — samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\nexport const email = regexDetector(\"EMAIL\", /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */\nexport const phone = regexDetector(\n \"PHONE\",\n /(?:\\+46[\\s-]?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8}\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"CREDIT_CARD\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADDRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\s<>\")]+/gi)\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, RedactOptions, RedactResult, Redaction } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[PERSON_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `@maskera/ner`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${d.label}::${d.value}`\n let token = tokenByKey.get(key)\n if (!token) {\n const next = (counters.get(d.label) ?? 0) + 1\n counters.set(d.label, next)\n token = placeholder(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Built-in PII labels. The `string` fallback lets you add custom detectors
3
+ * with arbitrary labels without fighting the type system.
4
+ */
5
+ type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | (string & {});
6
+ /** A raw match found by a detector, before placeholder assignment. */
7
+ interface Detection {
8
+ /** Inclusive start index into the source string. */
9
+ start: number;
10
+ /** Exclusive end index into the source string. */
11
+ end: number;
12
+ /** The matched substring. */
13
+ value: string;
14
+ /** Which detector produced this match. */
15
+ label: PiiLabel;
16
+ }
17
+ /** A detection that has been assigned a stable placeholder. */
18
+ interface Redaction extends Detection {
19
+ /** The token the value was replaced with, e.g. `[PERSONNUMMER_1]`. */
20
+ replacement: string;
21
+ }
22
+ /**
23
+ * A detector finds occurrences of one kind of PII in a string.
24
+ * Implementations must be pure and stateless.
25
+ */
26
+ interface Detector {
27
+ readonly label: PiiLabel;
28
+ detect(input: string): Array<Omit<Detection, "label">>;
29
+ }
30
+ interface RedactOptions {
31
+ /** Which detectors to run. Defaults to {@link defaultDetectors}. */
32
+ detectors?: Detector[];
33
+ /**
34
+ * Build the placeholder token for a given label and 1-based index.
35
+ * Defaults to ``(label, i) => `[${label}_${i}]` ``.
36
+ */
37
+ placeholder?: (label: PiiLabel, index: number) => string;
38
+ }
39
+ interface RedactResult {
40
+ /** The input with every detected value swapped for a placeholder. */
41
+ text: string;
42
+ /** Every redaction performed, in order of appearance. */
43
+ redactions: Redaction[];
44
+ /** Map of placeholder token -> original value, for local restoration. */
45
+ map: Record<string, string>;
46
+ /** Convenience: re-inserts original values into a (possibly LLM-modified) string. */
47
+ restore: (text: string) => string;
48
+ }
49
+
50
+ /**
51
+ * Detect and replace PII in `input`, returning the redacted text plus a
52
+ * restore map. Placeholders are *stable*: the same value always maps to the
53
+ * same token within one call, so an LLM can reason about `[PERSON_1]`
54
+ * consistently and you can map results back afterwards.
55
+ */
56
+ declare function redact(input: string, options?: RedactOptions): RedactResult;
57
+ /**
58
+ * Lower-level entry point: turn a pre-computed list of detections into a
59
+ * {@link RedactResult}. Use this when detections come from somewhere async or
60
+ * external (e.g. an NER model in `@maskera/ner`) and you want the same stable
61
+ * placeholder + overlap-resolution behaviour as {@link redact}.
62
+ */
63
+ declare function redactFromDetections(input: string, detections: Detection[], options?: Pick<RedactOptions, "placeholder">): RedactResult;
64
+ /**
65
+ * Re-insert original values into a string that contains placeholder tokens.
66
+ * Safe to call on LLM output that echoes the placeholders back.
67
+ */
68
+ declare function restore(text: string, map: Record<string, string>): string;
69
+
70
+ /**
71
+ * Build a detector from a global regex, with an optional `validate` predicate
72
+ * that can reject false positives (e.g. a number that fails a checksum).
73
+ */
74
+ declare function regexDetector(label: PiiLabel, regex: RegExp, validate?: (value: string) => boolean): Detector;
75
+ /** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */
76
+ declare const personnummer: Detector;
77
+ /** Samordningsnummer: personnummer-shaped but with day + 60. */
78
+ declare const samordningsnummer: Detector;
79
+ /** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */
80
+ declare const organisationsnummer: Detector;
81
+ declare const email: Detector;
82
+ /** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */
83
+ declare const phone: Detector;
84
+ /** Postnummer: NNN NN (space optional). */
85
+ declare const postnummer: Detector;
86
+ /**
87
+ * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The
88
+ * checksum is what separates a real bankgiro from look-alikes such as a year
89
+ * range ("2019-2024") or an arbitrary reference id.
90
+ */
91
+ declare const bankgiro: Detector;
92
+ /**
93
+ * Plusgiro: 1-7 digits, dash, single check digit, commonly written with
94
+ * space groups ("90 19 50-6"). The whole number carries a mod-10 (Luhn)
95
+ * check digit, which filters out look-alikes like list numbering ("punkt 1-2").
96
+ */
97
+ declare const plusgiro: Detector;
98
+ /** Swedish IBAN: SE + 22 digits (spaces tolerated). */
99
+ declare const iban: Detector;
100
+ declare const creditCard: Detector;
101
+ declare const ipAddress: Detector;
102
+ declare const url: Detector;
103
+ /**
104
+ * Default detector set, ordered so that the most specific / highest-confidence
105
+ * detectors run first. Overlap resolution keeps the longest, earliest match.
106
+ */
107
+ declare const defaultDetectors: Detector[];
108
+
109
+ /**
110
+ * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer
111
+ * and organisationsnummer. Operates on the digits only.
112
+ */
113
+ declare function luhnValid(digits: string): boolean;
114
+ /**
115
+ * Validate a Swedish personnummer.
116
+ * Accepts 10 or 12 digit forms with optional `-`/`+` separator.
117
+ * Checks the date part and the Luhn control digit (on the 10-digit core).
118
+ */
119
+ declare function isPersonnummer(value: string): boolean;
120
+ /** Swedish samordningsnummer: like a personnummer but day has +60. */
121
+ declare function isSamordningsnummer(value: string): boolean;
122
+ /** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
123
+ declare function isOrganisationsnummer(value: string): boolean;
124
+
125
+ export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Built-in PII labels. The `string` fallback lets you add custom detectors
3
+ * with arbitrary labels without fighting the type system.
4
+ */
5
+ type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | (string & {});
6
+ /** A raw match found by a detector, before placeholder assignment. */
7
+ interface Detection {
8
+ /** Inclusive start index into the source string. */
9
+ start: number;
10
+ /** Exclusive end index into the source string. */
11
+ end: number;
12
+ /** The matched substring. */
13
+ value: string;
14
+ /** Which detector produced this match. */
15
+ label: PiiLabel;
16
+ }
17
+ /** A detection that has been assigned a stable placeholder. */
18
+ interface Redaction extends Detection {
19
+ /** The token the value was replaced with, e.g. `[PERSONNUMMER_1]`. */
20
+ replacement: string;
21
+ }
22
+ /**
23
+ * A detector finds occurrences of one kind of PII in a string.
24
+ * Implementations must be pure and stateless.
25
+ */
26
+ interface Detector {
27
+ readonly label: PiiLabel;
28
+ detect(input: string): Array<Omit<Detection, "label">>;
29
+ }
30
+ interface RedactOptions {
31
+ /** Which detectors to run. Defaults to {@link defaultDetectors}. */
32
+ detectors?: Detector[];
33
+ /**
34
+ * Build the placeholder token for a given label and 1-based index.
35
+ * Defaults to ``(label, i) => `[${label}_${i}]` ``.
36
+ */
37
+ placeholder?: (label: PiiLabel, index: number) => string;
38
+ }
39
+ interface RedactResult {
40
+ /** The input with every detected value swapped for a placeholder. */
41
+ text: string;
42
+ /** Every redaction performed, in order of appearance. */
43
+ redactions: Redaction[];
44
+ /** Map of placeholder token -> original value, for local restoration. */
45
+ map: Record<string, string>;
46
+ /** Convenience: re-inserts original values into a (possibly LLM-modified) string. */
47
+ restore: (text: string) => string;
48
+ }
49
+
50
+ /**
51
+ * Detect and replace PII in `input`, returning the redacted text plus a
52
+ * restore map. Placeholders are *stable*: the same value always maps to the
53
+ * same token within one call, so an LLM can reason about `[PERSON_1]`
54
+ * consistently and you can map results back afterwards.
55
+ */
56
+ declare function redact(input: string, options?: RedactOptions): RedactResult;
57
+ /**
58
+ * Lower-level entry point: turn a pre-computed list of detections into a
59
+ * {@link RedactResult}. Use this when detections come from somewhere async or
60
+ * external (e.g. an NER model in `@maskera/ner`) and you want the same stable
61
+ * placeholder + overlap-resolution behaviour as {@link redact}.
62
+ */
63
+ declare function redactFromDetections(input: string, detections: Detection[], options?: Pick<RedactOptions, "placeholder">): RedactResult;
64
+ /**
65
+ * Re-insert original values into a string that contains placeholder tokens.
66
+ * Safe to call on LLM output that echoes the placeholders back.
67
+ */
68
+ declare function restore(text: string, map: Record<string, string>): string;
69
+
70
+ /**
71
+ * Build a detector from a global regex, with an optional `validate` predicate
72
+ * that can reject false positives (e.g. a number that fails a checksum).
73
+ */
74
+ declare function regexDetector(label: PiiLabel, regex: RegExp, validate?: (value: string) => boolean): Detector;
75
+ /** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */
76
+ declare const personnummer: Detector;
77
+ /** Samordningsnummer: personnummer-shaped but with day + 60. */
78
+ declare const samordningsnummer: Detector;
79
+ /** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */
80
+ declare const organisationsnummer: Detector;
81
+ declare const email: Detector;
82
+ /** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */
83
+ declare const phone: Detector;
84
+ /** Postnummer: NNN NN (space optional). */
85
+ declare const postnummer: Detector;
86
+ /**
87
+ * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The
88
+ * checksum is what separates a real bankgiro from look-alikes such as a year
89
+ * range ("2019-2024") or an arbitrary reference id.
90
+ */
91
+ declare const bankgiro: Detector;
92
+ /**
93
+ * Plusgiro: 1-7 digits, dash, single check digit, commonly written with
94
+ * space groups ("90 19 50-6"). The whole number carries a mod-10 (Luhn)
95
+ * check digit, which filters out look-alikes like list numbering ("punkt 1-2").
96
+ */
97
+ declare const plusgiro: Detector;
98
+ /** Swedish IBAN: SE + 22 digits (spaces tolerated). */
99
+ declare const iban: Detector;
100
+ declare const creditCard: Detector;
101
+ declare const ipAddress: Detector;
102
+ declare const url: Detector;
103
+ /**
104
+ * Default detector set, ordered so that the most specific / highest-confidence
105
+ * detectors run first. Overlap resolution keeps the longest, earliest match.
106
+ */
107
+ declare const defaultDetectors: Detector[];
108
+
109
+ /**
110
+ * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer
111
+ * and organisationsnummer. Operates on the digits only.
112
+ */
113
+ declare function luhnValid(digits: string): boolean;
114
+ /**
115
+ * Validate a Swedish personnummer.
116
+ * Accepts 10 or 12 digit forms with optional `-`/`+` separator.
117
+ * Checks the date part and the Luhn control digit (on the 10-digit core).
118
+ */
119
+ declare function isPersonnummer(value: string): boolean;
120
+ /** Swedish samordningsnummer: like a personnummer but day has +60. */
121
+ declare function isSamordningsnummer(value: string): boolean;
122
+ /** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
123
+ declare function isOrganisationsnummer(value: string): boolean;
124
+
125
+ export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
package/dist/index.js ADDED
@@ -0,0 +1,199 @@
1
+ // src/validators.ts
2
+ function luhnValid(digits) {
3
+ const only = digits.replace(/\D/g, "");
4
+ if (only.length === 0) return false;
5
+ let sum = 0;
6
+ let double = false;
7
+ for (let i = only.length - 1; i >= 0; i--) {
8
+ let d = only.charCodeAt(i) - 48;
9
+ if (double) {
10
+ d *= 2;
11
+ if (d > 9) d -= 9;
12
+ }
13
+ sum += d;
14
+ double = !double;
15
+ }
16
+ return sum % 10 === 0;
17
+ }
18
+ function isPersonnummer(value) {
19
+ const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
20
+ if (!m) return false;
21
+ const month = Number(m[3]);
22
+ const day = Number(m[4]);
23
+ if (month < 1 || month > 12) return false;
24
+ if (day < 1 || day > 31) return false;
25
+ const core = value.replace(/[-+]/g, "").slice(-10);
26
+ return luhnValid(core);
27
+ }
28
+ function isSamordningsnummer(value) {
29
+ const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
30
+ if (!m) return false;
31
+ const month = Number(m[3]);
32
+ const day = Number(m[4]);
33
+ if (month < 1 || month > 12) return false;
34
+ if (day < 61 || day > 91) return false;
35
+ const core = value.replace(/[-+]/g, "").slice(-10);
36
+ return luhnValid(core);
37
+ }
38
+ function isOrganisationsnummer(value) {
39
+ const only = value.replace(/\D/g, "");
40
+ const core = only.length === 12 ? only.slice(2) : only;
41
+ if (core.length !== 10) return false;
42
+ if (Number(core[2]) < 2) return false;
43
+ return luhnValid(core);
44
+ }
45
+
46
+ // src/detectors/index.ts
47
+ function regexDetector(label, regex, validate) {
48
+ if (!regex.global) {
49
+ throw new Error(`Detector "${label}" requires a global ("g") regex`);
50
+ }
51
+ return {
52
+ label,
53
+ detect(input) {
54
+ const out = [];
55
+ regex.lastIndex = 0;
56
+ for (const m of input.matchAll(regex)) {
57
+ if (m.index === void 0) continue;
58
+ const value = m[1] ?? m[0];
59
+ if (value.length === 0) continue;
60
+ const start = m.index + m[0].indexOf(value);
61
+ if (validate && !validate(value)) continue;
62
+ out.push({ start, end: start + value.length, value });
63
+ }
64
+ return out;
65
+ }
66
+ };
67
+ }
68
+ var personnummer = regexDetector(
69
+ "PERSONNUMMER",
70
+ /\b(?:19|20)?\d{6}[-+]?\d{4}\b/g,
71
+ isPersonnummer
72
+ );
73
+ var samordningsnummer = regexDetector(
74
+ "SAMORDNINGSNUMMER",
75
+ /\b(?:19|20)?\d{6}[-+]?\d{4}\b/g,
76
+ isSamordningsnummer
77
+ );
78
+ var organisationsnummer = regexDetector(
79
+ "ORGANISATIONSNUMMER",
80
+ /\b\d{6}[-]?\d{4}\b/g,
81
+ isOrganisationsnummer
82
+ );
83
+ var email = regexDetector("EMAIL", /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi);
84
+ var phone = regexDetector(
85
+ "PHONE",
86
+ /(?:\+46[\s-]?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8}\b/g
87
+ );
88
+ var postnummer = regexDetector("POSTNUMMER", /\b\d{3}\s?\d{2}\b/g);
89
+ var bankgiro = regexDetector(
90
+ "BANKGIRO",
91
+ /\b\d{3,4}-\d{4}\b/g,
92
+ (v) => luhnValid(v.replace(/\D/g, ""))
93
+ );
94
+ var plusgiro = regexDetector(
95
+ "PLUSGIRO",
96
+ /\b\d(?:\s?\d){0,6}-\d\b/g,
97
+ (v) => luhnValid(v.replace(/\D/g, ""))
98
+ );
99
+ var iban = regexDetector("IBAN", /\bSE\d{2}(?:\s?\d){20}\b/gi);
100
+ var creditCard = regexDetector("CREDIT_CARD", /\b\d(?:[ -]?\d){12,18}\b/g, (v) => {
101
+ const digits = v.replace(/\D/g, "");
102
+ return digits.length >= 13 && digits.length <= 19 && luhnValid(digits);
103
+ });
104
+ var ipAddress = regexDetector(
105
+ "IP_ADDRESS",
106
+ /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g
107
+ );
108
+ var url = regexDetector("URL", /\bhttps?:\/\/[^\s<>")]+/gi);
109
+ var defaultDetectors = [
110
+ email,
111
+ url,
112
+ personnummer,
113
+ samordningsnummer,
114
+ organisationsnummer,
115
+ iban,
116
+ creditCard,
117
+ bankgiro,
118
+ plusgiro,
119
+ phone,
120
+ postnummer,
121
+ ipAddress
122
+ ];
123
+
124
+ // src/redact.ts
125
+ function defaultPlaceholder(label, index) {
126
+ return `[${label}_${index}]`;
127
+ }
128
+ function resolveOverlaps(detections) {
129
+ const sorted = [...detections].sort((a, b) => {
130
+ if (a.start !== b.start) return a.start - b.start;
131
+ if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start);
132
+ return a.label.localeCompare(b.label);
133
+ });
134
+ const kept = [];
135
+ let cursor = -1;
136
+ for (const d of sorted) {
137
+ if (d.start >= cursor) {
138
+ kept.push(d);
139
+ cursor = d.end;
140
+ }
141
+ }
142
+ return kept;
143
+ }
144
+ function redact(input, options = {}) {
145
+ const detectors = options.detectors ?? defaultDetectors;
146
+ const all = [];
147
+ for (const detector of detectors) {
148
+ for (const m of detector.detect(input)) {
149
+ all.push({ ...m, label: detector.label });
150
+ }
151
+ }
152
+ return redactFromDetections(input, all, options);
153
+ }
154
+ function redactFromDetections(input, detections, options = {}) {
155
+ const placeholder = options.placeholder ?? defaultPlaceholder;
156
+ const resolved = resolveOverlaps(detections);
157
+ const counters = /* @__PURE__ */ new Map();
158
+ const tokenByKey = /* @__PURE__ */ new Map();
159
+ const map = {};
160
+ const redactions = [];
161
+ for (const d of resolved) {
162
+ const key = `${d.label}::${d.value}`;
163
+ let token = tokenByKey.get(key);
164
+ if (!token) {
165
+ const next = (counters.get(d.label) ?? 0) + 1;
166
+ counters.set(d.label, next);
167
+ token = placeholder(d.label, next);
168
+ tokenByKey.set(key, token);
169
+ map[token] = d.value;
170
+ }
171
+ redactions.push({ ...d, replacement: token });
172
+ }
173
+ let text = "";
174
+ let last = 0;
175
+ for (const r of redactions) {
176
+ text += input.slice(last, r.start);
177
+ text += r.replacement;
178
+ last = r.end;
179
+ }
180
+ text += input.slice(last);
181
+ return {
182
+ text,
183
+ redactions,
184
+ map,
185
+ restore: (s) => restore(s, map)
186
+ };
187
+ }
188
+ function restore(text, map) {
189
+ let out = text;
190
+ const tokens = Object.keys(map).sort((a, b) => b.length - a.length);
191
+ for (const token of tokens) {
192
+ out = out.split(token).join(map[token]);
193
+ }
194
+ return out;
195
+ }
196
+
197
+ export { bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
198
+ //# sourceMappingURL=index.js.map
199
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"mappings":";AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,M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AM,IAAI,KAAA,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer) — samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\nexport const email = regexDetector(\"EMAIL\", /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */\nexport const phone = regexDetector(\n \"PHONE\",\n /(?:\\+46[\\s-]?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8}\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"CREDIT_CARD\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADDRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\s<>\")]+/gi)\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, RedactOptions, RedactResult, Redaction } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[PERSON_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `@maskera/ner`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${d.label}::${d.value}`\n let token = tokenByKey.get(key)\n if (!token) {\n const next = (counters.get(d.label) ?? 0) + 1\n counters.set(d.label, next)\n token = placeholder(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@maskera/core",
3
+ "version": "0.2.0",
4
+ "description": "Swedish-first, zero-dependency PII detection & redaction. Runs in the browser, Node, and edge.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Joel Hägvall",
8
+ "keywords": [
9
+ "pii",
10
+ "redaction",
11
+ "anonymization",
12
+ "gdpr",
13
+ "swedish",
14
+ "personnummer",
15
+ "privacy",
16
+ "llm",
17
+ "ai"
18
+ ],
19
+ "homepage": "https://github.com/joelhagvall/maskera#readme",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/joelhagvall/maskera.git",
23
+ "directory": "packages/core"
24
+ },
25
+ "bugs": "https://github.com/joelhagvall/maskera/issues",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "sideEffects": false,
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "import": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/index.d.cts",
41
+ "default": "./dist/index.cjs"
42
+ }
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "CHANGELOG.md"
48
+ ],
49
+ "devDependencies": {
50
+ "fast-check": "^4.8.0",
51
+ "tsup": "^8.3.5",
52
+ "typescript": "^5.7.2",
53
+ "vitest": "^2.1.8"
54
+ },
55
+ "scripts": {
56
+ "build": "tsup",
57
+ "dev": "tsup --watch",
58
+ "test": "vitest run",
59
+ "test:watch": "vitest"
60
+ }
61
+ }