bailinghub 0.6.1 → 0.8.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.
Files changed (229) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +7 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  9. package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -1
  10. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  11. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  12. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  13. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  14. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  15. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  16. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  17. package/docs/AGENT_TASK_CONTROL.md +94 -0
  18. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  19. package/docs/CHANGELOG.en.md +24 -1
  20. package/docs/CHANGELOG.md +24 -1
  21. package/docs/COMPATIBILITY.en.md +2 -0
  22. package/docs/CONTRACT.en.md +2 -0
  23. package/docs/CONTRACT.md +2 -0
  24. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  25. package/docs/GENERATED_ARTIFACTS.md +108 -0
  26. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  27. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  28. package/docs/INVOCATION_RECEIPTS.md +111 -0
  29. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  30. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  31. package/docs/README.en.md +9 -0
  32. package/docs/README.md +9 -0
  33. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  34. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  35. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  36. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  37. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  38. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  39. package/docs/SDK.en.md +31 -0
  40. package/docs/TOOL_RATE_LIMITS.md +50 -0
  41. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  42. package/docs/UPGRADE_v0.8.0.md +73 -0
  43. package/docs/user-guide/conversations.en.md +4 -2
  44. package/docs/user-guide/conversations.md +4 -2
  45. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  46. package/package.json +1 -1
  47. package/schemas/config/route.schema.json +16 -2
  48. package/schemas/config/tool-provider.schema.json +2 -1
  49. package/scripts/check-doc-links.mjs +2 -0
  50. package/scripts/check-image-tags.sh +1 -1
  51. package/scripts/check-release-consistency.test.mjs +2 -2
  52. package/scripts/e2e-console.mjs +32 -2
  53. package/scripts/install.sh +1 -1
  54. package/scripts/publish-images.sh +1 -1
  55. package/scripts/release-audit.mjs +2 -0
  56. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  57. package/scripts/sdk-runtime-test.mjs +5 -2
  58. package/scripts/verify-github-repo.mjs +2 -0
  59. package/sdk/php/README.md +29 -0
  60. package/sdk/php/src/AgentAuth.php +100 -4
  61. package/sdk/php/src/HubClient.php +2 -1
  62. package/sdk/php7/README.md +31 -0
  63. package/sdk/php7/src/AgentAuth.php +99 -4
  64. package/sdk/php7/src/HubClient.php +2 -1
  65. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  66. package/sql/059_agent_subject_display.sql +5 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/README.en.md +15 -0
  71. package/sql/README.md +25 -0
  72. package/src/adapters/storage/object-storage.ts +15 -3
  73. package/src/adapters/storage/oss-signature.test.ts +40 -0
  74. package/src/adapters/storage/oss-signature.ts +21 -0
  75. package/src/app/agent-artifacts.test.ts +165 -0
  76. package/src/app/agent-artifacts.ts +85 -0
  77. package/src/app/agent-client-runtime.test.ts +76 -1
  78. package/src/app/agent-client-runtime.ts +13 -0
  79. package/src/app/agent-conversation-audit.ts +20 -0
  80. package/src/app/agent-invocation-snapshot.ts +35 -0
  81. package/src/app/agent-system-info.ts +41 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +239 -14
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/builtin-tools.ts +4 -0
  89. package/src/app/oss-edition.ts +1 -0
  90. package/src/app/tool-approvals.ts +4 -0
  91. package/src/app/tool-assembly.ts +5 -0
  92. package/src/core/config/agent-setup.ts +37 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/client-agent-setup.ts +25 -0
  95. package/src/core/config/config-codec.ts +3 -1
  96. package/src/core/config/config-models.ts +11 -1
  97. package/src/core/config/config-schema.test.ts +11 -0
  98. package/src/core/config/route-config.test.ts +28 -0
  99. package/src/core/config/route-config.ts +44 -4
  100. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  101. package/src/core/contracts/agent-subject-display.ts +36 -0
  102. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  103. package/src/core/contracts/tool-rate-limits.ts +48 -0
  104. package/src/core/contracts/tools.ts +122 -43
  105. package/src/core/contracts/types.ts +18 -1
  106. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  107. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  108. package/src/core/runtime/agent-task-control.test.ts +114 -0
  109. package/src/core/runtime/agent-task-control.ts +227 -0
  110. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  111. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  112. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  113. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  114. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  115. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  116. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  117. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  118. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  119. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  120. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  121. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  122. package/src/infrastructure/config/config-client-repository.ts +21 -0
  123. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  124. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  125. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  126. package/src/infrastructure/config/config-route-repository.ts +24 -0
  127. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  128. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  129. package/src/infrastructure/config/configstore.ts +16 -4
  130. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  131. package/src/routes/admin-access.ts +37 -0
  132. package/src/routes/admin-agent-clients.ts +11 -0
  133. package/src/routes/admin-agent-setup.test.ts +130 -0
  134. package/src/routes/admin-agent-setup.ts +68 -0
  135. package/src/routes/admin-agent-tasks.ts +32 -0
  136. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  137. package/src/routes/admin-dispatch-config.ts +2 -0
  138. package/src/routes/admin-tool-providers.test.ts +22 -0
  139. package/src/routes/admin-tool-providers.ts +9 -1
  140. package/src/routes/admin.ts +3 -0
  141. package/src/routes/agent-api.test.ts +76 -0
  142. package/src/routes/agent-api.ts +49 -1
  143. package/src/routes/agent-artifacts.ts +29 -0
  144. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  145. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  146. package/src/routes/agent-auth.test.ts +1 -1
  147. package/src/routes/agent-auth.ts +206 -16
  148. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  149. package/src/routes/agent-conversation-audit.ts +8 -2
  150. package/src/routes/agent-subject-display-http.test.ts +145 -0
  151. package/src/routes/agent-system-info.test.ts +132 -0
  152. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  153. package/src/routes/private.ts +1 -0
  154. package/src/routes/run.ts +2 -1
  155. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  156. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  157. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  158. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  159. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-BRCR3O0P.js} +1 -1
  163. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  164. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  165. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  166. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  167. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
  168. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
  169. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
  170. package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
  171. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
  172. package/web/console/assets/Clients-CI3DBDHf.js +3 -0
  173. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  174. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
  175. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
  176. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
  177. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
  178. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
  179. package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
  180. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
  181. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  182. package/web/console/assets/Routes-X9vHLpKW.js +124 -0
  183. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  184. package/web/console/assets/Runs-DYNDXsqk.js +3 -0
  185. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
  186. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  187. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  188. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  189. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  190. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
  191. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
  192. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
  193. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  194. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  195. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  196. package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
  197. package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
  198. package/web/console/index.html +1 -1
  199. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  200. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +275 -0
  202. package/web-admin/src/components/ClientConversations.vue +21 -4
  203. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  204. package/web-admin/src/components/conversation-audit.ts +20 -0
  205. package/web-admin/src/layout/Shell.vue +1 -1
  206. package/web-admin/src/pages/AgentClients.vue +99 -23
  207. package/web-admin/src/pages/AgentTasks.vue +281 -0
  208. package/web-admin/src/pages/Clients.vue +4 -1
  209. package/web-admin/src/pages/Routes.vue +10 -1
  210. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  211. package/web-admin/src/pages/Tools.vue +53 -4
  212. package/web-admin/src/router.ts +2 -0
  213. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  214. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  215. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  216. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  217. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  218. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  219. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  220. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  221. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  222. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
  223. package/web/console/assets/Shell-BEqpONiy.js +0 -1
  224. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  225. package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
  226. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  227. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  228. package/web/console/assets/Tools-CIHInlHL.js +0 -2
  229. package/web/console/assets/index-BkLbd7Cc.js +0 -2
