@broberg/legal 0.5.0 → 0.7.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.
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ var secretScan = require('@broberg/secret-scan');
4
+
5
+ // src/pseudonymise.ts
6
+ var MAX_RETENTION_MONTHS = 6;
7
+ var enc = new TextEncoder();
8
+ async function hmac(key, message) {
9
+ if (!key || key.length < 32) throw new Error("pseudonymisation key must be at least 32 characters \u2014 use a vault-held secret");
10
+ const k = await crypto.subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
11
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", k, enc.encode(message)));
12
+ return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");
13
+ }
14
+ async function pseudonymId(value, key, kind = "id") {
15
+ return `${kind}_${await hmac(key, `${kind}\0${value.trim().toLowerCase()}`)}`;
16
+ }
17
+ var HEALTH = /\b(smert\w*|ondt|diagnos\w*|sygdom\w*|syg|sygemeld\w*|medicin\w*|piller?|operation\w*|opereret|skade[nrs]?|gigt|kræft|depression\w*|angst\w*|gravid\w*|blodtryk\w*|diabetes|sukkersyge|allergi\w*|behandling\w*|fysioterap\w*|genoptræning\w*|hovedpine|migræne|hospital\w*|indlagt|læge[nr]?|symptom\w*|astma|hjerte\w*|psykolog\w*|psykiat\w*|stress\w*)\b/i;
18
+ var IPV4 = /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g;
19
+ var IPV6 = /\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\b/gi;
20
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
+ function createConversation(opts) {
22
+ const people = /* @__PURE__ */ new Map();
23
+ function personOf(name) {
24
+ const parts = name.trim().split(/\s+/).filter((p) => p.length >= 2);
25
+ const full = parts.join(" ").toLowerCase();
26
+ const existing = people.get(full);
27
+ const n = existing ?? (people.size ? Math.max(...people.values()) + 1 : 1);
28
+ people.set(full, n);
29
+ for (const p of parts) if (p.length >= 3 && !people.has(p.toLowerCase())) people.set(p.toLowerCase(), n);
30
+ return n;
31
+ }
32
+ return {
33
+ async pseudonymise(input) {
34
+ const replaced = { cpr: 0, email: 0, phone: 0, ip: 0, name: 0, health: 0 };
35
+ let text = input;
36
+ if ((opts.health ?? "remove") === "remove") {
37
+ text = text.split(/(?<=[.!?])\s+/).map((s) => HEALTH.test(s) ? (replaced.health++, "[HELBRED FJERNET]") : s).join(" ");
38
+ }
39
+ const hits = secretScan.findPersonalData(text).sort((a, b) => b.start - a.start);
40
+ for (const h of hits) {
41
+ const value = text.slice(h.start, h.end);
42
+ const marker = h.kind === "cpr" ? "[CPR]" : `[${h.kind.toUpperCase()}-${(await pseudonymId(value, opts.key, h.kind)).split("_")[1]}]`;
43
+ replaced[h.kind]++;
44
+ text = text.slice(0, h.start) + marker + text.slice(h.end);
45
+ }
46
+ for (const re of [IPV4, IPV6]) {
47
+ for (const m of [...text.matchAll(re)].reverse()) {
48
+ replaced.ip++;
49
+ text = text.slice(0, m.index) + `[IP-${(await pseudonymId(m[0], opts.key, "ip")).split("_")[1]}]` + text.slice(m.index + m[0].length);
50
+ }
51
+ }
52
+ const names = [...opts.knownNames ?? [], ...opts.findNames ? await opts.findNames(text) : []].filter((n) => n.trim().length >= 2);
53
+ for (const name of names) personOf(name);
54
+ const forms = [...people.keys()].sort((a, b) => b.length - a.length);
55
+ for (const form of forms) {
56
+ const re = new RegExp(`(?<![\\p{L}\\d])${escape(form).replace(/ /g, "\\s+")}(s)?(?![\\p{L}\\d])`, "giu");
57
+ text = text.replace(re, (_m, genitive) => {
58
+ replaced.name++;
59
+ return `[PERSON-${people.get(form)}]${genitive ? "s" : ""}`;
60
+ });
61
+ }
62
+ const notExamined = ["addresses", "indirect-identifiers"];
63
+ if (!opts.findNames) notExamined.unshift("names-not-known");
64
+ if ((opts.health ?? "remove") === "remove") notExamined.push("health-beyond-keywords");
65
+ return { text, replaced, notExamined };
66
+ }
67
+ };
68
+ }
69
+ function keepUntil(collectedAt, months = MAX_RETENTION_MONTHS) {
70
+ if (!Number.isInteger(months) || months < 1 || months > MAX_RETENTION_MONTHS) {
71
+ throw new Error(`retention must be 1\u2013${MAX_RETENTION_MONTHS} months (owner's ceiling)`);
72
+ }
73
+ const d = new Date(collectedAt.getTime());
74
+ const day = d.getUTCDate();
75
+ d.setUTCMonth(d.getUTCMonth() + months);
76
+ if (d.getUTCDate() !== day) d.setUTCDate(0);
77
+ return d;
78
+ }
79
+ async function toAnalysisRecord(input, conversation, key, months = MAX_RETENTION_MONTHS) {
80
+ const p = await conversation.pseudonymise(input.text);
81
+ return {
82
+ id: input.id,
83
+ subject: await pseudonymId(input.subjectId, key, "subject"),
84
+ text: p.text,
85
+ collectedAt: input.collectedAt.toISOString(),
86
+ keepUntil: keepUntil(input.collectedAt, months).toISOString(),
87
+ notExamined: p.notExamined
88
+ };
89
+ }
90
+ async function deleteExpired(store, now = /* @__PURE__ */ new Date()) {
91
+ const ids = await store.listExpired(now);
92
+ if (ids.length) await store.delete(ids);
93
+ return ids.length;
94
+ }
95
+
96
+ exports.MAX_RETENTION_MONTHS = MAX_RETENTION_MONTHS;
97
+ exports.createConversation = createConversation;
98
+ exports.deleteExpired = deleteExpired;
99
+ exports.keepUntil = keepUntil;
100
+ exports.pseudonymId = pseudonymId;
101
+ exports.toAnalysisRecord = toAnalysisRecord;
102
+ //# sourceMappingURL=pseudonymise.cjs.map
103
+ //# sourceMappingURL=pseudonymise.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pseudonymise.ts"],"names":["findPersonalData"],"mappings":";;;;;AAWO,IAAM,oBAAA,GAAuB;AAgCpC,IAAM,GAAA,GAAM,IAAI,WAAA,EAAY;AAE5B,eAAe,IAAA,CAAK,KAAa,OAAA,EAAkC;AACjE,EAA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C3C,WAAW,SAAA,CAAU,KAAA,CAAM,WAAA,EAAa,MAAM,EAAE,WAAA,EAAY;AAAA,IAC5D,aAAa,CAAA,CAAE;AAAA,GACjB;AACF;AASA,eAAsB,aAAA,CAAc,KAAA,EAAsB,GAAA,mBAAY,IAAI,MAAK,EAAoB;AACjG,EAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,WAAA,CAAY,GAAG,CAAA;AACvC,EAAA,IAAI,GAAA,CAAI,MAAA,EAAQ,MAAM,KAAA,CAAM,OAAO,GAAG,CAAA;AACtC,EAAA,OAAO,GAAA,CAAI,MAAA;AACb","file":"pseudonymise.cjs","sourcesContent":["// components F110.8 — pseudonymisation before a conversation enters the analysis copy.\n// The techniques and why are in docs/legal/pseudonymisation-standards.md (EDPB 01/2025,\n// ENISA 2019/2021, ISO/IEC 20889/27559, NIST SP 800-188). Pseudonymised data is STILL\n// personal data: this module never claims to anonymise, and everything it does not examine\n// is returned in `notExamined`, never passed silently as clean.\n//\n// Web Crypto only, so it runs in Node, Bun and edge runtimes alike.\n\nimport { findPersonalData } from \"@broberg/secret-scan\";\n\n/** The owner's ceiling for the analysis copy (31 Oct 2026). */\nexport const MAX_RETENTION_MONTHS = 6;\n\nexport interface PseudonymiseOptions {\n /**\n * The HMAC key of ONE pseudonymisation domain (e.g. \"product analysis\"). Keep it in the\n * Secrets Vault, never next to the analysis copy. Rotating it unlinks old pseudonyms from new.\n */\n key: string;\n /** Names the system already knows for this conversation (sender, case parties) — found and replaced. */\n knownNames?: string[];\n /**\n * Optional step that finds OTHER names in the text, e.g. an EU model through @broberg/ai-sdk.\n * Without it, names the system does not know are reported in `notExamined`.\n */\n findNames?: (text: string) => Promise<string[]>;\n /**\n * `\"remove\"` (default): sentences about health are removed before the copy (art. 9).\n * `\"consented\"`: only when the person has given EXPLICIT consent to analysis of their content.\n */\n health?: \"remove\" | \"consented\";\n}\n\nexport type NotExamined = \"names-not-known\" | \"health-beyond-keywords\" | \"addresses\" | \"indirect-identifiers\";\n\nexport interface PseudonymisedText {\n text: string;\n /** How many of each kind were replaced — never the values. */\n replaced: Record<\"cpr\" | \"email\" | \"phone\" | \"ip\" | \"name\" | \"health\", number>;\n /** What this step did NOT examine. A consumer must not call the result clean beyond these. */\n notExamined: NotExamined[];\n}\n\nconst enc = new TextEncoder();\n\nasync function hmac(key: string, message: string): Promise<string> {\n if (!key || key.length < 32) throw new Error(\"pseudonymisation key must be at least 32 characters — use a vault-held secret\");\n const k = await crypto.subtle.importKey(\"raw\", enc.encode(key), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const sig = new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, enc.encode(message)));\n return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A keyed pseudonym for a direct identifier (account id, e-mail, phone, IP). The same value\n * gives the same pseudonym under the same key; without the key it cannot be reversed or\n * guessed (a plain hash of an e-mail can be — ENISA/EDPB). `kind` keeps an e-mail and an\n * account id that happen to share a string from colliding.\n */\nexport async function pseudonymId(value: string, key: string, kind = \"id\"): Promise<string> {\n return `${kind}_${await hmac(key, `${kind}\\u0000${value.trim().toLowerCase()}`)}`;\n}\n\n// Danish health vocabulary — a keyword step, so what it misses is named in notExamined.\nconst HEALTH = /\\b(smert\\w*|ondt|diagnos\\w*|sygdom\\w*|syg|sygemeld\\w*|medicin\\w*|piller?|operation\\w*|opereret|skade[nrs]?|gigt|kræft|depression\\w*|angst\\w*|gravid\\w*|blodtryk\\w*|diabetes|sukkersyge|allergi\\w*|behandling\\w*|fysioterap\\w*|genoptræning\\w*|hovedpine|migræne|hospital\\w*|indlagt|læge[nr]?|symptom\\w*|astma|hjerte\\w*|psykolog\\w*|psykiat\\w*|stress\\w*)\\b/i;\nconst IPV4 = /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g;\nconst IPV6 = /\\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\\b/gi;\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * One conversation: names get the SAME marker throughout it («Mette Jensen» and later «Mette»\n * are both [PERSON-1]), and a new conversation starts counting again.\n */\nexport function createConversation(opts: PseudonymiseOptions) {\n const people = new Map<string, number>(); // lower-cased name part → person number\n\n function personOf(name: string): number {\n const parts = name.trim().split(/\\s+/).filter((p) => p.length >= 2);\n const full = parts.join(\" \").toLowerCase();\n // A full name matches only itself; a lone first name may match a person seen in full.\n // («Mette Hansen» and «Mette Jensen» stay two people.)\n const existing = people.get(full); // parts of names seen in full are stored too\n const n = existing ?? (people.size ? Math.max(...people.values()) + 1 : 1);\n people.set(full, n);\n for (const p of parts) if (p.length >= 3 && !people.has(p.toLowerCase())) people.set(p.toLowerCase(), n);\n return n;\n }\n\n return {\n async pseudonymise(input: string): Promise<PseudonymisedText> {\n const replaced = { cpr: 0, email: 0, phone: 0, ip: 0, name: 0, health: 0 };\n let text = input;\n\n // 1. Art. 9 first: a health sentence never reaches the copy, whatever else it holds.\n if ((opts.health ?? \"remove\") === \"remove\") {\n text = text\n .split(/(?<=[.!?])\\s+/)\n .map((s) => (HEALTH.test(s) ? (replaced.health++, \"[HELBRED FJERNET]\") : s))\n .join(\" \");\n }\n\n // 2. CPR removed, e-mail and phone pseudonymised (positions from @broberg/secret-scan).\n const hits = findPersonalData(text).sort((a, b) => b.start - a.start);\n for (const h of hits) {\n const value = text.slice(h.start, h.end);\n const marker = h.kind === \"cpr\" ? \"[CPR]\" : `[${h.kind.toUpperCase()}-${(await pseudonymId(value, opts.key, h.kind)).split(\"_\")[1]}]`;\n replaced[h.kind]++;\n text = text.slice(0, h.start) + marker + text.slice(h.end);\n }\n for (const re of [IPV4, IPV6]) {\n for (const m of [...text.matchAll(re)].reverse()) {\n replaced.ip++;\n text = text.slice(0, m.index!) + `[IP-${(await pseudonymId(m[0], opts.key, \"ip\")).split(\"_\")[1]}]` + text.slice(m.index! + m[0].length);\n }\n }\n\n // 3. Names: the ones the system knows, then (if given) the ones a model finds.\n const names = [...(opts.knownNames ?? []), ...(opts.findNames ? await opts.findNames(text) : [])].filter((n) => n.trim().length >= 2);\n for (const name of names) personOf(name);\n // Longest first, so «Mette Jensen» is replaced before «Mette».\n const forms = [...people.keys()].sort((a, b) => b.length - a.length);\n for (const form of forms) {\n const re = new RegExp(`(?<![\\\\p{L}\\\\d])${escape(form).replace(/ /g, \"\\\\s+\")}(s)?(?![\\\\p{L}\\\\d])`, \"giu\");\n text = text.replace(re, (_m, genitive?: string) => {\n replaced.name++;\n return `[PERSON-${people.get(form)}]${genitive ? \"s\" : \"\"}`;\n });\n }\n\n const notExamined: NotExamined[] = [\"addresses\", \"indirect-identifiers\"];\n if (!opts.findNames) notExamined.unshift(\"names-not-known\");\n if ((opts.health ?? \"remove\") === \"remove\") notExamined.push(\"health-beyond-keywords\");\n return { text, replaced, notExamined };\n },\n };\n}\n\n/** The date a record may be kept until — at most MAX_RETENTION_MONTHS after collection. */\nexport function keepUntil(collectedAt: Date, months = MAX_RETENTION_MONTHS): Date {\n if (!Number.isInteger(months) || months < 1 || months > MAX_RETENTION_MONTHS) {\n throw new Error(`retention must be 1–${MAX_RETENTION_MONTHS} months (owner's ceiling)`);\n }\n const d = new Date(collectedAt.getTime());\n const day = d.getUTCDate();\n d.setUTCMonth(d.getUTCMonth() + months);\n if (d.getUTCDate() !== day) d.setUTCDate(0); // 31 Aug + 6 → 28/29 Feb, never 3 Mar\n return d;\n}\n\n/** One record in the analysis copy. `subject` is a keyed pseudonym, never the account id. */\nexport interface AnalysisRecord {\n id: string;\n subject: string;\n text: string;\n collectedAt: string;\n keepUntil: string;\n notExamined: NotExamined[];\n}\n\n/** Build a record for the analysis copy: the subject pseudonymised, the text pseudonymised, the deadline set. */\nexport async function toAnalysisRecord(\n input: { id: string; subjectId: string; text: string; collectedAt: Date },\n conversation: ReturnType<typeof createConversation>,\n key: string,\n months = MAX_RETENTION_MONTHS,\n): Promise<AnalysisRecord> {\n const p = await conversation.pseudonymise(input.text);\n return {\n id: input.id,\n subject: await pseudonymId(input.subjectId, key, \"subject\"),\n text: p.text,\n collectedAt: input.collectedAt.toISOString(),\n keepUntil: keepUntil(input.collectedAt, months).toISOString(),\n notExamined: p.notExamined,\n };\n}\n\n/** The app owns the rows; the package owns the rule. */\nexport interface AnalysisStore {\n listExpired(now: Date): Promise<string[]>;\n delete(ids: string[]): Promise<void>;\n}\n\n/** Remove every record whose keepUntil has passed. Returns how many went. */\nexport async function deleteExpired(store: AnalysisStore, now: Date = new Date()): Promise<number> {\n const ids = await store.listExpired(now);\n if (ids.length) await store.delete(ids);\n return ids.length;\n}\n"]}
@@ -0,0 +1,70 @@
1
+ /** The owner's ceiling for the analysis copy (31 Oct 2026). */
2
+ declare const MAX_RETENTION_MONTHS = 6;
3
+ interface PseudonymiseOptions {
4
+ /**
5
+ * The HMAC key of ONE pseudonymisation domain (e.g. "product analysis"). Keep it in the
6
+ * Secrets Vault, never next to the analysis copy. Rotating it unlinks old pseudonyms from new.
7
+ */
8
+ key: string;
9
+ /** Names the system already knows for this conversation (sender, case parties) — found and replaced. */
10
+ knownNames?: string[];
11
+ /**
12
+ * Optional step that finds OTHER names in the text, e.g. an EU model through @broberg/ai-sdk.
13
+ * Without it, names the system does not know are reported in `notExamined`.
14
+ */
15
+ findNames?: (text: string) => Promise<string[]>;
16
+ /**
17
+ * `"remove"` (default): sentences about health are removed before the copy (art. 9).
18
+ * `"consented"`: only when the person has given EXPLICIT consent to analysis of their content.
19
+ */
20
+ health?: "remove" | "consented";
21
+ }
22
+ type NotExamined = "names-not-known" | "health-beyond-keywords" | "addresses" | "indirect-identifiers";
23
+ interface PseudonymisedText {
24
+ text: string;
25
+ /** How many of each kind were replaced — never the values. */
26
+ replaced: Record<"cpr" | "email" | "phone" | "ip" | "name" | "health", number>;
27
+ /** What this step did NOT examine. A consumer must not call the result clean beyond these. */
28
+ notExamined: NotExamined[];
29
+ }
30
+ /**
31
+ * A keyed pseudonym for a direct identifier (account id, e-mail, phone, IP). The same value
32
+ * gives the same pseudonym under the same key; without the key it cannot be reversed or
33
+ * guessed (a plain hash of an e-mail can be — ENISA/EDPB). `kind` keeps an e-mail and an
34
+ * account id that happen to share a string from colliding.
35
+ */
36
+ declare function pseudonymId(value: string, key: string, kind?: string): Promise<string>;
37
+ /**
38
+ * One conversation: names get the SAME marker throughout it («Mette Jensen» and later «Mette»
39
+ * are both [PERSON-1]), and a new conversation starts counting again.
40
+ */
41
+ declare function createConversation(opts: PseudonymiseOptions): {
42
+ pseudonymise(input: string): Promise<PseudonymisedText>;
43
+ };
44
+ /** The date a record may be kept until — at most MAX_RETENTION_MONTHS after collection. */
45
+ declare function keepUntil(collectedAt: Date, months?: number): Date;
46
+ /** One record in the analysis copy. `subject` is a keyed pseudonym, never the account id. */
47
+ interface AnalysisRecord {
48
+ id: string;
49
+ subject: string;
50
+ text: string;
51
+ collectedAt: string;
52
+ keepUntil: string;
53
+ notExamined: NotExamined[];
54
+ }
55
+ /** Build a record for the analysis copy: the subject pseudonymised, the text pseudonymised, the deadline set. */
56
+ declare function toAnalysisRecord(input: {
57
+ id: string;
58
+ subjectId: string;
59
+ text: string;
60
+ collectedAt: Date;
61
+ }, conversation: ReturnType<typeof createConversation>, key: string, months?: number): Promise<AnalysisRecord>;
62
+ /** The app owns the rows; the package owns the rule. */
63
+ interface AnalysisStore {
64
+ listExpired(now: Date): Promise<string[]>;
65
+ delete(ids: string[]): Promise<void>;
66
+ }
67
+ /** Remove every record whose keepUntil has passed. Returns how many went. */
68
+ declare function deleteExpired(store: AnalysisStore, now?: Date): Promise<number>;
69
+
70
+ export { type AnalysisRecord, type AnalysisStore, MAX_RETENTION_MONTHS, type NotExamined, type PseudonymiseOptions, type PseudonymisedText, createConversation, deleteExpired, keepUntil, pseudonymId, toAnalysisRecord };
@@ -0,0 +1,70 @@
1
+ /** The owner's ceiling for the analysis copy (31 Oct 2026). */
2
+ declare const MAX_RETENTION_MONTHS = 6;
3
+ interface PseudonymiseOptions {
4
+ /**
5
+ * The HMAC key of ONE pseudonymisation domain (e.g. "product analysis"). Keep it in the
6
+ * Secrets Vault, never next to the analysis copy. Rotating it unlinks old pseudonyms from new.
7
+ */
8
+ key: string;
9
+ /** Names the system already knows for this conversation (sender, case parties) — found and replaced. */
10
+ knownNames?: string[];
11
+ /**
12
+ * Optional step that finds OTHER names in the text, e.g. an EU model through @broberg/ai-sdk.
13
+ * Without it, names the system does not know are reported in `notExamined`.
14
+ */
15
+ findNames?: (text: string) => Promise<string[]>;
16
+ /**
17
+ * `"remove"` (default): sentences about health are removed before the copy (art. 9).
18
+ * `"consented"`: only when the person has given EXPLICIT consent to analysis of their content.
19
+ */
20
+ health?: "remove" | "consented";
21
+ }
22
+ type NotExamined = "names-not-known" | "health-beyond-keywords" | "addresses" | "indirect-identifiers";
23
+ interface PseudonymisedText {
24
+ text: string;
25
+ /** How many of each kind were replaced — never the values. */
26
+ replaced: Record<"cpr" | "email" | "phone" | "ip" | "name" | "health", number>;
27
+ /** What this step did NOT examine. A consumer must not call the result clean beyond these. */
28
+ notExamined: NotExamined[];
29
+ }
30
+ /**
31
+ * A keyed pseudonym for a direct identifier (account id, e-mail, phone, IP). The same value
32
+ * gives the same pseudonym under the same key; without the key it cannot be reversed or
33
+ * guessed (a plain hash of an e-mail can be — ENISA/EDPB). `kind` keeps an e-mail and an
34
+ * account id that happen to share a string from colliding.
35
+ */
36
+ declare function pseudonymId(value: string, key: string, kind?: string): Promise<string>;
37
+ /**
38
+ * One conversation: names get the SAME marker throughout it («Mette Jensen» and later «Mette»
39
+ * are both [PERSON-1]), and a new conversation starts counting again.
40
+ */
41
+ declare function createConversation(opts: PseudonymiseOptions): {
42
+ pseudonymise(input: string): Promise<PseudonymisedText>;
43
+ };
44
+ /** The date a record may be kept until — at most MAX_RETENTION_MONTHS after collection. */
45
+ declare function keepUntil(collectedAt: Date, months?: number): Date;
46
+ /** One record in the analysis copy. `subject` is a keyed pseudonym, never the account id. */
47
+ interface AnalysisRecord {
48
+ id: string;
49
+ subject: string;
50
+ text: string;
51
+ collectedAt: string;
52
+ keepUntil: string;
53
+ notExamined: NotExamined[];
54
+ }
55
+ /** Build a record for the analysis copy: the subject pseudonymised, the text pseudonymised, the deadline set. */
56
+ declare function toAnalysisRecord(input: {
57
+ id: string;
58
+ subjectId: string;
59
+ text: string;
60
+ collectedAt: Date;
61
+ }, conversation: ReturnType<typeof createConversation>, key: string, months?: number): Promise<AnalysisRecord>;
62
+ /** The app owns the rows; the package owns the rule. */
63
+ interface AnalysisStore {
64
+ listExpired(now: Date): Promise<string[]>;
65
+ delete(ids: string[]): Promise<void>;
66
+ }
67
+ /** Remove every record whose keepUntil has passed. Returns how many went. */
68
+ declare function deleteExpired(store: AnalysisStore, now?: Date): Promise<number>;
69
+
70
+ export { type AnalysisRecord, type AnalysisStore, MAX_RETENTION_MONTHS, type NotExamined, type PseudonymiseOptions, type PseudonymisedText, createConversation, deleteExpired, keepUntil, pseudonymId, toAnalysisRecord };
@@ -0,0 +1,96 @@
1
+ import { findPersonalData } from '@broberg/secret-scan';
2
+
3
+ // src/pseudonymise.ts
4
+ var MAX_RETENTION_MONTHS = 6;
5
+ var enc = new TextEncoder();
6
+ async function hmac(key, message) {
7
+ if (!key || key.length < 32) throw new Error("pseudonymisation key must be at least 32 characters \u2014 use a vault-held secret");
8
+ const k = await crypto.subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
9
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", k, enc.encode(message)));
10
+ return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");
11
+ }
12
+ async function pseudonymId(value, key, kind = "id") {
13
+ return `${kind}_${await hmac(key, `${kind}\0${value.trim().toLowerCase()}`)}`;
14
+ }
15
+ var HEALTH = /\b(smert\w*|ondt|diagnos\w*|sygdom\w*|syg|sygemeld\w*|medicin\w*|piller?|operation\w*|opereret|skade[nrs]?|gigt|kræft|depression\w*|angst\w*|gravid\w*|blodtryk\w*|diabetes|sukkersyge|allergi\w*|behandling\w*|fysioterap\w*|genoptræning\w*|hovedpine|migræne|hospital\w*|indlagt|læge[nr]?|symptom\w*|astma|hjerte\w*|psykolog\w*|psykiat\w*|stress\w*)\b/i;
16
+ var IPV4 = /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g;
17
+ var IPV6 = /\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\b/gi;
18
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ function createConversation(opts) {
20
+ const people = /* @__PURE__ */ new Map();
21
+ function personOf(name) {
22
+ const parts = name.trim().split(/\s+/).filter((p) => p.length >= 2);
23
+ const full = parts.join(" ").toLowerCase();
24
+ const existing = people.get(full);
25
+ const n = existing ?? (people.size ? Math.max(...people.values()) + 1 : 1);
26
+ people.set(full, n);
27
+ for (const p of parts) if (p.length >= 3 && !people.has(p.toLowerCase())) people.set(p.toLowerCase(), n);
28
+ return n;
29
+ }
30
+ return {
31
+ async pseudonymise(input) {
32
+ const replaced = { cpr: 0, email: 0, phone: 0, ip: 0, name: 0, health: 0 };
33
+ let text = input;
34
+ if ((opts.health ?? "remove") === "remove") {
35
+ text = text.split(/(?<=[.!?])\s+/).map((s) => HEALTH.test(s) ? (replaced.health++, "[HELBRED FJERNET]") : s).join(" ");
36
+ }
37
+ const hits = findPersonalData(text).sort((a, b) => b.start - a.start);
38
+ for (const h of hits) {
39
+ const value = text.slice(h.start, h.end);
40
+ const marker = h.kind === "cpr" ? "[CPR]" : `[${h.kind.toUpperCase()}-${(await pseudonymId(value, opts.key, h.kind)).split("_")[1]}]`;
41
+ replaced[h.kind]++;
42
+ text = text.slice(0, h.start) + marker + text.slice(h.end);
43
+ }
44
+ for (const re of [IPV4, IPV6]) {
45
+ for (const m of [...text.matchAll(re)].reverse()) {
46
+ replaced.ip++;
47
+ text = text.slice(0, m.index) + `[IP-${(await pseudonymId(m[0], opts.key, "ip")).split("_")[1]}]` + text.slice(m.index + m[0].length);
48
+ }
49
+ }
50
+ const names = [...opts.knownNames ?? [], ...opts.findNames ? await opts.findNames(text) : []].filter((n) => n.trim().length >= 2);
51
+ for (const name of names) personOf(name);
52
+ const forms = [...people.keys()].sort((a, b) => b.length - a.length);
53
+ for (const form of forms) {
54
+ const re = new RegExp(`(?<![\\p{L}\\d])${escape(form).replace(/ /g, "\\s+")}(s)?(?![\\p{L}\\d])`, "giu");
55
+ text = text.replace(re, (_m, genitive) => {
56
+ replaced.name++;
57
+ return `[PERSON-${people.get(form)}]${genitive ? "s" : ""}`;
58
+ });
59
+ }
60
+ const notExamined = ["addresses", "indirect-identifiers"];
61
+ if (!opts.findNames) notExamined.unshift("names-not-known");
62
+ if ((opts.health ?? "remove") === "remove") notExamined.push("health-beyond-keywords");
63
+ return { text, replaced, notExamined };
64
+ }
65
+ };
66
+ }
67
+ function keepUntil(collectedAt, months = MAX_RETENTION_MONTHS) {
68
+ if (!Number.isInteger(months) || months < 1 || months > MAX_RETENTION_MONTHS) {
69
+ throw new Error(`retention must be 1\u2013${MAX_RETENTION_MONTHS} months (owner's ceiling)`);
70
+ }
71
+ const d = new Date(collectedAt.getTime());
72
+ const day = d.getUTCDate();
73
+ d.setUTCMonth(d.getUTCMonth() + months);
74
+ if (d.getUTCDate() !== day) d.setUTCDate(0);
75
+ return d;
76
+ }
77
+ async function toAnalysisRecord(input, conversation, key, months = MAX_RETENTION_MONTHS) {
78
+ const p = await conversation.pseudonymise(input.text);
79
+ return {
80
+ id: input.id,
81
+ subject: await pseudonymId(input.subjectId, key, "subject"),
82
+ text: p.text,
83
+ collectedAt: input.collectedAt.toISOString(),
84
+ keepUntil: keepUntil(input.collectedAt, months).toISOString(),
85
+ notExamined: p.notExamined
86
+ };
87
+ }
88
+ async function deleteExpired(store, now = /* @__PURE__ */ new Date()) {
89
+ const ids = await store.listExpired(now);
90
+ if (ids.length) await store.delete(ids);
91
+ return ids.length;
92
+ }
93
+
94
+ export { MAX_RETENTION_MONTHS, createConversation, deleteExpired, keepUntil, pseudonymId, toAnalysisRecord };
95
+ //# sourceMappingURL=pseudonymise.js.map
96
+ //# sourceMappingURL=pseudonymise.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pseudonymise.ts"],"names":[],"mappings":";;;AAWO,IAAM,oBAAA,GAAuB;AAgCpC,IAAM,GAAA,GAAM,IAAI,WAAA,EAAY;AAE5B,eAAe,IAAA,CAAK,KAAa,OAAA,EAAkC;AACjE,EAAA,IAAI,CAAC,OAAO,GAAA,CAAI,MAAA,GAAS,IAAI,MAAM,IAAI,MAAM,oFAA+E,CAAA;AAC5H,EAAA,MAAM,IAAI,MAAM,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,IAAI,MAAA,CAAO,GAAG,GAAG,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,SAAA,IAAa,KAAA,EAAO,CAAC,MAAM,CAAC,CAAA;AAClH,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,MAAM,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,MAAA,EAAQ,CAAA,EAAG,GAAA,CAAI,MAAA,CAAO,OAAO,CAAC,CAAC,CAAA;AACnF,EAAA,OAAO,CAAC,GAAG,GAAA,CAAI,KAAA,CAAM,GAAG,CAAC,CAAC,EAAE,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA;AACjF;AAQA,eAAsB,WAAA,CAAY,KAAA,EAAe,GAAA,EAAa,IAAA,GAAO,IAAA,EAAuB;AAC1F,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,MAAM,KAAK,GAAA,EAAK,C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A;AAC1C,EAAA,OAAO,CAAA;AACT;AAaA,eAAsB,gBAAA,CACpB,KAAA,EACA,YAAA,EACA,GAAA,EACA,SAAS,oBAAA,EACgB;AACzB,EAAA,MAAM,CAAA,GAAI,MAAM,YAAA,CAAa,YAAA,CAAa,MAAM,IAAI,CAAA;AACpD,EAAA,OAAO;AAAA,IACL,IAAI,KAAA,CAAM,EAAA;AAAA,IACV,SAAS,MAAM,WAAA,CAAY,KAAA,CAAM,SAAA,EAAW,KAAK,SAAS,CAAA;AAAA,IAC1D,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,WAAA,EAAa,KAAA,CAAM,WAAA,CAAY,WAAA,EAAY;AAAA,IAC3C,WAAW,SAAA,CAAU,KAAA,CAAM,WAAA,EAAa,MAAM,EAAE,WAAA,EAAY;AAAA,IAC5D,aAAa,CAAA,CAAE;AAAA,GACjB;AACF;AASA,eAAsB,aAAA,CAAc,KAAA,EAAsB,GAAA,mBAAY,IAAI,MAAK,EAAoB;AACjG,EAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,WAAA,CAAY,GAAG,CAAA;AACvC,EAAA,IAAI,GAAA,CAAI,MAAA,EAAQ,MAAM,KAAA,CAAM,OAAO,GAAG,CAAA;AACtC,EAAA,OAAO,GAAA,CAAI,MAAA;AACb","file":"pseudonymise.js","sourcesContent":["// components F110.8 — pseudonymisation before a conversation enters the analysis copy.\n// The techniques and why are in docs/legal/pseudonymisation-standards.md (EDPB 01/2025,\n// ENISA 2019/2021, ISO/IEC 20889/27559, NIST SP 800-188). Pseudonymised data is STILL\n// personal data: this module never claims to anonymise, and everything it does not examine\n// is returned in `notExamined`, never passed silently as clean.\n//\n// Web Crypto only, so it runs in Node, Bun and edge runtimes alike.\n\nimport { findPersonalData } from \"@broberg/secret-scan\";\n\n/** The owner's ceiling for the analysis copy (31 Oct 2026). */\nexport const MAX_RETENTION_MONTHS = 6;\n\nexport interface PseudonymiseOptions {\n /**\n * The HMAC key of ONE pseudonymisation domain (e.g. \"product analysis\"). Keep it in the\n * Secrets Vault, never next to the analysis copy. Rotating it unlinks old pseudonyms from new.\n */\n key: string;\n /** Names the system already knows for this conversation (sender, case parties) — found and replaced. */\n knownNames?: string[];\n /**\n * Optional step that finds OTHER names in the text, e.g. an EU model through @broberg/ai-sdk.\n * Without it, names the system does not know are reported in `notExamined`.\n */\n findNames?: (text: string) => Promise<string[]>;\n /**\n * `\"remove\"` (default): sentences about health are removed before the copy (art. 9).\n * `\"consented\"`: only when the person has given EXPLICIT consent to analysis of their content.\n */\n health?: \"remove\" | \"consented\";\n}\n\nexport type NotExamined = \"names-not-known\" | \"health-beyond-keywords\" | \"addresses\" | \"indirect-identifiers\";\n\nexport interface PseudonymisedText {\n text: string;\n /** How many of each kind were replaced — never the values. */\n replaced: Record<\"cpr\" | \"email\" | \"phone\" | \"ip\" | \"name\" | \"health\", number>;\n /** What this step did NOT examine. A consumer must not call the result clean beyond these. */\n notExamined: NotExamined[];\n}\n\nconst enc = new TextEncoder();\n\nasync function hmac(key: string, message: string): Promise<string> {\n if (!key || key.length < 32) throw new Error(\"pseudonymisation key must be at least 32 characters — use a vault-held secret\");\n const k = await crypto.subtle.importKey(\"raw\", enc.encode(key), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const sig = new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, enc.encode(message)));\n return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A keyed pseudonym for a direct identifier (account id, e-mail, phone, IP). The same value\n * gives the same pseudonym under the same key; without the key it cannot be reversed or\n * guessed (a plain hash of an e-mail can be — ENISA/EDPB). `kind` keeps an e-mail and an\n * account id that happen to share a string from colliding.\n */\nexport async function pseudonymId(value: string, key: string, kind = \"id\"): Promise<string> {\n return `${kind}_${await hmac(key, `${kind}\\u0000${value.trim().toLowerCase()}`)}`;\n}\n\n// Danish health vocabulary — a keyword step, so what it misses is named in notExamined.\nconst HEALTH = /\\b(smert\\w*|ondt|diagnos\\w*|sygdom\\w*|syg|sygemeld\\w*|medicin\\w*|piller?|operation\\w*|opereret|skade[nrs]?|gigt|kræft|depression\\w*|angst\\w*|gravid\\w*|blodtryk\\w*|diabetes|sukkersyge|allergi\\w*|behandling\\w*|fysioterap\\w*|genoptræning\\w*|hovedpine|migræne|hospital\\w*|indlagt|læge[nr]?|symptom\\w*|astma|hjerte\\w*|psykolog\\w*|psykiat\\w*|stress\\w*)\\b/i;\nconst IPV4 = /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g;\nconst IPV6 = /\\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\\b/gi;\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * One conversation: names get the SAME marker throughout it («Mette Jensen» and later «Mette»\n * are both [PERSON-1]), and a new conversation starts counting again.\n */\nexport function createConversation(opts: PseudonymiseOptions) {\n const people = new Map<string, number>(); // lower-cased name part → person number\n\n function personOf(name: string): number {\n const parts = name.trim().split(/\\s+/).filter((p) => p.length >= 2);\n const full = parts.join(\" \").toLowerCase();\n // A full name matches only itself; a lone first name may match a person seen in full.\n // («Mette Hansen» and «Mette Jensen» stay two people.)\n const existing = people.get(full); // parts of names seen in full are stored too\n const n = existing ?? (people.size ? Math.max(...people.values()) + 1 : 1);\n people.set(full, n);\n for (const p of parts) if (p.length >= 3 && !people.has(p.toLowerCase())) people.set(p.toLowerCase(), n);\n return n;\n }\n\n return {\n async pseudonymise(input: string): Promise<PseudonymisedText> {\n const replaced = { cpr: 0, email: 0, phone: 0, ip: 0, name: 0, health: 0 };\n let text = input;\n\n // 1. Art. 9 first: a health sentence never reaches the copy, whatever else it holds.\n if ((opts.health ?? \"remove\") === \"remove\") {\n text = text\n .split(/(?<=[.!?])\\s+/)\n .map((s) => (HEALTH.test(s) ? (replaced.health++, \"[HELBRED FJERNET]\") : s))\n .join(\" \");\n }\n\n // 2. CPR removed, e-mail and phone pseudonymised (positions from @broberg/secret-scan).\n const hits = findPersonalData(text).sort((a, b) => b.start - a.start);\n for (const h of hits) {\n const value = text.slice(h.start, h.end);\n const marker = h.kind === \"cpr\" ? \"[CPR]\" : `[${h.kind.toUpperCase()}-${(await pseudonymId(value, opts.key, h.kind)).split(\"_\")[1]}]`;\n replaced[h.kind]++;\n text = text.slice(0, h.start) + marker + text.slice(h.end);\n }\n for (const re of [IPV4, IPV6]) {\n for (const m of [...text.matchAll(re)].reverse()) {\n replaced.ip++;\n text = text.slice(0, m.index!) + `[IP-${(await pseudonymId(m[0], opts.key, \"ip\")).split(\"_\")[1]}]` + text.slice(m.index! + m[0].length);\n }\n }\n\n // 3. Names: the ones the system knows, then (if given) the ones a model finds.\n const names = [...(opts.knownNames ?? []), ...(opts.findNames ? await opts.findNames(text) : [])].filter((n) => n.trim().length >= 2);\n for (const name of names) personOf(name);\n // Longest first, so «Mette Jensen» is replaced before «Mette».\n const forms = [...people.keys()].sort((a, b) => b.length - a.length);\n for (const form of forms) {\n const re = new RegExp(`(?<![\\\\p{L}\\\\d])${escape(form).replace(/ /g, \"\\\\s+\")}(s)?(?![\\\\p{L}\\\\d])`, \"giu\");\n text = text.replace(re, (_m, genitive?: string) => {\n replaced.name++;\n return `[PERSON-${people.get(form)}]${genitive ? \"s\" : \"\"}`;\n });\n }\n\n const notExamined: NotExamined[] = [\"addresses\", \"indirect-identifiers\"];\n if (!opts.findNames) notExamined.unshift(\"names-not-known\");\n if ((opts.health ?? \"remove\") === \"remove\") notExamined.push(\"health-beyond-keywords\");\n return { text, replaced, notExamined };\n },\n };\n}\n\n/** The date a record may be kept until — at most MAX_RETENTION_MONTHS after collection. */\nexport function keepUntil(collectedAt: Date, months = MAX_RETENTION_MONTHS): Date {\n if (!Number.isInteger(months) || months < 1 || months > MAX_RETENTION_MONTHS) {\n throw new Error(`retention must be 1–${MAX_RETENTION_MONTHS} months (owner's ceiling)`);\n }\n const d = new Date(collectedAt.getTime());\n const day = d.getUTCDate();\n d.setUTCMonth(d.getUTCMonth() + months);\n if (d.getUTCDate() !== day) d.setUTCDate(0); // 31 Aug + 6 → 28/29 Feb, never 3 Mar\n return d;\n}\n\n/** One record in the analysis copy. `subject` is a keyed pseudonym, never the account id. */\nexport interface AnalysisRecord {\n id: string;\n subject: string;\n text: string;\n collectedAt: string;\n keepUntil: string;\n notExamined: NotExamined[];\n}\n\n/** Build a record for the analysis copy: the subject pseudonymised, the text pseudonymised, the deadline set. */\nexport async function toAnalysisRecord(\n input: { id: string; subjectId: string; text: string; collectedAt: Date },\n conversation: ReturnType<typeof createConversation>,\n key: string,\n months = MAX_RETENTION_MONTHS,\n): Promise<AnalysisRecord> {\n const p = await conversation.pseudonymise(input.text);\n return {\n id: input.id,\n subject: await pseudonymId(input.subjectId, key, \"subject\"),\n text: p.text,\n collectedAt: input.collectedAt.toISOString(),\n keepUntil: keepUntil(input.collectedAt, months).toISOString(),\n notExamined: p.notExamined,\n };\n}\n\n/** The app owns the rows; the package owns the rule. */\nexport interface AnalysisStore {\n listExpired(now: Date): Promise<string[]>;\n delete(ids: string[]): Promise<void>;\n}\n\n/** Remove every record whose keepUntil has passed. Returns how many went. */\nexport async function deleteExpired(store: AnalysisStore, now: Date = new Date()): Promise<number> {\n const ids = await store.listExpired(now);\n if (ids.length) await store.delete(ids);\n return ids.length;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@broberg/legal",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "One set of legal documents for every broberg.ai product — terms, privacy, trust, DPA, support agreement — as structured, versioned, content-hashed data in Danish (master) and English. Sites style and re-flow; they never edit. Zero dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,13 +18,21 @@
18
18
  "import": "./dist/index.js",
19
19
  "require": "./dist/index.cjs"
20
20
  },
21
+ "./pseudonymise": {
22
+ "types": "./dist/pseudonymise.d.ts",
23
+ "import": "./dist/pseudonymise.js",
24
+ "require": "./dist/pseudonymise.cjs"
25
+ },
21
26
  "./package.json": "./package.json"
22
27
  },
23
28
  "scripts": {
24
29
  "build": "tsup",
25
- "test": "vitest run --reporter=default --reporter=json --outputFile.json=.vitest-report/results.json",
30
+ "test": "vitest run --reporter=default --reporter=json --outputFile.json=.vitest-report/results.json && node ../../scripts/mutations-if-changed.mjs test/mutations.mjs",
26
31
  "typecheck": "tsc --noEmit"
27
32
  },
33
+ "dependencies": {
34
+ "@broberg/secret-scan": ">=0.15.0 <1"
35
+ },
28
36
  "devDependencies": {
29
37
  "tsup": "^8.3.0",
30
38
  "typescript": "^5.6.0",