@agent-native/core 0.131.4 → 0.131.6

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 (330) hide show
  1. package/corpus/README.md +3 -3
  2. package/corpus/core/CHANGELOG.md +69 -0
  3. package/corpus/core/docs/content/agent-native-toolkit.mdx +13 -6
  4. package/corpus/core/docs/content/cloneable-saas.mdx +5 -5
  5. package/corpus/core/docs/content/creating-templates.mdx +9 -0
  6. package/corpus/core/docs/content/deployment.mdx +14 -10
  7. package/corpus/core/docs/content/docs-components.mdx +491 -0
  8. package/corpus/core/docs/content/doctor.mdx +8 -1
  9. package/corpus/core/docs/content/drop-in-agent.mdx +1 -1
  10. package/corpus/core/docs/content/extensions.mdx +18 -18
  11. package/corpus/core/docs/content/faq.mdx +4 -4
  12. package/corpus/core/docs/content/key-concepts.mdx +30 -21
  13. package/corpus/core/docs/content/template-brain-developers.mdx +4 -1
  14. package/corpus/core/docs/content/template-mail-developers.mdx +4 -1
  15. package/corpus/core/docs/content/what-is-agent-native.mdx +6 -6
  16. package/corpus/core/package.json +1 -1
  17. package/corpus/core/src/a2a/client.ts +449 -66
  18. package/corpus/core/src/a2a/correlation.ts +31 -0
  19. package/corpus/core/src/a2a/types.ts +4 -0
  20. package/corpus/core/src/action.ts +3 -0
  21. package/corpus/core/src/agent/engine/registry.ts +45 -5
  22. package/corpus/core/src/agent/production-agent.ts +151 -18
  23. package/corpus/core/src/agent/run-loop-with-resume.ts +190 -3
  24. package/corpus/core/src/agent/run-manager.ts +117 -41
  25. package/corpus/core/src/agent/thread-debug-history.ts +86 -0
  26. package/corpus/core/src/agent/types.ts +3 -1
  27. package/corpus/core/src/cli/create.ts +11 -1
  28. package/corpus/core/src/cli/templates-meta.ts +2 -2
  29. package/corpus/core/src/client/agent-chat-adapter.ts +91 -13
  30. package/corpus/core/src/client/resources/McpIntegrationDialog.tsx +11 -9
  31. package/corpus/core/src/client/sse-event-processor.ts +17 -3
  32. package/corpus/core/src/db/client.ts +57 -17
  33. package/corpus/core/src/integrations/adapters/slack.ts +8 -3
  34. package/corpus/core/src/localization/default-messages.ts +44 -0
  35. package/corpus/core/src/observability/traces.ts +78 -5
  36. package/corpus/core/src/scripts/call-agent.ts +290 -9
  37. package/corpus/core/src/scripts/describe-workspace-apps.ts +2 -2
  38. package/corpus/core/src/secrets/crypto.ts +126 -34
  39. package/corpus/core/src/secrets/storage.ts +61 -25
  40. package/corpus/core/src/server/agent-capabilities.ts +1 -1
  41. package/corpus/core/src/server/agent-chat/action-filters-a2a.ts +111 -7
  42. package/corpus/core/src/server/agent-chat/context-tools.ts +2 -0
  43. package/corpus/core/src/server/agent-chat/plugin-options.ts +34 -1
  44. package/corpus/core/src/server/agent-chat/prompt-resources.ts +1 -1
  45. package/corpus/core/src/server/agent-chat-plugin.ts +91 -59
  46. package/corpus/core/src/templates/default/.agents/skills/secrets/SKILL.md +14 -7
  47. package/corpus/core/src/templates/headless/.agents/skills/secrets/SKILL.md +14 -7
  48. package/corpus/core/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +18 -7
  49. package/corpus/core/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +15 -14
  50. package/corpus/core/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -7
  51. package/corpus/core/src/vite/client.ts +1 -0
  52. package/corpus/templates/analytics/.agents/skills/dashboard-ops/SKILL.md +5 -4
  53. package/corpus/templates/analytics/.agents/skills/gong/SKILL.md +6 -4
  54. package/corpus/templates/analytics/AGENTS.md +6 -4
  55. package/corpus/templates/analytics/actions/query-agent-native-analytics.ts +4 -3
  56. package/corpus/templates/analytics/changelog/2026-07-30-scheduled-dashboard-emails-complete-every-panel-without-pool.md +6 -0
  57. package/corpus/templates/analytics/scripts/emit-netlify-dashboard-report-cron.ts +28 -1
  58. package/corpus/templates/analytics/server/jobs/dashboard-report.ts +18 -11
  59. package/corpus/templates/analytics/server/lib/analytics-connector-catalog.ts +4 -4
  60. package/corpus/templates/analytics/server/lib/canonical-first-party-dashboard-repair.ts +9 -5
  61. package/corpus/templates/analytics/server/lib/dashboard-panel-query.ts +6 -2
  62. package/corpus/templates/analytics/server/lib/dashboard-panel-source-resolver.ts +11 -4
  63. package/corpus/templates/analytics/server/lib/dashboard-report-render.ts +49 -31
  64. package/corpus/templates/analytics/server/lib/first-party-analytics.ts +16 -8
  65. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +9 -3
  66. package/corpus/templates/analytics/server/lib/production-serverless-runtime.ts +11 -0
  67. package/corpus/templates/analytics/server/plugins/agent-chat.ts +3 -2
  68. package/corpus/templates/analytics/server/plugins/analytics-alert-jobs.ts +2 -1
  69. package/corpus/templates/analytics/server/plugins/dashboard-report-jobs.ts +2 -1
  70. package/corpus/templates/analytics/server/plugins/uptime-monitor-jobs.ts +1 -12
  71. package/corpus/templates/brain/.agents/skills/brain/RUNBOOK.md +54 -6
  72. package/corpus/templates/brain/.agents/skills/brain/SKILL.md +20 -9
  73. package/corpus/templates/brain/.agents/skills/ingestion-and-connectors/SKILL.md +33 -1
  74. package/corpus/templates/brain/AGENTS.md +3 -1
  75. package/corpus/templates/brain/README.md +4 -1
  76. package/corpus/templates/brain/actions/_schemas.ts +30 -8
  77. package/corpus/templates/brain/actions/ask-brain.ts +124 -14
  78. package/corpus/templates/brain/actions/create-source.ts +18 -2
  79. package/corpus/templates/brain/actions/enqueue-captures-distillation.ts +8 -123
  80. package/corpus/templates/brain/actions/enqueue-distillation.ts +6 -127
  81. package/corpus/templates/brain/actions/import-capture.ts +17 -5
  82. package/corpus/templates/brain/actions/import-transcript.ts +17 -5
  83. package/corpus/templates/brain/actions/update-source.ts +25 -5
  84. package/corpus/templates/brain/app/components/layout/Sidebar.tsx +1 -1
  85. package/corpus/templates/brain/changelog/2026-07-30-blessed-resources-can-feed-cited-company-answers.md +6 -0
  86. package/corpus/templates/brain/changelog/2026-07-30-the-left-sidebar-no-longer-shows-a-blank-organization-placeh.md +6 -0
  87. package/corpus/templates/brain/server/lib/brain.ts +49 -19
  88. package/corpus/templates/brain/server/lib/distillation-queue.ts +147 -0
  89. package/corpus/templates/brain/server/lib/source-policy.ts +264 -0
  90. package/corpus/templates/brain/server/plugins/agent-chat.ts +3 -2
  91. package/corpus/templates/brain/server/routes/api/_agent-native/brain/ingest.post.ts +116 -19
  92. package/corpus/templates/clips/app/components/meetings/google-oauth-identity-notice.tsx +51 -0
  93. package/corpus/templates/clips/app/i18n/en-US.ts +4 -0
  94. package/corpus/templates/clips/app/routes/_app.meetings._index.tsx +3 -1
  95. package/corpus/templates/clips/changelog/2026-07-30-google-calendar-warning.md +6 -0
  96. package/corpus/templates/content/.agents/skills/content-product-development/SKILL.md +47 -0
  97. package/corpus/templates/content/app/components/editor/VisualEditor.tsx +72 -8
  98. package/corpus/templates/content/changelog/2026-07-30-the-slash-command-hint-now-stays-on-only-the-active-empty-li.md +6 -0
  99. package/corpus/templates/design/.generated/bridge/editor-chrome.generated.ts +506 -11
  100. package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +148 -17
  101. package/corpus/templates/design/app/components/design/canvas-interactions/design-canvas-interactions.ts +357 -0
  102. package/corpus/templates/design/app/components/design/inspector/ScrubInput.tsx +7 -466
  103. package/corpus/templates/design/app/components/design/inspector/scrub-input-utils.ts +15 -311
  104. package/corpus/templates/design/app/components/visual-editor/CanvasCommentPins.tsx +19 -997
  105. package/corpus/templates/design/app/components/visual-editor/DrawOverlay.tsx +8 -1216
  106. package/corpus/templates/design/app/hooks/useDesignHotkeys.ts +31 -38
  107. package/corpus/templates/design/package.json +0 -1
  108. package/corpus/templates/dispatch/AGENTS.md +8 -0
  109. package/corpus/templates/dispatch/DEVELOPING.md +29 -0
  110. package/corpus/templates/dispatch/actions/view-screen.ts +34 -2
  111. package/corpus/templates/dispatch/app/i18n-data.ts +457 -0
  112. package/corpus/templates/dispatch/changelog/2026-07-30-delegated-dispatch-work-continues-reliably-in-the-background.md +6 -0
  113. package/corpus/templates/dispatch/changelog/2026-07-30-find-failed-runs-across-apps.md +6 -0
  114. package/corpus/templates/dispatch/netlify.toml +3 -0
  115. package/corpus/templates/slides/.agents/skills/analytics-data-for-decks/SKILL.md +8 -12
  116. package/corpus/templates/slides/AGENTS.md +4 -4
  117. package/corpus/templates/slides/actions/duplicate-deck.ts +19 -4
  118. package/corpus/templates/slides/app/components/deck/DeckCard.tsx +2 -10
  119. package/corpus/templates/slides/app/components/deck/MermaidRenderer.tsx +12 -1
  120. package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +30 -13
  121. package/corpus/templates/slides/app/components/editor/DeckEditorSkeleton.tsx +35 -0
  122. package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +63 -56
  123. package/corpus/templates/slides/app/components/editor/EditorToolbar.tsx +21 -76
  124. package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +1110 -292
  125. package/corpus/templates/slides/app/components/editor/SlideOverflowWarning.tsx +53 -0
  126. package/corpus/templates/slides/app/components/editor/SlideStyleInspector.tsx +235 -18
  127. package/corpus/templates/slides/app/components/editor/SpeakerNotesPanel.tsx +4 -1
  128. package/corpus/templates/slides/app/components/editor/canvas-interactions/index.ts +11 -0
  129. package/corpus/templates/slides/app/components/editor/canvas-interactions/slides-canvas-adapter.ts +129 -0
  130. package/corpus/templates/slides/app/components/editor/selection-overlay-measurement.ts +70 -0
  131. package/corpus/templates/slides/app/components/editor/slide-object-interactions.ts +519 -65
  132. package/corpus/templates/slides/app/components/visual-editor/CanvasCommentPins.tsx +36 -426
  133. package/corpus/templates/slides/app/components/visual-editor/DrawOverlay.tsx +19 -458
  134. package/corpus/templates/slides/app/context/DeckContext.tsx +179 -72
  135. package/corpus/templates/slides/app/global.css +105 -0
  136. package/corpus/templates/slides/app/i18n/en-US.ts +8 -0
  137. package/corpus/templates/slides/app/lib/deck-editor-loading.ts +26 -0
  138. package/corpus/templates/slides/app/lib/mermaid-blocks.ts +27 -0
  139. package/corpus/templates/slides/app/pages/DeckEditor.tsx +71 -38
  140. package/corpus/templates/slides/app/pages/Index.tsx +98 -41
  141. package/corpus/templates/slides/changelog/2026-07-30-deck-loading-no-longer-flashes-an-unavailable-message.md +6 -0
  142. package/corpus/templates/slides/changelog/2026-07-30-duplicating-a-deck-from-the-deck-list-now-opens-the-copy-imm.md +6 -0
  143. package/corpus/templates/slides/changelog/2026-07-30-layout-overflow-warning-is-readable-and-dismissible.md +6 -0
  144. package/corpus/templates/slides/changelog/2026-07-30-shared-canvas-annotations.md +6 -0
  145. package/corpus/templates/slides/changelog/2026-07-30-slide-objects-can-be-moved-as-a-group-copied-and-pasted-with.md +6 -0
  146. package/corpus/templates/slides/changelog/2026-07-30-slide-text-editing-and-object-controls-now-match-google-slides.md +6 -0
  147. package/corpus/templates/slides/changelog/2026-07-30-style-panel-now-scrolls-with-speaker-notes-open-shows-the-sl.md +6 -0
  148. package/corpus/templates/slides/changelog/2026-07-30-top-toolbar-controls-now-use-consistent-sizing-with-undo-and.md +6 -0
  149. package/corpus/templates/slides/netlify.toml +3 -1
  150. package/corpus/templates/slides/package.json +0 -1
  151. package/corpus/templates/slides/server/lib/chat-attachments.ts +18 -0
  152. package/corpus/templates/slides/server/plugins/agent-chat.ts +5 -0
  153. package/corpus/templates/slides/vite.config.ts +0 -1
  154. package/corpus/toolkit/CHANGELOG.md +13 -0
  155. package/corpus/toolkit/README.md +19 -0
  156. package/corpus/toolkit/agent-native.eject.json +38 -0
  157. package/corpus/toolkit/package.json +29 -1
  158. package/corpus/toolkit/src/canvas-annotations/CanvasCommentPins.tsx +861 -0
  159. package/corpus/toolkit/src/canvas-annotations/DrawOverlay.tsx +1233 -0
  160. package/corpus/toolkit/src/canvas-annotations/index.ts +15 -0
  161. package/corpus/toolkit/src/canvas-annotations/types.ts +14 -0
  162. package/corpus/toolkit/src/canvas-interactions/canvas-interactions.ts +933 -0
  163. package/corpus/toolkit/src/canvas-interactions/index.ts +67 -0
  164. package/corpus/toolkit/src/design-tweaks/scrub-input-utils.ts +311 -0
  165. package/corpus/toolkit/src/design-tweaks/scrub-input.tsx +491 -0
  166. package/corpus/toolkit/src/design-tweaks/visual-style-controls.tsx +26 -171
  167. package/corpus/toolkit/src/index.ts +1 -0
  168. package/dist/a2a/client.d.ts +23 -0
  169. package/dist/a2a/client.d.ts.map +1 -1
  170. package/dist/a2a/client.js +309 -44
  171. package/dist/a2a/client.js.map +1 -1
  172. package/dist/a2a/correlation.d.ts +1 -0
  173. package/dist/a2a/correlation.d.ts.map +1 -1
  174. package/dist/a2a/correlation.js +27 -0
  175. package/dist/a2a/correlation.js.map +1 -1
  176. package/dist/a2a/types.d.ts +4 -0
  177. package/dist/a2a/types.d.ts.map +1 -1
  178. package/dist/a2a/types.js.map +1 -1
  179. package/dist/action.d.ts +3 -0
  180. package/dist/action.d.ts.map +1 -1
  181. package/dist/action.js.map +1 -1
  182. package/dist/agent/engine/registry.d.ts.map +1 -1
  183. package/dist/agent/engine/registry.js +34 -7
  184. package/dist/agent/engine/registry.js.map +1 -1
  185. package/dist/agent/production-agent.d.ts +40 -1
  186. package/dist/agent/production-agent.d.ts.map +1 -1
  187. package/dist/agent/production-agent.js +113 -15
  188. package/dist/agent/production-agent.js.map +1 -1
  189. package/dist/agent/run-loop-with-resume.d.ts +21 -0
  190. package/dist/agent/run-loop-with-resume.d.ts.map +1 -1
  191. package/dist/agent/run-loop-with-resume.js +163 -4
  192. package/dist/agent/run-loop-with-resume.js.map +1 -1
  193. package/dist/agent/run-manager.d.ts +16 -9
  194. package/dist/agent/run-manager.d.ts.map +1 -1
  195. package/dist/agent/run-manager.js +93 -42
  196. package/dist/agent/run-manager.js.map +1 -1
  197. package/dist/agent/thread-debug-history.d.ts +10 -0
  198. package/dist/agent/thread-debug-history.d.ts.map +1 -0
  199. package/dist/agent/thread-debug-history.js +68 -0
  200. package/dist/agent/thread-debug-history.js.map +1 -0
  201. package/dist/agent/types.d.ts +3 -1
  202. package/dist/agent/types.d.ts.map +1 -1
  203. package/dist/agent/types.js.map +1 -1
  204. package/dist/cli/create.d.ts.map +1 -1
  205. package/dist/cli/create.js +6 -1
  206. package/dist/cli/create.js.map +1 -1
  207. package/dist/cli/templates-meta.js +2 -2
  208. package/dist/cli/templates-meta.js.map +1 -1
  209. package/dist/client/agent-chat-adapter.d.ts +1 -1
  210. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  211. package/dist/client/agent-chat-adapter.js +76 -13
  212. package/dist/client/agent-chat-adapter.js.map +1 -1
  213. package/dist/client/resources/McpIntegrationDialog.d.ts.map +1 -1
  214. package/dist/client/resources/McpIntegrationDialog.js +1 -1
  215. package/dist/client/resources/McpIntegrationDialog.js.map +1 -1
  216. package/dist/client/sse-event-processor.d.ts.map +1 -1
  217. package/dist/client/sse-event-processor.js +12 -3
  218. package/dist/client/sse-event-processor.js.map +1 -1
  219. package/dist/collab/awareness.d.ts +2 -2
  220. package/dist/collab/awareness.d.ts.map +1 -1
  221. package/dist/db/client.d.ts.map +1 -1
  222. package/dist/db/client.js +48 -17
  223. package/dist/db/client.js.map +1 -1
  224. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  225. package/dist/integrations/adapters/slack.js +7 -3
  226. package/dist/integrations/adapters/slack.js.map +1 -1
  227. package/dist/localization/default-messages.d.ts +43 -0
  228. package/dist/localization/default-messages.d.ts.map +1 -1
  229. package/dist/localization/default-messages.js +43 -0
  230. package/dist/localization/default-messages.js.map +1 -1
  231. package/dist/notifications/routes.d.ts +2 -2
  232. package/dist/observability/traces.d.ts +3 -1
  233. package/dist/observability/traces.d.ts.map +1 -1
  234. package/dist/observability/traces.js +73 -4
  235. package/dist/observability/traces.js.map +1 -1
  236. package/dist/progress/routes.d.ts +1 -1
  237. package/dist/provider-api/actions/custom-provider-registration.d.ts +12 -12
  238. package/dist/provider-api/actions/provider-api.d.ts +13 -13
  239. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  240. package/dist/resources/handlers.d.ts +1 -1
  241. package/dist/scripts/call-agent.d.ts.map +1 -1
  242. package/dist/scripts/call-agent.js +233 -10
  243. package/dist/scripts/call-agent.js.map +1 -1
  244. package/dist/scripts/describe-workspace-apps.js +2 -2
  245. package/dist/scripts/describe-workspace-apps.js.map +1 -1
  246. package/dist/secrets/crypto.d.ts +31 -21
  247. package/dist/secrets/crypto.d.ts.map +1 -1
  248. package/dist/secrets/crypto.js +108 -33
  249. package/dist/secrets/crypto.js.map +1 -1
  250. package/dist/secrets/storage.d.ts +3 -5
  251. package/dist/secrets/storage.d.ts.map +1 -1
  252. package/dist/secrets/storage.js +40 -25
  253. package/dist/secrets/storage.js.map +1 -1
  254. package/dist/server/agent-capabilities.js +1 -1
  255. package/dist/server/agent-capabilities.js.map +1 -1
  256. package/dist/server/agent-chat/action-filters-a2a.d.ts +17 -3
  257. package/dist/server/agent-chat/action-filters-a2a.d.ts.map +1 -1
  258. package/dist/server/agent-chat/action-filters-a2a.js +92 -3
  259. package/dist/server/agent-chat/action-filters-a2a.js.map +1 -1
  260. package/dist/server/agent-chat/context-tools.d.ts.map +1 -1
  261. package/dist/server/agent-chat/context-tools.js +2 -0
  262. package/dist/server/agent-chat/context-tools.js.map +1 -1
  263. package/dist/server/agent-chat/plugin-options.d.ts +23 -0
  264. package/dist/server/agent-chat/plugin-options.d.ts.map +1 -1
  265. package/dist/server/agent-chat/plugin-options.js +4 -1
  266. package/dist/server/agent-chat/plugin-options.js.map +1 -1
  267. package/dist/server/agent-chat/prompt-resources.js +1 -1
  268. package/dist/server/agent-chat/prompt-resources.js.map +1 -1
  269. package/dist/server/agent-chat-plugin.d.ts +2 -1
  270. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  271. package/dist/server/agent-chat-plugin.js +79 -56
  272. package/dist/server/agent-chat-plugin.js.map +1 -1
  273. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  274. package/dist/templates/default/.agents/skills/secrets/SKILL.md +14 -7
  275. package/dist/templates/headless/.agents/skills/secrets/SKILL.md +14 -7
  276. package/dist/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +18 -7
  277. package/dist/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +15 -14
  278. package/dist/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -7
  279. package/dist/vite/client.d.ts.map +1 -1
  280. package/dist/vite/client.js +1 -0
  281. package/dist/vite/client.js.map +1 -1
  282. package/docs/content/agent-native-toolkit.mdx +13 -6
  283. package/docs/content/cloneable-saas.mdx +5 -5
  284. package/docs/content/creating-templates.mdx +9 -0
  285. package/docs/content/deployment.mdx +14 -10
  286. package/docs/content/docs-components.mdx +491 -0
  287. package/docs/content/doctor.mdx +8 -1
  288. package/docs/content/drop-in-agent.mdx +1 -1
  289. package/docs/content/extensions.mdx +18 -18
  290. package/docs/content/faq.mdx +4 -4
  291. package/docs/content/key-concepts.mdx +30 -21
  292. package/docs/content/template-brain-developers.mdx +4 -1
  293. package/docs/content/template-mail-developers.mdx +4 -1
  294. package/docs/content/what-is-agent-native.mdx +6 -6
  295. package/package.json +2 -2
  296. package/src/a2a/client.ts +449 -66
  297. package/src/a2a/correlation.ts +31 -0
  298. package/src/a2a/types.ts +4 -0
  299. package/src/action.ts +3 -0
  300. package/src/agent/engine/registry.ts +45 -5
  301. package/src/agent/production-agent.ts +151 -18
  302. package/src/agent/run-loop-with-resume.ts +190 -3
  303. package/src/agent/run-manager.ts +117 -41
  304. package/src/agent/thread-debug-history.ts +86 -0
  305. package/src/agent/types.ts +3 -1
  306. package/src/cli/create.ts +11 -1
  307. package/src/cli/templates-meta.ts +2 -2
  308. package/src/client/agent-chat-adapter.ts +91 -13
  309. package/src/client/resources/McpIntegrationDialog.tsx +11 -9
  310. package/src/client/sse-event-processor.ts +17 -3
  311. package/src/db/client.ts +57 -17
  312. package/src/integrations/adapters/slack.ts +8 -3
  313. package/src/localization/default-messages.ts +44 -0
  314. package/src/observability/traces.ts +78 -5
  315. package/src/scripts/call-agent.ts +290 -9
  316. package/src/scripts/describe-workspace-apps.ts +2 -2
  317. package/src/secrets/crypto.ts +126 -34
  318. package/src/secrets/storage.ts +61 -25
  319. package/src/server/agent-capabilities.ts +1 -1
  320. package/src/server/agent-chat/action-filters-a2a.ts +111 -7
  321. package/src/server/agent-chat/context-tools.ts +2 -0
  322. package/src/server/agent-chat/plugin-options.ts +34 -1
  323. package/src/server/agent-chat/prompt-resources.ts +1 -1
  324. package/src/server/agent-chat-plugin.ts +91 -59
  325. package/src/templates/default/.agents/skills/secrets/SKILL.md +14 -7
  326. package/src/templates/headless/.agents/skills/secrets/SKILL.md +14 -7
  327. package/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +18 -7
  328. package/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +15 -14
  329. package/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -7
  330. package/src/vite/client.ts +1 -0
