@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/dist/vault.js CHANGED
@@ -1,18 +1,126 @@
1
1
  // Cofre: mapeamento entre marcadores e dados reais, e restauração (equivalente a veu/vault.py).
2
+ import { LABELS, SECRET_LABELS } from "./entities.js";
2
3
  import { hmacSha256, toHex } from "./sha256.js";
3
4
  import { fold, onlyDigits } from "./text.js";
4
5
  /** Rótulos comparados só pelos dígitos ("529.982.247-25" e "52998224725" são o mesmo CPF). */
5
6
  export const DIGIT_LABELS = new Set([
6
7
  "CPF", "TELEFONE", "CEP", "CARTAO_CREDITO", "PIS", "CNS", "CNH", "TITULO_ELEITOR", "RENAVAM",
7
- "CONTA_BANCARIA", "PROCESSO",
8
+ "CONTA_BANCARIA", "PROCESSO", "NIF_PT", "NISS_PT", "CUIT", "DNI", "NIT", "RUC", "CEDULA", "NUIT", "SSN",
9
+ "STEUER_ID", "NHS", "BSN", "SIN", "AADHAAR", "PORTA",
8
10
  ]);
9
- export const CODE_LABELS = new Set(["CNPJ", "RG", "PLACA", "PASSAPORTE", "CHAVE_PIX"]);
11
+ export const CODE_LABELS = new Set(["CNPJ", "RG", "PLACA", "PASSAPORTE", "CHAVE_PIX", "CC_PT", "CURP",
12
+ "RFC", "RUT", "RIF", "BI_AO", "BI_MZ", "MBI", "DNI_ES", "CODICE_FISCALE", "NIR", "NINO", "PAN", "VIN"]);
10
13
  // O colchete final é opcional: modelos às vezes escrevem "[CPF_1" ou "[CPF 1]".
11
- const PLACEHOLDER = "\\[\\s*(?<ph_label>[A-Za-z]+(?:_[A-Za-z]+)*)[_\\s-]+(?<ph_id>[0-9A-Fa-f]{1,8})(?:\\s*\\]|(?![\\p{L}\\p{N}_]))";
12
- const BARE = "(?<![\\p{L}\\p{N}_\\[])(?<bare_label>[A-Z]+(?:_[A-Z]+)*)_(?<bare_id>\\d{1,6}|[0-9a-f]{8})(?![\\p{L}\\p{N}_\\]])";
14
+ const PLACEHOLDER = "\\[\\s*(?<ph_label>[A-Za-z]+(?:_[A-Za-z]+)*)[_\\s-]+(?<ph_id>[0-9A-Fa-f]{1,16})(?:\\s*\\]|(?![\\p{L}\\p{N}_]))";
15
+ const BARE = "(?<![\\p{L}\\p{N}_\\[])(?<bare_label>[A-Z]+(?:_[A-Z]+)*)_(?<bare_id>\\d{1,6}|[0-9a-f]{16}|[0-9a-f]{8})(?![\\p{L}\\p{N}_\\]])";
13
16
  const RESTORE = new RegExp(`${PLACEHOLDER}|${BARE}`, "gu");
17
+ // Marcadores que já chegam no texto de entrada (escritos por uma página, um e-mail ou um documento).
18
+ const FORGED = /\[(?<open>\s*)(?<label>[A-Za-z]+(?:_[A-Za-z]+)*)(?<sep>[_\s-]+)(?<id>[0-9A-Fa-f]{1,16})(?=\s*\]|(?![\p{L}\p{N}_]))/gu;
14
19
  const TRAILING_WORD = /^[A-Za-z0-9_]+$/;
15
20
  export const MAX_HOLDBACK = 48;
