@harrylabsj/kiwi 0.12.32 → 0.12.34

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.
Files changed (259) hide show
  1. package/README.md +8 -0
  2. package/dist/a2a/inquiry-nonce-store.d.ts +12 -1
  3. package/dist/a2a/inquiry-nonce-store.js +49 -17
  4. package/dist/a2a/inquiry-nonce-store.js.map +1 -1
  5. package/dist/a2a/negotiate.d.ts +30 -1
  6. package/dist/a2a/negotiate.js +121 -32
  7. package/dist/a2a/negotiate.js.map +1 -1
  8. package/dist/a2a/node.d.ts +3 -0
  9. package/dist/a2a/node.js +13 -3
  10. package/dist/a2a/node.js.map +1 -1
  11. package/dist/a2a/open-inquiry-session.d.ts +1 -0
  12. package/dist/a2a/open-inquiry-session.js +3 -1
  13. package/dist/a2a/open-inquiry-session.js.map +1 -1
  14. package/dist/a2a/open-inquiry-verifier.js +2 -2
  15. package/dist/a2a/open-inquiry-verifier.js.map +1 -1
  16. package/dist/a2a/server/errors.d.ts +4 -3
  17. package/dist/a2a/server/errors.js +10 -2
  18. package/dist/a2a/server/errors.js.map +1 -1
  19. package/dist/a2a/server/merchant-handler.d.ts +41 -1
  20. package/dist/a2a/server/merchant-handler.js +259 -89
  21. package/dist/a2a/server/merchant-handler.js.map +1 -1
  22. package/dist/a2a/server/merchant-procurement.d.ts +90 -0
  23. package/dist/a2a/server/merchant-procurement.js +75 -0
  24. package/dist/a2a/server/merchant-procurement.js.map +1 -0
  25. package/dist/a2a/server/merchant-product-facts.d.ts +2 -0
  26. package/dist/a2a/server/merchant-product-facts.js.map +1 -1
  27. package/dist/a2a/server/negotiation-approvals.d.ts +11 -0
  28. package/dist/a2a/server/negotiation-approvals.js +43 -0
  29. package/dist/a2a/server/negotiation-approvals.js.map +1 -1
  30. package/dist/a2a/server/pipeline.js +4 -1
  31. package/dist/a2a/server/pipeline.js.map +1 -1
  32. package/dist/a2a/server/server.js +4 -3
  33. package/dist/a2a/server/server.js.map +1 -1
  34. package/dist/a2a/server/types.d.ts +2 -1
  35. package/dist/agent/alipay-native-view.d.ts +27 -0
  36. package/dist/agent/alipay-native-view.js +113 -0
  37. package/dist/agent/alipay-native-view.js.map +1 -0
  38. package/dist/agent/buyer/buyer-tools.d.ts +20 -0
  39. package/dist/agent/buyer/buyer-tools.js +241 -48
  40. package/dist/agent/buyer/buyer-tools.js.map +1 -1
  41. package/dist/agent/buyer/types.d.ts +1 -1
  42. package/dist/agent/buyer/types.js.map +1 -1
  43. package/dist/agent/chat-tui.js +16 -1
  44. package/dist/agent/chat-tui.js.map +1 -1
  45. package/dist/agent/kernel-builder.d.ts +2 -0
  46. package/dist/agent/kernel-builder.js +14 -0
  47. package/dist/agent/kernel-builder.js.map +1 -1
  48. package/dist/agent/kernel.d.ts +8 -0
  49. package/dist/agent/kernel.js +67 -1
  50. package/dist/agent/kernel.js.map +1 -1
  51. package/dist/buyer-core/a2a-accept-terms.d.ts +11 -0
  52. package/dist/buyer-core/a2a-accept-terms.js +28 -0
  53. package/dist/buyer-core/a2a-accept-terms.js.map +1 -0
  54. package/dist/buyer-core/a2a-knp.d.ts +3 -0
  55. package/dist/buyer-core/a2a-knp.js +3 -3
  56. package/dist/buyer-core/a2a-knp.js.map +1 -1
  57. package/dist/buyer-core/a2a-negotiator.d.ts +16 -0
  58. package/dist/buyer-core/a2a-negotiator.js +53 -16
  59. package/dist/buyer-core/a2a-negotiator.js.map +1 -1
  60. package/dist/buyer-core/a2a-quote-fetcher.d.ts +0 -15
  61. package/dist/buyer-core/a2a-quote-fetcher.js +10 -15
  62. package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
  63. package/dist/buyer-core/merchant-index.d.ts +2 -2
  64. package/dist/buyer-core/merchant-index.js +23 -5
  65. package/dist/buyer-core/merchant-index.js.map +1 -1
  66. package/dist/buyer-core/procurement/cases.d.ts +441 -0
  67. package/dist/buyer-core/procurement/cases.js +457 -0
  68. package/dist/buyer-core/procurement/cases.js.map +1 -0
  69. package/dist/buyer-core/procurement/quote-comparison.d.ts +137 -0
  70. package/dist/buyer-core/procurement/quote-comparison.js +106 -0
  71. package/dist/buyer-core/procurement/quote-comparison.js.map +1 -0
  72. package/dist/buyer-core/procurement/quote-normalizer.d.ts +45 -0
  73. package/dist/buyer-core/procurement/quote-normalizer.js +153 -0
  74. package/dist/buyer-core/procurement/quote-normalizer.js.map +1 -0
  75. package/dist/buyer-core/procurement/requirements.d.ts +50 -0
  76. package/dist/buyer-core/procurement/requirements.js +43 -0
  77. package/dist/buyer-core/procurement/requirements.js.map +1 -0
  78. package/dist/buyer-core/procurement/source-observation.d.ts +57 -0
  79. package/dist/buyer-core/procurement/source-observation.js +54 -0
  80. package/dist/buyer-core/procurement/source-observation.js.map +1 -0
  81. package/dist/buyer-core/procurement/store.d.ts +21 -0
  82. package/dist/buyer-core/procurement/store.js +68 -0
  83. package/dist/buyer-core/procurement/store.js.map +1 -0
  84. package/dist/buyer-core/protocol-recovery.d.ts +8 -0
  85. package/dist/buyer-core/protocol-recovery.js +17 -2
  86. package/dist/buyer-core/protocol-recovery.js.map +1 -1
  87. package/dist/buyer-core/quote-quantity.d.ts +5 -0
  88. package/dist/buyer-core/quote-quantity.js +15 -0
  89. package/dist/buyer-core/quote-quantity.js.map +1 -0
  90. package/dist/buyer-core/service.d.ts +71 -3
  91. package/dist/buyer-core/service.js +271 -28
  92. package/dist/buyer-core/service.js.map +1 -1
  93. package/dist/buyer-core/store.d.ts +13 -0
  94. package/dist/buyer-core/store.js +25 -3
  95. package/dist/buyer-core/store.js.map +1 -1
  96. package/dist/cli.js +13 -17
  97. package/dist/cli.js.map +1 -1
  98. package/dist/cloud/alipay-collection-http.d.ts +44 -0
  99. package/dist/cloud/alipay-collection-http.js +111 -0
  100. package/dist/cloud/alipay-collection-http.js.map +1 -0
  101. package/dist/cloud/bootstrap.js +98 -12
  102. package/dist/cloud/bootstrap.js.map +1 -1
  103. package/dist/cloud/http-router.d.ts +2 -0
  104. package/dist/cloud/http-router.js +5 -0
  105. package/dist/cloud/http-router.js.map +1 -1
  106. package/dist/commerce/receipt/dispatcher.d.ts +2 -1
  107. package/dist/commerce/receipt/dispatcher.js +18 -0
  108. package/dist/commerce/receipt/dispatcher.js.map +1 -1
  109. package/dist/commerce/receipt/receipts.d.ts +7 -0
  110. package/dist/commerce/receipt/receipts.js +43 -5
  111. package/dist/commerce/receipt/receipts.js.map +1 -1
  112. package/dist/discovery/catalog-source/buyer-follows.d.ts +3 -3
  113. package/dist/discovery/catalog-source/buyer-follows.js +6 -3
  114. package/dist/discovery/catalog-source/buyer-follows.js.map +1 -1
  115. package/dist/discovery/catalog-source/kiwi-record.d.ts +2 -0
  116. package/dist/discovery/catalog-source/kiwi-record.js.map +1 -1
  117. package/dist/discovery/catalog-source/kiwi-source.js +4 -0
  118. package/dist/discovery/catalog-source/kiwi-source.js.map +1 -1
  119. package/dist/handoff/alipay-collection.d.ts +23 -0
  120. package/dist/handoff/alipay-collection.js +70 -0
  121. package/dist/handoff/alipay-collection.js.map +1 -0
  122. package/dist/handoff/order-receipts.js +2 -1
  123. package/dist/handoff/order-receipts.js.map +1 -1
  124. package/dist/handoff/ucp-checkout/channel.d.ts +1 -0
  125. package/dist/handoff/ucp-checkout/channel.js +42 -17
  126. package/dist/handoff/ucp-checkout/channel.js.map +1 -1
  127. package/dist/http/customer-support-buyer.d.ts +24 -0
  128. package/dist/http/customer-support-buyer.js +306 -0
  129. package/dist/http/customer-support-buyer.js.map +1 -0
  130. package/dist/http/merchant-management/api.d.ts +12 -0
  131. package/dist/http/merchant-management/api.js +425 -6
  132. package/dist/http/merchant-management/api.js.map +1 -1
  133. package/dist/http/merchant-management/page.d.ts +2 -0
  134. package/dist/http/merchant-management/page.js +630 -3
  135. package/dist/http/merchant-management/page.js.map +1 -1
  136. package/dist/http/server.js +9 -2
  137. package/dist/http/server.js.map +1 -1
  138. package/dist/mcp/cli.d.ts +3 -1
  139. package/dist/mcp/cli.js +12 -2
  140. package/dist/mcp/cli.js.map +1 -1
  141. package/dist/mcp/merchant-runtime-assembly.d.ts +3 -0
  142. package/dist/mcp/merchant-runtime-assembly.js +9 -8
  143. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  144. package/dist/mcp/procurement-tools.d.ts +10 -0
  145. package/dist/mcp/procurement-tools.js +173 -0
  146. package/dist/mcp/procurement-tools.js.map +1 -0
  147. package/dist/mcp/server.d.ts +4 -0
  148. package/dist/mcp/server.js +63 -9
  149. package/dist/mcp/server.js.map +1 -1
  150. package/dist/mcp/tools.d.ts +4 -1
  151. package/dist/mcp/tools.js +76 -27
  152. package/dist/mcp/tools.js.map +1 -1
  153. package/dist/mcp/types.d.ts +1 -0
  154. package/dist/mcp/types.js.map +1 -1
  155. package/dist/merchant/ai-runtime/owner-storage-admission.js.map +1 -1
  156. package/dist/merchant/application/actor.d.ts +2 -0
  157. package/dist/merchant/application/actor.js +6 -0
  158. package/dist/merchant/application/actor.js.map +1 -1
  159. package/dist/merchant/negotiation-ops.d.ts +2 -0
  160. package/dist/merchant/negotiation-ops.js +4 -0
  161. package/dist/merchant/negotiation-ops.js.map +1 -1
  162. package/dist/merchant/weixin-channel.d.ts +224 -0
  163. package/dist/merchant/weixin-channel.js +435 -0
  164. package/dist/merchant/weixin-channel.js.map +1 -0
  165. package/dist/merchant/weixin-owner-agent-profile.d.ts +8 -0
  166. package/dist/merchant/weixin-owner-agent-profile.js +29 -0
  167. package/dist/merchant/weixin-owner-agent-profile.js.map +1 -0
  168. package/dist/merchant/weixin-owner-agent.d.ts +42 -0
  169. package/dist/merchant/weixin-owner-agent.js +97 -0
  170. package/dist/merchant/weixin-owner-agent.js.map +1 -0
  171. package/dist/merchant/weixin-owner-conversation.d.ts +156 -0
  172. package/dist/merchant/weixin-owner-conversation.js +559 -0
  173. package/dist/merchant/weixin-owner-conversation.js.map +1 -0
  174. package/dist/merchant/weixin-owner-digest.d.ts +30 -0
  175. package/dist/merchant/weixin-owner-digest.js +30 -0
  176. package/dist/merchant/weixin-owner-digest.js.map +1 -0
  177. package/dist/merchant/weixin-owner-inventory.d.ts +28 -0
  178. package/dist/merchant/weixin-owner-inventory.js +48 -0
  179. package/dist/merchant/weixin-owner-inventory.js.map +1 -0
  180. package/dist/merchant/weixin-owner-source.d.ts +22 -0
  181. package/dist/merchant/weixin-owner-source.js +104 -0
  182. package/dist/merchant/weixin-owner-source.js.map +1 -0
  183. package/dist/merchant/workbench-server.d.ts +4 -0
  184. package/dist/merchant/workbench-server.js +75 -9
  185. package/dist/merchant/workbench-server.js.map +1 -1
  186. package/dist/merchant-core/collection/alipay-store.d.ts +22 -0
  187. package/dist/merchant-core/collection/alipay-store.js +125 -0
  188. package/dist/merchant-core/collection/alipay-store.js.map +1 -0
  189. package/dist/merchant-core/commercial/calculate.js +6 -6
  190. package/dist/merchant-core/commercial/calculate.js.map +1 -1
  191. package/dist/merchant-core/operating/repository.d.ts +0 -1
  192. package/dist/merchant-core/operating/repository.js +2 -17
  193. package/dist/merchant-core/operating/repository.js.map +1 -1
  194. package/dist/merchant-core/operations-jobs/service.d.ts +11 -0
  195. package/dist/merchant-core/operations-jobs/service.js +65 -34
  196. package/dist/merchant-core/operations-jobs/service.js.map +1 -1
  197. package/dist/merchant-core/opportunity/repository.d.ts +0 -1
  198. package/dist/merchant-core/opportunity/repository.js +2 -17
  199. package/dist/merchant-core/opportunity/repository.js.map +1 -1
  200. package/dist/merchant-core/ops/surface.d.ts +1 -0
  201. package/dist/merchant-core/ops/surface.js +9 -0
  202. package/dist/merchant-core/ops/surface.js.map +1 -1
  203. package/dist/merchant-core/orders/model.d.ts +1 -8
  204. package/dist/merchant-core/orders/model.js +10 -2
  205. package/dist/merchant-core/orders/model.js.map +1 -1
  206. package/dist/merchant-core/orders/repository.d.ts +0 -1
  207. package/dist/merchant-core/orders/repository.js +3 -18
  208. package/dist/merchant-core/orders/repository.js.map +1 -1
  209. package/dist/merchant-core/orders/service.js +34 -8
  210. package/dist/merchant-core/orders/service.js.map +1 -1
  211. package/dist/merchant-core/proposal/engine.js +2 -0
  212. package/dist/merchant-core/proposal/engine.js.map +1 -1
  213. package/dist/merchant-core/proposal/publish.d.ts +0 -6
  214. package/dist/merchant-core/proposal/publish.js +37 -3
  215. package/dist/merchant-core/proposal/publish.js.map +1 -1
  216. package/dist/merchant-core/proposal/repository.d.ts +0 -7
  217. package/dist/merchant-core/proposal/repository.js +8 -17
  218. package/dist/merchant-core/proposal/repository.js.map +1 -1
  219. package/dist/merchant-core/proposal/types.d.ts +1 -0
  220. package/dist/merchant-core/proposal/types.js.map +1 -1
  221. package/dist/merchant-core/rfq/policy.d.ts +1 -0
  222. package/dist/merchant-core/rfq/policy.js +6 -7
  223. package/dist/merchant-core/rfq/policy.js.map +1 -1
  224. package/dist/merchant-core/rfq/repository.d.ts +0 -1
  225. package/dist/merchant-core/rfq/repository.js +2 -17
  226. package/dist/merchant-core/rfq/repository.js.map +1 -1
  227. package/dist/merchant-core/rfq/service.d.ts +2 -1
  228. package/dist/merchant-core/rfq/service.js +2 -4
  229. package/dist/merchant-core/rfq/service.js.map +1 -1
  230. package/dist/merchant-core/storage/transaction.d.ts +4 -11
  231. package/dist/merchant-core/storage/transaction.js +43 -65
  232. package/dist/merchant-core/storage/transaction.js.map +1 -1
  233. package/dist/merchant-core/support/manual-service.d.ts +114 -0
  234. package/dist/merchant-core/support/manual-service.js +300 -0
  235. package/dist/merchant-core/support/manual-service.js.map +1 -0
  236. package/dist/negotiation/domain/objects.d.ts +2 -0
  237. package/dist/negotiation/domain/objects.js +3 -0
  238. package/dist/negotiation/domain/objects.js.map +1 -1
  239. package/dist/negotiation/ledger/store.d.ts +6 -0
  240. package/dist/negotiation/ledger/store.js +28 -0
  241. package/dist/negotiation/ledger/store.js.map +1 -1
  242. package/dist/net/safe-http.d.ts +2 -0
  243. package/dist/net/safe-http.js +1 -1
  244. package/dist/net/safe-http.js.map +1 -1
  245. package/dist/product-init.d.ts +1 -0
  246. package/dist/product-init.js +4 -1
  247. package/dist/product-init.js.map +1 -1
  248. package/dist/trust/identity/message-signature.d.ts +1 -1
  249. package/dist/trust/identity/message-signature.js +6 -1
  250. package/dist/trust/identity/message-signature.js.map +1 -1
  251. package/dist/trust/identity/nonce.d.ts +5 -0
  252. package/dist/trust/identity/nonce.js +2 -0
  253. package/dist/trust/identity/nonce.js.map +1 -1
  254. package/dist/weixin/ilink-client.d.ts +3 -2
  255. package/dist/weixin/ilink-client.js +58 -20
  256. package/dist/weixin/ilink-client.js.map +1 -1
  257. package/dist/weixin/types.d.ts +3 -1
  258. package/dist/weixin/types.js.map +1 -1
  259. package/package.json +14 -14