@@ -215,6 +215,37 @@ $result = $agentAuth->approve(
215
215
 
216
216
  完整关系与 HTTP 契约见中枢文档 `docs/AGENT_CLIENT_QUICKSTART.md` 和 `docs/AGENT_AUTH_API.md`。
217
217
 
218
+ **Core 0.7.0 配套的生命周期接口**支持核对和收回现有授权。请同时升级本 SDK 下载包与 Core。PHP 7.3 版与 PHP 8.1+ 版方法和语义一致:
219
+
220
+ ```php
221
+ $page = $agentAuth->listSessions(array('tenant' => (string) $tenantId, 'limit' => 20));
222
+ $context = $agentAuth->context($authorizationId);
223
+ $session = isset($context['session']) ? $context['session'] : null;
224
+ $revoked = $agentAuth->revokeAuthorization($authorizationId);
225
+ ```
226
+
227
+ 默认每页 20 条、最大 100;下一页保留全部筛选条件并传 `next_cursor`,null 表示结束。按操作人
228
+ 筛选必须同时传 `principal_id` 与 `tenant`,无租户用 `tenant => ''`。分页反映当前状态,不是跨请求
229
+ 快照。`session` 缺失/null 不可猜测;`active` 不保证业务账号仍有权限,过期按 refresh 生命周期判断。
230
+ 撤销同一授权可幂等重试,503/超时或 consumed 映射缺失的 404 不代表成功。后端先确认管理权限,
231
+ 再调用这些方法;Client Token 不进入浏览器。完整字段见
232
+ [Agent Auth v1](../../docs/AGENT_AUTH_API.md)。
233
+
234
+ ### 授权后显示业务名称
235
+
236
+ Core 0.7.0 支持批准授权时附上服务端读取的业务名称。原四参数调用保持兼容;第五参数可选,名称可用于门店、公司、项目等业务对象。
237
+
238
+ ```php
239
+ $result = $agentAuth->approve($authorizationId, $principal, $onBehalfOf, $allowedRoutes, array('name' => $accountName));
240
+ $session = $agentAuth->updateSubjectDisplay($sessionId, array('name' => $accountName));
241
+ // 仅清除显示信息,不撤销或替换授权:
242
+ $session = $agentAuth->updateSubjectDisplay($sessionId, null);
243
+ ```
244
+
245
+ 名称由业务后端从真实记录读取,不参与身份或权限判断;更新只允许当前接入方自己的有效会话。
246
+ 旧授权没有名称时显示待同步,不需要重新登录或重建连接。详见
247
+ [授权名称与三方职责](../../docs/AGENT_SUBJECT_DISPLAY.md)。
248
+
218
249
  ## 范例
219
250
 
220
251
  - `examples/build-spec.php`:完整 builder 范例(覆盖全部字段;与 8.x 版同源,跑同一个跨语言契约测试)
@@ -27,12 +27,54 @@ final class AgentAuth
27
27
  return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
28
28
  }
