@calimero-network/mero-js 33.3.0 → 33.3.1

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/crypto/internal.ts", "../src/sealed/noise.ts", "../src/sealed/sealed.ts", "../src/sealed/sigstore-trust-root.ts", "../src/sealed/x509.ts", "../src/sealed/sigstore.ts", "../src/sealed/verify.ts", "../src/sealed/release.ts", "../src/runtime/attestation.ts", "../src/runtime/directory.ts", "../src/runtime/errors.ts", "../src/runtime/passkey.ts", "../src/runtime/transport.ts", "../node_modules/.pnpm/openapi-fetch@0.17.0/node_modules/openapi-fetch/src/index.js", "../src/routes/step-up.ts", "../src/routes/method.ts", "../src/generated/methods.ts", "../src/routes/route-client.ts", "../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js", "../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js", "../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js", "../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js", "../src/sealed/file.ts", "../src/client/files.ts", "../src/client/recovery-key.ts", "../src/client/approvals.ts", "../src/client/calimero-client.ts", "../src/client/capabilities.ts", "../src/agent-gate/chacha20poly1305.ts", "../src/agent-gate/hpke.ts", "../src/agent-gate/gate.ts", "../src/agent-gate/policy.ts", "../src/recovery/backup-files.ts"],
4
- "sourcesContent": ["// Mero.js: the JavaScript client for Calimero 1.0, the confidential cloud.\n//\n// `CalimeroClient` verifies a node's TDX attestation, seals every request to\n// it, and signs people in with passkeys and machines with API keys; its\n// groups (`client.orgs.get({ org })`, ...) are every route of the node,\n// generated from core's OpenAPI document. Everything below it is the pieces it\n// is built from, exported for callers who need one on its own. The layering\n// (runtime/ \u2192 generated/ + routes/ \u2192 client/) is described in\n// src/routes/index.ts.\n\n// The client, its errors and its types\nexport * from './client/index.js';\n\n// The node's routes as generated methods (`createRoutes`), the passkey answer\n// to a step-up (`passkeyConfirm`), and names for the document's types.\nexport * from './routes/index.js';\n\n// The runtime the client sends every route through (also its own entry point,\n// `@calimero-network/mero-js/runtime`): one `Transport.request` over the\n// attested, sealed channel, with the session, step-up and error mapping.\nexport {\n DEFAULT_RETRY,\n NodeTransport,\n directoryTransport,\n newIdempotencyKey,\n queryString,\n refusal,\n retryDelayMs,\n routePath,\n sseFrames,\n} from './runtime/transport.js';\nexport type {\n DirectorySource,\n HttpMethod,\n NodeTransportOptions,\n QueryValue,\n RequestOptions,\n Transport,\n} from './runtime/transport.js';\n\n// Sealed transport: requests encrypted end to end to a TEE node's attested key,\n// and the checks that decide whether a quote is trusted.\nexport * from './sealed/index.js';\n\n// Private agents (mero-tee's agent gate): attest one, claim it with your key,\n// give it its secrets sealed to its TD.\nexport * from './agent-gate/index.js';\n// The recovery disk's files as their holder's device opens them.\nexport * from './recovery/backup-files.js';\n", "/**\n * Byte-level primitives shared by the sealed transport, the attestation check\n * and the agent gate: hex handling, fixed-width integers and concatenation.\n * Internal \u2014 not exported from the package root.\n */\n\n/** Little-endian u32, for borsh fixed-width fields and epoch counters. */\nexport function u32le(value: number): Uint8Array {\n const out = new Uint8Array(4);\n new DataView(out.buffer).setUint32(0, value, true);\n return out;\n}\n\nexport function hex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nexport function fromHex(value: string, label: string, expectedBytes: number): Uint8Array {\n const clean = value.trim();\n if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length !== expectedBytes * 2) {\n throw new Error(\n `${label} must be ${expectedBytes * 2} hex characters, got ${clean.length}`,\n );\n }\n // Indexed rather than `match(/../g)!`: the length is already validated above,\n // so the assertion would only be telling the compiler what the guard proved,\n // and this needs no assertion at all.\n const bytes = new Uint8Array(expectedBytes);\n for (let i = 0; i < expectedBytes; i += 1) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Decode hex of an unknown length.\n *\n * The sized {@link fromHex} is the right default \u2014 every key and digest here\n * has a fixed width, and checking it catches a truncated paste at the edge\n * rather than deep inside a signature check. This one exists for the already-\n * encoded structures whose length is genuinely variable: a device certificate,\n * a login statement, a request signature. It still rejects odd-length and\n * non-hex input, so the only check it gives up is the one that cannot apply.\n */\nexport function fromHexUnsized(value: string, label: string): Uint8Array {\n const clean = value.trim();\n if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length % 2 !== 0) {\n throw new Error(`${label} must be an even number of hex characters`);\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i += 1) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nexport function u64le(value: number | bigint): Uint8Array {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setBigUint64(0, BigInt(value), true);\n return out;\n}\n\nexport function concat(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, p) => total + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n", "/**\n * The Noise NK handshake (`Noise_NK_25519_AESGCM_SHA256`) that opens a sealed\n * session, written against WebCrypto from the Noise specification\n * (revision 34, http://www.noiseprotocol.org/noise.html). The node runs the\n * other side with `snow`; core's published vectors check the two against each\n * other.\n *\n * NK: the initiator knows the responder's static key in advance \u2014 here the\n * transport key the node's quote commits to \u2014 and sends nothing but an\n * ephemeral key before both ephemerals are mixed in, so everything after the\n * handshake has forward secrecy.\n */\n\nimport { concat } from '../crypto/internal.js';\n\nconst PROTOCOL_NAME = 'Noise_NK_25519_AESGCM_SHA256';\nconst DH_LEN = 32;\nconst TAG_LEN = 16;\n/** PKCS#8 wrapping of a raw X25519 private key (RFC 8410). */\nconst PKCS8_X25519_PREFIX = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04,\n 0x22, 0x04, 0x20,\n]);\n\n/** Noise's `SymmetricState`: the chaining key, the handshake hash and the cipher key. */\nexport class SymmetricState {\n private ck: Uint8Array;\n private h: Uint8Array;\n private k: CryptoKey | null = null;\n private n = 0;\n\n private constructor(h: Uint8Array) {\n this.ck = h;\n this.h = h;\n }\n\n static async initialize(): Promise<SymmetricState> {\n // A name of 32 bytes or fewer is used as the hash, zero-padded.\n const name = new TextEncoder().encode(PROTOCOL_NAME);\n const h = new Uint8Array(32);\n h.set(name);\n return new SymmetricState(h);\n }\n\n async mixHash(data: Uint8Array): Promise<void> {\n this.h = await sha256(concat(this.h, data));\n }\n\n async mixKey(inputKeyMaterial: Uint8Array): Promise<void> {\n const [ck, key] = await hkdf2(this.ck, inputKeyMaterial);\n this.ck = ck;\n this.k = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt', 'decrypt']);\n this.n = 0;\n }\n\n async encryptAndHash(plaintext: Uint8Array): Promise<Uint8Array> {\n if (!this.k) throw new Error('Noise: no cipher key yet');\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: noiseNonce(this.n), additionalData: this.h },\n this.k,\n plaintext,\n ),\n );\n this.n += 1;\n await this.mixHash(ciphertext);\n return ciphertext;\n }\n\n async decryptAndHash(ciphertext: Uint8Array): Promise<Uint8Array> {\n if (!this.k) throw new Error('Noise: no cipher key yet');\n const plaintext = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: noiseNonce(this.n), additionalData: this.h },\n this.k,\n ciphertext,\n ),\n );\n this.n += 1;\n await this.mixHash(ciphertext);\n return plaintext;\n }\n\n /** The initiator-to-responder key, then the responder-to-initiator key. */\n split(): Promise<[Uint8Array, Uint8Array]> {\n return hkdf2(this.ck, new Uint8Array());\n }\n}\n\nexport interface X25519KeyPair {\n privateKey: CryptoKey;\n publicKey: Uint8Array;\n}\n\n/**\n * Start an NK handshake to `remoteStatic`. `fixedEphemeral` pins the\n * ephemeral secret, for the published test vectors only; leave it out.\n */\nexport async function initiate(\n remoteStatic: Uint8Array,\n prologue: Uint8Array,\n fixedEphemeral?: Uint8Array,\n): Promise<{\n message1: Uint8Array;\n finish(message2: Uint8Array): Promise<{ payload: Uint8Array; split: [Uint8Array, Uint8Array] }>;\n}> {\n const state = await SymmetricState.initialize();\n await state.mixHash(prologue);\n // <- s (known in advance)\n await state.mixHash(remoteStatic);\n // -> e, es\n const ephemeral = await x25519KeyPair(fixedEphemeral);\n await state.mixHash(ephemeral.publicKey);\n await state.mixKey(await dh(ephemeral.privateKey, remoteStatic));\n const message1 = concat(ephemeral.publicKey, await state.encryptAndHash(new Uint8Array()));\n\n return {\n message1,\n async finish(message2) {\n if (message2.length < DH_LEN + TAG_LEN) throw new Error('Noise: message 2 is too short');\n // <- e, ee\n const remoteEphemeral = message2.slice(0, DH_LEN);\n await state.mixHash(remoteEphemeral);\n await state.mixKey(await dh(ephemeral.privateKey, remoteEphemeral));\n const payload = await state.decryptAndHash(message2.slice(DH_LEN));\n return { payload, split: await state.split() };\n },\n };\n}\n\nexport async function x25519KeyPair(secret?: Uint8Array): Promise<X25519KeyPair> {\n if (!secret) {\n let pair: CryptoKeyPair;\n try {\n pair = (await crypto.subtle.generateKey({ name: 'X25519' }, true, [\n 'deriveBits',\n ])) as CryptoKeyPair;\n } catch (error) {\n throw new Error(\n 'Sealed transport needs WebCrypto with X25519, which this runtime lacks ' +\n `(${(error as Error)?.name ?? 'no crypto.subtle'}). Current browsers and Node have ` +\n 'it; in React Native, install react-native-quick-crypto as the global crypto.',\n );\n }\n const publicKey = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n return { privateKey: pair.privateKey, publicKey };\n }\n const privateKey = await crypto.subtle.importKey(\n 'pkcs8',\n concat(PKCS8_X25519_PREFIX, secret),\n { name: 'X25519' },\n true,\n ['deriveBits'],\n );\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n return { privateKey, publicKey: base64UrlDecode(jwk.x as string) };\n}\n\nexport async function dh(privateKey: CryptoKey, publicKey: Uint8Array): Promise<Uint8Array> {\n const peer = await crypto.subtle.importKey('raw', publicKey, { name: 'X25519' }, false, []);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'X25519', public: peer } as EcdhKeyDeriveParams, privateKey, 256),\n );\n}\n\n/** Noise's AESGCM nonce: 32 zero bits, then the counter as a big-endian u64. */\nfunction noiseNonce(n: number): Uint8Array {\n const nonce = new Uint8Array(12);\n new DataView(nonce.buffer).setBigUint64(4, BigInt(n), false);\n return nonce;\n}\n\nasync function sha256(data: Uint8Array): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\nasync function hmacSha256(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n const hmacKey = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n ]);\n return new Uint8Array(await crypto.subtle.sign('HMAC', hmacKey, data));\n}\n\n/** Noise's `HKDF` with two outputs. */\nasync function hkdf2(chainingKey: Uint8Array, inputKeyMaterial: Uint8Array): Promise<[Uint8Array, Uint8Array]> {\n const temp = await hmacSha256(chainingKey, inputKeyMaterial);\n const first = await hmacSha256(temp, new Uint8Array([1]));\n const second = await hmacSha256(temp, concat(first, new Uint8Array([2])));\n return [first, second];\n}\n\nfunction base64UrlDecode(value: string): Uint8Array {\n const base64 = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n", "/**\n * Sealed transport: requests encrypted end to end to a TEE node's attested key.\n *\n * A node speaks plain HTTP and any TLS in front of it ends outside the enclave,\n * at whatever proxy or relay the operator runs, so everything crossing that hop\n * (the bearer token, JSON-RPC arguments, results) is readable there. Sealing\n * encrypts it so that only the attested TD can read it, and only the TD can\n * produce a response the client accepts.\n *\n * The client opens a session with a Noise NK handshake to the X25519 transport\n * key the node's quote commits to (`fetchAttestedKey`, `GET /attestation`). The\n * transport key only authenticates the node: the session keys come from both\n * sides' ephemeral keys, so once a session is gone (an hour at most) what was\n * sent in it cannot be opened, not even with the transport key. Each request\n * is sealed under the session; each response streams back in sealed frames, so\n * server-sent events are sealed too. WebSockets cannot be, and the node\n * refuses one inside the envelope with a 501.\n *\n * The node's side, and the wire format this implements byte for byte, are in\n * core's `crates/sealed` (`calimero-sealed`):\n *\n * ```text\n * handshake Noise_NK_25519_AESGCM_SHA256, prologue \"calimero/sealed-http/v2\"\n * request POST /sealed/v2/handshake 0x02 || transport_pk || Noise message 1\n * response 0x02 || Noise message 2 (payload = session_id(16) || lifetime secs, u32 BE)\n * keys (req key, resp key) = Split()\n * exchange POST /sealed/v2\n * header 0x02 || session_id(16) || request_id (u64 BE; from 1, each used once)\n * request header || AES-256-GCM(req key, nonce = request_id || 0u32, aad = header, inner)\n * response frames, each u32 BE length || AES-256-GCM(resp key,\n * nonce = request_id || frame index (u32 BE, from 0), aad = header, kind || data)\n * kind 0 = head (JSON), 1 = body bytes, 2 = end; no end frame = cut short\n * inner u32 BE head length || head (JSON) || body\n * ```\n *\n * `CalimeroClient` seals every request this way; {@link createSealedFetch} is\n * the same channel as a plain `fetch`.\n */\n\nimport { concat } from '../crypto/internal.js';\nimport { initiate } from './noise.js';\nimport type { DcapCollateral } from './verify.js';\n\n/** Where a session is opened, relative to the node's base URL. */\nexport const HANDSHAKE_PATH = '/sealed/v2/handshake';\n/** Where sealed requests are posted, relative to the node's base URL. */\nexport const SEALED_PATH = '/sealed/v2';\n/** Content type of every sealed body. */\nexport const SEALED_CONTENT_TYPE = 'application/vnd.calimero.sealed';\n\nconst VERSION = 2;\nconst PROLOGUE = new TextEncoder().encode('calimero/sealed-http/v2');\nconst SESSION_ID_LEN = 16;\nconst HEADER_LEN = 1 + SESSION_ID_LEN + 8;\nconst FRAME_HEAD = 0;\nconst FRAME_DATA = 1;\nconst FRAME_END = 2;\n/**\n * The largest frame the node sends: a kind byte, at most 64 KiB of data, a tag.\n * Anything larger is refused before it is buffered, so a proxy cannot make the\n * client hold an unbounded frame it has yet to authenticate.\n */\nconst MAX_FRAME_LEN = 1 + 64 * 1024 + 16;\n/** Far more than a handshake reply (69 bytes) ever is. */\nconst MAX_HANDSHAKE_REPLY = 1024;\n/** Open a new session this long before the node would drop the current one. */\nconst RENEW_BEFORE_MS = 60_000;\nconst TRANSPORT_BINDING_DOMAIN = 'calimero.tee-attest.transport-key.v1';\nconst NULL_BODY_STATUSES = [101, 204, 205, 304];\n\nconst utf8 = new TextEncoder();\n\n/** The node no longer holds the transport key this client attested (it restarted). */\nexport class StaleTransportKeyError extends Error {\n name = 'StaleTransportKeyError';\n\n constructor() {\n super('The node no longer holds the attested transport key; attest again for the current one');\n }\n}\n\n/** The node refused the envelope itself, before anything inside it ran. */\nexport class SealedTransportError extends Error {\n name = 'SealedTransportError';\n\n constructor(\n public status: number,\n public code: string | undefined,\n message: string,\n /** How long the node asked to wait before retrying (`Retry-After`), if it did. */\n public retryAfterMs?: number,\n ) {\n super(message);\n }\n}\n\n/**\n * What the attest endpoint puts in report data bytes `32..64` when asked to\n * bind its transport key. `inner` is what would have been there otherwise: the\n * expected application hash, or 32 zero bytes when none was asked for.\n * Mirrors core's `attest_transport_binding`.\n */\nexport async function transportKeyBinding(\n inner: Uint8Array,\n transportKey: Uint8Array,\n): Promise<Uint8Array> {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n concat(utf8.encode(TRANSPORT_BINDING_DOMAIN), inner, transportKey),\n );\n return new Uint8Array(digest);\n}\n\nexport interface VerifyTransportQuote {\n /**\n * Verify `quoteB64` \u2014 never by asking the node being attested \u2014 and check\n * that its report data is `nonce || reportDataSuffix` (both hex). Resolve\n * true only when the quote is genuine, its measurements are ones you accept,\n * and the report data matches. {@link createQuoteVerifier} does all of this\n * in the page. `collateral` is what the node sent with the quote, when the\n * verifier asked for it.\n */\n (args: {\n quoteB64: string;\n nonce: string;\n reportDataSuffix: string;\n collateral?: DcapCollateral;\n }): Promise<boolean>;\n /**\n * Set by the verifiers this package builds. A Calimero 1.0 node sends no\n * collateral with its quote; the verifier fetches it itself.\n */\n readonly includeCollateral?: boolean;\n}\n\nexport interface SealedFetchOptions {\n /** The node's base URL. */\n baseUrl: string;\n /**\n * The node's attested transport key, or a function that attests and returns\n * it \u2014 typically `() => fetchAttestedKey(baseUrl, policy)`. Given a\n * function, a restarted node is handled: the key is attested again, through\n * your verifier, and the request retried once. Given bytes, a restart\n * surfaces as {@link StaleTransportKeyError}.\n */\n transportPublicKey: Uint8Array | (() => Promise<Uint8Array>);\n /** Fetch that carries the sealed envelope. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * A `fetch` that seals every request to the node's attested transport key.\n *\n * A request for any URL outside `baseUrl` is refused rather than sent in the\n * clear: falling back to plaintext would silently undo the point of sealing.\n */\nexport function createSealedFetch(options: SealedFetchOptions): typeof fetch {\n const base = new URL(options.baseUrl);\n const basePath = base.pathname.replace(/\\/+$/, '');\n const nodeUrl = `${base.origin}${basePath}`;\n const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));\n const attest =\n typeof options.transportPublicKey === 'function' ? options.transportPublicKey : undefined;\n let transportKey: Promise<Uint8Array> = attest\n ? Promise.resolve().then(attest)\n : Promise.resolve(options.transportPublicKey as Uint8Array);\n // Attesting starts now, before any request awaits it. A node that fails to\n // attest must surface on the request that needed the key, not earlier as an\n // unhandled rejection; the failure is still thrown to every awaiter.\n transportKey.catch(() => undefined);\n let session: Promise<Session> | undefined;\n\n const openSession = async (): Promise<Session> => {\n try {\n return await handshake(baseFetch, nodeUrl, await checkedKey(transportKey));\n } catch (error) {\n if (!(error instanceof StaleTransportKeyError) || !attest) throw error;\n transportKey = Promise.resolve().then(attest);\n return handshake(baseFetch, nodeUrl, await checkedKey(transportKey));\n }\n };\n /** The session to use now, and the promise it came from, to name it if it turns out stale. */\n const currentSession = async (): Promise<[Session, Promise<Session>]> => {\n const pending = session ?? renew(undefined);\n const open = await pending;\n if (Date.now() < open.renewAt) return [open, pending];\n const renewed = renew(pending);\n return [await renewed, renewed];\n };\n // Replace the session only if it is still the one found stale, so concurrent\n // requests that all find it stale open one new session between them.\n const renew = (stale: Promise<Session> | undefined): Promise<Session> => {\n if (session === stale) {\n const opening = openSession();\n session = opening;\n opening.catch(() => {\n if (session === opening) session = undefined;\n });\n }\n return session as Promise<Session>;\n };\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n if (url.origin !== base.origin || !url.pathname.startsWith(`${basePath}/`)) {\n throw new Error(`Refusing to send ${url.href} outside the sealed node at ${options.baseUrl}`);\n }\n const headers: Array<[string, string]> = [];\n request.headers.forEach((value, name) => headers.push([name, value]));\n const head = { method: request.method, path: url.pathname.slice(basePath.length) + url.search, headers };\n const body = new Uint8Array(await request.arrayBuffer());\n // The caller's own signal, not `request.signal`: a Request's signal follows\n // the one it was built from only through a weak reference (undici), so once\n // the Request is garbage collected (it is, while a stream stays open) an\n // abort no longer reaches the fetch, and an event stream never closes.\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n\n const send = async (open: Session): Promise<Response> => {\n const { requestId, header, envelope } = await sealRequest(open, head, body);\n const response = await baseFetch(`${nodeUrl}${SEALED_PATH}`, {\n method: 'POST',\n headers: { 'content-type': SEALED_CONTENT_TYPE },\n body: envelope,\n signal,\n });\n if (response.headers.get('content-type') !== SEALED_CONTENT_TYPE) {\n throw await envelopeRefusal(response);\n }\n return openResponse(response, open.responseKey, header, requestId);\n };\n\n const [open, pending] = await currentSession();\n try {\n return await send(open);\n } catch (error) {\n // The node refused the envelope before running anything in it, so the\n // request can be sent again safely under a new session.\n if (!(error instanceof SealedTransportError) || error.code !== 'unknown_session') throw error;\n return send(await renew(pending));\n }\n };\n}\n\nasync function checkedKey(key: Promise<Uint8Array>): Promise<Uint8Array> {\n const bytes = await key;\n if (bytes.length !== 32) throw new Error('transportPublicKey must be 32 bytes');\n return bytes;\n}\n\nexport interface Session {\n requestKey: CryptoKey;\n responseKey: CryptoKey;\n nextRequestId: number;\n renewAt: number;\n header(requestId: number): Uint8Array;\n}\n\nasync function handshake(\n baseFetch: typeof fetch,\n nodeUrl: string,\n transportKey: Uint8Array,\n): Promise<Session> {\n try {\n return await handshakeOnce(baseFetch, nodeUrl, transportKey);\n } catch (error) {\n // The node limits how fast sessions open. A refused handshake opened\n // nothing, so trying once more after the pause it asks for is safe.\n if (!(error instanceof SealedTransportError) || error.code !== 'busy') throw error;\n await new Promise((resolve) => setTimeout(resolve, error.retryAfterMs ?? 1000));\n return handshakeOnce(baseFetch, nodeUrl, transportKey);\n }\n}\n\nasync function handshakeOnce(\n baseFetch: typeof fetch,\n nodeUrl: string,\n transportKey: Uint8Array,\n): Promise<Session> {\n const noise = await initiate(transportKey, PROLOGUE);\n const response = await baseFetch(`${nodeUrl}${HANDSHAKE_PATH}`, {\n method: 'POST',\n headers: { 'content-type': SEALED_CONTENT_TYPE },\n body: concat(new Uint8Array([VERSION]), transportKey, noise.message1),\n });\n if (response.headers.get('content-type') !== SEALED_CONTENT_TYPE) {\n throw await envelopeRefusal(response);\n }\n const reply = await readAtMost(response, MAX_HANDSHAKE_REPLY);\n return sessionFrom(noise, reply);\n}\n\n/** Finish the handshake with the node's reply. Exported for the published vectors. */\nexport async function sessionFrom(\n noise: Awaited<ReturnType<typeof initiate>>,\n reply: Uint8Array,\n): Promise<Session> {\n if (reply[0] !== VERSION) throw new Error('The handshake reply is malformed');\n let finished: Awaited<ReturnType<(typeof noise)['finish']>>;\n try {\n finished = await noise.finish(reply.slice(1));\n } catch {\n throw new Error('The handshake reply did not open: it did not come from the attested node');\n }\n const { payload, split } = finished;\n if (payload.length !== SESSION_ID_LEN + 4) throw new Error('The handshake reply is malformed');\n const sessionId = payload.slice(0, SESSION_ID_LEN);\n const lifetimeSecs = new DataView(payload.buffer, payload.byteOffset).getUint32(SESSION_ID_LEN, false);\n const [requestKey, responseKey] = await Promise.all([\n crypto.subtle.importKey('raw', split[0], 'AES-GCM', false, ['encrypt']),\n crypto.subtle.importKey('raw', split[1], 'AES-GCM', false, ['decrypt']),\n ]);\n split[0].fill(0);\n split[1].fill(0);\n return {\n requestKey,\n responseKey,\n nextRequestId: 1,\n renewAt: Date.now() + lifetimeSecs * 1000 - RENEW_BEFORE_MS,\n header(requestId) {\n const header = new Uint8Array(HEADER_LEN);\n header[0] = VERSION;\n header.set(sessionId, 1);\n new DataView(header.buffer).setBigUint64(1 + SESSION_ID_LEN, BigInt(requestId), false);\n return header;\n },\n };\n}\n\n/** Seal one request under the session's next request id. */\nexport async function sealRequest(\n session: Session,\n head: RequestHead,\n body: Uint8Array,\n): Promise<{ requestId: number; header: Uint8Array; envelope: Uint8Array }> {\n const requestId = session.nextRequestId;\n session.nextRequestId += 1;\n const header = session.header(requestId);\n const sealed = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce(requestId, 0), additionalData: header },\n session.requestKey,\n joinInner(head, body),\n );\n return { requestId, header, envelope: concat(header, new Uint8Array(sealed)) };\n}\n\n/** `request_id || index`, as the node numbers them. */\nfunction nonce(requestId: number, index: number): Uint8Array {\n const bytes = new Uint8Array(12);\n const view = new DataView(bytes.buffer);\n view.setBigUint64(0, BigInt(requestId), false);\n view.setUint32(8, index, false);\n return bytes;\n}\n\nexport interface RequestHead {\n method: string;\n path: string;\n headers: Array<[string, string]>;\n}\n\nexport interface ResponseHead {\n status: number;\n headers: Array<[string, string]>;\n}\n\nfunction joinInner(head: RequestHead, body: Uint8Array): Uint8Array {\n const encoded = utf8.encode(JSON.stringify(head));\n const len = new Uint8Array(4);\n new DataView(len.buffer).setUint32(0, encoded.length, false);\n return concat(len, encoded, body);\n}\n\n/**\n * Open a sealed response as it streams: wait for its head, then hand back a\n * `Response` whose body opens each frame as it arrives. A frame that does not\n * open, arrives out of order, or a stream that stops before its end frame\n * errors the body rather than passing anything unauthenticated on.\n */\nexport async function openResponse(\n response: Response,\n responseKey: CryptoKey,\n header: Uint8Array,\n requestId: number,\n): Promise<Response> {\n if (!response.body) throw new Error('The sealed response has no body');\n const frames = frameReader(response.body.getReader());\n let index = 0;\n const next = async (): Promise<{ kind: number; data: Uint8Array } | null> => {\n const sealed = await frames.next();\n if (!sealed) return null;\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce(requestId, index), additionalData: header },\n responseKey,\n sealed,\n ),\n );\n } catch {\n throw new Error('A sealed response frame did not open: it was not sealed by the attested node');\n }\n index += 1;\n return { kind: plain[0], data: plain.slice(1) };\n };\n\n const first = await next();\n if (!first || first.kind !== FRAME_HEAD) throw new Error('The sealed response is malformed');\n const head = JSON.parse(new TextDecoder().decode(first.data)) as ResponseHead;\n if (NULL_BODY_STATUSES.includes(head.status)) {\n await frames.cancel();\n return new Response(null, { status: head.status, headers: head.headers });\n }\n\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const frame = await next();\n if (!frame) {\n controller.error(new Error('The sealed response was cut short'));\n } else if (frame.kind === FRAME_DATA) {\n controller.enqueue(frame.data);\n } else if (frame.kind === FRAME_END) {\n controller.close();\n await frames.cancel();\n } else {\n controller.error(new Error('The sealed response is malformed'));\n }\n } catch (error) {\n controller.error(error);\n }\n },\n cancel() {\n return frames.cancel();\n },\n });\n return new Response(body, { status: head.status, headers: head.headers });\n}\n\n/** Split a byte stream into length-prefixed frames. */\nfunction frameReader(reader: ReadableStreamDefaultReader<Uint8Array>): {\n next(): Promise<Uint8Array | null>;\n cancel(): Promise<void>;\n} {\n let buffer = new Uint8Array();\n const fill = async (length: number): Promise<boolean> => {\n while (buffer.length < length) {\n const { done, value } = await reader.read();\n if (done) return false;\n buffer = concat(buffer, value);\n }\n return true;\n };\n return {\n async next() {\n if (!(await fill(4))) return null;\n const length = new DataView(buffer.buffer, buffer.byteOffset).getUint32(0, false);\n if (length > MAX_FRAME_LEN) {\n await reader.cancel();\n throw new Error('The sealed response is malformed: a frame is larger than the node sends');\n }\n if (!(await fill(4 + length))) return null;\n const frame = buffer.slice(4, 4 + length);\n buffer = buffer.slice(4 + length);\n return frame;\n },\n cancel: () => reader.cancel(),\n };\n}\n\n/** Read a body, refusing one longer than `limit` rather than buffering it. */\nasync function readAtMost(response: Response, limit: number): Promise<Uint8Array> {\n if (!response.body) return new Uint8Array();\n const reader = response.body.getReader();\n let bytes = new Uint8Array();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return bytes;\n bytes = concat(bytes, value);\n if (bytes.length > limit) {\n await reader.cancel();\n throw new Error('The handshake reply is malformed: it is too long');\n }\n }\n}\n\nasync function envelopeRefusal(response: Response): Promise<Error> {\n let code: string | undefined;\n let message = `Sealed request refused: HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: string; message?: string } };\n code = body?.error?.code;\n if (body?.error?.message) message = `Sealed request refused: ${body.error.message}`;\n } catch {\n // Not the node's JSON refusal \u2014 a proxy's page, most likely. The status is\n // all that can honestly be reported.\n }\n if (code === 'stale_transport_key') return new StaleTransportKeyError();\n const retryAfter = Number(response.headers.get('retry-after'));\n const retryAfterMs =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 5) * 1000 : undefined;\n return new SealedTransportError(response.status, code, message, retryAfterMs);\n}\n", "/**\n * The parts of the Sigstore public-good trust root that verifying a mero-tee\n * release's cosign bundle needs: the Fulcio certificate authorities that issue\n * the release workflow's short-lived signing certificates, and the Rekor log\n * key that signs the bundle's signed entry timestamp. Each with the window in\n * which the trust root says it was in use.\n *\n * Copied from the `trusted_root.json` that Sigstore publishes through its TUF\n * repository (https://tuf-repo-cdn.sigstore.dev, target `trusted_root.json`),\n * as shipped by the `sigstore` Python client 4.5.0 in\n * `sigstore/_store/https%3A%2F%2Ftuf-repo-cdn.sigstore.dev/trusted_root.json`.\n * Embedded rather than fetched: fetching it at run time would trust whoever\n * serves it, the very thing this check exists to avoid.\n *\n * Left out, because a legacy cosign bundle never uses them: the CT logs (the\n * certificate's SCT is not checked here, as core does not either), the\n * timestamp authority, and the Rekor v2 log `log2025-1.rekor.sigstore.dev`,\n * whose Ed25519 key signs checkpoints rather than signed entry timestamps. A\n * bundle that names any log but those below is refused.\n *\n * To refresh it when Sigstore rotates a key or adds a CA: take the current\n * `trusted_root.json` from a TUF client (`python -m sigstore` or `cosign\n * initialize` both keep one, verified against the TUF root), and copy each\n * `certificateAuthorities[].certChain.certificates[].rawBytes` with its\n * `validFor`, and each ECDSA `tlogs[]` entry's `publicKey.rawBytes`,\n * `publicKey.validFor` and `logId.keyId` (as hex). The tests check each log id\n * is the SHA-256 of its key and each chain verifies.\n */\n\n/** A Fulcio CA: its chain from the certificate that issues leaves up to the root, DER as base64. */\nexport interface FulcioAuthority {\n uri: string;\n /** When the trust root says this CA issued certificates. No `end`: it still does. */\n validFor: { start: string; end?: string };\n certChain: string[];\n}\n\n/** A Rekor log whose signed entry timestamps are accepted. */\nexport interface RekorLog {\n baseUrl: string;\n /** The log id a bundle names it by: the SHA-256 of its public key, hex. */\n logId: string;\n /** Its public key: DER SubjectPublicKeyInfo, base64. ECDSA P-256 with SHA-256. */\n publicKey: string;\n validFor: { start: string; end?: string };\n}\n\nexport const FULCIO_AUTHORITIES: readonly FulcioAuthority[] = [\n {\n uri: 'https://fulcio.sigstore.dev',\n validFor: { start: '2021-03-07T03:20:29Z', end: '2022-12-31T23:59:59.999Z' },\n certChain: [\n 'MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9y' +\n 'ZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UE' +\n 'ChMMc2lnc3RvcmUuZGV2MREwDw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{\n baseUrl: 'https://rekor.sigstore.dev',\n logId: 'c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d',\n publicKey:\n 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufB' +\n 'nhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==',\n validFor: { start: '2021-01-12T11:53:27Z' },\n },\n];\n", "/**\n * Just enough DER and X.509 to check a Sigstore signing certificate with\n * WebCrypto: read a certificate's signed part, validity, key and extensions,\n * and verify the ECDSA signatures (P-256 and P-384) Sigstore uses.\n *\n * Written here, rather than taken from a library, so the SDK keeps no runtime\n * dependencies and runs wherever WebCrypto does. It parses strictly and throws\n * on anything it does not expect; it is not a general X.509 implementation.\n */\n\nconst SEQUENCE = 0x30;\nconst OID = 0x06;\nconst INTEGER = 0x02;\nconst BIT_STRING = 0x03;\nconst OCTET_STRING = 0x04;\nconst BOOLEAN = 0x01;\nconst UTC_TIME = 0x17;\nconst GENERALIZED_TIME = 0x18;\nconst CONTEXT_0 = 0xa0;\nconst CONTEXT_3 = 0xa3;\n\nconst EC_PUBLIC_KEY = '1.2.840.10045.2.1';\nconst CURVES: Record<string, Curve> = {\n '1.2.840.10045.3.1.7': 'P-256',\n '1.3.132.0.34': 'P-384',\n};\nconst CURVE_SIZE: Record<Curve, number> = { 'P-256': 32, 'P-384': 48 };\n/** The certificate signature algorithms accepted: ECDSA with SHA-256 or SHA-384. */\nconst SIGNATURE_HASHES: Record<string, Hash> = {\n '1.2.840.10045.4.3.2': 'SHA-256',\n '1.2.840.10045.4.3.3': 'SHA-384',\n};\n\nexport type Curve = 'P-256' | 'P-384';\nexport type Hash = 'SHA-256' | 'SHA-384';\n\n/** One DER element: its tag, and where it and its contents lie in `bytes`. */\nexport interface Element {\n tag: number;\n bytes: Uint8Array;\n /** Offset of the element's first (tag) byte. */\n offset: number;\n /** Offset of its contents. */\n start: number;\n /** Offset just past it. */\n end: number;\n}\n\nfunction read(bytes: Uint8Array, offset: number, limit: number): Element {\n if (offset + 2 > limit) throw new Error('it is truncated');\n const tag = bytes[offset];\n if ((tag & 0x1f) === 0x1f) throw new Error('it uses a tag this parser does not read');\n let length = bytes[offset + 1];\n let start = offset + 2;\n if (length & 0x80) {\n const count = length & 0x7f;\n if (count === 0 || count > 4 || start + count > limit) throw new Error('it has a length this parser does not read');\n length = 0;\n for (let i = 0; i < count; i += 1) length = length * 256 + bytes[start + i];\n start += count;\n }\n const end = start + length;\n if (end > limit) throw new Error('it is truncated');\n return { tag, bytes, offset, start, end };\n}\n\n/** Parse one complete DER element, refusing trailing bytes. */\nexport function parseDer(bytes: Uint8Array): Element {\n const element = read(bytes, 0, bytes.length);\n if (element.end !== bytes.length) throw new Error('it has trailing bytes');\n return element;\n}\n\nexport function children(element: Element): Element[] {\n const out: Element[] = [];\n for (let offset = element.start; offset < element.end; ) {\n const child = read(element.bytes, offset, element.end);\n out.push(child);\n offset = child.end;\n }\n return out;\n}\n\n/** `element` if it has `tag`; otherwise throws naming `what`. */\nexport function expectTag(element: Element | undefined, tag: number, what: string): Element {\n if (!element || element.tag !== tag) throw new Error(`${what} is not where it should be`);\n return element;\n}\n\nexport function contents(element: Element): Uint8Array {\n return element.bytes.slice(element.start, element.end);\n}\n\n/** The whole element, header included. */\nfunction whole(element: Element): Uint8Array {\n return element.bytes.slice(element.offset, element.end);\n}\n\nfunction oid(element: Element | undefined): string {\n const value = contents(expectTag(element, OID, 'An object identifier'));\n if (value.length === 0 || value[value.length - 1] & 0x80) throw new Error('it has a malformed object identifier');\n const arcs: number[] = [];\n let arc = 0;\n for (const byte of value) {\n arc = arc * 128 + (byte & 0x7f);\n if (!(byte & 0x80)) {\n arcs.push(arc);\n arc = 0;\n }\n }\n const first = arcs.shift() as number;\n const head = first < 80 ? [Math.floor(first / 40), first % 40] : [2, first - 80];\n return [...head, ...arcs].join('.');\n}\n\nfunction time(element: Element): number {\n const text = new TextDecoder().decode(contents(element));\n const utc = element.tag === UTC_TIME ? /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text) : null;\n const generalized =\n element.tag === GENERALIZED_TIME ? /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text) : null;\n const parts = utc ?? generalized;\n if (!parts) throw new Error(`it holds the time ${JSON.stringify(text)}, which is not one a certificate may hold`);\n let year = Number(parts[1]);\n if (utc) year += year < 50 ? 2000 : 1900;\n const [month, day, hour, minute, second] = parts.slice(2).map(Number);\n return Date.UTC(year, month - 1, day, hour, minute, second);\n}\n\nexport interface Certificate {\n der: Uint8Array;\n /** The signed part, exactly as the issuer signed it. */\n tbs: Uint8Array;\n /** The hash of the ECDSA signature the issuer made over `tbs`. */\n signatureHash: Hash;\n /** That signature, DER. */\n signature: Uint8Array;\n /** The issuer and subject names, DER, to compare byte for byte. */\n issuer: Uint8Array;\n subject: Uint8Array;\n /** Validity, in milliseconds since the epoch, both ends inclusive. */\n notBefore: number;\n notAfter: number;\n /** The subject's key, DER SubjectPublicKeyInfo, and its curve. */\n spki: Uint8Array;\n curve: Curve;\n /** Each extension's value (the contents of its OCTET STRING), by object identifier. */\n extensions: Map<string, Uint8Array>;\n}\n\n/**\n * Parse a DER X.509 certificate with an ECDSA key, signed with ECDSA. Throws\n * naming what is wrong.\n */\nexport function parseCertificate(der: Uint8Array): Certificate {\n try {\n const [tbsElement, algorithm, signature, ...rest] = children(\n expectTag(parseDer(der), SEQUENCE, 'The certificate'),\n );\n if (rest.length > 0) throw new Error('it has fields after its signature');\n const fields = children(expectTag(tbsElement, SEQUENCE, 'The signed part'));\n // `version` is [0] EXPLICIT; everything after it is positional.\n const first = fields[0]?.tag === CONTEXT_0 ? 1 : 0;\n const [serial, innerAlgorithm, issuer, validity, subject, spki, ...optional] = fields.slice(first);\n expectTag(serial, INTEGER, 'The serial number');\n\n const algorithmId = oid(children(expectTag(algorithm, SEQUENCE, 'The signature algorithm'))[0]);\n const innerId = oid(children(expectTag(innerAlgorithm, SEQUENCE, 'The signature algorithm'))[0]);\n if (innerId !== algorithmId) throw new Error('it names two different signature algorithms');\n const signatureHash = SIGNATURE_HASHES[algorithmId];\n if (!signatureHash) throw new Error(`it is signed with ${algorithmId}, not ECDSA with SHA-256 or SHA-384`);\n\n const [notBefore, notAfter] = children(expectTag(validity, SEQUENCE, 'The validity')).map(time);\n if (notAfter === undefined) throw new Error('its validity is incomplete');\n\n const [keyAlgorithm, keyBits] = children(expectTag(spki, SEQUENCE, 'The public key'));\n expectTag(keyBits, BIT_STRING, 'The public key');\n const [keyType, keyCurve] = children(expectTag(keyAlgorithm, SEQUENCE, 'The key algorithm'));\n if (oid(keyType) !== EC_PUBLIC_KEY) throw new Error('its key is not an elliptic-curve key');\n const curve = CURVES[oid(keyCurve)];\n if (!curve) throw new Error('its key is on a curve other than P-256 or P-384');\n\n const extensions = new Map<string, Uint8Array>();\n const extensionsField = optional.find((field) => field.tag === CONTEXT_3);\n if (extensionsField) {\n const [list] = children(extensionsField);\n for (const extension of children(expectTag(list, SEQUENCE, 'The extensions'))) {\n const parts = children(expectTag(extension, SEQUENCE, 'An extension'));\n if (parts.length === 3) expectTag(parts[1], BOOLEAN, 'An extension\\'s critical flag');\n else if (parts.length !== 2) throw new Error('it has a malformed extension');\n const id = oid(parts[0]);\n if (extensions.has(id)) throw new Error(`it has extension ${id} twice`);\n extensions.set(id, contents(expectTag(parts[parts.length - 1], OCTET_STRING, 'An extension value')));\n }\n }\n\n const signatureBits = contents(expectTag(signature, BIT_STRING, 'The signature'));\n if (signatureBits[0] !== 0) throw new Error('its signature is not a whole number of bytes');\n return {\n der,\n tbs: whole(tbsElement),\n signatureHash,\n signature: signatureBits.slice(1),\n issuer: whole(expectTag(issuer, SEQUENCE, 'The issuer')),\n subject: whole(expectTag(subject, SEQUENCE, 'The subject')),\n notBefore,\n notAfter,\n spki: whole(spki),\n curve,\n extensions,\n };\n } catch (error) {\n throw new Error(`The certificate is malformed: ${(error as Error).message}`);\n }\n}\n\n/** The object identifiers in a DER `SEQUENCE OF OBJECT IDENTIFIER` (an extended key usage). */\nexport function objectIdentifiers(der: Uint8Array): string[] {\n return children(expectTag(parseDer(der), SEQUENCE, 'The list')).map(oid);\n}\n\n/**\n * An ECDSA signature as WebCrypto takes it (IEEE P1363: `r || s`, each the\n * curve's size), from the DER `SEQUENCE { r INTEGER, s INTEGER }` X.509 and\n * cosign use.\n */\nexport function ecdsaSignatureToP1363(der: Uint8Array, curve: Curve): Uint8Array {\n const size = CURVE_SIZE[curve];\n const integers = children(expectTag(parseDer(der), SEQUENCE, 'The signature'));\n if (integers.length !== 2) throw new Error('The signature is not an ECDSA signature');\n const out = new Uint8Array(size * 2);\n integers.forEach((integer, index) => {\n let value = contents(expectTag(integer, INTEGER, 'The signature'));\n // r and s are positive: a set top bit with no leading zero is a negative number.\n if (value.length === 0 || value[0] & 0x80) throw new Error('The signature is not an ECDSA signature');\n while (value.length > 1 && value[0] === 0) value = value.subarray(1);\n if (value.length > size) throw new Error('The signature is not an ECDSA signature');\n out.set(value, index * size + size - value.length);\n });\n return out;\n}\n\n/** Verify a DER ECDSA `signature` over `data` with a DER SubjectPublicKeyInfo key. */\nexport async function verifyEcdsa(\n spki: Uint8Array,\n curve: Curve,\n hash: Hash,\n signature: Uint8Array,\n data: Uint8Array,\n): Promise<boolean> {\n let p1363: Uint8Array;\n try {\n p1363 = ecdsaSignatureToP1363(signature, curve);\n } catch {\n return false;\n }\n const key = await crypto.subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: curve }, false, ['verify']);\n return crypto.subtle.verify({ name: 'ECDSA', hash }, key, p1363, data);\n}\n\n/** Decode base64 (standard alphabet), refusing anything else. */\nexport function fromBase64(value: string, what: string): Uint8Array {\n const clean = value.replace(/\\s+/g, '');\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 !== 0) {\n throw new Error(`${what} is not base64`);\n }\n const binary = atob(clean);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The DER of the one `CERTIFICATE` block a PEM holds. */\nexport function pemCertificate(pem: string, what: string): Uint8Array {\n const blocks = [...pem.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];\n if (blocks.length !== 1 || pem.replace(blocks[0][0], '').trim() !== '') {\n throw new Error(`${what} is not exactly one PEM certificate`);\n }\n return fromBase64(blocks[0][1], what);\n}\n", "/**\n * Verifying a cosign keyless signature, as `cosign verify-blob --bundle` does,\n * with WebCrypto and the Sigstore trust root embedded in this package.\n *\n * mero-tee signs each release asset with cosign keyless: there is no release\n * key, only a Fulcio certificate that lives ten minutes, issued to one GitHub\n * Actions workflow run, and a Rekor log entry that proves the signature was\n * made while the certificate was valid. So the checks are: the signature over\n * the bytes verifies with the certificate's key; Rekor's signed entry\n * timestamp verifies, and the entry it signs is this signature over these\n * bytes by this certificate; the certificate chains to a Fulcio CA and was\n * valid when Rekor logged it; and the certificate names the workflow expected.\n * The same checks core runs in `crates/tee-release/src/sigstore_verify.rs`.\n *\n * Nothing here reads the clock. Every time is Rekor's `integratedTime`, which\n * its signature covers, so a verification that passes once passes forever,\n * whatever the client's clock says.\n */\n\nimport { hex } from '../crypto/internal.js';\nimport { FULCIO_AUTHORITIES, REKOR_LOGS } from './sigstore-trust-root.js';\nimport {\n children,\n contents,\n expectTag,\n fromBase64,\n objectIdentifiers,\n parseCertificate,\n parseDer,\n pemCertificate,\n verifyEcdsa,\n type Certificate,\n} from './x509.js';\n\nconst SUBJECT_ALT_NAME = '2.5.29.17';\nconst EXTENDED_KEY_USAGE = '2.5.29.37';\nconst CODE_SIGNING = '1.3.6.1.5.5.7.3.3';\n/** Fulcio's OIDC issuer extension, a DER UTF8String. */\nconst FULCIO_ISSUER_V2 = '1.3.6.1.4.1.57264.1.8';\n/** Its deprecated predecessor, the raw issuer bytes; read only when the other is absent. */\nconst FULCIO_ISSUER_V1 = '1.3.6.1.4.1.57264.1.1';\nconst SAN_URI = 0x86;\nconst UTF8_STRING = 0x0c;\nconst SEQUENCE = 0x30;\n\nconst utf8 = new TextEncoder();\n// Not `fatal`: not every runtime's TextDecoder takes options. A malformed byte\n// decodes to U+FFFD, which no pinned identity holds, so it can only fail a match.\nconst fromUtf8 = (bytes: Uint8Array) => new TextDecoder().decode(bytes);\n\n/** Who must have signed: the certificate's SAN URI and its OIDC issuer, each matched exactly. */\nexport interface SignerIdentity {\n identity: string;\n issuer: string;\n}\n\n/** A legacy cosign bundle (`cosign sign-blob --bundle`), as the fields verified here. */\ninterface CosignBundle {\n base64Signature: string;\n cert: string;\n rekorBundle: {\n SignedEntryTimestamp: string;\n Payload: { body: string; integratedTime: number; logIndex: number; logID: string };\n };\n}\n\n/**\n * Verify a cosign keyless `bundle` over `body`, signed by `signer`. Resolves\n * with the time Rekor logged it (seconds); rejects with the reason otherwise.\n * `signature`, when given, is the detached `.sig` published beside the file,\n * and must be the bundle's.\n */\nexport async function verifyCosignBundle(\n body: Uint8Array,\n bundle: unknown,\n signer: SignerIdentity,\n signature?: string,\n): Promise<{ integratedTime: number }> {\n const { base64Signature, cert, rekorBundle } = cosignBundle(bundle);\n const payload = rekorBundle.Payload;\n if (signature !== undefined && signature.trim() !== base64Signature.trim()) {\n throw new Error('The detached signature is not the one in the bundle');\n }\n const sig = fromBase64(base64Signature, 'The bundle signature');\n const leafDer = pemCertificate(fromUtf8(fromBase64(cert, 'The bundle certificate')), 'The bundle certificate');\n const leaf = parseCertificate(leafDer);\n\n // Rekor vouches for the entry and its time: nothing below is trusted before this.\n const log = REKOR_LOGS.find((candidate) => candidate.logId === payload.logID.toLowerCase());\n if (!log) throw new Error(`The bundle names Rekor log ${payload.logID}, which the Sigstore trust root does not know`);\n const canonical = utf8.encode(\n `{\"body\":${JSON.stringify(payload.body)},\"integratedTime\":${payload.integratedTime},` +\n `\"logID\":${JSON.stringify(payload.logID)},\"logIndex\":${payload.logIndex}}`,\n );\n const setVerifies = await verifyEcdsa(\n fromBase64(log.publicKey, 'The Rekor key'),\n 'P-256',\n 'SHA-256',\n fromBase64(rekorBundle.SignedEntryTimestamp, 'The signed entry timestamp'),\n canonical,\n );\n if (!setVerifies) {\n throw new Error(\"Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered\");\n }\n const at = payload.integratedTime * 1000;\n if (!within(at, log.validFor)) {\n throw new Error(`Rekor log ${log.baseUrl} was not in use at ${iso(at)}, when the entry says it was logged`);\n }\n\n // The entry Rekor signed is this signature, over these bytes, by this certificate.\n const entry = hashedRekord(payload.body);\n const digest = hex(new Uint8Array(await crypto.subtle.digest('SHA-256', body)));\n if (entry.hash !== digest) throw new Error(\"The file's SHA-256 is not the one Rekor logged: the file is not the one signed\");\n if (!equal(fromBase64(entry.signature, 'The logged signature'), sig)) {\n throw new Error(\"The bundle's signature is not the one Rekor logged\");\n }\n const loggedCert = pemCertificate(fromUtf8(fromBase64(entry.publicKey, 'The logged certificate')), 'The logged certificate');\n if (!equal(loggedCert, leafDer)) throw new Error(\"The bundle's certificate is not the one Rekor logged\");\n\n if (leaf.curve !== 'P-256' || !(await verifyEcdsa(leaf.spki, 'P-256', 'SHA-256', sig, body))) {\n throw new Error(\"The signature over the file does not verify with the bundle's certificate\");\n }\n\n await chainsToFulcio(leaf, at);\n checkSigner(leaf, signer);\n return { integratedTime: payload.integratedTime };\n}\n\n/**\n * Check that `leaf` was issued by a Fulcio CA in the trust root, and that it,\n * the CA's certificates and the CA itself (by the trust root's `validFor`)\n * were all valid at `at` (milliseconds): when Rekor logged the signature, not\n * now, since a Fulcio certificate lives ten minutes. Every signature on the\n * way is checked, with the algorithm its certificate names.\n */\nexport async function chainsToFulcio(leaf: Certificate, at: number): Promise<void> {\n if (!validAt(leaf, at)) {\n throw new Error(\n `The signing certificate was valid ${iso(leaf.notBefore)} to ${iso(leaf.notAfter)}, not at ${iso(at)} when Rekor logged it`,\n );\n }\n const reasons: string[] = [];\n for (const authority of FULCIO_AUTHORITIES) {\n const chain = authority.certChain.map((der) => parseCertificate(fromBase64(der, 'A Fulcio certificate')));\n if (!(await issuedBy(leaf, chain[0]))) continue;\n // The issuer is found; from here a failure is this CA's, so say which.\n const reason = await authorityRefusal(chain, authority.validFor, at);\n if (!reason) return;\n reasons.push(`${authority.uri} (valid from ${authority.validFor.start}): ${reason}`);\n }\n throw new Error(\n reasons.length > 0\n ? `The signing certificate's CA is not trusted at ${iso(at)}: ${reasons.join('; ')}`\n : 'The signing certificate was not issued by a Fulcio CA in the Sigstore trust root',\n );\n}\n\nasync function authorityRefusal(\n chain: Certificate[],\n validFor: { start: string; end?: string },\n at: number,\n): Promise<string | undefined> {\n if (!within(at, validFor)) return 'the trust root says it was not issuing certificates then';\n for (const [index, certificate] of chain.entries()) {\n if (!validAt(certificate, at)) return `its certificate ${index} was not valid then`;\n const parent = chain[index + 1] ?? certificate; // the root signs itself\n if (!(await issuedBy(certificate, parent))) return `its certificate ${index} is not signed by the next`;\n }\n return undefined;\n}\n\nasync function issuedBy(child: Certificate, parent: Certificate): Promise<boolean> {\n if (!equal(child.issuer, parent.subject)) return false;\n return verifyEcdsa(parent.spki, parent.curve, child.signatureHash, child.signature, child.tbs);\n}\n\nfunction checkSigner(leaf: Certificate, signer: SignerIdentity): void {\n const san = leaf.extensions.get(SUBJECT_ALT_NAME);\n if (!san) throw new Error('The signing certificate names no identity');\n const names = children(expectTag(parseDer(san), SEQUENCE, 'The subject alternative name'));\n const uris = names.filter((name) => name.tag === SAN_URI).map((name) => fromUtf8(contents(name)));\n if (uris.length !== 1 || names.length !== 1 || uris[0] !== signer.identity) {\n throw new Error(\n `The release was signed by ${JSON.stringify(uris.length === 1 ? uris[0] : uris)}, not by ${signer.identity}`,\n );\n }\n\n const v2 = leaf.extensions.get(FULCIO_ISSUER_V2);\n const v1 = leaf.extensions.get(FULCIO_ISSUER_V1);\n const issuer = v2\n ? fromUtf8(contents(expectTag(parseDer(v2), UTF8_STRING, 'The OIDC issuer')))\n : v1\n ? fromUtf8(v1)\n : undefined;\n if (issuer !== signer.issuer) {\n throw new Error(\n `The signing certificate's OIDC issuer is ${issuer === undefined ? 'missing' : JSON.stringify(issuer)}, not ${signer.issuer}`,\n );\n }\n\n const usage = leaf.extensions.get(EXTENDED_KEY_USAGE);\n if (!usage || !objectIdentifiers(usage).includes(CODE_SIGNING)) {\n throw new Error('The signing certificate is not for code signing');\n }\n}\n\nfunction cosignBundle(value: unknown): CosignBundle {\n let bundle = value;\n if (typeof bundle === 'string') {\n try {\n bundle = JSON.parse(bundle);\n } catch {\n throw new Error('The bundle is not JSON');\n }\n }\n const b = bundle as Partial<CosignBundle> | null;\n const p = b?.rekorBundle?.Payload;\n const ok =\n typeof b?.base64Signature === 'string' &&\n typeof b.cert === 'string' &&\n typeof b.rekorBundle?.SignedEntryTimestamp === 'string' &&\n typeof p?.body === 'string' &&\n typeof p.logID === 'string' &&\n /^[0-9a-fA-F]{64}$/.test(p.logID) &&\n Number.isSafeInteger(p.integratedTime) &&\n p.integratedTime >= 0 &&\n Number.isSafeInteger(p.logIndex) &&\n p.logIndex >= 0;\n if (!ok) throw new Error('The bundle is not a cosign bundle with a Rekor entry');\n return b as CosignBundle;\n}\n\n/** The fields of a logged `hashedrekord` entry that are compared. */\nfunction hashedRekord(body: string): { hash: string; signature: string; publicKey: string } {\n let entry: {\n kind?: unknown;\n spec?: {\n data?: { hash?: { algorithm?: unknown; value?: unknown } };\n signature?: { content?: unknown; publicKey?: { content?: unknown } };\n };\n };\n try {\n entry = JSON.parse(fromUtf8(fromBase64(body, 'The logged entry')));\n } catch {\n throw new Error('The logged entry is not JSON');\n }\n const hash = entry?.spec?.data?.hash;\n const signature = entry?.spec?.signature;\n if (\n entry?.kind !== 'hashedrekord' ||\n hash?.algorithm !== 'sha256' ||\n typeof hash.value !== 'string' ||\n typeof signature?.content !== 'string' ||\n typeof signature.publicKey?.content !== 'string'\n ) {\n throw new Error('The logged entry is not a SHA-256 hashedrekord');\n }\n return { hash: hash.value.toLowerCase(), signature: signature.content, publicKey: signature.publicKey.content };\n}\n\nfunction validAt(certificate: Certificate, at: number): boolean {\n return certificate.notBefore <= at && at <= certificate.notAfter;\n}\n\nfunction within(at: number, window: { start: string; end?: string }): boolean {\n return Date.parse(window.start) <= at && (window.end === undefined || at <= Date.parse(window.end));\n}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString();\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, index) => byte === b[index]);\n}\n", "/**\n * Verifying a TEE node's quote in the page, before trusting the key it binds.\n *\n * A quote proves what runs in a TD only once it has been checked: its\n * signatures against Intel's root, the TCB status of the platform, the\n * measurements of the image, and that its report data is the nonce and the\n * binding this client asked for. {@link createQuoteVerifier} does all of that\n * here. A Calimero 1.0 node sends no collateral: the verifier fetches Intel's\n * (`fetchCollateral`), which the node can neither forge nor choose.\n *\n * The DCAP verification itself \u2014 parsing the quote, checking its signature\n * chain and appraising its TCB level against the collateral \u2014 comes from a\n * library you pass in, normally `verify` from `@phala/dcap-qvl`, a pure\n * JavaScript implementation that runs in browsers, Node and React Native. It\n * is passed in rather than bundled so this SDK keeps no runtime dependencies,\n * and applications that never talk to a TEE node pay nothing for it.\n */\n\nimport { hex } from '../crypto/internal.js';\nimport type { VerifyTransportQuote } from './sealed.js';\n\n/**\n * The collateral a quote is verified against \u2014 TCB info, QE identity, CRLs and\n * their chains \u2014 in dcap-qvl's form: byte fields are hex strings or byte\n * arrays. What `@phala/dcap-qvl`'s `getCollateral` fetches.\n */\nexport interface DcapCollateral {\n pck_crl_issuer_chain: string;\n root_ca_crl: number[] | string;\n pck_crl: number[] | string;\n tcb_info_issuer_chain: string;\n tcb_info: string;\n tcb_info_signature: number[] | string;\n qe_identity_issuer_chain: string;\n qe_identity: string;\n qe_identity_signature: number[] | string;\n}\n\n/** The fields of a TDX report this verifier reads. */\ninterface TdReport {\n mrTd: Uint8Array;\n rtMr0: Uint8Array;\n rtMr1: Uint8Array;\n rtMr2: Uint8Array;\n rtMr3: Uint8Array;\n reportData: Uint8Array;\n tdAttributes?: Uint8Array;\n}\n\n/** What a DCAP verifier returns for a quote whose signature chain verified. */\nexport interface DcapVerifiedReport {\n status: string;\n advisory_ids?: string[];\n report: { type: string; data: unknown };\n}\n\n/**\n * Verify a quote's signature chain against `collateral` as of `nowSecs`, and\n * appraise its TCB level. Throws when it does not verify. `verify` from\n * `@phala/dcap-qvl` has exactly this shape.\n */\nexport type DcapVerify = (\n quote: Uint8Array,\n collateral: DcapCollateral,\n nowSecs: number,\n) => DcapVerifiedReport;\n\n/**\n * One image's measurements, all five registers, hex. A quote matches it only\n * when every register does, so measurements of different images never combine.\n */\nexport interface TrustedMeasurements {\n mrtd: string;\n rtmr0: string;\n rtmr1: string;\n rtmr2: string;\n rtmr3: string;\n}\n\nexport interface QuoteVerifierOptions {\n /** DCAP verification: `verify` from `@phala/dcap-qvl`. */\n dcapVerify: DcapVerify;\n /**\n * The images trusted, each by all of its measurements. The way to say which\n * code may read the traffic: build it with {@link trustedMeasurementsFromReleases}\n * from the `published-mrtds.json` of the releases you trust.\n */\n allowedMeasurements?: TrustedMeasurements[];\n /**\n * MRTDs (hex) accepted. On its own this does not name an image: on GCP the\n * MRTD measures the platform's TD firmware, which every image shares, and\n * the image is in RTMR1\u20133. So a verifier needs either\n * {@link allowedMeasurements}, or this with all of `allowedRtmr1`\u2013`3`.\n */\n allowedMrtd?: string[];\n /** RTMR allowlists (hex); a register is not checked when its list is left out. */\n allowedRtmr0?: string[];\n allowedRtmr1?: string[];\n allowedRtmr2?: string[];\n allowedRtmr3?: string[];\n /**\n * TCB statuses accepted. Defaults to `['UpToDate']`. `Revoked` is refused\n * even when listed.\n */\n allowedTcbStatuses?: string[];\n /**\n * Where to get collateral (a Calimero 1.0 node sends none): for example\n * `(quote) => getCollateral(PHALA_PCCS_URL, quote)` from `@phala/dcap-qvl`.\n * Without it, a quote that came without collateral is refused.\n */\n fetchCollateral?: (quote: Uint8Array) => Promise<DcapCollateral>;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/** A quote verifier as this package builds one ({@link createQuoteVerifier}). */\nexport type QuoteVerifier = VerifyTransportQuote & { readonly includeCollateral: true };\n\nconst MEASUREMENT_HEX = /^[0-9a-f]{96}$/;\nconst REGISTERS = ['mrtd', 'rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] as const;\n\n/**\n * A verifier that checks a TEE node's quote here, in the page, and accepts it\n * only when every check passes:\n *\n * - its signatures verify against Intel's root, with collateral that is valid\n * now;\n * - the platform's TCB status is one allowed (`UpToDate` by default), and\n * never `Revoked`;\n * - its measurements are those of a trusted image: one of\n * `allowedMeasurements` in full, and the MRTD and any RTMRs listed;\n * - its report data is the nonce followed by the binding the client computed.\n *\n * Any failure rejects with the reason; nothing is trusted from a quote that\n * does not pass. Mock quotes never pass: they carry no signature.\n *\n * ```ts\n * import { verify as dcapVerify } from '@phala/dcap-qvl';\n *\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...trustedMeasurementsFromReleases([publishedMrtds], { profile: 'locked-read-only' }),\n * });\n * const client = new CalimeroClient({ baseUrl, policy: { verifyQuote: verifier } });\n * ```\n */\nexport function createQuoteVerifier(options: QuoteVerifierOptions): QuoteVerifier {\n const allowedMrtd = measurements(options.allowedMrtd ?? [], 'allowedMrtd');\n const allowedImages = (options.allowedMeasurements ?? []).map((image, index) => {\n const label = `allowedMeasurements[${index}]`;\n return REGISTERS.map((register) => measurements([image?.[register] ?? ''], `${label}.${register}`)[0]).join();\n });\n const allowedRtmr = [\n measurements(options.allowedRtmr0 ?? [], 'allowedRtmr0'),\n measurements(options.allowedRtmr1 ?? [], 'allowedRtmr1'),\n measurements(options.allowedRtmr2 ?? [], 'allowedRtmr2'),\n measurements(options.allowedRtmr3 ?? [], 'allowedRtmr3'),\n ];\n if (options.allowedMeasurements !== undefined && allowedImages.length === 0) {\n throw new Error('allowedMeasurements is empty, so no quote would ever be accepted');\n }\n if (allowedImages.length === 0) {\n if (allowedMrtd.length === 0) {\n throw new Error('No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3');\n }\n if (allowedRtmr.slice(1).some((list) => list.length === 0)) {\n throw new Error(\n 'allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which ' +\n 'images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too',\n );\n }\n }\n const allowedStatuses = options.allowedTcbStatuses ?? ['UpToDate'];\n const now = options.now ?? Date.now;\n\n const verifier = async ({\n quoteB64,\n nonce,\n reportDataSuffix,\n collateral,\n }: Parameters<VerifyTransportQuote>[0]): Promise<boolean> => {\n const quote = fromBase64(quoteB64);\n const against = collateral ?? (await options.fetchCollateral?.(quote));\n if (!against) {\n throw new Error(\n 'The node sent no collateral for its quote, and no fetchCollateral was given to get it',\n );\n }\n\n let verified: DcapVerifiedReport;\n try {\n verified = options.dcapVerify(quote, against, Math.floor(now() / 1000));\n } catch (error) {\n throw new Error(`The quote did not verify: ${(error as Error)?.message ?? String(error)}`);\n }\n\n if (verified.status === 'Revoked' || !allowedStatuses.includes(verified.status)) {\n throw new Error(`The platform's TCB status is ${verified.status}, which is not accepted`);\n }\n const td = tdReport(verified.report);\n // TUD bit 0. A debug TD's memory and registers are open to the host, so its\n // measurements prove nothing about what runs in it. Checked here, not left\n // to `dcapVerify`, which a caller may swap for one that allows debug; an\n // attribute field that cannot be read counts as debug.\n if (td.tdAttributes?.length !== 8 || (td.tdAttributes[0] & 0x01) !== 0) {\n throw new Error('The quote is from a debug TD, or its TD attributes cannot be read');\n }\n const measured = [td.mrTd, td.rtMr0, td.rtMr1, td.rtMr2, td.rtMr3].map((register) => hex(register));\n if (allowedImages.length > 0 && !allowedImages.includes(measured.join())) {\n throw new Error(\n `The measurements (MRTD ${measured[0]}, RTMR0-3 ${measured.slice(1).join(', ')}) are not an image this verifier trusts`,\n );\n }\n if (allowedMrtd.length > 0 && !allowedMrtd.includes(measured[0])) {\n throw new Error(`MRTD ${measured[0]} is not an image this verifier trusts`);\n }\n const registers = [td.rtMr0, td.rtMr1, td.rtMr2, td.rtMr3];\n registers.forEach((register, index) => {\n const allowed = allowedRtmr[index];\n if (allowed.length > 0 && !allowed.includes(hex(register))) {\n throw new Error(`RTMR${index} ${hex(register)} is not one this verifier trusts`);\n }\n });\n if (hex(td.reportData) !== `${nonce}${reportDataSuffix}`.toLowerCase()) {\n throw new Error('The quote does not commit to this nonce and binding');\n }\n return true;\n };\n return Object.assign(verifier, { includeCollateral: true as const });\n}\n\nfunction measurements(values: string[], label: string): string[] {\n return values.map((value) => {\n const normalized = value.trim().toLowerCase();\n if (!MEASUREMENT_HEX.test(normalized)) {\n throw new Error(`${label} holds ${JSON.stringify(value)}, which is not a 48-byte hex measurement`);\n }\n return normalized;\n });\n}\n\n/** The TD report of a TDX quote (1.0 or 1.5); anything else is refused. */\nfunction tdReport(report: DcapVerifiedReport['report']): TdReport {\n const data = report.data as (TdReport & { base?: TdReport }) | undefined;\n if (report.type === 'td10' && data) return data;\n if (report.type === 'td15' && data?.base) return data.base;\n throw new Error(`The quote is a ${report.type} quote, not a TDX one`);\n}\n\nfunction fromBase64(value: string): Uint8Array {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * A mero-tee node release's `published-mrtds.json`: the measurements the\n * release workflow observed booting each profile of its image on TDX, signed\n * with the release. Only the fields read here are typed.\n */\nexport interface PublishedMrtds {\n role?: string;\n tag?: string;\n profiles: Record<\n string,\n {\n mrtd: string;\n rtmr0: string;\n rtmr1: string;\n rtmr2: string;\n rtmr3: string;\n allowed_tcb_statuses?: string[];\n }\n >;\n}\n\n/** TCB statuses as DCAP reports them; the release lists them in lower case. */\nconst TCB_STATUSES = [\n 'UpToDate',\n 'SWHardeningNeeded',\n 'ConfigurationNeeded',\n 'ConfigurationAndSWHardeningNeeded',\n 'OutOfDate',\n 'OutOfDateConfigurationNeeded',\n];\n\n/**\n * The {@link QuoteVerifierOptions} that trust exactly one profile of the given\n * releases: each release's image by all of its measurements, and only the TCB\n * statuses every one of those releases accepts.\n *\n * Pass every release a node you talk to may run. During a rollout that is the\n * old one and the new one; drop the old one once no node runs it.\n *\n * ```ts\n * import published from './trusted/mero-tee-v2.3.78.published-mrtds.json';\n *\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...trustedMeasurementsFromReleases([published], { profile: 'locked-read-only' }),\n * });\n * ```\n *\n * Where the file comes from is the trust decision. Shipping it with the app\n * (checked out of a release you verified) trusts that release; fetching it at\n * run time trusts whoever serves it.\n */\n/**\n * The one image profile a release publishes for production. The `debug` and\n * `debug-read-only` images are signed and published beside it, but run with\n * SSH and the operator's tooling inside the TD, so trusting one trusts an\n * image the operator can read.\n */\nexport const PRODUCTION_PROFILE = 'locked-read-only';\n\nexport interface TrustedProfileOptions {\n /** The image profile to trust, e.g. `locked-read-only`. */\n profile: string;\n /**\n * Trust a profile other than {@link PRODUCTION_PROFILE}, such as `debug`.\n * Its image is readable by whoever operates the node, so only for testing.\n */\n allowDebugProfile?: boolean;\n}\n\nexport function trustedMeasurementsFromReleases(\n releases: PublishedMrtds[],\n { profile, allowDebugProfile = false }: TrustedProfileOptions,\n): Required<Pick<QuoteVerifierOptions, 'allowedMeasurements' | 'allowedTcbStatuses'>> {\n if (releases.length === 0) {\n throw new Error('No release given, so no image would be trusted');\n }\n let statuses: string[] | undefined;\n const allowedMeasurements = releases.map((release, index) => {\n const name = release?.tag ?? `releases[${index}]`;\n if (release?.role !== undefined && release.role !== 'node') {\n throw new Error(`${name} lists the measurements of a ${release.role}, not of a node image`);\n }\n const image = release?.profiles?.[profile];\n if (!image) {\n const known = Object.keys(release?.profiles ?? {}).join(', ') || 'none';\n throw new Error(`${name} has no profile ${JSON.stringify(profile)} (it has: ${known})`);\n }\n if (profile !== PRODUCTION_PROFILE && !allowDebugProfile) {\n throw new Error(\n `${JSON.stringify(profile)} is not a production profile: its image is readable by whoever ` +\n `operates the node. Trust ${JSON.stringify(PRODUCTION_PROFILE)}, or pass allowDebugProfile to test`,\n );\n }\n const accepted = (image.allowed_tcb_statuses ?? ['uptodate']).map((status) => tcbStatus(status, name));\n statuses = statuses === undefined ? accepted : statuses.filter((status) => accepted.includes(status));\n return {\n mrtd: image.mrtd,\n rtmr0: image.rtmr0,\n rtmr1: image.rtmr1,\n rtmr2: image.rtmr2,\n rtmr3: image.rtmr3,\n };\n });\n if (!statuses || statuses.length === 0) {\n throw new Error('The releases given accept no TCB status in common');\n }\n return { allowedMeasurements, allowedTcbStatuses: statuses };\n}\n\nfunction tcbStatus(status: string, release: string): string {\n const known = TCB_STATUSES.find((candidate) => candidate.toLowerCase() === String(status).toLowerCase());\n if (!known) {\n throw new Error(`${release} accepts TCB status ${JSON.stringify(status)}, which this verifier does not know`);\n }\n return known;\n}\n", "/**\n * Trusting a TEE node's image by its signed release, fetched at run time from\n * anywhere, instead of shipping the release's `published-mrtds.json` with the\n * app.\n *\n * Each mero-tee node release publishes `published-mrtds.json` (the\n * measurements of its image) with a cosign keyless bundle, signed by the\n * mero-tee release workflow on GitHub Actions. {@link verifySignedNodeRelease}\n * checks that signature here, against the Sigstore trust root embedded in this\n * package, so the file can come from any source: the cloud's mirror\n * (`GET https://cloud.calimero.network/api/tee/node-releases/{version}`), a\n * mirror of your own, or a file bundled with the app. None of them is\n * trusted; a file whose signature does not verify is refused.\n *\n * What is trusted:\n *\n * - the signer: the node release workflow of `calimero-network/mero-tee` on\n * `master` ({@link NODE_RELEASE_SIGNER}), the identity core pins as\n * `NODE_RELEASE_IDENTITY`;\n * - the Sigstore public-good trust root: Fulcio's CAs and Rekor's key;\n * - the minimum release you pass, below which no release is accepted.\n *\n * What is not: the transport, the server that serves the release, and the\n * node's choice of release. A node can present any genuinely signed release\n * at or above the minimum, and no other; its quote must then match that\n * release's measurements exactly, so it cannot claim one release and run\n * another.\n */\n\nimport { verifyCosignBundle, type SignerIdentity } from './sigstore.js';\nimport {\n createQuoteVerifier,\n trustedMeasurementsFromReleases,\n type DcapVerify,\n type PublishedMrtds,\n type QuoteVerifier,\n type QuoteVerifierOptions,\n type TrustedProfileOptions,\n} from './verify.js';\n\n/** The workflow that signs every mero-tee node release, and the issuer of its identity. */\nexport const NODE_RELEASE_SIGNER: Readonly<SignerIdentity> = Object.freeze({\n identity:\n 'https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master',\n issuer: 'https://token.actions.githubusercontent.com',\n});\n\nconst MEASUREMENTS = ['mrtd', 'rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] as const;\n\n/**\n * The public mirror of signed node releases, used when no other source is\n * given. Only a transport: what it serves is verified, so it can fail to\n * answer but cannot make a release trusted.\n */\nexport const DEFAULT_RELEASE_MIRROR = 'https://cloud.calimero.network';\n\n/**\n * Where browsers get Intel's collateral for a quote: the cloud's mirror of the\n * PCCS paths `@phala/dcap-qvl` reads, open to any origin. Intel's PCS sends no\n * CORS header. The mirror only carries Intel-signed items.\n */\nexport const DEFAULT_COLLATERAL_MIRROR = `${DEFAULT_RELEASE_MIRROR}/api/tee/pcs`;\n\n/**\n * A node release as the servers hand it out, wrapped as `{\"data\": ...}`: the\n * release's `published-mrtds.json`, byte for byte, and its cosign bundle.\n * Unverified until {@link verifySignedNodeRelease} says otherwise.\n */\nexport interface SignedNodeRelease {\n /** The release, e.g. `2.3.87`. It must be the signed file's `tag`. */\n version: string;\n /** `published-mrtds.json`, exactly as signed. */\n publishedMrtds: string;\n /** `published-mrtds.json.bundle.json`, as JSON text. */\n bundle: string;\n}\n\nexport interface VerifySignedNodeReleaseOptions {\n /** Require the file's `tag` to be this release. */\n expectedVersion?: string;\n /** The certificate identity required. Defaults to {@link NODE_RELEASE_SIGNER}'s. */\n identity?: string;\n /** The OIDC issuer required. Defaults to {@link NODE_RELEASE_SIGNER}'s. */\n issuer?: string;\n /** The release's detached `published-mrtds.json.sig`, when you have it; it must be the bundle's. */\n signature?: string;\n}\n\n/**\n * Verify a node release's `published-mrtds.json` against its cosign bundle,\n * as `cosign verify-blob` would, and return the file parsed. Rejects, with the\n * reason, unless:\n *\n * - the signature over the exact bytes verifies with the bundle's certificate;\n * - that certificate chains to a Fulcio CA in the Sigstore trust root, and it\n * and the CA were valid when Rekor logged the signature;\n * - it names the node release workflow and GitHub Actions as its issuer;\n * - Rekor's signed entry timestamp verifies, for an entry that is this\n * signature over this file by this certificate;\n * - the file is a node release (`role: \"node\"`), and `expectedVersion`, when\n * given, is its `tag`.\n *\n * Nothing is read from the clock: the certificate is checked at the time Rekor\n * logged the signature, so a release that verifies once always does.\n */\nexport async function verifySignedNodeRelease(\n publishedMrtds: string | Uint8Array,\n bundle: string | object,\n options: VerifySignedNodeReleaseOptions = {},\n): Promise<PublishedMrtds> {\n const body = typeof publishedMrtds === 'string' ? new TextEncoder().encode(publishedMrtds) : publishedMrtds;\n await verifyCosignBundle(\n body,\n bundle,\n {\n identity: options.identity ?? NODE_RELEASE_SIGNER.identity,\n issuer: options.issuer ?? NODE_RELEASE_SIGNER.issuer,\n },\n options.signature,\n );\n\n let release: PublishedMrtds;\n try {\n release = JSON.parse(new TextDecoder().decode(body));\n } catch {\n throw new Error('The signed release is not JSON');\n }\n if (release?.role !== 'node') {\n throw new Error(`The signed release is a ${JSON.stringify(release?.role)} release, not a node one`);\n }\n // The workflow signs other files too, some with a `role` and `profiles` of\n // their own (`release-provenance.json`): the signature covers bytes, not a\n // file name, so check this is the measurements file.\n const profiles = Object.values(release.profiles ?? {});\n const measured = (image: unknown) =>\n MEASUREMENTS.every((register) => /^[0-9a-f]{96}$/i.test(String((image as Record<string, unknown>)?.[register])));\n if (typeof release.tag !== 'string' || profiles.length === 0 || !profiles.every(measured)) {\n throw new Error(\"The signed file is not a release's published-mrtds.json: it lists no measured profiles\");\n }\n if (options.expectedVersion !== undefined && release.tag !== options.expectedVersion) {\n throw new Error(`The signed release is ${release.tag}, not ${options.expectedVersion}`);\n }\n return release;\n}\n\n/**\n * Fetch a {@link SignedNodeRelease} from a server that wraps it as\n * `{\"data\": ...}`, such as the cloud's {@link cloudNodeReleaseUrl}. It is\n * only fetched: pass it to\n * {@link trustSignedRelease}, or {@link verifySignedNodeRelease}, before using it.\n */\nexport async function fetchNodeRelease(\n url: string,\n options: { fetch?: typeof fetch } = {},\n): Promise<SignedNodeRelease> {\n const response = await (options.fetch ?? fetch)(url, { headers: { accept: 'application/json' } });\n if (!response.ok) throw new Error(`Fetching the node release from ${url} failed: HTTP ${response.status}`);\n let release: Partial<SignedNodeRelease> | undefined;\n try {\n release = ((await response.json()) as { data?: Partial<SignedNodeRelease> })?.data;\n } catch {\n throw new Error(`${url} did not answer with JSON`);\n }\n if (\n typeof release?.version !== 'string' ||\n typeof release.publishedMrtds !== 'string' ||\n typeof release.bundle !== 'string'\n ) {\n throw new Error(`${url} did not answer with a signed node release`);\n }\n return { version: release.version, publishedMrtds: release.publishedMrtds, bundle: release.bundle };\n}\n\n/** Where mero-tee publishes its releases' assets, as core's `calimero-tee-release` fetches them. */\nexport const GITHUB_RELEASES = 'https://github.com/calimero-network/mero-tee/releases/download';\n\n/**\n * Node release `version` straight from its GitHub release (`mero-tee-v{version}`):\n * `published-mrtds.json` and its cosign bundle, the files core's Rust client\n * verifies. Only fetched: verify it with {@link trustSignedRelease}. GitHub's\n * downloads send no CORS headers, so in a browser use a mirror\n * ({@link cloudNodeReleaseUrl}) instead.\n */\nexport async function fetchGithubNodeRelease(\n version: string,\n options: { fetch?: typeof fetch; base?: string } = {},\n): Promise<SignedNodeRelease> {\n const tag = `mero-tee-v${releaseVersion(version, 'version')}`;\n const base = `${(options.base ?? GITHUB_RELEASES).replace(/\\/+$/, '')}/${tag}/published-mrtds.json`;\n const get = async (url: string): Promise<string> => {\n const response = await (options.fetch ?? fetch)(url);\n if (!response.ok) throw new Error(`Fetching ${url} failed: HTTP ${response.status}`);\n return response.text();\n };\n const [publishedMrtds, bundle] = await Promise.all([get(base), get(`${base}.bundle.json`)]);\n return { version, publishedMrtds, bundle };\n}\n\n/** Where the cloud at `cloudUrl` (e.g. `https://cloud.calimero.network`) mirrors node release `version`. */\nexport function cloudNodeReleaseUrl(cloudUrl: string, version: string): string {\n return `${cloudUrl.replace(/\\/+$/, '')}/api/tee/node-releases/${releaseVersion(version, 'version')}`;\n}\n\nexport interface TrustSignedReleaseOptions extends TrustedProfileOptions {\n /** The release, from any source; it is verified here. */\n release: SignedNodeRelease;\n /**\n * The oldest release accepted, e.g. `2.3.87`. Required: every release ever\n * signed stays validly signed, so without a floor a node could present an\n * old release, with a flaw since fixed, and a quote from that old image\n * would pass. Raise it when a release must no longer be trusted.\n */\n minReleaseVersion: string;\n /** Override the signer; defaults to {@link NODE_RELEASE_SIGNER}. */\n identity?: string;\n issuer?: string;\n}\n\n/**\n * The {@link QuoteVerifierOptions} that trust one profile of a signed node\n * release, from an untrusted source: its signature is verified, its signed\n * `tag` must be `release.version` and no older than `minReleaseVersion`, and\n * then it is read as {@link trustedMeasurementsFromReleases} reads a bundled\n * file.\n *\n * ```ts\n * const version = claimedRelease(attestationDoc, '2.3.109'); // the release the node names\n * const release = await fetchNodeRelease(cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, version));\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...(await trustSignedRelease({ release, profile: 'locked-read-only', minReleaseVersion: '2.3.87' })),\n * });\n * ```\n */\nexport async function trustSignedRelease(\n options: TrustSignedReleaseOptions,\n): Promise<Required<Pick<QuoteVerifierOptions, 'allowedMeasurements' | 'allowedTcbStatuses'>>> {\n const minimum = releaseVersion(options.minReleaseVersion, 'minReleaseVersion');\n const version = releaseVersion(options.release?.version, 'The release version');\n const published = await verifySignedNodeRelease(options.release.publishedMrtds, options.release.bundle, {\n expectedVersion: version,\n identity: options.identity,\n issuer: options.issuer,\n });\n if (compareReleaseVersions(version, minimum) < 0) {\n throw new Error(`Release ${version} is older than the minimum trusted, ${minimum}`);\n }\n return trustedMeasurementsFromReleases([published], {\n profile: options.profile,\n allowDebugProfile: options.allowDebugProfile,\n });\n}\n\nexport interface SignedReleaseVerifierOptions extends Omit<TrustSignedReleaseOptions, 'release'> {\n /** DCAP verification: `verify` from `@phala/dcap-qvl`. */\n dcapVerify: DcapVerify;\n /**\n * Where to get the node's release, asked again each time the node is\n * attested (a restarted node may run a newer one). Untrusted: it is\n * verified, and the quote must match it.\n */\n release: () => Promise<SignedNodeRelease>;\n /** As {@link QuoteVerifierOptions.fetchCollateral}. */\n fetchCollateral?: QuoteVerifierOptions['fetchCollateral'];\n /** The current time in milliseconds, for the quote's collateral; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/**\n * A {@link createQuoteVerifier} whose trusted image is the signed release the\n * node says it runs. On each attestation it gets the release, checks it with\n * {@link trustSignedRelease}, and verifies the quote against that release's\n * measurements only.\n *\n * The node's choice of release is the one thing taken from it, and it is\n * bounded: only a genuinely signed release at or above `minReleaseVersion`\n * passes, and the quote must then be of exactly that release's image. Pass it\n * as `NodePolicy.verifyQuote` to choose where the release comes from yourself.\n */\nexport function createSignedReleaseVerifier(options: SignedReleaseVerifierOptions): QuoteVerifier {\n releaseVersion(options.minReleaseVersion, 'minReleaseVersion');\n const verifier = async (args: Parameters<QuoteVerifier>[0]): Promise<boolean> => {\n const trusted = await trustSignedRelease({\n release: await options.release(),\n profile: options.profile,\n allowDebugProfile: options.allowDebugProfile,\n minReleaseVersion: options.minReleaseVersion,\n identity: options.identity,\n issuer: options.issuer,\n });\n return createQuoteVerifier({\n dcapVerify: options.dcapVerify,\n fetchCollateral: options.fetchCollateral,\n now: options.now,\n ...trusted,\n })(args);\n };\n return Object.assign(verifier, { includeCollateral: true as const });\n}\n\nconst RELEASE_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\n/** `value` if it is a release version (`2.3.87`, `2.3.88-rc.1`); throws otherwise. */\nexport function releaseVersion(value: unknown, what: string): string {\n const match = typeof value === 'string' ? RELEASE_VERSION.exec(value) : null;\n const pre = match?.[4];\n if (!match || (pre !== undefined && pre.split('.').some((id) => id === ''))) {\n throw new Error(`${what} is ${JSON.stringify(value)}, not a release version like 2.3.87`);\n }\n return value as string;\n}\n\n/**\n * Order two release versions as semver does, and as core's\n * `compare_release_versions`: numerically by `X.Y.Z`, a pre-release before its\n * release, build metadata ignored.\n */\nexport function compareReleaseVersions(a: string, b: string): number {\n const [aCore, aPre] = splitVersion(a);\n const [bCore, bPre] = splitVersion(b);\n for (let i = 0; i < 3; i += 1) {\n if (aCore[i] !== bCore[i]) return aCore[i] < bCore[i] ? -1 : 1;\n }\n if (aPre === undefined || bPre === undefined) return aPre === bPre ? 0 : aPre === undefined ? 1 : -1;\n const aIds = aPre.split('.');\n const bIds = bPre.split('.');\n for (let i = 0; i < Math.max(aIds.length, bIds.length); i += 1) {\n const [x, y] = [aIds[i], bIds[i]];\n if (x === undefined || y === undefined) return x === undefined ? -1 : 1;\n const [xNum, yNum] = [/^\\d+$/.test(x), /^\\d+$/.test(y)];\n const order =\n xNum && yNum ? Math.sign(Number(x) - Number(y)) : xNum !== yNum ? (xNum ? -1 : 1) : x < y ? -1 : x > y ? 1 : 0;\n if (order !== 0) return order;\n }\n return 0;\n}\n\nfunction splitVersion(version: string): [number[], string | undefined] {\n const match = RELEASE_VERSION.exec(version) as RegExpExecArray;\n return [[Number(match[1]), Number(match[2]), Number(match[3])], match[4]];\n}\n", "/**\n * The check every cloud client runs before it sends anything: the node's quote\n * must be genuine (or, in development, an explicitly allowed mock), from an\n * image this client trusts, and its report data must bind this nonce, the\n * expected app and the transport key the sealed channel will be opened to.\n *\n * Report data, as core's `calimero-cloud-client::attest` builds it:\n * `nonce(32) || SHA-256(\"calimero.tee-attest.transport-key.v1\" | app_hash | transport_key)`.\n *\n * A real quote is judged as the Rust client judges it (`attest::verify` with\n * `Measurements::Release`): the node names the mero-tee release it runs; that\n * release must be at least `minReleaseVersion`; its `published-mrtds.json` is\n * fetched and its Sigstore signature checked against the node release workflow;\n * the quote's signature chain and TCB status are checked against Intel's\n * collateral (fetched here: the node sends none, and cannot forge it); the TD\n * must not be a debug TD; and its registers must be the release's image for the\n * trusted profile, `locked-read-only` unless a debug profile is explicitly\n * allowed. Nothing here reads the environment: mock quotes pass only with\n * `allowMock`.\n */\n\nimport { fromHex, hex } from '../crypto/internal.js';\nimport {\n DEFAULT_COLLATERAL_MIRROR,\n DEFAULT_RELEASE_MIRROR,\n cloudNodeReleaseUrl,\n compareReleaseVersions,\n fetchGithubNodeRelease,\n fetchNodeRelease,\n releaseVersion,\n trustSignedRelease,\n type SignedNodeRelease,\n} from '../sealed/release.js';\nimport { transportKeyBinding, type VerifyTransportQuote } from '../sealed/sealed.js';\nimport { PRODUCTION_PROFILE, createQuoteVerifier, type DcapCollateral, type DcapVerify } from '../sealed/verify.js';\n\n/** The mock quote format development clusters use. */\nexport const MOCK_QUOTE_HEADER = 'MOCK_TDX_QUOTE_V1';\n\n/** How the signed release a node names is trusted (core's `Measurements::Release`). */\nexport interface NodeReleasePolicy {\n /**\n * The oldest mero-tee release trusted, e.g. `2.3.109`. Required: every\n * release ever signed stays validly signed, so without a floor a node could\n * name an old release with a flaw since fixed.\n */\n minReleaseVersion: string;\n /** The image profile trusted; defaults to `locked-read-only`. */\n profile?: string;\n /** Trust a debug profile. Its image is readable by the operator: testing only. */\n allowDebugProfile?: boolean;\n /**\n * Where the release's signed measurements come from: `'github'` (the release\n * assets, what core's Rust client reads; no CORS, so not in browsers), the\n * base URL of a mirror (default {@link DEFAULT_RELEASE_MIRROR}), or a function.\n * Untrusted either way: the Sigstore signature is checked here.\n */\n releaseSource?: 'github' | string | ((version: string) => Promise<SignedNodeRelease>);\n /** DCAP verification; defaults to `verify` from `@phala/dcap-qvl`, loaded on first use. */\n dcapVerify?: DcapVerify;\n /**\n * Intel's collateral for a quote. Defaults to `@phala/dcap-qvl`'s\n * `getCollateral` from `collateralSource`.\n */\n fetchCollateral?: (quote: Uint8Array) => Promise<DcapCollateral>;\n /**\n * Where the default `fetchCollateral` gets Intel's collateral: a PCCS base\n * URL (default {@link DEFAULT_COLLATERAL_MIRROR}, the cloud's mirror, which a\n * browser on any origin can read), or `'intel'` for Intel's PCS itself (no\n * CORS: not in browsers). Untrusted either way: every item is signed by\n * Intel and verified up to Intel's root CA, which `@phala/dcap-qvl` carries.\n */\n collateralSource?: 'intel' | string;\n /**\n * Refuse collateral whose TCB info Intel issued more than this many days\n * ago. Unset: only Intel's own `nextUpdate` (about 30 days out) bounds how\n * old it may be. A mirror cannot forge collateral, but it can replay an\n * older, still valid copy; this shortens that window. Too small a value\n * refuses every node if Intel is slow to re-sign.\n */\n maxCollateralAgeDays?: number;\n /** Override the release signer (defaults to the mero-tee node release workflow). */\n identity?: string;\n issuer?: string;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\nexport interface NodePolicy {\n /** Accept mock quotes. Development clusters only; never set from the environment. */\n allowMock?: boolean;\n /** Trust real quotes from the signed release the node runs. */\n release?: NodeReleasePolicy;\n /**\n * Verify a real quote yourself instead (e.g. `createQuoteVerifier` with\n * pinned measurements). Takes precedence over `release`.\n */\n verifyQuote?: VerifyTransportQuote;\n /** The app bundle hash (hex) the quote must bind, when talking to one app. */\n appHash?: string;\n}\n\nexport interface AttestationDoc {\n quote: string;\n transportKey: string;\n appHash: string;\n nonce: string;\n release: { version: string; profile: string };\n cluster: string;\n node: number;\n mock: boolean;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\ntype DcapModule = {\n verify?: unknown;\n getCollateral?: unknown;\n getCollateralFromPcs?: unknown;\n default?: { verify?: unknown; getCollateral?: unknown; getCollateralFromPcs?: unknown };\n};\nlet dcapModule: Promise<DcapModule> | undefined;\n\n/** A function out of `@phala/dcap-qvl`, whatever shape the bundler gave the (CommonJS) module. */\nasync function dcap<T>(name: 'verify' | 'getCollateral' | 'getCollateralFromPcs'): Promise<T> {\n dcapModule ??= import('@phala/dcap-qvl') as Promise<DcapModule>;\n const ns = await dcapModule;\n const f = typeof ns[name] === 'function' ? ns[name] : ns.default?.[name];\n if (typeof f !== 'function') throw new TypeError(`@phala/dcap-qvl loaded without ${name}`);\n return f as T;\n}\n\n/**\n * The release a node names, checked against the floor before anything is\n * fetched. Accepts `2.3.109` and the tag form `mero-tee-v2.3.109`.\n */\nexport function claimedRelease(doc: Pick<AttestationDoc, 'release'>, minReleaseVersion: string): string {\n const floor = releaseVersion(minReleaseVersion, 'minReleaseVersion');\n const raw = String(doc.release?.version ?? '').trim().replace(/^mero-tee-v/, '').replace(/^v/, '');\n const version = releaseVersion(raw, 'The release the node names');\n if (compareReleaseVersions(version, floor) < 0) {\n throw new Error(`mero-tee release ${version} is older than the minimum ${floor}`);\n }\n return version;\n}\n\nasync function releaseFor(version: string, policy: NodeReleasePolicy, fetchImpl: typeof fetch) {\n const source = policy.releaseSource;\n if (typeof source === 'function') return source(version);\n if (source === 'github') return fetchGithubNodeRelease(version, { fetch: fetchImpl });\n return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchImpl });\n}\n\n/** The collateral fetch a policy gets unless it brings its own: `@phala/dcap-qvl` against `collateralSource`. */\nfunction defaultCollateral(policy: NodeReleasePolicy): (quote: Uint8Array) => Promise<DcapCollateral> {\n const source = policy.collateralSource ?? DEFAULT_COLLATERAL_MIRROR;\n if (source === 'intel') {\n return async (quote) => (await dcap<(q: Uint8Array) => Promise<DcapCollateral>>('getCollateralFromPcs'))(quote);\n }\n return async (quote) =>\n (await dcap<(url: string, q: Uint8Array) => Promise<DcapCollateral>>('getCollateral'))(source, quote);\n}\n\n/** `fetch`, refusing collateral older than `policy.maxCollateralAgeDays` (by its TCB info's `issueDate`). */\nexport function freshCollateral(\n fetch: (quote: Uint8Array) => Promise<DcapCollateral>,\n policy: Pick<NodeReleasePolicy, 'maxCollateralAgeDays' | 'now'>,\n): (quote: Uint8Array) => Promise<DcapCollateral> {\n const maxDays = policy.maxCollateralAgeDays;\n if (maxDays === undefined) return fetch;\n return async (quote) => {\n const collateral = await fetch(quote);\n let issued: number;\n try {\n issued = Date.parse((JSON.parse(collateral.tcb_info) as { issueDate?: string }).issueDate ?? '');\n } catch {\n issued = Number.NaN;\n }\n if (!Number.isFinite(issued)) throw new Error(\"The quote's collateral names no TCB info issue date\");\n const ageDays = ((policy.now ?? Date.now)() - issued) / 86_400_000;\n if (ageDays > maxDays) {\n throw new Error(\n `The quote's collateral was issued ${Math.floor(ageDays)} days ago, more than the ${maxDays} this client accepts`,\n );\n }\n return collateral;\n };\n}\n\n/** Judge a real quote as core's `Measurements::Release` does. */\nasync function verifyRelease(\n doc: AttestationDoc,\n args: Parameters<VerifyTransportQuote>[0],\n policy: NodeReleasePolicy,\n fetchImpl: typeof fetch,\n): Promise<boolean> {\n // Refuse what no release could admit before reaching for the network.\n const version = claimedRelease(doc, policy.minReleaseVersion);\n const trusted = await trustSignedRelease({\n release: await releaseFor(version, policy, fetchImpl),\n profile: policy.profile ?? PRODUCTION_PROFILE,\n allowDebugProfile: policy.allowDebugProfile,\n minReleaseVersion: policy.minReleaseVersion,\n identity: policy.identity,\n issuer: policy.issuer,\n });\n const fetchCollateral = freshCollateral(policy.fetchCollateral ?? defaultCollateral(policy), policy);\n const verifier = createQuoteVerifier({\n dcapVerify: policy.dcapVerify ?? (await dcap<DcapVerify>('verify')),\n fetchCollateral,\n now: policy.now,\n ...trusted,\n });\n return verifier(args);\n}\n\n/** Fetch the node's attestation and return its transport key once it checks out. */\nexport async function fetchAttestedKey(\n baseUrl: string,\n policy: NodePolicy,\n fetchImpl: typeof fetch = (input, init) => fetch(input, init),\n): Promise<Uint8Array> {\n const nonce = hex(crypto.getRandomValues(new Uint8Array(32)));\n const url = new URL(`${baseUrl.replace(/\\/+$/, '')}/attestation`);\n url.searchParams.set('nonce', nonce);\n if (policy.appHash) url.searchParams.set('appHash', policy.appHash);\n const response = await fetchImpl(url.toString());\n if (!response.ok) throw new Error(`The node refused to attest: HTTP ${response.status}`);\n const doc = (await response.json()) as AttestationDoc;\n const transportKey = fromHex(doc.transportKey, 'transportKey', 32);\n const inner = policy.appHash ? fromHex(policy.appHash, 'appHash', 32) : new Uint8Array(32);\n const suffix = await transportKeyBinding(inner, transportKey);\n const quote = base64ToBytes(doc.quote);\n const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);\n if (equal(quote.slice(0, header.length), header)) {\n if (!policy.allowMock) {\n throw new Error('mock quote refused: this client only trusts real TEEs');\n }\n const report = quote.slice(header.length, header.length + 64);\n if (!equal(report.slice(0, 32), fromHex(nonce, 'nonce', 32)) || !equal(report.slice(32), suffix)) {\n throw new Error('the quote does not bind this transport key, app and nonce');\n }\n return transportKey;\n }\n const args = { quoteB64: doc.quote, nonce, reportDataSuffix: hex(suffix) };\n let ok: boolean;\n if (policy.verifyQuote) {\n ok = await policy.verifyQuote(args);\n } else if (policy.release) {\n ok = await verifyRelease(doc, args, policy.release, fetchImpl);\n } else {\n throw new Error('real quote refused: this client trusts no TD image (set policy.release)');\n }\n if (!ok) throw new Error('The attestation did not verify, so its transport key is not trusted');\n return transportKey;\n}\n", "/**\n * The Calimero Cloud node directory: which nodes of a cluster take traffic now,\n * and in what order this client tries them.\n *\n * `GET {directory}/{cluster}` (no auth) answers\n * `{ cluster, nodes: [{ id, url, zone, weight }], refreshAfterSeconds }`. The\n * directory is not trusted for security: it only picks which nodes to try.\n * Every node is attested under the caller's own policy before anything is sent\n * to it, so a bad list can only make connecting fail.\n */\n\n/** The Calimero Cloud control plane's public node directory. */\nexport const DEFAULT_DIRECTORY = 'https://manager.cloud.calimero.network/api/v2/directory';\n\n/** How long a listing stands when the directory does not say. */\nconst DEFAULT_REFRESH_SECONDS = 60;\n\n/** Why {@link DirectoryError} was thrown. */\nexport type DirectoryFailure = 'unreachable' | 'not-found' | 'bad-response' | 'empty';\n\n/**\n * The directory could not name a node to try: it could not be reached or\n * answered an error (`unreachable`), does not know the cluster (`not-found`,\n * a 404), answered something that is not a listing (`bad-response`), or listed\n * no usable node (`empty`).\n */\nexport class DirectoryError extends Error {\n constructor(\n readonly cluster: string,\n readonly reason: DirectoryFailure,\n message: string,\n readonly status?: number,\n readonly cause?: unknown,\n ) {\n super(`directory for cluster ${cluster}: ${message}`);\n this.name = 'DirectoryError';\n }\n}\n\n/** One usable node of a listing. */\nexport interface DirectoryNode {\n url: string;\n zone?: string;\n weight: number;\n}\n\nexport interface DirectoryListing {\n nodes: DirectoryNode[];\n refreshAfterSeconds: number;\n}\n\n/** The URL of `cluster`'s listing in `directory`. */\nexport function directoryUrl(directory: string, cluster: string): string {\n return `${directory.replace(/\\/+$/, '')}/${encodeURIComponent(cluster)}`;\n}\n\n/**\n * Read `cluster`'s listing, keeping only the entries with an http(s) URL and a\n * positive integer weight (the first of a repeated URL).\n */\nexport async function readDirectory(directory: string, cluster: string, fetcher: typeof fetch): Promise<DirectoryListing> {\n let response: Response;\n try {\n response = await fetcher(directoryUrl(directory, cluster), { method: 'GET', headers: { accept: 'application/json' } });\n } catch (error) {\n throw new DirectoryError(cluster, 'unreachable', `could not be reached: ${String(error)}`, undefined, error);\n }\n if (response.status === 404) throw new DirectoryError(cluster, 'not-found', 'unknown cluster', 404);\n if (!response.ok) throw new DirectoryError(cluster, 'unreachable', `answered ${response.status}`, response.status);\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new DirectoryError(cluster, 'bad-response', 'answered something other than JSON', response.status, error);\n }\n const listing = body as { nodes?: unknown; refreshAfterSeconds?: unknown } | null;\n if (!listing || typeof listing !== 'object' || !Array.isArray(listing.nodes)) {\n throw new DirectoryError(cluster, 'bad-response', 'answered no node list', response.status);\n }\n const nodes: DirectoryNode[] = [];\n const seen = new Set<string>();\n for (const entry of listing.nodes) {\n const node = usable(entry);\n if (node && !seen.has(node.url)) {\n seen.add(node.url);\n nodes.push(node);\n }\n }\n if (nodes.length === 0) throw new DirectoryError(cluster, 'empty', 'lists no usable node', response.status);\n const after = listing.refreshAfterSeconds;\n const refreshAfterSeconds =\n typeof after === 'number' && Number.isFinite(after) && after >= 1 ? after : DEFAULT_REFRESH_SECONDS;\n return { nodes, refreshAfterSeconds };\n}\n\nfunction usable(entry: unknown): DirectoryNode | undefined {\n if (!entry || typeof entry !== 'object') return undefined;\n const { url, zone, weight } = entry as Record<string, unknown>;\n if (typeof url !== 'string' || typeof weight !== 'number' || !Number.isInteger(weight) || weight < 1) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return undefined;\n return { url: url.replace(/\\/+$/, ''), zone: typeof zone === 'string' ? zone : undefined, weight };\n}\n\n/**\n * The order to try `nodes` in: those in `zone` first (when given), each group\n * in weighted-random order, a node's weight its relative chance to come next.\n * `random` answers in [0, 1), as `Math.random` does.\n */\nexport function orderNodes(nodes: DirectoryNode[], zone: string | undefined, random: () => number): string[] {\n const near = zone === undefined ? [] : nodes.filter((node) => node.zone === zone);\n const far = zone === undefined ? nodes : nodes.filter((node) => node.zone !== zone);\n return [...weightedOrder(near, random), ...weightedOrder(far, random)];\n}\n\nfunction weightedOrder(nodes: DirectoryNode[], random: () => number): string[] {\n const left = [...nodes];\n const order: string[] = [];\n while (left.length > 0) {\n let roll = random() * left.reduce((sum, node) => sum + node.weight, 0);\n let pick = 0;\n while (pick < left.length - 1 && roll >= left[pick].weight) roll -= left[pick++].weight;\n order.push(left.splice(pick, 1)[0].url);\n }\n return order;\n}\n", "/**\n * What the cloud node's refusals mean to a caller (spec D64, D70).\n *\n * The node answers an error as `{ error: CODE, message, details }` with an HTTP\n * status. {@link errorFrom} is the one place the client turns that into an\n * error a caller can switch on; every call, view and event stream goes through\n * it. It matches the status and the code together, never the status alone: the\n * node sends other 409s (`CONFLICT`, `NOT_INSTALLED`) that are not an\n * idempotency mismatch, and other 413s (`TOO_LARGE` from the sealed transport)\n * that are not oversized call arguments. Anything it does not recognise stays a\n * plain {@link CalimeroError} carrying both.\n *\n * Every typed error extends {@link CalimeroError}, so `instanceof CalimeroError`\n * and its `status` and `code` (the node's code) keep working for all of them.\n */\n\nexport class CalimeroError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n readonly details: Record<string, unknown> = {},\n ) {\n super(`${status} ${code}: ${message}`);\n this.name = 'CalimeroError';\n }\n}\n\n/**\n * `401 UNAUTHENTICATED` that refreshing could not answer: sign in (again) and\n * repeat the request.\n *\n * A session token is signed by the node that issued it, and other nodes take\n * it only while they can vouch for that node's signing key: a `401` often\n * means only that the issuer was replaced or cannot be reached, not that the\n * user signed out. The client answers that itself when it holds a refresh\n * token: it refreshes once (any node takes the refresh) and repeats the\n * request. This error reaches a caller when there is no refresh token (an API\n * key, say), or the refresh was refused.\n */\nexport class LoginRequired extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(401, 'UNAUTHENTICATED', message, details);\n this.name = 'LoginRequired';\n }\n}\n\n/**\n * `401 PASSKEY_UNKNOWN_HERE`: a sign-in (or a confirmation) with a passkey no\n * account of this cluster has. Accounts and passkeys are each cluster's own,\n * while clusters may share one WebAuthn rp-id (every Calimero Cloud cluster\n * uses `calimero.network`), so the browser offers a passkey made on another\n * cluster here too; a passkey removed from its account answers the same.\n *\n * It is not a {@link LoginRequired}: the client does not refresh for it, and\n * signing in again with the same passkey fails the same way. Offer to sign up\n * on this cluster, or point the person to the app link for the cluster their\n * account is on; the passkey's name in their password manager names that\n * cluster (`alice \u00B7 eu-shared-1`). The node does not say which cluster or\n * account the passkey belongs to: it only knows its own.\n */\nexport class PasskeyUnknownHere extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(\n 401,\n 'PASSKEY_UNKNOWN_HERE',\n message || 'this passkey belongs to another Calimero cluster or was removed from this one',\n details,\n );\n this.name = 'PasskeyUnknownHere';\n }\n}\n\n/**\n * `421 WRONG_NODE`: this node runs a mero-tee release the account's owners have\n * not approved, so it neither issues nor takes the account's sessions. Use\n * another node of the cluster; refreshing here would not help.\n *\n * The client moves to the next node it was given (`nodes`) and repeats the\n * request once by itself (a refresh: once per node). This error reaches a\n * caller when it knows no other node, when the next one refused too (for a\n * refresh, every node), or after a sign-in (which needs the passkey again:\n * repeat it, and it goes to the next node).\n */\nexport class WrongNode extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(421, 'WRONG_NODE', message, details);\n this.name = 'WrongNode';\n }\n}\n\n/**\n * `404 NOT_FOUND`: what the request names does not exist for this caller. For\n * an app this does not say whether it exists: an account the app does not\n * admit gets the same answer as a missing app.\n */\nexport class NotFound extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(404, 'NOT_FOUND', message, details);\n this.name = 'NotFound';\n }\n}\n\n/**\n * `412 CONFIRM_REQUIRED`: the call needs the account holder's passkey over a\n * challenge in `details`. The `*Confirmed` methods answer it themselves; it\n * reaches a caller only from a method that was given no passkey.\n */\nexport class ConfirmRequired extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(412, 'CONFIRM_REQUIRED', message, details);\n this.name = 'ConfirmRequired';\n }\n}\n\n/** The user declined the passkey prompt a confirmation asked for. Nothing was sent. */\nexport class ConfirmCancelled extends Error {\n constructor(readonly cause?: unknown) {\n super('the passkey confirmation was cancelled');\n this.name = 'ConfirmCancelled';\n }\n}\n\n/**\n * The browser or a password manager refused to show the passkey prompt a\n * confirmation asked for: the page was not focused (an extension's popup\n * still held focus), or another prompt was still open. The user did not\n * decline; nothing was sent. Ask them to try again from a click, e.g. \"Your\n * password manager or browser blocked the second prompt. Click to try again.\"\n * `cause` is the browser's error.\n */\nexport class ConfirmPromptBlocked extends Error {\n constructor(readonly cause?: unknown) {\n super('the passkey prompt was blocked by the browser or a password manager');\n this.name = 'ConfirmPromptBlocked';\n }\n}\n\n/** `413 ARGS_TOO_LARGE`: the call's arguments are over the node's limit; it did not run. */\nexport class ArgsTooLarge extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(413, 'ARGS_TOO_LARGE', message, details);\n this.name = 'ArgsTooLarge';\n }\n}\n\n/** `409 IDEMPOTENCY_MISMATCH`: the idempotency key was used before with different arguments. */\nexport class IdempotencyMismatch extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'IDEMPOTENCY_MISMATCH', message, details);\n this.name = 'IdempotencyMismatch';\n }\n}\n\n/**\n * `409 RELEASE_DEADLINE`: a mero-tee release's deadline has passed and the\n * set that governs this work (the app's publisher's, or its owner's) has not\n * approved it or a newer one, so new work (creating an app, installing a\n * release, upgrading an app) is refused. Apps already running keep running.\n * Approving `release` lifts it at once.\n */\nexport class ReleaseDeadlineError extends CalimeroError {\n /** The release to approve. */\n readonly release: string;\n /** Its deadline, RFC 3339 (`''` when the node did not say). */\n readonly after: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RELEASE_DEADLINE', message, details);\n this.name = 'ReleaseDeadlineError';\n this.release = typeof details.release === 'string' ? details.release : '';\n this.after = typeof details.after === 'string' ? details.after : '';\n }\n}\n\n/**\n * `409 RUNTIME_TOO_OLD`: a node that would run the app (one of its replicas\n * for an upgrade, a node it would be placed on or moved to) runs an older\n * runtime than the release's signed `minRuntimeVersion`. Nothing ran. The\n * app's report names the newest release it can reach (`latestReachable`).\n */\nexport class RuntimeTooOld extends CalimeroError {\n /** The runtime the release needs. */\n readonly minRuntimeVersion: string;\n /** Each node that falls short, and what it runs (`{ before }`: older than that). */\n readonly nodes: { node: number; runtime: string | { before: string } | null }[];\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RUNTIME_TOO_OLD', message, details);\n this.name = 'RuntimeTooOld';\n this.minRuntimeVersion = typeof details.minRuntimeVersion === 'string' ? details.minRuntimeVersion : '';\n this.nodes = Array.isArray(details.nodes) ? (details.nodes as RuntimeTooOld['nodes']) : [];\n }\n}\n\n/**\n * `409 CONSENT_STALE`: what a consent page showed (the app's bundle, the\n * target release, the release's measurements) changed before the person\n * approved. Nothing was approved; ask for a new consent request so they see\n * the new facts.\n */\nexport class ConsentStale extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'CONSENT_STALE', message, details);\n this.name = 'ConsentStale';\n }\n}\n\n/**\n * `403 ORIGIN_NOT_REGISTERED`: a sign-up or sign-in started on a web origin\n * the cluster does not know: neither the cluster's own nor one a package's\n * manager registered (`packageOrigins.add`). `origin` is the page's origin\n * and `package` the package it was expected to be registered for, when known.\n */\nexport class OriginNotRegistered extends CalimeroError {\n readonly origin: string;\n readonly package: string;\n /** What the node said, if anything. */\n readonly nodeMessage: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n const origin = typeof details.origin === 'string' ? details.origin : '';\n const pkg = typeof details.package === 'string' ? details.package : '';\n const site = origin ? `this site (${origin})` : 'this site';\n super(403, 'ORIGIN_NOT_REGISTERED', `${site} is not registered for ${pkg || 'any package'}${message ? ` (${message})` : ''}`, details);\n this.name = 'OriginNotRegistered';\n this.origin = origin;\n this.package = pkg;\n this.nodeMessage = message;\n }\n}\n\n/**\n * `400 BAD_ORIGIN` or `400 BAD_RP_ID`: the node does not accept the origin a\n * package's manager tried to register (it must be a bare web origin,\n * `scheme://host[:port]`), or the relying-party id given for it (which must\n * fit the origin's host). `code` says which. A served origin (`served: true`)\n * must also be `https://host` with no port, and not a name under the\n * cluster's apps domain or its rp-id.\n */\nexport class BadOrigin extends CalimeroError {\n constructor(code: 'BAD_ORIGIN' | 'BAD_RP_ID', message: string, details: Record<string, unknown> = {}) {\n super(400, code, message, details);\n this.name = 'BadOrigin';\n }\n}\n\n/**\n * `409 ORIGIN_TAKEN`: the origin is registered already (for another package,\n * or for this one with the other `served`: remove it first), or it is one of\n * the cluster's own (a node's API host, a cluster origin, a frontend it\n * serves).\n */\nexport class OriginTaken extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'ORIGIN_TAKEN', message, details);\n this.name = 'OriginTaken';\n }\n}\n\n/**\n * `400 NOT_SERVING`: a served origin (a custom domain, `served: true`) was\n * asked of a cluster that serves no frontends (merod without\n * `--apps-domain`). Register the origin unserved, or use a cluster that\n * serves them.\n */\nexport class NotServing extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(400, 'NOT_SERVING', message, details);\n this.name = 'NotServing';\n }\n}\n\n/**\n * `409 CLUSTER_NOT_UPGRADED`: the change needs every node of the cluster\n * (replicas, voters and learners) on the node's release or later, and one\n * is not yet; for instance adding a served origin. Retry once the cluster is\n * upgraded.\n */\nexport class ClusterNotUpgraded extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'CLUSTER_NOT_UPGRADED', message, details);\n this.name = 'ClusterNotUpgraded';\n }\n}\n\n/**\n * `409 FEATURE_NOT_ACTIVE`: the command (or a field of it) needs a cluster\n * version not every node of the cluster supports yet, during a rollout from\n * an older release; nothing was done. `feature` names it, `needs` is the core\n * release it needs and `active` the cluster's version now (`''` when not every\n * node said which it supports). It works once the old nodes leave the cluster:\n * retry then, or tell the user the feature is not available yet.\n */\nexport class FeatureNotActive extends CalimeroError {\n readonly feature: string;\n readonly needs: string;\n readonly active: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'FEATURE_NOT_ACTIVE', message, details);\n this.name = 'FeatureNotActive';\n this.feature = typeof details.feature === 'string' ? details.feature : '';\n this.needs = typeof details.needs === 'string' ? details.needs : '';\n this.active = typeof details.active === 'string' ? details.active : '';\n }\n}\n\n/**\n * `409 RECOVERY_NOT_READY`: a recovery (an account's or an organization's)\n * may finish only once its 72-hour delay has passed. `readyAt` is when it may\n * (Unix seconds), when the node said.\n */\nexport class RecoveryNotReady extends CalimeroError {\n readonly readyAt: number | undefined;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RECOVERY_NOT_READY', message, details);\n this.name = 'RecoveryNotReady';\n this.readyAt = typeof details.readyAt === 'number' ? details.readyAt : undefined;\n }\n}\n\n/**\n * The recovery code is not one the cluster holds: mistyped, replaced by a\n * newer one, or spent by a recovery that started (whether it finished or was\n * cancelled). The node answers it `401`; a recovery is signed out, so it is\n * this error, not {@link LoginRequired}.\n */\nexport class WrongRecoveryCode extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(401, 'UNAUTHENTICATED', message || 'unknown or used recovery code', details);\n this.name = 'WrongRecoveryCode';\n }\n}\n\n/** Why a sign-up was refused ({@link SignUpRefused.reason}), read from what the node said. */\nexport type SignUpRefusal = 'invite-only' | 'closed' | 'unknown-invite' | 'expired-invite' | 'org-gone' | 'other';\n\n/**\n * `403 SIGN_UP_REFUSED`: the cluster's sign-up policy does not take this\n * sign-up (core `SystemState::admits`), answered by `register/begin` before a\n * passkey is made and by `register/finish` before its challenge is spent.\n * `reason` says why, so a page can say \"invite only\" or \"this invite has\n * expired\" instead of the node's sentence:\n *\n * - `invite-only`: the cluster takes new accounts with an invite only.\n * - `closed`: only a cluster sign-up invite (the operator's or the owner's) admits.\n * - `unknown-invite`: the invite is not one the cluster knows (mistyped, revoked,\n * or used up: a spent invite is gone).\n * - `expired-invite`: past its expiry, or no use left.\n * - `org-gone`: the organization the invite was for was deleted.\n */\nexport class SignUpRefused extends CalimeroError {\n readonly reason: SignUpRefusal;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(403, 'SIGN_UP_REFUSED', message, details);\n this.name = 'SignUpRefused';\n this.reason = signUpRefusal(message);\n }\n}\n\nfunction signUpRefusal(message: string): SignUpRefusal {\n if (/invite only/.test(message)) return 'invite-only';\n if (/pre-authorized|sign-up invite/.test(message)) return 'closed';\n if (/unknown invite/.test(message)) return 'unknown-invite';\n if (/invite has expired/.test(message)) return 'expired-invite';\n if (/organization is gone/.test(message)) return 'org-gone';\n return 'other';\n}\n\n/**\n * `429 QUOTA_EXCEEDED`: the caller holds as many of something (origins,\n * served origins per package or per cluster, blobs, ...) as it may.\n */\nexport class QuotaExceeded extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(429, 'QUOTA_EXCEEDED', message, details);\n this.name = 'QuotaExceeded';\n }\n}\n\n/**\n * `422 APP_ERROR`: the app refused the call. `appCode` is the app's declared\n * error (`Taken`, `Forbidden`, ...) and `fields` its named fields. The call was\n * logged, so its idempotency key is spent.\n */\nexport class AppError extends CalimeroError {\n readonly appCode: string;\n readonly fields: Record<string, unknown>;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(422, 'APP_ERROR', message, details);\n this.name = 'AppError';\n const { appCode, fields } = appErrorOf(details);\n this.appCode = appCode;\n this.fields = fields;\n }\n}\n\n/** `422 TRAP`: the run trapped (`OutOfFuel`, `OutOfMemory`, ...). The call was logged. */\nexport class TrapError extends CalimeroError {\n readonly kind: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(422, 'TRAP', message, details);\n this.name = 'TrapError';\n this.kind = typeof details.kind === 'string' ? details.kind : '';\n }\n}\n\n/**\n * Whether a call the node answered 503 may have committed: `false` when the\n * node says it did not (`TIMEOUT`, `MIGRATING`), `\"unknown\"` otherwise (a call\n * that raced a leader change). Never a plain boolean: `\"unknown\"` must not read\n * as \"no\".\n */\nexport type Committed = false | 'unknown';\n\n/**\n * Any `503`, or a connection that failed, after the client's retries with the\n * same idempotency key ran out. `reason` is the node's code in lower case\n * (`timeout`, `migrating`, `unavailable`, ...), or `network` when the node gave\n * no answer at all (code `NETWORK`, `cause` the `fetch` failure); such a call\n * may have committed, so its `committed` is `'unknown'`.\n */\nexport class UnavailableError extends CalimeroError {\n readonly reason: string;\n readonly committed: Committed;\n /** Seconds the node asked to wait, when it said. */\n readonly retryAfter: number | undefined;\n /** What failed, when the node gave no answer. */\n readonly cause: unknown;\n\n constructor(code: string, message: string, details: Record<string, unknown> = {}, retryAfter?: number, cause?: unknown) {\n super(503, code, message, details);\n this.name = 'UnavailableError';\n this.reason = code.toLowerCase();\n this.committed = code === 'TIMEOUT' || code === 'MIGRATING' ? false : 'unknown';\n this.retryAfter = retryAfter;\n this.cause = cause;\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\n/**\n * The app's code and named fields. The node puts them in `details` as\n * `{ code, fields }`; an older node nests the app's error under `details.error`.\n * Positional payloads (`\"0\"`, `\"1\"`) are never read as fields (D63).\n */\nfunction appErrorOf(details: Record<string, unknown>): { appCode: string; fields: Record<string, unknown> } {\n const source = typeof details.code === 'string' ? details : record(details.error);\n const appCode = typeof source.code === 'string' ? source.code : '';\n return { appCode, fields: { ...record(source.fields) } };\n}\n\nfunction retryAfterOf(details: Record<string, unknown>, header?: string | null): number | undefined {\n for (const candidate of [details.retryAfter, header == null ? undefined : Number(header)]) {\n if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) return candidate;\n }\n return undefined;\n}\n\n/**\n * The error for a refusal the node answered with `status` and `body` (its JSON\n * `{ error, message, details }`, or whatever it sent). The one place statuses\n * become typed errors.\n */\nexport function errorFrom(status: number, body: unknown, retryAfterHeader?: string | null): CalimeroError {\n const value = record(body);\n const code = typeof value.error === 'string' ? value.error : 'ERROR';\n const message = typeof value.message === 'string' ? value.message : '';\n const details = record(value.details);\n if (status === 503) return new UnavailableError(code, message, details, retryAfterOf(details, retryAfterHeader));\n switch (`${status} ${code}`) {\n case '401 UNAUTHENTICATED':\n return new LoginRequired(message, details);\n case '401 PASSKEY_UNKNOWN_HERE':\n return new PasskeyUnknownHere(message, details);\n case '421 WRONG_NODE':\n return new WrongNode(message, details);\n case '404 NOT_FOUND':\n return new NotFound(message, details);\n case '409 IDEMPOTENCY_MISMATCH':\n return new IdempotencyMismatch(message, details);\n case '409 RELEASE_DEADLINE':\n return new ReleaseDeadlineError(message, details);\n case '409 RUNTIME_TOO_OLD':\n return new RuntimeTooOld(message, details);\n case '409 CONSENT_STALE':\n return new ConsentStale(message, details);\n case '403 ORIGIN_NOT_REGISTERED':\n return new OriginNotRegistered(message, details);\n case '400 BAD_ORIGIN':\n case '400 BAD_RP_ID':\n return new BadOrigin(code as 'BAD_ORIGIN' | 'BAD_RP_ID', message, details);\n case '409 ORIGIN_TAKEN':\n return new OriginTaken(message, details);\n case '400 NOT_SERVING':\n return new NotServing(message, details);\n case '409 CLUSTER_NOT_UPGRADED':\n return new ClusterNotUpgraded(message, details);\n case '409 FEATURE_NOT_ACTIVE':\n return new FeatureNotActive(message, details);\n case '429 QUOTA_EXCEEDED':\n return new QuotaExceeded(message, details);\n case '409 RECOVERY_NOT_READY':\n return new RecoveryNotReady(message, details);\n case '403 SIGN_UP_REFUSED':\n return new SignUpRefused(message, details);\n case '412 CONFIRM_REQUIRED':\n return new ConfirmRequired(message, details);\n case '413 ARGS_TOO_LARGE':\n return new ArgsTooLarge(message, details);\n case '422 APP_ERROR':\n return new AppError(message, details);\n case '422 TRAP':\n return new TrapError(message, details);\n default:\n return new CalimeroError(status, code, message, details);\n }\n}\n", "/**\n * Passkeys: the browser's WebAuthn API, or anything that answers like it.\n *\n * Every binary field crosses the wire as base64url, matching\n * `calimero-identity`'s `Registration` and `Assertion`.\n */\n\nimport type { components } from '../generated/api.js';\nimport { ConfirmCancelled, ConfirmPromptBlocked } from './errors.js';\n\nexport interface RegistrationJSON {\n attestationObject: string;\n clientDataJson: string;\n}\n\nexport interface AssertionJSON {\n credentialId: string;\n authenticatorData: string;\n clientDataJson: string;\n signature: string;\n}\n\n/** How strongly an assertion must verify the user (WebAuthn's `UserVerificationRequirement`). */\nexport type PasskeyUserVerification = \"required\" | \"preferred\" | \"discouraged\";\n\n/** What a confirmation asks of the passkey beyond the challenge. */\nexport interface PasskeyGetOptions {\n /**\n * `\"required\"` for a step-up confirmation (`412 CONFIRM_REQUIRED`): the\n * node accepts only an assertion with the user-verified flag (PIN or\n * biometric). `\"preferred\"` for the sign-up's confirmation, which the node\n * takes with the user present. Absent for a plain sign-in, where\n * `\"preferred\"` is enough.\n */\n userVerification?: PasskeyUserVerification;\n /**\n * Closes the open prompt when it aborts (a Cancel button, a page leaving).\n * The browser provider then rejects as a dismissed prompt does\n * (`NotAllowedError`), so the caller treats it as a cancel.\n */\n signal?: AbortSignal;\n}\n\n/** What a passkey creation takes beyond the node's options. */\nexport interface PasskeyCreateOptions {\n /** As {@link PasskeyGetOptions.signal}: aborting closes the prompt, rejecting as a cancel (`NotAllowedError`). */\n signal?: AbortSignal;\n}\n\n/** Something that holds a passkey. */\nexport interface PasskeyProvider {\n /**\n * Answer `navigator.credentials.create` for the node's options.\n * `createOptions.signal` closes the prompt when it aborts; a provider with\n * no prompt to close may ignore it.\n */\n create(options: Record<string, unknown>, createOptions?: PasskeyCreateOptions): Promise<RegistrationJSON>;\n /**\n * Sign `challenge` (an assertion), optionally limited to\n * `allowCredentials`. `options.userVerification` is `\"required\"` when the\n * client answers a step-up confirmation (`\"preferred\"` for the sign-up's);\n * a provider that always verifies the user may ignore it.\n * `options.signal` closes the prompt when it aborts.\n */\n get(\n challenge: Uint8Array,\n rpId: string,\n allowCredentials?: string[],\n options?: PasskeyGetOptions,\n ): Promise<AssertionJSON>;\n}\n\nexport function b64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport function fromB64url(s: string): Uint8Array {\n const pad =\n s.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"===\".slice((s.length + 3) % 4);\n const bin = atob(pad);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nconst buf = (b: Uint8Array): ArrayBuffer =>\n b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;\n\n/** A dismissed prompt, named as WebAuthn names one (`NotAllowedError`), so a confirmation reads it as declined. */\nfunction cancelled(message: string): Error {\n const error = new Error(message);\n error.name = \"NotAllowedError\";\n return error;\n}\n\n/**\n * Ask the browser's own WebAuthn API (`CredentialsContainer.prototype[method]`),\n * not whatever a password manager extension put on `navigator.credentials`.\n * Calimero's passkeys live in the platform's authenticators: iCloud Keychain\n * and Touch ID, Google Password Manager, Windows Hello, a phone over a QR code,\n * a security key. Extensions sit in between and broke sign-up: LastPass, after\n * creating a passkey, opened a hidden request of its own on the next prompt,\n * so the browser refused it (\"A request is already pending\") and every try\n * left a passkey with no account. A passkey kept only in an extension's vault\n * is therefore not offered here. Where the browser has no\n * `CredentialsContainer` (tests, older runtimes), `navigator.credentials` is used.\n */\ntype Ask = (\n options: CredentialCreationOptions | CredentialRequestOptions,\n) => Promise<Credential | null>;\n\nasync function ask(\n method: \"create\" | \"get\",\n options: CredentialCreationOptions | CredentialRequestOptions,\n signal: AbortSignal | undefined,\n what: string,\n): Promise<Credential | null> {\n const container = navigator.credentials;\n const own = (\n globalThis as unknown as {\n CredentialsContainer?: { prototype: Record<string, unknown> };\n }\n ).CredentialsContainer?.prototype?.[method] as Ask | undefined;\n const call = own ?? (container[method] as Ask);\n try {\n return await call.call(container, signal ? { ...options, signal } : options);\n } catch (error) {\n // An aborted `signal` rejects with its reason (an `AbortError` unless the\n // caller gave another): the prompt was closed on purpose, so it reads as\n // a dismissed one.\n if (signal?.aborted || (error as { name?: unknown } | null)?.name === \"AbortError\") {\n throw Object.assign(cancelled(`${what} was cancelled`), { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * The node's algorithms with ES256 alone when it is among them. Some password\n * managers make an Ed25519 (EdDSA, -8) passkey when the site offers it and\n * then fail to sign with it: the account's create succeeds and its very next\n * prompt fails. LastPass did this on Calimero's sign-up (create, then approve\n * at once), refusing the approval as \"A request is already pending\"; Proton\n * Pass answers UnsupportedAlgorithm. ES256 is what every authenticator makes,\n * and the node checks it as it checks EdDSA, so a passkey already made with\n * EdDSA still signs in.\n */\nexport function es256First(\n params: Array<{ type: \"public-key\"; alg: number }>,\n): Array<{ type: \"public-key\"; alg: number }> {\n const es256 = params.filter((p) => p.alg === -7);\n return es256.length ? es256 : params;\n}\n\n/** The platform authenticator (Touch ID, Face ID, Windows Hello, a security key, a synced passkey). */\nexport function browserPasskey(): PasskeyProvider {\n return {\n async create(options, createOptions) {\n const o = options as {\n challenge: string;\n rp: { id: string; name: string };\n user: { id: string; name: string; displayName: string };\n pubKeyCredParams: Array<{ type: \"public-key\"; alg: number }>;\n excludeCredentials?: Array<{ type: \"public-key\"; id: string }>;\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n timeout?: number;\n };\n const cred = (await ask(\"create\", {\n publicKey: {\n challenge: buf(fromB64url(o.challenge)),\n rp: o.rp,\n user: { ...o.user, id: buf(fromB64url(o.user.id)) },\n pubKeyCredParams: es256First(o.pubKeyCredParams),\n excludeCredentials: (o.excludeCredentials ?? []).map((c) => ({\n type: c.type,\n id: buf(fromB64url(c.id)),\n })),\n authenticatorSelection: o.authenticatorSelection,\n attestation: \"none\",\n timeout: o.timeout,\n },\n }, createOptions?.signal, \"passkey creation\")) as PublicKeyCredential | null;\n if (!cred) throw cancelled(\"passkey creation was cancelled\");\n const r = cred.response as AuthenticatorAttestationResponse;\n return {\n attestationObject: b64url(new Uint8Array(r.attestationObject)),\n clientDataJson: b64url(new Uint8Array(r.clientDataJSON)),\n };\n },\n async get(challenge, rpId, allowCredentials, options) {\n const cred = (await ask(\"get\", {\n publicKey: {\n challenge: buf(challenge),\n rpId,\n userVerification: options?.userVerification ?? \"preferred\",\n allowCredentials: (allowCredentials ?? []).map((id) => ({\n type: \"public-key\",\n id: buf(fromB64url(id)),\n })),\n },\n }, options?.signal, \"passkey sign-in\")) as PublicKeyCredential | null;\n if (!cred) throw cancelled(\"passkey sign-in was cancelled\");\n const r = cred.response as AuthenticatorAssertionResponse;\n return {\n credentialId: b64url(new Uint8Array(cred.rawId)),\n authenticatorData: b64url(new Uint8Array(r.authenticatorData)),\n clientDataJson: b64url(new Uint8Array(r.clientDataJSON)),\n signature: b64url(new Uint8Array(r.signature)),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------- the step-up\n/**\n * `details` of a `412 CONFIRM_REQUIRED`: the WebAuthn challenge to sign.\n * `userVerification` is read when a node names it (core does not today).\n */\nexport type ConfirmChallenge = components['schemas']['ConfirmRequired'] & { userVerification?: unknown };\n\n/** What a confirmation answers a `412` with: an assertion over the challenge. */\nexport type ConfirmCallback = (challenge: ConfirmChallenge, context: { request: Request }) => Promise<AssertionJSON>;\n\n/**\n * The user verification a confirmation asks the passkey for: what the node's\n * `412` details name, if it names one WebAuthn knows, else `fallback` (the\n * flow's own requirement: `required` for a step-up, which the node takes only\n * with the user verified; `preferred` for the sign-up confirmation, which it\n * takes with the user present).\n */\nexport function userVerificationOf(named: unknown, fallback: PasskeyUserVerification): PasskeyUserVerification {\n return named === 'required' || named === 'preferred' || named === 'discouraged' ? named : fallback;\n}\n\n/**\n * What a failed confirmation prompt means to the caller. The browser or a\n * password manager refusing to show the prompt (the page not focused because\n * an extension's popup still holds focus, or another prompt still open) is\n * {@link ConfirmPromptBlocked}; the user dismissing it (`NotAllowedError`, or\n * `AbortError` when it was aborted) is {@link ConfirmCancelled}; anything\n * else is a real failure, passed through.\n */\nexport function promptFailure(error: unknown): unknown {\n const e = error as { name?: unknown; message?: unknown } | null;\n const name = e?.name;\n const message = typeof e?.message === 'string' ? e.message : '';\n if (name === 'InvalidStateError' || /not focused|already pending/i.test(message)) {\n return new ConfirmPromptBlocked(error);\n }\n if (name === 'NotAllowedError' || name === 'AbortError') return new ConfirmCancelled(error);\n return error;\n}\n\n/** How {@link passkeyConfirm} prompts. */\nexport interface PasskeyConfirmOptions {\n /** The user verification asked for when the node names none. Default `required` (a step-up). */\n userVerification?: PasskeyUserVerification;\n /** Aborts the passkey prompt. */\n signal?: AbortSignal;\n}\n\n/**\n * `passkey`'s assertion over a `412` challenge: the {@link ConfirmCallback}\n * of a passkey. A prompt the user dismissed rejects with\n * {@link ConfirmCancelled}, one the browser would not show with\n * {@link ConfirmPromptBlocked}.\n */\nexport function passkeyConfirm(passkey: PasskeyProvider, options: PasskeyConfirmOptions = {}): ConfirmCallback {\n return async (challenge) => {\n try {\n // A step-up is taken only with the user verified (PIN or biometric);\n // `preferred` lets a password manager skip it, and the node then\n // refuses. Only the sign-up confirmation passes `preferred`. A\n // requirement the node names itself wins.\n return await passkey.get(fromB64url(challenge.challenge), challenge.rpId, challenge.allowCredentials, {\n userVerification: userVerificationOf(challenge.userVerification, options.userVerification ?? 'required'),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n } catch (declined) {\n throw promptFailure(declined);\n }\n };\n}\n", "/**\n * The runtime every route of a Calimero node is sent through: the part of\n * this client that is not a route.\n *\n * A route layer (the one generated from the node's OpenAPI document:\n * `createRouteClient` and `createRoutes` in `../api`, which {@link CalimeroClient}\n * exposes) knows a method, a path and what the route takes and answers.\n * Everything else is here, behind one call, {@link Transport.request}:\n *\n * - the sealed channel to each node, opened only after the node's attestation\n * passed the caller's policy (`../sealed`, `./attestation`);\n * - the credential (an API key or a session), and the session's refresh when a\n * node answers `401` to it;\n * - moving to another node of the cluster on `421 WRONG_NODE`, and failing\n * over when one stays unavailable to a call or a view (D70 retries);\n * - the `412 CONFIRM_REQUIRED` step-up: the passkey's assertion over the\n * node's challenge, sent with the same body again;\n * - error mapping (a refusal is a typed {@link CalimeroError}) and\n * server-sent event decoding.\n *\n * Paths are relative to the node (`apps/{app}/intents`, a leading `/` is\n * dropped); {@link routePath} fills a path template with encoded segments.\n */\n\nimport { SealedTransportError, createSealedFetch } from '../sealed/sealed.js';\nimport { fetchAttestedKey, type NodePolicy } from './attestation.js';\nimport { orderNodes, readDirectory } from './directory.js';\nimport {\n CalimeroError,\n ConfirmRequired,\n LoginRequired,\n UnavailableError,\n WrongNode,\n errorFrom,\n} from './errors.js';\nimport { b64url, type PasskeyProvider, type PasskeyUserVerification } from './passkey.js';\nimport { passkeyConfirm, type ConfirmChallenge } from './passkey.js';\nimport type { components } from '../generated/api.js';\n\n/** A signed-in session: what sign-up, sign-in and a refresh answer. */\nexport type CalimeroSession = components['schemas']['Session'];\n\n/** One server-sent event: `data` parsed as JSON when it is. */\nexport interface NodeEvent {\n id: string;\n kind: string;\n data: unknown;\n}\n\n/**\n * How a call or a view is sent again while the node is unavailable (D70): with\n * the same key, after a backoff that starts at `baseDelayMs` and doubles up to\n * `maxDelayMs`, no jitter, at most `retries` times. The defaults are the Rust\n * client's: 6 retries, 200 ms doubling, at most 2 s (about 9 s in all, past a\n * leader election).\n */\nexport interface RetryOptions {\n /** Retries after the first attempt. Default 6. */\n retries?: number;\n /** The first backoff; each retry doubles it. Default 200 ms. */\n baseDelayMs?: number;\n /** The longest backoff. Default 2 s. */\n maxDelayMs?: number;\n}\n\nexport const DEFAULT_RETRY = { retries: 6, baseDelayMs: 200, maxDelayMs: 2000 } as const;\n\n/** The backoff before retry `retry` (0 for the first): `baseDelayMs` doubling, at most `maxDelayMs`. */\nexport function retryDelayMs(retry: number, options: { baseDelayMs: number; maxDelayMs: number }): number {\n return Math.min(options.baseDelayMs * 2 ** retry, options.maxDelayMs);\n}\n\n/** The HTTP methods the node's routes use. */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/** A query parameter's value; `undefined` and `null` leave it out, an array repeats it. */\nexport type QueryValue = string | number | boolean | null | undefined;\n\n/** What a request carries beyond its method and path. */\nexport interface RequestOptions {\n /** Query parameters, appended to the path (encoded here). */\n query?: Record<string, QueryValue | QueryValue[]>;\n /** A JSON body. */\n body?: unknown;\n /** A raw body instead of JSON (a bundle, a package, a blob). */\n bytes?: Uint8Array;\n /** The raw body's content type. Default `application/wasm`. */\n contentType?: string;\n /**\n * Answers a `412 CONFIRM_REQUIRED`: the passkey asserts over the node's\n * challenge and the same JSON body is sent again with `confirm`. Without\n * one the `412` reaches the caller as {@link ConfirmRequired}.\n */\n passkey?: PasskeyProvider;\n /** The user verification the step-up asks for when the node names none. Default `required`. */\n userVerification?: PasskeyUserVerification;\n /**\n * D70 retries for a call or a view: `true` sends it again while the node\n * answers `503` or cannot be reached, then fails over to the next node;\n * `'once'` sends it exactly once (a confirmed attempt, whose challenge is\n * single-use). Only for a JSON body that carries its own idempotency key,\n * or a read.\n */\n retry?: boolean | 'once';\n /** Aborts the request (and a stream), and the step-up's passkey prompt. */\n signal?: AbortSignal;\n /** Aborts only the step-up's passkey prompt, not the requests around it. Default `signal`. */\n promptSignal?: AbortSignal;\n}\n\n/**\n * What a route layer calls. Every method sends through the attested, sealed\n * channel of the node in use, with the credential held now. A refusal (any\n * status other than 2xx) is thrown as a typed {@link CalimeroError}\n * ({@link errorFrom}); a transport failure as the error that caused it.\n */\nexport interface Transport {\n /** The response to `method path`, status 2xx; its body is not read. */\n request(method: HttpMethod, path: string, options?: RequestOptions): Promise<Response>;\n /** {@link request}'s JSON body (`{}` for an empty one). */\n json<T = Record<string, unknown>>(method: HttpMethod, path: string, options?: RequestOptions): Promise<T>;\n /** A server-sent event stream on `GET path`, until the stream ends or `signal` aborts. */\n events(path: string, options?: Pick<RequestOptions, 'query' | 'signal'>): AsyncGenerator<NodeEvent>;\n}\n\n/** How {@link NodeTransport} reaches a cluster's nodes. */\nexport interface NodeTransportOptions {\n /** One node of the cluster: the one the transport talks to first. */\n baseUrl: string;\n /** Other nodes of the same cluster, in the order to move to them. */\n nodes?: string[];\n /** What every node must attest to before anything is sent to it. */\n policy: NodePolicy;\n /** Fetch that carries attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n}\n\n/** Where a transport whose nodes came from the directory re-reads its node list. */\nexport interface DirectorySource {\n directory: string;\n cluster: string;\n zone: string | undefined;\n random: () => number;\n /** When the listing is due to be read again (ms since the epoch). */\n due: number;\n /** The re-read under way, if any. */\n reading?: Promise<void>;\n}\n\n/**\n * The node refuses an envelope past its 64 MiB sealed cap with `413` in the\n * clear, before opening it, so the refusal arrives as the transport's. To the\n * caller it is the API's `TOO_LARGE`, as the Rust client reports it.\n */\nfunction sealedError(error: unknown): unknown {\n if (error instanceof SealedTransportError && error.status === 413) {\n return errorFrom(413, {\n error: 'TOO_LARGE',\n message: error.message.replace(/^Sealed request refused: /, ''),\n });\n }\n return error;\n}\n\n/** Read a refused response's body and map it ({@link errorFrom}). */\nexport async function refusal(response: Response): Promise<CalimeroError> {\n const text = await response.text().catch(() => '');\n let body: unknown = {};\n try {\n body = text ? JSON.parse(text) : {};\n } catch {\n body = { message: text };\n }\n return errorFrom(response.status, body, response.headers.get('retry-after'));\n}\n\n/** Server-sent event frames from a response body: `{ id, kind, data }` each, `data` parsed as JSON when it is. */\nexport async function* sseFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<NodeEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n buffer += decoder.decode(value, { stream: true });\n let cut: number;\n while ((cut = buffer.indexOf('\\n\\n')) >= 0) {\n const frame = buffer.slice(0, cut);\n buffer = buffer.slice(cut + 2);\n let id = '';\n let kind = '';\n let data = '';\n for (const line of frame.split('\\n')) {\n if (line.startsWith('id:')) id = line.slice(3).trim();\n else if (line.startsWith('event:')) kind = line.slice(6).trim();\n else if (line.startsWith('data:')) data += line.slice(5).trim();\n }\n if (!kind && !data) continue;\n let parsed: unknown = data;\n try {\n parsed = JSON.parse(data);\n } catch {\n /* plain text */\n }\n yield { id, kind, data: parsed };\n }\n }\n}\n\n/**\n * A key for a call the caller gave none, made once so every retry shares it:\n * `node:c-` and 16 random bytes in base64url without padding, as the Rust\n * client mints it. It only has to outlive this client's own retries, so it\n * takes the node's short-lived class: a key starting `node:` is kept 10\n * minutes, a caller's own key 24 hours.\n * `getRandomValues`, not `randomUUID`, which a page outside a secure context lacks.\n */\nexport function newIdempotencyKey(): string {\n return `node:c-${b64url(crypto.getRandomValues(new Uint8Array(16)))}`;\n}\n\n/**\n * `template` (`apps/{app}/blobs/{id}`) with each `{name}` replaced by\n * `params[name]`, encoded as one path segment so an id cannot reach another\n * route. A name `params` lacks throws.\n */\nexport function routePath(template: string, params: Record<string, string | number> = {}): string {\n return template.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name];\n if (value === undefined) throw new Error(`no value for path parameter ${name} of ${template}`);\n return encodeURIComponent(String(value));\n });\n}\n\n/** `query` as a search string (`?a=1&b=2`), or `''` when it sets nothing. */\nexport function queryString(query: RequestOptions['query']): string {\n if (!query) return '';\n const search = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) {\n for (const one of Array.isArray(value) ? value : [value]) {\n if (one !== undefined && one !== null) search.append(name, String(one));\n }\n }\n const text = search.toString();\n return text ? `?${text}` : '';\n}\n\n/**\n * The ceremonies that mint a session, which {@link NodeTransport} never\n * repeats by itself: a sign-in or sign-up is started again by its caller (with\n * the passkey), and a refresh moves through the nodes in\n * {@link NodeTransport.refresh}. A node answers them `421 WRONG_NODE` before\n * it spends the challenge or the refresh token (core #4774).\n */\nfunction ceremony(path: string): boolean {\n return path === 'auth/refresh' || path.startsWith('auth/passkey/') || RECOVERY_CEREMONIES.has(path);\n}\n\n/** The signed-out halves of an account recovery: a `401` there is the code's, not a session's. */\nconst RECOVERY_CEREMONIES = new Set(['auth/recovery/begin', 'auth/recovery/start', 'auth/recovery/finish']);\n\n/** The route path a request names: no leading `/`. */\nfunction relative(path: string): string {\n return path.replace(/^\\/+/, '');\n}\n\n/**\n * The {@link Transport} to one Calimero cluster: its nodes, each attested\n * under one policy before its first request, the credential, and the session's\n * refresh. {@link CalimeroClient} is built on one (`client.transport`); a\n * generated route layer takes one too.\n */\nexport class NodeTransport implements Transport {\n /** Every node this transport may use, `baseUrl` first (or as the directory last ordered them). */\n private nodeUrls: string[];\n /** The one in use: an index into {@link nodeUrls}. */\n private at = 0;\n /** A sealed fetch per node, each attesting its own node on first use. */\n private readonly channels = new Map<string, typeof fetch>();\n private readonly policy: NodePolicy;\n /** The unsealed fetch, for the one route served in the clear (`/attestation`). */\n readonly raw: typeof fetch;\n private auth: string | undefined;\n private current: CalimeroSession | undefined;\n /** The refresh under way, which every request that needs one shares. */\n private refreshing: Promise<CalimeroSession> | undefined;\n /** The backoff between retries, for a caller that retries a request the routes do not. */\n readonly retry: Required<RetryOptions>;\n /** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */\n private readonly networkFailures = new WeakSet<object>();\n /** The directory the node list came from, if it came from one. */\n private source: DirectorySource | undefined;\n\n constructor(options: NodeTransportOptions) {\n const trim = (url: string) => url.replace(/\\/+$/, '');\n this.nodeUrls = [...new Set([options.baseUrl, ...(options.nodes ?? [])].map(trim))];\n this.policy = options.policy;\n this.retry = { ...DEFAULT_RETRY, ...options.retry };\n const given = options.fetch ?? ((input, init) => fetch(input, init));\n // `fetch` rejects with a `TypeError` when it gets no answer: the connection\n // was refused, reset or dropped before the response. The sealed fetch passes\n // that rejection on unchanged, so it is recognised here, at its source, and\n // not by its type alone (a bad URL is a `TypeError` too, and is not retried).\n const raw: typeof fetch = async (input, init) => {\n try {\n return await given(input, init);\n } catch (error) {\n if (error instanceof TypeError) this.networkFailures.add(error);\n throw error;\n }\n };\n this.raw = raw;\n }\n\n /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */\n isNetworkFailure(error: unknown): boolean {\n return error instanceof TypeError && this.networkFailures.has(error);\n }\n\n /** Re-read the node list from `source` when it is due, and after a failover. */\n useDirectory(source: DirectorySource): void {\n this.source = source;\n }\n\n /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved on. */\n get nodeUrl(): string {\n return this.nodeUrls[this.at];\n }\n\n /** Every node this transport may use, in the order it moves through them. */\n get nodes(): string[] {\n return [...this.nodeUrls];\n }\n\n /** Authenticate every request with an API key. */\n useApiKey(key: string): void {\n this.auth = key;\n this.current = undefined;\n }\n\n /** Authenticate every request with `session`, refreshed when a node answers `401` to it. */\n useSession(session: CalimeroSession): void {\n this.auth = session.sessionToken;\n this.current = session;\n }\n\n /** Drop the credential: no request after this carries it. */\n signOut(): void {\n this.auth = undefined;\n this.current = undefined;\n }\n\n get session(): CalimeroSession | undefined {\n return this.current;\n }\n\n /** The sealed channel to `url`, attested under the policy before its first request. */\n private channel(url: string): typeof fetch {\n let sealed = this.channels.get(url);\n if (!sealed) {\n sealed = createSealedFetch({\n baseUrl: url,\n transportPublicKey: () => fetchAttestedKey(url, this.policy, this.raw),\n fetch: this.raw,\n });\n this.channels.set(url, sealed);\n }\n return sealed;\n }\n\n /**\n * Move on from node `from` (the one that answered `421 WRONG_NODE`) to the\n * next one. False when there is no other. A request that saw the same node\n * refuse after another request moved on already does not move again.\n */\n private moveOn(from: string): boolean {\n if (this.nodeUrls.length < 2) return false;\n if (this.nodeUrl === from) this.at = (this.at + 1) % this.nodeUrls.length;\n return true;\n }\n\n /**\n * Fail over from node `from`, where a request's retries ran out, to the next\n * node it has not `tried`. False when it has tried them all. A request whose\n * node another request moved away from already goes to that node, if untried.\n */\n private failOver(from: string, tried: Set<string>): boolean {\n if (this.nodeUrl !== from && !tried.has(this.nodeUrl)) return true;\n const count = this.nodeUrls.length;\n for (let step = 1; step < count; step++) {\n const next = (this.at + step) % count;\n if (!tried.has(this.nodeUrls[next])) {\n this.at = next;\n this.reread();\n return true;\n }\n }\n return false;\n }\n\n /**\n * Read the node list again from the directory, in the background: the node\n * in use stays first, then the directory's order; a node no longer listed is\n * dropped. A failed read is ignored. One read at a time.\n */\n private reread(): void {\n const source = this.source;\n if (!source || source.reading) return;\n source.reading = readDirectory(source.directory, source.cluster, this.raw)\n .then((listing) => {\n const current = this.nodeUrl;\n const listed = orderNodes(listing.nodes, source.zone, source.random);\n this.nodeUrls = [current, ...listed.filter((url) => url !== current)];\n this.at = 0;\n source.due = Date.now() + listing.refreshAfterSeconds * 1000;\n })\n .catch(() => undefined)\n .finally(() => {\n source.reading = undefined;\n });\n }\n\n /**\n * Send one request to the node in use, with the credential held now, and\n * answer the response, whatever its status. {@link send} judges it.\n */\n private async once(method: string, path: string, options: RequestOptions): Promise<Response> {\n const headers: Record<string, string> = {};\n if (this.auth) headers.authorization = `Bearer ${this.auth}`;\n let payload: BodyInit | undefined;\n if (options.bytes) {\n headers['content-type'] = options.contentType ?? 'application/wasm';\n payload = options.bytes as unknown as BodyInit;\n } else if (options.body !== undefined) {\n headers['content-type'] = 'application/json';\n payload = JSON.stringify(options.body);\n }\n if (this.source && Date.now() >= this.source.due) this.reread();\n const url = this.nodeUrl;\n try {\n return await this.channel(url)(`${url}/${path}${queryString(options.query)}`, {\n method,\n headers,\n body: payload,\n signal: options.signal,\n });\n } catch (error) {\n throw sealedError(error);\n }\n }\n\n /**\n * {@link once}, answering what a lost issuing node or a node on the wrong\n * release does to a session: a successful response, or the refusal as a\n * typed error ({@link errorFrom}).\n *\n * - `401 UNAUTHENTICATED` to a request that carried a session: the node that\n * signed the session may be gone, replaced, or out of reach of the node\n * asked, which any node of the cluster answers with a refresh. The\n * transport refreshes once, shared by every request that needs it at the\n * same time ({@link refresh}), and repeats the request once. A refresh that\n * is refused surfaces as {@link LoginRequired}.\n * - `421 WRONG_NODE`: this node's release may not serve the account. The\n * transport moves to the next node it knows and repeats the request once;\n * with none, the {@link WrongNode} reaches the caller.\n *\n * Repeating is safe even for a request that is not idempotent: the node\n * answers `401` and `421` when it judges the credential, before it reads what\n * the request asks, so the first attempt ran nothing. The exceptions are the\n * ceremonies that mint a session ({@link ceremony}), never repeated here.\n */\n private async send(method: string, path: string, options: RequestOptions): Promise<Response> {\n const response = await this.answer(method, path, options);\n if (!response.ok) throw await refusal(response);\n return response;\n }\n\n /**\n * {@link send}'s answer, a refusal included: the response after the\n * session's refresh and the move past a `421 WRONG_NODE`, whatever its\n * status. The generated route layer reads a refusal itself.\n */\n private async answer(method: string, path: string, options: RequestOptions): Promise<Response> {\n let refreshed = false;\n let moved = false;\n for (;;) {\n const [token, at] = [this.auth, this.nodeUrl];\n const response = await this.once(method, path, options);\n if (response.ok || (response.status !== 401 && response.status !== 421)) return response;\n const error = await refusal(response.clone());\n if (error instanceof WrongNode && !moved) {\n moved = true;\n if (this.moveOn(at) && !ceremony(path)) continue;\n } else if (error instanceof LoginRequired && !refreshed && this.mayRefresh(token, path)) {\n refreshed = true;\n await this.renew(token as string);\n continue;\n }\n return response;\n }\n }\n\n /** Whether a `401` to a request sent with `token` is one a refresh may answer. */\n private mayRefresh(token: string | undefined, path: string): boolean {\n return token !== undefined && this.current !== undefined && !ceremony(path);\n }\n\n /**\n * A fresh session in place of the one `token` belonged to: by the refresh\n * another request already made, or by one this request starts.\n */\n private async renew(token: string): Promise<void> {\n if (this.auth !== token) return;\n await this.refresh();\n }\n\n private async read<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n const response = await this.send(method, path, options);\n const text = await response.text();\n return (text ? JSON.parse(text) : {}) as T;\n }\n\n /**\n * {@link read} for a call or a view (D70): while the node answers 503 or\n * cannot be reached, the same request, with the same idempotency key, is sent\n * again after {@link retryDelayMs} (or the pause the node asked for, if\n * longer), at most `retries` times. Every other answer is final.\n *\n * When a node's retries run out, the request fails over to the next node the\n * transport knows and its retries start again there, with the same key: the\n * key is kept in the app's replicated log, so the cluster answers it once\n * whichever node it reaches. Each node is tried once per request. The last\n * failure surfaces as {@link UnavailableError}: the node's 503, or reason\n * `network` for a connection that failed, whose `committed` is `'unknown'`.\n *\n * `once` sends the request exactly once, to the node in use (a confirmed\n * attempt, whose challenge is single-use).\n */\n private async retried<T>(method: string, path: string, options: RequestOptions, once: boolean): Promise<T> {\n const response = await this.answerRetried(method, path, options, once);\n if (!response.ok) throw await refusal(response);\n const text = await response.text();\n return (text ? JSON.parse(text) : {}) as T;\n }\n\n /**\n * {@link retried}'s answer: the last response, a refusal included (a `503`\n * whose retries ran out on every node too). A connection that failed on the\n * last node rejects with {@link UnavailableError} (reason `network`).\n */\n private async answerRetried(method: string, path: string, options: RequestOptions, once: boolean): Promise<Response> {\n const retries = once ? 0 : this.retry.retries;\n const tried = new Set<string>();\n for (;;) {\n let unavailable: UnavailableError | undefined;\n let last: Response | undefined;\n let node = this.nodeUrl;\n for (let attempt = 0; ; attempt++) {\n node = this.nodeUrl;\n tried.add(node);\n try {\n const response = await this.answer(method, path, options);\n if (response.status !== 503) return response;\n last = response;\n unavailable = (await refusal(response.clone())) as UnavailableError;\n } catch (error) {\n if (error instanceof TypeError && this.networkFailures.has(error)) {\n last = undefined;\n unavailable = new UnavailableError('NETWORK', `the node could not be reached: ${error.message}`, {}, undefined, error);\n } else throw error;\n }\n if (attempt >= retries) break;\n const backoff = retryDelayMs(attempt, this.retry);\n await new Promise((resolve) => setTimeout(resolve, Math.max(backoff, (unavailable.retryAfter ?? 0) * 1000)));\n }\n if (once || !this.failOver(node, tried)) {\n if (last) return last;\n throw unavailable;\n }\n }\n }\n\n /**\n * One request to a route, answered whatever its status: the runtime's part\n * (sealing, the session and its refresh, `421 WRONG_NODE`, and with\n * `options.retry` the D70 retries and failover) and nothing of the route's.\n * A refusal is the node's response, for the caller to read; a connection\n * that failed rejects as `fetch` did (with `retry`, as\n * {@link UnavailableError} once the retries ran out). The generated route\n * layer (`createRouteClient`) sends through this.\n */\n exchange(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<Response> {\n const relativePath = relative(path);\n if (!options.retry) return this.answer(method, relativePath, options);\n return this.answerRetried(method, relativePath, options, options.retry === 'once');\n }\n\n /**\n * One JSON request, retried as `options.retry` says. The confirmed attempt\n * of a step-up (`body.confirm` set) goes out exactly once.\n */\n private attempt<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n if (!options.retry) return this.read<T>(method, path, options);\n const confirming = (options.body as { confirm?: unknown } | undefined)?.confirm !== undefined;\n return this.retried<T>(method, path, options, options.retry === 'once' || confirming);\n }\n\n /**\n * {@link attempt}, answering a `412 CONFIRM_REQUIRED` with `passkey`'s\n * assertion over the node's challenge: the same body again, with `confirm`.\n * Without a passkey the `412` reaches the caller as {@link ConfirmRequired}.\n */\n private async confirmed<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n const { passkey } = options;\n try {\n return await this.attempt<T>(method, path, options);\n } catch (error) {\n if (!(error instanceof ConfirmRequired) || !passkey) throw error;\n const challenge = error.details as ConfirmChallenge;\n const assertion = await passkeyConfirm(passkey, {\n userVerification: options.userVerification,\n signal: options.promptSignal ?? options.signal,\n })(challenge, { request: new Request(`${this.nodeUrl}/${path}`, { method }) });\n const body = { ...(options.body as Record<string, unknown>), confirm: { challengeId: challenge.challengeId, assertion } };\n return this.attempt<T>(method, path, { ...options, body });\n }\n }\n\n request(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<Response> {\n return this.send(method, relative(path), options);\n }\n\n json<T = Record<string, unknown>>(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<T> {\n return this.confirmed<T>(method, relative(path), options);\n }\n\n async *events(path: string, options: Pick<RequestOptions, 'query' | 'signal'> = {}): AsyncGenerator<NodeEvent> {\n const response = await this.send('GET', relative(path), options);\n if (!response.body) throw new CalimeroError(response.status, 'EVENTS', 'the event stream has no body');\n yield* sseFrames(response.body);\n }\n\n /**\n * `GET path` in the clear, from the node in use: only for the route a node\n * serves unsealed (`attestation`), and never with the credential.\n */\n async unsealed(path: string, options: Pick<RequestOptions, 'query'> = {}): Promise<Response> {\n const response = await this.inTheClear(path, options);\n if (!response.ok) throw await refusal(response);\n return response;\n }\n\n /**\n * {@link unsealed}'s answer, a refusal included: `GET path` in the clear,\n * without the credential, for the routes a node serves unsealed\n * (`attestation`, `health`).\n */\n inTheClear(path: string, options: Pick<RequestOptions, 'query' | 'signal'> = {}): Promise<Response> {\n return this.raw(`${this.nodeUrl}/${relative(path)}${queryString(options.query)}`, { signal: options.signal });\n }\n\n /**\n * Swap the refresh token for a new session, on whichever node the transport\n * uses: any node of the cluster takes it. A refresh token is used once, so\n * requests made while one refresh is under way share it rather than sending\n * the same token again (which would revoke the session).\n */\n refresh(): Promise<CalimeroSession> {\n if (!this.refreshing) {\n const pending = this.exchangeRefresh();\n this.refreshing = pending;\n const clear = () => {\n if (this.refreshing === pending) this.refreshing = undefined;\n };\n pending.then(clear, clear);\n }\n return this.refreshing;\n }\n\n private async exchangeRefresh(): Promise<CalimeroSession> {\n const current = this.current;\n if (!current) throw new Error('no session to refresh');\n let session: CalimeroSession | undefined;\n // A node that may not serve the account answers `421 WRONG_NODE` before it\n // spends the refresh token (core #4774), so the same token goes to the next\n // node (`send` moved there already): once per node, at most.\n for (let tried = 1; session === undefined; tried++) {\n try {\n session = await this.json<CalimeroSession>('POST', 'auth/refresh', { body: { refreshToken: current.refreshToken } });\n } catch (error) {\n if (!(error instanceof WrongNode) || tried >= this.nodeUrls.length) throw error;\n }\n }\n // A sign-in or another session taken while this one was refreshing wins.\n if (this.current === current) this.useSession(session);\n return session;\n }\n}\n\n/**\n * A {@link NodeTransport} to the cluster named `cluster`, its node list read\n * from the node directory (`directory`), those in `zone` first, each group in\n * weighted-random order, and read again in the background after a failover\n * and once the listing's `refreshAfterSeconds` passed.\n */\nexport async function directoryTransport(options: {\n cluster: string;\n policy: NodePolicy;\n directory: string;\n zone?: string;\n fetch?: typeof fetch;\n retry?: RetryOptions;\n random?: () => number;\n}): Promise<NodeTransport> {\n const random = options.random ?? Math.random;\n const fetcher = options.fetch ?? ((input, init) => fetch(input, init));\n const listing = await readDirectory(options.directory, options.cluster, fetcher);\n const [baseUrl, ...nodes] = orderNodes(listing.nodes, options.zone, random);\n const transport = new NodeTransport({ baseUrl, nodes, policy: options.policy, fetch: options.fetch, retry: options.retry });\n transport.useDirectory({\n directory: options.directory,\n cluster: options.cluster,\n zone: options.zone,\n random,\n due: Date.now() + listing.refreshAfterSeconds * 1000,\n });\n return transport;\n}\n", "// settings & const\nconst PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nconst supportsRequestInitExt = () => {\n return (\n typeof process === \"object\" &&\n Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&\n process.versions.undici\n );\n};\n\n/**\n * Returns a cheap, non-cryptographically-secure random ID\n * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)\n */\nexport function randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\n\n/**\n * Create an openapi-fetch client.\n * @type {import(\"./index.js\").default}\n */\nexport default function createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = undefined,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n\n /**\n * Per-request fetch (keeps settings created in createClient()\n * @param {T} url\n * @param {import('./index.js').FetchOptions<T>} fetchOptions\n */\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n\n let querySerializer =\n typeof globalQuerySerializer === \"function\"\n ? globalQuerySerializer\n : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer =\n typeof requestQuerySerializer === \"function\"\n ? requestQuerySerializer\n : createQuerySerializer({\n ...(typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {}),\n ...requestQuerySerializer,\n });\n }\n\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n\n const serializedBody =\n body === undefined\n ? undefined\n : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header),\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === undefined ||\n // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData\n ? {}\n : {\n \"Content-Type\": \"application/json\",\n },\n baseHeaders,\n headers,\n params.header,\n );\n\n // Client level middleware take priority over request-level middleware\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders,\n };\n\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit,\n );\n let response;\n\n /** Add custom parameters to Request object */\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n\n if (finalMiddlewares.length) {\n id = randomID();\n\n // middleware (request)\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer,\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n\n if (!response) {\n // fetch!\n try {\n response = await fetch(request, requestInitExt);\n } catch (error) {\n let errorAfterMiddleware = error;\n // middleware (error)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n // if error is handled by returning a response, skip remaining middleware\n if (result instanceof Response) {\n errorAfterMiddleware = undefined;\n response = result;\n break;\n }\n\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n\n // rethrow error if not handled by middleware\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n\n // middleware (response)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n\n const contentLength = response.headers.get(\"Content-Length\");\n // handle empty content\n if (\n response.status === 204 ||\n request.method === \"HEAD\" ||\n (contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\"))\n ) {\n return response.ok ? { data: undefined, response } : { error: undefined, response };\n }\n\n // parse response (falling back to .text() when necessary)\n if (response.ok) {\n const getResponseData = async () => {\n // if \"stream\", skip parsing entirely\n if (parseAs === \"stream\") {\n return response.body;\n }\n\n if (parseAs === \"json\" && !contentLength) {\n // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)\n const raw = await response.text();\n return raw ? JSON.parse(raw) : undefined;\n }\n\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n\n // handle errors\n let error = await response.text();\n try {\n error = JSON.parse(error); // attempt to parse as JSON\n } catch {\n // noop\n }\n return { error, response };\n }\n\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n },\n };\n}\n\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\n\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\n\n/**\n * Wrap openapi-fetch client to support a path based API.\n * @type {import(\"./index.js\").wrapAsPathBasedClient}\n */\nexport function wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n\n // Put the proxy on the prototype chain of the actual client.\n // This means if we do not have a memoized PathCallForwarder,\n // we fall back to the proxy to synthesize it.\n // However, the proxy itself is not on the hot-path (if we fetch the same\n // endpoint multiple times, only the first call will hit the proxy).\n function Client() {}\n Client.prototype = proxy;\n\n const client = new Client();\n\n // Feed the client back to the proxy handler so it can store the generated\n // PathCallForwarder.\n handler.client = client;\n\n return client;\n}\n\n/**\n * Convenience method to an openapi-fetch path based client.\n * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.\n * @type {import(\"./index.js\").createPathBasedClient}\n */\nexport function createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\n\n// utils\n\n/**\n * Serialize primitive param values\n * @type {import(\"./index.js\").serializePrimitiveParam}\n */\nexport function serializePrimitiveParam(name, value, options) {\n if (value === undefined || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.\",\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\n\n/**\n * Serialize object param (shallow only)\n * @type {import(\"./index.js\").serializeObjectParam}\n */\nexport function serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner =\n {\n simple: \",\",\n label: \".\",\n matrix: \";\",\n }[options.style] || \"&\";\n\n // explode: false\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final = values.join(\",\"); // note: values are always joined by comma in explode: false (but joiner can prefix)\n switch (options.style) {\n case \"form\": {\n return `${name}=${final}`;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n default: {\n return final;\n }\n }\n }\n\n // explode: true\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\n\n/**\n * Serialize array param (shallow only)\n * @type {import(\"./index.js\").serializeArrayParam}\n */\nexport function serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n\n // explode: false\n if (options.explode === false) {\n const joiner = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\"; // note: for arrays, joiners vary wildly based on style + explode behavior\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n\n // explode: true\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\"\n ? `${joiner}${values.join(joiner)}`\n : values.join(joiner);\n}\n\n/**\n * Serialize query params to string\n * @type {import(\"./index.js\").createQuerySerializer}\n */\nexport function createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\n\n/**\n * Handle different OpenAPI 3.x serialization styles\n * @type {import(\"./index.js\").defaultPathSerializer}\n * @see https://swagger.io/docs/specification/serialization/#path\n */\nexport function defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\n\n/**\n * Serialize body object to string\n * @type {import(\"./index.js\").defaultBodySerializer}\n */\nexport function defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType =\n headers.get instanceof Function\n ? (headers.get(\"Content-Type\") ?? headers.get(\"content-type\"))\n : (headers[\"Content-Type\"] ?? headers[\"content-type\"]);\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\n\n/**\n * Construct URL string from baseUrl and handle path and query params\n * @type {import(\"./index.js\").createFinalURL}\n */\nexport function createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\n\n/**\n * Merge headers a and b, with b taking priority\n * @type {import(\"./index.js\").mergeHeaders}\n */\nexport function mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== undefined) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\n\n/**\n * Remove trailing slash from url\n * @type {import(\"./index.js\").removeTrailingSlash}\n */\nexport function removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n", "/**\n * The answers to the two challenges a node puts before a request it will only\n * take with a proof: the `412 CONFIRM_REQUIRED` passkey step-up and the\n * `428 OPERATOR_SIGNATURE_REQUIRED` operator signature (core\n * `crates/node/src/api/openapi.rs`, components `ConfirmRequired`, `Confirm`,\n * `OperatorSignatureRequired`, `OperatorProof`).\n *\n * Each is an `openapi-fetch` middleware: it keeps a copy of the request it\n * sees go out, and when the node answers the challenge it asks a callback the\n * caller supplied for the proof, then sends the same JSON body again with the\n * proof beside it (`confirm`, `operatorProof`) and answers that response in\n * place of the challenge. Without a callback (or when the callback is not\n * given for that request) the challenge reaches the caller as the\n * `{ error }` of the response.\n */\n\nimport type { Middleware } from 'openapi-fetch';\n\nimport type { components } from '../generated/api.js';\nimport type { ConfirmCallback, ConfirmChallenge } from '../runtime/passkey.js';\n\n/** `details` of a `428 OPERATOR_SIGNATURE_REQUIRED`: the statement and its exact bytes (`message`, base64). */\nexport type OperatorStatement = components['schemas']['OperatorSignatureRequired'];\n\n/** The operator key's proof the retry carries: its Ed25519 signature (hex) over `message`, with the statement's nonce. */\nexport type OperatorProof = components['schemas']['OperatorProof'];\n\n/** What a `428` is answered with: the operator key's signature over the statement. */\nexport type OperatorProofCallback = (statement: OperatorStatement, context: { request: Request }) => Promise<OperatorProof>;\n\n/**\n * A middleware that answers a `status code` refusal: `answer` turns its\n * `details` into the fields to add to the JSON body, and the request goes out\n * again once with them.\n */\nfunction challengeAnswer<D>(\n status: number,\n code: string,\n answer: (details: D, request: Request) => Promise<Record<string, unknown>>,\n): Middleware {\n const sent = new Map<string, Request>();\n return {\n onRequest({ request, id }) {\n // Kept before the body is read: the retry is the same request. Only a\n // JSON body (or none) can carry the proof, so an upload is never copied.\n const type = request.headers.get('content-type');\n const json = type === null || type.startsWith('application/json');\n if (json && request.method !== 'GET' && request.method !== 'HEAD') sent.set(id, request.clone());\n return undefined;\n },\n async onResponse({ response, id, options }) {\n const original = sent.get(id);\n sent.delete(id);\n if (response.status !== status || !original) return undefined;\n const refusal = (await response\n .clone()\n .json()\n .catch(() => undefined)) as { error?: unknown; details?: unknown } | undefined;\n if (refusal?.error !== code) return undefined;\n const fields = await answer((refusal.details ?? {}) as D, original);\n const text = await original.text();\n const body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n const headers = new Headers(original.headers);\n headers.set('content-type', 'application/json');\n const again = new Request(original.url, {\n method: original.method,\n headers,\n body: JSON.stringify({ ...body, ...fields }),\n signal: original.signal,\n });\n return options.fetch(again);\n },\n onError({ id }) {\n sent.delete(id);\n return undefined;\n },\n };\n}\n\n/**\n * The `412 CONFIRM_REQUIRED` step-up: `confirm` signs the node's challenge and\n * the same body goes again with `confirm: { challengeId, assertion }`. Add it\n * to a client (`api.use(stepUp(...))`) or to one request (`{ middleware:\n * [stepUp(passkeyConfirm(passkey))] }`).\n */\nexport function stepUp(confirm: ConfirmCallback): Middleware {\n return challengeAnswer<ConfirmChallenge>(412, 'CONFIRM_REQUIRED', async (challenge, request) => ({\n confirm: { challengeId: challenge.challengeId, assertion: await confirm(challenge, { request }) },\n }));\n}\n\n/**\n * The `428 OPERATOR_SIGNATURE_REQUIRED` operator signature: `sign` signs the\n * statement's `message` with the operator key and the same body goes again\n * with `operatorProof: { nonce, signature }`.\n */\nexport function operatorSignature(sign: OperatorProofCallback): Middleware {\n return challengeAnswer<OperatorStatement>(428, 'OPERATOR_SIGNATURE_REQUIRED', async (statement, request) => ({\n operatorProof: await sign(statement, { request }),\n }));\n}\n", "/**\n * What every generated method (`src/generated/methods.ts`, by\n * `scripts/gen-methods.mjs`) runs: one flattened argument object split back\n * into the route's path parameters, query and body, sent through the\n * generated `openapi-fetch` client, and its answer unwrapped (a refusal thrown\n * as the typed `CalimeroError`). The route types themselves all come from the\n * generated `operations`; nothing here names a route.\n */\n\nimport type { Middleware } from 'openapi-fetch';\n\nimport type { RouteClient } from './route-client.js';\nimport { unwrap } from './route-client.js';\nimport { operatorSignature, stepUp, type OperatorProofCallback } from './step-up.js';\nimport { type ConfirmCallback } from '../runtime/passkey.js';\n\n/** What a generated method takes beside its arguments. */\nexport interface MethodOptions {\n /**\n * Answers this request's `412 CONFIRM_REQUIRED` (say,\n * `passkeyConfirm(passkey)`), before the client's own `confirm`.\n */\n confirm?: ConfirmCallback;\n /** Answers this request's `428 OPERATOR_SIGNATURE_REQUIRED`, before the client's own `operatorProof`. */\n operatorProof?: OperatorProofCallback;\n /** Aborts the request (and a step-up's prompt, when `confirm` reads it). */\n signal?: AbortSignal;\n}\n\n/** A raw request body: the bytes as they are, sent with `contentType`. */\nexport interface RawBody {\n body: Uint8Array | ArrayBuffer | Blob | string;\n /** The body's media type. Default: the one the route documents. */\n contentType?: string;\n}\n\n/** How a generated method's arguments map onto its route (written by the generator). */\nexport interface RouteShape {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n path: string;\n /** Names of the path parameters. */\n pathParams: readonly string[];\n /** Names of the query parameters. */\n query: readonly string[];\n /** The query is `args.query` (a query parameter is named like a path parameter). */\n queryWhole?: boolean;\n /**\n * `fields`: the arguments other than the path and query are the JSON body;\n * `whole`: the JSON body is `args.body`; `raw`: `args.body` is sent as it is,\n * with `args.contentType` (or `media`); `none`: no body.\n */\n body: 'fields' | 'whole' | 'raw' | 'none';\n /** Whether the route takes no body at all as well (`fields`: an empty one is left out). */\n optionalBody: boolean;\n /** The raw body's documented media type. */\n media?: string;\n /** How the answer is read. */\n reply: 'json' | 'bytes' | 'text';\n /** The route answers `412 CONFIRM_REQUIRED` first (`x-calimero-step-up`). */\n stepUp?: boolean;\n /** The user verification its step-up asks the passkey for (`x-calimero-user-verification`). */\n userVerification?: 'required' | 'preferred' | 'discouraged';\n /** The route answers `428 OPERATOR_SIGNATURE_REQUIRED` first (`x-calimero-operator`). */\n operator?: boolean;\n}\n\n/** Send one generated route: split `args`, send it, answer its payload or throw its refusal. */\nexport async function route(\n api: RouteClient,\n shape: RouteShape,\n args: Record<string, unknown> | undefined,\n options: MethodOptions = {},\n): Promise<unknown> {\n const given = args ?? {};\n const path: Record<string, unknown> = {};\n const query: Record<string, unknown> = {};\n const rest: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(given)) {\n if (shape.pathParams.includes(name)) path[name] = value;\n else if (shape.queryWhole && name === 'query') Object.assign(query, value);\n else if (!shape.queryWhole && shape.query.includes(name)) query[name] = value;\n else rest[name] = value;\n }\n for (const name of shape.pathParams) {\n if (path[name] === undefined) throw new TypeError(`${shape.method} ${shape.path}: no value for ${name}`);\n }\n const init: Record<string, unknown> = { params: { path, query } };\n if (shape.body === 'fields') {\n const empty = Object.values(rest).every((value) => value === undefined);\n if (!(empty && shape.optionalBody)) init.body = rest;\n } else if (shape.body === 'whole') {\n if (rest.body !== undefined || !shape.optionalBody) init.body = rest.body;\n } else if (shape.body === 'raw') {\n init.body = rest.body;\n init.bodySerializer = (body: unknown) => body;\n init.headers = { 'Content-Type': (rest.contentType as string | undefined) ?? shape.media ?? 'application/octet-stream' };\n }\n if (shape.reply === 'bytes') init.parseAs = 'blob';\n else if (shape.reply === 'text') init.parseAs = 'text';\n const middleware: Middleware[] = [];\n if (options.confirm) {\n const confirm = options.confirm;\n // The route's own user verification, where the node's challenge names none\n // (a sign-up's confirmation takes `preferred`, every other step-up `required`).\n const answer: ConfirmCallback = shape.userVerification\n ? (challenge, context) => confirm({ userVerification: shape.userVerification, ...challenge }, context)\n : confirm;\n middleware.push(stepUp(answer));\n }\n if (options.operatorProof) middleware.push(operatorSignature(options.operatorProof));\n if (middleware.length) init.middleware = middleware;\n if (options.signal) init.signal = options.signal;\n // The shape was written from the same document as `api`'s types; the\n // generated method's own signature carries them.\n const send = api.request as unknown as (method: string, path: string, init: unknown) => ReturnType<RouteClient['GET']>;\n return unwrap(send(shape.method.toLowerCase(), shape.path, init));\n}\n", "// Generated by scripts/gen-methods.mjs from openapi/core-openapi.json (`pnpm gen:api`). Do not edit.\n//\n// One method per operation of the node's API, grouped by the operation's tag.\n// Each takes one argument object (path parameters, query and body fields\n// merged; the body under `body` when it is raw bytes or its fields would\n// collide) and answers the route's success payload; a refusal is thrown as the\n// typed `CalimeroError`. Event streams are not here: read them with\n// `transport.events`.\n// Streams left out: GET /apps/{app}/events, GET /apps/{app}/presence/stream.\n\nimport type { operations } from './api.js';\nimport type { RouteClient } from '../routes/route-client.js';\nimport { route, type MethodOptions, type RawBody } from '../routes/method.js';\n\n/** The generated methods, by group, sending through `api`. */\nexport function createRoutes(api: RouteClient) {\n return {\n apps: {\n /**\n * An app's ABI.\n *\n * `GET /apps/{app}/abi` (`app_abi`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n abi: (args: operations['app_abi']['parameters']['path'], options?: MethodOptions): Promise<operations['app_abi']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/abi\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_abi']['responses'][200]['content']['application/json']>,\n /**\n * Set who may reach an app.\n *\n * `POST /apps/{app}/access` (`app_access`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n access: (args: operations['app_access']['parameters']['path'] & operations['app_access']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_access']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/access\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_access']['responses'][200]['content']['application/json']>,\n /**\n * Every replica's receipt-key attestation.\n *\n * `GET /apps/{app}/attestation` (`app_attestation`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n attestation: (args: operations['app_attestation']['parameters']['path'] & NonNullable<operations['app_attestation']['parameters']['query']>, options?: MethodOptions): Promise<operations['app_attestation']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/attestation\",\"pathParams\":[\"app\"],\"query\":[\"nonce\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_attestation']['responses'][200]['content']['application/json']>,\n /**\n * Forget a blob.\n *\n * `DELETE /apps/{app}/blobs/{id}` (`blob_delete`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobDelete: (args: operations['blob_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}/blobs/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_delete']['responses'][200]['content']['application/json']>,\n /**\n * Download a blob.\n *\n * `GET /apps/{app}/blobs/{id}` (`blob_download`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobDownload: (args: operations['blob_download']['parameters']['path'] & NonNullable<operations['blob_download']['parameters']['query']>, options?: MethodOptions): Promise<Blob> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[\"grant\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"bytes\"}, args as unknown as Record<string, unknown>, options) as Promise<Blob>,\n /**\n * A blob's size.\n *\n * `GET /apps/{app}/blobs/{id}/info` (`blob_info`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobInfo: (args: operations['blob_info']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_info']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs/{id}/info\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_info']['responses'][200]['content']['application/json']>,\n /**\n * List an app's blobs.\n *\n * `GET /apps/{app}/blobs` (`blob_list`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobList: (args: operations['blob_list']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_list']['responses'][200]['content']['application/json']>,\n /**\n * Invalidate a blob's grants.\n *\n * `POST /apps/{app}/blobs/{id}/revoke` (`blob_revoke`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobRevoke: (args: operations['blob_revoke']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/blobs/{id}/revoke\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Upload a blob.\n *\n * `POST /apps/{app}/blobs` (`blob_upload`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobUpload: (args: operations['blob_upload']['parameters']['path'] & NonNullable<operations['blob_upload']['parameters']['query']> & RawBody, options?: MethodOptions): Promise<operations['blob_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/blobs\",\"pathParams\":[\"app\"],\"query\":[\"sealed\"],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_upload']['responses'][200]['content']['application/json']>,\n /**\n * Call a method.\n *\n * `POST /apps/{app}/intents` (`intents`). **Who:** whoever the app's access admits (a public app: anyone).\n * Answers `412 CONFIRM_REQUIRED` first when the method is a `confirm` method of the app's ABI: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Retried on `503` (D70), with its `idempotencyKey` (one is made when none is given).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n call: (args: operations['intents']['parameters']['path'] & operations['intents']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['intents']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/intents\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['intents']['responses'][200]['content']['application/json']>,\n /**\n * Create an app instance.\n *\n * `POST /apps` (`app_create`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['app_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['app_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete an app.\n *\n * `DELETE /apps/{app}` (`app_delete`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['app_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['app_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_delete']['responses'][200]['content']['application/json']>,\n /**\n * One sealed file.\n *\n * `GET /apps/{app}/files/{id}` (`file_info`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n fileInfo: (args: operations['file_info']['parameters']['path'], options?: MethodOptions): Promise<operations['file_info']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['file_info']['responses'][200]['content']['application/json']>,\n /**\n * List an app's sealed files.\n *\n * `GET /apps/{app}/files` (`files_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n filesList: (args: operations['files_list']['parameters']['path'], options?: MethodOptions): Promise<operations['files_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['files_list']['responses'][200]['content']['application/json']>,\n /**\n * Upload a sealed file.\n *\n * `POST /apps/{app}/files` (`files_upload`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n filesUpload: (args: operations['files_upload']['parameters']['path'] & RawBody, options?: MethodOptions): Promise<operations['files_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['files_upload']['responses'][200]['content']['application/json']>,\n /**\n * One app.\n *\n * `GET /apps/{app}` (`app_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['app_get']['parameters']['path'], options?: MethodOptions): Promise<operations['app_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_get']['responses'][200]['content']['application/json']>,\n /**\n * Apps the caller reaches.\n *\n * `GET /apps` (`app_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: NonNullable<operations['app_list']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['app_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps\",\"pathParams\":[],\"query\":[\"package\",\"bundle\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_list']['responses'][200]['content']['application/json']>,\n /**\n * Set an app's metadata.\n *\n * `POST /apps/{app}/metadata` (`app_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n metadata: (args: operations['app_metadata']['parameters']['path'] & operations['app_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/metadata\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Call a method by its path.\n *\n * `POST /apps/{app}/methods/{method}` (`app_method`). **Who:** whoever the app's access admits (a public app: anyone).\n * Answers `412 CONFIRM_REQUIRED` first when the method is a `confirm` method of the app's ABI: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Retried on `503` (D70), with its `idempotencyKey` (one is made when none is given).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n method: (args: operations['app_method']['parameters']['path'] & operations['app_method']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_method']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/methods/{method}\",\"pathParams\":[\"app\",\"method\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_method']['responses'][200]['content']['application/json']>,\n /**\n * Move an app to another organization.\n *\n * `POST /apps/{app}/move` (`app_move`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n move: (args: operations['app_move']['parameters']['path'] & operations['app_move']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_move']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/move\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_move']['responses'][200]['content']['application/json']>,\n /**\n * An app's OpenAPI document.\n *\n * `GET /apps/{app}/openapi.json` (`app_openapi`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n openapi: (args: operations['app_openapi']['parameters']['path'], options?: MethodOptions): Promise<operations['app_openapi']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/openapi.json\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_openapi']['responses'][200]['content']['application/json']>,\n /**\n * Who is present.\n *\n * `GET /apps/{app}/presence` (`presence_get`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n presenceGet: (args: operations['presence_get']['parameters']['path'], options?: MethodOptions): Promise<operations['presence_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/presence\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['presence_get']['responses'][200]['content']['application/json']>,\n /**\n * Publish presence.\n *\n * `POST /apps/{app}/presence` (`presence_publish`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n presencePublish: (args: operations['presence_publish']['parameters']['path'] & operations['presence_publish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['presence_publish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/presence\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['presence_publish']['responses'][200]['content']['application/json']>,\n /**\n * One compute run.\n *\n * `GET /apps/{app}/runs/{run}` (`app_run`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n run: (args: operations['app_run']['parameters']['path'], options?: MethodOptions): Promise<operations['app_run']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/runs/{run}\",\"pathParams\":[\"app\",\"run\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_run']['responses'][200]['content']['application/json']>,\n /**\n * An app's compute runs.\n *\n * `GET /apps/{app}/runs` (`app_runs`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n runs: (args: operations['app_runs']['parameters']['path'] & NonNullable<operations['app_runs']['parameters']['query']>, options?: MethodOptions): Promise<operations['app_runs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/runs\",\"pathParams\":[\"app\"],\"query\":[\"limit\",\"before\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_runs']['responses'][200]['content']['application/json']>,\n /**\n * What an app stores.\n *\n * `GET /apps/{app}/storage` (`app_storage`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n storage: (args: operations['app_storage']['parameters']['path'], options?: MethodOptions): Promise<operations['app_storage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/storage\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_storage']['responses'][200]['content']['application/json']>,\n /**\n * Hand an app to another account.\n *\n * `POST /apps/{app}/transfer` (`app_transfer`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n transfer: (args: operations['app_transfer']['parameters']['path'] & operations['app_transfer']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_transfer']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/transfer\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_transfer']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade an app instance.\n *\n * `POST /apps/{app}/upgrade` (`app_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgrade: (args: operations['app_upgrade']['parameters']['path'] & operations['app_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/upgrade\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Abort an upload.\n *\n * `DELETE /apps/{app}/files/uploads/{upload}` (`upload_abort`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadAbort: (args: operations['upload_abort']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_abort']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}/files/uploads/{upload}\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_abort']['responses'][200]['content']['application/json']>,\n /**\n * Begin a file upload.\n *\n * `POST /apps/{app}/files/uploads` (`upload_begin`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadBegin: (args: operations['upload_begin']['parameters']['path'] & operations['upload_begin']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['upload_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files/uploads\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_begin']['responses'][200]['content']['application/json']>,\n /**\n * Commit an upload.\n *\n * `POST /apps/{app}/files/uploads/{upload}/complete` (`upload_complete`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadComplete: (args: operations['upload_complete']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_complete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files/uploads/{upload}/complete\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_complete']['responses'][200]['content']['application/json']>,\n /**\n * Send one part.\n *\n * `PUT /apps/{app}/files/uploads/{upload}/parts/{k}` (`upload_part`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadPart: (args: operations['upload_part']['parameters']['path'] & RawBody, options?: MethodOptions): Promise<operations['upload_part']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"PUT\",\"path\":\"/apps/{app}/files/uploads/{upload}/parts/{k}\",\"pathParams\":[\"app\",\"upload\",\"k\"],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_part']['responses'][200]['content']['application/json']>,\n /**\n * Where an upload is.\n *\n * `GET /apps/{app}/files/uploads/{upload}` (`upload_status`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadStatus: (args: operations['upload_status']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files/uploads/{upload}\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_status']['responses'][200]['content']['application/json']>,\n /**\n * An app's runs per day.\n *\n * `GET /apps/{app}/usage` (`app_usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: operations['app_usage']['parameters']['path'], options?: MethodOptions): Promise<operations['app_usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/usage\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_usage']['responses'][200]['content']['application/json']>,\n /**\n * Read with a view method.\n *\n * `POST /apps/{app}/views` (`views`). **Who:** whoever the app's access admits (a public app: anyone).\n * Retried on `503` (D70).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n view: (args: operations['views']['parameters']['path'] & operations['views']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['views']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/views\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['views']['responses'][200]['content']['application/json']>,\n /**\n * An app's cross-app calls.\n *\n * `GET /apps/{app}/xcalls` (`app_xcalls`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n xcalls: (args: operations['app_xcalls']['parameters']['path'], options?: MethodOptions): Promise<operations['app_xcalls']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/xcalls\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_xcalls']['responses'][200]['content']['application/json']>,\n },\n auth: {\n /**\n * The account's own apps.\n *\n * `GET /auth/apps` (`account_apps`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountApps: (args: NonNullable<operations['account_apps']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['account_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/apps\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_apps']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes for the account's apps.\n *\n * `POST /auth/outbound` (`account_outbound_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountOutboundApproval: (args: operations['account_outbound_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_outbound_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/outbound\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_outbound_approval']['responses'][200]['content']['application/json']>,\n /**\n * Prove the account to another party.\n *\n * `POST /auth/account-proof` (`account_proof_prove`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountProofProve: (args: operations['account_proof_prove']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_proof_prove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/account-proof\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_proof_prove']['responses'][200]['content']['application/json']>,\n /**\n * Start an account recovery.\n *\n * `POST /auth/recovery/begin` (`account_recovery_begin`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryBegin: (args: operations['account_recovery_begin']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_recovery_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_begin']['responses'][200]['content']['application/json']>,\n /**\n * Cancel an account recovery.\n *\n * `POST /auth/recovery/cancel` (`account_recovery_cancel`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryCancel: (args: Partial<NonNullable<operations['account_recovery_cancel']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['account_recovery_cancel']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/cancel\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_cancel']['responses'][200]['content']['application/json']>,\n /**\n * Finish an account recovery.\n *\n * `POST /auth/recovery/finish` (`account_recovery_finish`). **Who:** anyone.\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryFinish: (args: operations['account_recovery_finish']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['account_recovery_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_finish']['responses'][200]['content']['application/json']>,\n /**\n * Spend the recovery code.\n *\n * `POST /auth/recovery/start` (`account_recovery_start`). **Who:** anyone.\n */\n accountRecoveryStart: (args: operations['account_recovery_start']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_recovery_start']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/start\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_start']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for the account's apps.\n *\n * `POST /auth/releases` (`account_release_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountReleaseApproval: (args: operations['account_release_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_release_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/releases\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_release_approval']['responses'][200]['content']['application/json']>,\n /**\n * What the account's passkeys did.\n *\n * `GET /auth/activity` (`activity_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n activityList: (args: NonNullable<operations['activity_list']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['activity_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/activity\",\"pathParams\":[],\"query\":[\"after\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['activity_list']['responses'][200]['content']['application/json']>,\n /**\n * Remove an alias.\n *\n * `DELETE /auth/aliases/{alias}` (`alias_delete`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasDelete: (args: operations['alias_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['alias_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_delete']['responses'][200]['content']['application/json']>,\n /**\n * Resolve an alias.\n *\n * `GET /auth/aliases/{alias}` (`alias_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasGet: (args: operations['alias_get']['parameters']['path'], options?: MethodOptions): Promise<operations['alias_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_get']['responses'][200]['content']['application/json']>,\n /**\n * The account's aliases.\n *\n * `GET /auth/aliases` (`alias_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['alias_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/aliases\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_list']['responses'][200]['content']['application/json']>,\n /**\n * Set an alias.\n *\n * `PUT /auth/aliases/{alias}` (`alias_set`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasSet: (args: operations['alias_set']['parameters']['path'] & operations['alias_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['alias_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"PUT\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_set']['responses'][200]['content']['application/json']>,\n /**\n * Make an API key.\n *\n * `POST /auth/apikeys` (`apikey_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyCreate: (args: operations['apikey_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['apikey_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/apikeys\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_create']['responses'][200]['content']['application/json']>,\n /**\n * The account's API keys.\n *\n * `GET /auth/apikeys` (`apikey_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['apikey_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/apikeys\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_list']['responses'][200]['content']['application/json']>,\n /**\n * Revoke an API key.\n *\n * `DELETE /auth/apikeys/{key}` (`apikey_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyRevoke: (args: operations['apikey_revoke']['parameters']['path'] & Partial<NonNullable<operations['apikey_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['apikey_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/apikeys/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Start a sign-in.\n *\n * `POST /auth/passkey/login/begin` (`login_begin`). **Who:** anyone.\n */\n loginBegin: (args: Partial<NonNullable<operations['login_begin']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['login_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/login/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['login_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish a sign-in.\n *\n * `POST /auth/passkey/login/finish` (`login_finish`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n loginFinish: (args: operations['login_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['login_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/login/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['login_finish']['responses'][200]['content']['application/json']>,\n /**\n * End this session.\n *\n * `POST /auth/logout` (`logout`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n logout: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['logout']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/logout\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['logout']['responses'][200]['content']['application/json']>,\n /**\n * End every session of the account.\n *\n * `POST /auth/logout-all` (`logout_all`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n logoutAll: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['logout_all']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/logout-all\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['logout_all']['responses'][200]['content']['application/json']>,\n /**\n * The caller's account.\n *\n * `GET /auth/me` (`me`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n me: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['me']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/me\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['me']['responses'][200]['content']['application/json']>,\n /**\n * Start adding a passkey.\n *\n * `POST /auth/passkeys/add/begin` (`passkey_add_begin`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyAddBegin: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['passkey_add_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/add/begin\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_add_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish adding a passkey.\n *\n * `POST /auth/passkeys/add/finish` (`passkey_add_finish`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyAddFinish: (args: operations['passkey_add_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['passkey_add_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/add/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_add_finish']['responses'][200]['content']['application/json']>,\n /**\n * Name a passkey.\n *\n * `POST /auth/passkeys/{cred}` (`passkey_label`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyLabel: (args: operations['passkey_label']['parameters']['path'] & operations['passkey_label']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['passkey_label']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/{cred}\",\"pathParams\":[\"cred\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_label']['responses'][200]['content']['application/json']>,\n /**\n * Remove a passkey.\n *\n * `DELETE /auth/passkeys/{cred}` (`passkey_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyRemove: (args: operations['passkey_remove']['parameters']['path'] & Partial<NonNullable<operations['passkey_remove']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['passkey_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/passkeys/{cred}\",\"pathParams\":[\"cred\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_remove']['responses'][200]['content']['application/json']>,\n /**\n * Make a recovery code.\n *\n * `POST /auth/recovery` (`recovery_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryCreate: (args: Partial<NonNullable<operations['recovery_create']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['recovery_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_create']['responses'][200]['content']['application/json']>,\n /**\n * Remove the recovery code.\n *\n * `DELETE /auth/recovery` (`recovery_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryRemove: (args: Partial<NonNullable<operations['recovery_remove']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['recovery_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/recovery\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_remove']['responses'][200]['content']['application/json']>,\n /**\n * Refresh a session.\n *\n * `POST /auth/refresh` (`refresh`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n refresh: (args: operations['refresh']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['refresh']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/refresh\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['refresh']['responses'][200]['content']['application/json']>,\n /**\n * Start a sign-up.\n *\n * `POST /auth/passkey/register/begin` (`register_begin`). **Who:** anyone.\n */\n registerBegin: (args: operations['register_begin']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['register_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/register/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['register_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish a sign-up.\n *\n * `POST /auth/passkey/register/finish` (`register_finish`). **Who:** anyone.\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `preferred`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n registerFinish: (args: operations['register_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['register_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/register/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"preferred\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['register_finish']['responses'][200]['content']['application/json']>,\n /**\n * End one session.\n *\n * `DELETE /auth/sessions/{session}` (`session_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n sessionRevoke: (args: operations['session_revoke']['parameters']['path'], options?: MethodOptions): Promise<operations['session_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/sessions/{session}\",\"pathParams\":[\"session\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['session_revoke']['responses'][200]['content']['application/json']>,\n /**\n * The account's live sessions.\n *\n * `GET /auth/sessions` (`sessions_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n sessionsList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sessions_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/sessions\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sessions_list']['responses'][200]['content']['application/json']>,\n /**\n * The account's usage against its quotas.\n *\n * `GET /auth/usage` (`usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/usage\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['usage']['responses'][200]['content']['application/json']>,\n },\n consent: {\n /**\n * Ask the account's owner to approve.\n *\n * `POST /consent/requests` (`consent_page_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n pageCreate: (args: { body: operations['consent_page_create']['requestBody']['content']['application/json'] }, options?: MethodOptions): Promise<operations['consent_page_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/consent/requests\",\"pathParams\":[],\"query\":[],\"body\":\"whole\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['consent_page_create']['responses'][200]['content']['application/json']>,\n /**\n * What became of a consent request.\n *\n * `GET /consent/{request}/result` (`consent_page_result`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n pageResult: (args: operations['consent_page_result']['parameters']['path'], options?: MethodOptions): Promise<operations['consent_page_result']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/consent/{request}/result\",\"pathParams\":[\"request\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['consent_page_result']['responses'][200]['content']['application/json']>,\n },\n deployments: {\n /**\n * Create a deployment.\n *\n * `POST /deployments` (`deployment_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['deployment_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployment_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployments\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete a deployment.\n *\n * `DELETE /deployments/{id}` (`deployment_delete`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['deployment_delete']['parameters']['path'] & Partial<NonNullable<operations['deployment_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployment_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployments/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_delete']['responses'][200]['content']['application/json']>,\n /**\n * Grant a deployer.\n *\n * `POST /deployers` (`deployer_grant`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerGrant: (args: operations['deployer_grant']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployer_grant']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_grant']['responses'][200]['content']['application/json']>,\n /**\n * The deployers.\n *\n * `GET /deployers` (`deployer_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['deployer_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_list']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer.\n *\n * `DELETE /deployers/{key}` (`deployer_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerRevoke: (args: operations['deployer_revoke']['parameters']['path'] & Partial<NonNullable<operations['deployer_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployer_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployers/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_revoke']['responses'][200]['content']['application/json']>,\n /**\n * One deployment.\n *\n * `GET /deployments/{id}` (`deployment_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['deployment_get']['parameters']['path'], options?: MethodOptions): Promise<operations['deployment_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_get']['responses'][200]['content']['application/json']>,\n /**\n * Deployments.\n *\n * `GET /deployments` (`deployment_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['deployment_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_list']['responses'][200]['content']['application/json']>,\n /**\n * Offer a release in a deployment.\n *\n * `POST /deployments/{id}/apps` (`deployment_offer`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n offer: (args: operations['deployment_offer']['parameters']['path'] & operations['deployment_offer']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployment_offer']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployments/{id}/apps\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_offer']['responses'][200]['content']['application/json']>,\n /**\n * The organizations a deployment serves.\n *\n * `GET /deployments/{id}/orgs` (`deployment_orgs`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n orgs: (args: operations['deployment_orgs']['parameters']['path'], options?: MethodOptions): Promise<operations['deployment_orgs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments/{id}/orgs\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_orgs']['responses'][200]['content']['application/json']>,\n /**\n * Issue a cluster sign-up invite.\n *\n * `POST /sign-up/invites` (`sign_up_invite_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteCreate: (args: operations['sign_up_invite_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['sign_up_invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_create']['responses'][200]['content']['application/json']>,\n /**\n * Cluster sign-up invites.\n *\n * `GET /sign-up/invites` (`sign_up_invite_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sign_up_invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite.\n *\n * `DELETE /sign-up/invites/{key}` (`sign_up_invite_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteRevoke: (args: operations['sign_up_invite_revoke']['parameters']['path'] & Partial<NonNullable<operations['sign_up_invite_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['sign_up_invite_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/sign-up/invites/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_revoke']['responses'][200]['content']['application/json']>,\n /**\n * The sign-up policy.\n *\n * `GET /sign-up` (`sign_up_public`). **Who:** anyone.\n */\n signUpPublic: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sign_up_public']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_public']['responses'][200]['content']['application/json']>,\n /**\n * Set the sign-up policy.\n *\n * `POST /sign-up` (`sign_up_set`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpSet: (args: operations['sign_up_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['sign_up_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_set']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw an offer.\n *\n * `DELETE /deployments/{id}/apps/{app}` (`deployment_withdraw`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n withdraw: (args: operations['deployment_withdraw']['parameters']['path'] & Partial<NonNullable<operations['deployment_withdraw']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployment_withdraw']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployments/{id}/apps/{app}\",\"pathParams\":[\"id\",\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_withdraw']['responses'][200]['content']['application/json']>,\n },\n ops: {\n /**\n * What each app runs.\n *\n * `GET /ops/apps` (`ops_apps`). **Who:** the ops token.\n */\n apps: (args: NonNullable<operations['ops_apps']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/apps\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_apps']['responses'][200]['content']['application/json']>,\n /**\n * Snapshot the apps this node leads.\n *\n * `POST /ops/backup` (`ops_backup`). **Who:** the ops token.\n */\n backup: (args: NonNullable<operations['ops_backup']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_backup']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/backup\",\"pathParams\":[],\"query\":[\"all\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_backup']['responses'][200]['content']['application/json']>,\n /**\n * The cluster's identity.\n *\n * `GET /ops/cluster` (`ops_cluster`). **Who:** the ops token.\n */\n cluster: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_cluster']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/cluster\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_cluster']['responses'][200]['content']['application/json']>,\n /**\n * Name the cluster's owner.\n *\n * `POST /ops/cluster-owner` (`ops_cluster_owner`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n clusterOwner: (args: operations['ops_cluster_owner']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_cluster_owner']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/cluster-owner\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_cluster_owner']['responses'][200]['content']['application/json']>,\n /**\n * Grant a deployer.\n *\n * `POST /ops/deployers` (`ops_deployer_grant`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerGrant: (args: operations['ops_deployer_grant']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_deployer_grant']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_grant']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer.\n *\n * `DELETE /ops/deployers/{key}` (`ops_deployer_revoke_delete`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerRevokeDelete: (args: operations['ops_deployer_revoke_delete']['parameters']['path'] & Partial<NonNullable<operations['ops_deployer_revoke_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_deployer_revoke_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/deployers/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_revoke_delete']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer (POST).\n *\n * `POST /ops/deployers/{key}/revoke` (`ops_deployer_revoke_post`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerRevokePost: (args: operations['ops_deployer_revoke_post']['parameters']['path'] & Partial<NonNullable<operations['ops_deployer_revoke_post']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_deployer_revoke_post']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployers/{key}/revoke\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_revoke_post']['responses'][200]['content']['application/json']>,\n /**\n * Require deployer grants.\n *\n * `POST /ops/deployments/granted` (`ops_deployments_granted`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deploymentsGranted: (args: Partial<NonNullable<operations['ops_deployments_granted']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['ops_deployments_granted']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployments/granted\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployments_granted']['responses'][200]['content']['application/json']>,\n /**\n * Prometheus metrics.\n *\n * `GET /ops/metrics` (`ops_metrics`). **Who:** the ops token.\n */\n metrics: (args: Record<string, never> = {}, options?: MethodOptions): Promise<string> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/metrics\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"text\"}, args as unknown as Record<string, unknown>, options) as Promise<string>,\n /**\n * Each organization's approved releases.\n *\n * `GET /ops/orgs` (`ops_orgs`). **Who:** the ops token.\n */\n orgs: (args: NonNullable<operations['ops_orgs']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_orgs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/orgs\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_orgs']['responses'][200]['content']['application/json']>,\n /**\n * An operator's upgrade run.\n *\n * `POST /ops/orgs/{org}/upgrade` (`ops_org_upgrade`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n orgUpgrade: (args: operations['ops_org_upgrade']['parameters']['path'] & operations['ops_org_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_org_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/orgs/{org}/upgrade\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_org_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes.\n *\n * `POST /ops/outbound` (`ops_outbound`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n outbound: (args: operations['ops_outbound']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_outbound']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/outbound\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_outbound']['responses'][200]['content']['application/json']>,\n /**\n * Install a release from the registry as the operator.\n *\n * `POST /ops/packages/install` (`ops_package_install`). **Who:** the ops token.\n */\n packageInstall: (args: operations['ops_package_install']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_package_install']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/packages/install\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_install']['responses'][200]['content']['application/json']>,\n /**\n * The releases the operator installed.\n *\n * `GET /ops/packages` (`ops_package_list`). **Who:** the ops token.\n */\n packageList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_package_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/packages\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_list']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall what the operator installed.\n *\n * `DELETE /ops/packages/{package}` (`ops_package_uninstall`). **Who:** the ops token.\n */\n packageUninstall: (args: operations['ops_package_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_package_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Install an uploaded release as the operator.\n *\n * `POST /ops/packages` (`ops_package_upload`). **Who:** the ops token.\n */\n packageUpload: (args: RawBody, options?: MethodOptions): Promise<operations['ops_package_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/packages\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_upload']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall one operator-installed version.\n *\n * `DELETE /ops/packages/{package}/{version}` (`ops_package_version_uninstall`). **Who:** the ops token.\n */\n packageVersionUninstall: (args: operations['ops_package_version_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_package_version_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/packages/{package}/{version}\",\"pathParams\":[\"package\",\"version\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_version_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Where every app's replicas are.\n *\n * `GET /ops/placement` (`ops_placement`). **Who:** the ops token.\n */\n placement: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_placement']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/placement\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_placement']['responses'][200]['content']['application/json']>,\n /**\n * Compute pools.\n *\n * `GET /ops/pools` (`ops_pools_get`). **Who:** the ops token.\n */\n poolsGet: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_pools_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/pools\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_pools_get']['responses'][200]['content']['application/json']>,\n /**\n * Set the compute pools.\n *\n * `POST /ops/pools` (`ops_pools_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n poolsSet: (args: operations['ops_pools_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_pools_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/pools\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_pools_set']['responses'][200]['content']['application/json']>,\n /**\n * The quotas.\n *\n * `GET /ops/quotas` (`ops_quotas_get`). **Who:** the ops token.\n */\n quotasGet: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_quotas_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/quotas\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_quotas_get']['responses'][200]['content']['application/json']>,\n /**\n * Change quotas.\n *\n * `POST /ops/quotas` (`ops_quotas_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n quotasSet: (args: operations['ops_quotas_set']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['ops_quotas_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/quotas\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_quotas_set']['responses'][200]['content']['application/json']>,\n /**\n * A node's receipt key.\n *\n * `GET /ops/nodes/{id}/receipt-key` (`ops_receipt_key`). **Who:** the ops token.\n */\n receiptKey: (args: operations['ops_receipt_key']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_receipt_key']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/nodes/{id}/receipt-key\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_receipt_key']['responses'][200]['content']['application/json']>,\n /**\n * Register a node.\n *\n * `POST /ops/nodes` (`ops_register_node`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n registerNode: (args: operations['ops_register_node']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_register_node']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/nodes\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_register_node']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for every app.\n *\n * `POST /ops/releases` (`ops_release`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n release: (args: operations['ops_release']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_release']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/releases\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release']['responses'][200]['content']['application/json']>,\n /**\n * Set a release deadline.\n *\n * `POST /ops/releases/{version}/deadline` (`ops_release_deadline`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n releaseDeadline: (args: operations['ops_release_deadline']['parameters']['path'] & operations['ops_release_deadline']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_release_deadline']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/releases/{version}/deadline\",\"pathParams\":[\"version\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release_deadline']['responses'][200]['content']['application/json']>,\n /**\n * Lift a release deadline.\n *\n * `DELETE /ops/releases/{version}/deadline` (`ops_release_deadline_lift`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n releaseDeadlineLift: (args: operations['ops_release_deadline_lift']['parameters']['path'] & Partial<NonNullable<operations['ops_release_deadline_lift']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_release_deadline_lift']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/releases/{version}/deadline\",\"pathParams\":[\"version\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release_deadline_lift']['responses'][200]['content']['application/json']>,\n /**\n * Remove a node.\n *\n * `DELETE /ops/nodes/{id}` (`ops_remove_node`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n removeNode: (args: operations['ops_remove_node']['parameters']['path'] & Partial<NonNullable<operations['ops_remove_node']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_remove_node']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/nodes/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_remove_node']['responses'][200]['content']['application/json']>,\n /**\n * Restore an app from its sealed backup.\n *\n * `POST /ops/apps/{app}/restore` (`ops_restore`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n restore: (args: operations['ops_restore']['parameters']['path'] & operations['ops_restore']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_restore']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/restore\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_restore']['responses'][200]['content']['application/json']>,\n /**\n * Custom domains to serve.\n *\n * `GET /ops/served-origins` (`ops_served`). **Who:** the ops token.\n */\n served: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_served']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/served-origins\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_served']['responses'][200]['content']['application/json']>,\n /**\n * Move an app's replicas.\n *\n * `POST /ops/apps/{app}/replicas` (`ops_set_replicas`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n setReplicas: (args: operations['ops_set_replicas']['parameters']['path'] & operations['ops_set_replicas']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_set_replicas']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/replicas\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_set_replicas']['responses'][200]['content']['application/json']>,\n /**\n * Issue a cluster sign-up invite.\n *\n * `POST /ops/sign-up/invites` (`ops_sign_up_invite_create`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteCreate: (args: operations['ops_sign_up_invite_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_sign_up_invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_create']['responses'][200]['content']['application/json']>,\n /**\n * Cluster sign-up invites.\n *\n * `GET /ops/sign-up/invites` (`ops_sign_up_invite_list`). **Who:** the ops token.\n */\n signUpInviteList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_sign_up_invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite.\n *\n * `DELETE /ops/sign-up/invites/{key}` (`ops_sign_up_invite_revoke_delete`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteRevokeDelete: (args: operations['ops_sign_up_invite_revoke_delete']['parameters']['path'] & Partial<NonNullable<operations['ops_sign_up_invite_revoke_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_sign_up_invite_revoke_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/sign-up/invites/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_revoke_delete']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite (POST).\n *\n * `POST /ops/sign-up/invites/{key}/revoke` (`ops_sign_up_invite_revoke_post`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteRevokePost: (args: operations['ops_sign_up_invite_revoke_post']['parameters']['path'] & Partial<NonNullable<operations['ops_sign_up_invite_revoke_post']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_sign_up_invite_revoke_post']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up/invites/{key}/revoke\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_revoke_post']['responses'][200]['content']['application/json']>,\n /**\n * Set the sign-up policy.\n *\n * `POST /ops/sign-up` (`ops_sign_up_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpSet: (args: operations['ops_sign_up_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_sign_up_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_set']['responses'][200]['content']['application/json']>,\n /**\n * The node and the cluster.\n *\n * `GET /ops/status` (`ops_status`). **Who:** the ops token.\n */\n status: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/status\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_status']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade an app as the operator.\n *\n * `POST /ops/apps/{app}/upgrade` (`ops_upgrade`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n upgrade: (args: operations['ops_upgrade']['parameters']['path'] & operations['ops_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/upgrade\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_upgrade']['responses'][200]['content']['application/json']>,\n },\n orgs: {\n /**\n * Give a member every app added later.\n *\n * `POST /orgs/{org}/all-apps` (`org_all_apps`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n allApps: (args: operations['org_all_apps']['parameters']['path'] & operations['org_all_apps']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_all_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/all-apps\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_all_apps']['responses'][200]['content']['application/json']>,\n /**\n * The organization's apps.\n *\n * `GET /orgs/{org}/apps` (`org_apps`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apps: (args: operations['org_apps']['parameters']['path'] & NonNullable<operations['org_apps']['parameters']['query']>, options?: MethodOptions): Promise<operations['org_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/apps\",\"pathParams\":[\"org\"],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_apps']['responses'][200]['content']['application/json']>,\n /**\n * The organization's app teams.\n *\n * `GET /orgs/{org}/app-teams` (`app_team_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n appTeamList: (args: operations['app_team_list']['parameters']['path'], options?: MethodOptions): Promise<operations['app_team_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/app-teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_team_list']['responses'][200]['content']['application/json']>,\n /**\n * Give apps app teams, or open or close one.\n *\n * `POST /orgs/{org}/app-teams` (`app_teams_scope`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n appTeamsScope: (args: operations['app_teams_scope']['parameters']['path'] & operations['app_teams_scope']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_teams_scope']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/app-teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_teams_scope']['responses'][200]['content']['application/json']>,\n /**\n * Set capabilities.\n *\n * `POST /orgs/{org}/capabilities` (`org_capabilities`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n capabilities: (args: operations['org_capabilities']['parameters']['path'] & operations['org_capabilities']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_capabilities']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/capabilities\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_capabilities']['responses'][200]['content']['application/json']>,\n /**\n * Create an organization.\n *\n * `POST /orgs` (`org_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['org_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete an organization.\n *\n * `DELETE /orgs/{org}` (`org_delete`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['org_delete']['parameters']['path'] & Partial<NonNullable<operations['org_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_delete']['responses'][200]['content']['application/json']>,\n /**\n * One organization.\n *\n * `GET /orgs/{org}` (`org_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['org_get']['parameters']['path'], options?: MethodOptions): Promise<operations['org_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_get']['responses'][200]['content']['application/json']>,\n /**\n * Make an invite.\n *\n * `POST /orgs/{org}/invites` (`invite_create`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteCreate: (args: operations['invite_create']['parameters']['path'] & operations['invite_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/invites\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_create']['responses'][200]['content']['application/json']>,\n /**\n * The organization's invites.\n *\n * `GET /orgs/{org}/invites` (`invite_list`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteList: (args: operations['invite_list']['parameters']['path'], options?: MethodOptions): Promise<operations['invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/invites\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Join with an invite.\n *\n * `POST /invites/{token}/redeem` (`invite_redeem`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteRedeem: (args: operations['invite_redeem']['parameters']['path'], options?: MethodOptions): Promise<operations['invite_redeem']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/invites/{token}/redeem\",\"pathParams\":[\"token\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_redeem']['responses'][200]['content']['application/json']>,\n /**\n * Revoke an invite.\n *\n * `DELETE /orgs/{org}/invites/{key}` (`invite_revoke`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteRevoke: (args: operations['invite_revoke']['parameters']['path'] & Partial<NonNullable<operations['invite_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['invite_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/invites/{key}\",\"pathParams\":[\"org\",\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's metadata.\n *\n * `POST /orgs/{org}/members/{account}/metadata` (`member_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberMetadata: (args: operations['member_metadata']['parameters']['path'] & operations['member_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members/{account}/metadata\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Remove a member from several teams, or leave them.\n *\n * `DELETE /orgs/{org}/members/{account}/teams` (`member_remove_teams`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberRemoveTeams: (args: operations['member_remove_teams']['parameters']['path'] & operations['member_remove_teams']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_remove_teams']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/members/{account}/teams\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_remove_teams']['responses'][200]['content']['application/json']>,\n /**\n * Members' lockout risk.\n *\n * `GET /orgs/{org}/members` (`org_members`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n members: (args: operations['org_members']['parameters']['path'] & NonNullable<operations['org_members']['parameters']['query']>, options?: MethodOptions): Promise<operations['org_members']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/members\",\"pathParams\":[\"org\"],\"query\":[\"detail\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_members']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's rows in several teams.\n *\n * `POST /orgs/{org}/members/{account}/teams` (`member_set_teams`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberSetTeams: (args: operations['member_set_teams']['parameters']['path'] & operations['member_set_teams']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_set_teams']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members/{account}/teams\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_set_teams']['responses'][200]['content']['application/json']>,\n /**\n * Set an organization's metadata.\n *\n * `POST /orgs/{org}/metadata` (`org_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n metadata: (args: operations['org_metadata']['parameters']['path'] & operations['org_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/metadata\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes for the organization's apps.\n *\n * `POST /orgs/{org}/outbound` (`org_outbound_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n outboundApproval: (args: operations['org_outbound_approval']['parameters']['path'] & operations['org_outbound_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_outbound_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/outbound\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_outbound_approval']['responses'][200]['content']['application/json']>,\n /**\n * Bind a package signing key.\n *\n * `POST /orgs/{org}/publishers` (`org_publisher`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisher: (args: operations['org_publisher']['parameters']['path'] & operations['org_publisher']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_publisher']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/publishers\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_publisher']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade every instance of a publisher's package.\n *\n * `POST /orgs/{org}/packages/{package}/upgrade` (`publisher_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisherUpgrade: (args: operations['publisher_upgrade']['parameters']['path'] & operations['publisher_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['publisher_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/packages/{package}/upgrade\",\"pathParams\":[\"org\",\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['publisher_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Cancel an organization recovery.\n *\n * `POST /orgs/{org}/recovery/cancel` (`recovery_cancel`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryCancel: (args: operations['recovery_cancel']['parameters']['path'] & Partial<NonNullable<operations['recovery_cancel']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['recovery_cancel']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/cancel\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_cancel']['responses'][200]['content']['application/json']>,\n /**\n * Finish an organization recovery.\n *\n * `POST /orgs/{org}/recovery/finish` (`recovery_finish`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryFinish: (args: operations['recovery_finish']['parameters']['path'] & Partial<NonNullable<operations['recovery_finish']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['recovery_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/finish\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_finish']['responses'][200]['content']['application/json']>,\n /**\n * Set the organization's recovery key.\n *\n * `POST /orgs/{org}/recovery` (`recovery_set`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoverySet: (args: operations['recovery_set']['parameters']['path'] & operations['recovery_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['recovery_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_set']['responses'][200]['content']['application/json']>,\n /**\n * Start an organization recovery.\n *\n * `POST /orgs/{org}/recovery/start` (`recovery_start`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryStart: (args: operations['recovery_start']['parameters']['path'] & operations['recovery_start']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['recovery_start']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/start\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_start']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for the organization's apps.\n *\n * `POST /orgs/{org}/releases` (`org_release_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n releaseApproval: (args: operations['org_release_approval']['parameters']['path'] & operations['org_release_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_release_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/releases\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_release_approval']['responses'][200]['content']['application/json']>,\n /**\n * Remove a member, or leave.\n *\n * `DELETE /orgs/{org}/members/{account}` (`org_remove_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n removeMember: (args: operations['org_remove_member']['parameters']['path'] & Partial<NonNullable<operations['org_remove_member']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_remove_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/members/{account}\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_remove_member']['responses'][200]['content']['application/json']>,\n /**\n * Rename an organization.\n *\n * `POST /orgs/{org}/name` (`org_rename`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n rename: (args: operations['org_rename']['parameters']['path'] & operations['org_rename']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_rename']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/name\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_rename']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's role.\n *\n * `POST /orgs/{org}/members` (`org_set_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n setMember: (args: operations['org_set_member']['parameters']['path'] & operations['org_set_member']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_set_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_set_member']['responses'][200]['content']['application/json']>,\n /**\n * Create a team.\n *\n * `POST /orgs/{org}/teams` (`team_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamCreate: (args: operations['team_create']['parameters']['path'] & operations['team_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete a team.\n *\n * `DELETE /orgs/{org}/teams/{team}` (`team_delete`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamDelete: (args: operations['team_delete']['parameters']['path'] & Partial<NonNullable<operations['team_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['team_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_delete']['responses'][200]['content']['application/json']>,\n /**\n * One team.\n *\n * `GET /orgs/{org}/teams/{team}` (`team_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamGet: (args: operations['team_get']['parameters']['path'], options?: MethodOptions): Promise<operations['team_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_get']['responses'][200]['content']['application/json']>,\n /**\n * Remove a team member, or leave.\n *\n * `DELETE /orgs/{org}/teams/{team}/members/{account}` (`team_remove_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamRemoveMember: (args: operations['team_remove_member']['parameters']['path'] & Partial<NonNullable<operations['team_remove_member']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['team_remove_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/teams/{team}/members/{account}\",\"pathParams\":[\"org\",\"team\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_remove_member']['responses'][200]['content']['application/json']>,\n /**\n * Add or change a team member.\n *\n * `POST /orgs/{org}/teams/{team}/members` (`team_set_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamSetMember: (args: operations['team_set_member']['parameters']['path'] & operations['team_set_member']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_set_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams/{team}/members\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_set_member']['responses'][200]['content']['application/json']>,\n /**\n * Update a team.\n *\n * `POST /orgs/{org}/teams/{team}` (`team_update`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamUpdate: (args: operations['team_update']['parameters']['path'] & operations['team_update']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_update']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_update']['responses'][200]['content']['application/json']>,\n /**\n * Start an upgrade run.\n *\n * `POST /orgs/{org}/upgrade` (`org_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgrade: (args: operations['org_upgrade']['parameters']['path'] & operations['org_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/upgrade\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Retry an upgrade run's failed apps.\n *\n * `POST /orgs/{org}/upgrades/{run}/retry` (`org_upgrade_retry`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgradeRetry: (args: operations['org_upgrade_retry']['parameters']['path'] & Partial<NonNullable<operations['org_upgrade_retry']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_upgrade_retry']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/upgrades/{run}/retry\",\"pathParams\":[\"org\",\"run\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade_retry']['responses'][200]['content']['application/json']>,\n /**\n * An upgrade run's progress.\n *\n * `GET /orgs/{org}/upgrades/{run}` (`org_upgrade_status`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgradeStatus: (args: operations['org_upgrade_status']['parameters']['path'], options?: MethodOptions): Promise<operations['org_upgrade_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/upgrades/{run}\",\"pathParams\":[\"org\",\"run\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade_status']['responses'][200]['content']['application/json']>,\n /**\n * An organization's usage.\n *\n * `GET /orgs/{org}/usage` (`org_usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: operations['org_usage']['parameters']['path'], options?: MethodOptions): Promise<operations['org_usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/usage\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_usage']['responses'][200]['content']['application/json']>,\n },\n packages: {\n /**\n * Upload a raw component.\n *\n * `POST /bundles` (`bundle_put`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n bundlePut: (args: RawBody, options?: MethodOptions): Promise<operations['bundle_put']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/bundles\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/wasm\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['bundle_put']['responses'][200]['content']['application/json']>,\n /**\n * One package.\n *\n * `GET /packages/{package}` (`package_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['package_get']['parameters']['path'], options?: MethodOptions): Promise<operations['package_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_get']['responses'][200]['content']['application/json']>,\n /**\n * Install a release from the registry.\n *\n * `POST /packages/install` (`package_install`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n install: (args: operations['package_install']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['package_install']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/packages/install\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_install']['responses'][200]['content']['application/json']>,\n /**\n * Installed packages.\n *\n * `GET /packages` (`package_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['package_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/packages\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_list']['responses'][200]['content']['application/json']>,\n /**\n * Register a frontend origin.\n *\n * `POST /package-origins/{package}` (`origins_add`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsAdd: (args: operations['origins_add']['parameters']['path'] & operations['origins_add']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['origins_add']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_add']['responses'][200]['content']['application/json']>,\n /**\n * A package's frontend origins.\n *\n * `GET /package-origins/{package}` (`origins_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsList: (args: operations['origins_list']['parameters']['path'], options?: MethodOptions): Promise<operations['origins_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_list']['responses'][200]['content']['application/json']>,\n /**\n * Remove a frontend origin.\n *\n * `DELETE /package-origins/{package}` (`origins_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsRemove: (args: operations['origins_remove']['parameters']['path'] & operations['origins_remove']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['origins_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_remove']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall a package.\n *\n * `DELETE /packages/{package}` (`package_uninstall`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uninstall: (args: operations['package_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['package_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Upload a signed release.\n *\n * `POST /packages` (`package_upload`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upload: (args: RawBody, options?: MethodOptions): Promise<operations['package_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/packages\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_upload']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall one version.\n *\n * `DELETE /packages/{package}/{version}` (`package_version_uninstall`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n versionUninstall: (args: operations['package_version_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['package_version_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/packages/{package}/{version}\",\"pathParams\":[\"package\",\"version\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_version_uninstall']['responses'][200]['content']['application/json']>,\n },\n public: {\n /**\n * The node's attestation.\n *\n * `GET /attestation` (`attestation`). **Who:** anyone.\n */\n attestation: (args: NonNullable<operations['attestation']['parameters']['query']>, options?: MethodOptions): Promise<operations['attestation']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/attestation\",\"pathParams\":[],\"query\":[\"nonce\",\"app\",\"appHash\",\"purpose\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['attestation']['responses'][200]['content']['application/json']>,\n /**\n * Node health.\n *\n * `GET /health` (`health`). **Who:** anyone.\n */\n health: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['health']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/health\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['health']['responses'][200]['content']['application/json']>,\n /**\n * Whether a signing key is bound.\n *\n * `GET /publishers/{signer}` (`publisher_binding`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisherBinding: (args: operations['publisher_binding']['parameters']['path'], options?: MethodOptions): Promise<operations['publisher_binding']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/publishers/{signer}\",\"pathParams\":[\"signer\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['publisher_binding']['responses'][200]['content']['application/json']>,\n /**\n * The cluster's releases.\n *\n * `GET /releases` (`releases_public`). **Who:** anyone.\n */\n releasesPublic: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['releases_public']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/releases\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['releases_public']['responses'][200]['content']['application/json']>,\n },\n };\n}\n\n/**\n * The routes the document marks `x-calimero-retry-safe`: the transport sends them again on a `503`\n * (D70), and one that `requires` an `idempotencyKey` is given one before it is first sent.\n */\nexport const RETRY_SAFE_ROUTES: ReadonlyArray<{ method: string; path: string; requires?: string }> = [{\"method\":\"POST\",\"path\":\"/apps/{app}/intents\",\"requires\":\"idempotencyKey\"},{\"method\":\"POST\",\"path\":\"/apps/{app}/methods/{method}\",\"requires\":\"idempotencyKey\"},{\"method\":\"POST\",\"path\":\"/apps/{app}/views\"}];\n\n/** Every generated group. */\nexport type Routes = ReturnType<typeof createRoutes>;\n/** The `apps` methods. */\nexport type AppsRoutes = Routes['apps'];\n/** The `auth` methods. */\nexport type AuthRoutes = Routes['auth'];\n/** The `consent` methods. */\nexport type ConsentRoutes = Routes['consent'];\n/** The `deployments` methods. */\nexport type DeploymentsRoutes = Routes['deployments'];\n/** The `ops` methods. */\nexport type OpsRoutes = Routes['ops'];\n/** The `orgs` methods. */\nexport type OrgsRoutes = Routes['orgs'];\n/** The `packages` methods. */\nexport type PackagesRoutes = Routes['packages'];\n/** The `public` methods. */\nexport type PublicRoutes = Routes['public'];\n", "/**\n * The node's routes as a typed client, generated from core's OpenAPI document\n * (`openapi/core-openapi.json`, types in `src/generated/api.ts` by\n * `pnpm gen:api`), run by `openapi-fetch` over this package's runtime:\n *\n * - its `fetch` is {@link transportFetch}: every request goes through a\n * {@link NodeTransport}, so it is sealed to an attested node, carries the\n * transport's credential (refreshed on a `401`), moves on past a\n * `421 WRONG_NODE`, and a route the document marks retry-safe retries a\n * `503` (D70); the two\n * routes a node serves in the clear (`/attestation`, `/health`) go\n * unsealed, without the credential;\n * - the `412 CONFIRM_REQUIRED` step-up and the `428\n * OPERATOR_SIGNATURE_REQUIRED` operator signature are middleware\n * (`./step-up.ts`), for the whole client or one request.\n *\n * A node's refusal is the `error` of the result (`{ status, error, message,\n * details? }`), typed per route; {@link unwrap} throws it as the typed\n * {@link CalimeroError} instead. A transport failure (the node unreachable,\n * an attestation the policy refuses, an envelope past the sealed cap) rejects.\n * Streams (`GET /apps/{app}/events`, `/presence/stream`) are not routes of this\n * client: read them with `transport.events`.\n */\n\nimport createClient, { type Client, type Middleware } from 'openapi-fetch';\n\nimport type { paths } from '../generated/api.js';\nimport { errorFrom, type CalimeroError } from '../runtime/errors.js';\nimport { newIdempotencyKey, type HttpMethod, type NodeTransport, type QueryValue } from '../runtime/transport.js';\nimport { operatorSignature, stepUp, type OperatorProofCallback } from './step-up.js';\nimport { type ConfirmCallback } from '../runtime/passkey.js';\nimport { RETRY_SAFE_ROUTES } from '../generated/methods.js';\n\n/** The typed client of every route of a Calimero node. */\nexport type RouteClient = Client<paths, 'application/json'>;\n\n/** The node's API, path by path (the generated `paths`). */\nexport type { paths as ApiPaths } from '../generated/api.js';\n\n/**\n * The base URL the generated client builds request URLs on. It names no\n * node: {@link transportFetch} sends the path and query to the node the\n * transport uses now.\n */\nexport const ROUTE_BASE_URL = 'https://calimero-node.invalid';\n\n/** What {@link createRouteClient} sends through: a {@link NodeTransport}, or anything that answers like its `exchange`. */\nexport interface RouteTransport {\n exchange: NodeTransport['exchange'];\n /** `GET` of a route the node serves in the clear; without it those go sealed too. */\n inTheClear?: NodeTransport['inTheClear'];\n}\n\n/**\n * The routes a node serves outside the sealed channel (the document's\n * `x-calimero-sealed: false`): `GET /attestation` and `GET /health`.\n */\nconst IN_THE_CLEAR = new Set(['attestation', 'health']);\n\n/** How {@link createRouteClient} answers the node's challenges for every request. */\nexport interface RouteClientOptions {\n /**\n * Answers every `412 CONFIRM_REQUIRED` (say, `passkeyConfirm(browserPasskey())`).\n * A request's own `stepUp` middleware answers first.\n */\n confirm?: ConfirmCallback;\n /** Answers every `428 OPERATOR_SIGNATURE_REQUIRED` with the operator key's signature. */\n operatorProof?: OperatorProofCallback;\n}\n\n/**\n * The routes a `503` is retried on (D70): those the document marks\n * `x-calimero-retry-safe` (a call, a view, a method by its path), each\n * carrying its idempotency key or reading. As path patterns, without the\n * leading `/`.\n */\nconst RETRIED = RETRY_SAFE_ROUTES.map((route) => ({\n method: route.method,\n pattern: new RegExp(`^${route.path.replace(/^\\//, '').replace(/\\{[^}]+\\}/g, '[^/]+')}$`),\n}));\n\n/** The route templates that must carry an `idempotencyKey` to be retried. */\nconst NEEDS_KEY = new Set(RETRY_SAFE_ROUTES.filter((r) => r.requires === 'idempotencyKey').map((r) => `${r.method} ${r.path}`));\n\n/**\n * A `fetch` that sends `openapi-fetch`'s request through `transport`: the\n * path and query after {@link ROUTE_BASE_URL}, the body as it was serialised,\n * and the request's signal. Headers other than `content-type` are not sent:\n * the transport sets the credential. A call or a view is retried as D70 says\n * (its confirmed attempt, carrying `confirm`, exactly once).\n */\nexport function transportFetch(transport: RouteTransport): (request: Request) => Promise<Response> {\n return async (request) => {\n if (!request.url.startsWith(`${ROUTE_BASE_URL}/`)) {\n throw new Error(`not a route of the generated client: ${request.url}`);\n }\n const url = new URL(request.url);\n const path = url.pathname.replace(/^\\/+/, '');\n const query: Record<string, QueryValue[]> = {};\n for (const [name, value] of url.searchParams) (query[name] ??= []).push(value);\n const method = request.method as HttpMethod;\n if (method === 'GET' && IN_THE_CLEAR.has(path) && transport.inTheClear) {\n return transport.inTheClear(path, { query, signal: request.signal });\n }\n const contentType = request.headers.get('content-type') ?? undefined;\n const bytes = method === 'GET' ? undefined : new Uint8Array(await request.arrayBuffer());\n const body = bytes && bytes.length > 0 ? bytes : undefined;\n let retry: boolean | 'once' = false;\n if (RETRIED.some((route) => route.method === method && route.pattern.test(path))) {\n const json = body ? (JSON.parse(new TextDecoder().decode(body)) as { confirm?: unknown }) : {};\n retry = json.confirm === undefined ? true : 'once';\n }\n return transport.exchange(method, path, {\n query,\n ...(body ? { bytes: body, contentType: contentType ?? 'application/octet-stream' } : {}),\n retry,\n signal: request.signal,\n });\n };\n}\n\n/**\n * Gives a request to a route whose retries require an `idempotencyKey`\n * (`x-calimero-retry-requires`: a call, a method by its path) one when it has\n * none, made before it is first sent, so its D70 retries and its step-up's\n * confirmed retry carry the same key.\n */\nexport const idempotencyKeys: Middleware = {\n async onRequest({ request, schemaPath }) {\n if (!NEEDS_KEY.has(`${request.method} ${schemaPath}`)) return undefined;\n const text = await request.clone().text();\n const body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n if (body.idempotencyKey !== undefined) return undefined;\n return new Request(request, { body: JSON.stringify({ ...body, idempotencyKey: newIdempotencyKey() }) });\n },\n};\n\n/**\n * The typed client of the node's routes, sent through `transport` (a\n * `CalimeroClient`'s is `client.transport`; its session is this client's).\n *\n * ```ts\n * const api = createRouteClient(client.transport);\n * const { data, error } = await api.POST('/apps/{app}/intents', {\n * params: { path: { app } },\n * body: { method: 'set', args: { key: 'a', value: 'b' } },\n * middleware: [stepUp(passkeyConfirm(passkey))],\n * });\n * ```\n */\nexport function createRouteClient(transport: RouteTransport, options: RouteClientOptions = {}): RouteClient {\n const api = createClient<paths, 'application/json'>({ baseUrl: ROUTE_BASE_URL, fetch: transportFetch(transport) });\n api.use(idempotencyKeys);\n if (options.confirm) api.use(stepUp(options.confirm));\n if (options.operatorProof) api.use(operatorSignature(options.operatorProof));\n return api;\n}\n\n/** What every method of {@link RouteClient} answers. */\nexport interface RouteResult<T> {\n data?: T;\n error?: unknown;\n response: Response;\n}\n\n/**\n * The `data` of a result, or its refusal thrown as the typed\n * {@link CalimeroError} ({@link errorFrom}, the `Retry-After` header\n * included). An empty answer is `{}`.\n */\nexport async function unwrap<T>(result: Promise<RouteResult<T>> | RouteResult<T>): Promise<NonNullable<T>> {\n const { data, error, response } = await result;\n if (!response.ok) throw refusalOf(response, error);\n return (data ?? {}) as NonNullable<T>;\n}\n\n/** A refused result as the typed {@link CalimeroError}. */\nexport function refusalOf(response: Response, error: unknown): CalimeroError {\n const body = typeof error === 'string' ? (error ? { message: error } : {}) : error;\n return errorFrom(response.status, body, response.headers.get('retry-after'));\n}\n\nexport type { Middleware };\n", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n 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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\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/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\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) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, 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 buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\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/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__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 {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * 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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\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// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\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 // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\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/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\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 the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * Opening a sealed file, byte for byte as core's `calimero-sealed` crate\n * (`file.rs`, `wrap.rs`) writes it: 64 KiB AES-256-GCM STREAM chunks under a\n * data key, cut into segments, and that key wrapped to an X25519 key the\n * requester made for one export.\n */\n\nimport { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\nimport { concat, hex } from '../crypto/internal.js';\nimport { dh, type X25519KeyPair } from './noise.js';\n\nconst CHUNK_BYTES = 64 * 1024; // plaintext bytes in every chunk but the last\nconst TAG_BYTES = 16;\nconst SEALED_CHUNK_BYTES = CHUNK_BYTES + TAG_BYTES;\n/** Stored bytes of every segment but the last: 256 whole sealed chunks. */\nexport const SEGMENT_BYTES = 256 * SEALED_CHUNK_BYTES;\nconst NONCE_BYTES = 12;\nconst enc = new TextEncoder();\nconst AAD_PREFIX = enc.encode('calimero.file.v1'); // then the last-chunk flag byte\nconst SEGMENT_DOMAIN = enc.encode('calimero.file.segments.v1\\0'); // prefix of a file id's preimage\nconst EXPORT_WRAP_SALT = enc.encode('calimero.export-wrap.v1');\nconst DERIVE_LABEL = enc.encode('calimero.sealed.derive.v1\\0'); // prefix of every wrap's HKDF info\n\n/** Why an export was refused locally. A node's own refusal stays the transport's typed error. */\nexport type ExportErrorCode = 'BAD_ANSWER' | 'NOT_THE_FILE' | 'TAMPERED' | 'TOO_LARGE' | 'ABORTED';\n\n/** An export that failed a check here, never one the node refused; messages carry no plaintext or keys. */\nexport class ExportError extends Error {\n constructor(\n readonly code: ExportErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ExportError';\n }\n}\n\nconst sha256 = async (data: Uint8Array): Promise<Uint8Array> =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n\n/** The file id: SHA-256 over the domain, the segment count (u32 big-endian) and the ordered segment hashes. */\nexport function fileId(segments: Uint8Array[]): Promise<Uint8Array> {\n const count = new Uint8Array(4);\n new DataView(count.buffer).setUint32(0, segments.length, false);\n return sha256(concat(SEGMENT_DOMAIN, count, ...segments));\n}\n\n/** What an export wrap is bound to: the app and the file (hex id). */\nexport interface ExportWrap {\n appId: string;\n fileId: string;\n}\n\nfunction prefixed(field: string): Uint8Array {\n const bytes = enc.encode(field);\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, bytes.length, false);\n return concat(length, bytes);\n}\n\n/** Open the data key `wrapped` (`nonce || AES-256-GCM`) that the node wrapped to `recipient` for `wrap`. */\nexport async function unwrapExport(\n recipient: X25519KeyPair,\n ephemeral: Uint8Array,\n wrap: ExportWrap,\n wrapped: Uint8Array,\n): Promise<Uint8Array> {\n if (wrapped.length < NONCE_BYTES) throw new ExportError('TAMPERED', 'the wrapped key is truncated');\n const shared = await dh(recipient.privateKey, ephemeral);\n if (shared.every((b) => b === 0)) throw new ExportError('BAD_ANSWER', 'the ephemeral key is of low order');\n const info = concat(ephemeral, recipient.publicKey, prefixed(wrap.appId), prefixed(wrap.fileId));\n const ikm = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveBits']);\n const keyBytes = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: EXPORT_WRAP_SALT, info: concat(DERIVE_LABEL, info) },\n ikm,\n 256,\n );\n const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);\n let secret: ArrayBuffer;\n try {\n secret = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: wrapped.subarray(0, NONCE_BYTES) },\n key,\n wrapped.subarray(NONCE_BYTES),\n );\n } catch {\n throw new ExportError('TAMPERED', 'the wrapped key does not open');\n }\n if (secret.byteLength !== 32) throw new ExportError('TAMPERED', 'the wrapped key has the wrong length');\n return new Uint8Array(secret);\n}\n\n/**\n * Joins a file's segments in order, each checked against the list before it is\n * opened; holds at most one segment and one chunk. Output is authentic but may\n * be a prefix of the file until {@link finishExpecting} returns.\n */\nexport class SegmentReader {\n private pending: Uint8Array = new Uint8Array();\n private index = 0;\n private next = 0;\n private size = 0;\n private readonly hash = nobleSha256.create();\n\n private constructor(\n private readonly key: CryptoKey,\n private readonly segments: string[],\n ) {}\n\n static async create(dataKey: Uint8Array, segments: Uint8Array[]): Promise<SegmentReader> {\n const key = await crypto.subtle.importKey('raw', dataKey, 'AES-GCM', false, ['decrypt']);\n return new SegmentReader(key, segments.map(hex));\n }\n\n /** Take the next segment; `emit` gets the plaintext of every chunk it completes. */\n async push(segment: Uint8Array, emit: (plaintext: Uint8Array) => Promise<void> | void): Promise<void> {\n const want = this.segments[this.next];\n if (want === undefined) throw new ExportError('TAMPERED', `the file has no segment ${this.next}`);\n if (this.next + 1 < this.segments.length && segment.length !== SEGMENT_BYTES) {\n throw new ExportError('TAMPERED', `segment ${this.next} is not a whole segment`);\n }\n if (hex(await sha256(segment)) !== want) {\n throw new ExportError('TAMPERED', `segment ${this.next} is not the one the file lists`);\n }\n this.next += 1;\n // Bytes past a full chunk prove it was not the last, so one chunk is always held back.\n const data = concat(this.pending, segment);\n let at = 0;\n while (data.length - at > SEALED_CHUNK_BYTES) {\n await emit(await this.open(data.subarray(at, at + SEALED_CHUNK_BYTES), false));\n at += SEALED_CHUNK_BYTES;\n }\n this.pending = data.slice(at);\n }\n\n /** Open the last chunk and check the whole plaintext's size and SHA-256: GCM does not commit to its key. */\n async finishExpecting(size: number, sha256Hex: string): Promise<Uint8Array> {\n if (this.next !== this.segments.length) throw new ExportError('TAMPERED', 'the file is missing segments');\n if (this.pending.length < TAG_BYTES) throw new ExportError('TAMPERED', 'the file is truncated');\n const last = await this.open(this.pending, true);\n if (this.size !== size || hex(this.hash.digest()) !== sha256Hex) {\n throw new ExportError('TAMPERED', 'the file is not the one that was sealed');\n }\n return last;\n }\n\n private async open(chunk: Uint8Array, last: boolean): Promise<Uint8Array> {\n const iv = new Uint8Array(NONCE_BYTES);\n new DataView(iv.buffer).setBigUint64(4, BigInt(this.index), false);\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv, additionalData: concat(AAD_PREFIX, new Uint8Array([last ? 1 : 0])) },\n this.key,\n chunk,\n ),\n );\n } catch {\n throw new ExportError(\n 'TAMPERED',\n `chunk ${this.index} does not open: the file is altered, truncated or under another key`,\n );\n }\n this.hash.update(plain);\n this.size += plain.length;\n this.index += 1;\n return plain;\n }\n}\n", "/**\n * Downloading a sealed file, as core's `Client::export_file_to` does: the node\n * answers only ciphertext and the file's data key wrapped to a key made here\n * for this call, and nothing it says is believed until it checks out.\n */\n\nimport { concat, fromHex, fromHexUnsized, hex } from '../crypto/internal.js';\nimport { ExportError, SEGMENT_BYTES, SegmentReader, fileId, unwrapExport } from '../sealed/file.js';\nimport { x25519KeyPair } from '../sealed/noise.js';\nimport { routePath, type Transport } from '../runtime/transport.js';\n\nexport { ExportError, type ExportErrorCode } from '../sealed/file.js';\n\n/** Where an export writes the plaintext, in order. A `WritableStreamDefaultWriter` fits. */\nexport interface FileSink {\n write(chunk: Uint8Array): Promise<void> | void;\n}\n\n/** What an export wrote, as proven against the file's mark. */\nexport interface ExportedFile {\n size: number;\n /** SHA-256 of the plaintext, hex. */\n sha256: string;\n}\n\ntype ExportTransport = Pick<Transport, 'json' | 'request'>;\n\nfunction hexField(value: unknown, label: string, bytes?: number): Uint8Array {\n if (typeof value !== 'string') throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);\n try {\n return bytes === undefined ? fromHexUnsized(value, label) : fromHex(value, label, bytes);\n } catch {\n throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);\n }\n}\n\n/** The answer's fields, checked for shape; whether they name the requested file is checked after. */\nfunction checked(answer: unknown) {\n const a = answer as Record<string, unknown> | null;\n if (typeof a !== 'object' || a === null) throw new ExportError('BAD_ANSWER', 'the node answered a bad export');\n if (typeof a.app !== 'string') throw new ExportError('BAD_ANSWER', 'the node answered a bad app');\n if (typeof a.size !== 'number' || !Number.isSafeInteger(a.size) || a.size < 0) {\n throw new ExportError('BAD_ANSWER', 'the node answered a bad size');\n }\n if (!Array.isArray(a.segments)) throw new ExportError('BAD_ANSWER', 'the node answered a bad segment list');\n return {\n app: a.app,\n size: a.size,\n named: hexField(a.id, 'file id', 32),\n segments: a.segments.map((h) => hexField(h, 'segment hash', 32)),\n sha256: hex(hexField(a.sha256, 'sha256', 32)),\n ephemeral: hexField(a.ephemeral, 'ephemeral key', 32),\n wrapped: hexField(a.wrapped, 'wrapped key'),\n };\n}\n\nconst aborted = () => new ExportError('ABORTED', 'the export was aborted');\n\n/** A segment's bytes, refusing one longer than a whole segment before buffering it, and stopping on `signal`. */\nasync function readSegment(response: Response, signal?: AbortSignal): Promise<Uint8Array> {\n const declared = Number(response.headers.get('content-length'));\n if (Number.isFinite(declared) && declared > SEGMENT_BYTES) {\n await response.body?.cancel();\n throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');\n }\n if (!response.body) return new Uint8Array();\n const reader = response.body.getReader();\n const stop = () => void reader.cancel();\n signal?.addEventListener('abort', stop);\n const parts: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > SEGMENT_BYTES) {\n await reader.cancel();\n throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');\n }\n parts.push(value);\n }\n } finally {\n signal?.removeEventListener('abort', stop);\n }\n if (signal?.aborted) throw aborted();\n return concat(...parts);\n}\n\n/**\n * Write the plaintext of sealed file `id` (64 hex) of app `app` to `sink`, one\n * segment at a time. Each segment is checked against its hash before it is\n * opened, and the segment list, size and plaintext hash against the file's id\n * and mark at the end. On rejection, discard what `sink` received: it is\n * authentic but may be a prefix of the file. A failed check is an\n * {@link ExportError}; a refusal by the node is the transport's own error.\n * `recipientSecret` pins the export key, for the published vectors only.\n */\nexport async function exportFileTo(\n transport: ExportTransport,\n app: string,\n id: string,\n sink: FileSink,\n signal?: AbortSignal,\n recipientSecret?: Uint8Array,\n): Promise<ExportedFile> {\n try {\n return await exportChecked(transport, app, id, sink, signal, recipientSecret);\n } catch (error) {\n if (signal?.aborted && !(error instanceof ExportError)) throw aborted();\n throw error;\n }\n}\n\nasync function exportChecked(\n transport: ExportTransport,\n app: string,\n id: string,\n sink: FileSink,\n signal?: AbortSignal,\n recipientSecret?: Uint8Array,\n): Promise<ExportedFile> {\n const recipient = await x25519KeyPair(recipientSecret);\n // shortcut: not in the generated routes until the next openapi sync; they move there then.\n const answer = checked(\n await transport.json('POST', routePath('apps/{app}/files/{id}/export', { app, id }), {\n body: { recipient: hex(recipient.publicKey) },\n signal,\n }),\n );\n const { segments, named } = answer;\n if (segments.length === 0 || hex(await fileId(segments)) !== hex(named) || hex(named) !== id) {\n throw new ExportError('NOT_THE_FILE', `the node answered segments that are not the file ${id}`);\n }\n const dataKey = await unwrapExport(recipient, answer.ephemeral, { appId: answer.app, fileId: id }, answer.wrapped);\n const reader = await SegmentReader.create(dataKey, segments);\n for (let k = 0; k < segments.length; k += 1) {\n if (signal?.aborted) throw aborted();\n const response = await transport.request('GET', routePath('apps/{app}/files/{id}/segments/{k}', { app, id, k }), {\n signal,\n });\n await reader.push(await readSegment(response, signal), (chunk) => sink.write(chunk));\n }\n const last = await reader.finishExpecting(answer.size, answer.sha256);\n if (last.length > 0) await sink.write(last);\n return { size: answer.size, sha256: answer.sha256 };\n}\n\n/** The plaintext of sealed file `id` of app `app`, in memory. Prefer {@link exportFileTo} for a large file. */\nexport async function exportFile(\n transport: ExportTransport,\n app: string,\n id: string,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n const chunks: Uint8Array[] = [];\n await exportFileTo(transport, app, id, { write: (chunk) => void chunks.push(chunk) }, signal);\n return concat(...chunks);\n}\n", "/**\n * An organization's recovery key (core `docs/specs/org-recovery.md`): an\n * Ed25519 key whose 32-byte seed the owner keeps offline. The node stores only\n * the public half; the seed signs, here and never on a node, the statement\n * that hands the organization to one account. Byte-for-byte core's\n * `calimero_identity::recovery`.\n */\n\nimport { b64url } from '../runtime/passkey.js';\n\n/** What a recovery signature covers before the organization, the account and the nonce. */\nexport const RECOVERY_DOMAIN = 'calimero.org-recovery.v1\\0';\n\n/** The longest nonce a recovery carries, in bytes (core's `MAX_RECOVERY_NONCE_BYTES`). */\nexport const MAX_RECOVERY_NONCE_BYTES = 64;\n\n/** PKCS#8 prefix of an Ed25519 private key; the 32-byte seed follows. */\nconst PKCS8_ED25519 = Uint8Array.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,\n]);\n\n/** A new random seed. */\nexport function newRecoverySeed(): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(32));\n}\n\n/** The seed as people write it down: 64 hex digits in eight groups of eight, joined by `-`. */\nexport function recoverySeedText(seed: Uint8Array): string {\n checkSeed(seed);\n const hex = Array.from(seed, (b) => b.toString(16).padStart(2, '0')).join('');\n const groups: string[] = [];\n for (let i = 0; i < hex.length; i += 8) groups.push(hex.slice(i, i + 8));\n return groups.join('-');\n}\n\n/** A seed from its written form: 64 hex digits; `-`, whitespace and case are ignored. */\nexport function parseRecoverySeed(text: string): Uint8Array {\n const digits = text.replace(/[-\\s]/g, '');\n if (!/^[0-9a-fA-F]{64}$/.test(digits)) throw new Error('a recovery seed is 64 hex digits');\n return Uint8Array.from({ length: 32 }, (_, i) => parseInt(digits.slice(2 * i, 2 * i + 2), 16));\n}\n\n/** The bytes a recovery signs: `\"calimero.org-recovery.v1\\0\" || org || 0 || account || 0 || nonce`. */\nexport function recoveryMessage(org: string, account: string, nonce: string): Uint8Array {\n return new TextEncoder().encode(`${RECOVERY_DOMAIN}${org}\\0${account}\\0${nonce}`);\n}\n\n/** The seed's public key, base64url: what the organization stores. */\nexport async function recoveryPublicKey(seed: Uint8Array): Promise<string> {\n const key = await privateKey(seed, true);\n const jwk = await crypto.subtle.exportKey('jwk', key);\n if (!jwk.x) throw new Error('this runtime cannot export an Ed25519 public key');\n return jwk.x;\n}\n\n/** The seed's signature (base64url) handing `org` to `account` under `nonce`. */\nexport async function signRecovery(seed: Uint8Array, org: string, account: string, nonce: string): Promise<string> {\n const nonceBytes = new TextEncoder().encode(nonce).length;\n if (nonceBytes === 0 || nonceBytes > MAX_RECOVERY_NONCE_BYTES) {\n throw new Error(`a recovery nonce is 1 to ${MAX_RECOVERY_NONCE_BYTES} bytes`);\n }\n const key = await privateKey(seed, false);\n const sig = await crypto.subtle.sign('Ed25519', key, buf(recoveryMessage(org, account, nonce)));\n return b64url(new Uint8Array(sig));\n}\n\nfunction checkSeed(seed: Uint8Array): void {\n if (seed.length !== 32) throw new Error('a recovery seed is 32 bytes');\n}\n\nfunction privateKey(seed: Uint8Array, extractable: boolean): Promise<CryptoKey> {\n checkSeed(seed);\n const pkcs8 = new Uint8Array(PKCS8_ED25519.length + 32);\n pkcs8.set(PKCS8_ED25519);\n pkcs8.set(seed, PKCS8_ED25519.length);\n return crypto.subtle.importKey('pkcs8', buf(pkcs8), { name: 'Ed25519' }, extractable, ['sign']);\n}\n\nconst buf = (b: Uint8Array): ArrayBuffer => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;\n", "/**\n * Release and upgrade approvals as core's node reports them, and the consent\n * page an app sends its user to when one is theirs to make.\n *\n * An app never approves in its own page. A passkey assertion is blind (the\n * authenticator shows a site name, never what the challenge commits to), so\n * the page that runs the ceremony decides what the person believes they\n * approve. The node therefore refuses every approval route to a session\n * opened on an app's frontend, and serves its own **consent page** instead:\n * the app asks for a request (`POST /consent/requests`), sends the person to\n * the page's `url` on the node's own origin, and reads the decision when the\n * page sends them back (`returnTo?request_id=\u2026&result=\u2026`) or from\n * `GET /consent/{id}/result`. See core's\n * [consent page](https://calimero-network.github.io/core/protocol/consent-page/)\n * and [governance](https://calimero-network.github.io/core/protocol/governance/).\n */\n\nimport { compareReleaseVersions } from '../sealed/release.js';\nimport type { ApiAnswer } from '../routes/types.js';\n\n// ---------------------------------------------------------------- governance\n\n/**\n * Who holds one decision on a cluster (core's `Authority`), fixed at genesis\n * and attested by every replica. `owner`: the parties around each app, with a\n * passkey (for release approvals the app's publisher, for upgrades whoever\n * its package's manifest names); `operator`: the operator, for every app.\n */\nexport type Authority = 'owner' | 'operator';\n\n/** Core's `Governance`: which side holds each decision on this cluster. */\nexport interface Governance {\n releases: Authority;\n appUpgrades: Authority;\n outbound: Authority;\n /** Who may install apps: any account (`open`, left out) or granted deployers only. */\n deployments?: 'open' | 'granted';\n /** Who grants deployers: the operator (left out) or the cluster's owner. */\n deployers?: 'operator' | 'owner';\n}\n\n// ---------------------------------------------------------------- reports\n\n/** Whose approvals a report covers: an organization's, or the account's own apps. */\nexport type ReportScope = { kind: 'account' } | { kind: 'org'; org: string };\n\n/** A bundle as a report names it: its digest, and its release where the reader may see it. */\nexport interface ReportedBundle {\n bundle: string;\n package?: string;\n version?: string;\n}\n\n/** Who made an upgrade, by kind. */\nexport type ActorKind = 'owner' | 'member' | 'operator';\n\n/** A replica's node whose runtime is older than a release needs, and what it runs: the version, or `{ before }` for a node on a release from before nodes named their runtime. */\nexport interface RuntimeShortNode {\n node: number;\n runtime: string | { before: string } | null;\n}\n\n/**\n * Why an app cannot move to the newest release it may see (core's\n * `latestBlocked`): `runtime`, a replica's node runs an older runtime than\n * the release's `minRuntimeVersion` (the upgrade would be refused `409\n * RUNTIME_TOO_OLD`); `authority`, the app's owner upgrades it and the\n * release would give its upgrades to the publisher.\n */\nexport interface LatestBlocked {\n version: string;\n reason: 'runtime' | 'authority';\n message: string;\n minRuntimeVersion?: string;\n nodes?: RuntimeShortNode[];\n}\n\n/** One app in a report. `name`, `team`, `availableVersions`, `latestReachable` and `latestBlocked` are in members' and accounts' reports only. */\nexport type ReportedApp = ApiAnswer<'org_apps'>['apps'][number];\n\n/** `GET /auth/apps` or `GET /orgs/{org}/apps`: one page. */\nexport type AppsReport = ApiAnswer<'org_apps'>;\n\n/** A page of a report: entries after the id `after`, at most `limit` (1 to {@link MAX_REPORT_PAGE}). */\nexport interface PageOptions {\n after?: string;\n limit?: number;\n}\n\n/** The most entries one page of a report answers (core's `MAX_REPORT_PAGE`). */\nexport const MAX_REPORT_PAGE = 100;\n\n/** `?after=&limit=` for a report route; `limit` outside 1 to 100 is refused before sending. */\nexport function pageQuery(page: PageOptions = {}): string {\n const q = new URLSearchParams();\n if (page.after !== undefined) q.set('after', page.after);\n if (page.limit !== undefined) {\n if (!Number.isInteger(page.limit) || page.limit < 1 || page.limit > MAX_REPORT_PAGE) {\n throw new RangeError(`limit is 1 to ${MAX_REPORT_PAGE}`);\n }\n q.set('limit', String(page.limit));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n\n// ---------------------------------------------------------------- deadlines\n\n/** A release's end-of-new-work deadline. */\nexport interface ReleaseDeadline {\n version: string;\n /** RFC 3339. */\n after: string;\n /** Unix seconds. */\n afterSecs: number;\n}\n\n/** `GET /releases`: the cluster's release rules, public inside the sealed channel. */\nexport type ReleaseRules = ApiAnswer<'releases_public'>;\n\n/** Semver order (core's `compare_versions`); text order for versions that are not semver. */\nexport function compareVersions(a: string, b: string): number {\n try {\n return compareReleaseVersions(a, b);\n } catch {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\n\n/**\n * Whether a scope whose approved set is `approved` has lost new work at `now`\n * (Unix seconds), as core's `SystemState::stalled` judges it: a release's\n * deadline has passed and the newest approved release is older. Names the\n * newest such release, since approving it lifts every one. `null` approved\n * (unrestricted) is never stalled.\n */\nexport function stalledBy(\n approved: string[] | null,\n deadlines: ReleaseDeadline[],\n now: number = Date.now() / 1000,\n): ReleaseDeadline | null {\n if (approved === null || approved.length === 0) return null;\n const newest = approved.reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));\n let stall: ReleaseDeadline | null = null;\n for (const d of deadlines) {\n if (d.afterSecs <= now && compareVersions(newest, d.version) < 0) {\n if (stall === null || compareVersions(d.version, stall.version) > 0) stall = d;\n }\n }\n return stall;\n}\n\n// ---------------------------------------------------------------- publishers\n\n/**\n * The text a package signing key signs to bind it to `org` as its publisher\n * (core's `system::publisher_binding_message`). Take `cluster` and\n * `generation` from `client.public.publisherBinding`; sign the UTF-8\n * bytes with the key's Ed25519 secret and send\n * `client.orgs.publisher`.\n */\nexport function publisherBindingMessage(cluster: string, org: string, signerId: string, generation: number): string {\n return `calimero-publisher-binding/v1\\n${cluster}\\n${org}\\n${signerId}\\n${generation}`;\n}\n\n/** {@link publisherBindingMessage} as the bytes to sign. */\nexport function publisherBindingBytes(cluster: string, org: string, signerId: string, generation: number): Uint8Array {\n return new TextEncoder().encode(publisherBindingMessage(cluster, org, signerId, generation));\n}\n\n// ---------------------------------------------------------------- consent page\n\n/** Whose approval a release or outbound request is for. */\nexport type ConsentScope = 'account' | { org: string };\n\n/** What the app asks its user to approve (`POST /consent/requests`). Unknown fields are refused. */\nexport type ConsentRequest =\n | {\n kind: 'release';\n scope: ConsentScope;\n /** `withdraw: true` asks to withdraw the release's approval instead of approving it. */\n subject: { version: string; withdraw?: boolean };\n /** Where the page sends the person back: the package's frontend origin, or one its manifest names. */\n returnTo: string;\n }\n | {\n kind: 'upgrade';\n subject: { app: string; toVersion: string };\n returnTo: string;\n }\n | {\n kind: 'outbound';\n scope: ConsentScope;\n /** `package`: a package-bound session's own when left out; `prefixes`: every one the latest release declares. */\n subject: { package?: string; prefixes?: string[] };\n returnTo: string;\n }\n | {\n /** A new organization, owned by whoever approves. Outcome: `{ orgId }`. */\n kind: 'createOrg';\n subject: { name: string };\n returnTo: string;\n }\n | {\n /** A new invite to `subject.org`. Outcome: `{ token }`. */\n kind: 'createInvite';\n subject: InviteConsentSubject;\n returnTo: string;\n }\n | {\n /** Joining an organization with an invite's `token`. Outcome: `{ org }`. */\n kind: 'acceptInvite';\n subject: { token: string };\n returnTo: string;\n };\n\n/** A consent request's kind. */\nexport type ConsentKind = ConsentRequest['kind'];\n\n/** A role an invite gives (core's `Role`). */\nexport type InviteRole = 'guest' | 'member' | 'admin';\n\n/** What a `createInvite` consent request asks for. */\nexport interface InviteConsentSubject {\n org: string;\n role: InviteRole;\n /** Teams the invite joins its user to. */\n teams?: string[];\n /** How long the invite lasts, in seconds. */\n ttlSecs?: number;\n /** How many times it may be used. */\n uses?: number;\n /** Whether it gives every app of the organization. */\n allApps?: boolean;\n}\n\n/** The node's answer to a consent request: send the person to `url`. */\nexport type ConsentStarted = ApiAnswer<'consent_page_create'>;\n\n/** How {@link CalimeroClient.openConsentPage} sends the person to the page. */\nexport interface OpenConsentOptions {\n /** Sends the browser to the page's `url`; by default `window.location.assign`. */\n navigate?: (url: string) => void;\n /**\n * Runs after the node answers and before navigating, with the answer: show\n * the person `started.code` here so they can check the page shows the same.\n * Answer `false` and the page is not opened (the request stays on the node\n * until it expires).\n */\n confirm?: (started: ConsentStarted) => boolean | Promise<boolean>;\n}\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\n\n/**\n * The confirmation code the node's consent page shows for `requestId`: the\n * first 30 bits of SHA-256 of its UTF-8 bytes, big-endian, as six Crockford\n * base32 characters written `XXX-XXX` (core's consent page). Compare it with\n * {@link ConsentStarted.code} to check the node's answer.\n */\nexport async function confirmationCode(requestId: string): Promise<string> {\n const h = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(requestId)));\n const word = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0;\n let code = '';\n for (let i = 0; i < 6; i++) {\n if (i === 3) code += '-';\n code += CROCKFORD[(word >>> (27 - 5 * i)) & 31];\n }\n return code;\n}\n\n/**\n * What an approval made, by kind (`outcome` on {@link ConsentResult}, once\n * approved): `release`, `upgrade` and `outbound` make nothing. An invite's\n * `token` is a credential: keep it out of logs.\n */\nexport interface ConsentOutcomes {\n release: never;\n upgrade: never;\n outbound: never;\n createOrg: { orgId: string };\n createInvite: { token: string };\n acceptInvite: { org: string };\n}\n\n/** `GET /consent/{id}/result` for a request of kind `K`. */\nexport interface ConsentResultOf<K extends ConsentKind> {\n requestId: string;\n kind: K;\n status: 'pending' | 'approved' | 'declined';\n /** Unix seconds; `null` while pending. */\n decidedAt: number | null;\n /** What the approval made, once approved, for the kinds that make something. */\n outcome?: ConsentOutcomes[K];\n}\n\n/**\n * `GET /consent/{id}/result`, narrowed by `kind`:\n * `if (r.kind === 'createOrg') r.outcome?.orgId`. Read `outcome` only from\n * this sealed answer, never from the page's redirect, which carries none.\n *\n * Typed here by hand: the vendored OpenAPI document does not name the\n * organization kinds (core#5014) yet; the next openapi-sync brings them.\n */\nexport type ConsentResult = { [K in ConsentKind]: ConsentResultOf<K> }[ConsentKind];\n\n/**\n * What the consent page put on `returnTo` when it sent the person back, or\n * `null` when `href` carries none. A hint only (anyone can type a URL): confirm\n * with `client.consent.pageResult` before acting on it.\n */\nexport function consentReturn(href: string | URL): { requestId: string; result: 'approved' | 'declined' } | null {\n const url = typeof href === 'string' ? new URL(href) : href;\n const requestId = url.searchParams.get('request_id');\n const result = url.searchParams.get('result');\n if (!requestId || (result !== 'approved' && result !== 'declined')) return null;\n return { requestId, result };\n}\n\n/** `href` without the consent page's `request_id` and `result`. */\nexport function withoutConsentReturn(href: string | URL): string {\n const url = new URL(String(href));\n url.searchParams.delete('request_id');\n url.searchParams.delete('result');\n return url.toString();\n}\n\n/** The `sessionStorage` key {@link CalimeroClient.openConsentPage} keeps its request id under, for {@link CalimeroClient.resumeConsent}. */\nexport const CONSENT_STORAGE_KEY = 'calimero.consent';\n\n/** How {@link CalimeroClient.resumeConsent} reads the page's return. */\nexport interface ResumeConsentOptions {\n /**\n * The request this page started; by default the one\n * {@link CalimeroClient.openConsentPage} stored in this tab.\n */\n requestId?: string;\n /** The URL the page sent the person back to; by default `location.href`, whose parameters are then removed. */\n href?: string;\n}\n\n// ---------------------------------------------------------------- pending\n\n/** The public verifier for mero-tee releases (`attestation-verifier`). */\nexport const RELEASE_VERIFIER = 'https://mero-tee.vercel.app';\n\n/** A mero-tee release's notes on GitHub. */\nexport function releaseNotesUrl(version: string): string {\n return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;\n}\n\n/** The public verifier's page for a mero-tee release. */\nexport function verifyReleaseUrl(version: string): string {\n return `${RELEASE_VERIFIER}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${version}`)}`;\n}\n\n/** A mero-tee release the cluster's nodes run that the scope has not approved. */\nexport interface PendingRelease {\n version: string;\n /** How many of the cluster's nodes run it. */\n nodes: number;\n /** Whether the scope's side holds release approvals (else the operator does). */\n actionable: boolean;\n releaseNotesUrl: string;\n verifyUrl: string;\n /** Its deadline, when it carries one. */\n deadline: ReleaseDeadline | null;\n}\n\n/** An app with newer releases of its package. */\nexport interface PendingUpgrade {\n app: string;\n name: string | null;\n package: string;\n from: string;\n /**\n * The newest it can move to now (the report's `latestReachable`); when\n * none can be (`reachable: false`), or from a node that does not say, the\n * newest it may see.\n */\n to: string;\n /** Whether an upgrade to `to` would be taken now; `false`: `blocked` says why none is. */\n reachable: boolean;\n /** Why the newest release it may see is not reachable, when it is not. */\n blocked: LatestBlocked | null;\n /** Every newer release it may move to, oldest first. */\n available: string[];\n /** Whether owners hold app upgrades on this cluster; the node checks the package's own `upgrades` when asked. */\n actionable: boolean;\n}\n\n/** What {@link CalimeroClient.pendingApprovals} answers. */\nexport interface PendingApprovals {\n scope: ReportScope;\n governance: Governance;\n approvedReleases: string[] | null;\n releases: PendingRelease[];\n upgrades: PendingUpgrade[];\n /** A passed deadline has stopped new work for the scope: approve `stalledBy.version` (or newer) to lift it. */\n stalledBy: ReleaseDeadline | null;\n /** Whether anything here is the user's to approve. */\n actionable: boolean;\n}\n\n/**\n * The pending list from a scope's report pages (every page's apps\n * concatenated into `report.apps`) and the cluster's release rules.\n */\nexport function pendingApprovalsFrom(report: AppsReport, rules: ReleaseRules, now: number = Date.now() / 1000): PendingApprovals {\n const deadlineOf = (v: string) => rules.deadlines.find((d) => d.version === v) ?? null;\n const releasesActionable = report.governance.releases === 'owner';\n const upgradesActionable = report.governance.appUpgrades === 'owner';\n const releases: PendingRelease[] = report.clusterReleases\n .filter((r) => !r.approved)\n .sort((a, b) => compareVersions(b.release, a.release))\n .map((r) => ({\n version: r.release,\n nodes: r.nodes,\n actionable: releasesActionable,\n releaseNotesUrl: releaseNotesUrl(r.release),\n verifyUrl: verifyReleaseUrl(r.release),\n deadline: deadlineOf(r.release),\n }));\n const upgrades: PendingUpgrade[] = [];\n for (const a of report.apps) {\n const available = a.availableVersions ?? [];\n if (a.package === null || available.length === 0) continue;\n const latest = available[available.length - 1];\n const reachable = a.latestReachable === undefined ? latest : a.latestReachable;\n upgrades.push({\n app: a.app,\n name: a.name ?? null,\n package: a.package.package,\n from: a.package.version,\n to: reachable ?? latest,\n reachable: reachable !== null,\n blocked: a.latestBlocked ?? null,\n available,\n actionable: upgradesActionable,\n });\n }\n return {\n scope: report.scope,\n governance: report.governance,\n approvedReleases: report.approvedReleases,\n releases,\n upgrades,\n stalledBy: stalledBy(report.approvedReleases, rules.deadlines, now),\n actionable: releases.some((r) => r.actionable) || upgrades.some((u) => u.actionable),\n };\n}\n\n/**\n * The consent request that approves `version` for `scope`, or with\n * `{ withdraw: true }` withdraws its approval ({@link withdrawConsent}).\n */\nexport function releaseConsent(\n scope: ReportScope,\n version: string,\n returnTo: string,\n options: { withdraw?: boolean } = {},\n): ConsentRequest {\n return {\n kind: 'release',\n scope: scope.kind === 'org' ? { org: scope.org } : 'account',\n subject: options.withdraw ? { version, withdraw: true } : { version },\n returnTo,\n };\n}\n\n/**\n * The consent request that withdraws `version`'s approval for `scope`: nodes\n * on it are then sent none of the scope's apps' data (nothing already there\n * moves). The page fetches no measurements for it. Withdrawing the scope's\n * last approved release is refused on the page (`400 REJECTED`, the request\n * stays pending), and the page warns before.\n */\nexport function withdrawConsent(scope: ReportScope, version: string, returnTo: string): ConsentRequest {\n return releaseConsent(scope, version, returnTo, { withdraw: true });\n}\n\n/** The consent request that upgrades `app` to `toVersion`. */\nexport function upgradeConsent(app: string, toVersion: string, returnTo: string): ConsentRequest {\n return { kind: 'upgrade', subject: { app, toVersion }, returnTo };\n}\n\n/** The consent request that creates an organization named `name`; its outcome names the new `orgId`. */\nexport function createOrgConsent(name: string, returnTo: string): ConsentRequest & { kind: 'createOrg' } {\n return { kind: 'createOrg', subject: { name }, returnTo };\n}\n\n/** The consent request that creates an invite to `subject.org`; its outcome carries the invite's `token`. */\nexport function createInviteConsent(subject: InviteConsentSubject, returnTo: string): ConsentRequest & { kind: 'createInvite' } {\n return { kind: 'createInvite', subject, returnTo };\n}\n\n/** The consent request that joins the organization `token` invites to; its outcome names the `org`. */\nexport function acceptInviteConsent(token: string, returnTo: string): ConsentRequest & { kind: 'acceptInvite' } {\n return { kind: 'acceptInvite', subject: { token }, returnTo };\n}\n", "/**\n * Client for Calimero 1.0, the confidential cloud: one app = one replicated log on\n * attested nodes; this client verifies the node, seals every request to it,\n * signs people in with passkeys and machines with API keys.\n *\n * ```ts\n * const cloud = new CalimeroClient({ baseUrl, policy: { release: { minReleaseVersion: '2.3.109' } } });\n * await cloud.signIn(browserPasskey());\n * const { result } = await cloud.call(appId, 'set', { key: 'a', value: '1' });\n * ```\n */\n\nimport {\n DEFAULT_RETRY,\n NodeTransport,\n directoryTransport,\n refusal,\n retryDelayMs,\n routePath,\n type CalimeroSession,\n type NodeEvent,\n type RetryOptions,\n type HttpMethod,\n} from '../runtime/transport.js';\nimport { type NodePolicy } from '../runtime/attestation.js';\nimport { DEFAULT_DIRECTORY } from '../runtime/directory.js';\nimport { CalimeroError, LoginRequired, NotFound, OriginNotRegistered, UnavailableError, WrongRecoveryCode } from '../runtime/errors.js';\nimport { b64url, fromB64url, type PasskeyProvider } from '../runtime/passkey.js';\nimport { createRouteClient, type RouteClientOptions } from '../routes/route-client.js';\nimport type { MethodOptions } from '../routes/method.js';\nimport { createRoutes, type Routes } from '../generated/methods.js';\nimport { passkeyConfirm, type PasskeyConfirmOptions } from '../runtime/passkey.js';\n\nimport { exportFile, exportFileTo, type ExportedFile, type FileSink } from './files.js';\nimport { signRecovery } from './recovery-key.js';\nimport {\n CONSENT_STORAGE_KEY,\n confirmationCode,\n pageQuery,\n pendingApprovalsFrom,\n withoutConsentReturn,\n type AppsReport,\n type ConsentRequest,\n type ConsentResult,\n type ConsentStarted,\n type OpenConsentOptions,\n type PageOptions,\n type ResumeConsentOptions,\n type PendingApprovals,\n type ReportedApp,\n} from './approvals.js';\nimport type { ApiAnswer, ApiSchema } from '../routes/types.js';\n\nexport {\n AppError,\n ArgsTooLarge,\n BadOrigin,\n CalimeroError,\n ConfirmCancelled,\n ConfirmPromptBlocked,\n ConfirmRequired,\n IdempotencyMismatch,\n LoginRequired,\n ConsentStale,\n FeatureNotActive,\n NotFound,\n OriginNotRegistered,\n OriginTaken,\n PasskeyUnknownHere,\n QuotaExceeded,\n RecoveryNotReady,\n ReleaseDeadlineError,\n RuntimeTooOld,\n SignUpRefused,\n TrapError,\n UnavailableError,\n WrongNode,\n WrongRecoveryCode,\n errorFrom,\n} from '../runtime/errors.js';\nexport type { Committed, SignUpRefusal } from '../runtime/errors.js';\n\nexport type { CalimeroSession, NodeEvent };\n\n/** The largest file sent as one request, and the part size a session is asked for. */\nexport const FILE_PART_BYTES = 16 * 1024 * 1024;\nconst PART_RESENDS = 1; // times a part is sent again before the node is asked where the session is\nconst MAX_FAILURES = 8; // failed sends in a row, with no part accepted between them, before giving up\nconst MAX_JUMPS = 16; // PART_OUT_OF_ORDER answers followed in one session before giving up\nconst CALL_RETRIES = 8; // times beginning and completing a session are sent again while the node is unavailable\n\nexport type CallResult = ApiAnswer<'intents'>;\n\nexport type ViewResult = ApiAnswer<'views'>;\n\n/** An installed package and its releases. */\nexport type PackageInfo = ApiSchema<'Package'>;\n\n/** One app instance as `listApps` answers it. */\n\nexport type AppInfo = ApiSchema<'AppEntry'>;\n\n/**\n * An organization-wide upgrade run, as `client.orgs.upgrade`, `client.orgs.upgradeStatus` and\n * `client.orgs.upgradeRetry` answer it (core's `UpgradeRun`).\n */\nexport type UpgradeRun = ApiSchema<'UpgradeRun'>;\n\n/** One of an app's blobs: `blobId` base58 (what apps print), `id` hex. */\nexport type BlobInfo = ApiAnswer<'blob_info'>;\n\n/** A sealed file: `id` and `sha256` hex, `blobId` base58 (what apps print), `index` the log index that recorded it. */\nexport type FileInfo = ApiAnswer<'file_info'>;\n\n/** What {@link CalimeroClient.uploadFile} takes; a `Blob` is read part by part, never whole. */\nexport type FileData = Blob | Uint8Array | ArrayBuffer;\n\n/** One device present in an app (`publishPresence`); `state` hex, `null` once retracted. */\nexport type PresenceEntry = ApiAnswer<'presence_get'>['present'][number];\n\n/**\n * `GET /orgs/{org}`: the organization as the caller sees it. Besides its\n * members, teams and metadata, who may approve its releases, the package\n * signing keys it publishes, and whether a passed release deadline has\n * stopped new work on its own set.\n */\nexport type OrgInfo = ApiSchema<'Org'>;\n\n/**\n * How an organization holds its apps, derived from its app teams (core\n * `OrgMode`): `legacy` has none (its apps use organization access),\n * `standalone` has only open ones (everyone has every app), `shared` has a\n * closed one (each app lists who is in it).\n */\nexport type OrgMode = 'legacy' | 'standalone' | 'shared';\n\n/** One app team, as `GET /orgs/{org}/app-teams` lists it (`client.orgs.appTeamList`). */\nexport type AppTeam = AppTeams['appTeams'][number];\n\n/** `GET /orgs/{org}/app-teams`: the organization's mode and its app teams. A guest sees only the app teams they are in. */\nexport type AppTeams = ApiAnswer<'app_team_list'>;\n\n/** One package's app team after `client.orgs.appTeamsScope`. */\nexport type ScopedAppTeam = ApiAnswer<'app_teams_scope'>['teams'][number];\n\n/** `POST /orgs/{org}/app-teams`: the organization's mode after, and each package's team. */\nexport type ScopeAppsResult = ApiAnswer<'app_teams_scope'>;\n\n/** A pending organization invite, as `GET /orgs/{org}/invites` lists it (never its token). */\nexport type OrgInvite = ApiAnswer<'invite_list'>['invites'][number];\n\n/** `GET /orgs/{org}/teams/{team}` (`client.orgs.teamGet`). */\nexport type TeamInfo = ApiSchema<'TeamView'>;\n\n/** When a recovery started and the earliest it may finish (Unix seconds). */\nexport interface RecoveryTimes {\n startedAt: number;\n readyAt: number;\n}\n\n/** One xcall that was never delivered (core's `DeadLetter`). */\nexport type DeadLetter = ApiSchema<'DeadLetter'>;\n\n/**\n * An account or an organization, as a deployer, a deployment's owner or the\n * cluster's owner: `{ account: id }` or `{ org: id }`.\n */\nexport type Deployer = { account: string } | { org: string };\n\n/** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */\nexport function deployerKey(deployer: Deployer): string {\n return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;\n}\n\n/**\n * A package frontend's `/.well-known/calimero.json`: the package, its\n * releases, the deployments offering it and the cluster's API URLs.\n */\nexport interface FrontendManifest {\n package: string;\n versions: string[];\n deployments: Array<{ id: string; name: string; app: string; version: string }>;\n api: string[];\n}\n\n/**\n * Read the `/.well-known/calimero.json` of the frontend at `origin` (by\n * default the page's own). Served in the clear by the frontend host, like the\n * page itself: for choosing a deployment and the API URL to connect to, never\n * for trust (the client attests the node it then talks to).\n */\nexport async function frontendManifest(origin?: string, fetcher: typeof fetch = fetch): Promise<FrontendManifest> {\n const base = origin ?? (globalThis as { location?: { origin?: string } }).location?.origin;\n if (!base) throw new Error('no page origin to read the frontend manifest from; pass `origin`');\n const response = await fetcher(new URL('/.well-known/calimero.json', base).toString());\n if (!response.ok) throw await refusal(response);\n const manifest = (await response.json()) as FrontendManifest;\n return { ...manifest, deployments: manifest.deployments ?? [] };\n}\n\n/**\n * The deployment a frontend page was opened for: the node serves\n * `/d/{deployment}/` by redirecting to `/{version}/\u2026?deployment={id}`, so the\n * page creates its instances from that deployment\n * (`client.apps.create({ name, deployment, package })`). `null` when the page was\n * not opened through a deployment. `href` defaults to `window.location.href`.\n */\nexport function pageDeployment(href?: string): string | null {\n const at = href ?? (globalThis as { location?: { href?: string } }).location?.href;\n if (!at) return null;\n try {\n return new URL(at).searchParams.get('deployment') || null;\n } catch {\n return null;\n }\n}\n\n/** A recovery of an account under way (core #4844, `docs/specs/account-recovery.md`). */\nexport interface AccountRecovery {\n accountId: string;\n /** The new passkey the recovery adds when it finishes. */\n credentialId: string;\n /** When it started (Unix seconds). */\n startedAt: number;\n /** The earliest it may finish (Unix seconds): 72 hours after the start. */\n readyAt: number;\n}\n\n/** One web origin registered for a package (`GET /package-origins/{package}`). */\nexport type PackageOrigin = ApiAnswer<'origins_list'>['origins'][number];\n\n/**\n * Where a sign-up or sign-in says it runs. By default the page's origin\n * (`window.location.origin`) when it is not the origin of a node the client\n * talks to; nothing outside a browser. A string sends that origin; `null`\n * sends none (the cluster's own origins).\n */\nexport interface SignInOptions {\n origin?: string | null;\n /**\n * Closes an open passkey prompt when it aborts (a Cancel button): the\n * ceremony then rejects as a dismissed prompt does (`NotAllowedError`; in a\n * sign-up's confirmation, {@link ConfirmCancelled}). Given to the\n * {@link PasskeyProvider} as `signal`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * {@link SignInOptions} for a sign-up, and the invite it is made with: an\n * organization invite's token (the new account joins the organization at\n * the invite's role) or a cluster sign-up invite's. A cluster whose policy\n * is `invite` or `closed` (`client.deployments.signUpPublic`) needs one.\n */\nexport interface SignUpOptions extends SignInOptions {\n invite?: string;\n}\n\n/**\n * `GET /sign-up`: who may create an account on the cluster (core's sign-up\n * policy, read without a session), so a page can say \"invite only\" before\n * any passkey prompt.\n */\nexport type SignUpPolicy = ApiAnswer<'sign_up_public'>;\n\n/** {@link PageOptions} as a generated route's query, checked as {@link pageQuery} checks them. */\nfunction pageParams(page: PageOptions): { after?: string; limit?: number } {\n pageQuery(page);\n return { after: page.after, limit: page.limit };\n}\n\n/** Bytes as lower-case hex. */\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * A presence state as `POST /apps/{app}/presence` takes it: the bytes as\n * lower-case hex, or `null`, which retracts this device's entry\n * (`client.apps.presencePublish({ app, seq, state: presenceState(bytes) })`).\n */\nexport function presenceState(state: Uint8Array | null): string | null {\n return state === null ? null : toHex(state);\n}\n\nexport { DEFAULT_RETRY, retryDelayMs };\nexport type { RetryOptions };\n\nexport interface CalimeroClientOptions {\n /** One node of the cluster: the one the client talks to first. */\n baseUrl: string;\n /**\n * Other nodes of the same cluster, in the order to move to them when a node\n * answers `421 WRONG_NODE` (its release may not serve this account), or stays\n * unavailable to a call or a view through all its retries. Each is attested\n * under the same `policy` before anything is sent to it. Without them a `421`\n * reaches the caller as {@link WrongNode}.\n */\n nodes?: string[];\n policy: NodePolicy;\n /** Fetch that carries attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n}\n\n/** How {@link CalimeroClient.connect} reaches a Calimero Cloud cluster by name. */\nexport interface CalimeroConnectOptions {\n /** The cluster's name, e.g. `eu-shared-1`. */\n cluster: string;\n /** What every node must attest to before anything is sent to it. */\n policy: NodePolicy;\n /** The node directory to ask. Default {@link DEFAULT_DIRECTORY}. */\n directory?: string;\n /** Try the nodes in this zone (e.g. `europe-west4-a`) first. */\n zone?: string;\n /** Fetch for the directory, attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n /** Randomness for the weighted node order, in [0, 1). Defaults to `Math.random`. */\n random?: () => number;\n}\n\n/** Bytes `start` to `end` of `data`, as a view or a slice: a `Blob` is never read whole. */\nasync function readSlice(data: FileData, start: number, end: number): Promise<Uint8Array> {\n if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());\n return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);\n}\n\n/** The `next` an answer names, which cannot be past the last part. */\nfunction nextPart(answer: unknown, parts: number): number {\n const next = (answer as { next?: unknown } | undefined)?.next;\n if (typeof next === 'number' && Number.isInteger(next) && next >= 0 && next <= parts) return next;\n throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);\n}\n\nexport class CalimeroClient {\n /**\n * The runtime every route of this client is sent through\n * (`@calimero-network/mero-js/runtime`): the attested, sealed channel to each\n * node, the credential and its refresh, the `412 CONFIRM_REQUIRED` step-up,\n * D70 retries and error mapping. A route layer of its own (one generated from\n * the node's OpenAPI document, say) sends through it and shares this\n * client's session.\n */\n readonly transport: NodeTransport;\n\n /**\n * The node's routes as methods, generated from core's OpenAPI document\n * (`src/generated/methods.ts`), one group per tag. Each takes one argument\n * object (path parameters, query and body fields merged) and answers the\n * route's payload; a refusal is thrown as the typed {@link CalimeroError}.\n * A step-up or an operator signature is answered by the client's `confirm`\n * / `operatorProof`, or the call's own (`{ confirm: passkeyConfirm(passkey) }`).\n *\n * `client.apps.call({ app, method, args })`, `client.orgs.get({ org })`,\n * `client.orgs.inviteCreate({ org, role }, { confirm })`.\n */\n readonly apps: Routes['apps'];\n /** Account, session, passkey and API-key routes: `client.auth.me()`. See {@link apps}. */\n readonly auth: Routes['auth'];\n /** The consent page's routes. See {@link apps}. */\n readonly consent: Routes['consent'];\n /** Operator routes (the ops token). See {@link apps}. */\n readonly ops: Routes['ops'];\n /** Organization, member, team and invite routes. See {@link apps}. */\n readonly orgs: Routes['orgs'];\n /** Routes anyone may read: attestation, health, releases, publisher bindings. See {@link apps}. */\n readonly public: Routes['public'];\n /** Package routes (`client.packages.install({ package, version })`). See {@link apps}. */\n readonly packages: Routes['packages'];\n /**\n * Deployment, deployer and sign-up routes (`client.deployments.create({ name, owner }, { confirm })`).\n * See {@link apps}.\n */\n readonly deployments: Routes['deployments'];\n\n /**\n * A client for the Calimero Cloud cluster named `cluster`: its node list read\n * from the public node directory, those in `zone` first, each group in\n * weighted-random order. The directory only picks which nodes to try: each is\n * attested under `policy` before anything is sent to it. Throws\n * {@link DirectoryError} when the directory names no usable node.\n *\n * The list is read again in the background after a failover, and at the\n * first request once the directory's `refreshAfterSeconds` has passed.\n */\n static async connect(options: CalimeroConnectOptions, challenges: RouteClientOptions = {}): Promise<CalimeroClient> {\n const transport = await directoryTransport({ ...options, directory: options.directory ?? DEFAULT_DIRECTORY });\n return new CalimeroClient(transport, challenges);\n }\n\n /**\n * A client of the nodes `options` names, or one sending through an existing\n * `transport`. `challenges` answers the node's challenges for every\n * generated method a call's own options leave open (`confirm` a\n * `412 CONFIRM_REQUIRED`, `operatorProof` a `428 OPERATOR_SIGNATURE_REQUIRED`).\n */\n constructor(options: CalimeroClientOptions | NodeTransport, challenges: RouteClientOptions = {}) {\n this.transport = options instanceof NodeTransport ? options : new NodeTransport(options);\n const routes = createRoutes(createRouteClient(this.transport, challenges));\n this.apps = routes.apps;\n this.auth = routes.auth;\n this.consent = routes.consent;\n this.ops = routes.ops;\n this.orgs = routes.orgs;\n this.public = routes.public;\n this.packages = routes.packages;\n this.deployments = routes.deployments;\n }\n\n /** A generated method's answer, as the type this class has always answered. */\n private as<T>(result: Promise<unknown>): Promise<T> {\n return result as Promise<T>;\n }\n\n /** The options that answer a `412 CONFIRM_REQUIRED` with `passkey`, when one is given. */\n private confirmWith(passkey: PasskeyProvider | undefined, options: PasskeyConfirmOptions = {}): MethodOptions | undefined {\n return passkey ? { confirm: passkeyConfirm(passkey, options) } : undefined;\n }\n\n /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved the client on. */\n get nodeUrl(): string {\n return this.transport.nodeUrl;\n }\n\n /** Every node this client may use, in the order it moves through them. */\n get nodes(): string[] {\n return this.transport.nodes;\n }\n\n /** Authenticate every request with an API key. */\n useApiKey(key: string): void {\n this.transport.useApiKey(key);\n }\n\n useSession(session: CalimeroSession): void {\n this.transport.useSession(session);\n }\n\n get session(): CalimeroSession | undefined {\n return this.transport.session;\n }\n\n /** A JSON request through the transport, to an untyped path. */\n private json<T>(method: HttpMethod, path: string, body?: unknown): Promise<T> {\n return this.transport.json<T>(method, path, { body });\n }\n\n // ---------------------------------------------------------------- identity\n\n /**\n * Create an account with a new passkey, and sign in. The node then asks the\n * new passkey to sign the account it creates (`412 CONFIRM_REQUIRED`), so a\n * sign-up prompts twice: create, then sign. On a page whose origin is not\n * the cluster's ({@link SignInOptions}), the node makes the passkey for that\n * origin's relying party (the confirmation's `rpId` is that origin's too)\n * and binds the session to the package the origin is registered for; an\n * unregistered origin is refused with {@link OriginNotRegistered}.\n *\n * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,\n * as the node judges it on each before it spends anything; a sign-up the\n * cluster's policy refuses, or an unknown, expired or used invite, is\n * {@link SignUpRefused} (from `begin`, before any passkey is made).\n */\n async signUp(passkey: PasskeyProvider, name: string, options: SignUpOptions = {}): Promise<CalimeroSession> {\n const origin = this.pageOrigin(options);\n const invite = options.invite ? { invite: options.invite } : {};\n const begin = await this.begin<{ challengeId: string; options: Record<string, unknown> }>(\n this.auth.registerBegin({ ...origin === undefined ? { name, ...invite } : { name, origin, ...invite } }),\n origin,\n );\n const signal = options.signal;\n const registration = await (signal ? passkey.create(begin.options, { signal }) : passkey.create(begin.options));\n // The node checks the sign-up's confirmation with the user present, not\n // verified (core `api.rs`: `rp(node)`, `require_uv: false`), as it made\n // the passkey with `preferred`: asking `required` here would refuse a\n // security key without a PIN after it has made the passkey, leaving a\n // passkey with no account. The document says so\n // (`x-calimero-user-verification: preferred`), and the generated method\n // asks the passkey for it.\n const session = await this.auth.registerFinish({ challengeId: begin.challengeId, registration, ...invite }, this.confirmWith(passkey, { signal }));\n this.useSession(session);\n return session;\n }\n\n /**\n * Sign in with an existing passkey. On a page whose origin is not the\n * cluster's ({@link SignInOptions}), the assertion is made for that\n * origin's relying-party id, as the node answers it, and the session is\n * bound to the origin's package; an unregistered origin is refused with\n * {@link OriginNotRegistered}. A passkey this cluster does not know (made\n * on another cluster, or removed) is refused with {@link PasskeyUnknownHere}.\n */\n async signIn(passkey: PasskeyProvider, options: SignInOptions = {}): Promise<CalimeroSession> {\n const origin = this.pageOrigin(options);\n const begin = await this.begin<{\n challengeId: string;\n options: { challenge: string; rpId?: string; rp?: { id?: string } };\n }>(this.auth.loginBegin({ ...origin === undefined ? {} : { origin } }), origin);\n const rpId = begin.options.rpId ?? begin.options.rp?.id ?? '';\n const challenge = fromB64url(begin.options.challenge);\n const assertion = await (options.signal\n ? passkey.get(challenge, rpId, undefined, { signal: options.signal })\n : passkey.get(challenge, rpId));\n const session = await this.auth.loginFinish({ challengeId: begin.challengeId, assertion });\n this.useSession(session);\n return session;\n }\n\n /**\n * The origin a sign-up or sign-in sends: the one given, or the page's own\n * when it is not a node's origin; `undefined` for none.\n */\n private pageOrigin(options: SignInOptions): string | undefined {\n if (options.origin !== undefined) return options.origin ?? undefined;\n const page = (globalThis as { location?: { origin?: string } }).location?.origin;\n if (!page || page === 'null') return undefined;\n const nodes = new Set(\n this.transport.nodes.map((url) => {\n try {\n return new URL(url).origin;\n } catch {\n return url;\n }\n }),\n );\n return nodes.has(page) ? undefined : page;\n }\n\n /** POST a ceremony's `begin`, naming the page's `origin` in an {@link OriginNotRegistered} the node leaves it out of. */\n private async begin<T>(result: Promise<unknown>, origin: string | undefined): Promise<T> {\n try {\n return await this.as<T>(result);\n } catch (error) {\n if (error instanceof OriginNotRegistered && !error.origin && origin !== undefined) {\n throw new OriginNotRegistered(error.nodeMessage, { ...error.details, origin });\n }\n throw error;\n }\n }\n\n /**\n * Swap the refresh token for a new session, on whichever node the client\n * uses: any node of the cluster takes it. A refresh token is used once, so\n * calls made while one refresh is under way share it rather than sending the\n * same token again (which would revoke the session).\n */\n refresh(): Promise<CalimeroSession> {\n return this.transport.refresh();\n }\n\n /**\n * End this session. The client is signed out whether or not the node\n * answers: the revoke (`POST /auth/logout`) is attempted, and its failure\n * (the node unreachable, say) is thrown after the session is dropped, so a\n * caller can say the server may still hold it, but no request after this\n * one carries its token.\n */\n async signOut(): Promise<void> {\n await this.signingOut(this.auth.logout());\n }\n\n /**\n * End every session of the signed-in account, on every device, this one\n * too. Like {@link signOut}, this client is signed out even when the\n * request fails, and the failure is thrown.\n */\n async signOutEverywhere(): Promise<void> {\n await this.signingOut(this.auth.logoutAll());\n }\n\n private async signingOut(result: Promise<unknown>): Promise<void> {\n try {\n await result;\n } finally {\n this.transport.signOut();\n }\n }\n\n /**\n * Add another passkey (another device, `passkey`) to the signed-in account;\n * answers its credential id. The node asks for the approval of a passkey\n * the account already has (`412 CONFIRM_REQUIRED`, never the new one),\n * which `approver` gives.\n */\n async addPasskey(passkey: PasskeyProvider, approver: PasskeyProvider): Promise<string> {\n const begin = await this.as<{ challengeId: string; options: Record<string, unknown> }>(this.auth.passkeyAddBegin());\n const registration = await passkey.create(begin.options);\n const { credentialId } = await this.auth.passkeyAddFinish({ challengeId: begin.challengeId, registration }, this.confirmWith(approver));\n return credentialId;\n }\n\n // ---------------------------------------------------------------- account recovery\n //\n // core #4844 (`docs/specs/account-recovery.md`): a recovery code, made with\n // a passkey and shown once, lets someone who lost every passkey register a\n // new one; it is added, and the account signed in, 72 hours later unless a\n // passkey the account still has cancels it first.\n\n /**\n * Signed out: start recovering the account `code` names. `passkey` makes a\n * new passkey for it (the browser's create prompt, user verified); the\n * node spends the code and keeps the passkey as pending. Nothing is added\n * and no session opens: finish with {@link finishAccountRecovery} at\n * `readyAt`. A code the cluster does not hold (mistyped, replaced or\n * spent) is {@link WrongRecoveryCode}; an account with a recovery already\n * under way `409 RECOVERY_PENDING`.\n */\n async startAccountRecovery(code: string, passkey: PasskeyProvider): Promise<AccountRecovery> {\n try {\n const begin = await this.as<{ challengeId: string; options: Record<string, unknown> }>(this.auth.accountRecoveryBegin({ code }));\n const registration = await passkey.create(begin.options);\n return await this.auth.accountRecoveryStart({ challengeId: begin.challengeId, code, registration });\n } catch (error) {\n if (error instanceof LoginRequired) throw new WrongRecoveryCode(error.message.replace(/^401 UNAUTHENTICATED: /, ''), error.details);\n throw error;\n }\n }\n\n /**\n * Signed out, once the delay passed: finish the recovery with the passkey\n * it registered (`passkey` signs the node's sign-in challenge). The passkey\n * joins the account, every other session of the account ends, and this\n * client is signed in. `accountId` (from the start) lets the node refuse\n * early and offer only that passkey; before `readyAt` it is\n * {@link RecoveryNotReady}, with no recovery under way {@link NotFound}.\n */\n async finishAccountRecovery(passkey: PasskeyProvider, accountId?: string): Promise<CalimeroSession> {\n const session = await this.auth.accountRecoveryFinish({ ...accountId ? { accountId } : {} }, this.confirmWith(passkey));\n this.useSession(session);\n return session;\n }\n\n // ---------------------------------------------------------------- apps\n\n /** One of `app`'s blobs, by id (base58 or hex). */\n async downloadBlob(app: string, id: string): Promise<Uint8Array> {\n return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());\n }\n\n /**\n * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,\n * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of\n * the file. A failed check is an `ExportError`; `signal` aborts the download.\n */\n exportFileTo(app: string, id: string, sink: FileSink, signal?: AbortSignal): Promise<ExportedFile> {\n return exportFileTo(this.transport, app, id, sink, signal);\n }\n\n /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */\n exportFile(app: string, id: string, signal?: AbortSignal): Promise<Uint8Array> {\n return exportFile(this.transport, app, id, signal);\n }\n\n /**\n * Download a component app's blob with a grant one of its runs handed out\n * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the\n * permission. A bad or expired grant answers `NotFound`, as a missing blob.\n */\n async downloadBlobGranted(app: string, id: string, grant: string): Promise<Uint8Array> {\n return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());\n }\n\n /**\n * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.\n * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new\n * file for each, so one that may have reached it is never repeated); a larger file\n * is a session of parts, each sent again after a dropped connection or a `503`.\n * A session the node lost is begun again once; any other failure aborts it.\n * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.\n */\n async uploadFile(app: string, data: FileData): Promise<FileInfo> {\n const size = data instanceof Blob ? data.size : data.byteLength;\n if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });\n try {\n return await this.uploadSession(app, data, size);\n } catch (error) {\n if (!(error instanceof CalimeroError) || error.code !== 'UPLOAD_UNKNOWN') throw error;\n return this.uploadSession(app, data, size);\n }\n }\n\n /** Begin a session, send its parts and complete it, aborting it if that fails for good. */\n private async uploadSession(app: string, data: FileData, size: number): Promise<FileInfo> {\n const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));\n const { uploadId: upload, partBytes, parts } = begin;\n if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {\n throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);\n }\n try {\n await this.sendParts(app, upload, data, size, partBytes, parts);\n return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));\n } catch (error) {\n if (!(error instanceof CalimeroError && error.code === 'UPLOAD_UNKNOWN')) await this.apps.uploadAbort({ app, upload }).catch(() => undefined);\n throw error;\n }\n }\n\n /** Send every part, in order, from wherever the node says the session is. */\n private async sendParts(app: string, upload: string, data: FileData, size: number, partBytes: number, parts: number): Promise<void> {\n let [next, failures, jumps] = [0, 0, 0];\n while (next < parts) {\n try {\n const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));\n next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);\n failures = 0;\n continue;\n } catch (error) {\n if (error instanceof CalimeroError && error.code === 'PART_OUT_OF_ORDER') {\n jumps += 1;\n if (jumps > MAX_JUMPS) throw error;\n next = nextPart(error.details, parts);\n continue;\n }\n if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));\n if (failures > PART_RESENDS) {\n try {\n const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);\n if (at > next) failures = 0;\n next = at;\n } catch (asked) {\n if (!this.isTransient(asked)) throw asked;\n }\n }\n }\n }\n }\n\n /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */\n private async untilAvailable<T>(send: () => Promise<T>): Promise<T> {\n for (let retry = 0; ; retry++) {\n try {\n return await send();\n } catch (error) {\n if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));\n }\n }\n }\n\n /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */\n private isTransient(error: unknown): boolean {\n return error instanceof UnavailableError || this.transport.isNetworkFailure(error);\n }\n\n // ---------------------------------------------------------------- packages\n\n // ---------------------------------------------------------------- app instances\n\n /** Committed events from index `from`, then live, until `signal` aborts. */\n events(app: string, from = 0, signal?: AbortSignal): AsyncGenerator<NodeEvent> {\n return this.transport.events(routePath('apps/{app}/events', { app }), { query: { from }, signal });\n }\n\n // ---------------------------------------------------------------- presence\n\n /**\n * Presence as a stream until `signal` aborts: a `snapshot` event (`data` the\n * entries present), then a `presence` event (`data` one entry) per change.\n */\n presenceStream(app: string, signal?: AbortSignal): AsyncGenerator<NodeEvent> {\n return this.transport.events(routePath('apps/{app}/presence/stream', { app }), { signal });\n }\n\n // ---------------------------------------------------------------- aliases\n\n // ---------------------------------------------------------------- organizations\n\n /**\n * Start handing `org` to the signed-in account with the recovery seed,\n * which signs here and never leaves this process. Finish with\n * `client.orgs.recoveryFinish` once `readyAt` has passed; until then the owner may\n * cancel. A wrong seed (or no organization, or none set) is a `403`.\n */\n async startRecovery(org: string, seed: Uint8Array): Promise<RecoveryTimes> {\n const account = (await this.auth.me()).accountId as string;\n const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)));\n const signature = await signRecovery(seed, org, account, nonce);\n return this.orgs.recoveryStart({ org, nonce, signature });\n }\n\n // ---------------------------------------------------------------- approvals\n\n /** The report of a scope's apps (`GET /orgs/{org}/apps`, or with `org` `null` the account's own, `GET /auth/apps`), every page, with the apps of all of them in `apps`. */\n async appsReportAll(org: string | null): Promise<AppsReport> {\n const report = (page: PageOptions = {}) =>\n org === null ? this.auth.accountApps(pageParams(page)) : this.orgs.apps({ org, ...pageParams(page) });\n const first = await report();\n const apps: ReportedApp[] = [...first.apps];\n let next = first.next;\n while (next !== null) {\n const page = await report({ after: next });\n apps.push(...page.apps);\n next = page.next;\n }\n return { ...first, apps, next: null };\n }\n\n /**\n * What waits for a decision in a scope (`org`, or the account's own apps\n * with `null`): mero-tee releases the cluster's nodes run that the scope has\n * not approved, apps with newer releases of their package, and whether a\n * passed deadline stops new work. Read over the sealed channel; act on an\n * item by sending the user to the consent page (`client.consent.pageCreate`,\n * `releaseConsent`, `upgradeConsent`).\n */\n async pendingApprovals(org: string | null = null): Promise<PendingApprovals> {\n const [report, rules] = await Promise.all([this.appsReportAll(org), this.public.releasesPublic()]);\n return pendingApprovalsFrom(report, rules);\n }\n\n /**\n * `client.consent.pageCreate`, then send the browser to the consent page\n * (`navigate`, by default `window.location.assign`). Pass `navigate` itself\n * or {@link OpenConsentOptions}, whose `confirm` runs first with the node's\n * answer so the app can show the person its `code`; when it answers `false`\n * the page is not opened. When the node sends a `code` that is not\n * {@link confirmationCode} of `requestId`, it throws `CalimeroError`\n * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request\n * once `navigate` returns (or `confirm` declines): with a popup\n * (`url => window.open(url)`), poll it with {@link waitForConsent}.\n * Before navigating it keeps `requestId` in `sessionStorage` (where there\n * is one), for {@link resumeConsent} when the page sends the person back.\n */\n async openConsentPage(\n request: ConsentRequest,\n navigateOrOptions: ((url: string) => void) | OpenConsentOptions = {},\n ): Promise<ConsentStarted> {\n const options = typeof navigateOrOptions === 'function' ? { navigate: navigateOrOptions } : navigateOrOptions;\n const navigate =\n options.navigate ??\n ((url: string) => {\n const w = (globalThis as { window?: { location: { assign(url: string): void } } }).window;\n if (!w) throw new Error('no window to open the consent page in; pass `navigate`');\n w.location.assign(url);\n });\n // The organization kinds (core#5014) are typed by hand in approvals.ts\n // until the vendored OpenAPI document names them.\n const started = await this.consent.pageCreate({ body: request as Parameters<Routes['consent']['pageCreate']>[0]['body'] });\n if (started.code !== undefined) {\n const expected = await confirmationCode(started.requestId);\n if (started.code !== expected) {\n throw new CalimeroError(200, 'CONSENT_CODE_MISMATCH', 'the consent page code does not match the request', {\n requestId: started.requestId,\n code: started.code,\n expected,\n });\n }\n }\n if (options.confirm && !(await options.confirm(started))) return started;\n try {\n consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);\n } catch {\n // No storage here: pass `requestId` to `resumeConsent`.\n }\n navigate(started.url);\n return started;\n }\n\n /**\n * On the page the consent page sent the person back to\n * (`returnTo?request_id=\u2026&result=\u2026`): the decision on the request this page\n * started, read from the node (`GET /consent/{id}/result`), never from the\n * URL. `null` when the URL carries no `request_id`. The request is\n * `options.requestId`, or the one {@link openConsentPage} stored in this\n * tab; with the default `href` (`location.href`) the parameters are then\n * removed with `history.replaceState`, and the stored id once decided.\n *\n * Throws `CalimeroError`:\n * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;\n * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;\n * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the\n * page sent the person back, a sign that another request was approved on a\n * page that was not the node's. Do not act on it;\n * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):\n * an account has one undecided request per node, and a newer one replaced\n * it, possibly on a page that was not the node's. Do not act on it either.\n *\n * The URL's `result` is never trusted: the answer's `status` is the node's.\n * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is\n * in the answer, typed by `kind`.\n */\n async resumeConsent(options: ResumeConsentOptions = {}): Promise<ConsentResult | null> {\n const g = globalThis as {\n location?: { href: string };\n history?: { state: unknown; replaceState(state: unknown, unused: string, url?: string): void };\n };\n const href = options.href ?? g.location?.href;\n if (href === undefined) throw new Error('no page to read the consent return from; pass `href`');\n const url = new URL(href);\n const returned = url.searchParams.get('request_id');\n if (!returned) return null;\n if (options.href === undefined && g.history) g.history.replaceState(g.history.state, '', withoutConsentReturn(url));\n\n let ownId = options.requestId;\n if (ownId === undefined) {\n try {\n ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? undefined;\n } catch {\n ownId = undefined;\n }\n }\n if (!ownId) {\n throw new CalimeroError(200, 'CONSENT_NOT_STARTED', 'this page started no consent request', { returned });\n }\n if (returned !== ownId) {\n throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the consent page returned another request than this page started', {\n requestId: ownId,\n returned,\n });\n }\n let result: ConsentResult;\n try {\n result = (await this.consent.pageResult({ request: ownId })) as ConsentResult;\n } catch (e) {\n // One undecided request per account per node: a newer one replaced\n // this page's, which then answers 404, perhaps swapped on a forged page.\n if (e instanceof NotFound) {\n forgetConsent(ownId);\n throw new CalimeroError(404, 'CONSENT_REPLACED', \"this page's consent request was replaced by a newer one\", {\n requestId: ownId,\n });\n }\n throw e;\n }\n if (result.requestId !== ownId) {\n throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the node answered another request', { requestId: ownId, returned: result.requestId });\n }\n if (result.status === 'pending') {\n throw new CalimeroError(200, 'CONSENT_NOT_DECIDED', 'the consent page returned, but this request is still pending', {\n requestId: ownId,\n });\n }\n forgetConsent(ownId);\n return result;\n }\n\n /**\n * Poll `client.consent.pageResult` until the request is decided, every\n * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)\n * passes, when it answers the last `pending` result.\n */\n async waitForConsent(\n requestId: string,\n options: { intervalMs?: number; signal?: AbortSignal; expiresAt?: number } = {},\n ): Promise<ConsentResult> {\n const interval = options.intervalMs ?? 2000;\n for (;;) {\n const result = (await this.consent.pageResult({ request: requestId })) as ConsentResult;\n if (result.status !== 'pending') return result;\n if (options.signal?.aborted) return result;\n if (options.expiresAt !== undefined && Date.now() / 1000 >= options.expiresAt) return result;\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n // ---------------------------------------------------------------- operator\n\n // ---------------------------------------------------------------- app teams\n\n // ---------------------------------------------------------------- package origins\n\n // ---------------------------------------------------------------- deployers\n\n // ---------------------------------------------------------------- deployments\n\n}\n\n/** This page's `sessionStorage`, where there is one (a sandboxed frame or a turned-off store throws). */\nfunction consentStorage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | undefined {\n try {\n return (globalThis as { sessionStorage?: Storage }).sessionStorage;\n } catch {\n return undefined;\n }\n}\n\n/** Drop the stored consent request id, when it is `requestId`. */\nfunction forgetConsent(requestId: string): void {\n try {\n const store = consentStorage();\n if (store?.getItem(CONSENT_STORAGE_KEY) === requestId) store.removeItem(CONSENT_STORAGE_KEY);\n } catch {\n // nothing to clear\n }\n}\n", "/**\n * What a member may do in an organization beyond their role, as core's\n * `caps` bits (`client.orgs.capabilities`, `client.orgs.teamSetMember`'s `capabilities`). A team's\n * lead and an organization's admin hold them all.\n */\nexport const ORG_CAPABILITIES = {\n /** Create an app in the organization (on its team, or org-wide). */\n CREATE_APP: 1 << 0,\n /** Mint invites (org-wide, or on each team the invite names). */\n INVITE_MEMBERS: 1 << 1,\n /** Inherited into open teams; denying it keeps a member out of them. */\n JOIN_OPEN_TEAMS: 1 << 2,\n /** Add and remove a team's members. */\n MANAGE_MEMBERS: 1 << 3,\n /** Upgrade the organization's apps (and, as a publisher, every instance of its `publisher` packages), start org upgrade runs, approve outbound hosts (org-wide). */\n MANAGE_APPLICATION: 1 << 4,\n /** Create a top-level team without being an admin. */\n CREATE_TEAM: 1 << 5,\n /** Delete a team, and what it holds, without being an admin. */\n DELETE_TEAM: 1 << 6,\n /** Change who may join a team (open or invite-only). */\n MANAGE_VISIBILITY: 1 << 7,\n /** Set the organization's and its teams' metadata. */\n MANAGE_METADATA: 1 << 8,\n /**\n * Approve (or withdraw) the mero-tee releases that hold the apps the\n * organization governs (those of the packages it publishes, and its own of\n * unbound packages), and bind a package signing key to it\n * (`client.orgs.publisher`). Organization-wide only. Bit 9 is left unused.\n */\n APPROVE_RELEASES: 1 << 10,\n} as const;\n\nexport type OrgCapability = keyof typeof ORG_CAPABILITIES;\n\n/** What a member holds unless an admin says otherwise. */\nexport const DEFAULT_ORG_CAPABILITIES = ORG_CAPABILITIES.JOIN_OPEN_TEAMS;\n\n/** The bitmask of `names`. */\nexport function orgCapabilities(...names: OrgCapability[]): number {\n return names.reduce((mask, name) => mask | ORG_CAPABILITIES[name], 0);\n}\n", "/**\n * ChaCha20-Poly1305 (RFC 8439), the AEAD mero-agent-gate's HPKE suite uses.\n * WebCrypto has no ChaCha20, and the SDK takes no runtime dependencies, so it\n * is written here from the RFC. Its tests check it against the RFC's vectors\n * and against Node's own implementation.\n *\n * Only for sealing a provisioning bundle once: short messages, one key per\n * message. Not constant-time in Poly1305's arithmetic (BigInt), which leaks\n * nothing here: the one-time Poly1305 key is never reused.\n */\n\nconst KEY_LEN = 32;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nfunction rotl(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nfunction quarterRound(s: Uint32Array, a: number, b: number, c: number, d: number): void {\n s[a] = (s[a] + s[b]) >>> 0;\n s[d] = rotl(s[d] ^ s[a], 16);\n s[c] = (s[c] + s[d]) >>> 0;\n s[b] = rotl(s[b] ^ s[c], 12);\n s[a] = (s[a] + s[b]) >>> 0;\n s[d] = rotl(s[d] ^ s[a], 8);\n s[c] = (s[c] + s[d]) >>> 0;\n s[b] = rotl(s[b] ^ s[c], 7);\n}\n\nfunction u32le(bytes: Uint8Array, offset: number): number {\n return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;\n}\n\n/** One 64-byte ChaCha20 block (RFC 8439 \u00A72.3). */\nexport function chacha20Block(key: Uint8Array, counter: number, nonce: Uint8Array): Uint8Array {\n const state = new Uint32Array(16);\n state[0] = 0x61707865;\n state[1] = 0x3320646e;\n state[2] = 0x79622d32;\n state[3] = 0x6b206574;\n for (let i = 0; i < 8; i += 1) state[4 + i] = u32le(key, i * 4);\n state[12] = counter >>> 0;\n for (let i = 0; i < 3; i += 1) state[13 + i] = u32le(nonce, i * 4);\n const working = state.slice();\n for (let round = 0; round < 10; round += 1) {\n quarterRound(working, 0, 4, 8, 12);\n quarterRound(working, 1, 5, 9, 13);\n quarterRound(working, 2, 6, 10, 14);\n quarterRound(working, 3, 7, 11, 15);\n quarterRound(working, 0, 5, 10, 15);\n quarterRound(working, 1, 6, 11, 12);\n quarterRound(working, 2, 7, 8, 13);\n quarterRound(working, 3, 4, 9, 14);\n }\n const out = new Uint8Array(64);\n for (let i = 0; i < 16; i += 1) {\n const word = (working[i] + state[i]) >>> 0;\n out[i * 4] = word & 0xff;\n out[i * 4 + 1] = (word >>> 8) & 0xff;\n out[i * 4 + 2] = (word >>> 16) & 0xff;\n out[i * 4 + 3] = (word >>> 24) & 0xff;\n }\n return out;\n}\n\n/** ChaCha20 encryption from block `counter` on (RFC 8439 \u00A72.4). */\nexport function chacha20(key: Uint8Array, counter: number, nonce: Uint8Array, data: Uint8Array): Uint8Array {\n const out = new Uint8Array(data.length);\n for (let offset = 0, block = counter; offset < data.length; offset += 64, block += 1) {\n const stream = chacha20Block(key, block, nonce);\n const end = Math.min(offset + 64, data.length);\n for (let i = offset; i < end; i += 1) out[i] = data[i] ^ stream[i - offset];\n }\n return out;\n}\n\nfunction leToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i -= 1) value = (value << 8n) | BigInt(bytes[i]);\n return value;\n}\n\nconst P1305 = (1n << 130n) - 5n;\n\n/** Poly1305 over `message` with the one-time `key` (RFC 8439 \u00A72.5). */\nexport function poly1305(key: Uint8Array, message: Uint8Array): Uint8Array {\n const r = leToBigInt(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n const s = leToBigInt(key.subarray(16, 32));\n let acc = 0n;\n for (let offset = 0; offset < message.length; offset += 16) {\n const block = message.subarray(offset, Math.min(offset + 16, message.length));\n const n = leToBigInt(block) + (1n << BigInt(8 * block.length));\n acc = ((acc + n) * r) % P1305;\n }\n let tag = (acc + s) & ((1n << 128n) - 1n);\n const out = new Uint8Array(TAG_LEN);\n for (let i = 0; i < TAG_LEN; i += 1) {\n out[i] = Number(tag & 0xffn);\n tag >>= 8n;\n }\n return out;\n}\n\nfunction pad16(length: number): Uint8Array {\n return new Uint8Array((16 - (length % 16)) % 16);\n}\n\nfunction u64le(value: number): Uint8Array {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setBigUint64(0, BigInt(value), true);\n return out;\n}\n\nfunction macData(aad: Uint8Array, ciphertext: Uint8Array): Uint8Array {\n const parts = [aad, pad16(aad.length), ciphertext, pad16(ciphertext.length), u64le(aad.length), u64le(ciphertext.length)];\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction check(key: Uint8Array, nonce: Uint8Array): void {\n if (key.length !== KEY_LEN) throw new Error('ChaCha20-Poly1305 needs a 32-byte key');\n if (nonce.length !== NONCE_LEN) throw new Error('ChaCha20-Poly1305 needs a 12-byte nonce');\n}\n\n/** Seal: the ciphertext followed by its 16-byte tag (RFC 8439 \u00A72.8). */\nexport function chacha20Poly1305Seal(\n key: Uint8Array,\n nonce: Uint8Array,\n plaintext: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n): Uint8Array {\n check(key, nonce);\n const otk = chacha20Block(key, 0, nonce).subarray(0, 32);\n const ciphertext = chacha20(key, 1, nonce, plaintext);\n const tag = poly1305(otk, macData(aad, ciphertext));\n const out = new Uint8Array(ciphertext.length + TAG_LEN);\n out.set(ciphertext);\n out.set(tag, ciphertext.length);\n return out;\n}\n\n/** Open what {@link chacha20Poly1305Seal} made; throws if it was altered. */\nexport function chacha20Poly1305Open(\n key: Uint8Array,\n nonce: Uint8Array,\n sealed: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n): Uint8Array {\n check(key, nonce);\n if (sealed.length < TAG_LEN) throw new Error('The sealed message is shorter than its tag');\n const ciphertext = sealed.subarray(0, sealed.length - TAG_LEN);\n const otk = chacha20Block(key, 0, nonce).subarray(0, 32);\n const expected = poly1305(otk, macData(aad, ciphertext));\n let diff = 0;\n for (let i = 0; i < TAG_LEN; i += 1) diff |= expected[i] ^ sealed[ciphertext.length + i];\n if (diff !== 0) throw new Error('The sealed message did not authenticate');\n return chacha20(key, 1, nonce, ciphertext);\n}\n", "/**\n * RFC 9180 HPKE, the one suite and mode mero-agent-gate takes: Auth mode,\n * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20-Poly1305, single-shot\n * (one message per context, sequence number 0). Auth mode proves the sender:\n * the gate opens a bundle only under the X25519 key it names, so nobody can\n * seal in an owner's name.\n *\n * X25519 and HMAC are WebCrypto; ChaCha20-Poly1305 is ./chacha20poly1305.\n * The tests open what mero-agent-gate (Rust, the `hpke` crate) sealed, and the\n * gate opens what this seals.\n */\n\nimport { concat } from '../crypto/internal.js';\nimport { dh, x25519KeyPair } from '../sealed/noise.js';\nimport { chacha20Poly1305Open, chacha20Poly1305Seal } from './chacha20poly1305.js';\n\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0003; // ChaCha20-Poly1305\nconst MODE_AUTH = 0x02;\nconst N_SECRET = 32;\nconst N_KEY = 32;\nconst N_NONCE = 12;\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\nconst i2osp2 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);\n\nconst KEM_SUITE = concat(utf8('KEM'), i2osp2(KEM_ID));\nconst HPKE_SUITE = concat(utf8('HPKE'), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n // An empty salt is HashLen zeros (RFC 5869); WebCrypto refuses a zero-length HMAC key.\n const raw = key.length === 0 ? new Uint8Array(32) : key;\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, data));\n}\n\nasync function expand(prk: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {\n const out = new Uint8Array(length);\n let previous = new Uint8Array(0);\n for (let i = 1, offset = 0; offset < length; i += 1) {\n previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));\n out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);\n offset += previous.length;\n }\n return out;\n}\n\nfunction labeledExtract(suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array): Promise<Uint8Array> {\n return hmac(salt, concat(utf8('HPKE-v1'), suite, utf8(label), ikm));\n}\n\nfunction labeledExpand(suite: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, length: number) {\n return expand(prk, concat(i2osp2(length), utf8('HPKE-v1'), suite, utf8(label), info), length);\n}\n\nasync function extractAndExpand(dhValue: Uint8Array, kemContext: Uint8Array): Promise<Uint8Array> {\n const prk = await labeledExtract(KEM_SUITE, new Uint8Array(0), 'eae_prk', dhValue);\n return labeledExpand(KEM_SUITE, prk, 'shared_secret', kemContext, N_SECRET);\n}\n\nasync function keySchedule(sharedSecret: Uint8Array, info: Uint8Array): Promise<{ key: Uint8Array; nonce: Uint8Array }> {\n const empty = new Uint8Array(0);\n const pskIdHash = await labeledExtract(HPKE_SUITE, empty, 'psk_id_hash', empty);\n const infoHash = await labeledExtract(HPKE_SUITE, empty, 'info_hash', info);\n const context = concat(new Uint8Array([MODE_AUTH]), pskIdHash, infoHash);\n const secret = await labeledExtract(HPKE_SUITE, sharedSecret, 'secret', empty);\n return {\n key: await labeledExpand(HPKE_SUITE, secret, 'key', context, N_KEY),\n nonce: await labeledExpand(HPKE_SUITE, secret, 'base_nonce', context, N_NONCE),\n };\n}\n\nexport interface HpkeSealed {\n /** The encapsulated key: the sender's ephemeral X25519 public key. */\n enc: Uint8Array;\n ciphertext: Uint8Array;\n}\n\n/**\n * Seal `plaintext` to `recipientPublic` in Auth mode as the holder of\n * `senderSecret` (32 raw X25519 bytes). `ephemeralSecret` is for tests.\n */\nexport async function hpkeSealAuth(\n recipientPublic: Uint8Array,\n senderSecret: Uint8Array,\n info: Uint8Array,\n plaintext: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n ephemeralSecret?: Uint8Array,\n): Promise<HpkeSealed> {\n if (recipientPublic.length !== 32) throw new Error('The recipient key is not 32 bytes of X25519');\n const ephemeral = await x25519KeyPair(ephemeralSecret);\n const sender = await x25519KeyPair(senderSecret);\n const dhValue = concat(await dh(ephemeral.privateKey, recipientPublic), await dh(sender.privateKey, recipientPublic));\n const shared = await extractAndExpand(dhValue, concat(ephemeral.publicKey, recipientPublic, sender.publicKey));\n const { key, nonce } = await keySchedule(shared, info);\n return { enc: ephemeral.publicKey, ciphertext: chacha20Poly1305Seal(key, nonce, plaintext, aad) };\n}\n\n/** Open what {@link hpkeSealAuth} (or the gate's own sealer) made, as the recipient. */\nexport async function hpkeOpenAuth(\n recipientSecret: Uint8Array,\n senderPublic: Uint8Array,\n info: Uint8Array,\n sealed: HpkeSealed,\n aad: Uint8Array = new Uint8Array(0),\n): Promise<Uint8Array> {\n const recipient = await x25519KeyPair(recipientSecret);\n const dhValue = concat(await dh(recipient.privateKey, sealed.enc), await dh(recipient.privateKey, senderPublic));\n const shared = await extractAndExpand(dhValue, concat(sealed.enc, recipient.publicKey, senderPublic));\n const { key, nonce } = await keySchedule(shared, info);\n return chacha20Poly1305Open(key, nonce, sealed.ciphertext, aad);\n}\n", "/**\n * A client for mero-agent-gate, the gate in a private agent TD (mero-tee,\n * `mero-agent-gate/`): attest an agent, claim it with your key, give it its\n * secrets sealed to the TD, and release it. It runs where the owner is (a\n * browser, a CLI), so whoever carries the requests, mdma included, sees only\n * quotes and ciphertext.\n *\n * One agent TD hosts several owners' agents, each named by an agent id. For\n * an agent the gate's quote binds, in its report data:\n *\n * `nonce \u2016 SHA-256(\"mero-agent-gate/attest/v3\" \u2016 provisioning_pub \u2016 len(id) \u2016 id \u2016 signing_pub \u2016 owner_pub)`\n *\n * (signing and owner keys 32 zero bytes while unclaimed). {@link attestAgent}\n * checks that and the quote itself before returning anything; every function\n * that sends refuses an agent whose quote names another owner.\n *\n * ```ts\n * import { verify as dcapVerify, getCollateral } from '@phala/dcap-qvl';\n *\n * const policy = await verifySignedAgentPolicy(policyJson, bundleJson, { profile: 'locked-read-only' });\n * const verifier = agentQuoteVerifier(policy, { dcapVerify, fetchCollateral: (q) => getCollateral(PCCS, q) });\n * const owner = await generateOwnerKey(); // keep owner.secret: it is the only key that can change the agent\n * const agent = await attestAgent({ gateUrl, agentId: 'a-1f2e', verifier });\n * await provisionAgent({ gateUrl, agent, ownerSecret: owner.secret, verifier, secrets: { NEAR_AI_API_KEY: key } });\n * ```\n */\n\nimport { concat, hex } from '../crypto/internal.js';\nimport { x25519KeyPair } from '../sealed/noise.js';\nimport type { VerifyTransportQuote } from '../sealed/sealed.js';\nimport { hpkeSealAuth } from './hpke.js';\n\nexport const AGENT_ATTEST_DOMAIN = 'mero-agent-gate/attest/v3';\nexport const AGENT_PROVISION_INFO_DOMAIN = 'mero-agent-gate/provision/v2';\n\nconst AGENT_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;\nconst SECRET_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;\nconst MAX_SECRETS = 64;\nconst MAX_SECRET_LEN = 64 * 1024;\n\n/** A gate's refusal, with its `error` code (`not_the_owner`, `no_free_slot`, \u2026) when it gave one. */\nexport class AgentGateError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n readonly code?: string,\n ) {\n super(message);\n this.name = 'AgentGateError';\n }\n}\n\n/** An agent's keys, once its quote passed {@link attestAgent}'s checks. */\nexport interface VerifiedAgent {\n agentId: string;\n /** Base64; secrets are sealed to it. Valid until the gate restarts. */\n provisioningPublicKey: string;\n /** Base64 Ed25519 key the agent signs with; absent while unclaimed. */\n signingPublicKey?: string;\n /** Base64 X25519 key of the owner that claimed it; absent while unclaimed. */\n ownerPublicKey?: string;\n}\n\nexport interface OwnerKey {\n /** 32 raw X25519 bytes. The only key that can provision or release the agent: keep it. */\n secret: Uint8Array;\n /** Base64 of the public half: what the gate's quote names as owner. */\n publicKey: string;\n}\n\ntype Fetch = typeof fetch;\n\nexport function validateAgentId(agentId: string): void {\n if (!AGENT_ID.test(agentId)) {\n throw new Error(`Agent id ${JSON.stringify(agentId)} must match [a-z0-9][a-z0-9-]{0,62}`);\n }\n}\n\nfunction utf8(value: string): Uint8Array {\n return new TextEncoder().encode(value);\n}\n\nfunction lengthPrefixed(agentId: string): Uint8Array {\n const id = utf8(agentId);\n return concat(new Uint8Array([id.length]), id);\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction fromBase64(value: string, label: string, length?: number): Uint8Array {\n let bytes: Uint8Array;\n try {\n bytes = Uint8Array.from(atob(value.trim()), (c) => c.charCodeAt(0));\n } catch {\n throw new Error(`${label} is not base64`);\n }\n if (length !== undefined && bytes.length !== length) throw new Error(`${label} is not ${length} bytes`);\n return bytes;\n}\n\n/** The 32 bytes after the nonce in a gate's quote for `agentId` (empty: the TD alone). */\nexport async function agentKeyBinding(\n provisioningPublic: Uint8Array,\n agentId: string,\n signingPublic?: Uint8Array,\n ownerPublic?: Uint8Array,\n): Promise<Uint8Array> {\n const zero = new Uint8Array(32);\n const data = concat(\n utf8(AGENT_ATTEST_DOMAIN),\n provisioningPublic,\n lengthPrefixed(agentId),\n signingPublic ?? zero,\n ownerPublic ?? zero,\n );\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\n/** HPKE `info` for a message to `agentId` on the gate whose provisioning key is `recipientPublic`. */\nexport function provisionInfo(recipientPublic: Uint8Array, agentId: string): Uint8Array {\n return concat(utf8(AGENT_PROVISION_INFO_DOMAIN), recipientPublic, lengthPrefixed(agentId));\n}\n\n/** A fresh owner key, made here; it never needs to leave the owner. */\nexport async function generateOwnerKey(): Promise<OwnerKey> {\n const secret = crypto.getRandomValues(new Uint8Array(32));\n return { secret, publicKey: await ownerPublicKey(secret) };\n}\n\n/** The base64 public half of an owner's X25519 secret. */\nexport async function ownerPublicKey(secret: Uint8Array): Promise<string> {\n if (secret.length !== 32) throw new Error('An owner key is 32 bytes');\n return toBase64((await x25519KeyPair(secret)).publicKey);\n}\n\nfunction url(gateUrl: string, path: string): string {\n return `${gateUrl.replace(/\\/+$/, '')}${path}`;\n}\n\nasync function postJson(fetchImpl: Fetch, target: string, body: unknown): Promise<unknown> {\n const response = await fetchImpl(target, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n let parsed: unknown = undefined;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n // Not JSON: reported below with the status.\n }\n if (!response.ok) {\n const error = parsed as { error?: string; details?: string } | undefined;\n throw new AgentGateError(\n `The gate answered ${response.status}${error?.error ? ` ${error.error}` : ''}: ${error?.details ?? text.slice(0, 200)}`,\n response.status,\n error?.error,\n );\n }\n return parsed;\n}\n\nexport interface AttestAgentOptions {\n /** The gate's base URL, or a relay of it (mdma's): only verified quotes are trusted. */\n gateUrl: string;\n /** The agent to attest; omit for the TD alone (no keys, nothing to send to). */\n agentId?: string;\n /** Checks the quote's signature, TCB, image and report data: {@link agentQuoteVerifier}. */\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\ninterface AttestResponseBody {\n quoteB64: string;\n provisioningPublicKeyB64: string;\n agentId?: string;\n signingPublicKeyB64?: string;\n ownerPublicKeyB64?: string;\n}\n\n/**\n * Ask the gate for a quote for `agentId` over a fresh nonce and verify it:\n * a genuine quote from a measured agent image, for this nonce, committing to\n * the agent id asked about and to the keys the gate names. Returns those\n * keys only once every check has passed.\n */\nexport async function attestAgent(options: AttestAgentOptions): Promise<VerifiedAgent> {\n const agentId = options.agentId ?? '';\n if (agentId) validateAgentId(agentId);\n const nonce = crypto.getRandomValues(new Uint8Array(32));\n const body = (await postJson(options.fetch ?? fetch, url(options.gateUrl, '/attest'), {\n nonceB64: toBase64(nonce),\n ...(agentId ? { agentId } : {}),\n })) as AttestResponseBody;\n if ((body?.agentId ?? '') !== agentId) {\n throw new Error(`Asked about agent ${JSON.stringify(agentId)}, the gate answered for ${JSON.stringify(body?.agentId)}`);\n }\n const provisioning = fromBase64(body.provisioningPublicKeyB64 ?? '', 'provisioningPublicKeyB64', 32);\n const signing = body.signingPublicKeyB64 ? fromBase64(body.signingPublicKeyB64, 'signingPublicKeyB64', 32) : undefined;\n const owner = body.ownerPublicKeyB64 ? fromBase64(body.ownerPublicKeyB64, 'ownerPublicKeyB64', 32) : undefined;\n if (!signing !== !owner) {\n throw new Error('A claimed agent has both a signing key and an owner; the gate named one');\n }\n // The id asked about, not the one answered: a quote for another agent fails here.\n const binding = await agentKeyBinding(provisioning, agentId, signing, owner);\n await options.verifier({ quoteB64: body.quoteB64, nonce: hex(nonce), reportDataSuffix: hex(binding) });\n return {\n agentId,\n provisioningPublicKey: toBase64(provisioning),\n ...(signing ? { signingPublicKey: toBase64(signing) } : {}),\n ...(owner ? { ownerPublicKey: toBase64(owner) } : {}),\n };\n}\n\n/** The owner key `ownerSecret` may act on `agent`: it is unclaimed, or claimed by that key. */\nexport async function checkOwner(agent: VerifiedAgent, ownerSecret: Uint8Array): Promise<string> {\n const mine = await ownerPublicKey(ownerSecret);\n if (agent.ownerPublicKey && agent.ownerPublicKey !== mine) {\n throw new AgentGateError(\n `This agent is claimed by another key (${agent.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,\n undefined,\n 'not_yours',\n );\n }\n return mine;\n}\n\nfunction validateSecrets(secrets: Record<string, string>): void {\n const names = Object.keys(secrets);\n if (names.length === 0) throw new Error('There are no secrets to provision');\n if (names.length > MAX_SECRETS) throw new Error(`At most ${MAX_SECRETS} secrets at once`);\n for (const name of names) {\n if (!SECRET_NAME.test(name)) throw new Error(`Secret name ${JSON.stringify(name)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);\n if (typeof secrets[name] !== 'string') throw new Error(`Secret ${name} is not a string`);\n if (utf8(secrets[name]).length > MAX_SECRET_LEN) throw new Error(`Secret ${name} is over ${MAX_SECRET_LEN} bytes`);\n }\n}\n\nasync function sendSealed(\n fetchImpl: Fetch,\n gateUrl: string,\n path: '/provision' | '/release',\n agent: VerifiedAgent,\n ownerSecret: Uint8Array,\n message: unknown,\n): Promise<unknown> {\n if (!agent.agentId) throw new Error('This quote names no agent; attest with the agent id');\n const mine = await checkOwner(agent, ownerSecret);\n const recipient = fromBase64(agent.provisioningPublicKey, 'provisioningPublicKey', 32);\n const sealed = await hpkeSealAuth(\n recipient,\n ownerSecret,\n provisionInfo(recipient, agent.agentId),\n utf8(JSON.stringify(message)),\n );\n return postJson(fetchImpl, url(gateUrl, path), {\n agentId: agent.agentId,\n provisioningPublicKeyB64: agent.provisioningPublicKey,\n senderPublicKeyB64: mine,\n encappedKeyB64: toBase64(sealed.enc),\n ciphertextB64: toBase64(sealed.ciphertext),\n });\n}\n\nexport interface ProvisionAgentOptions {\n gateUrl: string;\n /** What {@link attestAgent} returned for this agent, just now. */\n agent: VerifiedAgent;\n ownerSecret: Uint8Array;\n /** Name to value; a name replaces what was there, others stay. */\n secrets: Record<string, string>;\n /** The verifier `agent` was attested with: the claim is checked by a fresh quote. */\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\nexport interface ProvisionedAgent extends Required<VerifiedAgent> {\n written: string[];\n /** Whether this claimed the agent for your key. */\n claimed: boolean;\n}\n\n/**\n * Seal `secrets` to the agent as its owner and send them. The first bundle for\n * an unclaimed agent claims it for `ownerSecret`'s key. The gate's answer is\n * not taken as proof: a fresh quote must name your key as owner, and the\n * agent's signing key must not have changed.\n */\nexport async function provisionAgent(options: ProvisionAgentOptions): Promise<ProvisionedAgent> {\n validateSecrets(options.secrets);\n const fetchImpl = options.fetch ?? fetch;\n const answer = (await sendSealed(fetchImpl, options.gateUrl, '/provision', options.agent, options.ownerSecret, {\n secrets: options.secrets,\n })) as { written?: string[]; claimed?: boolean };\n const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });\n const mine = await ownerPublicKey(options.ownerSecret);\n if (after.ownerPublicKey !== mine || !after.signingPublicKey) {\n throw new AgentGateError('The gate accepted the secrets, but its quote does not name your key as owner');\n }\n if (options.agent.signingPublicKey && options.agent.signingPublicKey !== after.signingPublicKey) {\n throw new AgentGateError(\"The agent's signing key changed while provisioning\");\n }\n return {\n agentId: after.agentId,\n provisioningPublicKey: after.provisioningPublicKey,\n signingPublicKey: after.signingPublicKey,\n ownerPublicKey: mine,\n written: answer?.written ?? [],\n claimed: answer?.claimed === true,\n };\n}\n\nexport interface ReleaseAgentOptions {\n gateUrl: string;\n agent: VerifiedAgent;\n ownerSecret: Uint8Array;\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\n/**\n * Release the agent as its owner: the gate stops it and erases its claim,\n * keys, secrets and state. Checked by a fresh quote that names no owner.\n */\nexport async function releaseAgent(options: ReleaseAgentOptions): Promise<void> {\n if (!options.agent.ownerPublicKey) throw new Error('This agent is not claimed; there is nothing to release');\n const fetchImpl = options.fetch ?? fetch;\n await sendSealed(fetchImpl, options.gateUrl, '/release', options.agent, options.ownerSecret, { release: true });\n const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });\n if (after.ownerPublicKey) {\n throw new AgentGateError('The gate says it released the agent, but its quote still names an owner');\n }\n}\n", "/**\n * Which agent images to trust: a mero-kms release's signed agent allowlist,\n * `kms-agent-attestation-policy.<profile>.json`, and a quote verifier built\n * from it.\n *\n * The KMS release workflow measures the release's agent image and signs its\n * allowlist with cosign keyless, beside the rest of the release. The allowlist\n * can therefore come from anywhere (a release asset, mdma's mirror, a file in\n * the app): {@link verifySignedAgentPolicy} checks the signature here, against\n * the Sigstore trust root embedded in this package, and refuses anything else.\n */\n\nimport { verifyCosignBundle, type SignerIdentity } from '../sealed/sigstore.js';\nimport {\n PRODUCTION_PROFILE,\n createQuoteVerifier,\n type DcapCollateral,\n type DcapVerify,\n type QuoteVerifier,\n} from '../sealed/verify.js';\n\n/** The workflow that signs every mero-kms release, agent allowlists included. */\nexport const KMS_RELEASE_SIGNER: Readonly<SignerIdentity> = Object.freeze({\n identity: 'https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master',\n issuer: 'https://token.actions.githubusercontent.com',\n});\n\n/** An agent allowlist, as the KMS release publishes it. Every list must be non-empty. */\nexport interface AgentPolicy {\n schema_version?: number;\n role?: string;\n profile?: string;\n /** The mero-kms release it belongs to. */\n version?: string;\n allowed_tcb_statuses: string[];\n allowed_mrtd: string[];\n allowed_rtmr0: string[];\n allowed_rtmr1: string[];\n allowed_rtmr2: string[];\n allowed_rtmr3: string[];\n}\n\nconst LISTS = [\n 'allowed_tcb_statuses',\n 'allowed_mrtd',\n 'allowed_rtmr0',\n 'allowed_rtmr1',\n 'allowed_rtmr2',\n 'allowed_rtmr3',\n] as const;\n\nexport interface VerifySignedAgentPolicyOptions {\n /** Require this profile; defaults to `locked-read-only`, the only one whose host cannot reach in. */\n profile?: string;\n /** Require the file's `version` to be this mero-kms release. */\n expectedVersion?: string;\n /** The certificate identity required. Defaults to {@link KMS_RELEASE_SIGNER}'s. */\n identity?: string;\n /** The OIDC issuer required. Defaults to {@link KMS_RELEASE_SIGNER}'s. */\n issuer?: string;\n /**\n * The image role the allowlist must be for: `agent` (the default), or\n * `inference`, the release's `kms-inference-attestation-policy.<profile>.json`\n * for its private inference image. Both have the same shape and signer.\n */\n role?: 'agent' | 'inference';\n}\n\n/**\n * Verify an agent allowlist against its cosign bundle, as `cosign verify-blob`\n * would, and return it parsed. Rejects unless it was signed by the KMS release\n * workflow, it is an allowlist for `options.role` (default `agent`) and the profile asked\n * for, every list in it is non-empty, and `expectedVersion`, when given, is its\n * `version`.\n */\nexport async function verifySignedAgentPolicy(\n policy: string | Uint8Array,\n bundle: string | object,\n options: VerifySignedAgentPolicyOptions = {},\n): Promise<AgentPolicy> {\n const body = typeof policy === 'string' ? new TextEncoder().encode(policy) : policy;\n await verifyCosignBundle(body, bundle, {\n identity: options.identity ?? KMS_RELEASE_SIGNER.identity,\n issuer: options.issuer ?? KMS_RELEASE_SIGNER.issuer,\n });\n let parsed: AgentPolicy;\n try {\n parsed = JSON.parse(new TextDecoder().decode(body));\n } catch {\n throw new Error('The signed agent policy is not JSON');\n }\n const role = options.role ?? 'agent';\n if (parsed?.role !== role) {\n throw new Error(`The signed file is a ${JSON.stringify(parsed?.role)} policy, not an ${role} one`);\n }\n const profile = options.profile ?? PRODUCTION_PROFILE;\n if (parsed.profile !== profile) {\n throw new Error(`The signed agent policy is for the ${JSON.stringify(parsed.profile)} profile, not ${profile}`);\n }\n if (options.expectedVersion !== undefined && parsed.version !== options.expectedVersion) {\n throw new Error(`The signed agent policy is release ${JSON.stringify(parsed.version)}, not ${options.expectedVersion}`);\n }\n checkLists(parsed);\n return parsed;\n}\n\nfunction checkLists(policy: AgentPolicy): void {\n for (const list of LISTS) {\n if (!Array.isArray(policy?.[list]) || policy[list].length === 0) {\n // As the gate's own verifier: an empty list accepts nothing.\n throw new Error(`The agent policy's ${list} is empty, so no agent would be accepted`);\n }\n }\n}\n\n/** DCAP's spelling of each TCB status; the policy may use any case. */\nconst TCB_STATUSES = [\n 'UpToDate',\n 'SWHardeningNeeded',\n 'ConfigurationNeeded',\n 'ConfigurationAndSWHardeningNeeded',\n 'OutOfDate',\n 'OutOfDateConfigurationNeeded',\n];\n\nfunction tcbStatus(value: string): string {\n const found = TCB_STATUSES.find((status) => status.toLowerCase() === value.trim().toLowerCase());\n if (!found) throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(value)}`);\n return found;\n}\n\nconst register = (value: string) => value.trim().replace(/^0x/i, '');\n\nexport interface AgentQuoteVerifierOptions {\n /** `verify` from `@phala/dcap-qvl`, or anything that verifies a quote the same way. */\n dcapVerify: DcapVerify;\n /**\n * The gate sends no collateral: fetch it, e.g.\n * `(quote) => getCollateral(PHALA_PCCS_URL, quote)` from `@phala/dcap-qvl`.\n */\n fetchCollateral: (quote: Uint8Array) => Promise<DcapCollateral>;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/**\n * A verifier for {@link attestAgent} that accepts a quote only from an agent\n * image in `policy`: its signature and collateral verify, its TCB status is\n * one the policy allows (never `Revoked`), it is not a debug TD, and each of\n * MRTD and RTMR0-3 is in the policy's list. Mock quotes never pass.\n */\nexport function agentQuoteVerifier(policy: AgentPolicy, options: AgentQuoteVerifierOptions): QuoteVerifier {\n checkLists(policy);\n return createQuoteVerifier({\n dcapVerify: options.dcapVerify,\n fetchCollateral: options.fetchCollateral,\n now: options.now,\n allowedTcbStatuses: policy.allowed_tcb_statuses.map(tcbStatus),\n allowedMrtd: policy.allowed_mrtd.map(register),\n allowedRtmr0: policy.allowed_rtmr0.map(register),\n allowedRtmr1: policy.allowed_rtmr1.map(register),\n allowedRtmr2: policy.allowed_rtmr2.map(register),\n allowedRtmr3: policy.allowed_rtmr3.map(register),\n });\n}\n", "/**\n * The recovery disk's files, as their holder's device handles them.\n *\n * A Calimero node (`merod --recovery-dir`) writes each app's backup sealed to\n * the X25519 public key of whoever upgrades the app: the operator, or the\n * app's organization or owner account. Only that key's private half opens a\n * file, and it never reaches a node. The device:\n *\n * 1. makes the key pair ({@link newBackupKeyPair}) and registers the public\n * half (`POST /orgs/{org}/backup-key` or `/auth/backup-key`, with a passkey);\n * 2. after a loss, gets the files' headers (`GET /ops/recovery-files`, through\n * the operator), checks each with {@link verifyRecoveryHeader} and opens\n * each one's data key with {@link openDataKey};\n * 3. sends those keys straight to the node, over the attested sealed channel\n * (`POST /recover/holder`, {@link holderRecoveryBody}).\n *\n * The format is core's `calimero_client::recovery`: HPKE (RFC 9180) base mode,\n * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM, `info`\n * {@link HPKE_INFO}, `aad` {@link HPKE_AAD}; the header is JSON signed by the\n * node's Ed25519 receipt key over {@link SIGNING_LABEL} and its bytes. The\n * tests open what core sealed. {@link verifyRecoveryAttestation} checks, as\n * core's `verify_attestation` does, that the signing key is an attested node's\n * receipt key: give it the quote verifier the client trusts nodes with.\n */\n\nimport { concat, fromHex, hex } from '../crypto/internal.js';\nimport { dh, x25519KeyPair } from '../sealed/noise.js';\nimport type { VerifyTransportQuote } from '../sealed/sealed.js';\n\nexport const RECOVERY_FORMAT = 1;\nexport const SIGNING_LABEL = new TextEncoder().encode('calimero.recovery-backup.v1\\0');\nexport const HPKE_INFO = new TextEncoder().encode('calimero.recovery-backup.v1');\nexport const HPKE_AAD = new TextEncoder().encode('calimero.recovery-backup.key.v1');\n\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0002; // AES-256-GCM\nconst MODE_BASE = 0x00;\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\nconst i2osp2 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);\nconst KEM_SUITE = concat(utf8('KEM'), i2osp2(KEM_ID));\nconst HPKE_SUITE = concat(utf8('HPKE'), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));\n\n/** Who holds a backup key: `{ kind: 'operator' }`, `{ kind: 'org', id }`, `{ kind: 'account', id }`. */\nexport type BackupHolder = { kind: 'operator' } | { kind: 'org'; id: string } | { kind: 'account'; id: string };\n\n/** What a recovery file's header says (core's `recovery::Header`). */\nexport interface RecoveryHeader {\n format: number;\n kind: 'app' | 'holder' | 'system' | 'code';\n holder: BackupHolder;\n cluster: string;\n app?: string;\n org?: string;\n hash?: string;\n group: number;\n index: number;\n writtenAt: number;\n merod: string;\n release: string;\n node: number;\n recipient: string;\n enc: string;\n wrappedKey: string;\n size: number;\n sha256: string;\n bodyBytes: number;\n bodySha256: string;\n signingKey: string;\n attestation: unknown;\n}\n\n/** A listed file as `GET /ops/recovery-files` answers it. */\nexport interface ListedRecoveryFile {\n name: string;\n /** The header as signed (JSON text). */\n header: string;\n /** The node's Ed25519 signature, hex. */\n signature: string;\n}\n\n/** `operator`, `org:<id>` or `account:<id>`: how routes name a holder. */\nexport function holderKey(holder: BackupHolder): string {\n return holder.kind === 'operator' ? 'operator' : `${holder.kind}:${holder.id}`;\n}\n\n/**\n * A new backup key pair: keep `secret` (32 raw bytes) off every node, offline;\n * register `publicKey` (64 hex).\n */\nexport async function newBackupKeyPair(): Promise<{ secret: Uint8Array; publicKey: string }> {\n const secret = crypto.getRandomValues(new Uint8Array(32));\n return { secret, publicKey: await backupPublicKey(secret) };\n}\n\n/** The public key (64 hex) of a backup key's secret. */\nexport async function backupPublicKey(secret: Uint8Array): Promise<string> {\n return hex((await x25519KeyPair(secret)).publicKey);\n}\n\n/**\n * Check a header against the node's signature and read it. Refuses a format\n * newer than this release reads and a signature that does not hold.\n */\nexport async function verifyRecoveryHeader(file: Pick<ListedRecoveryFile, 'header' | 'signature'>): Promise<RecoveryHeader> {\n const bytes = utf8(file.header);\n const header = JSON.parse(file.header) as RecoveryHeader;\n if (typeof header.format !== 'number' || header.format > RECOVERY_FORMAT) {\n throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);\n }\n const key = await crypto.subtle.importKey(\n 'raw',\n fromHex(header.signingKey, 'signing key', 32),\n { name: 'Ed25519' },\n false,\n ['verify'],\n );\n const ok = await crypto.subtle.verify(\n 'Ed25519',\n key,\n fromHex(file.signature, 'signature', 64),\n concat(SIGNING_LABEL, bytes),\n );\n if (!ok) throw new Error(\"the node's signature over the header does not hold\");\n return header;\n}\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n const raw = key.length === 0 ? new Uint8Array(32) : key;\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, data));\n}\n\nasync function expand(prk: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {\n const out = new Uint8Array(length);\n let previous = new Uint8Array(0);\n for (let i = 1, offset = 0; offset < length; i += 1) {\n previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));\n out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);\n offset += previous.length;\n }\n return out;\n}\n\nconst labeledExtract = (suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array) =>\n hmac(salt, concat(utf8('HPKE-v1'), suite, utf8(label), ikm));\n\nconst labeledExpand = (suite: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, length: number) =>\n expand(prk, concat(i2osp2(length), utf8('HPKE-v1'), suite, utf8(label), info), length);\n\n/** Open a file's data key (32 bytes) with the holder's secret: HPKE base mode. */\nexport async function openDataKey(header: RecoveryHeader, secret: Uint8Array): Promise<Uint8Array> {\n const recipient = await x25519KeyPair(secret);\n if (hex(recipient.publicKey) !== header.recipient) {\n throw new Error('this key is not the one the file was sealed to');\n }\n const enc = fromHex(header.enc, 'encapsulated key', 32);\n const dhValue = await dh(recipient.privateKey, enc);\n const empty = new Uint8Array(0);\n const prk = await labeledExtract(KEM_SUITE, empty, 'eae_prk', dhValue);\n const shared = await labeledExpand(KEM_SUITE, prk, 'shared_secret', concat(enc, recipient.publicKey), 32);\n const pskIdHash = await labeledExtract(HPKE_SUITE, empty, 'psk_id_hash', empty);\n const infoHash = await labeledExtract(HPKE_SUITE, empty, 'info_hash', HPKE_INFO);\n const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);\n const schedule = await labeledExtract(HPKE_SUITE, shared, 'secret', empty);\n const key = await labeledExpand(HPKE_SUITE, schedule, 'key', context, 32);\n const nonce = await labeledExpand(HPKE_SUITE, schedule, 'base_nonce', context, 12);\n const aes = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce, additionalData: HPKE_AAD },\n aes,\n fromHex(header.wrappedKey, 'wrapped key', 48),\n ),\n );\n } catch {\n throw new Error('this key does not open the file');\n }\n if (plain.length !== 32) throw new Error('the data key is not 32 bytes');\n return plain;\n}\n\n/** `{ file, key }`: a file and its opened data key, as the recovery routes take them. */\nexport interface OpenedRecoveryFile {\n file: string;\n key: string;\n}\n\n/**\n * The body of `POST /recover/holder` from a holder's listed files: the newest\n * `holder` file, the newest file of each app in `apps` (all of them when\n * absent) and every code file, each checked and opened with `secret`; with\n * `verifyQuote`, each one's attestation too ({@link verifyRecoveryAttestation}).\n */\nexport async function holderRecoveryBody(\n holder: BackupHolder,\n files: ListedRecoveryFile[],\n secret: Uint8Array,\n options: { apps?: string[]; verifyQuote?: VerifyTransportQuote } = {},\n): Promise<{ holder: string; slice: OpenedRecoveryFile; apps: OpenedRecoveryFile[]; code: OpenedRecoveryFile[] }> {\n const checked: { name: string; header: RecoveryHeader }[] = [];\n for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {\n const header = await verifyRecoveryHeader(f);\n if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);\n if (holderKey(header.holder) !== holderKey(holder)) {\n throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);\n }\n checked.push({ name: f.name, header });\n }\n const open = async (c: { name: string; header: RecoveryHeader }) => ({\n file: c.name,\n key: hex(await openDataKey(c.header, secret)),\n });\n const slice = checked.filter((c) => c.header.kind === 'holder').pop();\n if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);\n const newestByApp = new Map<string, { name: string; header: RecoveryHeader }>();\n for (const c of checked) {\n if (c.header.kind === 'app' && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {\n newestByApp.set(c.header.app, c);\n }\n }\n return {\n holder: holderKey(holder),\n slice: await open(slice),\n apps: await Promise.all([...newestByApp.values()].map(open)),\n code: await Promise.all(checked.filter((c) => c.header.kind === 'code').map(open)),\n };\n}\n\nasync function sha256(data: Uint8Array): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\n/** The nonce a node's recovery attestation binds (core's `recovery::attestation_nonce`), hex. */\nexport async function recoveryAttestationNonce(cluster: string, node: number): Promise<string> {\n const name = utf8(cluster);\n const len = new Uint8Array(4);\n new DataView(len.buffer).setUint32(0, name.length, false);\n const id = new Uint8Array(8);\n new DataView(id.buffer).setBigUint64(0, BigInt(node), false);\n return hex(await sha256(concat(utf8('calimero.recovery-backup.attest.v1\\0'), len, name, id)));\n}\n\n/**\n * What a receipt-key quote binds after its nonce (core's `receipt_key_binding`),\n * hex: the key and the cluster's governance, as the node serialized it.\n */\nexport async function receiptKeyBinding(receiptKey: Uint8Array, governance: unknown): Promise<string> {\n const g = await sha256(utf8(JSON.stringify(governance)));\n return hex(await sha256(concat(utf8('calimero.tee-attest.receipt-key.v2'), receiptKey, g)));\n}\n\ninterface ReceiptAttestation {\n quote: string;\n nonce: string;\n cluster: string;\n node: number;\n receiptKey?: string;\n governance?: unknown;\n}\n\n/**\n * Check that the key that signed `header` is a node's receipt key, attested\n * (`purpose=receipts`) by a quote `verifyQuote` accepts: attested hardware\n * wrote the file. Rejects with the reason.\n */\nexport async function verifyRecoveryAttestation(\n header: RecoveryHeader,\n verifyQuote: VerifyTransportQuote,\n): Promise<void> {\n const doc = header.attestation as ReceiptAttestation | null;\n if (!doc || typeof doc.quote !== 'string') throw new Error('the file carries no attestation');\n if (doc.cluster !== header.cluster || doc.node !== header.node) {\n throw new Error(\"the attestation is another node's\");\n }\n if (doc.receiptKey !== header.signingKey) {\n throw new Error('the attested key is not the one that signed the file');\n }\n const nonce = await recoveryAttestationNonce(header.cluster, header.node);\n if (doc.nonce !== nonce) throw new Error('the attestation is not over the recovery nonce');\n const reportDataSuffix = await receiptKeyBinding(fromHex(header.signingKey, 'signing key', 32), doc.governance);\n const ok = await verifyQuote({ quoteB64: doc.quote, nonce, reportDataSuffix });\n if (!ok) throw new Error('the quote was not accepted');\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,EACrD;AACA,MAAI,IAAI,eAAe,OAAO,YAAY;AACxC,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AACA,QAAMS,SAAQ,MAAM,yBAAyB,OAAO,SAAS,OAAO,IAAI;AACxE,MAAI,IAAI,UAAUA,OAAO,OAAM,IAAI,MAAM,gDAAgD;AACzF,QAAM,mBAAmB,MAAM,kBAAkB,QAAQ,OAAO,YAAY,eAAe,EAAE,GAAG,IAAI,UAAU;AAC9G,QAAM,KAAK,MAAM,YAAY,EAAE,UAAU,IAAI,OAAO,OAAAA,QAAO,iBAAiB,CAAC;AAC7E,MAAI,CAAC,GAAI,OAAM,IAAI,MAAM,4BAA4B;AACvD;",
4
+ "sourcesContent": ["// Mero.js: the JavaScript client for Calimero 1.0, the confidential cloud.\n//\n// `CalimeroClient` verifies a node's TDX attestation, seals every request to\n// it, and signs people in with passkeys and machines with API keys; its\n// groups (`client.orgs.get({ org })`, ...) are every route of the node,\n// generated from core's OpenAPI document. Everything below it is the pieces it\n// is built from, exported for callers who need one on its own. The layering\n// (runtime/ \u2192 generated/ + routes/ \u2192 client/) is described in\n// src/routes/index.ts.\n\n// The client, its errors and its types\nexport * from './client/index.js';\n\n// The node's routes as generated methods (`createRoutes`), the passkey answer\n// to a step-up (`passkeyConfirm`), and names for the document's types.\nexport * from './routes/index.js';\n\n// The runtime the client sends every route through (also its own entry point,\n// `@calimero-network/mero-js/runtime`): one `Transport.request` over the\n// attested, sealed channel, with the session, step-up and error mapping.\nexport {\n DEFAULT_RETRY,\n NodeTransport,\n directoryTransport,\n newIdempotencyKey,\n queryString,\n refusal,\n retryDelayMs,\n routePath,\n sseFrames,\n} from './runtime/transport.js';\nexport type {\n DirectorySource,\n HttpMethod,\n NodeTransportOptions,\n QueryValue,\n RequestOptions,\n Transport,\n} from './runtime/transport.js';\n\n// Sealed transport: requests encrypted end to end to a TEE node's attested key,\n// and the checks that decide whether a quote is trusted.\nexport * from './sealed/index.js';\n\n// Private agents (mero-tee's agent gate): attest one, claim it with your key,\n// give it its secrets sealed to its TD.\nexport * from './agent-gate/index.js';\n// The recovery disk's files as their holder's device opens them.\nexport * from './recovery/backup-files.js';\n", "/**\n * Byte-level primitives shared by the sealed transport, the attestation check\n * and the agent gate: hex handling, fixed-width integers and concatenation.\n * Internal \u2014 not exported from the package root.\n */\n\n/** Little-endian u32, for borsh fixed-width fields and epoch counters. */\nexport function u32le(value: number): Uint8Array {\n const out = new Uint8Array(4);\n new DataView(out.buffer).setUint32(0, value, true);\n return out;\n}\n\nexport function hex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nexport function fromHex(value: string, label: string, expectedBytes: number): Uint8Array {\n const clean = value.trim();\n if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length !== expectedBytes * 2) {\n throw new Error(\n `${label} must be ${expectedBytes * 2} hex characters, got ${clean.length}`,\n );\n }\n // Indexed rather than `match(/../g)!`: the length is already validated above,\n // so the assertion would only be telling the compiler what the guard proved,\n // and this needs no assertion at all.\n const bytes = new Uint8Array(expectedBytes);\n for (let i = 0; i < expectedBytes; i += 1) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Decode hex of an unknown length.\n *\n * The sized {@link fromHex} is the right default \u2014 every key and digest here\n * has a fixed width, and checking it catches a truncated paste at the edge\n * rather than deep inside a signature check. This one exists for the already-\n * encoded structures whose length is genuinely variable: a device certificate,\n * a login statement, a request signature. It still rejects odd-length and\n * non-hex input, so the only check it gives up is the one that cannot apply.\n */\nexport function fromHexUnsized(value: string, label: string): Uint8Array {\n const clean = value.trim();\n if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length % 2 !== 0) {\n throw new Error(`${label} must be an even number of hex characters`);\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i += 1) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nexport function u64le(value: number | bigint): Uint8Array {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setBigUint64(0, BigInt(value), true);\n return out;\n}\n\nexport function concat(...parts: Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, p) => total + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n", "/**\n * The Noise NK handshake (`Noise_NK_25519_AESGCM_SHA256`) that opens a sealed\n * session, written against WebCrypto from the Noise specification\n * (revision 34, http://www.noiseprotocol.org/noise.html). The node runs the\n * other side with `snow`; core's published vectors check the two against each\n * other.\n *\n * NK: the initiator knows the responder's static key in advance \u2014 here the\n * transport key the node's quote commits to \u2014 and sends nothing but an\n * ephemeral key before both ephemerals are mixed in, so everything after the\n * handshake has forward secrecy.\n */\n\nimport { concat } from '../crypto/internal.js';\n\nconst PROTOCOL_NAME = 'Noise_NK_25519_AESGCM_SHA256';\nconst DH_LEN = 32;\nconst TAG_LEN = 16;\n/** PKCS#8 wrapping of a raw X25519 private key (RFC 8410). */\nconst PKCS8_X25519_PREFIX = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04,\n 0x22, 0x04, 0x20,\n]);\n\n/** Noise's `SymmetricState`: the chaining key, the handshake hash and the cipher key. */\nexport class SymmetricState {\n private ck: Uint8Array;\n private h: Uint8Array;\n private k: CryptoKey | null = null;\n private n = 0;\n\n private constructor(h: Uint8Array) {\n this.ck = h;\n this.h = h;\n }\n\n static async initialize(): Promise<SymmetricState> {\n // A name of 32 bytes or fewer is used as the hash, zero-padded.\n const name = new TextEncoder().encode(PROTOCOL_NAME);\n const h = new Uint8Array(32);\n h.set(name);\n return new SymmetricState(h);\n }\n\n async mixHash(data: Uint8Array): Promise<void> {\n this.h = await sha256(concat(this.h, data));\n }\n\n async mixKey(inputKeyMaterial: Uint8Array): Promise<void> {\n const [ck, key] = await hkdf2(this.ck, inputKeyMaterial);\n this.ck = ck;\n this.k = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt', 'decrypt']);\n this.n = 0;\n }\n\n async encryptAndHash(plaintext: Uint8Array): Promise<Uint8Array> {\n if (!this.k) throw new Error('Noise: no cipher key yet');\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: noiseNonce(this.n), additionalData: this.h },\n this.k,\n plaintext,\n ),\n );\n this.n += 1;\n await this.mixHash(ciphertext);\n return ciphertext;\n }\n\n async decryptAndHash(ciphertext: Uint8Array): Promise<Uint8Array> {\n if (!this.k) throw new Error('Noise: no cipher key yet');\n const plaintext = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: noiseNonce(this.n), additionalData: this.h },\n this.k,\n ciphertext,\n ),\n );\n this.n += 1;\n await this.mixHash(ciphertext);\n return plaintext;\n }\n\n /** The initiator-to-responder key, then the responder-to-initiator key. */\n split(): Promise<[Uint8Array, Uint8Array]> {\n return hkdf2(this.ck, new Uint8Array());\n }\n}\n\nexport interface X25519KeyPair {\n privateKey: CryptoKey;\n publicKey: Uint8Array;\n}\n\n/**\n * Start an NK handshake to `remoteStatic`. `fixedEphemeral` pins the\n * ephemeral secret, for the published test vectors only; leave it out.\n */\nexport async function initiate(\n remoteStatic: Uint8Array,\n prologue: Uint8Array,\n fixedEphemeral?: Uint8Array,\n): Promise<{\n message1: Uint8Array;\n finish(message2: Uint8Array): Promise<{ payload: Uint8Array; split: [Uint8Array, Uint8Array] }>;\n}> {\n const state = await SymmetricState.initialize();\n await state.mixHash(prologue);\n // <- s (known in advance)\n await state.mixHash(remoteStatic);\n // -> e, es\n const ephemeral = await x25519KeyPair(fixedEphemeral);\n await state.mixHash(ephemeral.publicKey);\n await state.mixKey(await dh(ephemeral.privateKey, remoteStatic));\n const message1 = concat(ephemeral.publicKey, await state.encryptAndHash(new Uint8Array()));\n\n return {\n message1,\n async finish(message2) {\n if (message2.length < DH_LEN + TAG_LEN) throw new Error('Noise: message 2 is too short');\n // <- e, ee\n const remoteEphemeral = message2.slice(0, DH_LEN);\n await state.mixHash(remoteEphemeral);\n await state.mixKey(await dh(ephemeral.privateKey, remoteEphemeral));\n const payload = await state.decryptAndHash(message2.slice(DH_LEN));\n return { payload, split: await state.split() };\n },\n };\n}\n\nexport async function x25519KeyPair(secret?: Uint8Array): Promise<X25519KeyPair> {\n if (!secret) {\n let pair: CryptoKeyPair;\n try {\n pair = (await crypto.subtle.generateKey({ name: 'X25519' }, true, [\n 'deriveBits',\n ])) as CryptoKeyPair;\n } catch (error) {\n throw new Error(\n 'Sealed transport needs WebCrypto with X25519, which this runtime lacks ' +\n `(${(error as Error)?.name ?? 'no crypto.subtle'}). Current browsers and Node have ` +\n 'it; in React Native, install react-native-quick-crypto as the global crypto.',\n );\n }\n const publicKey = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n return { privateKey: pair.privateKey, publicKey };\n }\n const privateKey = await crypto.subtle.importKey(\n 'pkcs8',\n concat(PKCS8_X25519_PREFIX, secret),\n { name: 'X25519' },\n true,\n ['deriveBits'],\n );\n const jwk = await crypto.subtle.exportKey('jwk', privateKey);\n return { privateKey, publicKey: base64UrlDecode(jwk.x as string) };\n}\n\nexport async function dh(privateKey: CryptoKey, publicKey: Uint8Array): Promise<Uint8Array> {\n const peer = await crypto.subtle.importKey('raw', publicKey, { name: 'X25519' }, false, []);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'X25519', public: peer } as EcdhKeyDeriveParams, privateKey, 256),\n );\n}\n\n/** Noise's AESGCM nonce: 32 zero bits, then the counter as a big-endian u64. */\nfunction noiseNonce(n: number): Uint8Array {\n const nonce = new Uint8Array(12);\n new DataView(nonce.buffer).setBigUint64(4, BigInt(n), false);\n return nonce;\n}\n\nasync function sha256(data: Uint8Array): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\nasync function hmacSha256(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n const hmacKey = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n ]);\n return new Uint8Array(await crypto.subtle.sign('HMAC', hmacKey, data));\n}\n\n/** Noise's `HKDF` with two outputs. */\nasync function hkdf2(chainingKey: Uint8Array, inputKeyMaterial: Uint8Array): Promise<[Uint8Array, Uint8Array]> {\n const temp = await hmacSha256(chainingKey, inputKeyMaterial);\n const first = await hmacSha256(temp, new Uint8Array([1]));\n const second = await hmacSha256(temp, concat(first, new Uint8Array([2])));\n return [first, second];\n}\n\nfunction base64UrlDecode(value: string): Uint8Array {\n const base64 = value.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n", "/**\n * Sealed transport: requests encrypted end to end to a TEE node's attested key.\n *\n * A node speaks plain HTTP and any TLS in front of it ends outside the enclave,\n * at whatever proxy or relay the operator runs, so everything crossing that hop\n * (the bearer token, JSON-RPC arguments, results) is readable there. Sealing\n * encrypts it so that only the attested TD can read it, and only the TD can\n * produce a response the client accepts.\n *\n * The client opens a session with a Noise NK handshake to the X25519 transport\n * key the node's quote commits to (`fetchAttestedKey`, `GET /attestation`). The\n * transport key only authenticates the node: the session keys come from both\n * sides' ephemeral keys, so once a session is gone (an hour at most) what was\n * sent in it cannot be opened, not even with the transport key. Each request\n * is sealed under the session; each response streams back in sealed frames, so\n * server-sent events are sealed too. WebSockets cannot be, and the node\n * refuses one inside the envelope with a 501.\n *\n * The node's side, and the wire format this implements byte for byte, are in\n * core's `crates/sealed` (`calimero-sealed`):\n *\n * ```text\n * handshake Noise_NK_25519_AESGCM_SHA256, prologue \"calimero/sealed-http/v2\"\n * request POST /sealed/v2/handshake 0x02 || transport_pk || Noise message 1\n * response 0x02 || Noise message 2 (payload = session_id(16) || lifetime secs, u32 BE)\n * keys (req key, resp key) = Split()\n * exchange POST /sealed/v2\n * header 0x02 || session_id(16) || request_id (u64 BE; from 1, each used once)\n * request header || AES-256-GCM(req key, nonce = request_id || 0u32, aad = header, inner)\n * response frames, each u32 BE length || AES-256-GCM(resp key,\n * nonce = request_id || frame index (u32 BE, from 0), aad = header, kind || data)\n * kind 0 = head (JSON), 1 = body bytes, 2 = end; no end frame = cut short\n * inner u32 BE head length || head (JSON) || body\n * ```\n *\n * `CalimeroClient` seals every request this way; {@link createSealedFetch} is\n * the same channel as a plain `fetch`.\n */\n\nimport { concat } from '../crypto/internal.js';\nimport { initiate } from './noise.js';\nimport type { DcapCollateral } from './verify.js';\n\n/** Where a session is opened, relative to the node's base URL. */\nexport const HANDSHAKE_PATH = '/sealed/v2/handshake';\n/** Where sealed requests are posted, relative to the node's base URL. */\nexport const SEALED_PATH = '/sealed/v2';\n/** Content type of every sealed body. */\nexport const SEALED_CONTENT_TYPE = 'application/vnd.calimero.sealed';\n\nconst VERSION = 2;\nconst PROLOGUE = new TextEncoder().encode('calimero/sealed-http/v2');\nconst SESSION_ID_LEN = 16;\nconst HEADER_LEN = 1 + SESSION_ID_LEN + 8;\nconst FRAME_HEAD = 0;\nconst FRAME_DATA = 1;\nconst FRAME_END = 2;\n/**\n * The largest frame the node sends: a kind byte, at most 64 KiB of data, a tag.\n * Anything larger is refused before it is buffered, so a proxy cannot make the\n * client hold an unbounded frame it has yet to authenticate.\n */\nconst MAX_FRAME_LEN = 1 + 64 * 1024 + 16;\n/** Far more than a handshake reply (69 bytes) ever is. */\nconst MAX_HANDSHAKE_REPLY = 1024;\n/** Open a new session this long before the node would drop the current one. */\nconst RENEW_BEFORE_MS = 60_000;\nconst TRANSPORT_BINDING_DOMAIN = 'calimero.tee-attest.transport-key.v1';\nconst NULL_BODY_STATUSES = [101, 204, 205, 304];\n\nconst utf8 = new TextEncoder();\n\n/** The node no longer holds the transport key this client attested (it restarted). */\nexport class StaleTransportKeyError extends Error {\n name = 'StaleTransportKeyError';\n\n constructor() {\n super('The node no longer holds the attested transport key; attest again for the current one');\n }\n}\n\n/** The node refused the envelope itself, before anything inside it ran. */\nexport class SealedTransportError extends Error {\n name = 'SealedTransportError';\n\n constructor(\n public status: number,\n public code: string | undefined,\n message: string,\n /** How long the node asked to wait before retrying (`Retry-After`), if it did. */\n public retryAfterMs?: number,\n ) {\n super(message);\n }\n}\n\n/**\n * What the attest endpoint puts in report data bytes `32..64` when asked to\n * bind its transport key. `inner` is what would have been there otherwise: the\n * expected application hash, or 32 zero bytes when none was asked for.\n * Mirrors core's `attest_transport_binding`.\n */\nexport async function transportKeyBinding(\n inner: Uint8Array,\n transportKey: Uint8Array,\n): Promise<Uint8Array> {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n concat(utf8.encode(TRANSPORT_BINDING_DOMAIN), inner, transportKey),\n );\n return new Uint8Array(digest);\n}\n\nexport interface VerifyTransportQuote {\n /**\n * Verify `quoteB64` \u2014 never by asking the node being attested \u2014 and check\n * that its report data is `nonce || reportDataSuffix` (both hex). Resolve\n * true only when the quote is genuine, its measurements are ones you accept,\n * and the report data matches. {@link createQuoteVerifier} does all of this\n * in the page. `collateral` is what the node sent with the quote, when the\n * verifier asked for it.\n */\n (args: {\n quoteB64: string;\n nonce: string;\n reportDataSuffix: string;\n collateral?: DcapCollateral;\n }): Promise<boolean>;\n /**\n * Set by the verifiers this package builds. A Calimero 1.0 node sends no\n * collateral with its quote; the verifier fetches it itself.\n */\n readonly includeCollateral?: boolean;\n}\n\nexport interface SealedFetchOptions {\n /** The node's base URL. */\n baseUrl: string;\n /**\n * The node's attested transport key, or a function that attests and returns\n * it \u2014 typically `() => fetchAttestedKey(baseUrl, policy)`. Given a\n * function, a restarted node is handled: the key is attested again, through\n * your verifier, and the request retried once. Given bytes, a restart\n * surfaces as {@link StaleTransportKeyError}.\n */\n transportPublicKey: Uint8Array | (() => Promise<Uint8Array>);\n /** Fetch that carries the sealed envelope. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * A `fetch` that seals every request to the node's attested transport key.\n *\n * A request for any URL outside `baseUrl` is refused rather than sent in the\n * clear: falling back to plaintext would silently undo the point of sealing.\n */\nexport function createSealedFetch(options: SealedFetchOptions): typeof fetch {\n const base = new URL(options.baseUrl);\n const basePath = base.pathname.replace(/\\/+$/, '');\n const nodeUrl = `${base.origin}${basePath}`;\n const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));\n const attest =\n typeof options.transportPublicKey === 'function' ? options.transportPublicKey : undefined;\n let transportKey: Promise<Uint8Array> = attest\n ? Promise.resolve().then(attest)\n : Promise.resolve(options.transportPublicKey as Uint8Array);\n // Attesting starts now, before any request awaits it. A node that fails to\n // attest must surface on the request that needed the key, not earlier as an\n // unhandled rejection; the failure is still thrown to every awaiter.\n transportKey.catch(() => undefined);\n let session: Promise<Session> | undefined;\n\n const openSession = async (): Promise<Session> => {\n try {\n return await handshake(baseFetch, nodeUrl, await checkedKey(transportKey));\n } catch (error) {\n if (!(error instanceof StaleTransportKeyError) || !attest) throw error;\n transportKey = Promise.resolve().then(attest);\n return handshake(baseFetch, nodeUrl, await checkedKey(transportKey));\n }\n };\n /** The session to use now, and the promise it came from, to name it if it turns out stale. */\n const currentSession = async (): Promise<[Session, Promise<Session>]> => {\n const pending = session ?? renew(undefined);\n const open = await pending;\n if (Date.now() < open.renewAt) return [open, pending];\n const renewed = renew(pending);\n return [await renewed, renewed];\n };\n // Replace the session only if it is still the one found stale, so concurrent\n // requests that all find it stale open one new session between them.\n const renew = (stale: Promise<Session> | undefined): Promise<Session> => {\n if (session === stale) {\n const opening = openSession();\n session = opening;\n opening.catch(() => {\n if (session === opening) session = undefined;\n });\n }\n return session as Promise<Session>;\n };\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n if (url.origin !== base.origin || !url.pathname.startsWith(`${basePath}/`)) {\n throw new Error(`Refusing to send ${url.href} outside the sealed node at ${options.baseUrl}`);\n }\n const headers: Array<[string, string]> = [];\n request.headers.forEach((value, name) => headers.push([name, value]));\n const head = { method: request.method, path: url.pathname.slice(basePath.length) + url.search, headers };\n const body = new Uint8Array(await request.arrayBuffer());\n // The caller's own signal, not `request.signal`: a Request's signal follows\n // the one it was built from only through a weak reference (undici), so once\n // the Request is garbage collected (it is, while a stream stays open) an\n // abort no longer reaches the fetch, and an event stream never closes.\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n\n const send = async (open: Session): Promise<Response> => {\n const { requestId, header, envelope } = await sealRequest(open, head, body);\n const response = await baseFetch(`${nodeUrl}${SEALED_PATH}`, {\n method: 'POST',\n headers: { 'content-type': SEALED_CONTENT_TYPE },\n body: envelope,\n signal,\n });\n if (response.headers.get('content-type') !== SEALED_CONTENT_TYPE) {\n throw await envelopeRefusal(response);\n }\n return openResponse(response, open.responseKey, header, requestId);\n };\n\n const [open, pending] = await currentSession();\n try {\n return await send(open);\n } catch (error) {\n // The node refused the envelope before running anything in it, so the\n // request can be sent again safely under a new session.\n if (!(error instanceof SealedTransportError) || error.code !== 'unknown_session') throw error;\n return send(await renew(pending));\n }\n };\n}\n\nasync function checkedKey(key: Promise<Uint8Array>): Promise<Uint8Array> {\n const bytes = await key;\n if (bytes.length !== 32) throw new Error('transportPublicKey must be 32 bytes');\n return bytes;\n}\n\nexport interface Session {\n requestKey: CryptoKey;\n responseKey: CryptoKey;\n nextRequestId: number;\n renewAt: number;\n header(requestId: number): Uint8Array;\n}\n\nasync function handshake(\n baseFetch: typeof fetch,\n nodeUrl: string,\n transportKey: Uint8Array,\n): Promise<Session> {\n try {\n return await handshakeOnce(baseFetch, nodeUrl, transportKey);\n } catch (error) {\n // The node limits how fast sessions open. A refused handshake opened\n // nothing, so trying once more after the pause it asks for is safe.\n if (!(error instanceof SealedTransportError) || error.code !== 'busy') throw error;\n await new Promise((resolve) => setTimeout(resolve, error.retryAfterMs ?? 1000));\n return handshakeOnce(baseFetch, nodeUrl, transportKey);\n }\n}\n\nasync function handshakeOnce(\n baseFetch: typeof fetch,\n nodeUrl: string,\n transportKey: Uint8Array,\n): Promise<Session> {\n const noise = await initiate(transportKey, PROLOGUE);\n const response = await baseFetch(`${nodeUrl}${HANDSHAKE_PATH}`, {\n method: 'POST',\n headers: { 'content-type': SEALED_CONTENT_TYPE },\n body: concat(new Uint8Array([VERSION]), transportKey, noise.message1),\n });\n if (response.headers.get('content-type') !== SEALED_CONTENT_TYPE) {\n throw await envelopeRefusal(response);\n }\n const reply = await readAtMost(response, MAX_HANDSHAKE_REPLY);\n return sessionFrom(noise, reply);\n}\n\n/** Finish the handshake with the node's reply. Exported for the published vectors. */\nexport async function sessionFrom(\n noise: Awaited<ReturnType<typeof initiate>>,\n reply: Uint8Array,\n): Promise<Session> {\n if (reply[0] !== VERSION) throw new Error('The handshake reply is malformed');\n let finished: Awaited<ReturnType<(typeof noise)['finish']>>;\n try {\n finished = await noise.finish(reply.slice(1));\n } catch {\n throw new Error('The handshake reply did not open: it did not come from the attested node');\n }\n const { payload, split } = finished;\n if (payload.length !== SESSION_ID_LEN + 4) throw new Error('The handshake reply is malformed');\n const sessionId = payload.slice(0, SESSION_ID_LEN);\n const lifetimeSecs = new DataView(payload.buffer, payload.byteOffset).getUint32(SESSION_ID_LEN, false);\n const [requestKey, responseKey] = await Promise.all([\n crypto.subtle.importKey('raw', split[0], 'AES-GCM', false, ['encrypt']),\n crypto.subtle.importKey('raw', split[1], 'AES-GCM', false, ['decrypt']),\n ]);\n split[0].fill(0);\n split[1].fill(0);\n return {\n requestKey,\n responseKey,\n nextRequestId: 1,\n renewAt: Date.now() + lifetimeSecs * 1000 - RENEW_BEFORE_MS,\n header(requestId) {\n const header = new Uint8Array(HEADER_LEN);\n header[0] = VERSION;\n header.set(sessionId, 1);\n new DataView(header.buffer).setBigUint64(1 + SESSION_ID_LEN, BigInt(requestId), false);\n return header;\n },\n };\n}\n\n/** Seal one request under the session's next request id. */\nexport async function sealRequest(\n session: Session,\n head: RequestHead,\n body: Uint8Array,\n): Promise<{ requestId: number; header: Uint8Array; envelope: Uint8Array }> {\n const requestId = session.nextRequestId;\n session.nextRequestId += 1;\n const header = session.header(requestId);\n const sealed = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce(requestId, 0), additionalData: header },\n session.requestKey,\n joinInner(head, body),\n );\n return { requestId, header, envelope: concat(header, new Uint8Array(sealed)) };\n}\n\n/** `request_id || index`, as the node numbers them. */\nfunction nonce(requestId: number, index: number): Uint8Array {\n const bytes = new Uint8Array(12);\n const view = new DataView(bytes.buffer);\n view.setBigUint64(0, BigInt(requestId), false);\n view.setUint32(8, index, false);\n return bytes;\n}\n\nexport interface RequestHead {\n method: string;\n path: string;\n headers: Array<[string, string]>;\n}\n\nexport interface ResponseHead {\n status: number;\n headers: Array<[string, string]>;\n}\n\nfunction joinInner(head: RequestHead, body: Uint8Array): Uint8Array {\n const encoded = utf8.encode(JSON.stringify(head));\n const len = new Uint8Array(4);\n new DataView(len.buffer).setUint32(0, encoded.length, false);\n return concat(len, encoded, body);\n}\n\n/**\n * Open a sealed response as it streams: wait for its head, then hand back a\n * `Response` whose body opens each frame as it arrives. A frame that does not\n * open, arrives out of order, or a stream that stops before its end frame\n * errors the body rather than passing anything unauthenticated on.\n */\nexport async function openResponse(\n response: Response,\n responseKey: CryptoKey,\n header: Uint8Array,\n requestId: number,\n): Promise<Response> {\n if (!response.body) throw new Error('The sealed response has no body');\n const frames = frameReader(response.body.getReader());\n let index = 0;\n const next = async (): Promise<{ kind: number; data: Uint8Array } | null> => {\n const sealed = await frames.next();\n if (!sealed) return null;\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce(requestId, index), additionalData: header },\n responseKey,\n sealed,\n ),\n );\n } catch {\n throw new Error('A sealed response frame did not open: it was not sealed by the attested node');\n }\n index += 1;\n return { kind: plain[0], data: plain.slice(1) };\n };\n\n const first = await next();\n if (!first || first.kind !== FRAME_HEAD) throw new Error('The sealed response is malformed');\n const head = JSON.parse(new TextDecoder().decode(first.data)) as ResponseHead;\n if (NULL_BODY_STATUSES.includes(head.status)) {\n await frames.cancel();\n return new Response(null, { status: head.status, headers: head.headers });\n }\n\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const frame = await next();\n if (!frame) {\n controller.error(new Error('The sealed response was cut short'));\n } else if (frame.kind === FRAME_DATA) {\n controller.enqueue(frame.data);\n } else if (frame.kind === FRAME_END) {\n controller.close();\n await frames.cancel();\n } else {\n controller.error(new Error('The sealed response is malformed'));\n }\n } catch (error) {\n controller.error(error);\n }\n },\n cancel() {\n return frames.cancel();\n },\n });\n return new Response(body, { status: head.status, headers: head.headers });\n}\n\n/** Split a byte stream into length-prefixed frames. */\nfunction frameReader(reader: ReadableStreamDefaultReader<Uint8Array>): {\n next(): Promise<Uint8Array | null>;\n cancel(): Promise<void>;\n} {\n let buffer = new Uint8Array();\n const fill = async (length: number): Promise<boolean> => {\n while (buffer.length < length) {\n const { done, value } = await reader.read();\n if (done) return false;\n buffer = concat(buffer, value);\n }\n return true;\n };\n return {\n async next() {\n if (!(await fill(4))) return null;\n const length = new DataView(buffer.buffer, buffer.byteOffset).getUint32(0, false);\n if (length > MAX_FRAME_LEN) {\n await reader.cancel();\n throw new Error('The sealed response is malformed: a frame is larger than the node sends');\n }\n if (!(await fill(4 + length))) return null;\n const frame = buffer.slice(4, 4 + length);\n buffer = buffer.slice(4 + length);\n return frame;\n },\n cancel: () => reader.cancel(),\n };\n}\n\n/** Read a body, refusing one longer than `limit` rather than buffering it. */\nasync function readAtMost(response: Response, limit: number): Promise<Uint8Array> {\n if (!response.body) return new Uint8Array();\n const reader = response.body.getReader();\n let bytes = new Uint8Array();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return bytes;\n bytes = concat(bytes, value);\n if (bytes.length > limit) {\n await reader.cancel();\n throw new Error('The handshake reply is malformed: it is too long');\n }\n }\n}\n\nasync function envelopeRefusal(response: Response): Promise<Error> {\n let code: string | undefined;\n let message = `Sealed request refused: HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: string; message?: string } };\n code = body?.error?.code;\n if (body?.error?.message) message = `Sealed request refused: ${body.error.message}`;\n } catch {\n // Not the node's JSON refusal \u2014 a proxy's page, most likely. The status is\n // all that can honestly be reported.\n }\n if (code === 'stale_transport_key') return new StaleTransportKeyError();\n const retryAfter = Number(response.headers.get('retry-after'));\n const retryAfterMs =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 5) * 1000 : undefined;\n return new SealedTransportError(response.status, code, message, retryAfterMs);\n}\n", "/**\n * The parts of the Sigstore public-good trust root that verifying a mero-tee\n * release's cosign bundle needs: the Fulcio certificate authorities that issue\n * the release workflow's short-lived signing certificates, and the Rekor log\n * key that signs the bundle's signed entry timestamp. Each with the window in\n * which the trust root says it was in use.\n *\n * Copied from the `trusted_root.json` that Sigstore publishes through its TUF\n * repository (https://tuf-repo-cdn.sigstore.dev, target `trusted_root.json`),\n * as shipped by the `sigstore` Python client 4.5.0 in\n * `sigstore/_store/https%3A%2F%2Ftuf-repo-cdn.sigstore.dev/trusted_root.json`.\n * Embedded rather than fetched: fetching it at run time would trust whoever\n * serves it, the very thing this check exists to avoid.\n *\n * Left out, because a legacy cosign bundle never uses them: the CT logs (the\n * certificate's SCT is not checked here, as core does not either), the\n * timestamp authority, and the Rekor v2 log `log2025-1.rekor.sigstore.dev`,\n * whose Ed25519 key signs checkpoints rather than signed entry timestamps. A\n * bundle that names any log but those below is refused.\n *\n * To refresh it when Sigstore rotates a key or adds a CA: take the current\n * `trusted_root.json` from a TUF client (`python -m sigstore` or `cosign\n * initialize` both keep one, verified against the TUF root), and copy each\n * `certificateAuthorities[].certChain.certificates[].rawBytes` with its\n * `validFor`, and each ECDSA `tlogs[]` entry's `publicKey.rawBytes`,\n * `publicKey.validFor` and `logId.keyId` (as hex). The tests check each log id\n * is the SHA-256 of its key and each chain verifies.\n */\n\n/** A Fulcio CA: its chain from the certificate that issues leaves up to the root, DER as base64. */\nexport interface FulcioAuthority {\n uri: string;\n /** When the trust root says this CA issued certificates. No `end`: it still does. */\n validFor: { start: string; end?: string };\n certChain: string[];\n}\n\n/** A Rekor log whose signed entry timestamps are accepted. */\nexport interface RekorLog {\n baseUrl: string;\n /** The log id a bundle names it by: the SHA-256 of its public key, hex. */\n logId: string;\n /** Its public key: DER SubjectPublicKeyInfo, base64. ECDSA P-256 with SHA-256. */\n publicKey: string;\n validFor: { start: string; end?: string };\n}\n\nexport const FULCIO_AUTHORITIES: readonly FulcioAuthority[] = [\n {\n uri: 'https://fulcio.sigstore.dev',\n validFor: { start: '2021-03-07T03:20:29Z', end: '2022-12-31T23:59:59.999Z' },\n certChain: [\n 'MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9y' +\n 'ZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UE' +\n 'ChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+p' +\n 'NO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+' +\n '2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYD' +\n 'VR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqG' +\n 'SM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjR' +\n 'ay5/aj/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0zMTEwMDUxMzU2NThaMCoxFTATBgNV' +\n 'BAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3' +\n 'PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS' +\n '5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud' +\n 'DgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjO' +\n 'PQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9' +\n 'ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ',\n ],\n },\n];\n\nexport const REKOR_LOGS: readonly RekorLog[] = [\n {\n baseUrl: 'https://rekor.sigstore.dev',\n logId: 'c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d',\n publicKey:\n 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufB' +\n 'nhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==',\n validFor: { start: '2021-01-12T11:53:27Z' },\n },\n];\n", "/**\n * Just enough DER and X.509 to check a Sigstore signing certificate with\n * WebCrypto: read a certificate's signed part, validity, key and extensions,\n * and verify the ECDSA signatures (P-256 and P-384) Sigstore uses.\n *\n * Written here, rather than taken from a library, so the SDK keeps no runtime\n * dependencies and runs wherever WebCrypto does. It parses strictly and throws\n * on anything it does not expect; it is not a general X.509 implementation.\n */\n\nconst SEQUENCE = 0x30;\nconst OID = 0x06;\nconst INTEGER = 0x02;\nconst BIT_STRING = 0x03;\nconst OCTET_STRING = 0x04;\nconst BOOLEAN = 0x01;\nconst UTC_TIME = 0x17;\nconst GENERALIZED_TIME = 0x18;\nconst CONTEXT_0 = 0xa0;\nconst CONTEXT_3 = 0xa3;\n\nconst EC_PUBLIC_KEY = '1.2.840.10045.2.1';\nconst CURVES: Record<string, Curve> = {\n '1.2.840.10045.3.1.7': 'P-256',\n '1.3.132.0.34': 'P-384',\n};\nconst CURVE_SIZE: Record<Curve, number> = { 'P-256': 32, 'P-384': 48 };\n/** The certificate signature algorithms accepted: ECDSA with SHA-256 or SHA-384. */\nconst SIGNATURE_HASHES: Record<string, Hash> = {\n '1.2.840.10045.4.3.2': 'SHA-256',\n '1.2.840.10045.4.3.3': 'SHA-384',\n};\n\nexport type Curve = 'P-256' | 'P-384';\nexport type Hash = 'SHA-256' | 'SHA-384';\n\n/** One DER element: its tag, and where it and its contents lie in `bytes`. */\nexport interface Element {\n tag: number;\n bytes: Uint8Array;\n /** Offset of the element's first (tag) byte. */\n offset: number;\n /** Offset of its contents. */\n start: number;\n /** Offset just past it. */\n end: number;\n}\n\nfunction read(bytes: Uint8Array, offset: number, limit: number): Element {\n if (offset + 2 > limit) throw new Error('it is truncated');\n const tag = bytes[offset];\n if ((tag & 0x1f) === 0x1f) throw new Error('it uses a tag this parser does not read');\n let length = bytes[offset + 1];\n let start = offset + 2;\n if (length & 0x80) {\n const count = length & 0x7f;\n if (count === 0 || count > 4 || start + count > limit) throw new Error('it has a length this parser does not read');\n length = 0;\n for (let i = 0; i < count; i += 1) length = length * 256 + bytes[start + i];\n start += count;\n }\n const end = start + length;\n if (end > limit) throw new Error('it is truncated');\n return { tag, bytes, offset, start, end };\n}\n\n/** Parse one complete DER element, refusing trailing bytes. */\nexport function parseDer(bytes: Uint8Array): Element {\n const element = read(bytes, 0, bytes.length);\n if (element.end !== bytes.length) throw new Error('it has trailing bytes');\n return element;\n}\n\nexport function children(element: Element): Element[] {\n const out: Element[] = [];\n for (let offset = element.start; offset < element.end; ) {\n const child = read(element.bytes, offset, element.end);\n out.push(child);\n offset = child.end;\n }\n return out;\n}\n\n/** `element` if it has `tag`; otherwise throws naming `what`. */\nexport function expectTag(element: Element | undefined, tag: number, what: string): Element {\n if (!element || element.tag !== tag) throw new Error(`${what} is not where it should be`);\n return element;\n}\n\nexport function contents(element: Element): Uint8Array {\n return element.bytes.slice(element.start, element.end);\n}\n\n/** The whole element, header included. */\nfunction whole(element: Element): Uint8Array {\n return element.bytes.slice(element.offset, element.end);\n}\n\nfunction oid(element: Element | undefined): string {\n const value = contents(expectTag(element, OID, 'An object identifier'));\n if (value.length === 0 || value[value.length - 1] & 0x80) throw new Error('it has a malformed object identifier');\n const arcs: number[] = [];\n let arc = 0;\n for (const byte of value) {\n arc = arc * 128 + (byte & 0x7f);\n if (!(byte & 0x80)) {\n arcs.push(arc);\n arc = 0;\n }\n }\n const first = arcs.shift() as number;\n const head = first < 80 ? [Math.floor(first / 40), first % 40] : [2, first - 80];\n return [...head, ...arcs].join('.');\n}\n\nfunction time(element: Element): number {\n const text = new TextDecoder().decode(contents(element));\n const utc = element.tag === UTC_TIME ? /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text) : null;\n const generalized =\n element.tag === GENERALIZED_TIME ? /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text) : null;\n const parts = utc ?? generalized;\n if (!parts) throw new Error(`it holds the time ${JSON.stringify(text)}, which is not one a certificate may hold`);\n let year = Number(parts[1]);\n if (utc) year += year < 50 ? 2000 : 1900;\n const [month, day, hour, minute, second] = parts.slice(2).map(Number);\n return Date.UTC(year, month - 1, day, hour, minute, second);\n}\n\nexport interface Certificate {\n der: Uint8Array;\n /** The signed part, exactly as the issuer signed it. */\n tbs: Uint8Array;\n /** The hash of the ECDSA signature the issuer made over `tbs`. */\n signatureHash: Hash;\n /** That signature, DER. */\n signature: Uint8Array;\n /** The issuer and subject names, DER, to compare byte for byte. */\n issuer: Uint8Array;\n subject: Uint8Array;\n /** Validity, in milliseconds since the epoch, both ends inclusive. */\n notBefore: number;\n notAfter: number;\n /** The subject's key, DER SubjectPublicKeyInfo, and its curve. */\n spki: Uint8Array;\n curve: Curve;\n /** Each extension's value (the contents of its OCTET STRING), by object identifier. */\n extensions: Map<string, Uint8Array>;\n}\n\n/**\n * Parse a DER X.509 certificate with an ECDSA key, signed with ECDSA. Throws\n * naming what is wrong.\n */\nexport function parseCertificate(der: Uint8Array): Certificate {\n try {\n const [tbsElement, algorithm, signature, ...rest] = children(\n expectTag(parseDer(der), SEQUENCE, 'The certificate'),\n );\n if (rest.length > 0) throw new Error('it has fields after its signature');\n const fields = children(expectTag(tbsElement, SEQUENCE, 'The signed part'));\n // `version` is [0] EXPLICIT; everything after it is positional.\n const first = fields[0]?.tag === CONTEXT_0 ? 1 : 0;\n const [serial, innerAlgorithm, issuer, validity, subject, spki, ...optional] = fields.slice(first);\n expectTag(serial, INTEGER, 'The serial number');\n\n const algorithmId = oid(children(expectTag(algorithm, SEQUENCE, 'The signature algorithm'))[0]);\n const innerId = oid(children(expectTag(innerAlgorithm, SEQUENCE, 'The signature algorithm'))[0]);\n if (innerId !== algorithmId) throw new Error('it names two different signature algorithms');\n const signatureHash = SIGNATURE_HASHES[algorithmId];\n if (!signatureHash) throw new Error(`it is signed with ${algorithmId}, not ECDSA with SHA-256 or SHA-384`);\n\n const [notBefore, notAfter] = children(expectTag(validity, SEQUENCE, 'The validity')).map(time);\n if (notAfter === undefined) throw new Error('its validity is incomplete');\n\n const [keyAlgorithm, keyBits] = children(expectTag(spki, SEQUENCE, 'The public key'));\n expectTag(keyBits, BIT_STRING, 'The public key');\n const [keyType, keyCurve] = children(expectTag(keyAlgorithm, SEQUENCE, 'The key algorithm'));\n if (oid(keyType) !== EC_PUBLIC_KEY) throw new Error('its key is not an elliptic-curve key');\n const curve = CURVES[oid(keyCurve)];\n if (!curve) throw new Error('its key is on a curve other than P-256 or P-384');\n\n const extensions = new Map<string, Uint8Array>();\n const extensionsField = optional.find((field) => field.tag === CONTEXT_3);\n if (extensionsField) {\n const [list] = children(extensionsField);\n for (const extension of children(expectTag(list, SEQUENCE, 'The extensions'))) {\n const parts = children(expectTag(extension, SEQUENCE, 'An extension'));\n if (parts.length === 3) expectTag(parts[1], BOOLEAN, 'An extension\\'s critical flag');\n else if (parts.length !== 2) throw new Error('it has a malformed extension');\n const id = oid(parts[0]);\n if (extensions.has(id)) throw new Error(`it has extension ${id} twice`);\n extensions.set(id, contents(expectTag(parts[parts.length - 1], OCTET_STRING, 'An extension value')));\n }\n }\n\n const signatureBits = contents(expectTag(signature, BIT_STRING, 'The signature'));\n if (signatureBits[0] !== 0) throw new Error('its signature is not a whole number of bytes');\n return {\n der,\n tbs: whole(tbsElement),\n signatureHash,\n signature: signatureBits.slice(1),\n issuer: whole(expectTag(issuer, SEQUENCE, 'The issuer')),\n subject: whole(expectTag(subject, SEQUENCE, 'The subject')),\n notBefore,\n notAfter,\n spki: whole(spki),\n curve,\n extensions,\n };\n } catch (error) {\n throw new Error(`The certificate is malformed: ${(error as Error).message}`);\n }\n}\n\n/** The object identifiers in a DER `SEQUENCE OF OBJECT IDENTIFIER` (an extended key usage). */\nexport function objectIdentifiers(der: Uint8Array): string[] {\n return children(expectTag(parseDer(der), SEQUENCE, 'The list')).map(oid);\n}\n\n/**\n * An ECDSA signature as WebCrypto takes it (IEEE P1363: `r || s`, each the\n * curve's size), from the DER `SEQUENCE { r INTEGER, s INTEGER }` X.509 and\n * cosign use.\n */\nexport function ecdsaSignatureToP1363(der: Uint8Array, curve: Curve): Uint8Array {\n const size = CURVE_SIZE[curve];\n const integers = children(expectTag(parseDer(der), SEQUENCE, 'The signature'));\n if (integers.length !== 2) throw new Error('The signature is not an ECDSA signature');\n const out = new Uint8Array(size * 2);\n integers.forEach((integer, index) => {\n let value = contents(expectTag(integer, INTEGER, 'The signature'));\n // r and s are positive: a set top bit with no leading zero is a negative number.\n if (value.length === 0 || value[0] & 0x80) throw new Error('The signature is not an ECDSA signature');\n while (value.length > 1 && value[0] === 0) value = value.subarray(1);\n if (value.length > size) throw new Error('The signature is not an ECDSA signature');\n out.set(value, index * size + size - value.length);\n });\n return out;\n}\n\n/** Verify a DER ECDSA `signature` over `data` with a DER SubjectPublicKeyInfo key. */\nexport async function verifyEcdsa(\n spki: Uint8Array,\n curve: Curve,\n hash: Hash,\n signature: Uint8Array,\n data: Uint8Array,\n): Promise<boolean> {\n let p1363: Uint8Array;\n try {\n p1363 = ecdsaSignatureToP1363(signature, curve);\n } catch {\n return false;\n }\n const key = await crypto.subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: curve }, false, ['verify']);\n return crypto.subtle.verify({ name: 'ECDSA', hash }, key, p1363, data);\n}\n\n/** Decode base64 (standard alphabet), refusing anything else. */\nexport function fromBase64(value: string, what: string): Uint8Array {\n const clean = value.replace(/\\s+/g, '');\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 !== 0) {\n throw new Error(`${what} is not base64`);\n }\n const binary = atob(clean);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The DER of the one `CERTIFICATE` block a PEM holds. */\nexport function pemCertificate(pem: string, what: string): Uint8Array {\n const blocks = [...pem.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];\n if (blocks.length !== 1 || pem.replace(blocks[0][0], '').trim() !== '') {\n throw new Error(`${what} is not exactly one PEM certificate`);\n }\n return fromBase64(blocks[0][1], what);\n}\n", "/**\n * Verifying a cosign keyless signature, as `cosign verify-blob --bundle` does,\n * with WebCrypto and the Sigstore trust root embedded in this package.\n *\n * mero-tee signs each release asset with cosign keyless: there is no release\n * key, only a Fulcio certificate that lives ten minutes, issued to one GitHub\n * Actions workflow run, and a Rekor log entry that proves the signature was\n * made while the certificate was valid. So the checks are: the signature over\n * the bytes verifies with the certificate's key; Rekor's signed entry\n * timestamp verifies, and the entry it signs is this signature over these\n * bytes by this certificate; the certificate chains to a Fulcio CA and was\n * valid when Rekor logged it; and the certificate names the workflow expected.\n * The same checks core runs in `crates/tee-release/src/sigstore_verify.rs`.\n *\n * Nothing here reads the clock. Every time is Rekor's `integratedTime`, which\n * its signature covers, so a verification that passes once passes forever,\n * whatever the client's clock says.\n */\n\nimport { hex } from '../crypto/internal.js';\nimport { FULCIO_AUTHORITIES, REKOR_LOGS } from './sigstore-trust-root.js';\nimport {\n children,\n contents,\n expectTag,\n fromBase64,\n objectIdentifiers,\n parseCertificate,\n parseDer,\n pemCertificate,\n verifyEcdsa,\n type Certificate,\n} from './x509.js';\n\nconst SUBJECT_ALT_NAME = '2.5.29.17';\nconst EXTENDED_KEY_USAGE = '2.5.29.37';\nconst CODE_SIGNING = '1.3.6.1.5.5.7.3.3';\n/** Fulcio's OIDC issuer extension, a DER UTF8String. */\nconst FULCIO_ISSUER_V2 = '1.3.6.1.4.1.57264.1.8';\n/** Its deprecated predecessor, the raw issuer bytes; read only when the other is absent. */\nconst FULCIO_ISSUER_V1 = '1.3.6.1.4.1.57264.1.1';\nconst SAN_URI = 0x86;\nconst UTF8_STRING = 0x0c;\nconst SEQUENCE = 0x30;\n\nconst utf8 = new TextEncoder();\n// Not `fatal`: not every runtime's TextDecoder takes options. A malformed byte\n// decodes to U+FFFD, which no pinned identity holds, so it can only fail a match.\nconst fromUtf8 = (bytes: Uint8Array) => new TextDecoder().decode(bytes);\n\n/** Who must have signed: the certificate's SAN URI and its OIDC issuer, each matched exactly. */\nexport interface SignerIdentity {\n identity: string;\n issuer: string;\n}\n\n/** A legacy cosign bundle (`cosign sign-blob --bundle`), as the fields verified here. */\ninterface CosignBundle {\n base64Signature: string;\n cert: string;\n rekorBundle: {\n SignedEntryTimestamp: string;\n Payload: { body: string; integratedTime: number; logIndex: number; logID: string };\n };\n}\n\n/**\n * Verify a cosign keyless `bundle` over `body`, signed by `signer`. Resolves\n * with the time Rekor logged it (seconds); rejects with the reason otherwise.\n * `signature`, when given, is the detached `.sig` published beside the file,\n * and must be the bundle's.\n */\nexport async function verifyCosignBundle(\n body: Uint8Array,\n bundle: unknown,\n signer: SignerIdentity,\n signature?: string,\n): Promise<{ integratedTime: number }> {\n const { base64Signature, cert, rekorBundle } = cosignBundle(bundle);\n const payload = rekorBundle.Payload;\n if (signature !== undefined && signature.trim() !== base64Signature.trim()) {\n throw new Error('The detached signature is not the one in the bundle');\n }\n const sig = fromBase64(base64Signature, 'The bundle signature');\n const leafDer = pemCertificate(fromUtf8(fromBase64(cert, 'The bundle certificate')), 'The bundle certificate');\n const leaf = parseCertificate(leafDer);\n\n // Rekor vouches for the entry and its time: nothing below is trusted before this.\n const log = REKOR_LOGS.find((candidate) => candidate.logId === payload.logID.toLowerCase());\n if (!log) throw new Error(`The bundle names Rekor log ${payload.logID}, which the Sigstore trust root does not know`);\n const canonical = utf8.encode(\n `{\"body\":${JSON.stringify(payload.body)},\"integratedTime\":${payload.integratedTime},` +\n `\"logID\":${JSON.stringify(payload.logID)},\"logIndex\":${payload.logIndex}}`,\n );\n const setVerifies = await verifyEcdsa(\n fromBase64(log.publicKey, 'The Rekor key'),\n 'P-256',\n 'SHA-256',\n fromBase64(rekorBundle.SignedEntryTimestamp, 'The signed entry timestamp'),\n canonical,\n );\n if (!setVerifies) {\n throw new Error(\"Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered\");\n }\n const at = payload.integratedTime * 1000;\n if (!within(at, log.validFor)) {\n throw new Error(`Rekor log ${log.baseUrl} was not in use at ${iso(at)}, when the entry says it was logged`);\n }\n\n // The entry Rekor signed is this signature, over these bytes, by this certificate.\n const entry = hashedRekord(payload.body);\n const digest = hex(new Uint8Array(await crypto.subtle.digest('SHA-256', body)));\n if (entry.hash !== digest) throw new Error(\"The file's SHA-256 is not the one Rekor logged: the file is not the one signed\");\n if (!equal(fromBase64(entry.signature, 'The logged signature'), sig)) {\n throw new Error(\"The bundle's signature is not the one Rekor logged\");\n }\n const loggedCert = pemCertificate(fromUtf8(fromBase64(entry.publicKey, 'The logged certificate')), 'The logged certificate');\n if (!equal(loggedCert, leafDer)) throw new Error(\"The bundle's certificate is not the one Rekor logged\");\n\n if (leaf.curve !== 'P-256' || !(await verifyEcdsa(leaf.spki, 'P-256', 'SHA-256', sig, body))) {\n throw new Error(\"The signature over the file does not verify with the bundle's certificate\");\n }\n\n await chainsToFulcio(leaf, at);\n checkSigner(leaf, signer);\n return { integratedTime: payload.integratedTime };\n}\n\n/**\n * Check that `leaf` was issued by a Fulcio CA in the trust root, and that it,\n * the CA's certificates and the CA itself (by the trust root's `validFor`)\n * were all valid at `at` (milliseconds): when Rekor logged the signature, not\n * now, since a Fulcio certificate lives ten minutes. Every signature on the\n * way is checked, with the algorithm its certificate names.\n */\nexport async function chainsToFulcio(leaf: Certificate, at: number): Promise<void> {\n if (!validAt(leaf, at)) {\n throw new Error(\n `The signing certificate was valid ${iso(leaf.notBefore)} to ${iso(leaf.notAfter)}, not at ${iso(at)} when Rekor logged it`,\n );\n }\n const reasons: string[] = [];\n for (const authority of FULCIO_AUTHORITIES) {\n const chain = authority.certChain.map((der) => parseCertificate(fromBase64(der, 'A Fulcio certificate')));\n if (!(await issuedBy(leaf, chain[0]))) continue;\n // The issuer is found; from here a failure is this CA's, so say which.\n const reason = await authorityRefusal(chain, authority.validFor, at);\n if (!reason) return;\n reasons.push(`${authority.uri} (valid from ${authority.validFor.start}): ${reason}`);\n }\n throw new Error(\n reasons.length > 0\n ? `The signing certificate's CA is not trusted at ${iso(at)}: ${reasons.join('; ')}`\n : 'The signing certificate was not issued by a Fulcio CA in the Sigstore trust root',\n );\n}\n\nasync function authorityRefusal(\n chain: Certificate[],\n validFor: { start: string; end?: string },\n at: number,\n): Promise<string | undefined> {\n if (!within(at, validFor)) return 'the trust root says it was not issuing certificates then';\n for (const [index, certificate] of chain.entries()) {\n if (!validAt(certificate, at)) return `its certificate ${index} was not valid then`;\n const parent = chain[index + 1] ?? certificate; // the root signs itself\n if (!(await issuedBy(certificate, parent))) return `its certificate ${index} is not signed by the next`;\n }\n return undefined;\n}\n\nasync function issuedBy(child: Certificate, parent: Certificate): Promise<boolean> {\n if (!equal(child.issuer, parent.subject)) return false;\n return verifyEcdsa(parent.spki, parent.curve, child.signatureHash, child.signature, child.tbs);\n}\n\nfunction checkSigner(leaf: Certificate, signer: SignerIdentity): void {\n const san = leaf.extensions.get(SUBJECT_ALT_NAME);\n if (!san) throw new Error('The signing certificate names no identity');\n const names = children(expectTag(parseDer(san), SEQUENCE, 'The subject alternative name'));\n const uris = names.filter((name) => name.tag === SAN_URI).map((name) => fromUtf8(contents(name)));\n if (uris.length !== 1 || names.length !== 1 || uris[0] !== signer.identity) {\n throw new Error(\n `The release was signed by ${JSON.stringify(uris.length === 1 ? uris[0] : uris)}, not by ${signer.identity}`,\n );\n }\n\n const v2 = leaf.extensions.get(FULCIO_ISSUER_V2);\n const v1 = leaf.extensions.get(FULCIO_ISSUER_V1);\n const issuer = v2\n ? fromUtf8(contents(expectTag(parseDer(v2), UTF8_STRING, 'The OIDC issuer')))\n : v1\n ? fromUtf8(v1)\n : undefined;\n if (issuer !== signer.issuer) {\n throw new Error(\n `The signing certificate's OIDC issuer is ${issuer === undefined ? 'missing' : JSON.stringify(issuer)}, not ${signer.issuer}`,\n );\n }\n\n const usage = leaf.extensions.get(EXTENDED_KEY_USAGE);\n if (!usage || !objectIdentifiers(usage).includes(CODE_SIGNING)) {\n throw new Error('The signing certificate is not for code signing');\n }\n}\n\nfunction cosignBundle(value: unknown): CosignBundle {\n let bundle = value;\n if (typeof bundle === 'string') {\n try {\n bundle = JSON.parse(bundle);\n } catch {\n throw new Error('The bundle is not JSON');\n }\n }\n const b = bundle as Partial<CosignBundle> | null;\n const p = b?.rekorBundle?.Payload;\n const ok =\n typeof b?.base64Signature === 'string' &&\n typeof b.cert === 'string' &&\n typeof b.rekorBundle?.SignedEntryTimestamp === 'string' &&\n typeof p?.body === 'string' &&\n typeof p.logID === 'string' &&\n /^[0-9a-fA-F]{64}$/.test(p.logID) &&\n Number.isSafeInteger(p.integratedTime) &&\n p.integratedTime >= 0 &&\n Number.isSafeInteger(p.logIndex) &&\n p.logIndex >= 0;\n if (!ok) throw new Error('The bundle is not a cosign bundle with a Rekor entry');\n return b as CosignBundle;\n}\n\n/** The fields of a logged `hashedrekord` entry that are compared. */\nfunction hashedRekord(body: string): { hash: string; signature: string; publicKey: string } {\n let entry: {\n kind?: unknown;\n spec?: {\n data?: { hash?: { algorithm?: unknown; value?: unknown } };\n signature?: { content?: unknown; publicKey?: { content?: unknown } };\n };\n };\n try {\n entry = JSON.parse(fromUtf8(fromBase64(body, 'The logged entry')));\n } catch {\n throw new Error('The logged entry is not JSON');\n }\n const hash = entry?.spec?.data?.hash;\n const signature = entry?.spec?.signature;\n if (\n entry?.kind !== 'hashedrekord' ||\n hash?.algorithm !== 'sha256' ||\n typeof hash.value !== 'string' ||\n typeof signature?.content !== 'string' ||\n typeof signature.publicKey?.content !== 'string'\n ) {\n throw new Error('The logged entry is not a SHA-256 hashedrekord');\n }\n return { hash: hash.value.toLowerCase(), signature: signature.content, publicKey: signature.publicKey.content };\n}\n\nfunction validAt(certificate: Certificate, at: number): boolean {\n return certificate.notBefore <= at && at <= certificate.notAfter;\n}\n\nfunction within(at: number, window: { start: string; end?: string }): boolean {\n return Date.parse(window.start) <= at && (window.end === undefined || at <= Date.parse(window.end));\n}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString();\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, index) => byte === b[index]);\n}\n", "/**\n * Verifying a TEE node's quote in the page, before trusting the key it binds.\n *\n * A quote proves what runs in a TD only once it has been checked: its\n * signatures against Intel's root, the TCB status of the platform, the\n * measurements of the image, and that its report data is the nonce and the\n * binding this client asked for. {@link createQuoteVerifier} does all of that\n * here. A Calimero 1.0 node sends no collateral: the verifier fetches Intel's\n * (`fetchCollateral`), which the node can neither forge nor choose.\n *\n * The DCAP verification itself \u2014 parsing the quote, checking its signature\n * chain and appraising its TCB level against the collateral \u2014 comes from a\n * library you pass in, normally `verify` from `@phala/dcap-qvl`, a pure\n * JavaScript implementation that runs in browsers, Node and React Native. It\n * is passed in rather than bundled so this SDK keeps no runtime dependencies,\n * and applications that never talk to a TEE node pay nothing for it.\n */\n\nimport { hex } from '../crypto/internal.js';\nimport type { VerifyTransportQuote } from './sealed.js';\n\n/**\n * The collateral a quote is verified against \u2014 TCB info, QE identity, CRLs and\n * their chains \u2014 in dcap-qvl's form: byte fields are hex strings or byte\n * arrays. What `@phala/dcap-qvl`'s `getCollateral` fetches.\n */\nexport interface DcapCollateral {\n pck_crl_issuer_chain: string;\n root_ca_crl: number[] | string;\n pck_crl: number[] | string;\n tcb_info_issuer_chain: string;\n tcb_info: string;\n tcb_info_signature: number[] | string;\n qe_identity_issuer_chain: string;\n qe_identity: string;\n qe_identity_signature: number[] | string;\n}\n\n/** The fields of a TDX report this verifier reads. */\ninterface TdReport {\n mrTd: Uint8Array;\n rtMr0: Uint8Array;\n rtMr1: Uint8Array;\n rtMr2: Uint8Array;\n rtMr3: Uint8Array;\n reportData: Uint8Array;\n tdAttributes?: Uint8Array;\n}\n\n/** What a DCAP verifier returns for a quote whose signature chain verified. */\nexport interface DcapVerifiedReport {\n status: string;\n advisory_ids?: string[];\n report: { type: string; data: unknown };\n}\n\n/**\n * Verify a quote's signature chain against `collateral` as of `nowSecs`, and\n * appraise its TCB level. Throws when it does not verify. `verify` from\n * `@phala/dcap-qvl` has exactly this shape.\n */\nexport type DcapVerify = (\n quote: Uint8Array,\n collateral: DcapCollateral,\n nowSecs: number,\n) => DcapVerifiedReport;\n\n/**\n * One image's measurements, all five registers, hex. A quote matches it only\n * when every register does, so measurements of different images never combine.\n */\nexport interface TrustedMeasurements {\n mrtd: string;\n rtmr0: string;\n rtmr1: string;\n rtmr2: string;\n rtmr3: string;\n}\n\nexport interface QuoteVerifierOptions {\n /** DCAP verification: `verify` from `@phala/dcap-qvl`. */\n dcapVerify: DcapVerify;\n /**\n * The images trusted, each by all of its measurements. The way to say which\n * code may read the traffic: build it with {@link trustedMeasurementsFromReleases}\n * from the `published-mrtds.json` of the releases you trust.\n */\n allowedMeasurements?: TrustedMeasurements[];\n /**\n * MRTDs (hex) accepted. On its own this does not name an image: on GCP the\n * MRTD measures the platform's TD firmware, which every image shares, and\n * the image is in RTMR1\u20133. So a verifier needs either\n * {@link allowedMeasurements}, or this with all of `allowedRtmr1`\u2013`3`.\n */\n allowedMrtd?: string[];\n /** RTMR allowlists (hex); a register is not checked when its list is left out. */\n allowedRtmr0?: string[];\n allowedRtmr1?: string[];\n allowedRtmr2?: string[];\n allowedRtmr3?: string[];\n /**\n * TCB statuses accepted. Defaults to `['UpToDate']`. `Revoked` is refused\n * even when listed.\n */\n allowedTcbStatuses?: string[];\n /**\n * Where to get collateral (a Calimero 1.0 node sends none): for example\n * `(quote) => getCollateral(PHALA_PCCS_URL, quote)` from `@phala/dcap-qvl`.\n * Without it, a quote that came without collateral is refused.\n */\n fetchCollateral?: (quote: Uint8Array) => Promise<DcapCollateral>;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/** A quote verifier as this package builds one ({@link createQuoteVerifier}). */\nexport type QuoteVerifier = VerifyTransportQuote & { readonly includeCollateral: true };\n\nconst MEASUREMENT_HEX = /^[0-9a-f]{96}$/;\nconst REGISTERS = ['mrtd', 'rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] as const;\n\n/**\n * A verifier that checks a TEE node's quote here, in the page, and accepts it\n * only when every check passes:\n *\n * - its signatures verify against Intel's root, with collateral that is valid\n * now;\n * - the platform's TCB status is one allowed (`UpToDate` by default), and\n * never `Revoked`;\n * - its measurements are those of a trusted image: one of\n * `allowedMeasurements` in full, and the MRTD and any RTMRs listed;\n * - its report data is the nonce followed by the binding the client computed.\n *\n * Any failure rejects with the reason; nothing is trusted from a quote that\n * does not pass. Mock quotes never pass: they carry no signature.\n *\n * ```ts\n * import { verify as dcapVerify } from '@phala/dcap-qvl';\n *\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...trustedMeasurementsFromReleases([publishedMrtds], { profile: 'locked-read-only' }),\n * });\n * const client = new CalimeroClient({ baseUrl, policy: { verifyQuote: verifier } });\n * ```\n */\nexport function createQuoteVerifier(options: QuoteVerifierOptions): QuoteVerifier {\n const allowedMrtd = measurements(options.allowedMrtd ?? [], 'allowedMrtd');\n const allowedImages = (options.allowedMeasurements ?? []).map((image, index) => {\n const label = `allowedMeasurements[${index}]`;\n return REGISTERS.map((register) => measurements([image?.[register] ?? ''], `${label}.${register}`)[0]).join();\n });\n const allowedRtmr = [\n measurements(options.allowedRtmr0 ?? [], 'allowedRtmr0'),\n measurements(options.allowedRtmr1 ?? [], 'allowedRtmr1'),\n measurements(options.allowedRtmr2 ?? [], 'allowedRtmr2'),\n measurements(options.allowedRtmr3 ?? [], 'allowedRtmr3'),\n ];\n if (options.allowedMeasurements !== undefined && allowedImages.length === 0) {\n throw new Error('allowedMeasurements is empty, so no quote would ever be accepted');\n }\n if (allowedImages.length === 0) {\n if (allowedMrtd.length === 0) {\n throw new Error('No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3');\n }\n if (allowedRtmr.slice(1).some((list) => list.length === 0)) {\n throw new Error(\n 'allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which ' +\n 'images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too',\n );\n }\n }\n const allowedStatuses = options.allowedTcbStatuses ?? ['UpToDate'];\n const now = options.now ?? Date.now;\n\n const verifier = async ({\n quoteB64,\n nonce,\n reportDataSuffix,\n collateral,\n }: Parameters<VerifyTransportQuote>[0]): Promise<boolean> => {\n const quote = fromBase64(quoteB64);\n const against = collateral ?? (await options.fetchCollateral?.(quote));\n if (!against) {\n throw new Error(\n 'The node sent no collateral for its quote, and no fetchCollateral was given to get it',\n );\n }\n\n let verified: DcapVerifiedReport;\n try {\n verified = options.dcapVerify(quote, against, Math.floor(now() / 1000));\n } catch (error) {\n throw new Error(`The quote did not verify: ${(error as Error)?.message ?? String(error)}`);\n }\n\n if (verified.status === 'Revoked' || !allowedStatuses.includes(verified.status)) {\n throw new Error(`The platform's TCB status is ${verified.status}, which is not accepted`);\n }\n const td = tdReport(verified.report);\n // TUD bit 0. A debug TD's memory and registers are open to the host, so its\n // measurements prove nothing about what runs in it. Checked here, not left\n // to `dcapVerify`, which a caller may swap for one that allows debug; an\n // attribute field that cannot be read counts as debug.\n if (td.tdAttributes?.length !== 8 || (td.tdAttributes[0] & 0x01) !== 0) {\n throw new Error('The quote is from a debug TD, or its TD attributes cannot be read');\n }\n const measured = [td.mrTd, td.rtMr0, td.rtMr1, td.rtMr2, td.rtMr3].map((register) => hex(register));\n if (allowedImages.length > 0 && !allowedImages.includes(measured.join())) {\n throw new Error(\n `The measurements (MRTD ${measured[0]}, RTMR0-3 ${measured.slice(1).join(', ')}) are not an image this verifier trusts`,\n );\n }\n if (allowedMrtd.length > 0 && !allowedMrtd.includes(measured[0])) {\n throw new Error(`MRTD ${measured[0]} is not an image this verifier trusts`);\n }\n const registers = [td.rtMr0, td.rtMr1, td.rtMr2, td.rtMr3];\n registers.forEach((register, index) => {\n const allowed = allowedRtmr[index];\n if (allowed.length > 0 && !allowed.includes(hex(register))) {\n throw new Error(`RTMR${index} ${hex(register)} is not one this verifier trusts`);\n }\n });\n if (hex(td.reportData) !== `${nonce}${reportDataSuffix}`.toLowerCase()) {\n throw new Error('The quote does not commit to this nonce and binding');\n }\n return true;\n };\n return Object.assign(verifier, { includeCollateral: true as const });\n}\n\nfunction measurements(values: string[], label: string): string[] {\n return values.map((value) => {\n const normalized = value.trim().toLowerCase();\n if (!MEASUREMENT_HEX.test(normalized)) {\n throw new Error(`${label} holds ${JSON.stringify(value)}, which is not a 48-byte hex measurement`);\n }\n return normalized;\n });\n}\n\n/** The TD report of a TDX quote (1.0 or 1.5); anything else is refused. */\nfunction tdReport(report: DcapVerifiedReport['report']): TdReport {\n const data = report.data as (TdReport & { base?: TdReport }) | undefined;\n if (report.type === 'td10' && data) return data;\n if (report.type === 'td15' && data?.base) return data.base;\n throw new Error(`The quote is a ${report.type} quote, not a TDX one`);\n}\n\nfunction fromBase64(value: string): Uint8Array {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * A mero-tee node release's `published-mrtds.json`: the measurements the\n * release workflow observed booting each profile of its image on TDX, signed\n * with the release. Only the fields read here are typed.\n */\nexport interface PublishedMrtds {\n role?: string;\n tag?: string;\n profiles: Record<\n string,\n {\n mrtd: string;\n rtmr0: string;\n rtmr1: string;\n rtmr2: string;\n rtmr3: string;\n allowed_tcb_statuses?: string[];\n }\n >;\n}\n\n/** TCB statuses as DCAP reports them; the release lists them in lower case. */\nconst TCB_STATUSES = [\n 'UpToDate',\n 'SWHardeningNeeded',\n 'ConfigurationNeeded',\n 'ConfigurationAndSWHardeningNeeded',\n 'OutOfDate',\n 'OutOfDateConfigurationNeeded',\n];\n\n/**\n * The {@link QuoteVerifierOptions} that trust exactly one profile of the given\n * releases: each release's image by all of its measurements, and only the TCB\n * statuses every one of those releases accepts.\n *\n * Pass every release a node you talk to may run. During a rollout that is the\n * old one and the new one; drop the old one once no node runs it.\n *\n * ```ts\n * import published from './trusted/mero-tee-v2.3.78.published-mrtds.json';\n *\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...trustedMeasurementsFromReleases([published], { profile: 'locked-read-only' }),\n * });\n * ```\n *\n * Where the file comes from is the trust decision. Shipping it with the app\n * (checked out of a release you verified) trusts that release; fetching it at\n * run time trusts whoever serves it.\n */\n/**\n * The one image profile a release publishes for production. The `debug` and\n * `debug-read-only` images are signed and published beside it, but run with\n * SSH and the operator's tooling inside the TD, so trusting one trusts an\n * image the operator can read.\n */\nexport const PRODUCTION_PROFILE = 'locked-read-only';\n\nexport interface TrustedProfileOptions {\n /** The image profile to trust, e.g. `locked-read-only`. */\n profile: string;\n /**\n * Trust a profile other than {@link PRODUCTION_PROFILE}, such as `debug`.\n * Its image is readable by whoever operates the node, so only for testing.\n */\n allowDebugProfile?: boolean;\n}\n\nexport function trustedMeasurementsFromReleases(\n releases: PublishedMrtds[],\n { profile, allowDebugProfile = false }: TrustedProfileOptions,\n): Required<Pick<QuoteVerifierOptions, 'allowedMeasurements' | 'allowedTcbStatuses'>> {\n if (releases.length === 0) {\n throw new Error('No release given, so no image would be trusted');\n }\n let statuses: string[] | undefined;\n const allowedMeasurements = releases.map((release, index) => {\n const name = release?.tag ?? `releases[${index}]`;\n if (release?.role !== undefined && release.role !== 'node') {\n throw new Error(`${name} lists the measurements of a ${release.role}, not of a node image`);\n }\n const image = release?.profiles?.[profile];\n if (!image) {\n const known = Object.keys(release?.profiles ?? {}).join(', ') || 'none';\n throw new Error(`${name} has no profile ${JSON.stringify(profile)} (it has: ${known})`);\n }\n if (profile !== PRODUCTION_PROFILE && !allowDebugProfile) {\n throw new Error(\n `${JSON.stringify(profile)} is not a production profile: its image is readable by whoever ` +\n `operates the node. Trust ${JSON.stringify(PRODUCTION_PROFILE)}, or pass allowDebugProfile to test`,\n );\n }\n const accepted = (image.allowed_tcb_statuses ?? ['uptodate']).map((status) => tcbStatus(status, name));\n statuses = statuses === undefined ? accepted : statuses.filter((status) => accepted.includes(status));\n return {\n mrtd: image.mrtd,\n rtmr0: image.rtmr0,\n rtmr1: image.rtmr1,\n rtmr2: image.rtmr2,\n rtmr3: image.rtmr3,\n };\n });\n if (!statuses || statuses.length === 0) {\n throw new Error('The releases given accept no TCB status in common');\n }\n return { allowedMeasurements, allowedTcbStatuses: statuses };\n}\n\nfunction tcbStatus(status: string, release: string): string {\n const known = TCB_STATUSES.find((candidate) => candidate.toLowerCase() === String(status).toLowerCase());\n if (!known) {\n throw new Error(`${release} accepts TCB status ${JSON.stringify(status)}, which this verifier does not know`);\n }\n return known;\n}\n", "/**\n * Trusting a TEE node's image by its signed release, fetched at run time from\n * anywhere, instead of shipping the release's `published-mrtds.json` with the\n * app.\n *\n * Each mero-tee node release publishes `published-mrtds.json` (the\n * measurements of its image) with a cosign keyless bundle, signed by the\n * mero-tee release workflow on GitHub Actions. {@link verifySignedNodeRelease}\n * checks that signature here, against the Sigstore trust root embedded in this\n * package, so the file can come from any source: the cloud's mirror\n * (`GET https://cloud.calimero.network/api/tee/node-releases/{version}`), a\n * mirror of your own, or a file bundled with the app. None of them is\n * trusted; a file whose signature does not verify is refused.\n *\n * What is trusted:\n *\n * - the signer: the node release workflow of `calimero-network/mero-tee` on\n * `master` ({@link NODE_RELEASE_SIGNER}), the identity core pins as\n * `NODE_RELEASE_IDENTITY`;\n * - the Sigstore public-good trust root: Fulcio's CAs and Rekor's key;\n * - the minimum release you pass, below which no release is accepted.\n *\n * What is not: the transport, the server that serves the release, and the\n * node's choice of release. A node can present any genuinely signed release\n * at or above the minimum, and no other; its quote must then match that\n * release's measurements exactly, so it cannot claim one release and run\n * another.\n */\n\nimport { verifyCosignBundle, type SignerIdentity } from './sigstore.js';\nimport {\n createQuoteVerifier,\n trustedMeasurementsFromReleases,\n type DcapVerify,\n type PublishedMrtds,\n type QuoteVerifier,\n type QuoteVerifierOptions,\n type TrustedProfileOptions,\n} from './verify.js';\n\n/** The workflow that signs every mero-tee node release, and the issuer of its identity. */\nexport const NODE_RELEASE_SIGNER: Readonly<SignerIdentity> = Object.freeze({\n identity:\n 'https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master',\n issuer: 'https://token.actions.githubusercontent.com',\n});\n\nconst MEASUREMENTS = ['mrtd', 'rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] as const;\n\n/**\n * The public mirror of signed node releases, used when no other source is\n * given. Only a transport: what it serves is verified, so it can fail to\n * answer but cannot make a release trusted.\n */\nexport const DEFAULT_RELEASE_MIRROR = 'https://cloud.calimero.network';\n\n/**\n * Where browsers get Intel's collateral for a quote: the cloud's mirror of the\n * PCCS paths `@phala/dcap-qvl` reads, open to any origin. Intel's PCS sends no\n * CORS header. The mirror only carries Intel-signed items.\n */\nexport const DEFAULT_COLLATERAL_MIRROR = `${DEFAULT_RELEASE_MIRROR}/api/tee/pcs`;\n\n/**\n * A node release as the servers hand it out, wrapped as `{\"data\": ...}`: the\n * release's `published-mrtds.json`, byte for byte, and its cosign bundle.\n * Unverified until {@link verifySignedNodeRelease} says otherwise.\n */\nexport interface SignedNodeRelease {\n /** The release, e.g. `2.3.87`. It must be the signed file's `tag`. */\n version: string;\n /** `published-mrtds.json`, exactly as signed. */\n publishedMrtds: string;\n /** `published-mrtds.json.bundle.json`, as JSON text. */\n bundle: string;\n}\n\nexport interface VerifySignedNodeReleaseOptions {\n /** Require the file's `tag` to be this release. */\n expectedVersion?: string;\n /** The certificate identity required. Defaults to {@link NODE_RELEASE_SIGNER}'s. */\n identity?: string;\n /** The OIDC issuer required. Defaults to {@link NODE_RELEASE_SIGNER}'s. */\n issuer?: string;\n /** The release's detached `published-mrtds.json.sig`, when you have it; it must be the bundle's. */\n signature?: string;\n}\n\n/**\n * Verify a node release's `published-mrtds.json` against its cosign bundle,\n * as `cosign verify-blob` would, and return the file parsed. Rejects, with the\n * reason, unless:\n *\n * - the signature over the exact bytes verifies with the bundle's certificate;\n * - that certificate chains to a Fulcio CA in the Sigstore trust root, and it\n * and the CA were valid when Rekor logged the signature;\n * - it names the node release workflow and GitHub Actions as its issuer;\n * - Rekor's signed entry timestamp verifies, for an entry that is this\n * signature over this file by this certificate;\n * - the file is a node release (`role: \"node\"`), and `expectedVersion`, when\n * given, is its `tag`.\n *\n * Nothing is read from the clock: the certificate is checked at the time Rekor\n * logged the signature, so a release that verifies once always does.\n */\nexport async function verifySignedNodeRelease(\n publishedMrtds: string | Uint8Array,\n bundle: string | object,\n options: VerifySignedNodeReleaseOptions = {},\n): Promise<PublishedMrtds> {\n const body = typeof publishedMrtds === 'string' ? new TextEncoder().encode(publishedMrtds) : publishedMrtds;\n await verifyCosignBundle(\n body,\n bundle,\n {\n identity: options.identity ?? NODE_RELEASE_SIGNER.identity,\n issuer: options.issuer ?? NODE_RELEASE_SIGNER.issuer,\n },\n options.signature,\n );\n\n let release: PublishedMrtds;\n try {\n release = JSON.parse(new TextDecoder().decode(body));\n } catch {\n throw new Error('The signed release is not JSON');\n }\n if (release?.role !== 'node') {\n throw new Error(`The signed release is a ${JSON.stringify(release?.role)} release, not a node one`);\n }\n // The workflow signs other files too, some with a `role` and `profiles` of\n // their own (`release-provenance.json`): the signature covers bytes, not a\n // file name, so check this is the measurements file.\n const profiles = Object.values(release.profiles ?? {});\n const measured = (image: unknown) =>\n MEASUREMENTS.every((register) => /^[0-9a-f]{96}$/i.test(String((image as Record<string, unknown>)?.[register])));\n if (typeof release.tag !== 'string' || profiles.length === 0 || !profiles.every(measured)) {\n throw new Error(\"The signed file is not a release's published-mrtds.json: it lists no measured profiles\");\n }\n if (options.expectedVersion !== undefined && release.tag !== options.expectedVersion) {\n throw new Error(`The signed release is ${release.tag}, not ${options.expectedVersion}`);\n }\n return release;\n}\n\n/**\n * Fetch a {@link SignedNodeRelease} from a server that wraps it as\n * `{\"data\": ...}`, such as the cloud's {@link cloudNodeReleaseUrl}. It is\n * only fetched: pass it to\n * {@link trustSignedRelease}, or {@link verifySignedNodeRelease}, before using it.\n */\nexport async function fetchNodeRelease(\n url: string,\n options: { fetch?: typeof fetch } = {},\n): Promise<SignedNodeRelease> {\n const response = await (options.fetch ?? fetch)(url, { headers: { accept: 'application/json' } });\n if (!response.ok) throw new Error(`Fetching the node release from ${url} failed: HTTP ${response.status}`);\n let release: Partial<SignedNodeRelease> | undefined;\n try {\n release = ((await response.json()) as { data?: Partial<SignedNodeRelease> })?.data;\n } catch {\n throw new Error(`${url} did not answer with JSON`);\n }\n if (\n typeof release?.version !== 'string' ||\n typeof release.publishedMrtds !== 'string' ||\n typeof release.bundle !== 'string'\n ) {\n throw new Error(`${url} did not answer with a signed node release`);\n }\n return { version: release.version, publishedMrtds: release.publishedMrtds, bundle: release.bundle };\n}\n\n/** Where mero-tee publishes its releases' assets, as core's `calimero-tee-release` fetches them. */\nexport const GITHUB_RELEASES = 'https://github.com/calimero-network/mero-tee/releases/download';\n\n/**\n * Node release `version` straight from its GitHub release (`mero-tee-v{version}`):\n * `published-mrtds.json` and its cosign bundle, the files core's Rust client\n * verifies. Only fetched: verify it with {@link trustSignedRelease}. GitHub's\n * downloads send no CORS headers, so in a browser use a mirror\n * ({@link cloudNodeReleaseUrl}) instead.\n */\nexport async function fetchGithubNodeRelease(\n version: string,\n options: { fetch?: typeof fetch; base?: string } = {},\n): Promise<SignedNodeRelease> {\n const tag = `mero-tee-v${releaseVersion(version, 'version')}`;\n const base = `${(options.base ?? GITHUB_RELEASES).replace(/\\/+$/, '')}/${tag}/published-mrtds.json`;\n const get = async (url: string): Promise<string> => {\n const response = await (options.fetch ?? fetch)(url);\n if (!response.ok) throw new Error(`Fetching ${url} failed: HTTP ${response.status}`);\n return response.text();\n };\n const [publishedMrtds, bundle] = await Promise.all([get(base), get(`${base}.bundle.json`)]);\n return { version, publishedMrtds, bundle };\n}\n\n/** Where the cloud at `cloudUrl` (e.g. `https://cloud.calimero.network`) mirrors node release `version`. */\nexport function cloudNodeReleaseUrl(cloudUrl: string, version: string): string {\n return `${cloudUrl.replace(/\\/+$/, '')}/api/tee/node-releases/${releaseVersion(version, 'version')}`;\n}\n\nexport interface TrustSignedReleaseOptions extends TrustedProfileOptions {\n /** The release, from any source; it is verified here. */\n release: SignedNodeRelease;\n /**\n * The oldest release accepted, e.g. `2.3.87`. Required: every release ever\n * signed stays validly signed, so without a floor a node could present an\n * old release, with a flaw since fixed, and a quote from that old image\n * would pass. Raise it when a release must no longer be trusted.\n */\n minReleaseVersion: string;\n /** Override the signer; defaults to {@link NODE_RELEASE_SIGNER}. */\n identity?: string;\n issuer?: string;\n}\n\n/**\n * The {@link QuoteVerifierOptions} that trust one profile of a signed node\n * release, from an untrusted source: its signature is verified, its signed\n * `tag` must be `release.version` and no older than `minReleaseVersion`, and\n * then it is read as {@link trustedMeasurementsFromReleases} reads a bundled\n * file.\n *\n * ```ts\n * const version = claimedRelease(attestationDoc, '2.3.109'); // the release the node names\n * const release = await fetchNodeRelease(cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, version));\n * const verifier = createQuoteVerifier({\n * dcapVerify,\n * ...(await trustSignedRelease({ release, profile: 'locked-read-only', minReleaseVersion: '2.3.87' })),\n * });\n * ```\n */\nexport async function trustSignedRelease(\n options: TrustSignedReleaseOptions,\n): Promise<Required<Pick<QuoteVerifierOptions, 'allowedMeasurements' | 'allowedTcbStatuses'>>> {\n const minimum = releaseVersion(options.minReleaseVersion, 'minReleaseVersion');\n const version = releaseVersion(options.release?.version, 'The release version');\n const published = await verifySignedNodeRelease(options.release.publishedMrtds, options.release.bundle, {\n expectedVersion: version,\n identity: options.identity,\n issuer: options.issuer,\n });\n if (compareReleaseVersions(version, minimum) < 0) {\n throw new Error(`Release ${version} is older than the minimum trusted, ${minimum}`);\n }\n return trustedMeasurementsFromReleases([published], {\n profile: options.profile,\n allowDebugProfile: options.allowDebugProfile,\n });\n}\n\nexport interface SignedReleaseVerifierOptions extends Omit<TrustSignedReleaseOptions, 'release'> {\n /** DCAP verification: `verify` from `@phala/dcap-qvl`. */\n dcapVerify: DcapVerify;\n /**\n * Where to get the node's release, asked again each time the node is\n * attested (a restarted node may run a newer one). Untrusted: it is\n * verified, and the quote must match it.\n */\n release: () => Promise<SignedNodeRelease>;\n /** As {@link QuoteVerifierOptions.fetchCollateral}. */\n fetchCollateral?: QuoteVerifierOptions['fetchCollateral'];\n /** The current time in milliseconds, for the quote's collateral; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/**\n * A {@link createQuoteVerifier} whose trusted image is the signed release the\n * node says it runs. On each attestation it gets the release, checks it with\n * {@link trustSignedRelease}, and verifies the quote against that release's\n * measurements only.\n *\n * The node's choice of release is the one thing taken from it, and it is\n * bounded: only a genuinely signed release at or above `minReleaseVersion`\n * passes, and the quote must then be of exactly that release's image. Pass it\n * as `NodePolicy.verifyQuote` to choose where the release comes from yourself.\n */\nexport function createSignedReleaseVerifier(options: SignedReleaseVerifierOptions): QuoteVerifier {\n releaseVersion(options.minReleaseVersion, 'minReleaseVersion');\n const verifier = async (args: Parameters<QuoteVerifier>[0]): Promise<boolean> => {\n const trusted = await trustSignedRelease({\n release: await options.release(),\n profile: options.profile,\n allowDebugProfile: options.allowDebugProfile,\n minReleaseVersion: options.minReleaseVersion,\n identity: options.identity,\n issuer: options.issuer,\n });\n return createQuoteVerifier({\n dcapVerify: options.dcapVerify,\n fetchCollateral: options.fetchCollateral,\n now: options.now,\n ...trusted,\n })(args);\n };\n return Object.assign(verifier, { includeCollateral: true as const });\n}\n\nconst RELEASE_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\n/** `value` if it is a release version (`2.3.87`, `2.3.88-rc.1`); throws otherwise. */\nexport function releaseVersion(value: unknown, what: string): string {\n const match = typeof value === 'string' ? RELEASE_VERSION.exec(value) : null;\n const pre = match?.[4];\n if (!match || (pre !== undefined && pre.split('.').some((id) => id === ''))) {\n throw new Error(`${what} is ${JSON.stringify(value)}, not a release version like 2.3.87`);\n }\n return value as string;\n}\n\n/**\n * Order two release versions as semver does, and as core's\n * `compare_release_versions`: numerically by `X.Y.Z`, a pre-release before its\n * release, build metadata ignored.\n */\nexport function compareReleaseVersions(a: string, b: string): number {\n const [aCore, aPre] = splitVersion(a);\n const [bCore, bPre] = splitVersion(b);\n for (let i = 0; i < 3; i += 1) {\n if (aCore[i] !== bCore[i]) return aCore[i] < bCore[i] ? -1 : 1;\n }\n if (aPre === undefined || bPre === undefined) return aPre === bPre ? 0 : aPre === undefined ? 1 : -1;\n const aIds = aPre.split('.');\n const bIds = bPre.split('.');\n for (let i = 0; i < Math.max(aIds.length, bIds.length); i += 1) {\n const [x, y] = [aIds[i], bIds[i]];\n if (x === undefined || y === undefined) return x === undefined ? -1 : 1;\n const [xNum, yNum] = [/^\\d+$/.test(x), /^\\d+$/.test(y)];\n const order =\n xNum && yNum ? Math.sign(Number(x) - Number(y)) : xNum !== yNum ? (xNum ? -1 : 1) : x < y ? -1 : x > y ? 1 : 0;\n if (order !== 0) return order;\n }\n return 0;\n}\n\nfunction splitVersion(version: string): [number[], string | undefined] {\n const match = RELEASE_VERSION.exec(version) as RegExpExecArray;\n return [[Number(match[1]), Number(match[2]), Number(match[3])], match[4]];\n}\n", "/**\n * The check every cloud client runs before it sends anything: the node's quote\n * must be genuine (or, in development, an explicitly allowed mock), from an\n * image this client trusts, and its report data must bind this nonce, the\n * expected app and the transport key the sealed channel will be opened to.\n *\n * Report data, as core's `calimero-cloud-client::attest` builds it:\n * `nonce(32) || SHA-256(\"calimero.tee-attest.transport-key.v1\" | app_hash | transport_key)`.\n *\n * A real quote is judged as the Rust client judges it (`attest::verify` with\n * `Measurements::Release`): the node names the mero-tee release it runs; that\n * release must be at least `minReleaseVersion`; its `published-mrtds.json` is\n * fetched and its Sigstore signature checked against the node release workflow;\n * the quote's signature chain and TCB status are checked against Intel's\n * collateral (fetched here: the node sends none, and cannot forge it); the TD\n * must not be a debug TD; and its registers must be the release's image for the\n * trusted profile, `locked-read-only` unless a debug profile is explicitly\n * allowed. Nothing here reads the environment: mock quotes pass only with\n * `allowMock`.\n */\n\nimport { fromHex, hex } from '../crypto/internal.js';\nimport {\n DEFAULT_COLLATERAL_MIRROR,\n DEFAULT_RELEASE_MIRROR,\n cloudNodeReleaseUrl,\n compareReleaseVersions,\n fetchGithubNodeRelease,\n fetchNodeRelease,\n releaseVersion,\n trustSignedRelease,\n type SignedNodeRelease,\n} from '../sealed/release.js';\nimport { transportKeyBinding, type VerifyTransportQuote } from '../sealed/sealed.js';\nimport { PRODUCTION_PROFILE, createQuoteVerifier, type DcapCollateral, type DcapVerify } from '../sealed/verify.js';\n\n/** The mock quote format development clusters use. */\nexport const MOCK_QUOTE_HEADER = 'MOCK_TDX_QUOTE_V1';\n\n/** How the signed release a node names is trusted (core's `Measurements::Release`). */\nexport interface NodeReleasePolicy {\n /**\n * The oldest mero-tee release trusted, e.g. `2.3.109`. Required: every\n * release ever signed stays validly signed, so without a floor a node could\n * name an old release with a flaw since fixed.\n */\n minReleaseVersion: string;\n /** The image profile trusted; defaults to `locked-read-only`. */\n profile?: string;\n /** Trust a debug profile. Its image is readable by the operator: testing only. */\n allowDebugProfile?: boolean;\n /**\n * Where the release's signed measurements come from: `'github'` (the release\n * assets, what core's Rust client reads; no CORS, so not in browsers), the\n * base URL of a mirror (default {@link DEFAULT_RELEASE_MIRROR}), or a function.\n * Untrusted either way: the Sigstore signature is checked here.\n */\n releaseSource?: 'github' | string | ((version: string) => Promise<SignedNodeRelease>);\n /** DCAP verification; defaults to `verify` from `@phala/dcap-qvl`, loaded on first use. */\n dcapVerify?: DcapVerify;\n /**\n * Intel's collateral for a quote. Defaults to `@phala/dcap-qvl`'s\n * `getCollateral` from `collateralSource`.\n */\n fetchCollateral?: (quote: Uint8Array) => Promise<DcapCollateral>;\n /**\n * Where the default `fetchCollateral` gets Intel's collateral: a PCCS base\n * URL (default {@link DEFAULT_COLLATERAL_MIRROR}, the cloud's mirror, which a\n * browser on any origin can read), or `'intel'` for Intel's PCS itself (no\n * CORS: not in browsers). Untrusted either way: every item is signed by\n * Intel and verified up to Intel's root CA, which `@phala/dcap-qvl` carries.\n */\n collateralSource?: 'intel' | string;\n /**\n * Refuse collateral whose TCB info Intel issued more than this many days\n * ago. Unset: only Intel's own `nextUpdate` (about 30 days out) bounds how\n * old it may be. A mirror cannot forge collateral, but it can replay an\n * older, still valid copy; this shortens that window. Too small a value\n * refuses every node if Intel is slow to re-sign.\n */\n maxCollateralAgeDays?: number;\n /** Override the release signer (defaults to the mero-tee node release workflow). */\n identity?: string;\n issuer?: string;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\nexport interface NodePolicy {\n /** Accept mock quotes. Development clusters only; never set from the environment. */\n allowMock?: boolean;\n /** Trust real quotes from the signed release the node runs. */\n release?: NodeReleasePolicy;\n /**\n * Verify a real quote yourself instead (e.g. `createQuoteVerifier` with\n * pinned measurements). Takes precedence over `release`.\n */\n verifyQuote?: VerifyTransportQuote;\n /** The app bundle hash (hex) the quote must bind, when talking to one app. */\n appHash?: string;\n}\n\nexport interface AttestationDoc {\n quote: string;\n transportKey: string;\n appHash: string;\n nonce: string;\n release: { version: string; profile: string };\n cluster: string;\n node: number;\n mock: boolean;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\ntype DcapModule = {\n verify?: unknown;\n getCollateral?: unknown;\n getCollateralFromPcs?: unknown;\n default?: { verify?: unknown; getCollateral?: unknown; getCollateralFromPcs?: unknown };\n};\nlet dcapModule: Promise<DcapModule> | undefined;\n\n/** A function out of `@phala/dcap-qvl`, whatever shape the bundler gave the (CommonJS) module. */\nasync function dcap<T>(name: 'verify' | 'getCollateral' | 'getCollateralFromPcs'): Promise<T> {\n dcapModule ??= import('@phala/dcap-qvl') as Promise<DcapModule>;\n const ns = await dcapModule;\n const f = typeof ns[name] === 'function' ? ns[name] : ns.default?.[name];\n if (typeof f !== 'function') throw new TypeError(`@phala/dcap-qvl loaded without ${name}`);\n return f as T;\n}\n\n/**\n * The release a node names, checked against the floor before anything is\n * fetched. Accepts `2.3.109` and the tag form `mero-tee-v2.3.109`.\n */\nexport function claimedRelease(doc: Pick<AttestationDoc, 'release'>, minReleaseVersion: string): string {\n const floor = releaseVersion(minReleaseVersion, 'minReleaseVersion');\n const raw = String(doc.release?.version ?? '').trim().replace(/^mero-tee-v/, '').replace(/^v/, '');\n const version = releaseVersion(raw, 'The release the node names');\n if (compareReleaseVersions(version, floor) < 0) {\n throw new Error(`mero-tee release ${version} is older than the minimum ${floor}`);\n }\n return version;\n}\n\nasync function releaseFor(version: string, policy: NodeReleasePolicy, fetchImpl: typeof fetch) {\n const source = policy.releaseSource;\n if (typeof source === 'function') return source(version);\n if (source === 'github') return fetchGithubNodeRelease(version, { fetch: fetchImpl });\n return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchImpl });\n}\n\n/** The collateral fetch a policy gets unless it brings its own: `@phala/dcap-qvl` against `collateralSource`. */\nfunction defaultCollateral(policy: NodeReleasePolicy): (quote: Uint8Array) => Promise<DcapCollateral> {\n const source = policy.collateralSource ?? DEFAULT_COLLATERAL_MIRROR;\n if (source === 'intel') {\n return async (quote) => (await dcap<(q: Uint8Array) => Promise<DcapCollateral>>('getCollateralFromPcs'))(quote);\n }\n return async (quote) =>\n (await dcap<(url: string, q: Uint8Array) => Promise<DcapCollateral>>('getCollateral'))(source, quote);\n}\n\n/** `fetch`, refusing collateral older than `policy.maxCollateralAgeDays` (by its TCB info's `issueDate`). */\nexport function freshCollateral(\n fetch: (quote: Uint8Array) => Promise<DcapCollateral>,\n policy: Pick<NodeReleasePolicy, 'maxCollateralAgeDays' | 'now'>,\n): (quote: Uint8Array) => Promise<DcapCollateral> {\n const maxDays = policy.maxCollateralAgeDays;\n if (maxDays === undefined) return fetch;\n return async (quote) => {\n const collateral = await fetch(quote);\n let issued: number;\n try {\n issued = Date.parse((JSON.parse(collateral.tcb_info) as { issueDate?: string }).issueDate ?? '');\n } catch {\n issued = Number.NaN;\n }\n if (!Number.isFinite(issued)) throw new Error(\"The quote's collateral names no TCB info issue date\");\n const ageDays = ((policy.now ?? Date.now)() - issued) / 86_400_000;\n if (ageDays > maxDays) {\n throw new Error(\n `The quote's collateral was issued ${Math.floor(ageDays)} days ago, more than the ${maxDays} this client accepts`,\n );\n }\n return collateral;\n };\n}\n\n/** Judge a real quote as core's `Measurements::Release` does. */\nasync function verifyRelease(\n doc: AttestationDoc,\n args: Parameters<VerifyTransportQuote>[0],\n policy: NodeReleasePolicy,\n fetchImpl: typeof fetch,\n): Promise<boolean> {\n // Refuse what no release could admit before reaching for the network.\n const version = claimedRelease(doc, policy.minReleaseVersion);\n const trusted = await trustSignedRelease({\n release: await releaseFor(version, policy, fetchImpl),\n profile: policy.profile ?? PRODUCTION_PROFILE,\n allowDebugProfile: policy.allowDebugProfile,\n minReleaseVersion: policy.minReleaseVersion,\n identity: policy.identity,\n issuer: policy.issuer,\n });\n const fetchCollateral = freshCollateral(policy.fetchCollateral ?? defaultCollateral(policy), policy);\n const verifier = createQuoteVerifier({\n dcapVerify: policy.dcapVerify ?? (await dcap<DcapVerify>('verify')),\n fetchCollateral,\n now: policy.now,\n ...trusted,\n });\n return verifier(args);\n}\n\n/** Fetch the node's attestation and return its transport key once it checks out. */\nexport async function fetchAttestedKey(\n baseUrl: string,\n policy: NodePolicy,\n fetchImpl: typeof fetch = (input, init) => fetch(input, init),\n): Promise<Uint8Array> {\n const nonce = hex(crypto.getRandomValues(new Uint8Array(32)));\n const url = new URL(`${baseUrl.replace(/\\/+$/, '')}/attestation`);\n url.searchParams.set('nonce', nonce);\n if (policy.appHash) url.searchParams.set('appHash', policy.appHash);\n const response = await fetchImpl(url.toString());\n if (!response.ok) throw new Error(`The node refused to attest: HTTP ${response.status}`);\n const doc = (await response.json()) as AttestationDoc;\n const transportKey = fromHex(doc.transportKey, 'transportKey', 32);\n const inner = policy.appHash ? fromHex(policy.appHash, 'appHash', 32) : new Uint8Array(32);\n const suffix = await transportKeyBinding(inner, transportKey);\n const quote = base64ToBytes(doc.quote);\n const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);\n if (equal(quote.slice(0, header.length), header)) {\n if (!policy.allowMock) {\n throw new Error('mock quote refused: this client only trusts real TEEs');\n }\n const report = quote.slice(header.length, header.length + 64);\n if (!equal(report.slice(0, 32), fromHex(nonce, 'nonce', 32)) || !equal(report.slice(32), suffix)) {\n throw new Error('the quote does not bind this transport key, app and nonce');\n }\n return transportKey;\n }\n const args = { quoteB64: doc.quote, nonce, reportDataSuffix: hex(suffix) };\n let ok: boolean;\n if (policy.verifyQuote) {\n ok = await policy.verifyQuote(args);\n } else if (policy.release) {\n ok = await verifyRelease(doc, args, policy.release, fetchImpl);\n } else {\n throw new Error('real quote refused: this client trusts no TD image (set policy.release)');\n }\n if (!ok) throw new Error('The attestation did not verify, so its transport key is not trusted');\n return transportKey;\n}\n", "/**\n * The Calimero Cloud node directory: which nodes of a cluster take traffic now,\n * and in what order this client tries them.\n *\n * `GET {directory}/{cluster}` (no auth) answers\n * `{ cluster, nodes: [{ id, url, zone, weight }], refreshAfterSeconds }`. The\n * directory is not trusted for security: it only picks which nodes to try.\n * Every node is attested under the caller's own policy before anything is sent\n * to it, so a bad list can only make connecting fail.\n */\n\n/** The Calimero Cloud control plane's public node directory. */\nexport const DEFAULT_DIRECTORY = 'https://manager.cloud.calimero.network/api/v2/directory';\n\n/** How long a listing stands when the directory does not say. */\nconst DEFAULT_REFRESH_SECONDS = 60;\n\n/** Why {@link DirectoryError} was thrown. */\nexport type DirectoryFailure = 'unreachable' | 'not-found' | 'bad-response' | 'empty';\n\n/**\n * The directory could not name a node to try: it could not be reached or\n * answered an error (`unreachable`), does not know the cluster (`not-found`,\n * a 404), answered something that is not a listing (`bad-response`), or listed\n * no usable node (`empty`).\n */\nexport class DirectoryError extends Error {\n constructor(\n readonly cluster: string,\n readonly reason: DirectoryFailure,\n message: string,\n readonly status?: number,\n readonly cause?: unknown,\n ) {\n super(`directory for cluster ${cluster}: ${message}`);\n this.name = 'DirectoryError';\n }\n}\n\n/** One usable node of a listing. */\nexport interface DirectoryNode {\n url: string;\n zone?: string;\n weight: number;\n}\n\nexport interface DirectoryListing {\n nodes: DirectoryNode[];\n refreshAfterSeconds: number;\n}\n\n/** The URL of `cluster`'s listing in `directory`. */\nexport function directoryUrl(directory: string, cluster: string): string {\n return `${directory.replace(/\\/+$/, '')}/${encodeURIComponent(cluster)}`;\n}\n\n/**\n * Read `cluster`'s listing, keeping only the entries with an http(s) URL and a\n * positive integer weight (the first of a repeated URL).\n */\nexport async function readDirectory(directory: string, cluster: string, fetcher: typeof fetch): Promise<DirectoryListing> {\n let response: Response;\n try {\n response = await fetcher(directoryUrl(directory, cluster), { method: 'GET', headers: { accept: 'application/json' } });\n } catch (error) {\n throw new DirectoryError(cluster, 'unreachable', `could not be reached: ${String(error)}`, undefined, error);\n }\n if (response.status === 404) throw new DirectoryError(cluster, 'not-found', 'unknown cluster', 404);\n if (!response.ok) throw new DirectoryError(cluster, 'unreachable', `answered ${response.status}`, response.status);\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new DirectoryError(cluster, 'bad-response', 'answered something other than JSON', response.status, error);\n }\n const listing = body as { nodes?: unknown; refreshAfterSeconds?: unknown } | null;\n if (!listing || typeof listing !== 'object' || !Array.isArray(listing.nodes)) {\n throw new DirectoryError(cluster, 'bad-response', 'answered no node list', response.status);\n }\n const nodes: DirectoryNode[] = [];\n const seen = new Set<string>();\n for (const entry of listing.nodes) {\n const node = usable(entry);\n if (node && !seen.has(node.url)) {\n seen.add(node.url);\n nodes.push(node);\n }\n }\n if (nodes.length === 0) throw new DirectoryError(cluster, 'empty', 'lists no usable node', response.status);\n const after = listing.refreshAfterSeconds;\n const refreshAfterSeconds =\n typeof after === 'number' && Number.isFinite(after) && after >= 1 ? after : DEFAULT_REFRESH_SECONDS;\n return { nodes, refreshAfterSeconds };\n}\n\nfunction usable(entry: unknown): DirectoryNode | undefined {\n if (!entry || typeof entry !== 'object') return undefined;\n const { url, zone, weight } = entry as Record<string, unknown>;\n if (typeof url !== 'string' || typeof weight !== 'number' || !Number.isInteger(weight) || weight < 1) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return undefined;\n return { url: url.replace(/\\/+$/, ''), zone: typeof zone === 'string' ? zone : undefined, weight };\n}\n\n/**\n * The order to try `nodes` in: those in `zone` first (when given), each group\n * in weighted-random order, a node's weight its relative chance to come next.\n * `random` answers in [0, 1), as `Math.random` does.\n */\nexport function orderNodes(nodes: DirectoryNode[], zone: string | undefined, random: () => number): string[] {\n const near = zone === undefined ? [] : nodes.filter((node) => node.zone === zone);\n const far = zone === undefined ? nodes : nodes.filter((node) => node.zone !== zone);\n return [...weightedOrder(near, random), ...weightedOrder(far, random)];\n}\n\nfunction weightedOrder(nodes: DirectoryNode[], random: () => number): string[] {\n const left = [...nodes];\n const order: string[] = [];\n while (left.length > 0) {\n let roll = random() * left.reduce((sum, node) => sum + node.weight, 0);\n let pick = 0;\n while (pick < left.length - 1 && roll >= left[pick].weight) roll -= left[pick++].weight;\n order.push(left.splice(pick, 1)[0].url);\n }\n return order;\n}\n", "/**\n * What the cloud node's refusals mean to a caller (spec D64, D70).\n *\n * The node answers an error as `{ error: CODE, message, details }` with an HTTP\n * status. {@link errorFrom} is the one place the client turns that into an\n * error a caller can switch on; every call, view and event stream goes through\n * it. It matches the status and the code together, never the status alone: the\n * node sends other 409s (`CONFLICT`, `NOT_INSTALLED`) that are not an\n * idempotency mismatch, and other 413s (`TOO_LARGE` from the sealed transport)\n * that are not oversized call arguments. Anything it does not recognise stays a\n * plain {@link CalimeroError} carrying both.\n *\n * Every typed error extends {@link CalimeroError}, so `instanceof CalimeroError`\n * and its `status` and `code` (the node's code) keep working for all of them.\n */\n\nexport class CalimeroError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n readonly details: Record<string, unknown> = {},\n ) {\n super(`${status} ${code}: ${message}`);\n this.name = 'CalimeroError';\n }\n}\n\n/**\n * `401 UNAUTHENTICATED` that refreshing could not answer: sign in (again) and\n * repeat the request.\n *\n * A session token is signed by the node that issued it, and other nodes take\n * it only while they can vouch for that node's signing key: a `401` often\n * means only that the issuer was replaced or cannot be reached, not that the\n * user signed out. The client answers that itself when it holds a refresh\n * token: it refreshes once (any node takes the refresh) and repeats the\n * request. This error reaches a caller when there is no refresh token (an API\n * key, say), or the refresh was refused.\n */\nexport class LoginRequired extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(401, 'UNAUTHENTICATED', message, details);\n this.name = 'LoginRequired';\n }\n}\n\n/**\n * `401 PASSKEY_UNKNOWN_HERE`: a sign-in (or a confirmation) with a passkey no\n * account of this cluster has. Accounts and passkeys are each cluster's own,\n * while clusters may share one WebAuthn rp-id (every Calimero Cloud cluster\n * uses `calimero.network`), so the browser offers a passkey made on another\n * cluster here too; a passkey removed from its account answers the same.\n *\n * It is not a {@link LoginRequired}: the client does not refresh for it, and\n * signing in again with the same passkey fails the same way. Offer to sign up\n * on this cluster, or point the person to the app link for the cluster their\n * account is on; the passkey's name in their password manager names that\n * cluster (`alice \u00B7 eu-shared-1`). The node does not say which cluster or\n * account the passkey belongs to: it only knows its own.\n */\nexport class PasskeyUnknownHere extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(\n 401,\n 'PASSKEY_UNKNOWN_HERE',\n message || 'this passkey belongs to another Calimero cluster or was removed from this one',\n details,\n );\n this.name = 'PasskeyUnknownHere';\n }\n}\n\n/**\n * `421 WRONG_NODE`: this node runs a mero-tee release the account's owners have\n * not approved, so it neither issues nor takes the account's sessions. Use\n * another node of the cluster; refreshing here would not help.\n *\n * The client moves to the next node it was given (`nodes`) and repeats the\n * request once by itself (a refresh: once per node). This error reaches a\n * caller when it knows no other node, when the next one refused too (for a\n * refresh, every node), or after a sign-in (which needs the passkey again:\n * repeat it, and it goes to the next node).\n */\nexport class WrongNode extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(421, 'WRONG_NODE', message, details);\n this.name = 'WrongNode';\n }\n}\n\n/**\n * `404 NOT_FOUND`: what the request names does not exist for this caller. For\n * an app this does not say whether it exists: an account the app does not\n * admit gets the same answer as a missing app.\n */\nexport class NotFound extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(404, 'NOT_FOUND', message, details);\n this.name = 'NotFound';\n }\n}\n\n/**\n * `412 CONFIRM_REQUIRED`: the call needs the account holder's passkey over a\n * challenge in `details`. The `*Confirmed` methods answer it themselves; it\n * reaches a caller only from a method that was given no passkey.\n */\nexport class ConfirmRequired extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(412, 'CONFIRM_REQUIRED', message, details);\n this.name = 'ConfirmRequired';\n }\n}\n\n/** The user declined the passkey prompt a confirmation asked for. Nothing was sent. */\nexport class ConfirmCancelled extends Error {\n constructor(readonly cause?: unknown) {\n super('the passkey confirmation was cancelled');\n this.name = 'ConfirmCancelled';\n }\n}\n\n/**\n * The browser or a password manager refused to show the passkey prompt a\n * confirmation asked for: the page was not focused (an extension's popup\n * still held focus), or another prompt was still open. The user did not\n * decline; nothing was sent. Ask them to try again from a click, e.g. \"Your\n * password manager or browser blocked the second prompt. Click to try again.\"\n * `cause` is the browser's error.\n */\nexport class ConfirmPromptBlocked extends Error {\n constructor(readonly cause?: unknown) {\n super('the passkey prompt was blocked by the browser or a password manager');\n this.name = 'ConfirmPromptBlocked';\n }\n}\n\n/** `413 ARGS_TOO_LARGE`: the call's arguments are over the node's limit; it did not run. */\nexport class ArgsTooLarge extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(413, 'ARGS_TOO_LARGE', message, details);\n this.name = 'ArgsTooLarge';\n }\n}\n\n/** `409 IDEMPOTENCY_MISMATCH`: the idempotency key was used before with different arguments. */\nexport class IdempotencyMismatch extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'IDEMPOTENCY_MISMATCH', message, details);\n this.name = 'IdempotencyMismatch';\n }\n}\n\n/**\n * `409 RELEASE_DEADLINE`: a mero-tee release's deadline has passed and the\n * set that governs this work (the app's publisher's, or its owner's) has not\n * approved it or a newer one, so new work (creating an app, installing a\n * release, upgrading an app) is refused. Apps already running keep running.\n * Approving `release` lifts it at once.\n */\nexport class ReleaseDeadlineError extends CalimeroError {\n /** The release to approve. */\n readonly release: string;\n /** Its deadline, RFC 3339 (`''` when the node did not say). */\n readonly after: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RELEASE_DEADLINE', message, details);\n this.name = 'ReleaseDeadlineError';\n this.release = typeof details.release === 'string' ? details.release : '';\n this.after = typeof details.after === 'string' ? details.after : '';\n }\n}\n\n/**\n * `409 RUNTIME_TOO_OLD`: a node that would run the app (one of its replicas\n * for an upgrade, a node it would be placed on or moved to) runs an older\n * runtime than the release's signed `minRuntimeVersion`. Nothing ran. The\n * app's report names the newest release it can reach (`latestReachable`).\n */\nexport class RuntimeTooOld extends CalimeroError {\n /** The runtime the release needs. */\n readonly minRuntimeVersion: string;\n /** Each node that falls short, and what it runs (`{ before }`: older than that). */\n readonly nodes: { node: number; runtime: string | { before: string } | null }[];\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RUNTIME_TOO_OLD', message, details);\n this.name = 'RuntimeTooOld';\n this.minRuntimeVersion = typeof details.minRuntimeVersion === 'string' ? details.minRuntimeVersion : '';\n this.nodes = Array.isArray(details.nodes) ? (details.nodes as RuntimeTooOld['nodes']) : [];\n }\n}\n\n/**\n * `409 CONSENT_STALE`: what a consent page showed (the app's bundle, the\n * target release, the release's measurements) changed before the person\n * approved. Nothing was approved; ask for a new consent request so they see\n * the new facts.\n */\nexport class ConsentStale extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'CONSENT_STALE', message, details);\n this.name = 'ConsentStale';\n }\n}\n\n/**\n * `403 ORIGIN_NOT_REGISTERED`: a sign-up or sign-in started on a web origin\n * the cluster does not know: neither the cluster's own nor one a package's\n * manager registered (`packageOrigins.add`). `origin` is the page's origin\n * and `package` the package it was expected to be registered for, when known.\n */\nexport class OriginNotRegistered extends CalimeroError {\n readonly origin: string;\n readonly package: string;\n /** What the node said, if anything. */\n readonly nodeMessage: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n const origin = typeof details.origin === 'string' ? details.origin : '';\n const pkg = typeof details.package === 'string' ? details.package : '';\n const site = origin ? `this site (${origin})` : 'this site';\n super(403, 'ORIGIN_NOT_REGISTERED', `${site} is not registered for ${pkg || 'any package'}${message ? ` (${message})` : ''}`, details);\n this.name = 'OriginNotRegistered';\n this.origin = origin;\n this.package = pkg;\n this.nodeMessage = message;\n }\n}\n\n/**\n * `400 BAD_ORIGIN` or `400 BAD_RP_ID`: the node does not accept the origin a\n * package's manager tried to register (it must be a bare web origin,\n * `scheme://host[:port]`), or the relying-party id given for it (which must\n * fit the origin's host). `code` says which. A served origin (`served: true`)\n * must also be `https://host` with no port, and not a name under the\n * cluster's apps domain or its rp-id.\n */\nexport class BadOrigin extends CalimeroError {\n constructor(code: 'BAD_ORIGIN' | 'BAD_RP_ID', message: string, details: Record<string, unknown> = {}) {\n super(400, code, message, details);\n this.name = 'BadOrigin';\n }\n}\n\n/**\n * `409 ORIGIN_TAKEN`: the origin is registered already (for another package,\n * or for this one with the other `served`: remove it first), or it is one of\n * the cluster's own (a node's API host, a cluster origin, a frontend it\n * serves).\n */\nexport class OriginTaken extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'ORIGIN_TAKEN', message, details);\n this.name = 'OriginTaken';\n }\n}\n\n/**\n * `400 NOT_SERVING`: a served origin (a custom domain, `served: true`) was\n * asked of a cluster that serves no frontends (merod without\n * `--apps-domain`). Register the origin unserved, or use a cluster that\n * serves them.\n */\nexport class NotServing extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(400, 'NOT_SERVING', message, details);\n this.name = 'NotServing';\n }\n}\n\n/**\n * `409 CLUSTER_NOT_UPGRADED`: the change needs every node of the cluster\n * (replicas, voters and learners) on the node's release or later, and one\n * is not yet; for instance adding a served origin. Retry once the cluster is\n * upgraded.\n */\nexport class ClusterNotUpgraded extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'CLUSTER_NOT_UPGRADED', message, details);\n this.name = 'ClusterNotUpgraded';\n }\n}\n\n/**\n * `409 FEATURE_NOT_ACTIVE`: the command (or a field of it) needs a cluster\n * version not every node of the cluster supports yet, during a rollout from\n * an older release; nothing was done. `feature` names it, `needs` is the core\n * release it needs and `active` the cluster's version now (`''` when not every\n * node said which it supports). It works once the old nodes leave the cluster:\n * retry then, or tell the user the feature is not available yet.\n */\nexport class FeatureNotActive extends CalimeroError {\n readonly feature: string;\n readonly needs: string;\n readonly active: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'FEATURE_NOT_ACTIVE', message, details);\n this.name = 'FeatureNotActive';\n this.feature = typeof details.feature === 'string' ? details.feature : '';\n this.needs = typeof details.needs === 'string' ? details.needs : '';\n this.active = typeof details.active === 'string' ? details.active : '';\n }\n}\n\n/**\n * `409 RECOVERY_NOT_READY`: a recovery (an account's or an organization's)\n * may finish only once its 72-hour delay has passed. `readyAt` is when it may\n * (Unix seconds), when the node said.\n */\nexport class RecoveryNotReady extends CalimeroError {\n readonly readyAt: number | undefined;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(409, 'RECOVERY_NOT_READY', message, details);\n this.name = 'RecoveryNotReady';\n this.readyAt = typeof details.readyAt === 'number' ? details.readyAt : undefined;\n }\n}\n\n/**\n * The recovery code is not one the cluster holds: mistyped, replaced by a\n * newer one, or spent by a recovery that started (whether it finished or was\n * cancelled). The node answers it `401`; a recovery is signed out, so it is\n * this error, not {@link LoginRequired}.\n */\nexport class WrongRecoveryCode extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(401, 'UNAUTHENTICATED', message || 'unknown or used recovery code', details);\n this.name = 'WrongRecoveryCode';\n }\n}\n\n/** Why a sign-up was refused ({@link SignUpRefused.reason}), read from what the node said. */\nexport type SignUpRefusal = 'invite-only' | 'closed' | 'unknown-invite' | 'expired-invite' | 'org-gone' | 'other';\n\n/**\n * `403 SIGN_UP_REFUSED`: the cluster's sign-up policy does not take this\n * sign-up (core `SystemState::admits`), answered by `register/begin` before a\n * passkey is made and by `register/finish` before its challenge is spent.\n * `reason` says why, so a page can say \"invite only\" or \"this invite has\n * expired\" instead of the node's sentence:\n *\n * - `invite-only`: the cluster takes new accounts with an invite only.\n * - `closed`: only a cluster sign-up invite (the operator's or the owner's) admits.\n * - `unknown-invite`: the invite is not one the cluster knows (mistyped, revoked,\n * or used up: a spent invite is gone).\n * - `expired-invite`: past its expiry, or no use left.\n * - `org-gone`: the organization the invite was for was deleted.\n */\nexport class SignUpRefused extends CalimeroError {\n readonly reason: SignUpRefusal;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(403, 'SIGN_UP_REFUSED', message, details);\n this.name = 'SignUpRefused';\n this.reason = signUpRefusal(message);\n }\n}\n\nfunction signUpRefusal(message: string): SignUpRefusal {\n if (/invite only/.test(message)) return 'invite-only';\n if (/pre-authorized|sign-up invite/.test(message)) return 'closed';\n if (/unknown invite/.test(message)) return 'unknown-invite';\n if (/invite has expired/.test(message)) return 'expired-invite';\n if (/organization is gone/.test(message)) return 'org-gone';\n return 'other';\n}\n\n/**\n * `429 QUOTA_EXCEEDED`: the caller holds as many of something (origins,\n * served origins per package or per cluster, blobs, ...) as it may.\n */\nexport class QuotaExceeded extends CalimeroError {\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(429, 'QUOTA_EXCEEDED', message, details);\n this.name = 'QuotaExceeded';\n }\n}\n\n/**\n * `422 APP_ERROR`: the app refused the call. `appCode` is the app's declared\n * error (`Taken`, `Forbidden`, ...) and `fields` its named fields. The call was\n * logged, so its idempotency key is spent.\n */\nexport class AppError extends CalimeroError {\n readonly appCode: string;\n readonly fields: Record<string, unknown>;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(422, 'APP_ERROR', message, details);\n this.name = 'AppError';\n const { appCode, fields } = appErrorOf(details);\n this.appCode = appCode;\n this.fields = fields;\n }\n}\n\n/** `422 TRAP`: the run trapped (`OutOfFuel`, `OutOfMemory`, ...). The call was logged. */\nexport class TrapError extends CalimeroError {\n readonly kind: string;\n\n constructor(message: string, details: Record<string, unknown> = {}) {\n super(422, 'TRAP', message, details);\n this.name = 'TrapError';\n this.kind = typeof details.kind === 'string' ? details.kind : '';\n }\n}\n\n/**\n * Whether a call the node answered 503 may have committed: `false` when the\n * node says it did not (`TIMEOUT`, `MIGRATING`), `\"unknown\"` otherwise (a call\n * that raced a leader change). Never a plain boolean: `\"unknown\"` must not read\n * as \"no\".\n */\nexport type Committed = false | 'unknown';\n\n/**\n * Any `503`, or a connection that failed, after the client's retries with the\n * same idempotency key ran out. `reason` is the node's code in lower case\n * (`timeout`, `migrating`, `unavailable`, ...), or `network` when the node gave\n * no answer at all (code `NETWORK`, `cause` the `fetch` failure); such a call\n * may have committed, so its `committed` is `'unknown'`.\n */\nexport class UnavailableError extends CalimeroError {\n readonly reason: string;\n readonly committed: Committed;\n /** Seconds the node asked to wait, when it said. */\n readonly retryAfter: number | undefined;\n /** What failed, when the node gave no answer. */\n readonly cause: unknown;\n\n constructor(code: string, message: string, details: Record<string, unknown> = {}, retryAfter?: number, cause?: unknown) {\n super(503, code, message, details);\n this.name = 'UnavailableError';\n this.reason = code.toLowerCase();\n this.committed = code === 'TIMEOUT' || code === 'MIGRATING' ? false : 'unknown';\n this.retryAfter = retryAfter;\n this.cause = cause;\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\n/**\n * The app's code and named fields. The node puts them in `details` as\n * `{ code, fields }`; an older node nests the app's error under `details.error`.\n * Positional payloads (`\"0\"`, `\"1\"`) are never read as fields (D63).\n */\nfunction appErrorOf(details: Record<string, unknown>): { appCode: string; fields: Record<string, unknown> } {\n const source = typeof details.code === 'string' ? details : record(details.error);\n const appCode = typeof source.code === 'string' ? source.code : '';\n return { appCode, fields: { ...record(source.fields) } };\n}\n\nfunction retryAfterOf(details: Record<string, unknown>, header?: string | null): number | undefined {\n for (const candidate of [details.retryAfter, header == null ? undefined : Number(header)]) {\n if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) return candidate;\n }\n return undefined;\n}\n\n/**\n * The error for a refusal the node answered with `status` and `body` (its JSON\n * `{ error, message, details }`, or whatever it sent). The one place statuses\n * become typed errors.\n */\nexport function errorFrom(status: number, body: unknown, retryAfterHeader?: string | null): CalimeroError {\n const value = record(body);\n const code = typeof value.error === 'string' ? value.error : 'ERROR';\n const message = typeof value.message === 'string' ? value.message : '';\n const details = record(value.details);\n if (status === 503) return new UnavailableError(code, message, details, retryAfterOf(details, retryAfterHeader));\n switch (`${status} ${code}`) {\n case '401 UNAUTHENTICATED':\n return new LoginRequired(message, details);\n case '401 PASSKEY_UNKNOWN_HERE':\n return new PasskeyUnknownHere(message, details);\n case '421 WRONG_NODE':\n return new WrongNode(message, details);\n case '404 NOT_FOUND':\n return new NotFound(message, details);\n case '409 IDEMPOTENCY_MISMATCH':\n return new IdempotencyMismatch(message, details);\n case '409 RELEASE_DEADLINE':\n return new ReleaseDeadlineError(message, details);\n case '409 RUNTIME_TOO_OLD':\n return new RuntimeTooOld(message, details);\n case '409 CONSENT_STALE':\n return new ConsentStale(message, details);\n case '403 ORIGIN_NOT_REGISTERED':\n return new OriginNotRegistered(message, details);\n case '400 BAD_ORIGIN':\n case '400 BAD_RP_ID':\n return new BadOrigin(code as 'BAD_ORIGIN' | 'BAD_RP_ID', message, details);\n case '409 ORIGIN_TAKEN':\n return new OriginTaken(message, details);\n case '400 NOT_SERVING':\n return new NotServing(message, details);\n case '409 CLUSTER_NOT_UPGRADED':\n return new ClusterNotUpgraded(message, details);\n case '409 FEATURE_NOT_ACTIVE':\n return new FeatureNotActive(message, details);\n case '429 QUOTA_EXCEEDED':\n return new QuotaExceeded(message, details);\n case '409 RECOVERY_NOT_READY':\n return new RecoveryNotReady(message, details);\n case '403 SIGN_UP_REFUSED':\n return new SignUpRefused(message, details);\n case '412 CONFIRM_REQUIRED':\n return new ConfirmRequired(message, details);\n case '413 ARGS_TOO_LARGE':\n return new ArgsTooLarge(message, details);\n case '422 APP_ERROR':\n return new AppError(message, details);\n case '422 TRAP':\n return new TrapError(message, details);\n default:\n return new CalimeroError(status, code, message, details);\n }\n}\n", "/**\n * Passkeys: the browser's WebAuthn API, or anything that answers like it.\n *\n * Every binary field crosses the wire as base64url, matching\n * `calimero-identity`'s `Registration` and `Assertion`.\n */\n\nimport type { components } from '../generated/api.js';\nimport { ConfirmCancelled, ConfirmPromptBlocked } from './errors.js';\n\nexport interface RegistrationJSON {\n attestationObject: string;\n clientDataJson: string;\n}\n\nexport interface AssertionJSON {\n credentialId: string;\n authenticatorData: string;\n clientDataJson: string;\n signature: string;\n}\n\n/** How strongly an assertion must verify the user (WebAuthn's `UserVerificationRequirement`). */\nexport type PasskeyUserVerification = \"required\" | \"preferred\" | \"discouraged\";\n\n/** What a confirmation asks of the passkey beyond the challenge. */\nexport interface PasskeyGetOptions {\n /**\n * `\"required\"` for a step-up confirmation (`412 CONFIRM_REQUIRED`): the\n * node accepts only an assertion with the user-verified flag (PIN or\n * biometric). `\"preferred\"` for the sign-up's confirmation, which the node\n * takes with the user present. Absent for a plain sign-in, where\n * `\"preferred\"` is enough.\n */\n userVerification?: PasskeyUserVerification;\n /**\n * Closes the open prompt when it aborts (a Cancel button, a page leaving).\n * The browser provider then rejects as a dismissed prompt does\n * (`NotAllowedError`), so the caller treats it as a cancel.\n */\n signal?: AbortSignal;\n}\n\n/** What a passkey creation takes beyond the node's options. */\nexport interface PasskeyCreateOptions {\n /** As {@link PasskeyGetOptions.signal}: aborting closes the prompt, rejecting as a cancel (`NotAllowedError`). */\n signal?: AbortSignal;\n}\n\n/** Something that holds a passkey. */\nexport interface PasskeyProvider {\n /**\n * Answer `navigator.credentials.create` for the node's options.\n * `createOptions.signal` closes the prompt when it aborts; a provider with\n * no prompt to close may ignore it.\n */\n create(options: Record<string, unknown>, createOptions?: PasskeyCreateOptions): Promise<RegistrationJSON>;\n /**\n * Sign `challenge` (an assertion), optionally limited to\n * `allowCredentials`. `options.userVerification` is `\"required\"` when the\n * client answers a step-up confirmation (`\"preferred\"` for the sign-up's);\n * a provider that always verifies the user may ignore it.\n * `options.signal` closes the prompt when it aborts.\n */\n get(\n challenge: Uint8Array,\n rpId: string,\n allowCredentials?: string[],\n options?: PasskeyGetOptions,\n ): Promise<AssertionJSON>;\n}\n\nexport function b64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport function fromB64url(s: string): Uint8Array {\n const pad =\n s.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"===\".slice((s.length + 3) % 4);\n const bin = atob(pad);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nconst buf = (b: Uint8Array): ArrayBuffer =>\n b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;\n\n/** A dismissed prompt, named as WebAuthn names one (`NotAllowedError`), so a confirmation reads it as declined. */\nfunction cancelled(message: string): Error {\n const error = new Error(message);\n error.name = \"NotAllowedError\";\n return error;\n}\n\n/**\n * Ask the browser's own WebAuthn API (`CredentialsContainer.prototype[method]`),\n * not whatever a password manager extension put on `navigator.credentials`.\n * Calimero's passkeys live in the platform's authenticators: iCloud Keychain\n * and Touch ID, Google Password Manager, Windows Hello, a phone over a QR code,\n * a security key. Extensions sit in between and broke sign-up: LastPass, after\n * creating a passkey, opened a hidden request of its own on the next prompt,\n * so the browser refused it (\"A request is already pending\") and every try\n * left a passkey with no account. A passkey kept only in an extension's vault\n * is therefore not offered here. Where the browser has no\n * `CredentialsContainer` (tests, older runtimes), `navigator.credentials` is used.\n */\ntype Ask = (\n options: CredentialCreationOptions | CredentialRequestOptions,\n) => Promise<Credential | null>;\n\nasync function ask(\n method: \"create\" | \"get\",\n options: CredentialCreationOptions | CredentialRequestOptions,\n signal: AbortSignal | undefined,\n what: string,\n): Promise<Credential | null> {\n const container = navigator.credentials;\n const own = (\n globalThis as unknown as {\n CredentialsContainer?: { prototype: Record<string, unknown> };\n }\n ).CredentialsContainer?.prototype?.[method] as Ask | undefined;\n const call = own ?? (container[method] as Ask);\n try {\n return await call.call(container, signal ? { ...options, signal } : options);\n } catch (error) {\n // An aborted `signal` rejects with its reason (an `AbortError` unless the\n // caller gave another): the prompt was closed on purpose, so it reads as\n // a dismissed one.\n if (signal?.aborted || (error as { name?: unknown } | null)?.name === \"AbortError\") {\n throw Object.assign(cancelled(`${what} was cancelled`), { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * The node's algorithms with ES256 alone when it is among them. Some password\n * managers make an Ed25519 (EdDSA, -8) passkey when the site offers it and\n * then fail to sign with it: the account's create succeeds and its very next\n * prompt fails. LastPass did this on Calimero's sign-up (create, then approve\n * at once), refusing the approval as \"A request is already pending\"; Proton\n * Pass answers UnsupportedAlgorithm. ES256 is what every authenticator makes,\n * and the node checks it as it checks EdDSA, so a passkey already made with\n * EdDSA still signs in.\n */\nexport function es256First(\n params: Array<{ type: \"public-key\"; alg: number }>,\n): Array<{ type: \"public-key\"; alg: number }> {\n const es256 = params.filter((p) => p.alg === -7);\n return es256.length ? es256 : params;\n}\n\n/** The platform authenticator (Touch ID, Face ID, Windows Hello, a security key, a synced passkey). */\nexport function browserPasskey(): PasskeyProvider {\n return {\n async create(options, createOptions) {\n const o = options as {\n challenge: string;\n rp: { id: string; name: string };\n user: { id: string; name: string; displayName: string };\n pubKeyCredParams: Array<{ type: \"public-key\"; alg: number }>;\n excludeCredentials?: Array<{ type: \"public-key\"; id: string }>;\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n timeout?: number;\n };\n const cred = (await ask(\"create\", {\n publicKey: {\n challenge: buf(fromB64url(o.challenge)),\n rp: o.rp,\n user: { ...o.user, id: buf(fromB64url(o.user.id)) },\n pubKeyCredParams: es256First(o.pubKeyCredParams),\n excludeCredentials: (o.excludeCredentials ?? []).map((c) => ({\n type: c.type,\n id: buf(fromB64url(c.id)),\n })),\n authenticatorSelection: o.authenticatorSelection,\n attestation: \"none\",\n timeout: o.timeout,\n },\n }, createOptions?.signal, \"passkey creation\")) as PublicKeyCredential | null;\n if (!cred) throw cancelled(\"passkey creation was cancelled\");\n const r = cred.response as AuthenticatorAttestationResponse;\n return {\n attestationObject: b64url(new Uint8Array(r.attestationObject)),\n clientDataJson: b64url(new Uint8Array(r.clientDataJSON)),\n };\n },\n async get(challenge, rpId, allowCredentials, options) {\n const cred = (await ask(\"get\", {\n publicKey: {\n challenge: buf(challenge),\n rpId,\n userVerification: options?.userVerification ?? \"preferred\",\n allowCredentials: (allowCredentials ?? []).map((id) => ({\n type: \"public-key\",\n id: buf(fromB64url(id)),\n })),\n },\n }, options?.signal, \"passkey sign-in\")) as PublicKeyCredential | null;\n if (!cred) throw cancelled(\"passkey sign-in was cancelled\");\n const r = cred.response as AuthenticatorAssertionResponse;\n return {\n credentialId: b64url(new Uint8Array(cred.rawId)),\n authenticatorData: b64url(new Uint8Array(r.authenticatorData)),\n clientDataJson: b64url(new Uint8Array(r.clientDataJSON)),\n signature: b64url(new Uint8Array(r.signature)),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------- the step-up\n/**\n * `details` of a `412 CONFIRM_REQUIRED`: the WebAuthn challenge to sign.\n * `userVerification` is read when a node names it (core does not today).\n */\nexport type ConfirmChallenge = components['schemas']['ConfirmRequired'] & { userVerification?: unknown };\n\n/** What a confirmation answers a `412` with: an assertion over the challenge. */\nexport type ConfirmCallback = (challenge: ConfirmChallenge, context: { request: Request }) => Promise<AssertionJSON>;\n\n/**\n * The user verification a confirmation asks the passkey for: what the node's\n * `412` details name, if it names one WebAuthn knows, else `fallback` (the\n * flow's own requirement: `required` for a step-up, which the node takes only\n * with the user verified; `preferred` for the sign-up confirmation, which it\n * takes with the user present).\n */\nexport function userVerificationOf(named: unknown, fallback: PasskeyUserVerification): PasskeyUserVerification {\n return named === 'required' || named === 'preferred' || named === 'discouraged' ? named : fallback;\n}\n\n/**\n * What a failed confirmation prompt means to the caller. The browser or a\n * password manager refusing to show the prompt (the page not focused because\n * an extension's popup still holds focus, or another prompt still open) is\n * {@link ConfirmPromptBlocked}; the user dismissing it (`NotAllowedError`, or\n * `AbortError` when it was aborted) is {@link ConfirmCancelled}; anything\n * else is a real failure, passed through.\n */\nexport function promptFailure(error: unknown): unknown {\n const e = error as { name?: unknown; message?: unknown } | null;\n const name = e?.name;\n const message = typeof e?.message === 'string' ? e.message : '';\n if (name === 'InvalidStateError' || /not focused|already pending/i.test(message)) {\n return new ConfirmPromptBlocked(error);\n }\n if (name === 'NotAllowedError' || name === 'AbortError') return new ConfirmCancelled(error);\n return error;\n}\n\n/** How {@link passkeyConfirm} prompts. */\nexport interface PasskeyConfirmOptions {\n /** The user verification asked for when the node names none. Default `required` (a step-up). */\n userVerification?: PasskeyUserVerification;\n /** Aborts the passkey prompt. */\n signal?: AbortSignal;\n}\n\n/**\n * `passkey`'s assertion over a `412` challenge: the {@link ConfirmCallback}\n * of a passkey. A prompt the user dismissed rejects with\n * {@link ConfirmCancelled}, one the browser would not show with\n * {@link ConfirmPromptBlocked}.\n */\nexport function passkeyConfirm(passkey: PasskeyProvider, options: PasskeyConfirmOptions = {}): ConfirmCallback {\n return async (challenge) => {\n try {\n // A step-up is taken only with the user verified (PIN or biometric);\n // `preferred` lets a password manager skip it, and the node then\n // refuses. Only the sign-up confirmation passes `preferred`. A\n // requirement the node names itself wins.\n return await passkey.get(fromB64url(challenge.challenge), challenge.rpId, challenge.allowCredentials, {\n userVerification: userVerificationOf(challenge.userVerification, options.userVerification ?? 'required'),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n } catch (declined) {\n throw promptFailure(declined);\n }\n };\n}\n", "/**\n * The runtime every route of a Calimero node is sent through: the part of\n * this client that is not a route.\n *\n * A route layer (the one generated from the node's OpenAPI document:\n * `createRouteClient` and `createRoutes` in `../api`, which {@link CalimeroClient}\n * exposes) knows a method, a path and what the route takes and answers.\n * Everything else is here, behind one call, {@link Transport.request}:\n *\n * - the sealed channel to each node, opened only after the node's attestation\n * passed the caller's policy (`../sealed`, `./attestation`);\n * - the credential (an API key or a session), and the session's refresh when a\n * node answers `401` to it;\n * - moving to another node of the cluster on `421 WRONG_NODE`, and failing\n * over when one stays unavailable to a call or a view (D70 retries);\n * - the `412 CONFIRM_REQUIRED` step-up: the passkey's assertion over the\n * node's challenge, sent with the same body again;\n * - error mapping (a refusal is a typed {@link CalimeroError}) and\n * server-sent event decoding.\n *\n * Paths are relative to the node (`apps/{app}/intents`, a leading `/` is\n * dropped); {@link routePath} fills a path template with encoded segments.\n */\n\nimport { SealedTransportError, createSealedFetch } from '../sealed/sealed.js';\nimport { fetchAttestedKey, type NodePolicy } from './attestation.js';\nimport { orderNodes, readDirectory } from './directory.js';\nimport {\n CalimeroError,\n ConfirmRequired,\n LoginRequired,\n UnavailableError,\n WrongNode,\n errorFrom,\n} from './errors.js';\nimport { b64url, type PasskeyProvider, type PasskeyUserVerification } from './passkey.js';\nimport { passkeyConfirm, type ConfirmChallenge } from './passkey.js';\nimport type { components } from '../generated/api.js';\n\n/** A signed-in session: what sign-up, sign-in and a refresh answer. */\nexport type CalimeroSession = components['schemas']['Session'];\n\n/** One server-sent event: `data` parsed as JSON when it is. */\nexport interface NodeEvent {\n id: string;\n kind: string;\n data: unknown;\n}\n\n/**\n * How a call or a view is sent again while the node is unavailable (D70): with\n * the same key, after a backoff that starts at `baseDelayMs` and doubles up to\n * `maxDelayMs`, no jitter, at most `retries` times. The defaults are the Rust\n * client's: 6 retries, 200 ms doubling, at most 2 s (about 9 s in all, past a\n * leader election).\n */\nexport interface RetryOptions {\n /** Retries after the first attempt. Default 6. */\n retries?: number;\n /** The first backoff; each retry doubles it. Default 200 ms. */\n baseDelayMs?: number;\n /** The longest backoff. Default 2 s. */\n maxDelayMs?: number;\n}\n\nexport const DEFAULT_RETRY = { retries: 6, baseDelayMs: 200, maxDelayMs: 2000 } as const;\n\n/** The backoff before retry `retry` (0 for the first): `baseDelayMs` doubling, at most `maxDelayMs`. */\nexport function retryDelayMs(retry: number, options: { baseDelayMs: number; maxDelayMs: number }): number {\n return Math.min(options.baseDelayMs * 2 ** retry, options.maxDelayMs);\n}\n\n/** The HTTP methods the node's routes use. */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/** A query parameter's value; `undefined` and `null` leave it out, an array repeats it. */\nexport type QueryValue = string | number | boolean | null | undefined;\n\n/** What a request carries beyond its method and path. */\nexport interface RequestOptions {\n /** Query parameters, appended to the path (encoded here). */\n query?: Record<string, QueryValue | QueryValue[]>;\n /** A JSON body. */\n body?: unknown;\n /** A raw body instead of JSON (a bundle, a package, a blob). */\n bytes?: Uint8Array;\n /** The raw body's content type. Default `application/wasm`. */\n contentType?: string;\n /**\n * Answers a `412 CONFIRM_REQUIRED`: the passkey asserts over the node's\n * challenge and the same JSON body is sent again with `confirm`. Without\n * one the `412` reaches the caller as {@link ConfirmRequired}.\n */\n passkey?: PasskeyProvider;\n /** The user verification the step-up asks for when the node names none. Default `required`. */\n userVerification?: PasskeyUserVerification;\n /**\n * D70 retries for a call or a view: `true` sends it again while the node\n * answers `503` or cannot be reached, then fails over to the next node;\n * `'once'` sends it exactly once (a confirmed attempt, whose challenge is\n * single-use). Only for a JSON body that carries its own idempotency key,\n * or a read.\n */\n retry?: boolean | 'once';\n /** Aborts the request (and a stream), and the step-up's passkey prompt. */\n signal?: AbortSignal;\n /** Aborts only the step-up's passkey prompt, not the requests around it. Default `signal`. */\n promptSignal?: AbortSignal;\n}\n\n/**\n * What a route layer calls. Every method sends through the attested, sealed\n * channel of the node in use, with the credential held now. A refusal (any\n * status other than 2xx) is thrown as a typed {@link CalimeroError}\n * ({@link errorFrom}); a transport failure as the error that caused it.\n */\nexport interface Transport {\n /** The response to `method path`, status 2xx; its body is not read. */\n request(method: HttpMethod, path: string, options?: RequestOptions): Promise<Response>;\n /** {@link request}'s JSON body (`{}` for an empty one). */\n json<T = Record<string, unknown>>(method: HttpMethod, path: string, options?: RequestOptions): Promise<T>;\n /** A server-sent event stream on `GET path`, until the stream ends or `signal` aborts. */\n events(path: string, options?: Pick<RequestOptions, 'query' | 'signal'>): AsyncGenerator<NodeEvent>;\n}\n\n/** How {@link NodeTransport} reaches a cluster's nodes. */\nexport interface NodeTransportOptions {\n /** One node of the cluster: the one the transport talks to first. */\n baseUrl: string;\n /** Other nodes of the same cluster, in the order to move to them. */\n nodes?: string[];\n /** What every node must attest to before anything is sent to it. */\n policy: NodePolicy;\n /** Fetch that carries attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n}\n\n/** Where a transport whose nodes came from the directory re-reads its node list. */\nexport interface DirectorySource {\n directory: string;\n cluster: string;\n zone: string | undefined;\n random: () => number;\n /** When the listing is due to be read again (ms since the epoch). */\n due: number;\n /** The re-read under way, if any. */\n reading?: Promise<void>;\n}\n\n/**\n * The node refuses an envelope past its 64 MiB sealed cap with `413` in the\n * clear, before opening it, so the refusal arrives as the transport's. To the\n * caller it is the API's `TOO_LARGE`, as the Rust client reports it.\n */\nfunction sealedError(error: unknown): unknown {\n if (error instanceof SealedTransportError && error.status === 413) {\n return errorFrom(413, {\n error: 'TOO_LARGE',\n message: error.message.replace(/^Sealed request refused: /, ''),\n });\n }\n return error;\n}\n\n/** Read a refused response's body and map it ({@link errorFrom}). */\nexport async function refusal(response: Response): Promise<CalimeroError> {\n const text = await response.text().catch(() => '');\n let body: unknown = {};\n try {\n body = text ? JSON.parse(text) : {};\n } catch {\n body = { message: text };\n }\n return errorFrom(response.status, body, response.headers.get('retry-after'));\n}\n\n/** Server-sent event frames from a response body: `{ id, kind, data }` each, `data` parsed as JSON when it is. */\nexport async function* sseFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<NodeEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n buffer += decoder.decode(value, { stream: true });\n let cut: number;\n while ((cut = buffer.indexOf('\\n\\n')) >= 0) {\n const frame = buffer.slice(0, cut);\n buffer = buffer.slice(cut + 2);\n let id = '';\n let kind = '';\n let data = '';\n for (const line of frame.split('\\n')) {\n if (line.startsWith('id:')) id = line.slice(3).trim();\n else if (line.startsWith('event:')) kind = line.slice(6).trim();\n else if (line.startsWith('data:')) data += line.slice(5).trim();\n }\n if (!kind && !data) continue;\n let parsed: unknown = data;\n try {\n parsed = JSON.parse(data);\n } catch {\n /* plain text */\n }\n yield { id, kind, data: parsed };\n }\n }\n}\n\n/**\n * A key for a call the caller gave none, made once so every retry shares it:\n * `node:c-` and 16 random bytes in base64url without padding, as the Rust\n * client mints it. It only has to outlive this client's own retries, so it\n * takes the node's short-lived class: a key starting `node:` is kept 10\n * minutes, a caller's own key 24 hours.\n * `getRandomValues`, not `randomUUID`, which a page outside a secure context lacks.\n */\nexport function newIdempotencyKey(): string {\n return `node:c-${b64url(crypto.getRandomValues(new Uint8Array(16)))}`;\n}\n\n/**\n * `template` (`apps/{app}/blobs/{id}`) with each `{name}` replaced by\n * `params[name]`, encoded as one path segment so an id cannot reach another\n * route. A name `params` lacks throws.\n */\nexport function routePath(template: string, params: Record<string, string | number> = {}): string {\n return template.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name];\n if (value === undefined) throw new Error(`no value for path parameter ${name} of ${template}`);\n return encodeURIComponent(String(value));\n });\n}\n\n/** `query` as a search string (`?a=1&b=2`), or `''` when it sets nothing. */\nexport function queryString(query: RequestOptions['query']): string {\n if (!query) return '';\n const search = new URLSearchParams();\n for (const [name, value] of Object.entries(query)) {\n for (const one of Array.isArray(value) ? value : [value]) {\n if (one !== undefined && one !== null) search.append(name, String(one));\n }\n }\n const text = search.toString();\n return text ? `?${text}` : '';\n}\n\n/**\n * The ceremonies that mint a session, which {@link NodeTransport} never\n * repeats by itself: a sign-in or sign-up is started again by its caller (with\n * the passkey), and a refresh moves through the nodes in\n * {@link NodeTransport.refresh}. A node answers them `421 WRONG_NODE` before\n * it spends the challenge or the refresh token (core #4774).\n */\nfunction ceremony(path: string): boolean {\n return path === 'auth/refresh' || path.startsWith('auth/passkey/') || RECOVERY_CEREMONIES.has(path);\n}\n\n/** The signed-out halves of an account recovery: a `401` there is the code's, not a session's. */\nconst RECOVERY_CEREMONIES = new Set(['auth/recovery/begin', 'auth/recovery/start', 'auth/recovery/finish']);\n\n/** The route path a request names: no leading `/`. */\nfunction relative(path: string): string {\n return path.replace(/^\\/+/, '');\n}\n\n/**\n * The {@link Transport} to one Calimero cluster: its nodes, each attested\n * under one policy before its first request, the credential, and the session's\n * refresh. {@link CalimeroClient} is built on one (`client.transport`); a\n * generated route layer takes one too.\n */\nexport class NodeTransport implements Transport {\n /** Every node this transport may use, `baseUrl` first (or as the directory last ordered them). */\n private nodeUrls: string[];\n /** The one in use: an index into {@link nodeUrls}. */\n private at = 0;\n /** A sealed fetch per node, each attesting its own node on first use. */\n private readonly channels = new Map<string, typeof fetch>();\n private readonly policy: NodePolicy;\n /** The unsealed fetch, for the one route served in the clear (`/attestation`). */\n readonly raw: typeof fetch;\n private auth: string | undefined;\n private current: CalimeroSession | undefined;\n /** The refresh under way, which every request that needs one shares. */\n private refreshing: Promise<CalimeroSession> | undefined;\n /** The backoff between retries, for a caller that retries a request the routes do not. */\n readonly retry: Required<RetryOptions>;\n /** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */\n private readonly networkFailures = new WeakSet<object>();\n /** The directory the node list came from, if it came from one. */\n private source: DirectorySource | undefined;\n\n constructor(options: NodeTransportOptions) {\n const trim = (url: string) => url.replace(/\\/+$/, '');\n this.nodeUrls = [...new Set([options.baseUrl, ...(options.nodes ?? [])].map(trim))];\n this.policy = options.policy;\n this.retry = { ...DEFAULT_RETRY, ...options.retry };\n const given = options.fetch ?? ((input, init) => fetch(input, init));\n // `fetch` rejects with a `TypeError` when it gets no answer: the connection\n // was refused, reset or dropped before the response. The sealed fetch passes\n // that rejection on unchanged, so it is recognised here, at its source, and\n // not by its type alone (a bad URL is a `TypeError` too, and is not retried).\n const raw: typeof fetch = async (input, init) => {\n try {\n return await given(input, init);\n } catch (error) {\n if (error instanceof TypeError) this.networkFailures.add(error);\n throw error;\n }\n };\n this.raw = raw;\n }\n\n /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */\n isNetworkFailure(error: unknown): boolean {\n return error instanceof TypeError && this.networkFailures.has(error);\n }\n\n /** Re-read the node list from `source` when it is due, and after a failover. */\n useDirectory(source: DirectorySource): void {\n this.source = source;\n }\n\n /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved on. */\n get nodeUrl(): string {\n return this.nodeUrls[this.at];\n }\n\n /** Every node this transport may use, in the order it moves through them. */\n get nodes(): string[] {\n return [...this.nodeUrls];\n }\n\n /** Authenticate every request with an API key. */\n useApiKey(key: string): void {\n this.auth = key;\n this.current = undefined;\n }\n\n /** Authenticate every request with `session`, refreshed when a node answers `401` to it. */\n useSession(session: CalimeroSession): void {\n this.auth = session.sessionToken;\n this.current = session;\n }\n\n /** Drop the credential: no request after this carries it. */\n signOut(): void {\n this.auth = undefined;\n this.current = undefined;\n }\n\n get session(): CalimeroSession | undefined {\n return this.current;\n }\n\n /** The sealed channel to `url`, attested under the policy before its first request. */\n private channel(url: string): typeof fetch {\n let sealed = this.channels.get(url);\n if (!sealed) {\n sealed = createSealedFetch({\n baseUrl: url,\n transportPublicKey: () => fetchAttestedKey(url, this.policy, this.raw),\n fetch: this.raw,\n });\n this.channels.set(url, sealed);\n }\n return sealed;\n }\n\n /**\n * Move on from node `from` (the one that answered `421 WRONG_NODE`) to the\n * next one. False when there is no other. A request that saw the same node\n * refuse after another request moved on already does not move again.\n */\n private moveOn(from: string): boolean {\n if (this.nodeUrls.length < 2) return false;\n if (this.nodeUrl === from) this.at = (this.at + 1) % this.nodeUrls.length;\n return true;\n }\n\n /**\n * Fail over from node `from`, where a request's retries ran out, to the next\n * node it has not `tried`. False when it has tried them all. A request whose\n * node another request moved away from already goes to that node, if untried.\n */\n private failOver(from: string, tried: Set<string>): boolean {\n if (this.nodeUrl !== from && !tried.has(this.nodeUrl)) return true;\n const count = this.nodeUrls.length;\n for (let step = 1; step < count; step++) {\n const next = (this.at + step) % count;\n if (!tried.has(this.nodeUrls[next])) {\n this.at = next;\n this.reread();\n return true;\n }\n }\n return false;\n }\n\n /**\n * Read the node list again from the directory, in the background: the node\n * in use stays first, then the directory's order; a node no longer listed is\n * dropped. A failed read is ignored. One read at a time.\n */\n private reread(): void {\n const source = this.source;\n if (!source || source.reading) return;\n source.reading = readDirectory(source.directory, source.cluster, this.raw)\n .then((listing) => {\n const current = this.nodeUrl;\n const listed = orderNodes(listing.nodes, source.zone, source.random);\n this.nodeUrls = [current, ...listed.filter((url) => url !== current)];\n this.at = 0;\n source.due = Date.now() + listing.refreshAfterSeconds * 1000;\n })\n .catch(() => undefined)\n .finally(() => {\n source.reading = undefined;\n });\n }\n\n /**\n * Send one request to the node in use, with the credential held now, and\n * answer the response, whatever its status. {@link send} judges it.\n */\n private async once(method: string, path: string, options: RequestOptions): Promise<Response> {\n const headers: Record<string, string> = {};\n if (this.auth) headers.authorization = `Bearer ${this.auth}`;\n let payload: BodyInit | undefined;\n if (options.bytes) {\n headers['content-type'] = options.contentType ?? 'application/wasm';\n payload = options.bytes as unknown as BodyInit;\n } else if (options.body !== undefined) {\n headers['content-type'] = 'application/json';\n payload = JSON.stringify(options.body);\n }\n if (this.source && Date.now() >= this.source.due) this.reread();\n const url = this.nodeUrl;\n try {\n return await this.channel(url)(`${url}/${path}${queryString(options.query)}`, {\n method,\n headers,\n body: payload,\n signal: options.signal,\n });\n } catch (error) {\n throw sealedError(error);\n }\n }\n\n /**\n * {@link once}, answering what a lost issuing node or a node on the wrong\n * release does to a session: a successful response, or the refusal as a\n * typed error ({@link errorFrom}).\n *\n * - `401 UNAUTHENTICATED` to a request that carried a session: the node that\n * signed the session may be gone, replaced, or out of reach of the node\n * asked, which any node of the cluster answers with a refresh. The\n * transport refreshes once, shared by every request that needs it at the\n * same time ({@link refresh}), and repeats the request once. A refresh that\n * is refused surfaces as {@link LoginRequired}.\n * - `421 WRONG_NODE`: this node's release may not serve the account. The\n * transport moves to the next node it knows and repeats the request once;\n * with none, the {@link WrongNode} reaches the caller.\n *\n * Repeating is safe even for a request that is not idempotent: the node\n * answers `401` and `421` when it judges the credential, before it reads what\n * the request asks, so the first attempt ran nothing. The exceptions are the\n * ceremonies that mint a session ({@link ceremony}), never repeated here.\n */\n private async send(method: string, path: string, options: RequestOptions): Promise<Response> {\n const response = await this.answer(method, path, options);\n if (!response.ok) throw await refusal(response);\n return response;\n }\n\n /**\n * {@link send}'s answer, a refusal included: the response after the\n * session's refresh and the move past a `421 WRONG_NODE`, whatever its\n * status. The generated route layer reads a refusal itself.\n */\n private async answer(method: string, path: string, options: RequestOptions): Promise<Response> {\n let refreshed = false;\n let moved = false;\n for (;;) {\n const [token, at] = [this.auth, this.nodeUrl];\n const response = await this.once(method, path, options);\n if (response.ok || (response.status !== 401 && response.status !== 421)) return response;\n const error = await refusal(response.clone());\n if (error instanceof WrongNode && !moved) {\n moved = true;\n if (this.moveOn(at) && !ceremony(path)) continue;\n } else if (error instanceof LoginRequired && !refreshed && this.mayRefresh(token, path)) {\n refreshed = true;\n await this.renew(token as string);\n continue;\n }\n return response;\n }\n }\n\n /** Whether a `401` to a request sent with `token` is one a refresh may answer. */\n private mayRefresh(token: string | undefined, path: string): boolean {\n return token !== undefined && this.current !== undefined && !ceremony(path);\n }\n\n /**\n * A fresh session in place of the one `token` belonged to: by the refresh\n * another request already made, or by one this request starts.\n */\n private async renew(token: string): Promise<void> {\n if (this.auth !== token) return;\n await this.refresh();\n }\n\n private async read<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n const response = await this.send(method, path, options);\n const text = await response.text();\n return (text ? JSON.parse(text) : {}) as T;\n }\n\n /**\n * {@link read} for a call or a view (D70): while the node answers 503 or\n * cannot be reached, the same request, with the same idempotency key, is sent\n * again after {@link retryDelayMs} (or the pause the node asked for, if\n * longer), at most `retries` times. Every other answer is final.\n *\n * When a node's retries run out, the request fails over to the next node the\n * transport knows and its retries start again there, with the same key: the\n * key is kept in the app's replicated log, so the cluster answers it once\n * whichever node it reaches. Each node is tried once per request. The last\n * failure surfaces as {@link UnavailableError}: the node's 503, or reason\n * `network` for a connection that failed, whose `committed` is `'unknown'`.\n *\n * `once` sends the request exactly once, to the node in use (a confirmed\n * attempt, whose challenge is single-use).\n */\n private async retried<T>(method: string, path: string, options: RequestOptions, once: boolean): Promise<T> {\n const response = await this.answerRetried(method, path, options, once);\n if (!response.ok) throw await refusal(response);\n const text = await response.text();\n return (text ? JSON.parse(text) : {}) as T;\n }\n\n /**\n * {@link retried}'s answer: the last response, a refusal included (a `503`\n * whose retries ran out on every node too). A connection that failed on the\n * last node rejects with {@link UnavailableError} (reason `network`).\n */\n private async answerRetried(method: string, path: string, options: RequestOptions, once: boolean): Promise<Response> {\n const retries = once ? 0 : this.retry.retries;\n const tried = new Set<string>();\n for (;;) {\n let unavailable: UnavailableError | undefined;\n let last: Response | undefined;\n let node = this.nodeUrl;\n for (let attempt = 0; ; attempt++) {\n node = this.nodeUrl;\n tried.add(node);\n try {\n const response = await this.answer(method, path, options);\n if (response.status !== 503) return response;\n last = response;\n unavailable = (await refusal(response.clone())) as UnavailableError;\n } catch (error) {\n if (error instanceof TypeError && this.networkFailures.has(error)) {\n last = undefined;\n unavailable = new UnavailableError('NETWORK', `the node could not be reached: ${error.message}`, {}, undefined, error);\n } else throw error;\n }\n if (attempt >= retries) break;\n const backoff = retryDelayMs(attempt, this.retry);\n await new Promise((resolve) => setTimeout(resolve, Math.max(backoff, (unavailable.retryAfter ?? 0) * 1000)));\n }\n if (once || !this.failOver(node, tried)) {\n if (last) return last;\n throw unavailable;\n }\n }\n }\n\n /**\n * One request to a route, answered whatever its status: the runtime's part\n * (sealing, the session and its refresh, `421 WRONG_NODE`, and with\n * `options.retry` the D70 retries and failover) and nothing of the route's.\n * A refusal is the node's response, for the caller to read; a connection\n * that failed rejects as `fetch` did (with `retry`, as\n * {@link UnavailableError} once the retries ran out). The generated route\n * layer (`createRouteClient`) sends through this.\n */\n exchange(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<Response> {\n const relativePath = relative(path);\n if (!options.retry) return this.answer(method, relativePath, options);\n return this.answerRetried(method, relativePath, options, options.retry === 'once');\n }\n\n /**\n * One JSON request, retried as `options.retry` says. The confirmed attempt\n * of a step-up (`body.confirm` set) goes out exactly once.\n */\n private attempt<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n if (!options.retry) return this.read<T>(method, path, options);\n const confirming = (options.body as { confirm?: unknown } | undefined)?.confirm !== undefined;\n return this.retried<T>(method, path, options, options.retry === 'once' || confirming);\n }\n\n /**\n * {@link attempt}, answering a `412 CONFIRM_REQUIRED` with `passkey`'s\n * assertion over the node's challenge: the same body again, with `confirm`.\n * Without a passkey the `412` reaches the caller as {@link ConfirmRequired}.\n */\n private async confirmed<T>(method: string, path: string, options: RequestOptions): Promise<T> {\n const { passkey } = options;\n try {\n return await this.attempt<T>(method, path, options);\n } catch (error) {\n if (!(error instanceof ConfirmRequired) || !passkey) throw error;\n const challenge = error.details as ConfirmChallenge;\n const assertion = await passkeyConfirm(passkey, {\n userVerification: options.userVerification,\n signal: options.promptSignal ?? options.signal,\n })(challenge, { request: new Request(`${this.nodeUrl}/${path}`, { method }) });\n const body = { ...(options.body as Record<string, unknown>), confirm: { challengeId: challenge.challengeId, assertion } };\n return this.attempt<T>(method, path, { ...options, body });\n }\n }\n\n request(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<Response> {\n return this.send(method, relative(path), options);\n }\n\n json<T = Record<string, unknown>>(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<T> {\n return this.confirmed<T>(method, relative(path), options);\n }\n\n async *events(path: string, options: Pick<RequestOptions, 'query' | 'signal'> = {}): AsyncGenerator<NodeEvent> {\n const response = await this.send('GET', relative(path), options);\n if (!response.body) throw new CalimeroError(response.status, 'EVENTS', 'the event stream has no body');\n yield* sseFrames(response.body);\n }\n\n /**\n * `GET path` in the clear, from the node in use: only for the route a node\n * serves unsealed (`attestation`), and never with the credential.\n */\n async unsealed(path: string, options: Pick<RequestOptions, 'query'> = {}): Promise<Response> {\n const response = await this.inTheClear(path, options);\n if (!response.ok) throw await refusal(response);\n return response;\n }\n\n /**\n * {@link unsealed}'s answer, a refusal included: `GET path` in the clear,\n * without the credential, for the routes a node serves unsealed\n * (`attestation`, `health`).\n */\n inTheClear(path: string, options: Pick<RequestOptions, 'query' | 'signal'> = {}): Promise<Response> {\n return this.raw(`${this.nodeUrl}/${relative(path)}${queryString(options.query)}`, { signal: options.signal });\n }\n\n /**\n * Swap the refresh token for a new session, on whichever node the transport\n * uses: any node of the cluster takes it. A refresh token is used once, so\n * requests made while one refresh is under way share it rather than sending\n * the same token again (which would revoke the session).\n */\n refresh(): Promise<CalimeroSession> {\n if (!this.refreshing) {\n const pending = this.exchangeRefresh();\n this.refreshing = pending;\n const clear = () => {\n if (this.refreshing === pending) this.refreshing = undefined;\n };\n pending.then(clear, clear);\n }\n return this.refreshing;\n }\n\n private async exchangeRefresh(): Promise<CalimeroSession> {\n const current = this.current;\n if (!current) throw new Error('no session to refresh');\n let session: CalimeroSession | undefined;\n // A node that may not serve the account answers `421 WRONG_NODE` before it\n // spends the refresh token (core #4774), so the same token goes to the next\n // node (`send` moved there already): once per node, at most.\n for (let tried = 1; session === undefined; tried++) {\n try {\n session = await this.json<CalimeroSession>('POST', 'auth/refresh', { body: { refreshToken: current.refreshToken } });\n } catch (error) {\n if (!(error instanceof WrongNode) || tried >= this.nodeUrls.length) throw error;\n }\n }\n // A sign-in or another session taken while this one was refreshing wins.\n if (this.current === current) this.useSession(session);\n return session;\n }\n}\n\n/**\n * A {@link NodeTransport} to the cluster named `cluster`, its node list read\n * from the node directory (`directory`), those in `zone` first, each group in\n * weighted-random order, and read again in the background after a failover\n * and once the listing's `refreshAfterSeconds` passed.\n */\nexport async function directoryTransport(options: {\n cluster: string;\n policy: NodePolicy;\n directory: string;\n zone?: string;\n fetch?: typeof fetch;\n retry?: RetryOptions;\n random?: () => number;\n}): Promise<NodeTransport> {\n const random = options.random ?? Math.random;\n const fetcher = options.fetch ?? ((input, init) => fetch(input, init));\n const listing = await readDirectory(options.directory, options.cluster, fetcher);\n const [baseUrl, ...nodes] = orderNodes(listing.nodes, options.zone, random);\n const transport = new NodeTransport({ baseUrl, nodes, policy: options.policy, fetch: options.fetch, retry: options.retry });\n transport.useDirectory({\n directory: options.directory,\n cluster: options.cluster,\n zone: options.zone,\n random,\n due: Date.now() + listing.refreshAfterSeconds * 1000,\n });\n return transport;\n}\n", "// settings & const\nconst PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nconst supportsRequestInitExt = () => {\n return (\n typeof process === \"object\" &&\n Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&\n process.versions.undici\n );\n};\n\n/**\n * Returns a cheap, non-cryptographically-secure random ID\n * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)\n */\nexport function randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\n\n/**\n * Create an openapi-fetch client.\n * @type {import(\"./index.js\").default}\n */\nexport default function createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = undefined,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n\n /**\n * Per-request fetch (keeps settings created in createClient()\n * @param {T} url\n * @param {import('./index.js').FetchOptions<T>} fetchOptions\n */\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n\n let querySerializer =\n typeof globalQuerySerializer === \"function\"\n ? globalQuerySerializer\n : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer =\n typeof requestQuerySerializer === \"function\"\n ? requestQuerySerializer\n : createQuerySerializer({\n ...(typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {}),\n ...requestQuerySerializer,\n });\n }\n\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n\n const serializedBody =\n body === undefined\n ? undefined\n : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header),\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === undefined ||\n // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData\n ? {}\n : {\n \"Content-Type\": \"application/json\",\n },\n baseHeaders,\n headers,\n params.header,\n );\n\n // Client level middleware take priority over request-level middleware\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders,\n };\n\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit,\n );\n let response;\n\n /** Add custom parameters to Request object */\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n\n if (finalMiddlewares.length) {\n id = randomID();\n\n // middleware (request)\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer,\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n\n if (!response) {\n // fetch!\n try {\n response = await fetch(request, requestInitExt);\n } catch (error) {\n let errorAfterMiddleware = error;\n // middleware (error)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n // if error is handled by returning a response, skip remaining middleware\n if (result instanceof Response) {\n errorAfterMiddleware = undefined;\n response = result;\n break;\n }\n\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n\n // rethrow error if not handled by middleware\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n\n // middleware (response)\n // execute in reverse-array order (first priority gets last transform)\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id,\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n\n const contentLength = response.headers.get(\"Content-Length\");\n // handle empty content\n if (\n response.status === 204 ||\n request.method === \"HEAD\" ||\n (contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\"))\n ) {\n return response.ok ? { data: undefined, response } : { error: undefined, response };\n }\n\n // parse response (falling back to .text() when necessary)\n if (response.ok) {\n const getResponseData = async () => {\n // if \"stream\", skip parsing entirely\n if (parseAs === \"stream\") {\n return response.body;\n }\n\n if (parseAs === \"json\" && !contentLength) {\n // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)\n const raw = await response.text();\n return raw ? JSON.parse(raw) : undefined;\n }\n\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n\n // handle errors\n let error = await response.text();\n try {\n error = JSON.parse(error); // attempt to parse as JSON\n } catch {\n // noop\n }\n return { error, response };\n }\n\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n },\n };\n}\n\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\n\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\n\n/**\n * Wrap openapi-fetch client to support a path based API.\n * @type {import(\"./index.js\").wrapAsPathBasedClient}\n */\nexport function wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n\n // Put the proxy on the prototype chain of the actual client.\n // This means if we do not have a memoized PathCallForwarder,\n // we fall back to the proxy to synthesize it.\n // However, the proxy itself is not on the hot-path (if we fetch the same\n // endpoint multiple times, only the first call will hit the proxy).\n function Client() {}\n Client.prototype = proxy;\n\n const client = new Client();\n\n // Feed the client back to the proxy handler so it can store the generated\n // PathCallForwarder.\n handler.client = client;\n\n return client;\n}\n\n/**\n * Convenience method to an openapi-fetch path based client.\n * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.\n * @type {import(\"./index.js\").createPathBasedClient}\n */\nexport function createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\n\n// utils\n\n/**\n * Serialize primitive param values\n * @type {import(\"./index.js\").serializePrimitiveParam}\n */\nexport function serializePrimitiveParam(name, value, options) {\n if (value === undefined || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.\",\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\n\n/**\n * Serialize object param (shallow only)\n * @type {import(\"./index.js\").serializeObjectParam}\n */\nexport function serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner =\n {\n simple: \",\",\n label: \".\",\n matrix: \";\",\n }[options.style] || \"&\";\n\n // explode: false\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final = values.join(\",\"); // note: values are always joined by comma in explode: false (but joiner can prefix)\n switch (options.style) {\n case \"form\": {\n return `${name}=${final}`;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n default: {\n return final;\n }\n }\n }\n\n // explode: true\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\n\n/**\n * Serialize array param (shallow only)\n * @type {import(\"./index.js\").serializeArrayParam}\n */\nexport function serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n\n // explode: false\n if (options.explode === false) {\n const joiner = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\"; // note: for arrays, joiners vary wildly based on style + explode behavior\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n\n // explode: true\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\"\n ? `${joiner}${values.join(joiner)}`\n : values.join(joiner);\n}\n\n/**\n * Serialize query params to string\n * @type {import(\"./index.js\").createQuerySerializer}\n */\nexport function createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false,\n }),\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\n\n/**\n * Handle different OpenAPI 3.x serialization styles\n * @type {import(\"./index.js\").defaultPathSerializer}\n * @see https://swagger.io/docs/specification/serialization/#path\n */\nexport function defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\n\n/**\n * Serialize body object to string\n * @type {import(\"./index.js\").defaultBodySerializer}\n */\nexport function defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType =\n headers.get instanceof Function\n ? (headers.get(\"Content-Type\") ?? headers.get(\"content-type\"))\n : (headers[\"Content-Type\"] ?? headers[\"content-type\"]);\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\n\n/**\n * Construct URL string from baseUrl and handle path and query params\n * @type {import(\"./index.js\").createFinalURL}\n */\nexport function createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\n\n/**\n * Merge headers a and b, with b taking priority\n * @type {import(\"./index.js\").mergeHeaders}\n */\nexport function mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== undefined) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\n\n/**\n * Remove trailing slash from url\n * @type {import(\"./index.js\").removeTrailingSlash}\n */\nexport function removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n", "/**\n * The answers to the two challenges a node puts before a request it will only\n * take with a proof: the `412 CONFIRM_REQUIRED` passkey step-up and the\n * `428 OPERATOR_SIGNATURE_REQUIRED` operator signature (core\n * `crates/node/src/api/openapi.rs`, components `ConfirmRequired`, `Confirm`,\n * `OperatorSignatureRequired`, `OperatorProof`).\n *\n * Each is an `openapi-fetch` middleware: it keeps a copy of the request it\n * sees go out, and when the node answers the challenge it asks a callback the\n * caller supplied for the proof, then sends the same JSON body again with the\n * proof beside it (`confirm`, `operatorProof`) and answers that response in\n * place of the challenge. Without a callback (or when the callback is not\n * given for that request) the challenge reaches the caller as the\n * `{ error }` of the response.\n */\n\nimport type { Middleware } from 'openapi-fetch';\n\nimport type { components } from '../generated/api.js';\nimport type { ConfirmCallback, ConfirmChallenge } from '../runtime/passkey.js';\n\n/** `details` of a `428 OPERATOR_SIGNATURE_REQUIRED`: the statement and its exact bytes (`message`, base64). */\nexport type OperatorStatement = components['schemas']['OperatorSignatureRequired'];\n\n/** The operator key's proof the retry carries: its Ed25519 signature (hex) over `message`, with the statement's nonce. */\nexport type OperatorProof = components['schemas']['OperatorProof'];\n\n/** What a `428` is answered with: the operator key's signature over the statement. */\nexport type OperatorProofCallback = (statement: OperatorStatement, context: { request: Request }) => Promise<OperatorProof>;\n\n/**\n * A middleware that answers a `status code` refusal: `answer` turns its\n * `details` into the fields to add to the JSON body, and the request goes out\n * again once with them.\n */\nfunction challengeAnswer<D>(\n status: number,\n code: string,\n answer: (details: D, request: Request) => Promise<Record<string, unknown>>,\n): Middleware {\n const sent = new Map<string, Request>();\n return {\n onRequest({ request, id }) {\n // Kept before the body is read: the retry is the same request. Only a\n // JSON body (or none) can carry the proof, so an upload is never copied.\n const type = request.headers.get('content-type');\n const json = type === null || type.startsWith('application/json');\n if (json && request.method !== 'GET' && request.method !== 'HEAD') sent.set(id, request.clone());\n return undefined;\n },\n async onResponse({ response, id, options }) {\n const original = sent.get(id);\n sent.delete(id);\n if (response.status !== status || !original) return undefined;\n const refusal = (await response\n .clone()\n .json()\n .catch(() => undefined)) as { error?: unknown; details?: unknown } | undefined;\n if (refusal?.error !== code) return undefined;\n const fields = await answer((refusal.details ?? {}) as D, original);\n const text = await original.text();\n const body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n const headers = new Headers(original.headers);\n headers.set('content-type', 'application/json');\n const again = new Request(original.url, {\n method: original.method,\n headers,\n body: JSON.stringify({ ...body, ...fields }),\n signal: original.signal,\n });\n return options.fetch(again);\n },\n onError({ id }) {\n sent.delete(id);\n return undefined;\n },\n };\n}\n\n/**\n * The `412 CONFIRM_REQUIRED` step-up: `confirm` signs the node's challenge and\n * the same body goes again with `confirm: { challengeId, assertion }`. Add it\n * to a client (`api.use(stepUp(...))`) or to one request (`{ middleware:\n * [stepUp(passkeyConfirm(passkey))] }`).\n */\nexport function stepUp(confirm: ConfirmCallback): Middleware {\n return challengeAnswer<ConfirmChallenge>(412, 'CONFIRM_REQUIRED', async (challenge, request) => ({\n confirm: { challengeId: challenge.challengeId, assertion: await confirm(challenge, { request }) },\n }));\n}\n\n/**\n * The `428 OPERATOR_SIGNATURE_REQUIRED` operator signature: `sign` signs the\n * statement's `message` with the operator key and the same body goes again\n * with `operatorProof: { nonce, signature }`.\n */\nexport function operatorSignature(sign: OperatorProofCallback): Middleware {\n return challengeAnswer<OperatorStatement>(428, 'OPERATOR_SIGNATURE_REQUIRED', async (statement, request) => ({\n operatorProof: await sign(statement, { request }),\n }));\n}\n", "/**\n * What every generated method (`src/generated/methods.ts`, by\n * `scripts/gen-methods.mjs`) runs: one flattened argument object split back\n * into the route's path parameters, query and body, sent through the\n * generated `openapi-fetch` client, and its answer unwrapped (a refusal thrown\n * as the typed `CalimeroError`). The route types themselves all come from the\n * generated `operations`; nothing here names a route.\n */\n\nimport type { Middleware } from 'openapi-fetch';\n\nimport type { RouteClient } from './route-client.js';\nimport { unwrap } from './route-client.js';\nimport { operatorSignature, stepUp, type OperatorProofCallback } from './step-up.js';\nimport { type ConfirmCallback } from '../runtime/passkey.js';\n\n/** What a generated method takes beside its arguments. */\nexport interface MethodOptions {\n /**\n * Answers this request's `412 CONFIRM_REQUIRED` (say,\n * `passkeyConfirm(passkey)`), before the client's own `confirm`.\n */\n confirm?: ConfirmCallback;\n /** Answers this request's `428 OPERATOR_SIGNATURE_REQUIRED`, before the client's own `operatorProof`. */\n operatorProof?: OperatorProofCallback;\n /** Aborts the request (and a step-up's prompt, when `confirm` reads it). */\n signal?: AbortSignal;\n}\n\n/** A raw request body: the bytes as they are, sent with `contentType`. */\nexport interface RawBody {\n body: Uint8Array | ArrayBuffer | Blob | string;\n /** The body's media type. Default: the one the route documents. */\n contentType?: string;\n}\n\n/** How a generated method's arguments map onto its route (written by the generator). */\nexport interface RouteShape {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n path: string;\n /** Names of the path parameters. */\n pathParams: readonly string[];\n /** Names of the query parameters. */\n query: readonly string[];\n /** The query is `args.query` (a query parameter is named like a path parameter). */\n queryWhole?: boolean;\n /**\n * `fields`: the arguments other than the path and query are the JSON body;\n * `whole`: the JSON body is `args.body`; `raw`: `args.body` is sent as it is,\n * with `args.contentType` (or `media`); `none`: no body.\n */\n body: 'fields' | 'whole' | 'raw' | 'none';\n /** Whether the route takes no body at all as well (`fields`: an empty one is left out). */\n optionalBody: boolean;\n /** The raw body's documented media type. */\n media?: string;\n /** How the answer is read. */\n reply: 'json' | 'bytes' | 'text';\n /** The route answers `412 CONFIRM_REQUIRED` first (`x-calimero-step-up`). */\n stepUp?: boolean;\n /** The user verification its step-up asks the passkey for (`x-calimero-user-verification`). */\n userVerification?: 'required' | 'preferred' | 'discouraged';\n /** The route answers `428 OPERATOR_SIGNATURE_REQUIRED` first (`x-calimero-operator`). */\n operator?: boolean;\n}\n\n/** Send one generated route: split `args`, send it, answer its payload or throw its refusal. */\nexport async function route(\n api: RouteClient,\n shape: RouteShape,\n args: Record<string, unknown> | undefined,\n options: MethodOptions = {},\n): Promise<unknown> {\n const given = args ?? {};\n const path: Record<string, unknown> = {};\n const query: Record<string, unknown> = {};\n const rest: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(given)) {\n if (shape.pathParams.includes(name)) path[name] = value;\n else if (shape.queryWhole && name === 'query') Object.assign(query, value);\n else if (!shape.queryWhole && shape.query.includes(name)) query[name] = value;\n else rest[name] = value;\n }\n for (const name of shape.pathParams) {\n if (path[name] === undefined) throw new TypeError(`${shape.method} ${shape.path}: no value for ${name}`);\n }\n const init: Record<string, unknown> = { params: { path, query } };\n if (shape.body === 'fields') {\n const empty = Object.values(rest).every((value) => value === undefined);\n if (!(empty && shape.optionalBody)) init.body = rest;\n } else if (shape.body === 'whole') {\n if (rest.body !== undefined || !shape.optionalBody) init.body = rest.body;\n } else if (shape.body === 'raw') {\n init.body = rest.body;\n init.bodySerializer = (body: unknown) => body;\n init.headers = { 'Content-Type': (rest.contentType as string | undefined) ?? shape.media ?? 'application/octet-stream' };\n }\n if (shape.reply === 'bytes') init.parseAs = 'blob';\n else if (shape.reply === 'text') init.parseAs = 'text';\n const middleware: Middleware[] = [];\n if (options.confirm) {\n const confirm = options.confirm;\n // The route's own user verification, where the node's challenge names none\n // (a sign-up's confirmation takes `preferred`, every other step-up `required`).\n const answer: ConfirmCallback = shape.userVerification\n ? (challenge, context) => confirm({ userVerification: shape.userVerification, ...challenge }, context)\n : confirm;\n middleware.push(stepUp(answer));\n }\n if (options.operatorProof) middleware.push(operatorSignature(options.operatorProof));\n if (middleware.length) init.middleware = middleware;\n if (options.signal) init.signal = options.signal;\n // The shape was written from the same document as `api`'s types; the\n // generated method's own signature carries them.\n const send = api.request as unknown as (method: string, path: string, init: unknown) => ReturnType<RouteClient['GET']>;\n return unwrap(send(shape.method.toLowerCase(), shape.path, init));\n}\n", "// Generated by scripts/gen-methods.mjs from openapi/core-openapi.json (`pnpm gen:api`). Do not edit.\n//\n// One method per operation of the node's API, grouped by the operation's tag.\n// Each takes one argument object (path parameters, query and body fields\n// merged; the body under `body` when it is raw bytes or its fields would\n// collide) and answers the route's success payload; a refusal is thrown as the\n// typed `CalimeroError`. Event streams are not here: read them with\n// `transport.events`.\n// Streams left out: GET /apps/{app}/events, GET /apps/{app}/presence/stream.\n\nimport type { operations } from './api.js';\nimport type { RouteClient } from '../routes/route-client.js';\nimport { route, type MethodOptions, type RawBody } from '../routes/method.js';\n\n/** The generated methods, by group, sending through `api`. */\nexport function createRoutes(api: RouteClient) {\n return {\n apps: {\n /**\n * An app's ABI.\n *\n * `GET /apps/{app}/abi` (`app_abi`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n abi: (args: operations['app_abi']['parameters']['path'], options?: MethodOptions): Promise<operations['app_abi']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/abi\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_abi']['responses'][200]['content']['application/json']>,\n /**\n * Set who may reach an app.\n *\n * `POST /apps/{app}/access` (`app_access`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n access: (args: operations['app_access']['parameters']['path'] & operations['app_access']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_access']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/access\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_access']['responses'][200]['content']['application/json']>,\n /**\n * Every replica's receipt-key attestation.\n *\n * `GET /apps/{app}/attestation` (`app_attestation`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n attestation: (args: operations['app_attestation']['parameters']['path'] & NonNullable<operations['app_attestation']['parameters']['query']>, options?: MethodOptions): Promise<operations['app_attestation']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/attestation\",\"pathParams\":[\"app\"],\"query\":[\"nonce\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_attestation']['responses'][200]['content']['application/json']>,\n /**\n * Forget a blob.\n *\n * `DELETE /apps/{app}/blobs/{id}` (`blob_delete`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobDelete: (args: operations['blob_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}/blobs/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_delete']['responses'][200]['content']['application/json']>,\n /**\n * Download a blob.\n *\n * `GET /apps/{app}/blobs/{id}` (`blob_download`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobDownload: (args: operations['blob_download']['parameters']['path'] & NonNullable<operations['blob_download']['parameters']['query']>, options?: MethodOptions): Promise<Blob> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[\"grant\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"bytes\"}, args as unknown as Record<string, unknown>, options) as Promise<Blob>,\n /**\n * A blob's size.\n *\n * `GET /apps/{app}/blobs/{id}/info` (`blob_info`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobInfo: (args: operations['blob_info']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_info']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs/{id}/info\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_info']['responses'][200]['content']['application/json']>,\n /**\n * List an app's blobs.\n *\n * `GET /apps/{app}/blobs` (`blob_list`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobList: (args: operations['blob_list']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/blobs\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_list']['responses'][200]['content']['application/json']>,\n /**\n * Invalidate a blob's grants.\n *\n * `POST /apps/{app}/blobs/{id}/revoke` (`blob_revoke`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobRevoke: (args: operations['blob_revoke']['parameters']['path'], options?: MethodOptions): Promise<operations['blob_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/blobs/{id}/revoke\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Upload a blob.\n *\n * `POST /apps/{app}/blobs` (`blob_upload`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n blobUpload: (args: operations['blob_upload']['parameters']['path'] & NonNullable<operations['blob_upload']['parameters']['query']> & RawBody, options?: MethodOptions): Promise<operations['blob_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/blobs\",\"pathParams\":[\"app\"],\"query\":[\"sealed\"],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['blob_upload']['responses'][200]['content']['application/json']>,\n /**\n * Call a method.\n *\n * `POST /apps/{app}/intents` (`intents`). **Who:** whoever the app's access admits (a public app: anyone).\n * Answers `412 CONFIRM_REQUIRED` first when the method is a `confirm` method of the app's ABI: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Retried on `503` (D70), with its `idempotencyKey` (one is made when none is given).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n call: (args: operations['intents']['parameters']['path'] & operations['intents']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['intents']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/intents\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['intents']['responses'][200]['content']['application/json']>,\n /**\n * Create an app instance.\n *\n * `POST /apps` (`app_create`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['app_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['app_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete an app.\n *\n * `DELETE /apps/{app}` (`app_delete`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['app_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['app_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_delete']['responses'][200]['content']['application/json']>,\n /**\n * One sealed file.\n *\n * `GET /apps/{app}/files/{id}` (`file_info`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n fileInfo: (args: operations['file_info']['parameters']['path'], options?: MethodOptions): Promise<operations['file_info']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files/{id}\",\"pathParams\":[\"app\",\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['file_info']['responses'][200]['content']['application/json']>,\n /**\n * List an app's sealed files.\n *\n * `GET /apps/{app}/files` (`files_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n filesList: (args: operations['files_list']['parameters']['path'], options?: MethodOptions): Promise<operations['files_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['files_list']['responses'][200]['content']['application/json']>,\n /**\n * Upload a sealed file.\n *\n * `POST /apps/{app}/files` (`files_upload`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n filesUpload: (args: operations['files_upload']['parameters']['path'] & RawBody, options?: MethodOptions): Promise<operations['files_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['files_upload']['responses'][200]['content']['application/json']>,\n /**\n * One app.\n *\n * `GET /apps/{app}` (`app_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['app_get']['parameters']['path'], options?: MethodOptions): Promise<operations['app_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_get']['responses'][200]['content']['application/json']>,\n /**\n * Apps the caller reaches.\n *\n * `GET /apps` (`app_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: NonNullable<operations['app_list']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['app_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps\",\"pathParams\":[],\"query\":[\"package\",\"bundle\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_list']['responses'][200]['content']['application/json']>,\n /**\n * Set an app's metadata.\n *\n * `POST /apps/{app}/metadata` (`app_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n metadata: (args: operations['app_metadata']['parameters']['path'] & operations['app_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/metadata\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Call a method by its path.\n *\n * `POST /apps/{app}/methods/{method}` (`app_method`). **Who:** whoever the app's access admits (a public app: anyone).\n * Answers `412 CONFIRM_REQUIRED` first when the method is a `confirm` method of the app's ABI: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Retried on `503` (D70), with its `idempotencyKey` (one is made when none is given).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n method: (args: operations['app_method']['parameters']['path'] & operations['app_method']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_method']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/methods/{method}\",\"pathParams\":[\"app\",\"method\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_method']['responses'][200]['content']['application/json']>,\n /**\n * Move an app to another organization.\n *\n * `POST /apps/{app}/move` (`app_move`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n move: (args: operations['app_move']['parameters']['path'] & operations['app_move']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_move']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/move\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_move']['responses'][200]['content']['application/json']>,\n /**\n * An app's OpenAPI document.\n *\n * `GET /apps/{app}/openapi.json` (`app_openapi`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n openapi: (args: operations['app_openapi']['parameters']['path'], options?: MethodOptions): Promise<operations['app_openapi']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/openapi.json\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_openapi']['responses'][200]['content']['application/json']>,\n /**\n * Who is present.\n *\n * `GET /apps/{app}/presence` (`presence_get`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n presenceGet: (args: operations['presence_get']['parameters']['path'], options?: MethodOptions): Promise<operations['presence_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/presence\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['presence_get']['responses'][200]['content']['application/json']>,\n /**\n * Publish presence.\n *\n * `POST /apps/{app}/presence` (`presence_publish`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n presencePublish: (args: operations['presence_publish']['parameters']['path'] & operations['presence_publish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['presence_publish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/presence\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['presence_publish']['responses'][200]['content']['application/json']>,\n /**\n * One compute run.\n *\n * `GET /apps/{app}/runs/{run}` (`app_run`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n run: (args: operations['app_run']['parameters']['path'], options?: MethodOptions): Promise<operations['app_run']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/runs/{run}\",\"pathParams\":[\"app\",\"run\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_run']['responses'][200]['content']['application/json']>,\n /**\n * An app's compute runs.\n *\n * `GET /apps/{app}/runs` (`app_runs`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n runs: (args: operations['app_runs']['parameters']['path'] & NonNullable<operations['app_runs']['parameters']['query']>, options?: MethodOptions): Promise<operations['app_runs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/runs\",\"pathParams\":[\"app\"],\"query\":[\"limit\",\"before\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_runs']['responses'][200]['content']['application/json']>,\n /**\n * What an app stores.\n *\n * `GET /apps/{app}/storage` (`app_storage`). **Who:** whoever the app's access admits (a public app: anyone).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n storage: (args: operations['app_storage']['parameters']['path'], options?: MethodOptions): Promise<operations['app_storage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/storage\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_storage']['responses'][200]['content']['application/json']>,\n /**\n * Hand an app to another account.\n *\n * `POST /apps/{app}/transfer` (`app_transfer`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n transfer: (args: operations['app_transfer']['parameters']['path'] & operations['app_transfer']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_transfer']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/transfer\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_transfer']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade an app instance.\n *\n * `POST /apps/{app}/upgrade` (`app_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgrade: (args: operations['app_upgrade']['parameters']['path'] & operations['app_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/upgrade\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Abort an upload.\n *\n * `DELETE /apps/{app}/files/uploads/{upload}` (`upload_abort`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadAbort: (args: operations['upload_abort']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_abort']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/apps/{app}/files/uploads/{upload}\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_abort']['responses'][200]['content']['application/json']>,\n /**\n * Begin a file upload.\n *\n * `POST /apps/{app}/files/uploads` (`upload_begin`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadBegin: (args: operations['upload_begin']['parameters']['path'] & operations['upload_begin']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['upload_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files/uploads\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_begin']['responses'][200]['content']['application/json']>,\n /**\n * Commit an upload.\n *\n * `POST /apps/{app}/files/uploads/{upload}/complete` (`upload_complete`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadComplete: (args: operations['upload_complete']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_complete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/files/uploads/{upload}/complete\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_complete']['responses'][200]['content']['application/json']>,\n /**\n * Send one part.\n *\n * `PUT /apps/{app}/files/uploads/{upload}/parts/{k}` (`upload_part`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadPart: (args: operations['upload_part']['parameters']['path'] & RawBody, options?: MethodOptions): Promise<operations['upload_part']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"PUT\",\"path\":\"/apps/{app}/files/uploads/{upload}/parts/{k}\",\"pathParams\":[\"app\",\"upload\",\"k\"],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_part']['responses'][200]['content']['application/json']>,\n /**\n * Where an upload is.\n *\n * `GET /apps/{app}/files/uploads/{upload}` (`upload_status`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uploadStatus: (args: operations['upload_status']['parameters']['path'], options?: MethodOptions): Promise<operations['upload_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/files/uploads/{upload}\",\"pathParams\":[\"app\",\"upload\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['upload_status']['responses'][200]['content']['application/json']>,\n /**\n * An app's runs per day.\n *\n * `GET /apps/{app}/usage` (`app_usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: operations['app_usage']['parameters']['path'], options?: MethodOptions): Promise<operations['app_usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/usage\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_usage']['responses'][200]['content']['application/json']>,\n /**\n * Read with a view method.\n *\n * `POST /apps/{app}/views` (`views`). **Who:** whoever the app's access admits (a public app: anyone).\n * Retried on `503` (D70).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n view: (args: operations['views']['parameters']['path'] & operations['views']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['views']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/apps/{app}/views\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['views']['responses'][200]['content']['application/json']>,\n /**\n * An app's cross-app calls.\n *\n * `GET /apps/{app}/xcalls` (`app_xcalls`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n xcalls: (args: operations['app_xcalls']['parameters']['path'], options?: MethodOptions): Promise<operations['app_xcalls']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/apps/{app}/xcalls\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_xcalls']['responses'][200]['content']['application/json']>,\n },\n auth: {\n /**\n * The account's own apps.\n *\n * `GET /auth/apps` (`account_apps`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountApps: (args: NonNullable<operations['account_apps']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['account_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/apps\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_apps']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes for the account's apps.\n *\n * `POST /auth/outbound` (`account_outbound_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountOutboundApproval: (args: operations['account_outbound_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_outbound_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/outbound\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_outbound_approval']['responses'][200]['content']['application/json']>,\n /**\n * Prove the account to another party.\n *\n * `POST /auth/account-proof` (`account_proof_prove`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountProofProve: (args: operations['account_proof_prove']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_proof_prove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/account-proof\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_proof_prove']['responses'][200]['content']['application/json']>,\n /**\n * Start an account recovery.\n *\n * `POST /auth/recovery/begin` (`account_recovery_begin`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryBegin: (args: operations['account_recovery_begin']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_recovery_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_begin']['responses'][200]['content']['application/json']>,\n /**\n * Cancel an account recovery.\n *\n * `POST /auth/recovery/cancel` (`account_recovery_cancel`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryCancel: (args: Partial<NonNullable<operations['account_recovery_cancel']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['account_recovery_cancel']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/cancel\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_cancel']['responses'][200]['content']['application/json']>,\n /**\n * Finish an account recovery.\n *\n * `POST /auth/recovery/finish` (`account_recovery_finish`). **Who:** anyone.\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountRecoveryFinish: (args: operations['account_recovery_finish']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['account_recovery_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_finish']['responses'][200]['content']['application/json']>,\n /**\n * Spend the recovery code.\n *\n * `POST /auth/recovery/start` (`account_recovery_start`). **Who:** anyone.\n */\n accountRecoveryStart: (args: operations['account_recovery_start']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_recovery_start']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery/start\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_recovery_start']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for the account's apps.\n *\n * `POST /auth/releases` (`account_release_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n accountReleaseApproval: (args: operations['account_release_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['account_release_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/releases\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['account_release_approval']['responses'][200]['content']['application/json']>,\n /**\n * What the account's passkeys did.\n *\n * `GET /auth/activity` (`activity_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n activityList: (args: NonNullable<operations['activity_list']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['activity_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/activity\",\"pathParams\":[],\"query\":[\"after\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['activity_list']['responses'][200]['content']['application/json']>,\n /**\n * Remove an alias.\n *\n * `DELETE /auth/aliases/{alias}` (`alias_delete`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasDelete: (args: operations['alias_delete']['parameters']['path'], options?: MethodOptions): Promise<operations['alias_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_delete']['responses'][200]['content']['application/json']>,\n /**\n * Resolve an alias.\n *\n * `GET /auth/aliases/{alias}` (`alias_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasGet: (args: operations['alias_get']['parameters']['path'], options?: MethodOptions): Promise<operations['alias_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_get']['responses'][200]['content']['application/json']>,\n /**\n * The account's aliases.\n *\n * `GET /auth/aliases` (`alias_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['alias_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/aliases\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_list']['responses'][200]['content']['application/json']>,\n /**\n * Set an alias.\n *\n * `PUT /auth/aliases/{alias}` (`alias_set`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n aliasSet: (args: operations['alias_set']['parameters']['path'] & operations['alias_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['alias_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"PUT\",\"path\":\"/auth/aliases/{alias}\",\"pathParams\":[\"alias\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['alias_set']['responses'][200]['content']['application/json']>,\n /**\n * Make an API key.\n *\n * `POST /auth/apikeys` (`apikey_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyCreate: (args: operations['apikey_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['apikey_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/apikeys\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_create']['responses'][200]['content']['application/json']>,\n /**\n * The account's API keys.\n *\n * `GET /auth/apikeys` (`apikey_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['apikey_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/apikeys\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_list']['responses'][200]['content']['application/json']>,\n /**\n * Revoke an API key.\n *\n * `DELETE /auth/apikeys/{key}` (`apikey_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apikeyRevoke: (args: operations['apikey_revoke']['parameters']['path'] & Partial<NonNullable<operations['apikey_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['apikey_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/apikeys/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['apikey_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Start a sign-in.\n *\n * `POST /auth/passkey/login/begin` (`login_begin`). **Who:** anyone.\n */\n loginBegin: (args: Partial<NonNullable<operations['login_begin']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['login_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/login/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['login_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish a sign-in.\n *\n * `POST /auth/passkey/login/finish` (`login_finish`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n loginFinish: (args: operations['login_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['login_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/login/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['login_finish']['responses'][200]['content']['application/json']>,\n /**\n * End this session.\n *\n * `POST /auth/logout` (`logout`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n logout: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['logout']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/logout\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['logout']['responses'][200]['content']['application/json']>,\n /**\n * End every session of the account.\n *\n * `POST /auth/logout-all` (`logout_all`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n logoutAll: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['logout_all']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/logout-all\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['logout_all']['responses'][200]['content']['application/json']>,\n /**\n * The caller's account.\n *\n * `GET /auth/me` (`me`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n me: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['me']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/me\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['me']['responses'][200]['content']['application/json']>,\n /**\n * Start adding a passkey.\n *\n * `POST /auth/passkeys/add/begin` (`passkey_add_begin`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyAddBegin: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['passkey_add_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/add/begin\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_add_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish adding a passkey.\n *\n * `POST /auth/passkeys/add/finish` (`passkey_add_finish`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyAddFinish: (args: operations['passkey_add_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['passkey_add_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/add/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_add_finish']['responses'][200]['content']['application/json']>,\n /**\n * Name a passkey.\n *\n * `POST /auth/passkeys/{cred}` (`passkey_label`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyLabel: (args: operations['passkey_label']['parameters']['path'] & operations['passkey_label']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['passkey_label']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkeys/{cred}\",\"pathParams\":[\"cred\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_label']['responses'][200]['content']['application/json']>,\n /**\n * Remove a passkey.\n *\n * `DELETE /auth/passkeys/{cred}` (`passkey_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n passkeyRemove: (args: operations['passkey_remove']['parameters']['path'] & Partial<NonNullable<operations['passkey_remove']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['passkey_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/passkeys/{cred}\",\"pathParams\":[\"cred\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['passkey_remove']['responses'][200]['content']['application/json']>,\n /**\n * Make a recovery code.\n *\n * `POST /auth/recovery` (`recovery_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryCreate: (args: Partial<NonNullable<operations['recovery_create']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['recovery_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/recovery\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_create']['responses'][200]['content']['application/json']>,\n /**\n * Remove the recovery code.\n *\n * `DELETE /auth/recovery` (`recovery_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryRemove: (args: Partial<NonNullable<operations['recovery_remove']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['recovery_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/recovery\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_remove']['responses'][200]['content']['application/json']>,\n /**\n * Refresh a session.\n *\n * `POST /auth/refresh` (`refresh`). **Who:** anyone.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n refresh: (args: operations['refresh']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['refresh']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/refresh\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['refresh']['responses'][200]['content']['application/json']>,\n /**\n * Start a sign-up.\n *\n * `POST /auth/passkey/register/begin` (`register_begin`). **Who:** anyone.\n */\n registerBegin: (args: operations['register_begin']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['register_begin']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/register/begin\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['register_begin']['responses'][200]['content']['application/json']>,\n /**\n * Finish a sign-up.\n *\n * `POST /auth/passkey/register/finish` (`register_finish`). **Who:** anyone.\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `preferred`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n registerFinish: (args: operations['register_finish']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['register_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/auth/passkey/register/finish\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"preferred\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['register_finish']['responses'][200]['content']['application/json']>,\n /**\n * End one session.\n *\n * `DELETE /auth/sessions/{session}` (`session_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n sessionRevoke: (args: operations['session_revoke']['parameters']['path'], options?: MethodOptions): Promise<operations['session_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/auth/sessions/{session}\",\"pathParams\":[\"session\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['session_revoke']['responses'][200]['content']['application/json']>,\n /**\n * The account's live sessions.\n *\n * `GET /auth/sessions` (`sessions_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n sessionsList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sessions_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/sessions\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sessions_list']['responses'][200]['content']['application/json']>,\n /**\n * The account's usage against its quotas.\n *\n * `GET /auth/usage` (`usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/auth/usage\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['usage']['responses'][200]['content']['application/json']>,\n },\n consent: {\n /**\n * Ask the account's owner to approve.\n *\n * `POST /consent/requests` (`consent_page_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n pageCreate: (args: { body: operations['consent_page_create']['requestBody']['content']['application/json'] }, options?: MethodOptions): Promise<operations['consent_page_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/consent/requests\",\"pathParams\":[],\"query\":[],\"body\":\"whole\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['consent_page_create']['responses'][200]['content']['application/json']>,\n /**\n * What became of a consent request.\n *\n * `GET /consent/{request}/result` (`consent_page_result`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n pageResult: (args: operations['consent_page_result']['parameters']['path'], options?: MethodOptions): Promise<operations['consent_page_result']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/consent/{request}/result\",\"pathParams\":[\"request\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['consent_page_result']['responses'][200]['content']['application/json']>,\n },\n deployments: {\n /**\n * Create a deployment.\n *\n * `POST /deployments` (`deployment_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['deployment_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployment_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployments\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete a deployment.\n *\n * `DELETE /deployments/{id}` (`deployment_delete`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['deployment_delete']['parameters']['path'] & Partial<NonNullable<operations['deployment_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployment_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployments/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_delete']['responses'][200]['content']['application/json']>,\n /**\n * Grant a deployer.\n *\n * `POST /deployers` (`deployer_grant`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerGrant: (args: operations['deployer_grant']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployer_grant']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_grant']['responses'][200]['content']['application/json']>,\n /**\n * The deployers.\n *\n * `GET /deployers` (`deployer_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['deployer_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_list']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer.\n *\n * `DELETE /deployers/{key}` (`deployer_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n deployerRevoke: (args: operations['deployer_revoke']['parameters']['path'] & Partial<NonNullable<operations['deployer_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployer_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployers/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployer_revoke']['responses'][200]['content']['application/json']>,\n /**\n * One deployment.\n *\n * `GET /deployments/{id}` (`deployment_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['deployment_get']['parameters']['path'], options?: MethodOptions): Promise<operations['deployment_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_get']['responses'][200]['content']['application/json']>,\n /**\n * Deployments.\n *\n * `GET /deployments` (`deployment_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['deployment_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_list']['responses'][200]['content']['application/json']>,\n /**\n * Offer a release in a deployment.\n *\n * `POST /deployments/{id}/apps` (`deployment_offer`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n offer: (args: operations['deployment_offer']['parameters']['path'] & operations['deployment_offer']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['deployment_offer']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/deployments/{id}/apps\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_offer']['responses'][200]['content']['application/json']>,\n /**\n * The organizations a deployment serves.\n *\n * `GET /deployments/{id}/orgs` (`deployment_orgs`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n orgs: (args: operations['deployment_orgs']['parameters']['path'], options?: MethodOptions): Promise<operations['deployment_orgs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/deployments/{id}/orgs\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_orgs']['responses'][200]['content']['application/json']>,\n /**\n * Issue a cluster sign-up invite.\n *\n * `POST /sign-up/invites` (`sign_up_invite_create`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteCreate: (args: operations['sign_up_invite_create']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['sign_up_invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_create']['responses'][200]['content']['application/json']>,\n /**\n * Cluster sign-up invites.\n *\n * `GET /sign-up/invites` (`sign_up_invite_list`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sign_up_invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite.\n *\n * `DELETE /sign-up/invites/{key}` (`sign_up_invite_revoke`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpInviteRevoke: (args: operations['sign_up_invite_revoke']['parameters']['path'] & Partial<NonNullable<operations['sign_up_invite_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['sign_up_invite_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/sign-up/invites/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_invite_revoke']['responses'][200]['content']['application/json']>,\n /**\n * The sign-up policy.\n *\n * `GET /sign-up` (`sign_up_public`). **Who:** anyone.\n */\n signUpPublic: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['sign_up_public']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_public']['responses'][200]['content']['application/json']>,\n /**\n * Set the sign-up policy.\n *\n * `POST /sign-up` (`sign_up_set`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n signUpSet: (args: operations['sign_up_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['sign_up_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['sign_up_set']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw an offer.\n *\n * `DELETE /deployments/{id}/apps/{app}` (`deployment_withdraw`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n withdraw: (args: operations['deployment_withdraw']['parameters']['path'] & Partial<NonNullable<operations['deployment_withdraw']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['deployment_withdraw']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/deployments/{id}/apps/{app}\",\"pathParams\":[\"id\",\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['deployment_withdraw']['responses'][200]['content']['application/json']>,\n },\n ops: {\n /**\n * What each app runs.\n *\n * `GET /ops/apps` (`ops_apps`). **Who:** the ops token.\n */\n apps: (args: NonNullable<operations['ops_apps']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/apps\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_apps']['responses'][200]['content']['application/json']>,\n /**\n * Snapshot the apps this node leads.\n *\n * `POST /ops/backup` (`ops_backup`). **Who:** the ops token.\n */\n backup: (args: NonNullable<operations['ops_backup']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_backup']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/backup\",\"pathParams\":[],\"query\":[\"all\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_backup']['responses'][200]['content']['application/json']>,\n /**\n * The cluster's identity.\n *\n * `GET /ops/cluster` (`ops_cluster`). **Who:** the ops token.\n */\n cluster: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_cluster']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/cluster\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_cluster']['responses'][200]['content']['application/json']>,\n /**\n * Name the cluster's owner.\n *\n * `POST /ops/cluster-owner` (`ops_cluster_owner`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n clusterOwner: (args: operations['ops_cluster_owner']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_cluster_owner']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/cluster-owner\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_cluster_owner']['responses'][200]['content']['application/json']>,\n /**\n * Grant a deployer.\n *\n * `POST /ops/deployers` (`ops_deployer_grant`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerGrant: (args: operations['ops_deployer_grant']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_deployer_grant']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployers\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_grant']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer.\n *\n * `DELETE /ops/deployers/{key}` (`ops_deployer_revoke_delete`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerRevokeDelete: (args: operations['ops_deployer_revoke_delete']['parameters']['path'] & Partial<NonNullable<operations['ops_deployer_revoke_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_deployer_revoke_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/deployers/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_revoke_delete']['responses'][200]['content']['application/json']>,\n /**\n * Revoke a deployer (POST).\n *\n * `POST /ops/deployers/{key}/revoke` (`ops_deployer_revoke_post`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deployerRevokePost: (args: operations['ops_deployer_revoke_post']['parameters']['path'] & Partial<NonNullable<operations['ops_deployer_revoke_post']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_deployer_revoke_post']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployers/{key}/revoke\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployer_revoke_post']['responses'][200]['content']['application/json']>,\n /**\n * Require deployer grants.\n *\n * `POST /ops/deployments/granted` (`ops_deployments_granted`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n deploymentsGranted: (args: Partial<NonNullable<operations['ops_deployments_granted']['requestBody']>['content']['application/json']> = {}, options?: MethodOptions): Promise<operations['ops_deployments_granted']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/deployments/granted\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_deployments_granted']['responses'][200]['content']['application/json']>,\n /**\n * Prometheus metrics.\n *\n * `GET /ops/metrics` (`ops_metrics`). **Who:** the ops token.\n */\n metrics: (args: Record<string, never> = {}, options?: MethodOptions): Promise<string> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/metrics\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"text\"}, args as unknown as Record<string, unknown>, options) as Promise<string>,\n /**\n * Each organization's approved releases.\n *\n * `GET /ops/orgs` (`ops_orgs`). **Who:** the ops token.\n */\n orgs: (args: NonNullable<operations['ops_orgs']['parameters']['query']> = {}, options?: MethodOptions): Promise<operations['ops_orgs']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/orgs\",\"pathParams\":[],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_orgs']['responses'][200]['content']['application/json']>,\n /**\n * An operator's upgrade run.\n *\n * `POST /ops/orgs/{org}/upgrade` (`ops_org_upgrade`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n orgUpgrade: (args: operations['ops_org_upgrade']['parameters']['path'] & operations['ops_org_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_org_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/orgs/{org}/upgrade\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_org_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes.\n *\n * `POST /ops/outbound` (`ops_outbound`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n outbound: (args: operations['ops_outbound']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_outbound']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/outbound\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_outbound']['responses'][200]['content']['application/json']>,\n /**\n * Install a release from the registry as the operator.\n *\n * `POST /ops/packages/install` (`ops_package_install`). **Who:** the ops token.\n */\n packageInstall: (args: operations['ops_package_install']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_package_install']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/packages/install\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_install']['responses'][200]['content']['application/json']>,\n /**\n * The releases the operator installed.\n *\n * `GET /ops/packages` (`ops_package_list`). **Who:** the ops token.\n */\n packageList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_package_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/packages\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_list']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall what the operator installed.\n *\n * `DELETE /ops/packages/{package}` (`ops_package_uninstall`). **Who:** the ops token.\n */\n packageUninstall: (args: operations['ops_package_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_package_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Install an uploaded release as the operator.\n *\n * `POST /ops/packages` (`ops_package_upload`). **Who:** the ops token.\n */\n packageUpload: (args: RawBody, options?: MethodOptions): Promise<operations['ops_package_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/packages\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_upload']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall one operator-installed version.\n *\n * `DELETE /ops/packages/{package}/{version}` (`ops_package_version_uninstall`). **Who:** the ops token.\n */\n packageVersionUninstall: (args: operations['ops_package_version_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_package_version_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/packages/{package}/{version}\",\"pathParams\":[\"package\",\"version\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_package_version_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Where every app's replicas are.\n *\n * `GET /ops/placement` (`ops_placement`). **Who:** the ops token.\n */\n placement: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_placement']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/placement\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_placement']['responses'][200]['content']['application/json']>,\n /**\n * Compute pools.\n *\n * `GET /ops/pools` (`ops_pools_get`). **Who:** the ops token.\n */\n poolsGet: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_pools_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/pools\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_pools_get']['responses'][200]['content']['application/json']>,\n /**\n * Set the compute pools.\n *\n * `POST /ops/pools` (`ops_pools_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n poolsSet: (args: operations['ops_pools_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_pools_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/pools\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_pools_set']['responses'][200]['content']['application/json']>,\n /**\n * The quotas.\n *\n * `GET /ops/quotas` (`ops_quotas_get`). **Who:** the ops token.\n */\n quotasGet: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_quotas_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/quotas\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_quotas_get']['responses'][200]['content']['application/json']>,\n /**\n * Change quotas.\n *\n * `POST /ops/quotas` (`ops_quotas_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n quotasSet: (args: operations['ops_quotas_set']['requestBody']['content']['application/json'] = {}, options?: MethodOptions): Promise<operations['ops_quotas_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/quotas\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_quotas_set']['responses'][200]['content']['application/json']>,\n /**\n * A node's receipt key.\n *\n * `GET /ops/nodes/{id}/receipt-key` (`ops_receipt_key`). **Who:** the ops token.\n */\n receiptKey: (args: operations['ops_receipt_key']['parameters']['path'], options?: MethodOptions): Promise<operations['ops_receipt_key']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/nodes/{id}/receipt-key\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_receipt_key']['responses'][200]['content']['application/json']>,\n /**\n * Register a node.\n *\n * `POST /ops/nodes` (`ops_register_node`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n registerNode: (args: operations['ops_register_node']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_register_node']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/nodes\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_register_node']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for every app.\n *\n * `POST /ops/releases` (`ops_release`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n release: (args: operations['ops_release']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_release']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/releases\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release']['responses'][200]['content']['application/json']>,\n /**\n * Set a release deadline.\n *\n * `POST /ops/releases/{version}/deadline` (`ops_release_deadline`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n releaseDeadline: (args: operations['ops_release_deadline']['parameters']['path'] & operations['ops_release_deadline']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_release_deadline']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/releases/{version}/deadline\",\"pathParams\":[\"version\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release_deadline']['responses'][200]['content']['application/json']>,\n /**\n * Lift a release deadline.\n *\n * `DELETE /ops/releases/{version}/deadline` (`ops_release_deadline_lift`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n releaseDeadlineLift: (args: operations['ops_release_deadline_lift']['parameters']['path'] & Partial<NonNullable<operations['ops_release_deadline_lift']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_release_deadline_lift']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/releases/{version}/deadline\",\"pathParams\":[\"version\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_release_deadline_lift']['responses'][200]['content']['application/json']>,\n /**\n * Remove a node.\n *\n * `DELETE /ops/nodes/{id}` (`ops_remove_node`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n removeNode: (args: operations['ops_remove_node']['parameters']['path'] & Partial<NonNullable<operations['ops_remove_node']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_remove_node']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/nodes/{id}\",\"pathParams\":[\"id\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_remove_node']['responses'][200]['content']['application/json']>,\n /**\n * Restore an app from its sealed backup.\n *\n * `POST /ops/apps/{app}/restore` (`ops_restore`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n restore: (args: operations['ops_restore']['parameters']['path'] & operations['ops_restore']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_restore']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/restore\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_restore']['responses'][200]['content']['application/json']>,\n /**\n * Custom domains to serve.\n *\n * `GET /ops/served-origins` (`ops_served`). **Who:** the ops token.\n */\n served: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_served']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/served-origins\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_served']['responses'][200]['content']['application/json']>,\n /**\n * Move an app's replicas.\n *\n * `POST /ops/apps/{app}/replicas` (`ops_set_replicas`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n setReplicas: (args: operations['ops_set_replicas']['parameters']['path'] & operations['ops_set_replicas']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_set_replicas']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/replicas\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_set_replicas']['responses'][200]['content']['application/json']>,\n /**\n * Issue a cluster sign-up invite.\n *\n * `POST /ops/sign-up/invites` (`ops_sign_up_invite_create`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteCreate: (args: operations['ops_sign_up_invite_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_sign_up_invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_create']['responses'][200]['content']['application/json']>,\n /**\n * Cluster sign-up invites.\n *\n * `GET /ops/sign-up/invites` (`ops_sign_up_invite_list`). **Who:** the ops token.\n */\n signUpInviteList: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_sign_up_invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/sign-up/invites\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite.\n *\n * `DELETE /ops/sign-up/invites/{key}` (`ops_sign_up_invite_revoke_delete`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteRevokeDelete: (args: operations['ops_sign_up_invite_revoke_delete']['parameters']['path'] & Partial<NonNullable<operations['ops_sign_up_invite_revoke_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_sign_up_invite_revoke_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/ops/sign-up/invites/{key}\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_revoke_delete']['responses'][200]['content']['application/json']>,\n /**\n * Withdraw a cluster sign-up invite (POST).\n *\n * `POST /ops/sign-up/invites/{key}/revoke` (`ops_sign_up_invite_revoke_post`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpInviteRevokePost: (args: operations['ops_sign_up_invite_revoke_post']['parameters']['path'] & Partial<NonNullable<operations['ops_sign_up_invite_revoke_post']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['ops_sign_up_invite_revoke_post']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up/invites/{key}/revoke\",\"pathParams\":[\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_invite_revoke_post']['responses'][200]['content']['application/json']>,\n /**\n * Set the sign-up policy.\n *\n * `POST /ops/sign-up` (`ops_sign_up_set`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n signUpSet: (args: operations['ops_sign_up_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_sign_up_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/sign-up\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_sign_up_set']['responses'][200]['content']['application/json']>,\n /**\n * The node and the cluster.\n *\n * `GET /ops/status` (`ops_status`). **Who:** the ops token.\n */\n status: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['ops_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/ops/status\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_status']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade an app as the operator.\n *\n * `POST /ops/apps/{app}/upgrade` (`ops_upgrade`). **Who:** the ops token.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n */\n upgrade: (args: operations['ops_upgrade']['parameters']['path'] & operations['ops_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['ops_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/ops/apps/{app}/upgrade\",\"pathParams\":[\"app\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['ops_upgrade']['responses'][200]['content']['application/json']>,\n },\n orgs: {\n /**\n * Give a member every app added later.\n *\n * `POST /orgs/{org}/all-apps` (`org_all_apps`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n allApps: (args: operations['org_all_apps']['parameters']['path'] & operations['org_all_apps']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_all_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/all-apps\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_all_apps']['responses'][200]['content']['application/json']>,\n /**\n * The organization's apps.\n *\n * `GET /orgs/{org}/apps` (`org_apps`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n apps: (args: operations['org_apps']['parameters']['path'] & NonNullable<operations['org_apps']['parameters']['query']>, options?: MethodOptions): Promise<operations['org_apps']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/apps\",\"pathParams\":[\"org\"],\"query\":[\"after\",\"limit\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_apps']['responses'][200]['content']['application/json']>,\n /**\n * The organization's app teams.\n *\n * `GET /orgs/{org}/app-teams` (`app_team_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n appTeamList: (args: operations['app_team_list']['parameters']['path'], options?: MethodOptions): Promise<operations['app_team_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/app-teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_team_list']['responses'][200]['content']['application/json']>,\n /**\n * Give apps app teams, or open or close one.\n *\n * `POST /orgs/{org}/app-teams` (`app_teams_scope`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n appTeamsScope: (args: operations['app_teams_scope']['parameters']['path'] & operations['app_teams_scope']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['app_teams_scope']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/app-teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['app_teams_scope']['responses'][200]['content']['application/json']>,\n /**\n * Set capabilities.\n *\n * `POST /orgs/{org}/capabilities` (`org_capabilities`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n capabilities: (args: operations['org_capabilities']['parameters']['path'] & operations['org_capabilities']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_capabilities']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/capabilities\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_capabilities']['responses'][200]['content']['application/json']>,\n /**\n * Create an organization.\n *\n * `POST /orgs` (`org_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n create: (args: operations['org_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete an organization.\n *\n * `DELETE /orgs/{org}` (`org_delete`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n delete: (args: operations['org_delete']['parameters']['path'] & Partial<NonNullable<operations['org_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_delete']['responses'][200]['content']['application/json']>,\n /**\n * One organization.\n *\n * `GET /orgs/{org}` (`org_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['org_get']['parameters']['path'], options?: MethodOptions): Promise<operations['org_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_get']['responses'][200]['content']['application/json']>,\n /**\n * Make an invite.\n *\n * `POST /orgs/{org}/invites` (`invite_create`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteCreate: (args: operations['invite_create']['parameters']['path'] & operations['invite_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['invite_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/invites\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_create']['responses'][200]['content']['application/json']>,\n /**\n * The organization's invites.\n *\n * `GET /orgs/{org}/invites` (`invite_list`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteList: (args: operations['invite_list']['parameters']['path'], options?: MethodOptions): Promise<operations['invite_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/invites\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_list']['responses'][200]['content']['application/json']>,\n /**\n * Join with an invite.\n *\n * `POST /invites/{token}/redeem` (`invite_redeem`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteRedeem: (args: operations['invite_redeem']['parameters']['path'], options?: MethodOptions): Promise<operations['invite_redeem']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/invites/{token}/redeem\",\"pathParams\":[\"token\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_redeem']['responses'][200]['content']['application/json']>,\n /**\n * Revoke an invite.\n *\n * `DELETE /orgs/{org}/invites/{key}` (`invite_revoke`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n inviteRevoke: (args: operations['invite_revoke']['parameters']['path'] & Partial<NonNullable<operations['invite_revoke']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['invite_revoke']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/invites/{key}\",\"pathParams\":[\"org\",\"key\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['invite_revoke']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's metadata.\n *\n * `POST /orgs/{org}/members/{account}/metadata` (`member_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberMetadata: (args: operations['member_metadata']['parameters']['path'] & operations['member_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members/{account}/metadata\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Remove a member from several teams, or leave them.\n *\n * `DELETE /orgs/{org}/members/{account}/teams` (`member_remove_teams`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberRemoveTeams: (args: operations['member_remove_teams']['parameters']['path'] & operations['member_remove_teams']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_remove_teams']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/members/{account}/teams\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_remove_teams']['responses'][200]['content']['application/json']>,\n /**\n * Members' lockout risk.\n *\n * `GET /orgs/{org}/members` (`org_members`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n members: (args: operations['org_members']['parameters']['path'] & NonNullable<operations['org_members']['parameters']['query']>, options?: MethodOptions): Promise<operations['org_members']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/members\",\"pathParams\":[\"org\"],\"query\":[\"detail\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_members']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's rows in several teams.\n *\n * `POST /orgs/{org}/members/{account}/teams` (`member_set_teams`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n memberSetTeams: (args: operations['member_set_teams']['parameters']['path'] & operations['member_set_teams']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['member_set_teams']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members/{account}/teams\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['member_set_teams']['responses'][200]['content']['application/json']>,\n /**\n * Set an organization's metadata.\n *\n * `POST /orgs/{org}/metadata` (`org_metadata`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n metadata: (args: operations['org_metadata']['parameters']['path'] & operations['org_metadata']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_metadata']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/metadata\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_metadata']['responses'][200]['content']['application/json']>,\n /**\n * Approve outbound prefixes for the organization's apps.\n *\n * `POST /orgs/{org}/outbound` (`org_outbound_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n outboundApproval: (args: operations['org_outbound_approval']['parameters']['path'] & operations['org_outbound_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_outbound_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/outbound\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_outbound_approval']['responses'][200]['content']['application/json']>,\n /**\n * Bind a package signing key.\n *\n * `POST /orgs/{org}/publishers` (`org_publisher`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisher: (args: operations['org_publisher']['parameters']['path'] & operations['org_publisher']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_publisher']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/publishers\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_publisher']['responses'][200]['content']['application/json']>,\n /**\n * Upgrade every instance of a publisher's package.\n *\n * `POST /orgs/{org}/packages/{package}/upgrade` (`publisher_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisherUpgrade: (args: operations['publisher_upgrade']['parameters']['path'] & operations['publisher_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['publisher_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/packages/{package}/upgrade\",\"pathParams\":[\"org\",\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['publisher_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Cancel an organization recovery.\n *\n * `POST /orgs/{org}/recovery/cancel` (`recovery_cancel`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryCancel: (args: operations['recovery_cancel']['parameters']['path'] & Partial<NonNullable<operations['recovery_cancel']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['recovery_cancel']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/cancel\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_cancel']['responses'][200]['content']['application/json']>,\n /**\n * Finish an organization recovery.\n *\n * `POST /orgs/{org}/recovery/finish` (`recovery_finish`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryFinish: (args: operations['recovery_finish']['parameters']['path'] & Partial<NonNullable<operations['recovery_finish']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['recovery_finish']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/finish\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_finish']['responses'][200]['content']['application/json']>,\n /**\n * Set the organization's recovery key.\n *\n * `POST /orgs/{org}/recovery` (`recovery_set`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoverySet: (args: operations['recovery_set']['parameters']['path'] & operations['recovery_set']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['recovery_set']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_set']['responses'][200]['content']['application/json']>,\n /**\n * Start an organization recovery.\n *\n * `POST /orgs/{org}/recovery/start` (`recovery_start`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n recoveryStart: (args: operations['recovery_start']['parameters']['path'] & operations['recovery_start']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['recovery_start']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/recovery/start\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['recovery_start']['responses'][200]['content']['application/json']>,\n /**\n * Approve a mero-tee release for the organization's apps.\n *\n * `POST /orgs/{org}/releases` (`org_release_approval`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n releaseApproval: (args: operations['org_release_approval']['parameters']['path'] & operations['org_release_approval']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_release_approval']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/releases\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_release_approval']['responses'][200]['content']['application/json']>,\n /**\n * Remove a member, or leave.\n *\n * `DELETE /orgs/{org}/members/{account}` (`org_remove_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n removeMember: (args: operations['org_remove_member']['parameters']['path'] & Partial<NonNullable<operations['org_remove_member']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_remove_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/members/{account}\",\"pathParams\":[\"org\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_remove_member']['responses'][200]['content']['application/json']>,\n /**\n * Rename an organization.\n *\n * `POST /orgs/{org}/name` (`org_rename`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n rename: (args: operations['org_rename']['parameters']['path'] & operations['org_rename']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_rename']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/name\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_rename']['responses'][200]['content']['application/json']>,\n /**\n * Set a member's role.\n *\n * `POST /orgs/{org}/members` (`org_set_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n setMember: (args: operations['org_set_member']['parameters']['path'] & operations['org_set_member']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_set_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/members\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_set_member']['responses'][200]['content']['application/json']>,\n /**\n * Create a team.\n *\n * `POST /orgs/{org}/teams` (`team_create`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamCreate: (args: operations['team_create']['parameters']['path'] & operations['team_create']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_create']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_create']['responses'][200]['content']['application/json']>,\n /**\n * Delete a team.\n *\n * `DELETE /orgs/{org}/teams/{team}` (`team_delete`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamDelete: (args: operations['team_delete']['parameters']['path'] & Partial<NonNullable<operations['team_delete']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['team_delete']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_delete']['responses'][200]['content']['application/json']>,\n /**\n * One team.\n *\n * `GET /orgs/{org}/teams/{team}` (`team_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamGet: (args: operations['team_get']['parameters']['path'], options?: MethodOptions): Promise<operations['team_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_get']['responses'][200]['content']['application/json']>,\n /**\n * Remove a team member, or leave.\n *\n * `DELETE /orgs/{org}/teams/{team}/members/{account}` (`team_remove_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamRemoveMember: (args: operations['team_remove_member']['parameters']['path'] & Partial<NonNullable<operations['team_remove_member']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['team_remove_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/orgs/{org}/teams/{team}/members/{account}\",\"pathParams\":[\"org\",\"team\",\"account\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_remove_member']['responses'][200]['content']['application/json']>,\n /**\n * Add or change a team member.\n *\n * `POST /orgs/{org}/teams/{team}/members` (`team_set_member`). **Who:** a passkey session (an API key is refused).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamSetMember: (args: operations['team_set_member']['parameters']['path'] & operations['team_set_member']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_set_member']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams/{team}/members\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_set_member']['responses'][200]['content']['application/json']>,\n /**\n * Update a team.\n *\n * `POST /orgs/{org}/teams/{team}` (`team_update`). **Who:** a passkey session (an API key is refused).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n teamUpdate: (args: operations['team_update']['parameters']['path'] & operations['team_update']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['team_update']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/teams/{team}\",\"pathParams\":[\"org\",\"team\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['team_update']['responses'][200]['content']['application/json']>,\n /**\n * Start an upgrade run.\n *\n * `POST /orgs/{org}/upgrade` (`org_upgrade`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgrade: (args: operations['org_upgrade']['parameters']['path'] & operations['org_upgrade']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['org_upgrade']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/upgrade\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade']['responses'][200]['content']['application/json']>,\n /**\n * Retry an upgrade run's failed apps.\n *\n * `POST /orgs/{org}/upgrades/{run}/retry` (`org_upgrade_retry`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgradeRetry: (args: operations['org_upgrade_retry']['parameters']['path'] & Partial<NonNullable<operations['org_upgrade_retry']['requestBody']>['content']['application/json']>, options?: MethodOptions): Promise<operations['org_upgrade_retry']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/orgs/{org}/upgrades/{run}/retry\",\"pathParams\":[\"org\",\"run\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":true,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\",\"operator\":true}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade_retry']['responses'][200]['content']['application/json']>,\n /**\n * An upgrade run's progress.\n *\n * `GET /orgs/{org}/upgrades/{run}` (`org_upgrade_status`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upgradeStatus: (args: operations['org_upgrade_status']['parameters']['path'], options?: MethodOptions): Promise<operations['org_upgrade_status']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/upgrades/{run}\",\"pathParams\":[\"org\",\"run\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_upgrade_status']['responses'][200]['content']['application/json']>,\n /**\n * An organization's usage.\n *\n * `GET /orgs/{org}/usage` (`org_usage`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n usage: (args: operations['org_usage']['parameters']['path'], options?: MethodOptions): Promise<operations['org_usage']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/orgs/{org}/usage\",\"pathParams\":[\"org\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['org_usage']['responses'][200]['content']['application/json']>,\n },\n packages: {\n /**\n * Upload a raw component.\n *\n * `POST /bundles` (`bundle_put`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n bundlePut: (args: RawBody, options?: MethodOptions): Promise<operations['bundle_put']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/bundles\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/wasm\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['bundle_put']['responses'][200]['content']['application/json']>,\n /**\n * One package.\n *\n * `GET /packages/{package}` (`package_get`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n get: (args: operations['package_get']['parameters']['path'], options?: MethodOptions): Promise<operations['package_get']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_get']['responses'][200]['content']['application/json']>,\n /**\n * Install a release from the registry.\n *\n * `POST /packages/install` (`package_install`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n install: (args: operations['package_install']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['package_install']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/packages/install\",\"pathParams\":[],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_install']['responses'][200]['content']['application/json']>,\n /**\n * Installed packages.\n *\n * `GET /packages` (`package_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n list: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['package_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/packages\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_list']['responses'][200]['content']['application/json']>,\n /**\n * Register a frontend origin.\n *\n * `POST /package-origins/{package}` (`origins_add`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsAdd: (args: operations['origins_add']['parameters']['path'] & operations['origins_add']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['origins_add']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_add']['responses'][200]['content']['application/json']>,\n /**\n * A package's frontend origins.\n *\n * `GET /package-origins/{package}` (`origins_list`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsList: (args: operations['origins_list']['parameters']['path'], options?: MethodOptions): Promise<operations['origins_list']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_list']['responses'][200]['content']['application/json']>,\n /**\n * Remove a frontend origin.\n *\n * `DELETE /package-origins/{package}` (`origins_remove`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * Answers `412 CONFIRM_REQUIRED` first: give `confirm` (here or on the client); the passkey must verify the user `required`.\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n originsRemove: (args: operations['origins_remove']['parameters']['path'] & operations['origins_remove']['requestBody']['content']['application/json'], options?: MethodOptions): Promise<operations['origins_remove']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/package-origins/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"fields\",\"optionalBody\":false,\"reply\":\"json\",\"stepUp\":true,\"userVerification\":\"required\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['origins_remove']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall a package.\n *\n * `DELETE /packages/{package}` (`package_uninstall`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n uninstall: (args: operations['package_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['package_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/packages/{package}\",\"pathParams\":[\"package\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_uninstall']['responses'][200]['content']['application/json']>,\n /**\n * Upload a signed release.\n *\n * `POST /packages` (`package_upload`). **Who:** an installer (an account holder, or an unscoped API key that is not read-only).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n upload: (args: RawBody, options?: MethodOptions): Promise<operations['package_upload']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"POST\",\"path\":\"/packages\",\"pathParams\":[],\"query\":[],\"body\":\"raw\",\"optionalBody\":false,\"media\":\"application/octet-stream\",\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_upload']['responses'][200]['content']['application/json']>,\n /**\n * Uninstall one version.\n *\n * `DELETE /packages/{package}/{version}` (`package_version_uninstall`). **Who:** an account holder (a passkey session not bound to an app's frontend).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n versionUninstall: (args: operations['package_version_uninstall']['parameters']['path'], options?: MethodOptions): Promise<operations['package_version_uninstall']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"DELETE\",\"path\":\"/packages/{package}/{version}\",\"pathParams\":[\"package\",\"version\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['package_version_uninstall']['responses'][200]['content']['application/json']>,\n },\n public: {\n /**\n * The node's attestation.\n *\n * `GET /attestation` (`attestation`). **Who:** anyone.\n */\n attestation: (args: NonNullable<operations['attestation']['parameters']['query']>, options?: MethodOptions): Promise<operations['attestation']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/attestation\",\"pathParams\":[],\"query\":[\"nonce\",\"app\",\"appHash\",\"purpose\"],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['attestation']['responses'][200]['content']['application/json']>,\n /**\n * Node health.\n *\n * `GET /health` (`health`). **Who:** anyone.\n */\n health: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['health']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/health\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['health']['responses'][200]['content']['application/json']>,\n /**\n * Whether a signing key is bound.\n *\n * `GET /publishers/{signer}` (`publisher_binding`). **Who:** signed in (a session or an API key).\n * A `421 WRONG_NODE` moves the client to the next node of the cluster.\n */\n publisherBinding: (args: operations['publisher_binding']['parameters']['path'], options?: MethodOptions): Promise<operations['publisher_binding']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/publishers/{signer}\",\"pathParams\":[\"signer\"],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['publisher_binding']['responses'][200]['content']['application/json']>,\n /**\n * The cluster's releases.\n *\n * `GET /releases` (`releases_public`). **Who:** anyone.\n */\n releasesPublic: (args: Record<string, never> = {}, options?: MethodOptions): Promise<operations['releases_public']['responses'][200]['content']['application/json']> =>\n route(api, {\"method\":\"GET\",\"path\":\"/releases\",\"pathParams\":[],\"query\":[],\"body\":\"none\",\"optionalBody\":false,\"reply\":\"json\"}, args as unknown as Record<string, unknown>, options) as Promise<operations['releases_public']['responses'][200]['content']['application/json']>,\n },\n };\n}\n\n/**\n * The routes the document marks `x-calimero-retry-safe`: the transport sends them again on a `503`\n * (D70), and one that `requires` an `idempotencyKey` is given one before it is first sent.\n */\nexport const RETRY_SAFE_ROUTES: ReadonlyArray<{ method: string; path: string; requires?: string }> = [{\"method\":\"POST\",\"path\":\"/apps/{app}/intents\",\"requires\":\"idempotencyKey\"},{\"method\":\"POST\",\"path\":\"/apps/{app}/methods/{method}\",\"requires\":\"idempotencyKey\"},{\"method\":\"POST\",\"path\":\"/apps/{app}/views\"}];\n\n/** Every generated group. */\nexport type Routes = ReturnType<typeof createRoutes>;\n/** The `apps` methods. */\nexport type AppsRoutes = Routes['apps'];\n/** The `auth` methods. */\nexport type AuthRoutes = Routes['auth'];\n/** The `consent` methods. */\nexport type ConsentRoutes = Routes['consent'];\n/** The `deployments` methods. */\nexport type DeploymentsRoutes = Routes['deployments'];\n/** The `ops` methods. */\nexport type OpsRoutes = Routes['ops'];\n/** The `orgs` methods. */\nexport type OrgsRoutes = Routes['orgs'];\n/** The `packages` methods. */\nexport type PackagesRoutes = Routes['packages'];\n/** The `public` methods. */\nexport type PublicRoutes = Routes['public'];\n", "/**\n * The node's routes as a typed client, generated from core's OpenAPI document\n * (`openapi/core-openapi.json`, types in `src/generated/api.ts` by\n * `pnpm gen:api`), run by `openapi-fetch` over this package's runtime:\n *\n * - its `fetch` is {@link transportFetch}: every request goes through a\n * {@link NodeTransport}, so it is sealed to an attested node, carries the\n * transport's credential (refreshed on a `401`), moves on past a\n * `421 WRONG_NODE`, and a route the document marks retry-safe retries a\n * `503` (D70); the two\n * routes a node serves in the clear (`/attestation`, `/health`) go\n * unsealed, without the credential;\n * - the `412 CONFIRM_REQUIRED` step-up and the `428\n * OPERATOR_SIGNATURE_REQUIRED` operator signature are middleware\n * (`./step-up.ts`), for the whole client or one request.\n *\n * A node's refusal is the `error` of the result (`{ status, error, message,\n * details? }`), typed per route; {@link unwrap} throws it as the typed\n * {@link CalimeroError} instead. A transport failure (the node unreachable,\n * an attestation the policy refuses, an envelope past the sealed cap) rejects.\n * Streams (`GET /apps/{app}/events`, `/presence/stream`) are not routes of this\n * client: read them with `transport.events`.\n */\n\nimport createClient, { type Client, type Middleware } from 'openapi-fetch';\n\nimport type { paths } from '../generated/api.js';\nimport { errorFrom, type CalimeroError } from '../runtime/errors.js';\nimport { newIdempotencyKey, type HttpMethod, type NodeTransport, type QueryValue } from '../runtime/transport.js';\nimport { operatorSignature, stepUp, type OperatorProofCallback } from './step-up.js';\nimport { type ConfirmCallback } from '../runtime/passkey.js';\nimport { RETRY_SAFE_ROUTES } from '../generated/methods.js';\n\n/** The typed client of every route of a Calimero node. */\nexport type RouteClient = Client<paths, 'application/json'>;\n\n/** The node's API, path by path (the generated `paths`). */\nexport type { paths as ApiPaths } from '../generated/api.js';\n\n/**\n * The base URL the generated client builds request URLs on. It names no\n * node: {@link transportFetch} sends the path and query to the node the\n * transport uses now.\n */\nexport const ROUTE_BASE_URL = 'https://calimero-node.invalid';\n\n/** What {@link createRouteClient} sends through: a {@link NodeTransport}, or anything that answers like its `exchange`. */\nexport interface RouteTransport {\n exchange: NodeTransport['exchange'];\n /** `GET` of a route the node serves in the clear; without it those go sealed too. */\n inTheClear?: NodeTransport['inTheClear'];\n}\n\n/**\n * The routes a node serves outside the sealed channel (the document's\n * `x-calimero-sealed: false`): `GET /attestation` and `GET /health`.\n */\nconst IN_THE_CLEAR = new Set(['attestation', 'health']);\n\n/** How {@link createRouteClient} answers the node's challenges for every request. */\nexport interface RouteClientOptions {\n /**\n * Answers every `412 CONFIRM_REQUIRED` (say, `passkeyConfirm(browserPasskey())`).\n * A request's own `stepUp` middleware answers first.\n */\n confirm?: ConfirmCallback;\n /** Answers every `428 OPERATOR_SIGNATURE_REQUIRED` with the operator key's signature. */\n operatorProof?: OperatorProofCallback;\n}\n\n/**\n * The routes a `503` is retried on (D70): those the document marks\n * `x-calimero-retry-safe` (a call, a view, a method by its path), each\n * carrying its idempotency key or reading. As path patterns, without the\n * leading `/`.\n */\nconst RETRIED = RETRY_SAFE_ROUTES.map((route) => ({\n method: route.method,\n pattern: new RegExp(`^${route.path.replace(/^\\//, '').replace(/\\{[^}]+\\}/g, '[^/]+')}$`),\n}));\n\n/** The route templates that must carry an `idempotencyKey` to be retried. */\nconst NEEDS_KEY = new Set(RETRY_SAFE_ROUTES.filter((r) => r.requires === 'idempotencyKey').map((r) => `${r.method} ${r.path}`));\n\n/**\n * A `fetch` that sends `openapi-fetch`'s request through `transport`: the\n * path and query after {@link ROUTE_BASE_URL}, the body as it was serialised,\n * and the request's signal. Headers other than `content-type` are not sent:\n * the transport sets the credential. A call or a view is retried as D70 says\n * (its confirmed attempt, carrying `confirm`, exactly once).\n */\nexport function transportFetch(transport: RouteTransport): (request: Request) => Promise<Response> {\n return async (request) => {\n if (!request.url.startsWith(`${ROUTE_BASE_URL}/`)) {\n throw new Error(`not a route of the generated client: ${request.url}`);\n }\n const url = new URL(request.url);\n const path = url.pathname.replace(/^\\/+/, '');\n const query: Record<string, QueryValue[]> = {};\n for (const [name, value] of url.searchParams) (query[name] ??= []).push(value);\n const method = request.method as HttpMethod;\n if (method === 'GET' && IN_THE_CLEAR.has(path) && transport.inTheClear) {\n return transport.inTheClear(path, { query, signal: request.signal });\n }\n const contentType = request.headers.get('content-type') ?? undefined;\n const bytes = method === 'GET' ? undefined : new Uint8Array(await request.arrayBuffer());\n const body = bytes && bytes.length > 0 ? bytes : undefined;\n let retry: boolean | 'once' = false;\n if (RETRIED.some((route) => route.method === method && route.pattern.test(path))) {\n const json = body ? (JSON.parse(new TextDecoder().decode(body)) as { confirm?: unknown }) : {};\n retry = json.confirm === undefined ? true : 'once';\n }\n return transport.exchange(method, path, {\n query,\n ...(body ? { bytes: body, contentType: contentType ?? 'application/octet-stream' } : {}),\n retry,\n signal: request.signal,\n });\n };\n}\n\n/**\n * Gives a request to a route whose retries require an `idempotencyKey`\n * (`x-calimero-retry-requires`: a call, a method by its path) one when it has\n * none, made before it is first sent, so its D70 retries and its step-up's\n * confirmed retry carry the same key.\n */\nexport const idempotencyKeys: Middleware = {\n async onRequest({ request, schemaPath }) {\n if (!NEEDS_KEY.has(`${request.method} ${schemaPath}`)) return undefined;\n const text = await request.clone().text();\n const body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n if (body.idempotencyKey !== undefined) return undefined;\n return new Request(request, { body: JSON.stringify({ ...body, idempotencyKey: newIdempotencyKey() }) });\n },\n};\n\n/**\n * The typed client of the node's routes, sent through `transport` (a\n * `CalimeroClient`'s is `client.transport`; its session is this client's).\n *\n * ```ts\n * const api = createRouteClient(client.transport);\n * const { data, error } = await api.POST('/apps/{app}/intents', {\n * params: { path: { app } },\n * body: { method: 'set', args: { key: 'a', value: 'b' } },\n * middleware: [stepUp(passkeyConfirm(passkey))],\n * });\n * ```\n */\nexport function createRouteClient(transport: RouteTransport, options: RouteClientOptions = {}): RouteClient {\n const api = createClient<paths, 'application/json'>({ baseUrl: ROUTE_BASE_URL, fetch: transportFetch(transport) });\n api.use(idempotencyKeys);\n if (options.confirm) api.use(stepUp(options.confirm));\n if (options.operatorProof) api.use(operatorSignature(options.operatorProof));\n return api;\n}\n\n/** What every method of {@link RouteClient} answers. */\nexport interface RouteResult<T> {\n data?: T;\n error?: unknown;\n response: Response;\n}\n\n/**\n * The `data` of a result, or its refusal thrown as the typed\n * {@link CalimeroError} ({@link errorFrom}, the `Retry-After` header\n * included). An empty answer is `{}`.\n */\nexport async function unwrap<T>(result: Promise<RouteResult<T>> | RouteResult<T>): Promise<NonNullable<T>> {\n const { data, error, response } = await result;\n if (!response.ok) throw refusalOf(response, error);\n return (data ?? {}) as NonNullable<T>;\n}\n\n/** A refused result as the typed {@link CalimeroError}. */\nexport function refusalOf(response: Response, error: unknown): CalimeroError {\n const body = typeof error === 'string' ? (error ? { message: error } : {}) : error;\n return errorFrom(response.status, body, response.headers.get('retry-after'));\n}\n\nexport type { Middleware };\n", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n 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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\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/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\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) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, 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 buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\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/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__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 {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * 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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\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// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\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 // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\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/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\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 the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * Opening a sealed file, byte for byte as core's `calimero-sealed` crate\n * (`file.rs`, `wrap.rs`) writes it: 64 KiB AES-256-GCM STREAM chunks under a\n * data key, cut into segments, and that key wrapped to an X25519 key the\n * requester made for one export.\n */\n\nimport { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\nimport { concat, hex } from '../crypto/internal.js';\nimport { dh, type X25519KeyPair } from './noise.js';\n\nconst CHUNK_BYTES = 64 * 1024; // plaintext bytes in every chunk but the last\nconst TAG_BYTES = 16;\nconst SEALED_CHUNK_BYTES = CHUNK_BYTES + TAG_BYTES;\n/** Stored bytes of every segment but the last: 256 whole sealed chunks. */\nexport const SEGMENT_BYTES = 256 * SEALED_CHUNK_BYTES;\nconst NONCE_BYTES = 12;\nconst enc = new TextEncoder();\nconst AAD_PREFIX = enc.encode('calimero.file.v1'); // then the last-chunk flag byte\nconst SEGMENT_DOMAIN = enc.encode('calimero.file.segments.v1\\0'); // prefix of a file id's preimage\nconst EXPORT_WRAP_SALT = enc.encode('calimero.export-wrap.v1');\nconst DERIVE_LABEL = enc.encode('calimero.sealed.derive.v1\\0'); // prefix of every wrap's HKDF info\n\n/** Why an export was refused locally. A node's own refusal stays the transport's typed error. */\nexport type ExportErrorCode = 'BAD_ANSWER' | 'NOT_THE_FILE' | 'TAMPERED' | 'TOO_LARGE' | 'ABORTED';\n\n/** An export that failed a check here, never one the node refused; messages carry no plaintext or keys. */\nexport class ExportError extends Error {\n constructor(\n readonly code: ExportErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ExportError';\n }\n}\n\nconst sha256 = async (data: Uint8Array): Promise<Uint8Array> =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n\n/** The file id: SHA-256 over the domain, the segment count (u32 big-endian) and the ordered segment hashes. */\nexport function fileId(segments: Uint8Array[]): Promise<Uint8Array> {\n const count = new Uint8Array(4);\n new DataView(count.buffer).setUint32(0, segments.length, false);\n return sha256(concat(SEGMENT_DOMAIN, count, ...segments));\n}\n\n/** What an export wrap is bound to: the app and the file (hex id). */\nexport interface ExportWrap {\n appId: string;\n fileId: string;\n}\n\nfunction prefixed(field: string): Uint8Array {\n const bytes = enc.encode(field);\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, bytes.length, false);\n return concat(length, bytes);\n}\n\n/** Open the data key `wrapped` (`nonce || AES-256-GCM`) that the node wrapped to `recipient` for `wrap`. */\nexport async function unwrapExport(\n recipient: X25519KeyPair,\n ephemeral: Uint8Array,\n wrap: ExportWrap,\n wrapped: Uint8Array,\n): Promise<Uint8Array> {\n if (wrapped.length < NONCE_BYTES) throw new ExportError('TAMPERED', 'the wrapped key is truncated');\n const shared = await dh(recipient.privateKey, ephemeral);\n if (shared.every((b) => b === 0)) throw new ExportError('BAD_ANSWER', 'the ephemeral key is of low order');\n const info = concat(ephemeral, recipient.publicKey, prefixed(wrap.appId), prefixed(wrap.fileId));\n const ikm = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveBits']);\n const keyBytes = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: EXPORT_WRAP_SALT, info: concat(DERIVE_LABEL, info) },\n ikm,\n 256,\n );\n const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);\n let secret: ArrayBuffer;\n try {\n secret = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: wrapped.subarray(0, NONCE_BYTES) },\n key,\n wrapped.subarray(NONCE_BYTES),\n );\n } catch {\n throw new ExportError('TAMPERED', 'the wrapped key does not open');\n }\n if (secret.byteLength !== 32) throw new ExportError('TAMPERED', 'the wrapped key has the wrong length');\n return new Uint8Array(secret);\n}\n\n/**\n * Joins a file's segments in order, each checked against the list before it is\n * opened; holds at most one segment and one chunk. Output is authentic but may\n * be a prefix of the file until {@link finishExpecting} returns.\n */\nexport class SegmentReader {\n private pending: Uint8Array = new Uint8Array();\n private index = 0;\n private next = 0;\n private size = 0;\n private readonly hash = nobleSha256.create();\n\n private constructor(\n private readonly key: CryptoKey,\n private readonly segments: string[],\n ) {}\n\n static async create(dataKey: Uint8Array, segments: Uint8Array[]): Promise<SegmentReader> {\n const key = await crypto.subtle.importKey('raw', dataKey, 'AES-GCM', false, ['decrypt']);\n return new SegmentReader(key, segments.map(hex));\n }\n\n /** Take the next segment; `emit` gets the plaintext of every chunk it completes. */\n async push(segment: Uint8Array, emit: (plaintext: Uint8Array) => Promise<void> | void): Promise<void> {\n const want = this.segments[this.next];\n if (want === undefined) throw new ExportError('TAMPERED', `the file has no segment ${this.next}`);\n if (this.next + 1 < this.segments.length && segment.length !== SEGMENT_BYTES) {\n throw new ExportError('TAMPERED', `segment ${this.next} is not a whole segment`);\n }\n if (hex(await sha256(segment)) !== want) {\n throw new ExportError('TAMPERED', `segment ${this.next} is not the one the file lists`);\n }\n this.next += 1;\n // Bytes past a full chunk prove it was not the last, so one chunk is always held back.\n const data = concat(this.pending, segment);\n let at = 0;\n while (data.length - at > SEALED_CHUNK_BYTES) {\n await emit(await this.open(data.subarray(at, at + SEALED_CHUNK_BYTES), false));\n at += SEALED_CHUNK_BYTES;\n }\n this.pending = data.slice(at);\n }\n\n /** Open the last chunk and check the whole plaintext's size and SHA-256: GCM does not commit to its key. */\n async finishExpecting(size: number, sha256Hex: string): Promise<Uint8Array> {\n if (this.next !== this.segments.length) throw new ExportError('TAMPERED', 'the file is missing segments');\n if (this.pending.length < TAG_BYTES) throw new ExportError('TAMPERED', 'the file is truncated');\n const last = await this.open(this.pending, true);\n if (this.size !== size || hex(this.hash.digest()) !== sha256Hex) {\n throw new ExportError('TAMPERED', 'the file is not the one that was sealed');\n }\n return last;\n }\n\n private async open(chunk: Uint8Array, last: boolean): Promise<Uint8Array> {\n const iv = new Uint8Array(NONCE_BYTES);\n new DataView(iv.buffer).setBigUint64(4, BigInt(this.index), false);\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv, additionalData: concat(AAD_PREFIX, new Uint8Array([last ? 1 : 0])) },\n this.key,\n chunk,\n ),\n );\n } catch {\n throw new ExportError(\n 'TAMPERED',\n `chunk ${this.index} does not open: the file is altered, truncated or under another key`,\n );\n }\n this.hash.update(plain);\n this.size += plain.length;\n this.index += 1;\n return plain;\n }\n}\n", "/**\n * Downloading a sealed file, as core's `Client::export_file_to` does: the node\n * answers only ciphertext and the file's data key wrapped to a key made here\n * for this call, and nothing it says is believed until it checks out.\n */\n\nimport { concat, fromHex, fromHexUnsized, hex } from '../crypto/internal.js';\nimport { ExportError, SEGMENT_BYTES, SegmentReader, fileId, unwrapExport } from '../sealed/file.js';\nimport { x25519KeyPair } from '../sealed/noise.js';\nimport { routePath, type Transport } from '../runtime/transport.js';\n\nexport { ExportError, type ExportErrorCode } from '../sealed/file.js';\n\n/** Where an export writes the plaintext, in order. A `WritableStreamDefaultWriter` fits. */\nexport interface FileSink {\n write(chunk: Uint8Array): Promise<void> | void;\n}\n\n/** What an export wrote, as proven against the file's mark. */\nexport interface ExportedFile {\n size: number;\n /** SHA-256 of the plaintext, hex. */\n sha256: string;\n}\n\ntype ExportTransport = Pick<Transport, 'json' | 'request'>;\n\nfunction hexField(value: unknown, label: string, bytes?: number): Uint8Array {\n if (typeof value !== 'string') throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);\n try {\n return bytes === undefined ? fromHexUnsized(value, label) : fromHex(value, label, bytes);\n } catch {\n throw new ExportError('BAD_ANSWER', `the node answered a bad ${label}`);\n }\n}\n\n/** The answer's fields, checked for shape; whether they name the requested file is checked after. */\nfunction checked(answer: unknown) {\n const a = answer as Record<string, unknown> | null;\n if (typeof a !== 'object' || a === null) throw new ExportError('BAD_ANSWER', 'the node answered a bad export');\n if (typeof a.app !== 'string') throw new ExportError('BAD_ANSWER', 'the node answered a bad app');\n if (typeof a.size !== 'number' || !Number.isSafeInteger(a.size) || a.size < 0) {\n throw new ExportError('BAD_ANSWER', 'the node answered a bad size');\n }\n if (!Array.isArray(a.segments)) throw new ExportError('BAD_ANSWER', 'the node answered a bad segment list');\n return {\n app: a.app,\n size: a.size,\n named: hexField(a.id, 'file id', 32),\n segments: a.segments.map((h) => hexField(h, 'segment hash', 32)),\n sha256: hex(hexField(a.sha256, 'sha256', 32)),\n ephemeral: hexField(a.ephemeral, 'ephemeral key', 32),\n wrapped: hexField(a.wrapped, 'wrapped key'),\n };\n}\n\nconst aborted = () => new ExportError('ABORTED', 'the export was aborted');\n\n/** A segment's bytes, refusing one longer than a whole segment before buffering it, and stopping on `signal`. */\nasync function readSegment(response: Response, signal?: AbortSignal): Promise<Uint8Array> {\n const declared = Number(response.headers.get('content-length'));\n if (Number.isFinite(declared) && declared > SEGMENT_BYTES) {\n await response.body?.cancel();\n throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');\n }\n if (!response.body) return new Uint8Array();\n const reader = response.body.getReader();\n const stop = () => void reader.cancel();\n signal?.addEventListener('abort', stop);\n const parts: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > SEGMENT_BYTES) {\n await reader.cancel();\n throw new ExportError('TOO_LARGE', 'a segment is longer than a whole segment');\n }\n parts.push(value);\n }\n } finally {\n signal?.removeEventListener('abort', stop);\n }\n if (signal?.aborted) throw aborted();\n return concat(...parts);\n}\n\n/**\n * Write the plaintext of sealed file `id` (64 hex) of app `app` to `sink`, one\n * segment at a time. Each segment is checked against its hash before it is\n * opened, and the segment list, size and plaintext hash against the file's id\n * and mark at the end. On rejection, discard what `sink` received: it is\n * authentic but may be a prefix of the file. A failed check is an\n * {@link ExportError}; a refusal by the node is the transport's own error.\n * `recipientSecret` pins the export key, for the published vectors only.\n */\nexport async function exportFileTo(\n transport: ExportTransport,\n app: string,\n id: string,\n sink: FileSink,\n signal?: AbortSignal,\n recipientSecret?: Uint8Array,\n): Promise<ExportedFile> {\n try {\n return await exportChecked(transport, app, id, sink, signal, recipientSecret);\n } catch (error) {\n if (signal?.aborted && !(error instanceof ExportError)) throw aborted();\n throw error;\n }\n}\n\nasync function exportChecked(\n transport: ExportTransport,\n app: string,\n id: string,\n sink: FileSink,\n signal?: AbortSignal,\n recipientSecret?: Uint8Array,\n): Promise<ExportedFile> {\n const recipient = await x25519KeyPair(recipientSecret);\n // shortcut: not in the generated routes until the next openapi sync; they move there then.\n const answer = checked(\n await transport.json('POST', routePath('apps/{app}/files/{id}/export', { app, id }), {\n body: { recipient: hex(recipient.publicKey) },\n signal,\n }),\n );\n const { segments, named } = answer;\n if (segments.length === 0 || hex(await fileId(segments)) !== hex(named) || hex(named) !== id) {\n throw new ExportError('NOT_THE_FILE', `the node answered segments that are not the file ${id}`);\n }\n const dataKey = await unwrapExport(recipient, answer.ephemeral, { appId: answer.app, fileId: id }, answer.wrapped);\n const reader = await SegmentReader.create(dataKey, segments);\n for (let k = 0; k < segments.length; k += 1) {\n if (signal?.aborted) throw aborted();\n const response = await transport.request('GET', routePath('apps/{app}/files/{id}/segments/{k}', { app, id, k }), {\n signal,\n });\n await reader.push(await readSegment(response, signal), (chunk) => sink.write(chunk));\n }\n const last = await reader.finishExpecting(answer.size, answer.sha256);\n if (last.length > 0) await sink.write(last);\n return { size: answer.size, sha256: answer.sha256 };\n}\n\n/** The plaintext of sealed file `id` of app `app`, in memory. Prefer {@link exportFileTo} for a large file. */\nexport async function exportFile(\n transport: ExportTransport,\n app: string,\n id: string,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n const chunks: Uint8Array[] = [];\n await exportFileTo(transport, app, id, { write: (chunk) => void chunks.push(chunk) }, signal);\n return concat(...chunks);\n}\n", "/**\n * An organization's recovery key (core `docs/specs/org-recovery.md`): an\n * Ed25519 key whose 32-byte seed the owner keeps offline. The node stores only\n * the public half; the seed signs, here and never on a node, the statement\n * that hands the organization to one account. Byte-for-byte core's\n * `calimero_identity::recovery`.\n */\n\nimport { b64url } from '../runtime/passkey.js';\n\n/** What a recovery signature covers before the organization, the account and the nonce. */\nexport const RECOVERY_DOMAIN = 'calimero.org-recovery.v1\\0';\n\n/** The longest nonce a recovery carries, in bytes (core's `MAX_RECOVERY_NONCE_BYTES`). */\nexport const MAX_RECOVERY_NONCE_BYTES = 64;\n\n/** PKCS#8 prefix of an Ed25519 private key; the 32-byte seed follows. */\nconst PKCS8_ED25519 = Uint8Array.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,\n]);\n\n/** A new random seed. */\nexport function newRecoverySeed(): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(32));\n}\n\n/** The seed as people write it down: 64 hex digits in eight groups of eight, joined by `-`. */\nexport function recoverySeedText(seed: Uint8Array): string {\n checkSeed(seed);\n const hex = Array.from(seed, (b) => b.toString(16).padStart(2, '0')).join('');\n const groups: string[] = [];\n for (let i = 0; i < hex.length; i += 8) groups.push(hex.slice(i, i + 8));\n return groups.join('-');\n}\n\n/** A seed from its written form: 64 hex digits; `-`, whitespace and case are ignored. */\nexport function parseRecoverySeed(text: string): Uint8Array {\n const digits = text.replace(/[-\\s]/g, '');\n if (!/^[0-9a-fA-F]{64}$/.test(digits)) throw new Error('a recovery seed is 64 hex digits');\n return Uint8Array.from({ length: 32 }, (_, i) => parseInt(digits.slice(2 * i, 2 * i + 2), 16));\n}\n\n/** The bytes a recovery signs: `\"calimero.org-recovery.v1\\0\" || org || 0 || account || 0 || nonce`. */\nexport function recoveryMessage(org: string, account: string, nonce: string): Uint8Array {\n return new TextEncoder().encode(`${RECOVERY_DOMAIN}${org}\\0${account}\\0${nonce}`);\n}\n\n/** The seed's public key, base64url: what the organization stores. */\nexport async function recoveryPublicKey(seed: Uint8Array): Promise<string> {\n const key = await privateKey(seed, true);\n const jwk = await crypto.subtle.exportKey('jwk', key);\n if (!jwk.x) throw new Error('this runtime cannot export an Ed25519 public key');\n return jwk.x;\n}\n\n/** The seed's signature (base64url) handing `org` to `account` under `nonce`. */\nexport async function signRecovery(seed: Uint8Array, org: string, account: string, nonce: string): Promise<string> {\n const nonceBytes = new TextEncoder().encode(nonce).length;\n if (nonceBytes === 0 || nonceBytes > MAX_RECOVERY_NONCE_BYTES) {\n throw new Error(`a recovery nonce is 1 to ${MAX_RECOVERY_NONCE_BYTES} bytes`);\n }\n const key = await privateKey(seed, false);\n const sig = await crypto.subtle.sign('Ed25519', key, buf(recoveryMessage(org, account, nonce)));\n return b64url(new Uint8Array(sig));\n}\n\nfunction checkSeed(seed: Uint8Array): void {\n if (seed.length !== 32) throw new Error('a recovery seed is 32 bytes');\n}\n\nfunction privateKey(seed: Uint8Array, extractable: boolean): Promise<CryptoKey> {\n checkSeed(seed);\n const pkcs8 = new Uint8Array(PKCS8_ED25519.length + 32);\n pkcs8.set(PKCS8_ED25519);\n pkcs8.set(seed, PKCS8_ED25519.length);\n return crypto.subtle.importKey('pkcs8', buf(pkcs8), { name: 'Ed25519' }, extractable, ['sign']);\n}\n\nconst buf = (b: Uint8Array): ArrayBuffer => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;\n", "/**\n * Release and upgrade approvals as core's node reports them, and the consent\n * page an app sends its user to when one is theirs to make.\n *\n * An app never approves in its own page. A passkey assertion is blind (the\n * authenticator shows a site name, never what the challenge commits to), so\n * the page that runs the ceremony decides what the person believes they\n * approve. The node therefore refuses every approval route to a session\n * opened on an app's frontend, and serves its own **consent page** instead:\n * the app asks for a request (`POST /consent/requests`), sends the person to\n * the page's `url` on the node's own origin, and reads the decision when the\n * page sends them back (`returnTo?request_id=\u2026&result=\u2026`) or from\n * `GET /consent/{id}/result`. See core's\n * [consent page](https://calimero-network.github.io/core/protocol/consent-page/)\n * and [governance](https://calimero-network.github.io/core/protocol/governance/).\n */\n\nimport { compareReleaseVersions } from '../sealed/release.js';\nimport type { ApiAnswer } from '../routes/types.js';\n\n// ---------------------------------------------------------------- governance\n\n/**\n * Who holds one decision on a cluster (core's `Authority`), fixed at genesis\n * and attested by every replica. `owner`: the parties around each app, with a\n * passkey (for release approvals the app's publisher, for upgrades whoever\n * its package's manifest names); `operator`: the operator, for every app.\n */\nexport type Authority = 'owner' | 'operator';\n\n/** Core's `Governance`: which side holds each decision on this cluster. */\nexport interface Governance {\n releases: Authority;\n appUpgrades: Authority;\n outbound: Authority;\n /** Who may install apps: any account (`open`, left out) or granted deployers only. */\n deployments?: 'open' | 'granted';\n /** Who grants deployers: the operator (left out) or the cluster's owner. */\n deployers?: 'operator' | 'owner';\n}\n\n// ---------------------------------------------------------------- reports\n\n/** Whose approvals a report covers: an organization's, or the account's own apps. */\nexport type ReportScope = { kind: 'account' } | { kind: 'org'; org: string };\n\n/** A bundle as a report names it: its digest, and its release where the reader may see it. */\nexport interface ReportedBundle {\n bundle: string;\n package?: string;\n version?: string;\n}\n\n/** Who made an upgrade, by kind. */\nexport type ActorKind = 'owner' | 'member' | 'operator';\n\n/** A replica's node whose runtime is older than a release needs, and what it runs: the version, or `{ before }` for a node on a release from before nodes named their runtime. */\nexport interface RuntimeShortNode {\n node: number;\n runtime: string | { before: string } | null;\n}\n\n/**\n * Why an app cannot move to the newest release it may see (core's\n * `latestBlocked`): `runtime`, a replica's node runs an older runtime than\n * the release's `minRuntimeVersion` (the upgrade would be refused `409\n * RUNTIME_TOO_OLD`); `authority`, the app's owner upgrades it and the\n * release would give its upgrades to the publisher.\n */\nexport interface LatestBlocked {\n version: string;\n reason: 'runtime' | 'authority';\n message: string;\n minRuntimeVersion?: string;\n nodes?: RuntimeShortNode[];\n}\n\n/** One app in a report. `name`, `team`, `availableVersions`, `latestReachable` and `latestBlocked` are in members' and accounts' reports only. */\nexport type ReportedApp = ApiAnswer<'org_apps'>['apps'][number];\n\n/** `GET /auth/apps` or `GET /orgs/{org}/apps`: one page. */\nexport type AppsReport = ApiAnswer<'org_apps'>;\n\n/** A page of a report: entries after the id `after`, at most `limit` (1 to {@link MAX_REPORT_PAGE}). */\nexport interface PageOptions {\n after?: string;\n limit?: number;\n}\n\n/** The most entries one page of a report answers (core's `MAX_REPORT_PAGE`). */\nexport const MAX_REPORT_PAGE = 100;\n\n/** `?after=&limit=` for a report route; `limit` outside 1 to 100 is refused before sending. */\nexport function pageQuery(page: PageOptions = {}): string {\n const q = new URLSearchParams();\n if (page.after !== undefined) q.set('after', page.after);\n if (page.limit !== undefined) {\n if (!Number.isInteger(page.limit) || page.limit < 1 || page.limit > MAX_REPORT_PAGE) {\n throw new RangeError(`limit is 1 to ${MAX_REPORT_PAGE}`);\n }\n q.set('limit', String(page.limit));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n\n// ---------------------------------------------------------------- deadlines\n\n/** A release's end-of-new-work deadline. */\nexport interface ReleaseDeadline {\n version: string;\n /** RFC 3339. */\n after: string;\n /** Unix seconds. */\n afterSecs: number;\n}\n\n/** `GET /releases`: the cluster's release rules, public inside the sealed channel. */\nexport type ReleaseRules = ApiAnswer<'releases_public'>;\n\n/** Semver order (core's `compare_versions`); text order for versions that are not semver. */\nexport function compareVersions(a: string, b: string): number {\n try {\n return compareReleaseVersions(a, b);\n } catch {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\n\n/**\n * Whether a scope whose approved set is `approved` has lost new work at `now`\n * (Unix seconds), as core's `SystemState::stalled` judges it: a release's\n * deadline has passed and the newest approved release is older. Names the\n * newest such release, since approving it lifts every one. `null` approved\n * (unrestricted) is never stalled.\n */\nexport function stalledBy(\n approved: string[] | null,\n deadlines: ReleaseDeadline[],\n now: number = Date.now() / 1000,\n): ReleaseDeadline | null {\n if (approved === null || approved.length === 0) return null;\n const newest = approved.reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));\n let stall: ReleaseDeadline | null = null;\n for (const d of deadlines) {\n if (d.afterSecs <= now && compareVersions(newest, d.version) < 0) {\n if (stall === null || compareVersions(d.version, stall.version) > 0) stall = d;\n }\n }\n return stall;\n}\n\n// ---------------------------------------------------------------- publishers\n\n/**\n * The text a package signing key signs to bind it to `org` as its publisher\n * (core's `system::publisher_binding_message`). Take `cluster` and\n * `generation` from `client.public.publisherBinding`; sign the UTF-8\n * bytes with the key's Ed25519 secret and send\n * `client.orgs.publisher`.\n */\nexport function publisherBindingMessage(cluster: string, org: string, signerId: string, generation: number): string {\n return `calimero-publisher-binding/v1\\n${cluster}\\n${org}\\n${signerId}\\n${generation}`;\n}\n\n/** {@link publisherBindingMessage} as the bytes to sign. */\nexport function publisherBindingBytes(cluster: string, org: string, signerId: string, generation: number): Uint8Array {\n return new TextEncoder().encode(publisherBindingMessage(cluster, org, signerId, generation));\n}\n\n// ---------------------------------------------------------------- consent page\n\n/** Whose approval a release or outbound request is for. */\nexport type ConsentScope = 'account' | { org: string };\n\n/** What the app asks its user to approve (`POST /consent/requests`). Unknown fields are refused. */\nexport type ConsentRequest =\n | {\n kind: 'release';\n scope: ConsentScope;\n /** `withdraw: true` asks to withdraw the release's approval instead of approving it. */\n subject: { version: string; withdraw?: boolean };\n /** Where the page sends the person back: the package's frontend origin, or one its manifest names. */\n returnTo: string;\n }\n | {\n kind: 'upgrade';\n subject: { app: string; toVersion: string };\n returnTo: string;\n }\n | {\n kind: 'outbound';\n scope: ConsentScope;\n /** `package`: a package-bound session's own when left out; `prefixes`: every one the latest release declares. */\n subject: { package?: string; prefixes?: string[] };\n returnTo: string;\n }\n | {\n /** A new organization, owned by whoever approves. Outcome: `{ orgId }`. */\n kind: 'createOrg';\n subject: { name: string };\n returnTo: string;\n }\n | {\n /** A new invite to `subject.org`. Outcome: `{ token }`. */\n kind: 'createInvite';\n subject: InviteConsentSubject;\n returnTo: string;\n }\n | {\n /** Joining an organization with an invite's `token`. Outcome: `{ org }`. */\n kind: 'acceptInvite';\n subject: { token: string };\n returnTo: string;\n };\n\n/** A consent request's kind. */\nexport type ConsentKind = ConsentRequest['kind'];\n\n/** A role an invite gives (core's `Role`). */\nexport type InviteRole = 'guest' | 'member' | 'admin';\n\n/** What a `createInvite` consent request asks for. */\nexport interface InviteConsentSubject {\n org: string;\n role: InviteRole;\n /** Teams the invite joins its user to. */\n teams?: string[];\n /** How long the invite lasts, in seconds. */\n ttlSecs?: number;\n /** How many times it may be used. */\n uses?: number;\n /** Whether it gives every app of the organization. */\n allApps?: boolean;\n}\n\n/** The node's answer to a consent request: send the person to `url`. */\nexport type ConsentStarted = ApiAnswer<'consent_page_create'>;\n\n/** How {@link CalimeroClient.openConsentPage} sends the person to the page. */\nexport interface OpenConsentOptions {\n /** Sends the browser to the page's `url`; by default `window.location.assign`. */\n navigate?: (url: string) => void;\n /**\n * Runs after the node answers and before navigating, with the answer: show\n * the person `started.code` here so they can check the page shows the same.\n * Answer `false` and the page is not opened (the request stays on the node\n * until it expires).\n */\n confirm?: (started: ConsentStarted) => boolean | Promise<boolean>;\n}\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\n\n/**\n * The confirmation code the node's consent page shows for `requestId`: the\n * first 30 bits of SHA-256 of its UTF-8 bytes, big-endian, as six Crockford\n * base32 characters written `XXX-XXX` (core's consent page). Compare it with\n * {@link ConsentStarted.code} to check the node's answer.\n */\nexport async function confirmationCode(requestId: string): Promise<string> {\n const h = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(requestId)));\n const word = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0;\n let code = '';\n for (let i = 0; i < 6; i++) {\n if (i === 3) code += '-';\n code += CROCKFORD[(word >>> (27 - 5 * i)) & 31];\n }\n return code;\n}\n\n/**\n * What an approval made, by kind (`outcome` on {@link ConsentResult}, once\n * approved): `release`, `upgrade` and `outbound` make nothing. An invite's\n * `token` is a credential: keep it out of logs.\n */\nexport interface ConsentOutcomes {\n release: never;\n upgrade: never;\n outbound: never;\n createOrg: { orgId: string };\n createInvite: { token: string };\n acceptInvite: { org: string };\n}\n\n/** `GET /consent/{id}/result` for a request of kind `K`. */\nexport interface ConsentResultOf<K extends ConsentKind> {\n requestId: string;\n kind: K;\n status: 'pending' | 'approved' | 'declined';\n /** Unix seconds; `null` while pending. */\n decidedAt: number | null;\n /** What the approval made, once approved, for the kinds that make something. */\n outcome?: ConsentOutcomes[K];\n}\n\n/**\n * `GET /consent/{id}/result`, narrowed by `kind`:\n * `if (r.kind === 'createOrg') r.outcome?.orgId`. Read `outcome` only from\n * this sealed answer, never from the page's redirect, which carries none.\n *\n * Typed here by hand: the vendored OpenAPI document does not name the\n * organization kinds (core#5014) yet; the next openapi-sync brings them.\n */\nexport type ConsentResult = { [K in ConsentKind]: ConsentResultOf<K> }[ConsentKind];\n\n/**\n * What the consent page put on `returnTo` when it sent the person back, or\n * `null` when `href` carries none. A hint only (anyone can type a URL): confirm\n * with `client.consent.pageResult` before acting on it.\n */\nexport function consentReturn(href: string | URL): { requestId: string; result: 'approved' | 'declined' } | null {\n const url = typeof href === 'string' ? new URL(href) : href;\n const requestId = url.searchParams.get('request_id');\n const result = url.searchParams.get('result');\n if (!requestId || (result !== 'approved' && result !== 'declined')) return null;\n return { requestId, result };\n}\n\n/** `href` without the consent page's `request_id` and `result`. */\nexport function withoutConsentReturn(href: string | URL): string {\n const url = new URL(String(href));\n url.searchParams.delete('request_id');\n url.searchParams.delete('result');\n return url.toString();\n}\n\n/** The `sessionStorage` key {@link CalimeroClient.openConsentPage} keeps its request id under, for {@link CalimeroClient.resumeConsent}. */\nexport const CONSENT_STORAGE_KEY = 'calimero.consent';\n\n/** How {@link CalimeroClient.resumeConsent} reads the page's return. */\nexport interface ResumeConsentOptions {\n /**\n * The request this page started; by default the one\n * {@link CalimeroClient.openConsentPage} stored in this tab.\n */\n requestId?: string;\n /** The URL the page sent the person back to; by default `location.href`, whose parameters are then removed. */\n href?: string;\n}\n\n// ---------------------------------------------------------------- pending\n\n/** The public verifier for mero-tee releases (`attestation-verifier`). */\nexport const RELEASE_VERIFIER = 'https://mero-tee.vercel.app';\n\n/** A mero-tee release's notes on GitHub. */\nexport function releaseNotesUrl(version: string): string {\n return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;\n}\n\n/** The public verifier's page for a mero-tee release. */\nexport function verifyReleaseUrl(version: string): string {\n return `${RELEASE_VERIFIER}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${version}`)}`;\n}\n\n/** A mero-tee release the cluster's nodes run that the scope has not approved. */\nexport interface PendingRelease {\n version: string;\n /** How many of the cluster's nodes run it. */\n nodes: number;\n /** Whether the scope's side holds release approvals (else the operator does). */\n actionable: boolean;\n releaseNotesUrl: string;\n verifyUrl: string;\n /** Its deadline, when it carries one. */\n deadline: ReleaseDeadline | null;\n}\n\n/** An app with newer releases of its package. */\nexport interface PendingUpgrade {\n app: string;\n name: string | null;\n package: string;\n from: string;\n /**\n * The newest it can move to now (the report's `latestReachable`); when\n * none can be (`reachable: false`), or from a node that does not say, the\n * newest it may see.\n */\n to: string;\n /** Whether an upgrade to `to` would be taken now; `false`: `blocked` says why none is. */\n reachable: boolean;\n /** Why the newest release it may see is not reachable, when it is not. */\n blocked: LatestBlocked | null;\n /** Every newer release it may move to, oldest first. */\n available: string[];\n /** Whether owners hold app upgrades on this cluster; the node checks the package's own `upgrades` when asked. */\n actionable: boolean;\n}\n\n/** What {@link CalimeroClient.pendingApprovals} answers. */\nexport interface PendingApprovals {\n scope: ReportScope;\n governance: Governance;\n approvedReleases: string[] | null;\n releases: PendingRelease[];\n upgrades: PendingUpgrade[];\n /** A passed deadline has stopped new work for the scope: approve `stalledBy.version` (or newer) to lift it. */\n stalledBy: ReleaseDeadline | null;\n /** Whether anything here is the user's to approve. */\n actionable: boolean;\n}\n\n/**\n * The pending list from a scope's report pages (every page's apps\n * concatenated into `report.apps`) and the cluster's release rules.\n */\nexport function pendingApprovalsFrom(report: AppsReport, rules: ReleaseRules, now: number = Date.now() / 1000): PendingApprovals {\n const deadlineOf = (v: string) => rules.deadlines.find((d) => d.version === v) ?? null;\n const releasesActionable = report.governance.releases === 'owner';\n const upgradesActionable = report.governance.appUpgrades === 'owner';\n const releases: PendingRelease[] = report.clusterReleases\n .filter((r) => !r.approved)\n .sort((a, b) => compareVersions(b.release, a.release))\n .map((r) => ({\n version: r.release,\n nodes: r.nodes,\n actionable: releasesActionable,\n releaseNotesUrl: releaseNotesUrl(r.release),\n verifyUrl: verifyReleaseUrl(r.release),\n deadline: deadlineOf(r.release),\n }));\n const upgrades: PendingUpgrade[] = [];\n for (const a of report.apps) {\n const available = a.availableVersions ?? [];\n if (a.package === null || available.length === 0) continue;\n const latest = available[available.length - 1];\n const reachable = a.latestReachable === undefined ? latest : a.latestReachable;\n upgrades.push({\n app: a.app,\n name: a.name ?? null,\n package: a.package.package,\n from: a.package.version,\n to: reachable ?? latest,\n reachable: reachable !== null,\n blocked: a.latestBlocked ?? null,\n available,\n actionable: upgradesActionable,\n });\n }\n return {\n scope: report.scope,\n governance: report.governance,\n approvedReleases: report.approvedReleases,\n releases,\n upgrades,\n stalledBy: stalledBy(report.approvedReleases, rules.deadlines, now),\n actionable: releases.some((r) => r.actionable) || upgrades.some((u) => u.actionable),\n };\n}\n\n/**\n * The consent request that approves `version` for `scope`, or with\n * `{ withdraw: true }` withdraws its approval ({@link withdrawConsent}).\n */\nexport function releaseConsent(\n scope: ReportScope,\n version: string,\n returnTo: string,\n options: { withdraw?: boolean } = {},\n): ConsentRequest {\n return {\n kind: 'release',\n scope: scope.kind === 'org' ? { org: scope.org } : 'account',\n subject: options.withdraw ? { version, withdraw: true } : { version },\n returnTo,\n };\n}\n\n/**\n * The consent request that withdraws `version`'s approval for `scope`: nodes\n * on it are then sent none of the scope's apps' data (nothing already there\n * moves). The page fetches no measurements for it. Withdrawing the scope's\n * last approved release is refused on the page (`400 REJECTED`, the request\n * stays pending), and the page warns before.\n */\nexport function withdrawConsent(scope: ReportScope, version: string, returnTo: string): ConsentRequest {\n return releaseConsent(scope, version, returnTo, { withdraw: true });\n}\n\n/** The consent request that upgrades `app` to `toVersion`. */\nexport function upgradeConsent(app: string, toVersion: string, returnTo: string): ConsentRequest {\n return { kind: 'upgrade', subject: { app, toVersion }, returnTo };\n}\n\n/** The consent request that creates an organization named `name`; its outcome names the new `orgId`. */\nexport function createOrgConsent(name: string, returnTo: string): ConsentRequest & { kind: 'createOrg' } {\n return { kind: 'createOrg', subject: { name }, returnTo };\n}\n\n/** The consent request that creates an invite to `subject.org`; its outcome carries the invite's `token`. */\nexport function createInviteConsent(subject: InviteConsentSubject, returnTo: string): ConsentRequest & { kind: 'createInvite' } {\n return { kind: 'createInvite', subject, returnTo };\n}\n\n/** The consent request that joins the organization `token` invites to; its outcome names the `org`. */\nexport function acceptInviteConsent(token: string, returnTo: string): ConsentRequest & { kind: 'acceptInvite' } {\n return { kind: 'acceptInvite', subject: { token }, returnTo };\n}\n", "/**\n * Client for Calimero 1.0, the confidential cloud: one app = one replicated log on\n * attested nodes; this client verifies the node, seals every request to it,\n * signs people in with passkeys and machines with API keys.\n *\n * ```ts\n * const cloud = new CalimeroClient({ baseUrl, policy: { release: { minReleaseVersion: '2.3.109' } } });\n * await cloud.signIn(browserPasskey());\n * const { result } = await cloud.call(appId, 'set', { key: 'a', value: '1' });\n * ```\n */\n\nimport {\n DEFAULT_RETRY,\n NodeTransport,\n directoryTransport,\n refusal,\n retryDelayMs,\n routePath,\n type CalimeroSession,\n type NodeEvent,\n type RetryOptions,\n type HttpMethod,\n} from '../runtime/transport.js';\nimport { type NodePolicy } from '../runtime/attestation.js';\nimport { DEFAULT_DIRECTORY } from '../runtime/directory.js';\nimport { CalimeroError, LoginRequired, NotFound, OriginNotRegistered, UnavailableError, WrongRecoveryCode } from '../runtime/errors.js';\nimport { b64url, fromB64url, type PasskeyProvider } from '../runtime/passkey.js';\nimport { createRouteClient, type RouteClientOptions } from '../routes/route-client.js';\nimport type { MethodOptions } from '../routes/method.js';\nimport { createRoutes, type Routes } from '../generated/methods.js';\nimport { passkeyConfirm, type PasskeyConfirmOptions } from '../runtime/passkey.js';\n\nimport { exportFile, exportFileTo, type ExportedFile, type FileSink } from './files.js';\nimport { signRecovery } from './recovery-key.js';\nimport {\n CONSENT_STORAGE_KEY,\n confirmationCode,\n pageQuery,\n pendingApprovalsFrom,\n withoutConsentReturn,\n type AppsReport,\n type ConsentRequest,\n type ConsentResult,\n type ConsentStarted,\n type OpenConsentOptions,\n type PageOptions,\n type ResumeConsentOptions,\n type PendingApprovals,\n type ReportedApp,\n} from './approvals.js';\nimport type { ApiAnswer, ApiSchema } from '../routes/types.js';\n\nexport {\n AppError,\n ArgsTooLarge,\n BadOrigin,\n CalimeroError,\n ConfirmCancelled,\n ConfirmPromptBlocked,\n ConfirmRequired,\n IdempotencyMismatch,\n LoginRequired,\n ConsentStale,\n FeatureNotActive,\n NotFound,\n OriginNotRegistered,\n OriginTaken,\n PasskeyUnknownHere,\n QuotaExceeded,\n RecoveryNotReady,\n ReleaseDeadlineError,\n RuntimeTooOld,\n SignUpRefused,\n TrapError,\n UnavailableError,\n WrongNode,\n WrongRecoveryCode,\n errorFrom,\n} from '../runtime/errors.js';\nexport type { Committed, SignUpRefusal } from '../runtime/errors.js';\n\nexport type { CalimeroSession, NodeEvent };\n\n/** The largest file sent as one request, and the part size a session is asked for. */\nexport const FILE_PART_BYTES = 16 * 1024 * 1024;\nconst PART_RESENDS = 1; // times a part is sent again before the node is asked where the session is\nconst MAX_FAILURES = 8; // failed sends in a row, with no part accepted between them, before giving up\nconst MAX_JUMPS = 16; // PART_OUT_OF_ORDER answers followed in one session before giving up\nconst CALL_RETRIES = 8; // times beginning and completing a session are sent again while the node is unavailable\n\nexport type CallResult = ApiAnswer<'intents'>;\n\nexport type ViewResult = ApiAnswer<'views'>;\n\n/** An installed package and its releases. */\nexport type PackageInfo = ApiSchema<'Package'>;\n\n/** One app instance as `listApps` answers it. */\n\nexport type AppInfo = ApiSchema<'AppEntry'>;\n\n/**\n * An organization-wide upgrade run, as `client.orgs.upgrade`, `client.orgs.upgradeStatus` and\n * `client.orgs.upgradeRetry` answer it (core's `UpgradeRun`).\n */\nexport type UpgradeRun = ApiSchema<'UpgradeRun'>;\n\n/** One of an app's blobs: `blobId` base58 (what apps print), `id` hex. */\nexport type BlobInfo = ApiAnswer<'blob_info'>;\n\n/** A sealed file: `id` and `sha256` hex, `blobId` base58 (what apps print), `index` the log index that recorded it. */\nexport type FileInfo = ApiAnswer<'file_info'>;\n\n/** What {@link CalimeroClient.uploadFile} takes; a `Blob` is read part by part, never whole. */\nexport type FileData = Blob | Uint8Array | ArrayBuffer;\n\n/** One device present in an app (`publishPresence`); `state` hex, `null` once retracted. */\nexport type PresenceEntry = ApiAnswer<'presence_get'>['present'][number];\n\n/**\n * `GET /orgs/{org}`: the organization as the caller sees it. Besides its\n * members, teams and metadata, who may approve its releases, the package\n * signing keys it publishes, and whether a passed release deadline has\n * stopped new work on its own set.\n */\nexport type OrgInfo = ApiSchema<'Org'>;\n\n/**\n * How an organization holds its apps, derived from its app teams (core\n * `OrgMode`): `legacy` has none (its apps use organization access),\n * `standalone` has only open ones (everyone has every app), `shared` has a\n * closed one (each app lists who is in it).\n */\nexport type OrgMode = 'legacy' | 'standalone' | 'shared';\n\n/** One app team, as `GET /orgs/{org}/app-teams` lists it (`client.orgs.appTeamList`). */\nexport type AppTeam = AppTeams['appTeams'][number];\n\n/** `GET /orgs/{org}/app-teams`: the organization's mode and its app teams. A guest sees only the app teams they are in. */\nexport type AppTeams = ApiAnswer<'app_team_list'>;\n\n/** One package's app team after `client.orgs.appTeamsScope`. */\nexport type ScopedAppTeam = ApiAnswer<'app_teams_scope'>['teams'][number];\n\n/** `POST /orgs/{org}/app-teams`: the organization's mode after, and each package's team. */\nexport type ScopeAppsResult = ApiAnswer<'app_teams_scope'>;\n\n/** A pending organization invite, as `GET /orgs/{org}/invites` lists it (never its token). */\nexport type OrgInvite = ApiAnswer<'invite_list'>['invites'][number];\n\n/** `GET /orgs/{org}/teams/{team}` (`client.orgs.teamGet`). */\nexport type TeamInfo = ApiSchema<'TeamView'>;\n\n/** When a recovery started and the earliest it may finish (Unix seconds). */\nexport interface RecoveryTimes {\n startedAt: number;\n readyAt: number;\n}\n\n/** One xcall that was never delivered (core's `DeadLetter`). */\nexport type DeadLetter = ApiSchema<'DeadLetter'>;\n\n/**\n * An account or an organization, as a deployer, a deployment's owner or the\n * cluster's owner: `{ account: id }` or `{ org: id }`.\n */\nexport type Deployer = { account: string } | { org: string };\n\n/** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */\nexport function deployerKey(deployer: Deployer): string {\n return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;\n}\n\n/**\n * A package frontend's `/.well-known/calimero.json`: the package, its\n * releases, the deployments offering it and the cluster's API URLs.\n */\nexport interface FrontendManifest {\n package: string;\n versions: string[];\n deployments: Array<{ id: string; name: string; app: string; version: string }>;\n api: string[];\n}\n\n/**\n * Read the `/.well-known/calimero.json` of the frontend at `origin` (by\n * default the page's own). Served in the clear by the frontend host, like the\n * page itself: for choosing a deployment and the API URL to connect to, never\n * for trust (the client attests the node it then talks to).\n */\nexport async function frontendManifest(origin?: string, fetcher: typeof fetch = fetch): Promise<FrontendManifest> {\n const base = origin ?? (globalThis as { location?: { origin?: string } }).location?.origin;\n if (!base) throw new Error('no page origin to read the frontend manifest from; pass `origin`');\n const response = await fetcher(new URL('/.well-known/calimero.json', base).toString());\n if (!response.ok) throw await refusal(response);\n const manifest = (await response.json()) as FrontendManifest;\n return { ...manifest, deployments: manifest.deployments ?? [] };\n}\n\n/**\n * The deployment a frontend page was opened for: the node serves\n * `/d/{deployment}/` by redirecting to `/{version}/\u2026?deployment={id}`, so the\n * page creates its instances from that deployment\n * (`client.apps.create({ name, deployment, package })`). `null` when the page was\n * not opened through a deployment. `href` defaults to `window.location.href`.\n */\nexport function pageDeployment(href?: string): string | null {\n const at = href ?? (globalThis as { location?: { href?: string } }).location?.href;\n if (!at) return null;\n try {\n return new URL(at).searchParams.get('deployment') || null;\n } catch {\n return null;\n }\n}\n\n/** A recovery of an account under way (core #4844, `docs/specs/account-recovery.md`). */\nexport interface AccountRecovery {\n accountId: string;\n /** The new passkey the recovery adds when it finishes. */\n credentialId: string;\n /** When it started (Unix seconds). */\n startedAt: number;\n /** The earliest it may finish (Unix seconds): 72 hours after the start. */\n readyAt: number;\n}\n\n/** One web origin registered for a package (`GET /package-origins/{package}`). */\nexport type PackageOrigin = ApiAnswer<'origins_list'>['origins'][number];\n\n/**\n * Where a sign-up or sign-in says it runs. By default the page's origin\n * (`window.location.origin`) when it is not the origin of a node the client\n * talks to; nothing outside a browser. A string sends that origin; `null`\n * sends none (the cluster's own origins).\n */\nexport interface SignInOptions {\n origin?: string | null;\n /**\n * Closes an open passkey prompt when it aborts (a Cancel button): the\n * ceremony then rejects as a dismissed prompt does (`NotAllowedError`; in a\n * sign-up's confirmation, {@link ConfirmCancelled}). Given to the\n * {@link PasskeyProvider} as `signal`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * {@link SignInOptions} for a sign-up, and the invite it is made with: an\n * organization invite's token (the new account joins the organization at\n * the invite's role) or a cluster sign-up invite's. A cluster whose policy\n * is `invite` or `closed` (`client.deployments.signUpPublic`) needs one.\n */\nexport interface SignUpOptions extends SignInOptions {\n invite?: string;\n}\n\n/**\n * `GET /sign-up`: who may create an account on the cluster (core's sign-up\n * policy, read without a session), so a page can say \"invite only\" before\n * any passkey prompt.\n */\nexport type SignUpPolicy = ApiAnswer<'sign_up_public'>;\n\n/** {@link PageOptions} as a generated route's query, checked as {@link pageQuery} checks them. */\nfunction pageParams(page: PageOptions): { after?: string; limit?: number } {\n pageQuery(page);\n return { after: page.after, limit: page.limit };\n}\n\n/** Bytes as lower-case hex. */\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * A presence state as `POST /apps/{app}/presence` takes it: the bytes as\n * lower-case hex, or `null`, which retracts this device's entry\n * (`client.apps.presencePublish({ app, seq, state: presenceState(bytes) })`).\n */\nexport function presenceState(state: Uint8Array | null): string | null {\n return state === null ? null : toHex(state);\n}\n\nexport { DEFAULT_RETRY, retryDelayMs };\nexport type { RetryOptions };\n\nexport interface CalimeroClientOptions {\n /** One node of the cluster: the one the client talks to first. */\n baseUrl: string;\n /**\n * Other nodes of the same cluster, in the order to move to them when a node\n * answers `421 WRONG_NODE` (its release may not serve this account), or stays\n * unavailable to a call or a view through all its retries. Each is attested\n * under the same `policy` before anything is sent to it. Without them a `421`\n * reaches the caller as {@link WrongNode}.\n */\n nodes?: string[];\n policy: NodePolicy;\n /** Fetch that carries attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n}\n\n/** How {@link CalimeroClient.connect} reaches a Calimero Cloud cluster by name. */\nexport interface CalimeroConnectOptions {\n /** The cluster's name, e.g. `eu-shared-1`. */\n cluster: string;\n /** What every node must attest to before anything is sent to it. */\n policy: NodePolicy;\n /** The node directory to ask. Default {@link DEFAULT_DIRECTORY}. */\n directory?: string;\n /** Try the nodes in this zone (e.g. `europe-west4-a`) first. */\n zone?: string;\n /** Fetch for the directory, attestation and envelopes. Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** How calls and views retry a 503 or a failed connection. */\n retry?: RetryOptions;\n /** Randomness for the weighted node order, in [0, 1). Defaults to `Math.random`. */\n random?: () => number;\n}\n\n/** Bytes `start` to `end` of `data`, as a view or a slice: a `Blob` is never read whole. */\nasync function readSlice(data: FileData, start: number, end: number): Promise<Uint8Array> {\n if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());\n return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);\n}\n\n/** The `next` an answer names, which cannot be past the last part. */\nfunction nextPart(answer: unknown, parts: number): number {\n const next = (answer as { next?: unknown } | undefined)?.next;\n if (typeof next === 'number' && Number.isInteger(next) && next >= 0 && next <= parts) return next;\n throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);\n}\n\nexport class CalimeroClient {\n /**\n * The runtime every route of this client is sent through\n * (`@calimero-network/mero-js/runtime`): the attested, sealed channel to each\n * node, the credential and its refresh, the `412 CONFIRM_REQUIRED` step-up,\n * D70 retries and error mapping. A route layer of its own (one generated from\n * the node's OpenAPI document, say) sends through it and shares this\n * client's session.\n */\n readonly transport: NodeTransport;\n\n /**\n * The node's routes as methods, generated from core's OpenAPI document\n * (`src/generated/methods.ts`), one group per tag. Each takes one argument\n * object (path parameters, query and body fields merged) and answers the\n * route's payload; a refusal is thrown as the typed {@link CalimeroError}.\n * A step-up or an operator signature is answered by the client's `confirm`\n * / `operatorProof`, or the call's own (`{ confirm: passkeyConfirm(passkey) }`).\n *\n * `client.apps.call({ app, method, args })`, `client.orgs.get({ org })`,\n * `client.orgs.inviteCreate({ org, role }, { confirm })`.\n */\n readonly apps: Routes['apps'];\n /** Account, session, passkey and API-key routes: `client.auth.me()`. See {@link apps}. */\n readonly auth: Routes['auth'];\n /** The consent page's routes. See {@link apps}. */\n readonly consent: Routes['consent'];\n /** Operator routes (the ops token). See {@link apps}. */\n readonly ops: Routes['ops'];\n /** Organization, member, team and invite routes. See {@link apps}. */\n readonly orgs: Routes['orgs'];\n /** Routes anyone may read: attestation, health, releases, publisher bindings. See {@link apps}. */\n readonly public: Routes['public'];\n /** Package routes (`client.packages.install({ package, version })`). See {@link apps}. */\n readonly packages: Routes['packages'];\n /**\n * Deployment, deployer and sign-up routes (`client.deployments.create({ name, owner }, { confirm })`).\n * See {@link apps}.\n */\n readonly deployments: Routes['deployments'];\n\n /**\n * A client for the Calimero Cloud cluster named `cluster`: its node list read\n * from the public node directory, those in `zone` first, each group in\n * weighted-random order. The directory only picks which nodes to try: each is\n * attested under `policy` before anything is sent to it. Throws\n * {@link DirectoryError} when the directory names no usable node.\n *\n * The list is read again in the background after a failover, and at the\n * first request once the directory's `refreshAfterSeconds` has passed.\n */\n static async connect(options: CalimeroConnectOptions, challenges: RouteClientOptions = {}): Promise<CalimeroClient> {\n const transport = await directoryTransport({ ...options, directory: options.directory ?? DEFAULT_DIRECTORY });\n return new CalimeroClient(transport, challenges);\n }\n\n /**\n * A client of the nodes `options` names, or one sending through an existing\n * `transport`. `challenges` answers the node's challenges for every\n * generated method a call's own options leave open (`confirm` a\n * `412 CONFIRM_REQUIRED`, `operatorProof` a `428 OPERATOR_SIGNATURE_REQUIRED`).\n */\n constructor(options: CalimeroClientOptions | NodeTransport, challenges: RouteClientOptions = {}) {\n this.transport = options instanceof NodeTransport ? options : new NodeTransport(options);\n const routes = createRoutes(createRouteClient(this.transport, challenges));\n this.apps = routes.apps;\n this.auth = routes.auth;\n this.consent = routes.consent;\n this.ops = routes.ops;\n this.orgs = routes.orgs;\n this.public = routes.public;\n this.packages = routes.packages;\n this.deployments = routes.deployments;\n }\n\n /** A generated method's answer, as the type this class has always answered. */\n private as<T>(result: Promise<unknown>): Promise<T> {\n return result as Promise<T>;\n }\n\n /** The options that answer a `412 CONFIRM_REQUIRED` with `passkey`, when one is given. */\n private confirmWith(passkey: PasskeyProvider | undefined, options: PasskeyConfirmOptions = {}): MethodOptions | undefined {\n return passkey ? { confirm: passkeyConfirm(passkey, options) } : undefined;\n }\n\n /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved the client on. */\n get nodeUrl(): string {\n return this.transport.nodeUrl;\n }\n\n /** Every node this client may use, in the order it moves through them. */\n get nodes(): string[] {\n return this.transport.nodes;\n }\n\n /** Authenticate every request with an API key. */\n useApiKey(key: string): void {\n this.transport.useApiKey(key);\n }\n\n useSession(session: CalimeroSession): void {\n this.transport.useSession(session);\n }\n\n get session(): CalimeroSession | undefined {\n return this.transport.session;\n }\n\n /** A JSON request through the transport, to an untyped path. */\n private json<T>(method: HttpMethod, path: string, body?: unknown): Promise<T> {\n return this.transport.json<T>(method, path, { body });\n }\n\n // ---------------------------------------------------------------- identity\n\n /**\n * Create an account with a new passkey, and sign in. The node then asks the\n * new passkey to sign the account it creates (`412 CONFIRM_REQUIRED`), so a\n * sign-up prompts twice: create, then sign. On a page whose origin is not\n * the cluster's ({@link SignInOptions}), the node makes the passkey for that\n * origin's relying party (the confirmation's `rpId` is that origin's too)\n * and binds the session to the package the origin is registered for; an\n * unregistered origin is refused with {@link OriginNotRegistered}.\n *\n * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,\n * as the node judges it on each before it spends anything; a sign-up the\n * cluster's policy refuses, or an unknown, expired or used invite, is\n * {@link SignUpRefused} (from `begin`, before any passkey is made).\n */\n async signUp(passkey: PasskeyProvider, name: string, options: SignUpOptions = {}): Promise<CalimeroSession> {\n const origin = this.pageOrigin(options);\n const invite = options.invite ? { invite: options.invite } : {};\n const begin = await this.begin<{ challengeId: string; options: Record<string, unknown> }>(\n this.auth.registerBegin({ ...origin === undefined ? { name, ...invite } : { name, origin, ...invite } }),\n origin,\n );\n const signal = options.signal;\n const registration = await (signal ? passkey.create(begin.options, { signal }) : passkey.create(begin.options));\n // The node checks the sign-up's confirmation with the user present, not\n // verified (core `api.rs`: `rp(node)`, `require_uv: false`), as it made\n // the passkey with `preferred`: asking `required` here would refuse a\n // security key without a PIN after it has made the passkey, leaving a\n // passkey with no account. The document says so\n // (`x-calimero-user-verification: preferred`), and the generated method\n // asks the passkey for it.\n const session = await this.auth.registerFinish({ challengeId: begin.challengeId, registration, ...invite }, this.confirmWith(passkey, { signal }));\n this.useSession(session);\n return session;\n }\n\n /**\n * Sign in with an existing passkey. On a page whose origin is not the\n * cluster's ({@link SignInOptions}), the assertion is made for that\n * origin's relying-party id, as the node answers it, and the session is\n * bound to the origin's package; an unregistered origin is refused with\n * {@link OriginNotRegistered}. A passkey this cluster does not know (made\n * on another cluster, or removed) is refused with {@link PasskeyUnknownHere}.\n */\n async signIn(passkey: PasskeyProvider, options: SignInOptions = {}): Promise<CalimeroSession> {\n const origin = this.pageOrigin(options);\n const begin = await this.begin<{\n challengeId: string;\n options: { challenge: string; rpId?: string; rp?: { id?: string } };\n }>(this.auth.loginBegin({ ...origin === undefined ? {} : { origin } }), origin);\n const rpId = begin.options.rpId ?? begin.options.rp?.id ?? '';\n const challenge = fromB64url(begin.options.challenge);\n const assertion = await (options.signal\n ? passkey.get(challenge, rpId, undefined, { signal: options.signal })\n : passkey.get(challenge, rpId));\n const session = await this.auth.loginFinish({ challengeId: begin.challengeId, assertion });\n this.useSession(session);\n return session;\n }\n\n /**\n * The origin a sign-up or sign-in sends: the one given, or the page's own\n * when it is not a node's origin; `undefined` for none.\n */\n private pageOrigin(options: SignInOptions): string | undefined {\n if (options.origin !== undefined) return options.origin ?? undefined;\n const page = (globalThis as { location?: { origin?: string } }).location?.origin;\n if (!page || page === 'null') return undefined;\n const nodes = new Set(\n this.transport.nodes.map((url) => {\n try {\n return new URL(url).origin;\n } catch {\n return url;\n }\n }),\n );\n return nodes.has(page) ? undefined : page;\n }\n\n /** POST a ceremony's `begin`, naming the page's `origin` in an {@link OriginNotRegistered} the node leaves it out of. */\n private async begin<T>(result: Promise<unknown>, origin: string | undefined): Promise<T> {\n try {\n return await this.as<T>(result);\n } catch (error) {\n if (error instanceof OriginNotRegistered && !error.origin && origin !== undefined) {\n throw new OriginNotRegistered(error.nodeMessage, { ...error.details, origin });\n }\n throw error;\n }\n }\n\n /**\n * Swap the refresh token for a new session, on whichever node the client\n * uses: any node of the cluster takes it. A refresh token is used once, so\n * calls made while one refresh is under way share it rather than sending the\n * same token again (which would revoke the session).\n */\n refresh(): Promise<CalimeroSession> {\n return this.transport.refresh();\n }\n\n /**\n * End this session. The client is signed out whether or not the node\n * answers: the revoke (`POST /auth/logout`) is attempted, and its failure\n * (the node unreachable, say) is thrown after the session is dropped, so a\n * caller can say the server may still hold it, but no request after this\n * one carries its token.\n */\n async signOut(): Promise<void> {\n await this.signingOut(this.auth.logout());\n }\n\n /**\n * End every session of the signed-in account, on every device, this one\n * too. Like {@link signOut}, this client is signed out even when the\n * request fails, and the failure is thrown.\n */\n async signOutEverywhere(): Promise<void> {\n await this.signingOut(this.auth.logoutAll());\n }\n\n private async signingOut(result: Promise<unknown>): Promise<void> {\n try {\n await result;\n } finally {\n this.transport.signOut();\n }\n }\n\n /**\n * Add another passkey (another device, `passkey`) to the signed-in account;\n * answers its credential id. The node asks for the approval of a passkey\n * the account already has (`412 CONFIRM_REQUIRED`, never the new one),\n * which `approver` gives.\n */\n async addPasskey(passkey: PasskeyProvider, approver: PasskeyProvider): Promise<string> {\n const begin = await this.as<{ challengeId: string; options: Record<string, unknown> }>(this.auth.passkeyAddBegin());\n const registration = await passkey.create(begin.options);\n const { credentialId } = await this.auth.passkeyAddFinish({ challengeId: begin.challengeId, registration }, this.confirmWith(approver));\n return credentialId;\n }\n\n // ---------------------------------------------------------------- account recovery\n //\n // core #4844 (`docs/specs/account-recovery.md`): a recovery code, made with\n // a passkey and shown once, lets someone who lost every passkey register a\n // new one; it is added, and the account signed in, 72 hours later unless a\n // passkey the account still has cancels it first.\n\n /**\n * Signed out: start recovering the account `code` names. `passkey` makes a\n * new passkey for it (the browser's create prompt, user verified); the\n * node spends the code and keeps the passkey as pending. Nothing is added\n * and no session opens: finish with {@link finishAccountRecovery} at\n * `readyAt`. A code the cluster does not hold (mistyped, replaced or\n * spent) is {@link WrongRecoveryCode}; an account with a recovery already\n * under way `409 RECOVERY_PENDING`.\n */\n async startAccountRecovery(code: string, passkey: PasskeyProvider): Promise<AccountRecovery> {\n try {\n const begin = await this.as<{ challengeId: string; options: Record<string, unknown> }>(this.auth.accountRecoveryBegin({ code }));\n const registration = await passkey.create(begin.options);\n return await this.auth.accountRecoveryStart({ challengeId: begin.challengeId, code, registration });\n } catch (error) {\n if (error instanceof LoginRequired) throw new WrongRecoveryCode(error.message.replace(/^401 UNAUTHENTICATED: /, ''), error.details);\n throw error;\n }\n }\n\n /**\n * Signed out, once the delay passed: finish the recovery with the passkey\n * it registered (`passkey` signs the node's sign-in challenge). The passkey\n * joins the account, every other session of the account ends, and this\n * client is signed in. `accountId` (from the start) lets the node refuse\n * early and offer only that passkey; before `readyAt` it is\n * {@link RecoveryNotReady}, with no recovery under way {@link NotFound}.\n */\n async finishAccountRecovery(passkey: PasskeyProvider, accountId?: string): Promise<CalimeroSession> {\n const session = await this.auth.accountRecoveryFinish({ ...accountId ? { accountId } : {} }, this.confirmWith(passkey));\n this.useSession(session);\n return session;\n }\n\n // ---------------------------------------------------------------- apps\n\n /** One of `app`'s blobs, by id (base58 or hex). */\n async downloadBlob(app: string, id: string): Promise<Uint8Array> {\n return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());\n }\n\n /**\n * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,\n * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of\n * the file. A failed check is an `ExportError`; `signal` aborts the download.\n */\n exportFileTo(app: string, id: string, sink: FileSink, signal?: AbortSignal): Promise<ExportedFile> {\n return exportFileTo(this.transport, app, id, sink, signal);\n }\n\n /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */\n exportFile(app: string, id: string, signal?: AbortSignal): Promise<Uint8Array> {\n return exportFile(this.transport, app, id, signal);\n }\n\n /**\n * Download a component app's blob with a grant one of its runs handed out\n * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the\n * permission. A bad or expired grant answers `NotFound`, as a missing blob.\n */\n async downloadBlobGranted(app: string, id: string, grant: string): Promise<Uint8Array> {\n return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());\n }\n\n /**\n * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.\n * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new\n * file for each, so one that may have reached it is never repeated); a larger file\n * is a session of parts, each sent again after a dropped connection or a `503`.\n * A session the node lost is begun again once; any other failure aborts it.\n * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.\n */\n async uploadFile(app: string, data: FileData): Promise<FileInfo> {\n const size = data instanceof Blob ? data.size : data.byteLength;\n if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });\n try {\n return await this.uploadSession(app, data, size);\n } catch (error) {\n if (!(error instanceof CalimeroError) || error.code !== 'UPLOAD_UNKNOWN') throw error;\n return this.uploadSession(app, data, size);\n }\n }\n\n /** Begin a session, send its parts and complete it, aborting it if that fails for good. */\n private async uploadSession(app: string, data: FileData, size: number): Promise<FileInfo> {\n const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));\n const { uploadId: upload, partBytes, parts } = begin;\n if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {\n throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);\n }\n try {\n await this.sendParts(app, upload, data, size, partBytes, parts);\n return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));\n } catch (error) {\n if (!(error instanceof CalimeroError && error.code === 'UPLOAD_UNKNOWN')) await this.apps.uploadAbort({ app, upload }).catch(() => undefined);\n throw error;\n }\n }\n\n /** Send every part, in order, from wherever the node says the session is. */\n private async sendParts(app: string, upload: string, data: FileData, size: number, partBytes: number, parts: number): Promise<void> {\n let [next, failures, jumps] = [0, 0, 0];\n while (next < parts) {\n try {\n const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));\n next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);\n failures = 0;\n continue;\n } catch (error) {\n if (error instanceof CalimeroError && error.code === 'PART_OUT_OF_ORDER') {\n jumps += 1;\n if (jumps > MAX_JUMPS) throw error;\n next = nextPart(error.details, parts);\n continue;\n }\n if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));\n if (failures > PART_RESENDS) {\n try {\n const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);\n if (at > next) failures = 0;\n next = at;\n } catch (asked) {\n if (!this.isTransient(asked)) throw asked;\n }\n }\n }\n }\n }\n\n /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */\n private async untilAvailable<T>(send: () => Promise<T>): Promise<T> {\n for (let retry = 0; ; retry++) {\n try {\n return await send();\n } catch (error) {\n if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));\n }\n }\n }\n\n /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */\n private isTransient(error: unknown): boolean {\n return error instanceof UnavailableError || this.transport.isNetworkFailure(error);\n }\n\n // ---------------------------------------------------------------- packages\n\n // ---------------------------------------------------------------- app instances\n\n /** Committed events from index `from`, then live, until `signal` aborts. */\n events(app: string, from = 0, signal?: AbortSignal): AsyncGenerator<NodeEvent> {\n return this.transport.events(routePath('apps/{app}/events', { app }), { query: { from }, signal });\n }\n\n // ---------------------------------------------------------------- presence\n\n /**\n * Presence as a stream until `signal` aborts: a `snapshot` event (`data` the\n * entries present), then a `presence` event (`data` one entry) per change.\n */\n presenceStream(app: string, signal?: AbortSignal): AsyncGenerator<NodeEvent> {\n return this.transport.events(routePath('apps/{app}/presence/stream', { app }), { signal });\n }\n\n // ---------------------------------------------------------------- aliases\n\n // ---------------------------------------------------------------- organizations\n\n /**\n * Start handing `org` to the signed-in account with the recovery seed,\n * which signs here and never leaves this process. Finish with\n * `client.orgs.recoveryFinish` once `readyAt` has passed; until then the owner may\n * cancel. A wrong seed (or no organization, or none set) is a `403`.\n */\n async startRecovery(org: string, seed: Uint8Array): Promise<RecoveryTimes> {\n const account = (await this.auth.me()).accountId as string;\n const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)));\n const signature = await signRecovery(seed, org, account, nonce);\n return this.orgs.recoveryStart({ org, nonce, signature });\n }\n\n // ---------------------------------------------------------------- approvals\n\n /** The report of a scope's apps (`GET /orgs/{org}/apps`, or with `org` `null` the account's own, `GET /auth/apps`), every page, with the apps of all of them in `apps`. */\n async appsReportAll(org: string | null): Promise<AppsReport> {\n const report = (page: PageOptions = {}) =>\n org === null ? this.auth.accountApps(pageParams(page)) : this.orgs.apps({ org, ...pageParams(page) });\n const first = await report();\n const apps: ReportedApp[] = [...first.apps];\n let next = first.next;\n while (next !== null) {\n const page = await report({ after: next });\n apps.push(...page.apps);\n next = page.next;\n }\n return { ...first, apps, next: null };\n }\n\n /**\n * What waits for a decision in a scope (`org`, or the account's own apps\n * with `null`): mero-tee releases the cluster's nodes run that the scope has\n * not approved, apps with newer releases of their package, and whether a\n * passed deadline stops new work. Read over the sealed channel; act on an\n * item by sending the user to the consent page (`client.consent.pageCreate`,\n * `releaseConsent`, `upgradeConsent`).\n */\n async pendingApprovals(org: string | null = null): Promise<PendingApprovals> {\n const [report, rules] = await Promise.all([this.appsReportAll(org), this.public.releasesPublic()]);\n return pendingApprovalsFrom(report, rules);\n }\n\n /**\n * `client.consent.pageCreate`, then send the browser to the consent page\n * (`navigate`, by default `window.location.assign`). Pass `navigate` itself\n * or {@link OpenConsentOptions}, whose `confirm` runs first with the node's\n * answer so the app can show the person its `code`; when it answers `false`\n * the page is not opened. When the node sends a `code` that is not\n * {@link confirmationCode} of `requestId`, it throws `CalimeroError`\n * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request\n * once `navigate` returns (or `confirm` declines): with a popup\n * (`url => window.open(url)`), poll it with {@link waitForConsent}.\n * Before navigating it keeps `requestId` in `sessionStorage` (where there\n * is one), for {@link resumeConsent} when the page sends the person back.\n */\n async openConsentPage(\n request: ConsentRequest,\n navigateOrOptions: ((url: string) => void) | OpenConsentOptions = {},\n ): Promise<ConsentStarted> {\n const options = typeof navigateOrOptions === 'function' ? { navigate: navigateOrOptions } : navigateOrOptions;\n const navigate =\n options.navigate ??\n ((url: string) => {\n const w = (globalThis as { window?: { location: { assign(url: string): void } } }).window;\n if (!w) throw new Error('no window to open the consent page in; pass `navigate`');\n w.location.assign(url);\n });\n // The organization kinds (core#5014) are typed by hand in approvals.ts\n // until the vendored OpenAPI document names them.\n const started = await this.consent.pageCreate({ body: request as Parameters<Routes['consent']['pageCreate']>[0]['body'] });\n if (started.code !== undefined) {\n const expected = await confirmationCode(started.requestId);\n if (started.code !== expected) {\n throw new CalimeroError(200, 'CONSENT_CODE_MISMATCH', 'the consent page code does not match the request', {\n requestId: started.requestId,\n code: started.code,\n expected,\n });\n }\n }\n if (options.confirm && !(await options.confirm(started))) return started;\n try {\n consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);\n } catch {\n // No storage here: pass `requestId` to `resumeConsent`.\n }\n navigate(started.url);\n return started;\n }\n\n /**\n * On the page the consent page sent the person back to\n * (`returnTo?request_id=\u2026&result=\u2026`): the decision on the request this page\n * started, read from the node (`GET /consent/{id}/result`), never from the\n * URL. `null` when the URL carries no `request_id`. The request is\n * `options.requestId`, or the one {@link openConsentPage} stored in this\n * tab; with the default `href` (`location.href`) the parameters are then\n * removed with `history.replaceState`, and the stored id once decided.\n *\n * Throws `CalimeroError`:\n * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;\n * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;\n * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the\n * page sent the person back, a sign that another request was approved on a\n * page that was not the node's. Do not act on it;\n * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):\n * an account has one undecided request per node, and a newer one replaced\n * it, possibly on a page that was not the node's. Do not act on it either.\n *\n * The URL's `result` is never trusted: the answer's `status` is the node's.\n * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is\n * in the answer, typed by `kind`.\n */\n async resumeConsent(options: ResumeConsentOptions = {}): Promise<ConsentResult | null> {\n const g = globalThis as {\n location?: { href: string };\n history?: { state: unknown; replaceState(state: unknown, unused: string, url?: string): void };\n };\n const href = options.href ?? g.location?.href;\n if (href === undefined) throw new Error('no page to read the consent return from; pass `href`');\n const url = new URL(href);\n const returned = url.searchParams.get('request_id');\n if (!returned) return null;\n if (options.href === undefined && g.history) g.history.replaceState(g.history.state, '', withoutConsentReturn(url));\n\n let ownId = options.requestId;\n if (ownId === undefined) {\n try {\n ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? undefined;\n } catch {\n ownId = undefined;\n }\n }\n if (!ownId) {\n throw new CalimeroError(200, 'CONSENT_NOT_STARTED', 'this page started no consent request', { returned });\n }\n if (returned !== ownId) {\n throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the consent page returned another request than this page started', {\n requestId: ownId,\n returned,\n });\n }\n let result: ConsentResult;\n try {\n result = (await this.consent.pageResult({ request: ownId })) as ConsentResult;\n } catch (e) {\n // One undecided request per account per node: a newer one replaced\n // this page's, which then answers 404, perhaps swapped on a forged page.\n if (e instanceof NotFound) {\n forgetConsent(ownId);\n throw new CalimeroError(404, 'CONSENT_REPLACED', \"this page's consent request was replaced by a newer one\", {\n requestId: ownId,\n });\n }\n throw e;\n }\n if (result.requestId !== ownId) {\n throw new CalimeroError(200, 'CONSENT_REQUEST_MISMATCH', 'the node answered another request', { requestId: ownId, returned: result.requestId });\n }\n if (result.status === 'pending') {\n throw new CalimeroError(200, 'CONSENT_NOT_DECIDED', 'the consent page returned, but this request is still pending', {\n requestId: ownId,\n });\n }\n forgetConsent(ownId);\n return result;\n }\n\n /**\n * Poll `client.consent.pageResult` until the request is decided, every\n * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)\n * passes, when it answers the last `pending` result.\n */\n async waitForConsent(\n requestId: string,\n options: { intervalMs?: number; signal?: AbortSignal; expiresAt?: number } = {},\n ): Promise<ConsentResult> {\n const interval = options.intervalMs ?? 2000;\n for (;;) {\n const result = (await this.consent.pageResult({ request: requestId })) as ConsentResult;\n if (result.status !== 'pending') return result;\n if (options.signal?.aborted) return result;\n if (options.expiresAt !== undefined && Date.now() / 1000 >= options.expiresAt) return result;\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n // ---------------------------------------------------------------- operator\n\n // ---------------------------------------------------------------- app teams\n\n // ---------------------------------------------------------------- package origins\n\n // ---------------------------------------------------------------- deployers\n\n // ---------------------------------------------------------------- deployments\n\n}\n\n/** This page's `sessionStorage`, where there is one (a sandboxed frame or a turned-off store throws). */\nfunction consentStorage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | undefined {\n try {\n return (globalThis as { sessionStorage?: Storage }).sessionStorage;\n } catch {\n return undefined;\n }\n}\n\n/** Drop the stored consent request id, when it is `requestId`. */\nfunction forgetConsent(requestId: string): void {\n try {\n const store = consentStorage();\n if (store?.getItem(CONSENT_STORAGE_KEY) === requestId) store.removeItem(CONSENT_STORAGE_KEY);\n } catch {\n // nothing to clear\n }\n}\n", "/**\n * What a member may do in an organization beyond their role, as core's\n * `caps` bits (`client.orgs.capabilities`, `client.orgs.teamSetMember`'s `capabilities`). A team's\n * lead and an organization's admin hold them all.\n */\nexport const ORG_CAPABILITIES = {\n /** Create an app in the organization (on its team, or org-wide). */\n CREATE_APP: 1 << 0,\n /** Mint invites (org-wide, or on each team the invite names). */\n INVITE_MEMBERS: 1 << 1,\n /** Inherited into open teams; denying it keeps a member out of them. */\n JOIN_OPEN_TEAMS: 1 << 2,\n /** Add and remove a team's members. */\n MANAGE_MEMBERS: 1 << 3,\n /** Upgrade the organization's apps (and, as a publisher, every instance of its `publisher` packages), start org upgrade runs, approve outbound hosts (org-wide). */\n MANAGE_APPLICATION: 1 << 4,\n /** Create a top-level team without being an admin. */\n CREATE_TEAM: 1 << 5,\n /** Delete a team, and what it holds, without being an admin. */\n DELETE_TEAM: 1 << 6,\n /** Change who may join a team (open or invite-only). */\n MANAGE_VISIBILITY: 1 << 7,\n /** Set the organization's and its teams' metadata. */\n MANAGE_METADATA: 1 << 8,\n /**\n * Approve (or withdraw) the mero-tee releases that hold the apps the\n * organization governs (those of the packages it publishes, and its own of\n * unbound packages), and bind a package signing key to it\n * (`client.orgs.publisher`). Organization-wide only. Bit 9 is left unused.\n */\n APPROVE_RELEASES: 1 << 10,\n} as const;\n\nexport type OrgCapability = keyof typeof ORG_CAPABILITIES;\n\n/** What a member holds unless an admin says otherwise. */\nexport const DEFAULT_ORG_CAPABILITIES = ORG_CAPABILITIES.JOIN_OPEN_TEAMS;\n\n/** The bitmask of `names`. */\nexport function orgCapabilities(...names: OrgCapability[]): number {\n return names.reduce((mask, name) => mask | ORG_CAPABILITIES[name], 0);\n}\n", "/**\n * ChaCha20-Poly1305 (RFC 8439), the AEAD mero-agent-gate's HPKE suite uses.\n * WebCrypto has no ChaCha20, and the SDK takes no runtime dependencies, so it\n * is written here from the RFC. Its tests check it against the RFC's vectors\n * and against Node's own implementation.\n *\n * Only for sealing a provisioning bundle once: short messages, one key per\n * message. Not constant-time in Poly1305's arithmetic (BigInt), which leaks\n * nothing here: the one-time Poly1305 key is never reused.\n */\n\nconst KEY_LEN = 32;\nconst NONCE_LEN = 12;\nconst TAG_LEN = 16;\n\nfunction rotl(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nfunction quarterRound(s: Uint32Array, a: number, b: number, c: number, d: number): void {\n s[a] = (s[a] + s[b]) >>> 0;\n s[d] = rotl(s[d] ^ s[a], 16);\n s[c] = (s[c] + s[d]) >>> 0;\n s[b] = rotl(s[b] ^ s[c], 12);\n s[a] = (s[a] + s[b]) >>> 0;\n s[d] = rotl(s[d] ^ s[a], 8);\n s[c] = (s[c] + s[d]) >>> 0;\n s[b] = rotl(s[b] ^ s[c], 7);\n}\n\nfunction u32le(bytes: Uint8Array, offset: number): number {\n return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;\n}\n\n/** One 64-byte ChaCha20 block (RFC 8439 \u00A72.3). */\nexport function chacha20Block(key: Uint8Array, counter: number, nonce: Uint8Array): Uint8Array {\n const state = new Uint32Array(16);\n state[0] = 0x61707865;\n state[1] = 0x3320646e;\n state[2] = 0x79622d32;\n state[3] = 0x6b206574;\n for (let i = 0; i < 8; i += 1) state[4 + i] = u32le(key, i * 4);\n state[12] = counter >>> 0;\n for (let i = 0; i < 3; i += 1) state[13 + i] = u32le(nonce, i * 4);\n const working = state.slice();\n for (let round = 0; round < 10; round += 1) {\n quarterRound(working, 0, 4, 8, 12);\n quarterRound(working, 1, 5, 9, 13);\n quarterRound(working, 2, 6, 10, 14);\n quarterRound(working, 3, 7, 11, 15);\n quarterRound(working, 0, 5, 10, 15);\n quarterRound(working, 1, 6, 11, 12);\n quarterRound(working, 2, 7, 8, 13);\n quarterRound(working, 3, 4, 9, 14);\n }\n const out = new Uint8Array(64);\n for (let i = 0; i < 16; i += 1) {\n const word = (working[i] + state[i]) >>> 0;\n out[i * 4] = word & 0xff;\n out[i * 4 + 1] = (word >>> 8) & 0xff;\n out[i * 4 + 2] = (word >>> 16) & 0xff;\n out[i * 4 + 3] = (word >>> 24) & 0xff;\n }\n return out;\n}\n\n/** ChaCha20 encryption from block `counter` on (RFC 8439 \u00A72.4). */\nexport function chacha20(key: Uint8Array, counter: number, nonce: Uint8Array, data: Uint8Array): Uint8Array {\n const out = new Uint8Array(data.length);\n for (let offset = 0, block = counter; offset < data.length; offset += 64, block += 1) {\n const stream = chacha20Block(key, block, nonce);\n const end = Math.min(offset + 64, data.length);\n for (let i = offset; i < end; i += 1) out[i] = data[i] ^ stream[i - offset];\n }\n return out;\n}\n\nfunction leToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i -= 1) value = (value << 8n) | BigInt(bytes[i]);\n return value;\n}\n\nconst P1305 = (1n << 130n) - 5n;\n\n/** Poly1305 over `message` with the one-time `key` (RFC 8439 \u00A72.5). */\nexport function poly1305(key: Uint8Array, message: Uint8Array): Uint8Array {\n const r = leToBigInt(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n const s = leToBigInt(key.subarray(16, 32));\n let acc = 0n;\n for (let offset = 0; offset < message.length; offset += 16) {\n const block = message.subarray(offset, Math.min(offset + 16, message.length));\n const n = leToBigInt(block) + (1n << BigInt(8 * block.length));\n acc = ((acc + n) * r) % P1305;\n }\n let tag = (acc + s) & ((1n << 128n) - 1n);\n const out = new Uint8Array(TAG_LEN);\n for (let i = 0; i < TAG_LEN; i += 1) {\n out[i] = Number(tag & 0xffn);\n tag >>= 8n;\n }\n return out;\n}\n\nfunction pad16(length: number): Uint8Array {\n return new Uint8Array((16 - (length % 16)) % 16);\n}\n\nfunction u64le(value: number): Uint8Array {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setBigUint64(0, BigInt(value), true);\n return out;\n}\n\nfunction macData(aad: Uint8Array, ciphertext: Uint8Array): Uint8Array {\n const parts = [aad, pad16(aad.length), ciphertext, pad16(ciphertext.length), u64le(aad.length), u64le(ciphertext.length)];\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction check(key: Uint8Array, nonce: Uint8Array): void {\n if (key.length !== KEY_LEN) throw new Error('ChaCha20-Poly1305 needs a 32-byte key');\n if (nonce.length !== NONCE_LEN) throw new Error('ChaCha20-Poly1305 needs a 12-byte nonce');\n}\n\n/** Seal: the ciphertext followed by its 16-byte tag (RFC 8439 \u00A72.8). */\nexport function chacha20Poly1305Seal(\n key: Uint8Array,\n nonce: Uint8Array,\n plaintext: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n): Uint8Array {\n check(key, nonce);\n const otk = chacha20Block(key, 0, nonce).subarray(0, 32);\n const ciphertext = chacha20(key, 1, nonce, plaintext);\n const tag = poly1305(otk, macData(aad, ciphertext));\n const out = new Uint8Array(ciphertext.length + TAG_LEN);\n out.set(ciphertext);\n out.set(tag, ciphertext.length);\n return out;\n}\n\n/** Open what {@link chacha20Poly1305Seal} made; throws if it was altered. */\nexport function chacha20Poly1305Open(\n key: Uint8Array,\n nonce: Uint8Array,\n sealed: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n): Uint8Array {\n check(key, nonce);\n if (sealed.length < TAG_LEN) throw new Error('The sealed message is shorter than its tag');\n const ciphertext = sealed.subarray(0, sealed.length - TAG_LEN);\n const otk = chacha20Block(key, 0, nonce).subarray(0, 32);\n const expected = poly1305(otk, macData(aad, ciphertext));\n let diff = 0;\n for (let i = 0; i < TAG_LEN; i += 1) diff |= expected[i] ^ sealed[ciphertext.length + i];\n if (diff !== 0) throw new Error('The sealed message did not authenticate');\n return chacha20(key, 1, nonce, ciphertext);\n}\n", "/**\n * RFC 9180 HPKE, the one suite and mode mero-agent-gate takes: Auth mode,\n * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20-Poly1305, single-shot\n * (one message per context, sequence number 0). Auth mode proves the sender:\n * the gate opens a bundle only under the X25519 key it names, so nobody can\n * seal in an owner's name.\n *\n * X25519 and HMAC are WebCrypto; ChaCha20-Poly1305 is ./chacha20poly1305.\n * The tests open what mero-agent-gate (Rust, the `hpke` crate) sealed, and the\n * gate opens what this seals.\n */\n\nimport { concat } from '../crypto/internal.js';\nimport { dh, x25519KeyPair } from '../sealed/noise.js';\nimport { chacha20Poly1305Open, chacha20Poly1305Seal } from './chacha20poly1305.js';\n\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0003; // ChaCha20-Poly1305\nconst MODE_AUTH = 0x02;\nconst N_SECRET = 32;\nconst N_KEY = 32;\nconst N_NONCE = 12;\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\nconst i2osp2 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);\n\nconst KEM_SUITE = concat(utf8('KEM'), i2osp2(KEM_ID));\nconst HPKE_SUITE = concat(utf8('HPKE'), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n // An empty salt is HashLen zeros (RFC 5869); WebCrypto refuses a zero-length HMAC key.\n const raw = key.length === 0 ? new Uint8Array(32) : key;\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, data));\n}\n\nasync function expand(prk: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {\n const out = new Uint8Array(length);\n let previous = new Uint8Array(0);\n for (let i = 1, offset = 0; offset < length; i += 1) {\n previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));\n out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);\n offset += previous.length;\n }\n return out;\n}\n\nfunction labeledExtract(suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array): Promise<Uint8Array> {\n return hmac(salt, concat(utf8('HPKE-v1'), suite, utf8(label), ikm));\n}\n\nfunction labeledExpand(suite: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, length: number) {\n return expand(prk, concat(i2osp2(length), utf8('HPKE-v1'), suite, utf8(label), info), length);\n}\n\nasync function extractAndExpand(dhValue: Uint8Array, kemContext: Uint8Array): Promise<Uint8Array> {\n const prk = await labeledExtract(KEM_SUITE, new Uint8Array(0), 'eae_prk', dhValue);\n return labeledExpand(KEM_SUITE, prk, 'shared_secret', kemContext, N_SECRET);\n}\n\nasync function keySchedule(sharedSecret: Uint8Array, info: Uint8Array): Promise<{ key: Uint8Array; nonce: Uint8Array }> {\n const empty = new Uint8Array(0);\n const pskIdHash = await labeledExtract(HPKE_SUITE, empty, 'psk_id_hash', empty);\n const infoHash = await labeledExtract(HPKE_SUITE, empty, 'info_hash', info);\n const context = concat(new Uint8Array([MODE_AUTH]), pskIdHash, infoHash);\n const secret = await labeledExtract(HPKE_SUITE, sharedSecret, 'secret', empty);\n return {\n key: await labeledExpand(HPKE_SUITE, secret, 'key', context, N_KEY),\n nonce: await labeledExpand(HPKE_SUITE, secret, 'base_nonce', context, N_NONCE),\n };\n}\n\nexport interface HpkeSealed {\n /** The encapsulated key: the sender's ephemeral X25519 public key. */\n enc: Uint8Array;\n ciphertext: Uint8Array;\n}\n\n/**\n * Seal `plaintext` to `recipientPublic` in Auth mode as the holder of\n * `senderSecret` (32 raw X25519 bytes). `ephemeralSecret` is for tests.\n */\nexport async function hpkeSealAuth(\n recipientPublic: Uint8Array,\n senderSecret: Uint8Array,\n info: Uint8Array,\n plaintext: Uint8Array,\n aad: Uint8Array = new Uint8Array(0),\n ephemeralSecret?: Uint8Array,\n): Promise<HpkeSealed> {\n if (recipientPublic.length !== 32) throw new Error('The recipient key is not 32 bytes of X25519');\n const ephemeral = await x25519KeyPair(ephemeralSecret);\n const sender = await x25519KeyPair(senderSecret);\n const dhValue = concat(await dh(ephemeral.privateKey, recipientPublic), await dh(sender.privateKey, recipientPublic));\n const shared = await extractAndExpand(dhValue, concat(ephemeral.publicKey, recipientPublic, sender.publicKey));\n const { key, nonce } = await keySchedule(shared, info);\n return { enc: ephemeral.publicKey, ciphertext: chacha20Poly1305Seal(key, nonce, plaintext, aad) };\n}\n\n/** Open what {@link hpkeSealAuth} (or the gate's own sealer) made, as the recipient. */\nexport async function hpkeOpenAuth(\n recipientSecret: Uint8Array,\n senderPublic: Uint8Array,\n info: Uint8Array,\n sealed: HpkeSealed,\n aad: Uint8Array = new Uint8Array(0),\n): Promise<Uint8Array> {\n const recipient = await x25519KeyPair(recipientSecret);\n const dhValue = concat(await dh(recipient.privateKey, sealed.enc), await dh(recipient.privateKey, senderPublic));\n const shared = await extractAndExpand(dhValue, concat(sealed.enc, recipient.publicKey, senderPublic));\n const { key, nonce } = await keySchedule(shared, info);\n return chacha20Poly1305Open(key, nonce, sealed.ciphertext, aad);\n}\n", "/**\n * A client for mero-agent-gate, the gate in a private agent TD (mero-tee,\n * `mero-agent-gate/`): attest an agent, claim it with your key, give it its\n * secrets sealed to the TD, and release it. It runs where the owner is (a\n * browser, a CLI), so whoever carries the requests, mdma included, sees only\n * quotes and ciphertext.\n *\n * One agent TD hosts several owners' agents, each named by an agent id. For\n * an agent the gate's quote binds, in its report data:\n *\n * `nonce \u2016 SHA-256(\"mero-agent-gate/attest/v3\" \u2016 provisioning_pub \u2016 len(id) \u2016 id \u2016 signing_pub \u2016 owner_pub)`\n *\n * (signing and owner keys 32 zero bytes while unclaimed). {@link attestAgent}\n * checks that and the quote itself before returning anything; every function\n * that sends refuses an agent whose quote names another owner.\n *\n * ```ts\n * import { verify as dcapVerify, getCollateral } from '@phala/dcap-qvl';\n *\n * const policy = await verifySignedAgentPolicy(policyJson, bundleJson, { profile: 'locked-read-only' });\n * const verifier = agentQuoteVerifier(policy, { dcapVerify, fetchCollateral: (q) => getCollateral(PCCS, q) });\n * const owner = await generateOwnerKey(); // keep owner.secret: it is the only key that can change the agent\n * const agent = await attestAgent({ gateUrl, agentId: 'a-1f2e', verifier });\n * await provisionAgent({ gateUrl, agent, ownerSecret: owner.secret, verifier, secrets: { NEAR_AI_API_KEY: key } });\n * ```\n */\n\nimport { concat, hex } from '../crypto/internal.js';\nimport { x25519KeyPair } from '../sealed/noise.js';\nimport type { VerifyTransportQuote } from '../sealed/sealed.js';\nimport { hpkeSealAuth } from './hpke.js';\n\nexport const AGENT_ATTEST_DOMAIN = 'mero-agent-gate/attest/v3';\nexport const AGENT_PROVISION_INFO_DOMAIN = 'mero-agent-gate/provision/v2';\n\nconst AGENT_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;\nconst SECRET_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;\nconst MAX_SECRETS = 64;\nconst MAX_SECRET_LEN = 64 * 1024;\n\n/** A gate's refusal, with its `error` code (`not_the_owner`, `no_free_slot`, \u2026) when it gave one. */\nexport class AgentGateError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n readonly code?: string,\n ) {\n super(message);\n this.name = 'AgentGateError';\n }\n}\n\n/** An agent's keys, once its quote passed {@link attestAgent}'s checks. */\nexport interface VerifiedAgent {\n agentId: string;\n /** Base64; secrets are sealed to it. Valid until the gate restarts. */\n provisioningPublicKey: string;\n /** Base64 Ed25519 key the agent signs with; absent while unclaimed. */\n signingPublicKey?: string;\n /** Base64 X25519 key of the owner that claimed it; absent while unclaimed. */\n ownerPublicKey?: string;\n}\n\nexport interface OwnerKey {\n /** 32 raw X25519 bytes. The only key that can provision or release the agent: keep it. */\n secret: Uint8Array;\n /** Base64 of the public half: what the gate's quote names as owner. */\n publicKey: string;\n}\n\ntype Fetch = typeof fetch;\n\nexport function validateAgentId(agentId: string): void {\n if (!AGENT_ID.test(agentId)) {\n throw new Error(`Agent id ${JSON.stringify(agentId)} must match [a-z0-9][a-z0-9-]{0,62}`);\n }\n}\n\nfunction utf8(value: string): Uint8Array {\n return new TextEncoder().encode(value);\n}\n\nfunction lengthPrefixed(agentId: string): Uint8Array {\n const id = utf8(agentId);\n return concat(new Uint8Array([id.length]), id);\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction fromBase64(value: string, label: string, length?: number): Uint8Array {\n let bytes: Uint8Array;\n try {\n bytes = Uint8Array.from(atob(value.trim()), (c) => c.charCodeAt(0));\n } catch {\n throw new Error(`${label} is not base64`);\n }\n if (length !== undefined && bytes.length !== length) throw new Error(`${label} is not ${length} bytes`);\n return bytes;\n}\n\n/** The 32 bytes after the nonce in a gate's quote for `agentId` (empty: the TD alone). */\nexport async function agentKeyBinding(\n provisioningPublic: Uint8Array,\n agentId: string,\n signingPublic?: Uint8Array,\n ownerPublic?: Uint8Array,\n): Promise<Uint8Array> {\n const zero = new Uint8Array(32);\n const data = concat(\n utf8(AGENT_ATTEST_DOMAIN),\n provisioningPublic,\n lengthPrefixed(agentId),\n signingPublic ?? zero,\n ownerPublic ?? zero,\n );\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\n/** HPKE `info` for a message to `agentId` on the gate whose provisioning key is `recipientPublic`. */\nexport function provisionInfo(recipientPublic: Uint8Array, agentId: string): Uint8Array {\n return concat(utf8(AGENT_PROVISION_INFO_DOMAIN), recipientPublic, lengthPrefixed(agentId));\n}\n\n/** A fresh owner key, made here; it never needs to leave the owner. */\nexport async function generateOwnerKey(): Promise<OwnerKey> {\n const secret = crypto.getRandomValues(new Uint8Array(32));\n return { secret, publicKey: await ownerPublicKey(secret) };\n}\n\n/** The base64 public half of an owner's X25519 secret. */\nexport async function ownerPublicKey(secret: Uint8Array): Promise<string> {\n if (secret.length !== 32) throw new Error('An owner key is 32 bytes');\n return toBase64((await x25519KeyPair(secret)).publicKey);\n}\n\nfunction url(gateUrl: string, path: string): string {\n return `${gateUrl.replace(/\\/+$/, '')}${path}`;\n}\n\nasync function postJson(fetchImpl: Fetch, target: string, body: unknown): Promise<unknown> {\n const response = await fetchImpl(target, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n let parsed: unknown = undefined;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n // Not JSON: reported below with the status.\n }\n if (!response.ok) {\n const error = parsed as { error?: string; details?: string } | undefined;\n throw new AgentGateError(\n `The gate answered ${response.status}${error?.error ? ` ${error.error}` : ''}: ${error?.details ?? text.slice(0, 200)}`,\n response.status,\n error?.error,\n );\n }\n return parsed;\n}\n\nexport interface AttestAgentOptions {\n /** The gate's base URL, or a relay of it (mdma's): only verified quotes are trusted. */\n gateUrl: string;\n /** The agent to attest; omit for the TD alone (no keys, nothing to send to). */\n agentId?: string;\n /** Checks the quote's signature, TCB, image and report data: {@link agentQuoteVerifier}. */\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\ninterface AttestResponseBody {\n quoteB64: string;\n provisioningPublicKeyB64: string;\n agentId?: string;\n signingPublicKeyB64?: string;\n ownerPublicKeyB64?: string;\n}\n\n/**\n * Ask the gate for a quote for `agentId` over a fresh nonce and verify it:\n * a genuine quote from a measured agent image, for this nonce, committing to\n * the agent id asked about and to the keys the gate names. Returns those\n * keys only once every check has passed.\n */\nexport async function attestAgent(options: AttestAgentOptions): Promise<VerifiedAgent> {\n const agentId = options.agentId ?? '';\n if (agentId) validateAgentId(agentId);\n const nonce = crypto.getRandomValues(new Uint8Array(32));\n const body = (await postJson(options.fetch ?? fetch, url(options.gateUrl, '/attest'), {\n nonceB64: toBase64(nonce),\n ...(agentId ? { agentId } : {}),\n })) as AttestResponseBody;\n if ((body?.agentId ?? '') !== agentId) {\n throw new Error(`Asked about agent ${JSON.stringify(agentId)}, the gate answered for ${JSON.stringify(body?.agentId)}`);\n }\n const provisioning = fromBase64(body.provisioningPublicKeyB64 ?? '', 'provisioningPublicKeyB64', 32);\n const signing = body.signingPublicKeyB64 ? fromBase64(body.signingPublicKeyB64, 'signingPublicKeyB64', 32) : undefined;\n const owner = body.ownerPublicKeyB64 ? fromBase64(body.ownerPublicKeyB64, 'ownerPublicKeyB64', 32) : undefined;\n if (!signing !== !owner) {\n throw new Error('A claimed agent has both a signing key and an owner; the gate named one');\n }\n // The id asked about, not the one answered: a quote for another agent fails here.\n const binding = await agentKeyBinding(provisioning, agentId, signing, owner);\n await options.verifier({ quoteB64: body.quoteB64, nonce: hex(nonce), reportDataSuffix: hex(binding) });\n return {\n agentId,\n provisioningPublicKey: toBase64(provisioning),\n ...(signing ? { signingPublicKey: toBase64(signing) } : {}),\n ...(owner ? { ownerPublicKey: toBase64(owner) } : {}),\n };\n}\n\n/** The owner key `ownerSecret` may act on `agent`: it is unclaimed, or claimed by that key. */\nexport async function checkOwner(agent: VerifiedAgent, ownerSecret: Uint8Array): Promise<string> {\n const mine = await ownerPublicKey(ownerSecret);\n if (agent.ownerPublicKey && agent.ownerPublicKey !== mine) {\n throw new AgentGateError(\n `This agent is claimed by another key (${agent.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,\n undefined,\n 'not_yours',\n );\n }\n return mine;\n}\n\nfunction validateSecrets(secrets: Record<string, string>): void {\n const names = Object.keys(secrets);\n if (names.length === 0) throw new Error('There are no secrets to provision');\n if (names.length > MAX_SECRETS) throw new Error(`At most ${MAX_SECRETS} secrets at once`);\n for (const name of names) {\n if (!SECRET_NAME.test(name)) throw new Error(`Secret name ${JSON.stringify(name)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);\n if (typeof secrets[name] !== 'string') throw new Error(`Secret ${name} is not a string`);\n if (utf8(secrets[name]).length > MAX_SECRET_LEN) throw new Error(`Secret ${name} is over ${MAX_SECRET_LEN} bytes`);\n }\n}\n\nasync function sendSealed(\n fetchImpl: Fetch,\n gateUrl: string,\n path: '/provision' | '/release',\n agent: VerifiedAgent,\n ownerSecret: Uint8Array,\n message: unknown,\n): Promise<unknown> {\n if (!agent.agentId) throw new Error('This quote names no agent; attest with the agent id');\n const mine = await checkOwner(agent, ownerSecret);\n const recipient = fromBase64(agent.provisioningPublicKey, 'provisioningPublicKey', 32);\n const sealed = await hpkeSealAuth(\n recipient,\n ownerSecret,\n provisionInfo(recipient, agent.agentId),\n utf8(JSON.stringify(message)),\n );\n return postJson(fetchImpl, url(gateUrl, path), {\n agentId: agent.agentId,\n provisioningPublicKeyB64: agent.provisioningPublicKey,\n senderPublicKeyB64: mine,\n encappedKeyB64: toBase64(sealed.enc),\n ciphertextB64: toBase64(sealed.ciphertext),\n });\n}\n\nexport interface ProvisionAgentOptions {\n gateUrl: string;\n /** What {@link attestAgent} returned for this agent, just now. */\n agent: VerifiedAgent;\n ownerSecret: Uint8Array;\n /** Name to value; a name replaces what was there, others stay. */\n secrets: Record<string, string>;\n /** The verifier `agent` was attested with: the claim is checked by a fresh quote. */\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\nexport interface ProvisionedAgent extends Required<VerifiedAgent> {\n written: string[];\n /** Whether this claimed the agent for your key. */\n claimed: boolean;\n}\n\n/**\n * Seal `secrets` to the agent as its owner and send them. The first bundle for\n * an unclaimed agent claims it for `ownerSecret`'s key. The gate's answer is\n * not taken as proof: a fresh quote must name your key as owner, and the\n * agent's signing key must not have changed.\n */\nexport async function provisionAgent(options: ProvisionAgentOptions): Promise<ProvisionedAgent> {\n validateSecrets(options.secrets);\n const fetchImpl = options.fetch ?? fetch;\n const answer = (await sendSealed(fetchImpl, options.gateUrl, '/provision', options.agent, options.ownerSecret, {\n secrets: options.secrets,\n })) as { written?: string[]; claimed?: boolean };\n const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });\n const mine = await ownerPublicKey(options.ownerSecret);\n if (after.ownerPublicKey !== mine || !after.signingPublicKey) {\n throw new AgentGateError('The gate accepted the secrets, but its quote does not name your key as owner');\n }\n if (options.agent.signingPublicKey && options.agent.signingPublicKey !== after.signingPublicKey) {\n throw new AgentGateError(\"The agent's signing key changed while provisioning\");\n }\n return {\n agentId: after.agentId,\n provisioningPublicKey: after.provisioningPublicKey,\n signingPublicKey: after.signingPublicKey,\n ownerPublicKey: mine,\n written: answer?.written ?? [],\n claimed: answer?.claimed === true,\n };\n}\n\nexport interface ReleaseAgentOptions {\n gateUrl: string;\n agent: VerifiedAgent;\n ownerSecret: Uint8Array;\n verifier: VerifyTransportQuote;\n fetch?: Fetch;\n}\n\n/**\n * Release the agent as its owner: the gate stops it and erases its claim,\n * keys, secrets and state. Checked by a fresh quote that names no owner.\n */\nexport async function releaseAgent(options: ReleaseAgentOptions): Promise<void> {\n if (!options.agent.ownerPublicKey) throw new Error('This agent is not claimed; there is nothing to release');\n const fetchImpl = options.fetch ?? fetch;\n await sendSealed(fetchImpl, options.gateUrl, '/release', options.agent, options.ownerSecret, { release: true });\n const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });\n if (after.ownerPublicKey) {\n throw new AgentGateError('The gate says it released the agent, but its quote still names an owner');\n }\n}\n", "/**\n * Which agent images to trust: a mero-kms release's signed agent allowlist,\n * `kms-agent-attestation-policy.<profile>.json`, and a quote verifier built\n * from it.\n *\n * The KMS release workflow measures the release's agent image and signs its\n * allowlist with cosign keyless, beside the rest of the release. The allowlist\n * can therefore come from anywhere (a release asset, mdma's mirror, a file in\n * the app): {@link verifySignedAgentPolicy} checks the signature here, against\n * the Sigstore trust root embedded in this package, and refuses anything else.\n */\n\nimport { verifyCosignBundle, type SignerIdentity } from '../sealed/sigstore.js';\nimport {\n PRODUCTION_PROFILE,\n createQuoteVerifier,\n type DcapCollateral,\n type DcapVerify,\n type QuoteVerifier,\n} from '../sealed/verify.js';\n\n/** The workflow that signs every mero-kms release, agent allowlists included. */\nexport const KMS_RELEASE_SIGNER: Readonly<SignerIdentity> = Object.freeze({\n identity: 'https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master',\n issuer: 'https://token.actions.githubusercontent.com',\n});\n\n/** An agent allowlist, as the KMS release publishes it. Every list must be non-empty. */\nexport interface AgentPolicy {\n schema_version?: number;\n role?: string;\n profile?: string;\n /** The mero-kms release it belongs to. */\n version?: string;\n allowed_tcb_statuses: string[];\n allowed_mrtd: string[];\n allowed_rtmr0: string[];\n allowed_rtmr1: string[];\n allowed_rtmr2: string[];\n allowed_rtmr3: string[];\n}\n\nconst LISTS = [\n 'allowed_tcb_statuses',\n 'allowed_mrtd',\n 'allowed_rtmr0',\n 'allowed_rtmr1',\n 'allowed_rtmr2',\n 'allowed_rtmr3',\n] as const;\n\nexport interface VerifySignedAgentPolicyOptions {\n /** Require this profile; defaults to `locked-read-only`, the only one whose host cannot reach in. */\n profile?: string;\n /** Require the file's `version` to be this mero-kms release. */\n expectedVersion?: string;\n /** The certificate identity required. Defaults to {@link KMS_RELEASE_SIGNER}'s. */\n identity?: string;\n /** The OIDC issuer required. Defaults to {@link KMS_RELEASE_SIGNER}'s. */\n issuer?: string;\n /**\n * The image role the allowlist must be for: `agent` (the default), or\n * `inference`, the release's `kms-inference-attestation-policy.<profile>.json`\n * for its private inference image. Both have the same shape and signer.\n */\n role?: 'agent' | 'inference';\n}\n\n/**\n * Verify an agent allowlist against its cosign bundle, as `cosign verify-blob`\n * would, and return it parsed. Rejects unless it was signed by the KMS release\n * workflow, it is an allowlist for `options.role` (default `agent`) and the profile asked\n * for, every list in it is non-empty, and `expectedVersion`, when given, is its\n * `version`.\n */\nexport async function verifySignedAgentPolicy(\n policy: string | Uint8Array,\n bundle: string | object,\n options: VerifySignedAgentPolicyOptions = {},\n): Promise<AgentPolicy> {\n const body = typeof policy === 'string' ? new TextEncoder().encode(policy) : policy;\n await verifyCosignBundle(body, bundle, {\n identity: options.identity ?? KMS_RELEASE_SIGNER.identity,\n issuer: options.issuer ?? KMS_RELEASE_SIGNER.issuer,\n });\n let parsed: AgentPolicy;\n try {\n parsed = JSON.parse(new TextDecoder().decode(body));\n } catch {\n throw new Error('The signed agent policy is not JSON');\n }\n const role = options.role ?? 'agent';\n if (parsed?.role !== role) {\n throw new Error(`The signed file is a ${JSON.stringify(parsed?.role)} policy, not an ${role} one`);\n }\n const profile = options.profile ?? PRODUCTION_PROFILE;\n if (parsed.profile !== profile) {\n throw new Error(`The signed agent policy is for the ${JSON.stringify(parsed.profile)} profile, not ${profile}`);\n }\n if (options.expectedVersion !== undefined && parsed.version !== options.expectedVersion) {\n throw new Error(`The signed agent policy is release ${JSON.stringify(parsed.version)}, not ${options.expectedVersion}`);\n }\n checkLists(parsed);\n return parsed;\n}\n\nfunction checkLists(policy: AgentPolicy): void {\n for (const list of LISTS) {\n if (!Array.isArray(policy?.[list]) || policy[list].length === 0) {\n // As the gate's own verifier: an empty list accepts nothing.\n throw new Error(`The agent policy's ${list} is empty, so no agent would be accepted`);\n }\n }\n}\n\n/** DCAP's spelling of each TCB status; the policy may use any case. */\nconst TCB_STATUSES = [\n 'UpToDate',\n 'SWHardeningNeeded',\n 'ConfigurationNeeded',\n 'ConfigurationAndSWHardeningNeeded',\n 'OutOfDate',\n 'OutOfDateConfigurationNeeded',\n];\n\nfunction tcbStatus(value: string): string {\n const found = TCB_STATUSES.find((status) => status.toLowerCase() === value.trim().toLowerCase());\n if (!found) throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(value)}`);\n return found;\n}\n\nconst register = (value: string) => value.trim().replace(/^0x/i, '');\n\nexport interface AgentQuoteVerifierOptions {\n /** `verify` from `@phala/dcap-qvl`, or anything that verifies a quote the same way. */\n dcapVerify: DcapVerify;\n /**\n * The gate sends no collateral: fetch it, e.g.\n * `(quote) => getCollateral(PHALA_PCCS_URL, quote)` from `@phala/dcap-qvl`.\n */\n fetchCollateral: (quote: Uint8Array) => Promise<DcapCollateral>;\n /** The current time in milliseconds; defaults to `Date.now`. For tests. */\n now?: () => number;\n}\n\n/**\n * A verifier for {@link attestAgent} that accepts a quote only from an agent\n * image in `policy`: its signature and collateral verify, its TCB status is\n * one the policy allows (never `Revoked`), it is not a debug TD, and each of\n * MRTD and RTMR0-3 is in the policy's list. Mock quotes never pass.\n */\nexport function agentQuoteVerifier(policy: AgentPolicy, options: AgentQuoteVerifierOptions): QuoteVerifier {\n checkLists(policy);\n return createQuoteVerifier({\n dcapVerify: options.dcapVerify,\n fetchCollateral: options.fetchCollateral,\n now: options.now,\n allowedTcbStatuses: policy.allowed_tcb_statuses.map(tcbStatus),\n allowedMrtd: policy.allowed_mrtd.map(register),\n allowedRtmr0: policy.allowed_rtmr0.map(register),\n allowedRtmr1: policy.allowed_rtmr1.map(register),\n allowedRtmr2: policy.allowed_rtmr2.map(register),\n allowedRtmr3: policy.allowed_rtmr3.map(register),\n });\n}\n", "/**\n * The recovery disk's files, as their holder's device handles them.\n *\n * A Calimero node (`merod --recovery-dir`) writes each app's backup sealed to\n * the X25519 public key of whoever upgrades the app: the operator, or the\n * app's organization or owner account. Only that key's private half opens a\n * file, and it never reaches a node. The device:\n *\n * 1. makes the key pair ({@link newBackupKeyPair}) and registers the public\n * half (`POST /orgs/{org}/backup-key` or `/auth/backup-key`, with a passkey);\n * 2. after a loss, gets the files' headers (`GET /ops/recovery-files`, through\n * the operator), checks each with {@link verifyRecoveryHeader} and opens\n * each one's data key with {@link openDataKey};\n * 3. sends those keys straight to the node, over the attested sealed channel\n * (`POST /recover/holder`, {@link holderRecoveryBody}).\n *\n * The format is core's `calimero_client::recovery`: HPKE (RFC 9180) base mode,\n * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM, `info`\n * {@link HPKE_INFO}, `aad` {@link HPKE_AAD}; the header is JSON signed by the\n * node's Ed25519 receipt key over {@link SIGNING_LABEL} and its bytes. The\n * tests open what core sealed. {@link verifyRecoveryAttestation} checks, as\n * core's `verify_attestation` does, that the signing key is an attested node's\n * receipt key: give it the quote verifier the client trusts nodes with.\n */\n\nimport { concat, fromHex, hex } from '../crypto/internal.js';\nimport { dh, x25519KeyPair } from '../sealed/noise.js';\nimport type { VerifyTransportQuote } from '../sealed/sealed.js';\n\nexport const RECOVERY_FORMAT = 1;\nexport const SIGNING_LABEL = new TextEncoder().encode('calimero.recovery-backup.v1\\0');\nexport const HPKE_INFO = new TextEncoder().encode('calimero.recovery-backup.v1');\nexport const HPKE_AAD = new TextEncoder().encode('calimero.recovery-backup.key.v1');\n\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0002; // AES-256-GCM\nconst MODE_BASE = 0x00;\n\nconst utf8 = (s: string) => new TextEncoder().encode(s);\nconst i2osp2 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);\nconst KEM_SUITE = concat(utf8('KEM'), i2osp2(KEM_ID));\nconst HPKE_SUITE = concat(utf8('HPKE'), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));\n\n/** Who holds a backup key: `{ kind: 'operator' }`, `{ kind: 'org', id }`, `{ kind: 'account', id }`. */\nexport type BackupHolder = { kind: 'operator' } | { kind: 'org'; id: string } | { kind: 'account'; id: string };\n\n/** What a recovery file's header says (core's `recovery::Header`). */\nexport interface RecoveryHeader {\n format: number;\n kind: 'app' | 'holder' | 'system' | 'code';\n holder: BackupHolder;\n cluster: string;\n app?: string;\n org?: string;\n hash?: string;\n group: number;\n index: number;\n writtenAt: number;\n merod: string;\n release: string;\n node: number;\n recipient: string;\n enc: string;\n wrappedKey: string;\n size: number;\n sha256: string;\n bodyBytes: number;\n bodySha256: string;\n signingKey: string;\n attestation: unknown;\n}\n\n/** A listed file as `GET /ops/recovery-files` answers it. */\nexport interface ListedRecoveryFile {\n name: string;\n /** The header as signed (JSON text). */\n header: string;\n /** The node's Ed25519 signature, hex. */\n signature: string;\n}\n\n/** `operator`, `org:<id>` or `account:<id>`: how routes name a holder. */\nexport function holderKey(holder: BackupHolder): string {\n return holder.kind === 'operator' ? 'operator' : `${holder.kind}:${holder.id}`;\n}\n\n/**\n * A new backup key pair: keep `secret` (32 raw bytes) off every node, offline;\n * register `publicKey` (64 hex).\n */\nexport async function newBackupKeyPair(): Promise<{ secret: Uint8Array; publicKey: string }> {\n const secret = crypto.getRandomValues(new Uint8Array(32));\n return { secret, publicKey: await backupPublicKey(secret) };\n}\n\n/** The public key (64 hex) of a backup key's secret. */\nexport async function backupPublicKey(secret: Uint8Array): Promise<string> {\n return hex((await x25519KeyPair(secret)).publicKey);\n}\n\n/**\n * Check a header against the node's signature and read it. Refuses a format\n * newer than this release reads and a signature that does not hold.\n */\nexport async function verifyRecoveryHeader(file: Pick<ListedRecoveryFile, 'header' | 'signature'>): Promise<RecoveryHeader> {\n const bytes = utf8(file.header);\n const header = JSON.parse(file.header) as RecoveryHeader;\n if (typeof header.format !== 'number' || header.format > RECOVERY_FORMAT) {\n throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);\n }\n const key = await crypto.subtle.importKey(\n 'raw',\n fromHex(header.signingKey, 'signing key', 32),\n { name: 'Ed25519' },\n false,\n ['verify'],\n );\n const ok = await crypto.subtle.verify(\n 'Ed25519',\n key,\n fromHex(file.signature, 'signature', 64),\n concat(SIGNING_LABEL, bytes),\n );\n if (!ok) throw new Error(\"the node's signature over the header does not hold\");\n return header;\n}\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n const raw = key.length === 0 ? new Uint8Array(32) : key;\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, data));\n}\n\nasync function expand(prk: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array> {\n const out = new Uint8Array(length);\n let previous = new Uint8Array(0);\n for (let i = 1, offset = 0; offset < length; i += 1) {\n previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));\n out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);\n offset += previous.length;\n }\n return out;\n}\n\nconst labeledExtract = (suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array) =>\n hmac(salt, concat(utf8('HPKE-v1'), suite, utf8(label), ikm));\n\nconst labeledExpand = (suite: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, length: number) =>\n expand(prk, concat(i2osp2(length), utf8('HPKE-v1'), suite, utf8(label), info), length);\n\n/** Open a file's data key (32 bytes) with the holder's secret: HPKE base mode. */\nexport async function openDataKey(header: RecoveryHeader, secret: Uint8Array): Promise<Uint8Array> {\n const recipient = await x25519KeyPair(secret);\n if (hex(recipient.publicKey) !== header.recipient) {\n throw new Error('this key is not the one the file was sealed to');\n }\n const enc = fromHex(header.enc, 'encapsulated key', 32);\n const dhValue = await dh(recipient.privateKey, enc);\n const empty = new Uint8Array(0);\n const prk = await labeledExtract(KEM_SUITE, empty, 'eae_prk', dhValue);\n const shared = await labeledExpand(KEM_SUITE, prk, 'shared_secret', concat(enc, recipient.publicKey), 32);\n const pskIdHash = await labeledExtract(HPKE_SUITE, empty, 'psk_id_hash', empty);\n const infoHash = await labeledExtract(HPKE_SUITE, empty, 'info_hash', HPKE_INFO);\n const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);\n const schedule = await labeledExtract(HPKE_SUITE, shared, 'secret', empty);\n const key = await labeledExpand(HPKE_SUITE, schedule, 'key', context, 32);\n const nonce = await labeledExpand(HPKE_SUITE, schedule, 'base_nonce', context, 12);\n const aes = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);\n let plain: Uint8Array;\n try {\n plain = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce, additionalData: HPKE_AAD },\n aes,\n fromHex(header.wrappedKey, 'wrapped key', 48),\n ),\n );\n } catch {\n throw new Error('this key does not open the file');\n }\n if (plain.length !== 32) throw new Error('the data key is not 32 bytes');\n return plain;\n}\n\n/** `{ file, key }`: a file and its opened data key, as the recovery routes take them. */\nexport interface OpenedRecoveryFile {\n file: string;\n key: string;\n}\n\n/**\n * The body of `POST /recover/holder` from a holder's listed files: the newest\n * `holder` file, the newest file of each app in `apps` (all of them when\n * absent) and every code file, each checked and opened with `secret`; with\n * `verifyQuote`, each one's attestation too ({@link verifyRecoveryAttestation}).\n */\nexport async function holderRecoveryBody(\n holder: BackupHolder,\n files: ListedRecoveryFile[],\n secret: Uint8Array,\n options: { apps?: string[]; verifyQuote?: VerifyTransportQuote } = {},\n): Promise<{ holder: string; slice: OpenedRecoveryFile; apps: OpenedRecoveryFile[]; code: OpenedRecoveryFile[] }> {\n const checked: { name: string; header: RecoveryHeader }[] = [];\n for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {\n const header = await verifyRecoveryHeader(f);\n if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);\n if (holderKey(header.holder) !== holderKey(holder)) {\n throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);\n }\n checked.push({ name: f.name, header });\n }\n const open = async (c: { name: string; header: RecoveryHeader }) => ({\n file: c.name,\n key: hex(await openDataKey(c.header, secret)),\n });\n const slice = checked.filter((c) => c.header.kind === 'holder').pop();\n if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);\n const newestByApp = new Map<string, { name: string; header: RecoveryHeader }>();\n for (const c of checked) {\n if (c.header.kind === 'app' && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {\n newestByApp.set(c.header.app, c);\n }\n }\n return {\n holder: holderKey(holder),\n slice: await open(slice),\n apps: await Promise.all([...newestByApp.values()].map(open)),\n code: await Promise.all(checked.filter((c) => c.header.kind === 'code').map(open)),\n };\n}\n\nasync function sha256(data: Uint8Array): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', data));\n}\n\n/** The nonce a node's recovery attestation binds (core's `recovery::attestation_nonce`), hex. */\nexport async function recoveryAttestationNonce(cluster: string, node: number): Promise<string> {\n const name = utf8(cluster);\n const len = new Uint8Array(4);\n new DataView(len.buffer).setUint32(0, name.length, false);\n const id = new Uint8Array(8);\n new DataView(id.buffer).setBigUint64(0, BigInt(node), false);\n return hex(await sha256(concat(utf8('calimero.recovery-backup.attest.v1\\0'), len, name, id)));\n}\n\n/**\n * What a receipt-key quote binds after its nonce (core's `receipt_key_binding`,\n * `receipt-key.v3`), hex: the key, the cluster's governance as the node\n * serialized it, and the cluster (u32-BE length-prefixed) and node id (u64 BE),\n * so one node's quote never stands for another node's or another cluster's.\n */\nexport async function receiptKeyBinding(\n receiptKey: Uint8Array,\n governance: unknown,\n cluster: string,\n node: number,\n): Promise<string> {\n const g = await sha256(utf8(JSON.stringify(governance)));\n const name = utf8(cluster);\n const len = new Uint8Array(4);\n new DataView(len.buffer).setUint32(0, name.length, false);\n const id = new Uint8Array(8);\n new DataView(id.buffer).setBigUint64(0, BigInt(node), false);\n return hex(await sha256(concat(utf8('calimero.tee-attest.receipt-key.v3'), receiptKey, g, len, name, id)));\n}\n\ninterface ReceiptAttestation {\n quote: string;\n nonce: string;\n cluster: string;\n node: number;\n receiptKey?: string;\n governance?: unknown;\n}\n\n/**\n * Check that the key that signed `header` is a node's receipt key, attested\n * (`purpose=receipts`) by a quote `verifyQuote` accepts: attested hardware\n * wrote the file. Rejects with the reason.\n */\nexport async function verifyRecoveryAttestation(\n header: RecoveryHeader,\n verifyQuote: VerifyTransportQuote,\n): Promise<void> {\n const doc = header.attestation as ReceiptAttestation | null;\n if (!doc || typeof doc.quote !== 'string') throw new Error('the file carries no attestation');\n if (doc.cluster !== header.cluster || doc.node !== header.node) {\n throw new Error(\"the attestation is another node's\");\n }\n if (doc.receiptKey !== header.signingKey) {\n throw new Error('the attested key is not the one that signed the file');\n }\n const nonce = await recoveryAttestationNonce(header.cluster, header.node);\n if (doc.nonce !== nonce) throw new Error('the attestation is not over the recovery nonce');\n const reportDataSuffix = await receiptKeyBinding(\n fromHex(header.signingKey, 'signing key', 32),\n doc.governance,\n header.cluster,\n header.node,\n );\n const ok = await verifyQuote({ quoteB64: doc.quote, nonce, reportDataSuffix });\n if (!ok) throw new Error('the quote was not accepted');\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AA,EACrD;AACA,MAAI,IAAI,eAAe,OAAO,YAAY;AACxC,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AACA,QAAMS,SAAQ,MAAM,yBAAyB,OAAO,SAAS,OAAO,IAAI;AACxE,MAAI,IAAI,UAAUA,OAAO,OAAM,IAAI,MAAM,gDAAgD;AACzF,QAAM,mBAAmB,MAAM;AAAA,IAC7B,QAAQ,OAAO,YAAY,eAAe,EAAE;AAAA,IAC5C,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AACA,QAAM,KAAK,MAAM,YAAY,EAAE,UAAU,IAAI,OAAO,OAAAA,QAAO,iBAAiB,CAAC;AAC7E,MAAI,CAAC,GAAI,OAAM,IAAI,MAAM,4BAA4B;AACvD;",
6
6
  "names": ["clean", "privateKey", "nonce", "url", "open", "clean", "SEQUENCE", "utf8", "register", "nonce", "fromBase64", "register", "url", "equal", "fetch", "nonce", "url", "url", "url", "fetch", "Request", "error", "url", "final", "joiner", "url", "refusal", "route", "url", "sha256", "sha256", "hex", "nonce", "buf", "url", "url", "nonce", "TAG_LEN", "nonce", "utf8", "nonce", "utf8", "fromBase64", "nonce", "TCB_STATUSES", "tcbStatus", "KEM_ID", "KDF_ID", "AEAD_ID", "utf8", "i2osp2", "KEM_SUITE", "HPKE_SUITE", "hmac", "expand", "labeledExtract", "labeledExpand", "enc", "nonce", "checked", "sha256"]
7
7
  }