keymaster-connect 0.1.0 → 0.1.2
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 +6 -4
- package/dist/{chunk-AAVOIS5Q.js → chunk-W2TNWBLP.js} +2 -8
- package/dist/chunk-W2TNWBLP.js.map +1 -0
- package/dist/index.d.ts +22 -49
- package/dist/index.js +120 -110
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +20 -45
- package/dist/protocol.js +1 -1
- package/dist/server.d.ts +7 -4
- package/dist/server.js +16 -13
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-AAVOIS5Q.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/binary.ts","../src/client.ts"],"names":[],"mappings":";;;;AAGO,SAAS,MAAA,CAAO,OAAsC,IAAA,EAA4B;AACvF,EAAA,MAAM,IAAA,GAAO,KAAA,YAAiB,WAAA,GAC1B,IAAI,WAAW,KAAK,CAAA,GACpB,IAAI,UAAA,CAAW,KAAA,CAAM,MAAA,EAAQ,KAAA,CAAM,UAAA,EAAY,MAAM,UAAU,CAAA;AACnE,EAAA,MAAM,IAAA,GAAO,IAAI,UAAA,CAAW,IAAA,CAAK,UAAU,CAAA;AAC3C,EAAA,IAAA,CAAK,IAAI,IAAI,CAAA;AACb,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,QAAA;AAAA,IACP,OAAO,IAAA,CAAK,MAAA;AAAA,IACZ,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS;AAAC,GACzB;AACF;AAGO,SAAS,YAAY,KAAA,EAAgC;AAC1D,EAAA,IAAI,MAAM,KAAA,KAAU,QAAA,IAAY,EAAE,KAAA,CAAM,iBAAiB,WAAA,CAAA,EAAc;AACrE,IAAA,MAAM,IAAI,UAAU,kCAAkC,CAAA;AAAA,EACxD;AACA,EAAA,OAAO,IAAI,UAAA,CAAW,KAAA,CAA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MAAM,CAAC,CAAC,CAAA,CAAA;AACxG;AAEA,SAAS,cAAA,CAAe,OAAe,IAAA,EAAsB;AAC3D,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,IAAK,KAAA,IAAS,CAAA,EAAG,MAAM,IAAI,SAAA,CAAU,CAAA,EAAG,IAAI,CAAA,0BAAA,CAA4B,CAAA;AAClG,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,eAAe,KAAA,EAAwB;AAC9C,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,MAAA,KAAW,IAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,SAAS,YAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF;AAEA,SAAS,YAAA,CAAa,OAAgB,QAAA,EAA0B;AAC9D,EAAA,OAAO,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,OAAA,GAAU,MAAM,OAAA,GAAU,QAAA;AACnE","file":"index.js","sourcesContent":["import type { BinaryField } from \"./protocol.js\";\n\n/** Wraps bytes in the explicit binary field required by Connect V1. */\nexport function binary(bytes: ArrayBuffer | ArrayBufferView, mime?: string): BinaryField {\n const view = bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const copy = new Uint8Array(view.byteLength);\n copy.set(view);\n return {\n $type: \"binary\",\n bytes: copy.buffer,\n ...(mime ? { mime } : {})\n };\n}\n\n/** Returns an immutable byte copy of a Connect binary field. */\nexport function binaryBytes(field: BinaryField): Uint8Array {\n if (field.$type !== \"binary\" || !(field.bytes instanceof ArrayBuffer)) {\n throw new TypeError(\"Expected a Keymaster BinaryField\");\n }\n return new Uint8Array(field.bytes.slice(0));\n}\n\n/** Encodes UTF-8 text as a Connect binary field. */\nexport function binaryText(value: string, mime = \"text/plain;charset=utf-8\"): BinaryField {\n return binary(new TextEncoder().encode(value), mime);\n}\n\n/** Decodes a Connect binary field as UTF-8 text. */\nexport function binaryToText(field: BinaryField): string {\n return new TextDecoder().decode(binaryBytes(field));\n}\n","import {\n PROTOCOL_VERSION,\n validateNetworkIdentity, sameNetworkIdentity, type NetworkIdentity,\n type ChannelPublishParams,\n type ChannelPublishResult,\n type ChannelSubscriptionSetParams,\n type ChannelSubscriptionSetResult,\n type CipherDecryptParams,\n type CipherDecryptResult,\n type CipherEncryptParams,\n type CipherEncryptResult,\n type ConnectLaunchParams,\n type ConnectLaunchResult,\n type ConnectLoginParams,\n type ConnectLoginResult,\n type ConnectLogoutResult,\n type ConnectResumeResult,\n type ConnectResumeParams,\n type IdentityGetParams,\n type IdentityGetResult,\n type IntentSignParams,\n type IntentSignResult,\n type MethodParams,\n type MethodResult,\n type MsFileBlockReadParams,\n type MsFileReadResult,\n type MsFileSeedReadParams,\n type MsFileStatParams,\n type MsFileStatResult,\n type P2pkhTransferParams,\n type P2pkhTransferResult,\n type PaymentPayParams,\n type PaymentPayResult,\n type PaymentStatusParams,\n type PaymentStatusResult,\n type PaymentChannelRegisterParams,\n type PaymentChannelRegisterResult,\n type PriceGetParams,\n type PriceGetResult,\n type PriceSubscribeParams,\n type PriceSubscriptionResult,\n type ProtocolErrorCode,\n type ProtocolEventMessage,\n type ProtocolMethod,\n type ProtocolResultMessage,\n type StorageDeleteParams,\n type StorageDeleteResult,\n type StorageDirectoryParams,\n type StorageDirectoryResult,\n type StorageGetParams,\n type StorageGetResult,\n type StorageListParams,\n type StorageListResult,\n type StoragePutParams,\n type StoragePutResult,\n} from \"./protocol.js\";\n\n/** How the SDK obtains its Keymaster Session Window. */\nexport type KeymasterConnectMode = \"popup\" | \"appView\";\n\n/** Observable lifecycle of the browser transport. */\nexport type KeymasterConnectState = \"idle\" | \"opening\" | \"connected\" | \"disconnected\";\n\n/** Failures produced by the browser transport before a protocol result exists. */\nexport type KeymasterTransportErrorCode =\n | \"popup_blocked\"\n | \"popup_closed\"\n | \"ready_timeout\"\n | \"request_timeout\"\n | \"send_failed\"\n | \"no_opener\"\n | \"appview_session_lost\"\n | \"client_closed\"\n | \"unsupported_protocol\";\n\n/** A browser transport failure. Protocol rejections use {@link KeymasterProtocolError}. */\nexport class KeymasterTransportError extends Error {\n constructor(\n public readonly code: KeymasterTransportErrorCode,\n message: string\n ) {\n super(message);\n this.name = \"KeymasterTransportError\";\n }\n}\n\n/** A structured rejection returned by Keymaster. */\nexport class KeymasterProtocolError extends Error {\n constructor(\n public readonly code: ProtocolErrorCode,\n message: string\n ) {\n super(message);\n this.name = \"KeymasterProtocolError\";\n }\n}\n\n/** Options applying to one protocol request. */\nexport interface KeymasterRequestOptions {\n /** Caller-controlled correlation id. A UUID is generated when omitted. */\n requestId?: string;\n /** Per-request timeout in milliseconds. */\n timeoutMs?: number;\n /** Aborting sends a best-effort protocol cancel and rejects the local promise. */\n signal?: AbortSignal;\n}\n\n/** Injectable browser primitives used by tests and embedded runtimes. */\nexport interface KeymasterBrowserEnvironment {\n open(url: string, target: string, features: string): Window | null;\n opener(): Window | null;\n addMessageListener(listener: (event: MessageEvent) => void): void;\n removeMessageListener(listener: (event: MessageEvent) => void): void;\n setTimeout(handler: () => void, timeoutMs: number): number;\n clearTimeout(timer: number): void;\n setInterval(handler: () => void, intervalMs: number): number;\n clearInterval(timer: number): void;\n randomUUID(): string;\n}\n\n/** Configuration for {@link KeymasterConnectClient}. */\nexport interface KeymasterConnectOptions {\n /** Exact Keymaster deployment origin supplied by the host application. */\n targetOrigin: string;\n /** `popup` for direct integrations; `appView` for apps launched by Keymaster. */\n mode?: KeymasterConnectMode;\n /** Session Window path relative to `targetOrigin`. */\n popupPath?: string;\n /** Browser window name reused by direct integrations. */\n popupName?: string;\n popupWidth?: number;\n popupHeight?: number;\n /** Maximum wait for a popup-mode `ready` message. Defaults to 30 seconds. */\n readyTimeoutMs?: number;\n /** Default request timeout. Defaults to two minutes. */\n requestTimeoutMs?: number;\n /** Session Window close detection interval. Defaults to 500ms. */\n closePollMs?: number;\n /** 接收当前精确订阅频道上的已验签 Channel 事件。 */\n onEvent?: (event: ProtocolEventMessage) => void;\n /** Receives transport lifecycle changes. */\n onStateChange?: (state: KeymasterConnectState) => void;\n /** Optional browser adapter, normally only supplied by tests. */\n environment?: KeymasterBrowserEnvironment;\n}\n\ninterface PendingRequest {\n method: ProtocolMethod;\n resolve(value: unknown): void;\n reject(reason: unknown): void;\n timer: number;\n signal?: AbortSignal;\n abortListener?: () => void;\n}\n\nconst DEFAULT_POPUP_PATH = \"/protocol/v1/popup\";\nconst DEFAULT_POPUP_NAME = \"keymaster-connect-v1\";\nconst DEFAULT_READY_TIMEOUT_MS = 30_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 120_000;\nconst DEFAULT_CLOSE_POLL_MS = 500;\n\n/**\n * Official browser client for Keymaster Connect V1.\n *\n * One client owns one reusable Session Window. It validates both the exact\n * message origin and the source window, correlates concurrent requests by id,\n * supports protocol cancellation through `AbortSignal`, and keeps persistent\n * Connect sessions separate from the window transport lifecycle.\n *\n * @example Direct popup login\n * ```ts\n * const keymaster = new KeymasterConnectClient({\n * targetOrigin: keymasterDeploymentOrigin\n * });\n *\n * const session = await keymaster.login({\n * text: \"Sign in to Example\",\n * claims: [\"profile.name\"]\n * });\n * ```\n *\n * @example appView launch\n * ```ts\n * const keymaster = new KeymasterConnectClient({\n * targetOrigin: sessionWindowOrigin,\n * mode: \"appView\"\n * });\n *\n * await keymaster.connect();\n * const session = await keymaster.launch({ launchToken, appIdentity });\n * ```\n *\n * @groupDescription Connect\n * Create, restore, revoke, or launch a persistent Connect session.\n *\n * @groupDescription Identity\n * Read signed identity claims or sign an application intent.\n *\n * @groupDescription Cipher\n * Encrypt and decrypt origin-bound application data.\n *\n * @groupDescription Transfer\n * Request a controlled BSV transfer.\n *\n * @groupDescription Channel\n * Publish JSON content and manage exact-channel subscriptions. Incoming\n * messages arrive as `channel.message_received` events.\n *\n * @groupDescription Price\n * Read the Keymaster display price (amount + unit) once, or subscribe to\n * `price.changed` pushes. The price is display-only reference data.\n *\n * @groupDescription Storage\n * Manage app-scoped directories and objects.\n *\n * @groupDescription Transport\n * Manage the Session Window and send lower-level protocol requests.\n */\nexport class KeymasterConnectClient {\n private identityValue: Readonly<NetworkIdentity> | null = null;\n private bindingId: string | null = null;\n\n /** Identity returned by the authenticated wallet, or null before establishment. */\n get networkIdentity(): Readonly<NetworkIdentity> | null { return this.identityValue; }\n private readonly targetOrigin: string;\n private readonly mode: KeymasterConnectMode;\n private readonly environment: KeymasterBrowserEnvironment;\n private readonly options: Required<Pick<KeymasterConnectOptions,\n \"popupPath\" | \"popupName\" | \"popupWidth\" | \"popupHeight\" |\n \"readyTimeoutMs\" | \"requestTimeoutMs\" | \"closePollMs\">> & KeymasterConnectOptions;\n private readonly pending = new Map<string, PendingRequest>();\n private stateValue: KeymasterConnectState = \"idle\";\n private sessionWindow: Window | null = null;\n private ownsSessionWindow = false;\n private listenerInstalled = false;\n private readyPromise: Promise<void> | null = null;\n private readyResolve: (() => void) | null = null;\n private readyReject: ((reason: unknown) => void) | null = null;\n private readyTimer: number | null = null;\n private closePoller: number | null = null;\n\n constructor(options: KeymasterConnectOptions) {\n if (\"networkIdentity\" in options) throw new TypeError(\"networkIdentity option has been removed; read identity from the connection result\");\n this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);\n this.mode = options.mode ?? \"popup\";\n this.options = {\n ...options,\n popupPath: options.popupPath ?? DEFAULT_POPUP_PATH,\n popupName: options.popupName ?? DEFAULT_POPUP_NAME,\n popupWidth: positiveNumber(options.popupWidth ?? 520, \"popupWidth\"),\n popupHeight: positiveNumber(options.popupHeight ?? 760, \"popupHeight\"),\n readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, \"readyTimeoutMs\"),\n requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, \"requestTimeoutMs\"),\n closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, \"closePollMs\")\n };\n this.environment = options.environment ?? createBrowserEnvironment();\n }\n\n /**\n * Current browser transport state.\n *\n * @group Transport\n */\n get state(): KeymasterConnectState {\n return this.stateValue;\n }\n\n /**\n * Establishes the browser transport.\n *\n * Popup mode opens the Session Window and waits for `ready`. appView mode\n * adopts `window.opener`, installs the listener, and sends the child `ready`\n * message without ever opening a fallback popup.\n *\n * @group Transport\n */\n connect(): Promise<void> {\n return this.mode === \"appView\" ? this.connectAppView() : this.connectPopup();\n }\n\n /**\n * Sends any public Connect method with compile-time parameter and result\n * inference.\n *\n * @group Transport\n */\n async request<M extends ProtocolMethod>(\n method: M,\n params: MethodParams<M>,\n options: KeymasterRequestOptions = {}\n ): Promise<MethodResult<M>> {\n if (options.signal?.aborted) throw abortReason(options.signal);\n if (!params || typeof params !== \"object\" || Array.isArray(params)) throw new TypeError(\"params must be an object\");\n for (const field of [\"walletPublicKeyHex\", \"networkIdentity\", \"bsvNetwork\", \"assetId\"]) {\n if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);\n }\n const establishing = [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(method);\n if (establishing && this.pending.size) throw new TypeError(\"Cannot establish a connection while requests are pending\");\n if (!establishing && !this.bindingId) throw new KeymasterProtocolError(\"invalid_request\", \"Login, resume or launch before making business requests\");\n if ([...this.pending.values()].some(request => [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(request.method))) throw new TypeError(\"Connection establishment is already pending\");\n await this.connect();\n if (establishing && this.pending.size) throw new TypeError(\"Cannot establish a connection while requests are pending\");\n if ([...this.pending.values()].some(request => [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(request.method))) throw new TypeError(\"Connection establishment is already pending\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n\n const target = this.sessionWindow;\n if (!target || isWindowClosed(target)) {\n throw new KeymasterTransportError(\"popup_closed\", \"Keymaster Session Window is closed\");\n }\n const requestId = options.requestId ?? this.environment.randomUUID();\n if (!requestId || this.pending.has(requestId)) {\n throw new TypeError(\"requestId must be non-empty and unique among pending requests\");\n }\n const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, \"timeoutMs\");\n\n return new Promise<MethodResult<M>>((resolve, reject) => {\n const timer = this.environment.setTimeout(() => {\n this.postCancel(requestId);\n this.deletePending(requestId);\n reject(new KeymasterTransportError(\"request_timeout\", `Keymaster request timed out: ${method}`));\n }, timeoutMs);\n const abortListener = options.signal\n ? () => {\n this.postCancel(requestId);\n this.deletePending(requestId);\n reject(abortReason(options.signal!));\n }\n : undefined;\n if (abortListener) options.signal!.addEventListener(\"abort\", abortListener, { once: true });\n this.pending.set(requestId, {\n method,\n resolve: (value) => resolve(value as MethodResult<M>),\n reject,\n timer,\n signal: options.signal,\n abortListener\n });\n\n try {\n target.postMessage({\n v: PROTOCOL_VERSION,\n type: \"request\",\n ...(!establishing ? { bindingId: this.bindingId } : {}),\n id: requestId,\n method,\n params\n }, this.targetOrigin);\n } catch (cause) {\n this.deletePending(requestId);\n reject(new KeymasterTransportError(\"send_failed\", errorMessage(cause, \"Unable to send Keymaster request\")));\n }\n });\n }\n\n /**\n * Calls `connect.login` to create a persistent Connect session.\n *\n * @group Connect\n */\n login(params: ConnectLoginParams, options?: KeymasterRequestOptions): Promise<ConnectLoginResult> {\n return this.request(\"connect.login\", params, options);\n }\n\n /**\n * Calls `connect.resume` to restore the unlock runtime for a persistent\n * session.\n *\n * @group Connect\n */\n resume(params: ConnectResumeParams = {}, options?: KeymasterRequestOptions): Promise<ConnectResumeResult> {\n return this.request(\"connect.resume\", params, options);\n }\n\n /**\n * Calls `connect.logout` to revoke a persistent Connect session.\n *\n * @group Connect\n */\n logout(options?: KeymasterRequestOptions): Promise<ConnectLogoutResult> {\n if (options !== undefined && (typeof options !== \"object\" || options === null)) return Promise.reject(new TypeError(\"logout no longer accepts a wallet public key\"));\n return this.request(\"connect.logout\", {}, options);\n }\n\n /**\n * Calls `connect.launch` to consume the one-time launch token of an appView\n * session.\n *\n * @group Connect\n */\n launch(params: ConnectLaunchParams, options?: KeymasterRequestOptions): Promise<ConnectLaunchResult> {\n if (this.mode !== \"appView\") {\n return Promise.reject(new TypeError(\"connect.launch requires mode: \\\"appView\\\"\"));\n }\n return this.request(\"connect.launch\", params, options);\n }\n\n /**\n * Calls `identity.get` to return signed identity claims for the session\n * owner.\n *\n * @group Identity\n */\n identityGet(params: IdentityGetParams, options?: KeymasterRequestOptions): Promise<IdentityGetResult> {\n return this.request(\"identity.get\", params, options);\n }\n\n /**\n * Calls `intent.sign` to sign caller-provided bytes with a human-readable\n * intent.\n *\n * @group Identity\n */\n intentSign(params: IntentSignParams, options?: KeymasterRequestOptions): Promise<IntentSignResult> {\n return this.request(\"intent.sign\", params, options);\n }\n\n /**\n * Calls `cipher.encrypt` to encrypt origin-bound application data.\n *\n * @group Cipher\n */\n cipherEncrypt(params: CipherEncryptParams, options?: KeymasterRequestOptions): Promise<CipherEncryptResult> {\n return this.request(\"cipher.encrypt\", params, options);\n }\n\n /**\n * Calls `cipher.decrypt` to decrypt data previously returned by\n * `cipher.encrypt`.\n *\n * @group Cipher\n */\n cipherDecrypt(params: CipherDecryptParams, options?: KeymasterRequestOptions): Promise<CipherDecryptResult> {\n return this.request(\"cipher.decrypt\", params, options);\n }\n\n /**\n * 请求 `payment.pay`;资金审批、选币与持久幂等由钱包负责。\n * Promise resolve 不等于已广播,应检查返回状态。\n *\n * @group Payment\n */\n paymentPay(params: PaymentPayParams, options?: KeymasterRequestOptions): Promise<PaymentPayResult> {\n return this.request(\"payment.pay\", params, options);\n }\n\n /** 按原业务 ID 只读查询付款状态,不自动重付或更换 ID。 */\n paymentStatus(params: PaymentStatusParams, options?: KeymasterRequestOptions): Promise<PaymentStatusResult> {\n return this.request(\"payment.status\", params, options);\n }\n\n /**\n * @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。\n * @group Transfer\n */\n p2pkhTransfer(params: P2pkhTransferParams, options?: KeymasterRequestOptions): Promise<P2pkhTransferResult> {\n return this.request(\"p2pkh.transfer\", params, options);\n }\n\n /** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */\n registerPaymentChannel(params: PaymentChannelRegisterParams, options?: KeymasterRequestOptions): Promise<PaymentChannelRegisterResult> {\n return this.request(\"payment.channel.register\", params, options);\n }\n\n /**\n * 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。\n *\n * @group Channel\n */\n channelPublish(\n params: ChannelPublishParams,\n options?: KeymasterRequestOptions\n ): Promise<ChannelPublishResult> {\n return this.request(\"channel.publish\", params, options);\n }\n\n /**\n * 替换当前 Connect caller 的精确频道订阅集合;传空数组表示释放。\n *\n * @group Channel\n */\n channelSubscriptionSet(\n params: ChannelSubscriptionSetParams,\n options?: KeymasterRequestOptions\n ): Promise<ChannelSubscriptionSetResult> {\n return this.request(\"channel.subscription_set\", params, options);\n }\n\n /**\n * 一次读取 Keymaster 当前的 BSV 展示价格(金额 + 单位)。\n *\n * 未就绪(未配置 / 未收到快照 / 订阅出错)时返回 `amount: \"0.00\"`;\n * 价格只作显示参考,不用于业务判断。\n *\n * @group Price\n */\n priceGet(params: PriceGetParams, options?: KeymasterRequestOptions): Promise<PriceGetResult> {\n return this.request(\"price.get\", params, options);\n }\n\n /**\n * 订阅 `price.changed` 推送;订阅前不会收到价格事件。\n *\n * @group Price\n */\n priceSubscribe(\n params: PriceSubscribeParams,\n options?: KeymasterRequestOptions\n ): Promise<PriceSubscriptionResult> {\n return this.request(\"price.subscribe\", params, options);\n }\n\n /**\n * 取消当前会话的 `price.changed` 推送。\n *\n * @group Price\n */\n priceUnsubscribe(\n params: PriceSubscribeParams,\n options?: KeymasterRequestOptions\n ): Promise<PriceSubscriptionResult> {\n return this.request(\"price.unsubscribe\", params, options);\n }\n\n /**\n * Calls `storage.list` to list paths in the verified application's namespace.\n *\n * @group Storage\n */\n storageList(params: StorageListParams, options?: KeymasterRequestOptions): Promise<StorageListResult> {\n return this.request(\"storage.list\", params, options);\n }\n\n /**\n * Calls `storage.directory.create` to create an app-scoped directory.\n *\n * @group Storage\n */\n storageDirectoryCreate(\n params: StorageDirectoryParams,\n options?: KeymasterRequestOptions\n ): Promise<StorageDirectoryResult> {\n return this.request(\"storage.directory.create\", params, options);\n }\n\n /**\n * Calls `storage.directory.delete` to delete an app-scoped directory.\n *\n * @group Storage\n */\n storageDirectoryDelete(\n params: StorageDirectoryParams,\n options?: KeymasterRequestOptions\n ): Promise<StorageDirectoryResult> {\n return this.request(\"storage.directory.delete\", params, options);\n }\n\n /**\n * Calls `storage.put` to write an app-scoped object.\n *\n * @group Storage\n */\n storagePut(params: StoragePutParams, options?: KeymasterRequestOptions): Promise<StoragePutResult> {\n return this.request(\"storage.put\", params, options);\n }\n\n /**\n * Calls `storage.get` to read an app-scoped object.\n *\n * @group Storage\n */\n storageGet(params: StorageGetParams, options?: KeymasterRequestOptions): Promise<StorageGetResult> {\n return this.request(\"storage.get\", params, options);\n }\n\n /**\n * Calls `storage.delete` to delete an app-scoped object.\n *\n * @group Storage\n */\n storageDelete(params: StorageDeleteParams, options?: KeymasterRequestOptions): Promise<StorageDeleteResult> {\n return this.request(\"storage.delete\", params, options);\n }\n\n /**\n * Calls `msfile.stat` to query every enabled MSFile supplier for a seed\n * hash. The caller selects supplier/hash only; price policy stays inside\n * Keymaster.\n *\n * @group MSFile\n */\n msfileStat(params: MsFileStatParams, options?: KeymasterRequestOptions): Promise<MsFileStatResult> {\n return this.request(\"msfile.stat\", params, options);\n }\n\n /**\n * Calls `msfile.seed.read` to buy and read a MasterSeed by hash. There is no\n * price parameter: Keymaster resolves the amount from its settings or asks\n * the user for approval when needed.\n *\n * @group MSFile\n */\n msfileReadSeed(params: MsFileSeedReadParams, options?: KeymasterRequestOptions): Promise<MsFileReadResult> {\n return this.request(\"msfile.seed.read\", params, options);\n }\n\n /**\n * Calls `msfile.block.read` to buy and read a single file block by hash.\n * Like {@link msfileReadSeed}, no caller-supplied price is accepted.\n *\n * @group MSFile\n */\n msfileReadBlock(params: MsFileBlockReadParams, options?: KeymasterRequestOptions): Promise<MsFileReadResult> {\n return this.request(\"msfile.block.read\", params, options);\n }\n\n /**\n * Cancels a locally pending request. Keymaster only cancels work that has not\n * entered execution; cancellation is therefore best-effort remotely.\n *\n * @group Transport\n */\n cancel(requestId: string, reason: unknown = new DOMException(\"The operation was aborted\", \"AbortError\")): boolean {\n const pending = this.pending.get(requestId);\n if (!pending) return false;\n this.postCancel(requestId);\n this.deletePending(requestId);\n pending.reject(reason);\n return true;\n }\n\n /**\n * Tears down the local transport. This does not revoke persistent Connect\n * sessions; call {@link logout} before closing when revocation is required.\n *\n * @group Transport\n */\n close(): void {\n this.identityValue = null;\n this.bindingId = null;\n const error = new KeymasterTransportError(\"client_closed\", \"Keymaster client was closed\");\n this.rejectAll(error);\n this.failReady(error);\n this.stopClosePolling();\n if (this.listenerInstalled) {\n this.environment.removeMessageListener(this.handleMessage);\n this.listenerInstalled = false;\n }\n try {\n if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {\n this.sessionWindow.close();\n }\n } catch {\n // Cross-origin windows can become unreadable during teardown.\n }\n this.sessionWindow = null;\n this.ownsSessionWindow = false;\n this.setState(\"disconnected\");\n }\n\n private connectPopup(): Promise<void> {\n if (this.isConnected()) return Promise.resolve();\n if (this.readyPromise) return this.readyPromise;\n\n const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);\n if (url.origin !== this.targetOrigin) {\n return Promise.reject(new TypeError(\"popupPath must resolve inside targetOrigin\"));\n }\n this.installListener();\n this.setState(\"opening\");\n this.sessionWindow = this.environment.open(\n url.toString(),\n this.options.popupName,\n popupFeatures(this.options.popupWidth, this.options.popupHeight)\n );\n if (!this.sessionWindow) {\n this.setState(\"disconnected\");\n return Promise.reject(new KeymasterTransportError(\"popup_blocked\", \"Keymaster Session Window was blocked\"));\n }\n this.ownsSessionWindow = true;\n this.startClosePolling();\n this.readyPromise = new Promise<void>((resolve, reject) => {\n this.readyResolve = resolve;\n this.readyReject = reject;\n this.readyTimer = this.environment.setTimeout(() => {\n this.disconnect(new KeymasterTransportError(\"ready_timeout\", \"Timed out waiting for Keymaster ready\"));\n }, this.options.readyTimeoutMs);\n });\n return this.readyPromise;\n }\n\n private connectAppView(): Promise<void> {\n if (this.isConnected()) return Promise.resolve();\n const opener = this.environment.opener();\n if (!opener || isWindowClosed(opener)) {\n const code: KeymasterTransportErrorCode = this.stateValue === \"idle\" ? \"no_opener\" : \"appview_session_lost\";\n this.setState(\"disconnected\");\n return Promise.reject(new KeymasterTransportError(\n code,\n \"No live Keymaster appView Session Window is available\"\n ));\n }\n this.installListener();\n this.sessionWindow = opener;\n this.ownsSessionWindow = false;\n try {\n opener.postMessage({ v: PROTOCOL_VERSION, type: \"ready\" }, this.targetOrigin);\n } catch (cause) {\n this.sessionWindow = null;\n this.setState(\"disconnected\");\n return Promise.reject(new KeymasterTransportError(\"send_failed\", errorMessage(cause, \"Unable to send appView ready\")));\n }\n this.startClosePolling();\n this.setState(\"connected\");\n return Promise.resolve();\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n if (!this.sessionWindow || event.origin !== this.targetOrigin || event.source !== this.sessionWindow) return;\n const value = event.data as Record<string, unknown> | null;\n if (!value || typeof value.type !== \"string\") return;\n if (value.v !== PROTOCOL_VERSION) {\n if (value.type === \"ready\" || value.type === \"result\") this.disconnect(new KeymasterTransportError(\"unsupported_protocol\", \"Incompatible Keymaster protocol version\"));\n return;\n }\n\n if (value.type === \"ready\" && this.mode === \"popup\") {\n this.finishReady();\n return;\n }\n if (value.type === \"closing\") {\n this.disconnect(new KeymasterTransportError(\"popup_closed\", \"Keymaster Session Window is closing\"));\n return;\n }\n if (value.type === \"event\") {\n try { if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, validateNetworkIdentity(value.networkIdentity))) return; } catch { return; }\n try {\n this.options.onEvent?.(event.data as ProtocolEventMessage);\n } catch {\n // Consumer callbacks do not own the transport event loop.\n }\n return;\n }\n if (value.type !== \"result\" || typeof value.id !== \"string\" || typeof value.ok !== \"boolean\") return;\n\n const result = event.data as ProtocolResultMessage;\n const pending = this.pending.get(result.id);\n if (!pending) return;\n this.deletePending(result.id);\n if (!result.ok) {\n // 关联到本请求的错误帧也必须校验,避免清掉计时器后因空 error 抛异常而永久悬挂。\n if (!result.error || typeof result.error.code !== \"string\" || !result.error.code || typeof result.error.message !== \"string\") {\n pending.reject(new KeymasterProtocolError(\"invalid_request\", \"Malformed Keymaster error result\"));\n return;\n }\n if (result.error.code === \"connection_expired\") { this.identityValue = null; this.bindingId = null; }\n pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));\n return;\n }\n try {\n const identity = validateNetworkIdentity(value.networkIdentity);\n if ([\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(pending.method)) {\n const connected = result.result as { networkIdentity: unknown };\n if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== \"string\" || !value.bindingId) throw new Error(\"Invalid connection identity or binding\");\n this.identityValue = Object.freeze({ ...identity });\n this.bindingId = value.bindingId;\n } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {\n throw new Error(\"Keymaster connection identity mismatch\");\n }\n if (pending.method === \"connect.logout\") { this.identityValue = null; this.bindingId = null; }\n pending.resolve(result.result);\n } catch (error) {\n pending.reject(new KeymasterProtocolError(\"invalid_request\", errorMessage(error, \"Invalid connection result\")));\n }\n };\n\n private isConnected(): boolean {\n return this.stateValue === \"connected\" && !!this.sessionWindow && !isWindowClosed(this.sessionWindow);\n }\n\n private installListener(): void {\n if (this.listenerInstalled) return;\n this.environment.addMessageListener(this.handleMessage);\n this.listenerInstalled = true;\n }\n\n private finishReady(): void {\n if (!this.readyPromise) return;\n if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);\n this.readyTimer = null;\n this.readyResolve?.();\n this.readyPromise = null;\n this.readyResolve = null;\n this.readyReject = null;\n this.setState(\"connected\");\n }\n\n private failReady(reason: unknown): void {\n if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);\n this.readyTimer = null;\n this.readyReject?.(reason);\n this.readyPromise = null;\n this.readyResolve = null;\n this.readyReject = null;\n }\n\n private disconnect(reason: unknown): void {\n this.identityValue = null;\n this.bindingId = null;\n this.rejectAll(reason);\n this.failReady(reason);\n this.stopClosePolling();\n try {\n if (this.ownsSessionWindow && this.sessionWindow && !isWindowClosed(this.sessionWindow)) {\n this.sessionWindow.close();\n }\n } catch {\n // Closing is best-effort.\n }\n this.sessionWindow = null;\n this.ownsSessionWindow = false;\n this.setState(\"disconnected\");\n }\n\n private startClosePolling(): void {\n this.stopClosePolling();\n this.closePoller = this.environment.setInterval(() => {\n if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {\n this.disconnect(new KeymasterTransportError(\"popup_closed\", \"Keymaster Session Window was closed\"));\n }\n }, this.options.closePollMs);\n }\n\n private stopClosePolling(): void {\n if (this.closePoller !== null) this.environment.clearInterval(this.closePoller);\n this.closePoller = null;\n }\n\n private rejectAll(reason: unknown): void {\n for (const [id, pending] of this.pending) {\n this.deletePending(id);\n pending.reject(reason);\n }\n }\n\n private deletePending(id: string): void {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.environment.clearTimeout(pending.timer);\n if (pending.signal && pending.abortListener) {\n pending.signal.removeEventListener(\"abort\", pending.abortListener);\n }\n this.pending.delete(id);\n }\n\n private postCancel(id: string): void {\n try {\n this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: \"cancel\", id, ...(this.bindingId ? { bindingId: this.bindingId } : {}) }, this.targetOrigin);\n } catch {\n // Protocol cancellation is best-effort.\n }\n }\n\n private setState(state: KeymasterConnectState): void {\n if (state === this.stateValue) return;\n this.stateValue = state;\n try {\n this.options.onStateChange?.(state);\n } catch {\n // Consumer callbacks cannot interrupt lifecycle transitions.\n }\n }\n}\n\n/** Creates a client without using `new`. */\nexport function createKeymasterConnect(options: KeymasterConnectOptions): KeymasterConnectClient {\n return new KeymasterConnectClient(options);\n}\n\n/** Creates the production environment adapter from the current browser window. */\nexport function createBrowserEnvironment(): KeymasterBrowserEnvironment {\n if (typeof window === \"undefined\") {\n throw new TypeError(\"keymaster-connect requires a browser Window or an explicit environment\");\n }\n return {\n open: (url, target, features) => window.open(url, target, features),\n opener: () => window.opener,\n addMessageListener: (listener) => window.addEventListener(\"message\", listener),\n removeMessageListener: (listener) => window.removeEventListener(\"message\", listener),\n setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),\n clearTimeout: (timer) => window.clearTimeout(timer),\n setInterval: (handler, intervalMs) => window.setInterval(handler, intervalMs),\n clearInterval: (timer) => window.clearInterval(timer),\n randomUUID: () => window.crypto.randomUUID()\n };\n}\n\nfunction normalizeHttpOrigin(input: string): string {\n const url = new URL(input);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\"targetOrigin must use http or https\");\n }\n return url.origin;\n}\n\nfunction popupFeatures(width: number, height: number): string {\n return `popup=yes,width=${Math.max(320, Math.trunc(width))},height=${Math.max(320, Math.trunc(height))}`;\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);\n return value;\n}\n\nfunction isWindowClosed(value: Window): boolean {\n try {\n return value.closed === true;\n } catch {\n return true;\n }\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nfunction errorMessage(value: unknown, fallback: string): string {\n return value instanceof Error && value.message ? value.message : fallback;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/binary.ts","../src/client.ts"],"names":[],"mappings":";;;;AAGO,SAAS,MAAA,CAAO,OAAsC,IAAA,EAA4B;AACvF,EAAA,MAAM,IAAA,GAAO,K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AAwB;AAC9C,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,MAAA,KAAW,IAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,SAAS,YAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF;AAEA,SAAS,YAAA,CAAa,OAAgB,QAAA,EAA0B;AAC9D,EAAA,OAAO,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,OAAA,GAAU,MAAM,OAAA,GAAU,QAAA;AACnE","file":"index.js","sourcesContent":["import type { BinaryField } from \"./protocol.js\";\n\n/** Wraps bytes in the explicit binary field required by Connect V1. */\nexport function binary(bytes: ArrayBuffer | ArrayBufferView, mime?: string): BinaryField {\n const view = bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const copy = new Uint8Array(view.byteLength);\n copy.set(view);\n return {\n $type: \"binary\",\n bytes: copy.buffer,\n ...(mime ? { mime } : {})\n };\n}\n\n/** Returns an immutable byte copy of a Connect binary field. */\nexport function binaryBytes(field: BinaryField): Uint8Array {\n if (field.$type !== \"binary\" || !(field.bytes instanceof ArrayBuffer)) {\n throw new TypeError(\"Expected a Keymaster BinaryField\");\n }\n return new Uint8Array(field.bytes.slice(0));\n}\n\n/** Encodes UTF-8 text as a Connect binary field. */\nexport function binaryText(value: string, mime = \"text/plain;charset=utf-8\"): BinaryField {\n return binary(new TextEncoder().encode(value), mime);\n}\n\n/** Decodes a Connect binary field as UTF-8 text. */\nexport function binaryToText(field: BinaryField): string {\n return new TextDecoder().decode(binaryBytes(field));\n}\n","import {\n PROTOCOL_VERSION, PROTOCOL_METHODS,\n validateNetworkIdentity, sameNetworkIdentity, type NetworkIdentity,\n type ChannelPublishParams,\n type ChannelPublishResult,\n type ChannelSubscriptionSetParams,\n type ChannelSubscriptionSetResult,\n type CipherDecryptParams,\n type CipherDecryptResult,\n type CipherEncryptParams,\n type CipherEncryptResult,\n type ConnectLaunchParams,\n type ConnectLaunchResult,\n type ConnectLoginParams,\n type ConnectLoginResult,\n type ConnectLogoutResult,\n type ConnectResumeResult,\n type ConnectResumeParams,\n type IdentityGetParams,\n type IdentityGetResult,\n type IntentSignParams,\n type IntentSignResult,\n type MethodParams,\n type MethodResult,\n type MsFileBlockReadParams,\n type MsFileReadResult,\n type MsFileSeedReadParams,\n type MsFileStatParams,\n type MsFileStatResult,\n type P2pkhTransferParams,\n type P2pkhTransferResult,\n type PaymentPayParams,\n type PaymentPayResult,\n type PaymentStatusParams,\n type PaymentStatusResult,\n type PaymentChannelRegisterParams,\n type PaymentChannelRegisterResult,\n type ProtocolErrorCode,\n type ProtocolEventMessage,\n type ProtocolMethod,\n type ProtocolResultMessage,\n type StorageDeleteParams,\n type StorageDeleteResult,\n type StorageDirectoryParams,\n type StorageDirectoryResult,\n type StorageGetParams,\n type StorageGetResult,\n type StorageListParams,\n type StorageListResult,\n type StoragePutParams,\n type StoragePutResult,\n} from \"./protocol.js\";\n\n/** 应用只在钱包创建的跨源 iframe 内连接其父钱包。 */\nexport type KeymasterConnectMode = \"appView\";\n\n/** Observable lifecycle of the browser transport. */\nexport type KeymasterConnectState = \"idle\" | \"opening\" | \"connected\" | \"paused\" | \"disconnected\";\n\n/** Failures produced by the browser transport before a protocol result exists. */\nexport type KeymasterTransportErrorCode =\n | \"wallet_closed\"\n | \"ready_timeout\"\n | \"request_timeout\"\n | \"send_failed\"\n | \"not_embedded\"\n | \"appview_session_lost\"\n | \"client_closed\"\n | \"unsupported_protocol\"\n | \"wallet_paused\";\n\n/** A browser transport failure. Protocol rejections use {@link KeymasterProtocolError}. */\nexport class KeymasterTransportError extends Error {\n constructor(\n public readonly code: KeymasterTransportErrorCode,\n message: string\n ) {\n super(message);\n this.name = \"KeymasterTransportError\";\n }\n}\n\n/** A structured rejection returned by Keymaster. */\nexport class KeymasterProtocolError extends Error {\n constructor(\n public readonly code: ProtocolErrorCode,\n message: string\n ) {\n super(message);\n this.name = \"KeymasterProtocolError\";\n }\n}\n\n/** Options applying to one protocol request. */\nexport interface KeymasterRequestOptions {\n /** Caller-controlled correlation id. A UUID is generated when omitted. */\n requestId?: string;\n /** Per-request timeout in milliseconds. */\n timeoutMs?: number;\n /** Aborting sends a best-effort protocol cancel and rejects the local promise. */\n signal?: AbortSignal;\n}\n\n/** Injectable browser primitives used by tests and embedded runtimes. */\nexport interface KeymasterBrowserEnvironment {\n parent(): Window | null;\n addMessageListener(listener: (event: MessageEvent) => void): void;\n removeMessageListener(listener: (event: MessageEvent) => void): void;\n setTimeout(handler: () => void, timeoutMs: number): number;\n clearTimeout(timer: number): void;\n setInterval(handler: () => void, intervalMs: number): number;\n clearInterval(timer: number): void;\n randomUUID(): string;\n}\n\n/** Configuration for {@link KeymasterConnectClient}. */\nexport interface KeymasterConnectOptions {\n /** Exact Keymaster deployment origin supplied by the host application. */\n targetOrigin: string;\n /** 钱包启动的 iframe 应用;独立页面不提供拉起钱包入口。 */\n mode?: KeymasterConnectMode;\n /** 等待完整钱包初始化/解锁并发送 ready 的最长时间,默认两分钟;超时不关闭钱包。 */\n readyTimeoutMs?: number;\n /** Default request timeout. Defaults to two minutes. */\n requestTimeoutMs?: number;\n /** Session Window close detection interval. Defaults to 500ms. */\n closePollMs?: number;\n /** 接收当前精确订阅频道上的已验签 Channel 事件。 */\n onEvent?: (event: ProtocolEventMessage) => void;\n /** Receives transport lifecycle changes. */\n onStateChange?: (state: KeymasterConnectState) => void;\n /** Optional browser adapter, normally only supplied by tests. */\n environment?: KeymasterBrowserEnvironment;\n}\n\ninterface PendingRequest {\n method: ProtocolMethod;\n resolve(value: unknown): void;\n reject(reason: unknown): void;\n timer: number;\n signal?: AbortSignal;\n abortListener?: () => void;\n}\n\nconst DEFAULT_READY_TIMEOUT_MS = 120_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 120_000;\nconst DEFAULT_CLOSE_POLL_MS = 500;\n\n/**\n * Official browser client for Keymaster Connect V1.\n *\n * 一个客户端关联一个完整钱包窗口,但不拥有关闭钱包的权利。It validates both the exact\n * message origin and the source window, correlates concurrent requests by id,\n * supports protocol cancellation through `AbortSignal`, and keeps persistent\n * Connect sessions separate from the window transport lifecycle.\n *\n * @example Direct popup login\n * ```ts\n * const keymaster = new KeymasterConnectClient({\n * targetOrigin: keymasterDeploymentOrigin\n * });\n *\n * const session = await keymaster.login({\n * text: \"Sign in to Example\",\n * claims: [\"profile.name\"]\n * });\n * ```\n *\n * @example appView launch\n * ```ts\n * const keymaster = new KeymasterConnectClient({\n * targetOrigin: sessionWindowOrigin,\n * mode: \"appView\"\n * });\n *\n * await keymaster.connect();\n * const session = await keymaster.launch({ launchToken, appIdentity });\n * ```\n *\n * @groupDescription Connect\n * Create, restore, revoke, or launch a persistent Connect session.\n *\n * @groupDescription Identity\n * Read signed identity claims or sign an application intent.\n *\n * @groupDescription Cipher\n * Encrypt and decrypt origin-bound application data.\n *\n * @groupDescription Transfer\n * Request a controlled BSV transfer.\n *\n * @groupDescription Channel\n * Publish JSON content and manage exact-channel subscriptions. Incoming\n * messages arrive as `channel.message_received` events.\n *\n * @groupDescription Storage\n * Manage app-scoped directories and objects.\n *\n * @groupDescription Transport\n * Manage the Session Window and send lower-level protocol requests.\n */\nexport class KeymasterConnectClient {\n private identityValue: Readonly<NetworkIdentity> | null = null;\n private bindingId: string | null = null;\n\n /** Identity returned by the authenticated wallet, or null before establishment. */\n get networkIdentity(): Readonly<NetworkIdentity> | null { return this.identityValue; }\n private readonly targetOrigin: string;\n private readonly environment: KeymasterBrowserEnvironment;\n private readonly options: Required<Pick<KeymasterConnectOptions,\n \"readyTimeoutMs\" | \"requestTimeoutMs\" | \"closePollMs\">> & KeymasterConnectOptions;\n private readonly pending = new Map<string, PendingRequest>();\n private stateValue: KeymasterConnectState = \"idle\";\n private sessionWindow: Window | null = null;\n private listenerInstalled = false;\n private readyPromise: Promise<void> | null = null;\n private readyResolve: (() => void) | null = null;\n private readyReject: ((reason: unknown) => void) | null = null;\n private readyTimer: number | null = null;\n private closePoller: number | null = null;\n private authorizationId: string | null = null;\n private authorizedIdentity: Readonly<NetworkIdentity> | null = null;\n private recoveryId: string | null = null;\n private recoveryWaiters = new Set<{ resolve(result: ConnectResumeResult): void; reject(error: unknown): void }>();\n\n constructor(options: KeymasterConnectOptions) {\n if (\"networkIdentity\" in options) throw new TypeError(\"networkIdentity option has been removed; read identity from the connection result\");\n this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);\n if (options.mode !== undefined && options.mode !== \"appView\") throw new TypeError(\"Connect apps must be launched inside the wallet\");\n this.options = {\n ...options,\n readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, \"readyTimeoutMs\"),\n requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, \"requestTimeoutMs\"),\n closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, \"closePollMs\")\n };\n this.environment = options.environment ?? createBrowserEnvironment();\n }\n\n /**\n * Current browser transport state.\n *\n * @group Transport\n */\n get state(): KeymasterConnectState {\n return this.stateValue;\n }\n\n /**\n * Establishes the browser transport.\n *\n * 绑定浏览器真实父页面,精确校验来源;独立页面直接失败,不打开钱包窗口。\n *\n * @group Transport\n */\n connect(): Promise<void> {\n return this.connectAppView();\n }\n\n /**\n * Sends any public Connect method with compile-time parameter and result\n * inference.\n *\n * @group Transport\n */\n async request<M extends ProtocolMethod>(\n method: M,\n params: MethodParams<M>,\n options: KeymasterRequestOptions = {}\n ): Promise<MethodResult<M>> {\n if (options.signal?.aborted) throw abortReason(options.signal);\n if (!PROTOCOL_METHODS.includes(method)) throw new TypeError(\"Unknown Connect method\");\n if (!params || typeof params !== \"object\" || Array.isArray(params)) throw new TypeError(\"params must be an object\");\n for (const field of [\"walletPublicKeyHex\", \"networkIdentity\", \"bsvNetwork\", \"assetId\"]) {\n if (field in params) throw new TypeError(`Removed wallet selector: ${field}`);\n }\n if (method === \"connect.resume\" && this.authorizationId) return this.continueConnection(options) as Promise<MethodResult<M>>;\n const establishing = [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(method);\n if (!establishing && this.stateValue === \"paused\") throw new KeymasterTransportError(\"wallet_paused\", \"Wallet connection is paused; old business requests are never replayed\");\n if (establishing && this.pending.size) throw new TypeError(\"Cannot establish a connection while requests are pending\");\n if (!establishing && !this.bindingId) throw new KeymasterProtocolError(\"invalid_request\", \"Login, resume or launch before making business requests\");\n if ([...this.pending.values()].some(request => [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(request.method))) throw new TypeError(\"Connection establishment is already pending\");\n await this.connect();\n if (establishing && this.pending.size) throw new TypeError(\"Cannot establish a connection while requests are pending\");\n if ([...this.pending.values()].some(request => [\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(request.method))) throw new TypeError(\"Connection establishment is already pending\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n\n const target = this.sessionWindow;\n if (!target || isWindowClosed(target)) {\n throw new KeymasterTransportError(\"wallet_closed\", \"Keymaster parent wallet is closed\");\n }\n const requestId = options.requestId ?? this.environment.randomUUID();\n if (!requestId || this.pending.has(requestId)) {\n throw new TypeError(\"requestId must be non-empty and unique among pending requests\");\n }\n const timeoutMs = positiveNumber(options.timeoutMs ?? this.options.requestTimeoutMs, \"timeoutMs\");\n\n return new Promise<MethodResult<M>>((resolve, reject) => {\n const timer = this.environment.setTimeout(() => {\n this.postCancel(requestId);\n this.deletePending(requestId);\n reject(new KeymasterTransportError(\"request_timeout\", `Keymaster request timed out: ${method}`));\n }, timeoutMs);\n const abortListener = options.signal\n ? () => {\n this.postCancel(requestId);\n this.deletePending(requestId);\n reject(abortReason(options.signal!));\n }\n : undefined;\n if (abortListener) options.signal!.addEventListener(\"abort\", abortListener, { once: true });\n this.pending.set(requestId, {\n method,\n resolve: (value) => resolve(value as MethodResult<M>),\n reject,\n timer,\n signal: options.signal,\n abortListener\n });\n\n try {\n target.postMessage({\n v: PROTOCOL_VERSION,\n type: \"request\",\n ...(!establishing ? { bindingId: this.bindingId } : {}),\n id: requestId,\n method,\n params\n }, this.targetOrigin);\n } catch (cause) {\n this.deletePending(requestId);\n reject(new KeymasterTransportError(\"send_failed\", errorMessage(cause, \"Unable to send Keymaster request\")));\n }\n });\n }\n\n /**\n * Calls `connect.login` to create a persistent Connect session.\n *\n * @group Connect\n */\n login(params: ConnectLoginParams, options?: KeymasterRequestOptions): Promise<ConnectLoginResult> {\n return this.request(\"connect.login\", params, options);\n }\n\n /**\n * Calls `connect.resume` to restore the unlock runtime for a persistent\n * session.\n *\n * @group Connect\n */\n resume(params: ConnectResumeParams = {}, options?: KeymasterRequestOptions): Promise<ConnectResumeResult> {\n return this.request(\"connect.resume\", params, options);\n }\n\n /**\n * Calls `connect.logout` to revoke a persistent Connect session.\n *\n * @group Connect\n */\n logout(options?: KeymasterRequestOptions): Promise<ConnectLogoutResult> {\n if (options !== undefined && (typeof options !== \"object\" || options === null)) return Promise.reject(new TypeError(\"logout no longer accepts a wallet public key\"));\n return this.request(\"connect.logout\", {}, options);\n }\n\n /**\n * Calls `connect.launch` to consume the one-time launch token of an appView\n * session.\n *\n * @group Connect\n */\n launch(params: ConnectLaunchParams, options?: KeymasterRequestOptions): Promise<ConnectLaunchResult> {\n return this.request(\"connect.launch\", params, options);\n }\n\n /**\n * Calls `identity.get` to return signed identity claims for the session\n * owner.\n *\n * @group Identity\n */\n identityGet(params: IdentityGetParams, options?: KeymasterRequestOptions): Promise<IdentityGetResult> {\n return this.request(\"identity.get\", params, options);\n }\n\n /**\n * Calls `intent.sign` to sign caller-provided bytes with a human-readable\n * intent.\n *\n * @group Identity\n */\n intentSign(params: IntentSignParams, options?: KeymasterRequestOptions): Promise<IntentSignResult> {\n return this.request(\"intent.sign\", params, options);\n }\n\n /**\n * Calls `cipher.encrypt` to encrypt origin-bound application data.\n *\n * @group Cipher\n */\n cipherEncrypt(params: CipherEncryptParams, options?: KeymasterRequestOptions): Promise<CipherEncryptResult> {\n return this.request(\"cipher.encrypt\", params, options);\n }\n\n /**\n * Calls `cipher.decrypt` to decrypt data previously returned by\n * `cipher.encrypt`.\n *\n * @group Cipher\n */\n cipherDecrypt(params: CipherDecryptParams, options?: KeymasterRequestOptions): Promise<CipherDecryptResult> {\n return this.request(\"cipher.decrypt\", params, options);\n }\n\n /**\n * 请求 `payment.pay`;资金审批、选币与持久幂等由钱包负责。\n * Promise resolve 不等于已广播,应检查返回状态。\n *\n * @group Payment\n */\n paymentPay(params: PaymentPayParams, options?: KeymasterRequestOptions): Promise<PaymentPayResult> {\n return this.request(\"payment.pay\", params, options);\n }\n\n /** 按原业务 ID 只读查询付款状态,不自动重付或更换 ID。 */\n paymentStatus(params: PaymentStatusParams, options?: KeymasterRequestOptions): Promise<PaymentStatusResult> {\n return this.request(\"payment.status\", params, options);\n }\n\n /**\n * @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。\n * @group Transfer\n */\n p2pkhTransfer(params: P2pkhTransferParams, options?: KeymasterRequestOptions): Promise<P2pkhTransferResult> {\n return this.request(\"p2pkh.transfer\", params, options);\n }\n\n /** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */\n registerPaymentChannel(params: PaymentChannelRegisterParams, options?: KeymasterRequestOptions): Promise<PaymentChannelRegisterResult> {\n return this.request(\"payment.channel.register\", params, options);\n }\n\n /**\n * 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。\n *\n * @group Channel\n */\n channelPublish(\n params: ChannelPublishParams,\n options?: KeymasterRequestOptions\n ): Promise<ChannelPublishResult> {\n return this.request(\"channel.publish\", params, options);\n }\n\n /**\n * 替换当前 Connect caller 的精确频道订阅集合;传空数组表示释放。\n *\n * @group Channel\n */\n channelSubscriptionSet(\n params: ChannelSubscriptionSetParams,\n options?: KeymasterRequestOptions\n ): Promise<ChannelSubscriptionSetResult> {\n return this.request(\"channel.subscription_set\", params, options);\n }\n\n /**\n * Calls `storage.list` to list paths in the verified application's namespace.\n *\n * @group Storage\n */\n storageList(params: StorageListParams, options?: KeymasterRequestOptions): Promise<StorageListResult> {\n return this.request(\"storage.list\", params, options);\n }\n\n /**\n * Calls `storage.directory.create` to create an app-scoped directory.\n *\n * @group Storage\n */\n storageDirectoryCreate(\n params: StorageDirectoryParams,\n options?: KeymasterRequestOptions\n ): Promise<StorageDirectoryResult> {\n return this.request(\"storage.directory.create\", params, options);\n }\n\n /**\n * Calls `storage.directory.delete` to delete an app-scoped directory.\n *\n * @group Storage\n */\n storageDirectoryDelete(\n params: StorageDirectoryParams,\n options?: KeymasterRequestOptions\n ): Promise<StorageDirectoryResult> {\n return this.request(\"storage.directory.delete\", params, options);\n }\n\n /**\n * Calls `storage.put` to write an app-scoped object.\n *\n * @group Storage\n */\n storagePut(params: StoragePutParams, options?: KeymasterRequestOptions): Promise<StoragePutResult> {\n return this.request(\"storage.put\", params, options);\n }\n\n /**\n * Calls `storage.get` to read an app-scoped object.\n *\n * @group Storage\n */\n storageGet(params: StorageGetParams, options?: KeymasterRequestOptions): Promise<StorageGetResult> {\n return this.request(\"storage.get\", params, options);\n }\n\n /**\n * Calls `storage.delete` to delete an app-scoped object.\n *\n * @group Storage\n */\n storageDelete(params: StorageDeleteParams, options?: KeymasterRequestOptions): Promise<StorageDeleteResult> {\n return this.request(\"storage.delete\", params, options);\n }\n\n /**\n * Calls `msfile.stat` to query every enabled MSFile supplier for a seed\n * hash. The caller selects supplier/hash only; price policy stays inside\n * Keymaster.\n *\n * @group MSFile\n */\n msfileStat(params: MsFileStatParams, options?: KeymasterRequestOptions): Promise<MsFileStatResult> {\n return this.request(\"msfile.stat\", params, options);\n }\n\n /**\n * Calls `msfile.seed.read` to buy and read a MasterSeed by hash. There is no\n * price parameter: Keymaster resolves the amount from its settings or asks\n * the user for approval when needed.\n *\n * @group MSFile\n */\n msfileReadSeed(params: MsFileSeedReadParams, options?: KeymasterRequestOptions): Promise<MsFileReadResult> {\n return this.request(\"msfile.seed.read\", params, options);\n }\n\n /**\n * Calls `msfile.block.read` to buy and read a single file block by hash.\n * Like {@link msfileReadSeed}, no caller-supplied price is accepted.\n *\n * @group MSFile\n */\n msfileReadBlock(params: MsFileBlockReadParams, options?: KeymasterRequestOptions): Promise<MsFileReadResult> {\n return this.request(\"msfile.block.read\", params, options);\n }\n\n /**\n * Cancels a locally pending request. Keymaster only cancels work that has not\n * entered execution; cancellation is therefore best-effort remotely.\n *\n * @group Transport\n */\n cancel(requestId: string, reason: unknown = new DOMException(\"The operation was aborted\", \"AbortError\")): boolean {\n const pending = this.pending.get(requestId);\n if (!pending) return false;\n this.postCancel(requestId);\n this.deletePending(requestId);\n pending.reject(reason);\n return true;\n }\n\n /**\n * Tears down the local transport. This does not revoke persistent Connect\n * sessions; call {@link logout} before closing when revocation is required.\n *\n * @group Transport\n */\n close(): void {\n // 取消仍可取消的请求;钱包窗口不是客户端的资源,始终由用户自己关闭。\n for (const id of this.pending.keys()) this.postCancel(id);\n this.identityValue = null;\n this.bindingId = null;\n const error = new KeymasterTransportError(\"client_closed\", \"Keymaster client was closed\");\n this.rejectAll(error);\n this.failReady(error);\n this.stopClosePolling();\n if (this.listenerInstalled) {\n this.environment.removeMessageListener(this.handleMessage);\n this.listenerInstalled = false;\n }\n if (!this.authorizationId) this.sessionWindow = null;\n this.recoveryId = null;\n this.finishRecovery(undefined, error);\n this.setState(this.authorizationId ? \"paused\" : \"disconnected\");\n }\n\n /** 恢复原父钱包连接;任何情况下都不另开窗口或重放旧业务。 */\n private continueConnection(options: KeymasterRequestOptions): Promise<ConnectResumeResult> {\n if (this.pending.size) return Promise.reject(new TypeError(\"Cannot resume while business requests are pending\"));\n this.installListener();\n const parent = this.environment.parent();\n if (!parent || isWindowClosed(parent)) return Promise.reject(new KeymasterTransportError(\"appview_session_lost\", \"No wallet parent is available; relaunch from the wallet\"));\n this.sessionWindow = parent;\n this.pause(new KeymasterTransportError(\"wallet_paused\", \"Re-establishing the original wallet connection\"));\n this.startClosePolling();\n return new Promise((resolve, reject) => {\n const finish = (error?: unknown, result?: ConnectResumeResult) => {\n this.environment.clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", aborted);\n this.recoveryWaiters.delete(waiter);\n if (error) reject(error); else resolve(result!);\n };\n const waiter = { resolve: (result: ConnectResumeResult) => finish(undefined, result), reject: (error: unknown) => finish(error) };\n const aborted = () => finish(abortReason(options.signal!));\n const timer = this.environment.setTimeout(() => finish(new KeymasterTransportError(\"request_timeout\", \"Timed out restoring wallet connection\")), positiveNumber(options.timeoutMs ?? this.options.readyTimeoutMs, \"timeoutMs\"));\n this.recoveryWaiters.add(waiter);\n options.signal?.addEventListener(\"abort\", aborted, { once: true });\n this.sendRecovery();\n });\n }\n\n private connectAppView(): Promise<void> {\n if (this.isConnected()) return Promise.resolve();\n const parent = this.environment.parent();\n if (!parent || isWindowClosed(parent)) {\n const code: KeymasterTransportErrorCode = this.stateValue === \"idle\" ? \"not_embedded\" : \"appview_session_lost\";\n this.setState(\"disconnected\");\n return Promise.reject(new KeymasterTransportError(\n code,\n \"No live wallet parent is available; launch the app from Keymaster\"\n ));\n }\n this.installListener();\n this.sessionWindow = parent;\n try {\n parent.postMessage({ v: PROTOCOL_VERSION, type: \"ready\" }, this.targetOrigin);\n } catch (cause) {\n this.sessionWindow = null;\n this.setState(\"disconnected\");\n return Promise.reject(new KeymasterTransportError(\"send_failed\", errorMessage(cause, \"Unable to send appView ready\")));\n }\n this.startClosePolling();\n this.setState(\"connected\");\n return Promise.resolve();\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n if (!this.sessionWindow || event.origin !== this.targetOrigin || event.source !== this.sessionWindow) return;\n const value = event.data as Record<string, unknown> | null;\n if (!value || typeof value.type !== \"string\") return;\n if (value.v !== PROTOCOL_VERSION) {\n if (value.type === \"ready\" || value.type === \"result\") this.disconnect(new KeymasterTransportError(\"unsupported_protocol\", \"Incompatible Keymaster protocol version\"));\n return;\n }\n\n if (value.type === \"ready\") return;\n if (value.type === \"closing\") {\n if (this.authorizationId) this.pause(new KeymasterTransportError(\"wallet_paused\", \"Wallet runtime is unavailable\"));\n else this.disconnect(new KeymasterTransportError(\"wallet_closed\", \"Keymaster wallet connection is closing\"));\n return;\n }\n if (value.type === \"revoked\" && value.authorizationId === this.authorizationId) {\n this.authorizationId = null; this.authorizedIdentity = null; this.recoveryId = null;\n this.finishRecovery(undefined, new KeymasterProtocolError(\"connection_expired\", \"Application connection authorization was revoked\"));\n this.disconnect(new KeymasterProtocolError(\"connection_expired\", \"Application connection authorization was revoked\"));\n return;\n }\n if (value.type === \"event\") {\n // 只投递当前公开契约中的事件,避免已删除能力仍透传给 App。\n if (value.event !== \"channel.message_received\") return;\n try { if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, validateNetworkIdentity(value.networkIdentity))) return; } catch { return; }\n try {\n this.options.onEvent?.(event.data as ProtocolEventMessage);\n } catch {\n // Consumer callbacks do not own the transport event loop.\n }\n return;\n }\n if (value.type !== \"result\" || typeof value.id !== \"string\" || typeof value.ok !== \"boolean\") return;\n\n const result = event.data as ProtocolResultMessage;\n if (this.authorizationId && result.id === this.recoveryId) {\n if (!result.ok) { this.pause(new KeymasterProtocolError(result.error.code, result.error.message)); return; }\n try {\n const identity = validateNetworkIdentity(value.networkIdentity);\n const restored = result.result as ConnectResumeResult;\n if (!this.authorizedIdentity || !sameNetworkIdentity(identity, this.authorizedIdentity) || !sameNetworkIdentity(identity, validateNetworkIdentity(restored.networkIdentity))\n || restored.authorizationId !== this.authorizationId || typeof value.bindingId !== \"string\" || !value.bindingId) throw new Error(\"Recovery must retain the original wallet and authorization\");\n if (this.bindingId !== value.bindingId) this.pause(new KeymasterTransportError(\"wallet_paused\", \"Wallet runtime was replaced\"));\n this.identityValue = Object.freeze({ ...identity }); this.bindingId = value.bindingId; this.recoveryId = null;\n this.setState(\"connected\"); this.finishRecovery(restored);\n } catch (error) { this.pause(error); this.finishRecovery(undefined, error); }\n return;\n }\n const pending = this.pending.get(result.id);\n if (!pending) return;\n this.deletePending(result.id);\n if (!result.ok) {\n // 关联到本请求的错误帧也必须校验,避免清掉计时器后因空 error 抛异常而永久悬挂。\n if (!result.error || typeof result.error.code !== \"string\" || !result.error.code || typeof result.error.message !== \"string\") {\n pending.reject(new KeymasterProtocolError(\"invalid_request\", \"Malformed Keymaster error result\"));\n return;\n }\n if (result.error.code === \"connection_expired\") { if (this.authorizationId) this.pause(new KeymasterProtocolError(result.error.code, result.error.message)); else { this.identityValue = null; this.bindingId = null; } }\n pending.reject(new KeymasterProtocolError(result.error.code, result.error.message));\n return;\n }\n try {\n const identity = validateNetworkIdentity(value.networkIdentity);\n if ([\"connect.login\", \"connect.resume\", \"connect.launch\"].includes(pending.method)) {\n const connected = result.result as { networkIdentity: unknown; authorizationId: string };\n if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== \"string\" || !value.bindingId || typeof connected.authorizationId !== \"string\" || !connected.authorizationId) throw new Error(\"Invalid connection identity or binding\");\n this.identityValue = Object.freeze({ ...identity });\n this.authorizedIdentity = this.identityValue; this.authorizationId = connected.authorizationId; this.recoveryId = null;\n this.bindingId = value.bindingId;\n } else if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, identity)) {\n throw new Error(\"Keymaster connection identity mismatch\");\n }\n if (pending.method === \"connect.logout\") { this.identityValue = null; this.bindingId = null; this.authorizationId = null; this.authorizedIdentity = null; this.recoveryId = null; }\n pending.resolve(result.result);\n } catch (error) {\n pending.reject(new KeymasterProtocolError(\"invalid_request\", errorMessage(error, \"Invalid connection result\")));\n }\n };\n\n private isConnected(): boolean {\n return this.stateValue === \"connected\" && !!this.sessionWindow && !isWindowClosed(this.sessionWindow);\n }\n\n private installListener(): void {\n if (this.listenerInstalled) return;\n this.environment.addMessageListener(this.handleMessage);\n this.listenerInstalled = true;\n }\n\n private finishReady(): void {\n if (!this.readyPromise) return;\n if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);\n this.readyTimer = null;\n this.readyResolve?.();\n this.readyPromise = null;\n this.readyResolve = null;\n this.readyReject = null;\n this.setState(\"connected\");\n }\n\n private failReady(reason: unknown): void {\n if (this.readyTimer !== null) this.environment.clearTimeout(this.readyTimer);\n this.readyTimer = null;\n this.readyReject?.(reason);\n this.readyPromise = null;\n this.readyResolve = null;\n this.readyReject = null;\n }\n\n private disconnect(reason: unknown): void {\n for (const id of this.pending.keys()) this.postCancel(id);\n this.identityValue = null;\n this.bindingId = null;\n this.rejectAll(reason);\n this.failReady(reason);\n this.stopClosePolling();\n this.sessionWindow = null;\n this.setState(\"disconnected\");\n }\n\n /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */\n private pause(reason: unknown): void {\n this.identityValue = null; this.bindingId = null;\n this.rejectAll(reason); this.failReady(reason);\n this.setState(\"paused\");\n }\n\n private sendRecovery(): void {\n if (!this.authorizationId || !this.sessionWindow || isWindowClosed(this.sessionWindow)) return;\n this.recoveryId ??= this.environment.randomUUID();\n try { this.sessionWindow.postMessage({ v: PROTOCOL_VERSION, type: \"reconnect\", id: this.recoveryId, authorizationId: this.authorizationId, ...(this.bindingId ? { bindingId: this.bindingId } : {}) }, this.targetOrigin); }\n catch (error) { this.pause(error); }\n }\n\n private finishRecovery(result?: ConnectResumeResult, error?: unknown): void {\n for (const waiter of [...this.recoveryWaiters]) { if (error) waiter.reject(error); else if (result) waiter.resolve(result); }\n }\n\n private startClosePolling(): void {\n this.stopClosePolling();\n this.closePoller = this.environment.setInterval(() => {\n if (this.sessionWindow && isWindowClosed(this.sessionWindow)) {\n if (this.authorizationId) { if (this.stateValue !== \"paused\") this.pause(new KeymasterTransportError(\"wallet_paused\", \"Wallet window is closed\")); }\n else this.disconnect(new KeymasterTransportError(\"wallet_closed\", \"Keymaster parent wallet was closed\"));\n } else this.sendRecovery();\n }, this.options.closePollMs);\n }\n\n private stopClosePolling(): void {\n if (this.closePoller !== null) this.environment.clearInterval(this.closePoller);\n this.closePoller = null;\n }\n\n private rejectAll(reason: unknown): void {\n for (const [id, pending] of this.pending) {\n this.deletePending(id);\n pending.reject(reason);\n }\n }\n\n private deletePending(id: string): void {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.environment.clearTimeout(pending.timer);\n if (pending.signal && pending.abortListener) {\n pending.signal.removeEventListener(\"abort\", pending.abortListener);\n }\n this.pending.delete(id);\n }\n\n private postCancel(id: string): void {\n try {\n this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: \"cancel\", id, ...(this.bindingId ? { bindingId: this.bindingId } : {}) }, this.targetOrigin);\n } catch {\n // Protocol cancellation is best-effort.\n }\n }\n\n private setState(state: KeymasterConnectState): void {\n if (state === this.stateValue) return;\n this.stateValue = state;\n try {\n this.options.onStateChange?.(state);\n } catch {\n // Consumer callbacks cannot interrupt lifecycle transitions.\n }\n }\n}\n\n/** Creates a client without using `new`. */\nexport function createKeymasterConnect(options: KeymasterConnectOptions): KeymasterConnectClient {\n return new KeymasterConnectClient(options);\n}\n\n/** Creates the production environment adapter from the current browser window. */\nexport function createBrowserEnvironment(): KeymasterBrowserEnvironment {\n if (typeof window === \"undefined\") {\n throw new TypeError(\"keymaster-connect requires a browser Window or an explicit environment\");\n }\n return {\n parent: () => window.parent !== window ? window.parent : null,\n addMessageListener: (listener) => window.addEventListener(\"message\", listener),\n removeMessageListener: (listener) => window.removeEventListener(\"message\", listener),\n setTimeout: (handler, timeoutMs) => window.setTimeout(handler, timeoutMs),\n clearTimeout: (timer) => window.clearTimeout(timer),\n setInterval: (handler, intervalMs) => window.setInterval(handler, intervalMs),\n clearInterval: (timer) => window.clearInterval(timer),\n randomUUID: () => window.crypto.randomUUID()\n };\n}\n\nfunction normalizeHttpOrigin(input: string): string {\n const url = new URL(input);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\"targetOrigin must use http or https\");\n }\n return url.origin;\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new TypeError(`${name} must be a positive number`);\n return value;\n}\n\nfunction isWindowClosed(value: Window): boolean {\n try {\n return value.closed === true;\n } catch {\n return true;\n }\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nfunction errorMessage(value: unknown, fallback: string): string {\n return value instanceof Error && value.message ? value.message : fallback;\n}\n"]}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -87,26 +87,6 @@ interface ChannelMessageReceivedEventData {
|
|
|
87
87
|
*/
|
|
88
88
|
rawEnvelope?: Uint8Array;
|
|
89
89
|
}
|
|
90
|
-
interface PriceGetParams extends Record<string, never> {
|
|
91
|
-
}
|
|
92
|
-
interface PriceValue {
|
|
93
|
-
/** 十进制金额字符串,例如 "45.12";未就绪时为 "0"。 */
|
|
94
|
-
amount: string;
|
|
95
|
-
/** 计价单位,例如 "USDT";未就绪时仍给出当前配置推导出的单位。 */
|
|
96
|
-
unit: string;
|
|
97
|
-
/** 行情快照生成的 Unix 毫秒时间;未就绪时为 0。 */
|
|
98
|
-
updatedAtMs: number;
|
|
99
|
-
}
|
|
100
|
-
/** `price.get` 结果。 */
|
|
101
|
-
type PriceGetResult = PriceValue;
|
|
102
|
-
interface PriceSubscribeParams extends Record<string, never> {
|
|
103
|
-
}
|
|
104
|
-
interface PriceSubscriptionResult {
|
|
105
|
-
/** 调用完成后该会话是否处于价格推送订阅态。 */
|
|
106
|
-
subscribed: boolean;
|
|
107
|
-
}
|
|
108
|
-
/** `price.changed` 事件数据;形状与 `price.get` 结果一致。 */
|
|
109
|
-
type PriceChangedEventData = PriceValue;
|
|
110
90
|
interface StorageListParams {
|
|
111
91
|
/** 目录前缀。 */
|
|
112
92
|
prefix?: string;
|
|
@@ -345,9 +325,7 @@ type ProtocolErrorCode =
|
|
|
345
325
|
/** Transport authority was revoked or belongs to another wallet/Worker generation. */
|
|
346
326
|
"connection_expired" | "invalid_request" | "invalid_origin" | "user_rejected" | "active_key_unavailable" | "decrypt_failed"
|
|
347
327
|
/**
|
|
348
|
-
*
|
|
349
|
-
* 例如 `p2pkh.transfer` / `feepool.*` 传 `assetId: "bsv-testnet"` 而
|
|
350
|
-
* P2PKH 设置里没有打开 testnet。accept 阶段 fail-fast,不进确认流。
|
|
328
|
+
* 请求资产与连接绑定的钱包网络不一致;accept 阶段拒绝,不进入业务执行。
|
|
351
329
|
*/
|
|
352
330
|
| "asset_not_enabled"
|
|
353
331
|
/** Connect v1 明确排除的方法族(新费用池签名等)。 */
|
|
@@ -386,10 +364,8 @@ interface ProtocolCancelMessage {
|
|
|
386
364
|
* 设计缘由:
|
|
387
365
|
* - `channel.message_received` 是已验签的 Channel 公开消息,只发送给
|
|
388
366
|
* 当前 session 已精确订阅的频道;
|
|
389
|
-
* - `price.changed` 是 Keymaster 当前 BSV 价格展示值变化,向所有活跃
|
|
390
|
-
* session 推送;未就绪时也可能推送 amount "0"。
|
|
391
367
|
*/
|
|
392
|
-
type ProtocolEventName = "channel.message_received"
|
|
368
|
+
type ProtocolEventName = "channel.message_received";
|
|
393
369
|
interface IdentityGetParams {
|
|
394
370
|
/** 目标站点 origin;必须等于 `event.origin`,否则拒绝。 */
|
|
395
371
|
aud: string;
|
|
@@ -483,9 +459,7 @@ interface PaymentChannelRegisterResult {
|
|
|
483
459
|
* 设计缘由(施工单 2026-09-18 001 多资产硬切换):
|
|
484
460
|
* - 公开命名固定 `bsv-mainnet` / `bsv-testnet`,不暴露 p2pkh 内部
|
|
485
461
|
* 的 `bsv` / `bsvtest`;
|
|
486
|
-
* -
|
|
487
|
-
* 否则 accept 阶段 fail-fast `asset_not_enabled`;
|
|
488
|
-
* - 缺省(不传 assetId)等同 `bsv-mainnet`,旧调用方零改动。
|
|
462
|
+
* - 资产由连接绑定的钱包网络决定,调用方不能选择或覆盖该网络。
|
|
489
463
|
*/
|
|
490
464
|
type P2pkhTransferAssetId = "bsv-mainnet" | "bsv-testnet";
|
|
491
465
|
interface P2pkhTransferParams {
|
|
@@ -495,11 +469,11 @@ interface P2pkhTransferParams {
|
|
|
495
469
|
recipientAddress: string;
|
|
496
470
|
/** 正整数 satoshis。 */
|
|
497
471
|
amountSatoshis: number;
|
|
498
|
-
/**
|
|
472
|
+
/** 可选费率(sat/kB),>= 1;缺省由钱包当前网络的有效费率策略决定。 */
|
|
499
473
|
feeRateSatoshisPerKb?: number;
|
|
500
474
|
}
|
|
501
475
|
interface P2pkhTransferResult {
|
|
502
|
-
/**
|
|
476
|
+
/** 本次实际转账的资产,与连接绑定的钱包网络一致。 */
|
|
503
477
|
assetId: P2pkhTransferAssetId;
|
|
504
478
|
/** 已广播交易的 canonical txid。 */
|
|
505
479
|
txid: string;
|
|
@@ -529,7 +503,7 @@ interface PaymentPayParams {
|
|
|
529
503
|
businessKind: string;
|
|
530
504
|
/** 业务金额(聪,不含矿工费)。 */
|
|
531
505
|
amountSatoshis: number;
|
|
532
|
-
/** 可选希望费率(sat/kB
|
|
506
|
+
/** 可选希望费率(sat/kB);缺省由钱包当前网络的有效费率策略决定。 */
|
|
533
507
|
feeRateSatoshisPerKb?: number;
|
|
534
508
|
recipient: ConnectPaymentRecipient;
|
|
535
509
|
}
|
|
@@ -572,6 +546,8 @@ interface ConnectLoginParams {
|
|
|
572
546
|
appIdentity?: AppIdentityProofV1;
|
|
573
547
|
}
|
|
574
548
|
interface ConnectLoginResult {
|
|
549
|
+
/** 不透明恢复凭据,绑定原钱包、应用和精确来源;不得写入日志或 URL。 */
|
|
550
|
+
authorizationId: string;
|
|
575
551
|
networkIdentity: NetworkIdentity;
|
|
576
552
|
/** 本次 login 时一次解析的 claims 真值快照。 */
|
|
577
553
|
resolvedClaims: Record<string, ResolvedClaimValue>;
|
|
@@ -584,6 +560,7 @@ interface ConnectResumeParams {
|
|
|
584
560
|
appIdentity?: AppIdentityProofV1;
|
|
585
561
|
}
|
|
586
562
|
interface ConnectResumeResult {
|
|
563
|
+
authorizationId: string;
|
|
587
564
|
networkIdentity: NetworkIdentity;
|
|
588
565
|
resolvedClaims: Record<string, ResolvedClaimValue>;
|
|
589
566
|
/**
|
|
@@ -606,13 +583,14 @@ interface ConnectLaunchParams {
|
|
|
606
583
|
appIdentity: AppIdentityProofV1;
|
|
607
584
|
}
|
|
608
585
|
interface ConnectLaunchResult {
|
|
586
|
+
authorizationId: string;
|
|
609
587
|
networkIdentity: NetworkIdentity;
|
|
610
588
|
resolvedClaims: Record<string, ResolvedClaimValue>;
|
|
611
589
|
resolvedAt: number;
|
|
612
590
|
appIdentity?: AppIdentitySnapshot;
|
|
613
591
|
}
|
|
614
592
|
/** 协议方法名常量集合。 */
|
|
615
|
-
declare const PROTOCOL_METHODS: readonly ["identity.get", "intent.sign", "cipher.encrypt", "cipher.decrypt", "p2pkh.transfer", "payment.pay", "payment.status", "payment.channel.register", "connect.login", "connect.resume", "connect.logout", "connect.launch", "channel.publish", "channel.subscription_set", "
|
|
593
|
+
declare const PROTOCOL_METHODS: readonly ["identity.get", "intent.sign", "cipher.encrypt", "cipher.decrypt", "p2pkh.transfer", "payment.pay", "payment.status", "payment.channel.register", "connect.login", "connect.resume", "connect.logout", "connect.launch", "channel.publish", "channel.subscription_set", "storage.list", "storage.directory.create", "storage.directory.delete", "storage.put", "storage.get", "storage.delete", "msfile.stat", "msfile.seed.read", "msfile.block.read"];
|
|
616
594
|
type ProtocolMethod = (typeof PROTOCOL_METHODS)[number];
|
|
617
595
|
/**
|
|
618
596
|
* 方法 -> 请求参数类型 的映射。`MethodParams<M>` 是计算出的参数类型。
|
|
@@ -633,9 +611,6 @@ interface MethodParamsMap {
|
|
|
633
611
|
"connect.launch": ConnectLaunchParams;
|
|
634
612
|
"channel.publish": ChannelPublishParams;
|
|
635
613
|
"channel.subscription_set": ChannelSubscriptionSetParams;
|
|
636
|
-
"price.get": PriceGetParams;
|
|
637
|
-
"price.subscribe": PriceSubscribeParams;
|
|
638
|
-
"price.unsubscribe": PriceSubscribeParams;
|
|
639
614
|
"storage.list": StorageListParams;
|
|
640
615
|
"storage.directory.create": StorageDirectoryParams;
|
|
641
616
|
"storage.directory.delete": StorageDirectoryParams;
|
|
@@ -661,9 +636,6 @@ interface MethodResultMap {
|
|
|
661
636
|
"connect.launch": ConnectLaunchResult;
|
|
662
637
|
"channel.publish": ChannelPublishResult;
|
|
663
638
|
"channel.subscription_set": ChannelSubscriptionSetResult;
|
|
664
|
-
"price.get": PriceGetResult;
|
|
665
|
-
"price.subscribe": PriceSubscriptionResult;
|
|
666
|
-
"price.unsubscribe": PriceSubscriptionResult;
|
|
667
639
|
"storage.list": StorageListResult;
|
|
668
640
|
"storage.directory.create": StorageDirectoryResult;
|
|
669
641
|
"storage.directory.delete": StorageDirectoryResult;
|
|
@@ -681,16 +653,19 @@ type ProtocolEventPayload = {
|
|
|
681
653
|
type: "event";
|
|
682
654
|
event: "channel.message_received";
|
|
683
655
|
data: ChannelMessageReceivedEventData;
|
|
684
|
-
} | {
|
|
685
|
-
v: typeof PROTOCOL_VERSION;
|
|
686
|
-
type: "event";
|
|
687
|
-
event: "price.changed";
|
|
688
|
-
data: PriceChangedEventData;
|
|
689
656
|
};
|
|
690
657
|
type ProtocolEventMessage = ProtocolEventPayload & {
|
|
691
658
|
networkIdentity: NetworkIdentity;
|
|
692
659
|
bindingId: string;
|
|
693
660
|
};
|
|
661
|
+
/** 暂停恢复控制,不携带钱包选择参数,也不是业务请求重放。 */
|
|
662
|
+
interface ProtocolReconnectMessage {
|
|
663
|
+
v: typeof PROTOCOL_VERSION;
|
|
664
|
+
type: "reconnect";
|
|
665
|
+
id: string;
|
|
666
|
+
authorizationId: string;
|
|
667
|
+
bindingId?: string;
|
|
668
|
+
}
|
|
694
669
|
interface ProtocolRequestMessage<M extends ProtocolMethod = ProtocolMethod> {
|
|
695
670
|
v: typeof PROTOCOL_VERSION;
|
|
696
671
|
type: "request";
|
|
@@ -716,4 +691,4 @@ type ProtocolResultMessage = {
|
|
|
716
691
|
networkIdentity?: NetworkIdentity;
|
|
717
692
|
};
|
|
718
693
|
|
|
719
|
-
export { type AppIdentityProofV1, type AppIdentitySnapshot, type AppRequirement, type BinaryField, type BsvNetwork, type ChannelMessageReceivedEventData, type ChannelPublishParams, type ChannelPublishResult, type ChannelSubscriptionErrorCode, type ChannelSubscriptionPhase, type ChannelSubscriptionSetParams, type ChannelSubscriptionSetResult, type ChannelSubscriptionStatus, type CipherDecryptParams, type CipherDecryptResult, type CipherEncryptParams, type CipherEncryptResult, type ConnectLaunchParams, type ConnectLaunchResult, type ConnectLoginParams, type ConnectLoginResult, type ConnectLogoutParams, type ConnectLogoutResult, type ConnectPaymentRecipient, type ConnectPaymentRecipientOwnership, type ConnectPaymentStatus, type ConnectPaymentType, type ConnectResumeParams, type ConnectResumeResult, type IdentityGetParams, type IdentityGetResult, type IntentSignParams, type IntentSignResult, type JSONValue, MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, type MethodParams, type MethodParamsMap, type MethodResult, type MethodResultMap, type MsFileBlockReadParams, type MsFileLocalSourceStat, type MsFileReadResult, type MsFileRemoteSourceStat, type MsFileSatoshiAmount, type MsFileSeedReadParams, type MsFileSourceKind, type MsFileSourceStat, type MsFileStatAbsentEntry, type MsFileStatAvailableEntry, type MsFileStatDiscoveringEntry, type MsFileStatNetworkErrorEntry, type MsFileStatParams, type MsFileStatQuotedEntry, type MsFileStatResult, type MsFileSupplierStat, type NetworkIdentity, type P2pkhTransferAssetId, type P2pkhTransferParams, type P2pkhTransferResult, PROTOCOL_METHODS, PROTOCOL_VERSION, type PaymentChannelRegisterParams, type PaymentChannelRegisterResult, type PaymentPayParams, type PaymentPayResult, type PaymentReleaseSummary, type PaymentStatusParams, type PaymentStatusResult, type
|
|
694
|
+
export { type AppIdentityProofV1, type AppIdentitySnapshot, type AppRequirement, type BinaryField, type BsvNetwork, type ChannelMessageReceivedEventData, type ChannelPublishParams, type ChannelPublishResult, type ChannelSubscriptionErrorCode, type ChannelSubscriptionPhase, type ChannelSubscriptionSetParams, type ChannelSubscriptionSetResult, type ChannelSubscriptionStatus, type CipherDecryptParams, type CipherDecryptResult, type CipherEncryptParams, type CipherEncryptResult, type ConnectLaunchParams, type ConnectLaunchResult, type ConnectLoginParams, type ConnectLoginResult, type ConnectLogoutParams, type ConnectLogoutResult, type ConnectPaymentRecipient, type ConnectPaymentRecipientOwnership, type ConnectPaymentStatus, type ConnectPaymentType, type ConnectResumeParams, type ConnectResumeResult, type IdentityGetParams, type IdentityGetResult, type IntentSignParams, type IntentSignResult, type JSONValue, MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, type MethodParams, type MethodParamsMap, type MethodResult, type MethodResultMap, type MsFileBlockReadParams, type MsFileLocalSourceStat, type MsFileReadResult, type MsFileRemoteSourceStat, type MsFileSatoshiAmount, type MsFileSeedReadParams, type MsFileSourceKind, type MsFileSourceStat, type MsFileStatAbsentEntry, type MsFileStatAvailableEntry, type MsFileStatDiscoveringEntry, type MsFileStatNetworkErrorEntry, type MsFileStatParams, type MsFileStatQuotedEntry, type MsFileStatResult, type MsFileSupplierStat, type NetworkIdentity, type P2pkhTransferAssetId, type P2pkhTransferParams, type P2pkhTransferResult, PROTOCOL_METHODS, PROTOCOL_VERSION, type PaymentChannelRegisterParams, type PaymentChannelRegisterResult, type PaymentPayParams, type PaymentPayResult, type PaymentReleaseSummary, type PaymentStatusParams, type PaymentStatusResult, type ProtocolCancelMessage, type ProtocolClosingMessage, type ProtocolError, type ProtocolErrorCode, type ProtocolEventMessage, type ProtocolEventName, type ProtocolEventPayload, type ProtocolMethod, type ProtocolReadyMessage, type ProtocolReconnectMessage, type ProtocolRequestMessage, type ProtocolResultMessage, type ResolvedClaimValue, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, type StorageDeleteParams, type StorageDeleteResult, type StorageDirectoryParams, type StorageDirectoryResult, type StorageGetParams, type StorageGetResult, type StorageListEntry, type StorageListParams, type StorageListResult, type StoragePutParams, type StoragePutResult, type VerifiedAppIdentity, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity };
|
package/dist/protocol.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-
|
|
1
|
+
export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-W2TNWBLP.js';
|
|
2
2
|
//# sourceMappingURL=protocol.js.map
|
|
3
3
|
//# sourceMappingURL=protocol.js.map
|
package/dist/server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProtocolErrorCode, P2pkhTransferAssetId, ProtocolRequestMessage, NetworkIdentity, ProtocolMethod, MethodParams, AppIdentityProofV1, VerifiedAppIdentity, ProtocolResultMessage, ProtocolReadyMessage, ProtocolClosingMessage, MethodResult, ProtocolError, ProtocolEventPayload } from './protocol.js';
|
|
1
|
+
import { ProtocolErrorCode, P2pkhTransferAssetId, ProtocolRequestMessage, NetworkIdentity, ProtocolMethod, MethodParams, AppIdentityProofV1, VerifiedAppIdentity, ProtocolResultMessage, ProtocolReadyMessage, ProtocolClosingMessage, MethodResult, ProtocolError, ProtocolEventPayload, ProtocolReconnectMessage } from './protocol.js';
|
|
2
2
|
|
|
3
3
|
/** 校验失败:抛出的对象。service 会捕获并组装 ProtocolError。 */
|
|
4
4
|
declare class ProtocolValidationError extends Error {
|
|
@@ -66,8 +66,6 @@ declare function verifyAppIdentityProof(raw: unknown): VerifiedAppIdentity;
|
|
|
66
66
|
/** 校验 session 中已验证 proof 的不可变 snapshot。 */
|
|
67
67
|
declare function isVerifiedAppIdentitySnapshot(value: unknown): value is VerifiedAppIdentity;
|
|
68
68
|
|
|
69
|
-
/** Connect v1 接收端。只拥有协议状态,不拥有钱包授权、私钥、余额或持久业务账本。 */
|
|
70
|
-
|
|
71
69
|
/** 窗口对象只作为消息源身份与发送目标;不读取跨源页面内容。 */
|
|
72
70
|
interface ConnectPeer {
|
|
73
71
|
postMessage(message: unknown, targetOrigin: string): void;
|
|
@@ -112,11 +110,14 @@ interface ReceiverRequest<M extends ProtocolMethod = ProtocolMethod> {
|
|
|
112
110
|
readonly walletGeneration: string;
|
|
113
111
|
readonly runGeneration: string;
|
|
114
112
|
readonly bindingId?: string;
|
|
113
|
+
readonly authorizationId?: string;
|
|
115
114
|
readonly signal: AbortSignal;
|
|
116
115
|
}
|
|
117
116
|
/** 判断建立连接的方法;ready 只表示传输可用,不属于身份授权。 */
|
|
118
117
|
declare function isEstablishing(method: string): boolean;
|
|
119
118
|
/** 生产钱包与闭环测试共用同一接收端,不内置测试业务或默认自动授权。 */
|
|
119
|
+
/** 外部恢复控制只携带不透明授权引用,不能夹带业务参数或钱包选择器。 */
|
|
120
|
+
declare function parseReconnectMessage(data: unknown): ProtocolReconnectMessage | null;
|
|
120
121
|
declare class KeymasterConnectReceiver {
|
|
121
122
|
private readonly options;
|
|
122
123
|
private readonly bindings;
|
|
@@ -143,6 +144,8 @@ declare class KeymasterConnectReceiver {
|
|
|
143
144
|
replyError(context: ReceiverRequest, error: ProtocolError): void;
|
|
144
145
|
/** 事件只给当前有效绑定添加接收端上下文;业务发布者不能自报绑定/钱包身份。 */
|
|
145
146
|
sendEvent(target: ConnectPeer, origin: string, event: ProtocolEventPayload): void;
|
|
147
|
+
/** 只读核对现存瞬时绑定;恢复轮询不能不断替换仍有效的绑定或打断在途业务。 */
|
|
148
|
+
matchesBinding(source: ConnectPeer, origin: string, id: string | undefined): boolean;
|
|
146
149
|
/** ready/closing 只承载生命周期,不携带授权或业务结果。 */
|
|
147
150
|
sendReady(target: ConnectPeer): void;
|
|
148
151
|
/** 同一运行期至多通知一次 closing,发送失败不重试。 */
|
|
@@ -159,4 +162,4 @@ declare class KeymasterConnectReceiver {
|
|
|
159
162
|
private send;
|
|
160
163
|
}
|
|
161
164
|
|
|
162
|
-
export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, type ConnectPeer, type ConnectReceiverOptions, KeymasterConnectReceiver, ProtocolEventPayload, ProtocolValidationError, type ReceiverLifecycle, type ReceiverMessage, type ReceiverPeerPolicy, type ReceiverRequest, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
|
|
165
|
+
export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, type ConnectPeer, type ConnectReceiverOptions, KeymasterConnectReceiver, ProtocolEventPayload, ProtocolValidationError, type ReceiverLifecycle, type ReceiverMessage, type ReceiverPeerPolicy, type ReceiverRequest, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-
|
|
1
|
+
import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-W2TNWBLP.js';
|
|
2
2
|
import { secp256k1 } from '@noble/curves/secp256k1.js';
|
|
3
3
|
import { sha256 } from '@noble/hashes/sha2.js';
|
|
4
4
|
|
|
@@ -365,11 +365,6 @@ function validateChannelSubscriptionSetParams(raw) {
|
|
|
365
365
|
}
|
|
366
366
|
return { channels };
|
|
367
367
|
}
|
|
368
|
-
function validatePriceParams(raw) {
|
|
369
|
-
const obj = expectObject(raw, "price params");
|
|
370
|
-
requireExactKeys(obj, [], "price params");
|
|
371
|
-
return {};
|
|
372
|
-
}
|
|
373
368
|
function validateExactChannel(value, field = "channel") {
|
|
374
369
|
const channel = expectString(value, field);
|
|
375
370
|
if (channel.length === 0 || channel === "*") {
|
|
@@ -761,11 +756,6 @@ function parseRequestMessage(raw, receiverIdentity) {
|
|
|
761
756
|
case "channel.subscription_set":
|
|
762
757
|
normalized = validateChannelSubscriptionSetParams(params);
|
|
763
758
|
break;
|
|
764
|
-
case "price.get":
|
|
765
|
-
case "price.subscribe":
|
|
766
|
-
case "price.unsubscribe":
|
|
767
|
-
normalized = validatePriceParams(params);
|
|
768
|
-
break;
|
|
769
759
|
case "storage.list":
|
|
770
760
|
normalized = validateStorageListParams(params);
|
|
771
761
|
break;
|
|
@@ -803,6 +793,12 @@ function parseRequestMessage(raw, receiverIdentity) {
|
|
|
803
793
|
function isEstablishing(method) {
|
|
804
794
|
return ["connect.login", "connect.resume", "connect.launch"].includes(method);
|
|
805
795
|
}
|
|
796
|
+
function parseReconnectMessage(data) {
|
|
797
|
+
if (!data || typeof data !== "object") return null;
|
|
798
|
+
const value = data;
|
|
799
|
+
if (value.v !== PROTOCOL_VERSION || value.type !== "reconnect" || typeof value.id !== "string" || !value.id || value.id.length > 128 || typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128 || value.bindingId !== void 0 && typeof value.bindingId !== "string" || Object.keys(value).some((key) => !["v", "type", "id", "authorizationId", "bindingId"].includes(key))) return null;
|
|
800
|
+
return value;
|
|
801
|
+
}
|
|
806
802
|
var KeymasterConnectReceiver = class {
|
|
807
803
|
constructor(options) {
|
|
808
804
|
this.options = options;
|
|
@@ -838,7 +834,8 @@ var KeymasterConnectReceiver = class {
|
|
|
838
834
|
/** 校验并签发请求上下文。重复在途 ID 被忽略;非法可信请求返回标准错误。 */
|
|
839
835
|
async accept(event) {
|
|
840
836
|
if (!this.isAllowedPeer(event)) return null;
|
|
841
|
-
const
|
|
837
|
+
const reconnect = parseReconnectMessage(event.data);
|
|
838
|
+
const raw = reconnect ? { v: PROTOCOL_VERSION, type: "request", id: reconnect.id, method: "connect.resume", params: {} } : event.data;
|
|
842
839
|
if (!raw || typeof raw !== "object" || raw.type !== "request") return null;
|
|
843
840
|
if (typeof raw.id === "string" && this.pending.get(event.source)?.has(raw.id)) return null;
|
|
844
841
|
try {
|
|
@@ -872,6 +869,7 @@ var KeymasterConnectReceiver = class {
|
|
|
872
869
|
walletGeneration: before.walletGeneration,
|
|
873
870
|
runGeneration: before.runGeneration,
|
|
874
871
|
bindingId: establishing ? void 0 : binding.id,
|
|
872
|
+
...reconnect ? { authorizationId: reconnect.authorizationId } : {},
|
|
875
873
|
signal: abort.signal
|
|
876
874
|
});
|
|
877
875
|
this.isAllowedPeer(event, true);
|
|
@@ -940,6 +938,11 @@ var KeymasterConnectReceiver = class {
|
|
|
940
938
|
} catch {
|
|
941
939
|
}
|
|
942
940
|
}
|
|
941
|
+
/** 只读核对现存瞬时绑定;恢复轮询不能不断替换仍有效的绑定或打断在途业务。 */
|
|
942
|
+
matchesBinding(source, origin, id) {
|
|
943
|
+
const binding = this.bindings.get(source), lifecycle = this.options.lifecycle();
|
|
944
|
+
return !!binding && binding.id === id && binding.origin === origin && binding.walletGeneration === lifecycle.walletGeneration && binding.runGeneration === lifecycle.runGeneration && this.isAllowedPeer({ source, origin, data: null });
|
|
945
|
+
}
|
|
943
946
|
/** ready/closing 只承载生命周期,不携带授权或业务结果。 */
|
|
944
947
|
sendReady(target) {
|
|
945
948
|
this.sendControl(target, "ready");
|
|
@@ -990,6 +993,6 @@ var KeymasterConnectReceiver = class {
|
|
|
990
993
|
}
|
|
991
994
|
};
|
|
992
995
|
|
|
993
|
-
export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
|
|
996
|
+
export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
|
|
994
997
|
//# sourceMappingURL=server.js.map
|
|
995
998
|
//# sourceMappingURL=server.js.map
|