@octopi-agent/engine 0.102.10 → 0.121.10

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 (317) hide show
  1. package/dist/builtin-model-info.js +28 -7
  2. package/dist/config-admin/agent-presets.d.ts +32 -0
  3. package/dist/config-admin/agent-presets.js +133 -0
  4. package/dist/config-admin/discover.d.ts +33 -4
  5. package/dist/config-admin/discover.js +101 -6
  6. package/dist/config-admin/env.d.ts +11 -0
  7. package/dist/config-admin/env.js +41 -0
  8. package/dist/config-admin/error-copy.d.ts +106 -0
  9. package/dist/config-admin/error-copy.js +287 -0
  10. package/dist/config-admin/i18n.d.ts +21 -0
  11. package/dist/config-admin/i18n.js +19 -0
  12. package/dist/config-admin/index.d.ts +6 -2
  13. package/dist/config-admin/index.js +3 -1
  14. package/dist/config-admin/model-presets.d.ts +14 -0
  15. package/dist/config-admin/model-presets.js +595 -70
  16. package/dist/config-admin/onboarding-apply.d.ts +71 -0
  17. package/dist/config-admin/onboarding-apply.js +235 -0
  18. package/dist/config-admin/onboarding.d.ts +154 -0
  19. package/dist/config-admin/onboarding.js +270 -0
  20. package/dist/config-admin/redact.d.ts +42 -9
  21. package/dist/config-admin/redact.js +69 -5
  22. package/dist/config-schema/agent.d.ts +5 -1
  23. package/dist/config-schema/agent.js +20 -2
  24. package/dist/config-schema/browser.d.ts +62 -0
  25. package/dist/config-schema/browser.js +89 -0
  26. package/dist/config-schema/context.d.ts +7 -2
  27. package/dist/config-schema/context.js +6 -3
  28. package/dist/config-schema/engine.d.ts +86 -7
  29. package/dist/config-schema/engine.js +9 -2
  30. package/dist/config-schema/governance.d.ts +12 -1
  31. package/dist/config-schema/governance.js +10 -2
  32. package/dist/config-schema/models.d.ts +12 -8
  33. package/dist/config-schema/models.js +16 -1
  34. package/dist/config-schema/run.d.ts +4 -0
  35. package/dist/config-schema/run.js +10 -0
  36. package/dist/config-schema/shared.d.ts +1 -0
  37. package/dist/config-schema/shared.js +4 -2
  38. package/dist/config-schema/substrate.d.ts +5 -0
  39. package/dist/config-schema/substrate.js +8 -0
  40. package/dist/config.d.ts +116 -10
  41. package/dist/config.js +109 -13
  42. package/dist/file-mode.d.ts +67 -0
  43. package/dist/file-mode.js +182 -0
  44. package/dist/fork-child.d.ts +82 -0
  45. package/dist/fork-child.js +123 -0
  46. package/dist/harness/activation/delegated-run.d.ts +42 -0
  47. package/dist/harness/activation/delegated-run.js +71 -0
  48. package/dist/harness/activation/dispatcher.js +4 -0
  49. package/dist/harness/activation/index.d.ts +1 -0
  50. package/dist/harness/activation/run-backend.d.ts +92 -0
  51. package/dist/harness/activation/run-backend.js +16 -0
  52. package/dist/harness/activation/run-protocol.d.ts +392 -0
  53. package/dist/harness/activation/run-protocol.js +19 -0
  54. package/dist/harness/activation/runtime.d.ts +33 -0
  55. package/dist/harness/activation/runtime.js +119 -28
  56. package/dist/harness/activation/types.d.ts +19 -2
  57. package/dist/harness/agent/builder.d.ts +12 -0
  58. package/dist/harness/agent/builder.js +78 -22
  59. package/dist/harness/agent/config-bridge.d.ts +10 -1
  60. package/dist/harness/agent/config-bridge.js +15 -3
  61. package/dist/harness/agent/registered-tool-adapter.d.ts +27 -0
  62. package/dist/harness/agent/registered-tool-adapter.js +67 -0
  63. package/dist/harness/agent/wire-agent-builder.d.ts +2 -0
  64. package/dist/harness/agent/wire-agent-builder.js +9 -2
  65. package/dist/harness/capabilities/document/backends/plain.js +2 -1
  66. package/dist/harness/capabilities/document/legacy/factory.js +3 -2
  67. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.d.ts +17 -0
  68. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.js +66 -36
  69. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.d.ts +6 -2
  70. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.js +27 -7
  71. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +13 -0
  72. package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -0
  73. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +11 -0
  74. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +17 -0
  75. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +13 -3
  76. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +48 -39
  77. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -0
  78. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +4 -0
  79. package/dist/harness/collaboration/delegation/child-run.d.ts +9 -0
  80. package/dist/harness/collaboration/delegation/child-run.js +34 -2
  81. package/dist/harness/collaboration/delegation/registry-types.d.ts +2 -0
  82. package/dist/harness/collaboration/delegation/service.d.ts +9 -4
  83. package/dist/harness/collaboration/delegation/service.js +33 -12
  84. package/dist/harness/collaboration/delegation/store.d.ts +2 -0
  85. package/dist/harness/collaboration/delegation/store.js +1 -0
  86. package/dist/harness/collaboration/delegation/types.d.ts +11 -0
  87. package/dist/harness/collaboration/delegation/wiring.d.ts +2 -0
  88. package/dist/harness/collaboration/delegation/wiring.js +1 -0
  89. package/dist/harness/context/capabilities/compact/engine.d.ts +44 -5
  90. package/dist/harness/context/capabilities/compact/engine.js +127 -39
  91. package/dist/harness/context/capabilities/compact/index.d.ts +2 -1
  92. package/dist/harness/context/capabilities/compact/index.js +1 -1
  93. package/dist/harness/context/capabilities/compact/types.d.ts +59 -9
  94. package/dist/harness/context/capabilities/summary/gate.d.ts +19 -2
  95. package/dist/harness/context/capabilities/summary/gate.js +53 -6
  96. package/dist/harness/context/capabilities/summary/registry.js +20 -0
  97. package/dist/harness/context/capabilities/summary/tool-binding.js +16 -12
  98. package/dist/harness/context/capabilities/summary/tool-bindings.d.ts +13 -0
  99. package/dist/harness/context/capabilities/summary/tool-bindings.js +22 -0
  100. package/dist/harness/context/capabilities/summary/types.d.ts +16 -0
  101. package/dist/harness/context/constitution/default-agents.md +85 -0
  102. package/dist/harness/context/context-size-ledger.js +8 -1
  103. package/dist/harness/context/default-context-engine.d.ts +100 -6
  104. package/dist/harness/context/default-context-engine.js +382 -89
  105. package/dist/harness/context/index.d.ts +2 -1
  106. package/dist/harness/context/index.js +1 -0
  107. package/dist/harness/context/layer-health.d.ts +4 -0
  108. package/dist/harness/context/layer-health.js +4 -0
  109. package/dist/harness/context/layer-types.d.ts +57 -0
  110. package/dist/harness/context/layer-types.js +73 -1
  111. package/dist/harness/context/layers.d.ts +3 -0
  112. package/dist/harness/context/layers.js +13 -6
  113. package/dist/harness/context/prefix-fingerprint.d.ts +46 -0
  114. package/dist/harness/context/prefix-fingerprint.js +52 -0
  115. package/dist/harness/context/summarize.js +18 -0
  116. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  117. package/dist/harness/context/system-prompt-assembler.js +5 -2
  118. package/dist/harness/context/tool-result-aging.d.ts +104 -16
  119. package/dist/harness/context/tool-result-aging.js +211 -57
  120. package/dist/harness/context/types.d.ts +71 -4
  121. package/dist/harness/context/types.js +25 -1
  122. package/dist/harness/extension/execution-environment/effect-policy.d.ts +4 -3
  123. package/dist/harness/extension/execution-environment/effect-policy.js +2 -2
  124. package/dist/harness/extension/execution-environment/privileged-exec.js +4 -1
  125. package/dist/harness/extension/execution-environment/workspace.js +1 -1
  126. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +27 -1
  127. package/dist/harness/extension/plugin-ecosystem/channel-types.js +11 -2
  128. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +12 -0
  129. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +25 -0
  130. package/dist/harness/extension/plugin-ecosystem/commands/builtin.js +28 -1
  131. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  132. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  133. package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +168 -1
  134. package/dist/harness/extension/plugin-ecosystem/plugins/api.js +156 -15
  135. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.d.ts +95 -0
  136. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.js +170 -0
  137. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.d.ts +178 -0
  138. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.js +314 -0
  139. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +40 -5
  140. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +45 -26
  141. package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +1 -1
  142. package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +11 -1
  143. package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +42 -76
  144. package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +30 -1
  145. package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +46 -0
  146. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +9 -0
  147. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +19 -14
  148. package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +3 -1
  149. package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +1 -1
  150. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.d.ts +333 -0
  151. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.js +16 -0
  152. package/dist/harness/extension/plugin-ecosystem/tools/browser.d.ts +64 -0
  153. package/dist/harness/extension/plugin-ecosystem/tools/browser.js +692 -0
  154. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +0 -37
  155. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +108 -4
  156. package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -0
  157. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +34 -0
  158. package/dist/harness/extension/plugin-ecosystem/tools/file-search.d.ts +0 -6
  159. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +57 -4
  160. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +81 -13
  161. package/dist/harness/extension/plugin-ecosystem/tools/http.js +5 -0
  162. package/dist/harness/extension/plugin-ecosystem/tools/knowledge.js +13 -7
  163. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +126 -14
  164. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +1 -1
  165. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +44 -5
  166. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +10 -24
  167. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.d.ts +7 -0
  168. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.js +4 -0
  169. package/dist/harness/governance/credentials/db.d.ts +9 -0
  170. package/dist/harness/governance/credentials/db.js +122 -31
  171. package/dist/harness/governance/credentials/store.d.ts +68 -7
  172. package/dist/harness/governance/credentials/store.js +177 -64
  173. package/dist/harness/governance/credentials/types.d.ts +13 -2
  174. package/dist/harness/governance/index.d.ts +1 -0
  175. package/dist/harness/governance/index.js +1 -0
  176. package/dist/harness/governance/registry/db.d.ts +32 -0
  177. package/dist/harness/governance/registry/db.js +142 -0
  178. package/dist/harness/governance/registry/index.d.ts +9 -0
  179. package/dist/harness/governance/registry/index.js +9 -0
  180. package/dist/harness/governance/registry/service.d.ts +381 -0
  181. package/dist/harness/governance/registry/service.js +825 -0
  182. package/dist/harness/governance/registry/types.d.ts +77 -0
  183. package/dist/harness/governance/registry/types.js +7 -0
  184. package/dist/harness/governance/security/default-security-guard.d.ts +3 -0
  185. package/dist/harness/governance/security/default-security-guard.js +12 -1
  186. package/dist/harness/governance/security/risk-evaluator.d.ts +13 -3
  187. package/dist/harness/governance/security/risk-evaluator.js +307 -21
  188. package/dist/harness/governance/security/shell-parser-treesitter.js +12 -4
  189. package/dist/harness/governance/session-acl/tool-rights.d.ts +1 -0
  190. package/dist/harness/index.d.ts +5 -3
  191. package/dist/harness/index.js +2 -2
  192. package/dist/harness/knowledge/boot-config.d.ts +2 -0
  193. package/dist/harness/knowledge/boot-config.js +2 -0
  194. package/dist/harness/knowledge/client.d.ts +53 -7
  195. package/dist/harness/knowledge/client.js +77 -20
  196. package/dist/harness/knowledge/db.d.ts +16 -0
  197. package/dist/harness/knowledge/db.js +107 -41
  198. package/dist/harness/knowledge/engine-thread.js +5 -7
  199. package/dist/harness/knowledge/grounding.js +4 -1
  200. package/dist/harness/knowledge/http-app.d.ts +15 -0
  201. package/dist/harness/knowledge/http-app.js +82 -21
  202. package/dist/harness/knowledge/http-bridge.d.ts +15 -0
  203. package/dist/harness/knowledge/http-bridge.js +19 -0
  204. package/dist/harness/knowledge/knowledge-serve-child.js +2 -3
  205. package/dist/harness/knowledge/query-service.d.ts +12 -2
  206. package/dist/harness/knowledge/query-service.js +75 -41
  207. package/dist/harness/knowledge/query-worker-client.d.ts +5 -1
  208. package/dist/harness/knowledge/query-worker-client.js +4 -1
  209. package/dist/harness/knowledge/query-worker.js +5 -3
  210. package/dist/harness/knowledge/read-http.d.ts +2 -0
  211. package/dist/harness/knowledge/read-http.js +9 -2
  212. package/dist/harness/knowledge/retriever.d.ts +1 -1
  213. package/dist/harness/knowledge/retriever.js +1 -2
  214. package/dist/harness/knowledge/serve.d.ts +6 -1
  215. package/dist/harness/knowledge/serve.js +5 -6
  216. package/dist/harness/knowledge/source-store.d.ts +101 -5
  217. package/dist/harness/knowledge/source-store.js +297 -71
  218. package/dist/harness/knowledge/start-service-process.d.ts +27 -8
  219. package/dist/harness/knowledge/start-service-process.js +49 -90
  220. package/dist/harness/knowledge/tenant-gate.d.ts +81 -0
  221. package/dist/harness/knowledge/tenant-gate.js +167 -0
  222. package/dist/harness/knowledge/writer-service.d.ts +18 -2
  223. package/dist/harness/knowledge/writer-service.js +80 -16
  224. package/dist/harness/knowledge/writer-worker-client.d.ts +9 -2
  225. package/dist/harness/knowledge/writer-worker-client.js +20 -3
  226. package/dist/harness/knowledge/writer-worker.js +11 -4
  227. package/dist/harness/memory/backfill-trigger.d.ts +10 -3
  228. package/dist/harness/memory/backfill-trigger.js +19 -19
  229. package/dist/harness/memory/cognition-seeds.d.ts +45 -0
  230. package/dist/harness/memory/cognition-seeds.js +67 -0
  231. package/dist/harness/memory/cognition.d.ts +12 -3
  232. package/dist/harness/memory/cognition.js +55 -35
  233. package/dist/harness/memory/conceptualizer.d.ts +11 -1
  234. package/dist/harness/memory/conceptualizer.js +10 -1
  235. package/dist/harness/memory/context-slice.d.ts +42 -0
  236. package/dist/harness/memory/context-slice.js +197 -0
  237. package/dist/harness/memory/health-probe.d.ts +8 -2
  238. package/dist/harness/memory/health-probe.js +10 -13
  239. package/dist/harness/memory/index.d.ts +5 -1
  240. package/dist/harness/memory/index.js +3 -1
  241. package/dist/harness/memory/sqlite/agent-db.d.ts +1 -0
  242. package/dist/harness/memory/sqlite/agent-db.js +9 -8
  243. package/dist/harness/memory/sqlite/cognition-store.d.ts +26 -3
  244. package/dist/harness/memory/sqlite/cognition-store.js +103 -45
  245. package/dist/harness/memory/sqlite/memory-store.js +4 -0
  246. package/dist/harness/memory/sqlite/sqlite-vec.d.ts +24 -1
  247. package/dist/harness/memory/sqlite/sqlite-vec.js +37 -1
  248. package/dist/harness/memory/types.d.ts +18 -2
  249. package/dist/harness/observability/observer/hub.d.ts +10 -0
  250. package/dist/harness/observability/observer/hub.js +95 -2
  251. package/dist/harness/run/agent/agent.js +3 -2
  252. package/dist/harness/run/concurrency/tool-validator.js +4 -3
  253. package/dist/harness/run/reliability/run-agent.d.ts +22 -0
  254. package/dist/harness/run/reliability/run-agent.js +79 -10
  255. package/dist/harness/run/run-host.d.ts +302 -0
  256. package/dist/harness/run/run-host.js +978 -0
  257. package/dist/harness/run/run-scope.d.ts +11 -0
  258. package/dist/harness/run/run-scope.js +19 -1
  259. package/dist/harness/run/runner.d.ts +149 -22
  260. package/dist/harness/run/runner.js +352 -35
  261. package/dist/harness/session/in-memory-store.js +13 -1
  262. package/dist/harness/session/schedules/service.d.ts +10 -2
  263. package/dist/harness/session/schedules/service.js +13 -2
  264. package/dist/harness/session/tasks/tools.js +12 -0
  265. package/dist/harness/session/types.d.ts +10 -14
  266. package/dist/harness/shared/events/agent-event-map.d.ts +29 -0
  267. package/dist/harness/shared/types/agent-definition.d.ts +6 -0
  268. package/dist/index.d.ts +3 -2
  269. package/dist/index.js +2 -1
  270. package/dist/integration/agent-runtime/channel-message-source.d.ts +3 -1
  271. package/dist/integration/agent-runtime/channel-message-source.js +4 -3
  272. package/dist/integration/browser/camoufox.d.ts +40 -0
  273. package/dist/integration/browser/camoufox.js +80 -0
  274. package/dist/integration/browser/index.d.ts +91 -0
  275. package/dist/integration/browser/index.js +110 -0
  276. package/dist/integration/browser/install.d.ts +47 -0
  277. package/dist/integration/browser/install.js +214 -0
  278. package/dist/integration/browser/playwright.d.ts +224 -0
  279. package/dist/integration/browser/playwright.js +925 -0
  280. package/dist/integration/browser/service.d.ts +41 -0
  281. package/dist/integration/browser/service.js +181 -0
  282. package/dist/integration/browser/stealth.d.ts +42 -0
  283. package/dist/integration/browser/stealth.js +104 -0
  284. package/dist/integration/providers/anthropic-message-normalize.d.ts +20 -0
  285. package/dist/integration/providers/anthropic-message-normalize.js +48 -0
  286. package/dist/integration/providers/anthropic.js +27 -2
  287. package/dist/integration/providers/fetch-timeout.d.ts +17 -0
  288. package/dist/integration/providers/fetch-timeout.js +24 -0
  289. package/dist/integration/providers/openai.d.ts +8 -0
  290. package/dist/integration/providers/openai.js +41 -1
  291. package/dist/integration/providers/wire-dump-diff.js +2 -1
  292. package/dist/integration/providers/wire-dump.d.ts +56 -2
  293. package/dist/integration/providers/wire-dump.js +119 -6
  294. package/dist/integration/storage/archive-manager.d.ts +14 -2
  295. package/dist/integration/storage/archive-manager.js +24 -8
  296. package/dist/integration/storage/atomic-tmp.d.ts +12 -0
  297. package/dist/integration/storage/atomic-tmp.js +36 -0
  298. package/dist/integration/storage/jsonl.d.ts +9 -0
  299. package/dist/integration/storage/jsonl.js +137 -38
  300. package/dist/integration/storage/session-index.d.ts +5 -0
  301. package/dist/integration/storage/session-index.js +25 -4
  302. package/dist/integration/tools/assemble.d.ts +50 -0
  303. package/dist/integration/tools/assemble.js +137 -0
  304. package/dist/paths.d.ts +18 -0
  305. package/dist/paths.js +36 -0
  306. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +3 -1
  307. package/dist/subsystems/cognition-steward/conceptualize/handler.js +74 -5
  308. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +3 -2
  309. package/dist/subsystems/cognition-steward/consolidate/config.yaml +11 -2
  310. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +6 -3
  311. package/dist/subsystems/cognition-steward/consolidate/handler.js +266 -28
  312. package/dist/subsystems/memory-steward/backfill/handler.js +3 -2
  313. package/dist/subsystems/memory-steward/govern/config.yaml +6 -1
  314. package/dist/subsystems/wisdom-steward/attribute/config.yaml +5 -1
  315. package/dist/subsystems/wisdom-steward/formation/config.yaml +3 -0
  316. package/dist/subsystems/wisdom-steward/govern/config.yaml +6 -1
  317. package/package.json +5 -3
