agent-customs 0.0.0-stage → 1.0.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.
Files changed (48) hide show
  1. package/LICENSE.md +341 -0
  2. package/README.md +592 -2
  3. package/bin/agent-customs.mjs +194 -0
  4. package/package.json +77 -4
  5. package/site/.well-known/agent-customs-key.json +13 -0
  6. package/site/certificate.js +944 -0
  7. package/site/customs/analyze.js +1224 -0
  8. package/site/customs/auto.js +44 -0
  9. package/site/customs/canary.js +270 -0
  10. package/site/customs/canonical.js +123 -0
  11. package/site/customs/capabilities.js +387 -0
  12. package/site/customs/diff.js +236 -0
  13. package/site/customs/english-words.js +153 -0
  14. package/site/customs/guard-notice.js +226 -0
  15. package/site/customs/guard-ui.js +105 -0
  16. package/site/customs/guard.js +259 -0
  17. package/site/customs/inspect.js +446 -0
  18. package/site/customs/judge.js +208 -0
  19. package/site/customs/languages.js +826 -0
  20. package/site/customs/locks.js +967 -0
  21. package/site/customs/pins.js +119 -0
  22. package/site/customs/protocols.js +621 -0
  23. package/site/customs/receipts.js +154 -0
  24. package/site/customs/rules.js +1470 -0
  25. package/site/customs/unicode.js +361 -0
  26. package/site/runtime/LICENSE.txt +176 -0
  27. package/site/runtime/generated/graph.gen.mjs +83 -0
  28. package/site/runtime/generated/validation.gen.mjs +70 -0
  29. package/site/runtime/hocon.js +262 -0
  30. package/site/runtime/kernel.js +237 -0
  31. package/site/runtime/model.js +44 -0
  32. package/tests/fixtures/official/NOTICE +3 -0
  33. package/tests/fixtures/official/guesthouse_agentified/agent-manifest.json +86 -0
  34. package/tests/fixtures/official/guesthouse_agentified/links.json +6 -0
  35. package/tests/fixtures/official/guesthouse_agentified/tidewhistle_guesthouse.network.json +56 -0
  36. package/tests/fixtures/official/harbor_tours_agentified/agent-manifest.json +86 -0
  37. package/tests/fixtures/official/harbor_tours_agentified/links.json +6 -0
  38. package/tests/fixtures/official/harbor_tours_agentified/marrow_point_harbor_tours.network.json +56 -0
  39. package/tests/fixtures/official/pizza_restaurant_agentified/agent-manifest.json +78 -0
  40. package/tests/fixtures/official/pizza_restaurant_agentified/links.json +6 -0
  41. package/tests/fixtures/official/pizza_restaurant_agentified/pizza_restaurant_website_assistant.network.json +156 -0
  42. package/tools/bench.mjs +731 -0
  43. package/tools/external-heldout.mjs +337 -0
  44. package/tools/fs-fetch.mjs +19 -0
  45. package/tools/heldout-corpus.mjs +135 -0
  46. package/tools/inspect-local.mjs +88 -0
  47. package/tools/round2-corpus.mjs +395 -0
  48. package/tools/round3-corpus.mjs +192 -0
