@paybox-sh/sdk 2.3.0 → 2.4.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/README.md +10 -1
- package/SKILL.md +34 -5
- package/dist/{chunk-YTHYNUMM.js → chunk-ACNRTJGL.js} +22 -4
- package/dist/chunk-ACNRTJGL.js.map +1 -0
- package/dist/cli.js +150 -26
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-YTHYNUMM.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/pairing.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/utils.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/_md.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha2.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha256.ts","../node_modules/.pnpm/@paybox+mcp-app@file+..+mcp-app_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__bn.js@5.2.3_ac1e09a20c76a1143611be5dd3d4f9db/node_modules/@paybox/mcp-app/src/signing/agent-code.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync, rmSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport { Command } from \"commander\";\n\nimport { appBaseFrom, loginDevice, openBrowser, refreshTokens } from \"./auth.js\";\nimport { pairSigningKey } from \"./pairing.js\";\nimport { PayboxClient, didNotHappen } from \"./client.js\";\nimport { configDir, configFile, loadConfig, saveConfig } from \"./config.js\";\nimport { pendingFundingResponse, pendingFundingToolResponse } from \"./pending-funding.js\";\nimport type { AgentResponse, McpToolResult, PluginSource, PluginStatus } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.paybox.sh\";\nconst PKG = \"@paybox-sh/sdk\";\nconst VERSION = createRequire(import.meta.url)(\"../package.json\").version as string;\n\nconst program = new Command();\nprogram\n .name(\"paybox\")\n .description(\"PayBox agent CLI — vaulted cards, wallets, and secrets for agents\")\n .version(VERSION)\n .option(\"--base-url <url>\", \"API origin (default https://api.paybox.sh or stored)\")\n .option(\"--json\", \"machine-readable JSON output\");\n\nfunction jsonMode(): boolean {\n return Boolean(program.opts().json);\n}\n\nfunction emit(data: unknown): void {\n const funding = pendingFundingResponse(data) ?? (\n Array.isArray((data as McpToolResult | null)?.content)\n ? pendingFundingToolResponse(data as McpToolResult) : null\n );\n if (funding) {\n console.error(\n \"Request incomplete; funding status is pending, not proof that funding has started or completed. \" +\n `Poll \\`paybox request ${funding.request_id}\\`; do not repeat the purchase.`,\n );\n }\n if (jsonMode()) console.log(JSON.stringify(data, null, 2));\n else console.dir(data, { depth: null, colors: process.stdout.isTTY });\n const d = data as {\n status?: unknown;\n response?: { status?: unknown };\n isError?: unknown;\n } | null;\n if (!funding && (didNotHappen(d) || didNotHappen(d?.response) || d?.isError === true)) {\n process.exitCode = 1;\n }\n}\n\nfunction client(): PayboxClient {\n return PayboxClient.fromConfig({ baseUrl: program.opts().baseUrl });\n}\n\nfunction readIntent(value: string): unknown {\n const raw = value.startsWith(\"@\") ? readFileSync(value.slice(1), \"utf8\") : value;\n return JSON.parse(raw);\n}\n\nfunction readObject(value: string): Record<string, unknown> {\n const parsed = readIntent(value);\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"--input must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction int(flag: string, value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n)) {\n throw new Error(`--${flag} must be an integer, got ${JSON.stringify(value)}`);\n }\n return n;\n}\n\nfunction optInt(flag: string, value: string | undefined): number | undefined {\n return value === undefined ? undefined : int(flag, value);\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction credentialId(value: string): string {\n return uuid(\n value,\n \"--credential expects a credential id, not a name\",\n \"Run `paybox credentials` and use the `credential.id` of the one you want.\",\n );\n}\n\nfunction requestId(value: string): string {\n return uuid(\n value,\n \"not a request id\",\n \"Request ids come back from the command that created the request, and from `paybox requests`.\",\n );\n}\n\nfunction uuid(value: string, what: string, hint: string): string {\n if (UUID.test(value)) return value;\n throw new Error(`${what}: got ${JSON.stringify(value)}. ${hint}`);\n}\n\nfunction isNewer(a: string, b: string): boolean {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n const x = pa[i] ?? 0;\n const y = pb[i] ?? 0;\n if (x !== y) return x > y;\n }\n return false;\n}\n\nasync function run(fn: () => Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (jsonMode()) console.log(JSON.stringify({ error: message }, null, 2));\n else console.error(message);\n process.exitCode = 1;\n }\n}\n\nfunction withNextAction(c: PayboxClient, result: unknown): unknown {\n const value = result as { status?: unknown; response?: unknown };\n const response = value.response as AgentResponse | undefined;\n if (response?.status) {\n return {\n ...value,\n response: { ...response, next_action: c.nextAction(response) },\n };\n }\n if (value.status) {\n return { ...value, next_action: c.nextAction(value as AgentResponse) };\n }\n return result;\n}\n\n\nfunction resolveBaseUrl(): string {\n const cfg = loadConfig();\n return (\n program.opts().baseUrl ??\n process.env.PAYBOX_API_URL ??\n cfg.baseUrl ??\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, \"\");\n}\n\nprogram\n .command(\"login\")\n .description(\"Authenticate via OAuth device approval, or store a pbx_live_ key\")\n .option(\"--key <key>\", \"store a pbx_live_ personal API key instead of OAuth\")\n .option(\"--no-open\", \"print the approval link without opening a browser\")\n .action((opts) =>\n run(async () => {\n const cfg = loadConfig();\n cfg.baseUrl = resolveBaseUrl();\n if (opts.key) {\n cfg.apiKey = opts.key;\n delete cfg.oauth;\n } else {\n cfg.oauth = await loginDevice(cfg.baseUrl, { open: opts.open });\n delete cfg.apiKey;\n }\n delete cfg.signingKey;\n saveConfig(cfg);\n console.error(`Saved credentials to ${configFile()}`);\n if (!process.env.PAYBOX_SIGNING_KEY) {\n console.error(\"Run `paybox connect` to connect a signing key; until then sign and swap stop at pending_signature.\");\n }\n }),\n );\n\nprogram\n .command(\"connect\")\n .description(\"Connect a wallet signing key to this machine by picking a number in PayBox\")\n .option(\"--app-url <url>\", \"PayBox app origin (default: derived from --base-url)\")\n .option(\"--no-open\", \"print the pairing link without opening a browser\")\n .action((opts) =>\n run(async () => {\n const cfg = loadConfig();\n const baseUrl = resolveBaseUrl();\n const appBase = appBaseFrom(baseUrl, opts.appUrl ?? process.env.PAYBOX_APP_URL ?? cfg.appUrl);\n if (!appBase) throw new Error(\"could not derive the PayBox app origin — pass --app-url\");\n if (opts.appUrl) cfg.appUrl = opts.appUrl;\n if (!cfg.apiKey && cfg.oauth?.expiresAt && Date.now() > cfg.oauth.expiresAt - 30_000) {\n cfg.oauth = await refreshTokens(baseUrl, cfg.oauth);\n saveConfig(cfg);\n }\n const bearer = cfg.apiKey ?? cfg.oauth?.accessToken;\n if (!bearer) throw new Error(\"not authenticated — run `paybox login` first\");\n cfg.signingKey = await pairSigningKey({\n baseUrl,\n appBase,\n bearer,\n onCode(code, url) {\n console.error(`\\n ${code}\\n`);\n console.error(`Open this on any device and pick that number to connect this machine:\\n ${url}\\n`);\n if (opts.open) openBrowser(url);\n },\n });\n saveConfig(cfg);\n console.error(\"Connected — sign and swap are enabled on this machine.\");\n }),\n );\n\nprogram\n .command(\"logout\")\n .description(\"Forget stored credentials\")\n .action(() =>\n run(async () => {\n const cfg = loadConfig();\n delete cfg.apiKey;\n delete cfg.oauth;\n delete cfg.signingKey;\n saveConfig(cfg);\n console.error(\"Logged out.\");\n }),\n );\n\nprogram\n .command(\"whoami\")\n .description(\"Show the configured endpoint, auth mode, and signing capability\")\n .action(() =>\n run(async () => {\n const cfg = loadConfig();\n const c = client();\n const mode = process.env.PAYBOX_ACCESS_TOKEN\n ? \"oauth (env token)\"\n : process.env.PAYBOX_API_KEY || cfg.apiKey\n ? \"api key\"\n : cfg.oauth\n ? \"oauth\"\n : \"none\";\n emit({ baseUrl: c.baseUrl, auth: mode, canSign: c.canSign, configFile: configFile() });\n }),\n );\n\nprogram\n .command(\"credentials\")\n .description(\"List the credentials this client may use\")\n .action(() => run(async () => emit(await client().listCredentials())));\n\nprogram\n .command(\"pay\")\n .description(\"Charge a card credential\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--merchant <name>\")\n .requiredOption(\"--url <url>\", \"real merchant URL the card is bound to\")\n .requiredOption(\"--amount <cents>\", \"amount in cents\")\n .option(\"--currency <code>\", \"ISO 4217 currency\", \"USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().requestPayment({\n credentialId: credentialId(o.credential),\n merchant: o.merchant,\n merchantUrl: o.url,\n amountCents: int(\"amount\", o.amount),\n currency: o.currency,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"secret\")\n .description(\"Reveal a secret credential (one-time token, or --raw value)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .option(\"--raw\", \"return the raw secret value (grant-gated)\")\n .option(\"--purpose <text>\", \"why the secret is requested (shown on approval)\")\n .action((o) =>\n run(async () =>\n emit(\n await client().requestSecret({\n credentialId: credentialId(o.credential),\n raw: Boolean(o.raw),\n purpose: o.purpose,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"sign\")\n .description(\"Sign with a wallet credential (intent JSON, or @file)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--intent <json>\", 'a SignIntent, e.g. \\'{\"op\":\"message\",\"message\":\"hi\"}\\' or @intent.json')\n .action((o) =>\n run(async () => {\n const c = client();\n const res = await c.requestWalletSign({\n credentialId: credentialId(o.credential),\n intent: readIntent(o.intent) as never,\n });\n emit(withNextAction(c, res));\n }),\n );\n\nprogram\n .command(\"swap\")\n .description(\"Swap tokens from a wallet credential\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--src-chain <caip2>\")\n .requiredOption(\"--src-token <addr>\", '\"native\" or a token address')\n .requiredOption(\"--dst-token <addr>\")\n .requiredOption(\"--amount <smallest-unit>\", \"source amount in smallest units\")\n .option(\"--dst-chain <caip2>\", \"defaults to --src-chain\")\n .option(\"--direction <dir>\", \"exact-amount-in | exact-amount-out\", \"exact-amount-in\")\n .option(\"--slippage <bps>\", \"slippage in bps\", \"150\")\n .option(\"--recipient <addr>\")\n .option(\"--value-cents <n>\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.requestSwap(\n {\n credentialId: credentialId(o.credential),\n srcChain: o.srcChain,\n dstChain: o.dstChain,\n srcToken: o.srcToken,\n dstToken: o.dstToken,\n amount: o.amount,\n swapDirection: o.direction,\n slippageBps: int(\"slippage\", o.slippage),\n recipient: o.recipient,\n valueCents: optInt(\"value-cents\", o.valueCents),\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"discover [query]\")\n .description(\"Discover curated paid x402 services from Bazaar (optional search)\")\n .option(\"--raw\", \"return uncurated compact Bazaar service summaries (debug)\")\n .action((query, o) =>\n run(async () => emit(await client().discoverServices(query, { raw: Boolean(o.raw) }))),\n );\n\nprogram\n .command(\"pay-x402\")\n .description(\"Pay a paid x402 endpoint (header mode — returns the X-PAYMENT header to replay)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--accepts <json>\", \"the 402's accepts[] array (JSON or @file)\")\n .requiredOption(\"--url <url>\", \"the paywalled resource URL\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.payX402(\n {\n credentialId: credentialId(o.credential),\n accepts: readIntent(o.accepts) as unknown[],\n resourceUrl: o.url,\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"use-service\")\n .description(\"Fetch a paid x402 resource and have paybox pay for it (gateway mode)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--url <url>\", \"the paid x402 resource URL\")\n .option(\"--method <verb>\", \"HTTP method\", \"GET\")\n .option(\"--body <json>\", \"request body (JSON or @file)\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.useService(\n {\n credentialId: credentialId(o.credential),\n url: o.url,\n method: o.method,\n body: o.body === undefined ? undefined : readIntent(o.body),\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"portfolio\")\n .description(\"List a wallet address's token balances across chains\")\n .requiredOption(\"--address <addr>\")\n .option(\"--networks <ids>\", 'comma-separated network IDs, e.g. \"1,8453\"')\n .option(\"--token <addr>\", \"mint, ERC-20, or native\")\n .option(\"--network-id <id>\", \"MoonX network id required with --token\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getPortfolio({\n address: o.address,\n networkIds: o.networks,\n token: o.token,\n networkId: o.networkId == null ? undefined : Number(o.networkId),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"verify-solana-balance\")\n .description(\"Verify a Solana transaction's wallet/token effect and current balance\")\n .requiredOption(\"--address <addr>\", \"canonical Solana wallet address\")\n .requiredOption(\"--mint <addr>\", \"canonical SPL or Token-2022 mint\")\n .requiredOption(\"--transaction <signature>\", \"confirmed Solana transaction signature\")\n .action((o) =>\n run(async () =>\n emit(\n await client().verifySolanaBalance({\n address: o.address,\n tokenMint: o.mint,\n transactionSignature: o.transaction,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"claim <request-id>\")\n .description(\"Claim the usable card credentials of an approved payment (one-time)\")\n .action((id) => run(async () => emit(await client().claimPaymentCredentials(requestId(id)))));\n\nprogram\n .command(\"account-change\")\n .description(\"Get a manage_url for the USER to update this client's access in the app\")\n .option(\"--note <text>\", \"why the change is needed (shown to the user)\")\n .action((o) => run(async () => emit(await client().requestAccountChange(o.note))));\n\nprogram\n .command(\"deposit-link\")\n .description(\"Open Deposit URL for a granted wallet (charges nothing)\")\n .requiredOption(\"--credential <id>\", \"a granted wallet credential\")\n .option(\"--amount-usd <n>\", \"optional amount hint in USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getDepositLink({\n credentialId: credentialId(o.credential),\n amountUsd: o.amountUsd === undefined ? undefined : Number(o.amountUsd),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"buy-link\")\n .description(\"Signed MoonPay checkout URL funding a granted wallet (charges nothing)\")\n .requiredOption(\"--credential <id>\", \"a granted wallet credential\")\n .option(\n \"--destination <chain>\",\n \"exact network: eip155:8453 (default EVM), eip155:1, eip155:4663, or solana:mainnet\",\n )\n .option(\"--currency <code>\", \"enabled MoonPay code matching the exact destination\")\n .option(\"--amount-usd <n>\", \"prefill amount in USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getBuyLink({\n credentialId: credentialId(o.credential),\n destinationChain: o.destination,\n currencyCode: o.currency,\n amountUsd: o.amountUsd === undefined ? undefined : Number(o.amountUsd),\n }),\n ),\n ),\n );\n\nconst plugins = program\n .command(\"plugins\")\n .description(\"Discover and use enabled plugins\");\n\nplugins\n .command(\"list [query]\")\n .description(\"Discover plugins at runtime\")\n .option(\"--source <source>\", \"all | official | user\", \"all\")\n .option(\"--status <status>\", \"all | enabled | disabled\", \"all\")\n .option(\"--limit <n>\", \"results per page\")\n .option(\"--cursor <cursor>\", \"cursor returned by the previous page\")\n .action((query, o) =>\n run(async () =>\n emit(\n await client().discoverPlugins({\n query,\n source: o.source as PluginSource,\n status: o.status as PluginStatus,\n limit: optInt(\"limit\", o.limit),\n cursor: o.cursor,\n }),\n ),\n ),\n );\n\nplugins\n .command(\"contract <contract-uri>\")\n .description(\"Read an official plugin contract returned by discovery\")\n .action((contractUri) =>\n run(async () => emit(await client().getPluginContract(contractUri))),\n );\n\nplugins\n .command(\"use <plugin-id> <tool-id>\")\n .description(\"Invoke a tool from its discovered plugin contract\")\n .option(\"--input <json>\", \"JSON object or @file\", \"{}\")\n .option(\"--invocation-id <uuid>\", \"reuse only for the same unofficial plugin call\")\n .action((pluginId, toolId, o) =>\n run(async () =>\n emit(\n await client().usePlugin({\n pluginId,\n toolId,\n input: readObject(o.input),\n invocationId: o.invocationId === undefined\n ? undefined\n : uuid(\n o.invocationId,\n \"--invocation-id expects a UUID\",\n \"Reuse it only to retrieve the same unofficial plugin invocation.\",\n ),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"request <id>\")\n .description(\"Poll a request's status\")\n .option(\"--wait\", \"block until it leaves the pending state\")\n .option(\"--complete-signature\", \"sign an existing wallet-sign request with the local key\")\n .action((id, o) =>\n run(async () => {\n const c = client();\n const rid = requestId(id);\n const response = o.completeSignature\n ? await c.completeWalletSignRequest(rid)\n : await c.getRequest(rid);\n emit(withNextAction(c, o.wait ? await c.waitForRequest(rid) : response));\n }),\n );\n\nprogram\n .command(\"version\")\n .description(\"Show the installed CLI version (and whether an update is available)\")\n .action(() =>\n run(async () => {\n let latest: string | undefined;\n try {\n const res = await fetch(`https://registry.npmjs.org/${PKG}/latest`);\n if (res.ok) latest = ((await res.json()) as { version?: string }).version;\n } catch {\n }\n const updateAvailable = Boolean(latest && isNewer(latest, VERSION));\n if (jsonMode()) {\n emit({\n version: VERSION,\n latest: latest ?? null,\n updateAvailable,\n binary: process.argv[1] ?? null,\n });\n return;\n }\n console.log(`${PKG} v${VERSION}`);\n if (updateAvailable) {\n console.log(`Update available: v${latest} — run \\`paybox update\\`.`);\n }\n }),\n );\n\nprogram\n .command(\"update\")\n .description(\"Update the globally-installed paybox CLI to the latest version\")\n .option(\"--print\", \"print the update command instead of running it\")\n .action((opts) =>\n run(async () => {\n const args = [\"install\", \"-g\", `${PKG}@latest`];\n if (opts.print) {\n console.log(`npm ${args.join(\" \")}`);\n return;\n }\n console.error(`Updating ${PKG} (npm ${args.join(\" \")})…`);\n const r = spawnSync(\"npm\", args, { stdio: \"inherit\" });\n if (r.status !== 0) {\n console.error(\n `\\nIf this isn't a global install: run \\`pnpm up ${PKG}\\` in your project, ` +\n `or use \\`npx ${PKG}@latest …\\` to always run the latest.`,\n );\n process.exitCode = r.status ?? 1;\n }\n }),\n );\n\nprogram\n .command(\"uninstall\")\n .description(\"Remove stored PayBox credentials/config (and show how to remove the CLI)\")\n .action(() =>\n run(async () => {\n const dir = configDir();\n rmSync(dir, { recursive: true, force: true });\n console.error(`Removed stored config at ${dir}.`);\n console.error(\n `The CLI binary is managed by npm — remove it with:\\n npm rm -g ${PKG}`,\n );\n }),\n );\n\nfunction rejectUnknownCommand(argv: string[]): void {\n if (!argv.includes(\"--help\") && !argv.includes(\"-h\")) return;\n let node: Command = program;\n for (let i = 2; i < argv.length; i++) {\n const arg = argv[i];\n if (node.options.some((o) => o.long === arg && o.required)) i++;\n if (arg.startsWith(\"-\")) continue;\n const next = node.commands.find((c) => c.name() === arg || c.aliases().includes(arg));\n if (next) {\n node = next;\n continue;\n }\n if (node.commands.length === 0) return;\n if (node === program && arg === \"help\") return;\n program.error(`error: unknown command '${arg}'`);\n }\n}\n\nrejectUnknownCommand(process.argv);\nprogram.parseAsync(process.argv);\n","import nacl from \"tweetnacl\";\nimport { deriveAgentCode, toHex } from \"@paybox/mcp-app/agent-code\";\nimport { encodeToken } from \"@paybox/mcp-app/creds\";\n\nconst POLL_MS = 1500;\nconst TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_BACKOFF_MS = 15_000;\nconst GIVE_UP_AFTER_FAILING_MS = 90_000;\n\nasync function json(url: string, init: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`${init.method ?? \"GET\"} ${new URL(url).pathname} failed (${res.status})${body ? `: ${body.slice(0, 200)}` : \"\"}`);\n }\n return res.json();\n}\n\nexport async function pairSigningKey(opts: {\n baseUrl: string;\n appBase: string;\n bearer: string;\n onCode(code: string, url: string): void;\n}): Promise<string> {\n const { pairing_token, client_id } = await json(`${opts.baseUrl}/api/agent-pairings/token`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${opts.bearer}`, accept: \"application/json\" },\n });\n\n const seed = nacl.randomBytes(nacl.sign.seedLength);\n const pair = nacl.sign.keyPair.fromSeed(seed);\n const keypair = { apiPubHex: toHex(pair.publicKey), apiPrivHex: toHex(seed) };\n\n const { pairing_id } = await json(`${opts.baseUrl}/iframe/pairing`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${pairing_token}`,\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n },\n body: JSON.stringify({ api_pub_hex: keypair.apiPubHex }),\n });\n\n const url = `${opts.appBase}/agent-key?client_id=${client_id}&pairing_id=${pairing_id}`;\n opts.onCode(await deriveAgentCode(pair.publicKey), url);\n\n const deadline = Date.now() + TIMEOUT_MS;\n let failures = 0;\n let failingSince = 0;\n while (Date.now() < deadline) {\n const backoff = failures ? Math.min(POLL_MS * 2 ** failures, MAX_BACKOFF_MS) : POLL_MS;\n await new Promise((resolve) => setTimeout(resolve, backoff));\n let status: string;\n try {\n status = (await json(`${opts.baseUrl}/iframe/pairing/${pairing_id}`, {\n headers: { accept: \"application/json\" },\n })).status;\n failures = 0;\n failingSince = 0;\n } catch (err) {\n failures += 1;\n failingSince ||= Date.now();\n if (Date.now() - failingSince >= GIVE_UP_AFTER_FAILING_MS) {\n throw new Error(`lost contact with PayBox while waiting: ${(err as Error).message}`);\n }\n continue;\n }\n if (status === \"completed\") return encodeToken(keypair);\n if (status === \"cancelled\") throw new Error(\"that request was declined in PayBox\");\n if (status === \"expired\") throw new Error(\"that request expired — run `paybox connect` again\");\n }\n throw new Error(\"timed out waiting for you to pick the number in PayBox\");\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n","import { sha256 } from \"@noble/hashes/sha256\";\n\nexport function toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function fromHex(hex: string): Uint8Array {\n const normalized = hex.trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new Error(\"value is not lowercase hex\");\n }\n const out = new Uint8Array(normalized.length / 2);\n for (let i = 0; i < out.length; i += 1) {\n out[i] = Number.parseInt(normalized.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nexport const OPTION_COUNT = 3;\nconst CODE_MIN = 10;\nconst CODE_SPAN = 90;\n\nfunction utf8(value: string): Uint8Array {\n return new TextEncoder().encode(value);\n}\n\nfunction codeFromDigest(digest: Uint8Array): string {\n const value = new DataView(digest.buffer, digest.byteOffset, 4).getUint32(0);\n return String(CODE_MIN + (value % CODE_SPAN));\n}\n\nexport async function deriveAgentCode(publicKey: Uint8Array): Promise<string> {\n if (publicKey.length !== 32) {\n throw new Error(`public key must be 32 bytes, got ${publicKey.length}`);\n }\n return codeFromDigest(sha256(publicKey));\n}\n\nexport type AgentCodeChallenge = {\n options: string[];\n answerIndex: number;\n};\n\nexport async function buildAgentCodeChallenge(\n publicKey: Uint8Array,\n): Promise<AgentCodeChallenge> {\n const answer = await deriveAgentCode(publicKey);\n const seed = toHex(publicKey);\n\n const decoys: string[] = [];\n const seen = new Set([answer]);\n for (let nonce = 0; decoys.length < OPTION_COUNT - 1; nonce += 1) {\n if (nonce > 1000) throw new Error(\"could not derive distinct decoy codes\");\n const candidate = codeFromDigest(sha256(utf8(`paybox/agent-code/decoy/${seed}/${nonce}`)));\n if (seen.has(candidate)) continue;\n seen.add(candidate);\n decoys.push(candidate);\n }\n\n const order = sha256(utf8(`paybox/agent-code/order/${seed}`));\n const answerIndex = order[0] % OPTION_COUNT;\n\n const options: string[] = [];\n let next = 0;\n for (let i = 0; i < OPTION_COUNT; i += 1) {\n options.push(i === answerIndex ? answer : decoys[next++]);\n }\n return { options, answerIndex };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAC1B,SAAS,cAAc,cAAc;AACrC,SAAS,qBAAqB;AAE9B,SAAS,eAAe;;;ACNxB,OAAO,UAAU;;;ACeX,SAAU,QAAQ,GAAU;AAChC,SAAO,aAAa,cAAe,YAAY,OAAO,CAAC,KAAK,EAAE,YAAY,SAAS;AACrF;AAQM,SAAU,OAAO,MAA8B,SAAiB;AACpE,MAAI,CAAC,QAAQ,CAAC;AAAG,UAAM,IAAI,MAAM,qBAA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
+
{"version":3,"sources":["../src/cli.ts","../src/pairing.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/utils.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/_md.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha2.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha256.ts","../node_modules/.pnpm/@paybox+mcp-app@file+..+mcp-app_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__bn.js@5.2.3_ac1e09a20c76a1143611be5dd3d4f9db/node_modules/@paybox/mcp-app/src/signing/agent-code.ts","../src/self-update.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync, rmSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport { Command } from \"commander\";\n\nimport { appBaseFrom, loginDevice, openBrowser, refreshTokens } from \"./auth.js\";\nimport { pairSigningKey } from \"./pairing.js\";\nimport { PayboxClient, PayboxError, didNotHappen } from \"./client.js\";\nimport { configDir, configFile, loadConfig, saveConfig } from \"./config.js\";\nimport { pendingFundingResponse, pendingFundingToolResponse } from \"./pending-funding.js\";\nimport { PKG, autoUpdate, installArgs, isNewer, latestVersion, npm } from \"./self-update.js\";\nimport type { AgentResponse, McpToolResult, PluginSource, PluginStatus } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.paybox.sh\";\nconst VERSION = createRequire(import.meta.url)(\"../package.json\").version as string;\n\nconst program = new Command();\nprogram\n .name(\"paybox\")\n .description(\"PayBox agent CLI — vaulted cards, wallets, and secrets for agents\")\n .version(VERSION)\n .option(\"--base-url <url>\", \"API origin (default https://api.paybox.sh or stored)\")\n .option(\"--json\", \"machine-readable JSON output\")\n .hook(\"preAction\", (_, command) => autoUpdate(command.name(), VERSION));\n\nfunction jsonMode(): boolean {\n return Boolean(program.opts().json);\n}\n\nfunction emit(data: unknown): void {\n const funding = pendingFundingResponse(data) ?? (\n Array.isArray((data as McpToolResult | null)?.content)\n ? pendingFundingToolResponse(data as McpToolResult) : null\n );\n if (funding) {\n console.error(\n \"Request incomplete; funding status is pending, not proof that funding has started or completed. \" +\n `Poll \\`paybox request ${funding.request_id}\\`; do not repeat the purchase.`,\n );\n }\n if (jsonMode()) console.log(JSON.stringify(data, null, 2));\n else console.dir(data, { depth: null, colors: process.stdout.isTTY });\n const d = data as {\n status?: unknown;\n response?: { status?: unknown };\n isError?: unknown;\n } | null;\n if (!funding && (didNotHappen(d) || didNotHappen(d?.response) || d?.isError === true)) {\n process.exitCode = 1;\n }\n}\n\nfunction client(): PayboxClient {\n return PayboxClient.fromConfig({ baseUrl: program.opts().baseUrl });\n}\n\nfunction readIntent(value: string): unknown {\n const raw = value.startsWith(\"@\") ? readFileSync(value.slice(1), \"utf8\") : value;\n return JSON.parse(raw);\n}\n\nfunction readObject(value: string): Record<string, unknown> {\n const parsed = readIntent(value);\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"--input must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction int(flag: string, value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n)) {\n throw new Error(`--${flag} must be an integer, got ${JSON.stringify(value)}`);\n }\n return n;\n}\n\nfunction optInt(flag: string, value: string | undefined): number | undefined {\n return value === undefined ? undefined : int(flag, value);\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction credentialId(value: string): string {\n return uuid(\n value,\n \"--credential expects a credential id, not a name\",\n \"Run `paybox credentials` and use the `credential.id` of the one you want.\",\n );\n}\n\nfunction requestId(value: string): string {\n return uuid(\n value,\n \"not a request id\",\n \"Request ids come back from the command that created the request, and from `paybox requests`.\",\n );\n}\n\nfunction uuid(value: string, what: string, hint: string): string {\n if (UUID.test(value)) return value;\n throw new Error(`${what}: got ${JSON.stringify(value)}. ${hint}`);\n}\n\nasync function run(fn: () => Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const reason = err instanceof PayboxError ? err.reason : undefined;\n if (jsonMode()) console.log(JSON.stringify({ error: message, reason }, null, 2));\n else console.error(message);\n process.exitCode = 1;\n }\n}\n\nfunction withNextAction(c: PayboxClient, result: unknown): unknown {\n const value = result as { status?: unknown; response?: unknown };\n const response = value.response as AgentResponse | undefined;\n if (response?.status) {\n return {\n ...value,\n response: { ...response, next_action: c.nextAction(response) },\n };\n }\n if (value.status) {\n return { ...value, next_action: c.nextAction(value as AgentResponse) };\n }\n return result;\n}\n\n\nfunction resolveBaseUrl(): string {\n const cfg = loadConfig();\n return (\n program.opts().baseUrl ??\n process.env.PAYBOX_API_URL ??\n cfg.baseUrl ??\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, \"\");\n}\n\nprogram\n .command(\"login\")\n .description(\"Authenticate via OAuth device approval, or store a pbx_live_ key\")\n .option(\"--key <key>\", \"store a pbx_live_ personal API key instead of OAuth\")\n .option(\"--no-open\", \"print the approval link without opening a browser\")\n .action((opts) =>\n run(async () => {\n const cfg = loadConfig();\n cfg.baseUrl = resolveBaseUrl();\n if (opts.key) {\n cfg.apiKey = opts.key;\n delete cfg.oauth;\n } else {\n cfg.oauth = await loginDevice(cfg.baseUrl, { open: opts.open });\n delete cfg.apiKey;\n }\n delete cfg.signingKey;\n saveConfig(cfg);\n console.error(`Saved credentials to ${configFile()}`);\n if (!process.env.PAYBOX_SIGNING_KEY) {\n console.error(\"Run `paybox connect` to connect a signing key; until then sign and swap stop at pending_signature.\");\n }\n }),\n );\n\nprogram\n .command(\"connect\")\n .description(\"Connect a wallet signing key to this machine by picking a number in PayBox\")\n .option(\"--app-url <url>\", \"PayBox app origin (default: derived from --base-url)\")\n .option(\"--no-open\", \"print the pairing link without opening a browser\")\n .action((opts) =>\n run(async () => {\n const cfg = loadConfig();\n const baseUrl = resolveBaseUrl();\n const appBase = appBaseFrom(baseUrl, opts.appUrl ?? process.env.PAYBOX_APP_URL ?? cfg.appUrl);\n if (!appBase) throw new Error(\"could not derive the PayBox app origin — pass --app-url\");\n if (opts.appUrl) cfg.appUrl = opts.appUrl;\n if (!cfg.apiKey && cfg.oauth?.expiresAt && Date.now() > cfg.oauth.expiresAt - 30_000) {\n cfg.oauth = await refreshTokens(baseUrl, cfg.oauth);\n saveConfig(cfg);\n }\n const bearer = cfg.apiKey ?? cfg.oauth?.accessToken;\n if (!bearer) throw new Error(\"not authenticated — run `paybox login` first\");\n cfg.signingKey = await pairSigningKey({\n baseUrl,\n appBase,\n bearer,\n onCode(code, url) {\n console.error(`\\n ${code}\\n`);\n console.error(`Open this on any device and pick that number to connect this machine:\\n ${url}\\n`);\n if (opts.open) openBrowser(url);\n },\n });\n saveConfig(cfg);\n console.error(\"Connected — sign and swap are enabled on this machine.\");\n }),\n );\n\nprogram\n .command(\"logout\")\n .description(\"Forget stored credentials\")\n .action(() =>\n run(async () => {\n const cfg = loadConfig();\n delete cfg.apiKey;\n delete cfg.oauth;\n delete cfg.signingKey;\n saveConfig(cfg);\n console.error(\"Logged out.\");\n }),\n );\n\nprogram\n .command(\"whoami\")\n .description(\"Show the configured endpoint, auth mode, and signing capability\")\n .action(() =>\n run(async () => {\n const cfg = loadConfig();\n const c = client();\n const mode = process.env.PAYBOX_ACCESS_TOKEN\n ? \"oauth (env token)\"\n : process.env.PAYBOX_API_KEY || cfg.apiKey\n ? \"api key\"\n : cfg.oauth\n ? \"oauth\"\n : \"none\";\n emit({ baseUrl: c.baseUrl, auth: mode, canSign: c.canSign, configFile: configFile() });\n }),\n );\n\nprogram\n .command(\"credentials\")\n .description(\"List the credentials this client may use\")\n .action(() => run(async () => emit(await client().listCredentials())));\n\nprogram\n .command(\"pay\")\n .description(\"Charge a card credential\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--merchant <name>\")\n .requiredOption(\"--url <url>\", \"real merchant URL the card is bound to\")\n .requiredOption(\"--amount <cents>\", \"amount in cents\")\n .option(\"--currency <code>\", \"ISO 4217 currency\", \"USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().requestPayment({\n credentialId: credentialId(o.credential),\n merchant: o.merchant,\n merchantUrl: o.url,\n amountCents: int(\"amount\", o.amount),\n currency: o.currency,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"secret\")\n .description(\"Reveal a secret credential (one-time token, or --raw value)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .option(\"--raw\", \"return the raw secret value (grant-gated)\")\n .option(\"--purpose <text>\", \"why the secret is requested (shown on approval)\")\n .action((o) =>\n run(async () =>\n emit(\n await client().requestSecret({\n credentialId: credentialId(o.credential),\n raw: Boolean(o.raw),\n purpose: o.purpose,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"sign\")\n .description(\"Sign with a wallet credential (intent JSON, or @file)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--intent <json>\", 'a SignIntent, e.g. \\'{\"op\":\"message\",\"message\":\"hi\"}\\' or @intent.json')\n .action((o) =>\n run(async () => {\n const c = client();\n const res = await c.requestWalletSign({\n credentialId: credentialId(o.credential),\n intent: readIntent(o.intent) as never,\n });\n emit(withNextAction(c, res));\n }),\n );\n\nprogram\n .command(\"swap\")\n .description(\"Swap tokens from a wallet credential\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--src-chain <caip2>\")\n .requiredOption(\"--src-token <addr>\", '\"native\" or a token address')\n .requiredOption(\"--dst-token <addr>\")\n .requiredOption(\"--amount <smallest-unit>\", \"source amount in smallest units\")\n .option(\"--dst-chain <caip2>\", \"defaults to --src-chain\")\n .option(\"--direction <dir>\", \"exact-amount-in | exact-amount-out\", \"exact-amount-in\")\n .option(\"--slippage <bps>\", \"slippage in bps\", \"150\")\n .option(\"--recipient <addr>\")\n .option(\"--value-cents <n>\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.requestSwap(\n {\n credentialId: credentialId(o.credential),\n srcChain: o.srcChain,\n dstChain: o.dstChain,\n srcToken: o.srcToken,\n dstToken: o.dstToken,\n amount: o.amount,\n swapDirection: o.direction,\n slippageBps: int(\"slippage\", o.slippage),\n recipient: o.recipient,\n valueCents: optInt(\"value-cents\", o.valueCents),\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"discover [query]\")\n .description(\"Discover curated paid x402 services from Bazaar (optional search)\")\n .option(\"--raw\", \"return uncurated compact Bazaar service summaries (debug)\")\n .action((query, o) =>\n run(async () => emit(await client().discoverServices(query, { raw: Boolean(o.raw) }))),\n );\n\nprogram\n .command(\"pay-x402\")\n .description(\"Pay a paid x402 endpoint (header mode — returns the X-PAYMENT header to replay)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--accepts <json>\", \"the 402's accepts[] array (JSON or @file)\")\n .requiredOption(\"--url <url>\", \"the paywalled resource URL\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.payX402(\n {\n credentialId: credentialId(o.credential),\n accepts: readIntent(o.accepts) as unknown[],\n resourceUrl: o.url,\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"use-service\")\n .description(\"Fetch a paid x402 resource and have paybox pay for it (gateway mode)\")\n .requiredOption(\"--credential <id>\", \"credential id from `paybox credentials`\")\n .requiredOption(\"--url <url>\", \"the paid x402 resource URL\")\n .option(\"--method <verb>\", \"HTTP method\", \"GET\")\n .option(\"--body <json>\", \"request body (JSON or @file)\")\n .option(\"--wait\", \"if approval is required, wait for it and then sign in-process\")\n .action((o) =>\n run(async () => {\n const c = client();\n const result = await c.useService(\n {\n credentialId: credentialId(o.credential),\n url: o.url,\n method: o.method,\n body: o.body === undefined ? undefined : readIntent(o.body),\n },\n { waitForApproval: Boolean(o.wait) },\n );\n emit(withNextAction(c, result));\n }),\n );\n\nprogram\n .command(\"portfolio\")\n .description(\"List a wallet address's token balances across chains\")\n .requiredOption(\"--address <addr>\")\n .option(\"--networks <ids>\", 'comma-separated network IDs, e.g. \"1,8453\"')\n .option(\"--token <addr>\", \"mint, ERC-20, or native\")\n .option(\"--network-id <id>\", \"MoonX network id required with --token\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getPortfolio({\n address: o.address,\n networkIds: o.networks,\n token: o.token,\n networkId: o.networkId == null ? undefined : Number(o.networkId),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"verify-solana-balance\")\n .description(\"Verify a Solana transaction's wallet/token effect and current balance\")\n .requiredOption(\"--address <addr>\", \"canonical Solana wallet address\")\n .requiredOption(\"--mint <addr>\", \"canonical SPL or Token-2022 mint\")\n .requiredOption(\"--transaction <signature>\", \"confirmed Solana transaction signature\")\n .action((o) =>\n run(async () =>\n emit(\n await client().verifySolanaBalance({\n address: o.address,\n tokenMint: o.mint,\n transactionSignature: o.transaction,\n }),\n ),\n ),\n );\n\nprogram\n .command(\"claim <request-id>\")\n .description(\"Claim the usable card credentials of an approved payment (one-time)\")\n .action((id) => run(async () => emit(await client().claimPaymentCredentials(requestId(id)))));\n\nprogram\n .command(\"account-change\")\n .description(\"Get a manage_url for the USER to update this client's access in the app\")\n .option(\"--note <text>\", \"why the change is needed (shown to the user)\")\n .action((o) => run(async () => emit(await client().requestAccountChange(o.note))));\n\nprogram\n .command(\"deposit-link\")\n .description(\"Open Deposit URL for a granted wallet (charges nothing)\")\n .requiredOption(\"--credential <id>\", \"a granted wallet credential\")\n .option(\"--amount-usd <n>\", \"optional amount hint in USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getDepositLink({\n credentialId: credentialId(o.credential),\n amountUsd: o.amountUsd === undefined ? undefined : Number(o.amountUsd),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"buy-link\")\n .description(\"Signed MoonPay checkout URL funding a granted wallet (charges nothing)\")\n .requiredOption(\"--credential <id>\", \"a granted wallet credential\")\n .option(\n \"--destination <chain>\",\n \"exact network: eip155:8453 (default EVM), eip155:1, eip155:4663, or solana:mainnet\",\n )\n .option(\"--currency <code>\", \"enabled MoonPay code matching the exact destination\")\n .option(\"--amount-usd <n>\", \"prefill amount in USD\")\n .action((o) =>\n run(async () =>\n emit(\n await client().getBuyLink({\n credentialId: credentialId(o.credential),\n destinationChain: o.destination,\n currencyCode: o.currency,\n amountUsd: o.amountUsd === undefined ? undefined : Number(o.amountUsd),\n }),\n ),\n ),\n );\n\nconst plugins = program\n .command(\"plugins\")\n .description(\"Discover and use enabled plugins\");\n\nplugins\n .command(\"list [query]\")\n .description(\"Discover plugins at runtime\")\n .option(\"--source <source>\", \"all | official | user\", \"all\")\n .option(\"--status <status>\", \"all | enabled | disabled\", \"all\")\n .option(\"--limit <n>\", \"results per page\")\n .option(\"--cursor <cursor>\", \"cursor returned by the previous page\")\n .action((query, o) =>\n run(async () =>\n emit(\n await client().discoverPlugins({\n query,\n source: o.source as PluginSource,\n status: o.status as PluginStatus,\n limit: optInt(\"limit\", o.limit),\n cursor: o.cursor,\n }),\n ),\n ),\n );\n\nplugins\n .command(\"contract <contract-uri>\")\n .description(\"Read an official plugin contract returned by discovery\")\n .action((contractUri) =>\n run(async () => emit(await client().getPluginContract(contractUri))),\n );\n\nplugins\n .command(\"use <plugin-id> <tool-id>\")\n .description(\"Invoke a tool from its discovered plugin contract\")\n .option(\"--input <json>\", \"JSON object or @file\", \"{}\")\n .option(\"--invocation-id <uuid>\", \"reuse only for the same unofficial plugin call\")\n .action((pluginId, toolId, o) =>\n run(async () =>\n emit(\n await client().usePlugin({\n pluginId,\n toolId,\n input: readObject(o.input),\n invocationId: o.invocationId === undefined\n ? undefined\n : uuid(\n o.invocationId,\n \"--invocation-id expects a UUID\",\n \"Reuse it only to retrieve the same unofficial plugin invocation.\",\n ),\n }),\n ),\n ),\n );\n\nprogram\n .command(\"request <id>\")\n .description(\"Poll a request's status\")\n .option(\"--wait\", \"block until it leaves the pending state\")\n .option(\"--complete-signature\", \"sign an existing wallet-sign request with the local key\")\n .action((id, o) =>\n run(async () => {\n const c = client();\n const rid = requestId(id);\n const response = o.completeSignature\n ? await c.completeWalletSignRequest(rid)\n : await c.getRequest(rid);\n emit(withNextAction(c, o.wait ? await c.waitForRequest(rid) : response));\n }),\n );\n\nprogram\n .command(\"version\")\n .description(\"Show the installed CLI version (and whether an update is available)\")\n .action(() =>\n run(async () => {\n const latest = await latestVersion();\n const updateAvailable = Boolean(latest && isNewer(latest, VERSION));\n if (jsonMode()) {\n emit({\n version: VERSION,\n latest: latest ?? null,\n updateAvailable,\n binary: process.argv[1] ?? null,\n });\n return;\n }\n console.log(`${PKG} v${VERSION}`);\n if (updateAvailable) {\n console.log(`Update available: v${latest} — run \\`paybox update\\`.`);\n }\n }),\n );\n\nprogram\n .command(\"update\")\n .description(\"Update the globally-installed paybox CLI to the latest version\")\n .option(\"--print\", \"print the update command instead of running it\")\n .action((opts) =>\n run(async () => {\n const args = installArgs(\"latest\");\n if (opts.print) {\n console.log(`npm ${args.join(\" \")}`);\n return;\n }\n console.error(`Updating ${PKG} (npm ${args.join(\" \")})…`);\n const r = npm(args, \"inherit\");\n if (r.status !== 0) {\n console.error(\n `\\nIf this isn't a global install: run \\`pnpm up ${PKG}\\` in your project, ` +\n `or use \\`npx ${PKG}@latest …\\` to always run the latest.`,\n );\n process.exitCode = r.status ?? 1;\n }\n }),\n );\n\nprogram\n .command(\"uninstall\")\n .description(\"Remove stored PayBox credentials/config (and show how to remove the CLI)\")\n .action(() =>\n run(async () => {\n const dir = configDir();\n rmSync(dir, { recursive: true, force: true });\n console.error(`Removed stored config at ${dir}.`);\n console.error(\n `The CLI binary is managed by npm — remove it with:\\n npm rm -g ${PKG}`,\n );\n }),\n );\n\nfunction rejectUnknownCommand(argv: string[]): void {\n if (!argv.includes(\"--help\") && !argv.includes(\"-h\")) return;\n let node: Command = program;\n for (let i = 2; i < argv.length; i++) {\n const arg = argv[i];\n if (node.options.some((o) => o.long === arg && o.required)) i++;\n if (arg.startsWith(\"-\")) continue;\n const next = node.commands.find((c) => c.name() === arg || c.aliases().includes(arg));\n if (next) {\n node = next;\n continue;\n }\n if (node.commands.length === 0) return;\n if (node === program && arg === \"help\") return;\n program.error(`error: unknown command '${arg}'`);\n }\n}\n\nrejectUnknownCommand(process.argv);\nprogram.parseAsync(process.argv);\n","import nacl from \"tweetnacl\";\nimport { deriveAgentCode, toHex } from \"@paybox/mcp-app/agent-code\";\nimport { encodeToken } from \"@paybox/mcp-app/creds\";\n\nconst POLL_MS = 1500;\nconst TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_BACKOFF_MS = 15_000;\nconst GIVE_UP_AFTER_FAILING_MS = 90_000;\n\nasync function json(url: string, init: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`${init.method ?? \"GET\"} ${new URL(url).pathname} failed (${res.status})${body ? `: ${body.slice(0, 200)}` : \"\"}`);\n }\n return res.json();\n}\n\nexport async function pairSigningKey(opts: {\n baseUrl: string;\n appBase: string;\n bearer: string;\n onCode(code: string, url: string): void;\n}): Promise<string> {\n const { pairing_token, client_id } = await json(`${opts.baseUrl}/api/agent-pairings/token`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${opts.bearer}`, accept: \"application/json\" },\n });\n\n const seed = nacl.randomBytes(nacl.sign.seedLength);\n const pair = nacl.sign.keyPair.fromSeed(seed);\n const keypair = { apiPubHex: toHex(pair.publicKey), apiPrivHex: toHex(seed) };\n\n const { pairing_id } = await json(`${opts.baseUrl}/iframe/pairing`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${pairing_token}`,\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n },\n body: JSON.stringify({ api_pub_hex: keypair.apiPubHex }),\n });\n\n const url = `${opts.appBase}/agent-key?client_id=${client_id}&pairing_id=${pairing_id}`;\n opts.onCode(await deriveAgentCode(pair.publicKey), url);\n\n const deadline = Date.now() + TIMEOUT_MS;\n let failures = 0;\n let failingSince = 0;\n while (Date.now() < deadline) {\n const backoff = failures ? Math.min(POLL_MS * 2 ** failures, MAX_BACKOFF_MS) : POLL_MS;\n await new Promise((resolve) => setTimeout(resolve, backoff));\n let status: string;\n try {\n status = (await json(`${opts.baseUrl}/iframe/pairing/${pairing_id}`, {\n headers: { accept: \"application/json\" },\n })).status;\n failures = 0;\n failingSince = 0;\n } catch (err) {\n failures += 1;\n failingSince ||= Date.now();\n if (Date.now() - failingSince >= GIVE_UP_AFTER_FAILING_MS) {\n throw new Error(`lost contact with PayBox while waiting: ${(err as Error).message}`);\n }\n continue;\n }\n if (status === \"completed\") return encodeToken(keypair);\n if (status === \"cancelled\") throw new Error(\"that request was declined in PayBox\");\n if (status === \"expired\") throw new Error(\"that request expired — run `paybox connect` again\");\n }\n throw new Error(\"timed out waiting for you to pick the number in PayBox\");\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n","import { sha256 } from \"@noble/hashes/sha256\";\n\nexport function toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function fromHex(hex: string): Uint8Array {\n const normalized = hex.trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new Error(\"value is not lowercase hex\");\n }\n const out = new Uint8Array(normalized.length / 2);\n for (let i = 0; i < out.length; i += 1) {\n out[i] = Number.parseInt(normalized.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nexport const OPTION_COUNT = 3;\nconst CODE_MIN = 10;\nconst CODE_SPAN = 90;\n\nfunction utf8(value: string): Uint8Array {\n return new TextEncoder().encode(value);\n}\n\nfunction codeFromDigest(digest: Uint8Array): string {\n const value = new DataView(digest.buffer, digest.byteOffset, 4).getUint32(0);\n return String(CODE_MIN + (value % CODE_SPAN));\n}\n\nexport async function deriveAgentCode(publicKey: Uint8Array): Promise<string> {\n if (publicKey.length !== 32) {\n throw new Error(`public key must be 32 bytes, got ${publicKey.length}`);\n }\n return codeFromDigest(sha256(publicKey));\n}\n\nexport type AgentCodeChallenge = {\n options: string[];\n answerIndex: number;\n};\n\nexport async function buildAgentCodeChallenge(\n publicKey: Uint8Array,\n): Promise<AgentCodeChallenge> {\n const answer = await deriveAgentCode(publicKey);\n const seed = toHex(publicKey);\n\n const decoys: string[] = [];\n const seen = new Set([answer]);\n for (let nonce = 0; decoys.length < OPTION_COUNT - 1; nonce += 1) {\n if (nonce > 1000) throw new Error(\"could not derive distinct decoy codes\");\n const candidate = codeFromDigest(sha256(utf8(`paybox/agent-code/decoy/${seed}/${nonce}`)));\n if (seen.has(candidate)) continue;\n seen.add(candidate);\n decoys.push(candidate);\n }\n\n const order = sha256(utf8(`paybox/agent-code/order/${seed}`));\n const answerIndex = order[0] % OPTION_COUNT;\n\n const options: string[] = [];\n let next = 0;\n for (let i = 0; i < OPTION_COUNT; i += 1) {\n options.push(i === answerIndex ? answer : decoys[next++]);\n }\n return { options, answerIndex };\n}\n","import { spawnSync, type SpawnSyncReturns } from \"node:child_process\";\nimport { closeSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { constants } from \"node:os\";\nimport { isAbsolute, join, relative } from \"node:path\";\n\nimport { configDir } from \"./config.js\";\n\nexport const PKG = \"@paybox-sh/sdk\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\nconst LOCK_STALE_MS = 10 * 60 * 1000;\nconst NPM_TIMEOUT_MS = 2 * 60 * 1000;\nconst SEMVER = /^\\d+\\.\\d+\\.\\d+$/;\nconst NO_AUTO_UPDATE = new Set([\"version\", \"update\", \"uninstall\"]);\n\nexport function isNewer(a: string, b: string): boolean {\n const pa = a.split(\".\").map(Number);\n const pb = b.split(\".\").map(Number);\n for (let i = 0; i < 3; i++) {\n const x = pa[i] ?? 0;\n const y = pb[i] ?? 0;\n if (x !== y) return x > y;\n }\n return false;\n}\n\nfunction registry(): string {\n return (process.env.PAYBOX_UPDATE_REGISTRY || \"https://registry.npmjs.org\").replace(/\\/+$/, \"\");\n}\n\nexport async function latestVersion(): Promise<string | undefined> {\n try {\n const res = await fetch(`${registry()}/${PKG}/latest`, { signal: AbortSignal.timeout(3_000) });\n if (!res.ok) return undefined;\n const { version } = (await res.json()) as { version?: unknown };\n return typeof version === \"string\" && SEMVER.test(version) ? version : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function installArgs(version: string): string[] {\n const pinned = `${registry()}/`;\n return [\"install\", \"-g\", `${PKG}@${version}`, \"--registry\", pinned, `--@paybox-sh:registry=${pinned}`];\n}\n\nexport function npm(args: string[], stdio: \"inherit\" | \"pipe\"): SpawnSyncReturns<string> {\n const background = stdio === \"pipe\";\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !(background && /^npm_config_.*registry$/i.test(key))),\n );\n const options = {\n stdio,\n encoding: \"utf8\" as const,\n timeout: background ? NPM_TIMEOUT_MS : undefined,\n cwd: background ? configDir() : undefined,\n };\n if (process.platform !== \"win32\") return spawnSync(\"npm\", args, { ...options, env });\n return spawnSync(process.env.ComSpec ?? \"cmd.exe\", [\"/d\", \"/s\", \"/c\", \"npm\", ...args], {\n ...options,\n env: { ...env, NoDefaultCurrentDirectoryInExePath: \"1\" },\n });\n}\n\nfunction available(latest: string, current: string): string {\n return `PayBox CLI v${latest} is available (this is v${current}). Run \\`paybox update\\`.`;\n}\n\nfunction globalCli(): string | undefined {\n const root = npm([\"root\", \"-g\"], \"pipe\");\n if (root.status !== 0 || !process.argv[1]) return undefined;\n const pkgDir = join(root.stdout.trim(), PKG);\n try {\n const rel = relative(realpathSync(pkgDir), realpathSync(process.argv[1]));\n return rel && !rel.startsWith(\"..\") && !isAbsolute(rel) ? join(pkgDir, \"dist\", \"cli.js\") : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction unlock(lock: string): void {\n try {\n rmSync(lock, { force: true });\n } catch {\n }\n}\n\nfunction startCheck(dir: string): boolean {\n const cache = join(dir, \"update-check.json\");\n const lock = join(dir, \"update.lock\");\n try {\n const age = Date.now() - (JSON.parse(readFileSync(cache, \"utf8\")) as { checkedAt: number }).checkedAt;\n if (age >= 0 && age < DAY_MS) return false;\n } catch {\n }\n try {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n closeSync(openSync(lock, \"wx\"));\n } catch {\n try {\n if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) unlock(lock);\n } catch {\n }\n return false;\n }\n try {\n writeFileSync(cache, JSON.stringify({ checkedAt: Date.now() }));\n return true;\n } catch {\n unlock(lock);\n return false;\n }\n}\n\nasync function install(current: string): Promise<{ cli: string; latest: string } | undefined> {\n const latest = await latestVersion();\n if (!latest || !isNewer(latest, current)) return undefined;\n const cli = latest.split(\".\")[0] === current.split(\".\")[0] ? globalCli() : undefined;\n if (!cli) {\n console.error(available(latest, current));\n return undefined;\n }\n if (npm(installArgs(latest), \"pipe\").status !== 0) {\n console.error(`Could not update PayBox CLI to v${latest}; continuing with v${current}. Run \\`paybox update\\` to see why.`);\n return undefined;\n }\n return { cli, latest };\n}\n\nexport async function autoUpdate(command: string, current: string): Promise<void> {\n if (NO_AUTO_UPDATE.has(command) || process.env.PAYBOX_NO_AUTO_UPDATE === \"1\") return;\n const updated = process.env.PAYBOX_AUTO_UPDATED;\n if (updated) {\n if (isNewer(updated, current)) console.error(available(updated, current));\n return;\n }\n const dir = configDir();\n if (!startCheck(dir)) return;\n let next: Awaited<ReturnType<typeof install>>;\n try {\n next = await install(current);\n } finally {\n unlock(join(dir, \"update.lock\"));\n }\n if (!next) return;\n console.error(`Updated PayBox CLI v${current} → v${next.latest}.`);\n const child = spawnSync(process.execPath, [next.cli, ...process.argv.slice(2)], {\n stdio: \"inherit\",\n env: { ...process.env, PAYBOX_AUTO_UPDATED: next.latest },\n });\n process.exit(child.status ?? (child.signal ? 128 + constants.signals[child.signal] : 1));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAEA,SAAS,gBAAAA,eAAc,UAAAC,eAAc;AACrC,SAAS,qBAAqB;AAE9B,SAAS,eAAe;;;ACLxB,OAAO,UAAU;;;ACeX,SAAU,QAAQ,GAAU;AAChC,SAAO,aAAa,cAAe,YAAY,OAAO,CAAC,KAAK,EAAE,YAAY,SAAS;AACrF;AAQM,SAAU,OAAO,MAA8B,SAAiB;AACpE,MAAI,CAAC,QAAQ,CAAC;AAAG,UAAM,IAAI,MAAM,qBAAqB;AACtD,MAAI,QAAQ,SAAS,KAAK,CAAC,QAAQ,SAAS,EA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M,OAAO,EAAE,QAAQ,EAAE,SAAS,GAAG,CAAC;AACpF,QAAI,MAAM;AACR,aAAO;AACP;AAAA,IACF;AACA,QAAI,KAAK,SAAS,WAAW,EAAG;AAChC,QAAI,SAAS,WAAW,QAAQ,OAAQ;AACxC,YAAQ,MAAM,2BAA2B,GAAG,GAAG;AAAA,EACjD;AACF;AAEA,qBAAqB,QAAQ,IAAI;AACjC,QAAQ,WAAW,QAAQ,IAAI;","names":["readFileSync","rmSync","sha256","sha256","readFileSync","rmSync"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -168,6 +168,7 @@ interface Grant {
|
|
|
168
168
|
interface ClientGrantSummary {
|
|
169
169
|
credential: CredentialSummary;
|
|
170
170
|
grant: Grant;
|
|
171
|
+
signer_status?: "ready" | "signer_missing" | "signer_wallet_not_authorized" | "signer_pairing_incomplete";
|
|
171
172
|
}
|
|
172
173
|
interface UngrantedCredential {
|
|
173
174
|
credential_id: string;
|
|
@@ -382,6 +383,7 @@ declare function nextActionFor(response: AgentResponse, capabilities: NextAction
|
|
|
382
383
|
declare class PayboxError extends Error {
|
|
383
384
|
readonly status: number;
|
|
384
385
|
readonly body: string;
|
|
386
|
+
readonly reason?: "signer_wallet_not_authorized";
|
|
385
387
|
constructor(status: number, body: string, context: string);
|
|
386
388
|
}
|
|
387
389
|
interface PayboxClientOptions {
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paybox-sh/sdk",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Typed Node SDK + `paybox` CLI for the PayBox agent API, with REST core operations and runtime MCP plugin discovery and invocation.",
|
|
6
6
|
"license": "Apache-2.0",
|