@guhttps/veu 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -3
- package/dist/analyzer.d.ts +10 -0
- package/dist/analyzer.js +49 -1
- package/dist/anonymizer.d.ts +16 -4
- package/dist/anonymizer.js +127 -25
- package/dist/cache.d.ts +17 -0
- package/dist/cache.js +48 -0
- package/dist/data.d.ts +10 -0
- package/dist/data.js +130 -4
- package/dist/entities.d.ts +2 -0
- package/dist/entities.js +34 -0
- package/dist/gateway.d.ts +7 -4
- package/dist/gateway.js +71 -20
- package/dist/index.d.ts +7 -5
- package/dist/index.js +7 -5
- package/dist/patterns.js +129 -3
- package/dist/persons.d.ts +3 -0
- package/dist/persons.js +21 -3
- package/dist/validators.d.ts +34 -0
- package/dist/validators.js +346 -0
- package/dist/vault.d.ts +66 -7
- package/dist/vault.js +195 -27
- package/dist/veu.global.js +23 -20
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @guhttps/veu
|
|
2
2
|
|
|
3
|
-
**Véu para JavaScript e TypeScript.** Esconde dados pessoais
|
|
3
|
+
**Véu para JavaScript e TypeScript.** Esconde dados pessoais e segredos (nomes, e-mails, telefones de qualquer país, CPF, CNPJ, cartões, chaves de API, senhas) antes de o texto chegar a um modelo de IA, e devolve os dados reais na resposta.
|
|
4
4
|
|
|
5
5
|
```
|
|
6
6
|
Você escreve: "Cliente Maria Souza, CPF 529.982.247-25, chave sk-proj-..."
|
|
@@ -10,7 +10,7 @@ Você recebe: "Olá Maria Souza, ..."
|
|
|
10
10
|
```
|
|
11
11
|
|
|
12
12
|
- **Sem dependências e sem servidor:** roda no Node, no Deno, no Bun, no navegador e em edge functions.
|
|
13
|
-
- **Mesma detecção da versão em Python:** um teste de conformidade com
|
|
13
|
+
- **Mesma detecção da versão em Python:** um teste de conformidade com 300 casos garante resultados idênticos.
|
|
14
14
|
- **Funciona com o que você já usa:** SDKs da OpenAI e da Anthropic, AI SDK da Vercel e qualquer código que aceite um `fetch`.
|
|
15
15
|
|
|
16
16
|
```bash
|
|
@@ -74,7 +74,7 @@ Protege textos, argumentos de ferramentas e resultados de ferramentas, em `gener
|
|
|
74
74
|
## No navegador
|
|
75
75
|
|
|
76
76
|
```html
|
|
77
|
-
<script src="https://cdn.jsdelivr.net/npm/@guhttps/veu@0.
|
|
77
|
+
<script src="https://cdn.jsdelivr.net/npm/@guhttps/veu@0.6.0/dist/veu.global.js"></script>
|
|
78
78
|
<script>
|
|
79
79
|
const resultado = new veu.Veu().anonymize(document.querySelector("textarea").value);
|
|
80
80
|
</script>
|
|
@@ -88,13 +88,32 @@ new Veu({
|
|
|
88
88
|
labels: ["CPF", "CNPJ", "CHAVE_API"], // só estes tipos
|
|
89
89
|
allowlist: ["contato@minhaempresa.com.br"],
|
|
90
90
|
allowPatterns: ["@minhaempresa\\.com\\.br$"],
|
|
91
|
+
cache: 2048, // cache de textos longos (0 desliga); um Veu por cliente num servidor
|
|
91
92
|
detectors: ["padroes", "segredos"], // sem nomes e endereços
|
|
92
93
|
operator: "mascara", // token (padrão), mascara, remover ou hash
|
|
93
94
|
operators: { CARTAO_CREDITO: "remover" },
|
|
94
95
|
customPatterns: [{ entidade: "MATRICULA", padrao: "MAT-\\d{6}" }],
|
|
96
|
+
restore: { linkHosts: ["intranet.minhaempresa.com.br"] }, // veja "Restauração segura"
|
|
95
97
|
});
|
|
96
98
|
```
|
|
97
99
|
|
|
100
|
+
## Restauração segura
|
|
101
|
+
|
|
102
|
+
A IA pode ser induzida, por uma página ou um e-mail que ela leu, a escrever ``. Se o marcador virasse o CPF real ali, o navegador o enviaria ao site. Por isso, por padrão:
|
|
103
|
+
|
|
104
|
+
- os dados reais **não voltam dentro de links, imagens, URLs e atributos HTML**, nem em streaming;
|
|
105
|
+
- chaves de API, tokens e senhas **não voltam nos argumentos de ferramentas**;
|
|
106
|
+
- marcadores que já chegam no texto (`[CPF_1]` escrito por outra pessoa) são desarmados para `[CPF#1]`.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
new Veu({ restore: {
|
|
110
|
+
links: false, // true: restaura também dentro de links
|
|
111
|
+
linkHosts: ["empresa.com"], // links destes domínios recebem os dados reais
|
|
112
|
+
tools: true, // false: não restaura nenhum argumento de ferramenta
|
|
113
|
+
secretsInTools: false, // true: restaura chaves e senhas nos argumentos
|
|
114
|
+
} });
|
|
115
|
+
```
|
|
116
|
+
|
|
98
117
|
O operador `sintetico` (outro CPF válido no lugar do original) ainda só existe na versão em Python.
|
|
99
118
|
|
|
100
119
|
## O que é detectado
|
|
@@ -102,6 +121,8 @@ O operador `sintetico` (outro CPF válido no lugar do original) ainda só existe
|
|
|
102
121
|
- **Documentos:** CPF, CNPJ (inclusive o alfanumérico de 2026), RG, CNH, título de eleitor, PIS, CNS e passaporte.
|
|
103
122
|
- **Contatos:** nomes, telefones (brasileiros e internacionais), e-mails e endereços.
|
|
104
123
|
- **Dados financeiros e outros:** CEP, placa, RENAVAM, cartões, contas, IBAN, chave Pix, IP, data de nascimento e processo judicial.
|
|
124
|
+
- **Outros países:** Portugal (NIF, Cartão de Cidadão, NISS), Argentina (CUIT/CUIL, DNI), México (CURP, RFC), Chile e Uruguai (RUT, cédula), Colômbia (NIT), Peru, Equador e Paraguai (RUC), Venezuela (RIF), Angola e Moçambique (BI, NUIT), EUA (SSN, ITIN, Medicare), Espanha (DNI, NIE), Itália (codice fiscale), França (NIR), Alemanha (Steuer-ID), Reino Unido (National Insurance, NHS), Países Baixos (BSN), Canadá (SIN) e Índia (Aadhaar, PAN).
|
|
125
|
+
- **Passaportes, veículos e carteiras:** zona de leitura do passaporte (MRZ), chassi (VIN) e endereços de Bitcoin e Ethereum.
|
|
105
126
|
- **Segredos:**
|
|
106
127
|
- chaves de API da OpenAI, Anthropic, AWS, Google, GitHub, Stripe, Mercado Pago, Asaas, Notion e mais 20 serviços;
|
|
107
128
|
- JWT e tokens Bearer;
|
package/dist/analyzer.d.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
+
import { DetectionCache } from "./cache.ts";
|
|
1
2
|
import type { Candidate, Entity, Recognizer } from "./entities.ts";
|
|
2
3
|
export declare const DEFAULT_THRESHOLD = 0.5;
|
|
4
|
+
/**
|
|
5
|
+
* Texto para a detecção e, se algum caractere saiu, a posição original de cada um (mais uma no fim).
|
|
6
|
+
* Hífens e largura total são trocados um por um (as posições não mudam); só os invisíveis saem.
|
|
7
|
+
*/
|
|
8
|
+
export declare function normalizeForDetection(text: string): [string, number[] | null];
|
|
3
9
|
export declare function defaultRecognizers(): Recognizer[];
|
|
4
10
|
export interface AnalyzerOptions {
|
|
5
11
|
/** Pontuação mínima de 0 a 1 (padrão 0,5). */
|
|
@@ -10,9 +16,13 @@ export interface AnalyzerOptions {
|
|
|
10
16
|
allowlist?: Iterable<string>;
|
|
11
17
|
/** Expressões regulares: valores que casarem nunca são escondidos. */
|
|
12
18
|
allowPatterns?: Iterable<string | RegExp>;
|
|
19
|
+
/** Itens no cache de detecção de textos longos (padrão 2048; 0 desliga). */
|
|
20
|
+
cache?: number;
|
|
13
21
|
}
|
|
14
22
|
export declare class Analyzer {
|
|
15
23
|
recognizers: Recognizer[];
|
|
24
|
+
/** Cache de detecção (null quando desligado). */
|
|
25
|
+
readonly cache: DetectionCache | null;
|
|
16
26
|
threshold: number;
|
|
17
27
|
labels: Set<string> | null;
|
|
18
28
|
private allowText;
|
package/dist/analyzer.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Junta os detectores, filtra pela pontuação e resolve sobreposições (equivalente a veu/analyzer.py).
|
|
2
|
+
import { DetectionCache } from "./cache.js";
|
|
2
3
|
import { AddressRecognizer } from "./addresses.js";
|
|
3
4
|
import { PatternRecognizer } from "./patterns.js";
|
|
4
5
|
import { PersonRecognizer } from "./persons.js";
|
|
@@ -6,11 +7,46 @@ import { SecretRecognizer } from "./secrets.js";
|
|
|
6
7
|
import { bisectLeft, fold, onlyDigits } from "./text.js";
|
|
7
8
|
import { normalizeCnpj } from "./validators.js";
|
|
8
9
|
export const DEFAULT_THRESHOLD = 0.5;
|
|
10
|
+
// Caracteres que escondem um dado da detecção sem mudar o que a pessoa lê: invisíveis (largura zero, hífen
|
|
11
|
+
// invisível), hífens tipográficos ("529.982.247‑25" copiado do Word) e letras e dígitos de largura total.
|
|
12
|
+
const INVISIBLE = "\u00ad\u200b\u200c\u200d\u2060\ufeff";
|
|
13
|
+
const HYPHENS = "\u2010\u2011\u2012\u2013\u2212\ufe63\uff0d";
|
|
14
|
+
const SPECIAL = new RegExp(`[${INVISIBLE}${HYPHENS}\uff01-\uff5e]`, "u");
|
|
15
|
+
const SAME_LENGTH = new RegExp(`[${HYPHENS}\uff01-\uff5e]`, "gu");
|
|
16
|
+
const HAS_INVISIBLE = new RegExp(`[${INVISIBLE}]`, "u");
|
|
17
|
+
/**
|
|
18
|
+
* Texto para a detecção e, se algum caractere saiu, a posição original de cada um (mais uma no fim).
|
|
19
|
+
* Hífens e largura total são trocados um por um (as posições não mudam); só os invisíveis saem.
|
|
20
|
+
*/
|
|
21
|
+
export function normalizeForDetection(text) {
|
|
22
|
+
if (!SPECIAL.test(text))
|
|
23
|
+
return [text, null];
|
|
24
|
+
const swapped = text.replace(SAME_LENGTH, (char) => (HYPHENS.includes(char) ? "-" : String.fromCharCode(char.charCodeAt(0) - 0xfee0)));
|
|
25
|
+
if (!HAS_INVISIBLE.test(swapped))
|
|
26
|
+
return [swapped, null];
|
|
27
|
+
const positions = [];
|
|
28
|
+
for (let index = 0; index < swapped.length; index += 1)
|
|
29
|
+
if (!INVISIBLE.includes(swapped[index]))
|
|
30
|
+
positions.push(index);
|
|
31
|
+
const normalized = positions.map((index) => swapped[index]).join("");
|
|
32
|
+
positions.push(swapped.length);
|
|
33
|
+
return [normalized, positions];
|
|
34
|
+
}
|
|
35
|
+
function detect(analyzer, text, threshold) {
|
|
36
|
+
const [normalized, positions] = normalizeForDetection(text);
|
|
37
|
+
// Sem caracteres removidos, as posições do texto normalizado são as do original.
|
|
38
|
+
const chosen = resolveOverlaps(analyzer.candidates(normalized, threshold));
|
|
39
|
+
if (!positions)
|
|
40
|
+
return chosen;
|
|
41
|
+
return chosen.map((c) => ({ ...c, start: positions[c.start], end: positions[c.end - 1] + 1 }));
|
|
42
|
+
}
|
|
9
43
|
export function defaultRecognizers() {
|
|
10
44
|
return [new PatternRecognizer(), new PersonRecognizer(), new AddressRecognizer(), new SecretRecognizer()];
|
|
11
45
|
}
|
|
12
46
|
export class Analyzer {
|
|
13
47
|
recognizers;
|
|
48
|
+
/** Cache de detecção (null quando desligado). */
|
|
49
|
+
cache;
|
|
14
50
|
threshold;
|
|
15
51
|
labels;
|
|
16
52
|
allowText;
|
|
@@ -19,6 +55,8 @@ export class Analyzer {
|
|
|
19
55
|
hasAllowlist;
|
|
20
56
|
constructor(recognizers, options = {}) {
|
|
21
57
|
this.recognizers = recognizers ?? defaultRecognizers();
|
|
58
|
+
const size = options.cache ?? 2048;
|
|
59
|
+
this.cache = size > 0 ? new DetectionCache(size) : null;
|
|
22
60
|
this.threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
|
23
61
|
const labels = options.labels ? [...options.labels] : [];
|
|
24
62
|
this.labels = labels.length ? new Set(labels.map((label) => label.toUpperCase())) : null;
|
|
@@ -58,9 +96,19 @@ export class Analyzer {
|
|
|
58
96
|
return found;
|
|
59
97
|
}
|
|
60
98
|
analyze(text, threshold) {
|
|
99
|
+
const cache = this.cache && this.cache.usable(text) ? this.cache : null;
|
|
100
|
+
const extra = threshold === undefined ? "" : String(threshold);
|
|
101
|
+
if (cache) {
|
|
102
|
+
const found = cache.get(text, extra);
|
|
103
|
+
if (found)
|
|
104
|
+
return found.map((c) => ({ ...c, text: text.slice(c.start, c.end) }));
|
|
105
|
+
}
|
|
61
106
|
if (!text)
|
|
62
107
|
return [];
|
|
63
|
-
|
|
108
|
+
const chosen = detect(this, text, threshold);
|
|
109
|
+
if (cache)
|
|
110
|
+
cache.put(text, chosen, extra);
|
|
111
|
+
return chosen.map((c) => ({ ...c, text: text.slice(c.start, c.end) }));
|
|
64
112
|
}
|
|
65
113
|
}
|
|
66
114
|
/** Um candidato por trecho: o contido em outro maior sai; nas sobreposições vence a maior pontuação. */
|
package/dist/anonymizer.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { Analyzer } from "./analyzer.ts";
|
|
2
2
|
import { type Entity } from "./entities.ts";
|
|
3
|
-
import { Vault } from "./vault.ts";
|
|
3
|
+
import { Vault, type RestorePolicy } from "./vault.ts";
|
|
4
4
|
export declare const OPERATORS: Record<string, string>;
|
|
5
|
-
|
|
5
|
+
/** Versão menos precisa do valor, que ainda serve para análises (idade, região) e identifica menos. */
|
|
6
|
+
export declare function generalizeValue(label: string, value: string): string;
|
|
7
|
+
export type Operator = "token" | "mascara" | "remover" | "hash" | "generalizar";
|
|
6
8
|
export declare function normalizeOperator(name: string): Operator;
|
|
7
9
|
export declare function maskValue(label: string, value: string): string;
|
|
8
10
|
export interface Replacement {
|
|
@@ -25,6 +27,8 @@ export interface AnonymizerOptions {
|
|
|
25
27
|
operators?: Record<string, string>;
|
|
26
28
|
linkNames?: boolean;
|
|
27
29
|
secret?: Uint8Array | string;
|
|
30
|
+
/** Onde a restauração pode devolver os dados reais (padrão: fora de links e sem segredos em ferramentas). */
|
|
31
|
+
restore?: RestorePolicy;
|
|
28
32
|
}
|
|
29
33
|
export declare class Anonymizer {
|
|
30
34
|
readonly analyzer: Analyzer;
|
|
@@ -32,12 +36,20 @@ export declare class Anonymizer {
|
|
|
32
36
|
readonly operators: Record<string, Operator>;
|
|
33
37
|
readonly linkNames: boolean;
|
|
34
38
|
readonly secret?: Uint8Array | string;
|
|
39
|
+
readonly restorePolicy: RestorePolicy;
|
|
35
40
|
constructor(analyzer: Analyzer, options?: AnonymizerOptions);
|
|
36
41
|
newVault(): Vault;
|
|
37
|
-
|
|
42
|
+
/**
|
|
43
|
+
* neutralize (padrão true): desarma marcadores que já vêm no texto (`[CPF_1]` vira `[CPF#1]`), para que um
|
|
44
|
+
* marcador escrito por outra pessoa nunca vire um dado real na restauração.
|
|
45
|
+
*/
|
|
46
|
+
anonymize(text: string, vault?: Vault, neutralize?: boolean): AnonymizationResult;
|
|
38
47
|
/** Substitui um valor inteiro já sabido ser de um tipo (ex.: toda a coluna "cpf" de uma planilha). */
|
|
39
48
|
replaceValue(label: string, value: string, vault: Vault): string;
|
|
40
49
|
private replace;
|
|
41
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* Propaga nomes já detectados no mesmo texto: menções soltas ao primeiro nome, ao sobrenome ou ao nome inteiro,
|
|
52
|
+
* em qualquer caixa e com ou sem acento, recebem o mesmo marcador do nome completo. Nomes ambíguos não se propagam.
|
|
53
|
+
*/
|
|
42
54
|
private linkPartialNames;
|
|
43
55
|
}
|
package/dist/anonymizer.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SECRET_LABELS } from "./entities.js";
|
|
2
|
-
import { CONNECTORS, ambiguousNames } from "./persons.js";
|
|
2
|
+
import { CONNECTORS, ambiguousNames, capitalizedOnlyNames } from "./persons.js";
|
|
3
3
|
import { secretPrefix } from "./secrets.js";
|
|
4
|
+
import { parseDate } from "./validators.js";
|
|
4
5
|
import { bisectRight, counter, escapeRegex, fold } from "./text.js";
|
|
5
6
|
import { Vault } from "./vault.js";
|
|
6
7
|
export const OPERATORS = {
|
|
@@ -8,8 +9,56 @@ export const OPERATORS = {
|
|
|
8
9
|
mascara: "mascara parte do valor, como ***.982.247-**; não é reversível",
|
|
9
10
|
remover: "troca pelo tipo, como [CPF]; não é reversível",
|
|
10
11
|
hash: "marcador estável entre requisições, como [CPF_3fa2c1d9]; reversível com o mesmo cofre",
|
|
12
|
+
generalizar: "guarda só o que serve para análise (ano de nascimento, região do CEP, DDD, rede do IP) e troca o resto pelo tipo; não é reversível",
|
|
11
13
|
};
|
|
12
|
-
const ALIASES = {
|
|
14
|
+
const ALIASES = {
|
|
15
|
+
marcador: "token", "máscara": "mascara", mask: "mascara", redact: "remover", generalize: "generalizar",
|
|
16
|
+
};
|
|
17
|
+
/** Versão menos precisa do valor, que ainda serve para análises (idade, região) e identifica menos. */
|
|
18
|
+
export function generalizeValue(label, value) {
|
|
19
|
+
const digits = value.replace(/\D/g, "");
|
|
20
|
+
if (label === "DATA_NASCIMENTO") {
|
|
21
|
+
const parsed = parseDate(value);
|
|
22
|
+
if (parsed)
|
|
23
|
+
return String(parsed.getUTCFullYear());
|
|
24
|
+
}
|
|
25
|
+
else if (label === "CEP" && digits.length === 8) {
|
|
26
|
+
return `${digits.slice(0, 5)}-***`;
|
|
27
|
+
}
|
|
28
|
+
else if (label === "TELEFONE") {
|
|
29
|
+
const country = /^\s*\+(\d{1,3})/.exec(value);
|
|
30
|
+
if (country && country[1] !== "55")
|
|
31
|
+
return `+${country[1]} ****`;
|
|
32
|
+
const local = (digits.length === 12 || digits.length === 13) && digits.startsWith("55") ? digits.slice(2) : digits;
|
|
33
|
+
if (local.length === 10 || local.length === 11)
|
|
34
|
+
return `(${local.slice(0, 2)}) ****-****`;
|
|
35
|
+
}
|
|
36
|
+
else if (label === "IP") {
|
|
37
|
+
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(value))
|
|
38
|
+
return `${value.split(".").slice(0, 3).join(".")}.0/24`;
|
|
39
|
+
if (value.includes(":")) {
|
|
40
|
+
const network = ipv6Network48(value);
|
|
41
|
+
if (network)
|
|
42
|
+
return network;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return `[${label}]`;
|
|
46
|
+
}
|
|
47
|
+
/** Rede /48 de um IPv6, no formato do ipaddress do Python ("2001:db8:85a3::/48"). */
|
|
48
|
+
function ipv6Network48(value) {
|
|
49
|
+
const [head, tail = ""] = value.split("::");
|
|
50
|
+
const left = head ? head.split(":") : [];
|
|
51
|
+
const right = value.includes("::") ? (tail ? tail.split(":") : []) : [];
|
|
52
|
+
if (!value.includes("::") && left.length !== 8)
|
|
53
|
+
return null;
|
|
54
|
+
const groups = [...left, ...Array(8 - left.length - right.length).fill("0"), ...right];
|
|
55
|
+
if (groups.length !== 8 || groups.some((group) => !/^[0-9a-fA-F]{1,4}$/.test(group)))
|
|
56
|
+
return null;
|
|
57
|
+
const first = groups.slice(0, 3).map((group) => parseInt(group, 16).toString(16));
|
|
58
|
+
while (first.length && first[first.length - 1] === "0")
|
|
59
|
+
first.pop();
|
|
60
|
+
return `${first.join(":")}::/48`;
|
|
61
|
+
}
|
|
13
62
|
export function normalizeOperator(name) {
|
|
14
63
|
const key = name.trim().toLowerCase();
|
|
15
64
|
const resolved = ALIASES[key] ?? key;
|
|
@@ -23,11 +72,12 @@ export function normalizeOperator(name) {
|
|
|
23
72
|
}
|
|
24
73
|
export function maskValue(label, value) {
|
|
25
74
|
if (label === "CPF") {
|
|
26
|
-
const
|
|
75
|
+
const digit = /\p{Nd}/u; // inclui dígitos de largura total, como o isdigit() do Python
|
|
76
|
+
const digits = [...value].filter((char) => digit.test(char));
|
|
27
77
|
if (digits.length === 11) {
|
|
28
78
|
let index = 0;
|
|
29
79
|
return [...value].map((char) => {
|
|
30
|
-
if (
|
|
80
|
+
if (!digit.test(char))
|
|
31
81
|
return char;
|
|
32
82
|
const visible = index >= 3 && index < 9;
|
|
33
83
|
index += 1;
|
|
@@ -73,23 +123,60 @@ export class AnonymizationResult {
|
|
|
73
123
|
return this.vault.restore(text);
|
|
74
124
|
}
|
|
75
125
|
}
|
|
126
|
+
// Palavras de nome (letras, com apóstrofo): a mesma definição do detector de nomes.
|
|
127
|
+
const NAME_WORD = /[A-Za-zÀ-ÖØ-öø-ÿ]+(?:['’][A-Za-zÀ-ÖØ-öø-ÿ]+)*/gu;
|
|
128
|
+
const WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
129
|
+
/** Sequências de palavras cuja forma normalizada está em parts (a mais longa primeiro), com custo linear. */
|
|
130
|
+
function findNames(text, parts) {
|
|
131
|
+
const longest = Math.max(...[...parts.keys()].map((key) => key.split(" ").length));
|
|
132
|
+
const words = [...text.matchAll(NAME_WORD)].map((m) => [m.index, m.index + m[0].length, fold(m[0])]);
|
|
133
|
+
const found = [];
|
|
134
|
+
let index = 0;
|
|
135
|
+
while (index < words.length) {
|
|
136
|
+
let matched = 0;
|
|
137
|
+
for (let size = Math.min(longest, words.length - index); size > 0; size -= 1) {
|
|
138
|
+
const chunk = words.slice(index, index + size);
|
|
139
|
+
if (chunk.slice(1).some((word, i) => !/^\s+$/u.test(text.slice(chunk[i][1], word[0]))))
|
|
140
|
+
continue;
|
|
141
|
+
const start = chunk[0][0];
|
|
142
|
+
const end = chunk[chunk.length - 1][1];
|
|
143
|
+
if ((start > 0 && WORD_CHAR.test(text[start - 1])) || (end < text.length && WORD_CHAR.test(text[end])))
|
|
144
|
+
continue;
|
|
145
|
+
if (parts.has(chunk.map((word) => word[2]).join(" "))) {
|
|
146
|
+
found.push([start, end]);
|
|
147
|
+
matched = size;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
index += matched || 1;
|
|
152
|
+
}
|
|
153
|
+
return found;
|
|
154
|
+
}
|
|
76
155
|
export class Anonymizer {
|
|
77
156
|
analyzer;
|
|
78
157
|
operator;
|
|
79
158
|
operators;
|
|
80
159
|
linkNames;
|
|
81
160
|
secret;
|
|
161
|
+
restorePolicy;
|
|
82
162
|
constructor(analyzer, options = {}) {
|
|
83
163
|
this.analyzer = analyzer;
|
|
84
164
|
this.operator = normalizeOperator(options.operator ?? "token");
|
|
85
165
|
this.operators = Object.fromEntries(Object.entries(options.operators ?? {}).map(([label, op]) => [label.toUpperCase(), normalizeOperator(op)]));
|
|
86
166
|
this.linkNames = options.linkNames ?? true;
|
|
87
167
|
this.secret = options.secret;
|
|
168
|
+
this.restorePolicy = options.restore ?? {};
|
|
88
169
|
}
|
|
89
170
|
newVault() {
|
|
90
|
-
return new Vault(this.secret);
|
|
171
|
+
return new Vault(this.secret, this.restorePolicy);
|
|
91
172
|
}
|
|
92
|
-
|
|
173
|
+
/**
|
|
174
|
+
* neutralize (padrão true): desarma marcadores que já vêm no texto (`[CPF_1]` vira `[CPF#1]`), para que um
|
|
175
|
+
* marcador escrito por outra pessoa nunca vire um dado real na restauração.
|
|
176
|
+
*/
|
|
177
|
+
anonymize(text, vault = this.newVault(), neutralize = true) {
|
|
178
|
+
if (neutralize)
|
|
179
|
+
text = vault.neutralize(text);
|
|
93
180
|
let entities = this.analyzer.analyze(text);
|
|
94
181
|
let canonical = new Map();
|
|
95
182
|
if (this.linkNames && entities.length)
|
|
@@ -125,48 +212,63 @@ export class Anonymizer {
|
|
|
125
212
|
return vault.placeholder(entity.label, entity.text, true);
|
|
126
213
|
if (operator === "mascara")
|
|
127
214
|
return maskValue(entity.label, entity.text);
|
|
215
|
+
if (operator === "generalizar")
|
|
216
|
+
return generalizeValue(entity.label, entity.text);
|
|
128
217
|
return `[${entity.label}]`;
|
|
129
218
|
}
|
|
130
|
-
/**
|
|
219
|
+
/**
|
|
220
|
+
* Propaga nomes já detectados no mesmo texto: menções soltas ao primeiro nome, ao sobrenome ou ao nome inteiro,
|
|
221
|
+
* em qualquer caixa e com ou sem acento, recebem o mesmo marcador do nome completo. Nomes ambíguos não se propagam.
|
|
222
|
+
*/
|
|
131
223
|
linkPartialNames(text, entities) {
|
|
132
224
|
const ambiguous = ambiguousNames();
|
|
225
|
+
const capitalizedOnly = capitalizedOnlyNames();
|
|
133
226
|
const parts = new Map();
|
|
134
|
-
|
|
135
|
-
|
|
227
|
+
// Nomes completos primeiro: "Ana" sozinho, antes de "Ana Beatriz Moura", usa o marcador do nome completo.
|
|
228
|
+
const byLength = [...entities].sort((a, b) => b.text.split(/\s+/).length - a.text.split(/\s+/).length);
|
|
229
|
+
for (const entity of byLength) {
|
|
230
|
+
if (entity.label !== "PESSOA" || entity.score < 0.6)
|
|
136
231
|
continue;
|
|
137
232
|
const words = entity.text.split(/\s+/).filter((word) => word && !CONNECTORS.has(fold(word)));
|
|
138
|
-
if (words.length
|
|
233
|
+
if (!words.length)
|
|
139
234
|
continue;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
235
|
+
let linked;
|
|
236
|
+
if (words.length >= 2) {
|
|
237
|
+
if (!parts.has(fold(entity.text)))
|
|
238
|
+
parts.set(fold(entity.text), entity.text);
|
|
239
|
+
linked = [words[0], words[words.length - 1]].filter((word) => word[0] !== word[0].toLowerCase());
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
linked = words;
|
|
243
|
+
}
|
|
244
|
+
for (const word of linked) {
|
|
245
|
+
if ([...word].length >= 3 && !ambiguous.has(fold(word)) && !parts.has(fold(word)))
|
|
246
|
+
parts.set(fold(word), entity.text);
|
|
144
247
|
}
|
|
145
248
|
}
|
|
146
249
|
const canonical = new Map();
|
|
147
250
|
if (!parts.size)
|
|
148
251
|
return [entities, canonical];
|
|
149
|
-
const alternatives = [...parts.keys()].sort((a, b) => b.length - a.length).map(escapeRegex).join("|");
|
|
150
|
-
const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives})(?![\\p{L}\\p{N}_])`, "gu");
|
|
151
252
|
const added = [];
|
|
152
253
|
const starts = entities.map((e) => e.start);
|
|
153
254
|
const ends = entities.map((e) => e.end);
|
|
154
|
-
for (const
|
|
155
|
-
const start = match.index;
|
|
156
|
-
const end = start + match[0].length;
|
|
255
|
+
for (const [start, end] of findNames(text, parts)) {
|
|
157
256
|
const position = bisectRight(starts, start);
|
|
158
257
|
if (position > 0 && ends[position - 1] > start)
|
|
159
258
|
continue;
|
|
160
259
|
if (position < starts.length && starts[position] < end)
|
|
161
260
|
continue;
|
|
162
|
-
|
|
163
|
-
|
|
261
|
+
const key = fold(text.slice(start, end));
|
|
262
|
+
// "Costa" é a pessoa; "costa" (o litoral) e "data de nascimento", não.
|
|
263
|
+
if (capitalizedOnly.has(key) && text[start] === text[start].toLowerCase())
|
|
264
|
+
continue;
|
|
265
|
+
added.push({ label: "PESSOA", start, end, score: 0.7, recognizer: "vinculo", text: text.slice(start, end) });
|
|
266
|
+
canonical.set(start, parts.get(key));
|
|
164
267
|
}
|
|
165
|
-
const byFolded = new Map([...parts.entries()].map(([word, full]) => [fold(word), full]));
|
|
166
268
|
for (const entity of entities) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
269
|
+
const full = entity.label === "PESSOA" ? parts.get(fold(entity.text)) : undefined;
|
|
270
|
+
if (full !== undefined && full !== entity.text)
|
|
271
|
+
canonical.set(entity.start, full);
|
|
170
272
|
}
|
|
171
273
|
return [[...entities, ...added].sort((a, b) => a.start - b.start), canonical];
|
|
172
274
|
}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Candidate } from "./entities.ts";
|
|
2
|
+
export declare class DetectionCache {
|
|
3
|
+
readonly maxEntries: number;
|
|
4
|
+
readonly minChars: number;
|
|
5
|
+
hits: number;
|
|
6
|
+
misses: number;
|
|
7
|
+
private readonly salt;
|
|
8
|
+
private readonly items;
|
|
9
|
+
private readonly encoder;
|
|
10
|
+
constructor(maxEntries?: number, minChars?: number);
|
|
11
|
+
usable(text: string): boolean;
|
|
12
|
+
private key;
|
|
13
|
+
get(text: string, extra?: string): readonly Candidate[] | undefined;
|
|
14
|
+
put(text: string, candidates: readonly Candidate[], extra?: string): void;
|
|
15
|
+
clear(): void;
|
|
16
|
+
get size(): number;
|
|
17
|
+
}
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { hmacSha256, toHex } from "./sha256.js";
|
|
2
|
+
export class DetectionCache {
|
|
3
|
+
maxEntries;
|
|
4
|
+
minChars;
|
|
5
|
+
hits = 0;
|
|
6
|
+
misses = 0;
|
|
7
|
+
salt;
|
|
8
|
+
items = new Map();
|
|
9
|
+
encoder = new TextEncoder();
|
|
10
|
+
constructor(maxEntries = 2048, minChars = 256) {
|
|
11
|
+
this.maxEntries = maxEntries;
|
|
12
|
+
this.minChars = minChars;
|
|
13
|
+
const salt = new Uint8Array(32);
|
|
14
|
+
globalThis.crypto.getRandomValues(salt);
|
|
15
|
+
this.salt = salt;
|
|
16
|
+
}
|
|
17
|
+
usable(text) {
|
|
18
|
+
return this.maxEntries > 0 && text.length >= this.minChars;
|
|
19
|
+
}
|
|
20
|
+
key(text, extra) {
|
|
21
|
+
return toHex(hmacSha256(this.salt, this.encoder.encode(`${extra}\u0000${text}`))).slice(0, 32);
|
|
22
|
+
}
|
|
23
|
+
get(text, extra = "") {
|
|
24
|
+
const key = this.key(text, extra);
|
|
25
|
+
const found = this.items.get(key);
|
|
26
|
+
if (found === undefined) {
|
|
27
|
+
this.misses += 1;
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
this.items.delete(key);
|
|
31
|
+
this.items.set(key, found);
|
|
32
|
+
this.hits += 1;
|
|
33
|
+
return found;
|
|
34
|
+
}
|
|
35
|
+
put(text, candidates, extra = "") {
|
|
36
|
+
const key = this.key(text, extra);
|
|
37
|
+
this.items.delete(key);
|
|
38
|
+
this.items.set(key, candidates.map((c) => ({ label: c.label, start: c.start, end: c.end, score: c.score, recognizer: c.recognizer })));
|
|
39
|
+
while (this.items.size > this.maxEntries)
|
|
40
|
+
this.items.delete(this.items.keys().next().value);
|
|
41
|
+
}
|
|
42
|
+
clear() {
|
|
43
|
+
this.items.clear();
|
|
44
|
+
}
|
|
45
|
+
get size() {
|
|
46
|
+
return this.items.size;
|
|
47
|
+
}
|
|
48
|
+
}
|
package/dist/data.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const firstNames: readonly string[];
|
|
2
2
|
export declare const surnames: readonly string[];
|
|
3
3
|
export declare const ambiguous: readonly string[];
|
|
4
|
+
export declare const ibgeAmbiguous: readonly string[];
|
|
4
5
|
export declare const stopwords: readonly string[];
|
|
5
6
|
export declare const places: readonly string[];
|
|
6
7
|
export declare const organizations: readonly string[];
|
|
@@ -14,3 +15,12 @@ export interface SecretRuleData {
|
|
|
14
15
|
aparar?: string;
|
|
15
16
|
}
|
|
16
17
|
export declare const secretRules: readonly SecretRuleData[];
|
|
18
|
+
export interface GroupData {
|
|
19
|
+
id: string;
|
|
20
|
+
titulo: string;
|
|
21
|
+
titulo_en: string;
|
|
22
|
+
exemplo: string;
|
|
23
|
+
exemplo_en: string;
|
|
24
|
+
tipos: string[];
|
|
25
|
+
}
|
|
26
|
+
export declare const groups: readonly GroupData[];
|