@@ -38,6 +38,9 @@
38
38
  * operation_id 查询路径(§11.1),绝不当作失败自动重做。
39
39
  */
40
40
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
41
+ import { MerchantWeixinError } from "../../merchant/weixin-channel.js";
42
+ import { OwnerConversationError } from "../../merchant/weixin-owner-conversation.js";
43
+ import { ManualSupportError } from "../../merchant-core/support/manual-service.js";
41
44
  import { contentHash } from "../../agent/merchant/action-candidate.js";
42
45
  import { ADMIN_SESSION_COOKIE } from "../../auth/merchant-sessions.js";
43
46
  import { FileListingPublicationError, } from "../../cloud/file-listing-publication.js";
@@ -45,7 +48,7 @@ import { parseProductTable, ProductTableError, productTableDigest, } from "../..
45
48
  import { convertTabularImport, renderImportTemplateCsv, renderImportTemplateXlsx, TABULAR_IMPORT_MAX_BYTES, } from "../../cloud/product-import-tabular.js";
46
49
  import { normalizeTradePlatformRules, } from "../../handoff/trade-platform-rules.js";
47
50
  import { MerchantImportDraftStore } from "./draft-store.js";
48
- import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, } from "../../merchant/application/actor.js";
51
+ import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, isDirectMerchantOwner, } from "../../merchant/application/actor.js";
49
52
  import { MANAGEMENT_API_MAJOR, MANAGEMENT_ERROR_STATUS, ManagementError, MerchantApplicationService, } from "../../merchant/application/service.js";