29
29
 
30
+ /**
31
+ * 查询当前接入方的授权会话;principal_id 必须同时指定 tenant。
32
+ * tenant='' 精确选择无租户主体,省略 tenant 则不按租户过滤。
33
+ * @param array $filters authorization_id/on_behalf_of/principal_id/tenant/state/limit/cursor
34
+ * @return array
35
+ */
36
+ public function listSessions(array $filters = array())
37
+ {
38
+ $allowed = array('authorization_id', 'on_behalf_of', 'principal_id', 'tenant', 'state', 'limit', 'cursor');
39
+ foreach ($filters as $key => $value) {
40
+ if (!in_array($key, $allowed, true)) {
41
+ throw new InvalidArgumentException('未知会话筛选字段');
42
+ }
43
+ if ($key === 'authorization_id') {
44
+ if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
45
+ throw new InvalidArgumentException('authorization_id 必须是 UUID');
46
+ }
47
+ } elseif (in_array($key, array('on_behalf_of', 'principal_id', 'tenant'), true)) {
48
+ self::assertFilterString($value, $key, $key === 'on_behalf_of' ? 191 : 128, $key === 'tenant');
49
+ } elseif ($key === 'state' && !in_array($value, array('active', 'expired', 'revoked'), true)) {
50
+ throw new InvalidArgumentException('state 必须是 active、expired 或 revoked');
51
+ } elseif ($key === 'limit' && (!is_int($value) || $value < 1 || $value > 100)) {
52
+ throw new InvalidArgumentException('limit 必须是 1 到 100 的整数');
53
+ } elseif ($key === 'cursor' && (!is_string($value) || strlen($value) > 2048 || !preg_match('/^[A-Za-z0-9_-]+$/D', $value))) {
54
+ throw new InvalidArgumentException('cursor 必须是非空、不带填充的 base64url 字符串,长度不超过 2048');
55
+ }
56
+ }
57
+ if (array_key_exists('principal_id', $filters) && !array_key_exists('tenant', $filters)) {
58
+ throw new InvalidArgumentException('principal_id 必须同时指定 tenant');
59
+ }
60
+ $query = http_build_query($filters, '', '&', PHP_QUERY_RFC3986);
61
+ return $this->hub->get('/agent-auth/v1/sessions' . ($query === '' ? '' : '?' . $query));
62
+ }
63
+
64
+ /** @return array */
65
+ public function revokeAuthorization($authorizationId)
66
+ {
67
+ self::assertId($authorizationId, 'authorizationId');
68
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/revoke', array());
69
+ }
70
+
30
71
  /**
31
72
  * @param array $principal 业务后端从当前登录态推导的主体,必须包含 id
32
73
  * @param array $allowedRoutes 本次授权允许的路由标识
74
+ * @param array|null $subjectDisplay 业务服务端提供的显示名称,不参与身份判定
33
75
  * @return array
34
76
  */
35
- public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes)
77
+ public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes, $subjectDisplay = null)
36
78
  {
37
79
  self::assertId($authorizationId, 'authorizationId');
38
80
  if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
@@ -47,11 +89,16 @@ final class AgentAuth
47
89
  if (!isset($principal['roles'])) {
48
90
  $principal['roles'] = array();
49
91
  }
50
- return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', array(
92
+ $body = array(
51
93
  'principal' => $principal,
52
94
  'on_behalf_of' => $onBehalfOf,
53
95
  'allowed_routes' => array_values($allowedRoutes),
54
- ));
96
+ );
97
+ // Existing four-argument calls keep their original HTTP shape for older Core versions.
98
+ if (func_num_args() >= 5) {
99
+ $body['subject_display'] = self::normalizeSubjectDisplay($subjectDisplay);
100
+ }
101
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', $body);
55
102
  }
56
103
 
57
104
  /** @return array */