@@ -10,24 +10,22 @@
10
10
  * existing single-app deployments can keep reading and writing secrets while
11
11
  * they migrate to the shared key.
12
12
  *
13
- * The default encryption key is derived from
14
- * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then `SECRETS_ENCRYPTION_KEY`,
15
- * then `BETTER_AUTH_SECRET`. The app-scoped key lets a local multi-app
16
- * workspace read one app's encrypted production data without replacing the
17
- * shared local auth secret. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`)
18
- * typically set none of those literal env vars per app; in that case the
19
- * shared-key variant falls back further to material derived from the
20
- * workspace-wide `A2A_SECRET` (see `getWorkspaceA2ADerivedSecret`), so sibling
21
- * apps in the same workspace still land on the same shared key without any
22
- * extra configuration. In production we refuse to start without configured
23
- * key material a CWD-derived fallback would be effectively static (e.g.
24
- * `/var/task` on Lambda), so anyone with read access to the DB could decrypt
25
- * every secret.
13
+ * The generic encryption key is derived from
14
+ * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then
15
+ * `SECRETS_ENCRYPTION_KEY`, then `BETTER_AUTH_SECRET`. Workspace-shared vault
16
+ * rows use a different precedence: `SECRETS_ENCRYPTION_KEY`, then material
17
+ * derived from the workspace-wide `A2A_SECRET`, then the app-local auth/key
18
+ * fallbacks retained for backward-compatible reads. This keeps sibling apps
19
+ * on one key even when each app correctly has a different auth secret.
20
+ *
21
+ * In production we refuse to start without configured key material a
22
+ * CWD-derived fallback would be effectively static (e.g. `/var/task` on
23
+ * Lambda), so anyone with read access to the DB could decrypt every secret.
26
24
  *
27
25
  * Encrypted values are tagged `v1:<iv-hex>:<ct-hex>:<tag-hex>`. The `v1:` prefix
28
26
  * lets readers distinguish ciphertext from legacy plaintext during migration.
29
27
  */
30
- import { getWorkspaceA2ADerivedSecret } from "../server/derived-secret.js";
28
+ import { deriveServerSecret, getWorkspaceA2ADerivedSecret, } from "../server/derived-secret.js";
31
29
  function getNodeCrypto() {
32
30
  if (typeof window !== "undefined" ||
33
31
  typeof process === "undefined" ||
@@ -66,15 +64,62 @@ function appScopedEncryptionKey() {
66
64
  ? process.env[`${appName}_SECRETS_ENCRYPTION_KEY`] // guard:allow-env-credential — deploy-level app encryption material, never a user credential.
67
65
  : undefined;
68
66
  }
69
- function sharedEncryptionKeyMaterial() {
67
+ /**
68
+ * Preserve the generic/app-local key precedence. Generic encrypted values are
69
+ * not a cross-app boundary, and changing their preferred key would strand
70
+ * existing OAuth tokens and credentials.
71
+ */
72
+ function genericEncryptionKeyMaterial() {
70
73
  if (typeof process === "undefined")
71
74
  return undefined;
72
75
  return (process.env.SECRETS_ENCRYPTION_KEY ||
73
76
  process.env.BETTER_AUTH_SECRET ||
74
77
  getWorkspaceA2ADerivedSecret("secrets-encryption"));
75
78
  }
76
- function deriveSecretEncryptionKey(explicit, errorMessage, warningMessage) {
79
+ /**
80
+ * Vault sharing follows configured A2A trust even on independently deployed
81
+ * sibling apps that are not launched by the workspace wrapper. The wrapper's
82
+ * `AGENT_NATIVE_WORKSPACE` flag remains required for auth/OAuth-derived
83
+ * secrets, but it must not be a hidden prerequisite for decrypting vault rows
84
+ * when every app already has the same explicit `A2A_SECRET`.
85
+ */
86
+ function a2aSharedEncryptionKeyMaterial() {
87
+ const workspaceDerived = getWorkspaceA2ADerivedSecret("secrets-encryption");
88
+ if (workspaceDerived)
89
+ return workspaceDerived;
90
+ if (typeof process === "undefined")
91
+ return undefined;
92
+ const rootSecret = process.env.A2A_SECRET?.trim();
93
+ return rootSecret
94
+ ? deriveServerSecret(rootSecret, "secrets-encryption")
95
+ : undefined;
96
+ }
97
+ /**
98
+ * Stable materials that may be used for workspace-shared vault rows, ordered
99
+ * from current preference to legacy compatibility fallbacks.
100
+ *
101
+ * `BETTER_AUTH_SECRET` deliberately comes after the A2A-derived material:
102
+ * sibling apps normally have different auth secrets but share A2A trust.
103
+ */
104
+ function sharedEncryptionKeyMaterials() {
105
+ if (typeof process === "undefined")
106
+ return [];
107
+ const candidates = [
108
+ process.env.SECRETS_ENCRYPTION_KEY,
109
+ a2aSharedEncryptionKeyMaterial(),
110
+ process.env.BETTER_AUTH_SECRET,
111
+ appScopedEncryptionKey(),
112
+ ].filter((value) => Boolean(value));
113
+ return [...new Set(candidates)];
114
+ }
115
+ function preferredSharedEncryptionKeyMaterial() {
116
+ return sharedEncryptionKeyMaterials()[0];
117
+ }
118
+ function hashSecretEncryptionKey(material) {
77
119
  const { createHash } = requireNodeCrypto();
120
+ return createHash("sha256").update(material).digest();
121
+ }
122
+ function deriveSecretEncryptionKey(explicit, errorMessage, warningMessage) {
78
123
  if (!explicit) {
79
124
  if (processNodeEnv() === "production") {
80
125
  throw new Error(errorMessage);
@@ -86,7 +131,7 @@ function deriveSecretEncryptionKey(explicit, errorMessage, warningMessage) {
86
131
  }
87
132
  }
88
133
  const material = explicit || `agent-native-secrets:${processCwd()}`;
89
- return createHash("sha256").update(material).digest();
134
+ return hashSecretEncryptionKey(material);
90
135
  }
91
136
  /**
92
137
  * Derive the key used by generic encrypted values such as credentials and
@@ -100,7 +145,7 @@ export function getSecretEncryptionKey() {
100
145
  .toUpperCase()
101
146
  .replace(/[^A-Z0-9]+/g, "_")
102
147
  .replace(/^_+|_+$/g, "");
103
- return deriveSecretEncryptionKey(appScopedEncryptionKey() || sharedEncryptionKeyMaterial(), "[agent-native/secrets] Refusing to start in production without an encryption key. " +
148
+ return deriveSecretEncryptionKey(appScopedEncryptionKey() || genericEncryptionKeyMaterial(), "[agent-native/secrets] Refusing to start in production without an encryption key. " +
104
149
  `Set ${appName ? `${appName}_SECRETS_ENCRYPTION_KEY, ` : ""}SECRETS_ENCRYPTION_KEY, or BETTER_AUTH_SECRET in the deploy environment. ` +
105
150
  "The previous CWD-derived fallback was effectively static (e.g. `/var/task` on Lambda), " +
106
151
  "which means anyone with read access to the DB could decrypt every secret.", "[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using a machine-local fallback. " +
@@ -109,25 +154,26 @@ export function getSecretEncryptionKey() {
109
154
  }
110
155
  /**
111
156
  * Derive the preferred workspace-shared key used by `app_secrets` rows.
112
- * Unlike generic column-level encryption, workspace vault data should decrypt
113
- * in sibling apps, so `SECRETS_ENCRYPTION_KEY` / `BETTER_AUTH_SECRET` take
114
- * precedence. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`) that set
115
- * neither literal var still get stable shared material derived from the
116
- * workspace-wide `A2A_SECRET` before falling further back. The app-scoped key
117
- * remains a compatibility fallback for deployments that have not configured
118
- * shared material yet; once the shared key is configured, writes use it and
119
- * reads still fall back to old rows.
157
+ * Unlike generic column-level encryption, workspace vault data must decrypt
158
+ * in sibling apps. An explicit `SECRETS_ENCRYPTION_KEY` wins; hosted
159
+ * workspaces otherwise derive stable material from their shared `A2A_SECRET`
160
+ * before considering app-local `BETTER_AUTH_SECRET` or app-scoped key
161
+ * fallbacks. Reads try every configured legacy candidate and report when the
162
+ * ciphertext should be refreshed under the preferred key.
120
163
  */