21
+ const HASH_HEX = 16; // 64 bits no operador hash
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
+ }
44
+ // O último caso é um domínio solto seguido de "/" (evil.com/?d=...), que muitos sites transformam em link.
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;
46
+ const LINK_ATTRIBUTE = /(?:\b(?:src|href|action|formaction|srcset|poster|ping|cite|background|lowsrc|data)\s*=\s*|\burl\(\s*)["']?$/i;
47
+ const ANGLE_OPEN = /\]\(\s*</g;
48
+ const RUN_DELIMITER = /[\s"'<>`]/u;
49
+ // Um trecho sem espaços maior que isto logo antes do marcador não é analisado: o marcador fica como está.
50
+ export const MAX_RUN = 2048;
51
+ /** O trecho final da linha sem espaços, aspas, < > ou crase. Varre do fim: tempo proporcional ao trecho. */
52
+ function trailingRun(line) {
53
+ let index = line.length;
54
+ while (index && !RUN_DELIMITER.test(line[index - 1]))
55
+ index -= 1;
56
+ return line.slice(index);
57
+ }
58
+ const HOST = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#\\\s]*)[/?#\\]/i;
59
+ const JSON_ESCAPE = /\\u([0-9a-fA-F]{4})|\\(\/)/g;
60
+ /** Se o marcador está dentro de um link, imagem ou URL, devolve a URL até ele; senão, null. */
61
+ export function linkContext(before) {
62
+ let line = before.slice(before.lastIndexOf("\n") + 1);
63
+ if (line.includes("\\")) {
64
+ line = line.replace(JSON_ESCAPE, (_, hex) => (hex ? String.fromCharCode(parseInt(hex, 16)) : "/"));
65
+ }
66
+ // Destino entre < > ("[x](<https://site/a b>)"), que aceita espaços: o primeiro "](<" depois do último ">".
67
+ ANGLE_OPEN.lastIndex = line.lastIndexOf(">") + 1;
68
+ const angle = ANGLE_OPEN.exec(line);
69
+ if (angle)
70
+ return line.slice(angle.index + angle[0].length);
71
+ const run = trailingRun(line);
72
+ if (run.length > MAX_RUN)
73
+ return run; // sem esquema nem domínio reconhecível: o marcador não é restaurado
74
+ const start = URL_START.exec(run);
75
+ if (start)
76
+ return start[0].startsWith("]") ? run.slice(start.index + start[0].length) : run.slice(start.index);
77
+ if (LINK_ATTRIBUTE.test(line.slice(0, line.length - run.length)))
78
+ return run;
79
+ return null;
80
+ }
81
+ /** Domínio de uma URL absoluta, só se ele já terminou (vazio se o marcador está no próprio domínio). */
82
+ export function urlHost(url) {
83
+ const match = HOST.exec(url);
84
+ if (!match)
85
+ return "";
86
+ const authority = match[1];
87
+ return authority.slice(authority.lastIndexOf("@") + 1).split(":")[0].toLowerCase().replace(/\.+$/, "");
88
+ }
89
+ /** A política deixa restaurar um valor do tipo `label`, precedido por `before` (o texto da mesma linha)? */
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
+ }
99
+ if (policy.links)
100
+ return true;
101
+ const url = linkContext(before);
102
+ if (url === null)
103
+ return true;
104
+ const host = urlHost(url);
105
+ return !!host && (policy.linkHosts ?? []).some((domain) => {
106
+ const allowed = domain.trim().toLowerCase().replace(/^\.+/, "");
107
+ return !!allowed && (host === allowed || host.endsWith(`.${allowed}`));
108
+ });
109
+ }
110
+ /**
111
+ * Desarma marcadores que já vêm no texto de entrada: `[CPF_1]` vira `[CPF#1]`. Só o Véu cria marcadores;
112
+ * um marcador escrito por outra pessoa não pode virar um dado real quando a IA o repete.
113
+ */
114
+ export function neutralizePlaceholders(text, labels = new Set()) {
115
+ if (!text.includes("["))
116
+ return text;
117
+ return text.replace(FORGED, (match, open, label, sep, id) => {
118
+ const upper = label.toUpperCase();
119
+ if (!(upper in LABELS) && !labels.has(upper))
120
+ return match;
121
+ return `[${open}${label}${"#".repeat(sep.length)}${id}`;
122
+ });
123
+ }
16
124
  export function normalizeValue(label, value) {
17
125
  if (label === "TELEFONE") {
18
126
  const digits = onlyDigits(value);
@@ -32,13 +140,18 @@ function randomSecret() {
32
140
  return bytes;
33
141
  }
34
142
  /** Mapeamento reversível entre dados reais e o que foi enviado ao modelo. Fica só na memória. */
143
+ const BARE_IN_INPUT = new RegExp(BARE, "gu");
35
144
  export class Vault {
145
+ // Marcadores soltos ("CPF_1", sem colchetes) que já vieram no texto de entrada: nunca são restaurados.
146
+ forgedBare = new Set();
36
147
  byKey = new Map();
37
148
  items = new Map();
38
149
  counters = new Map();
39
150
  secret;
40
- constructor(secret) {
151
+ policy;
152
+ constructor(secret, policy = {}) {
41
153
  this.secret = typeof secret === "string" ? new TextEncoder().encode(secret) : secret ?? randomSecret();
154
+ this.policy = policy;
42
155
  }
43
156
  static key(label, normalized) {
44
157
  return `${label}\u0000${normalized}`;
@@ -54,8 +167,10 @@ export class Vault {
54
167
  return existing;
55
168
  let replacement;
56
169
  if (hashed) {
57
- const digest = toHex(hmacSha256(this.secret, new TextEncoder().encode(`${label}:${normalized}`)));
58
- replacement = `[${label}_${digest.slice(0, 8)}]`;
170
+ replacement = `[${label}_${this.hashId(label, normalized)}]`;
171
+ // Colisão de 64 bits: improvável, mas nunca troca uma pessoa por outra.
172
+ if (this.items.has(replacement))
173
+ throw new Error(`Colisão no operador hash para ${label}. Use outro segredo.`);
59
174
  }
60
175
  else {
61
176
  const next = (this.counters.get(label) ?? 0) + 1;
@@ -65,6 +180,11 @@ export class Vault {
65
180
  this.store(key, { label, original: value, replacement, kind: "marcador" });
66
181
  return replacement;
67
182
  }
183
+ /** HMAC-SHA256 com uma chave derivada só para o operador hash (64 bits na saída). */
184
+ hashId(label, normalized) {
185
+ const key = hmacSha256(this.secret, HASH_CONTEXT);
186
+ return toHex(hmacSha256(key, new TextEncoder().encode(`${label}:${normalized}`))).slice(0, HASH_HEX);
187
+ }
68
188
  /** Faz outro valor (por exemplo, só o primeiro nome) usar um marcador já existente. */
69
189
  alias(label, value, replacement) {
70
190
  const key = Vault.key(label, normalizeValue(label, value));
@@ -81,32 +201,64 @@ export class Vault {
81
201
  entries() {
82
202
  return [...this.items.values()];
83
203
  }
204
+ /**
205
+ * Desarma os marcadores que já vêm no texto de entrada: "[CPF_1]" vira "[CPF#1]". Um "CPF_1" solto não é
206
+ * reescrito (pode ser um nome no código), mas a forma solta nunca mais é restaurada neste cofre.
207
+ */
208
+ neutralize(text) {
209
+ const labels = this.labels;
210
+ for (const match of text.matchAll(BARE_IN_INPUT)) {
211
+ const label = match.groups.bare_label;
212
+ if (label in LABELS || labels.has(label))
213
+ this.forgedBare.add(`[${label}_${match.groups.bare_id}]`);
214
+ }
215
+ return neutralizePlaceholders(text, labels);
216
+ }
84
217
  get labels() {
85
218
  return new Set([...this.items.values()].map((entry) => entry.label));
86
219
  }
87
220
  get hasPlaceholders() {
88
221
  return [...this.items.values()].some((entry) => entry.kind === "marcador");
89
222
  }
90
- /** Troca os marcadores pelos valores reais. jsonEscape: o texto é um pedaço de JSON. */
91
- restore(text, jsonEscape = false) {
223
+ entryFor(groups) {
224
+ const key = groups.ph_label
225
+ ? `[${groups.ph_label.toUpperCase()}_${groups.ph_id.toLowerCase()}]`
226
+ : `[${groups.bare_label}_${groups.bare_id}]`;
227
+ if (!groups.ph_label && this.forgedBare.has(key))
228
+ return undefined;
229
+ const entry = this.items.get(key);
230
+ return entry && entry.kind === "marcador" ? entry : undefined;
231
+ }
232
+ /**
233
+ * Troca os marcadores pelos valores reais, seguindo a política do cofre.
234
+ * jsonEscape: o texto é um pedaço de JSON. `context.tool` (padrão: igual a jsonEscape): argumento de ferramenta.
235
+ * Dentro de links e URLs, e para segredos em argumentos de ferramentas, o marcador fica como está.
236
+ */
237
+ restore(text, jsonEscape = false, context = {}) {
92
238
  if (!text || !this.items.size)
93
239
  return text;
94
- return text.replace(RESTORE, (...args) => {
240
+ const tool = context.tool ?? jsonEscape;
241
+ const prefix = context.prefix ?? "";
242
+ // O último caractere já emitido (streaming) entra só como contexto: "_" + "CPF_1" não é um marcador solto.
243
+ const lead = prefix.slice(-1);
244
+ return (lead + text).replace(RESTORE, (...args) => {
95
245
  const groups = args[args.length - 1];
96
246
  const match = args[0];
97
- let key;
98
- if (groups.ph_label)
99
- key = `[${groups.ph_label.toUpperCase()}_${groups.ph_id.toLowerCase()}]`;
100
- else
101
- key = `[${groups.bare_label}_${groups.bare_id}]`;
102
- const entry = this.items.get(key);
103
- if (!entry || entry.kind !== "marcador")
247
+ if (args[args.length - 3] < lead.length)
248
+ return match;
249
+ const offset = args[args.length - 3] - lead.length;
250
+ const entry = this.entryFor(groups);
251
+ if (!entry)
252
+ return match;
253
+ const newline = offset > 0 ? text.lastIndexOf("\n", offset - 1) : -1;
254
+ const before = newline === -1 ? prefix + text.slice(0, offset) : text.slice(newline + 1, offset);
255
+ if (!restoreAllowed(this.policy, entry.label, before, tool, tool ? context.toolName : undefined))
104
256
  return match;
105
257
  return jsonEscape ? JSON.stringify(entry.original).slice(1, -1) : entry.original;
106
- });
258
+ }).slice(lead.length);
107
259
  }
108
- restorer(jsonEscape = false) {
109
- return new StreamRestorer(this, jsonEscape);
260
+ restorer(jsonEscape = false, tool, toolName) {
261
+ return new StreamRestorer(this, jsonEscape, tool, toolName);
110
262
  }
111
263
  /** O fim do texto pode ser o começo de um marcador que chega no próximo pedaço? */
112
264
  mightContinue(tail) {
@@ -129,10 +281,11 @@ export class Vault {
129
281
  const [entidade, valor] = key.split("\u0000");
130
282
  return { entidade, valor, substituto };
131
283
  }),
284
+ ...(this.forgedBare.size ? { forjados: [...this.forgedBare].sort() } : {}),
132
285
  };
133
286
  }
134
- static fromJSON(data, secret) {
135
- const vault = new Vault(secret);
287
+ static fromJSON(data, secret, policy = {}) {
288
+ const vault = new Vault(secret, policy);
136
289
  for (const item of data.itens ?? []) {
137
290
  const entry = {
138
291
  label: item.entidade, original: item.original, replacement: item.substituto,
@@ -148,17 +301,31 @@ export class Vault {
148
301
  if (!vault.byKey.has(key))
149
302
  vault.byKey.set(key, item.substituto);
150
303
  }
304
+ for (const key of data.forjados ?? [])
305
+ vault.forgedBare.add(String(key));
151
306
  return vault;
152
307
  }
153
308
  }
154
309
  /** Restaura uma resposta que chega em pedaços: um marcador dividido ("[PES" + "SOA_1]") fica retido até completar. */
155
310
  export class StreamRestorer {
156
311
  buffer = "";
312
+ // Texto já emitido na linha atual: um link pode começar num pedaço e o marcador chegar em outro.
313
+ line = "";
157
314
  vault;
158
315
  jsonEscape;
159
- constructor(vault, jsonEscape = false) {
316
+ tool;
317
+ toolName;
318
+ constructor(vault, jsonEscape = false, tool, toolName) {
160
319
  this.vault = vault;
161
320
  this.jsonEscape = jsonEscape;
321
+ this.tool = tool ?? jsonEscape;
322
+ this.toolName = toolName;
323
+ }
324
+ emit(ready) {
325
+ const output = this.vault.restore(ready, this.jsonEscape, { tool: this.tool, toolName: this.toolName, prefix: this.line });
326
+ const newline = ready.lastIndexOf("\n");
327
+ this.line = newline === -1 ? this.line + ready : ready.slice(newline + 1);
328
+ return output;
162
329
  }
163
330
  feed(text) {
164
331
  if (!text)
@@ -167,12 +334,12 @@ export class StreamRestorer {
167
334
  const cut = this.safeCut(this.buffer);
168
335
  const ready = this.buffer.slice(0, cut);
169
336
  this.buffer = this.buffer.slice(cut);
170
- return this.vault.restore(ready, this.jsonEscape);
337
+ return this.emit(ready);
171
338
  }
172
339
  flush() {
173
340
  const ready = this.buffer;
174
341
  this.buffer = "";
175
- return this.vault.restore(ready, this.jsonEscape);
342
+ return this.emit(ready);
176
343
  }
177
344
  get pending() {
178
345
  return this.buffer.length > 0;
@@ -183,12 +350,13 @@ export class StreamRestorer {
183
350
  if (bracket !== -1 && !text.slice(bracket).includes("]") && text.length - bracket <= MAX_HOLDBACK)
184
351
  cut = bracket;
185
352
  const longest = Math.min(text.length, MAX_HOLDBACK);
186
- const alnum = /[\p{L}\p{N}]/u;
353
+ // No meio de uma palavra ("_CPF_1"), um marcador solto não começa: cortar ali o separaria do contexto.
354
+ const word = /[\p{L}\p{N}_]/u;
187
355
  for (let size = longest; size > 0; size -= 1) {
188
356
  const start = text.length - size;
189
357
  if (start >= cut)
190
358
  break;
191
- if (start > 0 && alnum.test(text[start - 1]) && alnum.test(text[start]))
359
+ if (start > 0 && word.test(text[start - 1]) && word.test(text[start]))
192
360
  continue;
193
361
  if (this.vault.mightContinue(text.slice(start))) {
194
362
  cut = start;