@@ -68,10 +115,58 @@ final class AgentAuth
68
115
  return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', array());
69
116
  }
70
117
 
118
+ /**
119
+ * 同步当前接入方已有有效授权的显示名称;不修改身份、权限或有效期。
120
+ * @param array{name:string}|null $subjectDisplay 业务服务端读取的名称,null 表示清除
121
+ * @return array
122
+ */
123
+ public function updateSubjectDisplay($sessionId, $subjectDisplay)
124
+ {
125
+ self::assertId($sessionId, 'sessionId');
126
+ return $this->hub->request('PUT', '/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/subject-display', array(
127
+ 'subject_display' => self::normalizeSubjectDisplay($subjectDisplay),
128
+ ));
129
+ }
130
+
131
+ private static function normalizeSubjectDisplay($value)
132
+ {
133
+ if ($value === null) {
134
+ return null;
135
+ }
136
+ if (!is_array($value) || array_keys($value) !== array('name') || !is_string($value['name'])) {
137
+ throw new InvalidArgumentException('subjectDisplay 只能包含字符串 name');
138
+ }
139
+ $name = $value['name'];
140
+ // Reject controls before trimming; line breaks must not become a valid one-line name.
141
+ if (preg_match('//u', $name) !== 1 || preg_match('/[\x00-\x1f\x7f-\x9f\x{2028}\x{2029}]/u', $name)) {
142
+ throw new InvalidArgumentException('subjectDisplay.name 必须是无控制字符的单行文本');
143
+ }
144
+ $name = preg_replace('/^[\p{Z}\x{FEFF}]+|[\p{Z}\x{FEFF}]+$/u', '', $name);
145
+ self::assertFilterString($name, 'subjectDisplay.name', 120, false);
146
+ return array('name' => $name);
147
+ }
148
+
71
149
  private static function assertId($value, $name)
72
150
  {
73
- if (!is_string($value) || !preg_match('/^[0-9a-f-]{36}$/i', $value)) {
151
+ if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
74
152
  throw new InvalidArgumentException($name . ' 必须是 UUID');
75
153
  }
76
154
  }
155
+
156
+ private static function assertFilterString($value, $name, $max, $allowEmpty)
157
+ {
158
+ if (!is_string($value) || (!$allowEmpty && $value === '') ||
159
+ preg_match('/[\x00-\x1f\x7f]|^[\p{Z}\x{FEFF}]|[\p{Z}\x{FEFF}]$/u', $value) ||
160
+ preg_match_all('/./us', $value, $characters) === false) {
161
+ throw new InvalidArgumentException($name . ' 必须是无首尾空白或控制字符的有效字符串');
162
+ }
163
+ // 与 HTTP 服务端的 UTF-16 长度一致,不依赖 mbstring 扩展。
164
+ $length = 0;
165
+ foreach ($characters[0] as $character) {
166
+ $length += strlen($character) > 3 ? 2 : 1;
167
+ }
168
+ if ($length > $max) {
169
+ throw new InvalidArgumentException($name . ' 长度超出限制');
170
+ }
171
+ }
77
172
  }
@@ -74,7 +74,8 @@ final class HubClient
74
74
  $headers = array('Authorization: Bearer ' . $this->token);
75
75
  $content = '';