121
164
  export function getSharedSecretEncryptionKey() {
122
- return deriveSecretEncryptionKey(sharedEncryptionKeyMaterial() || appScopedEncryptionKey(), "[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. " +
123
- "Set SECRETS_ENCRYPTION_KEY, BETTER_AUTH_SECRET, or the app-scoped *_SECRETS_ENCRYPTION_KEY in the deploy environment " +
124
- " or, on a hosted workspace deploy, ensure A2A_SECRET is set so shared material can be derived from it.", "[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. " +
125
- "Set SECRETS_ENCRYPTION_KEY or BETTER_AUTH_SECRET in every workspace app so sibling apps share vault rows, " +
126
- "or rely on A2A_SECRET-derived material on hosted workspace deploys.");
165
+ return deriveSecretEncryptionKey(preferredSharedEncryptionKeyMaterial(), "[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. " +
166
+ "Set SECRETS_ENCRYPTION_KEY, ensure a hosted workspace has A2A_SECRET, or set BETTER_AUTH_SECRET / an app-scoped " +
167
+ "*_SECRETS_ENCRYPTION_KEY compatibility fallback in the deploy environment.", "[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. " +
168
+ "Set SECRETS_ENCRYPTION_KEY or rely on A2A_SECRET-derived material on hosted workspace deploys so sibling apps share vault rows.");
127
169
  }
128
170
  /** Whether this deployment has stable workspace-shared key material. */
129
171
  export function hasSharedSecretEncryptionKeyMaterial() {
130
- return Boolean(sharedEncryptionKeyMaterial());
172
+ if (typeof process === "undefined")
173
+ return false;
174
+ return Boolean(process.env.SECRETS_ENCRYPTION_KEY ||
175
+ a2aSharedEncryptionKeyMaterial() ||
176
+ process.env.BETTER_AUTH_SECRET);
131
177
  }
