anonyma 1.1.0 → 1.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 +131 -2
- package/README.md +125 -7
- package/dist/ai/index.cjs +31 -20
- package/dist/ai/index.cjs.map +1 -1
- package/dist/ai/index.d.cts +5 -5
- package/dist/ai/index.d.ts +5 -5
- package/dist/ai/index.js +24 -13
- package/dist/ai/index.js.map +1 -1
- package/dist/audit/index.cjs +14 -14
- package/dist/audit/index.d.cts +2 -2
- package/dist/audit/index.d.ts +2 -2
- package/dist/audit/index.js +9 -9
- package/dist/{chunk-YMLR375Z.js → chunk-264R3VFP.js} +4 -3
- package/dist/chunk-264R3VFP.js.map +1 -0
- package/dist/{chunk-ISL5B4LU.cjs → chunk-32U3DM7M.cjs} +11 -11
- package/dist/{chunk-ISL5B4LU.cjs.map → chunk-32U3DM7M.cjs.map} +1 -1
- package/dist/{chunk-26IHMQHL.cjs → chunk-42ZZZUMO.cjs} +245 -85
- package/dist/chunk-42ZZZUMO.cjs.map +1 -0
- package/dist/chunk-4BYN6GVK.js +213 -0
- package/dist/chunk-4BYN6GVK.js.map +1 -0
- package/dist/{chunk-JKW36IPT.js → chunk-A2OMTO3L.js} +4 -4
- package/dist/{chunk-JKW36IPT.js.map → chunk-A2OMTO3L.js.map} +1 -1
- package/dist/{chunk-TW7PM3UJ.cjs → chunk-AITKBKQX.cjs} +2 -2
- package/dist/{chunk-TW7PM3UJ.cjs.map → chunk-AITKBKQX.cjs.map} +1 -1
- package/dist/{chunk-G4AN7FND.js → chunk-BWE4O2ES.js} +23 -9
- package/dist/chunk-BWE4O2ES.js.map +1 -0
- package/dist/{chunk-GS3FRH4K.js → chunk-CMJXIEBA.js} +2 -2
- package/dist/chunk-CMJXIEBA.js.map +1 -0
- package/dist/{chunk-GYMG5OI3.cjs → chunk-ESVFPMG4.cjs} +2 -2
- package/dist/{chunk-GYMG5OI3.cjs.map → chunk-ESVFPMG4.cjs.map} +1 -1
- package/dist/{chunk-2YG7R4KJ.cjs → chunk-EUNLKSYP.cjs} +5 -5
- package/dist/{chunk-2YG7R4KJ.cjs.map → chunk-EUNLKSYP.cjs.map} +1 -1
- package/dist/{chunk-S7NH6CHY.cjs → chunk-F3BYJFUM.cjs} +5 -3
- package/dist/chunk-F3BYJFUM.cjs.map +1 -0
- package/dist/{chunk-IJAMLYOT.cjs → chunk-HDHQXVUM.cjs} +50 -36
- package/dist/chunk-HDHQXVUM.cjs.map +1 -0
- package/dist/{chunk-OGNLB2KA.js → chunk-HFAIBE3T.js} +3 -3
- package/dist/{chunk-OGNLB2KA.js.map → chunk-HFAIBE3T.js.map} +1 -1
- package/dist/{chunk-PKHZ7CVI.js → chunk-IBDFBUFZ.js} +2 -2
- package/dist/chunk-IBDFBUFZ.js.map +1 -0
- package/dist/{chunk-3CY6ATKS.cjs → chunk-JBH2EFFF.cjs} +36 -36
- package/dist/{chunk-3CY6ATKS.cjs.map → chunk-JBH2EFFF.cjs.map} +1 -1
- package/dist/chunk-JPU7KQZX.cjs +82 -0
- package/dist/{chunk-CRXRJZEV.cjs.map → chunk-JPU7KQZX.cjs.map} +1 -1
- package/dist/{chunk-E3PICZYI.js → chunk-KHT23UVV.js} +3 -3
- package/dist/{chunk-E3PICZYI.js.map → chunk-KHT23UVV.js.map} +1 -1
- package/dist/{chunk-2ZZHLCEJ.js → chunk-LAZIR73I.js} +18 -87
- package/dist/chunk-LAZIR73I.js.map +1 -0
- package/dist/{chunk-FB56NAAH.cjs → chunk-NO4ZCIM6.cjs} +19 -92
- package/dist/chunk-NO4ZCIM6.cjs.map +1 -0
- package/dist/{chunk-S4BJ2ADB.cjs → chunk-PCU6AG7H.cjs} +4 -4
- package/dist/{chunk-S4BJ2ADB.cjs.map → chunk-PCU6AG7H.cjs.map} +1 -1
- package/dist/{chunk-W6RBCHYF.js → chunk-PSZHBY5V.js} +235 -75
- package/dist/chunk-PSZHBY5V.js.map +1 -0
- package/dist/{chunk-6LDAIJBL.js → chunk-QBBJR7DZ.js} +2 -2
- package/dist/{chunk-6LDAIJBL.js.map → chunk-QBBJR7DZ.js.map} +1 -1
- package/dist/{chunk-3D5ZCJ7R.js → chunk-QHQ2AU45.js} +3 -3
- package/dist/{chunk-3D5ZCJ7R.js.map → chunk-QHQ2AU45.js.map} +1 -1
- package/dist/{chunk-IHEIYZPL.cjs → chunk-RJX27YEX.cjs} +2 -2
- package/dist/chunk-RJX27YEX.cjs.map +1 -0
- package/dist/{chunk-QYD4F6T7.cjs → chunk-ROXNQKOA.cjs} +2 -2
- package/dist/{chunk-QYD4F6T7.cjs.map → chunk-ROXNQKOA.cjs.map} +1 -1
- package/dist/chunk-SHEXFU6T.js +107 -0
- package/dist/chunk-SHEXFU6T.js.map +1 -0
- package/dist/chunk-T2KIN6VL.cjs +218 -0
- package/dist/chunk-T2KIN6VL.cjs.map +1 -0
- package/dist/{chunk-RCW5IPPR.js → chunk-UCT6HDUD.js} +3 -3
- package/dist/{chunk-RCW5IPPR.js.map → chunk-UCT6HDUD.js.map} +1 -1
- package/dist/chunk-UN74SYHV.cjs +115 -0
- package/dist/chunk-UN74SYHV.cjs.map +1 -0
- package/dist/{chunk-F7O2FA3F.cjs → chunk-VAO3Y3HZ.cjs} +7 -6
- package/dist/chunk-VAO3Y3HZ.cjs.map +1 -0
- package/dist/{chunk-BBJPQPGP.js → chunk-VE3OSDM7.js} +5 -3
- package/dist/chunk-VE3OSDM7.js.map +1 -0
- package/dist/{chunk-7HK2V5Q4.js → chunk-X7IVXKDE.js} +3 -3
- package/dist/{chunk-7HK2V5Q4.js.map → chunk-X7IVXKDE.js.map} +1 -1
- package/dist/{chunk-UA3EOFBS.cjs → chunk-XVCVIUZS.cjs} +8 -8
- package/dist/{chunk-UA3EOFBS.cjs.map → chunk-XVCVIUZS.cjs.map} +1 -1
- package/dist/{chunk-SIHPDZXA.js → chunk-YSTC7WRF.js} +2 -2
- package/dist/{chunk-SIHPDZXA.js.map → chunk-YSTC7WRF.js.map} +1 -1
- package/dist/compliance/index.cjs +15 -15
- package/dist/compliance/index.d.cts +4 -4
- package/dist/compliance/index.d.ts +4 -4
- package/dist/compliance/index.js +5 -5
- package/dist/crypto.cjs +4 -4
- package/dist/crypto.d.cts +1 -1
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +2 -2
- package/dist/detectors/index.cjs +38 -38
- package/dist/detectors/index.d.cts +1 -1
- package/dist/detectors/index.d.ts +1 -1
- package/dist/detectors/index.js +3 -3
- package/dist/engine/index.cjs +70 -70
- package/dist/engine/index.d.cts +3 -3
- package/dist/engine/index.d.ts +3 -3
- package/dist/engine/index.js +8 -8
- package/dist/hash-P2VGKVFP.cjs +14 -0
- package/dist/{hash-2PSYNDMM.cjs.map → hash-P2VGKVFP.cjs.map} +1 -1
- package/dist/hash-T6YJG3DU.js +5 -0
- package/dist/{hash-CELLDNKN.js.map → hash-T6YJG3DU.js.map} +1 -1
- package/dist/index.cjs +44 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -5
- package/dist/index.d.ts +23 -5
- package/dist/index.js +11 -9
- package/dist/index.js.map +1 -1
- package/dist/{json-s8ny-RCo.d.cts → json-BXN577tt.d.cts} +3 -2
- package/dist/{json-CKDvlRtl.d.ts → json-BudrzkOQ.d.ts} +3 -2
- package/dist/mcp/index.cjs +29 -28
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.js +14 -13
- package/dist/mcp/index.js.map +1 -1
- package/dist/middleware/express.cjs +11 -11
- package/dist/middleware/express.d.cts +3 -3
- package/dist/middleware/express.d.ts +3 -3
- package/dist/middleware/express.js +10 -10
- package/dist/middleware/hono.cjs +11 -11
- package/dist/middleware/hono.d.cts +3 -3
- package/dist/middleware/hono.d.ts +3 -3
- package/dist/middleware/hono.js +10 -10
- package/dist/middleware/index.cjs +11 -11
- package/dist/middleware/index.d.cts +3 -3
- package/dist/middleware/index.d.ts +3 -3
- package/dist/middleware/index.js +10 -10
- package/dist/schemas.cjs +47 -47
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +2 -2
- package/dist/schemas.d.ts +2 -2
- package/dist/schemas.js +2 -2
- package/dist/schemas.js.map +1 -1
- package/dist/{session-BdRftyZ5.d.cts → session-CPXEQ2uC.d.cts} +18 -5
- package/dist/{session-Cs2zlNQp.d.ts → session-D3WMN6fE.d.ts} +18 -5
- package/dist/stream.cjs +10 -8
- package/dist/stream.cjs.map +1 -1
- package/dist/stream.d.cts +1 -1
- package/dist/stream.d.ts +1 -1
- package/dist/stream.js +7 -5
- package/dist/stream.js.map +1 -1
- package/dist/{types-Dtht33aq.d.ts → types-B3VjDuP8.d.cts} +2 -282
- package/dist/{types--tPm_AjY.d.ts → types-DHAVKfzT.d.ts} +2 -2
- package/dist/types-LZHFEgx5.d.cts +1083 -0
- package/dist/types-LZHFEgx5.d.ts +1083 -0
- package/dist/{types-0BJH_wqc.d.cts → types-vmONSbz4.d.cts} +2 -2
- package/dist/{types-CPUhjvl8.d.cts → types-yZHnS7yv.d.ts} +2 -282
- package/dist/validators.cjs +10 -10
- package/dist/validators.js +1 -1
- package/dist/vault/index.cjs +65 -46
- package/dist/vault/index.cjs.map +1 -1
- package/dist/vault/index.d.cts +98 -5
- package/dist/vault/index.d.ts +98 -5
- package/dist/vault/index.js +11 -5
- package/dist/vault/index.js.map +1 -1
- package/package.json +16 -7
- package/dist/chunk-26IHMQHL.cjs.map +0 -1
- package/dist/chunk-2ZZHLCEJ.js.map +0 -1
- package/dist/chunk-BBJPQPGP.js.map +0 -1
- package/dist/chunk-CRXRJZEV.cjs +0 -82
- package/dist/chunk-F7O2FA3F.cjs.map +0 -1
- package/dist/chunk-FB56NAAH.cjs.map +0 -1
- package/dist/chunk-G4AN7FND.js.map +0 -1
- package/dist/chunk-GS3FRH4K.js.map +0 -1
- package/dist/chunk-IHEIYZPL.cjs.map +0 -1
- package/dist/chunk-IJAMLYOT.cjs.map +0 -1
- package/dist/chunk-PKHZ7CVI.js.map +0 -1
- package/dist/chunk-S7NH6CHY.cjs.map +0 -1
- package/dist/chunk-W6RBCHYF.js.map +0 -1
- package/dist/chunk-YMLR375Z.js.map +0 -1
- package/dist/hash-2PSYNDMM.cjs +0 -14
- package/dist/hash-CELLDNKN.js +0 -5
- package/dist/types-EJTj_BKY.d.cts +0 -584
- package/dist/types-EJTj_BKY.d.ts +0 -584
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/compliance/regulations.ts","../src/compliance/traits.ts","../src/compliance/policy.ts"],"names":["REDACT"],"mappings":";;;;AAsBA,SAAS,GAAA,CAAI,QAAA,EAAkB,OAAA,EAAiB,GAAA,EAA6B;AAC3E,EAAA,OAAO,OAAO,MAAA,CAAO,EAAE,QAAA,EAAU,OAAA,EAAS,KAAK,CAAA;AACjD;AAEA,SAAS,KAAA,CACP,UAAA,EACA,UAAA,EACA,WAAA,EACA,aACA,SAAA,EACgB;AAChB,EAAA,OAAO,UAAA,CAAW,GAAA;AAAA,IAAI,CAAC,QAAA,KACrB,MAAA,CAAO,MAAA,CAAO;AAAA,MACZ,QAAA;AAAA,MACA,UAAA;AAAA,MACA,WAAA,EAAa,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA;AAAA,MACtC,WAAA;AAAA,MACA;AAAA,KACD;AAAA,GACH;AACF;AAEA,IAAM,SAAuB,MAAA,CAAO,MAAA,CAAO,EAAE,QAAA,EAAU,UAAU,CAAA;AAMjE,IAAM,QAAA,GAAW,+CAAA;AACjB,IAAM,kBAAA,GAAqB,GAAA;AAAA,EACzB,gBAAA;AAAA,EACA,gLAAA;AAAA,EACA;AACF,CAAA;AACA,IAAM,qBAAA,GAAwB,GAAA;AAAA,EAC5B,gBAAA;AAAA,EACA,gJAAA;AAAA,EACA;AACF,CAAA;AACA,IAAM,gBAAA,GAAmB,GAAA;AAAA,EACvB,cAAA;AAAA,EACA,4FAAA;AAAA,EACA;AACF,CAAA;AACA,IAAM,YAAA,GAAe,GAAA;AAAA,EACn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B,MAAA,GAAY,EAAE,aAAA,EAAe,QAAA,CAAS,aAAA,EAAc,GAAI,EAAC;AAAA,IACxF,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,QAAA,CAAS,KAAA,EAAM,GAAI,EAAC;AAAA,IAChE,GAAI,SAAS,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,EAAY,QAAA,CAAS,UAAA,EAAW,GAAI,EAAC;AAAA,IAC/E,GAAI,SAAS,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,QAAA,CAAS,OAAA,EAAQ,GAAI;AAAC,GACxE;AACF;AAeO,SAAS,iBAAiB,UAAA,EAA0C;AACzE,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,CAAA;AAAA,IACT,EAAA,EAAI,UAAA;AAAA,IACJ,WAAA,EAAa,WAAA,CAAY,UAAU,CAAA,CAAE,IAAA;AAAA,IACrC,OAAA,EAAS,CAAC,UAAU;AAAA,GACtB;AACF","file":"chunk-264R3VFP.js","sourcesContent":["/**\n * @module compliance/regulations\n * @description Regulation profiles: which categories of data each instrument\n * brings into scope, under which provision, and what protection the\n * transformed value must have.\n *\n * The profiles describe technical measures. They are not legal advice, and a\n * profile cannot make a system compliant on its own: every profile lists the\n * data elements its instrument names that this library cannot detect.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { StrategySpec } from \"../engine/types.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport type {\n CategoryRule,\n LegalReference,\n ProtectionRequirement,\n RegulationId,\n RegulationProfile,\n} from \"./types.js\";\n\nfunction ref(citation: string, summary: string, url: string): LegalReference {\n return Object.freeze({ citation, summary, url });\n}\n\nfunction rules(\n categories: readonly PiiCategory[],\n references: readonly LegalReference[],\n requirement: ProtectionRequirement,\n recommended: StrategySpec,\n rationale: string,\n): CategoryRule[] {\n return categories.map((category) =>\n Object.freeze({\n category,\n references,\n requirement: Object.freeze(requirement),\n recommended,\n rationale,\n }),\n );\n}\n\nconst REDACT: StrategySpec = Object.freeze({ strategy: \"redact\" });\n\n// ---------------------------------------------------------------------------\n// GDPR\n// ---------------------------------------------------------------------------\n\nconst GDPR_URL = \"https://eur-lex.europa.eu/eli/reg/2016/679/oj\";\nconst GDPR_PERSONAL_DATA = ref(\n \"GDPR Art. 4(1)\",\n \"Personal data is any information relating to an identified or identifiable natural person, including a name, an identification number, location data and an online identifier.\",\n GDPR_URL,\n);\nconst GDPR_PSEUDONYMISATION = ref(\n \"GDPR Art. 4(5)\",\n \"Pseudonymisation: the data can no longer be attributed to a data subject without additional information that is kept separately and protected.\",\n GDPR_URL,\n);\nconst GDPR_NATIONAL_ID = ref(\n \"GDPR Art. 87\",\n \"Member States may set specific conditions for processing a national identification number.\",\n GDPR_URL,\n);\nconst GDPR_SPECIAL = ref(\n \"GDPR Art. 9(1)\",\n \"Processing of special categories of personal data, including data concerning health, is prohibited unless an exception applies.\",\n GDPR_URL,\n);\nconst GDPR_ONLINE = ref(\n \"GDPR Recital 30\",\n \"Online identifiers such as IP addresses and cookie identifiers may be used to identify natural persons.\",\n GDPR_URL,\n);\n/** When an output is computed from the value, a separately kept secret must be involved. */\nconst KEYED_IF_DERIVED: ProtectionRequirement = { keyed: true };\nconst GDPR_DEFAULT: StrategySpec = Object.freeze({ strategy: \"pseudonymize\" });\nconst GDPR_RATIONALE =\n \"A replacement that is computed from the value without a secret can be recomputed by anyone, so the data stays attributable and is not pseudonymised in the sense of Art. 4(5).\";\n\nconst GDPR: RegulationProfile = {\n id: \"gdpr\",\n name: \"General Data Protection Regulation\",\n jurisdiction: \"European Union / EEA\",\n edition: \"Regulation (EU) 2016/679\",\n references: [\n ref(\n \"GDPR Art. 5(1)(c)\",\n \"Data minimisation: adequate, relevant and limited to what is necessary.\",\n GDPR_URL,\n ),\n ref(\n \"GDPR Art. 5(1)(e)\",\n \"Storage limitation: identifiable form for no longer than necessary.\",\n GDPR_URL,\n ),\n ref(\n \"GDPR Art. 25(1)\",\n \"Data protection by design and by default, such as pseudonymisation.\",\n GDPR_URL,\n ),\n ref(\n \"GDPR Art. 32(1)(a)\",\n \"Security of processing includes the pseudonymisation and encryption of personal data.\",\n GDPR_URL,\n ),\n ref(\n \"GDPR Recital 26\",\n \"The principles of data protection do not apply to anonymous information.\",\n GDPR_URL,\n ),\n GDPR_PSEUDONYMISATION,\n ],\n rules: [\n ...rules(\n [\"name\", \"email\", \"phone\", \"address\", \"date-of-birth\"],\n [GDPR_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n GDPR_DEFAULT,\n GDPR_RATIONALE,\n ),\n ...rules(\n [\"national-id\", \"ssn\", \"passport\", \"drivers-license\", \"tax-id\"],\n [GDPR_PERSONAL_DATA, GDPR_NATIONAL_ID],\n KEYED_IF_DERIVED,\n GDPR_DEFAULT,\n GDPR_RATIONALE,\n ),\n ...rules(\n [\"iban\", \"bank-account\", \"credit-card\", \"cryptocurrency\"],\n [GDPR_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n GDPR_DEFAULT,\n GDPR_RATIONALE,\n ),\n ...rules(\n [\"ipv4\", \"ipv6\", \"url\", \"social-media\"],\n [GDPR_PERSONAL_DATA, GDPR_ONLINE],\n KEYED_IF_DERIVED,\n GDPR_DEFAULT,\n GDPR_RATIONALE,\n ),\n ...rules(\n [\"medical-record\", \"health-insurance\", \"prescription\"],\n [GDPR_SPECIAL, GDPR_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n GDPR_DEFAULT,\n \"Identifiers of health records lead to data concerning health, a special category.\",\n ),\n ],\n gaps: [\n {\n element: \"Location data (coordinates, postal codes, city names)\",\n reference: GDPR_PERSONAL_DATA,\n mitigation:\n \"Add custom patterns for the formats in your data, or drop the fields that carry location.\",\n },\n {\n element: \"Device, advertising and cookie identifiers\",\n reference: GDPR_ONLINE,\n mitigation: \"Add custom patterns for the identifiers your systems emit.\",\n },\n {\n element:\n \"Special categories expressed in free text (health conditions, beliefs, union membership)\",\n reference: GDPR_SPECIAL,\n mitigation:\n \"Pattern matching cannot find these. Redact the fields that may contain them, by key.\",\n },\n {\n element: \"Names that are not introduced by a title, greeting or label\",\n reference: GDPR_PERSONAL_DATA,\n mitigation: \"Redact name fields by key; the name detector is a heuristic.\",\n },\n ],\n auditTrail: ref(\n \"GDPR Art. 30\",\n \"Controllers and processors maintain records of processing activities.\",\n GDPR_URL,\n ),\n erasure: ref(\"GDPR Art. 17\", \"Right to erasure ('right to be forgotten').\", GDPR_URL),\n};\n\n// ---------------------------------------------------------------------------\n// LGPD\n// ---------------------------------------------------------------------------\n\nconst LGPD_URL = \"https://www.planalto.gov.br/ccivil_03/_ato2015-2018/2018/lei/l13709.htm\";\nconst LGPD_PERSONAL_DATA = ref(\n \"LGPD Art. 5, I\",\n \"Dado pessoal: information relating to an identified or identifiable natural person.\",\n LGPD_URL,\n);\nconst LGPD_SENSITIVE = ref(\n \"LGPD Art. 5, II\",\n \"Dado pessoal sensível includes data concerning health, and genetic or biometric data linked to a natural person.\",\n LGPD_URL,\n);\nconst LGPD_RATIONALE =\n \"Data is anonymised only if it can no longer be associated with an individual by reasonable technical means (Art. 5, XI and Art. 12); a keyless transformation of the value can be reversed.\";\n\nconst LGPD: RegulationProfile = {\n id: \"lgpd\",\n name: \"Lei Geral de Proteção de Dados Pessoais\",\n jurisdiction: \"Brazil\",\n edition: \"Lei nº 13.709/2018, as amended\",\n references: [\n ref(\n \"LGPD Art. 5, III\",\n \"Dado anonimizado: data whose subject cannot be identified by reasonable technical means.\",\n LGPD_URL,\n ),\n ref(\n \"LGPD Art. 5, XI\",\n \"Anonimização: means by which data loses the possibility of association with an individual.\",\n LGPD_URL,\n ),\n ref(\n \"LGPD Art. 6, III\",\n \"Necessidade: processing limited to the minimum necessary for its purposes.\",\n LGPD_URL,\n ),\n ref(\n \"LGPD Art. 12\",\n \"Anonymised data is not personal data unless the process can be reversed with reasonable effort.\",\n LGPD_URL,\n ),\n ref(\n \"LGPD Art. 13, § 4º\",\n \"Pseudonimização: association is only possible with additional information kept separately by the controller.\",\n LGPD_URL,\n ),\n ref(\n \"LGPD Art. 46\",\n \"Processing agents adopt technical and administrative security measures to protect personal data.\",\n LGPD_URL,\n ),\n ],\n rules: [\n ...rules(\n [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"tax-id\",\n \"passport\",\n \"drivers-license\",\n ],\n [LGPD_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n REDACT,\n LGPD_RATIONALE,\n ),\n ...rules(\n [\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"cryptocurrency\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"license-plate\",\n ],\n [LGPD_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n REDACT,\n LGPD_RATIONALE,\n ),\n ...rules(\n [\"medical-record\", \"health-insurance\", \"prescription\"],\n [LGPD_SENSITIVE, LGPD_PERSONAL_DATA],\n KEYED_IF_DERIVED,\n REDACT,\n \"Identifiers of health records lead to dado pessoal sensível.\",\n ),\n ],\n gaps: [\n {\n element:\n \"CPF without punctuation, CNPJ, RG, CNH, título de eleitor, PIS/PASEP and Cartão Nacional de Saúde numbers\",\n reference: LGPD_PERSONAL_DATA,\n mitigation:\n \"Only the punctuated CPF format is detected. Add custom patterns with the checksum validators for the others.\",\n },\n {\n element:\n \"Brazilian phone numbers in national format, CEP postal codes and addresses written in Portuguese\",\n reference: LGPD_PERSONAL_DATA,\n mitigation: \"Add custom patterns, or redact the fields that carry them by key.\",\n },\n {\n element:\n \"Sensitive data in free text (health, religion, political opinion, union membership)\",\n reference: LGPD_SENSITIVE,\n mitigation:\n \"Pattern matching cannot find these. Redact the fields that may contain them, by key.\",\n },\n ],\n auditTrail: ref(\n \"LGPD Art. 37\",\n \"Controller and operator keep a record of the processing operations they carry out.\",\n LGPD_URL,\n ),\n erasure: ref(\n \"LGPD Art. 18, IV and VI\",\n \"The data subject may obtain anonymisation, blocking or deletion of unnecessary or excessive data, and deletion of data processed with consent.\",\n LGPD_URL,\n ),\n};\n\n// ---------------------------------------------------------------------------\n// PIPEDA\n// ---------------------------------------------------------------------------\n\nconst PIPEDA_URL = \"https://laws-lois.justice.gc.ca/eng/acts/P-8.6/\";\nconst PIPEDA_PERSONAL = ref(\n \"PIPEDA s. 2(1)\",\n \"Personal information means information about an identifiable individual.\",\n PIPEDA_URL,\n);\nconst PIPEDA_SAFEGUARDS = ref(\n \"PIPEDA Schedule 1, cl. 4.7\",\n \"Personal information is protected by security safeguards appropriate to its sensitivity; technological measures include passwords and encryption (cl. 4.7.3).\",\n PIPEDA_URL,\n);\n\nconst PIPEDA: RegulationProfile = {\n id: \"pipeda\",\n name: \"Personal Information Protection and Electronic Documents Act\",\n jurisdiction: \"Canada (federal, private sector)\",\n edition: \"S.C. 2000, c. 5, as amended\",\n references: [\n ref(\n \"PIPEDA Schedule 1, cl. 4.4\",\n \"Limiting collection to what is necessary for the identified purposes.\",\n PIPEDA_URL,\n ),\n PIPEDA_SAFEGUARDS,\n ref(\n \"PIPEDA s. 10.1\",\n \"Breaches of security safeguards that create a real risk of significant harm are reported and notified.\",\n PIPEDA_URL,\n ),\n ],\n rules: [\n ...rules(\n [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"ssn\",\n \"passport\",\n \"drivers-license\",\n \"tax-id\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"social-media\",\n ],\n [PIPEDA_PERSONAL, PIPEDA_SAFEGUARDS],\n {},\n REDACT,\n \"The Act prescribes no transformation; the safeguard has to match the sensitivity of the information.\",\n ),\n ...rules(\n [\"medical-record\", \"health-insurance\", \"prescription\"],\n [PIPEDA_PERSONAL, PIPEDA_SAFEGUARDS],\n KEYED_IF_DERIVED,\n REDACT,\n \"Health information is sensitive, so a replacement that anyone can recompute from the value is not an appropriate safeguard.\",\n ),\n ],\n gaps: [\n {\n element:\n \"Provincial health card numbers, postal codes, and bank transit and institution numbers\",\n reference: PIPEDA_PERSONAL,\n mitigation: \"Add custom patterns. The Social Insurance Number is detected as national-id.\",\n },\n {\n element: \"Names and addresses written in French\",\n reference: PIPEDA_PERSONAL,\n mitigation:\n \"Redact name and address fields by key; the detectors are tuned to English forms.\",\n },\n ],\n auditTrail: ref(\n \"PIPEDA s. 10.3\",\n \"Organizations keep a record of every breach of security safeguards.\",\n PIPEDA_URL,\n ),\n erasure: ref(\n \"PIPEDA Schedule 1, cl. 4.5.3\",\n \"Personal information that is no longer required should be destroyed, erased or made anonymous. This is a retention principle, not an individual right to erasure.\",\n PIPEDA_URL,\n ),\n};\n\n// ---------------------------------------------------------------------------\n// CCPA / CPRA\n// ---------------------------------------------------------------------------\n\nconst CCPA_URL =\n \"https://leginfo.legislature.ca.gov/faces/codes_displaySection.xhtml?lawCode=CIV§ionNum=1798.140\";\nconst CCPA_IDENTIFIERS = ref(\n \"Cal. Civ. Code § 1798.140(v)(1)(A)\",\n \"Personal information includes identifiers such as a real name, postal address, online identifier, IP address, email address, social security number, driver's license number and passport number.\",\n CCPA_URL,\n);\nconst CCPA_RECORDS = ref(\n \"Cal. Civ. Code § 1798.140(v)(1)(B)\",\n \"Personal information includes the categories of § 1798.80(e): telephone number, bank account and card numbers, medical information and health insurance information, among others.\",\n CCPA_URL,\n);\nconst CCPA_SENSITIVE = ref(\n \"Cal. Civ. Code § 1798.140(ae)\",\n \"Sensitive personal information includes social security, driver's license, state identification card and passport numbers; account log-in and financial account or card numbers with their credentials; and health information.\",\n CCPA_URL,\n);\nconst CCPA_SENSITIVE_RATIONALE =\n \"Pseudonymized information must not be attributable without separately kept information (§ 1798.140(aa)); a keyless transformation of sensitive personal information does not meet that.\";\n\nconst CCPA: RegulationProfile = {\n id: \"ccpa\",\n name: \"California Consumer Privacy Act, as amended by the California Privacy Rights Act\",\n jurisdiction: \"California, United States\",\n edition: \"Cal. Civ. Code §§ 1798.100–1798.199.100\",\n references: [\n ref(\n \"Cal. Civ. Code § 1798.100(e)\",\n \"A business implements reasonable security procedures and practices appropriate to the nature of the personal information.\",\n CCPA_URL,\n ),\n ref(\n \"Cal. Civ. Code § 1798.121\",\n \"A consumer may direct a business to limit its use of sensitive personal information.\",\n CCPA_URL,\n ),\n ref(\n \"Cal. Civ. Code § 1798.140(m)\",\n \"Deidentified information cannot reasonably be used to infer information about, or be linked to, a particular consumer.\",\n CCPA_URL,\n ),\n ref(\n \"Cal. Civ. Code § 1798.140(aa)\",\n \"Pseudonymization renders personal information no longer attributable without additional information that is kept separately.\",\n CCPA_URL,\n ),\n ref(\n \"Cal. Civ. Code § 1798.150\",\n \"Private right of action after a breach of nonencrypted and nonredacted personal information.\",\n CCPA_URL,\n ),\n ],\n rules: [\n ...rules(\n [\"name\", \"email\", \"address\", \"ipv4\", \"ipv6\", \"url\", \"social-media\"],\n [CCPA_IDENTIFIERS],\n {},\n REDACT,\n \"Redaction removes the identifier; the statute prescribes no particular transformation for non-sensitive identifiers.\",\n ),\n ...rules(\n [\"phone\", \"date-of-birth\", \"tax-id\"],\n [CCPA_RECORDS],\n {},\n REDACT,\n \"Covered through § 1798.80(e) or as information linkable to a consumer.\",\n ),\n ...rules(\n [\"ssn\", \"national-id\", \"passport\", \"drivers-license\"],\n [CCPA_SENSITIVE, CCPA_IDENTIFIERS],\n KEYED_IF_DERIVED,\n REDACT,\n CCPA_SENSITIVE_RATIONALE,\n ),\n ...rules(\n [\"bank-account\", \"credit-card\", \"api-key\"],\n [CCPA_SENSITIVE, CCPA_RECORDS],\n KEYED_IF_DERIVED,\n REDACT,\n CCPA_SENSITIVE_RATIONALE,\n ),\n ...rules(\n [\"medical-record\", \"health-insurance\"],\n [CCPA_SENSITIVE, CCPA_RECORDS],\n KEYED_IF_DERIVED,\n REDACT,\n CCPA_SENSITIVE_RATIONALE,\n ),\n ],\n gaps: [\n {\n element: \"Precise geolocation\",\n reference: ref(\n \"Cal. Civ. Code § 1798.140(w)\",\n \"Precise geolocation locates a consumer within a small geographic area.\",\n CCPA_URL,\n ),\n mitigation: \"Add custom patterns for coordinates, or drop the fields that carry them.\",\n },\n {\n element: \"Passwords, security codes and other account credentials\",\n reference: CCPA_SENSITIVE,\n mitigation: \"Redact credential fields by key. Only API-key shaped secrets are detected.\",\n },\n {\n element: \"Device, cookie and advertising identifiers\",\n reference: ref(\n \"Cal. Civ. Code § 1798.140(aj)\",\n \"A unique identifier is a persistent identifier that can recognise a consumer or a device over time.\",\n CCPA_URL,\n ),\n mitigation: \"Add custom patterns for the identifiers your systems emit.\",\n },\n {\n element: \"Biometric information, and inferences drawn about a consumer\",\n reference: ref(\n \"Cal. Civ. Code § 1798.140(c)\",\n \"Biometric information: physiological, biological or behavioural characteristics.\",\n CCPA_URL,\n ),\n mitigation:\n \"Pattern matching cannot find these. Redact the fields that may contain them, by key.\",\n },\n ],\n erasure: ref(\n \"Cal. Civ. Code § 1798.105\",\n \"A consumer may request deletion of personal information the business collected from the consumer.\",\n CCPA_URL,\n ),\n};\n\n// ---------------------------------------------------------------------------\n// HIPAA\n// ---------------------------------------------------------------------------\n\nconst HIPAA_URL = \"https://www.ecfr.gov/current/title-45/section-164.514\";\nconst safeHarbor = (letter: string, summary: string): LegalReference =>\n ref(`45 CFR § 164.514(b)(2)(i)(${letter})`, summary, HIPAA_URL);\nconst HIPAA_REIDENTIFICATION = ref(\n \"45 CFR § 164.514(c)\",\n \"A re-identification code must not be derived from or related to information about the individual, and the mechanism must not be disclosed.\",\n HIPAA_URL,\n);\n/** Safe Harbor removes the identifier; a replacement code may not be derived from it. */\nconst REMOVED: ProtectionRequirement = {\n notDerived: true,\n maxRevealed: { leading: 0, trailing: 0 },\n};\nconst HIPAA_RATIONALE =\n \"Safe Harbor requires the identifier to be removed. A hash, keyed hash, ciphertext or partial mask of it is derived from information about the individual, which § 164.514(c) forbids for re-identification codes.\";\nconst hipaa = (\n categories: readonly PiiCategory[],\n letter: string,\n summary: string,\n): CategoryRule[] =>\n rules(\n categories,\n [safeHarbor(letter, summary), HIPAA_REIDENTIFICATION],\n REMOVED,\n REDACT,\n HIPAA_RATIONALE,\n );\n\nconst HIPAA: RegulationProfile = {\n id: \"hipaa\",\n name: \"HIPAA Privacy Rule — de-identification by Safe Harbor\",\n jurisdiction: \"United States\",\n edition: \"45 CFR Part 164, Subpart E\",\n references: [\n ref(\n \"45 CFR § 164.514(a)\",\n \"Health information that does not identify an individual is not individually identifiable health information.\",\n HIPAA_URL,\n ),\n ref(\n \"45 CFR § 164.514(b)(1)\",\n \"Expert Determination: the alternative to Safe Harbor.\",\n HIPAA_URL,\n ),\n ref(\n \"45 CFR § 164.514(b)(2)(ii)\",\n \"The covered entity has no actual knowledge that the remaining information could identify the individual.\",\n HIPAA_URL,\n ),\n HIPAA_REIDENTIFICATION,\n ],\n rules: [\n ...hipaa([\"name\"], \"A\", \"Names.\"),\n ...hipaa(\n [\"address\"],\n \"B\",\n \"All geographic subdivisions smaller than a State, including street address.\",\n ),\n ...hipaa(\n [\"date-of-birth\"],\n \"C\",\n \"All elements of dates (except year) directly related to an individual, including birth date.\",\n ),\n ...hipaa([\"phone\"], \"D\", \"Telephone numbers (and, under (E), fax numbers).\"),\n ...hipaa([\"email\"], \"F\", \"Electronic mail addresses.\"),\n ...hipaa([\"ssn\"], \"G\", \"Social security numbers.\"),\n ...hipaa([\"medical-record\"], \"H\", \"Medical record numbers.\"),\n ...hipaa([\"health-insurance\"], \"I\", \"Health plan beneficiary numbers.\"),\n ...hipaa([\"bank-account\", \"credit-card\", \"iban\"], \"J\", \"Account numbers.\"),\n ...hipaa([\"drivers-license\", \"passport\", \"prescription\"], \"K\", \"Certificate/license numbers.\"),\n ...hipaa(\n [\"vin\", \"license-plate\"],\n \"L\",\n \"Vehicle identifiers and serial numbers, including license plate numbers.\",\n ),\n ...hipaa([\"url\"], \"N\", \"Web Universal Resource Locators (URLs).\"),\n ...hipaa([\"ipv4\", \"ipv6\"], \"O\", \"Internet Protocol (IP) address numbers.\"),\n ...hipaa(\n [\"national-id\", \"tax-id\", \"social-media\"],\n \"R\",\n \"Any other unique identifying number, characteristic, or code.\",\n ),\n ],\n gaps: [\n {\n element: \"City, county, precinct and ZIP code\",\n reference: safeHarbor(\"B\", \"All geographic subdivisions smaller than a State.\"),\n mitigation:\n \"Only street addresses are detected. Redact or generalise location fields by key.\",\n },\n {\n element: \"Admission, discharge and death dates, and ages over 89\",\n reference: safeHarbor(\"C\", \"All elements of dates (except year), and all ages over 89.\"),\n mitigation:\n \"Only dates that look like a date of birth are detected. Redact date and age fields by key.\",\n },\n {\n element: \"Device identifiers and serial numbers\",\n reference: safeHarbor(\"M\", \"Device identifiers and serial numbers.\"),\n mitigation: \"Add custom patterns for the device identifiers in your records.\",\n },\n {\n element: \"Biometric identifiers and full-face photographs\",\n reference: safeHarbor(\"P\", \"Biometric identifiers; (Q) full-face photographic images.\"),\n mitigation: \"Out of reach of text processing. Remove these attachments and fields.\",\n },\n {\n element: \"Names that are not introduced by a title, greeting or label\",\n reference: safeHarbor(\"A\", \"Names.\"),\n mitigation: \"Redact name fields by key; the name detector is a heuristic.\",\n },\n ],\n auditTrail: ref(\n \"45 CFR § 164.312(b)\",\n \"Audit controls: mechanisms that record and examine activity in systems that contain electronic protected health information.\",\n \"https://www.ecfr.gov/current/title-45/section-164.312\",\n ),\n};\n\n// ---------------------------------------------------------------------------\n// PCI DSS\n// ---------------------------------------------------------------------------\n\nconst PCI_URL = \"https://www.pcisecuritystandards.org/document_library/\";\nconst PCI_DISPLAY = ref(\n \"PCI DSS v4.0.1 Req. 3.4.1\",\n \"PAN is masked when displayed; the BIN and last four digits are the maximum number of digits to be displayed.\",\n PCI_URL,\n);\nconst PCI_STORAGE = ref(\n \"PCI DSS v4.0.1 Req. 3.5.1\",\n \"PAN is rendered unreadable anywhere it is stored: one-way hashes of the entire PAN, truncation, index tokens, or strong cryptography.\",\n PCI_URL,\n);\nconst PCI_KEYED_HASH = ref(\n \"PCI DSS v4.0.1 Req. 3.5.1.1\",\n \"Hashes used to render PAN unreadable are keyed cryptographic hashes of the entire PAN.\",\n PCI_URL,\n);\nconst PCI_SAD = ref(\n \"PCI DSS v4.0.1 Req. 3.3.1\",\n \"Sensitive authentication data is not retained after authorization.\",\n PCI_URL,\n);\n\nconst PCI_ADJACENT = ref(\n \"PCI DSS v4.0.1 Req. 3, account data\",\n \"Not account data; commonly stored next to it.\",\n PCI_URL,\n);\n\nconst PCI_DSS: RegulationProfile = {\n id: \"pci-dss\",\n name: \"Payment Card Industry Data Security Standard\",\n jurisdiction: \"Global (contractual, card brands)\",\n edition: \"PCI DSS v4.0.1\",\n references: [\n PCI_SAD,\n PCI_DISPLAY,\n PCI_STORAGE,\n PCI_KEYED_HASH,\n ref(\n \"PCI DSS v4.0.1 Req. 3.7.5\",\n \"Key management covers the retirement, replacement or destruction of keys.\",\n PCI_URL,\n ),\n ref(\n \"PCI DSS v4.0.1 Req. 10.5.1\",\n \"Audit log history is retained for at least 12 months.\",\n PCI_URL,\n ),\n ],\n rules: [\n ...rules(\n [\"credit-card\"],\n [PCI_DISPLAY, PCI_STORAGE, PCI_KEYED_HASH],\n { keyed: true, maxRevealed: { leading: 6, trailing: 4 } },\n { strategy: \"mask\", keepTrailing: 4 },\n \"At most the BIN and the last four digits may stay visible, and a hash of the PAN has to be keyed.\",\n ),\n ...rules(\n [\"name\"],\n [\n ref(\n \"PCI DSS v4.0.1 Req. 3, account data\",\n \"Cardholder name is cardholder data and is protected when stored with the PAN.\",\n PCI_URL,\n ),\n ],\n {},\n REDACT,\n \"Cardholder name is part of cardholder data.\",\n ),\n ...rules(\n [\"bank-account\"],\n [PCI_ADJACENT],\n {},\n { strategy: \"mask\", keepTrailing: 4 },\n \"Outside the standard's definition of account data; masked like a PAN because it accompanies card data in payment records.\",\n ),\n ...rules(\n [\"address\", \"email\", \"phone\"],\n [PCI_ADJACENT],\n {},\n REDACT,\n \"Outside the standard's definition of account data; included because these fields accompany card data in payment records.\",\n ),\n ],\n gaps: [\n {\n element:\n \"Card verification codes, full track data and PINs or PIN blocks (sensitive authentication data)\",\n reference: PCI_SAD,\n mitigation:\n \"These must not be stored at all. Redact the fields that carry them by key; no detector finds them.\",\n },\n {\n element: \"Expiration date and service code\",\n reference: ref(\n \"PCI DSS v4.0.1 Req. 3, account data\",\n \"Expiration date and service code are cardholder data.\",\n PCI_URL,\n ),\n mitigation: \"Redact the fields that carry them by key.\",\n },\n ],\n auditTrail: ref(\n \"PCI DSS v4.0.1 Req. 10.2.1 and 10.3.2\",\n \"Audit logs are enabled for all system components and cardholder data, and protected from modification.\",\n PCI_URL,\n ),\n};\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\nfunction freezeProfile(profile: RegulationProfile): RegulationProfile {\n return Object.freeze({\n ...profile,\n references: Object.freeze([...profile.references]),\n rules: Object.freeze([...profile.rules]),\n gaps: Object.freeze(profile.gaps.map((gap) => Object.freeze({ ...gap }))),\n });\n}\n\n/**\n * Every regulation profile, keyed by identifier.\n *\n * @example\n * ```ts\n * import { REGULATIONS } from \"anonyma/compliance\";\n *\n * for (const rule of REGULATIONS.hipaa.rules) {\n * console.log(rule.category, rule.references[0]?.citation);\n * }\n * ```\n */\nexport const REGULATIONS: Readonly<Record<RegulationId, RegulationProfile>> = Object.freeze({\n gdpr: freezeProfile(GDPR),\n lgpd: freezeProfile(LGPD),\n pipeda: freezeProfile(PIPEDA),\n ccpa: freezeProfile(CCPA),\n hipaa: freezeProfile(HIPAA),\n \"pci-dss\": freezeProfile(PCI_DSS),\n});\n\n/**\n * Whether `id` names a regulation profile.\n *\n * @example\n * ```ts\n * isRegulationId(\"hipaa\"); // true\n * isRegulationId(\"sox\"); // false\n * ```\n */\nexport function isRegulationId(id: unknown): id is RegulationId {\n return typeof id === \"string\" && Object.hasOwn(REGULATIONS, id);\n}\n\n/**\n * Get a regulation profile.\n *\n * @param id - The regulation identifier.\n * @returns The profile.\n * @throws {@link ValidationError} When `id` does not name a regulation profile.\n *\n * @example\n * ```ts\n * getRegulation(\"pci-dss\").rules.find((rule) => rule.category === \"credit-card\")?.requirement;\n * // { keyed: true, maxRevealed: { leading: 6, trailing: 4 } }\n * ```\n */\nexport function getRegulation(id: RegulationId): RegulationProfile {\n if (!isRegulationId(id)) throw new ValidationError(\"regulation\", \"is not a known regulation\");\n return REGULATIONS[id];\n}\n\n/**\n * One row of the compliance mapping matrix.\n */\nexport interface MatrixRow {\n /** The regulation. */\n readonly regulation: RegulationId;\n /** The category of data. */\n readonly category: PiiCategory;\n /** Citations that bring the category into scope. */\n readonly citations: readonly string[];\n /** The minimum protection, in words. */\n readonly requirement: string;\n /** The strategy the built-in preset applies. */\n readonly recommended: string;\n}\n\nfunction describeRequirement(requirement: ProtectionRequirement): string {\n const parts: string[] = [];\n /* v8 ignore if -- no built-in profile requires an irreversible replacement yet */\n if (requirement.irreversible === true) parts.push(\"irreversible\");\n if (requirement.notDerived === true) parts.push(\"not derived from the value\");\n if (requirement.keyed === true) parts.push(\"keyed if derived from the value\");\n if (requirement.maxRevealed !== undefined) {\n const { leading, trailing } = requirement.maxRevealed;\n parts.push(\n leading + trailing === 0\n ? \"nothing left visible\"\n : `at most ${String(leading)} leading and ${String(trailing)} trailing characters visible`,\n );\n }\n return parts.length === 0 ? \"clear value removed\" : parts.join(\"; \");\n}\n\n/**\n * The compliance mapping matrix as data: one row per regulation and category.\n *\n * @returns The rows, ordered by regulation and then by category.\n *\n * @example\n * ```ts\n * complianceMatrix().filter((row) => row.category === \"credit-card\");\n * ```\n */\nexport function complianceMatrix(): MatrixRow[] {\n const rows: MatrixRow[] = [];\n for (const profile of Object.values(REGULATIONS)) {\n for (const rule of profile.rules) {\n const { strategy, ...optionsOf } = rule.recommended;\n const optionText = Object.entries(optionsOf)\n .map(([name, value]) => `${name}: ${String(value)}`)\n .join(\", \");\n rows.push({\n regulation: profile.id,\n category: rule.category,\n citations: rule.references.map((reference) => reference.citation),\n requirement: describeRequirement(rule.requirement),\n recommended: optionText === \"\" ? strategy : `${strategy} (${optionText})`,\n });\n }\n }\n return rows;\n}\n","/**\n * @module compliance/traits\n * @description Describes what a strategy configuration does to a value, and\n * checks it against the protection a regulation requires.\n */\n\nimport type { StrategySpec } from \"../engine/types.js\";\nimport type { TokenizationProvider } from \"../vault/types.js\";\nimport type { ProtectionRequirement, StrategyTraits } from \"./types.js\";\n\n/**\n * What is known about the tokenization provider behind a `tokenize` strategy.\n */\nexport type TokenizationInfo = Pick<TokenizationProvider, \"scheme\" | \"reversible\">;\n\nconst NOTHING_REVEALED = Object.freeze({ leading: 0, trailing: 0 });\n\n/**\n * Describe what a strategy does to a value.\n *\n * @param spec - The strategy.\n * @param tokenization - The provider behind a `tokenize` strategy. When it is\n * not given, `tokenize` is described as its most permissive form: reversible\n * and computed from the value with a key.\n * @returns The traits of the strategy.\n *\n * @remarks\n * - `pseudonymize` with a seed is described as derived and **not** keyed: the\n * 1.x construction is a non-cryptographic hash that can be recomputed from\n * one known pair.\n * - `generalize` is described as revealing everything, because numeric input\n * keeps all but its last digits.\n *\n * @example\n * ```ts\n * describeStrategy({ strategy: \"mask\", keepTrailing: 4 });\n * // { reversible: false, derived: false, keyed: false, linkable: false, revealed: { leading: 0, trailing: 4 } }\n * ```\n */\nexport function describeStrategy(\n spec: StrategySpec,\n tokenization?: TokenizationInfo,\n): StrategyTraits {\n switch (spec.strategy) {\n case \"redact\":\n return {\n reversible: false,\n derived: false,\n keyed: false,\n linkable: false,\n revealed: NOTHING_REVEALED,\n };\n case \"mask\":\n return {\n reversible: false,\n derived: false,\n keyed: false,\n linkable: false,\n revealed: { leading: spec.keepLeading ?? 0, trailing: spec.keepTrailing ?? 0 },\n };\n case \"generalize\":\n return { reversible: false, derived: true, keyed: false, linkable: true, revealed: \"all\" };\n case \"pseudonymize\":\n return spec.seed === undefined\n ? {\n reversible: false,\n derived: false,\n keyed: false,\n linkable: false,\n revealed: NOTHING_REVEALED,\n }\n : {\n reversible: false,\n derived: true,\n keyed: false,\n linkable: true,\n revealed: NOTHING_REVEALED,\n };\n case \"synthesize\":\n return {\n reversible: false,\n derived: true,\n keyed: false,\n linkable: true,\n revealed: NOTHING_REVEALED,\n };\n case \"hash\":\n return {\n reversible: false,\n derived: true,\n keyed: spec.pepper !== undefined,\n linkable: true,\n revealed: NOTHING_REVEALED,\n };\n case \"encrypt\":\n return {\n reversible: true,\n derived: true,\n keyed: true,\n linkable: false,\n revealed: NOTHING_REVEALED,\n };\n case \"tokenize\": {\n const derived = tokenization?.scheme !== \"session\";\n return {\n reversible: tokenization?.reversible ?? true,\n derived,\n keyed: derived,\n linkable: true,\n revealed: NOTHING_REVEALED,\n };\n }\n }\n}\n\n/**\n * Check traits against a requirement.\n *\n * @param traits - What the strategy does.\n * @param requirement - What the regulation requires.\n * @returns One short reason per violated restriction; empty when the requirement is met.\n *\n * @example\n * ```ts\n * checkRequirement(describeStrategy({ strategy: \"hash\" }), { keyed: true });\n * // [\"the output is computed from the value without a secret key\"]\n * ```\n */\nexport function checkRequirement(\n traits: StrategyTraits,\n requirement: ProtectionRequirement,\n): string[] {\n const reasons: string[] = [];\n if (requirement.irreversible === true && traits.reversible) {\n reasons.push(\"the value can be restored by whoever holds the key or vault\");\n }\n if (requirement.notDerived === true && traits.derived) {\n reasons.push(\"the output is computed from the value\");\n }\n if (requirement.keyed === true && traits.derived && !traits.keyed) {\n reasons.push(\"the output is computed from the value without a secret key\");\n }\n if (requirement.maxRevealed !== undefined) {\n const { leading, trailing } = requirement.maxRevealed;\n if (traits.revealed === \"all\") {\n reasons.push(\"the value can pass through unchanged\");\n } else if (traits.revealed.leading > leading || traits.revealed.trailing > trailing) {\n reasons.push(\n `more than ${String(leading)} leading and ${String(trailing)} trailing characters stay visible`,\n );\n }\n }\n return reasons;\n}\n","/**\n * @module compliance/policy\n * @description The policy document parser: turns untrusted JSON into a checked\n * {@link Policy}, reporting every structural problem and every requirement of\n * an extended regulation that the document violates.\n */\n\nimport { PolicyError } from \"../errors.js\";\nimport { BUILTIN_CATEGORIES } from \"../engine/builtin.js\";\nimport type { PatternSpec, PipelineSpec, StrategySpec } from \"../engine/types.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport { REGULATIONS, isRegulationId } from \"./regulations.js\";\nimport { checkRequirement, describeStrategy } from \"./traits.js\";\nimport type { TokenizationInfo } from \"./traits.js\";\nimport type { LegalReference, Policy, PolicyDocument, PolicyIssue, RegulationId } from \"./types.js\";\n\ntype Json = Record<string, unknown>;\n\nconst REDACT: StrategySpec = Object.freeze({ strategy: \"redact\" });\n\nconst TOP_LEVEL = new Set([\n \"version\",\n \"id\",\n \"description\",\n \"extends\",\n \"categories\",\n \"defaultStrategy\",\n \"rules\",\n \"patterns\",\n \"minConfidence\",\n \"allow\",\n \"aggressive\",\n \"overlap\",\n]);\n\n/** Allowed options per strategy, with the JSON type each must have. */\nconst STRATEGY_OPTIONS: Readonly<Record<string, Readonly<Record<string, string>>>> = {\n redact: { label: \"string\" },\n mask: {\n maskChar: \"string\",\n keepLeading: \"count\",\n keepTrailing: \"count\",\n preserveFormat: \"boolean\",\n },\n pseudonymize: { seed: \"string\", prefix: \"string\" },\n hash: { truncate: \"count\", pepper: \"string\" },\n generalize: { bucketSize: \"count\" },\n synthesize: { seed: \"string\", locale: \"string\", category: \"string\" },\n tokenize: {},\n encrypt: {},\n};\n\nfunction isObject(value: unknown): value is Json {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isCategory(value: unknown): value is PiiCategory {\n return typeof value === \"string\" && (BUILTIN_CATEGORIES as readonly string[]).includes(value);\n}\n\nfunction escapePointer(segment: string): string {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\n/**\n * Options accepted by {@link checkPolicy} and {@link parsePolicy}.\n */\nexport interface PolicyOptions {\n /**\n * The provider that will back `tokenize` strategies. Requirements such as\n * \"not derived from the value\" depend on it.\n */\n readonly tokenization?: TokenizationInfo;\n}\n\n/**\n * Result of {@link checkPolicy}.\n */\nexport interface PolicyCheck {\n /** The checked policy; absent when the document has errors. */\n readonly policy?: Policy;\n /** Every problem found, errors first. */\n readonly issues: readonly PolicyIssue[];\n}\n\n/**\n * Check a policy document without throwing.\n *\n * @param input - The document, typically the result of `JSON.parse`.\n * @param options - What is known about the runtime the policy will run in.\n * @returns The policy when there are no errors, and every issue found.\n *\n * @example\n * ```ts\n * const { policy, issues } = checkPolicy({\n * version: 1,\n * id: \"payments\",\n * extends: [\"pci-dss\"],\n * rules: { \"credit-card\": { strategy: \"mask\", keepLeading: 8, keepTrailing: 4 } },\n * });\n * // policy === undefined\n * // issues[0].code === \"requirement-violated\"\n * // issues[0].reference.citation === \"PCI DSS v4.0.1 Req. 3.4.1\"\n * ```\n */\nexport function checkPolicy(input: unknown, options: PolicyOptions = {}): PolicyCheck {\n const issues: PolicyIssue[] = [];\n const error = (path: string, code: string, message: string, reference?: LegalReference): void => {\n issues.push({\n severity: \"error\",\n path,\n code,\n message,\n ...(reference !== undefined ? { reference } : {}),\n });\n };\n const warning = (\n path: string,\n code: string,\n message: string,\n reference?: LegalReference,\n ): void => {\n issues.push({\n severity: \"warning\",\n path,\n code,\n message,\n /* v8 ignore next -- no warning cites a provision yet */\n ...(reference !== undefined ? { reference } : {}),\n });\n };\n\n if (!isObject(input)) {\n error(\"\", \"not-an-object\", \"A policy document must be a JSON object.\");\n return { issues };\n }\n\n for (const key of Object.keys(input)) {\n if (!TOP_LEVEL.has(key))\n error(\n `/${escapePointer(key)}`,\n \"unknown-member\",\n \"This member is not part of the policy format.\",\n );\n }\n if (input[\"version\"] !== 1)\n error(\"/version\", \"unsupported-version\", \"The only supported policy version is 1.\");\n\n const id = input[\"id\"];\n if (typeof id !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(id)) {\n error(\n \"/id\",\n \"invalid-id\",\n \"The id must be 1-64 characters of letters, digits, '.', '_' and '-'.\",\n );\n }\n const description = input[\"description\"];\n if (description !== undefined && typeof description !== \"string\") {\n error(\"/description\", \"invalid-type\", \"The description must be a string.\");\n }\n\n // --- extends ---------------------------------------------------------------\n const regulations: RegulationId[] = [];\n const extended = input[\"extends\"];\n if (extended !== undefined) {\n if (!Array.isArray(extended)) {\n error(\"/extends\", \"invalid-type\", \"extends must be an array of regulation identifiers.\");\n } else {\n for (const [index, entry] of (extended as unknown[]).entries()) {\n if (!isRegulationId(entry)) {\n error(\n `/extends/${String(index)}`,\n \"unknown-regulation\",\n `Known regulations are: ${Object.keys(REGULATIONS).join(\", \")}.`,\n );\n } else if (!regulations.includes(entry)) {\n regulations.push(entry);\n }\n }\n }\n }\n\n // --- categories -------------------------------------------------------------\n const readCategories = (value: unknown, path: string): PiiCategory[] => {\n const out: PiiCategory[] = [];\n if (value === undefined) return out;\n if (!Array.isArray(value)) {\n error(path, \"invalid-type\", \"This member must be an array of category names.\");\n return out;\n }\n for (const [index, entry] of (value as unknown[]).entries()) {\n if (isCategory(entry)) out.push(entry);\n else\n error(`${path}/${String(index)}`, \"unknown-category\", \"This is not a built-in category.\");\n }\n return out;\n };\n let include: PiiCategory[] = [];\n let exclude: PiiCategory[] = [];\n const categoriesMember = input[\"categories\"];\n if (categoriesMember !== undefined) {\n if (!isObject(categoriesMember)) {\n error(\n \"/categories\",\n \"invalid-type\",\n \"categories must be an object with include and/or exclude.\",\n );\n } else {\n for (const key of Object.keys(categoriesMember)) {\n if (key !== \"include\" && key !== \"exclude\") {\n error(\n `/categories/${escapePointer(key)}`,\n \"unknown-member\",\n \"This member is not part of the policy format.\",\n );\n }\n }\n include = readCategories(categoriesMember[\"include\"], \"/categories/include\");\n exclude = readCategories(categoriesMember[\"exclude\"], \"/categories/exclude\");\n }\n }\n\n // --- strategies -------------------------------------------------------------\n const readStrategy = (value: unknown, path: string): StrategySpec | undefined => {\n if (!isObject(value)) {\n error(path, \"invalid-type\", \"A strategy must be an object with a strategy name.\");\n return undefined;\n }\n const name = value[\"strategy\"];\n const allowed =\n typeof name === \"string\" && Object.hasOwn(STRATEGY_OPTIONS, name)\n ? STRATEGY_OPTIONS[name]\n : undefined;\n if (allowed === undefined) {\n error(\n `${path}/strategy`,\n \"unknown-strategy\",\n `Known strategies are: ${Object.keys(STRATEGY_OPTIONS).join(\", \")}.`,\n );\n return undefined;\n }\n let valid = true;\n for (const [option, optionValue] of Object.entries(value)) {\n if (option === \"strategy\") continue;\n const expected = Object.hasOwn(allowed, option) ? allowed[option] : undefined;\n const fits =\n expected === \"count\"\n ? Number.isInteger(optionValue) && (optionValue as number) >= 0\n : expected !== undefined && typeof optionValue === expected;\n if (!fits) {\n valid = false;\n error(\n `${path}/${escapePointer(option)}`,\n expected === undefined ? \"unknown-option\" : \"invalid-option\",\n expected === undefined\n ? `The ${String(name)} strategy has no such option.`\n : `This option must be a ${expected === \"count\" ? \"non-negative integer\" : expected}.`,\n );\n }\n }\n return valid ? (Object.freeze({ ...value }) as StrategySpec) : undefined;\n };\n\n const defaultMember = input[\"defaultStrategy\"];\n const explicitDefault =\n defaultMember === undefined ? undefined : readStrategy(defaultMember, \"/defaultStrategy\");\n\n const explicitRules = new Map<string, StrategySpec>();\n const rulesMember = input[\"rules\"];\n if (rulesMember !== undefined) {\n if (!isObject(rulesMember)) {\n error(\"/rules\", \"invalid-type\", \"rules must be an object keyed by category.\");\n } else {\n for (const [category, value] of Object.entries(rulesMember)) {\n const strategy = readStrategy(value, `/rules/${escapePointer(category)}`);\n if (strategy !== undefined) explicitRules.set(category, strategy);\n }\n }\n }\n\n // --- patterns ---------------------------------------------------------------\n const patterns: PatternSpec[] = [];\n const patternsMember = input[\"patterns\"];\n if (patternsMember !== undefined) {\n if (!Array.isArray(patternsMember)) {\n error(\"/patterns\", \"invalid-type\", \"patterns must be an array.\");\n } else {\n for (const [index, entry] of (patternsMember as unknown[]).entries()) {\n const path = `/patterns/${String(index)}`;\n if (\n !isObject(entry) ||\n typeof entry[\"source\"] !== \"string\" ||\n typeof entry[\"category\"] !== \"string\" ||\n entry[\"category\"] === \"\"\n ) {\n error(\n path,\n \"invalid-pattern\",\n \"A pattern needs a source string and a non-empty category.\",\n );\n continue;\n }\n const flags = entry[\"flags\"];\n const confidence = entry[\"confidence\"];\n if (flags !== undefined && typeof flags !== \"string\") {\n error(`${path}/flags`, \"invalid-type\", \"flags must be a string.\");\n continue;\n }\n if (\n confidence !== undefined &&\n !(typeof confidence === \"number\" && confidence >= 0 && confidence <= 1)\n ) {\n error(\n `${path}/confidence`,\n \"invalid-type\",\n \"confidence must be a number between 0 and 1.\",\n );\n continue;\n }\n try {\n new RegExp(entry[\"source\"], flags ?? \"\");\n } catch {\n error(\n path,\n \"invalid-pattern\",\n \"The source and flags do not form a valid regular expression.\",\n );\n continue;\n }\n patterns.push(\n Object.freeze({\n source: entry[\"source\"],\n category: entry[\"category\"],\n ...(flags !== undefined ? { flags } : {}),\n ...(confidence !== undefined ? { confidence } : {}),\n }),\n );\n }\n }\n }\n\n // --- scalars ----------------------------------------------------------------\n const minConfidence = input[\"minConfidence\"];\n if (\n minConfidence !== undefined &&\n !(typeof minConfidence === \"number\" && minConfidence >= 0 && minConfidence <= 1)\n ) {\n error(\"/minConfidence\", \"invalid-type\", \"minConfidence must be a number between 0 and 1.\");\n }\n const allow = input[\"allow\"];\n if (\n allow !== undefined &&\n !(Array.isArray(allow) && (allow as unknown[]).every((entry) => typeof entry === \"string\"))\n ) {\n error(\"/allow\", \"invalid-type\", \"allow must be an array of strings.\");\n }\n const aggressive = input[\"aggressive\"];\n if (aggressive !== undefined && typeof aggressive !== \"boolean\") {\n error(\"/aggressive\", \"invalid-type\", \"aggressive must be a boolean.\");\n }\n const overlap = input[\"overlap\"];\n if (overlap !== undefined && overlap !== \"cover\" && overlap !== \"legacy\") {\n error(\"/overlap\", \"invalid-type\", 'overlap must be \"cover\" or \"legacy\".');\n }\n\n // --- effective categories ---------------------------------------------------\n const required = new Map<PiiCategory, RegulationId>();\n for (const regulation of regulations) {\n for (const rule of REGULATIONS[regulation].rules) {\n if (!required.has(rule.category)) required.set(rule.category, regulation);\n }\n }\n for (const [index, category] of exclude.entries()) {\n const regulation = required.get(category);\n if (regulation !== undefined) {\n const rule = REGULATIONS[regulation].rules.find(\n (candidate) => candidate.category === category,\n );\n error(\n `/categories/exclude/${String(index)}`,\n \"required-category-excluded\",\n `${REGULATIONS[regulation].name} brings \"${category}\" into scope; it cannot be excluded.`,\n rule?.references[0],\n );\n }\n }\n const wanted =\n regulations.length === 0 && include.length === 0\n ? new Set<PiiCategory>(BUILTIN_CATEGORIES)\n : new Set<PiiCategory>([...required.keys(), ...include]);\n for (const category of exclude) wanted.delete(category);\n const categories = BUILTIN_CATEGORIES.filter((category) => wanted.has(category));\n\n for (const category of explicitRules.keys()) {\n const known = isCategory(category)\n ? wanted.has(category)\n : patterns.some((pattern) => pattern.category === category);\n if (!known) {\n warning(\n `/rules/${escapePointer(category)}`,\n \"unused-rule\",\n \"No detector of this policy produces this category, so the rule never applies.\",\n );\n }\n }\n\n // --- effective strategies and compliance ------------------------------------\n const defaultStrategy = explicitDefault ?? REDACT;\n const strategies: Record<string, StrategySpec> = {};\n for (const category of categories) {\n const explicit = explicitRules.get(category) ?? explicitDefault;\n const inherited = regulations\n .map(\n (regulation) =>\n REGULATIONS[regulation].rules.find((rule) => rule.category === category)?.recommended,\n )\n .find((recommended) => recommended !== undefined);\n const strategy = explicit ?? inherited ?? REDACT;\n Object.defineProperty(strategies, category, { value: strategy, enumerable: true });\n\n const path = explicitRules.has(category)\n ? `/rules/${escapePointer(category)}`\n : \"/defaultStrategy\";\n const traits = describeStrategy(strategy, options.tokenization);\n for (const regulation of regulations) {\n const rule = REGULATIONS[regulation].rules.find(\n (candidate) => candidate.category === category,\n );\n if (rule === undefined) continue;\n for (const reason of checkRequirement(traits, rule.requirement)) {\n error(\n path,\n \"requirement-violated\",\n `\"${strategy.strategy}\" is not sufficient for \"${category}\" under ${REGULATIONS[regulation].name}: ${reason}.`,\n rule.references[0],\n );\n }\n }\n if (strategy.strategy === \"generalize\") {\n warning(\n path,\n \"generalize-non-numeric\",\n `\"generalize\" only shortens numbers; \"${category}\" values are redacted instead.`,\n );\n }\n if (strategy.strategy === \"hash\" && strategy.pepper === undefined) {\n warning(\n path,\n \"unkeyed-hash\",\n \"A hash without a pepper can be reversed by enumerating likely values.\",\n );\n }\n }\n for (const [category, strategy] of explicitRules) {\n if (!Object.hasOwn(strategies, category)) {\n Object.defineProperty(strategies, category, { value: strategy, enumerable: true });\n }\n }\n\n // Report each problem once, even when several categories share the default strategy.\n const seen = new Set<string>();\n const unique = issues.filter((issue) => {\n const key = `${issue.severity}\\0${issue.path}\\0${issue.code}\\0${issue.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n unique.sort((a, b) => Number(a.severity === \"warning\") - Number(b.severity === \"warning\"));\n\n if (unique.some((issue) => issue.severity === \"error\")) return { issues: unique };\n\n const document: PolicyDocument = Object.freeze({\n version: 1 as const,\n id: id as string,\n ...(typeof description === \"string\" ? { description } : {}),\n ...(regulations.length > 0 ? { extends: Object.freeze([...regulations]) } : {}),\n ...(include.length > 0 || exclude.length > 0\n ? {\n categories: Object.freeze({\n ...(include.length > 0 ? { include: Object.freeze([...include]) } : {}),\n ...(exclude.length > 0 ? { exclude: Object.freeze([...exclude]) } : {}),\n }),\n }\n : {}),\n ...(explicitDefault !== undefined ? { defaultStrategy: explicitDefault } : {}),\n ...(explicitRules.size > 0 ? { rules: Object.freeze(Object.fromEntries(explicitRules)) } : {}),\n ...(patterns.length > 0 ? { patterns: Object.freeze(patterns) } : {}),\n ...(typeof minConfidence === \"number\" ? { minConfidence } : {}),\n ...(Array.isArray(allow) ? { allow: Object.freeze([...(allow as string[])]) } : {}),\n ...(typeof aggressive === \"boolean\" ? { aggressive } : {}),\n ...(overlap === \"cover\" || overlap === \"legacy\" ? { overlap } : {}),\n });\n\n return {\n policy: Object.freeze({\n id: document.id,\n regulations: Object.freeze([...regulations]),\n categories: Object.freeze(categories),\n strategies: Object.freeze(strategies),\n defaultStrategy,\n document,\n warnings: Object.freeze(unique),\n }),\n issues: unique,\n };\n}\n\n/**\n * Parse and check a policy document.\n *\n * @param input - The document, typically the result of `JSON.parse`.\n * @param options - What is known about the runtime the policy will run in.\n * @returns The checked {@link Policy}.\n * @throws {@link PolicyError} When the document is malformed or violates a requirement of a\n * regulation it extends. `issues` lists every problem.\n *\n * @example\n * ```ts\n * import { compilePipeline } from \"anonyma/engine\";\n * import { parsePolicy, policyToSpec } from \"anonyma/compliance\";\n *\n * const policy = parsePolicy(JSON.parse(await readFile(\"policy.json\", \"utf8\")));\n * const pipeline = compilePipeline(policyToSpec(policy));\n * ```\n */\nexport function parsePolicy(input: unknown, options: PolicyOptions = {}): Policy {\n const { policy, issues } = checkPolicy(input, options);\n if (policy === undefined) throw new PolicyError(issues);\n return policy;\n}\n\n/**\n * Convert a checked policy into a pipeline specification for\n * `compilePipeline()`.\n *\n * @param policy - A policy returned by {@link parsePolicy} or {@link checkPolicy}.\n * @returns The equivalent {@link PipelineSpec}.\n *\n * @example\n * ```ts\n * const pipeline = compilePipeline(policyToSpec(policy), { tokenization });\n * ```\n */\nexport function policyToSpec(policy: Policy): PipelineSpec {\n const { document } = policy;\n return {\n categories: policy.categories,\n defaultStrategy: policy.defaultStrategy,\n rules: policy.strategies,\n ...(document.patterns !== undefined ? { patterns: document.patterns } : {}),\n ...(document.minConfidence !== undefined ? { minConfidence: document.minConfidence } : {}),\n ...(document.allow !== undefined ? { allow: document.allow } : {}),\n ...(document.aggressive !== undefined ? { aggressive: document.aggressive } : {}),\n ...(document.overlap !== undefined ? { overlap: document.overlap } : {}),\n };\n}\n\n/**\n * The policy document equivalent to a regulation profile with its recommended\n * strategies — a starting point for a custom policy.\n *\n * @param regulation - The regulation to start from.\n * @returns A policy document that extends the regulation.\n *\n * @example\n * ```ts\n * const document = { ...regulationPolicy(\"hipaa\"), id: \"clinic\", allow: [\"noreply@clinic.example\"] };\n * const policy = parsePolicy(document);\n * ```\n */\nexport function regulationPolicy(regulation: RegulationId): PolicyDocument {\n return {\n version: 1,\n id: regulation,\n description: REGULATIONS[regulation].name,\n extends: [regulation],\n };\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkRMMKYHUN_cjs = require('./chunk-RMMKYHUN.cjs');
|
|
4
|
-
var
|
|
5
|
-
var
|
|
4
|
+
var chunkF3BYJFUM_cjs = require('./chunk-F3BYJFUM.cjs');
|
|
5
|
+
var chunkHDHQXVUM_cjs = require('./chunk-HDHQXVUM.cjs');
|
|
6
6
|
var chunkWLJN7GIS_cjs = require('./chunk-WLJN7GIS.cjs');
|
|
7
7
|
|
|
8
8
|
// src/middleware/core.ts
|
|
@@ -59,7 +59,7 @@ function compressionOf(bytes, encoding) {
|
|
|
59
59
|
return encoding === "deflate" && zlib ? "deflate" : void 0;
|
|
60
60
|
}
|
|
61
61
|
function createScrubber(options = {}) {
|
|
62
|
-
const pipeline = options.pipeline ??
|
|
62
|
+
const pipeline = options.pipeline ?? chunkHDHQXVUM_cjs.compilePipeline(options.spec ?? {});
|
|
63
63
|
const {
|
|
64
64
|
keyRules,
|
|
65
65
|
keys,
|
|
@@ -76,7 +76,7 @@ function createScrubber(options = {}) {
|
|
|
76
76
|
...keys !== void 0 ? { keys } : {},
|
|
77
77
|
...numberDigits !== void 0 ? { numberDigits } : {}
|
|
78
78
|
};
|
|
79
|
-
|
|
79
|
+
chunkF3BYJFUM_cjs.sanitizeJson(null, jsonOptions);
|
|
80
80
|
function report(fields, source) {
|
|
81
81
|
if (audit === void 0 || fields.length === 0) return;
|
|
82
82
|
audit.record({
|
|
@@ -88,11 +88,11 @@ function createScrubber(options = {}) {
|
|
|
88
88
|
}).catch(onAuditError);
|
|
89
89
|
}
|
|
90
90
|
function json(value, source) {
|
|
91
|
-
let result =
|
|
91
|
+
let result = chunkF3BYJFUM_cjs.sanitizeJson(value, jsonOptions);
|
|
92
92
|
if (result.skipped.length > 0) {
|
|
93
93
|
const serialised = JSON.stringify(value);
|
|
94
94
|
if (serialised === void 0) return value;
|
|
95
|
-
result =
|
|
95
|
+
result = chunkF3BYJFUM_cjs.sanitizeJson(JSON.parse(serialised), jsonOptions);
|
|
96
96
|
}
|
|
97
97
|
report(result.fields, source);
|
|
98
98
|
return result.value;
|
|
@@ -109,16 +109,16 @@ function createScrubber(options = {}) {
|
|
|
109
109
|
if (input.length > maxBodyLength) throw tooLarge();
|
|
110
110
|
let parsed;
|
|
111
111
|
try {
|
|
112
|
-
parsed =
|
|
112
|
+
parsed = chunkF3BYJFUM_cjs.parseJsonLossless(input);
|
|
113
113
|
} catch {
|
|
114
114
|
return text(input, source);
|
|
115
115
|
}
|
|
116
|
-
const result =
|
|
116
|
+
const result = chunkF3BYJFUM_cjs.sanitizeJson(parsed.value, {
|
|
117
117
|
...jsonOptions,
|
|
118
118
|
...parsed.marker !== void 0 ? { rawNumberMarker: parsed.marker } : {}
|
|
119
119
|
});
|
|
120
120
|
report(result.fields, source);
|
|
121
|
-
return result.replaced === 0 ? input :
|
|
121
|
+
return result.replaced === 0 ? input : chunkF3BYJFUM_cjs.stringifyJsonLossless(result.value, parsed.marker);
|
|
122
122
|
}
|
|
123
123
|
return TEXT_TYPE.test(type) ? text(input, source) : input;
|
|
124
124
|
}
|
|
@@ -177,5 +177,5 @@ function createScrubber(options = {}) {
|
|
|
177
177
|
}
|
|
178
178
|
|
|
179
179
|
exports.createScrubber = createScrubber;
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
181
|
-
//# sourceMappingURL=chunk-
|
|
180
|
+
//# sourceMappingURL=chunk-32U3DM7M.cjs.map
|
|
181
|
+
//# sourceMappingURL=chunk-32U3DM7M.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware/core.ts"],"names":["ValidationError","compilePipeline","sanitizeJson","summarizeSpans","parseJsonLossless","stringifyJsonLossless"],"mappings":";;;;;;;;AA+FA,IAAM,SAAA,GAAY,sCAAA;AAClB,IAAM,SAAA,GACJ,0JAAA;AACF,IAAM,iBAAA,GAAoB,wBAAA;AAC1B,IAAM,OAAA,GAAU,mCA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AACrF,IAAA,IAAI,QAAA,KAAa,EAAA,IAAM,QAAA,KAAa,UAAA,EAAY;AAE9C,MAAA,MAAM,MAAA,GAAS,aAAA,CAAc,GAAA,EAAK,QAAQ,CAAA;AAC1C,MAAA,IAAI,WAAW,MAAA,EAAW;AACxB,QAAA,MAAM,QAAA,GAAW,IAAI,IAAA,CAAK,CAAC,GAAG,CAAC,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,IAAI,mBAAA,CAAoB,MAAM,CAAC,CAAA;AACrF,QAAA,GAAA,GAAM,MAAM,SAAA,CAAU,QAAA,EAAU,aAAA,GAAgB,CAAC,CAAA;AAAA,MACnD;AAAA,IACF;AACA,IAAA,OAAA,CAAQ,GAAA,CAAI,cAAA,EAAgB,MAAA,CAAO,IAAI,CAAC,CAAA;AACxC,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,MAAA,CAAO,GAAA,EAAK,IAAI,CAAA,EAAG,IAAA,EAAM,MAAM,CAAA,EAAG,IAAI,CAAA;AAAA,EACjE;AAEA,EAAA,OAAO,MAAA,CAAO,OAAO,EAAE,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,UAAU,CAAA;AAC5D","file":"chunk-ISL5B4LU.cjs","sourcesContent":["/**\n * @module middleware/core\n * @description Framework-independent payload scrubbing for HTTP services:\n * one object that sanitizes JSON values, text and Fetch API responses with a\n * pipeline, and records what it did in the audit log.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport { sanitizeJson } from \"../ai/json.js\";\nimport type { KeyRule } from \"../ai/json.js\";\nimport { summarizeSpans } from \"../audit/fields.js\";\nimport type { AuditFieldEntry, AuditLogger } from \"../audit/types.js\";\nimport { compilePipeline } from \"../engine/compile.js\";\nimport type { Pipeline, PipelineSpec } from \"../engine/types.js\";\nimport type { Bytes } from \"../internal/encoding.js\";\nimport { parseJsonLossless, stringifyJsonLossless } from \"../internal/json-numbers.js\";\n\n/**\n * Options shared by every middleware.\n */\nexport interface ScrubberOptions {\n /** The pipeline to apply. Its replacers must be synchronous. Takes precedence over `spec`. */\n readonly pipeline?: Pipeline;\n /** A pipeline specification, compiled once. Defaults to detecting every category and redacting it. */\n readonly spec?: PipelineSpec;\n /** Keys whose values are replaced whole, such as `password` or `ssn`. */\n readonly keyRules?: readonly KeyRule[];\n /**\n * What happens to a JSON object key in which the pipeline detects something:\n * `\"replace\"` (default) rewrites it like a value, `\"flag\"` leaves it.\n */\n readonly keys?: \"replace\" | \"flag\";\n /**\n * A JSON integer with at least this many digits is scanned as text and\n * becomes a string when a detector matches it. Defaults to `12`; shorter\n * numbers (phone numbers, timestamps) need a key rule.\n */\n readonly numberDigits?: number;\n /** Records every scrubbed payload, without its content. */\n readonly audit?: AuditLogger;\n /** Name of the service, recorded as the actor in audit records. */\n readonly actor?: string;\n /** Identifier of the policy in force, recorded in audit records. */\n readonly policyId?: string;\n /**\n * Largest text body, in characters, that is scrubbed. A larger body is not\n * sent on: scrubbing fails. For a `text/event-stream` response the limit\n * applies to each event. Defaults to 5,000,000.\n */\n readonly maxBodyLength?: number;\n /** Called when an audit record cannot be written. Defaults to ignoring the failure. */\n readonly onAuditError?: (error: unknown) => void;\n}\n\n/**\n * Scrubs payloads and reports to the audit log.\n */\nexport interface Scrubber {\n /**\n * Scrub a value that is about to be serialised as JSON. Returns a\n * structural copy. A value that is not plain JSON data (a class instance,\n * an object with `toJSON`, a `Date`) is first reduced to what\n * `JSON.stringify` would write, so the copy is what gets sent.\n */\n readonly json: <T>(value: T, source: string) => T;\n /** Scrub a text. */\n readonly text: (text: string, source: string) => string;\n /**\n * Scrub a serialised body according to its content type: JSON is parsed,\n * scrubbed and serialised again (a body in which nothing is replaced is\n * returned exactly as it was); textual types are scrubbed as text; anything\n * else is returned unchanged.\n */\n readonly body: (body: string, contentType: string | null | undefined, source: string) => string;\n /**\n * Scrub a body held as bytes. Returns the scrubbed text, or `undefined`\n * when the content type is not one the scrubber handles and the bytes\n * should be sent as they are.\n *\n * @throws ValidationError When the bytes are not text in the declared character set.\n */\n readonly bytes: (\n bytes: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ) => string | undefined;\n /**\n * Scrub a Fetch API `Response` with a JSON or text body. A\n * `text/event-stream` response is scrubbed event by event as it streams;\n * any other body is read to its end first. Other responses are returned as\n * they are.\n */\n readonly response: (response: Response, source: string) => Promise<Response>;\n}\n\nconst JSON_TYPE = /^application\\/(?:[\\w.+-]*\\+)?json\\b/i;\nconst TEXT_TYPE =\n /^(?:text\\/|application\\/(?:(?:[\\w.-]*\\+)?xml|x-ndjson|ndjson|jsonl|javascript|x-javascript|ecmascript|x-www-form-urlencoded|graphql|yaml|x-yaml|csv)\\b)/i;\nconst EVENT_STREAM_TYPE = /^text\\/event-stream\\b/i;\nconst CHARSET = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i;\n/** The blank line that ends a server-sent event. */\nconst EVENT_END = /\\r\\n\\r\\n|\\n\\n|\\r\\r/;\n\nfunction tooLarge(): ValidationError {\n return new ValidationError(\"body\", \"is larger than maxBodyLength and was not scrubbed\");\n}\n\n/** Decode `bytes` in the character set `contentType` declares (UTF-8 when it declares none). */\nfunction decode(bytes: Uint8Array, contentType: string): string {\n const label = CHARSET.exec(contentType)?.[1] ?? \"utf-8\";\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(label, { fatal: true });\n } catch {\n throw new ValidationError(\"body\", \"is in a character set that cannot be decoded\");\n }\n try {\n return decoder.decode(bytes);\n } catch {\n throw new ValidationError(\"body\", \"is not text in its declared character set\");\n }\n}\n\n/** `contentType` with its character set changed to UTF-8, which is what a scrubbed body is. */\nfunction asUtf8(contentType: string): string {\n return CHARSET.test(contentType) ? contentType.replace(CHARSET, \"; charset=utf-8\") : contentType;\n}\n\n/** Read a body to its end, giving up as soon as it is longer than `limit` bytes. */\nasync function readBytes(stream: ReadableStream<Uint8Array>, limit: number): Promise<Bytes> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > limit) {\n await reader.cancel();\n throw tooLarge();\n }\n chunks.push(value);\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/** The format `DecompressionStream` needs for bytes that really are compressed, if any. */\nfunction compressionOf(bytes: Uint8Array, encoding: string): \"gzip\" | \"deflate\" | undefined {\n if (bytes[0] === 0x1f && bytes[1] === 0x8b) return \"gzip\";\n const zlib = bytes[0] === 0x78 && ((bytes[0] << 8) | (bytes[1] ?? 0)) % 31 === 0;\n return encoding === \"deflate\" && zlib ? \"deflate\" : undefined;\n}\n\n/**\n * Create a scrubber.\n *\n * @param options - Pipeline, key rules and audit settings.\n * @returns The {@link Scrubber}.\n * @throws {@link ValidationError} When the spec is invalid.\n *\n * @example\n * ```ts\n * import { createScrubber } from \"anonyma/middleware\";\n *\n * const scrubber = createScrubber({ spec: { preset: \"gdpr\" } });\n *\n * // A Next.js route handler, a Cloudflare Worker, or any other Fetch API handler:\n * export async function GET(request: Request): Promise<Response> {\n * return scrubber.response(await upstream(request), \"GET /api/tickets\");\n * }\n * ```\n */\nexport function createScrubber(options: ScrubberOptions = {}): Scrubber {\n const pipeline = options.pipeline ?? compilePipeline(options.spec ?? {});\n const {\n keyRules,\n keys,\n numberDigits,\n audit,\n actor,\n policyId,\n maxBodyLength = 5_000_000,\n } = options;\n const onAuditError = options.onAuditError ?? ((): void => undefined);\n const jsonOptions = {\n pipeline,\n ...(keyRules !== undefined ? { keyRules } : {}),\n ...(keys !== undefined ? { keys } : {}),\n ...(numberDigits !== undefined ? { numberDigits } : {}),\n };\n // Fail on an invalid option now, not on the first response.\n sanitizeJson(null, jsonOptions);\n\n function report(fields: readonly AuditFieldEntry[], source: string): void {\n if (audit === undefined || fields.length === 0) return;\n audit\n .record({\n operation: \"anonymize\",\n source,\n fields,\n ...(actor !== undefined ? { actor } : {}),\n ...(policyId !== undefined ? { policy: { id: policyId } } : {}),\n })\n .catch(onAuditError);\n }\n\n function json<T>(value: T, source: string): T {\n let result = sanitizeJson(value, jsonOptions);\n if (result.skipped.length > 0) {\n // Not plain data: scrub what JSON.stringify would write, since that is what is sent.\n const serialised = JSON.stringify(value) as string | undefined;\n if (serialised === undefined) return value;\n result = sanitizeJson(JSON.parse(serialised) as T, jsonOptions);\n }\n report(result.fields, source);\n return result.value;\n }\n\n function text(input: string, source: string): string {\n if (input.length > maxBodyLength) throw tooLarge();\n const result = pipeline.transform(input);\n report(summarizeSpans(result.spans, { rule: (category) => category }), source);\n return result.text;\n }\n\n function body(input: string, contentType: string | null | undefined, source: string): string {\n const type = contentType ?? \"\";\n if (JSON_TYPE.test(type)) {\n if (input.length > maxBodyLength) throw tooLarge();\n let parsed: ReturnType<typeof parseJsonLossless>;\n try {\n parsed = parseJsonLossless(input);\n } catch {\n // Mislabelled or truncated JSON: still scrub it, as text.\n return text(input, source);\n }\n const result = sanitizeJson(parsed.value, {\n ...jsonOptions,\n ...(parsed.marker !== undefined ? { rawNumberMarker: parsed.marker } : {}),\n });\n report(result.fields, source);\n // Nothing replaced: the body goes out exactly as it came in.\n return result.replaced === 0 ? input : stringifyJsonLossless(result.value, parsed.marker);\n }\n return TEXT_TYPE.test(type) ? text(input, source) : input;\n }\n\n function bytes(\n input: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ): string | undefined {\n const type = contentType ?? \"\";\n if (!JSON_TYPE.test(type) && !TEXT_TYPE.test(type)) return undefined;\n // Four bytes are at most four characters, so this bound never rejects a body that fits.\n if (input.length > maxBodyLength * 4) throw tooLarge();\n return body(decode(input, type), type, source);\n }\n\n /** Scrub a stream of server-sent events one event at a time. */\n function events(source: string): TransformStream<string, string> {\n let pending = \"\";\n return new TransformStream<string, string>({\n transform(chunk, controller): void {\n pending += chunk;\n for (;;) {\n const end = EVENT_END.exec(pending);\n if (end === null) break;\n const length = end.index + end[0].length;\n controller.enqueue(text(pending.slice(0, length), source));\n pending = pending.slice(length);\n }\n if (pending.length > maxBodyLength) throw tooLarge();\n },\n flush(controller): void {\n if (pending.length > 0) controller.enqueue(text(pending, source));\n },\n });\n }\n\n async function response(original: Response, source: string): Promise<Response> {\n const type = original.headers.get(\"content-type\");\n if (\n original.body === null ||\n type === null ||\n !(JSON_TYPE.test(type) || TEXT_TYPE.test(type))\n ) {\n return original;\n }\n const headers = new Headers(original.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n const init = { status: original.status, statusText: original.statusText, headers };\n\n if (EVENT_STREAM_TYPE.test(type)) {\n // A stream is never read to its end first: it may not have one.\n const stream = original.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(events(source))\n .pipeThrough(new TextEncoderStream());\n return new Response(stream, init);\n }\n\n let raw = await readBytes(original.body, maxBodyLength * 4);\n const encoding = (original.headers.get(\"content-encoding\") ?? \"\").trim().toLowerCase();\n if (encoding !== \"\" && encoding !== \"identity\") {\n // fetch() hands over a decoded body under the original header; a handler may hand over compressed bytes.\n const format = compressionOf(raw, encoding);\n if (format !== undefined) {\n const inflated = new Blob([raw]).stream().pipeThrough(new DecompressionStream(format));\n raw = await readBytes(inflated, maxBodyLength * 4);\n }\n }\n headers.set(\"content-type\", asUtf8(type));\n return new Response(body(decode(raw, type), type, source), init);\n }\n\n return Object.freeze({ json, text, body, bytes, response });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/middleware/core.ts"],"names":["ValidationError","compilePipeline","sanitizeJson","summarizeSpans","parseJsonLossless","stringifyJsonLossless"],"mappings":";;;;;;;;AA+FA,IAAM,SAAA,GAAY,sCAAA;AAClB,IAAM,SAAA,GACJ,0JAAA;AACF,IAAM,iBAAA,GAAoB,wBAAA;AAC1B,IAAM,OAAA,GAAU,mCAAA;AAEhB,IAAM,SAAA,GAAY,oBAAA;AAElB,SAAS,QAAA,GAA4B;AACnC,EAAA,OAAO,IAAIA,iCAAA,CAAgB,MAAA,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c,GAAA,EAAK,QAAQ,CAAA;AAC1C,MAAA,IAAI,WAAW,MAAA,EAAW;AACxB,QAAA,MAAM,QAAA,GAAW,IAAI,IAAA,CAAK,CAAC,GAAG,CAAC,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,IAAI,mBAAA,CAAoB,MAAM,CAAC,CAAA;AACrF,QAAA,GAAA,GAAM,MAAM,SAAA,CAAU,QAAA,EAAU,aAAA,GAAgB,CAAC,CAAA;AAAA,MACnD;AAAA,IACF;AACA,IAAA,OAAA,CAAQ,GAAA,CAAI,cAAA,EAAgB,MAAA,CAAO,IAAI,CAAC,CAAA;AACxC,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,MAAA,CAAO,GAAA,EAAK,IAAI,CAAA,EAAG,IAAA,EAAM,MAAM,CAAA,EAAG,IAAI,CAAA;AAAA,EACjE;AAEA,EAAA,OAAO,MAAA,CAAO,OAAO,EAAE,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,UAAU,CAAA;AAC5D","file":"chunk-32U3DM7M.cjs","sourcesContent":["/**\n * @module middleware/core\n * @description Framework-independent payload scrubbing for HTTP services:\n * one object that sanitizes JSON values, text and Fetch API responses with a\n * pipeline, and records what it did in the audit log.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport { sanitizeJson } from \"../ai/json.js\";\nimport type { KeyRule } from \"../ai/json.js\";\nimport { summarizeSpans } from \"../audit/fields.js\";\nimport type { AuditFieldEntry, AuditLogger } from \"../audit/types.js\";\nimport { compilePipeline } from \"../engine/compile.js\";\nimport type { Pipeline, PipelineSpec } from \"../engine/types.js\";\nimport type { Bytes } from \"../internal/encoding.js\";\nimport { parseJsonLossless, stringifyJsonLossless } from \"../internal/json-numbers.js\";\n\n/**\n * Options shared by every middleware.\n */\nexport interface ScrubberOptions {\n /** The pipeline to apply. Its replacers must be synchronous. Takes precedence over `spec`. */\n readonly pipeline?: Pipeline;\n /** A pipeline specification, compiled once. Defaults to detecting every category and redacting it. */\n readonly spec?: PipelineSpec;\n /** Keys whose values are replaced whole, such as `password` or `ssn`. */\n readonly keyRules?: readonly KeyRule[];\n /**\n * What happens to a JSON object key in which the pipeline detects something:\n * `\"replace\"` (default) rewrites it like a value, `\"flag\"` leaves it.\n */\n readonly keys?: \"replace\" | \"flag\";\n /**\n * A JSON integer with at least this many digits is scanned as text and\n * becomes a string when a detector matches it. Defaults to `12`; shorter\n * numbers (phone numbers, timestamps) need a key rule.\n */\n readonly numberDigits?: number;\n /** Records every scrubbed payload, without its content. */\n readonly audit?: AuditLogger;\n /** Name of the service, recorded as the actor in audit records. */\n readonly actor?: string;\n /** Identifier of the policy in force, recorded in audit records. */\n readonly policyId?: string;\n /**\n * Largest text body, in characters, that is scrubbed. A larger body is not\n * sent on: scrubbing fails. For a `text/event-stream` response the limit\n * applies to each event. Defaults to 5,000,000.\n */\n readonly maxBodyLength?: number;\n /** Called when an audit record cannot be written. Defaults to ignoring the failure. */\n readonly onAuditError?: (error: unknown) => void;\n}\n\n/**\n * Scrubs payloads and reports to the audit log.\n */\nexport interface Scrubber {\n /**\n * Scrub a value that is about to be serialised as JSON. Returns a\n * structural copy. A value that is not plain JSON data (a class instance,\n * an object with `toJSON`, a `Date`) is first reduced to what\n * `JSON.stringify` would write, so the copy is what gets sent.\n */\n readonly json: <T>(value: T, source: string) => T;\n /** Scrub a text. */\n readonly text: (text: string, source: string) => string;\n /**\n * Scrub a serialised body according to its content type: JSON is parsed,\n * scrubbed and serialised again (a body in which nothing is replaced is\n * returned exactly as it was); textual types are scrubbed as text; anything\n * else is returned unchanged.\n */\n readonly body: (body: string, contentType: string | null | undefined, source: string) => string;\n /**\n * Scrub a body held as bytes. Returns the scrubbed text, or `undefined`\n * when the content type is not one the scrubber handles and the bytes\n * should be sent as they are.\n *\n * @throws ValidationError When the bytes are not text in the declared character set.\n */\n readonly bytes: (\n bytes: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ) => string | undefined;\n /**\n * Scrub a Fetch API `Response` with a JSON or text body. A\n * `text/event-stream` response is scrubbed event by event as it streams;\n * any other body is read to its end first. Other responses are returned as\n * they are.\n */\n readonly response: (response: Response, source: string) => Promise<Response>;\n}\n\nconst JSON_TYPE = /^application\\/(?:[\\w.+-]*\\+)?json\\b/i;\nconst TEXT_TYPE =\n /^(?:text\\/|application\\/(?:(?:[\\w.-]*\\+)?xml|x-ndjson|ndjson|jsonl|javascript|x-javascript|ecmascript|x-www-form-urlencoded|graphql|yaml|x-yaml|csv)\\b)/i;\nconst EVENT_STREAM_TYPE = /^text\\/event-stream\\b/i;\nconst CHARSET = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i;\n/** The blank line that ends a server-sent event. */\nconst EVENT_END = /\\r\\n\\r\\n|\\n\\n|\\r\\r/;\n\nfunction tooLarge(): ValidationError {\n return new ValidationError(\"body\", \"is larger than maxBodyLength and was not scrubbed\");\n}\n\n/** Decode `bytes` in the character set `contentType` declares (UTF-8 when it declares none). */\nfunction decode(bytes: Uint8Array, contentType: string): string {\n const label = CHARSET.exec(contentType)?.[1] ?? \"utf-8\";\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(label, { fatal: true });\n } catch {\n throw new ValidationError(\"body\", \"is in a character set that cannot be decoded\");\n }\n try {\n return decoder.decode(bytes);\n } catch {\n throw new ValidationError(\"body\", \"is not text in its declared character set\");\n }\n}\n\n/** `contentType` with its character set changed to UTF-8, which is what a scrubbed body is. */\nfunction asUtf8(contentType: string): string {\n return CHARSET.test(contentType) ? contentType.replace(CHARSET, \"; charset=utf-8\") : contentType;\n}\n\n/** Read a body to its end, giving up as soon as it is longer than `limit` bytes. */\nasync function readBytes(stream: ReadableStream<Uint8Array>, limit: number): Promise<Bytes> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > limit) {\n await reader.cancel();\n throw tooLarge();\n }\n chunks.push(value);\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/** The format `DecompressionStream` needs for bytes that really are compressed, if any. */\nfunction compressionOf(bytes: Uint8Array, encoding: string): \"gzip\" | \"deflate\" | undefined {\n if (bytes[0] === 0x1f && bytes[1] === 0x8b) return \"gzip\";\n const zlib = bytes[0] === 0x78 && ((bytes[0] << 8) | (bytes[1] ?? 0)) % 31 === 0;\n return encoding === \"deflate\" && zlib ? \"deflate\" : undefined;\n}\n\n/**\n * Create a scrubber.\n *\n * @param options - Pipeline, key rules and audit settings.\n * @returns The {@link Scrubber}.\n * @throws {@link ValidationError} When the spec is invalid.\n *\n * @example\n * ```ts\n * import { createScrubber } from \"anonyma/middleware\";\n *\n * const scrubber = createScrubber({ spec: { preset: \"gdpr\" } });\n *\n * // A Next.js route handler, a Cloudflare Worker, or any other Fetch API handler:\n * export async function GET(request: Request): Promise<Response> {\n * return scrubber.response(await upstream(request), \"GET /api/tickets\");\n * }\n * ```\n */\nexport function createScrubber(options: ScrubberOptions = {}): Scrubber {\n const pipeline = options.pipeline ?? compilePipeline(options.spec ?? {});\n const {\n keyRules,\n keys,\n numberDigits,\n audit,\n actor,\n policyId,\n maxBodyLength = 5_000_000,\n } = options;\n const onAuditError = options.onAuditError ?? ((): void => undefined);\n const jsonOptions = {\n pipeline,\n ...(keyRules !== undefined ? { keyRules } : {}),\n ...(keys !== undefined ? { keys } : {}),\n ...(numberDigits !== undefined ? { numberDigits } : {}),\n };\n // Fail on an invalid option now, not on the first response.\n sanitizeJson(null, jsonOptions);\n\n function report(fields: readonly AuditFieldEntry[], source: string): void {\n if (audit === undefined || fields.length === 0) return;\n audit\n .record({\n operation: \"anonymize\",\n source,\n fields,\n ...(actor !== undefined ? { actor } : {}),\n ...(policyId !== undefined ? { policy: { id: policyId } } : {}),\n })\n .catch(onAuditError);\n }\n\n function json<T>(value: T, source: string): T {\n let result = sanitizeJson(value, jsonOptions);\n if (result.skipped.length > 0) {\n // Not plain data: scrub what JSON.stringify would write, since that is what is sent.\n const serialised = JSON.stringify(value) as string | undefined;\n if (serialised === undefined) return value;\n result = sanitizeJson(JSON.parse(serialised) as T, jsonOptions);\n }\n report(result.fields, source);\n return result.value;\n }\n\n function text(input: string, source: string): string {\n if (input.length > maxBodyLength) throw tooLarge();\n const result = pipeline.transform(input);\n report(summarizeSpans(result.spans, { rule: (category) => category }), source);\n return result.text;\n }\n\n function body(input: string, contentType: string | null | undefined, source: string): string {\n const type = contentType ?? \"\";\n if (JSON_TYPE.test(type)) {\n if (input.length > maxBodyLength) throw tooLarge();\n let parsed: ReturnType<typeof parseJsonLossless>;\n try {\n parsed = parseJsonLossless(input);\n } catch {\n // Mislabelled or truncated JSON: still scrub it, as text.\n return text(input, source);\n }\n const result = sanitizeJson(parsed.value, {\n ...jsonOptions,\n ...(parsed.marker !== undefined ? { rawNumberMarker: parsed.marker } : {}),\n });\n report(result.fields, source);\n // Nothing replaced: the body goes out exactly as it came in.\n return result.replaced === 0 ? input : stringifyJsonLossless(result.value, parsed.marker);\n }\n return TEXT_TYPE.test(type) ? text(input, source) : input;\n }\n\n function bytes(\n input: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ): string | undefined {\n const type = contentType ?? \"\";\n if (!JSON_TYPE.test(type) && !TEXT_TYPE.test(type)) return undefined;\n // Four bytes are at most four characters, so this bound never rejects a body that fits.\n if (input.length > maxBodyLength * 4) throw tooLarge();\n return body(decode(input, type), type, source);\n }\n\n /** Scrub a stream of server-sent events one event at a time. */\n function events(source: string): TransformStream<string, string> {\n let pending = \"\";\n return new TransformStream<string, string>({\n transform(chunk, controller): void {\n pending += chunk;\n for (;;) {\n const end = EVENT_END.exec(pending);\n if (end === null) break;\n const length = end.index + end[0].length;\n controller.enqueue(text(pending.slice(0, length), source));\n pending = pending.slice(length);\n }\n if (pending.length > maxBodyLength) throw tooLarge();\n },\n flush(controller): void {\n if (pending.length > 0) controller.enqueue(text(pending, source));\n },\n });\n }\n\n async function response(original: Response, source: string): Promise<Response> {\n const type = original.headers.get(\"content-type\");\n if (\n original.body === null ||\n type === null ||\n !(JSON_TYPE.test(type) || TEXT_TYPE.test(type))\n ) {\n return original;\n }\n const headers = new Headers(original.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n const init = { status: original.status, statusText: original.statusText, headers };\n\n if (EVENT_STREAM_TYPE.test(type)) {\n // A stream is never read to its end first: it may not have one.\n const stream = original.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(events(source))\n .pipeThrough(new TextEncoderStream());\n return new Response(stream, init);\n }\n\n let raw = await readBytes(original.body, maxBodyLength * 4);\n const encoding = (original.headers.get(\"content-encoding\") ?? \"\").trim().toLowerCase();\n if (encoding !== \"\" && encoding !== \"identity\") {\n // fetch() hands over a decoded body under the original header; a handler may hand over compressed bytes.\n const format = compressionOf(raw, encoding);\n if (format !== undefined) {\n const inflated = new Blob([raw]).stream().pipeThrough(new DecompressionStream(format));\n raw = await readBytes(inflated, maxBodyLength * 4);\n }\n }\n headers.set(\"content-type\", asUtf8(type));\n return new Response(body(decode(raw, type), type, source), init);\n }\n\n return Object.freeze({ json, text, body, bytes, response });\n}\n"]}
|