50
53
  import { managementRequestDigest, MerchantManagementOperationStore } from "./operation-store.js";
51
54
  import { OnboardingStore } from "../../cloud/onboarding/store.js";
@@ -57,8 +60,10 @@ import { checkStepSubmission, planWizard, WIZARD_STEPS } from "../../cloud/onboa
57
60
  import { createWorkbenchProblem } from "./problem.js";
58
61
  import { WorkbenchConfirmationError, } from "./webauthn-confirmation.js";
59
62
  import { MerchantWorkbenchError, } from "../../merchant/workbench-service.js";
63
+ import { NegotiationOpsError } from "../../merchant/negotiation-ops.js";
60
64
  import { NEGOTIATION_STATUS_FILTERS, } from "../../merchant/negotiation-observer.js";
61
65
  import { parseReportPeriod, } from "../../merchant/operations-report.js";
66
+ import { AlipayCollectionConflict, isBoundedAlipayQrPng, } from "../../merchant-core/collection/alipay-store.js";
62
67
  import { OrderFactError } from "../../merchant-core/orders/model.js";
63
68
  import { OperatingPlanError } from "../../merchant-core/operating/types.js";
64
69
  import { OpportunityError } from "../../merchant-core/opportunity/types.js";
@@ -81,6 +86,8 @@ import { WorkbenchEventProjectionError, } from "./event-projection.js";
81
86
  import { GRANT_ACTIONS, MerchantGrantError, } from "../../merchant/grant-store.js";
