@guhttps/veu 0.7.2 → 0.8.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
@@ -6,10 +6,11 @@ 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", "PORTA",
9
+ "STEUER_ID", "NHS", "BSN", "SIN", "AADHAAR", "PORTA", "REGISTRO_PROFISSIONAL", "CADASTRO", "BOLETO",
10
+ "CERTIDAO", "IMEI",
10
11
  ]);
11
12
  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"]);
13
+ "RFC", "RUT", "RIF", "BI_AO", "BI_MZ", "MBI", "DNI_ES", "CODICE_FISCALE", "NIR", "NINO", "PAN", "VIN", "CTPS", "MAC"]);
13
14
  // O colchete final é opcional: modelos às vezes escrevem "[CPF_1" ou "[CPF 1]".
14
15
  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
16
  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}_\\]])";
@@ -43,15 +44,20 @@ export function toolAllowed(policy, name) {
43
44
  }
44
45
  // O último caso é um domínio solto seguido de "/" (evil.com/?d=...), que muitos sites transformam em link.
45
46
  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 LINK_ATTRIBUTE_NAME = /(?<![\p{L}\p{N}_])(?:src|href|action|formaction|srcset|poster|ping|cite|background|lowsrc|data)$/iu;
47
48
  const ANGLE_OPEN = /\]\(\s*</g;
48
49
  const RUN_DELIMITER = /[\s"'<>`]/u;
49
50
  // Um trecho sem espaços maior que isto logo antes do marcador não é analisado: o marcador fica como está.
50
51
  export const MAX_RUN = 2048;
51
52
  /** O trecho final da linha sem espaços, aspas, < > ou crase. Varre do fim: tempo proporcional ao trecho. */
53
+ /**
54
+ * O trecho final da linha sem espaços, aspas, < > ou crase. Varre do fim e para logo depois de MAX_RUN: passar de
55
+ * MAX_RUN já basta para não restaurar, e varrer até o começo deixava a restauração quadrática.
56
+ */
52
57
  function trailingRun(line) {
53
58
  let index = line.length;
54
- while (index && !RUN_DELIMITER.test(line[index - 1]))
59
+ const limit = Math.max(0, line.length - MAX_RUN - 1);
60
+ while (index > limit && !RUN_DELIMITER.test(line[index - 1]))
55
61
  index -= 1;
56
62
  return line.slice(index);
57
63
  }
@@ -59,25 +65,81 @@ const HOST = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#\\\s]*)[/?#\\]/i;
59
65
  const JSON_ESCAPE = /\\u([0-9a-fA-F]{4})|\\(\/)/g;
60
66
  /** Se o marcador está dentro de um link, imagem ou URL, devolve a URL até ele; senão, null. */
61
67
  export function linkContext(before) {
68
+ // Roda uma vez por marcador: nada aqui varre a linha inteira em JavaScript, para não ficar quadrático.
62
69
  let line = before.slice(before.lastIndexOf("\n") + 1);
63
70
  if (line.includes("\\")) {
64
- line = line.replace(JSON_ESCAPE, (_, hex) => (hex ? String.fromCharCode(parseInt(hex, 16)) : "/"));
71
+ const cut = Math.max(0, line.length - 4 * MAX_RUN);
72
+ line = line.slice(0, cut) + line.slice(cut).replace(JSON_ESCAPE, (_, hex) => (hex ? String.fromCharCode(parseInt(hex, 16)) : "/"));
65
73
  }
66
74
  // 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);
75
+ const opener = line.indexOf("](", line.lastIndexOf(">") + 1);
76
+ let angle = null;
77
+ if (opener !== -1) {
78
+ ANGLE_OPEN.lastIndex = opener;
79
+ angle = ANGLE_OPEN.exec(line);
80
+ }
69
81
  if (angle)
70
82
  return line.slice(angle.index + angle[0].length);
83
+ // Ainda dentro do destino de um link Markdown ("[x](javascript:fetch('...'+'[CPF_1]')") ou do valor de um atributo
84
+ // HTML (href="...'+'[CPF_1]"): aspas e "+" no caminho não tiram o marcador do link. Com a linha em branco antes do
85
+ // marcador, vale a linha de cima ("[x](https://site/?d=" e o marcador embaixo).
86
+ let inside = openLink(line);
87
+ if (inside === null && !line.trim() && before.includes("\n")) {
88
+ const above = before.slice(0, before.lastIndexOf("\n"));
89
+ inside = openLink(above.slice(above.lastIndexOf("\n") + 1));
90
+ }
91
+ if (inside !== null)
92
+ return inside;
71
93
  const run = trailingRun(line);
72
94
  if (run.length > MAX_RUN)
73
95
  return run; // sem esquema nem domínio reconhecível: o marcador não é restaurado
74
96
  const start = URL_START.exec(run);
75
97
  if (start)
76
98
  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)))