76
76
  if ($body !== null) {
77
- $content = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
77
+ // Hub API 请求顶层是对象,空参数也发送 {}(例如 deny/revoke)。
78
+ $content = $body === array() ? '{}' : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
78
79
  if ($content === false) {
79
80
  $content = '{}';
80
81
  }
@@ -0,0 +1,9 @@
1
+ -- Additive opt-in for cross-client/route audit membership. Legacy v1 rows keep
2
+ -- their original single binding; no Session, run, invocation or text is moved.
3
+ ALTER TABLE `bz_agent_conversation_audits` ADD COLUMN `membership_version` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '1=legacy common binding, 2=explicit per-member binding';
4
+
5
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `client_app_id` VARCHAR(64) DEFAULT NULL COMMENT 'Frozen original Client App, NULL for legacy v1';
6
+
7
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `route_key` VARCHAR(64) DEFAULT NULL COMMENT 'Frozen original route/workspace, NULL for legacy v1';
8
+
9
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `client_name` VARCHAR(128) DEFAULT NULL COMMENT 'Display snapshot only, never identity or authorization';
@@ -0,0 +1,5 @@
1
+ -- Optional business-supplied display metadata. Existing authorizations remain
2
+ -- unnamed; no inference from device labels, identities, route names or history.
3
+ ALTER TABLE `bz_agent_authorizations` ADD COLUMN `subject_display` JSON DEFAULT NULL COMMENT 'Business subject display only, never an authorization identity';
4
+
5
+ ALTER TABLE `bz_agent_sessions` ADD COLUMN `subject_display` JSON DEFAULT NULL COMMENT 'Current business subject display, independent of frozen audit labels';
@@ -0,0 +1,11 @@
1
+ -- Generated file delivery receipts. No credentials, binary data, or business messages.
2
+ CREATE TABLE IF NOT EXISTS bz_agent_artifacts (
3
+ session_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
4
+ upload_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
5
+ record_json JSON NOT NULL,
6
+ state VARCHAR(16) NOT NULL DEFAULT 'pending',
7
+ url TEXT NULL,
8
+ created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
9
+ updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
10
+ PRIMARY KEY (session_id, upload_id)
11
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,3 @@
1
+ -- NULL preserves existing declarations. Overrides affect Hub scheduling only, never business authorization or approval.
2
+ ALTER TABLE `bz_tool_providers`
3
+ ADD COLUMN `tool_rate_limits_json` JSON DEFAULT NULL COMMENT 'Hub tool limit default and per-operation overrides';
@@ -0,0 +1,92 @@
1
+ -- Candidate foundation only: no Agent HTTP or tool-dispatch admission is enabled by this migration.
2
+ -- Runtime wiring must use the same MySQL transaction for permit, approval consumption and Job fence.
3
+ CREATE TABLE IF NOT EXISTS `bz_agent_tasks` (
4
+ `task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
5
+ `create_key` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
6
+ `create_hash` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
7
+ `state` VARCHAR(16) NOT NULL,
8
+ `revision` BIGINT UNSIGNED NOT NULL,
9
+ `ledger_sequence` BIGINT UNSIGNED NOT NULL,
10
+ `policy_json` JSON NOT NULL,
11
+ `scope_hash` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
12
+ `write_reserved` BIGINT UNSIGNED NOT NULL DEFAULT 0,
13
+ `write_consumed` BIGINT UNSIGNED NOT NULL DEFAULT 0,
14
+ `active_permits` INT UNSIGNED NOT NULL DEFAULT 0,
15
+ `created_by` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
16
+ `created_at` DATETIME(3) NOT NULL,
17
+ `updated_at` DATETIME(3) NOT NULL,
18
+ PRIMARY KEY (`task_id`),
19
+ UNIQUE KEY `uk_agent_task_create` (`create_key`)
20
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
21
+
22
+ CREATE TABLE IF NOT EXISTS `bz_agent_task_members` (
23
+ `task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
24
+ `member_key` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
25
+ `session_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
26
+ `client_app_id` VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
27
+ `route_key` VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
28
+ `client_conversation_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
29
+ `allowed_tools_json` JSON NOT NULL,
30
+ `identity_hash` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
31
+ PRIMARY KEY (`task_id`,`member_key`),
32
+ KEY `idx_agent_task_member_session` (`session_id`,`task_id`)
33
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
34
+
35
+ -- Sticky: task cancellation/completion never removes a Session's enforcement marker.
36
+ CREATE TABLE IF NOT EXISTS `bz_agent_task_enforcements` (
37
+ `session_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
38
+ `first_task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
39
+ `created_by` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
40
+ `created_at` DATETIME(3) NOT NULL,
41
+ PRIMARY KEY (`session_id`)
42
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
43
+
44
+ CREATE TABLE IF NOT EXISTS `bz_agent_task_invocations` (
45
+ `session_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
46
+ `invocation_id` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
47
+ `task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
48
+ `run_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
49
+ `job_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
50
+ `tool` VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
51
+ `args_hash` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
52
+ `execution_fingerprint` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
53
+ `is_readonly` TINYINT NOT NULL,
54
+ `approval_required` TINYINT NOT NULL,
55
+ `approval_id` BIGINT UNSIGNED DEFAULT NULL,
56
+ `budget_state` VARCHAR(16) DEFAULT NULL,
57
+ `permit_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
58
+ `permit_state` VARCHAR(16) NOT NULL DEFAULT 'none',
59
+ `outcome` VARCHAR(32) DEFAULT NULL,
60
+ `is_terminal` TINYINT NOT NULL DEFAULT 0,
61
+ `attempt` INT UNSIGNED NOT NULL DEFAULT 0,
62
+ `created_at` DATETIME(3) NOT NULL,
63
+ `updated_at` DATETIME(3) NOT NULL,
64
+ PRIMARY KEY (`session_id`,`invocation_id`),
65
+ UNIQUE KEY `uk_agent_task_job` (`job_id`),
66
+ KEY `idx_agent_task_invocations` (`task_id`,`created_at`)
67
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
68
+
69
+ -- A real Agent run belongs to one task. A new invocation cannot switch its budget.
70
+ CREATE TABLE IF NOT EXISTS `bz_agent_task_runs` (
71
+ `run_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
72
+ `task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
73
+ `session_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
74
+ `created_at` DATETIME(3) NOT NULL,
75
+ PRIMARY KEY (`run_id`),
76
+ KEY `idx_agent_task_runs` (`task_id`,`created_at`)
77
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
78
+
79
+ CREATE TABLE IF NOT EXISTS `bz_agent_task_events` (
80
+ `task_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
81
+ `sequence` BIGINT UNSIGNED NOT NULL,
82
+ `event` VARCHAR(40) NOT NULL,
83
+ `request_key` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
84
+ `request_hash` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
85
+ `actor` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
86
+ `invocation_id` CHAR(64) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
87
+ `permit_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
88
+ `detail_json` JSON NOT NULL,
89
+ `created_at` DATETIME(3) NOT NULL,
90
+ PRIMARY KEY (`task_id`,`sequence`),
91
+ UNIQUE KEY `uk_agent_task_control_request` (`task_id`,`request_key`)
92
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
package/sql/README.en.md CHANGED
@@ -18,6 +18,21 @@ A small immutable catalog records the filename, original byte checksum, and leng
18
18
 
19
19
  Duplicate-column or duplicate-index errors are tolerated only when the live object exactly matches the official `ADD COLUMN` or `ADD INDEX` statement. Other SQL errors remain fatal.
20
20
 
21
+ ## Unreleased candidate: 059 authorization subject display
22
+
23
+ `059_agent_subject_display.sql` adds one nullable JSON column named `subject_display`,
24
+ with a NULL default, to each of `bz_agent_authorizations` and `bz_agent_sessions`.
25
+ Existing rows stay NULL (name pending sync); device names, local aliases and identity
26
+ values are not used to invent names. No principal, scope, credential, Session or
27
+ archive record is rewritten. Business backends can later name the original session
28
+ through the [authorization name API](../docs/AGENT_SUBJECT_DISPLAY.en.md).
29
+
30
+ Explicitly apply 059 through the existing migration entry point before starting this
31
+ candidate runtime. Custom Hosts must package the official SQL and implement the optional
32
+ display-update repository method. An older Host explicitly reports unavailable for
33
+ new naming operations while accepting the original approval request without a name.
34
+ These candidate files do not indicate that a deployment or migration has occurred.
35
+
21
36
  ## Migration Rules
22
37
 
23
38
  Schema files are part of the deployment safety boundary.
package/sql/README.md CHANGED
@@ -16,6 +16,31 @@ npm run db:init # 按文件名顺序应用所有未应用的结构文件
16
16
  - **错误码容错兜底**:`IF NOT EXISTS` 自身幂等;加列/索引遇到 1060/1061 时,只有实际列/索引结构与官方语句一致才按已完成处理,跑完即记账,此后走账本快路径。
17
17
  - **失败关闭**:账本出现既不属于活动序列、也不属于固化退役证据的文件,或者任一已记账摘要不匹配时,会在补录摘要或执行新迁移前拒绝继续。
18
18
 
19
+ ## 未发布候选:058 跨系统归档成员绑定
20
+
21
+ `058_agent_conversation_member_bindings.sql` 是尚未发布的增量候选,只给已有归档增加
22
+ `membership_version`(默认 1),给成员增加 `client_app_id`、`route_key`、`client_name`(默认 NULL)。
23
+ 057 保持原样;已应用 057 的实例不重复建表,也不回填或移动 Session、run、invocation、正文和旧成员身份。
24
+ 旧记录按 v1 的共同绑定解释,NULL 不能冒充逐成员系统或路由证据。
25
+
26
+ Host 需把官方 SQL 一起打包,并通过现有迁移入口显式执行;运行时启动不自动迁移。
27
+ 沿用上述迁移账本、摘要及结构核对,不引入另一套迁移引擎。仅有 057、缺少任一 058 新列,
28
+ 或旧 Host 未实现可选跨绑定仓储方法时,能力探测不能返回跨绑定支持;旧 v1 功能保持兼容。
29
+ 跨系统只在同一 Hub 和同一 Host 数据域内组合独立授权,不能跨租户拼库。
30
+ 完整候选协议见 [Agent 对话审计](../docs/AGENT_CONVERSATION_AUDIT.md#未发布候选跨系统成员绑定)。
31
+
32
+ ## 未发布候选:059 授权主体展示信息
33
+
34
+ `059_agent_subject_display.sql` 给 `bz_agent_authorizations` 和 `bz_agent_sessions`
35
+ 各增加一个可空、默认 NULL 的 JSON 列 `subject_display`,独立保存授权主体的展示名称。
36
+ 旧记录保留 NULL,表示名称待同步;不从设备名、用户备注或身份标识推断名称。
37
+ 不改写 principal、授权范围、凭据、Session 或归档记录。业务后端以后可通过
38
+ [授权名称接口](../docs/AGENT_SUBJECT_DISPLAY.md) 为原会话补名。
39
+
40
+ 升级到此候选运行时前,先通过现有迁移入口显式应用 059;自定义 Host 也需打包官方 SQL,
41
+ 并实现可选的名称更新仓储方法。旧 Host 不支持新命名操作时明确返回 unavailable,
42
+ 仍可使用原不带名称的授权请求。此目录提供候选结构,不代表已经部署或执行迁移。
43
+
19
44
  ## 写结构文件的铁律
20
45
 
21
46
  结构文件是部署方数据安全的边界。守住这三条,发布后的结构同步才可预期。
@@ -1,5 +1,6 @@
1
+ import { ossPutHeaders } from './oss-signature';
1
2
  // 媒体存储适配(聊天图片/语音/附件落盘或落桶取永久 URL)。
2
- // 默认 local:开箱即用,写到本机 data/uploads 并由 /uploads/* 公开读取;生产可切 COS,oss/s3 预留。
3
+ // 默认 local:开箱即用,写到本机 data/uploads 并由 /uploads/* 公开读取;生产可切 COS,OSS 也支持;S3 预留。
3
4
  // 设计:业务桶则 URL 即业务 CDN 地址(加商品零转存),中枢桶/本地存储则中枢掌控留存;URL 永久不清理,供完整追溯 + 多模态读图/听音。
4
5
  // COS 请求签名(q-sign-algorithm=sha1)按官方算法手写(零依赖,避免上线 npm install)。
5
6
  // ⚠ 签名为纯计算、本机无真桶可验——首次接真桶上传若 403,对照 COS 返回的 XML 报文核对 host/header-list 即可。
@@ -110,7 +111,7 @@ export function localObjectFile(root: string, key: string): { file: string; cont
110
111
  return { file, contentType: MIME_BY_EXT[extname(file).toLowerCase()] ?? 'application/octet-stream' };
111
112
  }
112
113
 
113
- /** 上传字节到存储,返回永久公开 URL。local 开箱即用;cos 已实现;oss/s3 预留。 */
114
+ /** 上传字节到存储,返回永久公开 URL。local 开箱即用;cos 已实现;OSS 也支持;S3 预留。 */
114
115
  export async function putObject(b: StorageBucket, key: string, body: Buffer, contentType: string, opts: { root?: string } = {}): Promise<string> {
115
116
  if (b.kind === 'local') {
116
117
  if (!opts.root) throw new Error('本地媒体存储需要 root');
@@ -121,12 +122,23 @@ export async function putObject(b: StorageBucket, key: string, body: Buffer, con
121
122
  const base = (b.public_base_url || LOCAL_UPLOAD_URL_PREFIX).replace(/\/+$/, '');
122
123
  return `${base}/${key}`;
123
124
  }
125
+ if (b.kind === 'oss') {
126
+ const endpoint = b.endpoint || `https://${b.bucket}.oss-${b.region.replace(/^oss-/, '')}.aliyuncs.com`;
127
+ const target = new URL(endpoint.includes('://') ? endpoint : `https://${endpoint}`);
128
+ if (target.protocol !== 'https:' || target.username || target.password || target.search || target.hash || target.pathname !== '/') throw new Error('Invalid OSS endpoint');
129
+ const path = key.split('/').map(rfc3986).join('/');
130
+ const response = await fetch(`${target.origin}/${path}`, { method: 'PUT', redirect: 'error',
131
+ headers: ossPutHeaders(b, key, body, contentType), body, signal: AbortSignal.timeout(20000) });
132
+ if (!response.ok) { await response.body?.cancel(); throw new Error(`OSS PUT ${response.status}`); }
133
+ await response.body?.cancel();
134
+ return `${(b.public_base_url || target.origin).replace(/\/+$/, '')}/${path}`;
135
+ }
124
136
  if (b.kind !== 'cos') throw new Error(`对象存储类型 ${b.kind} 暂未实现(当前支持 cos)`);
125
137
  const host = cosHost(b);
126
138
  const signed = { host, 'content-type': contentType, 'x-cos-acl': 'public-read' };
127
139
  const auth = cosAuth(b, 'put', key, signed, Math.floor(Date.now() / 1000));
128
140
  const r = await fetch(`https://${host}/${key}`, {
129
- method: 'PUT',
141
+ method: 'PUT', redirect: 'error',
130
142
  headers: { authorization: auth, 'content-type': contentType, 'x-cos-acl': 'public-read' },
131
143
  body,
132
144
  signal: AbortSignal.timeout(20000),
@@ -0,0 +1,40 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { ossPutHeaders } from './oss-signature';
4
+ import { putObject } from './object-storage';
5
+ import type { StorageBucket } from '../../core/contracts/types';
6
+
7
+ const bucket: StorageBucket = { name: 'media', kind: 'oss', bucket: 'example-bucket', access_key: 'TESTACCESSKEY', secret_key: 'synthetic-test-secret',
8
+ region: 'cn-shanghai', enabled: true, public_base_url: 'https://cdn.example.com', path_prefix: 'assets' };
9
+ // Fixed vectors independently verified against official ali-oss 6.23.0 signUtils.authorizationV4.
10
+ test('OSS V4 matches official SDK vectors, including encoded Unicode object paths', () => {
11
+ for (const [key, signature] of [
12
+ ['assets/front.png', '63193ef534c03b0752075a575f9731b3f0dbe559f1def4cea00ba44aea71512a'],
13
+ ['assets/中文 image(1).png', 'f15b9ebaefb3b1521403d87f7c2c85a7b122cda4ffc3568ab3c716cb406a445d'],
14
+ ]) {
15
+ const headers = ossPutHeaders(bucket, key!, Buffer.from('synthetic image'), 'image/png', new Date('2026-09-14T01:02:03Z'));
16
+ assert.equal(headers.authorization, `OSS4-HMAC-SHA256 Credential=TESTACCESSKEY/20260914/cn-shanghai/oss/aliyun_v4_request,Signature=${signature}`);
17
+ assert.equal(headers['x-oss-object-acl'], 'public-read');
18
+ }
19
+ });
20
+ test('OSS sends bytes with checksum and no redirect, returns configured CDN URL', async () => {
21
+ const original = globalThis.fetch; let calls = 0;
22
+ try {
23
+ globalThis.fetch = (async (url, init) => {
24
+ calls++; assert.equal(url, 'https://example-bucket.oss-cn-shanghai.aliyuncs.com/assets/front.png');
25
+ assert.equal(init!.method, 'PUT'); assert.equal(init!.redirect, 'error'); assert.deepEqual(init!.body, Buffer.from('bytes'));
26
+ assert.ok((init!.headers as Record<string, string>)['content-md5']);
27
+ return new Response(null, { status: 200 });
28
+ }) as typeof fetch;
29
+ assert.equal(await putObject(bucket, 'assets/front.png', Buffer.from('bytes'), 'image/png'), 'https://cdn.example.com/assets/front.png');
30
+ assert.equal(calls, 1);
31
+ } finally { globalThis.fetch = original; }
32
+ });
33
+ test('OSS failed upload keeps backend details out of the public error', async () => {
34
+ const original = globalThis.fetch;
35
+ try {
36
+ globalThis.fetch = (async () => new Response('<Error>private diagnostic</Error>', { status: 403 })) as typeof fetch;
37
+ await assert.rejects(putObject(bucket, 'assets/front.png', Buffer.from('bytes'), 'image/png'), { message: 'OSS PUT 403' });
38
+ await assert.rejects(putObject({ ...bucket, endpoint: 'http://example.com' }, 'assets/front.png', Buffer.from('bytes'), 'image/png'), { message: 'Invalid OSS endpoint' });
39
+ } finally { globalThis.fetch = original; }
40
+ });
@@ -0,0 +1,21 @@
1
+ import { createHash, createHmac } from 'node:crypto';
2
+ import type { StorageBucket } from '../../core/contracts/types';
3
+
4
+ const encode = (value: string) => encodeURIComponent(value).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
5
+ /** OSS V4 PUT signing; no query parameters. Public asset URLs do not contain this signature. */
6
+ export function ossPutHeaders(bucket: StorageBucket, key: string, body: Buffer, contentType: string, now = new Date()): Record<string, string> {
7
+ const timestamp = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
8
+ const date = timestamp.slice(0, 8);
9
+ const region = bucket.region.replace(/^oss-/, '');
10
+ const scope = `${date}/${region}/oss/aliyun_v4_request`;
11
+ const headers: Record<string, string> = { 'content-type': contentType,
12
+ 'content-md5': createHash('md5').update(body).digest('base64'),
13
+ 'x-oss-content-sha256': 'UNSIGNED-PAYLOAD', 'x-oss-date': timestamp, 'x-oss-object-acl': 'public-read' };
14
+ const canonical = `PUT\n/${encode(bucket.bucket)}/${key.split('/').map(encode).join('/')}\n\n` +
15
+ Object.keys(headers).sort().map(k => `${k}:${headers[k]}\n`).join('') + '\n\nUNSIGNED-PAYLOAD';
16
+ const stringToSign = `OSS4-HMAC-SHA256\n${timestamp}\n${scope}\n${createHash('sha256').update(canonical).digest('hex')}`;
17
+ let signingKey: Buffer = Buffer.from(`aliyun_v4${bucket.secret_key}`);
18
+ for (const part of [date, region, 'oss', 'aliyun_v4_request']) signingKey = createHmac('sha256', signingKey).update(part).digest();
19
+ headers.authorization = `OSS4-HMAC-SHA256 Credential=${bucket.access_key}/${scope},Signature=${createHmac('sha256', signingKey).update(stringToSign).digest('hex')}`;
20
+ return headers;
21
+ }