82
87
  const API_PREFIX = "/merchant/api";
83
88
  const WORKBENCH_API_PREFIX = "/merchant/api/v1";
89
+ const ALIPAY_COLLECTION_PATH = "/collection/alipay";
90
+ const ALIPAY_APPROVAL_PATH = `${ALIPAY_COLLECTION_PATH}/approvals`;
84
91
  const CATALOG_CONNECTION_SAFE_CODES = new Set([
85
92
  "PUBLICATION_NOT_ACTIVE", "PUBLICATION_NOT_VERIFIED", "CATALOG_UNREACHABLE",
86
93
  "CATALOG_MISMATCH", "BINDING_MERCHANT_MISMATCH", "BINDING_CLAIM_EXPIRED",
@@ -117,6 +124,51 @@ async function resolvePlatformRules(options) {
117
124
  return normalizeTradePlatformRules(undefined);
118
125
  }
119
126
  }
127
+ function alipayCollectionSummary(config) {
128
+ const mask = (value) => {
129
+ const letters = Array.from(value);
130
+ return letters.length > 1 ? `${letters[0]}***` : "***";
131
+ };
132
+ return {
133
+ version: config?.version ?? null,
134
+ enabled: config?.enabled ?? false,
135
+ recipient_masked: config === undefined ? null : mask(config.recipient),
136
+ account_masked: config?.account === undefined ? null : mask(config.account),
137
+ has_qr: config?.qrPngBase64 !== undefined,
138
+ };
139
+ }
140
+ function alipayFields(body, allowed) {
141
+ const fields = requireObject(body, "body");
142
+ if (Object.keys(fields).some((key) => !allowed.includes(key))) {
143
+ // Field names are also user input; never echo them on this settings surface.
144
+ throw new ManagementError("invalid_input", "支付宝收款请求包含不支持的字段");
145
+ }
146
+ return fields;
147
+ }
148
+ function alipayExpectedVersion(value) {
149
+ if (value === null || (typeof value === "string" && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/.test(value)))
150
+ return value;
151
+ throw new ManagementError("invalid_input", "需要有效的收款配置版本(首次设置为 null)");
152
+ }
153
+ function alipayCollectionInput(fields) {
154
+ const enabled = fields["enabled"];
155
+ const recipient = requireString(fields["recipient"], "recipient").trim();
156
+ const account = fields["account"] === undefined ? undefined : requireString(fields["account"], "account").trim();
157
+ const qrPngBase64 = fields["qr_png_base64"];
158
+ if (typeof enabled !== "boolean" || recipient.length > 80 || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(recipient)) {
159
+ throw new ManagementError("invalid_input", "收款主体名称或启用状态无效");
160
+ }
161
+ if (account !== undefined && (account.length > 128 || !/^(?:\+?[0-9]{5,20}|[A-Za-z0-9._+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)$/.test(account))) {
162
+ throw new ManagementError("invalid_input", "支付宝账号须为手机号或邮箱");
163
+ }
164
+ if (qrPngBase64 !== undefined && !isBoundedAlipayQrPng(qrPngBase64)) {
165
+ throw new ManagementError("invalid_input", "仅支持不超过 256 KiB、宽高不超过 1024 像素的静态 PNG");
166
+ }
167
+ if (account === undefined && qrPngBase64 === undefined) {
168
+ throw new ManagementError("invalid_input", "请填写支付宝账号或上传官方静态收款码");
169
+ }
170
+ return { enabled, recipient, ...(account === undefined ? {} : { account }), ...(qrPngBase64 === undefined ? {} : { qrPngBase64 }) };
171
+ }
120
172
  function deliveryField(body, key) {
121
173
  const value = body[key];
122
174
  if (typeof value !== "string" || value.trim() === "") {
@@ -153,6 +205,7 @@ export function createMerchantManagementApiHandler(options) {
153
205
  // CSRF 进程密钥:令牌 = HMAC(sessionId, key)。重启后页面重新拉取 /session
154
206
  // 即可取到新令牌;跨进程不可推导,持 Cookie 者本就可推导(CSRF 威胁模型成立)。
155
207
  const csrfKey = randomBytes(32);
208
+ const alipayPreviewKey = randomBytes(32);
156
209
  const baseDeps = {
157
210
  merchantId: options.merchantId,
158
211
  generation: options.generation,
@@ -219,6 +272,14 @@ export function createMerchantManagementApiHandler(options) {
219
272
  const requestId = `req_${randomBytes(12).toString("hex")}`;
220
273
  const rest = pathname === WORKBENCH_API_PREFIX ? "/" : pathname.slice(WORKBENCH_API_PREFIX.length);
221
274
  try {
275
+ if (options.manualSupport !== undefined && (rest === "/support" || rest.startsWith("/support/"))) {
276
+ await routeManualSupport(options.manualSupport, req, res, method, rest);
277
+ return;
278
+ }
279
+ if (rest === "/channels/weixin" || rest.startsWith("/channels/weixin/")) {
280
+ await routeWeixin(req, res, method, rest);
281
+ return;
282
+ }
222
283
  if (method === "GET") {
223
284
  await routeWorkbenchV1Get(req, res, url, rest, requestId);
224
285
  return;
@@ -262,6 +323,179 @@ export function createMerchantManagementApiHandler(options) {
262
323
  }
263
324
  writeJson(res, 404, errorBody("not_found", "unknown management api path"));
264
325
  }
326
+ async function routeManualSupport(support, req, res, method, rest) {
327
+ const auth = requireActor(req);
328
+ if (auth.ctx.merchantId !== options.merchantId)
329
+ throw new ManagementError("not_found", "工单不存在。");
330
+ if (auth.ctx.role !== "owner")
331
+ throw new ManagementError("forbidden", "当前预览仅店主可处理售后工单。");
332
+ const match = /^\/support\/cases\/(CS-[0-9a-f-]{36})(?:\/(claim|reply|resolve|revoke))?$/.exec(rest);
333
+ try {
334
+ if (method === "GET" && rest === "/support/cases") {
335
+ writeJson(res, 200, { cases: support.list(auth.ctx) });
336
+ return;
337
+ }
338
+ if (method === "GET" && match?.[1] !== undefined && match[2] === undefined) {
339
+ writeJson(res, 200, support.detail(auth.ctx, match[1]));
340
+ return;
341
+ }
342
+ if (method === "POST" && match?.[1] !== undefined && match[2] !== undefined) {
343
+ assertWriteGuards(req, auth.sessionId);
344
+ const kind = match[2];
345
+ const fields = objectFields(await readJsonBody(req, 8192), kind === "reply" || kind === "resolve"
346
+ ? ["expected_revision", "text"] : ["expected_revision"]);
347
+ const revision = fields.expected_revision;
348
+ if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 1) {
349
+ throw new ManagementError("invalid_input", "工单版本无效。");
350
+ }
351
+ // 请求体读取期间可能已经注销或撤销授权;不要提交旧会话已缓存的权限。
352
+ const fresh = requireActor(req);
353
+ if (fresh.ctx.generation !== auth.ctx.generation)
354
+ throw new ManagementError("forbidden", "管理部署代次已变化。");
355
+ if (kind === "reply" || kind === "resolve") {
356
+ if (typeof fields.text !== "string")
357
+ throw new ManagementError("invalid_input", "请输入人工说明。");
358
+ writeJson(res, 200, support.change(fresh.ctx, match[1], revision, { kind, text: fields.text }));
359
+ }
360
+ else if (kind === "claim" || kind === "revoke") {
361
+ writeJson(res, 200, support.change(fresh.ctx, match[1], revision, { kind }));
362
+ }
363
+ return;
364
+ }
365
+ }
366
+ catch (error) {
367
+ if (error instanceof BodyTooLarge)
368
+ throw new ManagementError("invalid_input", "工单请求过大。");
369
+ if (error instanceof ManualSupportError) {
370
+ switch (error.code) {
371
+ case "validation": throw new ManagementError("invalid_input", "工单输入无效。");
372
+ case "not_found": throw new ManagementError("not_found", "工单不存在。");
373
+ case "conflict": throw new ManagementError("precondition_changed", "工单版本、坐席或浏览器权限已变化。");
374
+ case "forbidden": throw new ManagementError("forbidden", "当前主体无权处理该工单。");
375
+ default: throw new ManagementError("unavailable", "工单服务暂不可用。");
376
+ }
377
+ }
378
+ throw error;
379
+ }
380
+ throw new ManagementError("not_found", "工单路由不存在。");
381
+ }
382
+ async function routeWeixin(req, res, method, rest) {
383
+ const channel = options.weixinChannel;
384
+ if (channel === undefined)
385
+ throw new ManagementError("not_found", "微信通道未启用。");
386
+ const auth = requireActor(req);
387
+ const actor = assertVerifiedActor(auth.ctx, now());
388
+ if (actor.merchantId !== options.merchantId)
389
+ throw new ManagementError("not_found", "微信通道不存在。");
390
+ if (actor.role !== "owner")
391
+ throw new ManagementError("forbidden", "仅店主可管理微信通道。");
392
+ const base = "/channels/weixin";
393
+ const owner = {
394
+ sessionId: auth.sessionId,
395
+ principalId: actor.actorId,
396
+ generation: actor.generation,
397
+ current: () => {
398
+ if (actor.generation !== options.generation())
399
+ return false;
400
+ const session = options.sessions.getSession(auth.sessionId);
401
+ return session?.role === "owner" && session.merchant_id === options.merchantId &&
402
+ session.principal_id === actor.actorId;
403
+ },
404
+ };
405
+ const action = rest.slice(base.length + 1);
406
+ const draftId = /^reply-drafts\/([0-9a-f-]{36})$/.exec(action)?.[1];
407
+ try {
408
+ if (method === "GET" && rest === base) {
409
+ const status = channel.status(owner.principalId);
410
+ writeJson(res, 200, !("conversation" in status) ? status : {
411
+ ...status, operations_available: options.governance?.flags.jobs_enabled === true && options.merchantOperations !== undefined &&
412
+ options.operationsSchedulerAvailable?.() === true,
413
+ });
414
+ return;
415
+ }
416
+ if (method === "GET" && action === "followup-preference") {
417
+ writeJson(res, 200, channel.followupPreference(owner));
418
+ return;
419
+ }
420
+ if (method === "GET" && action === "reply-drafts") {
421
+ writeJson(res, 200, { items: channel.replyDrafts(owner) });
422
+ return;
423
+ }
424
+ if (method === "GET" && draftId !== undefined) {
425
+ writeJson(res, 200, channel.replyDraft(owner, draftId));
426
+ return;
427
+ }
428
+ if (method !== "POST" || (draftId === undefined &&
429
+ !["begin", "poll", "cancel", "disconnect", "confirm-conversation", "clear-conversation", "revoke-conversation", "followup-preference"].includes(action))) {
430
+ throw new ManagementError("not_found", "微信通道路由不存在。");
431
+ }
432
+ assertWriteGuards(req, auth.sessionId);
433
+ let fields;
434
+ try {
435
+ fields = objectFields(await readJsonBody(req, draftId === undefined ? 2048 : 8192), draftId !== undefined ? ["version", "body"] : action === "followup-preference" ? ["version", "style"] : action === "poll" ? ["attempt_id", "verify_code"] : action === "cancel" ? ["attempt_id"] : action === "confirm-conversation" ? ["model_consent"] : []);
436
+ }
437
+ catch (error) {
438
+ if (error instanceof BodyTooLarge || error instanceof ManagementError) {
439
+ throw new ManagementError("invalid_input", "微信通道请求字段无效或请求过大。");
440
+ }
441
+ throw error;
442
+ }
443
+ if (draftId !== undefined) {
444
+ const version = fields["version"];
445
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1) {
446
+ throw new ManagementError("invalid_input", "草稿版本无效。");
447
+ }
448
+ writeJson(res, 200, channel.replyDraft(owner, draftId, { version, body: requireString(fields["body"], "body") }));
449
+ }
450
+ else if (action === "followup-preference") {
451
+ const version = fields["version"];
452
+ const style = fields["style"];
453
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0 ||
454
+ (style !== null && style !== "concise" && style !== "warm")) {
455
+ throw new ManagementError("invalid_input", "偏好的版本或语气无效。");
456
+ }
457
+ writeJson(res, 200, channel.followupPreference(owner, { version, style }));
458
+ }
459
+ else if (action === "confirm-conversation" || action === "clear-conversation" || action === "revoke-conversation") {
460
+ if (action === "confirm-conversation") {
461
+ const consent = fields["model_consent"];
462
+ if (consent !== undefined && (typeof consent !== "string" || !/^[a-f0-9]{64}$/.test(consent))) {
463
+ throw new ManagementError("invalid_input", "模型授权标识无效。");
464
+ }
465
+ channel.confirmConversation(owner, consent);
466
+ }
467
+ else if (action === "clear-conversation")
468
+ channel.clearConversation(owner);
469
+ else
470
+ channel.revokeConversation(owner);
471
+ writeJson(res, 200, { ok: true });
472
+ }
473
+ else if (action === "begin") {
474
+ writeJson(res, 200, await channel.begin(owner));
475
+ }
476
+ else if (action === "disconnect") {
477
+ await channel.disconnect(owner);
478
+ writeJson(res, 200, { status: "disconnected" });
479
+ }
480
+ else {
481
+ const id = requireString(fields["attempt_id"], "attempt_id");
482
+ if (action === "cancel") {
483
+ channel.cancel(owner, id);
484
+ writeJson(res, 200, { status: "cancelled" });
485
+ }
486
+ else {
487
+ const code = fields["verify_code"];
488
+ writeJson(res, 200, await channel.poll(owner, id, code === undefined ? undefined : requireString(code, "verify_code")));
489
+ }
490
+ }
491
+ }
492
+ catch (error) {
493
+ if (error instanceof MerchantWeixinError || error instanceof OwnerConversationError) {
494
+ throw new ManagementError(error.code, error.message);
495
+ }
496
+ throw error;
497
+ }
498
+ }
265
499
  // ── 只读路由(认证即鉴权入口;业务授权在服务层逐次复核)────────────────
266
500
  /** Workbench v1 读取面复用同一应用服务;未实现路由明确失败,不返回假数据。 */
267
501
  function governanceRouteDisabled(rest) {
@@ -285,7 +519,60 @@ export function createMerchantManagementApiHandler(options) {
285
519
  throw error;
286
520
  }
287
521
  }
522
+ function requireAlipayCollectionOwner(req) {
523
+ const auth = requireActor(req);
524
+ const ctx = assertVerifiedActor(auth.ctx, now());
525
+ if (ctx.merchantId !== options.merchantId) {
526
+ throw new ManagementError("not_found", "resource does not belong to this merchant");
527
+ }
528
+ if (!isDirectMerchantOwner(ctx, options.alipayCollectionOwnerActorId)) {
529
+ throw new ManagementError("forbidden", "支付宝收款设置仅限直接登录的商家管理员");
530
+ }
531
+ return auth;
532
+ }
533
+ function requireAlipayCollection() {
534
+ const store = options.alipayCollection;
535
+ if (store === undefined || store.merchantId !== options.merchantId) {
536
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
537
+ }
538
+ return store;
539
+ }
540
+ function requireAlipayApprovals() {
541
+ const approvals = options.alipayNegotiationApprovals;
542
+ if (approvals === undefined)
543
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
544
+ return approvals;
545
+ }
288
546
  async function routeWorkbenchV1Get(req, res, url, rest, requestId) {
547
+ if (rest === ALIPAY_COLLECTION_PATH) {
548
+ requireAlipayCollectionOwner(req);
549
+ const store = requireAlipayCollection();
550
+ try {
551
+ writeJson(res, 200, alipayCollectionSummary(store.current()), { "x-request-id": requestId });
552
+ }
553
+ catch {
554
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
555
+ }
556
+ return;
557
+ }
558
+ if (rest === ALIPAY_APPROVAL_PATH) {
559
+ requireAlipayCollectionOwner(req);
560
+ const store = requireAlipayCollection();
561
+ const approvals = requireAlipayApprovals();
562
+ try {
563
+ const items = store.current()?.enabled === true ? approvals.listApprovals("pending")
564
+ .filter((item) => item.currency === "CNY").slice(0, 100).map((item) => ({
565
+ approval_id: item.approval_id, negotiation_id: item.negotiation_id,
566
+ sku: item.sku, quantity: item.quantity, unit: item.unit ?? null,
567
+ buyer_offer_minor: item.buyer_offer_minor, currency: item.currency, expires_at: item.expires_at ?? null,
568
+ })) : [];
569
+ writeJson(res, 200, { items }, { "x-request-id": requestId });
570
+ }
571
+ catch {
572
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
573
+ }
574
+ return;
575
+ }
289
576
  if (governanceRouteDisabled(rest)) {
290
577
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
291
578
  return;
@@ -903,7 +1190,136 @@ export function createMerchantManagementApiHandler(options) {
903
1190
  }
904
1191
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
905
1192
  }
1193
+ function alipayPreviewMac(auth, expectedVersion, draft, expiry) {
1194
+ return createHmac("sha256", alipayPreviewKey).update(JSON.stringify([
1195
+ auth.sessionId, auth.ctx.actorId, auth.ctx.merchantId, auth.ctx.generation, expectedVersion, draft, expiry,
1196
+ ])).digest("base64url");
1197
+ }
1198
+ async function writeAlipayCollection(req, res, requestId, action) {
1199
+ try {
1200
+ const auth = requireAlipayCollectionOwner(req);
1201
+ assertWriteGuards(req, auth.sessionId);
1202
+ const store = requireAlipayCollection();
1203
+ const allowed = action === "disable" ? ["expected_version", "confirm_disable"]
1204
+ : ["expected_version", "enabled", "recipient", "account", "qr_png_base64"];
1205
+ if (action === "save")
1206
+ allowed.push("confirmation_ref", "confirm_owner_rights");
1207
+ const fields = alipayFields(await readJsonBody(req), allowed);
1208
+ const expectedVersion = alipayExpectedVersion(fields["expected_version"]);
1209
+ if (auth.ctx.generation !== requireAlipayCollectionOwner(req).ctx.generation) {
1210
+ throw new AlipayCollectionConflict();
1211
+ }
1212
+ const current = store.current();
1213
+ if ((current?.version ?? null) !== expectedVersion)
1214
+ throw new AlipayCollectionConflict();
1215
+ if (action === "disable") {
1216
+ if (fields["confirm_disable"] !== true)
1217
+ throw new ManagementError("invalid_input", "请明确确认停用收款方式");
1218
+ if (current?.enabled !== true)
1219
+ throw new AlipayCollectionConflict();
1220
+ const { version, ...details } = current;
1221
+ const disabled = store.replace(version, { ...details, enabled: false }, auth.ctx.actorId, now().toISOString());
1222
+ writeJson(res, 200, alipayCollectionSummary(disabled), { "x-request-id": requestId });
1223
+ return;
1224
+ }
1225
+ const draft = alipayCollectionInput(fields);
1226
+ if (action === "preview") {
1227
+ const expiry = now().getTime() + CONFIRMATION_TTL_MS;
1228
+ const token = `${expiry}.${alipayPreviewMac(auth, expectedVersion, draft, expiry)}`;
1229
+ writeJson(res, 200, { ...alipayCollectionSummary(draft), confirmation_ref: token }, { "x-request-id": requestId });
1230
+ return;
1231
+ }
1232
+ if (fields["confirm_owner_rights"] !== true) {
1233
+ throw new ManagementError("invalid_input", "请明确确认你有权使用该收款主体及账号或收款码");
1234
+ }
1235
+ const token = fields["confirmation_ref"];
1236
+ const parsed = typeof token === "string" ? /^(\d{1,15})\.([A-Za-z0-9_-]{43})$/.exec(token) : null;
1237
+ if (parsed === null || Number(parsed[1]) <= now().getTime() || !timingSafeEqual(Buffer.from(parsed[2]), Buffer.from(alipayPreviewMac(auth, expectedVersion, draft, Number(parsed[1]))))) {
1238
+ throw new ManagementError("precondition_changed", "收款信息、会话或确认有效期已变化,请重新预览");
1239
+ }
1240
+ const result = store.replace(expectedVersion, draft, auth.ctx.actorId, now().toISOString());
1241
+ writeJson(res, 200, alipayCollectionSummary(result), { "x-request-id": requestId });
1242
+ }
1243
+ catch (error) {
1244
+ if (error instanceof ManagementError || error instanceof ActorContextError)
1245
+ throw error;
1246
+ if (error instanceof AlipayCollectionConflict)
1247
+ throw new ManagementError("precondition_changed", error.message);
1248
+ if (error instanceof BodyTooLarge) {
1249
+ writeJson(res, 413, errorBody("invalid_input", "request body too large"), { "x-request-id": requestId });
1250
+ return;
1251
+ }
1252
+ // No unexpected exception (including SQLite diagnostics) is reflected or logged here.
1253
+ throw new ManagementError("unavailable", "支付宝收款设置暂不可用");
1254
+ }
1255
+ }
1256
+ async function approveAlipayTotal(req, res, requestId) {
1257
+ const auth = requireAlipayCollectionOwner(req);
1258
+ assertWriteGuards(req, auth.sessionId);
1259
+ const approvals = requireAlipayApprovals();
1260
+ const store = requireAlipayCollection();
1261
+ try {
1262
+ const fields = alipayFields(await readJsonBody(req), [
1263
+ "approval_id", "expected_version", "approved_minor", "alipay_total_minor", "confirm_final_total",
1264
+ ]);
1265
+ const approvalId = requireString(fields["approval_id"], "approval_id");
1266
+ const expectedVersion = alipayExpectedVersion(fields["expected_version"]);
1267
+ const approvedMinor = requirePositiveInteger(fields["approved_minor"], "approved_minor");
1268
+ const totalMinor = requirePositiveInteger(fields["alipay_total_minor"], "alipay_total_minor");
1269
+ if (!Number.isSafeInteger(approvedMinor) || !Number.isSafeInteger(totalMinor)) {
1270
+ throw new ManagementError("invalid_input", "单价与最终应付总额必须是安全整数分");
1271
+ }
1272
+ if (fields["confirm_final_total"] !== true) {
1273
+ throw new ManagementError("invalid_input", "请明确确认包含适用运费、税费及其他费用的 CNY 最终应付总额");
1274
+ }
1275
+ const current = store.current();
1276
+ if (auth.ctx.generation !== requireAlipayCollectionOwner(req).ctx.generation ||
1277
+ current?.enabled !== true || current.version !== expectedVersion)
1278
+ throw new AlipayCollectionConflict();
1279
+ const pending = approvals.listApprovals("pending").find((item) => item.approval_id === approvalId && item.currency === "CNY");
1280
+ if (pending === undefined)
1281
+ throw new ManagementError("not_found", "未找到待审批的人民币报价");
1282
+ const subtotal = approvedMinor * pending.quantity;
1283
+ if (subtotal <= 0 || !Number.isSafeInteger(subtotal) || totalMinor < subtotal) {
1284
+ throw new ManagementError("invalid_input", "最终应付总额不得低于已确认单价与数量计算的商品小计");
1285
+ }
1286
+ const receipt = approvals.approve({
1287
+ approval_id: approvalId, approved_minor: approvedMinor, alipay_total_minor: totalMinor, actor: auth.ctx.actorId,
1288
+ });
1289
+ writeJson(res, 200, {
1290
+ approval_id: receipt.approval_id, status: receipt.status,
1291
+ approved_minor: receipt.approved_minor, alipay_total_minor: receipt.alipay_total_minor,
1292
+ }, { "x-request-id": requestId });
1293
+ }
1294
+ catch (error) {
1295
+ if (error instanceof ManagementError || error instanceof ActorContextError)
1296
+ throw error;
1297
+ if (error instanceof AlipayCollectionConflict)
1298
+ throw new ManagementError("precondition_changed", error.message);
1299
+ if (error instanceof BodyTooLarge) {
1300
+ writeJson(res, 413, errorBody("invalid_input", "request body too large"), { "x-request-id": requestId });
1301
+ return;
1302
+ }
1303
+ if (error instanceof NegotiationOpsError) {
1304
+ if (error.code === "not_found" || error.code === "conflict") {
1305
+ throw new ManagementError("precondition_changed", "待审批报价已变更,请刷新后再试");
1306
+ }
1307
+ if (error.code === "forbidden" || error.code === "invalid_request") {
1308
+ throw new ManagementError("invalid_input", "金额不符合当前报价规则,请核对后再试");
1309
+ }
1310
+ }
1311
+ throw new ManagementError("unavailable", "支付宝报价审批暂不可用");
1312
+ }
1313
+ }
906
1314
  async function routeWorkbenchV1Post(req, res, rest, requestId, url) {
1315
+ if (rest === ALIPAY_APPROVAL_PATH) {
1316
+ await approveAlipayTotal(req, res, requestId);
1317
+ return;
1318
+ }
1319
+ if (rest === ALIPAY_COLLECTION_PATH || rest === `${ALIPAY_COLLECTION_PATH}/preview` || rest === `${ALIPAY_COLLECTION_PATH}/disable`) {
1320
+ await writeAlipayCollection(req, res, requestId, rest.endsWith("/preview") ? "preview" : rest.endsWith("/disable") ? "disable" : "save");
1321
+ return;
1322
+ }
907
1323
  if (governanceRouteDisabled(rest)) {
908
1324
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
909
1325
  return;
@@ -1259,13 +1675,14 @@ export function createMerchantManagementApiHandler(options) {
1259
1675
  writeJson(res, 201, writeGoverned(() => ops.activateRule(body)), { "x-request-id": requestId });
1260
1676
  return;
1261
1677
  }
1262
- const pauseRuleMatch = /^\/automation\/rules\/([^/]+)\/pause$/.exec(rest);
1263
- if (pauseRuleMatch !== null) {
1678
+ const ruleControlMatch = /^\/automation\/rules\/([^/]+)\/(pause|resume)$/.exec(rest);
1679
+ if (ruleControlMatch !== null) {
1264
1680
  const auth = requireActor(req);
1265
1681
  assertWriteGuards(req, auth.sessionId);
1266
1682
  authorizeOrThrow(auth.ctx, "followups:manage");
1267
1683
  const { body } = await readOpsBody();
1268
- writeJson(res, 200, writeGoverned(() => ops.pauseRule(pathSegment(pauseRuleMatch[1] ?? ""), body)), {
1684
+ const id = pathSegment(ruleControlMatch[1] ?? "");
1685
+ writeJson(res, 200, writeGoverned(() => ruleControlMatch[2] === "pause" ? ops.pauseRule(id, body) : ops.resumeRule(id, body)), {
1269
1686
  "x-request-id": requestId,
1270
1687
  });
1271
1688
  return;
@@ -2389,6 +2806,8 @@ export function createMerchantManagementApiHandler(options) {
2389
2806
  role: auth.session.role,
2390
2807
  expires_at: auth.session.expires_at,
2391
2808
  csrf_token: csrfTokenFor(auth.sessionId),
2809
+ can_manage_alipay_collection: options.alipayCollection?.merchantId === auth.ctx.merchantId &&
2810
+ auth.ctx.merchantId === options.merchantId && isDirectMerchantOwner(auth.ctx, options.alipayCollectionOwnerActorId),
2392
2811
  });
2393
2812
  return;
2394
2813
  }
@@ -3834,12 +4253,12 @@ export function createMerchantManagementApiHandler(options) {
3834
4253
  return expected.length === actual.length && timingSafeEqual(expected, actual);
3835
4254
  }
3836
4255
  // ── 输入与输出辅助 ─────────────────────────────────────────────────
3837
- async function readJsonBody(req) {
4256
+ async function readJsonBody(req, maxBytes = MAX_BODY_BYTES) {
3838
4257
  const chunks = [];
3839
4258
  let size = 0;
3840
4259
  for await (const chunk of req) {
3841
4260
  size += chunk.length;
3842
- if (size > MAX_BODY_BYTES)
4261
+ if (size > maxBytes)
3843
4262
  throw new BodyTooLarge();
3844
4263
  chunks.push(chunk);
3845
4264
  }