keymaster-connect 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,14 +2,16 @@
2
2
 
3
3
  Keymaster Connect v1 的独立生产协议栈,包含 Client、公开契约和 Receiver,不依赖钱包源码或 WebLoom。
4
4
 
5
- 无 scope 的 `keymaster-connect`,本包版本为 **0.1.8**,包含完整应用发布证明与显式登录/启动;wire 始终保持 v1。安装:
5
+ 无 scope 的 `keymaster-connect`,本包版本为 **0.4.0**,包含完整应用发布证明、带挑战码的显式登录/启动、链尖订阅与批量交易查询、可恢复 MSFile 读取;wire 始终保持 v1。安装:
6
6
 
7
7
  ```sh
8
- npm install --save-exact keymaster-connect@0.1.8
8
+ pnpm add --save-exact keymaster-connect@0.4.0
9
9
  ```
10
10
 
11
11
  支持钱包内嵌 iframe、钱包打开 App(appView)和 App 主动打开完整钱包(popup,默认)。App 主动连接打开完整钱包根页面 `/`,不打开独立协议页;错误和超时不关闭钱包窗口。完整说明见 [App 主动打开钱包](doc/site/concepts/popup-mode.md)。
12
12
 
13
+ 需要站点会话时,App 后端先签发 32 字节一次性挑战码,再将 lowercase hex 作为 `loginChallenge` 传给 `login` 或 `launch`。钱包在结果中返回 `loginProof`;后端必须验证签名、挑战码、网络、公钥和本站 origin 后建立会话。挑战码不得写入日志或重复使用。
14
+
13
15
  许可证沿用仓库原有 AGPL v3,见包内 LICENSE。
14
16
 
15
17
  ```ts
@@ -41,7 +43,7 @@ const { results } = await client.domain.profiles(authorPublicKeys);
41
43
  const publicKey = await client.domain.getPublicKey("alice");
42
44
  ```
43
45
 
44
- Profile 包含 `publicKeyHex`、带后缀的主要域名 `domain`、`expiresAt`、可选公开文字 `text` 和 BitFS 图片引用 `avatar`、`header`。批量接口最多接收 100 个公钥,按输入顺序返回 `{ publicKeyHex, profile }` 或 `{ publicKeyHex, error: { code } }`。域名查询当前可用工作树候选包验证。
46
+ Profile 包含 `publicKeyHex`、带后缀的主要域名 `domain`、`expiresAt`、可选公开文字 `text` 和 BitFS 图片引用 `avatar`、`header`。批量接口最多接收 100 个公钥,按输入顺序返回 `{ publicKeyHex, profile }` 或 `{ publicKeyHex, error: { code } }`。域名查询由 `0.3.0` 及以后的正式版本提供。
45
47
 
46
48
  ## 钱包接收端
47
49
 
@@ -59,9 +61,9 @@ import { KeymasterConnectReceiver } from "keymaster-connect/server";
59
61
 
60
62
  公开类型和纯常量也可从 `keymaster-connect/protocol` 引用;客户端入口不加载接收端代码。
61
63
 
62
- 仓库根目录是 SDK:`npm run typecheck` 检查类型,`npm run build` 只构建 SDK,`npm publish` 从根目录发布 SDK 新版本(已发布的版本不可覆盖)。发布命令见 [RELEASING.md](RELEASING.md)。
64
+ 仓库根目录是 SDK:`pnpm run typecheck` 检查类型,`pnpm run build` 只构建 SDK,`pnpm publish` 从根目录发布 SDK 新版本(已发布的版本不可覆盖)。发布命令见 [RELEASING.md](RELEASING.md)。
63
65
 
64
- 文档是私有的 [doc 子项目](doc/README.md):根目录执行 `npm run api:generate` 生成 API,`npm run doc:build` 构建站点,`npm run doc:dev` 启动预览开发。文档不进入 npm 发布包。包版本与 wire 版本不是同一概念。
66
+ 文档是私有的 [doc 子项目](doc/README.md):根目录执行 `pnpm run api:generate` 生成 API,`pnpm run doc:build` 构建站点,`pnpm run doc:dev` 启动预览开发。文档不进入 npm 发布包。包版本与 wire 版本不是同一概念。
65
67
 
66
68
  ## 数据持久化
67
69
 
@@ -77,6 +79,9 @@ SDK 不提供 App 文件或对象存储接口。App 自行管理数据;独立
77
79
 
78
80
  `client.chain` uses the session network for height, history, raw transactions, unspent outputs and broadcast.
79
81
 
82
+ `chain.subscribeHeight(handler)` returns an unsubscribe function. The listener receives `{ height, blockHash }` for the latest available chain tip and changes to either field. `chain.getHeight()` reads the same wallet cache once. Before the first successful sync, the read reports `internal_error` and the subscription waits for the first tip.
83
+
84
+ `client.chain.getTransactions({ txids, mode: "raw" | "status" })` 支持一次查询最多 20 个交易 ID。确认记录含区块高度和哈希。`raw` 模式同时返回原始交易,`status` 模式只返回观察状态。响应缺项可按原 ID 重试。
80
85
 
81
86
  ## MSFile
82
87
 
@@ -86,3 +91,11 @@ SDK 不提供 App 文件或对象存储接口。App 自行管理数据;独立
86
91
  - `msfile.readBlock({ sourceId, seedHashHex, blockHashHex })` reads a block from the selected source.
87
92
  - `msfile.import({ fileName, content })` imports content and returns its seed hash once the seller can find it.
88
93
  - `msfile.sellerStatus()` checks seller readiness.
