keymaster-connect 0.1.4 → 0.1.5

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,7 +2,7 @@
2
2
 
3
3
  Keymaster Connect v1 的独立生产协议栈,包含 Client、公开契约和 Receiver,不依赖钱包源码或 WebLoom。
4
4
 
5
- 无 scope 的 `keymaster-connect`,本版为 **0.1.4**,wire 始终保持 v1。发布后第三方安装:
5
+ 无 scope 的 `keymaster-connect`,当前公共版本为 **0.1.4**,源码 **0.1.5** 为可选加密存储候选,尚未公共发布;wire 始终保持 v1。已发布版本安装:
6
6
 
7
7
  ```sh
8
8
  npm install --save-exact keymaster-connect@0.1.4
@@ -19,7 +19,11 @@ const connected = await client.login({ text: "连接钱包" });
19
19
  console.log(connected.networkIdentity);
20
20
  ```
21
21
 
22
- 公开能力包括 Connect、Identity、Cipher、Payment、Channel、Storage 和 MSFile。首次连接不选择公钥或网络,后续业务使用接收端签发的连接绑定。钱包重置或 Worker 世代改变后旧绑定失效,App 必须显式重新连接。ready 只代表完整钱包已具备传输条件;logout 撤销连接授权,close 只关闭传输,不关闭用户的钱包窗口。取消是尽力通知,不表示已签名/广播的业务可以回滚。产品未上线,wire 固定为 v1,不维护已删除字段兼容分支。
22
+ 公开能力包括 Connect、Identity、Cipher、Payment(outputs 数组)、Channel、Storage 和 MSFile。首次连接不选择公钥或网络,后续业务使用接收端签发的连接绑定。钱包重置或 Worker 世代改变后旧绑定失效,App 必须显式重新连接。ready 只代表完整钱包已具备传输条件;logout 撤销连接授权,close 只关闭传输,不关闭用户的钱包窗口。取消是尽力通知,不表示已签名/广播的业务可以回滚。产品未上线,wire 固定为 v1,不维护已删除字段兼容分支。
23
+
24
+ `connect()` 只建立传输,不恢复授权;刷新恢复请使用 `resume()`,它先装载本地恢复记录再复用 `continueConnection()`。`login`/`launch`/`resume` 成功保存最近一条恢复记录(`sessionStorage`,键 `keymaster-connect:recovery:v1`,仅含版本、精确 origin、模式、授权引用和网络身份),`logout` 成功、明确授权失效或用户主动清除才删除;`close`、页面卸载、超时、窗口关闭均保留。`readConnectionRecovery()` 返回公开摘要(不含凭据),`clearConnectionRecovery()` 仅删本地材料;`KeymasterConnectOptions.recoveryStorage` 可替换存储,不降级到 `localStorage`。存储写入失败不影响已成功的登录,调用方可读 `client.recoverySaveError` 提示“已登录,但刷新恢复信息保存失败”。`connection_expired` 仅表达运行连接失效,保留记录;只有钱包返回 `authorization_expired` 或匹配的 `revoked` 才清除。
25
+
26
+ `payment.pay` 为 outputs 模型:`{ clientRequestId, outputs: [{ amount, script }] }`,顺序即链上顺序,找零由钱包追加;旧 `channelId/paymentType/businessKind/amountSatoshis/recipient/feeRate` 字段与 `payment.channel.register`、`p2pkh.transfer` 已移除。脚本解释经独立子入口 `keymaster-connect/script`(`interpretLockingScript`)供钱包与 CLI Web 展示,不决定是否允许支付。
23
27
 
24
28
  ## AI 工具(0.1.4)
25
29
 
@@ -44,3 +48,19 @@ import { KeymasterConnectReceiver } from "keymaster-connect/server";
44
48
  仓库根目录是 SDK:`npm run typecheck` 检查类型,`npm run build` 只构建 SDK,`npm publish` 从根目录发布 SDK 新版本(已发布的版本不可覆盖)。发布命令见 [RELEASING.md](RELEASING.md)。
45
49
 
46
50
  文档是私有的 [doc 子项目](doc/README.md):根目录执行 `npm run api:generate` 生成 API,`npm run doc:build` 构建站点,`npm run doc:dev` 启动预览开发。文档不进入 npm 发布包。包版本与 wire 版本不是同一概念。