132
178
  function encryptWithKey(plaintext, key) {
133
179
  const { createCipheriv, randomBytes } = requireNodeCrypto();
@@ -168,7 +214,36 @@ export function encryptSharedSecretValue(plaintext) {
168
214
  }
169
215
  /** Decrypt a workspace-shared `app_secrets` value. */
170
216
  export function decryptSharedSecretValue(encrypted) {
171
- return decryptWithKey(encrypted, getSharedSecretEncryptionKey());
217
+ return decryptSharedSecretValueDetailed(encrypted).value;
218
+ }
219
+ /**
220
+ * Decrypt workspace ciphertext with the preferred key first, then configured
221
+ * legacy candidates. The result never exposes which secret material matched.
222
+ */
223
+ export function decryptSharedSecretValueDetailed(encrypted) {
224
+ const preferredKey = getSharedSecretEncryptionKey();
225
+ const candidateKeys = [preferredKey];
226
+ for (const material of sharedEncryptionKeyMaterials()) {
227
+ const candidate = hashSecretEncryptionKey(material);
228
+ if (!candidateKeys.some((existing) => existing.equals(candidate))) {
229
+ candidateKeys.push(candidate);
230
+ }
231
+ }
232
+ let lastError;
233
+ for (const candidate of candidateKeys) {
234
+ try {
235
+ return {
236
+ value: decryptWithKey(encrypted, candidate),
237
+ needsReencrypt: !candidate.equals(preferredKey),
238
+ };
239
+ }
240
+ catch (error) {
241
+ lastError = error;
242
+ }
243
+ }
244
+ throw lastError instanceof Error
245
+ ? lastError
246
+ : new Error("Unable to decrypt workspace secret");
172
247
  }
173
248
  /**
174
249
  * Strict check for a value produced by `encryptSecretValue`: `v1:` followed by
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/secrets/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,4BAA4B,EAAE,MAAM,6BAA6B,CAAC;AAI3E,SAAS,aAAa;IACpB,IACE,OAAO,MAAM,KAAK,WAAW;QAC7B,OAAO,OAAO,KAAK,WAAW;QAC9B,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI;QACvB,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAC9C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAEhC,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,GAAG,aAAa,EAAE,CAAC;AAEnC,IAAI,eAAe,GAAG,KAAK,CAAC;AAE5B,SAAS,iBAAiB;IACxB,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CACb,oFAAoF,CACrF,CAAC;IACJ,CAAC;IACD,OAAO,U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,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;IAChD,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC;QACvB,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC1C,QAAQ,CAAC,KAAK,EAAE;KACjB,CAAC,CAAC;IACH,OAAO,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,kBAAkB,CAAC,SAAiB;IAClD,OAAO,cAAc,CAAC,SAAS,EAAE,sBAAsB,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,kBAAkB,CAAC,SAAiB;IAClD,OAAO,cAAc,CAAC,SAAS,EAAE,sBAAsB,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,wBAAwB,CAAC,SAAiB;IACxD,OAAO,cAAc,CAAC,SAAS,EAAE,4BAA4B,EAAE,CAAC,CAAC;AACnE,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,wBAAwB,CAAC,SAAiB;IACxD,OAAO,cAAc,CAAC,SAAS,EAAE,4BAA4B,EAAE,CAAC,CAAC;AACnE,CAAC;AAED;;;;;GAKG;AACH,MAAM,kBAAkB,GAAG,oCAAoC,CAAC;AAEhE,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACnD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrE,CAAC","sourcesContent":["/**\n * Shared AES-256-GCM encryption for secret values at rest.\n *\n * Used by the framework secrets vault, per-user/per-org credentials\n * (`resolveCredential` / `saveCredential`, stored in `settings`), and other\n * column-level encrypted values. The `app_secrets` storage layer uses the\n * shared-key variant below because workspace-scoped vault rows are readable by\n * sibling apps in the same workspace. When a deployment has not been given\n * shared key material yet, that variant falls back to the app-scoped key so\n * existing single-app deployments can keep reading and writing secrets while\n * they migrate to the shared key.\n *\n * The default encryption key is derived from\n * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then `SECRETS_ENCRYPTION_KEY`,\n * then `BETTER_AUTH_SECRET`. The app-scoped key lets a local multi-app\n * workspace read one app's encrypted production data without replacing the\n * shared local auth secret. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`)\n * typically set none of those literal env vars per app; in that case the\n * shared-key variant falls back further to material derived from the\n * workspace-wide `A2A_SECRET` (see `getWorkspaceA2ADerivedSecret`), so sibling\n * apps in the same workspace still land on the same shared key without any\n * extra configuration. In production we refuse to start without configured\n * key material — a CWD-derived fallback would be effectively static (e.g.\n * `/var/task` on Lambda), so anyone with read access to the DB could decrypt\n * every secret.\n *\n * Encrypted values are tagged `v1:<iv-hex>:<ct-hex>:<tag-hex>`. The `v1:` prefix\n * lets readers distinguish ciphertext from legacy plaintext during migration.\n */\n\nimport { getWorkspaceA2ADerivedSecret } from \"../server/derived-secret.js\";\n\ntype NodeCryptoModule = typeof import(\"node:crypto\");\n\nfunction getNodeCrypto(): NodeCryptoModule | undefined {\n if (\n typeof window !== \"undefined\" ||\n typeof process === \"undefined\" ||\n !process.versions?.node ||\n typeof process.getBuiltinModule !== \"function\"\n ) {\n return undefined;\n }\n return process.getBuiltinModule(\"node:crypto\") as\n | NodeCryptoModule\n | undefined;\n}\n\nconst nodeCrypto = getNodeCrypto();\n\nlet _warnedFallback = false;\n\nfunction requireNodeCrypto(): NonNullable<typeof nodeCrypto> {\n if (!nodeCrypto) {\n throw new Error(\n \"[agent-native/secrets] Secret encryption is only available in server/runtime code.\",\n );\n }\n return nodeCrypto;\n}\n\nfunction processNodeEnv(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n return process.env.NODE_ENV;\n}\n\nfunction processCwd(): string {\n if (typeof process === \"undefined\") return \".\";\n return process.cwd();\n}\n\nfunction appScopedEncryptionKey(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n const appName = process.env.APP_NAME?.trim() // guard:allow-env-credential — deploy-level app configuration selects the scoped encryption key.\n .toUpperCase()\n .replace(/[^A-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return appName\n ? process.env[`${appName}_SECRETS_ENCRYPTION_KEY`] // guard:allow-env-credential — deploy-level app encryption material, never a user credential.\n : undefined;\n}\n\nfunction sharedEncryptionKeyMaterial(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n return (\n process.env.SECRETS_ENCRYPTION_KEY ||\n process.env.BETTER_AUTH_SECRET ||\n getWorkspaceA2ADerivedSecret(\"secrets-encryption\")\n );\n}\n\nfunction deriveSecretEncryptionKey(\n explicit: string | undefined,\n errorMessage: string,\n warningMessage: string,\n): Buffer {\n const { createHash } = requireNodeCrypto();\n\n if (!explicit) {\n if (processNodeEnv() === \"production\") {\n throw new Error(errorMessage);\n }\n if (!_warnedFallback) {\n _warnedFallback = true;\n // eslint-disable-next-line no-console\n console.warn(warningMessage);\n }\n }\n\n const material = explicit || `agent-native-secrets:${processCwd()}`;\n return createHash(\"sha256\").update(material).digest();\n}\n\n/**\n * Derive the key used by generic encrypted values such as credentials and\n * OAuth tokens. App-specific key material is allowed for these app-local\n * values.\n */\nexport function getSecretEncryptionKey(): Buffer {\n const appName =\n typeof process === \"undefined\"\n ? undefined\n : process.env.APP_NAME?.trim() // guard:allow-env-credential — deploy-level app configuration selects the scoped encryption key.\n .toUpperCase()\n .replace(/[^A-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return deriveSecretEncryptionKey(\n appScopedEncryptionKey() || sharedEncryptionKeyMaterial(),\n \"[agent-native/secrets] Refusing to start in production without an encryption key. \" +\n `Set ${appName ? `${appName}_SECRETS_ENCRYPTION_KEY, ` : \"\"}SECRETS_ENCRYPTION_KEY, or BETTER_AUTH_SECRET in the deploy environment. ` +\n \"The previous CWD-derived fallback was effectively static (e.g. `/var/task` on Lambda), \" +\n \"which means anyone with read access to the DB could decrypt every secret.\",\n \"[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using a machine-local fallback. \" +\n \"Set an app-scoped *_SECRETS_ENCRYPTION_KEY, SECRETS_ENCRYPTION_KEY, or BETTER_AUTH_SECRET for production. \" +\n \"Production deploys without one of these env vars now hard-fail.\",\n );\n}\n\n/**\n * Derive the preferred workspace-shared key used by `app_secrets` rows.\n * Unlike generic column-level encryption, workspace vault data should decrypt\n * in sibling apps, so `SECRETS_ENCRYPTION_KEY` / `BETTER_AUTH_SECRET` take\n * precedence. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`) that set\n * neither literal var still get stable shared material derived from the\n * workspace-wide `A2A_SECRET` before falling further back. The app-scoped key\n * remains a compatibility fallback for deployments that have not configured\n * shared material yet; once the shared key is configured, writes use it and\n * reads still fall back to old rows.\n */\nexport function getSharedSecretEncryptionKey(): Buffer {\n return deriveSecretEncryptionKey(\n sharedEncryptionKeyMaterial() || appScopedEncryptionKey(),\n \"[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. \" +\n \"Set SECRETS_ENCRYPTION_KEY, BETTER_AUTH_SECRET, or the app-scoped *_SECRETS_ENCRYPTION_KEY in the deploy environment \" +\n \"— or, on a hosted workspace deploy, ensure A2A_SECRET is set so shared material can be derived from it.\",\n \"[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. \" +\n \"Set SECRETS_ENCRYPTION_KEY or BETTER_AUTH_SECRET in every workspace app so sibling apps share vault rows, \" +\n \"or rely on A2A_SECRET-derived material on hosted workspace deploys.\",\n );\n}\n\n/** Whether this deployment has stable workspace-shared key material. */\nexport function hasSharedSecretEncryptionKeyMaterial(): boolean {\n return Boolean(sharedEncryptionKeyMaterial());\n}\n\nfunction encryptWithKey(plaintext: string, key: Buffer): string {\n const { createCipheriv, randomBytes } = requireNodeCrypto();\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return `v1:${iv.toString(\"hex\")}:${ct.toString(\"hex\")}:${tag.toString(\"hex\")}`;\n}\n\nfunction decryptWithKey(encrypted: string, key: Buffer): string {\n const { createDecipheriv } = requireNodeCrypto();\n if (!encrypted.startsWith(\"v1:\")) {\n throw new Error(\"Unrecognised secret encoding\");\n }\n const [, ivHex, ctHex, tagHex] = encrypted.split(\":\");\n if (!ivHex || !ctHex || !tagHex) {\n throw new Error(\"Corrupt secret payload\");\n }\n const decipher = createDecipheriv(\n \"aes-256-gcm\",\n key,\n Buffer.from(ivHex, \"hex\"),\n );\n decipher.setAuthTag(Buffer.from(tagHex, \"hex\"));\n const pt = Buffer.concat([\n decipher.update(Buffer.from(ctHex, \"hex\")),\n decipher.final(),\n ]);\n return pt.toString(\"utf8\");\n}\n\n/** Encrypt a plain-text value with the generic app-local key. */\nexport function encryptSecretValue(plaintext: string): string {\n return encryptWithKey(plaintext, getSecretEncryptionKey());\n}\n\n/** Decrypt a value produced by `encryptSecretValue`. Throws on tampering. */\nexport function decryptSecretValue(encrypted: string): string {\n return decryptWithKey(encrypted, getSecretEncryptionKey());\n}\n\n/** Encrypt a workspace-shared `app_secrets` value. */\nexport function encryptSharedSecretValue(plaintext: string): string {\n return encryptWithKey(plaintext, getSharedSecretEncryptionKey());\n}\n\n/** Decrypt a workspace-shared `app_secrets` value. */\nexport function decryptSharedSecretValue(encrypted: string): string {\n return decryptWithKey(encrypted, getSharedSecretEncryptionKey());\n}\n\n/**\n * Strict check for a value produced by `encryptSecretValue`: `v1:` followed by\n * three hex segments. Intentionally strict so a legacy plaintext credential\n * that merely happens to start with `v1:` is treated as plaintext (and read via\n * the legacy fallback) rather than mis-decrypted.\n */\nconst ENCRYPTED_VALUE_RE = /^v1:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+$/;\n\nexport function isEncryptedSecretValue(value: unknown): value is string {\n return typeof value === \"string\" && ENCRYPTED_VALUE_RE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ACrE,CAAC","sourcesContent":["/**\n * Shared AES-256-GCM encryption for secret values at rest.\n *\n * Used by the framework secrets vault, per-user/per-org credentials\n * (`resolveCredential` / `saveCredential`, stored in `settings`), and other\n * column-level encrypted values. The `app_secrets` storage layer uses the\n * shared-key variant below because workspace-scoped vault rows are readable by\n * sibling apps in the same workspace. When a deployment has not been given\n * shared key material yet, that variant falls back to the app-scoped key so\n * existing single-app deployments can keep reading and writing secrets while\n * they migrate to the shared key.\n *\n * The generic encryption key is derived from\n * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then\n * `SECRETS_ENCRYPTION_KEY`, then `BETTER_AUTH_SECRET`. Workspace-shared vault\n * rows use a different precedence: `SECRETS_ENCRYPTION_KEY`, then material\n * derived from the workspace-wide `A2A_SECRET`, then the app-local auth/key\n * fallbacks retained for backward-compatible reads. This keeps sibling apps\n * on one key even when each app correctly has a different auth secret.\n *\n * In production we refuse to start without configured key material — a\n * CWD-derived fallback would be effectively static (e.g. `/var/task` on\n * Lambda), so anyone with read access to the DB could decrypt every secret.\n *\n * Encrypted values are tagged `v1:<iv-hex>:<ct-hex>:<tag-hex>`. The `v1:` prefix\n * lets readers distinguish ciphertext from legacy plaintext during migration.\n */\n\nimport {\n deriveServerSecret,\n getWorkspaceA2ADerivedSecret,\n} from \"../server/derived-secret.js\";\n\ntype NodeCryptoModule = typeof import(\"node:crypto\");\n\nfunction getNodeCrypto(): NodeCryptoModule | undefined {\n if (\n typeof window !== \"undefined\" ||\n typeof process === \"undefined\" ||\n !process.versions?.node ||\n typeof process.getBuiltinModule !== \"function\"\n ) {\n return undefined;\n }\n return process.getBuiltinModule(\"node:crypto\") as\n | NodeCryptoModule\n | undefined;\n}\n\nconst nodeCrypto = getNodeCrypto();\n\nlet _warnedFallback = false;\n\nfunction requireNodeCrypto(): NonNullable<typeof nodeCrypto> {\n if (!nodeCrypto) {\n throw new Error(\n \"[agent-native/secrets] Secret encryption is only available in server/runtime code.\",\n );\n }\n return nodeCrypto;\n}\n\nfunction processNodeEnv(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n return process.env.NODE_ENV;\n}\n\nfunction processCwd(): string {\n if (typeof process === \"undefined\") return \".\";\n return process.cwd();\n}\n\nfunction appScopedEncryptionKey(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n const appName = process.env.APP_NAME?.trim() // guard:allow-env-credential — deploy-level app configuration selects the scoped encryption key.\n .toUpperCase()\n .replace(/[^A-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return appName\n ? process.env[`${appName}_SECRETS_ENCRYPTION_KEY`] // guard:allow-env-credential — deploy-level app encryption material, never a user credential.\n : undefined;\n}\n\n/**\n * Preserve the generic/app-local key precedence. Generic encrypted values are\n * not a cross-app boundary, and changing their preferred key would strand\n * existing OAuth tokens and credentials.\n */\nfunction genericEncryptionKeyMaterial(): string | undefined {\n if (typeof process === \"undefined\") return undefined;\n return (\n process.env.SECRETS_ENCRYPTION_KEY ||\n process.env.BETTER_AUTH_SECRET ||\n getWorkspaceA2ADerivedSecret(\"secrets-encryption\")\n );\n}\n\n/**\n * Vault sharing follows configured A2A trust even on independently deployed\n * sibling apps that are not launched by the workspace wrapper. The wrapper's\n * `AGENT_NATIVE_WORKSPACE` flag remains required for auth/OAuth-derived\n * secrets, but it must not be a hidden prerequisite for decrypting vault rows\n * when every app already has the same explicit `A2A_SECRET`.\n */\nfunction a2aSharedEncryptionKeyMaterial(): string | undefined {\n const workspaceDerived = getWorkspaceA2ADerivedSecret(\"secrets-encryption\");\n if (workspaceDerived) return workspaceDerived;\n if (typeof process === \"undefined\") return undefined;\n const rootSecret = process.env.A2A_SECRET?.trim();\n return rootSecret\n ? deriveServerSecret(rootSecret, \"secrets-encryption\")\n : undefined;\n}\n\n/**\n * Stable materials that may be used for workspace-shared vault rows, ordered\n * from current preference to legacy compatibility fallbacks.\n *\n * `BETTER_AUTH_SECRET` deliberately comes after the A2A-derived material:\n * sibling apps normally have different auth secrets but share A2A trust.\n */\nfunction sharedEncryptionKeyMaterials(): string[] {\n if (typeof process === \"undefined\") return [];\n const candidates = [\n process.env.SECRETS_ENCRYPTION_KEY,\n a2aSharedEncryptionKeyMaterial(),\n process.env.BETTER_AUTH_SECRET,\n appScopedEncryptionKey(),\n ].filter((value): value is string => Boolean(value));\n return [...new Set(candidates)];\n}\n\nfunction preferredSharedEncryptionKeyMaterial(): string | undefined {\n return sharedEncryptionKeyMaterials()[0];\n}\n\nfunction hashSecretEncryptionKey(material: string): Buffer {\n const { createHash } = requireNodeCrypto();\n return createHash(\"sha256\").update(material).digest();\n}\n\nfunction deriveSecretEncryptionKey(\n explicit: string | undefined,\n errorMessage: string,\n warningMessage: string,\n): Buffer {\n if (!explicit) {\n if (processNodeEnv() === \"production\") {\n throw new Error(errorMessage);\n }\n if (!_warnedFallback) {\n _warnedFallback = true;\n // eslint-disable-next-line no-console\n console.warn(warningMessage);\n }\n }\n\n const material = explicit || `agent-native-secrets:${processCwd()}`;\n return hashSecretEncryptionKey(material);\n}\n\n/**\n * Derive the key used by generic encrypted values such as credentials and\n * OAuth tokens. App-specific key material is allowed for these app-local\n * values.\n */\nexport function getSecretEncryptionKey(): Buffer {\n const appName =\n typeof process === \"undefined\"\n ? undefined\n : process.env.APP_NAME?.trim() // guard:allow-env-credential — deploy-level app configuration selects the scoped encryption key.\n .toUpperCase()\n .replace(/[^A-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return deriveSecretEncryptionKey(\n appScopedEncryptionKey() || genericEncryptionKeyMaterial(),\n \"[agent-native/secrets] Refusing to start in production without an encryption key. \" +\n `Set ${appName ? `${appName}_SECRETS_ENCRYPTION_KEY, ` : \"\"}SECRETS_ENCRYPTION_KEY, or BETTER_AUTH_SECRET in the deploy environment. ` +\n \"The previous CWD-derived fallback was effectively static (e.g. `/var/task` on Lambda), \" +\n \"which means anyone with read access to the DB could decrypt every secret.\",\n \"[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using a machine-local fallback. \" +\n \"Set an app-scoped *_SECRETS_ENCRYPTION_KEY, SECRETS_ENCRYPTION_KEY, or BETTER_AUTH_SECRET for production. \" +\n \"Production deploys without one of these env vars now hard-fail.\",\n );\n}\n\n/**\n * Derive the preferred workspace-shared key used by `app_secrets` rows.\n * Unlike generic column-level encryption, workspace vault data must decrypt\n * in sibling apps. An explicit `SECRETS_ENCRYPTION_KEY` wins; hosted\n * workspaces otherwise derive stable material from their shared `A2A_SECRET`\n * before considering app-local `BETTER_AUTH_SECRET` or app-scoped key\n * fallbacks. Reads try every configured legacy candidate and report when the\n * ciphertext should be refreshed under the preferred key.\n */\nexport function getSharedSecretEncryptionKey(): Buffer {\n return deriveSecretEncryptionKey(\n preferredSharedEncryptionKeyMaterial(),\n \"[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. \" +\n \"Set SECRETS_ENCRYPTION_KEY, ensure a hosted workspace has A2A_SECRET, or set BETTER_AUTH_SECRET / an app-scoped \" +\n \"*_SECRETS_ENCRYPTION_KEY compatibility fallback in the deploy environment.\",\n \"[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. \" +\n \"Set SECRETS_ENCRYPTION_KEY or rely on A2A_SECRET-derived material on hosted workspace deploys so sibling apps share vault rows.\",\n );\n}\n\n/** Whether this deployment has stable workspace-shared key material. */\nexport function hasSharedSecretEncryptionKeyMaterial(): boolean {\n if (typeof process === \"undefined\") return false;\n return Boolean(\n process.env.SECRETS_ENCRYPTION_KEY ||\n a2aSharedEncryptionKeyMaterial() ||\n process.env.BETTER_AUTH_SECRET,\n );\n}\n\nfunction encryptWithKey(plaintext: string, key: Buffer): string {\n const { createCipheriv, randomBytes } = requireNodeCrypto();\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const tag = cipher.getAuthTag();\n return `v1:${iv.toString(\"hex\")}:${ct.toString(\"hex\")}:${tag.toString(\"hex\")}`;\n}\n\nfunction decryptWithKey(encrypted: string, key: Buffer): string {\n const { createDecipheriv } = requireNodeCrypto();\n if (!encrypted.startsWith(\"v1:\")) {\n throw new Error(\"Unrecognised secret encoding\");\n }\n const [, ivHex, ctHex, tagHex] = encrypted.split(\":\");\n if (!ivHex || !ctHex || !tagHex) {\n throw new Error(\"Corrupt secret payload\");\n }\n const decipher = createDecipheriv(\n \"aes-256-gcm\",\n key,\n Buffer.from(ivHex, \"hex\"),\n );\n decipher.setAuthTag(Buffer.from(tagHex, \"hex\"));\n const pt = Buffer.concat([\n decipher.update(Buffer.from(ctHex, \"hex\")),\n decipher.final(),\n ]);\n return pt.toString(\"utf8\");\n}\n\n/** Encrypt a plain-text value with the generic app-local key. */\nexport function encryptSecretValue(plaintext: string): string {\n return encryptWithKey(plaintext, getSecretEncryptionKey());\n}\n\n/** Decrypt a value produced by `encryptSecretValue`. Throws on tampering. */\nexport function decryptSecretValue(encrypted: string): string {\n return decryptWithKey(encrypted, getSecretEncryptionKey());\n}\n\n/** Encrypt a workspace-shared `app_secrets` value. */\nexport function encryptSharedSecretValue(plaintext: string): string {\n return encryptWithKey(plaintext, getSharedSecretEncryptionKey());\n}\n\n/** Decrypt a workspace-shared `app_secrets` value. */\nexport function decryptSharedSecretValue(encrypted: string): string {\n return decryptSharedSecretValueDetailed(encrypted).value;\n}\n\nexport interface DecryptedSharedSecretValue {\n value: string;\n /**\n * True when a legacy app-local candidate decrypted the value. Callers that\n * own the row should opportunistically re-encrypt it with the preferred\n * workspace key.\n */\n needsReencrypt: boolean;\n}\n\n/**\n * Decrypt workspace ciphertext with the preferred key first, then configured\n * legacy candidates. The result never exposes which secret material matched.\n */\nexport function decryptSharedSecretValueDetailed(\n encrypted: string,\n): DecryptedSharedSecretValue {\n const preferredKey = getSharedSecretEncryptionKey();\n const candidateKeys = [preferredKey];\n for (const material of sharedEncryptionKeyMaterials()) {\n const candidate = hashSecretEncryptionKey(material);\n if (!candidateKeys.some((existing) => existing.equals(candidate))) {\n candidateKeys.push(candidate);\n }\n }\n\n let lastError: unknown;\n for (const candidate of candidateKeys) {\n try {\n return {\n value: decryptWithKey(encrypted, candidate),\n needsReencrypt: !candidate.equals(preferredKey),\n };\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError instanceof Error\n ? lastError\n : new Error(\"Unable to decrypt workspace secret\");\n}\n\n/**\n * Strict check for a value produced by `encryptSecretValue`: `v1:` followed by\n * three hex segments. Intentionally strict so a legacy plaintext credential\n * that merely happens to start with `v1:` is treated as plaintext (and read via\n * the legacy fallback) rather than mis-decrypted.\n */\nconst ENCRYPTED_VALUE_RE = /^v1:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+$/;\n\nexport function isEncryptedSecretValue(value: unknown): value is string {\n return typeof value === \"string\" && ENCRYPTED_VALUE_RE.test(value);\n}\n"]}
@@ -3,11 +3,9 @@
3
3
  *