94
+
95
+ Version `0.4.0` supports resumable reads. Save a `clientRequestId` before calling `msfile.read(seedHashHex, { clientRequestId })` or `msfile.openContent({ seedHashHex, clientRequestId })`. Use `msfile.readStatus(clientRequestId)` to look up the same read after reconnecting.
96
+
97
+ `readStatus` and `openContent` report `pending` while the wallet is working, `available` when the complete file is readable, and `stopped` when the app should stop waiting. `stopped` includes `error.code` and `error.message`. If the wallet has an interrupted purchase, the user can resume it there and the app can check the same read ID again. `funds` reports settlement separately.
98
+
99
+ `msfile.readRange({ clientRequestId, offset, length })` reads verified ranges while the complete file is still pending.
100
+
101
+ `msfile.downloadPrice()` reads the wallet's maximum manual full-block price. Pass `maxFullBlockPriceSatoshis` to `openContent` to choose the new download's initial full-block price ceiling. The app may call `downloadPrice({ clientRequestId, maxFullBlockPriceSatoshis })` for a running download that it was authorized to adjust. Seed prices follow the wallet's existing rules.
@@ -42,6 +42,7 @@ var PROTOCOL_METHODS = [
42
42
  "chain.get_height",
43
43
  "chain.list_script_history",
44
44
  "chain.get_transaction",
45
+ "chain.get_transactions",
45
46
  "chain.list_script_unspent",
46
47
  "chain.broadcast",
47
48
  "application.key",
@@ -50,6 +51,10 @@ var PROTOCOL_METHODS = [
50
51
  "msfile.seller.status",
51
52
  "msfile.import",
52
53
  "msfile.content.read",
54
+ "msfile.content.status",
55
+ "msfile.content.open",
56
+ "msfile.content.price",
57
+ "msfile.content.range",
53
58
  "domain.profiles",
54
59
  "domain.get_public_key",
55
60
  "connect.login",
@@ -67,5 +72,5 @@ var PROTOCOL_METHODS = [
67
72
  ];
68
73
 
69
74
  export { DOMAIN_MAX_PROFILES, 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, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity };
70
- //# sourceMappingURL=chunk-A4VCQSB5.js.map
71
- //# sourceMappingURL=chunk-A4VCQSB5.js.map
75
+ //# sourceMappingURL=chunk-QUZZ2OXO.js.map
76
+ //# sourceMappingURL=chunk-QUZZ2OXO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol.ts"],"names":[],"mappings":";AAWO,SAAS,mBAAmB,KAAA,EAA4B;AAC3D,EAAA,IAAI,KAAA,KAAU,UAAU,KAAA,KAAU,MAAA;AAC9B,IAAA,MAAM,IAAI,UAAU,kCAAkC,CAAA;AAC1D,EAAA,OAAO,KAAA;AACX;AAEO,SAAS,wBAAwB,KAAA,EAAiC;AACrE,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,UAAU,QAAA,IAAY,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC1D,IAAA,MAAM,IAAI,UAAU,6BAA6B,CAAA;AACrD,EAAA,MAAM,KAAA,GAAQ,KAAA;AACd,EAAA,IAAI,OAAO,MAAM,YAAA,KAAiB,QAAA,IAAY,CAAC,yBAAA,CAA0B,IAAA,CAAK,MAAM,YAAY,CAAA;AAC5F,IAAA,MAAM,IAAI,UAAU,wCAAwC,CAAA;AAChE,EAAA,OAAO,MAAA,CAAO,MAAA,CAAO,EAAE,UAAA,EAAY,kBAAA,CAAmB,KAAA,CAAM,UAAU,CAAA,EAAG,YAAA,EAAc,KAAA,CAAM,YAAA,CAAa,WAAA,IAAe,CAAA;AAC7H;AAEO,SAAS,mBAAA,CAAoB,MAAuB,KAAA,EAAiC;AACxF,EAAA,OAAO,IAAA,CAAK,UAAA,KAAe,KAAA,CAAM,UAAA,IAAc,IAAA,CAAK,aAAa,WAAA,EAAY,KAAM,KAAA,CAAM,YAAA,CAAa,WAAA,EAAY;AACtH;AA0EO,IAAM,kBAAA,GAAqB;AAG3B,IAAM,uBAAA,GAA0B;AAEhC,IAAM,qBAAA,GAAwB,KAAK,IAAA,GAAO;AAE1C,IAAM,yBAAyB,GAAA,GAAM;AAErC,IAAM,wBAAA,GAA2B;AAEjC,IAAM,8BAAA,GAAiC;AAEvC,IAAM,0BAA0B,GAAA,GAAM;AAEtC,IAAM,wBAAA,GAA2B;AAMjC,IAAM,sBAAA,GAAyB;AAM/B,SAAS,sBAAsB,KAAA,EAAiC;AACnE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,KAChB,UAAU,sBAAA,IAA0B,qCAAA,CAAsC,KAAK,KAAK,CAAA,CAAA;AAChG;AAqJO,IAAM,gBAAA,GAAmB;AAwXzB,IAAM,mBAAA,GAAsB;AA6B5B,IAAM,gBAAA,GAAmB;AAAA,EAC5B,cAAA;AAAA,EACA,aAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,aAAA;AAAA,EACA,gBAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA,uBAAA;AAAA,EACA,wBAAA;AAAA,EACA,2BAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,0BAAA;AAAA,EACA,0BAAA;AAAA,EACA,sBAAA;AAAA,EACA,eAAA;AAAA,EACA,qBAAA;AAAA,EACA,uBAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,iBAAA;AAAA,EACA,uBAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA;AAAA,EAEA,iBAAA;AAAA,EACA,0BAAA;AAAA;AAAA;AAAA;AAAA,EAIA,aAAA;AAAA,EACA,kBAAA;AAAA,EACA;AACJ","file":"chunk-QUZZ2OXO.js","sourcesContent":["/** Connect v1 公开契约。独立于钱包内部执行 DTO、能力框架和持久化。 */\nexport type { AiToolSchema, AiToolDefinition, AiToolsRegistered, AiToolMessage } from \"./tools.js\";\n\n/** 身份网络在创建/导入时确定;公钥相同也不能跨网复用业务身份。 */\nexport type BsvNetwork = \"main\" | \"test\";\n\nexport interface NetworkIdentity {\n readonly bsvNetwork: BsvNetwork;\n readonly publicKeyHex: string;\n}\n\nexport function validateBsvNetwork(value: unknown): BsvNetwork {\n if (value !== \"main\" && value !== \"test\")\n throw new TypeError(\"BSV network must be main or test\");\n return value;\n}\n\nexport function validateNetworkIdentity(value: unknown): NetworkIdentity {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new TypeError(\"Network identity is invalid\");\n const input = value as Record<string, unknown>;\n if (typeof input.publicKeyHex !== \"string\" || !/^(02|03)[0-9a-f]{64}$/iu.test(input.publicKeyHex))\n throw new TypeError(\"Network identity public key is invalid\");\n return Object.freeze({ bsvNetwork: validateBsvNetwork(input.bsvNetwork), publicKeyHex: input.publicKeyHex.toLowerCase() });\n}\n\nexport function sameNetworkIdentity(left: NetworkIdentity, right: NetworkIdentity): boolean {\n return left.bsvNetwork === right.bsvNetwork && left.publicKeyHex.toLowerCase() === right.publicKeyHex.toLowerCase();\n}\n\n//\n// 说明:Channel 是唯一的消息/发布抽象。这里不暴露 Supplier、SSP Wire、私钥、\n// 付款信息或远端历史;这些都属于 Coordinator 和 SatSubscription 内部。\n/** ChannelProtocol/SSP 共用的递归 JSON 值。 */\nexport type JSONValue = null | boolean | number | string | JSONValue[] | {\n [key: string]: JSONValue;\n};\n\nexport interface ChannelPublishParams {\n /** 要发布到的 SSP 精确频道;不允许通配符。 */\n channel: string;\n /** App 自己定义的 JSON 内容;协议标识也应放在这里。 */\n content: JSONValue;\n}\n\nexport interface ChannelPublishResult {\n /** 由 Keymaster/ChannelProtocol 生成的消息编号。 */\n messageId: string;\n /**\n * 出站签名明文的精确字节(已签名、未加密);只有私密发布返回。\n * 调用方可把它作为出站证据原样保存,不需要也不允许重新签名。\n */\n signedMessage?: Uint8Array;\n}\n\nexport interface ChannelSubscriptionSetParams {\n /** 替换当前 caller 的完整精确频道集合;空数组表示释放全部订阅。 */\n channels: string[];\n}\n\nexport interface ChannelSubscriptionSetResult {\n /** Coordinator 已接受的当前 caller 逻辑期望集合;不代表 Supplier 物理订阅已完成。 */\n channels: string[];\n /**\n * Coordinator/Mux 返回的当前物理状态快照。\n * 旧 runtime 可以省略该字段;当前 Coordinator 会为每个 accepted\n * channel 返回一份权威快照,使新 caller 不必等待下一次状态事件。\n */\n statuses?: ChannelSubscriptionStatus[];\n}\n\n/** 当前 caller union 在 Coordinator/SSP 侧的物理订阅阶段。 */\nexport type ChannelSubscriptionPhase = \"idle\" | \"subscribing\" | \"subscribed\" | \"retrying\" | \"blocked\";\n\n/** 订阅失败的稳定业务错误码;不得把底层异常/堆栈直接暴露给插件。 */\nexport type ChannelSubscriptionErrorCode = \"config\" | \"connect\" | \"identity\" | \"protocol\" | \"balance\" | \"unknown_result\" | \"validation\" | \"unavailable\" | \"conflict\";\n\nexport interface ChannelSubscriptionStatus {\n channel: string;\n phase: ChannelSubscriptionPhase;\n errorCode: ChannelSubscriptionErrorCode | null;\n errorMessage: string | null;\n updatedAtMs: number;\n}\n\nexport interface ChannelMessageReceivedEventData {\n /** 实际收到的精确频道。 */\n channel: string;\n /** ChannelProtocol 验签得到的作者压缩公钥 hex。 */\n publisherPublicKeyHex: string;\n /** ChannelProtocol 消息编号。 */\n messageId: string;\n /** 已验签的 App JSON 内容。 */\n content: JSONValue;\n /**\n * 入站私密消息的加密信封精确字节(受信任插件用于原样留证)。\n * 公共消息或旧 Coordinator 可以省略。\n */\n rawEnvelope?: Uint8Array;\n}\n\n/** libp2p protocol ID;wire 真值来自 MSFile Proxy Wire Messages v1。 */\nexport const MSFILE_PROTOCOL_ID = \"/msfile/1.0.0\";\n\n/** Frame / 内容硬上限。与 wire 规范一致,两层共同执行。 */\nexport const MSFILE_MAX_HEADER_BYTES = 65536;\n\nexport const MSFILE_MAX_SEED_BYTES = 16 * 1024 * 1024;\n\nexport const MSFILE_MAX_BLOCK_BYTES = 256 * 1024;\n\nexport const MSFILE_MAX_CONTENT_BYTES = MSFILE_MAX_SEED_BYTES;\n\nexport const MSFILE_MAX_ERROR_MESSAGE_BYTES = 1024;\n\nexport const MSFILE_BLOCK_SIZE_BYTES = 256 * 1024;\n\nexport const MSFILE_DIGEST_SIZE_BYTES = 32;\n\n/** 单个内容对象的最高金额。规范十进制字符串:\"0\" 表示显式不限。 */\nexport type MsFileSatoshiAmount = string;\n\n/** Keymaster 内置本地 BitFS 来源的稳定路由标识。 */\nexport const MSFILE_LOCAL_SOURCE_ID = \"local-bitfs\";\n\n/** MSFile 来源类型;本地来源不经过 `/msfile/1.0.0`。 */\nexport type MsFileSourceKind = \"local-bitfs\" | \"remote-proxy\";\n\n/** 校验 MSFile 来源路由标识;拒绝路径字符和无界文本。 */\nexport function isValidMsFileSourceId(input: unknown): input is string {\n return typeof input === \"string\"\n && (input === MSFILE_LOCAL_SOURCE_ID || /^remote-proxy:(02|03)[0-9a-f]{64}$/u.test(input));\n}\n\nexport interface MsFileStatParams {\n seedHashHex: string;\n}\n\nexport interface MsFileContentReadParams extends MsFileStatParams {\n clientRequestId?: string;\n /** 本次下载任务的完整数据块单价上限,单位聪。 */\n maxFullBlockPriceSatoshis?: string;\n}\n\nexport interface MsFileReadStatusParams {\n clientRequestId: string;\n}\n\nexport type MsFileContentOpenParams = MsFileContentReadParams & MsFileReadStatusParams;\n\n/** 查询钱包允许的块价范围,或按读取编号修改当前任务的手动块价。 */\nexport interface MsFileDownloadPriceParams {\n clientRequestId?: string;\n maxFullBlockPriceSatoshis?: string;\n}\n\nexport interface MsFileDownloadPriceResult {\n /** 钱包允许应用设置的最大完整块单价,单位聪。 */\n walletMaxFullBlockPriceSatoshis: string;\n}\n\nexport interface MsFileContentRangeParams extends MsFileReadStatusParams {\n offset: number;\n length: number;\n}\n\nexport interface MsFileContentRangeResult {\n fileSizeBytes?: number;\n mediaType?: string;\n content?: BinaryField;\n}\n\ninterface MsFileReadStatusDetails {\n clientRequestId: string;\n seedHashHex: string;\n taskId?: string;\n verifiedBlockCount?: number;\n totalBlockCount?: number;\n funds?: \"none\" | \"pending\" | \"settled\" | \"problem\";\n /** 此读取记录有权调整关联下载任务的手动块价。 */\n priceAdjustable?: true;\n /** 当前任务的完整数据块单价上限,单位聪。 */\n currentMaxFullBlockPriceSatoshis?: string;\n}\n\n/** Action for the caller: wait for content, read the complete file, or stop waiting. */\nexport type MsFileReadStatus = MsFileReadStatusDetails & (\n | { phase: \"pending\" | \"available\"; error?: never }\n | { phase: \"stopped\"; error: ProtocolError }\n);\n\nexport interface MsFileStatAvailableEntry {\n supplierPublicKeyHex: string;\n status: \"available\";\n recommendedFilename: string;\n /** 十进制字符串形式的 uint64 字节数。 */\n fileSizeBytes: MsFileSatoshiAmount;\n mediaType: string;\n}\n\nexport interface MsFileStatAbsentEntry {\n supplierPublicKeyHex: string;\n status: \"absent\";\n}\n\nexport interface MsFileStatDiscoveringEntry {\n supplierPublicKeyHex: string;\n status: \"discovering\";\n retryAfterMs: number;\n}\n\nexport interface MsFileStatQuotedEntry {\n supplierPublicKeyHex: string;\n status: \"quoted\";\n recommendedFilename: string;\n fileSizeBytes: MsFileSatoshiAmount;\n mediaType: string;\n minSeedPriceSatoshis: MsFileSatoshiAmount;\n maxSeedPriceSatoshis: MsFileSatoshiAmount;\n minFullBlockPriceSatoshis: MsFileSatoshiAmount;\n maxFullBlockPriceSatoshis: MsFileSatoshiAmount;\n}\n\nexport interface MsFileStatNetworkErrorEntry {\n supplierPublicKeyHex: string;\n status: \"network-error\";\n}\n\nexport type MsFileSupplierStat = MsFileStatAvailableEntry | MsFileStatAbsentEntry | MsFileStatDiscoveringEntry | MsFileStatQuotedEntry | MsFileStatNetworkErrorEntry;\n\nexport /** 远程 Proxy 结果补充来源路由信息后的公共视图。 */\ntype MsFileRemoteSourceStat<T> = T extends MsFileSupplierStat ? T & {\n sourceId: string; /** 固定为远程 Proxy。 */\n sourceKind: \"remote-proxy\";\n} : never;\n\nexport /** local 结果没有远程供应商公钥,不能用假公钥占位。 */\ntype MsFileLocalSourceStat<T> = T extends MsFileSupplierStat ? Omit<T, \"supplierPublicKeyHex\"> & {\n sourceId: typeof MSFILE_LOCAL_SOURCE_ID; /** 固定为本地 BitFS。 */\n sourceKind: \"local-bitfs\";\n} : never;\n\n/** 统一 MSFile API 返回的 local/remote 来源状态。 */\nexport type MsFileSourceStat = MsFileRemoteSourceStat<MsFileSupplierStat> | MsFileLocalSourceStat<MsFileSupplierStat>;\n\nexport interface MsFileStatResult {\n seedHashHex: string;\n /** 所有本地与远程来源;本地来源固定排在第一位。 */\n sources: MsFileSourceStat[];\n}\n\nexport interface MsFileSeedReadParams {\n /** 要读取的来源路由标识。 */\n sourceId: string;\n seedHashHex: string;\n}\n\nexport interface MsFileBlockReadParams {\n /** 要读取的来源路由标识。 */\n sourceId: string;\n /** Block 所属 Seed;remote wire 不发送该字段。 */\n seedHashHex: string;\n blockHashHex: string;\n}\n\nexport interface MsFileReadResult {\n contentHashHex: string;\n content: BinaryField;\n}\n\nexport interface BinaryField {\n /** 固定 \"binary\"。缺省 / 其它值一律拒绝。 */\n $type: \"binary\";\n /** 真实字节;`structured clone` 会原样传过去。 */\n bytes: ArrayBuffer;\n /** 可选的内容类型;密文 / 图片 / 文件等有明确类型时填写。 */\n mime?: string;\n}\n\n/** 协议版本号;当前固定为 1。 */\n// 产品尚未上线,公开协议持续在 v1 内演进,不维护旧字段兼容分支。\nexport const PROTOCOL_VERSION = 1;\n\n/**\n * 协议错误码。`error.message` 走英文;UI 展示由调用方决定。\n * 错误码集合是稳定可判定的:第三方接入方写 switch 时不会因为新加错误\n * 类型而误把\"未识别\"分支当作\"成功\"。\n *\n * 触发语义(施工单 001 收口):\n * - invalid_request 顶层 message 结构 / 字段类型 / aud-iat-exp\n * 规则 / BinaryField 形状不合法;\n * 第一条非法 request 直接被 popup 忽略,\n * 不回 result(\"情况 B\")。\n * - invalid_origin identity.get / intent.sign 的\n * `params.aud !== event.origin`。\n * - user_rejected 用户在确认页或解锁页点\"取消\"。\n * - active_key_unavailable vault 已 unlocked,但 walletState 没有 ready\n * active key(\"情况 D\")。\n * - decrypt_failed cipher.decrypt 失败;origin 不匹配 / nonce\n * 错误 / 密文被篡改 / 内层结构不合法,V1\n * 统一为这一种错误。\n * - internal_error 兜底:用户可见但不属于以上分类的失败。\n *\n * 注意:V1 **不**对外暴露 `wallet_locked` 错误码。locked 态在 popup 内\n * 直接走解锁页(\"情况 C\"),用户取消解锁统一回 `user_rejected`。任何\n * \"locked 时直接拒绝\"的中间态都不属于 V1 公开语义。\n */\nexport type ProtocolErrorCode =\n/** Transport authority was revoked or belongs to another wallet/Worker generation. */\n\"connection_expired\" | \"authorization_expired\" | \"invalid_request\" | \"invalid_origin\" | \"user_rejected\" | \"active_key_unavailable\" | \"decrypt_failed\"\n/**\n * 请求资产与连接绑定的钱包网络不一致;accept 阶段拒绝,不进入业务执行。\n */\n | \"asset_not_enabled\"\n/** Connect v1 明确排除的方法族(新费用池签名等)。 */\n | \"unsupported_scope\"\n/** 通用支付需要已建立的可信来源会话(origin 是归属唯一基准)。 */\n | \"identity_required\"\n/** 当前硬件后端缺少 Connect 支付所需的受信展示/结构检查。 */\n | \"hardware_connect_payment_unsupported\" | \"payment_not_found\"\n/** Too many non-terminal Connect payment responsibilities. */\n | \"payment_pending_limit\"\n/** Same stable request key with different facts, or a resumable MSFile read failure. */\n | \"id_conflict\" | \"msfile_read_not_found\" | \"msfile_read_interrupted\" | \"msfile_read_cancelled\" | \"msfile_range_timeout\"\n | \"name_not_found\" | \"invalid_name\" | \"invalid_public_key\" | \"primary_name_required\"\n | \"domain_service_not_configured\" | \"domain_service_unavailable\" | \"domain_network_mismatch\"\n// MSFile 稳定公开错误码(施工单 §6)。supplier wire error code 保留为\n// 内部诊断,不把任意远端字符串直接变成公开 code。\n | \"msfile_not_configured\" | \"msfile_unavailable\" | \"msfile_identity_required\" | \"msfile_supplier_not_found\" | \"msfile_supplier_disabled\" | \"msfile_invalid_hash\" | \"msfile_price_limit_exceeded\" | \"msfile_integrity_error\" | \"msfile_content_not_found\" | \"msfile_rate_limited\" | \"msfile_supplier_error\" | \"msfile_transport_error\" | \"msfile_protocol_error\" | \"internal_error\";\n\nexport interface ProtocolError {\n code: ProtocolErrorCode;\n message: string;\n}\n\nexport interface ProtocolReadyMessage {\n v: typeof PROTOCOL_VERSION;\n type: \"ready\";\n}\n\nexport interface ProtocolClosingMessage {\n v: typeof PROTOCOL_VERSION;\n type: \"closing\";\n}\n\nexport interface ProtocolCancelMessage {\n /** Present for cancellation of an already-bound business request. */\n bindingId?: string;\n v: typeof PROTOCOL_VERSION;\n type: \"cancel\";\n /** 要取消的原 `request.id`。 */\n id: string;\n}\n\n/* ============== 顶层 event 报文(施工单 2026-09-02 Channel) ============== */\n/**\n * 协议对外 event 名常量集合(server-pushed 事件)。\n *\n * 设计缘由:\n * - `channel.message_received` 是已验签的 Channel 公开消息,只发送给\n * 当前 session 已精确订阅的频道;\n * - `chain.height_changed` 是当前连接钱包已同步的链尖快照;\n */\nexport type ProtocolEventName = \"channel.message_received\" | \"chain.height_changed\";\n\n/** 钱包同一次同步取得的链尖高度和哈希。 */\nexport interface ChainHeightResult {\n height: number;\n /** 64 位小写十六进制区块哈希。 */\n blockHash: string;\n}\n\nexport interface IdentityGetParams {\n /** 目标站点 origin;必须等于 `event.origin`,否则拒绝。 */\n aud: string;\n /** 签发时间(unix seconds)。 */\n iat: number;\n /** 过期时间(unix seconds);必须严格大于 iat。 */\n exp: number;\n /** 人类可读确认文案。 */\n text: string;\n /**\n * 请求索要的 claim 名列表。\n * - Keymaster 只返回请求里明确列出且当前本地有真值来源的 claim;\n * - 不存在的 claim 直接省略,不报错。\n */\n claims?: string[];\n}\n\n/** identity.get 解析后的 claim 真值。 */\nexport type ResolvedClaimValue = string | number | boolean | null | BinaryField | ResolvedClaimValue[] | {\n [key: string]: ResolvedClaimValue;\n};\n\nexport interface IdentityGetResult {\n /** Identity 信封最终真值字节(Deterministic CBOR)。 */\n identityEnvelope: BinaryField;\n /** 签名(compact 64-byte secp256k1)。 */\n signature: BinaryField;\n /** 签名主体公钥(33-byte compressed)。 */\n subject: {\n publicKey: BinaryField;\n };\n /** Keymaster 本次实际返回给调用方的 claim 真值。 */\n resolvedClaims: Record<string, ResolvedClaimValue>;\n}\n\nexport interface IntentSignParams {\n /** 目标站点 origin;必须等于 `event.origin`,否则拒绝。 */\n aud: string;\n /** 签发时间(unix seconds)。 */\n iat: number;\n /** 过期时间(unix seconds);必须严格大于 iat。 */\n exp: number;\n /** 人类可读确认文案。 */\n text: string;\n /** 调用方自定义的内容类型。 */\n contentType: string;\n /** 调用方准备好的最终二进制内容。允许为空字节。 */\n content: BinaryField;\n}\n\nexport interface IntentSignResult {\n /** 签名信封最终真值字节(Deterministic CBOR)。 */\n signedEnvelope: BinaryField;\n /** 签名(compact 64-byte secp256k1)。 */\n signature: BinaryField;\n}\n\nexport interface CipherEncryptParams {\n /** 人类可读确认文案。 */\n text: string;\n /** 调用方自定义的内容类型;与 contentBytes 一起进入密文内层结构。 */\n contentType: string;\n /** 业务字节本体。 */\n content: BinaryField;\n}\n\nexport interface CipherEncryptResult {\n /** 本次加密随机生成的 12 字节 nonce。 */\n nonce: BinaryField;\n /** AES-GCM 密文字节(含认证 tag)。 */\n cipherbytes: BinaryField;\n}\n\nexport interface CipherDecryptParams {\n /** 人类可读确认文案。 */\n text: string;\n /** 加密时保存的 12 字节 nonce。 */\n nonce: BinaryField;\n /** 加密时保存的密文字节。 */\n cipherbytes: BinaryField;\n}\n\nexport interface CipherDecryptResult {\n /** 密文内层结构里的 contentType。 */\n contentType: string;\n /** 还原后的业务字节。 */\n content: BinaryField;\n}\n\nexport type P2pkhTransferAssetId = \"bsv-mainnet\" | \"bsv-testnet\";\n\n/* ============== payment.pay / payment.status ============== */\n/** Connect v1 输出支付:业务输出数组,顺序即链上顺序。 */\nexport interface PaymentOutput {\n /** 聪,允许 0(数据输出)。必须为非负安全整数。 */\n amount: number;\n /** locking script hex;偶数长度 hex,允许空字符串(零长度锁定脚本)。 */\n script: string;\n}\n\nexport type ConnectPaymentStatus = \"pending\" | \"not_signed\" | \"signed_not_dispatched\" | \"unknown\" | \"failed\" | \"accepted\" | \"already_known\";\n\nexport interface PaymentPayParams {\n /** 稳定幂等身份,1–128 字符。 */\n clientRequestId: string;\n /** 业务输出;非空,顺序即链上顺序,找零由钱包追加。 */\n outputs: PaymentOutput[];\n}\n\nexport interface PaymentReleaseSummary {\n /** Historical amount safely released, NOT the current wallet balance. */\n releasedSatoshis: string;\n releasedInputCount: number;\n spentInputCount: number;\n heldInputCount: number;\n}\n\nexport interface PaymentPayResult {\n paymentId: string;\n clientRequestId: string;\n status: ConnectPaymentStatus;\n assetId: P2pkhTransferAssetId;\n /** 只有 accepted/already_known 才有 canonical txid。 */\n txid?: string;\n feeSatoshis?: number;\n changeSatoshis?: number;\n approval?: \"automatic\" | \"manual\" | \"unknown\";\n /** 稳定原因码;不包含签名/交易原文。 */\n reason?: string;\n release?: PaymentReleaseSummary;\n}\n\nexport interface PaymentStatusParams {\n clientRequestId: string;\n}\n\nexport type PaymentStatusResult = PaymentPayResult;\n\nexport interface ChainOutpoint {\n txid: string;\n vout: number;\n}\n\nexport interface PaymentDataSignature {\n outputIndex: number;\n offset: number;\n prefixHex: string;\n suffixHex: string;\n}\n\nexport interface PaymentPrepareParams extends PaymentStatusParams {\n outputs: PaymentOutput[];\n dataSignature: PaymentDataSignature;\n}\n\nexport type PaymentPrepareResult = PaymentPayResult & {\n reservation?: { reservationId: string; inputs: ChainOutpoint[]; expiresAt: number };\n};\n\nexport interface PaymentReservationParams extends PaymentStatusParams {\n reservationId: string;\n}\n\nexport interface PaymentCommitParams extends PaymentReservationParams {\n signingObject: BinaryField;\n}\n\nexport type ChainScriptHistoryParams = { script: string } & (\n { state: \"confirmed\"; fromHeight: number; toHeight: number; cursor?: string }\n | { state: \"unconfirmed\"; cursor?: string }\n);\n\nexport interface ChainScriptHistoryResult {\n entries: Array<{ txid: string; height: number | null }>;\n cursor?: string;\n}\n\nexport type ChainTransactionResult =\n | { state: \"not_observed\" | \"invalid\" }\n | { state: \"unconfirmed\"; rawTxHex: string }\n | { state: \"confirmed\"; rawTxHex: string; height: number; blockHash: string; index: number };\n\nexport type ChainTransactionBatchParams = { txids: string[]; mode: \"raw\" | \"status\" };\n\nexport type ChainTransactionBatchEntry = { txid: string } & (\n | { state: \"not_observed\" }\n | { state: \"unconfirmed\"; rawTxHex?: string }\n | { state: \"confirmed\"; height: number; blockHash: string; rawTxHex?: string }\n);\n\nexport interface ChainTransactionBatchResult {\n /** Missing IDs have no usable observation in this response and can be retried. */\n entries: ChainTransactionBatchEntry[];\n}\n\nexport interface ChainBroadcastResult {\n state: \"accepted\" | \"rejected\" | \"unknown\";\n txid: string;\n}\n\nexport interface ApplicationPaymentParams {\n purpose: string;\n inputs: ChainOutpoint[];\n address: string;\n feeSatoshis: number;\n rawTxHex: string;\n}\n\nexport interface MsFileImportParams {\n fileName: string;\n content: BinaryField;\n}\n\nexport interface MsFileContentResult {\n seed: BinaryField;\n content: BinaryField;\n}\n\n/** Signed by the connected wallet over the canonical login-proof envelope. */\nexport interface ConnectLoginProof {\n envelope: BinaryField;\n signature: BinaryField;\n}\n\nexport interface ConnectLoginParams {\n /** One-time challenge issued by the application backend (32 bytes, lowercase hex). */\n loginChallenge?: string;\n /** 人类可读确认文案。 */\n text: string;\n /**\n * 请求索要的 claim 名列表(与 `identity.get` 同语义)。\n * 缺省 = `[]`,不返回任何 claim;通常 caller 想获取 profile.* 时必须显式列出。\n */\n claims?: string[];\n /**\n * App 入口的发布来源证明记录字符串(`base64url(规范JSON).签名hex`)。\n * SDK 从当前入口 HTML 头读取并整体提交,不解码、不校验内容;\n * 钱包解码、验签并核对证明 origin 与可信 event.origin,应用不能自报来源。\n * 本地 Files 部署不依赖该字段(以 daemon 可信部署登记为准)。\n */\n publicationProof?: string;\n}\n\nexport interface ConnectLoginResult {\n /** Present when the request includes loginChallenge. */\n loginProof?: ConnectLoginProof;\n /** 不透明恢复凭据,绑定原钱包和精确来源;不得写入日志或 URL。 */\n authorizationId: string;\n networkIdentity: NetworkIdentity;\n /** 本次 login 时一次解析的 claims 真值快照。 */\n resolvedClaims: Record<string, ResolvedClaimValue>;\n /** 本次解析时间(unix milliseconds)。 */\n resolvedAt: number;\n}\n\nexport interface ConnectLogoutParams extends Record<string, never> {\n}\n\nexport interface ConnectLogoutResult {\n /** 吊销时间(unix milliseconds)。 */\n revokedAt: number;\n}\n\nexport interface ConnectLaunchParams {\n /** One-time challenge issued by the application backend (32 bytes, lowercase hex). */\n loginChallenge?: string;\n /** 由 launcher 写入 client app 启动 URL 的 launchToken。一次性消费。 */\n launchToken: string;\n /**\n * App 入口的发布来源证明记录字符串(可选;钱包发起的目录启动一般不需要客户端提交,\n * 钱包从所选入口自行读取;应用提交时钱包核对一致性,不能自报来源)。\n */\n publicationProof?: string;\n}\n\nexport interface ConnectLaunchResult {\n /** Present when the request includes loginChallenge. */\n loginProof?: ConnectLoginProof;\n authorizationId: string;\n networkIdentity: NetworkIdentity;\n resolvedClaims: Record<string, ResolvedClaimValue>;\n resolvedAt: number;\n}\n\n/** 协议方法名常量集合。 */\nexport const DOMAIN_MAX_PROFILES = 100;\n\nexport interface DomainProfile {\n publicKeyHex: string;\n domain: string;\n avatar?: { seedHashHex: string };\n header?: { seedHashHex: string };\n text?: Record<string, string>;\n expiresAt: number;\n}\n\nexport type ProfileResult =\n | { publicKeyHex: string; profile: DomainProfile }\n | { publicKeyHex: string; error: { code: \"invalid_public_key\" | \"name_not_found\" | \"primary_name_required\" } };\n\nexport interface DomainProfilesResult {\n results: ProfileResult[];\n}\n\nexport interface DomainProfilesParams {\n publicKeys: string[];\n serviceId?: string;\n}\n\nexport interface DomainGetPublicKeyParams {\n domain: string;\n serviceId?: string;\n}\n\nexport const PROTOCOL_METHODS = [\n \"identity.get\",\n \"intent.sign\",\n \"cipher.encrypt\",\n \"cipher.decrypt\",\n \"payment.pay\",\n \"payment.status\",\n \"payment.prepare\",\n \"payment.commit\",\n \"payment.cancel\",\n \"chain.get_height\",\n \"chain.list_script_history\",\n \"chain.get_transaction\",\n \"chain.get_transactions\",\n \"chain.list_script_unspent\",\n \"chain.broadcast\",\n \"application.key\",\n \"application.sign_message\",\n \"application.sign_payment\",\n \"msfile.seller.status\",\n \"msfile.import\",\n \"msfile.content.read\",\n \"msfile.content.status\",\n \"msfile.content.open\",\n \"msfile.content.price\",\n \"msfile.content.range\",\n \"domain.profiles\",\n \"domain.get_public_key\",\n \"connect.login\",\n \"connect.logout\",\n \"connect.launch\",\n // Channel 是唯一的公开频道 API,见 docs/SatSubscription与Channel.md。\n \"channel.publish\",\n \"channel.subscription_set\",\n // MSFile 对外方法族,见 docs/MSFile.md。作为\n // session-bound 且强制要求可信来源会话;Seed/Block 显式区分,\n // Read 不接受 maxPriceSatoshis(金额只能来自 Keymaster 设置或用户确认)。\n \"msfile.stat\",\n \"msfile.seed.read\",\n \"msfile.block.read\"\n] as const;\nexport type ProtocolMethod = (typeof PROTOCOL_METHODS)[number];\n/* ============== Method dispatch ============== */\n/**\n * 方法 -> 请求参数类型 的映射。`MethodParams<M>` 是计算出的参数类型。\n * 业务代码里直接 `MethodParams<\"identity.get\">` 等价于 `IdentityGetParams`。\n */\nexport interface MethodParamsMap {\n \"identity.get\": IdentityGetParams;\n \"intent.sign\": IntentSignParams;\n \"cipher.encrypt\": CipherEncryptParams;\n \"cipher.decrypt\": CipherDecryptParams;\n \"payment.pay\": PaymentPayParams;\n \"payment.status\": PaymentStatusParams;\n \"payment.prepare\": PaymentPrepareParams;\n \"payment.commit\": PaymentCommitParams;\n \"payment.cancel\": PaymentReservationParams;\n \"chain.get_height\": {};\n \"chain.list_script_history\": ChainScriptHistoryParams;\n \"chain.get_transaction\": { txid: string; observedRawTxHex?: string };\n \"chain.get_transactions\": ChainTransactionBatchParams;\n \"chain.list_script_unspent\": { script: string };\n \"chain.broadcast\": { rawTxHex: string };\n \"application.key\": { purpose: string };\n \"application.sign_message\": { purpose: string; message: BinaryField };\n \"application.sign_payment\": ApplicationPaymentParams;\n \"msfile.seller.status\": {};\n \"msfile.import\": MsFileImportParams;\n \"msfile.content.read\": MsFileContentReadParams;\n \"msfile.content.status\": MsFileReadStatusParams;\n \"msfile.content.open\": MsFileContentOpenParams;\n \"msfile.content.price\": MsFileDownloadPriceParams;\n \"msfile.content.range\": MsFileContentRangeParams;\n \"domain.profiles\": DomainProfilesParams;\n \"domain.get_public_key\": DomainGetPublicKeyParams;\n \"connect.login\": ConnectLoginParams;\n \"connect.logout\": ConnectLogoutParams;\n \"connect.launch\": ConnectLaunchParams;\n \"channel.publish\": ChannelPublishParams;\n \"channel.subscription_set\": ChannelSubscriptionSetParams;\n \"msfile.stat\": MsFileStatParams;\n \"msfile.seed.read\": MsFileSeedReadParams;\n \"msfile.block.read\": MsFileBlockReadParams;\n}\nexport interface MethodResultMap {\n \"identity.get\": IdentityGetResult;\n \"intent.sign\": IntentSignResult;\n \"cipher.encrypt\": CipherEncryptResult;\n \"cipher.decrypt\": CipherDecryptResult;\n \"payment.pay\": PaymentPayResult;\n \"payment.status\": PaymentStatusResult;\n \"payment.prepare\": PaymentPrepareResult;\n \"payment.commit\": PaymentPayResult;\n \"payment.cancel\": PaymentPayResult;\n \"chain.get_height\": ChainHeightResult;\n \"chain.list_script_history\": ChainScriptHistoryResult;\n \"chain.get_transaction\": ChainTransactionResult;\n \"chain.get_transactions\": ChainTransactionBatchResult;\n \"chain.list_script_unspent\": { outputs: Array<ChainOutpoint & { satoshis: number }> };\n \"chain.broadcast\": ChainBroadcastResult;\n \"application.key\": { publicKeyHex: string };\n \"application.sign_message\": { publicKeyHex: string; signature: BinaryField };\n \"application.sign_payment\": { rawTxHex: string };\n \"msfile.seller.status\": { ready: boolean };\n \"msfile.import\": { seedHashHex: string };\n \"msfile.content.read\": MsFileContentResult;\n \"msfile.content.status\": MsFileReadStatus;\n \"msfile.content.open\": MsFileReadStatus;\n \"msfile.content.price\": MsFileDownloadPriceResult;\n \"msfile.content.range\": MsFileContentRangeResult;\n \"domain.profiles\": DomainProfilesResult;\n \"domain.get_public_key\": { publicKeyHex: string };\n \"connect.login\": ConnectLoginResult;\n \"connect.logout\": ConnectLogoutResult;\n \"connect.launch\": ConnectLaunchResult;\n \"channel.publish\": ChannelPublishResult;\n \"channel.subscription_set\": ChannelSubscriptionSetResult;\n \"msfile.stat\": MsFileStatResult;\n \"msfile.seed.read\": MsFileReadResult;\n \"msfile.block.read\": MsFileReadResult;\n}\n\nexport type MethodParams<M extends ProtocolMethod> = M extends ProtocolMethod ? keyof MethodParamsMap[M] extends never ? Record<string, never> : MethodParamsMap[M] : never;\nexport type MethodResult<M extends ProtocolMethod = ProtocolMethod> = MethodResultMap[M];\nexport type ProtocolEventPayload =\n | { v: typeof PROTOCOL_VERSION; type: \"event\"; event: \"channel.message_received\"; data: ChannelMessageReceivedEventData }\n | { v: typeof PROTOCOL_VERSION; type: \"event\"; event: \"chain.height_changed\"; data: ChainHeightResult };\nexport type ProtocolEventMessage = ProtocolEventPayload & { networkIdentity: NetworkIdentity; bindingId: string };\nexport interface ProtocolRequestMessage<M extends ProtocolMethod = ProtocolMethod> {\n v: typeof PROTOCOL_VERSION; type: \"request\"; id: string; method: M; params: MethodParams<M>; bindingId?: string;\n}\nexport type ProtocolResultMessage =\n | { v: typeof PROTOCOL_VERSION; type: \"result\"; id: string; ok: true; result: MethodResult; networkIdentity: NetworkIdentity; bindingId: string }\n | { v: typeof PROTOCOL_VERSION; type: \"result\"; id: string; ok: false; error: ProtocolError; networkIdentity?: NetworkIdentity };\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BinaryField, D as DomainProfile, a as DomainProfilesResult, A as AiTool, b as AiToolsRegistered, N as NetworkIdentity, P as ProtocolEventMessage, c as ProtocolMethod, M as MethodParams, d as MethodResult, C as ConnectLoginParams, e as ConnectLoginResult, f as ConnectLogoutResult, g as ConnectLaunchParams, h as ConnectLaunchResult, I as IdentityGetParams, i as IdentityGetResult, j as IntentSignParams, k as IntentSignResult, l as CipherEncryptParams, m as CipherEncryptResult, n as CipherDecryptParams, o as CipherDecryptResult, p as PaymentPayParams, q as PaymentPayResult, r as PaymentPrepareResult, s as PaymentStatusParams, t as ChainScriptHistoryResult, u as ChainTransactionResult, v as ChainOutpoint, w as ChainBroadcastResult, x as MsFileContentResult, y as MsFileStatParams, z as MsFileStatResult, E as MsFileSeedReadParams, F as MsFileReadResult, G as MsFileBlockReadParams, H as PaymentStatusResult, J as ChannelPublishParams, K as ChannelPublishResult, L as ChannelSubscriptionSetParams, O as ChannelSubscriptionSetResult, Q as ProtocolErrorCode } from './protocol-Dfo305R9.js';
2
- export { R as AI_TOOLS_MAX_JSON_CHARS, S as AiToolDefinition, T as AiToolMessage, U as AiToolSchema, V as ApplicationPaymentParams, W as BsvNetwork, X as ChainScriptHistoryParams, Y as ChannelMessageReceivedEventData, Z as ChannelSubscriptionErrorCode, _ as ChannelSubscriptionPhase, $ as ChannelSubscriptionStatus, a0 as ConnectLogoutParams, a1 as ConnectPaymentStatus, a2 as DOMAIN_MAX_PROFILES, a3 as DomainGetPublicKeyParams, a4 as DomainProfilesParams, a5 as JSONValue, a6 as MSFILE_BLOCK_SIZE_BYTES, a7 as MSFILE_DIGEST_SIZE_BYTES, a8 as MSFILE_LOCAL_SOURCE_ID, a9 as MSFILE_MAX_BLOCK_BYTES, aa as MSFILE_MAX_CONTENT_BYTES, ab as MSFILE_MAX_ERROR_MESSAGE_BYTES, ac as MSFILE_MAX_HEADER_BYTES, ad as MSFILE_MAX_SEED_BYTES, ae as MSFILE_PROTOCOL_ID, af as MethodParamsMap, ag as MethodResultMap, ah as MsFileImportParams, ai as MsFileLocalSourceStat, aj as MsFileRemoteSourceStat, ak as MsFileSatoshiAmount, al as MsFileSourceKind, am as MsFileSourceStat, an as MsFileStatAbsentEntry, ao as MsFileStatAvailableEntry, ap as MsFileStatDiscoveringEntry, aq as MsFileStatNetworkErrorEntry, ar as MsFileStatQuotedEntry, as as MsFileSupplierStat, at as P2pkhTransferAssetId, au as PROTOCOL_METHODS, av as PROTOCOL_VERSION, aw as PaymentCommitParams, ax as PaymentDataSignature, ay as PaymentOutput, az as PaymentPrepareParams, aA as PaymentReleaseSummary, aB as PaymentReservationParams, aC as ProfileResult, aD as ProtocolCancelMessage, aE as ProtocolClosingMessage, aF as ProtocolError, aG as ProtocolEventName, aH as ProtocolEventPayload, aI as ProtocolReadyMessage, aJ as ProtocolRequestMessage, aK as ProtocolResultMessage, aL as ResolvedClaimValue, aM as assertToolJson, aN as assertToolPayload, aO as isAiToolMessage, aP as isValidMsFileSourceId, aQ as parseToolDefinitions, aR as sameNetworkIdentity, aS as validateBsvNetwork, aT as validateNetworkIdentity, aU as validateToolArguments } from './protocol-Dfo305R9.js';
1
+ import { B as BinaryField, D as DomainProfile, a as DomainProfilesResult, A as AiTool, b as AiToolsRegistered, N as NetworkIdentity, P as ProtocolEventMessage, c as ProtocolMethod, M as MethodParams, d as MethodResult, C as ConnectLoginParams, e as ConnectLoginResult, f as ConnectLogoutResult, g as ConnectLaunchParams, h as ConnectLaunchResult, I as IdentityGetParams, i as IdentityGetResult, j as IntentSignParams, k as IntentSignResult, l as CipherEncryptParams, m as CipherEncryptResult, n as CipherDecryptParams, o as CipherDecryptResult, p as PaymentPayParams, q as PaymentPayResult, r as PaymentPrepareResult, s as PaymentStatusParams, t as ChainHeightResult, u as ChainScriptHistoryResult, v as ChainTransactionResult, w as ChainTransactionBatchResult, x as ChainOutpoint, y as ChainBroadcastResult, z as MsFileContentResult, E as MsFileReadStatus, F as MsFileDownloadPriceResult, G as MsFileContentRangeResult, H as MsFileStatParams, J as MsFileStatResult, K as MsFileSeedReadParams, L as MsFileReadResult, O as MsFileBlockReadParams, Q as PaymentStatusResult, R as ChannelPublishParams, S as ChannelPublishResult, T as ChannelSubscriptionSetParams, U as ChannelSubscriptionSetResult, V as ProtocolErrorCode } from './protocol-Czc3NgOD.js';
2
+ export { W as AI_TOOLS_MAX_JSON_CHARS, X as AiToolDefinition, Y as AiToolMessage, Z as AiToolSchema, _ as ApplicationPaymentParams, $ as BsvNetwork, a0 as ChainScriptHistoryParams, a1 as ChainTransactionBatchEntry, a2 as ChainTransactionBatchParams, a3 as ChannelMessageReceivedEventData, a4 as ChannelSubscriptionErrorCode, a5 as ChannelSubscriptionPhase, a6 as ChannelSubscriptionStatus, a7 as ConnectLoginProof, a8 as ConnectLogoutParams, a9 as ConnectPaymentStatus, aa as DOMAIN_MAX_PROFILES, ab as DomainGetPublicKeyParams, ac as DomainProfilesParams, ad as JSONValue, ae as MSFILE_BLOCK_SIZE_BYTES, af as MSFILE_DIGEST_SIZE_BYTES, ag as MSFILE_LOCAL_SOURCE_ID, ah as MSFILE_MAX_BLOCK_BYTES, ai as MSFILE_MAX_CONTENT_BYTES, aj as MSFILE_MAX_ERROR_MESSAGE_BYTES, ak as MSFILE_MAX_HEADER_BYTES, al as MSFILE_MAX_SEED_BYTES, am as MSFILE_PROTOCOL_ID, an as MethodParamsMap, ao as MethodResultMap, ap as MsFileContentOpenParams, aq as MsFileContentRangeParams, ar as MsFileContentReadParams, as as MsFileDownloadPriceParams, at as MsFileImportParams, au as MsFileLocalSourceStat, av as MsFileReadStatusParams, aw as MsFileRemoteSourceStat, ax as MsFileSatoshiAmount, ay as MsFileSourceKind, az as MsFileSourceStat, aA as MsFileStatAbsentEntry, aB as MsFileStatAvailableEntry, aC as MsFileStatDiscoveringEntry, aD as MsFileStatNetworkErrorEntry, aE as MsFileStatQuotedEntry, aF as MsFileSupplierStat, aG as P2pkhTransferAssetId, aH as PROTOCOL_METHODS, aI as PROTOCOL_VERSION, aJ as PaymentCommitParams, aK as PaymentDataSignature, aL as PaymentOutput, aM as PaymentPrepareParams, aN as PaymentReleaseSummary, aO as PaymentReservationParams, aP as ProfileResult, aQ as ProtocolCancelMessage, aR as ProtocolClosingMessage, aS as ProtocolError, aT as ProtocolEventName, aU as ProtocolEventPayload, aV as ProtocolReadyMessage, aW as ProtocolRequestMessage, aX as ProtocolResultMessage, aY as ResolvedClaimValue, aZ as assertToolJson, a_ as assertToolPayload, a$ as isAiToolMessage, b0 as isValidMsFileSourceId, b1 as parseToolDefinitions, b2 as sameNetworkIdentity, b3 as validateBsvNetwork, b4 as validateNetworkIdentity, b5 as validateToolArguments } from './protocol-Czc3NgOD.js';
3
3
 
4
4
  /** Wraps bytes in the explicit binary field required by Connect V1. */
5
5
  declare function binary(bytes: ArrayBuffer | ArrayBufferView, mime?: string): BinaryField;
@@ -69,7 +69,7 @@ interface KeymasterConnectOptions {
69
69
  requestTimeoutMs?: number;
70
70
  /** Session Window close detection interval. Defaults to 500ms. */
71
71
  closePollMs?: number;
72
- /** 接收当前精确订阅频道上的已验签 Channel 事件。 */
72
+ /** 接收当前连接的公开事件。 */
73
73
  onEvent?: (event: ProtocolEventMessage) => void;
74
74
  /** Receives transport lifecycle changes. */
75
75
  onStateChange?: (state: KeymasterConnectState) => void;
@@ -138,6 +138,8 @@ declare class KeymasterConnectClient {
138
138
  };
139
139
  private identityValue;
140
140
  private bindingId;
141
+ private chainHeight;
142
+ private readonly heightListeners;
141
143
  private readonly aiTools;
142
144
  /** Replace this connection's tool set. Empty array unregisters all tools. Re-register explicitly after reconnect. */
143
145
  registerTools(tools: AiTool[], options?: Pick<KeymasterRequestOptions, "signal" | "timeoutMs">): Promise<AiToolsRegistered>;
@@ -240,13 +242,16 @@ declare class KeymasterConnectClient {
240
242
  status: (params: PaymentStatusParams, options?: KeymasterRequestOptions) => Promise<PaymentPayResult>;
241
243
  };
242
244
  readonly chain: {
243
- getHeight: (options?: KeymasterRequestOptions) => Promise<{
244
- height: number;
245
- }>;
245
+ /** 一次性读取钱包已同步的链尖高度和区块哈希。 */
246
+ getHeight: (options?: KeymasterRequestOptions) => Promise<ChainHeightResult>;
247
+ /** 接收已有链尖及后续高度或哈希变化,返回退订函数。 */
248
+ subscribeHeight: (handler: (height: ChainHeightResult) => void) => (() => void);
246
249
  listScriptHistory: (params: MethodParams<"chain.list_script_history">, options?: KeymasterRequestOptions) => Promise<ChainScriptHistoryResult>;
247
250
  getTransaction: (txid: string, options?: KeymasterRequestOptions & {
248
251
  observedRawTxHex?: string;
249
252
  }) => Promise<ChainTransactionResult>;
253
+ /** Observe up to 20 transactions with optional raw bytes and no block position lookup. */
254
+ getTransactions: (params: MethodParams<"chain.get_transactions">, options?: KeymasterRequestOptions) => Promise<ChainTransactionBatchResult>;
250
255
  listScriptUnspent: (script: string, options?: KeymasterRequestOptions) => Promise<{
251
256
  outputs: Array<ChainOutpoint & {
252
257
  satoshis: number;
@@ -277,7 +282,15 @@ declare class KeymasterConnectClient {
277
282
  seedHashHex: string;
278
283
  }>;
279
284
  /** Read a complete file by seed hash, discovering and buying it if needed. */
280
- read: (seedHashHex: string, options?: KeymasterRequestOptions) => Promise<MsFileContentResult>;
285
+ read: (seedHashHex: string, options?: KeymasterRequestOptions & Pick<MethodParams<"msfile.content.read">, "clientRequestId" | "maxFullBlockPriceSatoshis">) => Promise<MsFileContentResult>;
286
+ /** Query the original resumable read without starting a new purchase. */
287
+ readStatus: (clientRequestId: string, options?: KeymasterRequestOptions) => Promise<MsFileReadStatus>;
288
+ /** Open verified content or start/resume its authorized download. */
289
+ openContent: (params: MethodParams<"msfile.content.open">, options?: KeymasterRequestOptions) => Promise<MsFileReadStatus>;
290
+ /** Query the wallet block-price ceiling or adjust an owned running read. */
291
+ downloadPrice: (params?: MethodParams<"msfile.content.price">, options?: KeymasterRequestOptions) => Promise<MsFileDownloadPriceResult>;
292
+ /** Read up to 256 KiB from verified content while its download continues. */
293
+ readRange: (params: MethodParams<"msfile.content.range">, options?: KeymasterRequestOptions) => Promise<MsFileContentRangeResult>;
281
294
  /** Check availability in the wallet and at its configured suppliers. */
282
295
  stat: (params: MsFileStatParams, options?: KeymasterRequestOptions) => Promise<MsFileStatResult>;
283
296
  /** Read a MasterSeed from a specific source. The wallet handles any purchase. */
@@ -314,6 +327,7 @@ declare class KeymasterConnectClient {
314
327
  private failReady;
315
328
  /** 仅清理本地运行态,页签关闭不发送握手或等待回复。 */
316
329
  private readonly handlePageHide;
330
+ private notifyHeight;
317
331
  private disconnect;
318
332
  private startClosePolling;
319
333
  private stopClosePolling;
@@ -327,4 +341,4 @@ declare function createKeymasterConnect(options: KeymasterConnectOptions): Keyma
327
341
  /** Creates the production environment adapter from the current browser window. */
328
342
  declare function createBrowserEnvironment(): KeymasterBrowserEnvironment;
329
343
 
330
- export { AiTool, AiToolsRegistered, BinaryField, ChainBroadcastResult, ChainOutpoint, ChainScriptHistoryResult, ChainTransactionResult, ChannelPublishParams, ChannelPublishResult, ChannelSubscriptionSetParams, ChannelSubscriptionSetResult, CipherDecryptParams, CipherDecryptResult, CipherEncryptParams, CipherEncryptResult, ConnectLaunchParams, ConnectLaunchResult, ConnectLoginParams, ConnectLoginResult, ConnectLogoutResult, DomainProfile, DomainProfilesResult, type DomainQueryOptions, IdentityGetParams, IdentityGetResult, IntentSignParams, IntentSignResult, type KeymasterBrowserEnvironment, KeymasterConnectClient, type KeymasterConnectMode, type KeymasterConnectOptions, type KeymasterConnectState, KeymasterProtocolError, type KeymasterRequestOptions, KeymasterTransportError, type KeymasterTransportErrorCode, MethodParams, MethodResult, MsFileBlockReadParams, MsFileContentResult, MsFileReadResult, MsFileSeedReadParams, MsFileStatParams, MsFileStatResult, NetworkIdentity, PaymentPayParams, PaymentPayResult, PaymentPrepareResult, PaymentStatusParams, PaymentStatusResult, ProtocolErrorCode, ProtocolEventMessage, ProtocolMethod, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
344
+ export { AiTool, AiToolsRegistered, BinaryField, ChainBroadcastResult, ChainHeightResult, ChainOutpoint, ChainScriptHistoryResult, ChainTransactionBatchResult, ChainTransactionResult, ChannelPublishParams, ChannelPublishResult, ChannelSubscriptionSetParams, ChannelSubscriptionSetResult, CipherDecryptParams, CipherDecryptResult, CipherEncryptParams, CipherEncryptResult, ConnectLaunchParams, ConnectLaunchResult, ConnectLoginParams, ConnectLoginResult, ConnectLogoutResult, DomainProfile, DomainProfilesResult, type DomainQueryOptions, IdentityGetParams, IdentityGetResult, IntentSignParams, IntentSignResult, type KeymasterBrowserEnvironment, KeymasterConnectClient, type KeymasterConnectMode, type KeymasterConnectOptions, type KeymasterConnectState, KeymasterProtocolError, type KeymasterRequestOptions, KeymasterTransportError, type KeymasterTransportErrorCode, MethodParams, MethodResult, MsFileBlockReadParams, MsFileContentRangeResult, MsFileContentResult, MsFileDownloadPriceResult, MsFileReadResult, MsFileReadStatus, MsFileSeedReadParams, MsFileStatParams, MsFileStatResult, NetworkIdentity, PaymentPayParams, PaymentPayResult, PaymentPrepareResult, PaymentStatusParams, PaymentStatusResult, ProtocolErrorCode, ProtocolEventMessage, ProtocolMethod, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parseToolDefinitions, assertToolPayload, isAiToolMessage, validateToolArguments } from './chunk-VVOTW5ZT.js';
2
2
  export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
- import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-A4VCQSB5.js';
4
- export { DOMAIN_MAX_PROFILES, 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, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-A4VCQSB5.js';
3
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-QUZZ2OXO.js';
4
+ export { DOMAIN_MAX_PROFILES, 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, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-QUZZ2OXO.js';
5
5
 
6
6
  // src/binary.ts
7
7
  function binary(bytes, mime) {
@@ -175,6 +175,11 @@ var KeymasterProtocolError = class extends Error {
175
175
  var DEFAULT_READY_TIMEOUT_MS = 12e4;
176
176
  var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
177
177
  var DEFAULT_CLOSE_POLL_MS = 500;
178
+ function parseChainHeight(value) {
179
+ const { height, blockHash } = value ?? {};
180
+ if (typeof height !== "number" || !Number.isSafeInteger(height) || height < 0 || typeof blockHash !== "string" || !/^[0-9a-f]{64}$/u.test(blockHash)) return void 0;
181
+ return { height, blockHash };
182
+ }
178
183
  var KeymasterConnectClient = class {
179
184
  domain = {
180
185
  /** Read the primary domain's public profile for one public key. */
@@ -193,6 +198,8 @@ var KeymasterConnectClient = class {
193
198
  };
194
199
  identityValue = null;
195
200
  bindingId = null;
201
+ chainHeight;
202
+ heightListeners = /* @__PURE__ */ new Set();
196
203
  aiTools = new AiToolClient(
197
204
  () => this.stateValue === "connected" ? this.bindingId : null,
198
205
  (message) => {
@@ -423,9 +430,25 @@ var KeymasterConnectClient = class {
423
430
  status: (params, options) => this.paymentStatus(params, options)
424
431
  };
425
432
  chain = {
426
- getHeight: (options) => this.request("chain.get_height", {}, options),
433
+ /** 一次性读取钱包已同步的链尖高度和区块哈希。 */
434
+ getHeight: async (options) => {
435
+ const snapshot = parseChainHeight(await this.request("chain.get_height", {}, options));
436
+ if (!snapshot) throw new KeymasterProtocolError("invalid_request", "Malformed chain height result");
437
+ this.chainHeight = snapshot;
438
+ return { ...snapshot };
439
+ },
440
+ /** 接收已有链尖及后续高度或哈希变化,返回退订函数。 */
441
+ subscribeHeight: (handler) => {
442
+ this.heightListeners.add(handler);
443
+ if (this.chainHeight) this.notifyHeight(handler, this.chainHeight);
444
+ return () => {
445
+ this.heightListeners.delete(handler);
446
+ };
447
+ },
427
448
  listScriptHistory: (params, options) => this.request("chain.list_script_history", params, options),
428
449
  getTransaction: (txid, options) => this.request("chain.get_transaction", { txid, observedRawTxHex: options?.observedRawTxHex }, options),
450
+ /** Observe up to 20 transactions with optional raw bytes and no block position lookup. */
451
+ getTransactions: (params, options) => this.request("chain.get_transactions", params, options),
429
452
  listScriptUnspent: (script, options) => this.request("chain.list_script_unspent", { script }, options),
430
453
  broadcast: (rawTxHex, options) => this.request("chain.broadcast", { rawTxHex }, options)
431
454
  };
@@ -441,7 +464,19 @@ var KeymasterConnectClient = class {
441
464
  /** Import a complete file and wait for it to be available to the seller. */
442
465
  import: (params, options) => this.request("msfile.import", params, options),
443
466
  /** Read a complete file by seed hash, discovering and buying it if needed. */
444
- read: (seedHashHex, options) => this.request("msfile.content.read", { seedHashHex }, options),
467
+ read: (seedHashHex, options) => this.request("msfile.content.read", {
468
+ seedHashHex,
469
+ ...options?.clientRequestId !== void 0 ? { clientRequestId: options.clientRequestId } : {},
470
+ ...options?.maxFullBlockPriceSatoshis !== void 0 ? { maxFullBlockPriceSatoshis: options.maxFullBlockPriceSatoshis } : {}
471
+ }, options),
472
+ /** Query the original resumable read without starting a new purchase. */
473
+ readStatus: (clientRequestId, options) => this.request("msfile.content.status", { clientRequestId }, options),
474
+ /** Open verified content or start/resume its authorized download. */
475
+ openContent: (params, options) => this.request("msfile.content.open", params, options),
476
+ /** Query the wallet block-price ceiling or adjust an owned running read. */
477
+ downloadPrice: (params = {}, options) => this.request("msfile.content.price", params, options),
478
+ /** Read up to 256 KiB from verified content while its download continues. */
479
+ readRange: (params, options) => this.request("msfile.content.range", params, { ...options, timeoutMs: options?.timeoutMs ?? 65e3 }),
445
480
  /** Check availability in the wallet and at its configured suppliers. */
446
481
  stat: (params, options) => this.request("msfile.stat", params, options),
447
482
  /** Read a MasterSeed from a specific source. The wallet handles any purchase. */
@@ -559,12 +594,22 @@ var KeymasterConnectClient = class {
559
594
  return;
560
595
  }
561
596
  if (value.type === "event") {
562
- if (value.event !== "channel.message_received") return;
597
+ if (value.event !== "channel.message_received" && value.event !== "chain.height_changed") return;
563
598
  try {
564
599
  if (!this.identityValue || value.bindingId !== this.bindingId || !sameNetworkIdentity(this.identityValue, validateNetworkIdentity(value.networkIdentity))) return;
565
600
  } catch {
566
601
  return;
567
602
  }
603
+ if (value.event === "chain.height_changed") {
604
+ const next = parseChainHeight(value.data);
605
+ if (!next || next.height === this.chainHeight?.height && next.blockHash === this.chainHeight.blockHash) return;
606
+ this.chainHeight = next;
607
+ for (const handler of [...this.heightListeners]) {
608
+ if (this.bindingId !== value.bindingId) return;
609
+ if (this.heightListeners.has(handler)) this.notifyHeight(handler, next);
610
+ }
611
+ if (this.bindingId !== value.bindingId) return;
612
+ }
568
613
  try {
569
614
  this.options.onEvent?.(event.data);
570
615
  } catch {
@@ -592,6 +637,7 @@ var KeymasterConnectClient = class {
592
637
  const connected = result.result;
593
638
  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");
594
639
  this.aiTools.clear(new Error("Connection binding replaced; register tools again"));
640
+ this.chainHeight = void 0;
595
641
  this.identityValue = Object.freeze({ ...identity });
596
642
  this.authorizationId = connected.authorizationId;
597
643
  this.bindingId = value.bindingId;
@@ -644,10 +690,17 @@ var KeymasterConnectClient = class {
644
690
  }
645
691
  this.disconnect(new KeymasterTransportError("client_closed", "Application page unloaded"));
646
692
  };
693
+ notifyHeight(handler, snapshot) {
694
+ try {
695
+ handler({ ...snapshot });
696
+ } catch {
697
+ }
698
+ }
647
699
  disconnect(reason) {
648
700
  this.aiTools.clear(reason);
649
701
  this.identityValue = null;
650
702
  this.bindingId = null;
703
+ this.chainHeight = void 0;
651
704
  this.rejectAll(reason);
652
705
  this.failReady(reason);
653
706
  this.stopClosePolling();