99
+ if (endsWithLinkAttribute(line.slice(0, line.length - run.length)))
78
100
  return run;
79
101
  return null;
80
102
  }
103
+ function count(text, char) {
104
+ let total = 0;
105
+ for (let index = text.indexOf(char); index !== -1; index = text.indexOf(char, index + 1))
106
+ total += 1;
107
+ return total;
108
+ }
109
+ /** O destino de link Markdown ou o valor de atributo de link ainda aberto no fim da linha, ou null. */
110
+ function openLink(line) {
111
+ const opener = line.lastIndexOf("](");
112
+ if (opener !== -1) {
113
+ const rest = line.slice(opener + 2);
114
+ if (count(rest, "(") + 1 > count(rest, ")"))
115
+ return rest;
116
+ }
117
+ for (const quote of `"'`) {
118
+ if (count(line, quote) % 2) {
119
+ const position = line.lastIndexOf(quote);
120
+ if (endsWithLinkAttribute(line.slice(0, position)))
121
+ return line.slice(position + 1);
122
+ }
123
+ }
124
+ return null;
125
+ }
126
+ /** O texto termina num atributo de link (src=, href=, url( ...), com ou sem aspa? Olha só o fim, sem limite de espaços. */
127
+ function endsWithLinkAttribute(text) {
128
+ let end = text.length;
129
+ if (end && `"'`.includes(text[end - 1]))
130
+ end -= 1;
131
+ while (end && /\s/u.test(text[end - 1]))
132
+ end -= 1;
133
+ if (end && text[end - 1] === "=") {
134
+ end -= 1;
135
+ while (end && /\s/u.test(text[end - 1]))
136
+ end -= 1;
137
+ return LINK_ATTRIBUTE_NAME.test(text.slice(Math.max(0, end - 16), end));
138
+ }
139
+ if (end >= 4 && text.slice(end - 4, end).toLowerCase() === "url(")
140
+ return end === 4 || !/[\p{L}\p{N}_]/u.test(text[end - 5]);
141
+ return false;
142
+ }
81
143
  /** Domínio de uma URL absoluta, só se ele já terminou (vazio se o marcador está no próprio domínio). */
82
144
  export function urlHost(url) {
83
145
  const match = HOST.exec(url);
@@ -250,8 +312,11 @@ export class Vault {
250
312
  const entry = this.entryFor(groups);
251
313
  if (!entry)
252
314
  return match;
315
+ // A linha do marcador e a de cima: um link aberto na linha de cima ainda conta ("[x](https://site/?d=" e o
316
+ // marcador sozinho na linha de baixo).
253
317
  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);
318
+ const above = newline > 0 ? text.lastIndexOf("\n", newline - 1) : -1;
319
+ const before = above === -1 ? prefix + text.slice(0, offset) : text.slice(above + 1, offset);
255
320
  if (!restoreAllowed(this.policy, entry.label, before, tool, tool ? context.toolName : undefined))
256
321
  return match;
257
322
  return jsonEscape ? JSON.stringify(entry.original).slice(1, -1) : entry.original;
@@ -323,8 +388,12 @@ export class StreamRestorer {
323
388
  }
324
389
  emit(ready) {
325
390
  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);
391
+ // Guarda a linha atual e a de cima, como a restauração sem streaming vê.
392
+ let combined = this.line + ready;
393
+ const last = combined.lastIndexOf("\n");
394
+ if (last !== -1)
395
+ combined = combined.slice(last > 0 ? combined.lastIndexOf("\n", last - 1) + 1 : 0);
396
+ this.line = combined;
328
397
  return output;
329
398
  }
330
399
  feed(text) {