@hediet/linkrpc 0.0.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.
- package/README.md +383 -0
- package/dist/chunks/_empty-crypto-Bi0tGx5K.js +8 -0
- package/dist/chunks/boundedTrafficSubscription-1L592xc7.js +1126 -0
- package/dist/chunks/boundedTrafficSubscription-1L592xc7.js.map +1 -0
- package/dist/chunks/hub.interfaces-BzWfsVT2.js +526 -0
- package/dist/chunks/hub.interfaces-BzWfsVT2.js.map +1 -0
- package/dist/chunks/hubAccess-DwTZPiI8.d.ts +79 -0
- package/dist/chunks/hubAccess-DwTZPiI8.d.ts.map +1 -0
- package/dist/chunks/hubFacade-CQflVkVC.js +85 -0
- package/dist/chunks/hubFacade-CQflVkVC.js.map +1 -0
- package/dist/chunks/hubFacade-Dkgw2pTi.d.ts +101 -0
- package/dist/chunks/hubFacade-Dkgw2pTi.d.ts.map +1 -0
- package/dist/chunks/linkRpcConnection-CtlQmetO.d.ts +3623 -0
- package/dist/chunks/linkRpcConnection-CtlQmetO.d.ts.map +1 -0
- package/dist/chunks/rolldown-runtime-4LSo1kEK.js +17 -0
- package/dist/chunks/src-D3NUIwyo.js +7795 -0
- package/dist/chunks/src-D3NUIwyo.js.map +1 -0
- package/dist/hub/client/index.d.ts +50 -0
- package/dist/hub/client/index.d.ts.map +1 -0
- package/dist/hub/client/index.js +97 -0
- package/dist/hub/client/index.js.map +1 -0
- package/dist/hub/common/index.d.ts +1189 -0
- package/dist/hub/common/index.d.ts.map +1 -0
- package/dist/hub/common/index.js +267 -0
- package/dist/hub/common/index.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/inspection/index.d.ts +66 -0
- package/dist/inspection/index.d.ts.map +1 -0
- package/dist/inspection/index.js +6 -0
- package/dist/node.d.ts +548 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +1087 -0
- package/dist/node.js.map +1 -0
- package/dist/web.d.ts +44 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/web.js +58 -0
- package/dist/web.js.map +1 -0
- package/package.json +59 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-D3NUIwyo.js","names":["union","zEnum","base64UrlToBytes","sha256","dntShim.dntGlobalThis","__classPrivateFieldGet","__classPrivateFieldSet","__classPrivateFieldGet","__classPrivateFieldSet","base64UrlToBytes","x25519KeypairFromSeed","generateX25519Keypair","hpkeSeal","hpkeOpen","_x25519KeypairFromSeed","_generateX25519Keypair","_hpkeSeal","_hpkeOpen","_sha256","base64UrlToBytes","crypto.verify","crypto.sign","crypto.generateKeypair","base64UrlToBytes","crypto.hpkeSeal","crypto.hpkeOpen","crypto.generateX25519Keypair","crypto.sign","crypto.hpkeSeal","crypto.hpkeOpen","crypto.generateKeypair","crypto.generateX25519Keypair","base64UrlToBytes","crypto.sha256","crypto.generateKeypair","crypto.generateX25519Keypair","crypto.keypairFromSeed","crypto.x25519KeypairFromSeed"],"sources":["../../src/schema/assignability.ts","../../src/schema/assertSchemaReferences.ts","../../src/schema/materializeJsonSchema.ts","../../src/schema/schemaToZod.ts","../../src/connection/bareInterfaceTarget.ts","../../src/schema/codegen/utils/codeWriter.ts","../../src/schema/codegen/generateTsInterface.ts","../../src/hub/common/reflection.interfaces.ts","../../src/connection/streaming.ts","../../src/protocol/jsonRpc.ts","../../src/crypto/cryptoProvider.ts","../../src/protocol/signedObject.ts","../../src/protocol/capability.ts","../../src/protocol/methodName.ts","../../src/protocol/linkRpcEnvelope.ts","../../src/transport/messageTransport.ts","../../src/transport/multiplexedTransport.ts","../../src/connection/channel.ts","../../src/connection/requestTimeout.ts","../../src/hub/common/directoryWalk.ts","../../src/connection/jsonRpcChannel.ts","../../src/inspection/endpointTrafficInspector.ts","../../src/connection/linkRpcConnection.ts","../../src/connection/channelConnector.ts","../../src/connection/endpointUri.ts","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/errors.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/algorithm.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/identifiers.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/kemInterface.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kdfs/hkdf.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/misc.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkem.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/dhkemPrimitives.js","../../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/interfaces/aeadEncryptionContext.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/aeads/aesGcm.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/utils/emitNotSupported.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/encryptionContext.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/native.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemX25519.js","../../src/crypto/ed25519CryptoProvider.ts","../../src/crypto/crypto.ts","../../src/identity/signedObject.ts","../../src/identity/signedRpcEnvelope.ts","../../src/identity/capBag.ts","../../src/identity/principal.ts","../../src/identity/identity.ts","../../src/identity/identity.interfaces.ts","../../src/identity/managedIdentity.ts","../../src/identity/managedPrincipal.ts","../../src/identity/signingSender.ts","../../src/identity/capability.ts","../../src/identity/metaEnvelope.ts","../../src/identity/seededPrincipal.ts"],"sourcesContent":["import type {\n LinkRpcJsonSchema,\n JsonValue,\n ObjectSchema,\n ArraySchema,\n TupleSchema,\n UnionSchema,\n OneOfSchema,\n ConstSchema,\n EnumSchema,\n RefSchema,\n} from \"./linkRpcJsonSchema\";\n\n/**\n * Structural subtype check: returns `true` iff every JSON value matching\n * `sub` also matches `sup`, over the SvcJsonSchema subset.\n *\n * Cycles introduced by `$ref` are broken by assuming the recursive case\n * holds (standard coinductive subtyping). This is sound for productive\n * (non-degenerate) schemas; pathological inputs are out of scope.\n */\nexport function isAssignable(\n sub: LinkRpcJsonSchema,\n sup: LinkRpcJsonSchema,\n components: Components = {},\n): boolean {\n return _check(sub, sup, components, new Set());\n}\n\nexport interface Components {\n schemas?: Record<string, LinkRpcJsonSchema>;\n}\n\nfunction _check(sub: LinkRpcJsonSchema, sup: LinkRpcJsonSchema, c: Components, seen: Set<string>): boolean {\n // top / bottom shortcuts\n if (sup === true) return true;\n if (sub === false) return true;\n if (sup === false) return _isBottom(sub, c, seen);\n if (sub === true) return false;\n\n // resolve refs\n if (_isRef(sub)) {\n const k = `S:${sub.$ref}|${_keyOf(sup)}`;\n if (seen.has(k)) return true;\n const resolved = _resolveRef(sub, c);\n if (!resolved) return false;\n return _check(resolved, sup, c, new Set(seen).add(k));\n }\n if (_isRef(sup)) {\n const k = `${_keyOf(sub)}|T:${sup.$ref}`;\n if (seen.has(k)) return true;\n const resolved = _resolveRef(sup, c);\n if (!resolved) return false;\n return _check(sub, resolved, c, new Set(seen).add(k));\n }\n\n // unions distribute (anyOf / oneOf treated identically for assignability;\n // see SvcJsonSchema doc-comment)\n if (_isUnion(sub)) {\n return _branches(sub).every((branch) => _check(branch, sup, c, seen));\n }\n if (_isUnion(sup)) {\n return _branches(sup).some((branch) => _check(sub, branch, c, seen));\n }\n\n // const / enum on sub: every value must match sup\n if (_isConst(sub)) return _matches(sub.const, sup, c, seen);\n if (_isEnum(sub)) return sub.enum.every((v) => _matches(v, sup, c, seen));\n\n // const / enum on sup: sub must reduce to a subset\n if (_isConst(sup)) {\n if (_isConst(sub)) return _jsonEq(sub.const, sup.const);\n return false;\n }\n if (_isEnum(sup)) {\n if (_isConst(sub)) return sup.enum.some((v) => _jsonEq(sub.const, v));\n return false;\n }\n\n // From here on, both sides have a `type`. Mismatching types => not assignable,\n // except integer <: number.\n const subType = (sub as { type?: string }).type;\n const supType = (sup as { type?: string }).type;\n if (subType !== supType) {\n if (subType === \"integer\" && supType === \"number\") return true;\n return false;\n }\n\n switch (subType) {\n case \"null\":\n case \"boolean\":\n return true;\n\n case \"number\":\n case \"integer\":\n return _formatCompatible(\n (sub as { format?: string }).format,\n (sup as { format?: string }).format,\n );\n\n case \"string\":\n return _formatCompatible(\n (sub as { format?: string }).format,\n (sup as { format?: string }).format,\n );\n\n case \"array\":\n return _checkArrayLike(sub as ArrayLike, sup as ArrayLike, c, seen);\n\n case \"object\":\n return _checkObject(sub as ObjectSchema, sup as ObjectSchema, c, seen);\n\n default:\n return false;\n }\n}\n\n// ---- object ----\n\nfunction _checkObject(\n sub: ObjectSchema,\n sup: ObjectSchema,\n c: Components,\n seen: Set<string>,\n): boolean {\n const subReq = new Set(sub.required ?? []);\n const supReq = new Set(sup.required ?? []);\n\n // every required prop in sup must be required in sub\n for (const k of supReq) {\n if (!subReq.has(k)) return false;\n }\n\n // for each named prop in sup: sub.prop (or sub.additionalProperties) <: sup.prop\n for (const [k, supProp] of Object.entries(sup.properties)) {\n const subProp = sub.properties[k] ?? sub.additionalProperties;\n if (subProp === false) {\n // sub forbids this prop; only OK if sup doesn't require it AND\n // its schema is `true` (any). Otherwise sub-values omit it but\n // sup wouldn't permit absence.\n if (supReq.has(k)) return false;\n continue;\n }\n if (!_check(subProp, supProp, c, seen)) return false;\n }\n\n // sub may have extra named props: each must be <: sup.additionalProperties\n for (const [k, subProp] of Object.entries(sub.properties)) {\n if (k in sup.properties) continue;\n if (sup.additionalProperties === false) return false;\n if (!_check(subProp, sup.additionalProperties, c, seen)) return false;\n }\n\n // sub's additionalProperties bucket must fit sup's\n if (sub.additionalProperties === false) {\n // closed sub fits any sup additional bucket\n } else if (sup.additionalProperties === false) {\n // sub leaves room for arbitrary keys; sup forbids them — only sound\n // if sub's bucket is itself empty (`false`), which we handled above.\n return false;\n } else {\n if (!_check(sub.additionalProperties, sup.additionalProperties, c, seen)) return false;\n }\n\n return true;\n}\n\n// ---- array / tuple ----\n\ntype ArrayLike = (ArraySchema | TupleSchema) & { type: \"array\" };\n\nfunction _checkArrayLike(\n sub: ArrayLike,\n sup: ArrayLike,\n c: Components,\n seen: Set<string>,\n): boolean {\n const subPrefix = (sub as TupleSchema).prefixItems ?? [];\n const supPrefix = (sup as TupleSchema).prefixItems ?? [];\n const subRest = _restOf(sub);\n const supRest = _restOf(sup);\n\n const n = Math.max(subPrefix.length, supPrefix.length);\n for (let i = 0; i < n; i++) {\n const a = subPrefix[i] ?? subRest;\n const b = supPrefix[i] ?? supRest;\n if (a === false) {\n // sub asserts length <= i, so this position in sup is unreached.\n // Only OK if sup also forbids it (b === false) OR sup's position\n // is `true` (vacuously satisfied for non-existent values).\n if (b !== false && b !== true) return false;\n continue;\n }\n if (b === false) {\n // sup forbids this position; sub permits it.\n return false;\n }\n if (!_check(a, b, c, seen)) return false;\n }\n\n if (subRest === false) {\n // sub has bounded length; sup may permit more — OK.\n } else if (supRest === false) {\n // sup has bounded length but sub permits more.\n return false;\n } else {\n if (!_check(subRest, supRest, c, seen)) return false;\n }\n\n return true;\n}\n\nfunction _restOf(s: ArrayLike): LinkRpcJsonSchema | false {\n if (\"items\" in s) {\n if (s.items === undefined) return false; // exact-length tuple\n return s.items;\n }\n return true;\n}\n\n// ---- value matching (for const / enum on sub side) ----\n\nfunction _matches(\n v: JsonValue,\n sup: LinkRpcJsonSchema,\n c: Components,\n seen: Set<string>,\n): boolean {\n if (sup === true) return true;\n if (sup === false) return false;\n if (_isRef(sup)) {\n const r = _resolveRef(sup, c);\n return r ? _matches(v, r, c, seen) : false;\n }\n if (_isUnion(sup)) return _branches(sup).some((b) => _matches(v, b, c, seen));\n if (_isConst(sup)) return _jsonEq(v, sup.const);\n if (_isEnum(sup)) return sup.enum.some((e) => _jsonEq(v, e));\n\n const t = (sup as { type?: string }).type;\n switch (t) {\n case \"null\": return v === null;\n case \"boolean\": return typeof v === \"boolean\";\n case \"number\": return typeof v === \"number\";\n case \"integer\": return typeof v === \"number\" && Number.isInteger(v);\n case \"string\": return typeof v === \"string\";\n case \"array\": return Array.isArray(v) && _matchesArray(v, sup as ArrayLike, c, seen);\n case \"object\":\n return v !== null && typeof v === \"object\" && !Array.isArray(v)\n && _matchesObject(v as Record<string, JsonValue>, sup as ObjectSchema, c, seen);\n default: return false;\n }\n}\n\nfunction _matchesArray(\n v: JsonValue[],\n sup: ArrayLike,\n c: Components,\n seen: Set<string>,\n): boolean {\n const prefix = (sup as TupleSchema).prefixItems ?? [];\n const rest = _restOf(sup);\n if (rest === false && v.length !== prefix.length) {\n if (v.length > prefix.length) return false;\n }\n for (let i = 0; i < v.length; i++) {\n const s = prefix[i] ?? (rest === false ? false : rest);\n if (s === false) return false;\n if (!_matches(v[i], s, c, seen)) return false;\n }\n return true;\n}\n\nfunction _matchesObject(\n v: Record<string, JsonValue>,\n sup: ObjectSchema,\n c: Components,\n seen: Set<string>,\n): boolean {\n for (const k of sup.required ?? []) {\n if (!(k in v)) return false;\n }\n for (const [k, val] of Object.entries(v)) {\n const s = sup.properties[k] ?? sup.additionalProperties;\n if (s === false) return false;\n if (!_matches(val, s, c, seen)) return false;\n }\n return true;\n}\n\n// ---- bottom check ----\n\nfunction _isBottom(s: LinkRpcJsonSchema, c: Components, seen: Set<string>): boolean {\n if (s === false) return true;\n if (s === true) return false;\n if (_isRef(s)) {\n const k = `B:${s.$ref}`;\n if (seen.has(k)) return false;\n const r = _resolveRef(s, c);\n return r ? _isBottom(r, c, new Set(seen).add(k)) : false;\n }\n if (_isUnion(s)) return _branches(s).every((b) => _isBottom(b, c, seen));\n return false;\n}\n\n// ---- helpers ----\n\nfunction _formatCompatible(subFmt: string | undefined, supFmt: string | undefined): boolean {\n if (supFmt === undefined) return true;\n return subFmt === supFmt;\n}\n\nfunction _isRef(s: LinkRpcJsonSchema): s is RefSchema {\n return s !== true && s !== false && \"$ref\" in s;\n}\nfunction _isUnion(s: LinkRpcJsonSchema): s is UnionSchema | OneOfSchema {\n return s !== true && s !== false && (\"anyOf\" in s || \"oneOf\" in s);\n}\nfunction _branches(s: UnionSchema | OneOfSchema): LinkRpcJsonSchema[] {\n return \"anyOf\" in s ? s.anyOf : s.oneOf;\n}\nfunction _isConst(s: LinkRpcJsonSchema): s is ConstSchema {\n return s !== true && s !== false && \"const\" in s;\n}\nfunction _isEnum(s: LinkRpcJsonSchema): s is EnumSchema {\n return s !== true && s !== false && \"enum\" in s;\n}\n\nfunction _resolveRef(r: RefSchema, c: Components): LinkRpcJsonSchema | undefined {\n const prefix = \"#/components/schemas/\";\n if (!r.$ref.startsWith(prefix)) return undefined;\n const name = r.$ref.slice(prefix.length);\n return c.schemas?.[name];\n}\n\nfunction _keyOf(s: LinkRpcJsonSchema): string {\n if (s === true || s === false) return String(s);\n if (\"$ref\" in s) return `R:${s.$ref}`;\n return JSON.stringify(s);\n}\n\nfunction _jsonEq(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (a === null || b === null) return false;\n if (typeof a !== typeof b) return false;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => _jsonEq(v, b[i]));\n }\n if (typeof a === \"object\") {\n const ao = a as Record<string, JsonValue>;\n const bo = b as Record<string, JsonValue>;\n const ak = Object.keys(ao).sort();\n const bk = Object.keys(bo).sort();\n if (ak.length !== bk.length) return false;\n return ak.every((k, i) => k === bk[i] && _jsonEq(ao[k], bo[k]));\n }\n return false;\n}\n","import type { LinkRpcJsonSchema } from './linkRpcJsonSchema';\n\ntype SchemaNode = Exclude<LinkRpcJsonSchema, boolean>;\nconst componentPrefix = '#/components/schemas/';\n\nexport function componentSchemaRef(name: string): string {\n return componentPrefix + name.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\nexport function componentSchemaName(ref: string): string {\n if (!ref.startsWith(componentPrefix)) {\n throw new Error(`Invalid component reference: ${ref}`);\n }\n const token = ref.slice(componentPrefix.length);\n if (token.includes('/') || /~(?:[^01]|$)/.test(token)) {\n throw new Error(`Invalid component reference token: ${ref}`);\n }\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\n/**\n * Check the finite schema graph without interpreting JSON literal payloads.\n * A reference/union-only cycle is invalid; descending into an object member\n * or an array item guards a cycle, but does not imply the schema is nonempty.\n */\nexport function assertSchemaReferences(\n roots: Iterable<LinkRpcJsonSchema>,\n components: Record<string, LinkRpcJsonSchema> = {},\n): void {\n const nodes = new Set<SchemaNode>();\n const pending = [...roots, ...Object.values(components)];\n const unguarded = new Map<SchemaNode, LinkRpcJsonSchema[]>();\n while (pending.length > 0) {\n const node = pending.pop()!;\n if (typeof node === 'boolean' || nodes.has(node)) continue;\n nodes.add(node);\n const edges: LinkRpcJsonSchema[] = [];\n if ('$ref' in node) {\n const name = componentSchemaName(node.$ref);\n if (!Object.hasOwn(components, name)) {\n throw new Error(`Unresolved component reference: ${node.$ref}`);\n }\n edges.push(components[name]);\n }\n if ('anyOf' in node) edges.push(...node.anyOf);\n if ('oneOf' in node) edges.push(...node.oneOf);\n unguarded.set(node, edges);\n pending.push(...edges);\n if ('type' in node && node.type === 'object') {\n pending.push(...Object.values(node.properties ?? {}), node.additionalProperties);\n }\n if ('type' in node && node.type === 'array') {\n if ('prefixItems' in node) pending.push(...node.prefixItems);\n if (node.items !== undefined) pending.push(node.items);\n }\n }\n\n const visiting = new Set<SchemaNode>();\n const checked = new Set<SchemaNode>();\n const visit = (node: LinkRpcJsonSchema): void => {\n if (typeof node === 'boolean' || checked.has(node)) return;\n if (visiting.has(node)) {\n throw new Error('Unguarded recursive schema: cycle does not descend into a child value');\n }\n visiting.add(node);\n for (const child of unguarded.get(node) ?? []) visit(child);\n visiting.delete(node);\n checked.add(node);\n };\n for (const node of nodes) visit(node);\n}\n","import type { LinkRpcJsonSchema } from \"./linkRpcJsonSchema\";\n\nexport interface MaterializedJsonSchema {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n $defs?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * Export a LinkRPC schema and its components as standalone JSON Schema\n * draft 2020-12. Node-local `x-json-schema` constraints are conjoined via\n * `allOf`, so a refinement cannot accidentally override the wire contract.\n *\n * References are rewritten rather than dereferenced. Consequently recursive\n * and mutually-recursive component graphs are materialized in finite time.\n */\nexport function materializeJsonSchema(\n root: LinkRpcJsonSchema,\n components: Record<string, LinkRpcJsonSchema> = {},\n): MaterializedJsonSchema {\n const materialized = materializeNode(root);\n const rootObject: Record<string, unknown> =\n typeof materialized === \"boolean\" ? { allOf: [materialized] } : materialized;\n return {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n ...rootObject,\n ...(Object.keys(components).length === 0 ? {} : {\n $defs: Object.fromEntries(\n Object.entries(components).map(([name, schema]) => [name, materializeNode(schema)]),\n ),\n }),\n };\n}\n\nfunction materializeNode(value: unknown): boolean | Record<string, unknown> {\n if (typeof value === \"boolean\") return value;\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\"materializeJsonSchema: expected a JSON Schema node\");\n }\n const input = value as Record<string, unknown>;\n const refinement = input[\"x-json-schema\"];\n const base: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(input)) {\n if (key === \"x-json-schema\") continue;\n if (key === \"$ref\" && typeof child === \"string\") {\n base.$ref = rewriteRef(child);\n } else if (key === \"properties\" && isRecord(child)) {\n base.properties = Object.fromEntries(\n Object.entries(child).map(([name, schema]) => [name, materializeNode(schema)]),\n );\n } else if (key === \"items\" || key === \"additionalProperties\") {\n base[key] = typeof child === \"boolean\" ? child : materializeNode(child);\n } else if (key === \"prefixItems\" || key === \"anyOf\" || key === \"oneOf\") {\n const outputKey = key === \"oneOf\" ? \"anyOf\" : key;\n base[outputKey] = Array.isArray(child) ? child.map(materializeNode) : child;\n } else {\n base[key] = child;\n }\n }\n if (input.type === \"array\" && Array.isArray(input.prefixItems)) {\n base.minItems = input.prefixItems.length;\n if (input.items === undefined || input.items === false) {\n base.maxItems = input.prefixItems.length;\n }\n }\n if (refinement === undefined) return base;\n if (typeof refinement !== \"boolean\" && !isRecord(refinement)) {\n throw new Error(\"materializeJsonSchema: x-json-schema must be a boolean or object\");\n }\n return { allOf: [base, materializeGeneralSchema(refinement)] };\n}\n\nfunction materializeGeneralSchema(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value;\n const result: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (key === \"$ref\" && typeof child === \"string\") {\n result[key] = rewriteRef(child);\n } else if (key === \"x-json-schema\") {\n result[key] = materializeGeneralSchema(child);\n } else if (schemaMapKeywords.has(key) && isRecord(child)) {\n result[key] = Object.fromEntries(\n Object.entries(child).map(([name, schema]) => [name, materializeGeneralSchema(schema)]),\n );\n } else if (schemaArrayKeywords.has(key) && Array.isArray(child)) {\n result[key] = child.map(materializeGeneralSchema);\n } else if (schemaKeywords.has(key)) {\n result[key] = materializeGeneralSchema(child);\n } else {\n // Keywords such as const/default/examples carry JSON payloads.\n result[key] = child;\n }\n }\n return result;\n}\n\nconst schemaMapKeywords = new Set([\n \"$defs\", \"definitions\", \"properties\", \"patternProperties\", \"dependentSchemas\",\n]);\nconst schemaArrayKeywords = new Set([\"allOf\", \"anyOf\", \"oneOf\", \"prefixItems\"]);\nconst schemaKeywords = new Set([\n \"additionalProperties\", \"contains\", \"contentSchema\", \"else\", \"if\", \"items\",\n \"not\", \"propertyNames\", \"then\", \"unevaluatedItems\", \"unevaluatedProperties\",\n]);\n\nfunction rewriteRef(ref: string): string {\n const prefix = \"#/components/schemas/\";\n return ref.startsWith(prefix) ? `#/$defs/${ref.slice(prefix.length)}` : ref;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { z } from \"zod\";\nimport {\n assertSchemaReferences,\n componentSchemaName,\n} from \"./assertSchemaReferences\";\nimport type { LinkRpcJsonSchema } from \"./linkRpcJsonSchema\";\n\nexport interface SchemaToZodContext {\n readonly toZod: (schema: LinkRpcJsonSchema) => z.ZodType<unknown>;\n}\n\n/**\n * Create a recursive LinkRPC-schema validator materializer. Component\n * references are lazy, so self and mutual recursion remain guarded.\n */\nexport function createSchemaToZod(\n components: Record<string, LinkRpcJsonSchema> = {},\n): SchemaToZodContext {\n assertSchemaReferences([], components);\n const refs = new Map<string, z.ZodType<unknown>>();\n const component = (name: string): z.ZodType<unknown> => {\n const existing = refs.get(name);\n if (existing !== undefined) return existing;\n const source = components[name];\n if (source === undefined) throw new Error(`schemaToZod: dangling component reference \"${name}\"`);\n const lazy: z.ZodType<unknown> = z.lazy(() => compile(source));\n refs.set(name, lazy);\n return lazy;\n };\n\n const compile = (schema: LinkRpcJsonSchema): z.ZodType<unknown> => {\n if (schema === true) return z.unknown();\n if (schema === false) return z.never();\n const raw = schema as unknown as Record<string, unknown>;\n if (Array.isArray(raw.type)) {\n return union(raw.type.map((type) =>\n compile({ ...raw, type } as unknown as LinkRpcJsonSchema)\n ));\n }\n let base: z.ZodType<unknown>;\n if (\"$ref\" in schema) {\n base = component(componentSchemaName(schema.$ref));\n } else if (\"const\" in schema) {\n base = valueSchema(schema.const);\n } else if (\"enum\" in schema) {\n base = union(schema.enum.map(valueSchema));\n } else if (\"anyOf\" in schema) {\n base = union(schema.anyOf.map(compile));\n } else if (\"oneOf\" in schema) {\n // LinkRPC's normative structural semantics treat oneOf as a union;\n // exclusivity is only available through rich JSON Schema export.\n base = union(schema.oneOf.map(compile));\n } else if (isAnnotationOnlySchema(raw)) {\n base = z.unknown();\n } else {\n switch (schema.type) {\n case \"null\":\n base = z.null();\n break;\n case \"boolean\":\n base = z.boolean();\n break;\n case \"string\":\n base = stringSchema(schema.format);\n break;\n case \"integer\":\n base = z.number().int();\n break;\n case \"number\":\n base = z.number();\n break;\n case \"array\":\n if (\"prefixItems\" in schema) {\n const tuple = z.tuple(schema.prefixItems.map(compile) as [\n z.ZodType<unknown>,\n ...z.ZodType<unknown>[],\n ]);\n base = schema.items !== undefined && schema.items !== false\n ? tuple.rest(compile(schema.items))\n : tuple;\n } else {\n base = z.array(compile(schema.items));\n }\n break;\n case \"object\": {\n const required = new Set(schema.required ?? []);\n const shape: Record<string, z.ZodType<unknown>> = {};\n for (const [name, property] of Object.entries(schema.properties)) {\n const validator = compile(property);\n shape[name] = required.has(name) ? validator : validator.optional();\n }\n const object = z.object(shape);\n if (schema.additionalProperties === false) {\n base = object.strict();\n } else if (schema.additionalProperties === true) {\n base = object.loose();\n } else {\n base = object.catchall(compile(schema.additionalProperties));\n }\n break;\n }\n }\n }\n return base;\n };\n return {\n toZod(schema): z.ZodType<unknown> {\n assertSchemaReferences([schema], components);\n return compile(schema);\n },\n };\n}\n\nfunction isAnnotationOnlySchema(schema: Record<string, unknown>): boolean {\n const structuralKeys = [\n \"$ref\", \"const\", \"enum\", \"anyOf\", \"oneOf\", \"type\",\n \"properties\", \"items\", \"prefixItems\", \"additionalProperties\",\n ];\n return !structuralKeys.some((key) => Object.hasOwn(schema, key));\n}\n\nexport function schemaToZod(\n schema: LinkRpcJsonSchema,\n components: Record<string, LinkRpcJsonSchema> = {},\n): z.ZodType<unknown> {\n return createSchemaToZod(components).toZod(schema);\n}\n\nfunction union(items: z.ZodType<unknown>[]): z.ZodType<unknown> {\n if (items.length === 0) return z.never();\n if (items.length === 1) return items[0]!;\n return z.union(items as [z.ZodType<unknown>, z.ZodType<unknown>, ...z.ZodType<unknown>[]]);\n}\n\nfunction valueSchema(expected: import(\"../protocol/jsonValue\").JsonValue): z.ZodType<unknown> {\n return z.unknown().refine((actual) => jsonValueEqual(actual, expected), {\n message: `Expected ${JSON.stringify(expected)}`,\n });\n}\n\nfunction jsonValueEqual(actual: unknown, expected: unknown): boolean {\n if (Object.is(actual, expected)) return true;\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length &&\n actual.every((value, index) => jsonValueEqual(value, expected[index]));\n }\n if (\n actual !== null && expected !== null &&\n typeof actual === \"object\" && typeof expected === \"object\" &&\n !Array.isArray(actual) && !Array.isArray(expected)\n ) {\n const actualRecord = actual as Record<string, unknown>;\n const expectedRecord = expected as Record<string, unknown>;\n const keys = Object.keys(actualRecord);\n return keys.length === Object.keys(expectedRecord).length &&\n keys.every((key) =>\n Object.hasOwn(expectedRecord, key) &&\n jsonValueEqual(actualRecord[key], expectedRecord[key])\n );\n }\n return false;\n}\n\nfunction stringSchema(format: string | undefined): z.ZodType<unknown> {\n switch (format) {\n case \"email\": return z.email();\n case \"uri\":\n case \"url\": return z.url();\n case \"uuid\": return z.uuid();\n case \"date-time\": return z.iso.datetime();\n default: return z.string();\n }\n}\n","import type { InterfaceDefinition } from './interfaceDefinition';\n\n/** A metadata-free foreign-protocol interface and its wire-method prefix. */\nexport interface BareInterfaceTarget<TDef extends InterfaceDefinition<any>> {\n readonly mode: 'bare';\n readonly interface: TDef;\n readonly prefix: string;\n}\n\n/**\n * Bundle an interface definition with metadata-free foreign-protocol\n * addressing for use with `connection.get(target)`.\n */\nexport function bareInterfaceTarget<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n options: { readonly prefix?: string } = {},\n): BareInterfaceTarget<TDef> {\n const prefix = options.prefix ?? '';\n validateBarePrefix(prefix, 'bareInterfaceTarget');\n return Object.freeze({\n mode: 'bare' as const,\n interface: iface,\n prefix,\n });\n}\n\nexport function isBareInterfaceTarget<TDef extends InterfaceDefinition<any>>(\n value: TDef | BareInterfaceTarget<TDef>,\n): value is BareInterfaceTarget<TDef> {\n return typeof value === 'object'\n && value !== null\n && 'mode' in value\n && value.mode === 'bare'\n && 'interface' in value\n && 'prefix' in value;\n}\n\nexport function validateBarePrefix(\n prefix: string,\n api: 'bareInterfaceTarget' | 'bindBare' | 'getBare',\n): void {\n if (prefix.includes('::') || !/^[\\x20-\\x7e]*$/.test(prefix)) {\n throw new Error(`${api}: prefix must contain only printable ASCII and must not contain \"::\".`);\n }\n}\n","/**\n * Minimal indentation-aware text builder for code generation.\n *\n * Usage pattern:\n * - {@link append} extends the *current* (unfinished) line. Indentation\n * is inserted lazily the first time content lands on a fresh line, so\n * blank lines stay blank.\n * - {@link newline} ends the current line.\n * - {@link writeLine} is `append` + `newline`.\n * - {@link indent} / {@link dedent} change the indent level used for\n * *future* fresh lines; they do not retroactively reformat the\n * in-progress line.\n *\n * Indentation is fixed at four spaces, matching the surrounding codebase.\n */\nexport class CodeWriter {\n private readonly _lines: string[] = [];\n private _current = \"\";\n private _indent = 0;\n private _onFreshLine = true;\n\n public indent(): this {\n this._indent++;\n return this;\n }\n\n public dedent(): this {\n if (this._indent === 0) throw new Error(\"CodeWriter: dedent below 0\");\n this._indent--;\n return this;\n }\n\n public append(text: string): this {\n if (text.length === 0) return this;\n if (this._onFreshLine) {\n this._current = \" \".repeat(this._indent);\n this._onFreshLine = false;\n }\n this._current += text;\n return this;\n }\n\n public newline(): this {\n this._lines.push(this._current);\n this._current = \"\";\n this._onFreshLine = true;\n return this;\n }\n\n public writeLine(text = \"\"): this {\n return this.append(text).newline();\n }\n\n public toString(): string {\n const lines = [...this._lines];\n if (!this._onFreshLine) lines.push(this._current);\n return lines.join(\"\\n\") + \"\\n\";\n }\n}\n","import type { JsonValue } from '../../protocol/jsonValue';\nimport type {\n MemberAnnotations,\n MethodSchema,\n LinkRpcInterfaceSchema,\n} from '../linkRpcInterfaceSchema';\nimport type { LinkRpcJsonSchema } from '../linkRpcJsonSchema';\nimport { validateBarePrefix } from '../../connection/bareInterfaceTarget';\nimport { CodeWriter } from './utils/codeWriter';\n\nexport interface GenerateInterfaceOptions {\n /**\n * Module specifier from which `defineInterface`, `requestType`,\n * `notificationType` are imported. Defaults to `@hediet/linkrpc`.\n */\n linkRpcImport?: string;\n /**\n * Identifier for the exported `InterfaceDefinition` const. Defaults to\n * a sanitized form of the interface id with an `Interface` suffix\n * (e.g. `hubrpc.directory` → `linkRpcDirectoryInterface`).\n */\n exportName?: string;\n /**\n * Preserve the supplied wire schema verbatim instead of reconstructing it\n * from the generated Zod schemas. This permits type-safe generation for\n * wire shapes that Zod represents differently, such as untagged `oneOf`.\n */\n preserveWireSchema?: boolean;\n /**\n * Also export a metadata-free target for `connection.get(target)`.\n * The interface definition remains a separate export.\n */\n bareTarget?: {\n exportName: string;\n prefix: string;\n };\n}\n\n/**\n * Render a {@link LinkRpcInterfaceSchema} as a stand-alone TypeScript source\n * file that, when evaluated, reproduces the same canonical schema (and\n * therefore the same `schemaHash`).\n *\n * Components in `components.schemas` are emitted as named `const`\n * declarations referenced from the bodies via `$ref`. Only recursive\n * components receive explicit payload types; other types remain Zod-inferred.\n */\nexport function generateTsInterface(\n schema: LinkRpcInterfaceSchema,\n options: GenerateInterfaceOptions = {},\n): string {\n const linkRpcImport = options.linkRpcImport ?? '@hediet/linkrpc';\n const exportName = options.exportName ?? _deriveExportName(schema.id);\n const preserveWireSchema = options.preserveWireSchema ?? false;\n if (options.bareTarget !== undefined) {\n validateBarePrefix(options.bareTarget.prefix, 'bareInterfaceTarget');\n }\n\n const w = new CodeWriter();\n const bareTargetImport = options.bareTarget === undefined ? '' : 'bareInterfaceTarget, ';\n const definitionImport = preserveWireSchema ?\n `${bareTargetImport}InterfaceDefinition, notificationType, requestType, type LinkRpcInterfaceSchema` :\n `${bareTargetImport}defineInterface, notificationType, requestType`;\n w.writeLine(`import { ${definitionImport} } from \"${linkRpcImport}\";`);\n w.writeLine(`import { z } from \"zod\";`);\n w.writeLine();\n\n const componentSchemas = schema.components?.schemas ?? {};\n const cyclicComponents = _findCyclicComponents(componentSchemas);\n const componentNames = _allocateComponentNames(componentSchemas);\n const payloadNames = _allocatePayloadNames(componentSchemas, cyclicComponents);\n\n for (const [name, sub] of _sortComponents(componentSchemas)) {\n if (!cyclicComponents.has(name)) continue;\n w.writeLine(\n `type ${payloadNames.get(name)!} = ${_schemaType(sub, componentNames, payloadNames)};`,\n );\n }\n if (cyclicComponents.size > 0) w.writeLine();\n\n for (const [name, sub] of _sortComponents(componentSchemas)) {\n const varName = componentNames.get(name)!;\n _writeJsDoc(w, _schemaDescription(sub));\n if (cyclicComponents.has(name)) {\n w.append(`const ${varName}: z.ZodType<${payloadNames.get(name)!}> = z.lazy(() => `);\n } else {\n w.append(`const ${varName} = `);\n }\n _writeSchema(w, sub, componentNames, preserveWireSchema, name);\n if (cyclicComponents.has(name)) w.append(')');\n w.append(';');\n w.newline();\n w.writeLine();\n }\n\n if (preserveWireSchema) {\n w.writeLine(\n `const wireSchema: LinkRpcInterfaceSchema = JSON.parse(${JSON.stringify(JSON.stringify(schema))});`,\n );\n w.writeLine();\n }\n\n _writeJsDoc(w, schema.description);\n w.append(\n `export const ${exportName} = ${preserveWireSchema ? 'new InterfaceDefinition' : 'defineInterface'}(`,\n );\n w.newline();\n w.indent();\n _writeInterfaceInfo(w, schema, preserveWireSchema);\n w.append(',');\n w.newline();\n _writeMembers(w, schema.methods, componentNames, componentSchemas, preserveWireSchema);\n w.append(',');\n w.newline();\n if (preserveWireSchema) {\n w.writeLine('{ frozenSchema: wireSchema },');\n }\n w.dedent();\n w.writeLine(');');\n if (options.bareTarget !== undefined) {\n w.writeLine();\n w.writeLine(\n `export const ${options.bareTarget.exportName} = bareInterfaceTarget(${exportName}, { prefix: ${JSON.stringify(options.bareTarget.prefix)} });`,\n );\n }\n\n return w.toString();\n}\n\n// ---------------------------------------------------------------- info\n\nfunction _schemaType(\n schema: LinkRpcJsonSchema,\n components: Map<string, string>,\n payloads: Map<string, string>,\n): string {\n if (schema === true) return 'unknown';\n if (schema === false) return 'never';\n\n const s = schema as unknown as Record<string, unknown>;\n if (Array.isArray(s['type'])) {\n return s['type']\n .map((type) => _schemaType(\n { ...s, type } as unknown as LinkRpcJsonSchema,\n components,\n payloads,\n ))\n .join(' | ') || 'never';\n }\n if (typeof s['$ref'] === 'string') {\n const name = _parseRef(s['$ref']);\n const payload = payloads.get(name);\n if (payload !== undefined) return payload;\n const component = components.get(name);\n if (component === undefined) {\n throw new Error(`generateInterface: dangling $ref \"${s['$ref']}\"`);\n }\n return `z.infer<typeof ${component}>`;\n }\n if ('const' in s) return _jsonLiteral(s['const'] as JsonValue);\n if (Array.isArray(s['enum'])) {\n return (s['enum'] as JsonValue[]).map(_jsonLiteral).join(' | ') || 'never';\n }\n\n const union = (s['oneOf'] ?? s['anyOf']) as LinkRpcJsonSchema[] | undefined;\n if (Array.isArray(union)) {\n return union.map((item) => _schemaType(item, components, payloads)).join(' | ') || 'never';\n }\n\n if (s['type'] === 'object') {\n const properties = (s['properties'] as Record<string, LinkRpcJsonSchema> | undefined) ?? {};\n const required = new Set((s['required'] as string[] | undefined) ?? []);\n const members = Object.entries(properties).map(([name, property]) =>\n `${_propKey(name)}${required.has(name) ? '' : '?'}: ${_schemaType(property, components, payloads)};`,\n );\n const objectType = `{ ${members.join(' ')} }`;\n const additional = s['additionalProperties'];\n if (additional === true) return `${objectType} & { [key: string]: unknown }`;\n if (additional !== undefined && additional !== false) {\n return `${objectType} & { [key: string]: ${_schemaType(additional as LinkRpcJsonSchema, components, payloads)} }`;\n }\n return objectType;\n }\n\n if (s['type'] === 'array' && Array.isArray(s['prefixItems'])) {\n const prefix = (s['prefixItems'] as LinkRpcJsonSchema[])\n .map((item) => _schemaType(item, components, payloads));\n const rest = s['items'];\n if (rest !== undefined && rest !== false) {\n prefix.push(`...Array<${_schemaType(rest as LinkRpcJsonSchema, components, payloads)}>`);\n }\n return `[${prefix.join(', ')}]`;\n }\n if (s['type'] === 'array') {\n const item = (s['items'] as LinkRpcJsonSchema | undefined) ?? true;\n return `Array<${_schemaType(item, components, payloads)}>`;\n }\n\n if (_isAnnotationOnlySchema(s)) return 'unknown';\n\n switch (s['type']) {\n case 'null': return 'null';\n case 'boolean': return 'boolean';\n case 'string': return 'string';\n case 'integer': return 'number';\n case 'number': return 'number';\n default:\n throw new Error(`generateInterface: unsupported schema: ${JSON.stringify(schema)}`);\n }\n}\n\nfunction _writeInterfaceInfo(\n w: CodeWriter,\n schema: LinkRpcInterfaceSchema,\n includeHash: boolean,\n): void {\n w.append('{').newline();\n w.indent();\n w.append(`id: ${JSON.stringify(schema.id)},`).newline();\n if (schema.description !== undefined) {\n w.append(`description: ${JSON.stringify(schema.description)},`).newline();\n }\n if (schema.comment !== undefined) {\n w.append(`comment: ${JSON.stringify(schema.comment)},`).newline();\n }\n if (includeHash) {\n w.append(`hash: ${JSON.stringify(schema.hash)},`).newline();\n }\n w.dedent();\n w.append('}');\n}\n\n// ------------------------------------------------------------- members\n\nfunction _writeMembers(\n w: CodeWriter,\n methods: Record<string, MethodSchema>,\n components: Map<string, string>,\n componentSchemas: Record<string, LinkRpcJsonSchema>,\n preserveWireSchema: boolean,\n): void {\n w.append('{').newline();\n w.indent();\n for (const [name, method] of Object.entries(methods)) {\n _writeJsDoc(w, _methodDescription(method, componentSchemas));\n w.append(`${_propKey(name)}: `);\n _writeMethod(w, method, components, preserveWireSchema);\n w.append(',');\n w.newline();\n }\n w.dedent();\n w.append('}');\n}\n\nfunction _writeMethod(\n w: CodeWriter,\n method: MethodSchema,\n components: Map<string, string>,\n preserveWireSchema: boolean,\n): void {\n const docs = _collectMemberDocs(method);\n\n if (method.result === undefined) {\n w.append('notificationType(').newline();\n w.indent();\n _writeSchema(w, method.params, components, preserveWireSchema);\n w.append(',').newline();\n if (docs !== undefined) {\n _writeDocs(w, docs);\n w.append(',').newline();\n }\n w.dedent();\n w.append(')');\n return;\n }\n\n w.append('requestType(').newline();\n w.indent();\n _writeSchema(w, method.params, components, preserveWireSchema);\n w.append(',').newline();\n _writeSchema(w, method.result, components, preserveWireSchema);\n w.append(',').newline();\n if (docs !== undefined) {\n _writeDocs(w, docs);\n w.append(',').newline();\n }\n w.dedent();\n w.append(')');\n\n // Streams attach through `withStream({ client?, server? })`.\n if (method.clientStream !== undefined || method.serverStream !== undefined) {\n w.append('.withStream({').newline();\n w.indent();\n if (method.clientStream !== undefined) {\n w.append('client: ');\n _writeSchema(w, method.clientStream, components, preserveWireSchema);\n w.append(',').newline();\n }\n if (method.serverStream !== undefined) {\n w.append('server: ');\n _writeSchema(w, method.serverStream, components, preserveWireSchema);\n w.append(',').newline();\n }\n w.dedent();\n w.append('})');\n }\n}\n\ninterface CollectedDocs {\n description?: string;\n comment?: string;\n annotations?: MemberAnnotations;\n}\n\nfunction _collectMemberDocs(method: MethodSchema): CollectedDocs | undefined {\n const docs: CollectedDocs = {};\n if (method.description !== undefined) docs.description = method.description;\n if (method.comment !== undefined) docs.comment = method.comment;\n if (method.annotations !== undefined && Object.keys(method.annotations).length > 0) {\n docs.annotations = method.annotations;\n }\n return docs.description === undefined && docs.comment === undefined && docs.annotations === undefined ?\n undefined :\n docs;\n}\n\nfunction _writeDocs(w: CodeWriter, docs: CollectedDocs): void {\n w.append('{').newline();\n w.indent();\n if (docs.description !== undefined) {\n w.append(`description: ${JSON.stringify(docs.description)},`).newline();\n }\n if (docs.comment !== undefined) {\n w.append(`comment: ${JSON.stringify(docs.comment)},`).newline();\n }\n if (docs.annotations !== undefined) {\n w.append(`annotations: ${JSON.stringify(docs.annotations)},`).newline();\n }\n w.dedent();\n w.append('}');\n}\n\n// ------------------------------------------------------------- schemas\n\n/**\n * Emit a zod expression equivalent to `schema`. The expression begins at\n * the writer's current line position and may span multiple lines; it\n * ends without a trailing newline so the caller can append punctuation.\n */\nfunction _writeSchema(\n w: CodeWriter,\n schema: LinkRpcJsonSchema,\n components: Map<string, string>,\n preserveWireSchema = false,\n currentComponent?: string,\n): void {\n if (schema === true) {\n _writeMetaWrapped(w, 'z.unknown()', undefined);\n return;\n }\n if (schema === false) {\n _writeMetaWrapped(w, 'z.never()', undefined);\n return;\n }\n\n const s = schema as unknown as Record<string, unknown>;\n if (Array.isArray(s['type'])) {\n _writeUnion(\n w,\n 'z.union',\n s['type'].map((type) => ({ ...s, type }) as unknown as LinkRpcJsonSchema),\n components,\n preserveWireSchema,\n currentComponent,\n );\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n\n // $ref -> component variable\n if (typeof s['$ref'] === 'string') {\n const refName = _parseRef(s['$ref']);\n const varName = components.get(refName);\n if (varName === undefined) {\n throw new Error(`generateInterface: dangling $ref \"${s['$ref']}\"`);\n }\n _writeMetaWrapped(w, varName, _metaOf(s));\n return;\n }\n\n // const / enum\n if ('const' in s) {\n _writeMetaWrapped(w, `z.literal(${_jsonLiteral(s['const'] as JsonValue)})`, _metaOf(s));\n return;\n }\n if (Array.isArray(s['enum'])) {\n const values = s['enum'] as JsonValue[];\n if (values.every((v) => typeof v === 'string')) {\n const tuple = (values as string[]).map((v) => JSON.stringify(v)).join(', ');\n _writeMetaWrapped(w, `z.enum([${tuple}])`, _metaOf(s));\n return;\n }\n // Heterogeneous enums become a union of literals.\n const branches = values.map((v) => `z.literal(${_jsonLiteral(v)})`).join(', ');\n _writeMetaWrapped(w, `z.union([${branches}])`, _metaOf(s));\n return;\n }\n\n // anyOf / oneOf\n if (Array.isArray(s['oneOf'])) {\n const branches = s['oneOf'] as LinkRpcJsonSchema[];\n const disc = s['discriminator'] as { propertyName?: string; } | undefined;\n if (disc?.propertyName !== undefined) {\n _writeUnion(\n w,\n 'z.discriminatedUnion',\n branches,\n components,\n preserveWireSchema,\n currentComponent,\n disc.propertyName,\n );\n } else {\n // General exclusive unions are not representable in Zod. LinkRPC\n // treats oneOf and anyOf identically, so emit the normative union.\n _writeUnion(w, 'z.union', branches, components, preserveWireSchema, currentComponent);\n }\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n if (Array.isArray(s['anyOf'])) {\n _writeUnion(\n w,\n 'z.union',\n s['anyOf'] as LinkRpcJsonSchema[],\n components,\n preserveWireSchema,\n currentComponent,\n );\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n\n // object\n if (s['type'] === 'object') {\n _writeObject(w, s, components, preserveWireSchema, currentComponent);\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n\n // tuple\n if (s['type'] === 'array' && Array.isArray(s['prefixItems'])) {\n _writeTuple(w, s, components, preserveWireSchema, currentComponent);\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n\n // array\n if (s['type'] === 'array') {\n const items = (s['items'] as LinkRpcJsonSchema | undefined) ?? true;\n w.append('z.array(');\n _writeSchema(w, items, components, preserveWireSchema, currentComponent);\n w.append(')');\n _writeMetaSuffix(w, _metaOf(s));\n return;\n }\n\n // primitives\n const primitive = _primitiveExpr(s);\n if (primitive !== undefined) {\n _writeMetaWrapped(w, primitive, _metaOf(s));\n return;\n }\n\n if (_isAnnotationOnlySchema(s)) {\n _writeMetaWrapped(w, 'z.unknown()', _metaOf(s));\n return;\n }\n\n throw new Error(`generateInterface: unsupported schema: ${JSON.stringify(schema)}`);\n}\n\nfunction _isAnnotationOnlySchema(schema: Record<string, unknown>): boolean {\n const structuralKeys = [\n '$ref', 'const', 'enum', 'anyOf', 'oneOf', 'type',\n 'properties', 'items', 'prefixItems', 'additionalProperties',\n ];\n return !structuralKeys.some((key) => Object.hasOwn(schema, key));\n}\n\nfunction _writeObject(\n w: CodeWriter,\n s: Record<string, unknown>,\n components: Map<string, string>,\n preserveWireSchema: boolean,\n currentComponent?: string,\n): void {\n const properties = (s['properties'] as Record<string, LinkRpcJsonSchema> | undefined) ?? {};\n const required = new Set((s['required'] as string[] | undefined) ?? []);\n const additional = s['additionalProperties'];\n\n const constructor = additional === false || additional === undefined ?\n 'z.object' :\n 'z.looseObject';\n\n const keys = Object.keys(properties);\n if (keys.length === 0) {\n w.append(`${constructor}({})`);\n } else {\n w.append(`${constructor}({`).newline();\n w.indent();\n for (const key of keys) {\n const property = properties[key]!;\n _writeJsDoc(w, _schemaDescription(property));\n const recursive = currentComponent !== undefined &&\n _containsRef(property, currentComponent);\n if (recursive) {\n w.append(`get ${_propKey(key)}() {`).newline();\n w.indent();\n w.append('return ');\n _writeSchema(w, property, components, preserveWireSchema, currentComponent);\n if (!required.has(key)) w.append('.optional()');\n w.append(';').newline();\n w.dedent();\n w.append('},').newline();\n } else {\n w.append(`${_propKey(key)}: `);\n _writeSchema(w, property, components, preserveWireSchema, currentComponent);\n if (!required.has(key)) w.append('.optional()');\n w.append(',').newline();\n }\n }\n w.dedent();\n w.append('})');\n }\n\n // `additionalProperties: <schema>` (not `false`, not `true`/missing) lowers\n // through `.catchall(...)`.\n if (additional !== false && additional !== undefined && additional !== true) {\n w.append('.catchall(');\n _writeSchema(w, additional as LinkRpcJsonSchema, components, preserveWireSchema, currentComponent);\n w.append(')');\n }\n}\n\nfunction _writeTuple(\n w: CodeWriter,\n s: Record<string, unknown>,\n components: Map<string, string>,\n preserveWireSchema: boolean,\n currentComponent?: string,\n): void {\n const prefix = s['prefixItems'] as LinkRpcJsonSchema[];\n w.append('z.tuple([').newline();\n w.indent();\n for (const item of prefix) {\n _writeSchema(w, item, components, preserveWireSchema, currentComponent);\n w.append(',').newline();\n }\n w.dedent();\n w.append('])');\n\n const rest = s['items'];\n if (rest !== undefined && rest !== false) {\n w.append('.rest(');\n _writeSchema(w, rest as LinkRpcJsonSchema, components, preserveWireSchema, currentComponent);\n w.append(')');\n }\n}\n\nfunction _writeUnion(\n w: CodeWriter,\n constructor: 'z.union' | 'z.discriminatedUnion',\n branches: LinkRpcJsonSchema[],\n components: Map<string, string>,\n preserveWireSchema: boolean,\n currentComponent?: string,\n discriminator?: string,\n): void {\n if (constructor === 'z.discriminatedUnion' && discriminator !== undefined) {\n w.append(`${constructor}(${JSON.stringify(discriminator)}, [`).newline();\n } else {\n w.append(`${constructor}([`).newline();\n }\n w.indent();\n for (const branch of branches) {\n _writeSchema(w, branch, components, preserveWireSchema, currentComponent);\n w.append(',').newline();\n }\n w.dedent();\n w.append('])');\n}\n\nfunction _primitiveExpr(s: Record<string, unknown>): string | undefined {\n const type = s['type'];\n const format = s['format'] as string | undefined;\n switch (type) {\n case 'null':\n return 'z.null()';\n case 'boolean':\n return 'z.boolean()';\n case 'string':\n return _stringExpr(format);\n case 'integer':\n return _integerExpr(format);\n case 'number':\n return _numberExpr(format);\n default:\n return undefined;\n }\n}\n\nfunction _stringExpr(format: string | undefined): string {\n if (format === undefined) return 'z.string()';\n // Well-known formats supported by zod 4. Unknown formats fall back to\n // a plain string — `format` is opaque in our subset.\n switch (format) {\n case 'email':\n return 'z.email()';\n case 'uri':\n case 'url':\n return 'z.url()';\n case 'uuid':\n return 'z.uuid()';\n case 'date-time':\n return 'z.iso.datetime()';\n case 'date':\n return 'z.iso.date()';\n case 'time':\n return 'z.iso.time()';\n case 'duration':\n return 'z.iso.duration()';\n case 'ipv4':\n return 'z.ipv4()';\n case 'ipv6':\n return 'z.ipv6()';\n case 'base64':\n return 'z.base64()';\n case 'base64url':\n return 'z.base64url()';\n case 'nanoid':\n return 'z.nanoid()';\n case 'cuid':\n return 'z.cuid()';\n case 'cuid2':\n return 'z.cuid2()';\n case 'ulid':\n return 'z.ulid()';\n default:\n return 'z.string()';\n }\n}\n\nfunction _integerExpr(format: string | undefined): string {\n switch (format) {\n case 'int32':\n return 'z.int32()';\n case 'uint32':\n return 'z.uint32()';\n case 'int64':\n // LinkRPC values travel as JSON numbers. Zod's int64 validator\n // accepts bigint, which cannot be JSON serialized and is\n // incompatible with existing TypeScript clients.\n return 'z.int()';\n case 'uint64':\n // Retain the unsigned constraint while staying in JSON's number\n // domain instead of Zod's bigint-based uint64 representation.\n return 'z.int().nonnegative()';\n case undefined:\n return 'z.int()';\n default:\n return 'z.int()';\n }\n}\n\nfunction _numberExpr(format: string | undefined): string {\n switch (format) {\n case 'float32':\n return 'z.float32()';\n case 'float64':\n return 'z.float64()';\n case undefined:\n return 'z.number()';\n default:\n return 'z.number()';\n }\n}\n\n// ----------------------------------------------------------- meta wrapping\n\ninterface SchemaMeta {\n title?: string;\n description?: string;\n}\n\nfunction _metaOf(s: Record<string, unknown>): SchemaMeta | undefined {\n const meta: SchemaMeta = {};\n if (typeof s['description'] === 'string') meta.description = s['description'];\n if (typeof s['title'] === 'string') meta.title = s['title'];\n return meta.description === undefined && meta.title === undefined ? undefined : meta;\n}\n\n/** Wrap a single-line zod expression with `.describe()` / `.meta()`. */\nfunction _writeMetaWrapped(w: CodeWriter, expr: string, meta: SchemaMeta | undefined): void {\n w.append(expr);\n _writeMetaSuffix(w, meta);\n}\n\nfunction _writeMetaSuffix(w: CodeWriter, meta: SchemaMeta | undefined): void {\n if (meta === undefined) return;\n if (meta.title === undefined && meta.description !== undefined) {\n w.append(`.describe(${JSON.stringify(meta.description)})`);\n return;\n }\n const entries: string[] = [];\n if (meta.title !== undefined) entries.push(`title: ${JSON.stringify(meta.title)}`);\n if (meta.description !== undefined) entries.push(`description: ${JSON.stringify(meta.description)}`);\n w.append(`.meta({ ${entries.join(', ')} })`);\n}\n\n// ----------------------------------------------------------------- utils\n\nfunction _methodDescription(\n method: MethodSchema,\n components: Record<string, LinkRpcJsonSchema>,\n): string | undefined {\n if (method.description !== undefined) return method.description;\n if (method.params === true || method.params === false) return undefined;\n const params = method.params as unknown as Record<string, unknown>;\n if (typeof params['$ref'] !== 'string') return _schemaDescription(method.params);\n return _schemaDescription(components[_parseRef(params['$ref'])]);\n}\n\nfunction _schemaDescription(schema: LinkRpcJsonSchema | undefined): string | undefined {\n if (schema === undefined || schema === true || schema === false) return undefined;\n const value = schema as unknown as Record<string, unknown>;\n if (typeof value['description'] === 'string') return value['description'];\n return typeof value['title'] === 'string' ? value['title'] : undefined;\n}\n\nfunction _writeJsDoc(w: CodeWriter, description: string | undefined): void {\n if (description === undefined || description.length === 0) return;\n w.writeLine('/**');\n for (const line of description.replaceAll('*/', '*\\\\/').split(/\\r?\\n/)) {\n w.writeLine(line.length === 0 ? ' *' : ` * ${line}`);\n }\n w.writeLine(' */');\n}\n\nfunction _sortComponents(\n schemas: Record<string, LinkRpcJsonSchema>,\n): [string, LinkRpcJsonSchema][] {\n const result: [string, LinkRpcJsonSchema][] = [];\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n const visit = (name: string): void => {\n if (visited.has(name)) return;\n if (visiting.has(name)) return;\n\n const schema = schemas[name];\n if (schema === undefined) return;\n visiting.add(name);\n for (const dependency of _collectRefs(schema)) {\n if (dependency !== name && schemas[dependency] !== undefined) {\n visit(dependency);\n }\n }\n visiting.delete(name);\n visited.add(name);\n result.push([name, schema]);\n };\n\n for (const name of Object.keys(schemas)) visit(name);\n return result;\n}\n\n/** Find every node belonging to a strongly-connected component with a cycle. */\nfunction _findCyclicComponents(\n schemas: Record<string, LinkRpcJsonSchema>,\n): Set<string> {\n let nextIndex = 0;\n const index = new Map<string, number>();\n const lowLink = new Map<string, number>();\n const stack: string[] = [];\n const onStack = new Set<string>();\n const cyclic = new Set<string>();\n\n const visit = (name: string): void => {\n index.set(name, nextIndex);\n lowLink.set(name, nextIndex++);\n stack.push(name);\n onStack.add(name);\n const dependencies = [..._collectRefs(schemas[name])].filter((ref) => schemas[ref] !== undefined);\n for (const dependency of dependencies) {\n if (!index.has(dependency)) {\n visit(dependency);\n lowLink.set(name, Math.min(lowLink.get(name)!, lowLink.get(dependency)!));\n } else if (onStack.has(dependency)) {\n lowLink.set(name, Math.min(lowLink.get(name)!, index.get(dependency)!));\n }\n }\n if (lowLink.get(name) !== index.get(name)) return;\n const component: string[] = [];\n let current: string;\n do {\n current = stack.pop()!;\n onStack.delete(current);\n component.push(current);\n } while (current !== name);\n if (component.length > 1 || _collectRefs(schemas[name]).has(name)) {\n for (const item of component) cyclic.add(item);\n }\n };\n for (const name of Object.keys(schemas)) {\n if (!index.has(name)) visit(name);\n }\n return cyclic;\n}\n\nfunction _collectRefs(value: unknown, refs = new Set<string>()): Set<string> {\n if (value === null || typeof value !== 'object') return refs;\n if (Array.isArray(value)) {\n for (const item of value) _collectRefs(item, refs);\n return refs;\n }\n const record = value as Record<string, unknown>;\n if (typeof record['$ref'] === 'string') {\n refs.add(_parseRef(record['$ref']));\n }\n for (const [key, child] of Object.entries(record)) {\n if (!key.startsWith(\"x-\")) _collectRefs(child, refs);\n }\n return refs;\n}\n\nfunction _containsRef(schema: LinkRpcJsonSchema, name: string): boolean {\n return _collectRefs(schema).has(name);\n}\n\nfunction _propKey(name: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n}\n\nfunction _jsonLiteral(value: JsonValue): string {\n return JSON.stringify(value);\n}\n\nfunction _parseRef(ref: string): string {\n const prefix = '#/components/schemas/';\n if (!ref.startsWith(prefix)) {\n throw new Error(`generateInterface: unsupported $ref \"${ref}\"`);\n }\n return ref.slice(prefix.length);\n}\n\nfunction _toComponentVar(name: string): string {\n return _toIdentifier(name) + 'Schema';\n}\n\nfunction _toIdentifier(name: string): string {\n const sanitized = name.replace(/[^A-Za-z0-9_$]/g, '_');\n return /^[A-Za-z_$]/.test(sanitized) ? sanitized : `_${sanitized}`;\n}\n\nfunction _allocateComponentNames(\n schemas: Record<string, LinkRpcJsonSchema>,\n): Map<string, string> {\n return _allocateNames(Object.keys(schemas), _toComponentVar, new Set([\n 'z',\n 'defineInterface',\n 'InterfaceDefinition',\n 'notificationType',\n 'requestType',\n 'wireSchema',\n ]));\n}\n\nfunction _allocatePayloadNames(\n schemas: Record<string, LinkRpcJsonSchema>,\n cyclic: Set<string>,\n): Map<string, string> {\n return _allocateNames(\n Object.keys(schemas).filter((name) => cyclic.has(name)),\n _toIdentifier,\n new Set([\n ..._typescriptReservedWords,\n 'z', 'Array', 'LinkRpcInterfaceSchema', 'InterfaceDefinition',\n ]),\n );\n}\n\nconst _typescriptReservedWords = [\n 'any', 'as', 'asserts', 'async', 'await', 'bigint', 'boolean', 'break',\n 'case', 'catch', 'class', 'const', 'constructor', 'continue', 'debugger',\n 'declare', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends',\n 'false', 'finally', 'for', 'from', 'function', 'get', 'global', 'if',\n 'implements', 'import', 'in', 'infer', 'instanceof', 'interface',\n 'intrinsic', 'is', 'keyof', 'let', 'module', 'namespace', 'never', 'new',\n 'null', 'number', 'object', 'of', 'package', 'private', 'protected',\n 'public', 'readonly', 'require', 'return', 'satisfies', 'set', 'static',\n 'string', 'super', 'switch', 'symbol', 'this', 'throw', 'true', 'try',\n 'type', 'typeof', 'undefined', 'unique', 'unknown', 'using', 'var', 'void',\n 'while', 'with', 'yield',\n] as const;\n\nfunction _allocateNames(\n names: string[],\n candidate: (name: string) => string,\n used: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const name of names) {\n const base = candidate(name);\n let allocated = base;\n let suffix = 2;\n while (used.has(allocated)) allocated = `${base}_${suffix++}`;\n used.add(allocated);\n result.set(name, allocated);\n }\n return result;\n}\n\nfunction _deriveExportName(id: string): string {\n const parts = id.split(/[^A-Za-z0-9]+/).filter((p) => p.length > 0);\n if (parts.length === 0) return 'iface';\n const camel = parts[0]!.toLowerCase() +\n parts.slice(1).map((p) => p[0]!.toUpperCase() + p.slice(1).toLowerCase()).join('');\n return camel + 'Interface';\n}\n","import { array, boolean, int, nonnegative, number, object, optional, positive, string, union, unknown } from \"zod/mini\";\nimport type { output as zInfer } from \"zod/v4/core\";\nimport { defineInterface, type StreamApi } from \"../../connection/interfaceDefinition\";\nimport { requestType } from \"../../schema/memberTypes\";\n\nexport const defaultsInterface = defineInterface(\n {\n id: \"hubrpc.defaults\",\n description: \"Reflection: preset default service / interface on this connection.\",\n },\n {\n get: requestType(\n object({}),\n object({\n serviceId: optional(string()),\n interfaceId: optional(string()),\n /** Hash of the preset interface, if known. */\n interfaceHash: optional(string()),\n }),\n ),\n listBindings: requestType(\n object({}),\n object({\n bindings: array(object({\n prefix: string(),\n serviceId: optional(string()),\n interfaceId: string(),\n interfaceHash: string(),\n })),\n }),\n ),\n },\n);\n\n/**\n * A single root-principal requirement. `transitive: true` means the requirement\n * also applies to every service reachable *through* this one — i.e. when this\n * listing is a `hubrpc.directory` reference, everything it lists inherits the\n * requirement (also as transitive).\n */\nconst zRootPrincipalReq = object({\n principal: string(),\n transitive: optional(boolean()),\n});\n\n/** One OR-set. The set is satisfied by holding *any one* of its principals. */\nconst zRootPrincipalSet = array(zRootPrincipalReq);\n\nexport type RootPrincipalReq = zInfer<typeof zRootPrincipalReq>;\nexport type RootPrincipalSet = zInfer<typeof zRootPrincipalSet>;\n\nexport const zServiceIdPattern = union([\n object({ exact: string() }),\n object({ prefix: string() }),\n]);\n\nexport type ServiceIdPattern = zInfer<typeof zServiceIdPattern>;\n\nconst zServiceListing = object({\n serviceId: string(),\n interfaceId: string(),\n /** Hash of the interface as implemented by this service. */\n interfaceHash: string(),\n /** Optional non-normative description of the owning service. */\n serviceDescription: optional(string()),\n /**\n * Root principals required to access this service, in CNF: the caller must\n * satisfy **every** set (AND), and a set is satisfied by **any one** of its\n * principals (OR). Omitted/empty => no root-principal requirement.\n */\n rootPrincipalSets: optional(array(zRootPrincipalSet)),\n /**\n * Service-id regions reachable through this referral. Meaningful only for\n * `hubrpc.directory` entries; omission defaults to the referral service-id\n * subtree.\n */\n reachableServiceIds: optional(array(zServiceIdPattern)),\n});\n\nexport const directoryInterface = defineInterface(\n {\n id: \"hubrpc.directory\",\n description:\n \"Reflection: list services exposed by this endpoint. Can also list other directory services that can be explored.\",\n },\n {\n list: requestType(\n object({\n /** Filter: only return services implementing this interface id. */\n interfaceId: optional(string()),\n /** Filter: only return services whose interface id starts with this prefix. */\n interfaceIdPrefix: optional(string()),\n /** Filter: only return entries for this service id. */\n serviceId: optional(string()),\n /** Union filter used to constrain a transitive directory walk. */\n serviceIdScopes: optional(array(zServiceIdPattern)),\n\n /** Paging: opaque continuation token from a previous response. */\n cursor: optional(string()),\n /** Paging: max items in this page. Server MAY return fewer. */\n limit: optional(number().check(int(), positive())),\n\n /** Soft cap on time the server spends gathering this page, in ms. */\n timeoutMs: optional(number().check(int(), nonnegative())),\n }),\n object({\n items: array(zServiceListing),\n /** Omitted => no more pages. */\n nextCursor: optional(string()),\n /** True if `timeoutMs` cut the page short before exhausting results. */\n truncated: optional(boolean()),\n }),\n ),\n /**\n * Coarse change tap on the directory.\n *\n * `watch` is a long-lived streaming request that emits an **empty tick**\n * whenever the (optionally filtered) directory *might* have changed. The\n * tick carries no delta and no payload — its only meaning is \"re-`list`\n * now\". The consumer reconciles against its own last snapshot.\n *\n * This keeps the server stateless: it never computes or replays\n * per-item deltas, never does an initial-sync replay. Over-emission is\n * allowed (the consumer re-lists and finds nothing new); under-emission\n * is not. Ticks are coalesced. The `interfaceId` / `serviceId` filters\n * mirror `list` and are a relevance hint, not a guarantee.\n *\n * The request resolves when the caller cancels (or the connection\n * drops); the runtime auto-detaches the stream when it settles.\n */\n watch: requestType(\n object({\n /** Relevance hint: changes touching this interface id. */\n interfaceId: optional(string()),\n /** Relevance hint: changes touching an interface id with this prefix. */\n interfaceIdPrefix: optional(string()),\n /** Relevance hint: changes touching this service id. */\n serviceId: optional(string()),\n /** Relevance hint: changes within any of these service-id regions. */\n serviceIdScopes: optional(array(zServiceIdPattern)),\n }),\n object({}),\n ).withStream({\n /** Empty tick: \"the directory may have changed; re-list.\" */\n server: object({}),\n }),\n },\n);\n\n/**\n * A `directoryInterface.watch` handler for a **static** directory. It opens the\n * stream, never ticks, and resolves when the caller cancels. Dynamic providers,\n * including {@link LinkRpcConnection.enableReflection}, use a change-emitting\n * implementation instead.\n */\nexport function directoryWatchNever(\n _params: {\n interfaceId?: string;\n interfaceIdPrefix?: string;\n serviceId?: string;\n serviceIdScopes?: ServiceIdPattern[];\n },\n _ctx: unknown,\n stream: StreamApi<unknown, Record<string, never>>,\n): Promise<Record<string, never>> {\n return new Promise((resolve) => {\n if (stream.signal.aborted) {\n resolve({});\n return;\n }\n stream.signal.addEventListener(\"abort\", () => resolve({}), { once: true });\n });\n}\n\nexport const schemasInterface = defineInterface(\n {\n id: \"hubrpc.schemas\",\n description:\n \"Reflection: fetch interface schemas by id (+ optional hash). Must serve the interfaces advertised in this endpoint's directory.\",\n },\n {\n get: requestType(\n object({\n interfaceId: string(),\n /** Omit => server picks the version it exposes. */\n hash: optional(string()),\n }),\n object({\n /** A full `SvcInterfaceSchema`. */\n schema: unknown(),\n }),\n ),\n },\n);\n","import { enum as zEnum, number, object, optional, string, union, unknown } from \"zod/mini\";\nimport type { output as zInfer } from \"zod/v4/core\";\nimport { defineInterface } from \"./interfaceDefinition\";\nimport { notificationType } from \"../schema/memberTypes\";\n\n/**\n * Direction a {@link STREAM_METHOD} message travels, relative to the\n * request it is correlated with. Made explicit on the wire so that a\n * middlebox (the hub) can *author* a stream message — e.g. inject a\n * cancel when a caller disconnects — without an inbound message whose\n * arrival link it could infer the direction from.\n */\nexport const StreamDir = {\n /** callee → caller: progress, partial results. Routes like a response. */\n toCaller: \"toCaller\",\n /** caller → callee: input, cancellation, keepalive ping. */\n toCallee: \"toCallee\",\n} as const;\nexport type StreamDir = (typeof StreamDir)[keyof typeof StreamDir];\n\n/**\n * Reserved control verbs. A control message carries no app `payload`; it\n * is interpreted by the runtime / hub itself, independently of the\n * originating method's stream schemas, so *any* request is cancellable\n * and keep-alive-able even when it declares no app stream.\n */\nexport const StreamControlType = {\n /**\n * Ask the callee to abort the in-flight request. Always {@link\n * StreamDir.toCallee}. The callee surfaces this as an `AbortSignal`\n * and is expected to settle the request (typically with a\n * `cancelled` error response).\n */\n cancel: \"cancel\",\n /**\n * Keepalive / liveness probe. Resets the hub's per-request idle timer\n * so a long-running call is not reaped, and lets either side actively\n * probe the peer. Carries a `nonce` the peer echoes in its {@link\n * StreamControlType.pong}. May travel in either direction. Emitted\n * automatically (without awaiting a pong) by the channel for streaming\n * calls; see {@link STREAM_METHOD}.\n */\n ping: \"ping\",\n /**\n * Reply to a {@link StreamControlType.ping}, echoing the ping's\n * `nonce` so the prober can correlate it. Travels opposite the ping.\n * Carries no app effect — purely a liveness acknowledgement.\n */\n pong: \"pong\",\n} as const;\nexport type StreamControlType = (typeof StreamControlType)[keyof typeof StreamControlType];\n\n/**\n * Well-known `control.reason` strings. The set is **open** — any string\n * is valid on the wire; these are the reasons linkrpc itself emits.\n */\nexport const StreamControlReason = {\n /**\n * The caller's transport dropped while the request was in flight; the\n * hub cancels the callee's now-orphaned work.\n */\n clientDisconnected: \"clientDisconnected\",\n /**\n * The request exceeded the hub's idle timeout with no stream activity\n * (no ping, no stream message). See {@link STREAM_METHOD} docs.\n */\n idleTimeout: \"idleTimeout\",\n} as const;\nexport type StreamControlReason = (typeof StreamControlReason)[keyof typeof StreamControlReason];\n\n/**\n * Streaming sub-protocol. Long-running requests can emit additional\n * notifications correlated with the original call in either direction\n * (callee → caller progress, caller → callee input / cancellation /\n * keepalive).\n *\n * Wire form: a JSON-RPC notification whose method is\n * `${streamInterface.info.id}::send` and whose params match\n * `streamInterface.members.send.paramsSchema`. The hub routes purely on\n * `requestId` (following the originating request's established path, like\n * a response); the originating request's capability authorization covers\n * its full stream lifetime, so stream notifications carry no method /\n * interface namespace of their own. App `payload` contents are typed per\n * request via the originating method's\n * `RequestType.clientStreamSchema` / `serverStreamSchema`; reserved\n * `control` messages are schema-independent.\n *\n * Idle timeout: a request that never streams (no `control` ping, no\n * stream message) is subject to the hub's per-request idle timeout\n * (default 30 minutes) — at which point it is cancelled and its caller\n * gets a `requestTimeout` error. This bounds the hub's pending-request\n * table, which is also what protects it from a slow-loris / DDoS that\n * opens requests and never completes them. Streaming-enabled calls keep\n * themselves alive by emitting a periodic {@link StreamControlType.ping}.\n *\n * The interface is declarative: nobody calls\n * `LinkRpcConnection.register(streamInterface, ...)`. The channel and the\n * hub intercept `$stream::send` directly. The definition exists so\n * reflection / consent UIs can describe the wire shape and so all wire\n * constants derive from one source.\n */\nexport const streamInterface = defineInterface(\n {\n id: \"$stream\",\n description:\n \"Reserved sub-protocol for in-flight stream messages \"\n + \"correlated to a request by `requestId`.\",\n },\n {\n send: notificationType(\n object({\n /**\n * Id of the in-flight request the message belongs to.\n * The hub rewrites this across the forwarding boundary\n * in the same way it rewrites response ids.\n */\n requestId: union([number(), string()]),\n /**\n * Which way this message travels relative to the request.\n * Explicit so the hub can author messages (e.g. cancel on\n * disconnect) without inferring direction from arrival.\n */\n dir: zEnum([\"toCaller\", \"toCallee\"]),\n /**\n * Reserved control verb (cancel / ping / pong). Mutually\n * exclusive with `payload` in practice: a control message\n * is interpreted by the runtime, not the application.\n */\n control: optional(\n object({\n type: zEnum([\"cancel\", \"ping\", \"pong\"]),\n /** Open-set human/diagnostic reason; see {@link StreamControlReason}. */\n reason: optional(string()),\n /**\n * Correlation token. A `ping` carries a fresh nonce;\n * the matching `pong` echoes it back so the prober\n * can resolve the right outstanding probe.\n */\n nonce: optional(string()),\n })\n ),\n /** Opaque app payload — typed per call by the request's stream schema. */\n payload: optional(unknown()),\n }),\n {\n description:\n \"Emit a stream message tied to the request `requestId`.\",\n },\n ),\n },\n);\n\n/**\n * Full wire method name for stream notifications. Pulled from the\n * interface object so we have a single source of truth.\n */\nexport const STREAM_METHOD = `${streamInterface.info.id}::send` as const;\n\n/** Wire-level shape carried on `params` of {@link STREAM_METHOD}. */\nexport type StreamSendParams = zInfer<typeof streamInterface.members.send.paramsSchema>;\n\n","/**\n * Minimal JSON-RPC 2.0 wire types — only what we need to send and receive\n * requests, notifications, and responses.\n */\n\nimport type { JsonValue } from \"./jsonValue\";\n\nexport type { JsonValue };\n\nexport type RequestId = number | string;\n\nexport interface JsonRpcRequest<TParams = JsonValue> {\n jsonrpc: \"2.0\";\n id: RequestId;\n method: string;\n params?: TParams;\n}\n\nexport interface JsonRpcNotification<TParams = JsonValue> {\n jsonrpc: \"2.0\";\n method: string;\n params?: TParams;\n}\n\nexport interface JsonRpcSuccess {\n jsonrpc: \"2.0\";\n id: RequestId | null;\n result: JsonValue;\n}\n\nexport interface JsonRpcError {\n jsonrpc: \"2.0\";\n id: RequestId | null;\n error: { code: number; message: string; data?: JsonValue };\n}\n\nexport type JsonRpcResponse = JsonRpcSuccess | JsonRpcError;\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;\n\nexport const ErrorCode = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n /** Caller is authenticated but lacks a capability covering the call. */\n permissionRequired: -32401,\n /** The peer a request was routed to detached before it could respond. */\n peerDisconnected: -32402,\n /** The request exceeded the hub's idle timeout with no stream activity. */\n requestTimeout: -32403,\n /** The request was cancelled (by the caller, or by the hub on disconnect). */\n cancelled: -32800,\n} as const;\n\nexport function isRequest(m: JsonRpcMessage): m is JsonRpcRequest {\n return typeof (m as JsonRpcRequest).method === \"string\"\n && (m as JsonRpcRequest).id !== undefined;\n}\n\nexport function isNotification(m: JsonRpcMessage): m is JsonRpcNotification {\n return typeof (m as JsonRpcNotification).method === \"string\"\n && (m as JsonRpcRequest).id === undefined;\n}\n\nexport function isResponse(m: JsonRpcMessage): m is JsonRpcResponse {\n return typeof (m as JsonRpcRequest).method !== \"string\";\n}\n","/**\n * Identity primitives. linkrpc itself is identity-agnostic; this module\n * defines the shared types. No crypto code lives here — the crypto API is\n * `./crypto` (backed by the Web Crypto implementation in\n * `./ed25519CryptoProvider`).\n */\n\n/** Raw Ed25519 public key (32 bytes). */\nexport type PublicKey = Uint8Array;\n\n/** Raw Ed25519 private key (32 bytes — seed form). */\nexport type PrivateKey = Uint8Array;\n\n/** Raw Ed25519 signature (64 bytes). */\nexport type Signature = Uint8Array;\n\n/**\n * A **principal**: an identity's stable, opaque name. In Phase 1 every\n * principal is *perpetual* and self-describing — its genesis signing key is\n * embedded verbatim:\n *\n * principal = \"id:\" + keyId (e.g. \"id:key:<b64url(pubKey)>\")\n *\n * So the genesis check is pure string equality (`\"id:\" + keyId === principal`)\n * and no key-binding records are ever needed. Treat as opaque; construct via\n * {@link principalForPublicKey} and resolve a verifying key via\n * {@link resolveSigningKey}.\n */\nexport type PrincipalId = string;\n\n/**\n * A **keyId**: names the signing key that produced a signature. In Phase 1 the\n * only form is an *inline* key — the public key encoded verbatim:\n *\n * keyId = \"key:\" + b64url(pubKey)\n *\n * (Future forms, e.g. `\"keydoc:\" + b64url(sha256(jcs(doc)))`, are resolved\n * through bindings — see the design doc — but Phase 1 needs none.)\n */\nexport type KeyId = string;\n\nexport interface Keypair {\n readonly publicKey: PublicKey;\n readonly privateKey: PrivateKey;\n}\n\n/** Raw X25519 keypair. Both halves are 32 bytes. */\nexport interface X25519Keypair {\n readonly publicKey: Uint8Array;\n readonly privateKey: Uint8Array;\n}\n\n// ---- base64url codec (no padding) ----------------------------------------\n\nconst _b64UrlAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst _b64UrlReverse: Record<string, number> = (() => {\n const m: Record<string, number> = {};\n for (let i = 0; i < _b64UrlAlphabet.length; i++) m[_b64UrlAlphabet[i]] = i;\n return m;\n})();\n\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n let i = 0;\n for (; i + 3 <= bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out += _b64UrlAlphabet[(n >> 18) & 63]\n + _b64UrlAlphabet[(n >> 12) & 63]\n + _b64UrlAlphabet[(n >> 6) & 63]\n + _b64UrlAlphabet[n & 63];\n }\n const rem = bytes.length - i;\n if (rem === 1) {\n const n = bytes[i] << 16;\n out += _b64UrlAlphabet[(n >> 18) & 63] + _b64UrlAlphabet[(n >> 12) & 63];\n } else if (rem === 2) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8);\n out += _b64UrlAlphabet[(n >> 18) & 63]\n + _b64UrlAlphabet[(n >> 12) & 63]\n + _b64UrlAlphabet[(n >> 6) & 63];\n }\n return out;\n}\n\nexport function base64UrlToBytes(s: string): Uint8Array {\n const len = s.length;\n const fullGroups = Math.floor(len / 4);\n const rem = len % 4;\n if (rem === 1) throw new Error(\"base64UrlToBytes: invalid length\");\n const outLen = fullGroups * 3 + (rem === 0 ? 0 : rem - 1);\n const out = new Uint8Array(outLen);\n let oi = 0;\n let i = 0;\n for (let g = 0; g < fullGroups; g++, i += 4) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12) | (_lookup(s, i + 2) << 6) | _lookup(s, i + 3);\n out[oi++] = (n >> 16) & 0xff;\n out[oi++] = (n >> 8) & 0xff;\n out[oi++] = n & 0xff;\n }\n if (rem === 2) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12);\n out[oi++] = (n >> 16) & 0xff;\n } else if (rem === 3) {\n const n = (_lookup(s, i) << 18) | (_lookup(s, i + 1) << 12) | (_lookup(s, i + 2) << 6);\n out[oi++] = (n >> 16) & 0xff;\n out[oi++] = (n >> 8) & 0xff;\n }\n return out;\n}\n\nfunction _lookup(s: string, i: number): number {\n const v = _b64UrlReverse[s[i]];\n if (v === undefined) throw new Error(`base64UrlToBytes: invalid char at ${i}`);\n return v;\n}\n\n// ---- principals & keyIds (the identity ⇄ key seam) -----------------------\n\n/** Role-tag prefix on a {@link KeyId}'s inline-key form. */\nexport const KEY_ID_PREFIX = \"key:\";\n\n/** Role-tag prefix that wraps a genesis {@link KeyId} into a {@link PrincipalId}. */\nexport const PRINCIPAL_PREFIX = \"id:\";\n\n/** The inline {@link KeyId} for a raw public key: `\"key:\" + b64url(pk)`. */\nexport function keyIdForPublicKey(pk: PublicKey): KeyId {\n return KEY_ID_PREFIX + bytesToBase64Url(pk);\n}\n\n/** The perpetual {@link PrincipalId} for a raw public key: `\"id:key:\" + b64url(pk)`. */\nexport function principalForPublicKey(pk: PublicKey): PrincipalId {\n return PRINCIPAL_PREFIX + keyIdForPublicKey(pk);\n}\n\n/**\n * The genesis {@link KeyId} embedded in a perpetual {@link PrincipalId}\n * (`\"id:\" + keyId`). Throws if `principal` is not a well-formed `id:` name.\n */\nexport function keyIdForPrincipal(principal: PrincipalId): KeyId {\n if (!principal.startsWith(PRINCIPAL_PREFIX)) {\n throw new Error(`malformed principal (missing \"${PRINCIPAL_PREFIX}\" prefix): ${principal}`);\n }\n return principal.slice(PRINCIPAL_PREFIX.length);\n}\n\n/**\n * The raw public key carried inline by a `\"key:\"` {@link KeyId}. Throws on a\n * missing prefix or malformed base64url.\n */\nexport function publicKeyForKeyId(keyId: KeyId): PublicKey {\n if (!keyId.startsWith(KEY_ID_PREFIX)) {\n throw new Error(`unsupported keyId (expected \"${KEY_ID_PREFIX}\" prefix): ${keyId}`);\n }\n return base64UrlToBytes(keyId.slice(KEY_ID_PREFIX.length));\n}\n\n/** Arguments to {@link resolveSigningKey}. */\nexport interface ResolveSigningKeyArgs {\n /** The identity the signature claims to be from. */\n readonly principal: PrincipalId;\n /** Which key (per `$hubrpcSignature[domain].keyId`) is claimed to have signed. */\n readonly keyId: KeyId;\n /** Presented key-binding records. Unused in Phase 1 (perpetual ids need none). */\n readonly bindings?: Record<KeyId, unknown>;\n /** Time the signature was made (e.g. `signedAtMs`). Unused in Phase 1. */\n readonly timeMs?: number;\n}\n\n/**\n * Resolve the verifying public key for `(principal, keyId)`, or `undefined`\n * to **reject** (fail closed). This is the single seam every verifier goes\n * through, replacing the old \"the id *is* the key\" decode.\n *\n * Phase 1 supports only inline genesis keys: the `keyId` must be a `\"key:\"`\n * form and the principal must be exactly `\"id:\" + keyId` (genesis\n * self-certification by string equality). `keydoc:`/rotation forms resolve\n * through `bindings`/`timeMs` later and are intentionally not handled here.\n */\nexport function resolveSigningKey(args: ResolveSigningKeyArgs): { publicKey: PublicKey } | undefined {\n const { principal, keyId } = args;\n if (!keyId.startsWith(KEY_ID_PREFIX)) {\n return undefined; // keydoc:/rotation — deferred\n }\n if (PRINCIPAL_PREFIX + keyId !== principal) {\n return undefined; // not this principal's genesis key\n }\n try {\n return { publicKey: base64UrlToBytes(keyId.slice(KEY_ID_PREFIX.length)) };\n } catch {\n return undefined; // malformed base64url\n }\n}\n","/**\n * The HubRPC **signed-object** standard: one rule for committing a\n * signature (and a content hash) over any JSON object.\n *\n * > The signature `obj.$hubrpcSignature[domain]` covers\n * > `jcs({ [domainValue(domain)]: obj without $hubrpcSignature and $hubrpcUnsigned })`.\n *\n * Both reserved keys are stripped before canonicalization — on **every**\n * object, call or capability alike:\n *\n * - {@link HUBRPC_SIGNATURE_KEY} (`$hubrpcSignature`) holds the signature\n * itself (a domain-keyed map of `{ keyId, sig }` entries). It can't sign\n * itself, so it's excluded.\n * - {@link HUBRPC_UNSIGNED_KEY} (`$hubrpcUnsigned`) holds extrinsic\n * *attachments* (e.g. the presented capability bag) authored by someone\n * other than this signer, so it's excluded too.\n *\n * Domain separation is intrinsic: the per-domain {@link signingDomainValue}\n * is the sole key of the canonicalized wrapper object. A `\"call\"` signature\n * can therefore never verify as a `\"capability\"` (or vice-versa). The domain\n * is *supplied by context* by signer and verifier;\n * the on-wire `$hubrpcSignature` key is a convenience index, never a trust\n * claim.\n *\n * This module is pure (no private keys, no `crypto.verify`): it only defines\n * the canonical bytes. Signing/verifying live in `../identity/signedObject`.\n */\n\nimport { jcsCanonicalizeBytes } from \"./jcs\";\nimport { sha256 } from \"../crypto/sha256\";\nimport { bytesToBase64Url, type KeyId } from \"../crypto/cryptoProvider\";\n\n/** An open signature domain. Each gets a distinct {@link signingDomainValue}. */\nexport type SignDomain = string;\n\n/** Reserved wire-key: the signature map `{ [domain]: SignatureEnvelope }`. */\nexport const HUBRPC_SIGNATURE_KEY = \"$hubrpcSignature\";\n\n/** Reserved wire-key: extrinsic unsigned attachments (e.g. the capability bag). */\nexport const HUBRPC_UNSIGNED_KEY = \"$hubrpcUnsigned\";\n\n/** Reserved wire-key: signed call meta, present only on calls (dodges the JSON-RPC param namespace). */\nexport const HUBRPC_META_KEY = \"$hubrpc\";\n\n/** @deprecated Use {@link HUBRPC_SIGNATURE_KEY}. */\nexport const LINKRPC_SIGNATURE_KEY = HUBRPC_SIGNATURE_KEY;\n/** @deprecated Use {@link HUBRPC_UNSIGNED_KEY}. */\nexport const LINKRPC_UNSIGNED_KEY = HUBRPC_UNSIGNED_KEY;\n/** @deprecated Use {@link HUBRPC_META_KEY}. */\nexport const LINKRPC_META_KEY = HUBRPC_META_KEY;\n\n/**\n * One domain's signature on the wire: which key signed ({@link KeyId}, an\n * **unsigned** routing hint) plus the raw `base64url(sig)`. Lying about\n * `keyId` only makes verification fail (the resolver rejects or the key\n * mismatches), so it carries no integrity claim and is excluded from the\n * signed bytes along with the rest of `$hubrpcSignature`.\n */\nexport interface SignatureEnvelope {\n /** The key the signer used (`\"key:...\"`). Resolved against the principal. */\n readonly keyId: KeyId;\n /** `base64url` of the raw signature over {@link signingInput}. */\n readonly sig: string;\n}\n\n/** Per-domain signature map carried under {@link HUBRPC_SIGNATURE_KEY}. */\nexport type Signatures = { readonly [D in SignDomain]?: SignatureEnvelope };\n\n/** Documentary brand for `base64url(sha256(signingInput(domain, T)))`. */\nexport type Base64Sha256<T = unknown> = string & { readonly __sha256Of?: T };\n\n/**\n * The domain-separation key. It includes the frozen signature-suite version\n * and becomes the sole key of the object passed to JCS.\n */\nexport function signingDomainValue(domain: SignDomain): string {\n return `hubrpc-sig/v1/${domain}`;\n}\n\n/**\n * THE bytes a signature commits to (and a content hash hashes) for `obj` in\n * `domain`: `jcs({ [domainValue(domain)]: obj minus the two reserved keys })`.\n */\nexport function signingInput(domain: SignDomain, obj: object): Uint8Array {\n const signed = { ...(obj as Record<string, unknown>) };\n delete signed[HUBRPC_SIGNATURE_KEY];\n delete signed[HUBRPC_UNSIGNED_KEY];\n return jcsCanonicalizeBytes({ [signingDomainValue(domain)]: signed });\n}\n\n/**\n * Content identity of a signed object: `base64url(sha256(signingInput(...)))`.\n * The single operation behind both a capability's `callBind.payloadHash`\n * (domain `\"call\"`) and a child capability's `parentHash` (domain\n * `\"capability\"`).\n */\nexport function signedHash<T extends object>(domain: SignDomain, obj: T): Base64Sha256<T> {\n return bytesToBase64Url(sha256(signingInput(domain, obj))) as Base64Sha256<T>;\n}\n\n/** Read the signature envelope for `domain` off an object's `$hubrpcSignature` map. */\nexport function readSignature(obj: object, domain: SignDomain): SignatureEnvelope | undefined {\n const sigs = (obj as Record<string, unknown>)[HUBRPC_SIGNATURE_KEY] as Signatures | undefined;\n if (sigs === null || typeof sigs !== \"object\") return undefined;\n const entry = sigs[domain];\n if (entry === null || typeof entry !== \"object\") return undefined;\n const { keyId, sig } = entry as { keyId?: unknown; sig?: unknown };\n if (typeof keyId !== \"string\" || typeof sig !== \"string\") return undefined;\n return { keyId, sig };\n}\n\n/** The {@link KeyId} the signer used for `domain` (the unsigned routing hint), if any. */\nexport function getKeyId(obj: object, domain: SignDomain): KeyId | undefined {\n return readSignature(obj, domain)?.keyId;\n}\n\n/**\n * Return a copy of `obj` with `$hubrpcSignature[domain]` set to `envelope`,\n * preserving any sibling-domain signatures already present.\n */\nexport function withSignature<T extends object>(obj: T, domain: SignDomain, envelope: SignatureEnvelope): T & { $hubrpcSignature: Record<string, SignatureEnvelope> } {\n const prev = (obj as Record<string, unknown>)[HUBRPC_SIGNATURE_KEY] as Signatures | undefined;\n return { ...obj, [HUBRPC_SIGNATURE_KEY]: { ...prev, [domain]: envelope } } as T & { $hubrpcSignature: Record<string, SignatureEnvelope> };\n}\n","/**\n * Capability protocol types and pure (sync, no-crypto) helpers.\n *\n * Wire shapes and the matchers that decide whether a call falls inside a\n * capability's permissions. Anything involving signature verification or\n * private keys lives in `../identity/capability` instead.\n */\n\nimport { type PrincipalId } from \"../crypto/cryptoProvider\";\nimport { jcsCanonicalize } from \"./jcs\";\nimport {\n type Base64Sha256,\n HUBRPC_SIGNATURE_KEY,\n readSignature,\n type Signatures,\n} from \"./signedObject\";\n\n// ---- Types ---------------------------------------------------------------\n\n/**\n * A single axis matcher. Empty prefix matches anything. Non-empty prefix `p`\n * matches `value` iff:\n * - `value === p`, OR\n * - `value` starts with `p + delimiter` (delimiter depends on the axis).\n *\n * For axes without a delimiter (`member`), prefix degrades to `startsWith`.\n */\nexport type Pattern = { exact: string } | { prefix: string };\n\n/**\n * Per-field matcher used by {@link Permission.params}. The set of declared\n * keys is a strict allowlist — a call whose params carry an undeclared key\n * is rejected, so the only way to permit a free value is to say\n * `{ any: true }` explicitly. Values are compared via canonical-JSON\n * equality, so anything JSON-serializable is acceptable.\n *\n * - `exact` — canonical-JSON equality against a single value.\n * - `enum` — canonical-JSON equality against any value in the list.\n * - `prefix` — value MUST be a string and `startsWith(prefix)`. Used to\n * pin e.g. a URL to a base-path subtree.\n * - `subsetOf` — value MUST be a `string[]` whose every element is in this\n * set. Order-independent; the empty array is a valid subset.\n * Used to bound a requested scope set.\n * - `any` — matches anything (the explicit wildcard).\n */\nexport type ParamMatcher =\n | { exact: unknown }\n | { enum: unknown[] }\n | { prefix: string }\n | { subsetOf: string[] }\n | { any: true };\n\n/**\n * The exact, point-precision narrowing of a {@link Permission}: it admits\n * **one** signed RPC call — the one whose call content-hash\n * ({@link import(\"./signedObject\").signedHash}`(\"call\", signedCall)`, i.e.\n * `base64url(sha256(jcs({ \"hubrpc-sig/v1/call\": userParams + $hubrpc })))`)\n * equals `payloadHash`. No field-by-field comparison; pure hash equality.\n * This is the *same bytes the call signature commits to*, so the host can\n * pre-compute it at consent time exactly as the consumer will sign.\n *\n * Because it binds the entire signed payload, `callBind` pins **every**\n * signed field at once — method, user params, `nonce`, `signedAtMs`,\n * `signer`, and `interfaceHash?`. Since the bound bytes include the\n * per-request `nonce`, a `callBind` grant is intrinsically single-use:\n * the request-nonce ledger rejects any replay of the one call it names.\n *\n * Used for \"Allow once\" flows where the user approved a single concrete call.\n */\nexport interface CallBind {\n /** Hash algorithm. Currently always \"sha256\". */\n alg: \"sha256\";\n /**\n * `signedHash(\"call\", signedCall)` — the SHA-256 of exactly the bytes the\n * RPC signature commits to, for the one call this permission is bound to.\n */\n payloadHash: Base64Sha256;\n}\n\n/**\n * The address of a class of calls, expressed as patterns. A\n * {@link CallTarget} is admitted iff every axis pattern admits it.\n */\nexport interface TargetPattern {\n /** Delimiter `/`. `\"github\"` matches `\"github/repos\"` but not `\"githubclone\"`. */\n serviceId: Pattern;\n /** Delimiter `.`. `\"linkrpc\"` matches `\"hubrpc.directory\"` but not `\"linkrpcx.foo\"`. */\n interfaceId: Pattern;\n /**\n * Optional schema-version pin. When set, the call's asserted\n * `interfaceHash` (carried in `$hubrpc.interfaceHash`) must equal this\n * string. Omit to accept any version.\n */\n interfaceHash?: string;\n /**\n * Any-of: the call's member must match at least one pattern. Empty\n * list matches nothing. `[{ prefix: \"\" }]` is the universal wildcard.\n */\n members: Pattern[];\n}\n\n/**\n * One grant clause of a {@link Capability}. Denotes a set of calls the\n * holder may make, described at up to three zoom levels (coarse → exact):\n *\n * - `target` — *which endpoint* (always present);\n * - `params` — *which argument values* (optional value allowlist);\n * - `callBind` — *which exact call* (optional collapse to a single call).\n *\n * The {@link canInvoke}/{@link canDelegate} flags say what the holder may\n * *do* with that set: invoke calls in it, and/or delegate (re-issue a\n * narrowed grant) onward. Both default to `false` (fail closed) — a\n * permission that grants neither admits nothing.\n */\nexport interface Permission {\n /** Which endpoints this clause talks about. */\n target: TargetPattern;\n /** The holder may invoke calls in the set. Default `false`. */\n canInvoke?: boolean;\n /** The holder may delegate (re-issue a narrowed grant) of the set. Default `false`. */\n canDelegate?: boolean;\n /**\n * Optional value-level narrowing. Strict allowlist by top-level param\n * key: the call's param key-set must equal the declared set; each value\n * must satisfy its matcher. Omit to accept any params.\n */\n params?: Record<string, ParamMatcher>;\n /** Optional collapse to a single exact signed call. See {@link CallBind}. */\n callBind?: CallBind;\n}\n\nexport interface Capability {\n /** Issuer principal (signer of this cap). */\n issuer: PrincipalId;\n /** Audience principal (holder allowed to wield it). */\n audience: PrincipalId;\n /** What the holder may do. A call is permitted by the cap iff it is permitted by **any** permission. */\n permissions: Permission[];\n /** Unix milliseconds. Absent = never expires. */\n expiresAtMs?: number;\n /**\n * The single parent this cap delegates from, referenced by its content\n * hash (`signedHash(\"capability\", parent)`). Linearized — at most one\n * parent. The parent itself travels out-of-band in the call's\n * `$hubrpcUnsigned.capabilities` bag and is resolved by this hash.\n * Effective authority is the intersection over the chain: a call must be\n * permitted by every link. Absent = this cap is a root.\n */\n parentHash?: Base64Sha256<Capability>;\n /** Per-cap distinguisher (base64url). Identifies the capability for audit/logging. */\n nonce: string;\n}\n\n/**\n * A capability with its issuer's signature attached under\n * `$hubrpcSignature.capability`. It IS a {@link Capability} (the fields are\n * top-level) plus the signature map — no separate wrapper object. The\n * signature commits to `signingInput(\"capability\", cap)`, i.e. the cap with\n * `$hubrpcSignature`/`$hubrpcUnsigned` stripped.\n */\nexport type SignedCapability = Capability & {\n readonly [HUBRPC_SIGNATURE_KEY]: Signatures;\n};\n\n/**\n * Structural wire-shape check for an untrusted signed capability. This does\n * not establish authenticity; callers must still verify its signature and\n * delegation chain.\n */\nexport function hasSignedCapabilityShape(value: unknown): value is SignedCapability {\n if (!_isRecord(value)) return false;\n if (\n typeof value.issuer !== \"string\" ||\n typeof value.audience !== \"string\" ||\n typeof value.nonce !== \"string\" ||\n !Array.isArray(value.permissions) ||\n !value.permissions.every(_hasPermissionShape) ||\n (value.expiresAtMs !== undefined && typeof value.expiresAtMs !== \"number\") ||\n (value.parentHash !== undefined && typeof value.parentHash !== \"string\")\n ) {\n return false;\n }\n return readSignature(value, \"capability\") !== undefined;\n}\n\n/**\n * The address of a concrete call — *which endpoint*, with no arguments.\n * This is what {@link TargetPattern} matches against. The full concrete\n * call (with params/nonce/signer/bytes) is `Call` in `identity/capability`.\n */\nexport interface CallTarget {\n serviceId: string;\n interfaceId: string;\n member: string;\n /**\n * Schema-version assertion the caller stamps from its compile-time\n * knowledge of the interface (typed clients use `iface.schemaHash`).\n * Compared against `TargetPattern.interfaceHash` by the matcher. Absent\n * means the caller didn't pin a version — the matcher then requires\n * `target.interfaceHash` to also be absent.\n */\n interfaceHash?: string;\n}\n\nfunction _hasPermissionShape(value: unknown): value is Permission {\n if (!_isRecord(value) || !_isRecord(value.target)) return false;\n const target = value.target;\n if (\n !_hasPatternShape(target.serviceId) ||\n !_hasPatternShape(target.interfaceId) ||\n !Array.isArray(target.members) ||\n !target.members.every(_hasPatternShape) ||\n (target.interfaceHash !== undefined && typeof target.interfaceHash !== \"string\") ||\n (value.canInvoke !== undefined && typeof value.canInvoke !== \"boolean\") ||\n (value.canDelegate !== undefined && typeof value.canDelegate !== \"boolean\")\n ) {\n return false;\n }\n if (value.params !== undefined) {\n if (!_isRecord(value.params) || !Object.values(value.params).every(_hasParamMatcherShape)) {\n return false;\n }\n }\n if (value.callBind !== undefined) {\n if (\n !_isRecord(value.callBind) ||\n value.callBind.alg !== \"sha256\" ||\n typeof value.callBind.payloadHash !== \"string\"\n ) {\n return false;\n }\n }\n return true;\n}\n\nfunction _hasPatternShape(value: unknown): value is Pattern {\n if (!_isRecord(value)) return false;\n return (\"exact\" in value && typeof value.exact === \"string\") ||\n (\"prefix\" in value && typeof value.prefix === \"string\");\n}\n\nfunction _hasParamMatcherShape(value: unknown): value is ParamMatcher {\n if (!_isRecord(value)) return false;\n if (\"exact\" in value) return true;\n if (\"enum\" in value) return Array.isArray(value.enum);\n if (\"prefix\" in value) return typeof value.prefix === \"string\";\n if (\"subsetOf\" in value) {\n return Array.isArray(value.subsetOf) && value.subsetOf.every((item) => typeof item === \"string\");\n }\n return value.any === true;\n}\n\nfunction _isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// ---- addressing matchers (synchronous, pure) -----------------------------\n\n/**\n * Addressing match for a single permission: do its\n * `serviceId`/`interfaceId`/`interfaceHash`/`members` patterns admit\n * `target`?\n */\nexport function permissionMatchesTarget(target: CallTarget, perm: Permission): boolean {\n return _targetMismatchReason(target, perm) === undefined;\n}\n\ntype TargetMismatch =\n | { kind: \"serviceId\"; actual: string; expected: Pattern }\n | { kind: \"interfaceId\"; actual: string; expected: Pattern }\n | { kind: \"interfaceHash\"; actual: string | undefined; expected: string }\n | { kind: \"invalidMembers\" }\n | { kind: \"member\"; actual: string; expected: Pattern[] };\n\nclass TargetMismatchReason {\n constructor(readonly mismatch: TargetMismatch) {}\n\n toString(): string {\n const mismatch = this.mismatch;\n switch (mismatch.kind) {\n case \"serviceId\":\n case \"interfaceId\":\n return `${mismatch.kind} ${JSON.stringify(mismatch.actual)} does not match ${_formatPattern(mismatch.expected)}`;\n case \"interfaceHash\": {\n const actual = mismatch.actual === undefined ? \"<none>\" : JSON.stringify(mismatch.actual);\n return `interfaceHash ${actual} does not match required ${JSON.stringify(mismatch.expected)}`;\n }\n case \"invalidMembers\":\n return \"permission target has invalid members\";\n case \"member\": {\n const allowed = mismatch.expected.map(_formatPattern).join(\", \") || \"<none>\";\n return `member ${JSON.stringify(mismatch.actual)} does not match allowed patterns [${allowed}]`;\n }\n }\n }\n}\n\nfunction _targetMismatchReason(target: CallTarget, perm: Permission): TargetMismatchReason | undefined {\n const t = perm.target;\n if (!_patternMatches(target.serviceId, t.serviceId, \"/\")) {\n return new TargetMismatchReason({\n kind: \"serviceId\",\n actual: target.serviceId,\n expected: t.serviceId,\n });\n }\n if (!_patternMatches(target.interfaceId, t.interfaceId, \".\")) {\n return new TargetMismatchReason({\n kind: \"interfaceId\",\n actual: target.interfaceId,\n expected: t.interfaceId,\n });\n }\n if (t.interfaceHash !== undefined && target.interfaceHash !== t.interfaceHash) {\n return new TargetMismatchReason({\n kind: \"interfaceHash\",\n actual: target.interfaceHash,\n expected: t.interfaceHash,\n });\n }\n // Defense-in-depth: an upstream issuer that bypasses schema validation can\n // produce caps whose permissions omit `members`. Treat as a non-match\n // rather than crashing on `.some` of undefined.\n if (!Array.isArray(t.members)) {\n return new TargetMismatchReason({ kind: \"invalidMembers\" });\n }\n if (!t.members.some((m) => _patternMatches(target.member, m, \"\"))) {\n return new TargetMismatchReason({\n kind: \"member\",\n actual: target.member,\n expected: t.members,\n });\n }\n return undefined;\n}\n\nfunction _patternMatches(value: string, pat: Pattern, delim: string): boolean {\n if (\"exact\" in pat) return value === pat.exact;\n const p = pat.prefix;\n if (p === \"\") return true;\n if (value === p) return true;\n if (delim === \"\") return value.startsWith(p);\n return value.startsWith(p + delim);\n}\n\nfunction _formatPattern(pattern: Pattern): string {\n return \"exact\" in pattern\n ? `exact ${JSON.stringify(pattern.exact)}`\n : `prefix ${JSON.stringify(pattern.prefix)}`;\n}\n\n// ---- pure param-allowlist matcher ----------------------------------------\n\n/**\n * Strict allowlist match for {@link Permission.params}. The set of\n * top-level keys in the call MUST equal the declared set; values must\n * satisfy their matchers. Nested objects/arrays are compared as opaque\n * JSON values via canonical-JSON equality. Pure (no crypto).\n */\nexport function matchParams(\n declared: Record<string, ParamMatcher>,\n actualParams: unknown,\n): { ok: true } | { ok: false; reason: string } {\n const declaredKeys = Object.keys(declared).sort();\n const actualObj =\n actualParams !== null && typeof actualParams === \"object\" && !Array.isArray(actualParams)\n ? (actualParams as Record<string, unknown>)\n : undefined;\n const actualKeys = actualObj ? Object.keys(actualObj).sort() : [];\n if (\n declaredKeys.length !== actualKeys.length ||\n declaredKeys.some((k, i) => k !== actualKeys[i])\n ) {\n return {\n ok: false,\n reason: `param keys mismatch (declared=${declaredKeys.join(\",\")}, actual=${actualKeys.join(\",\")})`,\n };\n }\n for (const k of declaredKeys) {\n if (!_matchParamValue(declared[k], actualObj![k])) {\n return { ok: false, reason: `param \"${k}\" does not match` };\n }\n }\n return { ok: true };\n}\n\nfunction _matchParamValue(matcher: ParamMatcher, value: unknown): boolean {\n if (\"any\" in matcher) return true;\n if (\"prefix\" in matcher) {\n return typeof value === \"string\" && value.startsWith(matcher.prefix);\n }\n if (\"subsetOf\" in matcher) {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof v === \"string\" && matcher.subsetOf.includes(v))\n );\n }\n if (\"exact\" in matcher) {\n return jcsCanonicalize(matcher.exact) === jcsCanonicalize(value);\n }\n if (\"enum\" in matcher) {\n const v = jcsCanonicalize(value);\n return matcher.enum.some((opt) => jcsCanonicalize(opt) === v);\n }\n return false;\n}\n\n\n/** What a holder may do with a permission's call-set. */\nexport type Ability = \"invoke\" | \"delegate\";\n\n\n/**\n * A concrete, authenticated RPC call — the thing {@link permits} judges.\n * It is the call's {@link CallTarget} (which endpoint) plus the arguments\n * and the authenticated request metadata. Built by `verifyCall` from a\n * signed wire envelope.\n */\nexport interface Call {\n /** Which endpoint is being called. */\n target: CallTarget;\n /** User params with identity envelopes stripped. */\n params: unknown;\n /** Per-request replay nonce (the unit the gate dedups on). */\n nonce: string;\n /** Unix milliseconds the call was signed. */\n signedAtMs: number;\n /** The authenticated signer — must equal the leaf capability's audience. */\n signer: PrincipalId;\n /** The call's content hash (`signedHash(\"call\", signedCall)`) — what `callBind` compares against. */\n callHash: Base64Sha256;\n}\n\ntype Verdict = { ok: true } | { ok: false; reason: string };\n\n// ---- membership: does a call fall inside a permission / capability? ------\n\n/**\n * Does `permission` admit `call` for the given `ability`? Checks, in\n * order: the ability flag (`canInvoke`/`canDelegate`, both default\n * `false`), the target address, the optional `params` allowlist, and the\n * optional `callBind` hash-binding. Pure.\n */\nexport function permissionPermits(call: Call, permission: Permission, ability: Ability): Verdict {\n const granted = ability === \"invoke\" ? permission.canInvoke === true : permission.canDelegate === true;\n if (!granted) return { ok: false, reason: `permission does not grant ${ability}` };\n const targetMismatch = _targetMismatchReason(call.target, permission);\n if (targetMismatch !== undefined) {\n return {\n ok: false,\n reason: `permission does not address this call: ${targetMismatch.toString()}`,\n };\n }\n if (permission.params !== undefined) {\n const r = matchParams(permission.params, call.params);\n if (!r.ok) return { ok: false, reason: `params: ${r.reason}` };\n }\n if (permission.callBind !== undefined) {\n if (permission.callBind.alg !== \"sha256\") {\n return { ok: false, reason: `callBind: unsupported hash alg (${permission.callBind.alg})` };\n }\n if (call.callHash !== permission.callBind.payloadHash) {\n return { ok: false, reason: \"callBind: payload hash mismatch\" };\n }\n }\n return { ok: true };\n}\n\n/**\n * Does `cap` admit `call` for the given `ability`? True iff **any** of its\n * permissions does (the union over permissions). This is one *link's*\n * judgment; chain intersection is enforced by {@link verifyChain}.\n */\nexport function capabilityPermits(call: Call, cap: Capability, ability: Ability): Verdict {\n let lastReason = `no permission grants ${ability} for this call`;\n for (const permission of cap.permissions) {\n const r = permissionPermits(call, permission, ability);\n if (r.ok) return { ok: true };\n lastReason = r.reason;\n }\n return { ok: false, reason: lastReason };\n}\n","import type { CallTarget } from \"./capability\";\n\n/**\n * Parsed JSON-RPC method string. The linkrpc dialect uses `::` to\n * separate up to three segments:\n *\n * - `\"member\"` — bare (preset-bound dispatch)\n * - `\"interfaceId::member\"` — interface form (root service)\n * - `\"::interfaceId::member\"` — explicit root form\n * - `\"serviceId::interfaceId::member\"` — fully-qualified form\n *\n * The hub does not accept the `bare` form (it has no interface context\n * to route on). Connection-level dispatch accepts all three.\n */\nexport type ParsedMethodName =\n | { kind: \"bare\"; member: string }\n | { kind: \"interface\"; interfaceId: string; member: string }\n | { kind: \"full\"; serviceId: string; interfaceId: string; member: string };\n\n/**\n * Parse a JSON-RPC method string. Returns `undefined` if any segment is\n * empty or the segment count is out of range.\n */\nexport function parseMethodName(method: string): ParsedMethodName | undefined {\n const parts = method.split(\"::\");\n if (parts.length === 3 && parts[0].length === 0 && parts[1].length > 0 && parts[2].length > 0) {\n return { kind: \"interface\", interfaceId: parts[1], member: parts[2] };\n }\n if (parts.some((p) => p.length === 0)) return undefined;\n if (parts.length === 1) return { kind: \"bare\", member: parts[0] };\n if (parts.length === 2) return { kind: \"interface\", interfaceId: parts[0], member: parts[1] };\n if (parts.length === 3) return { kind: \"full\", serviceId: parts[0], interfaceId: parts[1], member: parts[2] };\n return undefined;\n}\n\n/**\n * Convert a parsed method string to a {@link CallTarget} for capability\n * matching. Interface-form calls are addressed to the root service —\n * represented as an empty `serviceId`. Throws on `bare` form (no\n * interface context) and on malformed input.\n */\nexport function methodNameToTarget(method: string): CallTarget {\n const p = parseMethodName(method);\n if (!p) throw new Error(`linkrpc: malformed method: ${method}`);\n if (p.kind === \"bare\") {\n throw new Error(`linkrpc: bare method has no interface context: ${method}`);\n }\n if (p.kind === \"interface\") {\n return { serviceId: \"\", interfaceId: p.interfaceId, member: p.member };\n }\n return { serviceId: p.serviceId, interfaceId: p.interfaceId, member: p.member };\n}\n","import type { JsonValue } from \"./jsonValue\";\nimport type { PrincipalId } from \"../crypto/cryptoProvider\";\nimport type { SignedCapability } from \"./capability\";\nimport type { JsonRpcNotification, JsonRpcRequest } from \"./jsonRpc\";\nimport {\n HUBRPC_META_KEY,\n HUBRPC_SIGNATURE_KEY,\n HUBRPC_UNSIGNED_KEY,\n type Signatures,\n} from \"./signedObject\";\n\nexport {\n HUBRPC_META_KEY,\n HUBRPC_SIGNATURE_KEY,\n HUBRPC_UNSIGNED_KEY,\n type Signatures,\n};\n\n/**\n * Signed call meta. Lives under `params.$hubrpc` so it can't collide with\n * the user's top-level param keys. Present on signed AND unsigned calls\n * (the latter omit {@link CallMeta.principal} and carry no `$hubrpcSignature`).\n *\n * Included verbatim in the bytes a call signature commits to — the\n * signature covers `signingInput(\"call\", { ...userParams, $hubrpc })`.\n */\nexport interface CallMeta {\n /** Fully-qualified wire method. The verifier asserts it equals the JSON-RPC `method`. */\n readonly method: string;\n /** Replay-protection nonce (base64url). The gate dedups on this. */\n readonly nonce: string;\n /** Unix milliseconds. Skew window enforced by the verifier. */\n readonly signedAtMs: number;\n /** Identity wielding the call. Present iff signed; equals the audience of every presented cap. */\n readonly principal?: PrincipalId;\n /** Optional schema hash assertion. Matched against `TargetPattern.interfaceHash`. */\n readonly interfaceHash?: string;\n}\n\n/**\n * Extrinsic, unsigned attachments carried under `params.$hubrpcUnsigned`.\n * Not covered by the call signature (they aren't authored by the signer).\n */\nexport interface LinkRpcUnsigned {\n /** Caller's presented capability bag. Parents are resolved out of this by hash. */\n readonly capabilities?: readonly SignedCapability[];\n}\n\n/** Reserved wire-key meta carried on a linkrpc call's params object. */\nexport interface LinkRpcWireMeta {\n readonly [HUBRPC_META_KEY]?: CallMeta;\n readonly [HUBRPC_SIGNATURE_KEY]?: Signatures;\n readonly [HUBRPC_UNSIGNED_KEY]?: LinkRpcUnsigned;\n}\n\n\n/**\n * Wire shape of `params` on a linkrpc JSON-RPC call.\n *\n * The user's params object (if any) is spread as-is, with the\n * {@link LinkRpcWireMeta} keys attached on top. `TUserParams` carries the\n * user-visible param shape; defaults to an open object. User params MUST be\n * a plain object — enforced at signing/verification via\n * {@link requireObjectParams}.\n */\nexport type LinkRpcWireParams<\n TUserParams extends { [key: string]: JsonValue | undefined } = { [key: string]: JsonValue | undefined },\n> = TUserParams & LinkRpcWireMeta;\n\n/** JSON-RPC request whose `params` carry the linkrpc wire meta. */\nexport type LinkRpcJsonRpcRequest<\n TUserParams extends { [key: string]: JsonValue | undefined } = { [key: string]: JsonValue | undefined },\n> = JsonRpcRequest<LinkRpcWireParams<TUserParams>>;\n\n/** JSON-RPC notification whose `params` carry the linkrpc wire meta. */\nexport type LinkRpcJsonRpcNotification<\n TUserParams extends { [key: string]: JsonValue | undefined } = { [key: string]: JsonValue | undefined },\n> = JsonRpcNotification<LinkRpcWireParams<TUserParams>>;\n\n/** Either of the two linkrpc-bearing JSON-RPC message shapes. */\nexport type LinkRpcJsonRpcMessage<\n TUserParams extends { [key: string]: JsonValue | undefined } = { [key: string]: JsonValue | undefined },\n> = LinkRpcJsonRpcRequest<TUserParams> | LinkRpcJsonRpcNotification<TUserParams>;\n\n/**\n * The linkrpc signing/cap system accepts only plain-object user params (or\n * none). Reject arrays/primitives at the boundary so \"strip `$hubrpc*`, the\n * rest is the signed user params\" stays unambiguous.\n */\nexport function requireObjectParams(\n userParams: JsonValue | undefined,\n): Record<string, JsonValue | undefined> {\n if (userParams === undefined) return {};\n if (userParams === null || typeof userParams !== \"object\" || Array.isArray(userParams)) {\n throw new Error(\"linkrpc: user params must be a plain JSON object or undefined\");\n }\n return userParams as Record<string, JsonValue | undefined>;\n}\n\n/**\n * Return the application-authored portion of a LinkRPC params value.\n *\n * Routing and gate layers must continue forwarding the original wire params so\n * every chained hub can independently verify the envelope. Terminal dispatch\n * may use this derived value for application-schema validation without mutating\n * or replacing the wire message.\n */\nexport function stripLinkRpcWireMeta(wireParams: unknown): JsonValue | undefined {\n if (wireParams === undefined) return undefined;\n if (wireParams === null || typeof wireParams !== \"object\" || Array.isArray(wireParams)) {\n return wireParams as JsonValue;\n }\n const object = wireParams as Record<string, unknown>;\n const reserved = [HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY];\n if (!reserved.some((key) => key in object)) return object as JsonValue;\n\n const userParams: Record<string, unknown> = {};\n for (const key of Object.keys(object)) {\n if (reserved.includes(key)) continue;\n userParams[key] = object[key];\n }\n return userParams as JsonValue;\n}\n","import type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport { IDisposable } from '../disposable';\n\nexport interface IMessageTransport<TIncoming = JsonRpcMessage, TOutgoing = JsonRpcMessage> {\n send(message: TOutgoing): void | Promise<void>;\n /**\n * Sets the listener for incoming messages. Setting `undefined` detaches.\n * The transport buffers messages received before a listener is attached\n * and delivers them the next tick when one is set.\n * Forgetting to set a listener will cause the queue to leak.\n */\n setListener(listener: ((message: TIncoming) => void) | undefined): void;\n dispose(): void;\n}\n\nexport type MessageWithContext<TCtx> = JsonRpcMessage & { context: TCtx; };\n\nexport type MessageTransportWithContext<TCtx> = IMessageTransport<JsonRpcMessage, MessageWithContext<TCtx>>;\n\nexport type MessageTransportDirection = 'send' | 'receive';\nexport type MessageTransportTrace = (\n direction: MessageTransportDirection,\n message: JsonRpcMessage,\n) => void;\n\n/**\n * Observe every message crossing a transport without changing its buffering or\n * lifecycle behavior.\n */\nexport function traceMessageTransport(\n transport: IMessageTransport,\n trace: MessageTransportTrace,\n): IMessageTransport {\n return {\n send(message): void | Promise<void> {\n trace('send', message);\n return transport.send(message);\n },\n setListener(listener): void {\n transport.setListener(listener === undefined\n ? undefined\n : (message) => {\n trace('receive', message);\n listener(message);\n });\n },\n dispose(): void {\n transport.dispose();\n },\n };\n}\n\n/**\n * Pipe two transports together: every message one receives is forwarded to\n * the other's `send`. Returns a disposable that detaches both listeners.\n *\n * Neither transport is disposed — the caller owns their lifecycle. This is\n * the building block for relays (e.g. bridging a `WindowMessageTransport`\n * for an iframe to a multiplexer channel).\n */\nexport function connectTransports<T extends JsonRpcMessage>(\n a: IMessageTransport<T>,\n b: IMessageTransport<T>,\n): IDisposable {\n a.setListener((m) => void b.send(m));\n b.setListener((m) => void a.send(m));\n return {\n dispose(): void {\n a.setListener(undefined);\n b.setListener(undefined);\n },\n };\n}\n\n\n/**\n * Two in-memory transports wired back-to-back. Useful for tests and for\n * same-process bridges.\n *\n * Generic in the per-direction payload type so asymmetric pairs (e.g. one\n * side sends plain `JsonRpcMessage`, the other side sends\n * `JsonRpcMessage & { context: Participant }`) are expressible at the type\n * level. At runtime both halves just hand objects through by reference.\n */\nexport class TransportPair<TFromA = JsonRpcMessage, TFromB = JsonRpcMessage> {\n public readonly a: IMessageTransport<TFromB, TFromA>;\n public readonly b: IMessageTransport<TFromA, TFromB>;\n\n constructor() {\n const aT = new _InMemoryTransport<TFromB, TFromA>();\n const bT = new _InMemoryTransport<TFromA, TFromB>();\n aT._peer = bT as unknown as _InMemoryTransport<TFromA, TFromB>;\n bT._peer = aT as unknown as _InMemoryTransport<TFromB, TFromA>;\n this.a = aT;\n this.b = bT;\n }\n}\n\nclass _InMemoryTransport<TIn, TOut> implements IMessageTransport<TIn, TOut> {\n public _peer!: _InMemoryTransport<TOut, TIn>;\n private _listener: ((m: TIn) => void) | undefined;\n private readonly _buffer: TIn[] = [];\n private _closed = false;\n\n send(message: TOut): void {\n if (this._closed || this._peer._closed) return;\n // Deliver asynchronously to mimic a real transport — keeps tests honest\n // about ordering and prevents unintended sync reentrancy.\n this._peer._deliver(message);\n }\n\n setListener(listener: ((m: TIn) => void) | undefined): void {\n this._listener = listener;\n if (listener) {\n while (this._buffer.length > 0 && this._listener) {\n const m = this._buffer.shift()!;\n this._listener(m);\n }\n }\n }\n\n dispose(): void {\n this._closed = true;\n }\n\n _deliver(m: TIn): void {\n if (this._listener) this._listener(m);\n else this._buffer.push(m);\n }\n}\n","import type { JsonRpcMessage } from \"../protocol/jsonRpc\";\nimport type { IMessageTransport } from \"./messageTransport\";\nimport type { IDisposable } from '../disposable';\n\nexport interface MuxEnvelope {\n readonly $mux: \"v1\";\n readonly ch: string;\n readonly m: JsonRpcMessage;\n}\n\nexport class MultiplexedTransport<TChannels extends Record<string, string>> implements IDisposable {\n public static create<TChannels extends Record<string, string>>(\n base: IMessageTransport<MuxEnvelope, MuxEnvelope>,\n channels: TChannels,\n ): MultiplexedTransport<TChannels> {\n return new MultiplexedTransport(base, channels);\n }\n\n /** Logical transports keyed by the friendly channel names. */\n public readonly transports: { readonly [K in keyof TChannels]: IMessageTransport };\n\n private readonly _base: IMessageTransport<MuxEnvelope, MuxEnvelope>;\n private readonly _byId = new Map<string, _ChannelTransport>();\n private readonly _usedIds = new Set<string>();\n private _disposed = false;\n\n constructor(base: IMessageTransport<MuxEnvelope, MuxEnvelope>, channels: TChannels) {\n this._base = base;\n const transports = {} as { [K in keyof TChannels]: _ChannelTransport };\n\n for (const name of Object.keys(channels) as (keyof TChannels)[]) {\n const id = channels[name];\n const t = this._createChannel(id);\n transports[name] = t;\n }\n this.transports = transports;\n\n base.setListener((data) => {\n // Route purely by channel id. Concrete transports own their own\n // framing, so we don't re-validate the envelope shape here; anything\n // that doesn't carry a known channel id is simply ignored.\n const t = data == null ? undefined : this._byId.get(data.ch);\n t?._deliver(data.m);\n });\n }\n\n /**\n * Add a logical channel after the multiplexer has started.\n *\n * Channel ids are permanently retired when disposed. This prevents a late\n * envelope for an old iframe from being delivered to a replacement iframe.\n */\n public addChannel(id: string): IMessageTransport {\n if (this._disposed) {\n throw new Error(\"Cannot add a channel to a disposed multiplexed transport.\");\n }\n return this._createChannel(id);\n }\n\n dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._base.setListener(undefined);\n for (const t of [...this._byId.values()]) t.dispose();\n this._byId.clear();\n }\n\n private _createChannel(id: string): _ChannelTransport {\n if (id.length === 0) {\n throw new Error(\"Multiplexed transport channel ids must not be empty.\");\n }\n if (this._usedIds.has(id)) {\n throw new Error(`Multiplexed transport channel id \"${id}\" has already been used.`);\n }\n\n this._usedIds.add(id);\n const t = new _ChannelTransport(this._base, id, () => {\n if (this._byId.get(id) === t) {\n this._byId.delete(id);\n }\n });\n this._byId.set(id, t);\n return t;\n }\n}\n\nclass _ChannelTransport implements IMessageTransport {\n private _listener: ((m: JsonRpcMessage) => void) | undefined;\n private readonly _buffer: JsonRpcMessage[] = [];\n private _closed = false;\n\n constructor(\n private readonly _base: IMessageTransport<MuxEnvelope, MuxEnvelope>,\n private readonly _ch: string,\n private readonly _onDispose: () => void,\n ) { }\n\n send(message: JsonRpcMessage): void {\n if (this._closed) return;\n void this._base.send({ $mux: \"v1\", ch: this._ch, m: message });\n }\n\n setListener(listener: ((m: JsonRpcMessage) => void) | undefined): void {\n this._listener = listener;\n if (listener) {\n while (this._buffer.length > 0 && this._listener) {\n listener(this._buffer.shift()!);\n }\n }\n }\n\n dispose(): void {\n if (this._closed) return;\n this._closed = true;\n this._listener = undefined;\n this._buffer.length = 0;\n this._onDispose();\n }\n\n _deliver(m: JsonRpcMessage): void {\n if (this._closed) return;\n if (this._listener) this._listener(m);\n else this._buffer.push(m);\n }\n}\n","import type { JsonRpcMessage, JsonValue } from '../protocol/jsonRpc';\nimport type { IMessageTransport } from '../transport/messageTransport';\n\nexport class Channel<TInCtx = undefined, TOutCtx = undefined> {\n constructor(\n public readonly sender: IRequestSender<TOutCtx>,\n private readonly _setHandler: (h: IRequestHandler<TInCtx> | undefined) => void,\n private readonly _setWireObserver?: (observer: WireMessageObserver | undefined) => void,\n ) { }\n\n /** Bind the inbound request/notification handler. May be called before or after construction of {@link LinkRpcConnection}. */\n public setRequestHandler(handler: IRequestHandler<TInCtx> | undefined): void {\n this._setHandler(handler);\n }\n\n /**\n * Install the endpoint inspection observer at the JSON-RPC wire boundary.\n * Intended for {@link LinkRpcConnection}; ordinary consumers should use the\n * public `hubrpc.traffic` service instead.\n */\n public setWireMessageObserver(observer: WireMessageObserver | undefined): void {\n this._setWireObserver?.(observer);\n }\n\n /**\n * Compose this channel with a sender-side decorator (typically the\n * signing layer). The decorator wraps {@link sender} only; the\n * {@link setRequestHandler} binding is shared with the original channel\n * so the receive side is bound exactly once regardless of decoration depth.\n */\n public withSender<TNewOutCtx>(\n decorate: (raw: IRequestSender<TOutCtx>) => IRequestSender<TNewOutCtx>,\n ): Channel<TInCtx, TNewOutCtx> {\n return new Channel<TInCtx, TNewOutCtx>(\n decorate(this.sender),\n this._setHandler,\n this._setWireObserver,\n );\n }\n}\n\nexport type WireMessageDirection = 'inbound' | 'outbound';\nexport type WireMessageObserver = (\n direction: WireMessageDirection,\n message: JsonRpcMessage,\n) => void;\n\nexport interface IRequestHandler<TInCtx = undefined> {\n handleRequest(call: IncomingCall<TInCtx>): Promise<Result>;\n handleNotification(call: IncomingCall<TInCtx>): void;\n}\n\n/**\n * Inbound call observed by an {@link IRequestHandler}. `TInCtx` is the\n * per-call out-of-band context the transport attached on the receiving\n * side (e.g. the hub stamps `Participant` on overlay-bound messages).\n * For wire transports it's `undefined`.\n */\nexport interface IncomingCall<TInCtx = undefined> {\n method: string;\n params: JsonValue | undefined;\n /** Out-of-band context attached by the transport, if any. */\n context: TInCtx;\n /**\n * Per-call streaming handle. Both directions live on this object,\n * scoped to the request's lifetime. The inbound listener is auto-\n * detached when the handler's response settles. For notifications\n * (no request id) the handle is a no-op stub.\n */\n stream: IncomingStream;\n /**\n * Aborts when the caller cancels this in-flight request (a\n * `toCallee` `cancel` control), or when the hub cancels it on the\n * caller's behalf (caller disconnect / idle timeout). The handler\n * should observe this and settle promptly — typically by throwing,\n * which surfaces as a `cancelled` error response. For notifications\n * this never aborts.\n */\n signal: AbortSignal;\n}\n\n/**\n * Per-call streaming handle attached to {@link IncomingCall.stream}.\n * Scoped to a single in-flight request; the channel automatically\n * detaches the inbound listener when the handler's response settles.\n *\n * For notifications (which have no request id), `requestId` is\n * `undefined`, `send` is a no-op, and `onMessage` is a no-op.\n */\nexport interface IncomingStream {\n /** Emit a server→client stream notification correlated with this call. */\n send(payload: JsonValue): Promise<void>;\n /**\n * Register a listener for client→server stream messages correlated\n * with this call. Pass `undefined` to detach. Replaces any prior\n * listener. The channel detaches the listener automatically when\n * the handler's response settles.\n */\n onMessage(listener: ((payload: JsonValue) => void) | undefined): void;\n /**\n * Liveness probe toward the caller: emit a `toCaller` ping and\n * resolve once the caller's `pong` (matching nonce) returns. Rejects\n * if the request settles first. Independent of the channel's\n * automatic keepalive ping.\n */\n ping(): Promise<void>;\n}\n\nexport type Result =\n | { result: JsonValue; }\n | { error: { code: number; message: string; data?: JsonValue; }; };\n\n/**\n * What callers use to send. The {@link Channel} factory binds an\n * {@link IRequestHandler} at construction (immutable for the channel's\n * lifetime) and hands the caller back an `IRequestSender`.\n *\n * `TOutCtx` is the per-call context bag this sender understands. For\n * the base {@link JsonRpcChannel} it's `undefined` (the channel\n * doesn't read any overrides). Decorators like `SigningSender`\n * parametrise it on their own ctx shape.\n */\nexport interface IRequestSender<TOutCtx = undefined> {\n sendRequest(method: string, params: JsonValue | undefined, opts?: SendOpts<TOutCtx>): Promise<JsonValue>;\n sendNotification(method: string, params: JsonValue | undefined, opts?: SendOpts<TOutCtx>): Promise<void>;\n /**\n * Issue a request that participates in the streaming sub-protocol.\n * Returns synchronously with the wire request id, the result\n * promise, and a `send` for emitting client→server stream messages.\n */\n sendRequestWithStream(method: string, params: JsonValue | undefined, opts?: StreamSendOpts<TOutCtx>): RawStreamingCall;\n close(): void;\n}\n\n/**\n * Handle for a request issued via\n * {@link IRequestSender.sendRequestWithStream}. `send` emits\n * client→server stream messages correlated with this call. `result`\n * resolves with the call's response.\n */\nexport interface RawStreamingCall {\n readonly result: Promise<JsonValue>;\n /** Emit a client→server (`toCallee`) stream message correlated with this call. */\n send(payload: JsonValue): void;\n /**\n * Ask the callee to abort this in-flight request (a `toCallee`\n * `cancel` control). Advisory: the request settles via its normal\n * response (typically a `cancelled` error). `reason` is an open-set\n * diagnostic string (see `StreamControlReason`).\n */\n cancel(reason?: string): void;\n /**\n * Stop tracking this request locally and reject {@link result}. This does\n * not notify the callee; call {@link cancel} first when remote work should\n * also be cancelled. Safe to call after the request has already settled.\n */\n dispose?(reason?: string): void;\n /**\n * Liveness probe toward the callee: emit a `toCallee` ping and\n * resolve once the callee's `pong` (matching nonce) returns. Rejects\n * if the request settles first. Independent of the channel's\n * automatic keepalive ping.\n */\n ping(): Promise<void>;\n}\n\n/**\n * Per-send options.\n *\n * `interfaceHash` is interface-level call metadata: the schema hash of\n * the interface a typed proxy is calling. It is independent of\n * `TOutCtx` — the connection stamps it from the interface definition,\n * the base {@link JsonRpcChannel} ignores it, and signing decorators\n * bake it into the `$hubrpc` envelope.\n *\n * `ctx` is the sender's `TOutCtx`-typed override / extension bag for\n * per-call decorator overrides (e.g. `signerOverride`, `capsOverride`).\n * The base {@link JsonRpcChannel} ignores `ctx` entirely; decorators\n * like `SigningSender` interpret it.\n */\nexport interface SendOpts<TOutCtx = undefined> {\n readonly ctx?: TOutCtx;\n /** Interface schema hash for this call (interface-level metadata). */\n readonly interfaceHash?: string;\n}\n\nexport interface StreamSendOpts<TOutCtx = undefined> extends SendOpts<TOutCtx> {\n readonly onStreamMessage?: (payload: JsonValue) => void;\n}\n\n/**\n * Convenience: the transport type a {@link JsonRpcChannel} expects.\n * Outbound is plain `JsonRpcMessage` — the base channel does not\n * attach context to outgoing wire messages.\n */\nexport type ChannelTransport<TInCtx = undefined> = IMessageTransport<MessageWithCtx<TInCtx>>;\n\n/**\n * Type of incoming messages on the channel's transport. With\n * `TInCtx = undefined` (default) this is just `JsonRpcMessage`. With a\n * concrete `TInCtx`, the transport carries a `context` field alongside\n * the message — out-of-band, never sent over a wire, set by the\n * in-process producer.\n */\nexport type MessageWithCtx<TInCtx> = [TInCtx] extends [undefined] ? JsonRpcMessage :\n JsonRpcMessage & { context: TInCtx; };\n\nexport class RpcError extends Error {\n constructor(\n message: string,\n public readonly code: number,\n public readonly data?: JsonValue,\n ) {\n super(message);\n this.name = 'RpcError';\n }\n}\n","export const DEFAULT_RPC_TIMEOUT_MS = 5_000;\n\nexport interface CancellableRequest<T> extends Promise<T> {\n cancel(reason?: string): void | Promise<void>;\n dispose?(reason?: string): void;\n}\n\nexport async function withRpcTimeout<T>(\n request: CancellableRequest<T>,\n target: string,\n timeoutMs = DEFAULT_RPC_TIMEOUT_MS,\n): Promise<T> {\n if (timeoutMs <= 0) return request;\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const reason = `${target} timed out after ${timeoutMs}ms`;\n try {\n Promise.resolve(request.cancel(reason)).catch(() => {\n // The timeout remains authoritative even if remote cancellation fails.\n });\n } finally {\n try {\n request.dispose?.(reason);\n } catch {\n // Local disposal must not replace the timeout result.\n }\n }\n reject(new Error(reason));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([request, timeout]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","import type { IRequestSender, RawStreamingCall } from '../../connection/channel';\nimport { DEFAULT_RPC_TIMEOUT_MS, withRpcTimeout } from '../../connection/requestTimeout';\nimport type { SigningCallCtx } from '../../identity/signingSender';\nimport type { JsonValue } from '../../protocol/jsonValue';\nimport type { LinkRpcInterfaceSchema, MethodSchema } from '../../schema/linkRpcInterfaceSchema';\nimport {\n directoryInterface,\n type RootPrincipalSet,\n type ServiceIdPattern,\n} from './reflection.interfaces';\n\n/**\n * Portable reflection walk over the `hubrpc.directory` referral tree.\n *\n * A directory may explicitly list other `hubrpc.directory` services as\n * referrals. Flattening that graph into an interface inventory is the\n * consumer's job. Routing state is deliberately not part of this contract.\n */\n\n/**\n * The sender reflection helpers speak over: the signing decorator that wraps\n * the live channel. Decoupled from the concrete `JsonRpcChannel` so reconnect\n * can swap the underlying channel transparently.\n */\nexport type ReflectionChannel = IRequestSender<SigningCallCtx>;\n\nexport interface ServiceListing {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly path?: string;\n /** Optional non-normative description of the owning service. */\n readonly serviceDescription?: string;\n /**\n * Root node ids required to access the owning service, in CNF. Surfaced by\n * the directory; {@link walkHubDetailed} additionally folds transitive\n * requirements from ancestor directories onto descendants.\n */\n readonly rootPrincipalSets?: readonly RootPrincipalSet[];\n /** Scope carried by a directory referral; omitted means its service-id subtree. */\n readonly reachableServiceIds?: readonly ServiceIdPattern[];\n}\n\n/**\n * A {@link ServiceListing} enriched with the service id of the directory that\n * reported it. This is provenance only: every listing is asserted reachable by\n * sending to the endpoint that answered the directory.\n */\nexport interface DiscoveredListing extends ServiceListing {\n readonly discoveredFrom: string;\n}\n\nexport interface ListOptions {\n readonly interfaceId?: string;\n readonly interfaceIdPrefix?: string;\n readonly serviceId?: string;\n readonly serviceIdScopes?: readonly ServiceIdPattern[];\n readonly limit?: number;\n readonly timeoutMs?: number;\n /**\n * When set, send the reflection call to that service via form-3\n * (`<target>::hubrpc.directory::list`) instead of the implicit root\n * directory. Used when talking to a hub: the root directory is the hub\n * itself, but per-service reflection lives on each participant.\n */\n readonly target?: string;\n}\n\nexport async function fetchDirectory(\n channel: ReflectionChannel,\n opts: ListOptions = {},\n): Promise<ServiceListing[]> {\n const method = opts.target\n ? `${opts.target}::hubrpc.directory::list`\n : 'hubrpc.directory::list';\n const all: ServiceListing[] = [];\n let cursor: string | undefined;\n while (true) {\n const params: Record<string, JsonValue | undefined> = {};\n if (opts.interfaceId !== undefined) params.interfaceId = opts.interfaceId;\n if (opts.interfaceIdPrefix !== undefined) params.interfaceIdPrefix = opts.interfaceIdPrefix;\n if (opts.serviceId !== undefined) params.serviceId = opts.serviceId;\n if (opts.serviceIdScopes !== undefined) params.serviceIdScopes = [...opts.serviceIdScopes];\n if (opts.limit !== undefined) params.limit = opts.limit;\n if (opts.timeoutMs !== undefined) params.timeoutMs = opts.timeoutMs;\n if (cursor !== undefined) params.cursor = cursor;\n\n const call = channel.sendRequestWithStream(method, params, {\n interfaceHash: directoryInterface.schemaHash,\n });\n const target = opts.target ?? '<root>';\n const raw = await withRpcTimeout(\n Object.assign(call.result, {\n cancel: (reason?: string) => call.cancel(reason),\n dispose: (reason?: string) => call.dispose?.(reason),\n }),\n `hub directory service '${target}'`,\n opts.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS,\n );\n const page = raw as unknown as {\n items: {\n serviceId: string;\n interfaceId: string;\n interfaceHash: string;\n path?: string;\n serviceDescription?: string;\n rootPrincipalSets?: readonly RootPrincipalSet[];\n reachableServiceIds?: readonly ServiceIdPattern[];\n }[];\n nextCursor?: string;\n };\n for (const it of page.items) {\n all.push({\n serviceId: it.serviceId,\n interfaceId: it.interfaceId,\n hash: it.interfaceHash,\n ...(it.path !== undefined ? { path: it.path } : {}),\n ...(it.serviceDescription !== undefined\n ? { serviceDescription: it.serviceDescription }\n : {}),\n ...(Array.isArray(it.rootPrincipalSets)\n ? { rootPrincipalSets: it.rootPrincipalSets }\n : {}),\n ...(Array.isArray(it.reachableServiceIds)\n ? { reachableServiceIds: it.reachableServiceIds }\n : {}),\n });\n }\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return all;\n}\n\nexport async function fetchSchema(\n channel: ReflectionChannel,\n interfaceId: string,\n hash: string | undefined,\n /**\n * Optional routing target. When set, the schema request is addressed to\n * `<target>::hubrpc.schemas::get` (form-3) so it reaches the service that\n * actually hosts this interface — needed when talking to a hub and the\n * interface lives behind a participant.\n */\n target?: string,\n): Promise<LinkRpcInterfaceSchema> {\n const method = target\n ? `${target}::hubrpc.schemas::get`\n : 'hubrpc.schemas::get';\n const params: Record<string, JsonValue | undefined> = { interfaceId };\n if (hash !== undefined) params.hash = hash;\n const raw = await channel.sendRequest(method, params);\n const wrap = raw as unknown as { schema: LinkRpcInterfaceSchema; };\n return wrap.schema;\n}\n\nexport function findMethodInSchema(\n schema: LinkRpcInterfaceSchema,\n methodName: string,\n): MethodSchema | undefined {\n return schema.methods[methodName];\n}\n\n/** Default recursion depth when walking the bus. */\nexport const DEFAULT_WALK_DEPTH = 5;\nconst DIRECTORY_INTERFACE_ID = 'hubrpc.directory';\nconst ROOT_NODE_KEY = '\\u0000root';\n\n/** Segment-aware service-id pattern matching (`foo` includes `foo/bar`, not `foobar`). */\nexport function serviceIdMatchesPattern(serviceId: string, pattern: ServiceIdPattern): boolean {\n if ('exact' in pattern) return serviceId === pattern.exact;\n return pattern.prefix === ''\n || serviceId === pattern.prefix\n || serviceId.startsWith(`${pattern.prefix}/`);\n}\n\n/** Whether a service id is included by a union of patterns. `undefined` means unfiltered. */\nexport function serviceIdMatchesScopes(\n serviceId: string,\n scopes: readonly ServiceIdPattern[] | undefined,\n): boolean {\n return scopes === undefined || scopes.some((pattern) => serviceIdMatchesPattern(serviceId, pattern));\n}\n\n/** Canonicalize a pattern union by removing duplicates and contained patterns. */\nexport function normalizeServiceIdScopes(\n scopes: readonly ServiceIdPattern[],\n): ServiceIdPattern[] {\n const unique = new Map<string, ServiceIdPattern>();\n for (const pattern of scopes) {\n unique.set(patternKey(pattern), pattern);\n }\n const patterns = [...unique.values()];\n return patterns\n .filter((candidate, index) => !patterns.some((other, otherIndex) =>\n index !== otherIndex && patternContains(other, candidate)))\n .sort((a, b) => patternKey(a).localeCompare(patternKey(b)));\n}\n\n/** Pairwise intersection of two pattern unions. */\nexport function intersectServiceIdScopes(\n left: readonly ServiceIdPattern[],\n right: readonly ServiceIdPattern[],\n): ServiceIdPattern[] {\n const intersections: ServiceIdPattern[] = [];\n for (const a of left) {\n for (const b of right) {\n const intersection = intersectPattern(a, b);\n if (intersection !== undefined) intersections.push(intersection);\n }\n }\n return normalizeServiceIdScopes(intersections);\n}\n\nfunction intersectPattern(\n left: ServiceIdPattern,\n right: ServiceIdPattern,\n): ServiceIdPattern | undefined {\n if ('exact' in left) {\n if ('exact' in right) return left.exact === right.exact ? left : undefined;\n return serviceIdMatchesPattern(left.exact, right) ? left : undefined;\n }\n if ('exact' in right) {\n return serviceIdMatchesPattern(right.exact, left) ? right : undefined;\n }\n if (serviceIdMatchesPattern(left.prefix, right)) return left;\n if (serviceIdMatchesPattern(right.prefix, left)) return right;\n return undefined;\n}\n\nfunction patternContains(container: ServiceIdPattern, candidate: ServiceIdPattern): boolean {\n if ('exact' in container) {\n return 'exact' in candidate && container.exact === candidate.exact;\n }\n if ('exact' in candidate) return serviceIdMatchesPattern(candidate.exact, container);\n return serviceIdMatchesPattern(candidate.prefix, container);\n}\n\nfunction patternKey(pattern: ServiceIdPattern): string {\n return 'exact' in pattern ? `e:${pattern.exact}` : `p:${pattern.prefix}`;\n}\n\nfunction scopesKey(scopes: readonly ServiceIdPattern[]): string {\n return normalizeServiceIdScopes(scopes).map(patternKey).join('\\u0000');\n}\n\n/**\n * A sub-directory the walk surfaced but could not enumerate — typically because\n * it is capability-gated (e.g. the `hub` directory, reachable only once the\n * connection holds a capability for it). The services it would have listed are\n * therefore absent from the walk; callers can surface `reason` to explain the\n * gap rather than silently dropping the branch.\n */\nexport interface InaccessibleDirectory {\n /** The directory target (serviceId) that could not be enumerated. */\n readonly serviceId: string;\n /** The error message from the denied directory lookup. */\n readonly reason: string;\n}\n\nexport interface WalkHubResult {\n /** Every interface reachable from the directories the walk could read. */\n readonly listings: DiscoveredListing[];\n /**\n * Sub-directories that were referenced but could not be enumerated (e.g.\n * capability-gated). Their services are not present in `listings`.\n */\n readonly inaccessible: InaccessibleDirectory[];\n}\n\n/**\n * Recursive graph walk: list a directory, intersect the accumulated service-id\n * scope with every explicit `hubrpc.directory` referral, and recurse. Bounded\n * by `maxDepth`.\n *\n * Every listing is tagged with `discoveredFrom` — the serviceId of the\n * directory that produced it. When the same `(serviceId, interfaceId, hash)`\n * shows up via several directories (e.g. once forwarded by the hub, once\n * directly from the participant), we keep the one whose `discoveredFrom`\n * matches the item's `serviceId`, since that's the directory that\n * authoritatively knows about it.\n *\n * Transitive root-node-id requirements flow down the tree: when the walk\n * recurses into a directory whose own `rootPrincipalSets` include `transitive`\n * reqs, every interface discovered at or below that directory inherits them (as\n * singleton AND-sets, kept transitive so they keep flowing further down). This\n * replaces the hub-side `applyTransitiveReqs` fold that the v1 aggregating\n * directory performed.\n *\n * A sub-directory the walk cannot read is recorded in\n * {@link WalkHubResult.inaccessible} rather than silently dropped. A failure to\n * read the *root* directory is left silent — there is no sub-tree to explain —\n * and simply yields empty results.\n *\n * When {@link WalkHubOptions.unlockGatedDirectory} is supplied, each gated\n * sub-directory is offered to the hook; if it returns `true` (a capability was\n * granted), that directory is re-queued and the walk continues into it — a\n * fixpoint that keeps unlocking newly-revealed gated branches until nothing\n * more can be opened (still bounded by `maxDepth`).\n */\nexport interface WalkHubOptions {\n readonly maxDepth?: number;\n /** Hard deadline for each directory page request. Defaults to 5 seconds. */\n readonly timeoutMs?: number;\n /** Return only listings for this exact interface id after traversing directories. */\n readonly interfaceId?: string;\n /** Return only listings whose interface id starts with this prefix after traversal. */\n readonly interfaceIdPrefix?: string;\n /** Return only listings for this exact service id after traversal. */\n readonly serviceId?: string;\n /** Initial service-id scope. Defaults to the universal `{ prefix: \"\" }`. */\n readonly serviceIdScopes?: readonly ServiceIdPattern[];\n /**\n * The directory the walk starts from. Defaults to the implicit root\n * directory (form-2 `hubrpc.directory::list`). Pass a serviceId to start at\n * `<rootTarget>::hubrpc.directory::list` — e.g. the hub's own global\n * directory (`'hub'`) when walking from the hub's in-process connection.\n */\n readonly rootTarget?: string;\n /**\n * Invoked once per gated sub-directory the walk encounters. Return `true`\n * if a capability for its `hubrpc.directory::list` was granted and the\n * directory should be re-listed; `false` (or omitted hook) leaves it in\n * {@link WalkHubResult.inaccessible}. Called at most once per `serviceId`.\n */\n unlockGatedDirectory?: (serviceId: string) => Promise<boolean>;\n /** Optional diagnostic sink for inaccessible lists and ended watches. */\n readonly log?: (message: string) => void;\n}\n\nexport async function walkHubDetailed(\n channel: ReflectionChannel,\n opts: WalkHubOptions = {},\n): Promise<WalkHubResult> {\n return new HubDirectoryExplorer(channel, opts).explore();\n}\n\n/**\n * Backward-compatible wrapper over {@link walkHubDetailed} that returns only the\n * reachable listings, dropping the inaccessible-directory report.\n */\nexport async function walkHub(\n channel: ReflectionChannel,\n opts: WalkHubOptions = {},\n): Promise<DiscoveredListing[]> {\n return (await walkHubDetailed(channel, opts)).listings;\n}\n\nexport interface HubDirectoryChange {\n /** Directory that emitted the tick. `undefined` denotes the connection root. */\n readonly target: string | undefined;\n readonly result: WalkHubResult;\n}\n\nexport type HubDirectoryGraphTarget =\n | { readonly kind: 'root'; readonly serviceId?: string; }\n | { readonly kind: 'addressed'; readonly serviceId: string; };\n\nexport type HubDirectoryNodeState =\n | 'unexplored'\n | 'loading'\n | 'loaded'\n | 'inaccessible';\n\nexport interface HubDirectoryParentReport {\n readonly target: HubDirectoryGraphTarget;\n readonly scopes: readonly ServiceIdPattern[];\n /** Resulting depth for this incoming parent path. */\n readonly depth: number;\n}\n\n/** Stable public report for one native directory response. */\nexport interface HubDirectoryNodeReport {\n readonly target: HubDirectoryGraphTarget;\n readonly state: HubDirectoryNodeState;\n readonly effectiveScopes: readonly ServiceIdPattern[];\n readonly depth: number;\n readonly parents: readonly HubDirectoryParentReport[];\n /** Per-directory listings, normalized to `ServiceListing`, before inherited metadata is folded. */\n readonly nativeListings: readonly ServiceListing[];\n readonly inaccessibleReason?: string;\n readonly watching: boolean;\n}\n\n/**\n * Complete point-in-time graph document. `root` exists from construction in\n * the `unexplored` state, so consumers can render before exploration starts.\n */\nexport interface HubDirectoryGraphSnapshot {\n readonly revision: number;\n readonly complete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: readonly HubDirectoryNodeReport[];\n readonly result: WalkHubResult;\n}\n\nexport type HubDirectoryGraphEvent =\n | {\n readonly type: 'snapshot';\n readonly reason: 'subscribed' | 'reconciliation-started' | 'reset';\n readonly snapshot: HubDirectoryGraphSnapshot;\n }\n | {\n readonly type: 'node-added';\n readonly reason: 'referral';\n readonly node: HubDirectoryNodeReport;\n readonly snapshot: HubDirectoryGraphSnapshot;\n }\n | {\n readonly type: 'node-updated';\n readonly reason:\n | 'loading'\n | 'loaded'\n | 'inaccessible'\n | 'referral'\n | 'watch-started'\n | 'watch-stopped'\n | 'watch-ended'\n | 'reset';\n readonly previous: HubDirectoryNodeReport;\n readonly node: HubDirectoryNodeReport;\n readonly snapshot: HubDirectoryGraphSnapshot;\n }\n | {\n readonly type: 'node-removed';\n readonly reason: 'unreachable' | 'reset';\n readonly previous: HubDirectoryNodeReport;\n readonly snapshot: HubDirectoryGraphSnapshot;\n }\n | {\n readonly type: 'settled';\n readonly snapshot: HubDirectoryGraphSnapshot;\n };\n\n/**\n * Reusable directory graph explorer and watcher.\n *\n * The class keeps one native snapshot per directory target. A watch tick\n * re-lists only its source target; outgoing referral changes then propagate\n * through affected descendants. Unchanged siblings retain both their snapshot\n * and watch. Multi-parent targets are queried with the normalized union of all\n * incoming path scopes.\n */\nexport class HubDirectoryExplorer {\n private readonly _maxDepth: number;\n private readonly _initialScopes: ServiceIdPattern[];\n private readonly _nodes = new Map<string, DirectoryNode>();\n private readonly _unlockAttempted = new Set<string>();\n private readonly _listeners = new Set<(change: HubDirectoryChange) => void>();\n private readonly _graphListeners = new Set<(event: HubDirectoryGraphEvent) => void>();\n private readonly _pendingTicks = new Set<string>();\n private readonly _watchRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly _watchRetryDelays = new Map<string, number>();\n private _initialized = false;\n private _disposed = false;\n private _watching = false;\n private _complete = false;\n private _revision = 0;\n private _work: Promise<void> = Promise.resolve();\n private _explorePromise: Promise<WalkHubResult> | undefined;\n\n public constructor(\n private readonly _channel: ReflectionChannel,\n private readonly _options: WalkHubOptions = {},\n ) {\n this._maxDepth = _options.maxDepth ?? DEFAULT_WALK_DEPTH;\n this._initialScopes = normalizeServiceIdScopes(\n _options.serviceIdScopes ?? [{ prefix: '' }],\n );\n this._nodes.set(ROOT_NODE_KEY, this._createRootNode());\n }\n\n /** Perform a fresh bounded exploration without starting watches. */\n public explore(): Promise<WalkHubResult> {\n this._throwIfDisposed();\n if (this._explorePromise !== undefined) return this._explorePromise;\n const promise = this._explore();\n this._explorePromise = promise;\n const clear = () => {\n if (this._explorePromise === promise) this._explorePromise = undefined;\n };\n void promise.then(clear, clear);\n return promise;\n }\n\n private async _explore(): Promise<WalkHubResult> {\n if (this._initialized || this._nodes.get(ROOT_NODE_KEY)?.state !== 'unexplored') {\n this._resetForExplore();\n }\n const root = this._nodes.get(ROOT_NODE_KEY)!;\n await this._loadNode(root);\n if (this._disposed) return { listings: [], inaccessible: [] };\n await this._reconcileScopesFromRoot();\n await this._pruneUnreachable();\n this._initialized = true;\n if (this._watching) await this._synchronizeWatches();\n this._settle();\n return this.result;\n }\n\n /** Current deduplicated graph snapshot. */\n public get result(): WalkHubResult {\n const best = new Map<string, DiscoveredListing>();\n for (const node of this._nodes.values()) {\n if (!node.loaded) continue;\n for (const item of node.listings) {\n const effective = mergePrincipalSets(item.rootPrincipalSets, node.inherited);\n const tagged: DiscoveredListing = {\n ...item,\n ...(effective.length > 0 ? { rootPrincipalSets: effective } : {}),\n discoveredFrom: node.target ?? '',\n };\n const key = listingKey(item);\n const existing = best.get(key);\n if (!existing || _isAuthoritative(tagged, existing)) best.set(key, tagged);\n }\n }\n const listings = [...best.values()]\n .filter((item) => this._options.interfaceId === undefined\n || item.interfaceId === this._options.interfaceId)\n .filter((item) => this._options.interfaceIdPrefix === undefined\n || item.interfaceId.startsWith(this._options.interfaceIdPrefix))\n .filter((item) => this._options.serviceId === undefined\n || item.serviceId === this._options.serviceId);\n const inaccessible = [...this._nodes.values()]\n .filter((node) => node.key !== ROOT_NODE_KEY && node.inaccessibleReason !== undefined)\n .map((node) => ({\n serviceId: node.target!,\n reason: node.inaccessibleReason!,\n }));\n return { listings, inaccessible };\n }\n\n /** Current complete-or-progressive directory graph report. */\n public get graphSnapshot(): HubDirectoryGraphSnapshot {\n const root = this._nodes.get(ROOT_NODE_KEY) ?? this._createRootNode();\n const directories = [...this._nodes.values()]\n .filter((node) => node.key !== ROOT_NODE_KEY)\n .sort((a, b) => (a.target ?? '').localeCompare(b.target ?? ''))\n .map((node) => this._nodeReport(node));\n return {\n revision: this._revision,\n complete: this._complete,\n root: this._nodeReport(root),\n directories,\n result: this.result,\n };\n }\n\n /**\n * Subscribe to progressive graph reports. The listener is registered before\n * receiving a synchronous current snapshot, avoiding the subscribe/explore\n * race for both idle and already-running explorers.\n */\n public subscribe(listener: (event: HubDirectoryGraphEvent) => void): () => void {\n this._throwIfDisposed();\n this._graphListeners.add(listener);\n this._deliverGraphEvent(listener, {\n type: 'snapshot',\n reason: 'subscribed',\n snapshot: this.graphSnapshot,\n });\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n this._graphListeners.delete(listener);\n };\n }\n\n /**\n * Explore once, then watch every reachable directory. Resolves after the\n * initial graph and watches are established.\n */\n public async watch(\n listener: (change: HubDirectoryChange) => void,\n ): Promise<() => void> {\n this._throwIfDisposed();\n this._listeners.add(listener);\n this._watching = true;\n if (!this._initialized) {\n await this.explore();\n } else {\n this._startReconciliation();\n await this._synchronizeWatches();\n this._settle();\n }\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n this._listeners.delete(listener);\n if (this._listeners.size === 0) {\n this._watching = false;\n this._stopAllWatches();\n }\n };\n }\n\n /** Wait until all currently queued watch reconciliation has settled. */\n public async whenIdle(): Promise<void> {\n await this._work;\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._listeners.clear();\n this._pendingTicks.clear();\n this._stopAllWatches(false);\n this._graphListeners.clear();\n this._clearNodes();\n }\n\n private async _loadNode(node: DirectoryNode, reconcileOutgoing = true): Promise<void> {\n if (node.loading) {\n node.reloadRequested = true;\n return;\n }\n node.loading = true;\n this._updateNode(node, 'loading', () => {\n node.state = 'loading';\n });\n try {\n do {\n node.reloadRequested = false;\n const scopesAtRequest = node.scopes;\n let listings: ServiceListing[];\n try {\n listings = await fetchDirectory(this._channel, {\n target: node.target,\n serviceIdScopes: scopesAtRequest,\n timeoutMs: this._options.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS,\n });\n if (this._disposed) break;\n } catch (error) {\n if (this._disposed) break;\n if (await this._tryUnlock(node)) {\n node.reloadRequested = true;\n continue;\n }\n const previous = this._nodeReport(node);\n node.inaccessibleReason = errorMessage(error);\n this._options.log?.(\n `hub directory list(${node.target ?? '<root>'}) failed: ${node.inaccessibleReason}`,\n );\n // A watcher retains the last good branch while it is\n // temporarily inaccessible. A never-loaded node contributes\n // no entries but remains in the inaccessible report.\n if (node.loaded) {\n node.listings = node.listings.filter((item) =>\n serviceIdMatchesScopes(item.serviceId, node.scopes));\n }\n node.state = 'inaccessible';\n this._emitNodeUpdated(node, previous, 'inaccessible');\n if (node.loaded && reconcileOutgoing) await this._reconcileOutgoing(node);\n break;\n }\n if (scopesKey(scopesAtRequest) !== scopesKey(node.scopes)) {\n node.reloadRequested = true;\n continue;\n }\n const previous = this._nodeReport(node);\n node.inaccessibleReason = undefined;\n node.loaded = true;\n node.listings = listings.filter((item) =>\n serviceIdMatchesScopes(item.serviceId, node.scopes));\n node.state = 'loaded';\n this._emitNodeUpdated(node, previous, 'loaded');\n if (reconcileOutgoing) await this._reconcileOutgoing(node);\n } while (node.reloadRequested && !this._disposed);\n } finally {\n node.loading = false;\n }\n }\n\n private async _tryUnlock(node: DirectoryNode): Promise<boolean> {\n if (\n node.target === undefined\n || this._options.unlockGatedDirectory === undefined\n || this._unlockAttempted.has(node.target)\n ) {\n return false;\n }\n this._unlockAttempted.add(node.target);\n try {\n return await this._options.unlockGatedDirectory(node.target);\n } catch {\n return false;\n }\n }\n\n private async _reconcileOutgoing(node: DirectoryNode): Promise<void> {\n const next = this._outgoingFor(node.scopes, node.inherited, node.depth, node.listings);\n\n const affected = new Set<string>([...node.outgoing.keys(), ...next.keys()]);\n node.outgoing = next;\n for (const childKey of affected) {\n if (this._disposed) return;\n const contribution = next.get(childKey);\n let child = this._nodes.get(childKey);\n let previous: HubDirectoryNodeReport | undefined;\n if (contribution === undefined) {\n if (child === undefined) continue;\n previous = this._nodeReport(child);\n child.parents.delete(node.key);\n } else {\n if (child === undefined) {\n child = this._createNode(childKey);\n child.parents.set(node.key, contribution);\n this._deriveNodeFromParents(child);\n this._nodes.set(childKey, child);\n this._emitNodeAdded(child);\n await this._loadNode(child);\n continue;\n }\n previous = this._nodeReport(child);\n child.parents.set(node.key, contribution);\n }\n await this._updateNodeFromParents(child, previous);\n }\n }\n\n private _outgoingFor(\n scopes: readonly ServiceIdPattern[],\n inherited: readonly RootPrincipalSet[],\n depth: number,\n listings: readonly ServiceListing[],\n ): Map<string, ParentContribution> {\n const outgoing = new Map<string, ParentContribution>();\n if (depth >= this._maxDepth) return outgoing;\n for (const item of listings) {\n if (\n item.interfaceId !== DIRECTORY_INTERFACE_ID\n || !serviceIdMatchesScopes(item.serviceId, scopes)\n ) {\n continue;\n }\n const referralScopes = item.reachableServiceIds\n ?? [{ prefix: item.serviceId }];\n const childScopes = intersectServiceIdScopes(scopes, referralScopes);\n if (childScopes.length === 0) continue;\n const childKey = this._nodeKeyForTarget(item.serviceId);\n if (childKey === ROOT_NODE_KEY) continue;\n const contribution: ParentContribution = {\n scopes: childScopes,\n inherited: mergePrincipalSets(\n inherited,\n transitiveReqsOf(item.rootPrincipalSets),\n ),\n depth: depth + 1,\n };\n const previous = outgoing.get(childKey);\n outgoing.set(childKey, previous === undefined\n ? contribution\n : mergeContributions(previous, contribution));\n }\n return outgoing;\n }\n\n private _createRootNode(): DirectoryNode {\n return {\n key: ROOT_NODE_KEY,\n target: this._options.rootTarget,\n parents: new Map(),\n scopes: [...this._initialScopes],\n inherited: [],\n depth: 0,\n listings: [],\n outgoing: new Map(),\n loaded: false,\n loading: false,\n reloadRequested: false,\n state: 'unexplored',\n };\n }\n\n private _createNode(key: string): DirectoryNode {\n return {\n key,\n target: key.slice(2),\n parents: new Map(),\n scopes: [],\n inherited: [],\n depth: Number.POSITIVE_INFINITY,\n listings: [],\n outgoing: new Map(),\n loaded: false,\n loading: false,\n reloadRequested: false,\n state: 'unexplored',\n };\n }\n\n private async _updateNodeFromParents(\n node: DirectoryNode,\n previous = this._nodeReport(node),\n ): Promise<void> {\n if (node.key === ROOT_NODE_KEY || node.parents.size === 0) return;\n const { scopes, inherited, depth } = this._derivedNodeState(node);\n const changed = scopesKey(scopes) !== scopesKey(node.scopes)\n || principalSetsKey(inherited) !== principalSetsKey(node.inherited)\n || depth !== node.depth;\n if (!changed) return;\n node.scopes = scopes;\n node.inherited = inherited;\n node.depth = depth;\n this._emitNodeUpdated(node, previous, 'referral');\n await this._loadNode(node);\n }\n\n private _deriveNodeFromParents(node: DirectoryNode): void {\n const derived = this._derivedNodeState(node);\n node.scopes = derived.scopes;\n node.inherited = derived.inherited;\n node.depth = derived.depth;\n }\n\n private _derivedNodeState(node: DirectoryNode): {\n scopes: ServiceIdPattern[];\n inherited: RootPrincipalSet[];\n depth: number;\n } {\n const contributions = [...node.parents.values()];\n return {\n scopes: normalizeServiceIdScopes(contributions.flatMap((value) => value.scopes)),\n inherited: mergePrincipalSets(\n ...contributions.map((value) => value.inherited),\n ),\n depth: Math.min(...contributions.map((value) => value.depth)),\n };\n }\n\n /**\n * Rebuild incoming contributions from the root seed. Starting with no\n * non-root contributions computes the least fixed point, so a disconnected\n * or narrowed cycle cannot keep scopes contributed by its previous state.\n */\n private async _reconcileScopesFromRoot(): Promise<void> {\n const maxRounds = Math.max(\n 16,\n (this._nodes.size + (Number.isFinite(this._maxDepth) ? this._maxDepth : 256)) * 4,\n );\n for (let round = 0; round < maxRounds; round++) {\n const computed = this._computeScopeFixedPoint();\n let relisted = false;\n const ordered = [...computed.states.entries()]\n .sort(([, left], [, right]) => left.depth - right.depth);\n\n for (const [key, state] of ordered) {\n if (key === ROOT_NODE_KEY) {\n const root = this._nodes.get(ROOT_NODE_KEY)!;\n root.outgoing = computed.outgoing.get(key) ?? new Map();\n continue;\n }\n let node = this._nodes.get(key);\n if (node === undefined) {\n node = this._createNode(key);\n node.parents = computed.parents.get(key) ?? new Map();\n node.scopes = state.scopes;\n node.inherited = state.inherited;\n node.depth = state.depth;\n node.outgoing = computed.outgoing.get(key) ?? new Map();\n this._nodes.set(key, node);\n this._emitNodeAdded(node);\n await this._loadNode(node, false);\n relisted = true;\n continue;\n }\n\n const parents = computed.parents.get(key) ?? new Map();\n const scopesChanged = scopesKey(node.scopes) !== scopesKey(state.scopes);\n const inheritedChanged =\n principalSetsKey(node.inherited) !== principalSetsKey(state.inherited);\n const depthChanged = node.depth !== state.depth;\n const parentsChanged =\n parentContributionsKey(node.parents) !== parentContributionsKey(parents);\n const previous = scopesChanged || inheritedChanged || depthChanged || parentsChanged\n ? this._nodeReport(node)\n : undefined;\n node.parents = parents;\n node.scopes = state.scopes;\n node.inherited = state.inherited;\n node.depth = state.depth;\n node.outgoing = computed.outgoing.get(key) ?? new Map();\n if (previous !== undefined) this._emitNodeUpdated(node, previous, 'referral');\n if (scopesChanged) {\n await this._loadNode(node, false);\n relisted = true;\n }\n }\n\n const unreachable = [...this._nodes.values()]\n .filter((node) => !computed.states.has(node.key))\n .sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n for (const node of unreachable) {\n const previous = this._nodeReport(node);\n this._stopWatch(node, false);\n this._nodes.delete(node.key);\n this._emitNodeRemoved(previous);\n }\n\n if (!relisted) return;\n }\n throw new Error('Hub directory scope reconciliation did not converge');\n }\n\n private _computeScopeFixedPoint(): ComputedDirectoryGraph {\n const states = new Map<string, DerivedNodeState>();\n const parents = new Map<string, Map<string, ParentContribution>>();\n const outgoing = new Map<string, Map<string, ParentContribution>>();\n states.set(ROOT_NODE_KEY, {\n scopes: [...this._initialScopes],\n inherited: [],\n depth: 0,\n });\n parents.set(ROOT_NODE_KEY, new Map());\n const queue = [ROOT_NODE_KEY];\n const processed = new Map<string, string>();\n\n while (queue.length > 0) {\n const key = queue.shift()!;\n const state = states.get(key);\n if (state === undefined) continue;\n const stateKey = derivedStateKey(state);\n if (processed.get(key) === stateKey) continue;\n processed.set(key, stateKey);\n\n const node = this._nodes.get(key);\n const next = node === undefined\n ? new Map<string, ParentContribution>()\n : this._outgoingFor(\n state.scopes,\n state.inherited,\n state.depth,\n node.listings,\n );\n outgoing.set(key, next);\n for (const [childKey, contribution] of next) {\n const childParents = parents.get(childKey) ?? new Map<string, ParentContribution>();\n childParents.set(key, contribution);\n parents.set(childKey, childParents);\n const childState = derivedStateFromParents(childParents);\n const oldState = states.get(childKey);\n if (oldState === undefined || derivedStateKey(oldState) !== derivedStateKey(childState)) {\n states.set(childKey, childState);\n queue.push(childKey);\n }\n }\n }\n return { states, parents, outgoing };\n }\n\n private async _pruneUnreachable(): Promise<void> {\n const reachable = new Set<string>();\n const queue = [ROOT_NODE_KEY];\n while (queue.length > 0) {\n const key = queue.shift()!;\n if (reachable.has(key)) continue;\n reachable.add(key);\n const node = this._nodes.get(key);\n if (node === undefined) continue;\n for (const childKey of node.outgoing.keys()) queue.push(childKey);\n }\n const removedNodes = [...this._nodes.values()]\n .filter((node) => !reachable.has(node.key))\n .sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n if (removedNodes.length === 0) return;\n const removed = new Set(removedNodes.map((node) => node.key));\n for (const node of removedNodes) {\n const previous = this._nodeReport(node);\n this._stopWatch(node, false);\n this._nodes.delete(node.key);\n this._emitNodeRemoved(previous);\n }\n for (const node of this._nodes.values()) {\n const previous = this._nodeReport(node);\n let changed = false;\n for (const parentKey of removed) changed = node.parents.delete(parentKey) || changed;\n if (changed) await this._updateNodeFromParents(node, previous);\n }\n }\n\n /**\n * Every changed watch scope uses list/watch/list: callers reach this method\n * only after a list under the current scope, then the replacement watch is\n * installed before a verification list. Either the verification sees a\n * handoff mutation or the new watch ticks for it.\n */\n private async _synchronizeWatches(): Promise<void> {\n const maxPasses = Math.max(8, this._nodes.size * 4);\n for (let pass = 0; pass < maxPasses && !this._disposed; pass++) {\n const pending = [...this._nodes.values()]\n .filter((node) =>\n node.watch === undefined || node.watchScopesKey !== scopesKey(node.scopes))\n .sort((a, b) => a.depth - b.depth || a.key.localeCompare(b.key));\n if (pending.length === 0) return;\n let installed = false;\n for (const node of pending) {\n if (this._nodes.get(node.key) !== node) continue;\n installed = this._replaceWatch(node) || installed;\n if (node.watchScopesKey === scopesKey(node.scopes)) {\n await this._loadNode(node);\n await this._reconcileScopesFromRoot();\n await this._pruneUnreachable();\n }\n }\n if (!installed) return;\n }\n throw new Error('Hub directory watch synchronization did not converge');\n }\n\n private _replaceWatch(node: DirectoryNode): boolean {\n if (!this._watching || this._disposed) return false;\n const method = node.target === undefined\n ? 'hubrpc.directory::watch'\n : `${node.target}::hubrpc.directory::watch`;\n const params: Record<string, JsonValue | undefined> = {\n serviceIdScopes: [...node.scopes],\n };\n let call: RawStreamingCall;\n try {\n call = this._channel.sendRequestWithStream(method, params, {\n onStreamMessage: () => this._queueTick(node.key),\n });\n } catch (error) {\n this._options.log?.(\n `hub directory watch(${node.target ?? '<root>'}) failed: ${errorMessage(error)}`,\n );\n this._scheduleWatchRetry(node);\n return false;\n }\n const previous = this._nodeReport(node);\n const oldWatch = node.watch;\n node.watch = call;\n node.watchScopesKey = scopesKey(node.scopes);\n this._emitNodeUpdated(node, previous, 'watch-started');\n if (oldWatch !== undefined) {\n try {\n oldWatch.cancel('directory explorer watch scope replaced');\n } catch {\n // Best-effort replacement.\n }\n }\n void call.result.then(() => {\n if (this._disposed || node.watch !== call) return;\n const previous = this._nodeReport(node);\n node.watch = undefined;\n node.watchScopesKey = undefined;\n this._emitNodeUpdated(node, previous, 'watch-ended');\n this._scheduleWatchRetry(node);\n }, (error) => {\n if (this._disposed || node.watch !== call) return;\n const previous = this._nodeReport(node);\n node.watch = undefined;\n node.watchScopesKey = undefined;\n this._options.log?.(\n `hub directory watch(${node.target ?? '<root>'}) ended: ${errorMessage(error)}`,\n );\n this._emitNodeUpdated(node, previous, 'watch-ended');\n this._scheduleWatchRetry(node);\n });\n return true;\n }\n\n private _queueTick(key: string): void {\n if (this._disposed || !this._nodes.has(key)) return;\n this._watchRetryDelays.delete(key);\n this._pendingTicks.add(key);\n this._startReconciliation();\n this._work = this._work.then(async () => {\n while (this._pendingTicks.size > 0 && !this._disposed) {\n const nextKey = this._pendingTicks.values().next().value as string;\n this._pendingTicks.delete(nextKey);\n const node = this._nodes.get(nextKey);\n if (node === undefined) continue;\n await this._loadNode(node);\n await this._reconcileScopesFromRoot();\n await this._pruneUnreachable();\n await this._synchronizeWatches();\n const change = { target: node.target, result: this.result };\n for (const listener of [...this._listeners]) {\n try {\n listener(change);\n } catch (error) {\n this._options.log?.(\n `hub directory change listener failed: ${errorMessage(error)}`,\n );\n }\n }\n }\n this._settle();\n }).catch((error) => {\n this._options.log?.(`hub directory reconciliation failed: ${errorMessage(error)}`);\n this._settle();\n });\n }\n\n private _stopWatch(node: DirectoryNode, emit = true): void {\n this._clearWatchRetry(node.key);\n const watch = node.watch;\n if (watch === undefined) return;\n const previous = emit ? this._nodeReport(node) : undefined;\n node.watch = undefined;\n node.watchScopesKey = undefined;\n try {\n watch.cancel('directory explorer watch stopped');\n } catch {\n // Best-effort teardown.\n }\n if (previous !== undefined) this._emitNodeUpdated(node, previous, 'watch-stopped');\n }\n\n private _stopAllWatches(emit = true): void {\n for (const node of this._nodes.values()) this._stopWatch(node, emit);\n for (const key of [...this._watchRetryTimers.keys()]) this._clearWatchRetry(key);\n }\n\n private _scheduleWatchRetry(node: DirectoryNode): void {\n if (\n !this._watching\n || this._disposed\n || this._nodes.get(node.key) !== node\n || this._watchRetryTimers.has(node.key)\n ) {\n return;\n }\n const delay = this._watchRetryDelays.get(node.key) ?? 200;\n this._watchRetryDelays.set(node.key, Math.min(5_000, delay * 2));\n const timer = setTimeout(() => {\n this._watchRetryTimers.delete(node.key);\n if (\n !this._watching\n || this._disposed\n || this._nodes.get(node.key) !== node\n || node.watch !== undefined\n ) {\n return;\n }\n this._startReconciliation();\n this._work = this._work.then(async () => {\n await this._synchronizeWatches();\n this._settle();\n }).catch((error) => {\n this._options.log?.(\n `hub directory watch retry failed: ${errorMessage(error)}`,\n );\n this._settle();\n this._scheduleWatchRetry(node);\n });\n }, delay);\n this._watchRetryTimers.set(node.key, timer);\n }\n\n private _clearWatchRetry(key: string): void {\n const timer = this._watchRetryTimers.get(key);\n if (timer !== undefined) clearTimeout(timer);\n this._watchRetryTimers.delete(key);\n this._watchRetryDelays.delete(key);\n }\n\n private _clearNodes(): void {\n this._stopAllWatches(false);\n this._nodes.clear();\n this._unlockAttempted.clear();\n this._pendingTicks.clear();\n this._initialized = false;\n }\n\n private _resetForExplore(): void {\n this._complete = false;\n this._emitSnapshot('reset');\n this._stopAllWatches(false);\n const addressed = [...this._nodes.values()]\n .filter((node) => node.key !== ROOT_NODE_KEY)\n .sort((a, b) => b.depth - a.depth || a.key.localeCompare(b.key));\n for (const node of addressed) {\n const previous = this._nodeReport(node);\n this._nodes.delete(node.key);\n this._emitNodeRemoved(previous, 'reset');\n }\n const previousRoot = this._nodes.get(ROOT_NODE_KEY);\n const root = this._createRootNode();\n this._nodes.set(ROOT_NODE_KEY, root);\n if (previousRoot !== undefined) {\n this._emitNodeUpdated(root, this._nodeReport(previousRoot), 'reset');\n }\n this._unlockAttempted.clear();\n this._pendingTicks.clear();\n this._initialized = false;\n }\n\n private _updateNode(\n node: DirectoryNode,\n reason: Extract<HubDirectoryGraphEvent, { type: 'node-updated' }>['reason'],\n update: () => void,\n ): void {\n const previous = this._nodeReport(node);\n update();\n this._emitNodeUpdated(node, previous, reason);\n }\n\n private _nodeReport(node: DirectoryNode): HubDirectoryNodeReport {\n const parents = [...node.parents.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([parentKey, contribution]) => ({\n target: this._targetForKey(parentKey),\n scopes: cloneScopes(contribution.scopes),\n depth: contribution.depth,\n }));\n return {\n target: this._targetForKey(node.key),\n state: node.state,\n effectiveScopes: cloneScopes(node.scopes),\n depth: node.depth,\n parents,\n nativeListings: node.listings.map(cloneListing),\n ...(node.inaccessibleReason === undefined\n ? {}\n : { inaccessibleReason: node.inaccessibleReason }),\n watching: node.watch !== undefined,\n };\n }\n\n private _targetForKey(key: string): HubDirectoryGraphTarget {\n if (key === ROOT_NODE_KEY) {\n return this._options.rootTarget === undefined\n ? { kind: 'root' }\n : { kind: 'root', serviceId: this._options.rootTarget };\n }\n return { kind: 'addressed', serviceId: key.slice(2) };\n }\n\n private _emitNodeAdded(node: DirectoryNode): void {\n this._revision++;\n this._emitGraphEvent({\n type: 'node-added',\n reason: 'referral',\n node: this._nodeReport(node),\n snapshot: this.graphSnapshot,\n });\n }\n\n private _emitNodeUpdated(\n node: DirectoryNode,\n previous: HubDirectoryNodeReport,\n reason: Extract<HubDirectoryGraphEvent, { type: 'node-updated' }>['reason'],\n ): void {\n this._revision++;\n this._emitGraphEvent({\n type: 'node-updated',\n reason,\n previous,\n node: this._nodeReport(node),\n snapshot: this.graphSnapshot,\n });\n }\n\n private _emitNodeRemoved(\n previous: HubDirectoryNodeReport,\n reason: Extract<HubDirectoryGraphEvent, { type: 'node-removed' }>['reason'] = 'unreachable',\n ): void {\n this._revision++;\n this._emitGraphEvent({\n type: 'node-removed',\n reason,\n previous,\n snapshot: this.graphSnapshot,\n });\n }\n\n private _startReconciliation(): void {\n if (!this._complete) return;\n this._complete = false;\n this._emitSnapshot('reconciliation-started');\n }\n\n private _settle(): void {\n if (this._complete || this._disposed) return;\n this._complete = true;\n this._revision++;\n this._emitGraphEvent({ type: 'settled', snapshot: this.graphSnapshot });\n }\n\n private _emitSnapshot(\n reason: Extract<HubDirectoryGraphEvent, { type: 'snapshot' }>['reason'],\n ): void {\n this._revision++;\n this._emitGraphEvent({ type: 'snapshot', reason, snapshot: this.graphSnapshot });\n }\n\n private _emitGraphEvent(event: HubDirectoryGraphEvent): void {\n for (const listener of this._graphListeners) this._deliverGraphEvent(listener, event);\n }\n\n private _deliverGraphEvent(\n listener: (event: HubDirectoryGraphEvent) => void,\n event: HubDirectoryGraphEvent,\n ): void {\n try {\n listener(event);\n } catch (error) {\n this._options.log?.(`hub directory graph listener failed: ${errorMessage(error)}`);\n }\n }\n\n private _nodeKeyForTarget(target: string): string {\n const isImplicitRoot = this._options.rootTarget === undefined && target === '';\n return target === this._options.rootTarget || isImplicitRoot\n ? ROOT_NODE_KEY\n : `s:${target}`;\n }\n\n private _throwIfDisposed(): void {\n if (this._disposed) throw new Error('HubDirectoryExplorer is disposed');\n }\n}\n\ninterface ParentContribution {\n readonly scopes: readonly ServiceIdPattern[];\n readonly inherited: readonly RootPrincipalSet[];\n readonly depth: number;\n}\n\ninterface DirectoryNode {\n readonly key: string;\n readonly target: string | undefined;\n parents: Map<string, ParentContribution>;\n scopes: ServiceIdPattern[];\n inherited: RootPrincipalSet[];\n depth: number;\n listings: ServiceListing[];\n outgoing: Map<string, ParentContribution>;\n loaded: boolean;\n loading: boolean;\n reloadRequested: boolean;\n state: HubDirectoryNodeState;\n inaccessibleReason?: string;\n watch?: RawStreamingCall;\n watchScopesKey?: string;\n}\n\ninterface DerivedNodeState {\n readonly scopes: ServiceIdPattern[];\n readonly inherited: RootPrincipalSet[];\n readonly depth: number;\n}\n\ninterface ComputedDirectoryGraph {\n readonly states: Map<string, DerivedNodeState>;\n readonly parents: Map<string, Map<string, ParentContribution>>;\n readonly outgoing: Map<string, Map<string, ParentContribution>>;\n}\n\nfunction mergeContributions(\n left: ParentContribution,\n right: ParentContribution,\n): ParentContribution {\n return {\n scopes: normalizeServiceIdScopes([...left.scopes, ...right.scopes]),\n inherited: mergePrincipalSets(left.inherited, right.inherited),\n depth: Math.min(left.depth, right.depth),\n };\n}\n\nfunction derivedStateFromParents(\n parents: ReadonlyMap<string, ParentContribution>,\n): DerivedNodeState {\n const contributions = [...parents.values()];\n return {\n scopes: normalizeServiceIdScopes(contributions.flatMap((value) => value.scopes)),\n inherited: mergePrincipalSets(\n ...contributions.map((value) => value.inherited),\n ),\n depth: Math.min(...contributions.map((value) => value.depth)),\n };\n}\n\nfunction derivedStateKey(state: {\n readonly scopes: readonly ServiceIdPattern[];\n readonly inherited: readonly RootPrincipalSet[];\n readonly depth: number;\n}): string {\n return `${scopesKey(state.scopes)}\\u0001${principalSetsKey(state.inherited)}\\u0001${state.depth}`;\n}\n\nfunction parentContributionsKey(\n parents: ReadonlyMap<string, ParentContribution>,\n): string {\n return [...parents.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, contribution]) =>\n `${key}\\u0002${derivedStateKey(contribution)}`)\n .join('\\u0003');\n}\n\nfunction mergePrincipalSets(\n ...groups: readonly (readonly RootPrincipalSet[] | undefined)[]\n): RootPrincipalSet[] {\n const unique = new Map<string, RootPrincipalSet>();\n for (const group of groups) {\n for (const set of group ?? []) {\n const copy = set.map((requirement) => ({ ...requirement }));\n const key = JSON.stringify(copy);\n if (!unique.has(key)) unique.set(key, copy);\n }\n }\n return [...unique.values()];\n}\n\nfunction principalSetsKey(sets: readonly RootPrincipalSet[]): string {\n return JSON.stringify(sets);\n}\n\nfunction listingKey(item: ServiceListing): string {\n return `${item.serviceId}\\u0000${item.interfaceId}\\u0000${item.hash}`;\n}\n\nfunction cloneScopes(scopes: readonly ServiceIdPattern[]): ServiceIdPattern[] {\n return scopes.map((scope) => ({ ...scope }));\n}\n\nfunction cloneListing(item: ServiceListing): ServiceListing {\n return {\n ...item,\n ...(item.rootPrincipalSets === undefined\n ? {}\n : {\n rootPrincipalSets: item.rootPrincipalSets.map((set) =>\n set.map((requirement) => ({ ...requirement }))),\n }),\n ...(item.reachableServiceIds === undefined\n ? {}\n : { reachableServiceIds: cloneScopes(item.reachableServiceIds) }),\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Extract the `transitive` requirements of a CNF requirement collection as\n * singleton AND-sets (kept transitive), so they keep flowing down further hops.\n */\nfunction transitiveReqsOf(sets: readonly RootPrincipalSet[] | undefined): RootPrincipalSet[] {\n return (sets ?? [])\n .flatMap((set) => set.filter((req) => req.transitive === true))\n .map((req) => [req] as RootPrincipalSet);\n}\n\n/**\n * Prefer a listing whose reporter (`discoveredFrom`) equals its own `serviceId`\n * — that's the participant speaking about itself, and is more authoritative\n * than an aggregator forwarding it.\n */\nfunction _isAuthoritative(candidate: DiscoveredListing, current: DiscoveredListing): boolean {\n const candidateDirect = candidate.discoveredFrom === candidate.serviceId;\n const currentDirect = current.discoveredFrom === current.serviceId;\n return candidateDirect && !currentDirect;\n}\n","import {\n ErrorCode,\n isNotification,\n isRequest,\n isResponse,\n type JsonRpcError,\n type JsonRpcMessage,\n type JsonRpcNotification,\n type JsonRpcRequest,\n type JsonValue,\n type RequestId,\n} from '../protocol/jsonRpc';\nimport {\n STREAM_METHOD,\n StreamControlType,\n StreamDir,\n type StreamSendParams,\n} from './streaming';\nimport {\n Channel,\n type MessageWithCtx,\n type ChannelTransport,\n type IncomingStream,\n type IRequestHandler,\n type IRequestSender,\n type RawStreamingCall,\n type Result,\n RpcError,\n type SendOpts,\n type StreamSendOpts,\n type WireMessageObserver,\n} from './channel';\n\n/**\n * How often a streaming-enabled call emits a `toCallee` keepalive ping so a\n * routing hub's per-request idle timer never reaps the in-flight request.\n * Must stay comfortably below the hub's idle timeout (default 30 min).\n */\nconst KEEPALIVE_PING_INTERVAL_MS = 10 * 60_000;\n\n/**\n * Minimal JSON-RPC 2.0 channel: correlates requests with responses,\n * dispatches incoming requests/notifications to a handler.\n *\n * Construct via {@link JsonRpcChannel.create}: it returns a\n * {@link Channel} factory which materialises the live channel once a\n * handler is supplied via `.connect(handler)`. The handler is fixed for\n * the channel's lifetime — no setter, no mid-flight swap.\n *\n * The outbound `TOutCtx` of the produced sender is `unknown` — this\n * channel ignores per-call ctx entirely. Decorators (e.g.\n * `SigningSender`) lift it to a concrete shape.\n */\nexport class JsonRpcChannel<TInCtx = undefined> implements IRequestSender<unknown> {\n /**\n * Wrap a transport in a {@link Channel}. The channel's sender is live\n * immediately; call {@link Channel.setRequestHandler} (or pass the channel\n * to {@link LinkRpcConnection}) to bind the inbound handler.\n */\n public static create<TInCtx = undefined>(transport: ChannelTransport<TInCtx>): Channel<TInCtx, unknown> {\n return this.createWithClose(transport).channel;\n }\n\n /** Wrap a transport and retain an explicit lifecycle hook for its owner. */\n public static createWithClose<TInCtx = undefined>(\n transport: ChannelTransport<TInCtx>,\n ): { channel: Channel<TInCtx, unknown>; close: () => void; } {\n const jrc = new JsonRpcChannel<TInCtx>(transport);\n const channel = new Channel<TInCtx, unknown>(\n jrc,\n (h) => jrc.setRequestHandler(h),\n (observer) => jrc.setWireMessageObserver(observer),\n );\n return { channel, close: () => jrc.close() };\n }\n\n private _nextId = 1;\n private readonly _pending = new Map<string, {\n resolve: (v: JsonValue) => void;\n reject: (err: Error) => void;\n }>();\n /**\n * Per-request callbacks invoked when a {@link STREAM_METHOD}\n * notification arrives with a matching `requestId`. Used in both\n * directions: outgoing-request callers register here keyed by the\n * id they sent; per-call incoming-request stream handles register\n * keyed by the id they observed. Entries are removed when the\n * corresponding request completes (response received for outgoing,\n * response sent for incoming).\n */\n private readonly _streamListeners = new Map<string, (payload: JsonValue) => void>();\n\n /**\n * Per-incoming-request handlers for reserved `control` messages\n * (cancel / ping / pong) arriving as stream notifications. Keyed\n * by the id observed; removed when the request settles.\n */\n private readonly _streamControl = new Map<\n string,\n (control: { type: string; reason?: string; nonce?: string; }) => void\n >();\n private readonly _incomingAborts = new Map<string, AbortController>();\n\n private _handler: IRequestHandler<TInCtx> | undefined;\n private _wireObserver: WireMessageObserver | undefined;\n private _closeError: Error | undefined;\n\n public setRequestHandler(handler: IRequestHandler<TInCtx> | undefined): void {\n this._handler = handler;\n }\n\n public setWireMessageObserver(\n observer: WireMessageObserver | undefined,\n ): void {\n this._wireObserver = observer;\n }\n\n private constructor(private readonly _transport: ChannelTransport<TInCtx>) {\n this._transport.setListener((m) => this._onMessage(m));\n }\n\n public async sendRequest(\n method: string,\n params: JsonValue | undefined,\n opts?: SendOpts<unknown>,\n ): Promise<JsonValue> {\n this._throwIfClosed();\n const id = this._nextId++;\n const req: JsonRpcRequest = { jsonrpc: '2.0', id, method };\n if (params !== undefined) req.params = params;\n const promise = new Promise<JsonValue>((resolve, reject) => {\n this._pending.set(String(id), { resolve, reject });\n });\n this._observeOutbound(req, opts);\n try {\n await this._transport.send(req);\n } catch (error) {\n this._pending.delete(String(id));\n this._observeSendFailure(id, error);\n throw error;\n }\n return promise;\n }\n\n public async sendNotification(\n method: string,\n params: JsonValue | undefined,\n opts?: SendOpts<unknown>,\n ): Promise<void> {\n this._throwIfClosed();\n const n: JsonRpcNotification = { jsonrpc: '2.0', method };\n if (params !== undefined) n.params = params;\n this._observeOutbound(n, opts);\n await this._transport.send(n);\n }\n\n public sendRequestWithStream(\n method: string,\n params: JsonValue | undefined,\n opts?: StreamSendOpts<unknown>,\n ): RawStreamingCall {\n this._throwIfClosed();\n const id = this._nextId++;\n const key = String(id);\n let resolveResult!: (v: JsonValue) => void;\n let rejectResult!: (err: Error) => void;\n const result = new Promise<JsonValue>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n this._pending.set(key, { resolve: resolveResult, reject: rejectResult });\n if (opts?.onStreamMessage) {\n this._streamListeners.set(key, opts.onStreamMessage);\n }\n // Symmetric ping/pong for this call. We emit controls `toCallee`,\n // so an inbound ping is answered with a `toCallee` pong.\n const pinger = this._makePinger(id, StreamDir.toCallee);\n this._streamControl.set(key, pinger.onControl);\n // Keepalive: a streaming-enabled call emits a periodic `toCallee`\n // ping so the hub's per-request idle timer never reaps it. Cleared\n // once the call settles (in either direction). Fire-and-forget: the\n // peer's pong (no matching nonce) is ignored.\n const ping = setInterval(() => {\n void this._sendStream(id, StreamDir.toCallee, {\n control: { type: StreamControlType.ping },\n });\n }, KEEPALIVE_PING_INTERVAL_MS);\n (ping as { unref?: () => void; }).unref?.();\n const stopPing = (): void => {\n clearInterval(ping);\n pinger.dispose();\n this._streamControl.delete(key);\n };\n const dispose = (reason = 'streaming request disposed'): void => {\n if (!this._pending.delete(key)) return;\n this._streamListeners.delete(key);\n stopPing();\n rejectResult(new RpcError(reason, ErrorCode.cancelled));\n };\n result.then(stopPing, stopPing);\n (async () => {\n const req: JsonRpcRequest = { jsonrpc: '2.0', id, method };\n if (params !== undefined) req.params = params;\n this._observeOutbound(req, opts);\n await this._transport.send(req);\n })().catch((err) => {\n // Send-time failure: clear bookkeeping and surface on result.\n this._pending.delete(key);\n this._streamListeners.delete(key);\n this._observeSendFailure(id, err);\n stopPing();\n rejectResult(err instanceof Error ? err : new Error(String(err)));\n });\n return {\n result,\n send: (payload) => this._sendStream(id, StreamDir.toCallee, { payload }),\n cancel: (reason) =>\n this._sendStream(id, StreamDir.toCallee, {\n control: reason !== undefined ?\n { type: StreamControlType.cancel, reason } :\n { type: StreamControlType.cancel },\n }),\n dispose,\n ping: pinger.ping,\n };\n }\n\n /**\n * Build the symmetric ping/pong machinery for one in-flight request.\n *\n * `outboundDir` is the direction *this* side emits controls in\n * (`toCallee` for the caller, `toCaller` for the callee). A received\n * ping is answered with a pong in that same direction, echoing the\n * ping's nonce; a received pong resolves the matching outstanding\n * {@link ping} probe.\n */\n private _makePinger(requestId: RequestId, outboundDir: StreamDir): {\n ping: () => Promise<void>;\n onControl: (control: { type: string; nonce?: string; }) => void;\n dispose: () => void;\n } {\n const pending = new Map<string, { resolve: () => void; reject: (e: Error) => void; }>();\n let nextNonce = 1;\n const ping = (): Promise<void> => {\n const nonce = `${requestId}:${nextNonce++}`;\n const p = new Promise<void>((resolve, reject) => pending.set(nonce, { resolve, reject }));\n void this._sendStream(requestId, outboundDir, {\n control: { type: StreamControlType.ping, nonce },\n });\n return p;\n };\n const onControl = (control: { type: string; nonce?: string; }): void => {\n if (control.type === StreamControlType.ping) {\n // Auto-answer: echo the nonce back the way our controls travel.\n void this._sendStream(requestId, outboundDir, {\n control: { type: StreamControlType.pong, nonce: control.nonce },\n });\n } else if (control.type === StreamControlType.pong && control.nonce !== undefined) {\n const waiter = pending.get(control.nonce);\n if (waiter) {\n pending.delete(control.nonce);\n waiter.resolve();\n }\n }\n };\n const dispose = (): void => {\n const err = new RpcError('Request settled before pong', ErrorCode.cancelled);\n for (const w of pending.values()) w.reject(err);\n pending.clear();\n };\n return { ping, onControl, dispose };\n }\n\n /**\n * Emit a stream notification ({@link STREAM_METHOD}) associated with\n * an in-flight request. Internal: outgoing-side callers reach this\n * via {@link RawStreamingCall.send} / `cancel`; incoming-side handlers\n * reach it via {@link IncomingStream.send}.\n */\n private async _sendStream(\n requestId: RequestId,\n dir: StreamDir,\n fields: {\n payload?: JsonValue;\n control?: { type: StreamControlType; reason?: string; nonce?: string; };\n },\n ): Promise<void> {\n this._throwIfClosed();\n const params: StreamSendParams = { requestId, dir, ...fields };\n const n: JsonRpcNotification = {\n jsonrpc: '2.0',\n method: STREAM_METHOD,\n params: params as unknown as JsonValue,\n };\n this._observeOutbound(n);\n await this._transport.send(n);\n }\n\n public close(): void {\n if (this._closeError) return;\n const error = new RpcError('Connection closed', ErrorCode.peerDisconnected);\n this._closeError = error;\n for (const abort of this._incomingAborts.values()) abort.abort(error);\n this._incomingAborts.clear();\n this._transport.dispose();\n for (const p of this._pending.values()) p.reject(error);\n this._pending.clear();\n this._streamListeners.clear();\n this._streamControl.clear();\n }\n\n private _throwIfClosed(): void {\n if (this._closeError) throw this._closeError;\n }\n\n private _onMessage(m: MessageWithCtx<TInCtx>): void {\n // `context` is present iff TInCtx ≠ undefined; the channel itself\n // doesn't care which case we're in and just forwards whatever the\n // transport delivered.\n const ctx = (m as { context?: TInCtx; }).context as TInCtx;\n this._observeInbound(m);\n if (isResponse(m)) {\n if (m.id === null) return;\n const key = String(m.id);\n const pending = this._pending.get(key);\n if (!pending) return;\n this._pending.delete(key);\n // Outgoing-request stream listener (if any) is scoped to the\n // request's lifetime; drop it when the response arrives.\n this._streamListeners.delete(key);\n if ('error' in m) {\n const e = m.error;\n const err = new RpcError(e.message, e.code, e.data);\n pending.reject(err);\n } else {\n pending.resolve(m.result);\n }\n return;\n }\n if (isRequest(m)) {\n void this._handleRequest(m, ctx).catch(() => {\n // A response can lose its transport after the request handler\n // has completed; there is no caller left to receive that error.\n });\n return;\n }\n if (isNotification(m)) {\n if (m.method === STREAM_METHOD) {\n this._handleStreamNotification(m);\n return;\n }\n this._handleNotification(m, ctx);\n return;\n }\n }\n\n private _handleStreamNotification(m: JsonRpcNotification): void {\n const params = m.params as StreamSendParams | undefined;\n if (!params) return;\n const requestId = params.requestId;\n if (requestId === undefined) return;\n const key = String(requestId);\n // Reserved control (cancel / ping): routed to the per-request\n // control handler, never to the app payload listener.\n if (params.control) {\n this._streamControl.get(key)?.(params.control);\n return;\n }\n const listener = this._streamListeners.get(key);\n if (!listener) return;\n listener(params.payload as JsonValue);\n }\n\n private async _handleRequest(m: JsonRpcRequest, context: TInCtx): Promise<void> {\n const key = String(m.id);\n // Symmetric ping/pong for this call. The handler emits controls\n // `toCaller`, so an inbound ping is answered with a `toCaller` pong.\n const pinger = this._makePinger(m.id, StreamDir.toCaller);\n const stream: IncomingStream = {\n send: (payload) => this._sendStream(m.id, StreamDir.toCaller, { payload }),\n onMessage: (listener) => {\n if (listener) this._streamListeners.set(key, listener);\n else this._streamListeners.delete(key);\n },\n ping: pinger.ping,\n };\n // A `toCallee` cancel control trips the handler's AbortSignal;\n // ping/pong are liveness only and handled by the pinger.\n const abort = new AbortController();\n this._incomingAborts.set(key, abort);\n this._streamControl.set(key, (control) => {\n if (control.type === StreamControlType.cancel) {\n abort.abort(new RpcError(control.reason ?? 'cancelled', ErrorCode.cancelled));\n } else {\n pinger.onControl(control);\n }\n });\n\n let result: Result;\n try {\n if (!this._handler) {\n result = {\n error: {\n code: ErrorCode.methodNotFound,\n message: `No handler registered on this endpoint (method: ${m.method}).`,\n },\n };\n } else {\n try {\n result = await this._handler.handleRequest({\n method: m.method,\n params: m.params,\n context,\n stream,\n signal: abort.signal,\n });\n } catch (e) {\n result = {\n error: {\n code: ErrorCode.internalError,\n message: e instanceof Error ? e.message : String(e),\n },\n };\n }\n }\n } finally {\n // Auto-detach the inbound stream listener + control: the handler is done.\n this._streamListeners.delete(key);\n this._streamControl.delete(key);\n this._incomingAborts.delete(key);\n pinger.dispose();\n }\n if ('result' in result) {\n const response = {\n jsonrpc: '2.0',\n id: m.id,\n result: result.result,\n } as const;\n this._observeOutbound(response);\n await this._transport.send(response);\n } else {\n const resp: JsonRpcError = {\n jsonrpc: '2.0',\n id: m.id,\n error: result.error,\n };\n this._observeOutbound(resp);\n await this._transport.send(resp);\n }\n }\n\n private _handleNotification(m: JsonRpcNotification, context: TInCtx): void {\n if (!this._handler) return;\n try {\n this._handler.handleNotification({\n method: m.method,\n params: m.params,\n context,\n stream: _NOOP_STREAM,\n signal: _NEVER_ABORT,\n });\n } catch {\n // Notifications have no response; swallow exceptions to avoid\n // killing the transport.\n }\n }\n\n private _observeInbound(message: JsonRpcMessage): void {\n const observer = this._wireObserver;\n if (observer === undefined) return;\n observer('inbound', message);\n }\n\n private _observeOutbound(\n message: JsonRpcMessage,\n opts?: SendOpts<unknown>,\n ): void {\n const observer = this._wireObserver;\n if (observer === undefined) return;\n observer('outbound', message);\n }\n\n private _observeSendFailure(requestId: RequestId, error: unknown): void {\n if (this._wireObserver === undefined) return;\n this._observeInbound({\n jsonrpc: '2.0',\n id: requestId,\n error: {\n code: ErrorCode.peerDisconnected,\n message: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n}\n\n/** Stub stream handle for notifications, which carry no request id. */\nconst _NOOP_STREAM: IncomingStream = {\n send: () => Promise.resolve(),\n onMessage: () => { },\n ping: () => Promise.resolve(),\n};\n\n/** A signal that never aborts — handed to notification handlers. */\nconst _NEVER_ABORT: AbortSignal = new AbortController().signal;\n","import {\n isNotification,\n isRequest,\n isResponse,\n type JsonRpcMessage,\n type RequestId,\n} from '../protocol/jsonRpc';\nimport {\n STREAM_METHOD,\n type StreamSendParams,\n} from '../connection/streaming';\nimport type {\n TrafficEvent,\n TrafficTransitEvent,\n} from './inspection.interfaces';\nimport {\n BoundedTrafficSubscription,\n type TrafficSubscription,\n type TrafficSubscriptionOptions,\n} from './boundedTrafficSubscription';\nimport { TrafficWatchFlowTracker } from './trafficFlowFilter';\nimport type { WireMessageDirection, WireMessageObserver } from '../connection/channel';\n\ninterface RequestCorrelation {\n readonly method: string;\n readonly timeMs: number;\n}\n\nconst REQUEST_CORRELATION_RETENTION_MS = 30 * 60_000;\nconst MAX_REQUEST_CORRELATIONS = 4096;\n\nexport interface EndpointTrafficWatchOptions extends TrafficSubscriptionOptions {}\n\nexport interface EndpointTrafficSubscription extends TrafficSubscription {}\n\nexport interface EndpointTrafficObservation {\n dispose(): void;\n}\n\nexport class EndpointTrafficInspector {\n private readonly _subscribers = new Set<BoundedTrafficSubscription>();\n private readonly _observers = new Set<(transit: TrafficTransitEvent) => void>();\n private readonly _outboundRequests = new Map<string, RequestCorrelation>();\n private readonly _inboundRequests = new Map<string, RequestCorrelation>();\n private readonly _trafficWatches = new TrafficWatchFlowTracker();\n\n public readonly observe: WireMessageObserver = (direction, message) => {\n this._onMessage(direction, message);\n };\n\n constructor(\n private readonly _nodeId: string,\n private readonly _portId: string,\n private readonly _setActive: (active: boolean) => void,\n ) { }\n\n public start(): void {\n this._setActive(true);\n }\n\n public get observerCount(): number {\n return this._subscribers.size + this._observers.size;\n }\n\n public subscribe(\n options: EndpointTrafficWatchOptions,\n send: (event: TrafficEvent) => Promise<void>,\n ): EndpointTrafficSubscription {\n if (\n options.trafficIgnoreKey !== undefined\n && !this._trafficWatches.claim(options.trafficIgnoreKey)\n ) {\n throw new Error('Traffic watch request was not observed before subscription');\n }\n const subscriber = new BoundedTrafficSubscription(options, send, () => {\n this._subscribers.delete(subscriber);\n this._clearCorrelationsIfUnused();\n });\n this._subscribers.add(subscriber);\n return subscriber;\n }\n\n public observeTransits(observer: (transit: TrafficTransitEvent) => void): EndpointTrafficObservation {\n this._observers.add(observer);\n let disposed = false;\n return {\n dispose: () => {\n if (disposed) return;\n disposed = true;\n this._observers.delete(observer);\n this._clearCorrelationsIfUnused();\n },\n };\n }\n\n public dispose(): void {\n for (const subscriber of [...this._subscribers]) subscriber.dispose();\n this._subscribers.clear();\n this._observers.clear();\n this._outboundRequests.clear();\n this._inboundRequests.clear();\n this._trafficWatches.clear();\n this._setActive(false);\n }\n\n private _onMessage(\n direction: WireMessageDirection,\n message: JsonRpcMessage,\n ): void {\n const now = Date.now();\n this._pruneRequestCorrelations(now);\n const publiclyObserved = this._subscribers.size !== 0 || this._observers.size !== 0;\n let transit: TrafficTransitEvent;\n const endpoint = this._endpoint('id' in message ? message.id ?? undefined : undefined);\n const base = {\n type: 'transit' as const,\n timeMs: now,\n nodeId: this._nodeId,\n ...(direction === 'inbound' ? { in: endpoint } : { out: endpoint }),\n disposition: direction === 'inbound' ? 'consumed' as const : 'forwarded' as const,\n };\n if (isRequest(message)) {\n const correlation: RequestCorrelation = {\n method: message.method,\n timeMs: now,\n };\n if (publiclyObserved) {\n const map = this._requestMap(direction);\n const key = requestKey(message.id);\n map.delete(key);\n map.set(key, correlation);\n }\n transit = {\n ...base,\n kind: 'request',\n method: message.method,\n params: message.params,\n };\n } else if (isResponse(message)) {\n const responseMap = direction === 'inbound'\n ? this._outboundRequests\n : this._inboundRequests;\n const key = requestKey(message.id);\n const correlation = responseMap.get(key);\n responseMap.delete(key);\n transit = {\n ...base,\n kind: 'response',\n method: correlation?.method,\n result: 'result' in message ? message.result : undefined,\n error: 'error' in message ? message.error : undefined,\n };\n } else if (isNotification(message) && message.method === STREAM_METHOD) {\n const params = message.params as StreamSendParams | undefined;\n const streamEndpoint = this._endpoint(params?.requestId);\n transit = {\n ...base,\n ...(direction === 'inbound' ? { in: streamEndpoint } : { out: streamEndpoint }),\n kind: 'stream',\n method: STREAM_METHOD,\n params: message.params,\n };\n } else {\n transit = {\n ...base,\n kind: 'notification',\n method: message.method,\n params: message.params,\n };\n }\n\n function requestKey(requestId: RequestId | null): string {\n return JSON.stringify([typeof requestId, requestId]);\n }\n\n if (this._trafficWatches.accept(transit)) return;\n if (!publiclyObserved) return;\n for (const observer of [...this._observers]) {\n try {\n observer(transit);\n } catch {\n // Diagnostic observers never participate in transport lifecycle.\n }\n }\n for (const subscriber of this._subscribers) subscriber.enqueue(transit);\n }\n\n private _requestMap(\n direction: WireMessageDirection,\n ): Map<string, RequestCorrelation> {\n return direction === 'outbound'\n ? this._outboundRequests\n : this._inboundRequests;\n }\n\n private _endpoint(requestId: RequestId | undefined) {\n return {\n edgeId: this._portId,\n portId: this._portId,\n ...(requestId !== undefined ? { requestId } : {}),\n } as const;\n }\n\n private _clearCorrelationsIfUnused(): void {\n if (this._subscribers.size !== 0 || this._observers.size !== 0) return;\n this._outboundRequests.clear();\n this._inboundRequests.clear();\n }\n\n private _pruneRequestCorrelations(timeMs: number): void {\n this._pruneRequestMap(this._outboundRequests, timeMs);\n this._pruneRequestMap(this._inboundRequests, timeMs);\n }\n\n private _pruneRequestMap(\n map: Map<string, RequestCorrelation>,\n timeMs: number,\n ): void {\n while (map.size !== 0) {\n const first = map.entries().next().value as\n | [string, RequestCorrelation]\n | undefined;\n if (\n first === undefined\n || (\n map.size <= MAX_REQUEST_CORRELATIONS\n && timeMs - first[1].timeMs <= REQUEST_CORRELATION_RETENTION_MS\n )\n ) {\n return;\n }\n map.delete(first[0]);\n }\n }\n\n}\n","import { ErrorCode, type JsonRpcMessage, type JsonValue } from '../protocol/jsonRpc';\nimport { parseMethodName } from '../protocol/methodName';\nimport { stripLinkRpcWireMeta } from '../protocol/linkRpcEnvelope';\nimport {\n defaultsInterface,\n directoryInterface,\n schemasInterface,\n type RootPrincipalSet,\n type ServiceIdPattern,\n} from '../hub/common/reflection.interfaces';\nimport { serviceIdMatchesScopes } from '../hub/common/directoryWalk';\nimport { nodeInterface, type NodeInfo, type TopologyIdGenerator } from '../inspection/node.interfaces';\nimport {\n topologyInterface,\n trafficInterface,\n type TopologyGraph,\n type ParticipantDescriptorSource,\n type TrafficEvent,\n type TrafficTransitEvent,\n type TrafficWatchResult,\n} from '../inspection/inspection.interfaces';\nimport type {\n InterfaceClient,\n InterfaceDefinition,\n InterfaceHandlers,\n StreamApi,\n} from './interfaceDefinition';\nimport { type MemberType, NotificationType, RequestType, type Schema } from '../schema/memberTypes';\nimport { safeParse } from 'zod/v4/core';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport {\n Channel,\n type MessageWithCtx,\n type IncomingCall,\n type IncomingStream,\n type IRequestSender, type Result,\n RpcError,\n type StreamSendOpts,\n} from './channel';\nimport { JsonRpcChannel } from './jsonRpcChannel';\nimport { bytesToBase64Url } from '../crypto/cryptoProvider';\nimport {\n EndpointTrafficInspector,\n type EndpointTrafficWatchOptions,\n} from '../inspection/endpointTrafficInspector';\nimport {\n isBareInterfaceTarget,\n validateBarePrefix,\n type BareInterfaceTarget,\n} from './bareInterfaceTarget';\n\nexport interface LinkRpcConnectionOptions {\n /** Topology node/port ID generator. Defaults to cryptographic randomness. */\n readonly generateTopologyId?: TopologyIdGenerator;\n /**\n * Validate parameters passed through typed interface clients before sending\n * them. Enabled by default. Disable only when interoperating with a peer\n * whose accepted wire shape intentionally differs from the local schema.\n */\n readonly validateOutboundParams?: boolean;\n}\n\n/**\n * High-level linkrpc connection. Layers method-name routing and zod-driven\n * validation on top of a plain JSON-RPC channel.\n *\n * Typed proxies built by this class merely forward each call's\n * `interfaceHash` hint to the channel so the signer stamps it into the\n * `$hubrpc` envelope.\n *\n * `TInCtx` is the per-call out-of-band context the connection's transport\n * carries. Default `undefined` covers cross-process and ordinary in-process\n * transports. The hub's self/overlay connections instantiate with a\n * concrete `TInCtx` (e.g. `Participant`) so handlers can see who originated\n * the call.\n *\n * `TOutCtx` is the per-call override / extension bag the outbound sender\n * understands (see {@link SendOpts.ctx}). It only ever flows into the\n * sender as input, so it is a contravariant type parameter. Default `any`\n * keeps the bare `LinkRpcConnection` a valid supertype for holders that do\n * not care about the outbound ctx; pass a concrete shape (e.g.\n * `SigningCallCtx`) to get precise {@link get} typing. The connection\n * itself is agnostic to its contents — it merely forwards the `ctx`\n * defaults supplied to {@link get}.\n */\nexport class LinkRpcConnection<TInCtx = any, TOutCtx = any> {\n /**\n * Convenience: build a {@link JsonRpcChannel} `Channel` from the\n * given transport and wrap it in an `LinkRpcConnection`. Use this\n * when you have a transport at hand and don't need a decorator\n * stack (e.g. signing).\n */\n public static fromTransport<TInCtx = undefined>(\n transport: IMessageTransport<MessageWithCtx<TInCtx>, JsonRpcMessage>,\n options: LinkRpcConnectionOptions = {},\n ): LinkRpcConnection<TInCtx> {\n return new LinkRpcConnection<TInCtx>(JsonRpcChannel.create<TInCtx>(transport), options);\n }\n\n /** Underlying JSON-RPC sender — useful for callers that need raw access (e.g. to call hub-served methods that bypass the interface registry). */\n public readonly channel: IRequestSender<TOutCtx>;\n\n /** key = `${serviceId ?? \"\"}::${interfaceId}` */\n private readonly _registry = new Map<string, RegisteredInterface>();\n\n /** Descriptions for services that have been registered with a `serviceDescription`. */\n private readonly _serviceDescriptions = new Map<string, string>();\n\n /** Root-node-id requirement sets recorded per serviceId. */\n private readonly _serviceRootPrincipalSets = new Map<string, readonly RootPrincipalSet[]>();\n\n private readonly _directoryWatchers = new Set<DirectoryWatcher>();\n private readonly _directoryListeners = new Set<() => void>();\n\n private _inspection: InspectionRegistration | undefined;\n private _trafficInspector: EndpointTrafficInspector | undefined;\n private readonly _serviceInspectionRegistrations = new Map<string, InterfaceRegistration[]>();\n private readonly _wireChannel: Channel<TInCtx, TOutCtx> | undefined;\n private readonly _validateOutboundParams: boolean;\n /** Bare-method bindings, keyed by their exact wire prefix. */\n private readonly _bareBindings = new Map<string, BareBinding>();\n private readonly _generateTopologyId: TopologyIdGenerator;\n\n /**\n * Construct from a {@link Channel} (binds the inbound handler and uses\n * `channel.sender` for outbound calls) or from a bare\n * {@link IRequestSender} (send-only — no inbound handler is registered,\n * useful for bootstrap flows like `createManagedIdentity`).\n */\n constructor(\n channel: Channel<TInCtx, TOutCtx> | IRequestSender<TOutCtx>,\n options: LinkRpcConnectionOptions = {},\n ) {\n this._validateOutboundParams = options.validateOutboundParams !== false;\n this._generateTopologyId = options.generateTopologyId ?? createInspectionId;\n if ('sender' in channel) {\n this._wireChannel = channel;\n this.channel = channel.sender;\n channel.setRequestHandler({\n handleRequest: (c) => this._handleRequest(c),\n handleNotification: (c) => this._handleNotification(c),\n });\n } else {\n this._wireChannel = undefined;\n this.channel = channel;\n }\n }\n\n /** Get a typed metadata-free client for a bundled bare interface target. */\n public get<TDef extends InterfaceDefinition<any>>(\n target: BareInterfaceTarget<TDef>,\n ): InterfaceClient<TDef>;\n\n /** Get a typed client for `iface`, routed to the implicit (root) service. */\n public get<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n opts?: GetOptions<TOutCtx>,\n ): InterfaceClient<TDef>;\n\n public get<TDef extends InterfaceDefinition<any>>(\n ifaceOrTarget: TDef | BareInterfaceTarget<TDef>,\n opts?: GetOptions<TOutCtx>,\n ): InterfaceClient<TDef> {\n if (isBareInterfaceTarget(ifaceOrTarget)) {\n if (opts !== undefined) {\n throw new Error('get: bare interface targets do not accept service or call options.');\n }\n return this.getBare(ifaceOrTarget.interface, {\n prefix: ifaceOrTarget.prefix,\n });\n }\n return this._buildClient(ifaceOrTarget, opts ?? {}) as InterfaceClient<TDef>;\n }\n\n /**\n * Get a typed client that emits foreign-protocol bare method names.\n * Unlike {@link get}, these calls carry no LinkRPC interface metadata.\n */\n public getBare<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n opts: BareGetOptions = {},\n ): InterfaceClient<TDef> {\n const prefix = opts.prefix ?? '';\n validateBarePrefix(prefix, 'getBare');\n for (const [name, member] of Object.entries(iface.members)) {\n if (\n member instanceof RequestType\n && (member.clientStreamSchema !== undefined || member.serverStreamSchema !== undefined)\n ) {\n throw new Error(`getBare: streaming method \"${name}\" is not supported on foreign wires.`);\n }\n }\n return this._buildClient(iface, {}, prefix) as InterfaceClient<TDef>;\n }\n\n /** Get a service-scoped handle; all interfaces obtained from it route via `serviceId` (form 3). */\n public service(serviceId: string): ServiceHandle<TInCtx, TOutCtx> {\n return new ServiceHandle<TInCtx, TOutCtx>(this, serviceId);\n }\n\n /** Register handlers for an interface on this connection's server side. */\n public register<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n handlers: InterfaceHandlers<TDef, TInCtx>,\n opts: RegisterOptions = {},\n ): InterfaceRegistration {\n return this._register(iface, handlers, opts, false);\n }\n\n private _register<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n handlers: InterfaceHandlers<TDef, TInCtx>,\n opts: RegisterOptions,\n internalInspection: boolean,\n ): InterfaceRegistration {\n const serviceId = opts.serviceId;\n const key = `${serviceId ?? ''}::${iface.info.id}`;\n if (this._registry.has(key)) {\n throw new Error(\n `Interface \"${iface.info.id}\" already registered${serviceId ? ` under service \"${serviceId}\"` : ''}.`,\n );\n }\n\n let serviceMetadataChanged = false;\n if (opts.serviceDescription !== undefined) {\n if (serviceId === undefined) {\n throw new Error('register: `serviceDescription` requires `serviceId`.');\n }\n const existing = this._serviceDescriptions.get(serviceId);\n if (existing !== undefined && existing !== opts.serviceDescription) {\n throw new Error(\n `register: conflicting descriptions for service \"${serviceId}\".`,\n );\n }\n this._serviceDescriptions.set(serviceId, opts.serviceDescription);\n serviceMetadataChanged = existing === undefined;\n }\n\n if (opts.rootPrincipalSets !== undefined) {\n if (serviceId === undefined) {\n throw new Error('register: `rootPrincipalSets` requires `serviceId`.');\n }\n const existing = this._serviceRootPrincipalSets.get(serviceId);\n if (existing !== undefined && !rootPrincipalSetsEqual(existing, opts.rootPrincipalSets)) {\n throw new Error(\n `register: conflicting rootPrincipalSets for service \"${serviceId}\".`,\n );\n }\n this._serviceRootPrincipalSets.set(serviceId, opts.rootPrincipalSets);\n serviceMetadataChanged ||= existing === undefined;\n }\n\n const entry: RegisteredInterface = {\n iface,\n handlers: handlers as Record<string, (p: any, c: any) => any>,\n serviceId,\n internalInspection,\n };\n this._registry.set(key, entry);\n this._notifyDirectoryWatchers(entry, serviceMetadataChanged);\n\n if (\n !internalInspection\n && serviceId !== undefined\n && this._inspection !== undefined\n && !this._serviceInspectionRegistrations.has(serviceId)\n ) {\n try {\n this._installServiceInspection(serviceId);\n } catch (error) {\n this._registry.delete(key);\n this._notifyDirectoryWatchers(entry);\n throw error;\n }\n }\n\n let disposed = false;\n return {\n dispose: () => {\n if (disposed) return;\n disposed = true;\n if (this._registry.get(key) !== entry) return;\n\n this._registry.delete(key);\n for (const [prefix, binding] of this._bareBindings) {\n if (binding.entry === entry) this._bareBindings.delete(prefix);\n }\n this._notifyDirectoryWatchers(entry);\n if (\n serviceId !== undefined\n && !this._hasBusinessServiceRegistration(serviceId)\n ) {\n this._removeServiceInspection(serviceId);\n this._serviceDescriptions.delete(serviceId);\n this._serviceRootPrincipalSets.delete(serviceId);\n }\n },\n };\n }\n\n /**\n * Declare the preset interface for form-1 (bare-method) dispatch. The\n * interface must already be registered under the root (no serviceId).\n * Surfaced via `hubrpc.defaults::get`.\n */\n public setPreset(iface: InterfaceDefinition<any>): void {\n const key = `::${iface.info.id}`;\n const entry = this._registry.get(key);\n if (!entry) {\n throw new Error(`setPreset: interface \"${iface.info.id}\" is not registered under the root service.`);\n }\n // The preset and an explicit empty-prefix binding intentionally share\n // one slot. Legacy setPreset replacement semantics win deterministically.\n this._bareBindings.set('', { prefix: '', entry });\n }\n\n /**\n * Bind foreign-protocol bare methods to an already registered interface.\n * Matching uses the longest prefix; once selected, a missing member does\n * not fall through to a shorter binding.\n */\n public bindBare(\n iface: InterfaceDefinition<any>,\n opts: { prefix: string; serviceId?: string; },\n ): InterfaceRegistration {\n validateBarePrefix(opts.prefix, 'bindBare');\n const key = `${opts.serviceId ?? ''}::${iface.info.id}`;\n const entry = this._registry.get(key);\n if (!entry) {\n throw new Error(\n `bindBare: interface \"${iface.info.id}\" is not registered`\n + (opts.serviceId === undefined ? ' under the root service.' : ` under service \"${opts.serviceId}\".`),\n );\n }\n if (this._bareBindings.has(opts.prefix)) {\n throw new Error(`bindBare: prefix \"${opts.prefix}\" is already bound.`);\n }\n const binding: BareBinding = { prefix: opts.prefix, entry };\n this._bareBindings.set(opts.prefix, binding);\n let disposed = false;\n return {\n dispose: () => {\n if (disposed) return;\n disposed = true;\n if (this._bareBindings.get(opts.prefix) === binding) {\n this._bareBindings.delete(opts.prefix);\n }\n },\n };\n }\n\n /** Snapshot of every interface currently registered on this connection. */\n public listRegisteredInterfaces(): readonly {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly interfaceHash: string;\n readonly serviceDescription?: string;\n readonly rootPrincipalSets?: readonly RootPrincipalSet[];\n }[] {\n return Array.from(this._registry.values()).map((r) => {\n const sid = r.serviceId ?? '';\n const item: {\n serviceId: string;\n interfaceId: string;\n interfaceHash: string;\n serviceDescription?: string;\n rootPrincipalSets?: readonly RootPrincipalSet[];\n } = {\n serviceId: sid,\n interfaceId: r.iface.info.id,\n interfaceHash: r.iface.schemaHash,\n };\n const desc = sid === '' ? undefined : this._serviceDescriptions.get(sid);\n if (desc !== undefined) item.serviceDescription = desc;\n const sets = sid === '' ? undefined : this._serviceRootPrincipalSets.get(sid);\n if (sets !== undefined) item.rootPrincipalSets = sets;\n return item;\n });\n }\n\n /** Subscribe to coarse local directory changes; listeners must re-list. */\n public onDidChangeDirectory(listener: () => void): () => void {\n this._directoryListeners.add(listener);\n return () => this._directoryListeners.delete(listener);\n }\n\n /**\n * Look up a registered interface definition by id (and optional content\n * hash). Returns `undefined` if no registered interface matches.\n */\n public findRegisteredInterface(\n interfaceId: string,\n hash?: string,\n ): InterfaceDefinition<any> | undefined {\n for (const r of this._registry.values()) {\n if (r.iface.info.id !== interfaceId) continue;\n if (hash !== undefined && r.iface.schemaHash !== hash) continue;\n return r.iface;\n }\n return undefined;\n }\n\n /**\n * Register the three linkrpc reflection interfaces (`defaults`,\n * `directory`, `schemas`), backed by this connection's live registry.\n *\n * By default they live under the root service (form-2 reachable as\n * `hubrpc.directory::list`). Pass `serviceId` to additionally mount\n * them under a specific service — useful for participants that live\n * behind a hub, so callers can reach reflection via form-3\n * `<serviceId>::hubrpc.directory::list`.\n *\n * Idempotent: re-registering the same `(serviceId, interfaceId)` pair\n * is a no-op.\n */\n public enableReflection(opts: { serviceId?: string; } = {}): InterfaceRegistration {\n const key = `${opts.serviceId ?? ''}::${defaultsInterface.info.id}`;\n if (this._registry.has(key)) return { dispose() { } };\n const prefix = `${opts.serviceId ?? ''}::`;\n for (const iface of [directoryInterface, schemasInterface]) {\n if (this._registry.has(`${prefix}${iface.info.id}`)) {\n throw new Error(\n `enableReflection: partial reflection registration for service \"${opts.serviceId ?? ''}\".`,\n );\n }\n }\n\n const regOpts: RegisterOptions = opts.serviceId !== undefined ?\n { serviceId: opts.serviceId } :\n {};\n const registrations: InterfaceRegistration[] = [];\n\n registrations.push(this.register(defaultsInterface, {\n get: () => {\n const binding = this._bareBindings.get('');\n if (!binding) return {};\n return {\n serviceId: binding.entry.serviceId,\n interfaceId: binding.entry.iface.info.id,\n interfaceHash: binding.entry.iface.schemaHash,\n };\n },\n listBindings: () => ({\n bindings: Array.from(this._bareBindings.values())\n .sort((a, b) => a.prefix < b.prefix ? -1 : a.prefix > b.prefix ? 1 : 0)\n .map((binding) => ({\n prefix: binding.prefix,\n serviceId: binding.entry.serviceId,\n interfaceId: binding.entry.iface.info.id,\n interfaceHash: binding.entry.iface.schemaHash,\n })),\n }),\n }, regOpts));\n\n registrations.push(this.register(directoryInterface, {\n list: ({ interfaceId, interfaceIdPrefix, serviceId, serviceIdScopes, cursor, limit }) => {\n const all = this.listRegisteredInterfaces()\n .filter((r) => opts.serviceId === undefined || r.serviceId === opts.serviceId)\n .filter((r) => interfaceId === undefined || r.interfaceId === interfaceId)\n .filter((r) => interfaceIdPrefix === undefined || r.interfaceId.startsWith(interfaceIdPrefix))\n .filter((r) => serviceId === undefined || r.serviceId === serviceId)\n .filter((r) => serviceIdMatchesScopes(r.serviceId, serviceIdScopes));\n const start = cursor === undefined ? 0 : Number.parseInt(cursor, 10) || 0;\n const end = limit === undefined ? all.length : Math.min(all.length, start + limit);\n const page = all.slice(start, end).map((r) => ({\n serviceId: r.serviceId,\n interfaceId: r.interfaceId,\n interfaceHash: r.interfaceHash,\n serviceDescription: r.serviceDescription,\n rootPrincipalSets: r.rootPrincipalSets?.map((set) => set.map((p) => ({ ...p }))),\n }));\n return end < all.length ?\n { items: page, nextCursor: String(end) } :\n { items: page };\n },\n watch: (params, _ctx, stream) => new Promise((resolve) => {\n const watcher: DirectoryWatcher = {\n interfaceId: params.interfaceId,\n interfaceIdPrefix: params.interfaceIdPrefix,\n serviceId: params.serviceId,\n serviceIdScopes: params.serviceIdScopes,\n send: () => stream.send({}),\n };\n this._directoryWatchers.add(watcher);\n const finish = () => {\n this._directoryWatchers.delete(watcher);\n resolve({});\n };\n if (stream.signal.aborted) {\n finish();\n return;\n }\n stream.signal.addEventListener('abort', finish, { once: true });\n }),\n }, regOpts));\n\n registrations.push(this.register(schemasInterface, {\n get: ({ interfaceId, hash }) => {\n const iface = this.findRegisteredInterface(interfaceId, hash);\n if (!iface) {\n throw new RpcError(\n 'Interface not found',\n ErrorCode.methodNotFound,\n { reason: 'unknown-interface', interfaceId, hash },\n );\n }\n return { schema: iface.toSchema() as unknown };\n },\n }, regOpts));\n\n // A service-scoped reflection set is *also* surfaced at the connection\n // root, so a hub that reads this connection's root directory\n // (`H·root → P`) discovers its `<serviceId>::hubrpc.directory` referral\n // without reaching the (capability-gated) service directory. Keyed\n // separately and guarded above, so the recursive root call is a no-op\n // once root reflection exists.\n if (opts.serviceId !== undefined) {\n try {\n this.enableReflection();\n } catch (error) {\n for (const registration of registrations.reverse()) {\n registration.dispose();\n }\n throw error;\n }\n }\n\n let disposed = false;\n return {\n dispose: () => {\n if (disposed) return;\n disposed = true;\n for (const registration of registrations.reverse()) {\n registration.dispose();\n }\n },\n };\n }\n\n private _notifyDirectoryWatchers(\n entry: RegisteredInterface,\n serviceMetadataChanged = false,\n ): void {\n for (const listener of this._directoryListeners) {\n try {\n listener();\n } catch {\n // Directory invalidation observers cannot interrupt registry mutations.\n }\n }\n for (const watcher of this._directoryWatchers) {\n if (watcher.pending) continue;\n const directlyMatches = directoryWatcherMatchesEntry(watcher, entry);\n const metadataMatches = serviceMetadataChanged\n && entry.serviceId !== undefined\n && [...this._registry.values()].some((candidate) =>\n candidate.serviceId === entry.serviceId\n && directoryWatcherMatchesEntry(watcher, candidate));\n if (!directlyMatches && !metadataMatches) continue;\n watcher.pending = true;\n queueMicrotask(() => {\n watcher.pending = false;\n if (this._directoryWatchers.has(watcher)) watcher.send();\n });\n }\n }\n\n /**\n * Enable the root `hubrpc.node::getNodeId` topology-bootstrap service.\n *\n * The generated ids are stable while this registration is active. They are\n * unauthenticated correlation labels only; callers must not use them for\n * identity, capability, or authorization decisions.\n */\n public enableInspection(\n descriptors?: readonly ParticipantDescriptorSource[],\n ): InspectionRegistration {\n if (this._inspection !== undefined) return this._inspection;\n\n const info: NodeInfo = {\n nodeId: this._generateTopologyId('node'),\n portId: this._generateTopologyId('port'),\n ...(descriptors !== undefined ? { descriptors: [...descriptors] } : {}),\n };\n const registration = this._register(nodeInterface, {\n getNodeId: () => info,\n }, {}, true);\n\n const trafficInspector = new EndpointTrafficInspector(\n info.nodeId,\n info.portId,\n (active) => this._wireChannel?.setWireMessageObserver(\n active ? trafficInspector.observe : undefined,\n ),\n );\n this._trafficInspector = trafficInspector;\n trafficInspector.start();\n\n let disposed = false;\n const result: InspectionRegistration = {\n ...info,\n observeTraffic: (observer) => trafficInspector.observeTransits(observer),\n dispose: () => {\n if (disposed) return;\n disposed = true;\n for (const serviceId of [...this._serviceInspectionRegistrations.keys()]) {\n this._removeServiceInspection(serviceId);\n }\n trafficInspector.dispose();\n if (this._trafficInspector === trafficInspector) {\n this._trafficInspector = undefined;\n }\n registration.dispose();\n if (this._inspection === result) {\n this._inspection = undefined;\n }\n },\n };\n this._inspection = result;\n try {\n const services = new Set(\n Array.from(this._registry.values())\n .filter((entry) =>\n entry.serviceId !== undefined && !entry.internalInspection)\n .map((entry) => entry.serviceId!),\n );\n for (const serviceId of services) this._installServiceInspection(serviceId);\n } catch (error) {\n result.dispose();\n throw error;\n }\n return result;\n }\n\n /** Number of active endpoint traffic stream subscribers. */\n public get trafficObserverCount(): number {\n return this._trafficInspector?.observerCount ?? 0;\n }\n\n public close(): void {\n this.channel.close();\n }\n\n // ---- client side ----\n\n private _buildClient(\n iface: InterfaceDefinition<any>,\n opts: GetOptions<TOutCtx>,\n barePrefix?: string,\n ): Record<string, (params: any) => any> {\n const { serviceId, ...ctxRest } = opts;\n const sendOpts = barePrefix === undefined\n ? { ctx: ctxRest as unknown as TOutCtx, interfaceHash: iface.schemaHash }\n : undefined;\n const prefix = barePrefix ?? (serviceId ? `${serviceId}::${iface.info.id}::` : `${iface.info.id}::`);\n const proxy: Record<string, (p: any) => any> = {};\n for (const [name, member] of Object.entries(iface.members) as [string, MemberType][]) {\n const wireMethod = `${prefix}${name}`;\n\n if (member.kind === 'request') {\n const hasStream = member.clientStreamSchema !== undefined ||\n member.serverStreamSchema !== undefined;\n\n if (hasStream) {\n // Streaming-enabled call. Returns a Promise<R> augmented\n // with `send`. `requestId` resolves once the request has\n // been allocated by the channel; `send` defers until\n // then so callers can emit client-stream messages\n // synchronously after the call returns.\n const serverStreamSchema = member.serverStreamSchema;\n proxy[name] = (\n params: unknown,\n callOpts?: { onMessage?: (m: unknown) => void; },\n ) => {\n const userListener = callOpts?.onMessage;\n // Symmetric with the server-side handler: parse\n // inbound stream payloads against the declared\n // schema and drop anything that doesn't match.\n // The handler always sees validated data.\n const onStreamMessage = userListener !== undefined ?\n (raw: JsonValue) => {\n if (serverStreamSchema !== undefined) {\n const r = safeParse(serverStreamSchema, raw);\n if (!r.success) return;\n userListener(r.data);\n return;\n }\n userListener(raw);\n } :\n undefined;\n\n const channelOpts: StreamSendOpts<TOutCtx> | undefined = onStreamMessage !== undefined ?\n { ...sendOpts, onStreamMessage } :\n sendOpts;\n this._validateOutboundParamsFor(member, wireMethod, params);\n const call = this.channel.sendRequestWithStream(\n wireMethod,\n params as JsonValue | undefined,\n channelOpts,\n );\n const result = call.result.then((raw) =>\n validateWireResult(member.resultSchema, raw, wireMethod));\n\n return Object.assign(result, {\n send: async (payload: unknown) => call.send(payload as JsonValue),\n cancel: async (reason?: string) => call.cancel(reason),\n dispose: (reason?: string) => call.dispose?.(reason),\n ping: () => call.ping(),\n });\n };\n } else {\n proxy[name] = async (params: unknown) => {\n this._validateOutboundParamsFor(member, wireMethod, params);\n const raw = await this.channel.sendRequest(\n wireMethod,\n params as JsonValue | undefined,\n sendOpts,\n );\n return validateWireResult(member.resultSchema, raw, wireMethod);\n };\n }\n } else {\n const notify = (params: unknown) => {\n this._validateOutboundParamsFor(member, wireMethod, params);\n void this.channel.sendNotification(\n wireMethod,\n params as JsonValue | undefined,\n sendOpts,\n );\n };\n // Preserve native notifications' async rejection and bare\n // notifications' synchronous validation errors.\n proxy[name] = barePrefix === undefined ? async (params: unknown) => notify(params) : notify;\n }\n }\n return proxy;\n }\n\n private _validateOutboundParamsFor(\n member: MemberType,\n wireMethod: string,\n params: unknown,\n ): void {\n if (!this._validateOutboundParams) return;\n validateValue(\n member.paramsSchema,\n params,\n `Invalid params for ${wireMethod}`,\n ErrorCode.invalidParams,\n );\n }\n\n // ---- server side ----\n\n private async _handleRequest(call: IncomingCall<TInCtx>): Promise<Result> {\n const parsed = this._parseRouted(call.method);\n if (!parsed.ok) return notFound(parsed.reason, call.method);\n\n const { entry, memberName } = parsed;\n const member = entry.iface.members[memberName];\n if (!member) return notFound('unknown-method', call.method);\n\n const handler = entry.handlers[memberName] as\n | ((params: unknown, ctx: TInCtx, stream: StreamApi<unknown, unknown>) => unknown)\n | undefined;\n if (!handler) return notFound('unknown-method', call.method);\n\n // Keep call.params intact for chained-hub verification and transport\n // middleware; only the terminal application-schema view is stripped.\n const userParams = stripLinkRpcWireMeta(call.params);\n const parsedParams = safeParse((member as MemberType).paramsSchema, userParams);\n if (!parsedParams.success) {\n return {\n error: {\n code: ErrorCode.invalidParams,\n message: 'Invalid params',\n data: { issues: parsedParams.error.issues as unknown as JsonValue },\n },\n };\n }\n\n if (!(member instanceof RequestType)) {\n // Caller used request semantics on a notification-only method.\n return notFound('unknown-method', call.method);\n }\n\n const stream = this._buildStreamApi(call.stream, call.signal, member);\n try {\n const pendingResult = handler(parsedParams.data, call.context, stream);\n const result = await pendingResult;\n validateValue(\n member.resultSchema,\n result,\n `Invalid result for ${call.method}`,\n ErrorCode.internalError,\n );\n return { result: result === undefined ? null : (result as JsonValue) };\n } catch (e) {\n if (e instanceof RpcError) {\n return { error: { code: e.code, message: e.message, data: e.data } };\n }\n return {\n error: {\n code: ErrorCode.internalError,\n message: e instanceof Error ? e.message : String(e),\n },\n };\n }\n // Inbound stream listener is auto-detached by JsonRpcChannel when\n // the handler's response settles — no manual unregister needed.\n }\n\n private _buildStreamApi(\n callStream: IncomingStream,\n signal: AbortSignal,\n member: RequestType<unknown, unknown, unknown, unknown, unknown>,\n ): StreamApi<unknown, unknown> {\n return {\n send: (payload: unknown) => {\n if (member.serverStreamSchema) {\n const r = safeParse(member.serverStreamSchema, payload);\n if (!r.success) {\n throw new Error(\n `Server stream payload failed schema validation: ${r.error.message}`,\n );\n }\n }\n return callStream.send(payload as JsonValue);\n },\n onMessage: (listener: (payload: unknown) => void) => {\n callStream.onMessage((raw) => {\n if (member.clientStreamSchema) {\n const r = safeParse(member.clientStreamSchema, raw);\n if (!r.success) return; // drop invalid client stream payload\n listener(r.data);\n return;\n }\n // No declared client stream schema => the method does\n // not accept client-emitted stream messages. Drop.\n });\n },\n ping: () => callStream.ping(),\n signal,\n };\n }\n\n private _handleNotification(call: IncomingCall<TInCtx>): void {\n const parsed = this._parseRouted(call.method);\n if (!parsed.ok) return;\n const { entry, memberName } = parsed;\n const member = entry.iface.members[memberName];\n if (!(member instanceof NotificationType)) return;\n const handler = entry.handlers[memberName] as\n | ((params: unknown, ctx: TInCtx) => unknown)\n | undefined;\n if (!handler) return;\n\n const userParams = stripLinkRpcWireMeta(call.params);\n const parsedParams = safeParse(member.paramsSchema, userParams);\n if (!parsedParams.success) return;\n void handler(parsedParams.data, call.context);\n }\n\n private _parseRouted(method: string):\n | { ok: true; entry: RegisteredInterface; memberName: string; }\n | { ok: false; reason: string; } {\n const parsed = parseMethodName(method);\n if (!parsed) return { ok: false, reason: 'bad-method-grammar' };\n\n if (parsed.kind === 'bare') {\n let selected: BareBinding | undefined;\n for (const binding of this._bareBindings.values()) {\n if (\n parsed.member.startsWith(binding.prefix)\n && (selected === undefined || binding.prefix.length > selected.prefix.length)\n ) {\n selected = binding;\n }\n }\n if (!selected) return { ok: false, reason: 'no-preset' };\n return {\n ok: true,\n entry: selected.entry,\n memberName: parsed.member.slice(selected.prefix.length),\n };\n }\n\n const serviceId = parsed.kind === 'full' ? parsed.serviceId : undefined;\n const key = `${serviceId ?? ''}::${parsed.interfaceId}`;\n const entry = this._registry.get(key);\n if (!entry) {\n return {\n ok: false,\n reason: serviceId ? 'unknown-service' : 'unknown-interface',\n };\n }\n return { ok: true, entry, memberName: parsed.member };\n }\n\n private _installServiceInspection(serviceId: string): void {\n if (this._serviceInspectionRegistrations.has(serviceId)) return;\n const info = this._inspection;\n const trafficInspector = this._trafficInspector;\n if (info === undefined || trafficInspector === undefined) return;\n\n const registrations: InterfaceRegistration[] = [];\n const opts = { serviceId };\n try {\n registrations.push(this._register(nodeInterface, {\n getNodeId: () => ({ nodeId: info.nodeId, portId: info.portId }),\n }, opts, true));\n registrations.push(this._register(topologyInterface, {\n getGraph: () => this._endpointGraph(serviceId, info),\n watchGraph: async (_params, _ctx, stream) => {\n await waitForAbort(stream.signal);\n return {};\n },\n }, opts, true));\n registrations.push(this._register(trafficInterface, {\n watch: ({ methodPrefix, trafficIgnoreKey, focusRequest }, _ctx, stream) =>\n this._watchTraffic(\n trafficInspector,\n { methodPrefix, trafficIgnoreKey, focusRequest },\n stream,\n ),\n watchWithPayloads: ({\n methodPrefix,\n maxPayloadBytes,\n trafficIgnoreKey,\n focusRequest,\n }, _ctx, stream) =>\n this._watchTraffic(\n trafficInspector,\n {\n methodPrefix,\n maxPayloadBytes,\n trafficIgnoreKey,\n focusRequest,\n },\n stream,\n ),\n }, opts, true));\n } catch (error) {\n for (const registration of registrations.reverse()) registration.dispose();\n throw error;\n }\n this._serviceInspectionRegistrations.set(serviceId, registrations);\n }\n\n private _removeServiceInspection(serviceId: string): void {\n const registrations = this._serviceInspectionRegistrations.get(serviceId);\n if (registrations === undefined) return;\n this._serviceInspectionRegistrations.delete(serviceId);\n for (const registration of registrations.reverse()) registration.dispose();\n }\n\n private _hasBusinessServiceRegistration(serviceId: string): boolean {\n return Array.from(this._registry.values()).some((entry) =>\n entry.serviceId === serviceId && !entry.internalInspection);\n }\n\n private _endpointGraph(serviceId: string, info: NodeInfo): TopologyGraph {\n return {\n observerServiceId: serviceId,\n entryNodeId: info.nodeId,\n nodes: [{\n nodeId: info.nodeId,\n kind: 'endpoint',\n ...(info.descriptors !== undefined ? { descriptors: info.descriptors } : {}),\n ports: [{ portId: info.portId }],\n }],\n links: [],\n routes: [{\n serviceId,\n nodeId: info.nodeId,\n portId: info.portId,\n match: 'exact',\n }],\n };\n }\n\n private async _watchTraffic<TClient>(\n inspector: EndpointTrafficInspector,\n options: EndpointTrafficWatchOptions,\n stream: StreamApi<TClient, TrafficEvent>,\n ): Promise<TrafficWatchResult> {\n const subscription = inspector.subscribe(options, (event) => stream.send(event));\n const dispose = () => subscription.dispose();\n if (stream.signal.aborted) {\n dispose();\n } else {\n stream.signal.addEventListener('abort', dispose, { once: true });\n }\n try {\n return await subscription.closed;\n } finally {\n stream.signal.removeEventListener('abort', dispose);\n subscription.dispose();\n }\n }\n}\n\n\n/**\n * Options when obtaining a typed client for an interface.\n *\n * - `serviceId`: route to a specific service (form 3). Omit for form 2\n * (implicit / root service on the connection).\n * - any `TOutCtx` property: a per-client default merged into the `ctx`\n * of every call issued through the returned proxy (e.g.\n * `signerOverride`, `capsOverride` for a signing channel). The\n * connection forwards these verbatim; it does not interpret them.\n *\n * Schema-version pinning travels as interface-level call metadata\n * ({@link SendOpts.interfaceHash}); the typed proxy stamps\n * `iface.schemaHash` automatically, independent of `TOutCtx`.\n */\nexport type GetOptions<TOutCtx = undefined> = {\n serviceId?: string;\n} & Partial<TOutCtx>;\n\n/** Options for a metadata-free, bare-method typed client. */\nexport interface BareGetOptions {\n prefix?: string;\n}\n\nexport interface RegisterOptions {\n /**\n * If set, this interface is mounted under this service id (form 3).\n */\n serviceId?: string;\n /**\n * Optional human description recorded for `serviceId` and surfaced\n * through `hubrpc.directory::list`. Requires `serviceId`. The first\n * registration's description wins; any later registration that\n * supplies a *different* non-undefined description throws.\n */\n serviceDescription?: string;\n /**\n * Root node ids required to access `serviceId`, in CNF (AND of OR-sets):\n * the caller must satisfy **every** set, and a set is satisfied by **any\n * one** of its node ids. Surfaced through `hubrpc.directory::list`.\n * Requires `serviceId`. Recorded per service; a later registration that\n * supplies a *different* value for the same `serviceId` throws.\n */\n rootPrincipalSets?: readonly RootPrincipalSet[];\n}\n\n/** A live interface registration. Disposing it removes dispatch and reflection state. */\nexport interface InterfaceRegistration {\n /** Remove this exact registration. Idempotent. */\n dispose(): void;\n}\n\n/** Generated topology identity and its live root-interface registration. */\nexport interface InspectionRegistration extends InterfaceRegistration, NodeInfo {\n /**\n * Observe this endpoint's full-payload traffic in-process. Wire observation\n * remains disabled until either this or an RPC traffic watch is active.\n */\n observeTraffic(observer: (transit: TrafficTransitEvent) => void): InterfaceRegistration;\n}\n\nfunction createInspectionId(kind: 'node' | 'port'): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return `${kind}:${bytesToBase64Url(bytes)}`;\n}\n\n/** Structural equality for two CNF root-node-id requirement collections. */\nfunction rootPrincipalSetsEqual(\n a: readonly RootPrincipalSet[],\n b: readonly RootPrincipalSet[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const sa = a[i];\n const sb = b[i];\n if (sa.length !== sb.length) return false;\n for (let j = 0; j < sa.length; j++) {\n if (sa[j].principal !== sb[j].principal) return false;\n if ((sa[j].transitive === true) !== (sb[j].transitive === true)) return false;\n }\n }\n return true;\n}\n\ninterface RegisteredInterface {\n iface: InterfaceDefinition<any>;\n handlers: Record<string, (params: any, ctx: any) => any>;\n serviceId: string | undefined;\n internalInspection: boolean;\n}\n\ninterface DirectoryWatcher {\n readonly interfaceId: string | undefined;\n readonly interfaceIdPrefix: string | undefined;\n readonly serviceId: string | undefined;\n readonly serviceIdScopes: readonly ServiceIdPattern[] | undefined;\n readonly send: () => void;\n pending?: boolean;\n}\n\nfunction directoryWatcherMatchesEntry(\n watcher: DirectoryWatcher,\n entry: RegisteredInterface,\n): boolean {\n const serviceId = entry.serviceId ?? '';\n return (watcher.interfaceId === undefined || watcher.interfaceId === entry.iface.info.id)\n && (watcher.interfaceIdPrefix === undefined\n || entry.iface.info.id.startsWith(watcher.interfaceIdPrefix))\n && (watcher.serviceId === undefined || watcher.serviceId === serviceId)\n && serviceIdMatchesScopes(serviceId, watcher.serviceIdScopes);\n}\n\ninterface BareBinding {\n readonly prefix: string;\n readonly entry: RegisteredInterface;\n}\n\nfunction validateWireResult(schema: Schema, raw: JsonValue, wireMethod: string): JsonValue | undefined {\n const value = normalizeWireResult(schema, raw);\n validateValue(schema, value, `Invalid result for ${wireMethod}`, ErrorCode.internalError);\n return value;\n}\n\n/** Validate at both ends without stripping extra keys or applying schema transforms. */\nfunction validateValue(schema: Schema, value: unknown, message: string, code: number): void {\n const checked = safeParse(schema, value);\n if (!checked.success) {\n throw new RpcError(\n message,\n code,\n { issues: checked.error.issues as unknown as JsonValue },\n );\n }\n}\n\n/** Undo the server's undefined → null convention only when the schema rejects null. */\nfunction normalizeWireResult(schema: Schema, raw: JsonValue): JsonValue | undefined {\n if (raw !== null) return raw;\n if (safeParse(schema, null).success) return null;\n if (safeParse(schema, undefined).success) return undefined;\n return null;\n}\n\n\n/** Service-scoped handle returned by `connection.service(id)`. */\nexport class ServiceHandle<TInCtx = undefined, TOutCtx = undefined> {\n constructor(\n private readonly _connection: LinkRpcConnection<TInCtx, TOutCtx>,\n private readonly _serviceId: string,\n ) { }\n\n public get<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n opts: Partial<TOutCtx> = {},\n ): InterfaceClient<TDef> {\n return this._connection.get(iface, { ...opts, serviceId: this._serviceId } as GetOptions<TOutCtx>);\n }\n\n public register<TDef extends InterfaceDefinition<any>>(\n iface: TDef,\n handlers: InterfaceHandlers<TDef, TInCtx>,\n opts: Omit<RegisterOptions, 'serviceId'> = {},\n ): InterfaceRegistration {\n return this._connection.register(iface, handlers, { ...opts, serviceId: this._serviceId });\n }\n}\n\nfunction notFound(reason: string, method: string): Result {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Method not found: ${method}`,\n data: { reason, method },\n },\n };\n}\n\nfunction isInspectionInterface(iface: InterfaceDefinition<any>): boolean {\n return iface === nodeInterface\n || iface === topologyInterface\n || iface === trafficInterface;\n}\n\nfunction waitForAbort(signal: AbortSignal): Promise<void> {\n if (signal.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n signal.addEventListener('abort', () => resolve(), { once: true });\n });\n}\n","import type { Channel } from './channel';\nimport type { IDisposable } from '../disposable';\n\n/**\n * A raw channel that signals when it closes (and, when possible, can be torn\n * down). Both {@link openHubChannel}'s `HubChannel` and `openStdioChannel`'s\n * `StdioChannel` satisfy this shape.\n */\nexport type ConnectableChannel = Channel<undefined, unknown> & {\n /**\n * Fires once when the channel closes. Returns a disposable to unsubscribe.\n *\n * Ordering contract: when a close causes a sending method (e.g. a request\n * or notification) to reject/throw, {@link onClose} must fire *before* that\n * rejection surfaces to the caller. This lets consumers reliably tell a\n * close-induced failure (the channel is already observably closed) apart\n * from a genuine error (the channel is still open). See\n * {@link ChannelConnector.keepConnected}.\n */\n onClose(listener: () => void): IDisposable;\n /** Tear the channel down. Optional — stdio channels have no explicit close. */\n close?(): void;\n};\n\n/** Handle returned by {@link ChannelConnector.keepConnected}. */\nexport interface KeepConnectedHandle {\n /**\n * Resolves when the loop exits: the channel closed and the connector does\n * not redial, or {@link stop} (or the supplied signal) fired.\n */\n readonly done: Promise<void>;\n /** Stop redialing and close the current channel (if any). */\n stop(): void;\n}\n\n/** Callback run on every (re)connect. The channel is the raw, unsigned channel. */\nexport type OnChannelConnect<T extends ConnectableChannel> = (\n ctx: { channel: T; },\n) => void | Promise<void>;\n\nexport interface ExpBackoffOptions {\n readonly initialBackoffMs?: number;\n readonly maxBackoffMs?: number;\n}\n\nconst DEFAULT_INITIAL_BACKOFF_MS = 250;\nconst DEFAULT_MAX_BACKOFF_MS = 60_000;\n\n/**\n * Drives a connect / (re)connect loop over a raw {@link ConnectableChannel}.\n *\n * Unlike connection-level helpers, this works at the channel layer: the\n * caller composes identity / signing on top of the channel handed to\n * {@link keepConnected} (e.g. `SigningSender.wrapChannel(channel, { principal })`).\n *\n * Construct via {@link ChannelConnector.once} (a single, already-open channel\n * that never redials) or {@link ChannelConnector.expBackoff} (re-open via a\n * factory with exponential backoff after each close).\n */\nexport class ChannelConnector<T extends ConnectableChannel> {\n private constructor(\n private readonly _open: () => Promise<T>,\n private readonly _redial: boolean,\n private readonly _initialBackoffMs: number,\n private readonly _maxBackoffMs: number,\n ) { }\n\n /**\n * A connector over a single channel (or a promise of one). Never redials;\n * the loop ends when the channel closes or {@link KeepConnectedHandle.stop}\n * fires.\n */\n public static once<T extends ConnectableChannel>(channel: T | Promise<T>): ChannelConnector<T> {\n return new ChannelConnector<T>(\n async () => channel,\n false,\n DEFAULT_INITIAL_BACKOFF_MS,\n DEFAULT_MAX_BACKOFF_MS,\n );\n }\n\n /**\n * A redialing connector: `open` is called once per attempt, and the loop\n * reconnects with exponential backoff after each close (or failed open).\n */\n public static expBackoff<T extends ConnectableChannel>(\n open: () => Promise<T>,\n opts: ExpBackoffOptions = {},\n ): ChannelConnector<T> {\n return new ChannelConnector<T>(\n open,\n true,\n opts.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS,\n opts.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS,\n );\n }\n\n /**\n * Run `onConnect` on every (re)connect with the freshly opened channel.\n * The callback typically wraps the channel with signing and registers\n * handlers. Returns once the loop exits (see {@link KeepConnectedHandle}).\n */\n public keepConnected(\n onConnect: OnChannelConnect<T>,\n opts: { signal?: AbortSignal; } = {},\n ): KeepConnectedHandle {\n let stopped = false;\n let current: T | undefined;\n\n const stop = (): void => {\n if (stopped) {\n return;\n }\n stopped = true;\n const c = current;\n current = undefined;\n c?.close?.();\n };\n\n if (opts.signal) {\n if (opts.signal.aborted) {\n stopped = true;\n } else {\n opts.signal.addEventListener('abort', stop, { once: true });\n }\n }\n\n const done = (async () => {\n let backoff = this._initialBackoffMs;\n while (!stopped) {\n let channel: T;\n try {\n channel = await this._open();\n } catch (e) {\n if (stopped || !this._redial) {\n throw e;\n }\n await _delay(backoff, opts.signal);\n backoff = Math.min(backoff * 2, this._maxBackoffMs);\n continue;\n }\n\n if (stopped) {\n channel.close?.();\n return;\n }\n\n current = channel;\n let isClosed = false;\n const closed = new Promise<void>((resolve) => {\n channel.onClose(() => {\n isClosed = true;\n resolve();\n });\n });\n\n try {\n await onConnect({ channel });\n backoff = this._initialBackoffMs;\n } catch (e) {\n // Per the onClose ordering contract, a close-induced failure\n // fires onClose before the sending method throws, so the\n // channel is already observably closed here. In that case the\n // error is just the close surfacing, and we fall through to\n // redial. Otherwise it's a genuine error: tear down and\n // rethrow rather than swallow it.\n if (!isClosed) {\n channel.close?.();\n throw e;\n }\n if (current === channel) {\n current = undefined;\n }\n if (stopped || !this._redial) {\n return;\n }\n await _delay(backoff, opts.signal);\n backoff = Math.min(backoff * 2, this._maxBackoffMs);\n continue;\n }\n\n await closed;\n if (current === channel) {\n current = undefined;\n }\n if (stopped || !this._redial) {\n return;\n }\n }\n })();\n\n return { done, stop };\n }\n}\n\nfunction _delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/**\n * A strict, RFC-3986 URI vocabulary for \"where the linkrpc server lives, and\n * how to reach (or start) it\". Every endpoint round-trips through\n * {@link parseEndpointUri} / {@link formatEndpointUri} and is a valid `new URL()`\n * — safe to put in env vars, logs, and config.\n *\n * Supported schemes:\n * - `unix:/path/to.sock?token=…` → {@link SocketEndpoint}\n * - `npipe://./pipe/name?token=…` → {@link SocketEndpoint} (Windows)\n * - `ws://host:port?token=…` / `wss:…` → {@link WsEndpoint} (LinkRPC handshake)\n * - `ws-no-init://host:port?…` → {@link WsNoInitEndpoint}\n * - `cmd-stdio:?command=…` / `…?argv=…` → {@link CmdStdioEndpoint}\n * - `cmd:?command=…` / `…?argv=…` → {@link CmdEnvEndpoint}\n *\n * The command payload is `{ command: string } | { argv: string[] }`:\n * - `?command=node%20server.js` — one verbatim string, split by the OS shell.\n * - `?argv=node&argv=server.js` — repeated `argv` params, structure-preserving.\n *\n * A bare string with no scheme (legacy `LINKRPC_ENDPOINT`) is auto-detected: a\n * `ws://`/`wss://` URL stays WebSocket, anything else is a socket path.\n */\n\n/** Verbatim command line (`{ command }`) or pre-split argv (`{ argv }`). */\nexport type EndpointCommand =\n | { readonly command: string }\n | { readonly argv: readonly string[] };\n\n/** Named pipe / unix-domain-socket the server already listens on. */\nexport interface SocketEndpoint {\n readonly kind: 'socket';\n readonly path: string;\n readonly token?: string;\n /**\n * Present on sockets created by `hub connect`. Local framing still uses the\n * LinkRPC transport handshake; this describes whether forwarded application\n * calls target a LinkRPC or plain JSON-RPC peer.\n */\n readonly brokerMode?: 'linkrpc' | 'raw';\n}\n\n/** A running WebSocket hub; `token` rides in the `hubrpc::initialize` handshake. */\nexport interface WsEndpoint {\n readonly kind: 'ws';\n readonly url: string;\n readonly token?: string;\n}\n\n/**\n * A running plain-JSON-RPC WebSocket endpoint. Unlike {@link WsEndpoint}, CLI\n * consumers use it without the `hubrpc::initialize` handshake or LinkRPC signing.\n * Query parameters are preserved verbatim for protocols that authenticate\n * during the WebSocket upgrade (for example AHP's `tkn` parameter).\n */\nexport interface WsNoInitEndpoint {\n readonly kind: 'ws-no-init';\n /** Actual `ws://` URL passed to the WebSocket constructor. */\n readonly url: string;\n}\n\n/** Spawn a child and talk linkrpc over its stdin/stdout. */\nexport interface CmdStdioEndpoint {\n readonly kind: 'cmd-stdio';\n readonly command: EndpointCommand;\n /** Extra environment variables injected into the spawned child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Working directory for the spawned child. */\n readonly cwd?: string;\n}\n\n/**\n * Spawn a child against a freshly-started *local hub*: the parent listens on a\n * private socket, hands the child its address + token via `LINKRPC_ENDPOINT` /\n * `LINKRPC_TOKEN`, and the child dials in as a hub participant (registering its\n * services), exactly as it would against a remote hub.\n */\nexport interface CmdEnvEndpoint {\n readonly kind: 'cmd-env';\n readonly command: EndpointCommand;\n /**\n * When set, the local hub provisions (or reuses) a *persistent* managed\n * identity under this slot id, so the child's HPKE wrap/unwrap keys survive\n * across runs (sealed archives re-open).\n */\n readonly provisionSlot?: string;\n /** Extra environment variables injected into the spawned child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Working directory for the spawned child. */\n readonly cwd?: string;\n}\n\nexport type ResolvedEndpoint =\n | SocketEndpoint\n | WsEndpoint\n | WsNoInitEndpoint\n | CmdStdioEndpoint\n | CmdEnvEndpoint;\n\nconst TOKEN_PARAM = 'token';\nconst BROKER_PARAM = 'broker';\nconst COMMAND_PARAM = 'command';\nconst ARGV_PARAM = 'argv';\nconst PROVISION_SLOT_PARAM = 'provisionSlot';\nconst ENV_PARAM = 'env';\nconst CWD_PARAM = 'cwd';\n\nfunction _tryParseUrl(uri: string): URL | undefined {\n try {\n return new URL(uri);\n } catch {\n return undefined;\n }\n}\n\nfunction _looksLikeWsUrl(uri: string): boolean {\n return /^wss?:\\/\\//i.test(uri);\n}\n\n/** True for a Windows named-pipe path (`\\\\.\\pipe\\…` or `\\\\?\\pipe\\…`). */\nfunction _isWindowsPipePath(path: string): boolean {\n return /^\\\\\\\\[.?]\\\\pipe\\\\/i.test(path);\n}\n\nfunction _parseCommand(url: URL): EndpointCommand {\n const argv = url.searchParams.getAll(ARGV_PARAM);\n if (argv.length > 0) {\n return { argv };\n }\n const command = url.searchParams.get(COMMAND_PARAM);\n if (command !== null) {\n return { command };\n }\n throw new Error(\n `endpoint '${url.protocol}' requires a '${COMMAND_PARAM}' or '${ARGV_PARAM}' query parameter`,\n );\n}\n\n/** Parse repeated `env=KEY=VALUE` params into a record (first `=` splits). */\nfunction _parseEnv(url: URL): Readonly<Record<string, string>> | undefined {\n const entries = url.searchParams.getAll(ENV_PARAM);\n if (entries.length === 0) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const entry of entries) {\n const eq = entry.indexOf('=');\n if (eq === -1) {\n throw new Error(`endpoint '${ENV_PARAM}' param must be 'KEY=VALUE', got '${entry}'`);\n }\n env[entry.slice(0, eq)] = entry.slice(eq + 1);\n }\n return env;\n}\n\n/**\n * Parse a strict endpoint URI into an {@link ResolvedEndpoint}. Throws on an\n * unknown scheme or a malformed command endpoint. A bare (scheme-less) string\n * is auto-detected as `ws`/`wss` URL or a socket path.\n */\nexport function parseEndpointUri(uri: string): ResolvedEndpoint {\n const trimmed = uri.trim();\n if (trimmed === '') {\n throw new Error('endpoint URI is empty');\n }\n\n const url = _tryParseUrl(trimmed);\n if (!url) {\n // Bare form (no scheme): legacy LINKRPC_ENDPOINT.\n if (_looksLikeWsUrl(trimmed)) {\n return { kind: 'ws', url: trimmed };\n }\n return { kind: 'socket', path: trimmed };\n }\n\n switch (url.protocol) {\n case 'ws:':\n case 'wss:': {\n const token = url.searchParams.get(TOKEN_PARAM) ?? undefined;\n // The token travels in the LinkRPC initialize handshake, never the URL.\n url.searchParams.delete(TOKEN_PARAM);\n const cleanUrl = url.toString();\n return token !== undefined ?\n { kind: 'ws', url: cleanUrl, token } :\n { kind: 'ws', url: cleanUrl };\n }\n case 'ws-no-init:': {\n const wsUrl = new URL(trimmed.replace(/^ws-no-init:/i, 'ws:')).toString();\n return { kind: 'ws-no-init', url: wsUrl };\n }\n case 'unix:': {\n const token = url.searchParams.get(TOKEN_PARAM) ?? undefined;\n const brokerMode = _parseBrokerMode(url);\n const path = decodeURIComponent(url.pathname);\n return {\n kind: 'socket',\n path,\n ...(token !== undefined ? { token } : {}),\n ...(brokerMode !== undefined ? { brokerMode } : {}),\n };\n }\n case 'npipe:': {\n const token = url.searchParams.get(TOKEN_PARAM) ?? undefined;\n const brokerMode = _parseBrokerMode(url);\n // `npipe://./pipe/foo` → `\\\\.\\pipe\\foo`.\n const host = url.host === '' ? '.' : url.host;\n const tail = decodeURIComponent(url.pathname).replace(/\\//g, '\\\\');\n const path = `\\\\\\\\${host}${tail}`;\n return {\n kind: 'socket',\n path,\n ...(token !== undefined ? { token } : {}),\n ...(brokerMode !== undefined ? { brokerMode } : {}),\n };\n }\n case 'cmd-stdio:': {\n const env = _parseEnv(url);\n const cwd = url.searchParams.get(CWD_PARAM) ?? undefined;\n return {\n kind: 'cmd-stdio',\n command: _parseCommand(url),\n ...(env !== undefined ? { env } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n };\n }\n case 'cmd:': {\n const command = _parseCommand(url);\n const provisionSlot = url.searchParams.get(PROVISION_SLOT_PARAM) ?? undefined;\n const env = _parseEnv(url);\n const cwd = url.searchParams.get(CWD_PARAM) ?? undefined;\n return {\n kind: 'cmd-env',\n command,\n ...(provisionSlot !== undefined ? { provisionSlot } : {}),\n ...(env !== undefined ? { env } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n };\n }\n default:\n throw new Error(\n `unsupported endpoint scheme '${url.protocol}' `\n + `(expected unix:, npipe:, ws:, wss:, ws-no-init:, cmd:, or cmd-stdio:)`,\n );\n }\n}\n\nexport interface FormatEndpointOptions {\n /** Emit the real token instead of redacting it. Default: redact. */\n readonly revealToken?: boolean;\n}\n\nconst REDACTED = '***';\n\nfunction _appendToken(params: URLSearchParams, token: string | undefined, reveal: boolean): void {\n if (token === undefined) return;\n params.set(TOKEN_PARAM, reveal ? token : REDACTED);\n}\n\nfunction _parseBrokerMode(url: URL): SocketEndpoint['brokerMode'] {\n const value = url.searchParams.get(BROKER_PARAM);\n if (value === null) return undefined;\n if (value === 'linkrpc' || value === 'raw') return value;\n throw new Error(`endpoint '${BROKER_PARAM}' param must be 'linkrpc' or 'raw', got '${value}'`);\n}\n\nfunction _appendCommand(params: URLSearchParams, command: EndpointCommand): void {\n if ('argv' in command) {\n for (const a of command.argv) params.append(ARGV_PARAM, a);\n } else {\n params.set(COMMAND_PARAM, command.command);\n }\n}\n\nfunction _appendEnv(params: URLSearchParams, env: Readonly<Record<string, string>> | undefined): void {\n if (env === undefined) return;\n for (const [key, value] of Object.entries(env)) {\n params.append(ENV_PARAM, `${key}=${value}`);\n }\n}\n\n/**\n * Render an {@link ResolvedEndpoint} back to a canonical strict URI. The token is\n * redacted (`***`) unless `revealToken` is set, so the result is paste-safe for\n * logs. Round-trips with {@link parseEndpointUri} when `revealToken` is true.\n */\nexport function formatEndpointUri(spec: ResolvedEndpoint, options?: FormatEndpointOptions): string {\n const reveal = options?.revealToken === true;\n switch (spec.kind) {\n case 'socket': {\n const params = new URLSearchParams();\n _appendToken(params, spec.token, reveal);\n if (spec.brokerMode !== undefined) params.set(BROKER_PARAM, spec.brokerMode);\n const query = params.toString();\n const suffix = query === '' ? '' : `?${query}`;\n if (_isWindowsPipePath(spec.path)) {\n // `\\\\.\\pipe\\foo` → `npipe://./pipe/foo`.\n const m = spec.path.match(/^\\\\\\\\([.?])\\\\(.*)$/);\n const host = m ? m[1] : '.';\n const tail = (m ? m[2] : spec.path).replace(/\\\\/g, '/');\n return `npipe://${host}/${tail}${suffix}`;\n }\n return `unix:${spec.path}${suffix}`;\n }\n case 'ws': {\n const url = new URL(spec.url);\n _appendToken(url.searchParams, spec.token, reveal);\n return url.toString();\n }\n case 'ws-no-init': {\n return spec.url.replace(/^ws:/i, 'ws-no-init:');\n }\n case 'cmd-stdio': {\n const params = new URLSearchParams();\n _appendCommand(params, spec.command);\n _appendEnv(params, spec.env);\n if (spec.cwd !== undefined) params.set(CWD_PARAM, spec.cwd);\n return `cmd-stdio:?${params.toString()}`;\n }\n case 'cmd-env': {\n const params = new URLSearchParams();\n _appendCommand(params, spec.command);\n if (spec.provisionSlot !== undefined) {\n params.set(PROVISION_SLOT_PARAM, spec.provisionSlot);\n }\n _appendEnv(params, spec.env);\n if (spec.cwd !== undefined) params.set(CWD_PARAM, spec.cwd);\n return `cmd:?${params.toString()}`;\n }\n }\n}\n\n/** True for endpoints that connect to existing, possibly-remote infrastructure. */\nexport function isHubEndpoint(spec: ResolvedEndpoint): spec is SocketEndpoint | WsEndpoint {\n return (spec.kind === 'socket' && spec.brokerMode !== 'raw') || spec.kind === 'ws';\n}\n","/**\n * The base error class of hpke-js.\n * @group Errors\n */\nexport class HpkeError extends Error {\n constructor(e) {\n let message;\n if (e instanceof Error) {\n message = e.message;\n }\n else if (typeof e === \"string\") {\n message = e;\n }\n else {\n message = \"\";\n }\n super(message);\n this.name = this.constructor.name;\n }\n}\n/**\n * Invalid parameter.\n * @group Errors\n */\nexport class InvalidParamError extends HpkeError {\n}\n/**\n * KEM input or output validation failure.\n * @group Errors\n */\nexport class ValidationError extends HpkeError {\n}\n/**\n * Public or private key serialization failure.\n * @group Errors\n */\nexport class SerializeError extends HpkeError {\n}\n/**\n * Public or private key deserialization failure.\n * @group Errors\n */\nexport class DeserializeError extends HpkeError {\n}\n/**\n * encap() failure.\n * @group Errors\n */\nexport class EncapError extends HpkeError {\n}\n/**\n * decap() failure.\n * @group Errors\n */\nexport class DecapError extends HpkeError {\n}\n/**\n * Secret export failure.\n * @group Errors\n */\nexport class ExportError extends HpkeError {\n}\n/**\n * seal() failure.\n * @group Errors\n */\nexport class SealError extends HpkeError {\n}\n/**\n * open() failure.\n * @group Errors\n */\nexport class OpenError extends HpkeError {\n}\n/**\n * Sequence number overflow on the encryption context.\n * @group Errors\n */\nexport class MessageLimitReachedError extends HpkeError {\n}\n/**\n * Key pair derivation failure.\n * @group Errors\n */\nexport class DeriveKeyPairError extends HpkeError {\n}\n/**\n * Not supported failure.\n * @group Errors\n */\nexport class NotSupportedError extends HpkeError {\n}\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","import * as dntShim from \"../_dnt.shims.js\";\nimport { NotSupportedError } from \"./errors.js\";\nasync function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n}\nexport class NativeAlgorithm {\n constructor() {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n }\n async _setup() {\n if (this._api !== undefined) {\n return;\n }\n this._api = await loadSubtleCrypto();\n }\n}\n","/**\n * The supported HPKE modes.\n */\nexport const Mode = {\n Base: 0x00,\n Psk: 0x01,\n Auth: 0x02,\n AuthPsk: 0x03,\n};\n/**\n * The supported Key Encapsulation Mechanism (KEM) identifiers.\n */\nexport const KemId = {\n NotAssigned: 0x0000,\n DhkemP256HkdfSha256: 0x0010,\n DhkemP384HkdfSha384: 0x0011,\n DhkemP521HkdfSha512: 0x0012,\n DhkemSecp256k1HkdfSha256: 0x0013,\n DhkemX25519HkdfSha256: 0x0020,\n DhkemX448HkdfSha512: 0x0021,\n HybridkemX25519Kyber768: 0x0030,\n MlKem512: 0x0040,\n MlKem768: 0x0041,\n MlKem1024: 0x0042,\n XWing: 0x647a,\n};\n/**\n * The supported Key Derivation Function (KDF) identifiers.\n */\nexport const KdfId = {\n HkdfSha256: 0x0001,\n HkdfSha384: 0x0002,\n HkdfSha512: 0x0003,\n Sha3256: 0x0004,\n Sha3384: 0x0005,\n Sha3512: 0x0006,\n Shake128: 0x0010,\n Shake256: 0x0011,\n TurboShake128: 0x0012,\n TurboShake256: 0x0013,\n};\n/**\n * The supported Authenticated Encryption with Associated Data (AEAD) identifiers.\n */\nexport const AeadId = {\n Aes128Gcm: 0x0001,\n Aes256Gcm: 0x0002,\n Chacha20Poly1305: 0x0003,\n ExportOnly: 0xFFFF,\n};\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n const out = new Array(256);\n let i = 0;\n let value = 0n;\n while (i < 256) {\n out[i] = value;\n i++;\n value += 1n;\n }\n return out;\n})();\n","// b\"KEM\"\nexport const SUITE_ID_HEADER_KEM = /* @__PURE__ */ new Uint8Array([\n 75,\n 69,\n 77,\n 0,\n 0,\n]);\n","import { EMPTY } from \"../consts.js\";\nimport { InvalidParamError } from \"../errors.js\";\nimport { KdfId } from \"../identifiers.js\";\nimport { NativeAlgorithm } from \"../algorithm.js\";\n// b\"HPKE-v1\"\nconst HPKE_VERSION = /* @__PURE__ */ new Uint8Array([\n 72,\n 80,\n 75,\n 69,\n 45,\n 118,\n 49,\n]);\nexport function toUint8Array(input) {\n return new Uint8Array(toArrayBuffer(input));\n}\nexport function toArrayBuffer(input) {\n if (input instanceof ArrayBuffer) {\n return input;\n }\n if (ArrayBuffer.isView(input)) {\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength)\n .slice().buffer;\n }\n return new Uint8Array(input).slice().buffer;\n}\nexport class HkdfNative extends NativeAlgorithm {\n constructor() {\n super();\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: EMPTY\n });\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n init(suiteId) {\n this._suiteId = suiteId;\n }\n buildLabeledIkm(label, ikm) {\n this._checkInit();\n const ret = new Uint8Array(7 + this._suiteId.byteLength + label.byteLength + ikm.byteLength);\n ret.set(HPKE_VERSION, 0);\n ret.set(this._suiteId, 7);\n ret.set(label, 7 + this._suiteId.byteLength);\n ret.set(ikm, 7 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n buildLabeledInfo(label, info, len) {\n this._checkInit();\n const ret = new Uint8Array(9 + this._suiteId.byteLength + label.byteLength + info.byteLength);\n ret.set(new Uint8Array([0, len]), 0);\n ret.set(HPKE_VERSION, 2);\n ret.set(this._suiteId, 9);\n ret.set(label, 9 + this._suiteId.byteLength);\n ret.set(info, 9 + this._suiteId.byteLength + label.byteLength);\n return ret;\n }\n async extract(salt, ikm) {\n await this._setup();\n const saltBuf = salt.byteLength === 0\n ? new ArrayBuffer(this.hashSize)\n : toArrayBuffer(salt);\n if (saltBuf.byteLength !== this.hashSize) {\n throw new InvalidParamError(\"The salt length must be the same as the hashSize\");\n }\n const ikmBuf = toArrayBuffer(ikm);\n const key = await this._api.importKey(\"raw\", saltBuf, this.algHash, false, [\n \"sign\",\n ]);\n return await this._api.sign(\"HMAC\", key, ikmBuf);\n }\n async expand(prk, info, len) {\n await this._setup();\n const prkBuf = toArrayBuffer(prk);\n const key = await this._api.importKey(\"raw\", prkBuf, this.algHash, false, [\n \"sign\",\n ]);\n const okm = new ArrayBuffer(len);\n const okmBytes = new Uint8Array(okm);\n let prev = EMPTY;\n const mid = toUint8Array(info);\n const tail = new Uint8Array(1);\n if (len > 255 * this.hashSize) {\n throw new Error(\"Entropy limit reached\");\n }\n const tmp = new Uint8Array(this.hashSize + mid.length + 1);\n for (let i = 1, cur = 0; cur < okmBytes.length; i++) {\n tail[0] = i;\n tmp.set(prev, 0);\n tmp.set(mid, prev.length);\n tmp.set(tail, prev.length + mid.length);\n prev = new Uint8Array(await this._api.sign(\"HMAC\", key, tmp.slice(0, prev.length + mid.length + 1)));\n if (okmBytes.length - cur >= prev.length) {\n okmBytes.set(prev, cur);\n cur += prev.length;\n }\n else {\n okmBytes.set(prev.slice(0, okmBytes.length - cur), cur);\n cur += okmBytes.length - cur;\n }\n }\n return okm;\n }\n async extractAndExpand(salt, ikm, info, len) {\n await this._setup();\n const ikmBuf = toArrayBuffer(ikm);\n const baseKey = await this._api.importKey(\"raw\", ikmBuf, \"HKDF\", false, [\"deriveBits\"]);\n return await this._api.deriveBits({\n name: \"HKDF\",\n hash: this.algHash.hash,\n salt: toArrayBuffer(salt),\n info: toArrayBuffer(info),\n }, baseKey, len * 8);\n }\n async labeledExtract(salt, label, ikm) {\n return await this.extract(salt, this.buildLabeledIkm(label, ikm));\n }\n async labeledExpand(prk, label, info, len) {\n return await this.expand(prk, this.buildLabeledInfo(label, info, len), len);\n }\n _checkInit() {\n if (this._suiteId === EMPTY) {\n throw new Error(\"Not initialized. Call init()\");\n }\n }\n}\nexport class HkdfSha256Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha256 (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha256\n });\n /** 32 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-256\",\n length: 256,\n }\n });\n }\n}\nexport class HkdfSha384Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha384 (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha384\n });\n /** 48 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 48\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-384\",\n length: 384,\n }\n });\n }\n}\nexport class HkdfSha512Native extends HkdfNative {\n constructor() {\n super(...arguments);\n /** KdfId.HkdfSha512 (0x0003) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KdfId.HkdfSha512\n });\n /** 64 */\n Object.defineProperty(this, \"hashSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 64\n });\n /** The parameters for Web Cryptography API */\n Object.defineProperty(this, \"algHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n name: \"HMAC\",\n hash: \"SHA-512\",\n length: 512,\n }\n });\n }\n}\n","import * as dntShim from \"../../_dnt.shims.js\";\nimport { KemId } from \"../identifiers.js\";\nexport const isDenoV1 = () => \n// deno-lint-ignore no-explicit-any\ndntShim.dntGlobalThis.process === undefined;\n/**\n * Checks whether the runtime is Deno or not (Node.js).\n * @returns boolean - true if the runtime is Deno, false Node.js.\n */\nexport function isDeno() {\n // deno-lint-ignore no-explicit-any\n if (dntShim.dntGlobalThis.process === undefined) {\n return true;\n }\n // deno-lint-ignore no-explicit-any\n return dntShim.dntGlobalThis.process?.versions?.deno !== undefined;\n}\n/**\n * Checks whetehr the type of input is CryptoKeyPair or not.\n */\nexport const isCryptoKeyPair = (x) => typeof x === \"object\" &&\n x !== null &&\n typeof x.privateKey === \"object\" &&\n typeof x.publicKey === \"object\";\n/**\n * Converts integer to octet string. I2OSP implementation.\n */\nexport function i2Osp(n, w) {\n if (w <= 0) {\n throw new Error(\"i2Osp: too small size\");\n }\n if (n >= 256 ** w) {\n throw new Error(\"i2Osp: too large integer\");\n }\n const ret = new Uint8Array(w);\n for (let i = 0; i < w && n; i++) {\n ret[w - (i + 1)] = n % 256;\n n = Math.floor(n / 256);\n }\n return ret;\n}\n/**\n * Concatenates two Uint8Arrays.\n * @param a Uint8Array\n * @param b Uint8Array\n * @returns Concatenated Uint8Array\n */\nexport function concat(a, b) {\n const ret = new Uint8Array(a.length + b.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n return ret;\n}\n/**\n * Decodes Base64Url-encoded data.\n * @param v Base64Url-encoded string\n * @returns Uint8Array\n */\nexport function base64UrlToBytes(v) {\n const base64 = v.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const byteString = atob(base64);\n const ret = new Uint8Array(byteString.length);\n for (let i = 0; i < byteString.length; i++) {\n ret[i] = byteString.charCodeAt(i);\n }\n return ret;\n}\n/**\n * Encodes Uint8Array to Base64Url.\n * @param v Uint8Array\n * @returns Base64Url-encoded string\n */\nexport function bytesToBase64Url(v) {\n return btoa(String.fromCharCode(...v))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=*$/g, \"\");\n}\n/**\n * Decodes hex string to Uint8Array.\n * @param v Hex string\n * @returns Uint8Array\n * @throws Error if the input is not a hex string.\n */\nexport function hexToBytes(v) {\n if (v.length === 0) {\n return new Uint8Array([]);\n }\n const res = v.match(/[\\da-f]{2}/gi);\n if (res == null) {\n throw new Error(\"Not hex string.\");\n }\n return new Uint8Array(res.map(function (h) {\n return parseInt(h, 16);\n }));\n}\n/**\n * Encodes Uint8Array to hex string.\n * @param v Uint8Array\n * @returns Hex string\n */\nexport function bytesToHex(v) {\n return [...v].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/**\n * Converts KemId to KeyAlgorithm.\n * @param kem KemId\n * @returns KeyAlgorithm\n */\nexport function kemToKeyGenAlgorithm(kem) {\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n return {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n };\n case KemId.DhkemP384HkdfSha384:\n return {\n name: \"ECDH\",\n namedCurve: \"P-384\",\n };\n case KemId.DhkemP521HkdfSha512:\n return {\n name: \"ECDH\",\n namedCurve: \"P-521\",\n };\n default:\n // case KemId.DhkemX25519HkdfSha256\n return {\n name: \"X25519\",\n };\n }\n}\nexport async function loadSubtleCrypto() {\n if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto.subtle;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto.subtle;\n }\n catch (_e) {\n throw new Error(\"Failed to load SubtleCrypto\");\n }\n}\nexport async function loadCrypto() {\n if (typeof dntShim.dntGlobalThis !== \"undefined\" && globalThis.crypto !== undefined) {\n // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc.\n return globalThis.crypto;\n }\n // Node.js <= v18\n try {\n // @ts-ignore: to ignore \"crypto\"\n const { webcrypto } = await import(\"crypto\"); // node:crypto\n return webcrypto;\n }\n catch (_e) {\n throw new Error(\"failed to load Crypto\");\n }\n}\n/**\n * XOR for Uint8Array.\n */\nexport function xor(a, b) {\n if (a.byteLength !== b.byteLength) {\n throw new Error(\"xor: different length inputs\");\n }\n const buf = new Uint8Array(a.byteLength);\n for (let i = 0; i < a.byteLength; i++) {\n buf[i] = a[i] ^ b[i];\n }\n return buf;\n}\n","import { EMPTY, INPUT_LENGTH_LIMIT } from \"../consts.js\";\nimport { DecapError, EncapError, InvalidParamError } from \"../errors.js\";\nimport { SUITE_ID_HEADER_KEM } from \"../interfaces/kemInterface.js\";\nimport { toArrayBuffer } from \"../kdfs/hkdf.js\";\nimport { concat, i2Osp, isCryptoKeyPair } from \"../utils/misc.js\";\n// b\"eae_prk\"\nconst LABEL_EAE_PRK = /* @__PURE__ */ new Uint8Array([\n 101,\n 97,\n 101,\n 95,\n 112,\n 114,\n 107,\n]);\n// b\"shared_secret\"\n// deno-fmt-ignore\nconst LABEL_SHARED_SECRET = /* @__PURE__ */ new Uint8Array([\n 115, 104, 97, 114, 101, 100, 95, 115, 101, 99,\n 114, 101, 116,\n]);\nfunction concat3(a, b, c) {\n const ret = new Uint8Array(a.length + b.length + c.length);\n ret.set(a, 0);\n ret.set(b, a.length);\n ret.set(c, a.length + b.length);\n return ret;\n}\nexport class Dhkem {\n constructor(id, prim, kdf) {\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"_prim\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.id = id;\n this._prim = prim;\n this._kdf = kdf;\n const suiteId = new Uint8Array(SUITE_ID_HEADER_KEM);\n suiteId.set(i2Osp(this.id, 2), 3);\n this._kdf.init(suiteId);\n }\n async serializePublicKey(key) {\n return await this._prim.serializePublicKey(key);\n }\n async deserializePublicKey(key) {\n return await this._prim.deserializePublicKey(toArrayBuffer(key));\n }\n async serializePrivateKey(key) {\n return await this._prim.serializePrivateKey(key);\n }\n async deserializePrivateKey(key) {\n return await this._prim.deserializePrivateKey(toArrayBuffer(key));\n }\n async importKey(format, key, isPublic = true) {\n return await this._prim.importKey(format, key, isPublic);\n }\n async generateKeyPair() {\n return await this._prim.generateKeyPair();\n }\n async deriveKeyPair(ikm) {\n const rawIkm = toArrayBuffer(ikm);\n if (rawIkm.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long ikm\");\n }\n return await this._prim.deriveKeyPair(rawIkm);\n }\n async encap(params) {\n let ke;\n if (params.ekm === undefined) {\n ke = await this.generateKeyPair();\n }\n else if (isCryptoKeyPair(params.ekm)) {\n // params.ekm is only used for testing.\n ke = params.ekm;\n }\n else {\n // params.ekm is only used for testing.\n ke = await this.deriveKeyPair(params.ekm);\n }\n const enc = await this._prim.serializePublicKey(ke.publicKey);\n const pkrm = await this._prim.serializePublicKey(params.recipientPublicKey);\n try {\n let dh;\n if (params.senderKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n }\n else {\n const sks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.privateKey\n : params.senderKey;\n const dh1 = new Uint8Array(await this._prim.dh(ke.privateKey, params.recipientPublicKey));\n const dh2 = new Uint8Array(await this._prim.dh(sks, params.recipientPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderKey === undefined) {\n kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n }\n else {\n const pks = isCryptoKeyPair(params.senderKey)\n ? params.senderKey.publicKey\n : await this._prim.derivePublicKey(params.senderKey);\n const pksm = await this._prim.serializePublicKey(pks);\n kemContext = concat3(new Uint8Array(enc), new Uint8Array(pkrm), new Uint8Array(pksm));\n }\n const sharedSecret = await this._generateSharedSecret(dh, kemContext);\n return {\n enc: enc,\n sharedSecret: sharedSecret,\n };\n }\n catch (e) {\n throw new EncapError(e);\n }\n }\n async decap(params) {\n const enc = toArrayBuffer(params.enc);\n const pke = await this._prim.deserializePublicKey(enc);\n const skr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.privateKey\n : params.recipientKey;\n const pkr = isCryptoKeyPair(params.recipientKey)\n ? params.recipientKey.publicKey\n : await this._prim.derivePublicKey(params.recipientKey);\n const pkrm = await this._prim.serializePublicKey(pkr);\n try {\n let dh;\n if (params.senderPublicKey === undefined) {\n dh = new Uint8Array(await this._prim.dh(skr, pke));\n }\n else {\n const dh1 = new Uint8Array(await this._prim.dh(skr, pke));\n const dh2 = new Uint8Array(await this._prim.dh(skr, params.senderPublicKey));\n dh = concat(dh1, dh2);\n }\n let kemContext;\n if (params.senderPublicKey === undefined) {\n kemContext = concat(new Uint8Array(enc), new Uint8Array(pkrm));\n }\n else {\n const pksm = await this._prim.serializePublicKey(params.senderPublicKey);\n kemContext = new Uint8Array(enc.byteLength + pkrm.byteLength + pksm.byteLength);\n kemContext.set(new Uint8Array(enc), 0);\n kemContext.set(new Uint8Array(pkrm), enc.byteLength);\n kemContext.set(new Uint8Array(pksm), enc.byteLength + pkrm.byteLength);\n }\n return await this._generateSharedSecret(dh, kemContext);\n }\n catch (e) {\n throw new DecapError(e);\n }\n }\n async _generateSharedSecret(dh, kemContext) {\n const labeledIkm = this._kdf.buildLabeledIkm(LABEL_EAE_PRK, dh);\n const labeledInfo = this._kdf.buildLabeledInfo(LABEL_SHARED_SECRET, kemContext, this.secretSize);\n return await this._kdf.extractAndExpand(EMPTY, labeledIkm, labeledInfo, this.secretSize);\n }\n}\n","// The key usages for KEM.\nexport const KEM_USAGES = [\"deriveBits\"];\n// b\"dkp_prk\"\nexport const LABEL_DKP_PRK = /* @__PURE__ */ new Uint8Array([\n 100,\n 107,\n 112,\n 95,\n 112,\n 114,\n 107,\n]);\n// b\"sk\"\nexport const LABEL_SK = /* @__PURE__ */ new Uint8Array([115, 107]);\n","// The key usages for AEAD.\nexport const AEAD_USAGES = [\"encrypt\", \"decrypt\"];\n","import { AEAD_USAGES, AeadId, NativeAlgorithm, toArrayBuffer, } from \"@hpke/common\";\nexport class AesGcmContext extends NativeAlgorithm {\n constructor(key) {\n super();\n Object.defineProperty(this, \"_rawKey\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_key\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: undefined\n });\n this._rawKey = toArrayBuffer(key);\n }\n async seal(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: toArrayBuffer(iv),\n additionalData: toArrayBuffer(aad),\n };\n const ct = await this._api.encrypt(alg, this._key, toArrayBuffer(data));\n return ct;\n }\n async open(iv, data, aad) {\n await this._setupKey();\n const alg = {\n name: \"AES-GCM\",\n iv: toArrayBuffer(iv),\n additionalData: toArrayBuffer(aad),\n };\n const pt = await this._api.decrypt(alg, this._key, toArrayBuffer(data));\n return pt;\n }\n async _setupKey() {\n if (this._key !== undefined) {\n return;\n }\n await this._setup();\n const key = await this._importKey(this._rawKey);\n (new Uint8Array(this._rawKey)).fill(0);\n this._key = key;\n return;\n }\n async _importKey(key) {\n return await this._api.importKey(\"raw\", key, { name: \"AES-GCM\" }, true, AEAD_USAGES);\n }\n}\n/**\n * The AES-128-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes128Gcm`.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class Aes128Gcm {\n constructor() {\n /** AeadId.Aes128Gcm (0x0001) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes128Gcm\n });\n /** 16 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n createEncryptionContext(key) {\n return new AesGcmContext(key);\n }\n}\n/**\n * The AES-256-GCM for HPKE AEAD implementing {@link AeadInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Aes256Gcm`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class Aes256Gcm extends Aes128Gcm {\n constructor() {\n super(...arguments);\n /** AeadId.Aes256Gcm (0x0002) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: AeadId.Aes256Gcm\n });\n /** 32 */\n Object.defineProperty(this, \"keySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 12 */\n Object.defineProperty(this, \"nonceSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 12\n });\n /** 16 */\n Object.defineProperty(this, \"tagSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n }\n}\n","import { NotSupportedError } from \"@hpke/common\";\nexport function emitNotSupported() {\n return new Promise((_resolve, reject) => {\n reject(new NotSupportedError(\"Not supported\"));\n });\n}\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n const rawExporterContext = toArrayBuffer(exporterContext);\n if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","import { i2Osp, MessageLimitReachedError, xor } from \"@hpke/common\";\nimport { ExporterContextImpl } from \"./exporterContext.js\";\nexport class EncryptionContextImpl extends ExporterContextImpl {\n constructor(api, kdf, params) {\n super(api, kdf, params.exporterSecret);\n // AEAD id.\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a key for the algorithm.\n Object.defineProperty(this, \"_nK\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of a nonce for the algorithm.\n Object.defineProperty(this, \"_nN\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The length in bytes of an authentication tag for the algorithm.\n Object.defineProperty(this, \"_nT\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // The end-to-end encryption key information.\n Object.defineProperty(this, \"_ctx\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (params.key === undefined || params.baseNonce === undefined ||\n params.seq === undefined) {\n throw new Error(\"Required parameters are missing\");\n }\n this._aead = params.aead;\n this._nK = this._aead.keySize;\n this._nN = this._aead.nonceSize;\n this._nT = this._aead.tagSize;\n const key = this._aead.createEncryptionContext(params.key);\n this._ctx = {\n key: key,\n baseNonce: params.baseNonce,\n seq: params.seq,\n };\n }\n computeNonce(k) {\n const seqBytes = i2Osp(k.seq, k.baseNonce.byteLength);\n return xor(k.baseNonce, seqBytes).buffer;\n }\n incrementSeq(k) {\n // if (this.seq >= (1 << (8 * this.baseNonce.byteLength)) - 1) {\n if (k.seq > Number.MAX_SAFE_INTEGER) {\n throw new MessageLimitReachedError(\"Message limit reached\");\n }\n k.seq += 1;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : toUint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, } from \"@hpke/common\";\nimport { CipherSuiteNative } from \"./cipherSuiteNative.js\";\nimport { DhkemP256HkdfSha256Native, DhkemP384HkdfSha384Native, DhkemP521HkdfSha512Native, } from \"./kems/dhkemNative.js\";\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This class is the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteNative | @hpke/core#CipherSuiteNative} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - `DHKEM(X448, HKDF-SHA512)`\n * - `ChaCha20Poly1305`\n *\n * In addtion, the HKDF functions contained in this `CipherSuiteNative`\n * class can only derive keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use DHKEM(X25519, HKDF-SHA256).\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemX25519HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuite extends CipherSuiteNative {\n}\n/**\n * The DHKEM(P-256, HKDF-SHA256) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP256HkdfSha256`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP256HkdfSha256 extends DhkemP256HkdfSha256Native {\n}\n/**\n * The DHKEM(P-384, HKDF-SHA384) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP384HkdfSha384`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemP384HkdfSha384 extends DhkemP384HkdfSha384Native {\n}\n/**\n * The DHKEM(P-521, HKDF-SHA512) for HPKE KEM implementing {@link KemInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KemId.DhkemP521HkdfSha512`\n * as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class DhkemP521HkdfSha512 extends DhkemP521HkdfSha512Native {\n}\n/**\n * The HKDF-SHA256 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha256`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha256 extends HkdfSha256Native {\n}\n/**\n * The HKDF-SHA384 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha384`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * DhkemP384HkdfSha384,\n * HkdfSha384,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP384HkdfSha384(),\n * kdf: new HkdfSha384(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class HkdfSha384 extends HkdfSha384Native {\n}\n/**\n * The HKDF-SHA512 for HPKE KDF implementing {@link KdfInterface}.\n *\n * When using `@hpke/core`, the instance of this class must be specified\n * to the `kem` parameter of {@link CipherSuiteParams} instead of `KdfId.HkdfSha512`.\n *\n * The KDF class can only derive keys of the same length as the `hashSize`.\n * If you want to derive keys longer than the `hashSize`,\n * please use {@link https://jsr.io/@hpke/hpke-js/doc/~/CipherSuite | hpke-js#CipherSuite}.\n *\n * @example\n *\n * ```ts\n * import {\n * Aes256Gcm,\n * CipherSuite,\n * DhkemP521HkdfSha512,\n * HkdfSha512,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP521HkdfSha512(),\n * kdf: new HkdfSha512(),\n * aead: new Aes256Gcm(),\n * });\n * ```\n */\nexport class HkdfSha512 extends HkdfSha512Native {\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(32);\n p[0] = 9;\n return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported X25519 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { Dhkem, HkdfSha256Native, KemId } from \"@hpke/common\";\nimport { X25519 } from \"./dhkemPrimitives/x25519.js\";\n/**\n * The DHKEM(X25519, HKDF-SHA256) for HPKE KEM implementing {@link KemInterface}.\n *\n * The instance of this class can be specified to the\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuiteParams | CipherSuiteParams} as follows:\n *\n * @example\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * CipherSuite,\n * HkdfSha256,\n * DhkemX25519HkdfSha256,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class DhkemX25519HkdfSha256 extends Dhkem {\n constructor() {\n const kdf = new HkdfSha256Native();\n super(KemId.DhkemX25519HkdfSha256, new X25519(kdf), kdf);\n /** KemId.DhkemX25519HkdfSha256 (0x0020) */\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: KemId.DhkemX25519HkdfSha256\n });\n /** 32 */\n Object.defineProperty(this, \"secretSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 32 */\n Object.defineProperty(this, \"encSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 32 */\n Object.defineProperty(this, \"publicKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n /** 32 */\n Object.defineProperty(this, \"privateKeySize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 32\n });\n }\n}\n","/**\n * The single place in linkrpc that touches the Web Crypto API\n * (`globalThis.crypto.subtle`). These low-level functions are surfaced to the\n * rest of the codebase through the `./crypto` facade — import from there, not\n * from this file.\n *\n * Web Crypto is available unchanged in modern browsers and in Node 20+, so\n * there is no longer a node-specific vs. web-specific implementation — this\n * one file works in both runtimes.\n */\nimport { Aes256Gcm, CipherSuite, DhkemX25519HkdfSha256, HkdfSha256 } from \"@hpke/core\";\nimport {\n base64UrlToBytes,\n type Keypair,\n type PrivateKey,\n type PublicKey,\n type Signature,\n type X25519Keypair,\n} from \"./cryptoProvider\";\n\n// RFC 8410 ASN.1 DER prefix wrapping a raw 32-byte Ed25519 seed into PKCS8 —\n// Web Crypto's `importKey` accepts raw bytes only for public keys, not for\n// Ed25519 private keys, so we have to wrap the seed every time we sign.\nconst _PKCS8_PREFIX = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,\n]);\n\n// Same PKCS8 wrapper for a raw 32-byte X25519 scalar — identical to the Ed25519\n// prefix except the algorithm OID byte (0x6e = X25519 instead of 0x70 = Ed25519).\nconst _PKCS8_X25519_PREFIX = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\n\nfunction _wrapPkcs8(seed: Uint8Array, prefix: Uint8Array = _PKCS8_PREFIX): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(prefix.length + seed.length);\n out.set(prefix, 0);\n out.set(seed, prefix.length);\n return out;\n}\n\nconst _ALG = \"Ed25519\";\n\n// ---- X25519 + HPKE-base / DHKEM(X25519,HKDF-SHA256) / HKDF-SHA256 /\n// AES-256-GCM (RFC 9180 ciphersuite 0x0020/0x0001/0x0002) ----\n//\n// The HPKE composition (HKDF, DHKEM encap/decap, key schedule) is provided by\n// `@hpke/core` — a Web Crypto-based, RFC 9180 test-vector-verified\n// implementation with no native dependencies that runs unchanged in modern\n// browsers and Node 20+. We only bridge between its CryptoKey-oriented API and\n// the raw-bytes contract used elsewhere in linkrpc, and assemble the wire blob\n// as `enc (32 B) || ciphertext || tag (16 B)`.\n\nconst _ENC_LEN = 32; // DHKEM(X25519) encapsulated-key length\nconst _TAG_LEN = 16; // AES-256-GCM authentication-tag length\n\n// Built lazily on first use rather than at module load. Constructing the\n// `@hpke/core` `CipherSuite` eagerly is a top-level side effect that bundlers\n// cannot prove pure, which pins `@hpke/*` into every bundle that merely reaches\n// this module (e.g. a stdio-only client that never signs/encrypts). Deferring\n// the construction keeps module evaluation side-effect-free so the HPKE code\n// can be tree-shaken away when none of the functions below are called.\nlet _hpkeSuiteInstance: CipherSuite | undefined;\nfunction _hpkeSuite(): CipherSuite {\n return (_hpkeSuiteInstance ??= new CipherSuite({\n kem: new DhkemX25519HkdfSha256(),\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n }));\n}\n\nfunction _concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Copy a (possibly offset) view into a fresh, exact-length ArrayBuffer — the\n// shape `@hpke/core` expects for key material and message inputs.\nfunction _toBuffer(bytes: Uint8Array): ArrayBuffer {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n}\n\n// ---- Public function API ---------------------------------------------------\n// These are the low-level crypto primitives; the `./crypto` facade re-exports\n// them as the package's controlled crypto API.\n\n/** Generate a fresh Ed25519 keypair (raw 32-byte seed + 32-byte public key). */\nexport async function generateEd25519Keypair(): Promise<Keypair> {\n const kp = (await crypto.subtle.generateKey(_ALG, true, [\"sign\", \"verify\"])) as CryptoKeyPair;\n const pub = new Uint8Array(await crypto.subtle.exportKey(\"raw\", kp.publicKey));\n const pkcs8 = new Uint8Array(await crypto.subtle.exportKey(\"pkcs8\", kp.privateKey));\n return {\n publicKey: pub,\n privateKey: new Uint8Array(pkcs8.subarray(pkcs8.length - 32)),\n };\n}\n\n/** Ed25519 sign `message` with a raw 32-byte seed private key. */\nexport async function ed25519Sign(privateKey: PrivateKey, message: Uint8Array): Promise<Signature> {\n const key = await crypto.subtle.importKey(\"pkcs8\", _wrapPkcs8(privateKey), _ALG, false, [\"sign\"]);\n const sig = await crypto.subtle.sign(_ALG, key, new Uint8Array(message));\n return new Uint8Array(sig);\n}\n\n/** Ed25519 verify. Returns `false` (never throws) on malformed input. */\nexport async function ed25519Verify(publicKey: PublicKey, message: Uint8Array, sig: Signature): Promise<boolean> {\n try {\n const key = await crypto.subtle.importKey(\"raw\", new Uint8Array(publicKey), _ALG, false, [\"verify\"]);\n return await crypto.subtle.verify(_ALG, key, new Uint8Array(sig), new Uint8Array(message));\n } catch {\n return false;\n }\n}\n\n/**\n * Deterministically derive an Ed25519 keypair from a raw 32-byte seed (the\n * seed *is* the private key). The public key is recovered via a JWK round-trip\n * (`importKey` pkcs8 → `exportKey` jwk → `x`). For tests / reproducible\n * identities — NOT for production key generation, which must be random.\n */\nexport async function ed25519KeypairFromSeed(seed: Uint8Array): Promise<Keypair> {\n if (seed.length !== 32) throw new Error(\"ed25519KeypairFromSeed: seed must be 32 bytes\");\n const key = await crypto.subtle.importKey(\"pkcs8\", _wrapPkcs8(seed), _ALG, true, [\"sign\"]);\n const jwk = (await crypto.subtle.exportKey(\"jwk\", key)) as JsonWebKey;\n if (!jwk.x) throw new Error(\"ed25519KeypairFromSeed: failed to derive public key\");\n return { publicKey: base64UrlToBytes(jwk.x), privateKey: new Uint8Array(seed) };\n}\n\n/**\n * Deterministically derive an X25519 keypair from a raw 32-byte scalar (the\n * scalar *is* the private key). Public key recovered via the same JWK\n * round-trip. For tests / reproducible identities only.\n */\nexport async function x25519KeypairFromSeed(seed: Uint8Array): Promise<X25519Keypair> {\n if (seed.length !== 32) throw new Error(\"x25519KeypairFromSeed: seed must be 32 bytes\");\n const key = await crypto.subtle.importKey(\n \"pkcs8\",\n _wrapPkcs8(seed, _PKCS8_X25519_PREFIX),\n \"X25519\",\n true,\n [\"deriveBits\"],\n );\n const jwk = (await crypto.subtle.exportKey(\"jwk\", key)) as JsonWebKey;\n if (!jwk.x) throw new Error(\"x25519KeypairFromSeed: failed to derive public key\");\n return { publicKey: base64UrlToBytes(jwk.x), privateKey: new Uint8Array(seed) };\n}\n\n/** Generate a fresh X25519 keypair (raw 32-byte scalar + 32-byte public key). */\nexport async function generateX25519Keypair(): Promise<X25519Keypair> {\n const suite = _hpkeSuite();\n const kp = await suite.kem.generateKeyPair();\n return {\n publicKey: new Uint8Array(await suite.kem.serializePublicKey(kp.publicKey)),\n privateKey: new Uint8Array(await suite.kem.serializePrivateKey(kp.privateKey)),\n };\n}\n\n/**\n * HPKE-base-mode single-shot seal. Output blob layout is\n * `enc (32 B) || ciphertext || tag (16 B)`. `domain` is bound into both the\n * HPKE `info` parameter and the AEAD AAD.\n */\nexport async function hpkeSeal(args: {\n readonly recipientPublicKey: Uint8Array;\n readonly domain: Uint8Array;\n readonly plaintext: Uint8Array;\n}): Promise<Uint8Array> {\n const recipientPublicKey = await _hpkeSuite().kem.deserializePublicKey(_toBuffer(args.recipientPublicKey));\n // Bind domain into the HPKE info parameter, and into the AEAD AAD as well —\n // defence in depth.\n const sender = await _hpkeSuite().createSenderContext({\n recipientPublicKey,\n info: _toBuffer(args.domain),\n });\n // AES-GCM appends the 16-byte tag to the ciphertext, giving the `ct || tag`\n // layout; `sender.enc` is the 32-byte encapsulated key.\n const ctAndTag = new Uint8Array(await sender.seal(_toBuffer(args.plaintext), _toBuffer(args.domain)));\n return _concat(new Uint8Array(sender.enc), ctAndTag);\n}\n\n/**\n * HPKE-base-mode single-shot open. Throws on any tag failure (wrong domain,\n * wrong recipient key, or tampered blob); the error deliberately does NOT\n * distinguish these cases.\n */\nexport async function hpkeOpen(args: {\n readonly recipientPrivateKey: Uint8Array;\n readonly domain: Uint8Array;\n readonly blob: Uint8Array;\n}): Promise<Uint8Array> {\n if (args.blob.length < _ENC_LEN + _TAG_LEN) {\n throw new Error(\"hpkeOpen: blob too short\");\n }\n const enc = args.blob.subarray(0, _ENC_LEN);\n const ctAndTag = args.blob.subarray(_ENC_LEN); // ct || tag, exactly what AES-GCM open expects.\n const recipientKey = await _hpkeSuite().kem.deserializePrivateKey(_toBuffer(args.recipientPrivateKey));\n const recipient = await _hpkeSuite().createRecipientContext({\n recipientKey,\n enc: _toBuffer(enc),\n info: _toBuffer(args.domain),\n });\n return new Uint8Array(await recipient.open(_toBuffer(ctAndTag), _toBuffer(args.domain)));\n}\n","/**\n * The single, explicit public crypto API for linkrpc.\n *\n * All signing, verifying, key generation, HPKE sealing/opening and hashing go\n * through the functions exported here. They delegate to the one Web Crypto\n * implementation in `./ed25519CryptoProvider` (the only module that touches\n * `globalThis.crypto.subtle`). Consumers should `import * as crypto from\n * \".../identity/crypto\"` and call `crypto.sign(...)` etc. — there is no\n * pluggable provider; crypto is just this API.\n */\nimport type { Keypair, PrivateKey, PublicKey, Signature, X25519Keypair } from \"./cryptoProvider\";\nimport {\n ed25519Sign,\n ed25519Verify,\n ed25519KeypairFromSeed,\n generateEd25519Keypair,\n generateX25519Keypair as _generateX25519Keypair,\n hpkeOpen as _hpkeOpen,\n hpkeSeal as _hpkeSeal,\n x25519KeypairFromSeed as _x25519KeypairFromSeed,\n} from \"./ed25519CryptoProvider\";\nimport { sha256 as _sha256 } from \"./sha256\";\n\n/** Generate a fresh Ed25519 keypair (raw 32-byte seed + 32-byte public key). */\nexport function generateKeypair(): Promise<Keypair> {\n return generateEd25519Keypair();\n}\n\n/**\n * Deterministically derive an Ed25519 keypair from a raw 32-byte seed. For\n * tests / reproducible identities only — production keys must be random\n * (use {@link generateKeypair}).\n */\nexport function keypairFromSeed(seed: Uint8Array): Promise<Keypair> {\n return ed25519KeypairFromSeed(seed);\n}\n\n/**\n * Deterministically derive an X25519 keypair from a raw 32-byte scalar. For\n * tests / reproducible identities only.\n */\nexport function x25519KeypairFromSeed(seed: Uint8Array): Promise<X25519Keypair> {\n return _x25519KeypairFromSeed(seed);\n}\n\n/** Ed25519 sign `message` with a raw 32-byte seed private key. */\nexport function sign(privateKey: PrivateKey, message: Uint8Array): Promise<Signature> {\n return ed25519Sign(privateKey, message);\n}\n\n/** Ed25519 verify. Returns `false` (never throws) on malformed input. */\nexport function verify(publicKey: PublicKey, message: Uint8Array, sig: Signature): Promise<boolean> {\n return ed25519Verify(publicKey, message, sig);\n}\n\n/** Generate a fresh X25519 keypair (raw 32-byte scalar + 32-byte public key). */\nexport function generateX25519Keypair(): Promise<X25519Keypair> {\n return _generateX25519Keypair();\n}\n\n/**\n * HPKE-base-mode single-shot seal. Output blob layout is\n * `enc (32 B) || ciphertext || tag (16 B)`; `domain` is bound into both the\n * HPKE `info` parameter and the AEAD AAD.\n */\nexport function hpkeSeal(args: {\n readonly recipientPublicKey: Uint8Array;\n readonly domain: Uint8Array;\n readonly plaintext: Uint8Array;\n}): Promise<Uint8Array> {\n return _hpkeSeal(args);\n}\n\n/**\n * HPKE-base-mode single-shot open. Throws on any tag failure (wrong domain,\n * wrong recipient key, or tampered blob); the error deliberately does NOT\n * distinguish these cases.\n */\nexport function hpkeOpen(args: {\n readonly recipientPrivateKey: Uint8Array;\n readonly domain: Uint8Array;\n readonly blob: Uint8Array;\n}): Promise<Uint8Array> {\n return _hpkeOpen(args);\n}\n\n/** SHA-256 digest (synchronous, dependency-free). */\nexport function sha256(bytes: Uint8Array): Uint8Array {\n return _sha256(bytes);\n}\n","/**\n * Identity-layer signing over the {@link signingInput linkrpc signed-object\n * standard}. These need a {@link SigningIdentity} / public key, so they live\n * in the identity layer; the pure byte definitions stay in\n * `../protocol/signedObject`.\n */\n\nimport { base64UrlToBytes, bytesToBase64Url, type PrincipalId, PublicKey, resolveSigningKey } from \"../crypto/cryptoProvider\";\nimport * as crypto from \"../crypto/crypto\";\nimport {\n type SignDomain,\n readSignature,\n signingInput,\n withSignature,\n} from \"../protocol/signedObject\";\nimport type { SigningIdentity } from \"./identity\";\n\nexport {\n HUBRPC_META_KEY,\n HUBRPC_SIGNATURE_KEY,\n HUBRPC_UNSIGNED_KEY,\n LINKRPC_META_KEY,\n LINKRPC_SIGNATURE_KEY,\n LINKRPC_UNSIGNED_KEY,\n type Base64Sha256,\n type SignDomain,\n type SignatureEnvelope,\n type Signatures,\n getKeyId,\n readSignature,\n signedHash,\n signingDomainValue,\n signingInput,\n} from \"../protocol/signedObject\";\n\n/**\n * Sign `obj` in `domain` with `identity`, returning a copy with\n * `$hubrpcSignature[domain]` populated (sibling signatures preserved). The\n * signature commits to {@link signingInput}`(domain, obj)`; the signer's\n * {@link SigningIdentity.publicSigningIdentity}.keyId is stamped alongside it\n * as the (unsigned) routing hint.\n */\nexport async function signObject<T extends object>(\n domain: SignDomain,\n obj: T,\n identity: SigningIdentity,\n): Promise<T & { $hubrpcSignature: Record<string, { keyId: string; sig: string }> }> {\n const sig = await identity.sign(signingInput(domain, obj));\n return withSignature(obj, domain, {\n keyId: identity.publicSigningIdentity.keyId,\n sig: bytesToBase64Url(sig),\n }) as T & { $hubrpcSignature: Record<string, { keyId: string; sig: string }> };\n}\n\n/**\n * Verify `obj`'s `domain` signature against `signerKey` (a raw public key).\n * Returns `false` (never throws) on a missing/malformed signature.\n */\nexport async function verifyObject(\n domain: SignDomain,\n obj: object,\n signerKey: PublicKey,\n): Promise<boolean> {\n const env = readSignature(obj, domain);\n if (env === undefined) return false;\n let sigBytes: Uint8Array;\n try {\n sigBytes = base64UrlToBytes(env.sig);\n } catch {\n return false;\n }\n return crypto.verify(signerKey, signingInput(domain, obj), sigBytes);\n}\n\n/**\n * Convenience: verify against a signer {@link PrincipalId}. Reads the keyId off\n * `$hubrpcSignature[domain]`, resolves the verifying key via\n * {@link resolveSigningKey} (fail-closed on an unresolvable/mismatched key),\n * then checks the signature.\n */\nexport async function verifyObjectByPrincipal(\n domain: SignDomain,\n obj: object,\n principal: PrincipalId,\n signedAtMs?: number,\n): Promise<boolean> {\n const env = readSignature(obj, domain);\n if (env === undefined) return false;\n const resolved = resolveSigningKey({\n principal,\n keyId: env.keyId,\n ...(signedAtMs !== undefined ? { timeMs: signedAtMs } : {}),\n });\n if (resolved === undefined) return false;\n return verifyObject(domain, obj, resolved.publicKey);\n}\n","/**\n * Sign / verify the linkrpc identity envelopes on a JSON-RPC call.\n *\n * Wire shape (signed call params):\n *\n * params: {\n * ...userParams,\n * $hubrpc: CallMeta, // signed\n * $hubrpcSignature: { call: sig }, // the signature\n * $hubrpcUnsigned: { capabilities } // unsigned attachments\n * }\n *\n * The call signature commits to `signingInput(\"call\", paramsObject)` — the\n * params with the two reserved keys (`$hubrpcSignature`, `$hubrpcUnsigned`)\n * stripped and the `\"call\"` pad prefixed. This is the same\n * {@link signedHash} the cap-minter uses for `callBind.payloadHash`, so the\n * two can never drift.\n */\n\nimport type { SignedCapability } from '../protocol/capability';\nimport type { JsonValue } from '../protocol/jsonValue';\nimport {\n HUBRPC_UNSIGNED_KEY,\n type CallMeta,\n type LinkRpcUnsigned,\n type LinkRpcWireParams,\n requireObjectParams,\n stripLinkRpcWireMeta,\n} from '../protocol/linkRpcEnvelope';\nimport { bytesToBase64Url, type PrincipalId, resolveSigningKey } from '../crypto/cryptoProvider';\nimport {\n HUBRPC_META_KEY,\n HUBRPC_SIGNATURE_KEY,\n type Base64Sha256,\n readSignature,\n signObject,\n signedHash,\n verifyObject,\n} from './signedObject';\nimport type { SigningIdentity } from './identity';\n\nexport { HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY, type CallMeta };\n\n// ---- signing -------------------------------------------------------\n\nexport interface SignRpcCallOptions {\n readonly method: string;\n /** The user's params. Must be a plain JSON object or `undefined` (else throws). */\n readonly params?: JsonValue;\n /** Identity that produces the signature. */\n readonly signingIdentity: SigningIdentity;\n /** Unix milliseconds. Defaults to `Date.now()`. */\n readonly nowMs?: number;\n /** Override the random nonce (testing). */\n readonly nonce?: Uint8Array;\n /** Optional schema hash assertion. */\n readonly interfaceHash?: string;\n}\n\nexport interface SignedRpcCall {\n /**\n * Wire params for the JSON-RPC request: the user's params merged with\n * `$hubrpc` (signed meta) and `$hubrpcSignature` (the `call` signature).\n * Capabilities are attached separately via {@link attachCapabilities}\n * since they are unsigned authority hints, not part of what the\n * signature commits to.\n */\n readonly wireParams: LinkRpcWireParams;\n /** The signed call meta embedded under `$hubrpc`. */\n readonly callMeta: CallMeta;\n /** The call's content hash (`signedHash(\"call\", signedParams)`) — what `callBind` binds to. */\n readonly callHash: Base64Sha256;\n}\n\n/**\n * Sign a single JSON-RPC call. Produces the wire-form params with the\n * `$hubrpc` (signed meta) and `$hubrpcSignature.call` envelopes attached,\n * plus the call content hash.\n */\nexport async function signRpcCall(opts: SignRpcCallOptions): Promise<SignedRpcCall> {\n const userParams = requireObjectParams(opts.params);\n const nonce = opts.nonce ?? _randomNonce();\n const signedAtMs = opts.nowMs ?? Date.now();\n const callMeta: CallMeta = {\n method: opts.method,\n nonce: bytesToBase64Url(nonce),\n signedAtMs,\n principal: opts.signingIdentity.publicSigningIdentity.principal,\n ...(opts.interfaceHash !== undefined ? { interfaceHash: opts.interfaceHash } : {}),\n };\n const signedParams = { ...userParams, [HUBRPC_META_KEY]: callMeta };\n const callHash = signedHash(\"call\", signedParams);\n const wireParams = await signObject(\"call\", signedParams, opts.signingIdentity) as LinkRpcWireParams;\n return { wireParams, callMeta, callHash };\n}\n\n/**\n * Attach capabilities to a {@link SignedRpcCall.wireParams}. Capabilities\n * ride in `$hubrpcUnsigned.capabilities` — they are NOT part of what the\n * signature commits to (which is why this is a separate step). Returns a\n * new wireParams object; the input is not mutated.\n */\nexport function attachCapabilities(\n wireParams: LinkRpcWireParams,\n capabilities: readonly SignedCapability[],\n): LinkRpcWireParams {\n if (capabilities.length === 0) return wireParams;\n const obj = wireParams as unknown as Record<string, unknown>;\n const existing = obj[HUBRPC_UNSIGNED_KEY] as LinkRpcUnsigned | undefined;\n const merged: LinkRpcUnsigned = { ...existing, capabilities };\n return { ...obj, [HUBRPC_UNSIGNED_KEY]: merged } as LinkRpcWireParams;\n}\n\n// ---- verification --------------------------------------------------\n\nexport interface VerifyRpcCallOptions {\n readonly wireMethod: string;\n /** Raw params object received on the wire. */\n readonly wireParams: unknown;\n /** Defaults to `Date.now()`. */\n readonly nowMs?: number;\n /** Max clock skew in milliseconds. Default 300000 (5 min). */\n readonly maxSkewMs?: number;\n /** When `true`, reject calls lacking a signed envelope + signature. */\n readonly requireSigned?: boolean;\n}\n\nexport type VerifyRpcCallResult =\n | {\n readonly ok: true;\n /** `undefined` when the call had no signed (`$hubrpc` + `$hubrpcSignature.call`) envelope. */\n readonly identity:\n | undefined\n | {\n readonly callMeta: CallMeta;\n /** The authenticated principal (`callMeta.principal`). */\n readonly signer: PrincipalId;\n /** The call's content hash — input to `callBind.payloadHash`. */\n readonly callHash: Base64Sha256;\n readonly capabilities: SignedCapability[];\n };\n /** Params the handler should see (user params with the reserved keys stripped). */\n readonly params: JsonValue | undefined;\n }\n | { readonly ok: false; readonly reason: string; };\n\n/**\n * Verify the identity envelope on a JSON-RPC call. Does **not** evaluate\n * capability chains or caveats — that is the hub / authoriser's job.\n *\n * A signed call carries `$hubrpc` (with `principal`) and a `call` signature\n * under `$hubrpcSignature`. The signature is checked against\n * `signingInput(\"call\", wireParams)` (the reserved keys are stripped by the\n * signed-object standard). Bare/unsigned calls return `identity: undefined`.\n */\nexport async function verifyRpcCall(opts: VerifyRpcCallOptions): Promise<VerifyRpcCallResult> {\n const { wireParams } = opts;\n const meta = _extractObject<CallMeta>(wireParams, HUBRPC_META_KEY);\n const userParams = stripLinkRpcWireMeta(wireParams);\n\n if (meta === undefined) {\n if (opts.requireSigned) return { ok: false, reason: 'missing $hubrpc envelope' };\n return { ok: true, identity: undefined, params: userParams };\n }\n\n // Validate the always-present meta fields.\n if (\n typeof meta.method !== 'string' ||\n typeof meta.nonce !== 'string' ||\n typeof meta.signedAtMs !== 'number' ||\n (meta.principal !== undefined && typeof meta.principal !== 'string') ||\n (meta.interfaceHash !== undefined && typeof meta.interfaceHash !== 'string')\n ) {\n return { ok: false, reason: 'malformed linkrpc envelope' };\n }\n\n // Anti-confusion: the signed method must match the JSON-RPC method.\n if (meta.method !== opts.wireMethod) {\n return { ok: false, reason: 'method mismatch' };\n }\n\n // Skew window applies to signed and unsigned-with-meta calls alike.\n const now = opts.nowMs ?? Date.now();\n const skew = opts.maxSkewMs ?? 300000;\n if (Math.abs(meta.signedAtMs - now) > skew) {\n return { ok: false, reason: `timestamp skew > ${skew}ms` };\n }\n\n const signature = readSignature(wireParams as object, 'call');\n if (meta.principal === undefined || signature === undefined) {\n // Has $hubrpc meta but no signature — an unsigned call.\n if (opts.requireSigned) return { ok: false, reason: 'unsigned call' };\n return { ok: true, identity: undefined, params: userParams };\n }\n\n const resolved = resolveSigningKey({\n principal: meta.principal,\n keyId: signature.keyId,\n timeMs: meta.signedAtMs,\n });\n if (resolved === undefined) {\n return { ok: false, reason: `unresolvable signing key for principal ${meta.principal}` };\n }\n\n // The signature covers `signingInput(\"call\", wireParams)` — the\n // standard strips `$hubrpcSignature`/`$hubrpcUnsigned` for us.\n const sigOk = await verifyObject('call', wireParams as object, resolved.publicKey);\n if (!sigOk) return { ok: false, reason: 'bad signature' };\n\n const callHash = signedHash('call', wireParams as object);\n const unsigned = _extractObject<LinkRpcUnsigned>(wireParams, HUBRPC_UNSIGNED_KEY);\n const capabilities = Array.isArray(unsigned?.capabilities)\n ? (unsigned!.capabilities as SignedCapability[])\n : [];\n\n return {\n ok: true,\n identity: {\n callMeta: meta,\n signer: meta.principal,\n callHash,\n capabilities,\n },\n params: userParams,\n };\n}\n\n// ---- helpers -------------------------------------------------------\n\nfunction _extractObject<T>(wireParams: unknown, key: string): T | undefined {\n if (wireParams === null || typeof wireParams !== 'object' || Array.isArray(wireParams)) {\n return undefined;\n }\n const env = (wireParams as Record<string, unknown>)[key];\n if (env === undefined || env === null || typeof env !== 'object' || Array.isArray(env)) {\n return undefined;\n }\n return env as T;\n}\n\nfunction _randomNonce(): Uint8Array {\n const out = new Uint8Array(16);\n globalThis.crypto.getRandomValues(out);\n return out;\n}\n","import type { CapProvider } from './signingSender';\nimport {\n type SignedCapability,\n} from './capability';\nimport type { ManagedIdentityStorage } from './managedIdentity';\n\nexport interface CapBagOptions {\n /**\n * Per-identity persistent storage (e.g.\n * {@link ManagedIdentityHandle.storage}). Omit for a memory-only bag\n * that forgets its caps when the process exits.\n */\n readonly storage?: ManagedIdentityStorage;\n /** Storage key. Defaults to `hubrpc.caps.v1`. */\n readonly storageKey?: string;\n /** Optional sink for non-fatal storage warnings. */\n readonly onWarn?: (message: string) => void;\n}\n\nconst DEFAULT_STORAGE_KEY = 'hubrpc.caps.v1';\n\n/**\n * A process-lifetime bag of hub-issued capabilities. Plug\n * {@link CapBag.provider} straight into a connection's cap provider so every\n * outbound signed call carries whatever caps have been granted so far. The\n * hub picks whichever cap matches the call per dispatch.\n *\n * When constructed with {@link CapBagOptions.storage} the bag hydrates from\n * (and persists to) storage, so the next process spawn for the same identity\n * reuses its grants without re-prompting.\n */\nexport class CapBag {\n /** Create a bag, hydrating from storage when one was supplied. */\n public static async load(options: CapBagOptions = {}): Promise<CapBag> {\n const bag = new CapBag(options);\n await bag._hydrate();\n return bag;\n }\n\n private readonly _caps: SignedCapability[] = [];\n private readonly _storage?: ManagedIdentityStorage;\n private readonly _storageKey: string;\n private readonly _onWarn: (message: string) => void;\n\n private constructor(options: CapBagOptions) {\n this._storage = options.storage;\n this._storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;\n this._onWarn = options.onWarn ?? (() => { });\n }\n\n public get capabilities(): readonly SignedCapability[] {\n return this._caps;\n }\n\n /**\n * A {@link CapProvider} reflecting the bag at call-time. Assign it to\n * `HubClientHandle.signing.capProvider` or pass it through\n * `SigningSenderConfig.capProvider`.\n */\n public readonly provider: CapProvider = async () => this._caps.length > 0 ? { capabilities: this._caps } : {};\n\n /** Append capabilities and persist (when backed by storage). */\n public async add(...caps: readonly SignedCapability[]): Promise<void> {\n if (caps.length === 0) {\n return;\n }\n this._caps.push(...caps);\n await this._persist();\n }\n\n /** Drop all capabilities and persist the empty bag. */\n public async clear(): Promise<void> {\n if (this._caps.length === 0) {\n return;\n }\n this._caps.length = 0;\n await this._persist();\n }\n\n private async _hydrate(): Promise<void> {\n if (!this._storage) {\n return;\n }\n try {\n const persisted = await this._storage.get<SignedCapability[]>(this._storageKey);\n if (!Array.isArray(persisted)) {\n return;\n }\n for (const cap of persisted) {\n if (cap && typeof cap === 'object' && '$hubrpcSignature' in cap) {\n this._caps.push(cap);\n } else {\n this._onWarn(`skipping malformed persisted cap`);\n }\n }\n } catch (e) {\n this._onWarn(`failed to read caps from storage: ${(e as Error).message}`);\n }\n }\n\n private async _persist(): Promise<void> {\n if (!this._storage) {\n return;\n }\n try {\n await this._storage.set(this._storageKey, this._caps);\n } catch (e) {\n this._onWarn(`failed to persist caps: ${(e as Error).message}`);\n }\n }\n}\n","import { CapBag } from './capBag';\nimport type { SigningIdentity } from './identity';\nimport type { PrincipalId } from '../crypto/cryptoProvider';\nimport type { SignedCapability } from './capability';\n\n/**\n * A signing identity bundled with its durable capability set. The\n * {@link SigningIdentity} is fixed for the life of the principal; the\n * {@link CapBag} is mutable and extensible — caps accumulate as the peer grants\n * them.\n *\n * Transient, per-call (one-shot) grants are deliberately NOT part of a\n * principal: that is a separate policy, see `OneShotCapStaging`.\n *\n * Lives in its own module (rather than alongside `SigningSender`) so the\n * `SigningSender` ⇄ `createManagedPrincipal` factory cycle does not run through\n * a top-level `class … extends Principal`: such a cycle would hit a TDZ\n * (\"Class extends value undefined\") depending on module evaluation order.\n */\nexport class Principal {\n public static async create(\n identity: SigningIdentity,\n capabilities: readonly SignedCapability[] = [],\n ): Promise<Principal> {\n const capBag = await CapBag.load();\n await capBag.add(...capabilities);\n return new Principal(identity, capBag);\n }\n\n constructor(\n public readonly identity: SigningIdentity,\n public readonly capBag: CapBag,\n ) { }\n\n public get id(): PrincipalId {\n return this.identity.publicSigningIdentity.principal;\n }\n}\n","import {\n base64UrlToBytes,\n bytesToBase64Url,\n type KeyId,\n keyIdForPrincipal,\n type Keypair,\n type PrincipalId,\n type PrivateKey,\n principalForPublicKey,\n publicKeyForKeyId,\n type Signature,\n type X25519Keypair,\n} from \"../crypto/cryptoProvider\";\nimport * as crypto from \"../crypto/crypto\";\n\n/** JSON-serializable form of a {@link KeypairSigningIdentity} (base64url keys). */\nexport interface SerializedKeypairSigningIdentity {\n readonly privateKey: string;\n readonly publicKey: string;\n}\n\n/**\n * The public face of a signing identity: its stable {@link PrincipalId} name\n * and the {@link KeyId} its signatures are stamped with. In Phase 1 (perpetual\n * identities) the keyId is the genesis key embedded in the principal, so it is\n * derived by stripping the `id:` prefix.\n */\nexport class PublicSigningIdentity {\n constructor(public readonly principal: PrincipalId) { }\n\n /** The {@link KeyId} this identity signs with (its genesis key, in Phase 1). */\n public get keyId(): KeyId {\n return keyIdForPrincipal(this.principal);\n }\n}\n\nexport interface SigningIdentity {\n readonly publicSigningIdentity: PublicSigningIdentity;\n sign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\n/**\n * {@link SigningIdentity} backed by an in-process keypair. For the common\n * case where the signing material lives in memory. For external HSM-style\n * backends, implement {@link SigningIdentity} directly.\n */\nexport class KeypairSigningIdentity implements SigningIdentity {\n public readonly publicSigningIdentity: PublicSigningIdentity;\n\n constructor(\n principal: PrincipalId,\n private readonly _privateKey: PrivateKey,\n ) {\n this.publicSigningIdentity = new PublicSigningIdentity(principal);\n }\n\n public sign(message: Uint8Array): Promise<Signature> {\n return crypto.sign(this._privateKey, message);\n }\n\n public static fromKeypair(keypair: Keypair): KeypairSigningIdentity {\n return new KeypairSigningIdentity(\n principalForPublicKey(keypair.publicKey),\n keypair.privateKey,\n );\n }\n\n /** Generate a fresh signing identity (Ed25519 keypair). */\n public static async generateNew(): Promise<KeypairSigningIdentity> {\n return KeypairSigningIdentity.fromKeypair(await crypto.generateKeypair());\n }\n\n /** Restore an identity from its {@link toJson} form. */\n public static fromJson(json: SerializedKeypairSigningIdentity): KeypairSigningIdentity {\n return KeypairSigningIdentity.fromKeypair({\n privateKey: base64UrlToBytes(json.privateKey),\n publicKey: base64UrlToBytes(json.publicKey),\n });\n }\n\n /** Serialize the keypair to a JSON-friendly form (base64url keys). */\n public toJson(): SerializedKeypairSigningIdentity {\n return {\n privateKey: bytesToBase64Url(this._privateKey),\n publicKey: bytesToBase64Url(publicKeyForKeyId(this.publicSigningIdentity.keyId)),\n };\n }\n}\n\nexport class PublicWrappingIdentity {\n constructor(public readonly wrapPublicKey: Uint8Array) { }\n}\n\nexport interface WrappingIdentity {\n readonly publicWrappingIdentity: PublicWrappingIdentity;\n wrap(domain: string, bytes: Uint8Array): Promise<Uint8Array>;\n unwrap(domain: string, blob: Uint8Array): Promise<Uint8Array>;\n}\n\nexport interface Identity extends SigningIdentity, WrappingIdentity {\n /** The identity's stable {@link PrincipalId} name. */\n readonly principal: PrincipalId;\n /** @deprecated */\n readonly wrapPublicKey: Uint8Array;\n}\n\n/**\n * Full {@link Identity} backed by in-process Ed25519 (signing) and X25519\n * (wrapping) keypairs. The local counterpart to a keystore/executor-backed\n * identity — used by self-managed principals that hold their own key\n * material (e.g. loaded from disk). For external HSM-style backends,\n * implement {@link Identity} directly.\n */\nexport class KeypairIdentity implements Identity {\n public readonly principal: PrincipalId;\n public readonly wrapPublicKey: Uint8Array;\n public readonly publicSigningIdentity: PublicSigningIdentity;\n public readonly publicWrappingIdentity: PublicWrappingIdentity;\n\n constructor(\n principal: PrincipalId,\n private readonly _privateKey: PrivateKey,\n private readonly _wrap: X25519Keypair,\n ) {\n this.principal = principal;\n this.wrapPublicKey = _wrap.publicKey;\n this.publicSigningIdentity = new PublicSigningIdentity(principal);\n this.publicWrappingIdentity = new PublicWrappingIdentity(_wrap.publicKey);\n }\n\n public sign(message: Uint8Array): Promise<Signature> {\n return crypto.sign(this._privateKey, message);\n }\n\n public wrap(domain: string, bytes: Uint8Array): Promise<Uint8Array> {\n return crypto.hpkeSeal({\n recipientPublicKey: this._wrap.publicKey,\n domain: new TextEncoder().encode(domain),\n plaintext: bytes,\n });\n }\n\n public unwrap(domain: string, blob: Uint8Array): Promise<Uint8Array> {\n return crypto.hpkeOpen({\n recipientPrivateKey: this._wrap.privateKey,\n domain: new TextEncoder().encode(domain),\n blob,\n });\n }\n\n /** Generate a fresh identity (Ed25519 + X25519 keypairs). */\n public static async generate(): Promise<KeypairIdentity> {\n const ed = await crypto.generateKeypair();\n const wrap = await crypto.generateX25519Keypair();\n return new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap);\n }\n}\n","import { array, boolean, object, optional, string, unknown } from 'zod/mini';\nimport { defineInterface } from '../connection/interfaceDefinition';\nimport { requestType } from '../schema/memberTypes';\n\n// ---- The wire interface --------------------------------------------------\nconst zB64 = string();\n/**\n * Per-participant key oracle. Reached on the participant's root overlay\n * (form-2 method names like `identity::sign`). Private key material lives\n * in the executor; the participant only sees the operations.\n *\n * Wire shape:\n * sign / wrap / unwrap all take and return base64url-encoded bytes.\n * `domain` is a caller-chosen string bound into HPKE info and the AEAD\n * AAD. `unwrap` succeeds only when invoked with the exact `domain` that\n * `wrap` was called with. Use a stable, namespaced string (e.g.\n * `secrets.vault.master-key.v1`).\n */\n\nexport const identityInterface = defineInterface(\n {\n id: 'identity',\n description: 'Per-participant key oracle: exposes signing and HPKE-based ' +\n 'wrap/unwrap for the identity the executor has attached to ' +\n \"this participant's root overlay. Private keys never leave \" +\n 'the executor.',\n },\n {\n getPrincipal: requestType(\n object({}),\n object({ principal: string() })\n ),\n getWrapPublicKey: requestType(\n object({}),\n object({ wrapPublicKey: zB64 })\n ),\n sign: requestType(\n object({ bytes: zB64 }),\n object({ signature: zB64 })\n ),\n wrap: requestType(\n object({ domain: string(), bytes: zB64 }),\n object({ blob: zB64 })\n ),\n unwrap: requestType(\n object({ domain: string(), blob: zB64 }),\n object({ bytes: zB64 })\n ),\n }\n);\n/**\n * Per-identity persistent key/value store. Reached on the participant's\n * root overlay as `identity.storage::get` etc. — same overlay that serves\n * `identity::*`, same single-participant addressability.\n *\n * Storage scope is the executor's managed-identity slot (e.g.\n * `service:demo`). Lifecycle is bound to the identity: when the executor\n * deletes the identity for a slot, the storage for that slot is wiped in\n * the same operation. New identity issued for the same slot starts empty.\n *\n * The executor encrypts the backing file at rest with the same secret it\n * uses for identity files — see {@link IdentityKeystore} in\n * `@hediet/linkrpc/node`.\n *\n * Keys must match `^[A-Za-z0-9._/-]{1,256}$`. `/` is conventional for\n * namespacing (`caps.v1`, `prefs/foo`) and `list({ prefix })` honours\n * that. Values are arbitrary JSON.\n */\n\nexport const identityStorageInterface = defineInterface(\n {\n id: 'identity.storage',\n description: 'Per-identity persistent key/value store. Scope is the ' +\n \"executor's managed-identity slot; lifecycle is tied to the \" +\n 'identity itself. Backed by an at-rest-encrypted file in the ' +\n 'executor.',\n },\n {\n get: requestType(\n object({ key: string() }),\n // `value` is omitted when the key is absent — mirrors\n // `web-app-host::storageGet`'s convention.\n object({ value: optional(unknown()) })\n ),\n set: requestType(\n object({ key: string(), value: unknown() }),\n object({})\n ),\n delete: requestType(\n object({ key: string() }),\n object({ existed: boolean() })\n ),\n list: requestType(\n object({ prefix: optional(string()) }),\n object({ keys: array(string()) })\n ),\n }\n);\n","import type { IRequestSender } from '../connection/channel';\nimport { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport { type SigningCallCtx } from './signingSender';\nimport {\n base64UrlToBytes,\n bytesToBase64Url,\n keyIdForPrincipal,\n type Keypair,\n type PrincipalId,\n principalForPublicKey,\n publicKeyForKeyId,\n type Signature,\n type X25519Keypair,\n} from '../crypto/cryptoProvider';\nimport * as crypto from '../crypto/crypto';\nimport {\n Identity,\n PublicSigningIdentity,\n PublicWrappingIdentity,\n} from './identity';\nimport { identityInterface, identityStorageInterface } from './identity.interfaces';\n\n/**\n * Valid `identity.storage` key shape. The interface schema declares\n * `z.string()` so we don't break clients with regex errors at the wire;\n * the executor-side handler applies this stricter check.\n */\nconst _STORAGE_KEY_RE = /^[A-Za-z0-9._/-]{1,256}$/;\n\n/**\n * Executor-side backing for `identity.storage::*`. Lifecycle tied to a\n * single managed-identity slot; the executor decides where bytes are\n * stored.\n */\nexport interface ManagedIdentityStorageBackend {\n get(key: string): Promise<unknown | undefined>;\n set(key: string, value: unknown): Promise<void>;\n /** Returns `true` iff the key existed before this call. */\n delete(key: string): Promise<boolean>;\n list(prefix?: string): Promise<string[]>;\n}\n\n/**\n * In-process storage backend. Used by tests and by any executor that\n * doesn't need at-rest persistence.\n */\nexport class InMemoryManagedIdentityStorage implements ManagedIdentityStorageBackend {\n private readonly _data = new Map<string, unknown>();\n\n public async get(key: string): Promise<unknown | undefined> {\n return this._data.has(key) ? this._data.get(key) : undefined;\n }\n\n public async set(key: string, value: unknown): Promise<void> {\n this._data.set(key, value);\n }\n\n public async delete(key: string): Promise<boolean> {\n return this._data.delete(key);\n }\n\n public async list(prefix?: string): Promise<string[]> {\n const all = [...this._data.keys()];\n return prefix === undefined ? all : all.filter((k) => k.startsWith(prefix));\n }\n}\n\n/**\n * In-process `ManagedIdentity` that holds the private key in memory and\n * uses the package crypto API. Useful for tests and for hub-side features\n * that want a short-lived identity without touching disk.\n */\nexport class InMemoryManagedIdentity implements Identity {\n public readonly principal: PrincipalId;\n public readonly wrapPublicKey: Uint8Array;\n\n constructor(\n private readonly _ed: Keypair,\n private readonly _wrap: X25519Keypair,\n ) {\n this.principal = principalForPublicKey(_ed.publicKey);\n this.wrapPublicKey = _wrap.publicKey;\n }\n\n public get publicSigningIdentity(): PublicSigningIdentity {\n return new PublicSigningIdentity(this.principal);\n }\n\n public get publicWrappingIdentity(): PublicWrappingIdentity {\n return new PublicWrappingIdentity(this.wrapPublicKey);\n }\n\n public sign(bytes: Uint8Array): Promise<Signature> {\n return crypto.sign(this._ed.privateKey, bytes);\n }\n\n public wrap(domain: string, bytes: Uint8Array): Promise<Uint8Array> {\n return crypto.hpkeSeal({\n recipientPublicKey: this._wrap.publicKey,\n domain: _encodeDomain(domain),\n plaintext: bytes,\n });\n }\n\n public unwrap(domain: string, blob: Uint8Array): Promise<Uint8Array> {\n return crypto.hpkeOpen({\n recipientPrivateKey: this._wrap.privateKey,\n domain: _encodeDomain(domain),\n blob,\n });\n }\n\n /** Generate a fresh in-memory identity (Ed25519 + X25519 keypairs). */\n public static async generate(): Promise<InMemoryManagedIdentity> {\n const ed = await crypto.generateKeypair();\n const wrap = await crypto.generateX25519Keypair();\n return new InMemoryManagedIdentity(ed, wrap);\n }\n}\n\n// ---- Overlay registration (executor → participant) -----------------------\n\n/**\n * Register the `identity` interface on `overlay` so the bound participant\n * can call `identity::sign` etc. on its root overlay. The overlay is\n * private to one participant — no other peer can reach these methods.\n *\n * When `storage` is supplied, the `identity.storage` interface is\n * registered alongside `identity::*`. Lifetime/scope of the backend is\n * the executor's responsibility — for keystore-backed identities the\n * backend lives as long as the identity slot does.\n *\n * Typical caller: the executor (e.g. the VS Code extension), right after\n * `Hub.attachParticipant`, on the `rootOverlay` returned from the attach\n * handle.\n */\nexport function registerIdentityOnOverlay(\n overlay: LinkRpcConnection,\n identity: Identity,\n storage?: ManagedIdentityStorageBackend,\n): void {\n overlay.register(identityInterface, {\n getPrincipal: async () => ({ principal: identity.principal }),\n getWrapPublicKey: async () => ({\n wrapPublicKey: bytesToBase64Url(identity.wrapPublicKey),\n }),\n sign: async ({ bytes }) => ({\n signature: bytesToBase64Url(await identity.sign(base64UrlToBytes(bytes))),\n }),\n wrap: async ({ domain, bytes }) => ({\n blob: bytesToBase64Url(await identity.wrap(domain, base64UrlToBytes(bytes))),\n }),\n unwrap: async ({ domain, blob }) => ({\n bytes: bytesToBase64Url(await identity.unwrap(domain, base64UrlToBytes(blob))),\n }),\n });\n\n if (storage) {\n _registerStorageInterface(overlay, storage);\n }\n}\n\n/**\n * Like {@link registerIdentityOnOverlay}, but resolves the identity lazily on\n * first use via `resolveIdentity`. The identity is materialized only when the\n * bound participant actually calls `identity::*` — registering the overlay\n * does NOT create or load any identity.\n *\n * This is essential for the consent model: a host can serve `identity::*` on a\n * keystore slot without making the slot privileged (`hasState`) until the app\n * genuinely opts into an identity. `resolveIdentity` is expected to be cheap on\n * repeat calls (the keystore caches in memory), and to reflect lifecycle\n * changes — e.g. after a slot is wiped and re-created (\"Reset Identity\"), the\n * next call resolves the fresh identity.\n *\n * `storage` is registered eagerly because reading/writing storage is itself\n * the privileged act the app must perform to gain state — exposing the\n * interface costs nothing until used.\n */\nexport function registerLazyIdentityOnOverlay(\n overlay: LinkRpcConnection<unknown>,\n resolveIdentity: () => Promise<Identity>,\n storage?: ManagedIdentityStorageBackend,\n): void {\n overlay.register(identityInterface, {\n getPrincipal: async () => ({ principal: (await resolveIdentity()).principal }),\n getWrapPublicKey: async () => ({\n wrapPublicKey: bytesToBase64Url((await resolveIdentity()).wrapPublicKey),\n }),\n sign: async ({ bytes }) => ({\n signature: bytesToBase64Url(await (await resolveIdentity()).sign(base64UrlToBytes(bytes))),\n }),\n wrap: async ({ domain, bytes }) => ({\n blob: bytesToBase64Url(await (await resolveIdentity()).wrap(domain, base64UrlToBytes(bytes))),\n }),\n unwrap: async ({ domain, blob }) => ({\n bytes: bytesToBase64Url(await (await resolveIdentity()).unwrap(domain, base64UrlToBytes(blob))),\n }),\n });\n\n if (storage) {\n _registerStorageInterface(overlay, storage);\n }\n}\n\nfunction _registerStorageInterface(\n overlay: LinkRpcConnection,\n storage: ManagedIdentityStorageBackend,\n): void {\n overlay.register(identityStorageInterface, {\n get: async ({ key }) => {\n _assertStorageKey(key);\n const value = await storage.get(key);\n return value === undefined ? {} : { value };\n },\n set: async ({ key, value }) => {\n _assertStorageKey(key);\n await storage.set(key, value);\n return {};\n },\n delete: async ({ key }) => {\n _assertStorageKey(key);\n const existed = await storage.delete(key);\n return { existed };\n },\n list: async ({ prefix }) => {\n const keys = await storage.list(prefix);\n return { keys };\n },\n });\n}\n\nfunction _assertStorageKey(key: string): void {\n if (!_STORAGE_KEY_RE.test(key)) {\n throw new Error(\n `identity.storage: invalid key '${key}'. Must match ${_STORAGE_KEY_RE}.`,\n );\n }\n}\n\n// ---- Client-side: resolve an identity that round-trips through identity:: ---\n\n/**\n * Client-side proxy for `identity.storage::*`. Methods round-trip through\n * the participant's root overlay; the executor enforces key-shape rules\n * server-side.\n *\n * Calls are unsigned (same recursion-guard rationale as\n * {@link createManagedIdentity} — the overlay is private to one\n * participant, so transport-level routing already authenticates).\n */\nexport interface ManagedIdentityStorage {\n get<T = unknown>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown): Promise<void>;\n delete(key: string): Promise<boolean>;\n list(prefix?: string): Promise<string[]>;\n}\n\n/**\n * A managed identity resolved from an executor's `identity::*` overlay: a\n * full {@link Identity} (signing + HPKE wrap/unwrap, all round-tripping\n * through the executor — private keys never leave it) plus the\n * per-identity {@link ManagedIdentityStorage}.\n */\nexport interface ManagedIdentity extends Identity {\n /**\n * Per-identity persistent key/value store. Backed by the executor's\n * `identity.storage::*` overlay; calls throw when the executor did not\n * register storage for this slot (e.g. an in-process identity for tests).\n */\n readonly storage: ManagedIdentityStorage;\n}\n\n/**\n * Bootstrap a {@link ManagedIdentity} from a sender (typically the raw\n * unsigned sender obtained via `channel.sender` before wrapping with\n * {@link SigningSender}). Makes `identity::*` calls unsigned — the\n * executor's overlay is private to one participant so routing already\n * identifies the caller, preventing signing recursion.\n *\n * The returned identity signs / wraps / unwraps by round-tripping through\n * the executor's `identity::*` overlay; the caller wires it into their\n * {@link SigningSender} configuration (e.g. as a {@link Principal}). No\n * side effects on any existing connection or holder.\n */\nexport async function createManagedIdentity(\n sender: IRequestSender<unknown>,\n): Promise<ManagedIdentity> {\n const conn = new LinkRpcConnection<unknown, SigningCallCtx>(sender);\n const id = conn.get(identityInterface, { signerOverride: null });\n const storage = conn.get(identityStorageInterface, { signerOverride: null });\n\n const { principal } = await id.getPrincipal({});\n // Sanity: refuse to install if the executor returns a malformed principal.\n publicKeyForKeyId(keyIdForPrincipal(principal));\n\n const { wrapPublicKey: wrapPublicKeyB64 } = await id.getWrapPublicKey({});\n const wrapPublicKey = base64UrlToBytes(wrapPublicKeyB64);\n\n const identity: ManagedIdentity = {\n principal,\n wrapPublicKey,\n publicSigningIdentity: new PublicSigningIdentity(principal),\n publicWrappingIdentity: new PublicWrappingIdentity(wrapPublicKey),\n sign: async (message: Uint8Array): Promise<Signature> => {\n const { signature } = await id.sign({ bytes: bytesToBase64Url(message) });\n return base64UrlToBytes(signature);\n },\n wrap: async (domain, bytes) => {\n const { blob } = await id.wrap({ domain, bytes: bytesToBase64Url(bytes) });\n return base64UrlToBytes(blob);\n },\n unwrap: async (domain, blob) => {\n const { bytes } = await id.unwrap({ domain, blob: bytesToBase64Url(blob) });\n return base64UrlToBytes(bytes);\n },\n storage: {\n get: async <T = unknown>(key: string) => {\n const { value } = await storage.get({ key });\n return value === undefined ? undefined : (value as T);\n },\n set: async (key, value) => {\n await storage.set({ key, value });\n },\n delete: async (key) => {\n const { existed } = await storage.delete({ key });\n return existed;\n },\n list: async (prefix) => {\n const { keys } = await storage.list(prefix === undefined ? {} : { prefix });\n return keys;\n },\n },\n };\n\n return identity;\n}\n\nfunction _encodeDomain(domain: string): Uint8Array {\n return new TextEncoder().encode(domain);\n}\n\n// Re-export for callers that want to know what `channel.setSigner` expects.\nexport type { JsonRpcChannel };\n","import type { IRequestSender } from '../connection/channel';\nimport { Principal } from './principal';\nimport type { Identity } from './identity';\nimport { CapBag } from './capBag';\nimport { createManagedIdentity, type ManagedIdentityStorage } from './managedIdentity';\n\n/**\n * A {@link Principal} that also exposes the executor-backed per-identity\n * {@link ManagedIdentityStorage}. Returned by {@link createManagedPrincipal}\n * so callers can persist their own app state (e.g. a resolved serviceId)\n * alongside the granted capabilities, using the very same durable store the\n * {@link CapBag} hydrates from — no second storage wiring required.\n */\nexport class PrincipalWithStore extends Principal {\n public declare readonly identity: Identity;\n\n constructor(\n identity: Identity,\n capBag: CapBag,\n public readonly store: ManagedIdentityStorage,\n ) {\n super(identity, capBag);\n }\n}\n\n/**\n * Executor-managed principal: the peer signs for us through its\n * `identity::sign` overlay (we never hold a private key). Bootstrapped purely\n * from the outbound `sender` — no side effects on any connection — and caps\n * persist in the executor-backed per-identity storage. Works over any\n * transport whose peer serves the identity overlay (hub *or* stdio).\n *\n * Call this exactly once per channel: it performs the `identity::*` handshake\n * and hydrates the {@link CapBag} from storage. The returned\n * {@link PrincipalWithStore} additionally surfaces that same durable\n * {@link ManagedIdentityStorage} as `store`.\n */\nexport async function createManagedPrincipal(\n sender: IRequestSender<unknown>,\n): Promise<PrincipalWithStore> {\n const identity = await createManagedIdentity(sender);\n const capBag = await CapBag.load({ storage: identity.storage });\n return new PrincipalWithStore(identity, capBag, identity.storage);\n}\n","import type { SignedCapability } from './capability';\nimport { bytesToBase64Url, type PrincipalId } from '../crypto/cryptoProvider';\nimport { attachCapabilities, signRpcCall } from './signedRpcEnvelope';\nimport type { SigningIdentity } from './identity';\nimport { Principal } from './principal';\nimport type { JsonValue } from '../protocol/jsonRpc';\nimport {\n Channel,\n type IRequestSender,\n type RawStreamingCall,\n type SendOpts,\n type StreamSendOpts,\n} from '../connection/channel';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport { createManagedPrincipal, type PrincipalWithStore } from './managedPrincipal';\n\n/**\n * Per-outbound-call hook. Sees every signed call this sender makes,\n * and gets a chance to:\n * - attach capabilities (the common case),\n * - override `method` / `params` / `interfaceHash` (rewriting,\n * auditing, schema-pinning),\n * - advance `signedAtMs` (e.g. after a slow consent prompt that needs\n * to issue a cap bound to a fresher timestamp than the sender's\n * initial wall-clock).\n *\n * `signer` and `nonce` are NOT overridable. `signer` is the call's\n * identity; `nonce` ties any cap to this specific call attempt and must\n * not drift between the cap-issuance request and the call itself.\n */\nexport type CapProvider = (req: {\n readonly method: string;\n readonly params: JsonValue | undefined;\n readonly signer: PrincipalId;\n readonly nonce: string;\n readonly signedAtMs: number;\n readonly interfaceHash?: string;\n}) => Promise<CapProviderResult>;\n\nexport interface CapProviderResult {\n readonly capabilities?: readonly SignedCapability[];\n /** Override the wire method this sender signs. Default: the original. */\n readonly method?: string;\n /** Override the params this sender signs. Default: the original. */\n readonly params?: JsonValue;\n /** Override the interfaceHash baked into the signed envelope. */\n readonly interfaceHash?: string;\n /** Advance the Unix-ms timestamp baked into the signed envelope. */\n readonly signedAtMs?: number;\n}\n\ninterface BaseCallIntent {\n readonly method: string;\n readonly params: JsonValue | undefined;\n readonly interfaceHash?: string;\n}\n\ninterface NegotiatedCallIntent {\n method: string;\n params: JsonValue | undefined;\n interfaceHash?: string;\n signedAtMs: number;\n}\n\ninterface SigningCoordinates {\n readonly nonceBytes: Uint8Array;\n readonly nonce: string;\n readonly signedAtMs: number;\n}\n\ninterface PreparedOutboundCall {\n readonly method: string;\n readonly params: JsonValue | undefined;\n}\n\n/**\n * Per-call ctx the {@link SigningSender} consumes. All fields are\n * optional; the sender's persistent {@link SigningSenderConfig.principal} is\n * the default.\n *\n * To install a signer after the sender is already constructed (e.g. a\n * managed-identity bootstrap), mutate the caller-owned config object — it is\n * read fresh on every call. No setter on the sender itself.\n */\nexport interface SigningCallCtx {\n /**\n * Override the signer for this call only. Pass `null` to skip\n * signing entirely (plain unsigned JSON-RPC). Bootstrap flows that\n * must talk to `identity::*` before a managed signer is available\n * use `signerOverride: null` for those calls.\n */\n readonly signerOverride?: SigningIdentity | null;\n /**\n * Replace whatever caps the persistent cap provider would attach.\n * Skips the persistent provider for this call.\n */\n readonly capsOverride?: readonly SignedCapability[];\n /**\n * Reserved for the perm-denied / consent retry path. Currently a\n * passthrough — sender does not act on it yet.\n */\n readonly requestPermissionWhenDenied?: boolean;\n}\n\n/**\n * Persistent config for a {@link SigningSender}.\n *\n * `principal` is the call identity plus its durable, extensible capability\n * set. `oneShotCaps` is an optional side-policy that may stage a single-use\n * capability onto the very next call without touching the principal. Both\n * fields are read fresh on every call, so callers may install or swap them\n * after the sender has been constructed.\n *\n * A missing `principal` means \"no signing / no caps\" for that call, unless\n * overridden via {@link SigningCallCtx}.\n */\nexport interface SigningSenderConfig {\n /** Identity + persistent (extensible) capabilities. */\n readonly principal?: Principal;\n /**\n * Optional per-call capability provider. Runs at sign-time with the\n * concrete method/params/nonce/timestamp and may return caps and/or\n * signing overrides.\n */\n readonly capProvider?: CapProvider;\n /**\n * Optional one-shot capability staging policy. Independent of the\n * principal; drained per outbound signed call.\n */\n readonly oneShotCaps?: OneShotCapStaging;\n}\n\n/**\n * A call identity bundled with its durable capability set — re-exported from\n * its own module so the `SigningSender` ⇄ managed-principal factory cycle never\n * runs through a top-level `class … extends Principal` (TDZ-safe).\n */\nexport { Principal };\n\n/**\n * Side-policy for staging *one-shot* capabilities onto the next outbound\n * signed call, independent of any {@link Principal}. The {@link SigningSender}\n * drains the staged caps after attaching them once, so a spent cap never\n * leaks into a later call.\n *\n * Requesting the one-shot grant (prompting the user / hub) lives next to —\n * not inside — the principal: the principal owns identity and durable\n * capabilities; this owns the transient per-call grant.\n */\nexport class OneShotCapStaging {\n private _staged: readonly SignedCapability[] = [];\n\n /** Stage caps for the next signed call. Replaces any still-pending caps. */\n public stage(caps: readonly SignedCapability[]): void {\n this._staged = caps;\n }\n\n /**\n * Take (and clear) the staged caps. Called by {@link SigningSender} once\n * per outbound signed call.\n */\n public take(): readonly SignedCapability[] {\n const caps = this._staged;\n this._staged = [];\n return caps;\n }\n}\n\n/**\n * Outbound sender decorator that wraps every call in a `$hubrpc` signed\n * envelope and (optionally) attaches capabilities. Stateless w.r.t. signing\n * config — the {@link Principal} and {@link OneShotCapStaging} are resolved\n * per-call from {@link SigningSenderConfig}, so the caller can install or\n * swap them after construction by mutating that object.\n */\n/**\n * The result of {@link SigningSender.fromChannelWithManagedPrincipal} /\n * {@link SigningSender.fromTransportWithManagedPrincipal}: a signing\n * {@link Channel} ready for `LinkRpcConnection`, plus the executor-managed\n * {@link PrincipalWithStore} that drives it (caps, per-identity storage, nodeId).\n */\nexport interface ManagedSigningChannel<TInCtx = undefined> {\n readonly channel: Channel<TInCtx, SigningCallCtx>;\n readonly principal: PrincipalWithStore;\n}\n\nexport class SigningSender<TInCtx = unknown> implements IRequestSender<SigningCallCtx> {\n /**\n * Wrap an inner channel with signing. Composes via {@link Channel.withSender}\n * so the resulting `Channel<TInCtx, SigningCallCtx>` plugs into\n * `LinkRpcConnection`.\n */\n public static wrapChannel<TInCtx>(\n inner: Channel<TInCtx, unknown>,\n config: SigningSenderConfig,\n ): Channel<TInCtx, SigningCallCtx> {\n return inner.withSender((raw) => new SigningSender<TInCtx>(raw, config));\n }\n\n /**\n * Bootstrap an executor-managed {@link Principal} over the **unsigned**\n * `channel`, then wrap that same channel with signing driven by it.\n *\n * Crucially, the `identity::*` handshake that mints the managed principal\n * rides the *raw* channel (`channel.sender`), so those bootstrap calls are\n * themselves never signed — there is no \"sign the sign call\" recursion and\n * no reliance on threading `signerOverride: null` through every transport\n * layer. The returned signing {@link Channel} is what callers hand to\n * `LinkRpcConnection`; the {@link PrincipalWithStore} is returned alongside\n * for caps / per-identity storage / nodeId.\n */\n public static async fromChannelWithManagedPrincipal<TInCtx>(\n channel: Channel<TInCtx, unknown>,\n config?: Omit<SigningSenderConfig, 'principal'>,\n ): Promise<ManagedSigningChannel<TInCtx>> {\n const principal = await createManagedPrincipal(channel.sender);\n const signing = SigningSender.wrapChannel(channel, { ...config, principal });\n return { channel: signing, principal };\n }\n\n /**\n * Convenience over {@link fromChannelWithManagedPrincipal}: build the\n * unsigned {@link JsonRpcChannel} from `transport` first. The common entry\n * point for app hosts / services that own a raw {@link IMessageTransport}.\n */\n public static fromTransportWithManagedPrincipal(\n transport: IMessageTransport,\n config?: Omit<SigningSenderConfig, 'principal'>,\n ): Promise<ManagedSigningChannel<undefined>> {\n return SigningSender.fromChannelWithManagedPrincipal(JsonRpcChannel.create(transport), config);\n }\n\n constructor(\n private readonly _inner: IRequestSender<unknown>,\n private readonly _config: SigningSenderConfig,\n ) { }\n\n public async sendRequest(method: string, params: JsonValue | undefined, opts?: SendOpts<SigningCallCtx>): Promise<JsonValue> {\n const out: PreparedOutboundCall = await this._prepareOutbound(method, params, opts);\n return this._inner.sendRequest(out.method, out.params);\n }\n\n public async sendNotification(\n method: string,\n params: JsonValue | undefined,\n opts?: SendOpts<SigningCallCtx>,\n ): Promise<void> {\n const out: PreparedOutboundCall = await this._prepareOutbound(method, params, opts);\n await this._inner.sendNotification(out.method, out.params);\n }\n\n public sendRequestWithStream(\n method: string,\n params: JsonValue | undefined,\n opts?: StreamSendOpts<SigningCallCtx>,\n ): RawStreamingCall {\n const id$ = this._prepareOutbound(method, params, opts);\n // Result + stream send proxy. We can't allocate the wire id\n // synchronously when signing is async, so the inner call is\n // started after the sign completes. `requestId` is exposed as\n // a placeholder that flips to the real id once known; callers\n // who need synchronous correlation should not stream against a\n // signing sender, or should `await` the underlying inner call.\n let realCall: RawStreamingCall | undefined;\n let queuedSends: JsonValue[] | undefined = [];\n let resolveResult!: (v: JsonValue) => void;\n let rejectResult!: (e: Error) => void;\n const result = new Promise<JsonValue>((res, rej) => {\n resolveResult = res;\n rejectResult = rej;\n });\n let cancelled = false;\n let cancelReason: string | undefined;\n let disposedReason: string | undefined;\n id$.then((out) => {\n const inner = this._inner.sendRequestWithStream(out.method, out.params, opts);\n if (cancelled) {\n inner.cancel(cancelReason);\n }\n if (disposedReason !== undefined) {\n inner.dispose?.(disposedReason);\n }\n realCall = inner;\n inner.result.then(resolveResult, rejectResult);\n if (queuedSends && queuedSends.length > 0) {\n for (const p of queuedSends) void inner.send(p);\n }\n queuedSends = undefined;\n }).catch((err) => rejectResult(err instanceof Error ? err : new Error(String(err))));\n return {\n result,\n cancel: (reason) => {\n cancelled = true;\n cancelReason = reason;\n if (realCall) {\n realCall.cancel(reason);\n }\n },\n dispose: (reason = 'streaming request disposed') => {\n if (disposedReason !== undefined) return;\n disposedReason = reason;\n queuedSends = undefined;\n if (realCall) {\n realCall.dispose?.(reason);\n }\n rejectResult(new Error(reason));\n },\n send: async (payload) => {\n if (realCall) await realCall.send(payload);\n else queuedSends!.push(payload);\n },\n // The inner call (and its pinger) only exists after signing\n // completes; defer until then. Ordering: the `id$.then` that\n // assigns `realCall` is registered before this one, so it has\n // run by the time this continuation fires.\n ping: () => realCall ? realCall.ping() : id$.then(() => realCall!.ping()),\n };\n }\n\n public close(): void {\n this._inner.close();\n }\n\n private async _prepareOutbound(\n method: string,\n params: JsonValue | undefined,\n opts: SendOpts<SigningCallCtx> | undefined,\n ): Promise<PreparedOutboundCall> {\n const ctx = opts?.ctx;\n const signer = this._resolveSigner(ctx);\n if (signer === undefined) {\n return { method, params };\n }\n\n const baseIntent: BaseCallIntent = {\n method,\n params,\n ...(opts?.interfaceHash !== undefined ? { interfaceHash: opts.interfaceHash } : {}),\n };\n const coords = this._createSigningCoordinates();\n const { intent, capabilities } = await this._resolveIntentAndCapabilities(baseIntent, signer, coords, ctx);\n return this._signPreparedCall(intent, signer, coords.nonceBytes, capabilities);\n }\n\n // Per-call override beats persistent principal. `null` means explicit unsigned call.\n private _resolveSigner(ctx: SigningCallCtx | undefined): SigningIdentity | undefined {\n return ctx?.signerOverride === null\n ? undefined\n : ctx?.signerOverride ?? this._config.principal?.identity;\n }\n\n private _createSigningCoordinates(): SigningCoordinates {\n const nonceBytes = _randomNonceBytes();\n return {\n nonceBytes,\n nonce: bytesToBase64Url(nonceBytes),\n signedAtMs: Date.now(),\n };\n }\n\n private async _resolveIntentAndCapabilities(\n baseIntent: BaseCallIntent,\n signer: SigningIdentity,\n coords: SigningCoordinates,\n ctx: SigningCallCtx | undefined,\n ): Promise<{\n intent: NegotiatedCallIntent;\n capabilities: readonly SignedCapability[];\n }> {\n const intent: NegotiatedCallIntent = {\n method: baseIntent.method,\n params: baseIntent.params,\n ...(baseIntent.interfaceHash !== undefined ? { interfaceHash: baseIntent.interfaceHash } : {}),\n signedAtMs: coords.signedAtMs,\n };\n\n // Resolve the caps to attach. A per-call override wins outright;\n // otherwise take the principal's persistent caps and append any\n // one-shot caps the side-policy has staged for this call.\n let capabilities: readonly SignedCapability[];\n if (ctx?.capsOverride !== undefined) {\n capabilities = ctx.capsOverride;\n } else {\n const persistent = this._config.principal?.capBag.capabilities ?? [];\n const oneShot = this._config.oneShotCaps?.take() ?? [];\n capabilities = oneShot.length > 0 ? [...persistent, ...oneShot] : persistent;\n\n const provider = this._config.capProvider;\n if (provider) {\n const provided = await provider({\n method: intent.method,\n params: intent.params,\n signer: signer.publicSigningIdentity.principal,\n nonce: coords.nonce,\n signedAtMs: intent.signedAtMs,\n ...(intent.interfaceHash !== undefined ? { interfaceHash: intent.interfaceHash } : {}),\n });\n if (provided.method !== undefined) intent.method = provided.method;\n if (provided.params !== undefined) intent.params = provided.params;\n if (provided.interfaceHash !== undefined) intent.interfaceHash = provided.interfaceHash;\n if (provided.signedAtMs !== undefined) intent.signedAtMs = provided.signedAtMs;\n if (provided.capabilities !== undefined) capabilities = provided.capabilities;\n }\n }\n\n return { intent, capabilities };\n }\n\n private async _signPreparedCall(\n intent: NegotiatedCallIntent,\n signer: SigningIdentity,\n nonceBytes: Uint8Array,\n capabilities: readonly SignedCapability[],\n ): Promise<PreparedOutboundCall> {\n const signed = await signRpcCall({\n method: intent.method,\n params: intent.params,\n signingIdentity: signer,\n nonce: nonceBytes,\n nowMs: intent.signedAtMs,\n ...(intent.interfaceHash !== undefined ? { interfaceHash: intent.interfaceHash } : {}),\n });\n const outboundParams = capabilities.length > 0 ?\n attachCapabilities(signed.wireParams, capabilities) :\n signed.wireParams;\n return { method: intent.method, params: outboundParams as unknown as JsonValue };\n }\n}\n\nfunction _randomNonceBytes(): Uint8Array {\n const out = new Uint8Array(16);\n crypto.getRandomValues(out);\n return out;\n}\n","/**\n * Capability **semantics**: the authorization layer over the pure\n * protocol syntax in `../protocol/capability`. This module answers the\n * single question \"may this concrete signed call proceed?\" via\n * {@link permits}, built from the chain verifier {@link verifyChain} and\n * the membership predicate {@link capabilityPermits}. Signing lives here\n * too, since it needs a {@link SigningIdentity}.\n */\n\nimport {\n bytesToBase64Url,\n resolveSigningKey,\n type PrincipalId,\n} from \"../crypto/cryptoProvider\";\nimport {\n Call,\n capabilityPermits,\n hasSignedCapabilityShape,\n type Capability, type ParamMatcher, type Permission, type SignedCapability\n} from \"../protocol/capability\";\nimport { signObject, signedHash, verifyObject, readSignature } from \"./signedObject\";\nimport type { InterfaceDefinition, MemberMap } from \"../connection/interfaceDefinition\";\nimport type { RequestType } from \"../schema/memberTypes\";\nimport type { PublicSigningIdentity, SigningIdentity } from \"./identity\";\n\n// Re-export protocol-level types and pure helpers so existing consumers\n// keep working through `@hediet/linkrpc`'s identity barrel.\nexport {\n permissionMatchesTarget,\n matchParams,\n type Call,\n type CallBind,\n type CallTarget,\n type Capability,\n type ParamMatcher,\n type Pattern,\n type Permission,\n type SignedCapability,\n type TargetPattern,\n} from \"../protocol/capability\";\nexport { type Base64Sha256, signedHash } from \"../protocol/signedObject\";\n\n\n// ---- freshness -----------------------------------------------------------\n\n/**\n * Pure freshness check for a single capability link: `true` when the cap never\n * expires, or its `expiresAtMs` is still in the future at `now + marginMs`.\n *\n * Mirrors the gate's expiry rule in {@link verifyChain}'s link check\n * (`expiresAtMs < nowMs` ⇒ expired) so a producer can decide, *before signing*,\n * whether to re-acquire a cap rather than attach one the gate will reject as\n * `expired`. The `marginMs` safety window absorbs in-flight transit time and\n * client/hub clock skew — pass the call's `signedAtMs` as `now` so the check\n * evaluates expiry against the same instant baked into the envelope.\n *\n * This checks ONE link. Effective authority requires every link in a\n * delegation chain to be unexpired, so a producer attaching a bag should apply\n * this to every cap it would attach (see {@link capBagFreshAt}).\n */\nexport function capabilityFreshAt(\n cap: Capability,\n now: number,\n marginMs = 0,\n): boolean {\n return cap.expiresAtMs === undefined || cap.expiresAtMs > now + marginMs;\n}\n\n/**\n * Freshness over a whole presented bag: `true` only when every cap is fresh at\n * `now + marginMs` (see {@link capabilityFreshAt}). An empty bag is trivially\n * fresh. Use this at the cap-production point to decide whether to re-acquire.\n */\nexport function capBagFreshAt(\n caps: readonly Capability[],\n now: number,\n marginMs = 0,\n): boolean {\n return caps.every((cap) => capabilityFreshAt(cap, now, marginMs));\n}\n\n\n// ---- chain verification --------------------------------------------------\n\n/** Result of {@link verifyChain}; not part of the public API ({@link permits} is). */\ntype ChainResult =\n | { ok: true; rootIssuer: PrincipalId; leafNonce: string }\n | { ok: false; reason: string; verifiedRootIssuer?: PrincipalId };\n\ntype LinkResult =\n | { ok: true; rootIssuer: PrincipalId }\n | { ok: false; reason: string };\n\n/** Options for {@link verifyChain}; not part of the public API ({@link permits} is). */\ninterface VerifyChainOptions {\n /** The leaf cap's `audience` must equal this. Usually the signer of the request. */\n expectedAudience: PrincipalId;\n /** Unix milliseconds. */\n nowMs: number;\n /**\n * Optional terminal trust check. A chain only succeeds if its root issuer\n * passes; when it does not, the verifier keeps trying other presented\n * leaves. This lets a caller present several capabilities (e.g. a\n * self-issued one and an admin-issued one) and have the trusted chain win.\n */\n acceptRoot?: (rootIssuer: PrincipalId) => boolean;\n /** Hard cap on recursion to bound work and prevent cycles. */\n maxDepth?: number;\n}\n\n/**\n * Verify that some delegation chain among the presented `capabilities`\n * authorizes `call`, and return the issuer at its top (the trust anchor the\n * caller then judges). The bag's topology is inferred: any capability whose\n * `audience` is the caller is tried as a leaf, and parents are resolved out\n * of the same bag by content hash (`parentHash`).\n *\n * Each link must be authentic (signature), unexpired, and bound to the next\n * link's issuer; the **leaf** must grant `invoke` for the call and every\n * **parent** must grant `delegate`. Effective authority is therefore the\n * intersection over the chain — a delegate can only narrow.\n *\n * @internal Chain *authenticity* only — it makes **no** trust decision. The\n * public authorization entry point is {@link permits}, which layers the\n * accepted-root policy on top.\n */\nasync function verifyChain(\n capabilities: readonly SignedCapability[],\n call: Call,\n opts: VerifyChainOptions,\n): Promise<ChainResult> {\n // Content-address the bag once; parents resolve out of it by hash.\n const byHash = new Map<string, SignedCapability>();\n for (const c of capabilities) byHash.set(signedHash(\"capability\", c), c);\n const resolveParent = (h: string) => byHash.get(h);\n const maxDepth = opts.maxDepth ?? 16;\n\n // Try each presented capability as a leaf. The reason we surface on total\n // failure prefers a cap the caller actually holds (audience === caller),\n // so a single rejected cap reports *its* fault rather than \"no leaf\".\n let leafReason: string | undefined;\n let anyReason = \"no presented capability addresses this call\";\n let unacceptedRoot: PrincipalId | undefined;\n for (const leaf of capabilities) {\n const r = await _verifyLink(leaf, call, opts.expectedAudience, opts.nowMs, maxDepth, true, resolveParent);\n if (!r.ok) {\n anyReason = r.reason;\n if (leaf.audience === opts.expectedAudience) leafReason = r.reason;\n continue;\n }\n if (opts.acceptRoot !== undefined && !opts.acceptRoot(r.rootIssuer)) {\n unacceptedRoot = r.rootIssuer;\n continue;\n }\n return { ok: true, rootIssuer: r.rootIssuer, leafNonce: leaf.nonce };\n }\n if (unacceptedRoot !== undefined) {\n return { ok: false, reason: \"no chain roots at an accepted issuer\", verifiedRootIssuer: unacceptedRoot };\n }\n return { ok: false, reason: leafReason ?? anyReason };\n}\n\nasync function _verifyLink(\n link: SignedCapability,\n call: Call,\n expectedAudience: PrincipalId,\n nowMs: number,\n depthLeft: number,\n isLeaf: boolean,\n resolveParent: (parentHash: string) => SignedCapability | undefined,\n): Promise<LinkResult> {\n if (depthLeft <= 0) return { ok: false, reason: \"chain too deep\" };\n\n if (link.audience !== expectedAudience) {\n return { ok: false, reason: `audience mismatch (expected ${expectedAudience}, got ${link.audience})` };\n }\n if (link.expiresAtMs !== undefined && link.expiresAtMs < nowMs) {\n return { ok: false, reason: \"expired\" };\n }\n const permitted = capabilityPermits(call, link, isLeaf ? \"invoke\" : \"delegate\");\n if (!permitted.ok) {\n return { ok: false, reason: permitted.reason };\n }\n\n let issuerKey: Uint8Array;\n const resolved = resolveSigningKey({\n principal: link.issuer,\n keyId: readSignature(link, \"capability\")?.keyId ?? \"\",\n timeMs: nowMs,\n });\n if (resolved === undefined) {\n return { ok: false, reason: \"unresolvable issuer key\" };\n }\n issuerKey = resolved.publicKey;\n const sigOk = await verifyObject(\"capability\", link, issuerKey);\n if (!sigOk) return { ok: false, reason: \"bad signature\" };\n\n if (link.parentHash === undefined) {\n return { ok: true, rootIssuer: link.issuer };\n }\n\n const parent = resolveParent(link.parentHash);\n if (parent === undefined) {\n return { ok: false, reason: \"parent capability not presented\" };\n }\n if (signedHash(\"capability\", parent) !== link.parentHash) {\n return { ok: false, reason: \"parent hash mismatch\" };\n }\n return _verifyLink(parent, call, link.issuer, nowMs, depthLeft - 1, false, resolveParent);\n}\n\n// ---- authorization: the single entry point -------------------------------\n\nexport type PermitResult =\n | { ok: true; capabilityNonce: string; rootIssuer: PrincipalId }\n | { ok: false; reason: string };\n\n/**\n * A trust anchor accepted as a capability-chain root, plus whether it may be\n * named in authorization error messages.\n */\nexport interface AcceptedRootIssuer {\n /** The principal accepted as a chain root for the queried service. */\n principal: PrincipalId;\n /**\n * Whether this issuer may be disclosed in `permits` rejection reasons.\n * Public anchors (e.g. a hub's well-known admin identity) are surfaced to\n * help diagnose \"wrong root\" failures; private ones are withheld so the\n * error never leaks the set of trusted issuers.\n */\n isPublic: boolean;\n}\n\n/**\n * **The** authorization predicate. A call is permitted iff some presented\n * capability (1) addresses the call, (2) has a genuine, well-delegated\n * chain whose leaf audience is the caller (`call.signer`), and (3) roots\n * at an issuer the verifier accepts **for the call's service**.\n *\n * Pure: it reports the verdict (and the `capabilityNonce` / `rootIssuer`\n * for audit) but performs no consumption. Replay is the caller's job — the\n * gate dedups `call.nonce`, so `callBind` grants are single-use for free.\n *\n * `acceptedRootIssuers` is consulted with the call's `serviceId` and returns\n * the accepted {@link AcceptedRootIssuer} anchors; an empty result rejects\n * every capability (fail closed) — trust is the verifier's, never the\n * token's. Anchors flagged `isPublic` are named in the rejection reason when\n * a chain roots at an unaccepted issuer.\n */\nexport async function permits(\n call: Call,\n capabilities: readonly SignedCapability[],\n acceptedRootIssuers: (serviceId: string) => readonly AcceptedRootIssuer[],\n nowMs: number,\n opts?: { maxDepth?: number },\n): Promise<PermitResult> {\n if (capabilities.length === 0) {\n return { ok: false, reason: \"no capabilities were presented with this call\" };\n }\n if (!capabilities.every(hasSignedCapabilityShape)) {\n return { ok: false, reason: \"malformed capability\" };\n }\n\n const accepted = acceptedRootIssuers(call.target.serviceId);\n const acceptedIds = new Set(accepted.map((a) => a.principal));\n const chain = await verifyChain(capabilities, call, {\n expectedAudience: call.signer,\n nowMs,\n acceptRoot: (rootIssuer) => acceptedIds.has(rootIssuer),\n ...(opts?.maxDepth !== undefined ? { maxDepth: opts.maxDepth } : {}),\n });\n if (chain.ok) {\n return { ok: true, capabilityNonce: chain.leafNonce, rootIssuer: chain.rootIssuer };\n }\n if (chain.verifiedRootIssuer !== undefined) {\n return { ok: false, reason: _rootIssuerRejectedReason(call.target.serviceId, chain.verifiedRootIssuer, accepted) };\n }\n return { ok: false, reason: chain.reason };\n}\n\n/**\n * Reason string for a chain that verified but rooted at an unaccepted issuer.\n * Names the (caller-owned) `rootIssuer` it actually rooted at, plus the\n * `isPublic` accepted anchors to point the caller at the right root.\n */\nfunction _rootIssuerRejectedReason(\n serviceId: string,\n rootIssuer: PrincipalId,\n accepted: readonly AcceptedRootIssuer[],\n): string {\n const head = `capability root issuer ${rootIssuer} is not accepted for service \"${serviceId}\"`;\n if (accepted.length === 0) {\n return `${head} (no root issuers are accepted for this service)`;\n }\n const publicIds = accepted.filter((a) => a.isPublic).map((a) => a.principal);\n if (publicIds.length === 0) {\n return head;\n }\n return `${head}; accepted root issuer(s): ${publicIds.join(\", \")}`;\n}\n\n// ---- signing ------------------------------------------------------------\n\n/**\n * Sign a `Capability` with a {@link SigningIdentity}. The private key never\n * leaves the identity. The result verifies via {@link verifyChain}.\n */\nexport async function signCapability(capability: Capability, issuer: SigningIdentity): Promise<SignedCapability> {\n return await signObject(\"capability\", capability, issuer);\n}\n\nexport interface IssueCapabilityOptions {\n /** Identity allowed to present the capability. */\n readonly audience: PublicSigningIdentity;\n /** Authority granted to the audience. */\n readonly permissions: readonly Permission[];\n /** Optional expiration time as Unix milliseconds. */\n readonly expiresAtMs?: number;\n /** Optional parent whose authority this capability narrows. */\n readonly parent?: SignedCapability;\n}\n\n/**\n * Issue and sign a capability, deriving its issuer, nonce, and optional parent\n * hash. The result is plain JSON data and survives a JSON stringify/parse\n * round-trip without reconstruction.\n */\nexport async function issueCapability(\n issuer: SigningIdentity,\n options: IssueCapabilityOptions,\n): Promise<SignedCapability> {\n const capability: Capability = {\n issuer: issuer.publicSigningIdentity.principal,\n audience: options.audience.principal,\n permissions: [...options.permissions],\n nonce: _randomCapabilityNonce(),\n ...(options.expiresAtMs !== undefined ? { expiresAtMs: options.expiresAtMs } : {}),\n ...(options.parent !== undefined\n ? { parentHash: signedHash(\"capability\", options.parent) }\n : {}),\n };\n return signCapability(capability, issuer);\n}\n\nexport type ParamMatcherFor<T> =\n | { exact: T }\n | { enum: T[] }\n | { any: true }\n | (T extends string ? { prefix: string } : never)\n | (T extends readonly string[] ? { subsetOf: string[] } : never);\n\n/** Type-safe top-level parameter matchers for one interface member. */\nexport type ParamMatchers<T> = T extends Record<string, unknown>\n ? { [K in keyof T]: ParamMatcherFor<Exclude<T[K], undefined>> }\n : never;\n\ntype RequestMemberName<TMembers extends MemberMap> = {\n [K in keyof TMembers]: TMembers[K] extends RequestType<any, any, any, any, any> ? K : never;\n}[keyof TMembers] & string;\n\ntype RequestParams<TMember> = TMember extends RequestType<infer TParams, any, any, any, any>\n ? TParams\n : never;\n\n/** Match a string parameter by prefix. */\nexport function prefix(value: string): { prefix: string } {\n return { prefix: value };\n}\n\n/**\n * Build an invoke permission from a typed interface member. The helper derives\n * the interface id and schema hash and type-checks parameter matcher names and\n * values against the member's params.\n */\nexport function invoke<\n TMembers extends MemberMap,\n TMember extends RequestMemberName<TMembers>,\n>(\n serviceId: string,\n iface: InterfaceDefinition<TMembers>,\n member: TMember,\n params?: ParamMatchers<RequestParams<TMembers[TMember]>>,\n): Permission {\n return {\n target: {\n serviceId: { exact: serviceId },\n interfaceId: { exact: iface.info.id },\n interfaceHash: iface.schemaHash,\n members: [{ exact: member }],\n },\n canInvoke: true,\n ...(params !== undefined\n ? { params: params as Record<string, ParamMatcher> }\n : {}),\n };\n}\n\nfunction _randomCapabilityNonce(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return bytesToBase64Url(bytes);\n}\n","import type { PrincipalId } from \"../crypto/cryptoProvider\";\nimport type { SigningIdentity } from \"./identity\";\nimport {\n type Call,\n type CallTarget,\n type SignedCapability,\n} from \"./capability\";\nimport type { Base64Sha256 } from \"../protocol/signedObject\";\nimport type { JsonValue } from \"../protocol/jsonValue\";\nimport {\n HUBRPC_META_KEY,\n HUBRPC_SIGNATURE_KEY,\n HUBRPC_UNSIGNED_KEY,\n attachCapabilities,\n signRpcCall,\n verifyRpcCall,\n} from \"./signedRpcEnvelope\";\nimport type { CallMeta } from \"../protocol/linkRpcEnvelope\";\n\nexport { attachCapabilities };\n\n/** Plain JSON object with optional values — the wire shape JSON-RPC params take. */\nexport type JsonObject = { [key: string]: JsonValue | undefined };\n\n// ---- signing -----------------------------------------------------------\n\nexport interface SignParamsOptions {\n method: string;\n /** Caller-supplied params (without identity envelopes). Must be an object or undefined. */\n params: JsonObject | undefined;\n /** Identity that produces the signature. */\n signingIdentity: SigningIdentity;\n /**\n * Caps to attach. They are NOT signed — they ride in `$hubrpcUnsigned`.\n */\n capabilities?: readonly SignedCapability[];\n /** Unix milliseconds; defaults to `Date.now()`. */\n nowMs?: number;\n /** Override nonce (testing); otherwise 16 random bytes. */\n nonce?: Uint8Array;\n /** Stamped into the signed envelope as `interfaceHash`. */\n interfaceHash?: string;\n}\n\n/**\n * Returns a wire-form params object carrying the `$hubrpc` envelope, the\n * `call` signature under `$hubrpcSignature`, and (optionally) capabilities\n * under `$hubrpcUnsigned`.\n */\nexport async function signParams(opts: SignParamsOptions): Promise<JsonObject> {\n if (opts.params !== undefined\n && (typeof opts.params !== \"object\" || Array.isArray(opts.params))) {\n throw new Error(\"signParams: params must be an object or undefined\");\n }\n const signed = await signRpcCall({\n method: opts.method,\n params: (opts.params ?? undefined) as JsonValue | undefined,\n signingIdentity: opts.signingIdentity,\n ...(opts.nowMs !== undefined ? { nowMs: opts.nowMs } : {}),\n ...(opts.nonce !== undefined ? { nonce: opts.nonce } : {}),\n ...(opts.interfaceHash !== undefined ? { interfaceHash: opts.interfaceHash } : {}),\n });\n const wireParams = opts.capabilities && opts.capabilities.length > 0\n ? attachCapabilities(signed.wireParams, opts.capabilities)\n : signed.wireParams;\n return wireParams as unknown as JsonObject;\n}\n\n// ---- verification ------------------------------------------------------\n\nexport interface VerifyCallOptions {\n method: string;\n /** Raw params as received on the wire. Carries `$hubrpc` + `$hubrpcSignature` when signed. */\n params: unknown;\n /** Decode the method string into the call's target address. */\n parseMethod: (method: string) => CallTarget;\n nowMs?: number;\n /** Max clock skew in milliseconds. Default 300000 (±5min). */\n maxSkewMs?: number;\n /** Reject if no capability is presented. */\n requireCapability?: boolean;\n}\n\nexport type VerifyResult =\n | {\n ok: true;\n signer: PrincipalId;\n /**\n * The resolved, authenticated call — the unit `permits()` judges.\n * Authorization is intentionally NOT done here; the gate owns it\n * (and the replay ledger).\n */\n call: Call;\n /** Params with the reserved keys stripped — pass this to the actual handler. */\n strippedParams: Record<string, unknown> | undefined;\n /** Leaf + parent capabilities to hand to `permits()`. */\n capabilities: SignedCapability[];\n /** Per-call nonce extracted from the envelope (for replay-protection ledgers). */\n nonce: string;\n /** The call's content hash — input to `callBind.payloadHash`. */\n callHash: Base64Sha256;\n /** The `$hubrpc` envelope as received. */\n callMeta: CallMeta;\n /** Schema-version assertion the caller stamped. */\n interfaceHash: string | undefined;\n }\n | {\n ok: false;\n /**\n * Failure category:\n * - `\"capability\"` — the call shape was fine; the caller needs to\n * acquire (or present) a capability. Hub should surface this as\n * `permissionRequired` so consumers know to negotiate access.\n * - `\"envelope\"` — anything else (missing/bad signature, replay,\n * malformed nonce, etc). Hub should surface as `invalidRequest`.\n */\n kind: \"capability\" | \"envelope\";\n reason: string;\n };\n\nexport async function verifyCall(opts: VerifyCallOptions): Promise<VerifyResult> {\n const res = await verifyRpcCall({\n wireMethod: opts.method,\n wireParams: opts.params,\n ...(opts.nowMs !== undefined ? { nowMs: opts.nowMs } : {}),\n ...(opts.maxSkewMs !== undefined ? { maxSkewMs: opts.maxSkewMs } : {}),\n requireSigned: opts.requireCapability === true,\n });\n if (!res.ok) return { ok: false, kind: \"envelope\", reason: res.reason };\n if (!res.identity) {\n return { ok: false, kind: \"envelope\", reason: \"missing identity envelope\" };\n }\n const { identity } = res;\n\n if (opts.requireCapability && identity.capabilities.length === 0) {\n return { ok: false, kind: \"capability\", reason: \"capability required but none provided\" };\n }\n\n const params = res.params;\n let strippedParams: Record<string, unknown> | undefined;\n if (params === undefined || params === null) {\n strippedParams = undefined;\n } else if (typeof params === \"object\" && !Array.isArray(params)) {\n // Preserve `{}` — a handler whose schema is `z.object({...})` (no\n // required fields) accepts `{}` but rejects `undefined`.\n strippedParams = params as Record<string, unknown>;\n } else {\n // Non-object params: callers expect Record<string, unknown> | undefined.\n strippedParams = undefined;\n }\n\n const target = opts.parseMethod(opts.method);\n if (identity.callMeta.interfaceHash !== undefined) {\n target.interfaceHash = identity.callMeta.interfaceHash;\n }\n const call: Call = {\n target,\n params,\n nonce: identity.callMeta.nonce,\n signedAtMs: identity.callMeta.signedAtMs,\n signer: identity.signer,\n callHash: identity.callHash,\n };\n\n return {\n ok: true,\n signer: identity.signer,\n call,\n strippedParams,\n capabilities: identity.capabilities,\n nonce: identity.callMeta.nonce,\n callHash: identity.callHash,\n callMeta: identity.callMeta,\n interfaceHash: identity.callMeta.interfaceHash,\n };\n}\n\n// Re-exported so callers can spot signed calls without going through `verifyCall`.\nexport { HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY };\n","import * as crypto from '../crypto/crypto';\nimport { principalForPublicKey } from '../crypto/cryptoProvider';\nimport { CapBag } from './capBag';\nimport { KeypairIdentity, KeypairSigningIdentity } from './identity';\nimport { Principal } from './signingSender';\n\nexport interface SeededPrincipalOptions {\n /** Numeric seed; the same value always yields the same identity / principal. */\n readonly seed: number;\n}\n\n/** Derive a domain-separated 32-byte seed from the numeric seed. */\nfunction _seedBytes(domain: string, seed: number): Uint8Array {\n return crypto.sha256(new TextEncoder().encode(`${domain}:${seed}`));\n}\n\n/**\n * Build a **random**, in-memory {@link Principal}: a fresh Ed25519 signing\n * identity + X25519 wrapping key, paired with an empty memory-only\n * {@link CapBag}. Full-entropy (unlike {@link createSeededMemoryPrincipal}), so\n * it is safe to sign trusted calls — e.g. an in-process \"agent\" identity a hub\n * admin delegates read authority to (via a minted capability) for directory\n * discovery. The identity is ephemeral: it vanishes with the process.\n */\nexport async function createMemoryPrincipal(): Promise<Principal> {\n const ed = await crypto.generateKeypair();\n const wrap = await crypto.generateX25519Keypair();\n const identity = new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap);\n const capBag = await CapBag.load();\n return new Principal(identity, capBag);\n}\n\n/**\n * Build a deterministic {@link Principal} from a numeric seed: a reproducible\n * Ed25519 signing identity (so the nodeId is stable across runs) plus a matching\n * X25519 wrapping key, paired with an empty, memory-only {@link CapBag}.\n *\n * For tests and reproducible local setups ONLY — the key material is derived\n * from a low-entropy seed and must never be used to sign anything trusted.\n */\nexport async function createSeededMemoryPrincipal(opts: SeededPrincipalOptions): Promise<Principal> {\n const ed = await crypto.keypairFromSeed(_seedBytes('linkrpc.seed.ed25519', opts.seed));\n const wrap = await crypto.x25519KeypairFromSeed(_seedBytes('linkrpc.seed.x25519', opts.seed));\n const identity = new KeypairIdentity(principalForPublicKey(ed.publicKey), ed.privateKey, wrap);\n const capBag = await CapBag.load();\n return new Principal(identity, capBag);\n}\n\n/**\n * Derive a deterministic {@link KeypairSigningIdentity} from a numeric seed: a\n * reproducible Ed25519 signing identity (so the nodeId is stable across runs),\n * with no wrapping key. Use it where only signing/issuing is needed — e.g. a\n * hub admin `issuer` that mints capabilities in tests.\n *\n * For tests and reproducible local setups ONLY — the key material is derived\n * from a low-entropy seed and must never be used to sign anything trusted.\n */\nexport async function createSeededSigningIdentity(opts: SeededPrincipalOptions): Promise<KeypairSigningIdentity> {\n const ed = await crypto.keypairFromSeed(_seedBytes('linkrpc.seed.ed25519', opts.seed));\n return KeypairSigningIdentity.fromKeypair(ed);\n}\n"],"x_google_ignoreList":[25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,SAAgB,aACZ,KACA,KACA,aAAyB,CAAC,GACnB;CACP,OAAO,OAAO,KAAK,KAAK,4BAAY,IAAI,IAAI,CAAC;AACjD;AAMA,SAAS,OAAO,KAAwB,KAAwB,GAAe,MAA4B;CAEvG,IAAI,QAAQ,MAAM,OAAO;CACzB,IAAI,QAAQ,OAAO,OAAO;CAC1B,IAAI,QAAQ,OAAO,OAAO,UAAU,KAAK,GAAG,IAAI;CAChD,IAAI,QAAQ,MAAM,OAAO;CAGzB,IAAI,OAAO,GAAG,GAAG;EACb,MAAM,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO,GAAG;EACrC,IAAI,KAAK,IAAI,CAAC,GAAG,OAAO;EACxB,MAAM,WAAW,YAAY,KAAK,CAAC;EACnC,IAAI,CAAC,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