4
4
  * Values are encrypted at rest with AES-256-GCM. The workspace-shared
5
5
  * encryption key is derived from `SECRETS_ENCRYPTION_KEY` (preferred) or the
6
- * existing `BETTER_AUTH_SECRET` env var (fallback so templates don't need a
7
- * second secret during development). Deployments that only have the legacy
8
- * app-scoped key continue to work until shared key material is configured;
9
- * once configured, new rows use the shared key and reads retain a legacy-key
10
- * fallback for existing rows.
6
+ * workspace-wide `A2A_SECRET`. `BETTER_AUTH_SECRET` and app-scoped keys remain
7
+ * read fallbacks for rows written before sibling apps converged on the shared
8
+ * key. Successful fallback reads race-safely refresh the shared ciphertext.
11
9
  *
12
10
  * Secret values are NEVER logged and NEVER returned from any route handler.
13
11
  */
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/secrets/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAaH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AA+FjD;;;GAGG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAI3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AgB,GAAG,IAAI,CAAC,CA8BlC;AAED,wEAAwE;AACxE,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACxB,KAAK,EAAE,WAAW,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAoCzC;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,SAAS,GACb,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAItD;AAED,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,WAAW,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,SAAS,GACb,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAsC5B;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CAuCvB;AAeD,wBAAsB,eAAe,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,CAStE"}
@@ -3,18 +3,16 @@
3
3
  *
4
4
  * Values are encrypted at rest with AES-256-GCM. The workspace-shared
5
5
  * encryption key is derived from `SECRETS_ENCRYPTION_KEY` (preferred) or the
6
- * existing `BETTER_AUTH_SECRET` env var (fallback so templates don't need a
7
- * second secret during development). Deployments that only have the legacy
8
- * app-scoped key continue to work until shared key material is configured;
9
- * once configured, new rows use the shared key and reads retain a legacy-key
10
- * fallback for existing rows.
6
+ * workspace-wide `A2A_SECRET`. `BETTER_AUTH_SECRET` and app-scoped keys remain
7
+ * read fallbacks for rows written before sibling apps converged on the shared
8
+ * key. Successful fallback reads race-safely refresh the shared ciphertext.
11
9
  *
12
10
  * Secret values are NEVER logged and NEVER returned from any route handler.
13
11
  */
14
12
  import { randomUUID } from "node:crypto";
15
13
  import { getDbExec, isPostgres } from "../db/client.js";
16
14
  import { ensureColumnExists, ensureTableExists } from "../db/ddl-guard.js";
17
- import { encryptSecretValue as encryptLegacyValue, encryptSharedSecretValue as encryptValue, decryptSharedSecretValue as decryptValue, decryptSecretValue as decryptLegacyValue, hasSharedSecretEncryptionKeyMaterial, } from "./crypto.js";
15
+ import { encryptSecretValue as encryptLegacyValue, encryptSharedSecretValue as encryptValue, decryptSharedSecretValueDetailed as decryptValue, decryptSecretValue as decryptLegacyValue, hasSharedSecretEncryptionKeyMaterial, } from "./crypto.js";
18
16
  import { APP_SECRETS_CREATE_SQL } from "./schema.js";
19
17
  // ---------------------------------------------------------------------------
20
18
  // Table bootstrap
@@ -139,8 +137,9 @@ export async function writeAppSecret(args) {
139
137
  // pointing at data that's no longer current. Siblings then get an honest
140
138
  // cache miss (falling back to the legacy column or reporting missing) until
141
139
  // the owning app's next read repopulates shared_encrypted_value via
142
- // `populateSharedAppSecret`, which only ever fills a NULL column. A
143
- // temporary miss is safer than serving rotated-away plaintext.
140
+ // `populateSharedAppSecret`, which fills a NULL column or compare-and-swap
141
+ // replaces the exact legacy ciphertext it just decrypted. A temporary miss
142
+ // is safer than serving rotated-away plaintext.
144
143
  const upsertSql = `INSERT INTO app_secrets (id, scope, scope_id, key, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at)
145
144
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
146
145
  ON CONFLICT (scope, scope_id, key) DO UPDATE SET
@@ -183,10 +182,14 @@ export async function writeAppSecret(args) {
183
182
  function decryptAppSecretValue(encrypted, sharedEncrypted) {
184
183
  if (sharedEncrypted) {
185
184
  try {
185
+ const decrypted = decryptValue(sharedEncrypted);
186
186
  return {
187
- value: decryptValue(sharedEncrypted),
187
+ value: decrypted.value,
188
188
  usedLegacyKey: false,
189
- needsSharedCiphertext: false,
189
+ needsSharedCiphertext: decrypted.needsReencrypt,
190
+ sharedCiphertextToReplace: decrypted.needsReencrypt
191
+ ? sharedEncrypted
192
+ : undefined,
190
193
  };
191
194
  }
192
195
  catch {
@@ -195,10 +198,12 @@ function decryptAppSecretValue(encrypted, sharedEncrypted) {
195
198
  }
196
199
  }
197
200
  try {
201
+ const decrypted = decryptValue(encrypted);
198
202
  return {
199
- value: decryptValue(encrypted),
203
+ value: decrypted.value,
200
204
  usedLegacyKey: false,
201
205
  needsSharedCiphertext: true,
206
+ sharedCiphertextToReplace: sharedEncrypted ?? null,
202
207
  };
203
208
  }
204
209
  catch {
@@ -206,27 +211,37 @@ function decryptAppSecretValue(encrypted, sharedEncrypted) {
206
211
  value: decryptLegacyValue(encrypted),
207
212
  usedLegacyKey: true,
208
213
  needsSharedCiphertext: true,
214
+ sharedCiphertextToReplace: sharedEncrypted ?? null,
209
215
  };
210
216
  }
211
217
  }
212
218
  /**
213
- * Populate the shared column without touching encrypted_value. This is
214
- * intentionally best-effort: a read must still succeed if a deployment's DB
215
- * role cannot update the row. The NULL predicate prevents a concurrent writer
216
- * from overwriting newly-populated shared ciphertext, and leaving updated_at
217
- * untouched preserves the row's user-visible ordering/metadata.
219
+ * Create or refresh the shared column without touching encrypted_value. This
220
+ * is intentionally best-effort: a read must still succeed if a deployment's
221
+ * DB role cannot update the row. The compare-and-swap predicate prevents a
222
+ * concurrent writer from being overwritten, and leaving updated_at untouched
223
+ * preserves the row's user-visible ordering/metadata.
218
224
  */
219
- async function populateSharedAppSecret(id, value) {
225
+ async function populateSharedAppSecret(id, value, sharedCiphertextToReplace) {
220
226
  if (id === undefined ||
221
227
  id === null ||
222
228
  !hasSharedSecretEncryptionKeyMaterial()) {
223
229
  return;
224
230
  }
225
231
  try {
226
- await getDbExec().execute({
227
- sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value IS NULL`,
228
- args: [encryptValue(value), id],
229
- });
232
+ const encrypted = encryptValue(value);
233
+ if (sharedCiphertextToReplace === null) {
234
+ await getDbExec().execute({
235
+ sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value IS NULL`,
236
+ args: [encrypted, id],
237
+ });
238
+ }
239
+ else {
240
+ await getDbExec().execute({
241
+ sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value = ?`,
242
+ args: [encrypted, id, sharedCiphertextToReplace],
243
+ });
244
+ }
230
245
  }