@@ -0,0 +1,44 @@
1
+ // auto.js: Agent Customs in one line. Add this to a page made with Cognizant's
2
+ // agentify-website kit, and the guard starts with its default settings:
3
+ //
4
+ // <script type="module" src="https://cdn.jsdelivr.net/gh/montbaga/agent-customs@v1.0.0/site/customs/auto.js"></script>
5
+ //
6
+ // The kit's runtime publishes its engine as window.__nsweb once boot() is done. This file waits
7
+ // for that moment and installs the guard. For other settings, import guard.js instead.
8
+ import { installCustomsGuard } from "./guard.js";
9
+
10
+ /**
11
+ * Install the guard on the runtime's engine as soon as the runtime publishes it.
12
+ *
13
+ * :param target: The page's window.
14
+ * :param install: The installer (installCustomsGuard; tests pass their own).
15
+ */
16
+ export function guardWhenReady(target = globalThis, install = installCustomsGuard) {
17
+ const attach = (value) => {
18
+ if (!value?.engine) return;
19
+ try {
20
+ install(value.engine);
21
+ } catch (error) {
22
+ // Never break the page's own start-up.
23
+ console.error("Agent Customs could not start:", error);
24
+ }
25
+ };
26
+ const existing = Object.getOwnPropertyDescriptor(target, "__nsweb");
27
+ if (existing && "value" in existing) {
28
+ attach(existing.value);
29
+ return;
30
+ }
31
+ if (existing) return;
32
+ let current;
33
+ Object.defineProperty(target, "__nsweb", {
34
+ configurable: true,
35
+ enumerable: true,
36
+ get: () => current,
37
+ set: (value) => {
38
+ current = value;
39
+ attach(value);
40
+ },
41
+ });
42
+ }
43
+
44
+ if (typeof window !== "undefined") guardWhenReady(window);
@@ -0,0 +1,270 @@
1
+ // canary.js: synthetic canary tokens and multi-encoding exfiltration detection.
2
+ //
3
+ // A canary token sits in protected host context that outside partners should never see or
4
+ // echo back. If a partner or compromised turn tries to exfiltrate the token in raw,
5
+ // URL-encoded, Base64 (at any 0/1/2-byte offset), Base64url, hex, ROT13, spaced, or
6
+ // reversed form, detectCanaryLeak() flags the channel.
7
+ //
8
+ // Known limit: a token split piece-by-piece across separate fields or separate tool calls
9
+ // cannot be reassembled reliably in general without high false-positive risk.
10
+
11
+ function randomHex(bytes = 6) {
12
+ const buf = new Uint8Array(bytes);
13
+ if (globalThis.crypto?.getRandomValues) {
14
+ globalThis.crypto.getRandomValues(buf);
15
+ } else {
16
+ for (let i = 0; i < bytes; i += 1) buf[i] = Math.floor(Math.random() * 256);
17
+ }
18
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
19
+ }
20
+
21
+ function toBase64Bytes(bytes) {
22
+ let bin = "";
23
+ for (const b of bytes) bin += String.fromCharCode(b);
24
+ return btoa(bin);
25
+ }
26
+
27
+ function toBase64(text) {
28
+ return toBase64Bytes(new TextEncoder().encode(text));
29
+ }
30
+
31
+ function toHex(text) {
32
+ const bytes = new TextEncoder().encode(text);
33
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
34
+ }
35
+
36
+ function rot13(text) {
37
+ return String(text || "").replace(/[A-Za-z]/g, (c) => {
38
+ const base = c <= "Z" ? 90 : 122;
39
+ const n = c.charCodeAt(0) + 13;
40
+ return String.fromCharCode(base >= n ? n : n - 26);
41
+ });
42
+ }
43
+
44
+ function fromBase64Chunk(blob) {
45
+ const std = blob.replace(/-/g, "+").replace(/_/g, "/");
46
+ if (std.length % 4 === 1) return "";
47
+ const padded = std.includes("=") ? std : std + "=".repeat((4 - (std.length % 4)) % 4);
48
+ try {
49
+ const bin = typeof atob === "function" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
50
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
51
+ return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
52
+ } catch {
53
+ return "";
54
+ }
55
+ }
56
+
57
+ // Compute alignment-independent Base64/Base64url interior substrings for offsets k = 0, 1, 2
58
+ // so tokens embedded mid-string (e.g. btoa("ctx:" + token + "}")) match reliably.
59
+ function base64OffsetNeedles(token) {
60
+ const rawBytes = new TextEncoder().encode(token);
61
+ const b64Needles = [];
62
+ const b64uNeedles = [];
63
+ for (let k = 0; k < 3; k += 1) {
64
+ const buf = new Uint8Array(k + rawBytes.length);
65
+ buf.set(rawBytes, k);
66
+ const fullB64 = toBase64Bytes(buf);
67
+ const fullB64u = fullB64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
68
+ const start = k > 0 ? 4 : 0;
69
+ const cleanEnd = Math.floor(buf.length / 3) * 4;
70
+ if (cleanEnd - start >= 12) {
71
+ b64Needles.push(fullB64.slice(start, cleanEnd));
72
+ b64uNeedles.push(fullB64u.slice(start, cleanEnd));
73
+ }
74
+ }
75
+ return { b64Needles, b64uNeedles };
76
+ }
77
+
78
+ /**
79
+ * Create a high-entropy canary token for runtime tripwire checks.
80
+ *
81
+ * :param prefix: Identifier prefix (default "ac_cnr_").
82
+ * :return: A canary string unlikely to occur in normal traffic.
83
+ */
84
+ export function generateCanaryToken(prefix = "ac_cnr_") {
85
+ return `${prefix}${randomHex(6)}`;
86
+ }
87
+
88
+ /**
89
+ * Compute encodings an attacker might use to disguise a canary token in transit.
90
+ *
91
+ * :param token: The active canary token.
92
+ * :return: Object mapping encoding label to encoded string.
93
+ */
94
+ export function canaryEncodings(token) {
95
+ const raw = String(token || "");
96
+ if (!raw) return null;
97
+ const b64 = toBase64(raw);
98
+ return {
99
+ raw,
100
+ reversed: [...raw].reverse().join(""),
101
+ base64: b64,
102
+ base64url: b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""),
103
+ hex: toHex(raw),
104
+ rot13: rot13(raw),
105
+ };
106
+ }
107
+
108
+ function fromHexBytes(hexStr) {
109
+ if (!hexStr || hexStr.length % 2 !== 0) return "";
110
+ try {
111
+ const bytes = new Uint8Array(hexStr.length / 2);
112
+ for (let i = 0; i < hexStr.length; i += 2) {
113
+ bytes[i / 2] = parseInt(hexStr.slice(i, i + 2), 16);
114
+ }
115
+ return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
116
+ } catch {
117
+ return "";
118
+ }
119
+ }
120
+
121
+ function canaryTargets(token) {
122
+ const raw = String(token || "");
123
+ if (!raw) return [];
124
+ const targets = [raw];
125
+ // Extract the random entropy suffix when present (e.g. 12 hex chars in ac_cnr_...);
126
+ // 10+ hex/token suffix chars carry negligible chance-match risk if sent without the prefix.
127
+ const suffixMatch = raw.match(/^(?:[a-z][a-z0-9]*_[a-z]+_|ac_cnr_)([0-9a-f]{10,}|[a-z0-9]{11,})$/i);
128
+ if (suffixMatch && suffixMatch[1] && suffixMatch[1].length < raw.length) {
129
+ targets.push(suffixMatch[1]);
130
+ }
131
+ return targets;
132
+ }
133
+
134
+ function buildTargetCheck(target) {
135
+ const enc = canaryEncodings(target);
136
+ const { b64Needles, b64uNeedles } = base64OffsetNeedles(enc.raw);
137
+ return {
138
+ enc,
139
+ b64Needles,
140
+ b64uNeedles,
141
+ compactToken: enc.raw.replace(/[^a-z0-9]/gi, "").toLowerCase(),
142
+ compactRev: enc.reversed.replace(/[^a-z0-9]/gi, "").toLowerCase(),
143
+ compactRot13: enc.rot13.replace(/[^a-z0-9]/gi, "").toLowerCase(),
144
+ };
145
+ }
146
+
147
+ function matchSinglePass(text, isUrlDecoded, c) {
148
+ const { enc, b64Needles, b64uNeedles, compactToken, compactRev, compactRot13 } = c;
149
+ const lower = text.toLowerCase();
150
+ const noWs = /(?:\\[nrt]|\s)/.test(text) ? text.replace(/(?:\\[nrt]|\s)+/g, "") : "";
151
+ const compactText = text.replace(/[^a-z0-9]/gi, "").toLowerCase();
152
+ const compactHex = text.replace(/0x/gi, "").replace(/[^0-9a-f]/gi, "").toLowerCase();
153
+
154
+ if (text.includes(enc.raw) || lower.includes(enc.raw.toLowerCase())) {
155
+ return { leaked: true, encoding: isUrlDecoded ? "url" : "raw" };
156
+ }
157
+ if (text.includes(enc.reversed) || lower.includes(enc.reversed.toLowerCase())) {
158
+ return { leaked: true, encoding: "reversed" };
159
+ }
160
+ if (text.includes(enc.rot13) || lower.includes(enc.rot13.toLowerCase())) {
161
+ return { leaked: true, encoding: "rot13" };
162
+ }
163
+ if (text.includes(enc.base64) || (noWs && noWs.includes(enc.base64))) return { leaked: true, encoding: "base64" };
164
+ if (text.includes(enc.base64url) || (noWs && noWs.includes(enc.base64url))) return { leaked: true, encoding: "base64url" };
165
+ if (b64Needles.some((n) => text.includes(n) || (noWs && noWs.includes(n)))) return { leaked: true, encoding: "base64" };
166
+ if (b64uNeedles.some((n) => text.includes(n) || (noWs && noWs.includes(n)))) return { leaked: true, encoding: "base64url" };
167
+ if (lower.includes(enc.hex) || compactHex.includes(enc.hex)) return { leaked: true, encoding: "hex" };
168
+
169
+ if (compactToken.length >= 8) {
170
+ if (compactText.includes(compactToken)) return { leaked: true, encoding: "spaced" };
171
+ if (compactText.includes(compactRev)) return { leaked: true, encoding: "reversed" };
172
+ if (compactText.includes(compactRot13)) return { leaked: true, encoding: "rot13" };
173
+ }
174
+ return null;
175
+ }
176
+
177
+ function collectLeafStrings(value, out = [], seen = new Set()) {
178
+ if (typeof value === "string") {
179
+ if (value) out.push(value);
180
+ return out;
181
+ }
182
+ if (!value || typeof value !== "object" || seen.has(value)) return out;
183
+ seen.add(value);
184
+ if (Array.isArray(value)) {
185
+ for (const item of value) collectLeafStrings(item, out, seen);
186
+ return out;
187
+ }
188
+ for (const v of Object.values(value)) collectLeafStrings(v, out, seen);
189
+ return out;
190
+ }
191
+
192
+ function matchTargets(value, checks, depth = 0) {
193
+ if (!checks.length || value === null || value === undefined || depth > 2) return null;
194
+ if (typeof value !== "string") {
195
+ for (const leaf of collectLeafStrings(value)) {
196
+ const hit = matchTargets(leaf, checks, depth);
197
+ if (hit) return hit;
198
+ }
199
+ }
200
+ const serialized = typeof value === "string" ? value : JSON.stringify(value ?? "");
201
+ if (!serialized) return null;
202
+
203
+ const variants = [serialized];
204
+ if (/%[0-9a-f]{2}|\+/i.test(serialized)) {
205
+ try {
206
+ const decoded = decodeURIComponent(serialized.replace(/\+/g, " "));
207
+ if (decoded !== serialized) variants.push(decoded);
208
+ } catch { /* malformed percent-escapes stay as serialized */ }
209
+ }
210
+
211
+ // Test full-token checks across all variants first so URL-encoded ac%5Fcnr%5F... reports
212
+ // "url" before falling back to standalone random suffix matches.
213
+ for (const c of checks) {
214
+ for (let i = 0; i < variants.length; i += 1) {
215
+ const hit = matchSinglePass(variants[i], i > 0, c);
216
+ if (hit) return hit;
217
+ }
218
+ }
219
+
220
+ if (depth < 2) {
221
+ for (let i = 0; i < variants.length; i += 1) {
222
+ const text = variants[i];
223
+ const noWs = /(?:\\[nrt]|\s)/.test(text) ? text.replace(/(?:\\[nrt]|\s)+/g, "") : "";
224
+ const b64Sources = noWs ? [text, noWs] : [text];
225
+ for (const src of b64Sources) {
226
+ const b64Runs = src.match(/(?<![A-Za-z0-9+/_=-])[A-Za-z0-9+/_-]{16,}={0,2}(?![A-Za-z0-9+/_=-])/g) || [];
227
+ for (const chunk of b64Runs) {
228
+ const decoded = fromBase64Chunk(chunk);
229
+ if (!decoded) continue;
230
+ const inner = matchTargets(decoded, checks, depth + 1);
231
+ if (inner) return { leaked: true, encoding: inner.encoding === "raw" ? "base64" : inner.encoding };
232
+ }
233
+ }
234
+
235
+ const hexByteRuns = text.match(/(?:0x)?[0-9a-f]{2}(?:[\s,:;-]+(?:0x)?[0-9a-f]{2}){5,}/gi) || [];
236
+ for (const run of hexByteRuns) {
237
+ const cleanHex = run.replace(/0x/gi, "").replace(/[^0-9a-f]/gi, "");
238
+ const decoded = fromHexBytes(cleanHex);
239
+ if (!decoded) continue;
240
+ const inner = matchTargets(decoded, checks, depth + 1);
241
+ if (inner) return { leaked: true, encoding: inner.encoding === "raw" ? "hex" : inner.encoding };
242
+ }
243
+
244
+ const codeRuns = text.match(/(?<!\d)(?:(?:1[01]\d|12[0-6]|[3-9]\d)(?:\s*,\s*|\s+)){7,}(?:1[01]\d|12[0-6]|[3-9]\d)(?!\d)/g) || [];
245
+ for (const run of codeRuns) {
246
+ const nums = run.trim().split(/[\s,]+/).map((n) => Number(n));
247
+ if (!nums.every((n) => n >= 32 && n <= 126)) continue;
248
+ const decoded = String.fromCharCode(...nums);
249
+ const inner = matchTargets(decoded, checks, depth + 1);
250
+ if (inner) return { leaked: true, encoding: inner.encoding === "raw" ? "charcodes" : inner.encoding };
251
+ }
252
+ }
253
+ }
254
+ return null;
255
+ }
256
+
257
+ /**
258
+ * Check a string or JSON-serializable value for a canary token across common encodings.
259
+ *
260
+ * :param value: Text, URL, or tool/action arguments object.
261
+ * :param token: Active canary token.
262
+ * :param depth: Internal recursion depth when inspecting Base64/hex/charcode chunks.
263
+ * :return: { leaked: true, encoding } when detected, or null otherwise.
264
+ */
265
+ export function detectCanaryLeak(value, token, depth = 0) {
266
+ const targets = canaryTargets(token);
267
+ if (!targets.length || targets[0].length < 6) return null;
268
+ const checks = targets.map(buildTargetCheck);
269
+ return matchTargets(value, checks, depth);
270
+ }
@@ -0,0 +1,123 @@
1
+ // canonical.js: a stable fingerprint for a published agent network.
2
+ //
3
+ // The fingerprint is the SHA-256 of the network's canonical JSON: keys sorted, no
4
+ // whitespace. Two files that differ only in key order or spacing get the same
5
+ // fingerprint; any change to an instruction, tool or schema gives a new one.
6
+
7
+ /**
8
+ * Serialize a JSON value with sorted object keys and no whitespace.
9
+ *
10
+ * :param value: Any JSON-compatible value.
11
+ * :return: The canonical JSON string.
12
+ */
13
+ export function canonicalJson(value) {
14
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
15
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
16
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
17
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
18
+ }
19
+
20
+ /**
21
+ * The part of a compiled network that defines its behavior. The runtime merges the
22
+ * site's links.json into config.links; links are fingerprinted separately, so a
23
+ * network's identity does not change when only its partner bindings do.
24
+ *
25
+ * :param config: The runtime's filtered network config (AgentNetwork.config).
26
+ * :return: {network, links}
27
+ */
28
+ export function splitConfig(config) {
29
+ const { links, ...network } = config || {};
30
+ return { network, links: links || {} };
31
+ }
32
+
33
+ /**
34
+ * SHA-256 of a string, as lowercase hex. Uses Web Crypto when it is available
35
+ * (browsers on HTTPS or localhost, and Node 20+), and a small JavaScript fallback
36
+ * otherwise, so plain-HTTP previews still work.
37
+ *
38
+ * :param text: The string to hash (UTF-8).
39
+ * :return: The hex digest.
40
+ */
41
+ export async function sha256Hex(text) {
42
+ const bytes = new TextEncoder().encode(text);
43
+ const subtle = globalThis.crypto?.subtle;
44
+ if (subtle) {
45
+ const digest = await subtle.digest("SHA-256", bytes);
46
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
47
+ }
48
+ return sha256Fallback(bytes);
49
+ }
50
+
51
+ /**
52
+ * Fingerprint a compiled network config.
53
+ *
54
+ * :param config: AgentNetwork.config.
55
+ * :return: {hash, linksHash, short}, where hash looks like "sha256:ab12…".
56
+ */
57
+ export async function fingerprintConfig(config) {
58
+ const { network, links } = splitConfig(config);
59
+ const hash = "sha256:" + await sha256Hex(canonicalJson(network));
60
+ const linksHash = "sha256:" + await sha256Hex(canonicalJson(links));
61
+ return { hash, linksHash, short: hash.slice(7, 19) };
62
+ }
63
+
64
+ const K = new Uint32Array([
65
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
66
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
67
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
68
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
69
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
70
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
71
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
72
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
73
+ ]);
74
+
75
+ function sha256Fallback(bytes) {
76
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
77
+ const bitLen = bytes.length * 8;
78
+ const padded = new Uint8Array(((bytes.length + 9 + 63) >> 6) << 6);
79
+ padded.set(bytes);
80
+ padded[bytes.length] = 0x80;
81
+ const view = new DataView(padded.buffer);
82
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
83
+ view.setUint32(padded.length - 4, bitLen >>> 0);
84
+ const w = new Uint32Array(64);
85
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
86
+ for (let off = 0; off < padded.length; off += 64) {
87
+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
88
+ for (let i = 16; i < 64; i += 1) {
89
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
90
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
91
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
92
+ }
93
+ let [a, b, c, d, e, f, g, hh] = h;
94
+ for (let i = 0; i < 64; i += 1) {
95
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
96
+ const ch = (e & f) ^ (~e & g);
97
+ const t1 = (hh + S1 + ch + K[i] + w[i]) >>> 0;
98
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
99
+ const maj = (a & b) ^ (a & c) ^ (b & c);
100
+ const t2 = (S0 + maj) >>> 0;
101
+ hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
102
+ }
103
+ h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
104
+ }
105
+ return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join("");
106
+ }
107
+
108
+ /**
109
+ * Validate an International Bank Account Number using ISO 7064 Mod-97 check digits.
110
+ *
111
+ * :param raw: Candidate IBAN string.
112
+ * :return: True when length and check digits validate cleanly.
113
+ */
114
+ export function ibanValid(raw) {
115
+ const s = String(raw || "").replace(/\s+/g, "").toUpperCase();
116
+ if (s.length < 15 || s.length > 34 || !/^[A-Z]{2}\d{2}[A-Z0-9]+$/.test(s)) return false;
117
+ let rest = 0;
118
+ for (const ch of s.slice(4) + s.slice(0, 4)) {
119
+ const v = ch >= "A" && ch <= "Z" ? ch.charCodeAt(0) - 55 : ch.charCodeAt(0) - 48;
120
+ rest = (rest * (v > 9 ? 100 : 10) + v) % 97;
121
+ }
122
+ return rest === 1;
123
+ }