@guhttps/veu 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data.d.ts +9 -0
- package/dist/data.js +125 -0
- package/dist/entities.d.ts +2 -0
- package/dist/entities.js +4 -0
- package/dist/gateway.d.ts +4 -4
- package/dist/gateway.js +39 -14
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/patterns.js +22 -3
- package/dist/validators.d.ts +2 -0
- package/dist/validators.js +4 -0
- package/dist/vault.d.ts +14 -4
- package/dist/vault.js +38 -9
- package/dist/veu.global.js +13 -13
- package/package.json +1 -1
package/dist/data.d.ts
CHANGED
|
@@ -15,3 +15,12 @@ export interface SecretRuleData {
|
|
|
15
15
|
aparar?: string;
|
|
16
16
|
}
|
|
17
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[];
|
package/dist/data.js
CHANGED
|
@@ -248,3 +248,128 @@ export const secretRules = [
|
|
|
248
248
|
"padrao": "(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{1,20}://[^\\s:/@'\"<>]{1,128}:[^\\s@'\"<>/]{1,256}@[^\\s'\"<>)\\]},;]+"
|
|
249
249
|
}
|
|
250
250
|
];
|
|
251
|
+
export const groups = [
|
|
252
|
+
{
|
|
253
|
+
"id": "pessoas",
|
|
254
|
+
"titulo": "Nomes e contatos",
|
|
255
|
+
"titulo_en": "Names and contacts",
|
|
256
|
+
"exemplo": "nomes, telefones, e-mails, endereços, CEP, datas de nascimento",
|
|
257
|
+
"exemplo_en": "names, phone numbers, e-mails, addresses, postal codes, dates of birth",
|
|
258
|
+
"tipos": [
|
|
259
|
+
"PESSOA",
|
|
260
|
+
"TELEFONE",
|
|
261
|
+
"EMAIL",
|
|
262
|
+
"ENDERECO",
|
|
263
|
+
"CEP",
|
|
264
|
+
"DATA_NASCIMENTO"
|
|
265
|
+
]
|
|
266
|
+
},
|
|
267
|
+
{
|
|
268
|
+
"id": "documentos",
|
|
269
|
+
"titulo": "Documentos",
|
|
270
|
+
"titulo_en": "Brazilian documents",
|
|
271
|
+
"exemplo": "CPF, CNPJ, RG, CNH, título de eleitor, PIS, cartão do SUS, passaporte, processos",
|
|
272
|
+
"exemplo_en": "CPF, CNPJ, RG, driver's license, voter ID, PIS, SUS card, passport, lawsuit numbers",
|
|
273
|
+
"tipos": [
|
|
274
|
+
"CPF",
|
|
275
|
+
"CNPJ",
|
|
276
|
+
"RG",
|
|
277
|
+
"CNH",
|
|
278
|
+
"TITULO_ELEITOR",
|
|
279
|
+
"PIS",
|
|
280
|
+
"CNS",
|
|
281
|
+
"PASSAPORTE",
|
|
282
|
+
"PROCESSO"
|
|
283
|
+
]
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
"id": "estrangeiros",
|
|
287
|
+
"titulo": "Documentos de outros países",
|
|
288
|
+
"titulo_en": "Documents from other countries",
|
|
289
|
+
"exemplo": "Portugal, América Latina, Angola e Moçambique, EUA (SSN), Europa (DNI, codice fiscale, NIR, NINO), Canadá, Índia e passaportes (MRZ)",
|
|
290
|
+
"exemplo_en": "Portugal, Latin America, Angola and Mozambique, US (SSN), Europe (DNI, codice fiscale, NIR, NINO), Canada, India and passports (MRZ)",
|
|
291
|
+
"tipos": [
|
|
292
|
+
"NIF_PT",
|
|
293
|
+
"CC_PT",
|
|
294
|
+
"NISS_PT",
|
|
295
|
+
"CUIT",
|
|
296
|
+
"DNI",
|
|
297
|
+
"CURP",
|
|
298
|
+
"RFC",
|
|
299
|
+
"RUT",
|
|
300
|
+
"CEDULA",
|
|
301
|
+
"NIT",
|
|
302
|
+
"RUC",
|
|
303
|
+
"RIF",
|
|
304
|
+
"NUIT",
|
|
305
|
+
"BI_AO",
|
|
306
|
+
"BI_MZ",
|
|
307
|
+
"SSN",
|
|
308
|
+
"MBI",
|
|
309
|
+
"DNI_ES",
|
|
310
|
+
"CODICE_FISCALE",
|
|
311
|
+
"NIR",
|
|
312
|
+
"STEUER_ID",
|
|
313
|
+
"NINO",
|
|
314
|
+
"NHS",
|
|
315
|
+
"BSN",
|
|
316
|
+
"SIN",
|
|
317
|
+
"AADHAAR",
|
|
318
|
+
"PAN",
|
|
319
|
+
"MRZ"
|
|
320
|
+
]
|
|
321
|
+
},
|
|
322
|
+
{
|
|
323
|
+
"id": "financeiro",
|
|
324
|
+
"titulo": "Dados financeiros",
|
|
325
|
+
"titulo_en": "Financial data",
|
|
326
|
+
"exemplo": "cartões, contas bancárias, chave Pix, IBAN, carteiras de criptomoeda",
|
|
327
|
+
"exemplo_en": "cards, bank accounts, Pix keys, IBAN, crypto wallets",
|
|
328
|
+
"tipos": [
|
|
329
|
+
"CARTAO_CREDITO",
|
|
330
|
+
"CONTA_BANCARIA",
|
|
331
|
+
"CHAVE_PIX",
|
|
332
|
+
"IBAN",
|
|
333
|
+
"CRIPTO"
|
|
334
|
+
]
|
|
335
|
+
},
|
|
336
|
+
{
|
|
337
|
+
"id": "segredos",
|
|
338
|
+
"titulo": "Senhas e chaves de acesso",
|
|
339
|
+
"titulo_en": "Passwords and access keys",
|
|
340
|
+
"exemplo": "senhas, chaves de API, tokens, chaves privadas",
|
|
341
|
+
"exemplo_en": "passwords, API keys, tokens, private keys",
|
|
342
|
+
"tipos": [
|
|
343
|
+
"CHAVE_API",
|
|
344
|
+
"TOKEN",
|
|
345
|
+
"SENHA",
|
|
346
|
+
"CHAVE_PRIVADA",
|
|
347
|
+
"URL_CONEXAO",
|
|
348
|
+
"SEGREDO"
|
|
349
|
+
]
|
|
350
|
+
},
|
|
351
|
+
{
|
|
352
|
+
"id": "infra",
|
|
353
|
+
"titulo": "Infraestrutura de TI",
|
|
354
|
+
"titulo_en": "IT infrastructure",
|
|
355
|
+
"exemplo": "endereços IP, portas e nomes de servidores internos",
|
|
356
|
+
"exemplo_en": "IP addresses, ports and internal server names",
|
|
357
|
+
"tipos": [
|
|
358
|
+
"IP",
|
|
359
|
+
"PORTA",
|
|
360
|
+
"SERVIDOR"
|
|
361
|
+
]
|
|
362
|
+
},
|
|
363
|
+
{
|
|
364
|
+
"id": "outros",
|
|
365
|
+
"titulo": "Veículos",
|
|
366
|
+
"titulo_en": "Vehicles",
|
|
367
|
+
"exemplo": "placas, RENAVAM, chassi (VIN)",
|
|
368
|
+
"exemplo_en": "license plates, RENAVAM, VIN",
|
|
369
|
+
"tipos": [
|
|
370
|
+
"PLACA",
|
|
371
|
+
"RENAVAM",
|
|
372
|
+
"VIN"
|
|
373
|
+
]
|
|
374
|
+
}
|
|
375
|
+
];
|
package/dist/entities.d.ts
CHANGED
|
@@ -18,3 +18,5 @@ export interface Recognizer {
|
|
|
18
18
|
labels: ReadonlySet<string>;
|
|
19
19
|
find(text: string): Iterable<Candidate>;
|
|
20
20
|
}
|
|
21
|
+
/** Grupos de tipos para caixinhas de escolha (os mesmos do painel): cada tipo fica em exatamente um grupo. */
|
|
22
|
+
export { groups as GROUPS, type GroupData } from "./data.ts";
|
package/dist/entities.js
CHANGED
|
@@ -52,6 +52,8 @@ export const LABELS = {
|
|
|
52
52
|
MRZ: "Zona de leitura de passaporte (MRZ)",
|
|
53
53
|
VIN: "Chassi (VIN)",
|
|
54
54
|
CRIPTO: "Carteira de criptomoeda (Bitcoin, Ethereum)",
|
|
55
|
+
PORTA: "Porta de rede",
|
|
56
|
+
SERVIDOR: "Nome de servidor interno",
|
|
55
57
|
CHAVE_API: "Chave de API ou token de serviço (OpenAI, AWS, GitHub...)",
|
|
56
58
|
TOKEN: "Token de acesso (JWT, Bearer)",
|
|
57
59
|
SENHA: "Senha",
|
|
@@ -62,3 +64,5 @@ export const LABELS = {
|
|
|
62
64
|
export const SECRET_LABELS = new Set([
|
|
63
65
|
"CHAVE_API", "TOKEN", "SENHA", "CHAVE_PRIVADA", "URL_CONEXAO", "SEGREDO",
|
|
64
66
|
]);
|
|
67
|
+
/** Grupos de tipos para caixinhas de escolha (os mesmos do painel): cada tipo fica em exatamente um grupo. */
|
|
68
|
+
export { groups as GROUPS } from "./data.js";
|
package/dist/gateway.d.ts
CHANGED
|
@@ -14,21 +14,21 @@ export declare class Masker {
|
|
|
14
14
|
jsonString(value: Json): Json;
|
|
15
15
|
obj(value: Json): Json;
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
export declare function restoreObj(value: Json, vault: Vault, tool?: boolean): Json;
|
|
17
|
+
export declare function restoreObj(value: Json, vault: Vault, tool?: boolean, toolName?: string): Json;
|
|
19
18
|
/** Argumentos de ferramenta em texto JSON: restaura os valores sem quebrar o JSON. */
|
|
20
|
-
export declare function restoreJsonString(value: string, vault: Vault, tool?: boolean): string;
|
|
19
|
+
export declare function restoreJsonString(value: string, vault: Vault, tool?: boolean, toolName?: string): string;
|
|
21
20
|
/** Um restaurador por campo de texto do stream (cada escolha, bloco ou argumento de ferramenta). */
|
|
22
21
|
export declare class StreamState {
|
|
23
22
|
readonly vault: Vault;
|
|
24
23
|
readonly meta: Record<string, Json>;
|
|
24
|
+
readonly toolNames: Map<string, string>;
|
|
25
25
|
private restorers;
|
|
26
26
|
constructor(vault: Vault);
|
|
27
27
|
/** tool: o texto é argumento de ferramenta (padrão: igual a jsonEscape). */
|
|
28
28
|
feed(key: Json[], text: string, jsonEscape?: boolean, tool?: boolean): string;
|
|
29
29
|
flush(key: Json[]): string;
|
|
30
30
|
pendingKeys(): Json[][];
|
|
31
|
-
restore(value: Json): Json;
|
|
31
|
+
restore(value: Json, toolName?: string): Json;
|
|
32
32
|
}
|
|
33
33
|
export declare abstract class Adapter {
|
|
34
34
|
abstract name: string;
|
package/dist/gateway.js
CHANGED
|
@@ -48,44 +48,55 @@ const TOOL_KEYS = new Set(["arguments", "partial_json", "args", "functionCall",
|
|
|
48
48
|
const TOOL_TYPES = new Set(["tool_use", "server_tool_use", "function_call", "custom_tool_call", "local_shell_call",
|
|
49
49
|
"response.custom_tool_call_input.done", "response.function_call_arguments.done"]);
|
|
50
50
|
/** Restaura todos os textos de uma resposta JSON. tool: o valor é argumento de uma chamada de ferramenta. */
|
|
51
|
-
|
|
51
|
+
/** O nome da ferramenta de uma chamada: {name, arguments|input|args} em todas as APIs. */
|
|
52
|
+
function toolNameOf(value, inherited) {
|
|
53
|
+
if (value.type === "local_shell_call")
|
|
54
|
+
return "local_shell";
|
|
55
|
+
if (typeof value.name === "string" && ("arguments" in value || "input" in value || "args" in value))
|
|
56
|
+
return value.name;
|
|
57
|
+
return inherited;
|
|
58
|
+
}
|
|
59
|
+
export function restoreObj(value, vault, tool = false, toolName) {
|
|
52
60
|
if (typeof value === "string")
|
|
53
|
-
return vault.restore(value, false, { tool });
|
|
61
|
+
return vault.restore(value, false, { tool, toolName: tool ? toolName : undefined });
|
|
54
62
|
if (Array.isArray(value))
|
|
55
|
-
return value.map((item) => restoreObj(item, vault, tool));
|
|
63
|
+
return value.map((item) => restoreObj(item, vault, tool, toolName));
|
|
56
64
|
if (isObject(value)) {
|
|
57
65
|
if (UNTOUCHED_TYPES.has(value.type))
|
|
58
66
|
return value;
|
|
59
67
|
const call = TOOL_TYPES.has(value.type);
|
|
68
|
+
const name = toolNameOf(value, toolName);
|
|
60
69
|
const restored = {};
|
|
61
70
|
for (const [key, item] of Object.entries(value)) {
|
|
62
71
|
const inTool = tool || TOOL_KEYS.has(key) || (call && (key === "input" || key === "arguments"));
|
|
63
72
|
if (UNTOUCHED_KEYS.has(key))
|
|
64
73
|
restored[key] = item;
|
|
65
74
|
else if ((key === "arguments" || key === "partial_json") && typeof item === "string")
|
|
66
|
-
restored[key] = restoreJsonString(item, vault);
|
|
75
|
+
restored[key] = restoreJsonString(item, vault, true, name);
|
|
67
76
|
else
|
|
68
|
-
restored[key] = restoreObj(item, vault, inTool);
|
|
77
|
+
restored[key] = restoreObj(item, vault, inTool, name);
|
|
69
78
|
}
|
|
70
79
|
return restored;
|
|
71
80
|
}
|
|
72
81
|
return value;
|
|
73
82
|
}
|
|
74
83
|
/** Argumentos de ferramenta em texto JSON: restaura os valores sem quebrar o JSON. */
|
|
75
|
-
export function restoreJsonString(value, vault, tool = true) {
|
|
84
|
+
export function restoreJsonString(value, vault, tool = true, toolName) {
|
|
76
85
|
let parsed;
|
|
77
86
|
try {
|
|
78
87
|
parsed = JSON.parse(value);
|
|
79
88
|
}
|
|
80
89
|
catch {
|
|
81
|
-
return vault.restore(value, true, { tool });
|
|
90
|
+
return vault.restore(value, true, { tool, toolName });
|
|
82
91
|
}
|
|
83
|
-
return JSON.stringify(restoreObj(parsed, vault, tool));
|
|
92
|
+
return JSON.stringify(restoreObj(parsed, vault, tool, toolName));
|
|
84
93
|
}
|
|
85
94
|
/** Um restaurador por campo de texto do stream (cada escolha, bloco ou argumento de ferramenta). */
|
|
86
95
|
export class StreamState {
|
|
87
96
|
vault;
|
|
88
97
|
meta = {};
|
|
98
|
+
// Nome da ferramenta de cada campo de argumentos do stream (chega antes dos argumentos, num evento à parte).
|
|
99
|
+
toolNames = new Map();
|
|
89
100
|
restorers = new Map();
|
|
90
101
|
constructor(vault) {
|
|
91
102
|
this.vault = vault;
|
|
@@ -95,7 +106,7 @@ export class StreamState {
|
|
|
95
106
|
const id = JSON.stringify(key);
|
|
96
107
|
let entry = this.restorers.get(id);
|
|
97
108
|
if (!entry) {
|
|
98
|
-
entry = { key, restorer: this.vault.restorer(jsonEscape, tool) };
|
|
109
|
+
entry = { key, restorer: this.vault.restorer(jsonEscape, tool, this.toolNames.get(id)) };
|
|
99
110
|
this.restorers.set(id, entry);
|
|
100
111
|
}
|
|
101
112
|
return entry.restorer.feed(text);
|
|
@@ -109,8 +120,8 @@ export class StreamState {
|
|
|
109
120
|
pendingKeys() {
|
|
110
121
|
return [...this.restorers.values()].filter((entry) => entry.restorer.pending).map((entry) => entry.key);
|
|
111
122
|
}
|
|
112
|
-
restore(value) {
|
|
113
|
-
return restoreObj(value, this.vault);
|
|
123
|
+
restore(value, toolName) {
|
|
124
|
+
return restoreObj(value, this.vault, false, toolName);
|
|
114
125
|
}
|
|
115
126
|
}
|
|
116
127
|
export class Adapter {
|
|
@@ -186,8 +197,11 @@ export class OpenAIChatAdapter extends Adapter {
|
|
|
186
197
|
delta[field] = state.feed(["c", index, field], delta[field]);
|
|
187
198
|
}
|
|
188
199
|
for (const call of delta.tool_calls ?? []) {
|
|
200
|
+
const key = ["t", index, call?.index ?? 0];
|
|
201
|
+
if (typeof call?.function?.name === "string")
|
|
202
|
+
state.toolNames.set(JSON.stringify(key), call.function.name);
|
|
189
203
|
if (typeof call?.function?.arguments === "string") {
|
|
190
|
-
call.function.arguments = state.feed(
|
|
204
|
+
call.function.arguments = state.feed(key, call.function.arguments, true);
|
|
191
205
|
}
|
|
192
206
|
}
|
|
193
207
|
if (choice.finish_reason)
|
|
@@ -319,6 +333,13 @@ export class OpenAIResponsesAdapter extends Adapter {
|
|
|
319
333
|
if (!isObject(data))
|
|
320
334
|
return [[name, data]];
|
|
321
335
|
const kind = data.type;
|
|
336
|
+
if (kind === "response.output_item.added" && isObject(data.item)) {
|
|
337
|
+
const name = data.item.type === "local_shell_call" ? "local_shell" : data.item.name;
|
|
338
|
+
if (typeof name === "string") {
|
|
339
|
+
for (const prefix of ["f", "c"])
|
|
340
|
+
state.toolNames.set(JSON.stringify([prefix, data.output_index ?? 0]), name);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
322
343
|
if (kind === "response.output_text.delta") {
|
|
323
344
|
data.delta = state.feed(["o", data.output_index ?? 0, data.content_index ?? 0], data.delta ?? "");
|
|
324
345
|
return [[name, data]];
|
|
@@ -344,7 +365,7 @@ export class OpenAIResponsesAdapter extends Adapter {
|
|
|
344
365
|
const extra = template(data, ["item_id", "output_index", "content_index"]);
|
|
345
366
|
events.push([name ? deltaKind : null, { type: deltaKind, ...extra, delta: tail }]);
|
|
346
367
|
}
|
|
347
|
-
events.push([name, state.restore(data)]);
|
|
368
|
+
events.push([name, state.restore(data, state.toolNames.get(JSON.stringify(key)))]);
|
|
348
369
|
return events;
|
|
349
370
|
}
|
|
350
371
|
if (typeof kind === "string" && kind.includes("reasoning"))
|
|
@@ -421,8 +442,12 @@ export class AnthropicMessagesAdapter extends Adapter {
|
|
|
421
442
|
if (!isObject(data))
|
|
422
443
|
return [[name, data]];
|
|
423
444
|
const kind = data.type;
|
|
424
|
-
if (kind === "content_block_start")
|
|
445
|
+
if (kind === "content_block_start") {
|
|
446
|
+
if (typeof data.content_block?.name === "string") {
|
|
447
|
+
state.toolNames.set(JSON.stringify(["b", data.index ?? 0, "input_json_delta"]), data.content_block.name);
|
|
448
|
+
}
|
|
425
449
|
return [[name, state.restore(data)]];
|
|
450
|
+
}
|
|
426
451
|
if (kind === "content_block_delta") {
|
|
427
452
|
const index = data.index ?? 0;
|
|
428
453
|
const delta = data.delta ?? {};
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { StreamRestorer, Vault } from "./vault.ts";
|
|
|
5
5
|
export { Analyzer, resolveOverlaps, defaultRecognizers } from "./analyzer.ts";
|
|
6
6
|
export { AnonymizationResult, Anonymizer, maskValue, normalizeOperator, OPERATORS } from "./anonymizer.ts";
|
|
7
7
|
export type { Operator, Replacement } from "./anonymizer.ts";
|
|
8
|
-
export { LABELS, SECRET_LABELS } from "./entities.ts";
|
|
8
|
+
export { GROUPS, LABELS, SECRET_LABELS, type GroupData } from "./entities.ts";
|
|
9
9
|
export type { Candidate, Entity, Recognizer } from "./entities.ts";
|
|
10
10
|
export { AddressRecognizer } from "./addresses.ts";
|
|
11
11
|
export { PatternRecognizer, customPattern, DEFAULT_SPECS } from "./patterns.ts";
|
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import { counter } from "./text.js";
|
|
|
9
9
|
import { StreamRestorer, Vault } from "./vault.js";
|
|
10
10
|
export { Analyzer, resolveOverlaps, defaultRecognizers } from "./analyzer.js";
|
|
11
11
|
export { AnonymizationResult, Anonymizer, maskValue, normalizeOperator, OPERATORS } from "./anonymizer.js";
|
|
12
|
-
export { LABELS, SECRET_LABELS } from "./entities.js";
|
|
12
|
+
export { GROUPS, LABELS, SECRET_LABELS } from "./entities.js";
|
|
13
13
|
export { AddressRecognizer } from "./addresses.js";
|
|
14
14
|
export { PatternRecognizer, customPattern, DEFAULT_SPECS } from "./patterns.js";
|
|
15
15
|
export { PersonRecognizer } from "./persons.js";
|
package/dist/patterns.js
CHANGED
|
@@ -14,7 +14,8 @@ export function pickScore(scores, isValid, hasContext) {
|
|
|
14
14
|
export function spec(label, pattern, scores, options = {}) {
|
|
15
15
|
return {
|
|
16
16
|
label,
|
|
17
|
-
|
|
17
|
+
// "d" guarda as posições dos grupos: com um grupo "valor", só ele é o dado (a porta em "10.0.0.5:8080").
|
|
18
|
+
regex: new RegExp(pattern, `g${options.flags ?? ""}u${pattern.includes("(?<valor>") ? "d" : ""}`),
|
|
18
19
|
scores,
|
|
19
20
|
validator: options.validator,
|
|
20
21
|
context: wordsRegex(options.context ?? []),
|
|
@@ -83,6 +84,12 @@ const CTX_AADHAAR = ["aadhaar", "uidai", "uid number"];
|
|
|
83
84
|
const CTX_PAN = ["pan", "permanent account number", "income tax"];
|
|
84
85
|
const CTX_MRZ = ["passaporte", "passport", "mrz"];
|
|
85
86
|
const CTX_VIN = ["chassi", "chassis", "vin", "numero do chassi"];
|
|
87
|
+
const CTX_HOST = ["servidor", "server", "host", "hostname", "banco", "database", "conectar", "conexao", "endpoint", "porta",
|
|
88
|
+
"port", "ssh", "redis", "postgres", "mysql", "api"];
|
|
89
|
+
const CTX_SHELL = ["ssh", "scp", "sftp", "psql", "mysql", "telnet", "nc", "docker", "redis-cli", "mongosh"];
|
|
90
|
+
// Terminações de nomes que só existem dentro de uma rede (RFC 6762, RFC 8375 e os costumes de redes de empresas).
|
|
91
|
+
const INTERNAL_TLDS = "(?:local|localdomain|internal|interna|interno|lan|corp|intranet|home\\.arpa)";
|
|
92
|
+
const W = "\\p{L}\\p{N}_";
|
|
86
93
|
const CTX_CRYPTO = ["carteira", "wallet", "bitcoin", "btc", "ethereum", "eth", "cripto", "usdt"];
|
|
87
94
|
// 1ª linha da MRZ: "P<" + país + sobrenome<<nomes, completando com "<".
|
|
88
95
|
const mrzNameLine = (value) => value.slice(5).includes("<<") && /[A-Z]/.test(value.slice(5));
|
|
@@ -203,6 +210,17 @@ export const DEFAULT_SPECS = [
|
|
|
203
210
|
// Chassi: o dígito da posição 9 só é obrigatório nos EUA e na China; sem ele, só com "chassi" ou "VIN" por perto.
|
|
204
211
|
spec("VIN", `${B}[A-HJ-NPR-Z0-9]{17}${E}`, S(0.85, null, 0.97, 0.8), { validator: v.isValidVin, context: CTX_VIN, exclude: (value) => /^(?:\d+|[A-Z]+)$/.test(value) }),
|
|
205
212
|
spec("CRIPTO", `${B}(?:0x[0-9a-fA-F]{40}|[13][1-9A-HJ-NP-Za-km-z]{25,34}|(?:bc|tb)1[02-9ac-hj-np-z]{11,71})${E}`, S(0.9, null, 0.97), { validator: v.isValidCryptoAddress, context: CTX_CRYPTO }),
|
|
213
|
+
// Infraestrutura. Uma porta é só um número: vale colada a um IP ou a um servidor, depois de "porta"/"port" ou
|
|
214
|
+
// numa opção de comando (-p), nunca solta. O grupo "valor" é o que vira o marcador; o resto é só o contexto.
|
|
215
|
+
spec("PORTA", `${B}(?:\\d{1,3}\\.){3}\\d{1,3}:(?<valor>\\d{2,5})${E}`, S(0.9), { validator: v.isValidPort }),
|
|
216
|
+
spec("PORTA", `\\[[0-9A-Fa-f:.]{3,45}\\]:(?<valor>\\d{2,5})${E}`, S(0.9), { validator: v.isValidPort }),
|
|
217
|
+
spec("PORTA", `://(?:[^\\s/@]{1,200}@)?[A-Za-z0-9.\\-]{1,253}:(?<valor>\\d{2,5})${E}`, S(0.9), { validator: v.isValidPort }),
|
|
218
|
+
spec("PORTA", `(?<![${W}.@\\-])(?:localhost|(?:[A-Za-z0-9\\-]+\\.)+${INTERNAL_TLDS}):(?<valor>\\d{2,5})${E}`, S(0.9), { validator: v.isValidPort, flags: "i" }),
|
|
219
|
+
spec("PORTA", `(?<![${W}.@/\\-])(?=[A-Za-z0-9.\\-]*[A-Za-z])(?:[A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,24}:(?<valor>\\d{2,5})${E}`, S(null, null, 0.85), { validator: v.isValidPort, context: CTX_HOST }),
|
|
220
|
+
spec("PORTA", `(?<![A-Za-z])(?:portas?|ports?|--port)["']?\\s*(?:[:=]\\s*|n[ºo°]\\.?\\s*)?(?<valor>\\d{2,5})${E}`, S(0.85), { validator: v.isValidPort, flags: "i" }),
|
|
221
|
+
spec("PORTA", `(?<![${W}\\-])-[pP]\\s+(?<valor>\\d{2,5})${E}`, S(null, null, 0.85), { validator: v.isValidPort, context: CTX_SHELL, before: 60 }),
|
|
222
|
+
spec("PORTA", `(?<![${W}\\-])-[pP]\\s+\\d{2,5}:(?<valor>\\d{2,5})${E}`, S(null, null, 0.85), { validator: v.isValidPort, context: CTX_SHELL, before: 60 }),
|
|
223
|
+
spec("SERVIDOR", `(?<![${W}.@\\-])(?:[A-Za-z0-9\\-]+\\.)+${INTERNAL_TLDS}(?![${W}\\-]|\\.[A-Za-z])`, S(0.85), { flags: "i" }),
|
|
206
224
|
];
|
|
207
225
|
const round3 = (value) => Math.round(value * 1000) / 1000;
|
|
208
226
|
export class PatternRecognizer {
|
|
@@ -223,8 +241,9 @@ export class PatternRecognizer {
|
|
|
223
241
|
continue;
|
|
224
242
|
}
|
|
225
243
|
for (const match of text.matchAll(item.regex)) {
|
|
226
|
-
const
|
|
227
|
-
const
|
|
244
|
+
const span = match.indices?.groups?.valor;
|
|
245
|
+
const value = span ? text.slice(span[0], span[1]) : match[0];
|
|
246
|
+
const start = span ? span[0] : match.index;
|
|
228
247
|
if (item.exclude?.(value))
|
|
229
248
|
continue;
|
|
230
249
|
const isValid = item.validator ? item.validator(value) : true;
|
package/dist/validators.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export declare function phoneDigits(value: string): string;
|
|
|
24
24
|
export declare function isValidPhone(value: string): boolean;
|
|
25
25
|
export declare function isValidIntlPhone(value: string): boolean;
|
|
26
26
|
export declare function isValidIban(value: string): boolean;
|
|
27
|
+
/** Porta de rede: de 1 a 65535, sem zeros à esquerda. */
|
|
28
|
+
export declare function isValidPort(value: string): boolean;
|
|
27
29
|
export declare function isValidIpv4(value: string): boolean;
|
|
28
30
|
export declare function isValidIpv6(value: string): boolean;
|
|
29
31
|
export declare function parseDate(value: string): Date | null;
|
package/dist/validators.js
CHANGED
|
@@ -199,6 +199,10 @@ export function isValidIban(value) {
|
|
|
199
199
|
const number = [...rearranged].map((char) => parseInt(char, 36).toString()).join("");
|
|
200
200
|
return mod97(number) === 1;
|
|
201
201
|
}
|
|
202
|
+
/** Porta de rede: de 1 a 65535, sem zeros à esquerda. */
|
|
203
|
+
export function isValidPort(value) {
|
|
204
|
+
return /^[1-9]\d{0,4}$/.test(value) && Number(value) <= 65535;
|
|
205
|
+
}
|
|
202
206
|
export function isValidIpv4(value) {
|
|
203
207
|
const parts = value.split(".");
|
|
204
208
|
if (parts.length !== 4)
|
package/dist/vault.d.ts
CHANGED
|
@@ -10,25 +10,34 @@ export declare const MAX_HOLDBACK = 48;
|
|
|
10
10
|
* - `linkHosts`: domínios (e subdomínios) cujos links podem receber os dados reais mesmo assim.
|
|
11
11
|
* - `tools` (padrão true): restaura os argumentos das chamadas de ferramenta.
|
|
12
12
|
* - `secretsInTools` (padrão false): restaura chaves de API, tokens e senhas nesses argumentos.
|
|
13
|
+
* - `toolsWithoutData`: palavras de nomes de ferramentas que nunca recebem dados reais (padrão: rede e mensagens).
|
|
14
|
+
* - `toolsWithData`: se preenchida, só estas ferramentas (pelo nome exato) recebem dados reais.
|
|
13
15
|
*/
|
|
14
16
|
export interface RestorePolicy {
|
|
15
17
|
links?: boolean;
|
|
16
18
|
linkHosts?: string[];
|
|
17
19
|
tools?: boolean;
|
|
18
20
|
secretsInTools?: boolean;
|
|
21
|
+
toolsWithoutData?: string[];
|
|
22
|
+
toolsWithData?: string[];
|
|
19
23
|
}
|
|
20
|
-
/** Contexto de uma restauração: argumento de ferramenta e texto da mesma linha que já passou
|
|
24
|
+
/** Contexto de uma restauração: argumento de ferramenta, nome dela e texto da mesma linha que já passou. */
|
|
21
25
|
export interface RestoreContext {
|
|
22
26
|
tool?: boolean;
|
|
27
|
+
toolName?: string;
|
|
23
28
|
prefix?: string;
|
|
24
29
|
}
|
|
30
|
+
export declare const NETWORK_TOOL_WORDS: readonly string[];
|
|
31
|
+
export declare const toolWords: (name: string) => Set<string>;
|
|
32
|
+
/** A ferramenta com este nome pode receber dados reais nos argumentos? */
|
|
33
|
+
export declare function toolAllowed(policy: RestorePolicy, name: string): boolean;
|
|
25
34
|
export declare const MAX_RUN = 2048;
|
|
26
35
|
/** Se o marcador está dentro de um link, imagem ou URL, devolve a URL até ele; senão, null. */
|
|
27
36
|
export declare function linkContext(before: string): string | null;
|
|
28
37
|
/** Domínio de uma URL absoluta, só se ele já terminou (vazio se o marcador está no próprio domínio). */
|
|
29
38
|
export declare function urlHost(url: string): string;
|
|
30
39
|
/** A política deixa restaurar um valor do tipo `label`, precedido por `before` (o texto da mesma linha)? */
|
|
31
|
-
export declare function restoreAllowed(policy: RestorePolicy, label: string, before: string, tool: boolean): boolean;
|
|
40
|
+
export declare function restoreAllowed(policy: RestorePolicy, label: string, before: string, tool: boolean, toolName?: string): boolean;
|
|
32
41
|
/**
|
|
33
42
|
* Desarma marcadores que já vêm no texto de entrada: `[CPF_1]` vira `[CPF#1]`. Só o Véu cria marcadores;
|
|
34
43
|
* um marcador escrito por outra pessoa não pode virar um dado real quando a IA o repete.
|
|
@@ -89,7 +98,7 @@ export declare class Vault {
|
|
|
89
98
|
* Dentro de links e URLs, e para segredos em argumentos de ferramentas, o marcador fica como está.
|
|
90
99
|
*/
|
|
91
100
|
restore(text: string, jsonEscape?: boolean, context?: RestoreContext): string;
|
|
92
|
-
restorer(jsonEscape?: boolean, tool?: boolean): StreamRestorer;
|
|
101
|
+
restorer(jsonEscape?: boolean, tool?: boolean, toolName?: string): StreamRestorer;
|
|
93
102
|
/** O fim do texto pode ser o começo de um marcador que chega no próximo pedaço? */
|
|
94
103
|
mightContinue(tail: string): boolean;
|
|
95
104
|
/** O arquivo exportado contém os dados reais: guarde com cuidado. */
|
|
@@ -103,7 +112,8 @@ export declare class StreamRestorer {
|
|
|
103
112
|
readonly vault: Vault;
|
|
104
113
|
readonly jsonEscape: boolean;
|
|
105
114
|
readonly tool: boolean;
|
|
106
|
-
|
|
115
|
+
readonly toolName?: string;
|
|
116
|
+
constructor(vault: Vault, jsonEscape?: boolean, tool?: boolean, toolName?: string);
|
|
107
117
|
private emit;
|
|
108
118
|
feed(text: string): string;
|
|
109
119
|
flush(): string;
|
package/dist/vault.js
CHANGED
|
@@ -6,7 +6,7 @@ import { fold, onlyDigits } from "./text.js";
|
|
|
6
6
|
export const DIGIT_LABELS = new Set([
|
|
7
7
|
"CPF", "TELEFONE", "CEP", "CARTAO_CREDITO", "PIS", "CNS", "CNH", "TITULO_ELEITOR", "RENAVAM",
|
|
8
8
|
"CONTA_BANCARIA", "PROCESSO", "NIF_PT", "NISS_PT", "CUIT", "DNI", "NIT", "RUC", "CEDULA", "NUIT", "SSN",
|
|
9
|
-
"STEUER_ID", "NHS", "BSN", "SIN", "AADHAAR",
|
|
9
|
+
"STEUER_ID", "NHS", "BSN", "SIN", "AADHAAR", "PORTA",
|
|
10
10
|
]);
|
|
11
11
|
export const CODE_LABELS = new Set(["CNPJ", "RG", "PLACA", "PASSAPORTE", "CHAVE_PIX", "CC_PT", "CURP",
|
|
12
12
|
"RFC", "RUT", "RIF", "BI_AO", "BI_MZ", "MBI", "DNI_ES", "CODICE_FISCALE", "NIR", "NINO", "PAN", "VIN"]);
|
|
@@ -20,6 +20,27 @@ const TRAILING_WORD = /^[A-Za-z0-9_]+$/;
|
|
|
20
20
|
export const MAX_HOLDBACK = 48;
|
|
21
21
|
const HASH_HEX = 16; // 64 bits no operador hash
|
|
22
22
|
const HASH_CONTEXT = new TextEncoder().encode("veu/hash/v2");
|
|
23
|
+
// Ferramentas que levam dados para fora (rede, mensagens, publicação): não recebem dados reais nos argumentos.
|
|
24
|
+
// O nome é quebrado em palavras ("WebFetch" -> web, fetch), então "postgres_query" não é confundido com "post".
|
|
25
|
+
export const NETWORK_TOOL_WORDS = [
|
|
26
|
+
"fetch", "http", "https", "request", "url", "browse", "browser", "navigate", "web", "email", "mail", "gmail",
|
|
27
|
+
"outlook", "send", "post", "webhook", "upload", "slack", "discord", "telegram", "whatsapp", "sms", "message",
|
|
28
|
+
"tweet", "publish", "share", "notify", "curl", "wget",
|
|
29
|
+
];
|
|
30
|
+
const TOOL_WORD = /[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g;
|
|
31
|
+
// Comandos que mandam dados pela rede: o dado real não vai depois deles na mesma linha (nem no corpo do curl).
|
|
32
|
+
const NETWORK_COMMAND = /(?<![\p{L}\p{N}_.-])(?:curl|wget|nc|ncat|netcat|telnet|ftp|sftp|scp|ssh|rsync|invoke-webrequest|invoke-restmethod|iwr|irm|start-bitstransfer|sendmail|mutt)(?![\p{L}\p{N}_-])/iu;
|
|
33
|
+
export const toolWords = (name) => new Set((name.match(TOOL_WORD) ?? []).map((w) => w.toLowerCase()));
|
|
34
|
+
/** A ferramenta com este nome pode receber dados reais nos argumentos? */
|
|
35
|
+
export function toolAllowed(policy, name) {
|
|
36
|
+
const allowed = new Set((policy.toolsWithData ?? []).map((item) => item.toLowerCase()));
|
|
37
|
+
if (allowed.has(name.toLowerCase()))
|
|
38
|
+
return true;
|
|
39
|
+
if (allowed.size)
|
|
40
|
+
return false;
|
|
41
|
+
const denied = new Set((policy.toolsWithoutData ?? NETWORK_TOOL_WORDS).map((word) => word.toLowerCase()));
|
|
42
|
+
return ![...toolWords(name)].some((word) => denied.has(word));
|
|
43
|
+
}
|
|
23
44
|
// O último caso é um domínio solto seguido de "/" (evil.com/?d=...), que muitos sites transformam em link.
|
|
24
45
|
const URL_START = /\b[a-z][a-z0-9+.-]*:\/\/|\bwww\.|\bmailto:|\]\(\s*<?|(?<![:/\p{L}\p{N}_])\/\/|\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,24}(?::\d{1,5})?\//iu;
|
|
25
46
|
const LINK_ATTRIBUTE = /(?:\b(?:src|href|action|formaction|srcset|poster|ping|cite|background|lowsrc|data)\s*=\s*|\burl\(\s*)["']?$/i;
|
|
@@ -66,9 +87,15 @@ export function urlHost(url) {
|
|
|
66
87
|
return authority.slice(authority.lastIndexOf("@") + 1).split(":")[0].toLowerCase().replace(/\.+$/, "");
|
|
67
88
|
}
|
|
68
89
|
/** A política deixa restaurar um valor do tipo `label`, precedido por `before` (o texto da mesma linha)? */
|
|
69
|
-
export function restoreAllowed(policy, label, before, tool) {
|
|
70
|
-
if (tool
|
|
71
|
-
|
|
90
|
+
export function restoreAllowed(policy, label, before, tool, toolName) {
|
|
91
|
+
if (tool) {
|
|
92
|
+
if (policy.tools === false || (SECRET_LABELS.has(label) && !policy.secretsInTools))
|
|
93
|
+
return false;
|
|
94
|
+
if (toolName && !toolAllowed(policy, toolName))
|
|
95
|
+
return false;
|
|
96
|
+
if (NETWORK_COMMAND.test(before.split(/\\n|\n/).pop() ?? ""))
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
72
99
|
if (policy.links)
|
|
73
100
|
return true;
|
|
74
101
|
const url = linkContext(before);
|
|
@@ -225,13 +252,13 @@ export class Vault {
|
|
|
225
252
|
return match;
|
|
226
253
|
const newline = offset > 0 ? text.lastIndexOf("\n", offset - 1) : -1;
|
|
227
254
|
const before = newline === -1 ? prefix + text.slice(0, offset) : text.slice(newline + 1, offset);
|
|
228
|
-
if (!restoreAllowed(this.policy, entry.label, before, tool))
|
|
255
|
+
if (!restoreAllowed(this.policy, entry.label, before, tool, tool ? context.toolName : undefined))
|
|
229
256
|
return match;
|
|
230
257
|
return jsonEscape ? JSON.stringify(entry.original).slice(1, -1) : entry.original;
|
|
231
258
|
}).slice(lead.length);
|
|
232
259
|
}
|
|
233
|
-
restorer(jsonEscape = false, tool) {
|
|
234
|
-
return new StreamRestorer(this, jsonEscape, tool);
|
|
260
|
+
restorer(jsonEscape = false, tool, toolName) {
|
|
261
|
+
return new StreamRestorer(this, jsonEscape, tool, toolName);
|
|
235
262
|
}
|
|
236
263
|
/** O fim do texto pode ser o começo de um marcador que chega no próximo pedaço? */
|
|
237
264
|
mightContinue(tail) {
|
|
@@ -287,13 +314,15 @@ export class StreamRestorer {
|
|
|
287
314
|
vault;
|
|
288
315
|
jsonEscape;
|
|
289
316
|
tool;
|
|
290
|
-
|
|
317
|
+
toolName;
|
|
318
|
+
constructor(vault, jsonEscape = false, tool, toolName) {
|
|
291
319
|
this.vault = vault;
|
|
292
320
|
this.jsonEscape = jsonEscape;
|
|
293
321
|
this.tool = tool ?? jsonEscape;
|
|
322
|
+
this.toolName = toolName;
|
|
294
323
|
}
|
|
295
324
|
emit(ready) {
|
|
296
|
-
const output = this.vault.restore(ready, this.jsonEscape, { tool: this.tool, prefix: this.line });
|
|
325
|
+
const output = this.vault.restore(ready, this.jsonEscape, { tool: this.tool, toolName: this.toolName, prefix: this.line });
|
|
297
326
|
const newline = ready.lastIndexOf("\n");
|
|
298
327
|
this.line = newline === -1 ? this.line + ready : ready.slice(newline + 1);
|
|
299
328
|
return output;
|