231
246
  catch {
232
247
  // Migration is opportunistic. Preserve the successful read if the update
@@ -280,7 +295,7 @@ export async function readAppSecret(ref) {
280
295
  const encrypted = rows[0].encrypted_value;
281
296
  const decrypted = decryptAppSecretValue(encrypted, rows[0].shared_encrypted_value);
282
297
  if (decrypted.needsSharedCiphertext) {
283
- await populateSharedAppSecret(rows[0].id, decrypted.value);
298
+ await populateSharedAppSecret(rows[0].id, decrypted.value, decrypted.sharedCiphertextToReplace ?? null);
284
299
  }
285
300
  return {
286
301
  value: decrypted.value,
@@ -313,7 +328,7 @@ export async function readAppSecrets(args) {
313
328
  const encrypted = row.encrypted_value;
314
329
  const decrypted = decryptAppSecretValue(encrypted, row.shared_encrypted_value);
315
330
  if (decrypted.needsSharedCiphertext) {
316
- await populateSharedAppSecret(row.id, decrypted.value);
331
+ await populateSharedAppSecret(row.id, decrypted.value, decrypted.sharedCiphertextToReplace ?? null);
317
332
  }
318
333
  results.set(key, {
319
334
  value: decrypted.value,
@@ -359,7 +374,7 @@ export async function readAppSecretMeta(ref) {
359
374
  const encrypted = row.encrypted_value;
360
375
  const decrypted = decryptAppSecretValue(encrypted, row.shared_encrypted_value);
361
376
  if (decrypted.needsSharedCiphertext) {
362
- await populateSharedAppSecret(row.id, decrypted.value);
377
+ await populateSharedAppSecret(row.id, decrypted.value, decrypted.sharedCiphertextToReplace ?? null);
363
378
  }
364
379
  last4Value = last4(decrypted.value);
365
380
  }
@@ -396,7 +411,7 @@ export async function listAppSecretsForScope(scope, scopeId) {
396
411
  const encrypted = row.encrypted_value;
397
412
  const decrypted = decryptAppSecretValue(encrypted, row.shared_encrypted_value);
398
413
  if (decrypted.needsSharedCiphertext) {
399
- await populateSharedAppSecret(row.id, decrypted.value);
414
+ await populateSharedAppSecret(row.id, decrypted.value, decrypted.sharedCiphertextToReplace ?? null);
400
415
  }
401
416
  last4Value = last4(decrypted.value);
402
417
  }
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/secrets/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EACL,kBAAkB,IAAI,kBAAkB,EACxC,wBAAwB,IAAI,YAAY,EACxC,wBAAwB,IAAI,YAAY,EACxC,kBAAkB,IAAI,kBAAkB,EACxC,oCAAoC,GACrC,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErD,8EAA8E;AAC9E,kBAAkB;AAClB,8EAA8E;AAE9E,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,uEAAuE;YACvE,gEAAgE;YAChE,MAAM,SA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C;QAC/B,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,EAAE,CAAC;YACxE,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,GAAc;IAClD,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;IACpC,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;QAC5C,GAAG,EAAE,sEAAsE;QAC3E,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC;KAC5B,CAAC,CAAC;IACH,OAAO,YAAY,GAAG,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Storage layer for the framework secrets registry.\n *\n * Values are encrypted at rest with AES-256-GCM. The workspace-shared\n * encryption key is derived from `SECRETS_ENCRYPTION_KEY` (preferred) or the\n * existing `BETTER_AUTH_SECRET` env var (fallback so templates don't need a\n * second secret during development). Deployments that only have the legacy\n * app-scoped key continue to work until shared key material is configured;\n * once configured, new rows use the shared key and reads retain a legacy-key\n * fallback for existing rows.\n *\n * Secret values are NEVER logged and NEVER returned from any route handler.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { getDbExec, isPostgres } from \"../db/client.js\";\nimport { ensureColumnExists, ensureTableExists } from \"../db/ddl-guard.js\";\nimport {\n encryptSecretValue as encryptLegacyValue,\n encryptSharedSecretValue as encryptValue,\n decryptSharedSecretValue as decryptValue,\n decryptSecretValue as decryptLegacyValue,\n hasSharedSecretEncryptionKeyMaterial,\n} from \"./crypto.js\";\nimport type { SecretScope } from \"./register.js\";\nimport { APP_SECRETS_CREATE_SQL } from \"./schema.js\";\n\n// ---------------------------------------------------------------------------\n// Table bootstrap\n// ---------------------------------------------------------------------------\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n // Postgres version of the CREATE TABLE — the generic `INTEGER` maps to\n // BIGINT on Postgres, which we need for millisecond timestamps.\n const createSql = isPostgres()\n ? APP_SECRETS_CREATE_SQL.replace(/\\bINTEGER\\b/g, \"BIGINT\")\n : APP_SECRETS_CREATE_SQL;\n\n if (isPostgres()) {\n // Hot path: in production the table and both additive columns are\n // virtually always already present. Issuing `CREATE`/`ALTER` would\n // still take an ACCESS EXCLUSIVE lock — which, in a fresh background\n // worker process behind a concurrent connection on the shared Neon DB,\n // can block ~indefinitely. `ensureTableExists` / `ensureColumnExists`\n // check `information_schema` first (a plain read, no lock) and run DDL\n // ONLY for what is actually missing, wrapping any DDL that must run in a\n // transaction-scoped `lock_timeout` so a contended lock fails fast. They\n // also re-probe after a swallowed lock-timeout and THROW if the schema\n // is still missing, so a timed-out DDL never poisons this init memo.\n await ensureTableExists(\"app_secrets\", createSql);\n await ensureColumnExists(\n \"app_secrets\",\n \"description\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS description TEXT`,\n );\n await ensureColumnExists(\n \"app_secrets\",\n \"url_allowlist\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS url_allowlist TEXT`,\n );\n await ensureColumnExists(\n \"app_secrets\",\n \"shared_encrypted_value\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS shared_encrypted_value TEXT`,\n );\n return;\n }\n\n // SQLite (local dev): no ACCESS EXCLUSIVE lock problem, keep the original\n // create-then-additive-alter behaviour. SQLite has no\n // `ADD COLUMN IF NOT EXISTS`, so the ALTERs stay wrapped in try/catch.\n await client.execute(createSql);\n\n // Additive migration: description column (for ad-hoc keys)\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN description TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n\n // Additive migration: url_allowlist column\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN url_allowlist TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n\n // Additive migration: workspace-shared ciphertext. Keep the legacy\n // encrypted_value column so older app versions remain readable.\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN shared_encrypted_value TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n })().catch((err) => {\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Encryption — see ./crypto.ts. Keep encrypted_value on the legacy app-key\n// format for mixed-version deployments, and add shared_encrypted_value when a\n// stable workspace key is configured so sibling apps can read the same row.\n// ---------------------------------------------------------------------------\n\n/**\n * Return the last 4 characters of a secret, with any leading characters\n * masked. Used to show a preview without leaking the value.\n */\nexport function last4(value: string): string {\n if (!value) return \"\";\n if (value.length <= 4) return \"••••\";\n return \"••••\" + value.slice(-4);\n}\n\n// ---------------------------------------------------------------------------\n// CRUD\n// ---------------------------------------------------------------------------\n\nexport interface SecretRef {\n key: string;\n scope: SecretScope;\n scopeId: string;\n}\n\nexport interface WriteSecretArgs extends SecretRef {\n value: string;\n /** Optional human-readable description (used for ad-hoc keys). */\n description?: string;\n /** Optional JSON-stringified array of allowed URL origins. */\n urlAllowlist?: string;\n}\n\n/**\n * Write (insert or update) a secret. The value is encrypted before being\n * stored — the caller's plaintext is never persisted. Returns the new\n * record's id.\n */\nexport async function writeAppSecret(args: WriteSecretArgs): Promise<string> {\n await ensureTable();\n const { key, value, scope, scopeId, description, urlAllowlist } = args;\n if (!key || !value || !scope || !scopeId) {\n throw new Error(\n \"writeAppSecret: key, value, scope, and scopeId are all required\",\n );\n }\n const client = getDbExec();\n const now = Date.now();\n // Dual-write during rollout: old readers continue using encrypted_value,\n // while new readers prefer the nullable shared ciphertext. An app-only\n // deployment leaves the shared column null; on an update, a writer without\n // shared key material clears any existing shared ciphertext rather than\n // preserving it (see the upsert SQL below for why).\n const encrypted = encryptLegacyValue(value);\n const sharedEncrypted = hasSharedSecretEncryptionKeyMaterial()\n ? encryptValue(value)\n : null;\n const id = randomUUID();\n\n // Atomic upsert by (scope, scope_id, key). Previously this was a\n // SELECT-then-branch (UPDATE if found, else INSERT): under concurrent\n // writers for the same key both could see \"no row\" and both attempt\n // INSERT, and the loser threw a raw UNIQUE(scope, scope_id, key)\n // constraint violation (a user-facing 500) instead of updating. A single\n // `INSERT ... ON CONFLICT DO UPDATE` closes that window — it's one\n // statement, so there's no gap between \"check\" and \"act\". `id` is\n // deliberately left out of the `DO UPDATE SET` list so an existing row\n // keeps its original id (any stored references stay stable); only a\n // genuinely new row gets the freshly generated `id`. This syntax is\n // portable across SQLite (UPSERT since 3.24) and Postgres.\n //\n // shared_encrypted_value is overwritten with `excluded.shared_encrypted_value`\n // (NULL when this writer lacks shared key material) rather than preserved\n // via COALESCE. Preserving an existing shared ciphertext across a value\n // update would let a sibling app silently decrypt a STALE value after the\n // owner rotates it — a material-less writer has no way to produce the new\n // shared ciphertext, so it must clear the old one instead of leaving it\n // pointing at data that's no longer current. Siblings then get an honest\n // cache miss (falling back to the legacy column or reporting missing) until\n // the owning app's next read repopulates shared_encrypted_value via\n // `populateSharedAppSecret`, which only ever fills a NULL column. A\n // temporary miss is safer than serving rotated-away plaintext.\n const upsertSql = `INSERT INTO app_secrets (id, scope, scope_id, key, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (scope, scope_id, key) DO UPDATE SET\n encrypted_value = excluded.encrypted_value,\n shared_encrypted_value = excluded.shared_encrypted_value,\n description = excluded.description,\n url_allowlist = excluded.url_allowlist,\n updated_at = excluded.updated_at`;\n const upsertArgs = [\n id,\n scope,\n scopeId,\n key,\n encrypted,\n sharedEncrypted,\n description ?? null,\n urlAllowlist ?? null,\n now,\n now,\n ];\n\n if (isPostgres()) {\n const { rows } = await client.execute({\n sql: `${upsertSql} RETURNING id`,\n args: upsertArgs,\n });\n return String(rows[0]?.id ?? id);\n }\n\n // SQLite: RETURNING support varies across better-sqlite3/libsql builds, so\n // (matching the convention elsewhere in this codebase, e.g.\n // integrations/pending-tasks-store.ts) re-read the id afterward instead of\n // relying on it. The row is guaranteed to exist at this point, so this is\n // a plain lookup rather than a TOCTOU-prone gate on the write itself.\n await client.execute({ sql: upsertSql, args: upsertArgs });\n const { rows } = await client.execute({\n sql: `SELECT id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n return String(rows[0]?.id ?? id);\n}\n\nexport interface ReadSecretResult {\n value: string;\n last4: string;\n updatedAt: number;\n}\n\n/**\n * Read the shared-key format and retain compatibility with rows written before\n * app_secrets moved to its workspace-shared encryption boundary. The legacy\n * fallback is only useful when the current app owns the old row; sibling apps\n * will receive shared-key ciphertext after the next vault sync or update.\n */\ninterface DecryptedAppSecretValue {\n value: string;\n /** True when the app-scoped fallback decrypted encrypted_value. */\n usedLegacyKey: boolean;\n /** True when shared_encrypted_value was not the source of the plaintext. */\n needsSharedCiphertext: boolean;\n}\n\nfunction decryptAppSecretValue(\n encrypted: string,\n sharedEncrypted?: string | null,\n): DecryptedAppSecretValue {\n if (sharedEncrypted) {\n try {\n return {\n value: decryptValue(sharedEncrypted),\n usedLegacyKey: false,\n needsSharedCiphertext: false,\n };\n } catch {\n // Fall through to the legacy column. A partially migrated row may have\n // a stale shared ciphertext while the old app-key value is valid.\n }\n }\n try {\n return {\n value: decryptValue(encrypted),\n usedLegacyKey: false,\n needsSharedCiphertext: true,\n };\n } catch {\n return {\n value: decryptLegacyValue(encrypted),\n usedLegacyKey: true,\n needsSharedCiphertext: true,\n };\n }\n}\n\n/**\n * Populate the shared column without touching encrypted_value. This is\n * intentionally best-effort: a read must still succeed if a deployment's DB\n * role cannot update the row. The NULL predicate prevents a concurrent writer\n * from overwriting newly-populated shared ciphertext, and leaving updated_at\n * untouched preserves the row's user-visible ordering/metadata.\n */\nasync function populateSharedAppSecret(\n id: unknown,\n value: string,\n): Promise<void> {\n if (\n id === undefined ||\n id === null ||\n !hasSharedSecretEncryptionKeyMaterial()\n ) {\n return;\n }\n try {\n await getDbExec().execute({\n sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value IS NULL`,\n args: [encryptValue(value), id],\n });\n } catch {\n // Migration is opportunistic. Preserve the successful read if the update\n // is unavailable due to a read-only role, transient DB failure, or race.\n }\n}\n\ntype AppSecretsReadQuery = { sql: string; args: unknown[] };\n\n/**\n * True only when the database says the app_secrets table itself is missing.\n * Other query failures must propagate unchanged: attempting schema bootstrap\n * for connectivity, permission, or syntax errors both hides the real failure\n * and can introduce DDL onto a latency-sensitive read path.\n */\nfunction isMissingAppSecretsTableError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = String((error as Error & { code?: unknown }).code ?? \"\");\n const message = error.message.toLowerCase();\n const namesAppSecrets = /(?:app_secrets|\"app_secrets\")/.test(message);\n\n if (code === \"42P01\") return namesAppSecrets;\n return (\n namesAppSecrets &&\n (message.includes(\"no such table\") ||\n (message.includes(\"relation\") && message.includes(\"does not exist\")))\n );\n}\n\n/** Execute a read without schema probes on the normal path. */\nasync function executeAppSecretsRead(query: AppSecretsReadQuery) {\n const client = getDbExec();\n try {\n return await client.execute(query);\n } catch (error) {\n if (!isMissingAppSecretsTableError(error)) throw error;\n await ensureTable();\n return client.execute(query);\n }\n}\n\n/**\n * Read a secret's plaintext value. Returns null when not found. The caller\n * is responsible for never logging the returned value.\n */\nexport async function readAppSecret(\n ref: SecretRef,\n): Promise<ReadSecretResult | null> {\n const { key, scope, scopeId } = ref;\n const { rows } = await executeAppSecretsRead({\n sql: `SELECT encrypted_value, shared_encrypted_value, updated_at, id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n if (rows.length === 0) return null;\n try {\n const encrypted = rows[0].encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n rows[0].shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(rows[0].id, decrypted.value);\n }\n return {\n value: decrypted.value,\n last4: last4(decrypted.value),\n updatedAt: Number(rows[0].updated_at ?? 0),\n };\n } catch {\n // Decryption failure — key rotated, tampered row, etc. Don't throw up the\n // stack in a way that could leak the ciphertext; just report missing.\n return null;\n }\n}\n\n/** Read several keys from one scope in a single database round trip. */\nexport async function readAppSecrets(args: {\n keys: readonly string[];\n scope: SecretScope;\n scopeId: string;\n}): Promise<Map<string, ReadSecretResult>> {\n const keys = [...new Set(args.keys.filter(Boolean))];\n if (keys.length === 0) return new Map();\n\n const placeholders = keys.map(() => \"?\").join(\", \");\n const { rows } = await executeAppSecretsRead({\n sql: `SELECT key, encrypted_value, shared_encrypted_value, updated_at, id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key IN (${placeholders})`,\n args: [args.scope, args.scopeId, ...keys],\n });\n const results = new Map<string, ReadSecretResult>();\n for (const row of rows) {\n const key = String(row.key ?? \"\");\n if (!key) continue;\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(row.id, decrypted.value);\n }\n results.set(key, {\n value: decrypted.value,\n last4: last4(decrypted.value),\n updatedAt: Number(row.updated_at ?? 0),\n });\n } catch {\n // Match readAppSecret: corrupted or stale ciphertext behaves as missing.\n }\n }\n return results;\n}\n\n/**\n * Return just the metadata for a secret (no value). Used by the list route so\n * the UI can show the \"Set\" pill and last-4 without the decrypted value going\n * over the wire.\n */\nexport async function getAppSecretMeta(\n ref: SecretRef,\n): Promise<{ last4: string; updatedAt: number } | null> {\n const result = await readAppSecret(ref);\n if (!result) return null;\n return { last4: result.last4, updatedAt: result.updatedAt };\n}\n\nexport interface SecretMeta {\n key: string;\n scope: SecretScope;\n scopeId: string;\n last4: string;\n description: string | null;\n urlAllowlist: string[] | null;\n createdAt: number;\n updatedAt: number;\n}\n\n/**\n * Read a secret's metadata, including ad-hoc fields (description, allowlist),\n * without ever decrypting or returning the plaintext value. Used by the\n * ad-hoc list route and any UI that wants to render a key tile.\n */\nexport async function readAppSecretMeta(\n ref: SecretRef,\n): Promise<SecretMeta | null> {\n await ensureTable();\n const { key, scope, scopeId } = ref;\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n if (rows.length === 0) return null;\n const row = rows[0];\n let last4Value = \"\";\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(row.id, decrypted.value);\n }\n last4Value = last4(decrypted.value);\n } catch {\n last4Value = \"\";\n }\n return {\n key,\n scope,\n scopeId,\n last4: last4Value,\n description: (row.description as string | null) ?? null,\n urlAllowlist: parseAllowlist(row.url_allowlist as string | null),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\n/**\n * List all secrets for a given scope. Returns metadata only — values are\n * never decrypted or returned. Used by the ad-hoc list route to surface\n * user-created keys.\n */\nexport async function listAppSecretsForScope(\n scope: SecretScope,\n scopeId: string,\n): Promise<SecretMeta[]> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, key, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at FROM app_secrets WHERE scope = ? AND scope_id = ? ORDER BY updated_at DESC`,\n args: [scope, scopeId],\n });\n const results: SecretMeta[] = [];\n for (const row of rows) {\n let last4Value = \"\";\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(row.id, decrypted.value);\n }\n last4Value = last4(decrypted.value);\n } catch {\n last4Value = \"\";\n }\n results.push({\n key: row.key as string,\n scope,\n scopeId,\n last4: last4Value,\n description: (row.description as string | null) ?? null,\n urlAllowlist: parseAllowlist(row.url_allowlist as string | null),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n });\n }\n return results;\n}\n\nfunction parseAllowlist(raw: string | null): string[] | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed) && parsed.every((v) => typeof v === \"string\")) {\n return parsed;\n }\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function deleteAppSecret(ref: SecretRef): Promise<boolean> {\n await ensureTable();\n const { key, scope, scopeId } = ref;\n const client = getDbExec();\n const { rowsAffected } = await client.execute({\n sql: `DELETE FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ?`,\n args: [scope, scopeId, key],\n });\n return rowsAffected > 0;\n}\n"]}
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/secrets/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EACL,kBAAkB,IAAI,kBAAkB,EACxC,wBAAwB,IAAI,YAAY,EACxC,gCAAgC,IAAI,YAAY,EAChD,kBAAkB,IAAI,kBAAkB,EACxC,oCAAoC,GACrC,MAAM,aAAa,CAAC;AAErB,OAA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,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,GAAc;IAClD,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;IACpC,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;QAC5C,GAAG,EAAE,sEAAsE;QAC3E,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC;KAC5B,CAAC,CAAC;IACH,OAAO,YAAY,GAAG,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Storage layer for the framework secrets registry.\n *\n * Values are encrypted at rest with AES-256-GCM. The workspace-shared\n * encryption key is derived from `SECRETS_ENCRYPTION_KEY` (preferred) or the\n * workspace-wide `A2A_SECRET`. `BETTER_AUTH_SECRET` and app-scoped keys remain\n * read fallbacks for rows written before sibling apps converged on the shared\n * key. Successful fallback reads race-safely refresh the shared ciphertext.\n *\n * Secret values are NEVER logged and NEVER returned from any route handler.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { getDbExec, isPostgres } from \"../db/client.js\";\nimport { ensureColumnExists, ensureTableExists } from \"../db/ddl-guard.js\";\nimport {\n encryptSecretValue as encryptLegacyValue,\n encryptSharedSecretValue as encryptValue,\n decryptSharedSecretValueDetailed as decryptValue,\n decryptSecretValue as decryptLegacyValue,\n hasSharedSecretEncryptionKeyMaterial,\n} from \"./crypto.js\";\nimport type { SecretScope } from \"./register.js\";\nimport { APP_SECRETS_CREATE_SQL } from \"./schema.js\";\n\n// ---------------------------------------------------------------------------\n// Table bootstrap\n// ---------------------------------------------------------------------------\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n // Postgres version of the CREATE TABLE — the generic `INTEGER` maps to\n // BIGINT on Postgres, which we need for millisecond timestamps.\n const createSql = isPostgres()\n ? APP_SECRETS_CREATE_SQL.replace(/\\bINTEGER\\b/g, \"BIGINT\")\n : APP_SECRETS_CREATE_SQL;\n\n if (isPostgres()) {\n // Hot path: in production the table and both additive columns are\n // virtually always already present. Issuing `CREATE`/`ALTER` would\n // still take an ACCESS EXCLUSIVE lock — which, in a fresh background\n // worker process behind a concurrent connection on the shared Neon DB,\n // can block ~indefinitely. `ensureTableExists` / `ensureColumnExists`\n // check `information_schema` first (a plain read, no lock) and run DDL\n // ONLY for what is actually missing, wrapping any DDL that must run in a\n // transaction-scoped `lock_timeout` so a contended lock fails fast. They\n // also re-probe after a swallowed lock-timeout and THROW if the schema\n // is still missing, so a timed-out DDL never poisons this init memo.\n await ensureTableExists(\"app_secrets\", createSql);\n await ensureColumnExists(\n \"app_secrets\",\n \"description\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS description TEXT`,\n );\n await ensureColumnExists(\n \"app_secrets\",\n \"url_allowlist\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS url_allowlist TEXT`,\n );\n await ensureColumnExists(\n \"app_secrets\",\n \"shared_encrypted_value\",\n `ALTER TABLE app_secrets ADD COLUMN IF NOT EXISTS shared_encrypted_value TEXT`,\n );\n return;\n }\n\n // SQLite (local dev): no ACCESS EXCLUSIVE lock problem, keep the original\n // create-then-additive-alter behaviour. SQLite has no\n // `ADD COLUMN IF NOT EXISTS`, so the ALTERs stay wrapped in try/catch.\n await client.execute(createSql);\n\n // Additive migration: description column (for ad-hoc keys)\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN description TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n\n // Additive migration: url_allowlist column\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN url_allowlist TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n\n // Additive migration: workspace-shared ciphertext. Keep the legacy\n // encrypted_value column so older app versions remain readable.\n try {\n await client.execute(\n `ALTER TABLE app_secrets ADD COLUMN shared_encrypted_value TEXT`,\n );\n } catch {\n // Column already exists — expected\n }\n })().catch((err) => {\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Encryption — see ./crypto.ts. Keep encrypted_value on the legacy app-key\n// format for mixed-version deployments, and add shared_encrypted_value when a\n// stable workspace key is configured so sibling apps can read the same row.\n// ---------------------------------------------------------------------------\n\n/**\n * Return the last 4 characters of a secret, with any leading characters\n * masked. Used to show a preview without leaking the value.\n */\nexport function last4(value: string): string {\n if (!value) return \"\";\n if (value.length <= 4) return \"••••\";\n return \"••••\" + value.slice(-4);\n}\n\n// ---------------------------------------------------------------------------\n// CRUD\n// ---------------------------------------------------------------------------\n\nexport interface SecretRef {\n key: string;\n scope: SecretScope;\n scopeId: string;\n}\n\nexport interface WriteSecretArgs extends SecretRef {\n value: string;\n /** Optional human-readable description (used for ad-hoc keys). */\n description?: string;\n /** Optional JSON-stringified array of allowed URL origins. */\n urlAllowlist?: string;\n}\n\n/**\n * Write (insert or update) a secret. The value is encrypted before being\n * stored — the caller's plaintext is never persisted. Returns the new\n * record's id.\n */\nexport async function writeAppSecret(args: WriteSecretArgs): Promise<string> {\n await ensureTable();\n const { key, value, scope, scopeId, description, urlAllowlist } = args;\n if (!key || !value || !scope || !scopeId) {\n throw new Error(\n \"writeAppSecret: key, value, scope, and scopeId are all required\",\n );\n }\n const client = getDbExec();\n const now = Date.now();\n // Dual-write during rollout: old readers continue using encrypted_value,\n // while new readers prefer the nullable shared ciphertext. An app-only\n // deployment leaves the shared column null; on an update, a writer without\n // shared key material clears any existing shared ciphertext rather than\n // preserving it (see the upsert SQL below for why).\n const encrypted = encryptLegacyValue(value);\n const sharedEncrypted = hasSharedSecretEncryptionKeyMaterial()\n ? encryptValue(value)\n : null;\n const id = randomUUID();\n\n // Atomic upsert by (scope, scope_id, key). Previously this was a\n // SELECT-then-branch (UPDATE if found, else INSERT): under concurrent\n // writers for the same key both could see \"no row\" and both attempt\n // INSERT, and the loser threw a raw UNIQUE(scope, scope_id, key)\n // constraint violation (a user-facing 500) instead of updating. A single\n // `INSERT ... ON CONFLICT DO UPDATE` closes that window — it's one\n // statement, so there's no gap between \"check\" and \"act\". `id` is\n // deliberately left out of the `DO UPDATE SET` list so an existing row\n // keeps its original id (any stored references stay stable); only a\n // genuinely new row gets the freshly generated `id`. This syntax is\n // portable across SQLite (UPSERT since 3.24) and Postgres.\n //\n // shared_encrypted_value is overwritten with `excluded.shared_encrypted_value`\n // (NULL when this writer lacks shared key material) rather than preserved\n // via COALESCE. Preserving an existing shared ciphertext across a value\n // update would let a sibling app silently decrypt a STALE value after the\n // owner rotates it — a material-less writer has no way to produce the new\n // shared ciphertext, so it must clear the old one instead of leaving it\n // pointing at data that's no longer current. Siblings then get an honest\n // cache miss (falling back to the legacy column or reporting missing) until\n // the owning app's next read repopulates shared_encrypted_value via\n // `populateSharedAppSecret`, which fills a NULL column or compare-and-swap\n // replaces the exact legacy ciphertext it just decrypted. A temporary miss\n // is safer than serving rotated-away plaintext.\n const upsertSql = `INSERT INTO app_secrets (id, scope, scope_id, key, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (scope, scope_id, key) DO UPDATE SET\n encrypted_value = excluded.encrypted_value,\n shared_encrypted_value = excluded.shared_encrypted_value,\n description = excluded.description,\n url_allowlist = excluded.url_allowlist,\n updated_at = excluded.updated_at`;\n const upsertArgs = [\n id,\n scope,\n scopeId,\n key,\n encrypted,\n sharedEncrypted,\n description ?? null,\n urlAllowlist ?? null,\n now,\n now,\n ];\n\n if (isPostgres()) {\n const { rows } = await client.execute({\n sql: `${upsertSql} RETURNING id`,\n args: upsertArgs,\n });\n return String(rows[0]?.id ?? id);\n }\n\n // SQLite: RETURNING support varies across better-sqlite3/libsql builds, so\n // (matching the convention elsewhere in this codebase, e.g.\n // integrations/pending-tasks-store.ts) re-read the id afterward instead of\n // relying on it. The row is guaranteed to exist at this point, so this is\n // a plain lookup rather than a TOCTOU-prone gate on the write itself.\n await client.execute({ sql: upsertSql, args: upsertArgs });\n const { rows } = await client.execute({\n sql: `SELECT id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n return String(rows[0]?.id ?? id);\n}\n\nexport interface ReadSecretResult {\n value: string;\n last4: string;\n updatedAt: number;\n}\n\n/**\n * Read the shared-key format and retain compatibility with rows written before\n * app_secrets moved to its workspace-shared encryption boundary. The legacy\n * fallback is only useful when the current app owns the old row; sibling apps\n * will receive shared-key ciphertext after the next vault sync or update.\n */\ninterface DecryptedAppSecretValue {\n value: string;\n /** True when the app-scoped fallback decrypted encrypted_value. */\n usedLegacyKey: boolean;\n /** True when shared_encrypted_value needs to be created or refreshed. */\n needsSharedCiphertext: boolean;\n /**\n * Existing ciphertext that must still match before a refresh. Null means the\n * migration may only fill an empty shared column.\n */\n sharedCiphertextToReplace?: string | null;\n}\n\nfunction decryptAppSecretValue(\n encrypted: string,\n sharedEncrypted?: string | null,\n): DecryptedAppSecretValue {\n if (sharedEncrypted) {\n try {\n const decrypted = decryptValue(sharedEncrypted);\n return {\n value: decrypted.value,\n usedLegacyKey: false,\n needsSharedCiphertext: decrypted.needsReencrypt,\n sharedCiphertextToReplace: decrypted.needsReencrypt\n ? sharedEncrypted\n : undefined,\n };\n } catch {\n // Fall through to the legacy column. A partially migrated row may have\n // a stale shared ciphertext while the old app-key value is valid.\n }\n }\n try {\n const decrypted = decryptValue(encrypted);\n return {\n value: decrypted.value,\n usedLegacyKey: false,\n needsSharedCiphertext: true,\n sharedCiphertextToReplace: sharedEncrypted ?? null,\n };\n } catch {\n return {\n value: decryptLegacyValue(encrypted),\n usedLegacyKey: true,\n needsSharedCiphertext: true,\n sharedCiphertextToReplace: sharedEncrypted ?? null,\n };\n }\n}\n\n/**\n * Create or refresh the shared column without touching encrypted_value. This\n * is intentionally best-effort: a read must still succeed if a deployment's\n * DB role cannot update the row. The compare-and-swap predicate prevents a\n * concurrent writer from being overwritten, and leaving updated_at untouched\n * preserves the row's user-visible ordering/metadata.\n */\nasync function populateSharedAppSecret(\n id: unknown,\n value: string,\n sharedCiphertextToReplace: string | null,\n): Promise<void> {\n if (\n id === undefined ||\n id === null ||\n !hasSharedSecretEncryptionKeyMaterial()\n ) {\n return;\n }\n try {\n const encrypted = encryptValue(value);\n if (sharedCiphertextToReplace === null) {\n await getDbExec().execute({\n sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value IS NULL`,\n args: [encrypted, id],\n });\n } else {\n await getDbExec().execute({\n sql: `UPDATE app_secrets SET shared_encrypted_value = ? WHERE id = ? AND shared_encrypted_value = ?`,\n args: [encrypted, id, sharedCiphertextToReplace],\n });\n }\n } catch {\n // Migration is opportunistic. Preserve the successful read if the update\n // is unavailable due to a read-only role, transient DB failure, or race.\n }\n}\n\ntype AppSecretsReadQuery = { sql: string; args: unknown[] };\n\n/**\n * True only when the database says the app_secrets table itself is missing.\n * Other query failures must propagate unchanged: attempting schema bootstrap\n * for connectivity, permission, or syntax errors both hides the real failure\n * and can introduce DDL onto a latency-sensitive read path.\n */\nfunction isMissingAppSecretsTableError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = String((error as Error & { code?: unknown }).code ?? \"\");\n const message = error.message.toLowerCase();\n const namesAppSecrets = /(?:app_secrets|\"app_secrets\")/.test(message);\n\n if (code === \"42P01\") return namesAppSecrets;\n return (\n namesAppSecrets &&\n (message.includes(\"no such table\") ||\n (message.includes(\"relation\") && message.includes(\"does not exist\")))\n );\n}\n\n/** Execute a read without schema probes on the normal path. */\nasync function executeAppSecretsRead(query: AppSecretsReadQuery) {\n const client = getDbExec();\n try {\n return await client.execute(query);\n } catch (error) {\n if (!isMissingAppSecretsTableError(error)) throw error;\n await ensureTable();\n return client.execute(query);\n }\n}\n\n/**\n * Read a secret's plaintext value. Returns null when not found. The caller\n * is responsible for never logging the returned value.\n */\nexport async function readAppSecret(\n ref: SecretRef,\n): Promise<ReadSecretResult | null> {\n const { key, scope, scopeId } = ref;\n const { rows } = await executeAppSecretsRead({\n sql: `SELECT encrypted_value, shared_encrypted_value, updated_at, id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n if (rows.length === 0) return null;\n try {\n const encrypted = rows[0].encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n rows[0].shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(\n rows[0].id,\n decrypted.value,\n decrypted.sharedCiphertextToReplace ?? null,\n );\n }\n return {\n value: decrypted.value,\n last4: last4(decrypted.value),\n updatedAt: Number(rows[0].updated_at ?? 0),\n };\n } catch {\n // Decryption failure — key rotated, tampered row, etc. Don't throw up the\n // stack in a way that could leak the ciphertext; just report missing.\n return null;\n }\n}\n\n/** Read several keys from one scope in a single database round trip. */\nexport async function readAppSecrets(args: {\n keys: readonly string[];\n scope: SecretScope;\n scopeId: string;\n}): Promise<Map<string, ReadSecretResult>> {\n const keys = [...new Set(args.keys.filter(Boolean))];\n if (keys.length === 0) return new Map();\n\n const placeholders = keys.map(() => \"?\").join(\", \");\n const { rows } = await executeAppSecretsRead({\n sql: `SELECT key, encrypted_value, shared_encrypted_value, updated_at, id FROM app_secrets WHERE scope = ? AND scope_id = ? AND key IN (${placeholders})`,\n args: [args.scope, args.scopeId, ...keys],\n });\n const results = new Map<string, ReadSecretResult>();\n for (const row of rows) {\n const key = String(row.key ?? \"\");\n if (!key) continue;\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(\n row.id,\n decrypted.value,\n decrypted.sharedCiphertextToReplace ?? null,\n );\n }\n results.set(key, {\n value: decrypted.value,\n last4: last4(decrypted.value),\n updatedAt: Number(row.updated_at ?? 0),\n });\n } catch {\n // Match readAppSecret: corrupted or stale ciphertext behaves as missing.\n }\n }\n return results;\n}\n\n/**\n * Return just the metadata for a secret (no value). Used by the list route so\n * the UI can show the \"Set\" pill and last-4 without the decrypted value going\n * over the wire.\n */\nexport async function getAppSecretMeta(\n ref: SecretRef,\n): Promise<{ last4: string; updatedAt: number } | null> {\n const result = await readAppSecret(ref);\n if (!result) return null;\n return { last4: result.last4, updatedAt: result.updatedAt };\n}\n\nexport interface SecretMeta {\n key: string;\n scope: SecretScope;\n scopeId: string;\n last4: string;\n description: string | null;\n urlAllowlist: string[] | null;\n createdAt: number;\n updatedAt: number;\n}\n\n/**\n * Read a secret's metadata, including ad-hoc fields (description, allowlist),\n * without ever decrypting or returning the plaintext value. Used by the\n * ad-hoc list route and any UI that wants to render a key tile.\n */\nexport async function readAppSecretMeta(\n ref: SecretRef,\n): Promise<SecretMeta | null> {\n await ensureTable();\n const { key, scope, scopeId } = ref;\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ? LIMIT 1`,\n args: [scope, scopeId, key],\n });\n if (rows.length === 0) return null;\n const row = rows[0];\n let last4Value = \"\";\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(\n row.id,\n decrypted.value,\n decrypted.sharedCiphertextToReplace ?? null,\n );\n }\n last4Value = last4(decrypted.value);\n } catch {\n last4Value = \"\";\n }\n return {\n key,\n scope,\n scopeId,\n last4: last4Value,\n description: (row.description as string | null) ?? null,\n urlAllowlist: parseAllowlist(row.url_allowlist as string | null),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\n/**\n * List all secrets for a given scope. Returns metadata only — values are\n * never decrypted or returned. Used by the ad-hoc list route to surface\n * user-created keys.\n */\nexport async function listAppSecretsForScope(\n scope: SecretScope,\n scopeId: string,\n): Promise<SecretMeta[]> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, key, encrypted_value, shared_encrypted_value, description, url_allowlist, created_at, updated_at FROM app_secrets WHERE scope = ? AND scope_id = ? ORDER BY updated_at DESC`,\n args: [scope, scopeId],\n });\n const results: SecretMeta[] = [];\n for (const row of rows) {\n let last4Value = \"\";\n try {\n const encrypted = row.encrypted_value as string;\n const decrypted = decryptAppSecretValue(\n encrypted,\n row.shared_encrypted_value as string | null,\n );\n if (decrypted.needsSharedCiphertext) {\n await populateSharedAppSecret(\n row.id,\n decrypted.value,\n decrypted.sharedCiphertextToReplace ?? null,\n );\n }\n last4Value = last4(decrypted.value);\n } catch {\n last4Value = \"\";\n }\n results.push({\n key: row.key as string,\n scope,\n scopeId,\n last4: last4Value,\n description: (row.description as string | null) ?? null,\n urlAllowlist: parseAllowlist(row.url_allowlist as string | null),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n });\n }\n return results;\n}\n\nfunction parseAllowlist(raw: string | null): string[] | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed) && parsed.every((v) => typeof v === \"string\")) {\n return parsed;\n }\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function deleteAppSecret(ref: SecretRef): Promise<boolean> {\n await ensureTable();\n const { key, scope, scopeId } = ref;\n const client = getDbExec();\n const { rowsAffected } = await client.execute({\n sql: `DELETE FROM app_secrets WHERE scope = ? AND scope_id = ? AND key = ?`,\n args: [scope, scopeId, key],\n });\n return rowsAffected > 0;\n}\n"]}