@@ -3,8 +3,10 @@
3
3
  *
4
4
  * 与 knowledge.db / octopi.json 分离:资源级访问凭证,规模可随集成增长。
5
5
  */
6
+ import { statSync } from 'node:fs';
6
7
  import { mkdir } from 'node:fs/promises';
7
8
  import { dirname, join } from 'node:path';
9
+ import { restrictToOwner } from '../../../file-mode.js';
8
10
  /**
9
11
  * 解析 Credential 数据面路径
10
12
  *
@@ -14,6 +16,48 @@ export function resolveCredentialPaths(octopiHome) {
14
16
  const root = join(octopiHome, 'credentials');
15
17
  return { root, dbPath: join(root, 'credentials.db') };
16
18
  }
19
+ /**
20
+ * 把 Credential 数据面目录收紧到当前用户,并回溯收紧已存在的库文件。
21
+ *
22
+ * 为什么要做:`credentials.db` 与其边车(`-wal` / `-shm` / `-journal`)都生在这个目录里,
23
+ * 目录不收紧要等于库不收紧。此前是裸 `mkdir` —— POSIX 上按 umask 落成 0755(group/other
24
+ * 可读),Windows 上完全继承 OCTOPI_HOME 所在位置的 ACL(指到共享卷即他人可读)。
25
+ *
26
+ * 顺序要点:**先收紧目录、再 open 数据库**。SQLite 在打开期间创建/重建的边车会继承目录
27
+ * 的 ACE(Windows `(OI)(CI)` / POSIX 0700),因此不存在"新边车更宽"的窗口。
28
+ *
29
+ * 目录收紧失败即抛:宁可拒绝打开数据面,也不在已知可见的位置建库。已存在的文件回溯失败
30
+ * 只告警——库里是密文与引用,为它中断服务不划算,但绝不能假装已保护。
31
+ *
32
+ * @param root - Credential 数据面目录
33
+ * @param dbPath - 库文件路径(用于回溯收紧自身与边车)
34
+ * @throws 当目录无法收紧到当前用户时(错误带 `cause`)
35
+ */
36
+ function hardenCredentialDir(root, dbPath) {
37
+ try {
38
+ restrictToOwner(root, 'dir');
39
+ }
40
+ catch (err) {
41
+ throw new Error(`[credentials] cannot restrict ${root} to the current user`, { cause: err });
42
+ }
43
+ // 目录收紧不会回溯改写已存在文件的 ACE —— 老库是在旧权限下建出来的。
44
+ // `-journal` 也要管:`wal: false` 或回滚日志模式下用它,升级前遗留的会保留旧 ACL。
45
+ for (const sibling of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`, `${dbPath}-journal`]) {
46
+ try {
47
+ // 用 statSync 而不是 existsSync:少一次 TOCTOU 形状
48
+ statSync(sibling);
49
+ }
50
+ catch {
51
+ continue; // 不存在(正常路径:干净关闭后边车会被 SQLite 删掉)
52
+ }
53
+ try {
54
+ restrictToOwner(sibling, 'file');
55
+ }
56
+ catch (err) {
57
+ console.warn(`[credentials] could not restrict existing ${sibling} (${String(err)}); it stays readable per its current ACL`);
58
+ }
59
+ }
60
+ }
17
61
  export class CredentialDatabase {
18
62
  db;
19
63
  constructor(db) {
@@ -33,7 +77,10 @@ export class CredentialDatabase {
33
77
  }
34
78
  const dbPath = options?.dbPath ?? ':memory:';
35
79
  if (dbPath !== ':memory:') {
36
- await mkdir(dirname(dbPath), { recursive: true });
80
+ const root = dirname(dbPath);
81
+ await mkdir(root, { recursive: true });
82
+ if (options?.hardenDir)
83
+ hardenCredentialDir(root, dbPath);
37
84
  }
38
85
  const db = new DatabaseSyncCtor(dbPath, {
39
86
  timeout: options?.busyTimeoutMs ?? 5000,
@@ -47,36 +94,80 @@ export class CredentialDatabase {
47
94
  return cdb;
48
95
  }
49
96
  createTables() {
50
- this.db.exec(`
51
- CREATE TABLE IF NOT EXISTS credentials (
52
- id TEXT PRIMARY KEY,
53
- name TEXT NOT NULL UNIQUE,
54
- kind TEXT NOT NULL,
55
- description TEXT,
56
- username TEXT,
57
- header_name TEXT,
58
- header_prefix TEXT,
59
- secret_mode TEXT NOT NULL,
60
- secret_env TEXT,
61
- secret_cipher BLOB,
62
- secret_nonce BLOB,
63
- secret_file TEXT,
64
- scope_level TEXT NOT NULL DEFAULT 'global',
65
- scope_key TEXT NOT NULL DEFAULT 'global',
66
- created_at INTEGER NOT NULL,
67
- updated_at INTEGER NOT NULL,
68
- last_used_at INTEGER,
69
- expires_at INTEGER
70
- );
71
-
72
- CREATE TABLE IF NOT EXISTS credential_bindings (
73
- credential_id TEXT NOT NULL,
74
- consumer_kind TEXT NOT NULL,
75
- consumer_id TEXT NOT NULL,
76
- created_at INTEGER NOT NULL,
77
- PRIMARY KEY (credential_id, consumer_kind, consumer_id)
78
- );
79
- `);
97
+ // v2(arch/multi-tenancy.md §4 域分离):唯一键 name → (name, scope_level, scope_key)。
98
+ // v1 的 UNIQUE(name) 是跨租户同名互覆的洞(同名 upsert 会写穿他租户);存量库重建迁移。
99
+ const CREATE_CREDENTIALS_V2 = `
100
+ CREATE TABLE IF NOT EXISTS credentials (
101
+ id TEXT PRIMARY KEY,
102
+ name TEXT NOT NULL,
103
+ kind TEXT NOT NULL,
104
+ description TEXT,
105
+ username TEXT,
106
+ header_name TEXT,
107
+ header_prefix TEXT,
108
+ secret_mode TEXT NOT NULL,
109
+ secret_env TEXT,
110
+ secret_cipher BLOB,
111
+ secret_nonce BLOB,
112
+ secret_file TEXT,
113
+ scope_level TEXT NOT NULL DEFAULT 'global',
114
+ scope_key TEXT NOT NULL DEFAULT 'global',
115
+ created_at INTEGER NOT NULL,
116
+ updated_at INTEGER NOT NULL,
117
+ last_used_at INTEGER,
118
+ expires_at INTEGER
119
+ );
120
+ `;
121
+ const CREATE_BINDINGS = `
122
+ CREATE TABLE IF NOT EXISTS credential_bindings (
123
+ credential_id TEXT NOT NULL,
124
+ consumer_kind TEXT NOT NULL,
125
+ consumer_id TEXT NOT NULL,
126
+ created_at INTEGER NOT NULL,
127
+ PRIMARY KEY (credential_id, consumer_kind, consumer_id)
128
+ );
129
+ `;
130
+ const tableExists = this.db
131
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'credentials'")
132
+ .get();
133
+ const domainIndexExists = this.db
134
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'credentials_domain_name'")
135
+ .get();
136
+ if (tableExists && !domainIndexExists) {
137
+ // v1 → v2 迁移:整表重建(SQLite 改不了列级 UNIQUE;拷贝后原地换表)。
138
+ // 原子性(评审 MAJ-4):单事务内完成 + 失败 ROLLBACK 并抛出(fail-loud,半迁移库
139
+ // 不得继续使用);残留 v1 残表先清(MIN-1 前置);唯一索引并入同事务(MIN-1)。
140
+ this.db.exec('DROP TABLE IF EXISTS credentials_v1_legacy;');
141
+ this.db.exec('BEGIN IMMEDIATE;');
142
+ try {
143
+ this.db.exec(`
144
+ ALTER TABLE credentials RENAME TO credentials_v1_legacy;
145
+ ${CREATE_CREDENTIALS_V2}
146
+ INSERT INTO credentials (
147
+ id, name, kind, description, username, header_name, header_prefix,
148
+ secret_mode, secret_env, secret_cipher, secret_nonce, secret_file,
149
+ scope_level, scope_key, created_at, updated_at, last_used_at, expires_at
150
+ )
151
+ SELECT
152
+ id, name, kind, description, username, header_name, header_prefix,
153
+ secret_mode, secret_env, secret_cipher, secret_nonce, secret_file,
154
+ scope_level, scope_key, created_at, updated_at, last_used_at, expires_at
155
+ FROM credentials_v1_legacy;
156
+ DROP TABLE credentials_v1_legacy;
157
+ CREATE UNIQUE INDEX credentials_domain_name ON credentials(name, scope_level, scope_key);
158
+ `);
159
+ this.db.exec('COMMIT;');
160
+ }
161
+ catch (err) {
162
+ this.db.exec('ROLLBACK;');
163
+ throw err;
164
+ }
165
+ }
166
+ else {
167
+ this.db.exec(CREATE_CREDENTIALS_V2);
168
+ this.db.exec('CREATE UNIQUE INDEX IF NOT EXISTS credentials_domain_name ON credentials(name, scope_level, scope_key);');
169
+ }
170
+ this.db.exec(CREATE_BINDINGS);
80
171
  }
81
172
  get raw() {
82
173
  return this.db;
@@ -5,7 +5,7 @@
5
5
  * 永不通过 list/get 返回明文密钥;resolve 时校验 expiresAt,过期返回 null。
6
6
  */
7
7
  import { CredentialDatabase } from './db.js';
8
- import { type CredentialConsumerRef, type CredentialMeta, type CredentialWrite, type ResolvedCredential } from './types.js';
8
+ import { type CredentialConsumerRef, type CredentialMeta, type CredentialScopeRef, type CredentialWrite, type ResolvedCredential } from './types.js';
9
9
  export declare class CredentialStore {
10
10
  private db;
11
11
  /** true 时无绑定的凭证不可 resolve(部署拧紧 / untrusted) */
@@ -16,6 +16,7 @@ export declare class CredentialStore {
16
16
  static open(options?: {
17
17
  dbPath?: string;
18
18
  requireBindings?: boolean;
19
+ hardenDir?: boolean;
19
20
  }): Promise<CredentialStore>;
20
21
  /**
21
22
  * 按 OCTOPI_HOME 打开默认 credentials.db
@@ -31,13 +32,51 @@ export declare class CredentialStore {
31
32
  * @returns 无密文元数据
32
33
  */
33
34
  set(write: CredentialWrite): CredentialMeta;
35
+ /** 按域精确定位(唯一键 (name, scope_level, scope_key)) */ private findByScope;
36
+ /**
37
+ * 域内按名定位(§4 域分离):
38
+ * - 有归属租户:本租户私有(level=tenant, key=tenantId)优先——同名遮蔽平台同名;
39
+ * 平台域兜底;他租户私有对本域不存在(不泄露存在性)。
40
+ * - 无归属:**平台域**(level != tenant,含管理域 project/agent/plugin),不含任何
41
+ * 租户私有行——租户密文只经归属租户解析(MAJ-10/评审 MIN-18:unattributed 解析
42
+ * 不得成为读他租户密文的旁路)。管理面(get/list/delete)仍可不带域查看全量元数据。
43
+ */
44
+ private findRow;
34
45
  private hasCipher;
35
46
  /**
36
- * 读元数据(无密文)
47
+ * 读元数据(无密文)。
48
+ * 同名跨域(遮蔽)时:给 scope 精确定位;不给取最早登记(宿主面确定性视图)。
49
+ *
50
+ * @param name - 凭证名
51
+ * @param scope - 域(level/key);缺省不限域
37
52
  */
38
- get(name: string): CredentialMeta | null;
53
+ get(name: string, scope?: CredentialScopeRef): CredentialMeta | null;
39
54
  list(): CredentialMeta[];
40
- delete(name: string): boolean;
55
+ /**
56
+ * 删除凭证(含绑定)。同名跨域且未给 scope = 歧义 fail-loud——域唯一后
57
+ * name 不再是唯一身份,静默删错行等于数据事故。
58
+ *
59
+ * @param name - 凭证名
60
+ * @param scope - 域(level/key);缺省不限域
61
+ * @returns 是否删除了记录
62
+ */
63
+ delete(name: string, scope?: CredentialScopeRef): boolean;
64
+ /** 按名(可选域)取全部匹配行 */
65
+ private findAll;
66
+ /** 按名(可选域)定位唯一行;歧义 fail-loud(写路径专用) */
67
+ private requireNamed;
68
+ /**
69
+ * 用时解析为明文 secret(短命;调用方禁止日志/持久化)。
70
+ * 消费约束与 {@link resolve} 相同(SEC-3c 绑定检查、过期返回 null)。
71
+ * 供插件 secret 原语(api.secrets)等非 header 形态的消费者使用。
72
+ *
73
+ * @param name - 凭证名
74
+ * @param consumer - 消费方;绑定非空时必填
75
+ * @param options - requireBindings 覆盖
76
+ * @returns 明文 secret;无档、无密钥材料或过期时 null
77
+ * @throws 绑定策略拒绝时抛错(勿静默降级)
78
+ */
79
+ reveal(name: string, consumer?: import('./types.js').CredentialConsumerRef | null, options?: import('./types.js').ResolveCredentialOptions): Promise<string | null>;
41
80
  /**
42
81
  * 用时解析为请求头(短命;调用方禁止日志)。
43
82
  * 消费侧强制 `credential_bindings`(SEC-3c):绑定非空须命中 consumer;
@@ -50,9 +89,31 @@ export declare class CredentialStore {
50
89
  * @throws 绑定策略拒绝时抛错(勿静默降级)
51
90
  */
52
91
  resolve(name: string, consumer?: import('./types.js').CredentialConsumerRef | null, options?: import('./types.js').ResolveCredentialOptions): Promise<ResolvedCredential | null>;
53
- bind(consumer: CredentialConsumerRef, name: string): void;
54
- unbind(consumer: CredentialConsumerRef, name: string): void;
55
- listBindings(name: string): Array<{
92
+ /** 明文解析单一实现点(reveal/resolve 共用):材料解析 + 绑定检查 + last_used_at。 */
93
+ private revealSecret;
94
+ /**
95
+ * 绑定消费方。同名跨域且未给 scope = 歧义 fail-loud。
96
+ *
97
+ * @param consumer - 消费方
98
+ * @param name - 凭证名
99
+ * @param scope - 域(level/key);缺省不限域
100
+ */
101
+ bind(consumer: CredentialConsumerRef, name: string, scope?: CredentialScopeRef): void;
102
+ /**
103
+ * 解绑消费方。同名跨域且未给 scope = 歧义 fail-loud。
104
+ *
105
+ * @param consumer - 消费方
106
+ * @param name - 凭证名
107
+ * @param scope - 域(level/key);缺省不限域
108
+ */
109
+ unbind(consumer: CredentialConsumerRef, name: string, scope?: CredentialScopeRef): void;
110
+ /**
111
+ * 列绑定(按命中行 id;同名跨域给 scope 定位)。
112
+ *
113
+ * @param name - 凭证名
114
+ * @param scope - 域(level/key);缺省不限域(取最早登记)
115
+ */
116
+ listBindings(name: string, scope?: CredentialScopeRef): Array<{
56
117
  kind: string;
57
118
  id: string;
58
119
  }>;
@@ -56,6 +56,8 @@ export class CredentialStore {
56
56
  return CredentialStore.open({
57
57
  dbPath: paths.dbPath,
58
58
  requireBindings: options?.requireBindings,
59
+ // 这是产品自有的数据面目录(resolveCredentialPaths 产出),可以安全收紧
60
+ hardenDir: true,
59
61
  });
60
62
  }
61
63
  get database() {
@@ -77,6 +79,23 @@ export class CredentialStore {
77
79
  if (mode === 'file' && !write.secretFile?.trim()) {
78
80
  throw new Error('secretMode=file requires secretFile');
79
81
  }
82
+ // 域(§4):唯一键 (name, scope_level, scope_key)——同名分域各存各的,不互覆。
83
+ // 先校验后归一化(评审 MAJ-3):非 global 域必须显式 key;global 不得携带异域 key
84
+ const scopeLevel = write.scope?.level ?? 'global';
85
+ let scopeKey;
86
+ if (scopeLevel === 'global') {
87
+ const key = write.scope?.key?.trim();
88
+ if (key && key !== 'global') {
89
+ throw new Error('scope.level=global must not carry a tenant/agent key');
90
+ }
91
+ scopeKey = 'global';
92
+ }
93
+ else {
94
+ scopeKey = write.scope?.key?.trim() ?? '';
95
+ if (!scopeKey) {
96
+ throw new Error(`scope.level=${scopeLevel} requires scope.key (e.g. tenantId for level=tenant)`);
97
+ }
98
+ }
80
99
  let cipher = null;
81
100
  let nonce = null;
82
101
  if (mode === 'encrypted') {
@@ -85,51 +104,72 @@ export class CredentialStore {
85
104
  cipher = enc.cipher;
86
105
  nonce = enc.nonce;
87
106
  }
88
- else if (!this.hasCipher(write.name)) {
107
+ else if (!this.hasCipher(write.name, scopeLevel, scopeKey)) {
89
108
  throw new Error('secretMode=encrypted requires secretValue');
90
109
  }
91
110
  }
92
- const existing = this.get(write.name);
111
+ const existingRow = this.findByScope(write.name, scopeLevel, scopeKey);
112
+ const existing = existingRow ? rowToMeta(existingRow) : null;
93
113
  const id = existing?.id ?? `cred_${randomUUID().slice(0, 12)}`;
94
- const scopeLevel = write.scope?.level ?? 'global';
95
- const scopeKey = scopeLevel === 'global' ? 'global' : (write.scope?.key ?? 'global');
96
114
  this.db.raw
97
- .prepare(`INSERT INTO credentials (
98
- id, name, kind, description, username, header_name, header_prefix,
99
- secret_mode, secret_env, secret_cipher, secret_nonce, secret_file,
100
- scope_level, scope_key, created_at, updated_at, last_used_at, expires_at
101
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
102
- ON CONFLICT(name) DO UPDATE SET
103
- kind=excluded.kind,
104
- description=excluded.description,
105
- username=excluded.username,
106
- header_name=excluded.header_name,
107
- header_prefix=excluded.header_prefix,
108
- secret_mode=excluded.secret_mode,
109
- secret_env=excluded.secret_env,
110
- secret_cipher=COALESCE(excluded.secret_cipher, credentials.secret_cipher),
111
- secret_nonce=COALESCE(excluded.secret_nonce, credentials.secret_nonce),
112
- secret_file=excluded.secret_file,
113
- scope_level=excluded.scope_level,
114
- scope_key=excluded.scope_key,
115
- updated_at=excluded.updated_at,
115
+ .prepare(`INSERT INTO credentials (
116
+ id, name, kind, description, username, header_name, header_prefix,
117
+ secret_mode, secret_env, secret_cipher, secret_nonce, secret_file,
118
+ scope_level, scope_key, created_at, updated_at, last_used_at, expires_at
119
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
120
+ ON CONFLICT(name, scope_level, scope_key) DO UPDATE SET
121
+ kind=excluded.kind,
122
+ description=excluded.description,
123
+ username=excluded.username,
124
+ header_name=excluded.header_name,
125
+ header_prefix=excluded.header_prefix,
126
+ secret_mode=excluded.secret_mode,
127
+ secret_env=excluded.secret_env,
128
+ secret_cipher=COALESCE(excluded.secret_cipher, credentials.secret_cipher),
129
+ secret_nonce=COALESCE(excluded.secret_nonce, credentials.secret_nonce),
130
+ secret_file=excluded.secret_file,
131
+ updated_at=excluded.updated_at,
116
132
  expires_at=excluded.expires_at`)
117
133
  .run(id, write.name, write.kind, write.description ?? null, write.username ?? null, write.headerName ?? null, write.headerPrefix ?? null, mode, write.secretEnv ?? null, cipher, nonce, write.secretFile ?? null, scopeLevel, scopeKey, existing?.createdAt ?? now, now, existing?.lastUsedAt ?? null, write.expiresAt ?? existing?.expiresAt ?? null);
118
- return this.get(write.name);
134
+ return rowToMeta(this.findByScope(write.name, scopeLevel, scopeKey));
135
+ }
136
+ /** 按域精确定位(唯一键 (name, scope_level, scope_key)) */ findByScope(name, scopeLevel, scopeKey) {
137
+ return this.db.raw
138
+ .prepare('SELECT * FROM credentials WHERE name = ? AND scope_level = ? AND scope_key = ?')
139
+ .get(name, scopeLevel, scopeKey);
119
140
  }
120
- hasCipher(name) {
121
- const row = this.db.raw
122
- .prepare(`SELECT secret_cipher FROM credentials WHERE name = ?`)
141
+ /**
142
+ * 域内按名定位(§4 域分离):
143
+ * - 有归属租户:本租户私有(level=tenant, key=tenantId)优先——同名遮蔽平台同名;
144
+ * 平台域兜底;他租户私有对本域不存在(不泄露存在性)。
145
+ * - 无归属:**平台域**(level != tenant,含管理域 project/agent/plugin),不含任何
146
+ * 租户私有行——租户密文只经归属租户解析(MAJ-10/评审 MIN-18:unattributed 解析
147
+ * 不得成为读他租户密文的旁路)。管理面(get/list/delete)仍可不带域查看全量元数据。
148
+ */
149
+ findRow(name, tenantId) {
150
+ if (tenantId) {
151
+ return (this.findByScope(name, 'tenant', tenantId) ??
152
+ this.db.raw
153
+ .prepare(`SELECT * FROM credentials WHERE name = ? AND scope_level != 'tenant' ORDER BY created_at, rowid LIMIT 1`)
154
+ .get(name));
155
+ }
156
+ return this.db.raw
157
+ .prepare(`SELECT * FROM credentials WHERE name = ? AND scope_level != 'tenant' ORDER BY created_at, rowid LIMIT 1`)
123
158
  .get(name);
159
+ }
160
+ hasCipher(name, scopeLevel, scopeKey) {
161
+ const row = this.findByScope(name, scopeLevel, scopeKey);
124
162
  return Boolean(row?.secret_cipher);
125
163
  }
126
164
  /**
127
- * 读元数据(无密文)
165
+ * 读元数据(无密文)。
166
+ * 同名跨域(遮蔽)时:给 scope 精确定位;不给取最早登记(宿主面确定性视图)。
167
+ *
168
+ * @param name - 凭证名
169
+ * @param scope - 域(level/key);缺省不限域
128
170
  */
129
- get(name) {
130
- const row = this.db.raw
131
- .prepare(`SELECT * FROM credentials WHERE name = ?`)
132
- .get(name);
171
+ get(name, scope) {
172
+ const row = scope ? this.findByScope(name, scope.level, scope.key) : this.findRow(name);
133
173
  return row ? rowToMeta(row) : null;
134
174
  }
135
175
  list() {
@@ -138,13 +178,61 @@ export class CredentialStore {
138
178
  .all();
139
179
  return rows.map(rowToMeta);
140
180
  }
141
- delete(name) {
142
- const meta = this.get(name);
143
- if (!meta)
181
+ /**
182
+ * 删除凭证(含绑定)。同名跨域且未给 scope = 歧义 fail-loud——域唯一后
183
+ * name 不再是唯一身份,静默删错行等于数据事故。
184
+ *
185
+ * @param name - 凭证名
186
+ * @param scope - 域(level/key);缺省不限域
187
+ * @returns 是否删除了记录
188
+ */
189
+ delete(name, scope) {
190
+ const metas = this.findAll(name, scope);
191
+ if (metas.length === 0)
144
192
  return false;
145
- this.db.raw.prepare(`DELETE FROM credential_bindings WHERE credential_id = ?`).run(meta.id);
146
- const res = this.db.raw.prepare(`DELETE FROM credentials WHERE id = ?`).run(meta.id);
147
- return Number(res.changes ?? 0) > 0;
193
+ if (metas.length > 1 && !scope) {
194
+ throw new Error(`credential "${name}" matches multiple domains; pass scope to delete`);
195
+ }
196
+ let deleted = false;
197
+ for (const meta of metas) {
198
+ this.db.raw.prepare(`DELETE FROM credential_bindings WHERE credential_id = ?`).run(meta.id);
199
+ const res = this.db.raw.prepare(`DELETE FROM credentials WHERE id = ?`).run(meta.id);
200
+ deleted = deleted || Number(res.changes ?? 0) > 0;
201
+ }
202
+ return deleted;
203
+ }
204
+ /** 按名(可选域)取全部匹配行 */
205
+ findAll(name, scope) {
206
+ const rows = scope
207
+ ? [this.findByScope(name, scope.level, scope.key)].filter(Boolean)
208
+ : this.db.raw
209
+ .prepare('SELECT * FROM credentials WHERE name = ? ORDER BY created_at, rowid')
210
+ .all(name);
211
+ return rows.map((r) => rowToMeta(r));
212
+ }
213
+ /** 按名(可选域)定位唯一行;歧义 fail-loud(写路径专用) */
214
+ requireNamed(name, scope) {
215
+ const metas = this.findAll(name, scope);
216
+ if (metas.length === 0)
217
+ throw new Error(`credential not found: ${name}`);
218
+ if (metas.length > 1 && !scope) {
219
+ throw new Error(`credential "${name}" matches multiple domains; pass scope`);
220
+ }
221
+ return metas[0];
222
+ }
223
+ /**
224
+ * 用时解析为明文 secret(短命;调用方禁止日志/持久化)。
225
+ * 消费约束与 {@link resolve} 相同(SEC-3c 绑定检查、过期返回 null)。
226
+ * 供插件 secret 原语(api.secrets)等非 header 形态的消费者使用。
227
+ *
228
+ * @param name - 凭证名
229
+ * @param consumer - 消费方;绑定非空时必填
230
+ * @param options - requireBindings 覆盖
231
+ * @returns 明文 secret;无档、无密钥材料或过期时 null
232
+ * @throws 绑定策略拒绝时抛错(勿静默降级)
233
+ */
234
+ async reveal(name, consumer, options) {
235
+ return this.revealSecret(name, consumer, options);
148
236
  }
149
237
  /**
150
238
  * 用时解析为请求头(短命;调用方禁止日志)。
@@ -158,18 +246,37 @@ export class CredentialStore {
158
246
  * @throws 绑定策略拒绝时抛错(勿静默降级)
159
247
  */
160
248
  async resolve(name, consumer, options) {
161
- const row = this.db.raw
162
- .prepare(`SELECT * FROM credentials WHERE name = ?`)
163
- .get(name);
249
+ const row = this.findRow(name, options?.tenantId);
164
250
  if (!row)
165
251
  return null;
166
252
  const meta = rowToMeta(row);
253
+ const secret = await this.revealSecret(name, consumer, options, meta, row);
254
+ if (!secret)
255
+ return null;
256
+ return {
257
+ name: meta.name,
258
+ headers: defaultCredentialHeaders({
259
+ kind: meta.kind,
260
+ username: meta.username,
261
+ headerName: meta.headerName,
262
+ headerPrefix: meta.headerPrefix,
263
+ secret,
264
+ }),
265
+ };
266
+ }
267
+ /** 明文解析单一实现点(reveal/resolve 共用):材料解析 + 绑定检查 + last_used_at。 */
268
+ async revealSecret(name, consumer, options, knownMeta, knownRow) {
269
+ const row = knownRow ?? this.findRow(name, options?.tenantId);
270
+ if (!row)
271
+ return null;
272
+ const meta = knownMeta ?? rowToMeta(row);
167
273
  if (meta.expiresAt != null && meta.expiresAt < Date.now()) {
168
274
  return null;
169
275
  }
170
276
  // 只紧不松:显式 true 可收紧;false/undefined 不得覆盖 store 级 requireBindings
171
277
  const require = options?.requireBindings === true || this.requireBindings === true;
172
- const bindings = this.listBindings(name);
278
+ // 绑定检查按命中行的域定位(遮蔽场景不得串查平台同名行的绑定表)
279
+ const bindings = this.listBindings(name, meta.scope);
173
280
  if (require && bindings.length === 0) {
174
281
  throw new Error(`credential "${name}" has no bindings and requireBindings is enabled`);
175
282
  }
@@ -183,7 +290,6 @@ export class CredentialStore {
183
290
  throw new Error(`credential "${name}" is not bound to consumer ${ref.kind}:${ref.id}`);
184
291
  }
185
292
  }
186
- const kind = meta.kind;
187
293
  let secret = null;
188
294
  if (meta.secretMode === 'env' && meta.secretEnv) {
189
295
  const v = process.env[meta.secretEnv];
@@ -215,36 +321,43 @@ export class CredentialStore {
215
321
  this.db.raw
216
322
  .prepare(`UPDATE credentials SET last_used_at = ? WHERE id = ?`)
217
323
  .run(Date.now(), meta.id);
218
- return {
219
- name: meta.name,
220
- headers: defaultCredentialHeaders({
221
- kind,
222
- username: meta.username,
223
- headerName: meta.headerName,
224
- headerPrefix: meta.headerPrefix,
225
- secret,
226
- }),
227
- };
324
+ return secret;
228
325
  }
229
- bind(consumer, name) {
230
- const meta = this.get(name);
231
- if (!meta)
232
- throw new Error(`credential not found: ${name}`);
326
+ /**
327
+ * 绑定消费方。同名跨域且未给 scope = 歧义 fail-loud。
328
+ *
329
+ * @param consumer - 消费方
330
+ * @param name - 凭证名
331
+ * @param scope - 域(level/key);缺省不限域
332
+ */
333
+ bind(consumer, name, scope) {
334
+ const meta = this.requireNamed(name, scope);
233
335
  this.db.raw
234
- .prepare(`INSERT OR IGNORE INTO credential_bindings (credential_id, consumer_kind, consumer_id, created_at)
336
+ .prepare(`INSERT OR IGNORE INTO credential_bindings (credential_id, consumer_kind, consumer_id, created_at)
235
337
  VALUES (?, ?, ?, ?)`)
236
338
  .run(meta.id, consumer.kind, consumer.id, Date.now());
237
339
  }
238
- unbind(consumer, name) {
239
- const meta = this.get(name);
240
- if (!meta)
241
- return;
340
+ /**
341
+ * 解绑消费方。同名跨域且未给 scope = 歧义 fail-loud。
342
+ *
343
+ * @param consumer - 消费方
344
+ * @param name - 凭证名
345
+ * @param scope - 域(level/key);缺省不限域
346
+ */
347
+ unbind(consumer, name, scope) {
348
+ const meta = this.requireNamed(name, scope);
242
349
  this.db.raw
243
350
  .prepare(`DELETE FROM credential_bindings WHERE credential_id = ? AND consumer_kind = ? AND consumer_id = ?`)
244
351
  .run(meta.id, consumer.kind, consumer.id);
245
352
  }
246
- listBindings(name) {
247
- const meta = this.get(name);
353
+ /**
354
+ * 列绑定(按命中行 id;同名跨域给 scope 定位)。
355
+ *
356
+ * @param name - 凭证名
357
+ * @param scope - 域(level/key);缺省不限域(取最早登记)
358
+ */
359
+ listBindings(name, scope) {
360
+ const meta = this.get(name, scope);
248
361
  if (!meta)
249
362
  return [];
250
363
  const rows = this.db.raw
@@ -5,12 +5,17 @@
5
5
  */
6
6
  export type CredentialKind = 'bearer' | 'basic' | 'api_key' | 'header_map' | 'oauth2_client';
7
7
  export type SecretMode = 'env' | 'encrypted' | 'file';
8
- export type CredentialScopeLevel = 'global' | 'project' | 'agent';
8
+ /**
9
+ * 凭证域(arch/multi-tenancy.md §4 credentials 行):
10
+ * - `global` / `project` / `agent` / `plugin` = 平台域(宿主管理;租户可引)
11
+ * - `tenant` = 租户私有域(key = tenantId);租户只引自己的 + 平台域
12
+ */
13
+ export type CredentialScopeLevel = 'global' | 'project' | 'agent' | 'plugin' | 'tenant';
9
14
  export interface CredentialScopeRef {
10
15
  level: CredentialScopeLevel;
11
16
  key: string;
12
17
  }
13
- export type CredentialConsumerKind = 'knowledge_source' | 'tool' | 'agent' | 'connector';
18
+ export type CredentialConsumerKind = 'knowledge_source' | 'tool' | 'agent' | 'connector' | 'plugin';
14
19
  export interface CredentialConsumerRef {
15
20
  kind: CredentialConsumerKind;
16
21
  id: string;
@@ -68,6 +73,12 @@ export interface ResolveCredentialOptions {
68
73
  consumer?: CredentialConsumerRef | null;
69
74
  /** 覆盖 store 级 requireBindings(untrusted 严档 / 配置) */
70
75
  requireBindings?: boolean;
76
+ /**
77
+ * 请求方归属租户(§4 域分离)。
78
+ * 在场:解析域 = 平台域 ∪ 本租户私有域(私有同名**遮蔽**平台同名);他租户私有对本域不存在。
79
+ * 缺场 = 宿主面(信任边界,与 query 自报收口同语义):不限域。
80
+ */
81
+ tenantId?: string;
71
82
  }
72
83
  export declare function defaultCredentialHeaders(input: {
73
84
  kind: CredentialKind;
@@ -8,3 +8,4 @@ export * from './security/index.js';
8
8
  export * from './human-in-the-loop/index.js';
9
9
  export * from './credentials/index.js';
10
10
  export * from './accounting/index.js';
11
+ export * from './registry/index.js';
@@ -8,3 +8,4 @@ export * from './security/index.js';
8
8
  export * from './human-in-the-loop/index.js';
9
9
  export * from './credentials/index.js';
10
10
  export * from './accounting/index.js';
11
+ export * from './registry/index.js';