51
+
52
+ ## App 文件存储
53
+
54
+ `storageList`、`storageDirectoryCreate`、`storageDirectoryDelete`、`storagePut`、`storageGet`、`storageDelete` 使用钱包配置的 S3 兼容服务。App 必须通过带 `storage` requirement 的 App 独立公钥签名身份连接,只提交自身目录内的相对路径;SDK 不配置或返回 S3 凭据、桶或物理对象根。钱包未配置 S3 时返回 `storage_not_configured`,不会回退到浏览器本地文件。钱包密钥及内部业务存储与 App S3 文件分离;旧 App 本地文件不自动迁移。
55
+
56
+ S3 文件从桶根按 `<网络>/<钱包公钥>/<App公钥>/files/<文件路径>` 保存,不配置 Root Prefix。每个 App 使用独立公钥,当前 proof 的 `publisherPublicKey` 字段承载该 App 公钥;App 编号和显示名不参与 S3 目录。同一网络、钱包公钥和 App 公钥在配置相同桶后访问同一远端目录;换浏览器仍须初始化/解锁钱包并重新连接。对象内容按 App 提交字节保存,敏感内容需要 App 自行加密。`revision` 是不透明版本标签,供 `storageGet({ path, ifMatch })` 条件读取;`storagePut({ path, content, overwrite: false })` 要求远端原子条件创建,冲突返回 `storage_conflict`。目录删除不递归,上传为单对象 put,不提供 multipart 或断点续传。取消或超时不证明远端写入未发生,App 应按自身业务标识对账。
57
+
58
+ 以上为钱包配套实现的能力约定;SDK 类型和传输本身不能保证某个钱包部署已启用 S3。
59
+
60
+ ### 可选加密存储(0.1.5 候选)
61
+
62
+ `client.storagePutEncrypted(params)` 对应 `storage.encrypted.put`,接收与普通 put 相同的明文参数,由钱包 Vault 加密后上传;`client.storageGetEncrypted(params)` 对应 `storage.encrypted.get`,由钱包解密后返回明文。密钥绑定钱包、网络、App 公钥和对象路径;App 私钥本身不能独立解密。文件路径仍可见,正文与原始 MIME 保存在密文中。App 编号或显示名变更不改存储身份,每个 App 应使用独立签名公钥;复用公钥即共享存储身份。
63
+
64
+ 加密读取的 offset/length 和 totalSize 表示明文范围,revision/ifMatch 表示远端密文版本;普通 get 返回原始对象,list 的 size 是远端字节数。密文篡改、跨路径复制、错误密钥或把普通对象交给加密读取均报 `storage_provider_error`,不退回普通读取。两种对象共用原有目录、条件创建和删除接口;加密接口不改变普通 put/get。
65
+
66
+ 这些新方法需钱包与 App 消费配套的正式 SDK 版本;0.1.4 Receiver 会拒绝新方法,不能通过发送普通 put 偷渡加密标记。发布前只在隔离候选包中验证,不把候选测试当作公共发布成功。
@@ -36,10 +36,8 @@ var PROTOCOL_METHODS = [
36
36
  "intent.sign",
37
37
  "cipher.encrypt",
38
38
  "cipher.decrypt",
39
- "p2pkh.transfer",
40
39
  "payment.pay",
41
40
  "payment.status",
42
- "payment.channel.register",
43
41
  "connect.login",
44
42
  "connect.resume",
45
43
  "connect.logout",
@@ -52,6 +50,8 @@ var PROTOCOL_METHODS = [
52
50
  "storage.directory.delete",
53
51
  "storage.put",
54
52
  "storage.get",
53
+ "storage.encrypted.put",
54
+ "storage.encrypted.get",
55
55
  "storage.delete",
56
56
  // MSFile 对外方法族,见 docs/MSFile.md。与 storage.* 同为
57
57
  // session-bound 且强制要求 verified App Identity;Seed/Block 显式区分,
@@ -62,5 +62,5 @@ var PROTOCOL_METHODS = [
62
62
  ];
63
63
 
64
64
  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 };
65
- //# sourceMappingURL=chunk-2EYARFS3.js.map
66
- //# sourceMappingURL=chunk-2EYARFS3.js.map
65
+ //# sourceMappingURL=chunk-ZDIFZJYD.js.map
66
+ //# sourceMappingURL=chunk-ZDIFZJYD.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;AA6NO,IAAM,yBAAA,GAA4B,KAAK,IAAA,GAAO;AAE9C,IAAM,0BAAA,GAA6B;AAEnC,IAAM,sBAAA,GAAyB;AAG/B,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;AAgGO,IAAM,gBAAA,GAAmB;AA2RzB,IAAM,gBAAA,GAAmB;AAAA,EAC5B,cAAA;AAAA,EACA,aAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,aAAA;AAAA,EACA,gBAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA;AAAA,EAEA,iBAAA;AAAA,EACA,0BAAA;AAAA,EACA,cAAA;AAAA,EACA,0BAAA;AAAA,EACA,0BAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA,uBAAA;AAAA,EACA,uBAAA;AAAA,EACA,gBAAA;AAAA;AAAA;AAAA;AAAA,EAIA,aAAA;AAAA,EACA,kBAAA;AAAA,EACA;AACJ","file":"chunk-ZDIFZJYD.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\nexport type AppRequirement = \"private-key\" | \"storage\";\n\nexport interface AppIdentityProofV1 {\n version: 1;\n publisherPublicKey: string;\n app: {\n id: string;\n name: string;\n description: string;\n };\n requirements: AppRequirement[];\n signature: string;\n}\n\nexport interface VerifiedAppIdentity {\n version: 1;\n publisherPublicKeyHex: string;\n appId: string;\n appName: string;\n identityDigestHex: string;\n}\n\nexport type AppIdentitySnapshot = VerifiedAppIdentity;\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\nexport interface StorageListParams {\n /** 目录前缀。 */\n prefix?: string;\n /** 分页游标。 */\n cursor?: string;\n /** 每页数量。 */\n limit?: number;\n}\n\nexport interface StorageListEntry {\n /** Connect 可见的相对路径。 */\n path: string;\n /** 当前目录下的文件名。 */\n name: string;\n /** 文件大小(字节)。 */\n size: number;\n /** 抽象版本标签。 */\n revision?: string;\n /** 最后修改时间。 */\n lastModified?: string;\n}\n\nexport interface StorageListResult {\n /** 当前目录前缀。 */\n prefix: string;\n /** 父目录前缀。 */\n parentPrefix: string;\n /** 虚拟目录列表。 */\n directories: Array<{\n path: string;\n name: string;\n }>;\n /** 当前页文件。 */\n files: StorageListEntry[];\n /** 目录 marker 路径。 */\n markerPath?: string;\n /** 下一页游标。 */\n nextCursor?: string;\n}\n\nexport interface StorageDirectoryParams {\n /** 目录路径。 */\n path: string;\n /** 是否允许覆盖已有 marker。 */\n overwrite?: boolean;\n}\n\nexport interface StorageDirectoryResult {\n /** 目录路径。 */\n path: string;\n /** 是否创建。 */\n created?: boolean;\n /** 是否删除。 */\n deleted?: boolean;\n}\n\nexport interface StoragePutParams {\n /** 文件路径。 */\n path: string;\n /** 二进制文件内容。 */\n content: BinaryField;\n /** MIME 类型。 */\n contentType?: string;\n /** 是否覆盖已有对象。 */\n overwrite?: boolean;\n}\n\nexport interface StoragePutResult {\n /** 文件路径。 */\n path: string;\n /** 写入大小(字节)。 */\n size: number;\n /** 抽象版本标签。 */\n revision?: string;\n /** 写入时间戳(毫秒)。 */\n updatedAt: number;\n}\n\nexport interface StorageGetParams {\n /** 文件路径。 */\n path: string;\n /** 起始偏移(字节)。 */\n offset?: number;\n /** 读取长度(字节)。 */\n length?: number;\n /** 期望的抽象版本标签。 */\n ifMatch?: string;\n}\n\nexport interface StorageGetResult {\n /** 文件路径。 */\n path: string;\n /** 二进制内容。 */\n content: BinaryField;\n /** MIME 类型。 */\n contentType?: string;\n /** 实际起始偏移。 */\n offset: number;\n /** 文件总大小(字节)。 */\n totalSize: number;\n /** 是否已读到文件结尾。 */\n eof: boolean;\n /** 抽象版本标签。 */\n revision?: string;\n /** 最后修改时间。 */\n lastModified?: string;\n}\n\nexport interface StorageDeleteParams {\n /** 文件路径。 */\n path: string;\n}\n\nexport interface StorageDeleteResult {\n /** 文件路径。 */\n path: string;\n /** 固定成功标记。 */\n deleted: true;\n /** 删除时间戳(毫秒)。 */\n updatedAt: number;\n}\n\n// K-V、partition、commit 和 revision 契约。\n/** K-V 引擎的硬限制;字段名和单位均在此集中定义。 */\nexport const STORAGE_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;\n\nexport const STORAGE_DEFAULT_LIST_LIMIT = 200;\n\nexport const STORAGE_MAX_LIST_LIMIT = 1000;\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 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/** 通用支付需要已验证 App 身份(publisher 是归属唯一基准)。 */\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 payment key with different frozen facts. */\n | \"id_conflict\" | \"storage_not_configured\" | \"storage_unavailable\" | \"storage_invalid_path\" | \"storage_not_found\" | \"storage_conflict\" | \"storage_forbidden\" | \"storage_limit_exceeded\" | \"storage_provider_error\" | \"storage_identity_required\"\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 */\nexport type ProtocolEventName = \"channel.message_received\";\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 ConnectLoginParams {\n /** 人类可读确认文案。 */\n text: string;\n /**\n * 请求索要的 claim 名列表(与 `identity.get` 同语义)。\n * 缺省 = `[]`,不返回任何 claim;通常 caller 想获取 profile.* 时必须显式列出。\n */\n claims?: string[];\n /** 发布者签名的 caller identity proof;缺省时建立无 storage 的普通 session。 */\n appIdentity?: AppIdentityProofV1;\n}\n\nexport interface ConnectLoginResult {\n /** 不透明恢复凭据,绑定原钱包、应用和精确来源;不得写入日志或 URL。 */\n authorizationId: string;\n networkIdentity: NetworkIdentity;\n /** 本次 login 时一次解析的 claims 真值快照。 */\n resolvedClaims: Record<string, ResolvedClaimValue>;\n /** 本次解析时间(unix milliseconds)。 */\n resolvedAt: number;\n appIdentity?: AppIdentitySnapshot;\n}\n\nexport interface ConnectResumeParams {\n /** 本地数据重置后重新验证已有发行人签名 proof。 */\n appIdentity?: AppIdentityProofV1;\n}\n\nexport interface ConnectResumeResult {\n authorizationId: string;\n networkIdentity: NetworkIdentity;\n resolvedClaims: Record<string, ResolvedClaimValue>;\n /**\n * 解析时间——本次 resume 时间戳,**不**是 connect.login 时的快照时间。\n * 给 caller 用来做\"是否要重新登录\"的客户端超时策略。\n */\n resolvedAt: number;\n appIdentity?: AppIdentitySnapshot;\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 /** 由 launcher 写入 client app 启动 URL 的 launchToken。一次性消费。 */\n launchToken: string;\n /** 与 launcher 预建 session 绑定的完整签名 proof。 */\n appIdentity: AppIdentityProofV1;\n}\n\nexport interface ConnectLaunchResult {\n authorizationId: string;\n networkIdentity: NetworkIdentity;\n resolvedClaims: Record<string, ResolvedClaimValue>;\n resolvedAt: number;\n appIdentity?: AppIdentitySnapshot;\n}\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 \"connect.login\",\n \"connect.resume\",\n \"connect.logout\",\n \"connect.launch\",\n // Channel 是唯一的公开频道 API,见 docs/SatSubscription与Channel.md。\n \"channel.publish\",\n \"channel.subscription_set\",\n \"storage.list\",\n \"storage.directory.create\",\n \"storage.directory.delete\",\n \"storage.put\",\n \"storage.get\",\n \"storage.encrypted.put\",\n \"storage.encrypted.get\",\n \"storage.delete\",\n // MSFile 对外方法族,见 docs/MSFile.md。与 storage.* 同为\n // session-bound 且强制要求 verified App Identity;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 \"connect.login\": ConnectLoginParams;\n \"connect.resume\": ConnectResumeParams;\n \"connect.logout\": ConnectLogoutParams;\n \"connect.launch\": ConnectLaunchParams;\n \"channel.publish\": ChannelPublishParams;\n \"channel.subscription_set\": ChannelSubscriptionSetParams;\n \"storage.list\": StorageListParams;\n \"storage.directory.create\": StorageDirectoryParams;\n \"storage.directory.delete\": StorageDirectoryParams;\n \"storage.put\": StoragePutParams;\n \"storage.encrypted.put\": StoragePutParams;\n \"storage.get\": StorageGetParams;\n \"storage.encrypted.get\": StorageGetParams;\n \"storage.delete\": StorageDeleteParams;\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 \"connect.login\": ConnectLoginResult;\n \"connect.resume\": ConnectResumeResult;\n \"connect.logout\": ConnectLogoutResult;\n \"connect.launch\": ConnectLaunchResult;\n \"channel.publish\": ChannelPublishResult;\n \"channel.subscription_set\": ChannelSubscriptionSetResult;\n \"storage.list\": StorageListResult;\n \"storage.directory.create\": StorageDirectoryResult;\n \"storage.directory.delete\": StorageDirectoryResult;\n \"storage.put\": StoragePutResult;\n \"storage.encrypted.put\": StoragePutResult;\n \"storage.get\": StorageGetResult;\n \"storage.encrypted.get\": StorageGetResult;\n \"storage.delete\": StorageDeleteResult;\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 };\nexport type ProtocolEventMessage = ProtocolEventPayload & { networkIdentity: NetworkIdentity; bindingId: string };\n/** 暂停恢复控制,不携带钱包选择参数,也不是业务请求重放。 */\nexport interface ProtocolReconnectMessage {\n v: typeof PROTOCOL_VERSION;\n type: \"reconnect\";\n id: string;\n authorizationId: string;\n bindingId?: string;\n /** 刷新恢复时提交的当前入口 proof;后台心跳可省略,宿主按原授权核对。 */\n appIdentity?: AppIdentityProofV1;\n}\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, A as AiTool, a as AiToolsRegistered, N as NetworkIdentity, P as ProtocolEventMessage, b as ProtocolMethod, M as MethodParams, c as MethodResult, C as ConnectLoginParams, d as ConnectLoginResult, e as ConnectResumeParams, f as ConnectResumeResult, g as ConnectLogoutResult, h as ConnectLaunchParams, i as ConnectLaunchResult, I as IdentityGetParams, j as IdentityGetResult, k as IntentSignParams, l as IntentSignResult, m as CipherEncryptParams, n as CipherEncryptResult, o as CipherDecryptParams, p as CipherDecryptResult, q as PaymentPayParams, r as PaymentPayResult, s as PaymentStatusParams, t as PaymentStatusResult, u as P2pkhTransferParams, v as P2pkhTransferResult, w as PaymentChannelRegisterParams, x as PaymentChannelRegisterResult, y as ChannelPublishParams, z as ChannelPublishResult, D as ChannelSubscriptionSetParams, E as ChannelSubscriptionSetResult, S as StorageListParams, F as StorageListResult, G as StorageDirectoryParams, H as StorageDirectoryResult, J as StoragePutParams, K as StoragePutResult, L as StorageGetParams, O as StorageGetResult, Q as StorageDeleteParams, R as StorageDeleteResult, T as MsFileStatParams, U as MsFileStatResult, V as MsFileSeedReadParams, W as MsFileReadResult, X as MsFileBlockReadParams, Y as ProtocolErrorCode } from './protocol-NcRDmEKZ.js';
2
- export { Z as AI_TOOLS_MAX_JSON_CHARS, _ as AiToolDefinition, $ as AiToolMessage, a0 as AiToolSchema, a1 as AppIdentityProofV1, a2 as AppIdentitySnapshot, a3 as AppRequirement, a4 as BsvNetwork, a5 as ChannelMessageReceivedEventData, a6 as ChannelSubscriptionErrorCode, a7 as ChannelSubscriptionPhase, a8 as ChannelSubscriptionStatus, a9 as ConnectLogoutParams, aa as ConnectPaymentRecipient, ab as ConnectPaymentRecipientOwnership, ac as ConnectPaymentStatus, ad as ConnectPaymentType, ae as JSONValue, af as MSFILE_BLOCK_SIZE_BYTES, ag as MSFILE_DIGEST_SIZE_BYTES, ah as MSFILE_LOCAL_SOURCE_ID, ai as MSFILE_MAX_BLOCK_BYTES, aj as MSFILE_MAX_CONTENT_BYTES, ak as MSFILE_MAX_ERROR_MESSAGE_BYTES, al as MSFILE_MAX_HEADER_BYTES, am as MSFILE_MAX_SEED_BYTES, an as MSFILE_PROTOCOL_ID, ao as MethodParamsMap, ap as MethodResultMap, aq as MsFileLocalSourceStat, ar as MsFileRemoteSourceStat, as as MsFileSatoshiAmount, at as MsFileSourceKind, au as MsFileSourceStat, av as MsFileStatAbsentEntry, aw as MsFileStatAvailableEntry, ax as MsFileStatDiscoveringEntry, ay as MsFileStatNetworkErrorEntry, az as MsFileStatQuotedEntry, aA as MsFileSupplierStat, aB as P2pkhTransferAssetId, aC as PROTOCOL_METHODS, aD as PROTOCOL_VERSION, aE as PaymentReleaseSummary, aF as ProtocolCancelMessage, aG as ProtocolClosingMessage, aH as ProtocolError, aI as ProtocolEventName, aJ as ProtocolEventPayload, aK as ProtocolReadyMessage, aL as ProtocolReconnectMessage, aM as ProtocolRequestMessage, aN as ProtocolResultMessage, aO as ResolvedClaimValue, aP as STORAGE_DEFAULT_LIST_LIMIT, aQ as STORAGE_MAX_LIST_LIMIT, aR as STORAGE_MAX_PAYLOAD_BYTES, aS as StorageListEntry, aT as VerifiedAppIdentity, aU as assertToolJson, aV as assertToolPayload, aW as isAiToolMessage, aX as isValidMsFileSourceId, aY as parseToolDefinitions, aZ as sameNetworkIdentity, a_ as validateBsvNetwork, a$ as validateNetworkIdentity, b0 as validateToolArguments } from './protocol-NcRDmEKZ.js';
1
+ import { B as BinaryField, N as NetworkIdentity, A as AiTool, a as AiToolsRegistered, P as ProtocolEventMessage, b as ProtocolMethod, M as MethodParams, c as MethodResult, C as ConnectLoginParams, d as ConnectLoginResult, e as ConnectResumeParams, f as ConnectResumeResult, g as ConnectLogoutResult, h as ConnectLaunchParams, i as ConnectLaunchResult, I as IdentityGetParams, j as IdentityGetResult, k as IntentSignParams, l as IntentSignResult, m as CipherEncryptParams, n as CipherEncryptResult, o as CipherDecryptParams, p as CipherDecryptResult, q as PaymentPayParams, r as PaymentPayResult, s as PaymentStatusParams, t as PaymentStatusResult, u as ChannelPublishParams, v as ChannelPublishResult, w as ChannelSubscriptionSetParams, x as ChannelSubscriptionSetResult, S as StorageListParams, y as StorageListResult, z as StorageDirectoryParams, D as StorageDirectoryResult, E as StoragePutParams, F as StoragePutResult, G as StorageGetParams, H as StorageGetResult, J as StorageDeleteParams, K as StorageDeleteResult, L as MsFileStatParams, O as MsFileStatResult, Q as MsFileSeedReadParams, R as MsFileReadResult, T as MsFileBlockReadParams, U as ProtocolErrorCode } from './protocol-C8z30CKK.js';
2
+ export { V as AI_TOOLS_MAX_JSON_CHARS, W as AiToolDefinition, X as AiToolMessage, Y as AiToolSchema, Z as AppIdentityProofV1, _ as AppIdentitySnapshot, $ as AppRequirement, a0 as BsvNetwork, a1 as ChannelMessageReceivedEventData, a2 as ChannelSubscriptionErrorCode, a3 as ChannelSubscriptionPhase, a4 as ChannelSubscriptionStatus, a5 as ConnectLogoutParams, a6 as ConnectPaymentStatus, a7 as JSONValue, a8 as MSFILE_BLOCK_SIZE_BYTES, a9 as MSFILE_DIGEST_SIZE_BYTES, aa as MSFILE_LOCAL_SOURCE_ID, ab as MSFILE_MAX_BLOCK_BYTES, ac as MSFILE_MAX_CONTENT_BYTES, ad as MSFILE_MAX_ERROR_MESSAGE_BYTES, ae as MSFILE_MAX_HEADER_BYTES, af as MSFILE_MAX_SEED_BYTES, ag as MSFILE_PROTOCOL_ID, ah as MethodParamsMap, ai as MethodResultMap, aj as MsFileLocalSourceStat, ak as MsFileRemoteSourceStat, al as MsFileSatoshiAmount, am as MsFileSourceKind, an as MsFileSourceStat, ao as MsFileStatAbsentEntry, ap as MsFileStatAvailableEntry, aq as MsFileStatDiscoveringEntry, ar as MsFileStatNetworkErrorEntry, as as MsFileStatQuotedEntry, at as MsFileSupplierStat, au as P2pkhTransferAssetId, av as PROTOCOL_METHODS, aw as PROTOCOL_VERSION, ax as PaymentOutput, ay as PaymentReleaseSummary, az as ProtocolCancelMessage, aA as ProtocolClosingMessage, aB as ProtocolError, aC as ProtocolEventName, aD as ProtocolEventPayload, aE as ProtocolReadyMessage, aF as ProtocolReconnectMessage, aG as ProtocolRequestMessage, aH as ProtocolResultMessage, aI as ResolvedClaimValue, aJ as STORAGE_DEFAULT_LIST_LIMIT, aK as STORAGE_MAX_LIST_LIMIT, aL as STORAGE_MAX_PAYLOAD_BYTES, aM as StorageListEntry, aN as VerifiedAppIdentity, aO as assertToolJson, aP as assertToolPayload, aQ as isAiToolMessage, aR as isValidMsFileSourceId, aS as parseToolDefinitions, aT as sameNetworkIdentity, aU as validateBsvNetwork, aV as validateNetworkIdentity, aW as validateToolArguments } from './protocol-C8z30CKK.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;
@@ -10,6 +10,65 @@ declare function binaryText(value: string, mime?: string): BinaryField;
10
10
  /** Decodes a Connect binary field as UTF-8 text. */
11
11
  declare function binaryToText(field: BinaryField): string;
12
12
 
13
+ /** 浏览器刷新恢复记录:只保存最近一次成功连接的可恢复引用,不保存业务材料。 */
14
+
15
+ /** sessionStorage 下唯一的恢复记录键。 */
16
+ declare const RECOVERY_STORAGE_KEY = "keymaster-connect:recovery:v1";
17
+ /** 本地持久的完整恢复记录(含不透明授权引用,不向 UI 公开)。 */
18
+ interface ConnectionRecoveryRecord {
19
+ version: 1;
20
+ targetOrigin: string;
21
+ mode: KeymasterConnectMode;
22
+ authorizationId: string;
23
+ networkIdentity: NetworkIdentity;
24
+ }
25
+ /** 公开给应用的恢复摘要,不含凭据。 */
26
+ interface ConnectionRecoverySummary {
27
+ version: 1;
28
+ targetOrigin: string;
29
+ mode: KeymasterConnectMode;
30
+ networkIdentity: NetworkIdentity;
31
+ }
32
+ /** 可替换的存储适配器;默认实现访问 sessionStorage,不自动降级到 localStorage。 */
33
+ interface ConnectionRecoveryStorage {
34
+ getItem(key: string): string | null;
35
+ setItem(key: string, value: string): void;
36
+ removeItem(key: string): void;
37
+ }
38
+ /** 解析默认 sessionStorage;不可用时返回 null,不抛错、不降级。 */
39
+ declare function resolveRecoveryStorage(explicit?: ConnectionRecoveryStorage): ConnectionRecoveryStorage | null;
40
+ /** 存储是否可用(可用不代表已有记录)。 */
41
+ declare function isRecoveryStorageAvailable(storage?: ConnectionRecoveryStorage): boolean;
42
+ interface ReadRecoveryInit {
43
+ recoveryStorage?: ConnectionRecoveryStorage;
44
+ targetOrigin?: string;
45
+ mode?: KeymasterConnectMode;
46
+ }
47
+ /**
48
+ * 读取恢复摘要供应用在创建 client 前展示,不向 UI 暴露凭据。
49
+ * 提供 targetOrigin/mode 时只在完全相符时返回,否则返回 null。
50
+ */
51
+ declare function readConnectionRecovery(init?: ReadRecoveryInit): ConnectionRecoverySummary | null;
52
+ /** 供 client.resume() 内部装载完整凭据;不直接设置为已登录。 */
53
+ declare function loadConnectionRecoveryRecord(init: {
54
+ recoveryStorage?: ConnectionRecoveryStorage;
55
+ targetOrigin: string;
56
+ mode: KeymasterConnectMode;
57
+ }): ConnectionRecoveryRecord | null;
58
+ /** 保存最近一次成功连接的恢复记录;写入失败时抛错,由调用方决定提示。 */
59
+ declare function saveConnectionRecoveryRecord(storage: ConnectionRecoveryStorage | null, record: ConnectionRecoveryRecord): void;
60
+ interface ClearRecoveryInit {
61
+ recoveryStorage?: ConnectionRecoveryStorage;
62
+ targetOrigin?: string;
63
+ authorizationId?: string;
64
+ }
65
+ /**
66
+ * 主动清除本地恢复记录,只删除本地材料,不代表钱包授权已撤销。
67
+ * 提供 targetOrigin/authorizationId 时仅在完全相符时删除,避免旧实例误删新记录。
68
+ * 返回 true 表示已删除。
69
+ */
70
+ declare function clearConnectionRecovery(init?: ClearRecoveryInit): boolean;
71
+
13
72
  /** iframe:钱包内嵌;appView:钱包弹出 App;popup:App 主动打开钱包。 */
14
73
  type KeymasterConnectMode = "iframe" | "appView" | "popup";
15
74
  /** Observable lifecycle of the browser transport. */
@@ -68,6 +127,8 @@ interface KeymasterConnectOptions {
68
127
  onStateChange?: (state: KeymasterConnectState) => void;
69
128
  /** Optional browser adapter, normally only supplied by tests. */
70
129
  environment?: KeymasterBrowserEnvironment;
130
+ /** 可替换的刷新恢复存储;默认访问 Demo origin 下的 sessionStorage,不降级到 localStorage。 */
131
+ recoveryStorage?: ConnectionRecoveryStorage;
71
132
  }
72
133
  /**
73
134
  * Official browser client for Keymaster Connect V1.
@@ -109,8 +170,8 @@ interface KeymasterConnectOptions {
109
170
  * @groupDescription Cipher
110
171
  * Encrypt and decrypt origin-bound application data.
111
172
  *
112
- * @groupDescription Transfer
113
- * Request a controlled BSV transfer.
173
+ * @groupDescription Payment
174
+ * Submit business outputs and query payment status.
114
175
  *
115
176
  * @groupDescription Channel
116
177
  * Publish JSON content and manage exact-channel subscriptions. Incoming
@@ -130,6 +191,10 @@ declare class KeymasterConnectClient {
130
191
  registerTools(tools: AiTool[], options?: Pick<KeymasterRequestOptions, "signal" | "timeoutMs">): Promise<AiToolsRegistered>;
131
192
  /** Identity returned by the authenticated wallet, or null before establishment. */
132
193
  get networkIdentity(): Readonly<NetworkIdentity> | null;
194
+ /** 最近一次持久化失败的原因;成功后清零。登录成功不受写入失败影响。 */
195
+ get recoverySaveError(): string | null;
196
+ /** 刷新恢复存储是否可用;不可用时仍可登录,但刷新后需重新登录。 */
197
+ get recoveryStorageAvailable(): boolean;
133
198
  private readonly targetOrigin;
134
199
  private readonly mode;
135
200
  private readonly environment;
@@ -146,6 +211,17 @@ declare class KeymasterConnectClient {
146
211
  private authorizationId;
147
212
  private authorizedIdentity;
148
213
  private recoveryId;
214
+ private readonly recoveryStorage;
215
+ private recoverySaveErrorValue;
216
+ /** 显式恢复期间暂停后台心跳,保证本次尝试使用同一份 proof;结束(成功/失败/取消/超时)后恢复。 */
217
+ private explicitRecoveryActive;
218
+ private explicitRecoveryProof;
219
+ /** 内存授权是否已验证:login/launch/恢复成功置 true;仅从存储装载的待验证凭据为 false。 */
220
+ private authorizationVerified;
221
+ /** 当前传输窗口是否已可信就绪(收到过匹配来源与窗口的 ready);新开窗口后重置,存在≠就绪。 */
222
+ private sessionWindowReady;
223
+ /** 新 popup 首发前等待可信窗口 ready 的一次性继续函数;超时/结束时清空。 */
224
+ private recoveryReadyContinue;
149
225
  private recoveryWaiters;
150
226
  constructor(options: KeymasterConnectOptions);
151
227
  /**
@@ -157,7 +233,10 @@ declare class KeymasterConnectClient {
157
233
  /**
158
234
  * Establishes the browser transport.
159
235
  *
160
- * iframe / appView 绑定真实 parent / opener;popup 打开完整钱包等待 ready。
236
+ * 只建立传输,不恢复授权:iframe / appView 绑定真实 parent / opener;
237
+ * popup 打开完整钱包等待 ready。刷新后的授权恢复请使用 `resume()`,
238
+ * 它会先装载本地恢复记录再复用 `continueConnection()`;`connect()` 本身
239
+ * 不读取恢复记录、不自动恢复。
161
240
  *
162
241
  * @group Transport
163
242
  */
@@ -179,6 +258,11 @@ declare class KeymasterConnectClient {
179
258
  * Calls `connect.resume` to restore the unlock runtime for a persistent
180
259
  * session.
181
260
  *
261
+ * 刷新恢复时只把保存的凭据和预期身份载入待恢复上下文,不直接置为已登录;
262
+ * 钱包验证成功、结果身份一致并取得新 binding 后才开放业务调用。
263
+ * 无可用凭据时直接拒绝并提示重新登录,不回退到无凭据的重建默认授权。
264
+ * 恢复请求携带调用方当前入口的 `appIdentity`(如有),不静默丢弃。
265
+ *
182
266
  * @group Connect
183
267
  */
184
268
  resume(params?: ConnectResumeParams, options?: KeymasterRequestOptions): Promise<ConnectResumeResult>;
@@ -231,13 +315,6 @@ declare class KeymasterConnectClient {
231
315
  paymentPay(params: PaymentPayParams, options?: KeymasterRequestOptions): Promise<PaymentPayResult>;
232
316
  /** 按原业务 ID 只读查询付款状态,不自动重付或更换 ID。 */
233
317
  paymentStatus(params: PaymentStatusParams, options?: KeymasterRequestOptions): Promise<PaymentStatusResult>;
234
- /**
235
- * @deprecated Connect v1 接收端拒绝旧转账方法,使用 paymentPay。
236
- * @group Transfer
237
- */
238
- p2pkhTransfer(params: P2pkhTransferParams, options?: KeymasterRequestOptions): Promise<P2pkhTransferResult>;
239
- /** 注册零额度渠道;用户在钱包设置额度后,付款携带返回的 channelId。 */
240
- registerPaymentChannel(params: PaymentChannelRegisterParams, options?: KeymasterRequestOptions): Promise<PaymentChannelRegisterResult>;
241
318
  /**
242
319
  * 发布到任意精确频道;owner、公钥签名和消息编号由 Keymaster 生成。
243
320
  *
@@ -280,6 +357,18 @@ declare class KeymasterConnectClient {
280
357
  * @group Storage
281
358
  */
282
359
  storageGet(params: StorageGetParams, options?: KeymasterRequestOptions): Promise<StorageGetResult>;
360
+ /**
361
+ * 可选加密写入:向钱包提交明文,钱包以当前钱包密钥和 App 公钥隔离后加密保存。
362
+ * 路径、条件创建语义与 storagePut 相同,size 返回明文字节数;不会返回加密密钥。
363
+ * @group Storage
364
+ */
365
+ storagePutEncrypted(params: StoragePutParams, options?: KeymasterRequestOptions): Promise<StoragePutResult>;
366
+ /**
367
+ * 可选加密读取:仅同一钱包能解密;offset/length 作用于明文,ifMatch 仍比较远端版本。
368
+ * 明文对象、错误格式、篡改或密钥不匹配均失败,不自动回退为普通读取。
369
+ * @group Storage
370
+ */
371
+ storageGetEncrypted(params: StorageGetParams, options?: KeymasterRequestOptions): Promise<StorageGetResult>;
283
372
  /**
284
373
  * Calls `storage.delete` to delete an app-scoped object.
285
374
  *
@@ -320,6 +409,9 @@ declare class KeymasterConnectClient {
320
409
  * Tears down the local transport. This does not revoke persistent Connect
321
410
  * sessions; call {@link logout} before closing when revocation is required.
322
411
  *
412
+ * 只结束运行连接,保留刷新恢复材料:`close()`、页面卸载和运行失效都不删除
413
+ * 本地恢复记录;`logout` 成功、明确授权失效或用户主动清除才删除。
414
+ *
323
415
  * @group Transport
324
416
  */
325
417
  close(): void;
@@ -335,6 +427,10 @@ declare class KeymasterConnectClient {
335
427
  private disconnect;
336
428
  /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
337
429
  private pause;
430
+ /** 保存最近成功连接的恢复记录;写入失败只记录原因,不影响已成功的登录。 */
431
+ private persistRecoveryRecord;
432
+ /** 按目标与授权核对后清除本地恢复记录;旧实例迟到结果不得删除新记录。 */
433
+ private dropRecoveryRecord;
338
434
  private sendRecovery;
339
435
  private finishRecovery;
340
436
  private startClosePolling;
@@ -349,4 +445,4 @@ declare function createKeymasterConnect(options: KeymasterConnectOptions): Keyma
349
445
  /** Creates the production environment adapter from the current browser window. */
350
446
  declare function createBrowserEnvironment(): KeymasterBrowserEnvironment;
351
447
 
352
- export { AiTool, AiToolsRegistered, BinaryField, ChannelPublishParams, ChannelPublishResult, ChannelSubscriptionSetParams, ChannelSubscriptionSetResult, CipherDecryptParams, CipherDecryptResult, CipherEncryptParams, CipherEncryptResult, ConnectLaunchParams, ConnectLaunchResult, ConnectLoginParams, ConnectLoginResult, ConnectLogoutResult, ConnectResumeParams, ConnectResumeResult, IdentityGetParams, IdentityGetResult, IntentSignParams, IntentSignResult, type KeymasterBrowserEnvironment, KeymasterConnectClient, type KeymasterConnectMode, type KeymasterConnectOptions, type KeymasterConnectState, KeymasterProtocolError, type KeymasterRequestOptions, KeymasterTransportError, type KeymasterTransportErrorCode, MethodParams, MethodResult, MsFileBlockReadParams, MsFileReadResult, MsFileSeedReadParams, MsFileStatParams, MsFileStatResult, NetworkIdentity, P2pkhTransferParams, P2pkhTransferResult, PaymentChannelRegisterParams, PaymentChannelRegisterResult, PaymentPayParams, PaymentPayResult, PaymentStatusParams, PaymentStatusResult, ProtocolErrorCode, ProtocolEventMessage, ProtocolMethod, StorageDeleteParams, StorageDeleteResult, StorageDirectoryParams, StorageDirectoryResult, StorageGetParams, StorageGetResult, StorageListParams, StorageListResult, StoragePutParams, StoragePutResult, binary, binaryBytes, binaryText, binaryToText, createBrowserEnvironment, createKeymasterConnect };
448
+ export { AiTool, AiToolsRegistered, BinaryField, ChannelPublishParams, ChannelPublishResult, ChannelSubscriptionSetParams, ChannelSubscriptionSetResult, CipherDecryptParams, CipherDecryptResult, CipherEncryptParams, CipherEncryptResult, type ClearRecoveryInit, ConnectLaunchParams, ConnectLaunchResult, ConnectLoginParams, ConnectLoginResult, ConnectLogoutResult, ConnectResumeParams, ConnectResumeResult, type ConnectionRecoveryRecord, type ConnectionRecoveryStorage, type ConnectionRecoverySummary, IdentityGetParams, IdentityGetResult, IntentSignParams, IntentSignResult, type KeymasterBrowserEnvironment, KeymasterConnectClient, type KeymasterConnectMode, type KeymasterConnectOptions, type KeymasterConnectState, KeymasterProtocolError, type KeymasterRequestOptions, KeymasterTransportError, type KeymasterTransportErrorCode, MethodParams, MethodResult, MsFileBlockReadParams, MsFileReadResult, MsFileSeedReadParams, MsFileStatParams, MsFileStatResult, NetworkIdentity, PaymentPayParams, PaymentPayResult, PaymentStatusParams, PaymentStatusResult, ProtocolErrorCode, ProtocolEventMessage, ProtocolMethod, RECOVERY_STORAGE_KEY, type ReadRecoveryInit, StorageDeleteParams, StorageDeleteResult, StorageDirectoryParams, StorageDirectoryResult, StorageGetParams, StorageGetResult, StorageListParams, StorageListResult, StoragePutParams, StoragePutResult, binary, binaryBytes, binaryText, binaryToText, clearConnectionRecovery, createBrowserEnvironment, createKeymasterConnect, isRecoveryStorageAvailable, loadConnectionRecoveryRecord, readConnectionRecovery, resolveRecoveryStorage, saveConnectionRecoveryRecord };