@agent-native/core 0.132.2 → 0.133.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +181 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/a2a/correlation.ts +11 -1
- package/corpus/core/src/a2a/types.ts +11 -3
- package/corpus/core/src/agent/engine/ai-sdk-engine.ts +61 -46
- package/corpus/core/src/agent/engine/builder-engine.ts +22 -10
- package/corpus/core/src/agent/engine/error-detail.ts +184 -3
- package/corpus/core/src/agent/engine/failure-taxonomy.ts +123 -0
- package/corpus/core/src/agent/engine/index.ts +8 -0
- package/corpus/core/src/agent/engine/registry.ts +92 -8
- package/corpus/core/src/agent/engine/translate-ai-sdk.ts +17 -2
- package/corpus/core/src/agent/production-agent.ts +13 -33
- package/corpus/core/src/agent/run-loop-with-resume.ts +1 -1
- package/corpus/core/src/agent/run-manager.ts +43 -14
- package/corpus/core/src/agent/run-store.ts +49 -7
- package/corpus/core/src/agent/thread-data-builder.ts +36 -4
- package/corpus/core/src/cli/templates-meta.ts +13 -0
- package/corpus/core/src/cli/workspace-dev.ts +1 -0
- package/corpus/core/src/client/error-format.ts +12 -0
- package/corpus/core/src/credentials/index.ts +51 -12
- package/corpus/core/src/extensions/url-safety.ts +46 -12
- package/corpus/core/src/integrations/adapters/slack.ts +32 -10
- package/corpus/core/src/integrations/google-docs-poller.ts +12 -1
- package/corpus/core/src/integrations/installations-store.ts +30 -0
- package/corpus/core/src/integrations/plugin.ts +5 -5
- package/corpus/core/src/integrations/types.ts +7 -0
- package/corpus/core/src/integrations/webhook-handler.ts +24 -1
- package/corpus/core/src/jobs/background-automation-runner.ts +38 -1
- package/corpus/core/src/provider-api/index.ts +8 -2
- package/corpus/core/src/scripts/call-agent.ts +6 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +30 -9
- package/corpus/core/src/server/agent-discovery.ts +2 -0
- package/corpus/core/src/server/builder-design-systems.ts +21 -0
- package/corpus/core/src/server/credential-provider.ts +51 -12
- package/corpus/core/src/server/index.ts +1 -0
- package/corpus/core/src/server/onboarding-html.ts +37 -2
- package/corpus/core/src/shared/reasoning-effort.ts +1 -1
- package/corpus/core/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +6 -2
- package/corpus/templates/assets/app/components/layout/Sidebar.tsx +39 -19
- package/corpus/templates/assets/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/brain/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/brain/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/calendar/app/components/layout/AppLayout.tsx +1 -1
- package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +54 -25
- package/corpus/templates/calendar/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/clips/app/components/library/library-layout.tsx +37 -21
- package/corpus/templates/clips/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/clips/desktop/src/hooks/useMediaDevices.ts +1 -1
- package/corpus/templates/clips/desktop/src/lib/media-capture-constraints.ts +1 -1
- package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +34 -17
- package/corpus/templates/content/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +6 -2
- package/corpus/templates/design/actions/create-design-system.ts +1 -0
- package/corpus/templates/design/actions/set-default-design-system.ts +34 -26
- package/corpus/templates/design/app/components/layout/Sidebar.tsx +21 -4
- package/corpus/templates/design/app/i18n-data.ts +39 -0
- package/corpus/templates/design/app/pages/DesignSystemSetup.tsx +229 -12
- package/corpus/templates/design/app/pages/DesignSystems.tsx +10 -4
- package/corpus/templates/design/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/design/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
- package/corpus/templates/design/server/lib/builder-design-system-proxy.ts +19 -4
- package/corpus/templates/dispatch/AGENTS.md +4 -0
- package/corpus/templates/factory/.agents/skills/actions/SKILL.md +562 -0
- package/corpus/templates/factory/.agents/skills/adding-a-feature/SKILL.md +198 -0
- package/corpus/templates/factory/.agents/skills/agent-native-docs/SKILL.md +115 -0
- package/corpus/templates/factory/.agents/skills/agent-native-toolkit/SKILL.md +182 -0
- package/corpus/templates/factory/.agents/skills/capture-learnings/SKILL.md +89 -0
- package/corpus/templates/factory/.agents/skills/create-skill/SKILL.md +221 -0
- package/corpus/templates/factory/.agents/skills/customizing-agent-native/SKILL.md +220 -0
- package/corpus/templates/factory/.agents/skills/delegate-to-agent/SKILL.md +263 -0
- package/corpus/templates/factory/.agents/skills/factory-graphs/SKILL.md +52 -0
- package/corpus/templates/factory/.agents/skills/feature-flags/SKILL.md +169 -0
- package/corpus/templates/factory/.agents/skills/frontend-design/SKILL.md +174 -0
- package/corpus/templates/factory/.agents/skills/real-time-sync/SKILL.md +232 -0
- package/corpus/templates/factory/.agents/skills/security/SKILL.md +324 -0
- package/corpus/templates/factory/.agents/skills/self-modifying-code/SKILL.md +119 -0
- package/corpus/templates/factory/.agents/skills/shadcn-ui/SKILL.md +123 -0
- package/corpus/templates/factory/.agents/skills/sharing/SKILL.md +232 -0
- package/corpus/templates/factory/.agents/skills/storing-data/SKILL.md +178 -0
- package/corpus/templates/factory/.agents/skills/upgrade-agent-native/SKILL.md +122 -0
- package/corpus/templates/factory/.env.example +24 -0
- package/corpus/templates/factory/.ignore +0 -0
- package/corpus/templates/factory/.oxfmtrc.json +8 -0
- package/corpus/templates/factory/AGENTS.md +90 -0
- package/corpus/templates/factory/CHANGELOG.md +10 -0
- package/corpus/templates/factory/DEVELOPING.md +185 -0
- package/corpus/templates/factory/README.md +64 -0
- package/corpus/templates/factory/_gitignore +42 -0
- package/corpus/templates/factory/actions/add-factory-comment.ts +55 -0
- package/corpus/templates/factory/actions/approve-factory-item.ts +214 -0
- package/corpus/templates/factory/actions/babysit-pull-request.ts +126 -0
- package/corpus/templates/factory/actions/evaluate-triage-item.ts +172 -0
- package/corpus/templates/factory/actions/get-factory-graph.ts +62 -0
- package/corpus/templates/factory/actions/get-triage-config.ts +42 -0
- package/corpus/templates/factory/actions/get-triage-item.ts +74 -0
- package/corpus/templates/factory/actions/hello.ts +13 -0
- package/corpus/templates/factory/actions/ingest-github-observation.ts +100 -0
- package/corpus/templates/factory/actions/list-factories.ts +40 -0
- package/corpus/templates/factory/actions/list-factory-comments.ts +40 -0
- package/corpus/templates/factory/actions/list-triage-items.ts +85 -0
- package/corpus/templates/factory/actions/list-triage-rules.ts +44 -0
- package/corpus/templates/factory/actions/navigate.ts +41 -0
- package/corpus/templates/factory/actions/poll-slack-channel.ts +118 -0
- package/corpus/templates/factory/actions/reconcile-triage-run.ts +179 -0
- package/corpus/templates/factory/actions/record-triage-feedback.ts +58 -0
- package/corpus/templates/factory/actions/run.ts +2 -0
- package/corpus/templates/factory/actions/save-factory-graph.ts +129 -0
- package/corpus/templates/factory/actions/save-triage-config.ts +67 -0
- package/corpus/templates/factory/actions/save-triage-rule.ts +89 -0
- package/corpus/templates/factory/actions/suggest-factory-rules.ts +70 -0
- package/corpus/templates/factory/actions/view-screen.ts +73 -0
- package/corpus/templates/factory/app/components/factory/FactoryCanvas.tsx +441 -0
- package/corpus/templates/factory/app/components/factory/FactoryInspector.tsx +388 -0
- package/corpus/templates/factory/app/components/layout/Header.tsx +60 -0
- package/corpus/templates/factory/app/components/layout/Layout.tsx +190 -0
- package/corpus/templates/factory/app/components/layout/Sidebar.tsx +538 -0
- package/corpus/templates/factory/app/components/triage/triage-status-pill.tsx +28 -0
- package/corpus/templates/factory/app/components/ui/button.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/card.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/dropdown-menu.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/input.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/label.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/sheet.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/textarea.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/toolkit-provider.tsx +17 -0
- package/corpus/templates/factory/app/components/ui/tooltip.tsx +1 -0
- package/corpus/templates/factory/app/design-system.ts +3 -0
- package/corpus/templates/factory/app/entry.client.tsx +22 -0
- package/corpus/templates/factory/app/entry.server.tsx +10 -0
- package/corpus/templates/factory/app/global.css +93 -0
- package/corpus/templates/factory/app/hooks/use-navigation-state.ts +113 -0
- package/corpus/templates/factory/app/i18n/en-US.ts +211 -0
- package/corpus/templates/factory/app/i18n/index.ts +34 -0
- package/corpus/templates/factory/app/i18n-data.ts +556 -0
- package/corpus/templates/factory/app/lib/agent-page.tsx +49 -0
- package/corpus/templates/factory/app/lib/app-config.ts +11 -0
- package/corpus/templates/factory/app/lib/tab-id.ts +1 -0
- package/corpus/templates/factory/app/lib/utils.ts +1 -0
- package/corpus/templates/factory/app/root.tsx +175 -0
- package/corpus/templates/factory/app/routes/_index.tsx +94 -0
- package/corpus/templates/factory/app/routes/agent.tsx +24 -0
- package/corpus/templates/factory/app/routes/chat.$threadId.tsx +1 -0
- package/corpus/templates/factory/app/routes/database.tsx +17 -0
- package/corpus/templates/factory/app/routes/extensions.$id.$slug.tsx +2 -0
- package/corpus/templates/factory/app/routes/extensions.$id.tsx +11 -0
- package/corpus/templates/factory/app/routes/extensions._index.tsx +11 -0
- package/corpus/templates/factory/app/routes/extensions.tsx +5 -0
- package/corpus/templates/factory/app/routes/factory.tsx +1003 -0
- package/corpus/templates/factory/app/routes/observability.tsx +19 -0
- package/corpus/templates/factory/app/routes/settings.tsx +89 -0
- package/corpus/templates/factory/app/routes/team.tsx +11 -0
- package/corpus/templates/factory/app/routes.ts +4 -0
- package/corpus/templates/factory/app/vite-env.d.ts +6 -0
- package/corpus/templates/factory/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-27-traditional-chinese-copy-uses-taiwan-terminology.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-28-left-sidebar-collapse-motion-and-footer-chrome-are-quieter.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-29-chat-layouts-adapt-when-the-agent-sidebar-is-open.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-08-settings-are-cleaner-and-searchable.md +5 -0
- package/corpus/templates/factory/changelog/2026-07-10-chat-now-makes-ai-connection-setup-clear-without-shifting-th.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-13-a-full-agent-page-now-brings-context-files-connections-jobs-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-14-chat-opens-reliably-on-hosted-deployments-instead-of-failing.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-14-fixed-chat-template-startup-with-older-core-versions.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-15-chat-navigation-focuses-on-chat-and-agent.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-17-the-agent-chat-sidebar-stays-closed-until-you-open-it-or-sta.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-compact-sidebar-footer.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-full-page-chat-keeps-the-active-conversation-when-moving-to-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-recent-chats-are-easier-to-scan-and-expand.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-23-full-page-chat-is-better-centered-with-quieter-chat-history-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-24-borderless-secondary-surfaces.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-24-sidebar-footer-controls-follow-a-consistent-order.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-29-sidebar-footers-now-keep-feedback-search-and-collapse-togeth.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-31-added-an-inspectable-observe-only-factory-queue-for-slack-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/factory/components.json +20 -0
- package/corpus/templates/factory/data/sync-config.json +1 -0
- package/corpus/templates/factory/learnings.defaults.md +5 -0
- package/corpus/templates/factory/netlify.toml +10 -0
- package/corpus/templates/factory/package.json +105 -0
- package/corpus/templates/factory/public/agent-native-icon-dark.svg +10 -0
- package/corpus/templates/factory/public/agent-native-icon-light.svg +10 -0
- package/corpus/templates/factory/public/agent-native-logo-dark.svg +21 -0
- package/corpus/templates/factory/public/agent-native-logo-light.svg +21 -0
- package/corpus/templates/factory/public/favicon.svg +1 -0
- package/corpus/templates/factory/public/icon-180.svg +1 -0
- package/corpus/templates/factory/public/icon-192.svg +1 -0
- package/corpus/templates/factory/public/icon-512.svg +1 -0
- package/corpus/templates/factory/public/manifest.json +21 -0
- package/corpus/templates/factory/react-router.config.ts +7 -0
- package/corpus/templates/factory/server/connectors/credentials.ts +129 -0
- package/corpus/templates/factory/server/connectors/slack.ts +129 -0
- package/corpus/templates/factory/server/db/index.ts +6 -0
- package/corpus/templates/factory/server/db/schema.ts +193 -0
- package/corpus/templates/factory/server/factory-graph/contracts.ts +212 -0
- package/corpus/templates/factory/server/factory-graph/store.ts +121 -0
- package/corpus/templates/factory/server/lib/require-workspace-member.ts +55 -0
- package/corpus/templates/factory/server/middleware/auth.ts +15 -0
- package/corpus/templates/factory/server/plugins/agent-chat.ts +58 -0
- package/corpus/templates/factory/server/plugins/auth.ts +14 -0
- package/corpus/templates/factory/server/plugins/factory-migrations.ts +247 -0
- package/corpus/templates/factory/server/plugins/factory-scheduler-job.ts +116 -0
- package/corpus/templates/factory/server/plugins/integrations.ts +46 -0
- package/corpus/templates/factory/server/routes/[...page].get.ts +5 -0
- package/corpus/templates/factory/server/routes/_agent-native/factory/builder-callback.post.ts +116 -0
- package/corpus/templates/factory/server/triage/ai-services-git.ts +197 -0
- package/corpus/templates/factory/server/triage/builder-executor.ts +118 -0
- package/corpus/templates/factory/server/triage/contracts.ts +164 -0
- package/corpus/templates/factory/server/triage/github-ingestion.ts +35 -0
- package/corpus/templates/factory/server/triage/guards.ts +121 -0
- package/corpus/templates/factory/server/triage/ids.ts +27 -0
- package/corpus/templates/factory/server/triage/pr-babysit.ts +100 -0
- package/corpus/templates/factory/server/triage/pr-monitor.ts +220 -0
- package/corpus/templates/factory/server/triage/slack-client.ts +55 -0
- package/corpus/templates/factory/server/triage/slack-poller.ts +152 -0
- package/corpus/templates/factory/ssr-entry.ts +15 -0
- package/corpus/templates/factory/tsconfig.json +21 -0
- package/corpus/templates/factory/vite.config.ts +19 -0
- package/corpus/templates/forms/app/components/layout/Sidebar.tsx +55 -5
- package/corpus/templates/forms/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/macros/app/components/layout/AppLayout.tsx +6 -2
- package/corpus/templates/plan/app/components/layout/Sidebar.tsx +21 -6
- package/corpus/templates/plan/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/slides/.agents/skills/create-deck/SKILL.md +12 -0
- package/corpus/templates/slides/.agents/skills/design-systems/SKILL.md +9 -0
- package/corpus/templates/slides/.agents/skills/slide-editing/SKILL.md +11 -0
- package/corpus/templates/slides/AGENTS.md +5 -6
- package/corpus/templates/slides/actions/_await-fit-check.ts +20 -10
- package/corpus/templates/slides/actions/add-slide.ts +17 -4
- package/corpus/templates/slides/actions/create-design-system.ts +16 -4
- package/corpus/templates/slides/actions/delete-design-system.ts +18 -2
- package/corpus/templates/slides/actions/get-layout-overflows.ts +88 -0
- package/corpus/templates/slides/actions/import-file.ts +1 -0
- package/corpus/templates/slides/actions/index-design-system-with-builder.ts +8 -0
- package/corpus/templates/slides/actions/patch-deck.ts +48 -16
- package/corpus/templates/slides/actions/set-default-design-system.ts +49 -19
- package/corpus/templates/slides/actions/update-slide.ts +13 -3
- package/corpus/templates/slides/actions/view-screen.ts +87 -10
- package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +155 -28
- package/corpus/templates/slides/app/components/design-system/DesignSystemCard.tsx +21 -17
- package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +849 -341
- package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +102 -2
- package/corpus/templates/slides/app/components/editor/PromptDialog.tsx +13 -16
- package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +60 -12
- package/corpus/templates/slides/app/components/editor/SlideOverflowWarning.tsx +11 -1
- package/corpus/templates/slides/app/components/layout/Sidebar.tsx +66 -19
- package/corpus/templates/slides/app/i18n/en-US.ts +23 -0
- package/corpus/templates/slides/app/lib/normalize-slide-padding.ts +8 -15
- package/corpus/templates/slides/app/pages/DeckEditor.tsx +4 -3
- package/corpus/templates/slides/app/pages/DesignSystems.tsx +4 -3
- package/corpus/templates/slides/app/pages/Index.tsx +1 -1
- package/corpus/templates/slides/changelog/2026-07-31-design-system-details-now-show-their-source-and-indexing-sta.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-design-system-setup-keeps-focus-rings-visible-and-uses-a-sim.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-skip-prompt-is-now-available-in-the-new-deck-prompt-header.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-slides-now-detect-real-text-and-box-overflow-across-the-deck.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/slides/server/handlers/design-systems.ts +1 -0
- package/corpus/templates/slides/server/handlers/index-design-system-sources.ts +1 -0
- package/corpus/templates/slides/server/lib/builder-design-system-proxy.ts +23 -4
- package/corpus/templates/slides/server/plugins/agent-chat.ts +5 -0
- package/corpus/templates/slides/server/plugins/creative-context.ts +16 -3
- package/corpus/templates/slides/server/workspace-defaults.ts +5 -1
- package/corpus/templates/slides/shared/slide-fit.ts +26 -0
- package/corpus/templates/tasks/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/tasks/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/dist/a2a/correlation.d.ts +4 -1
- package/dist/a2a/correlation.d.ts.map +1 -1
- package/dist/a2a/correlation.js +8 -1
- package/dist/a2a/correlation.js.map +1 -1
- package/dist/a2a/types.d.ts +11 -3
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.js +51 -41
- package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
- package/dist/agent/engine/builder-engine.d.ts.map +1 -1
- package/dist/agent/engine/builder-engine.js +18 -8
- package/dist/agent/engine/builder-engine.js.map +1 -1
- package/dist/agent/engine/error-detail.d.ts +61 -0
- package/dist/agent/engine/error-detail.d.ts.map +1 -1
- package/dist/agent/engine/error-detail.js +145 -3
- package/dist/agent/engine/error-detail.js.map +1 -1
- package/dist/agent/engine/failure-taxonomy.d.ts +24 -0
- package/dist/agent/engine/failure-taxonomy.d.ts.map +1 -0
- package/dist/agent/engine/failure-taxonomy.js +88 -0
- package/dist/agent/engine/failure-taxonomy.js.map +1 -0
- package/dist/agent/engine/index.d.ts +2 -1
- package/dist/agent/engine/index.d.ts.map +1 -1
- package/dist/agent/engine/index.js +2 -1
- package/dist/agent/engine/index.js.map +1 -1
- package/dist/agent/engine/registry.d.ts +16 -0
- package/dist/agent/engine/registry.d.ts.map +1 -1
- package/dist/agent/engine/registry.js +71 -6
- package/dist/agent/engine/registry.js.map +1 -1
- package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -1
- package/dist/agent/engine/translate-ai-sdk.js +14 -2
- package/dist/agent/engine/translate-ai-sdk.js.map +1 -1
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +13 -24
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-loop-with-resume.js +1 -1
- package/dist/agent/run-loop-with-resume.js.map +1 -1
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +39 -10
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/run-store.d.ts +10 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +38 -6
- package/dist/agent/run-store.js.map +1 -1
- package/dist/agent/thread-data-builder.d.ts.map +1 -1
- package/dist/agent/thread-data-builder.js +28 -4
- package/dist/agent/thread-data-builder.js.map +1 -1
- package/dist/cli/templates-meta.d.ts.map +1 -1
- package/dist/cli/templates-meta.js +13 -0
- package/dist/cli/templates-meta.js.map +1 -1
- package/dist/cli/workspace-dev.d.ts.map +1 -1
- package/dist/cli/workspace-dev.js +1 -0
- package/dist/cli/workspace-dev.js.map +1 -1
- package/dist/client/error-format.d.ts.map +1 -1
- package/dist/client/error-format.js +10 -0
- package/dist/client/error-format.js.map +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/credentials/index.d.ts +9 -2
- package/dist/credentials/index.d.ts.map +1 -1
- package/dist/credentials/index.js +50 -8
- package/dist/credentials/index.js.map +1 -1
- package/dist/extensions/url-safety.d.ts.map +1 -1
- package/dist/extensions/url-safety.js +38 -12
- package/dist/extensions/url-safety.js.map +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +25 -8
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/integrations/google-docs-poller.d.ts.map +1 -1
- package/dist/integrations/google-docs-poller.js +13 -1
- package/dist/integrations/google-docs-poller.js.map +1 -1
- package/dist/integrations/installations-store.d.ts +10 -0
- package/dist/integrations/installations-store.d.ts.map +1 -1
- package/dist/integrations/installations-store.js +24 -0
- package/dist/integrations/installations-store.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +6 -5
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/integrations/types.d.ts +7 -0
- package/dist/integrations/types.d.ts.map +1 -1
- package/dist/integrations/types.js.map +1 -1
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +16 -1
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/jobs/background-automation-runner.d.ts.map +1 -1
- package/dist/jobs/background-automation-runner.js +35 -2
- package/dist/jobs/background-automation-runner.js.map +1 -1
- package/dist/mcp/screen-memory-stdio.d.ts +7 -7
- package/dist/mcp/screen-memory-stdio.d.ts.map +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/observability/routes.d.ts +1 -1
- package/dist/provider-api/actions/custom-provider-registration.d.ts +14 -14
- package/dist/provider-api/actions/provider-api.d.ts +8 -8
- package/dist/provider-api/index.js +7 -3
- package/dist/provider-api/index.js.map +1 -1
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/scripts/call-agent.d.ts.map +1 -1
- package/dist/scripts/call-agent.js +6 -1
- package/dist/scripts/call-agent.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +25 -7
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-discovery.d.ts +2 -0
- package/dist/server/agent-discovery.d.ts.map +1 -1
- package/dist/server/agent-discovery.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/builder-design-systems.d.ts +4 -1
- package/dist/server/builder-design-systems.d.ts.map +1 -1
- package/dist/server/builder-design-systems.js +11 -1
- package/dist/server/builder-design-systems.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +49 -12
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +37 -2
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/shared/reasoning-effort.d.ts +1 -0
- package/dist/shared/reasoning-effort.d.ts.map +1 -1
- package/dist/shared/reasoning-effort.js +1 -1
- package/dist/shared/reasoning-effort.js.map +1 -1
- package/dist/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/dist/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/dist/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/package.json +1 -1
- package/src/a2a/correlation.ts +11 -1
- package/src/a2a/types.ts +11 -3
- package/src/agent/engine/ai-sdk-engine.ts +61 -46
- package/src/agent/engine/builder-engine.ts +22 -10
- package/src/agent/engine/error-detail.ts +184 -3
- package/src/agent/engine/failure-taxonomy.ts +123 -0
- package/src/agent/engine/index.ts +8 -0
- package/src/agent/engine/registry.ts +92 -8
- package/src/agent/engine/translate-ai-sdk.ts +17 -2
- package/src/agent/production-agent.ts +13 -33
- package/src/agent/run-loop-with-resume.ts +1 -1
- package/src/agent/run-manager.ts +43 -14
- package/src/agent/run-store.ts +49 -7
- package/src/agent/thread-data-builder.ts +36 -4
- package/src/cli/templates-meta.ts +13 -0
- package/src/cli/workspace-dev.ts +1 -0
- package/src/client/error-format.ts +12 -0
- package/src/credentials/index.ts +51 -12
- package/src/extensions/url-safety.ts +46 -12
- package/src/integrations/adapters/slack.ts +32 -10
- package/src/integrations/google-docs-poller.ts +12 -1
- package/src/integrations/installations-store.ts +30 -0
- package/src/integrations/plugin.ts +5 -5
- package/src/integrations/types.ts +7 -0
- package/src/integrations/webhook-handler.ts +24 -1
- package/src/jobs/background-automation-runner.ts +38 -1
- package/src/provider-api/index.ts +8 -2
- package/src/scripts/call-agent.ts +6 -0
- package/src/server/agent-chat-plugin.ts +30 -9
- package/src/server/agent-discovery.ts +2 -0
- package/src/server/builder-design-systems.ts +21 -0
- package/src/server/credential-provider.ts +51 -12
- package/src/server/index.ts +1 -0
- package/src/server/onboarding-html.ts +37 -2
- package/src/shared/reasoning-effort.ts +1 -1
- package/src/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/src/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/corpus/templates/clips/desktop/src/lib/media-device-selection.ts +0 -157
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-format.js","sourceRoot":"","sources":["../../src/client/error-format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,gIAAgI,CAAC;AAEnI,8EAA8E;AAC9E,6EAA6E;AAC7E,iFAAiF;AACjF,MAAM,CAAC,MAAM,oBAAoB,GAAG,uBAAuB,CAAC;AAE5D,SAAS,gBAAgB,CAAC,GAAW;IACnC,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ;YAAE,OAAO,KAAK,CAAC;QAC/C,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC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AC;AACZ,CAAC","sourcesContent":["/**\n * Append a Builder CTA markdown link to gateway errors that users can fix\n * outside the app. Used by both\n * chat SSE consumers (`sse-event-processor.ts` and `useProductionAgent.ts`)\n * to keep the copy in lockstep.\n *\n * `upgradeUrl` comes from the gateway response body and ends up interpolated\n * into markdown, so we validate it's a plain https URL with no characters\n * that would escape the `[...](url)` link target. Only `)` and whitespace\n * terminate the link target — `(`, `<`, `>` are fine inside it — so the\n * regex stays narrow; the gateway may emit URLs containing `(`\n * (e.g. `?ref=Acme%20(staging)`) and we don't want to reject them.\n */\nexport const BUILDER_SPACE_SETTINGS_URL =\n \"https://builder.io/account/space?utm_source=agent-native&utm_medium=product&utm_campaign=onboarding&utm_content=space_settings\";\n\n// Pseudo-href used to mark an in-app \"Start new chat\" CTA inside the markdown\n// error message. The chat renderer intercepts this href and renders a button\n// that dispatches the `agent-native:new-chat` CustomEvent instead of navigating.\nexport const NEW_CHAT_ACTION_HREF = \"agent-native:new-chat\";\n\nfunction isSafeUpgradeUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"https:\") return false;\n return !/[\\s)]/.test(url);\n } catch {\n return false;\n }\n}\n\nexport function formatChatErrorText(\n errorMessage: string,\n upgradeUrl?: string,\n errorCode?: string,\n): string {\n const normalized = normalizeChatError(errorMessage, errorCode);\n if (\n errorCode === \"gateway_not_enabled\" ||\n /space has not enabled the LLM gateway/i.test(normalized.message)\n ) {\n return `Error: ${normalized.message}\\n\\n[Open Builder space settings](${BUILDER_SPACE_SETTINGS_URL})`;\n }\n if (errorCode === \"builder_gateway_error\") {\n return `Error: ${normalized.message}\\n\\n[Start new chat](${NEW_CHAT_ACTION_HREF})`;\n }\n if (\n errorCode === \"context_length_exceeded\" ||\n errorCode === \"input_too_long\"\n ) {\n return `Error: ${normalized.message}\\n\\n[Start new chat](${NEW_CHAT_ACTION_HREF})`;\n }\n if (!upgradeUrl || !isSafeUpgradeUrl(upgradeUrl)) {\n return `Error: ${normalized.message}`;\n }\n return `Error: ${normalized.message}\\n\\n[Upgrade at builder.io](${upgradeUrl})`;\n}\n\nexport interface NormalizedChatError {\n message: string;\n details?: string;\n}\n\nfunction normalizeErrorCode(errorCode?: string): string {\n return String(errorCode ?? \"\")\n .trim()\n .toLowerCase();\n}\n\nfunction isProviderRateLimit(text: string, errorCode?: string): boolean {\n const code = normalizeErrorCode(errorCode);\n return (\n code === \"provider_rate_limited\" ||\n code === \"http_429\" ||\n code === \"rate_limited\" ||\n code === \"rate_limit_exceeded\" ||\n /^429 status code(?:\\s*\\(no body\\))?$/i.test(text) ||\n /\\b(?:http\\s*)?429\\b.*\\b(?:status|too many requests|rate[-_\\s]?limit|no body)\\b/i.test(\n text,\n ) ||\n /\\b(?:too many requests|rate[-_\\s]?limit(?:ed| exceeded)?)\\b/i.test(text)\n );\n}\n\nfunction isProviderAuthenticationError(\n text: string,\n errorCode?: string,\n): boolean {\n const code = normalizeErrorCode(errorCode);\n const lower = text.toLowerCase();\n return (\n code === \"authentication_error\" ||\n code === \"http_401\" ||\n /^401 status code(?:\\s*\\(no body\\))?$/i.test(text) ||\n /\\b(?:http\\s*)?401\\b.*\\b(?:status|unauthorized|authentication|auth|no body)\\b/i.test(\n text,\n ) ||\n lower.includes(\"invalid x-api-key\") ||\n lower.includes(\"invalid api key\") ||\n lower.includes(\"incorrect api key\") ||\n lower.includes(\"api key is invalid\") ||\n (lower.includes(\"authentication_error\") && lower.includes(\"api\"))\n );\n}\n\nfunction isConnectionError(text: string, errorCode?: string): boolean {\n const code = normalizeErrorCode(errorCode);\n return (\n code === \"provider_network_error\" ||\n code === \"connection_error\" ||\n code === \"network_error\" ||\n /^(?:provider_network_error|connection_error|network_error)$/i.test(\n text.trim(),\n )\n );\n}\n\nexport function normalizeChatError(\n errorMessage: string,\n errorCode?: string,\n): NormalizedChatError {\n const raw = String(errorMessage || \"Unknown error\");\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(raw);\n const text = looksHtml ? htmlToText(raw) : raw.trim();\n\n const code = normalizeErrorCode(errorCode);\n\n if (code === \"builder_model_unauthorized\") {\n return {\n message:\n \"The provider behind this model rejected the request. Pick a different model, then retry.\",\n details: text,\n };\n }\n\n if (code === \"builder_auth_error\") {\n return {\n message:\n \"Builder rejected the connected credentials. Reconnect Builder.io in Settings, then retry.\",\n details: text,\n };\n }\n\n if (isProviderRateLimit(text, errorCode)) {\n return {\n message:\n \"The model provider is rate-limiting this chat right now. Wait a moment, then retry.\",\n details: text,\n };\n }\n\n if (isProviderAuthenticationError(text, errorCode)) {\n return {\n message:\n \"The model provider rejected the saved API key. Update the key in API Keys & Connections, then retry.\",\n details: text,\n };\n }\n\n if (isConnectionError(text, errorCode)) {\n const providerNetworkError =\n normalizeErrorCode(errorCode) === \"provider_network_error\" ||\n /provider_network_error/i.test(text);\n return {\n message: providerNetworkError\n ? \"The model provider could not be reached. Check your connection and retry.\"\n : \"The agent connection was interrupted. Check your connection and retry.\",\n details: text,\n };\n }\n\n if (/^Gateway error \\(no detail; raw event:/i.test(text)) {\n // The previous copy promised auto-recovery and suggested switching models,\n // but neither helps for this code: the server already retried once and\n // the client deliberately skips auto-continuation\n // (see `builder_gateway_error` in sse-event-processor.ts). The error is\n // almost always upstream, so retrying the same conversation with a\n // different model lands on the same wall.\n return {\n message:\n \"The model gateway returned no error details and the chat couldn't recover. Wait a moment and retry, or start a new chat if it keeps happening.\",\n details: text,\n };\n }\n\n if (/inactivity timeout/i.test(text)) {\n return {\n message:\n \"The agent connection timed out before it could finish. You can continue from the partial work or retry.\",\n details: text,\n };\n }\n\n if (/Invalid request body:\\s*tools\\.\\d+\\.input_schema\\.type/i.test(text)) {\n return {\n message:\n \"A tool schema was invalid, so the model rejected the request before it started. The invalid tool can be skipped and the request retried.\",\n details: text,\n };\n }\n\n if (looksHtml) {\n return {\n message:\n text.slice(0, 240) || \"The provider returned an HTML error page.\",\n details: text,\n };\n }\n\n return { message: text };\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-format.js","sourceRoot":"","sources":["../../src/client/error-format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,gIAAgI,CAAC;AAEnI,8EAA8E;AAC9E,6EAA6E;AAC7E,iFAAiF;AACjF,MAAM,CAAC,MAAM,oBAAoB,GAAG,uBAAuB,CAAC;AAE5D,SAAS,gBAAgB,CAAC,GAAW;IACnC,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ;YAAE,OAAO,KAAK,CAAC;QAC/C,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,YAAoB,EACpB,UAAmB,EACnB,SAAkB;IAElB,MAAM,UAAU,GAAG,kBAAkB,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC;IAC/D,IACE,SAAS,KAAK,qBAAqB;QACnC,wCAAwC,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,EACjE,CAAC;QACD,OAAO,U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OAAO;YACL,OAAO,EACL,yGAAyG;YAC3G,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;IAED,IAAI,yDAAyD,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACzE,OAAO;YACL,OAAO,EACL,0IAA0I;YAC5I,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;IAED,IAAI,SAAS,EAAE,CAAC;QACd,OAAO;YACL,OAAO,EACL,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,2CAA2C;YACnE,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI;SACR,OAAO,CAAC,6BAA6B,EAAE,GAAG,CAAC;SAC3C,OAAO,CAAC,2BAA2B,EAAE,GAAG,CAAC;SACzC,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC;SAC7B,OAAO,CAAC,8BAA8B,EAAE,IAAI,CAAC;SAC7C,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC;SAC1B,IAAI,EAAE,CAAC;AACZ,CAAC","sourcesContent":["/**\n * Append a Builder CTA markdown link to gateway errors that users can fix\n * outside the app. Used by both\n * chat SSE consumers (`sse-event-processor.ts` and `useProductionAgent.ts`)\n * to keep the copy in lockstep.\n *\n * `upgradeUrl` comes from the gateway response body and ends up interpolated\n * into markdown, so we validate it's a plain https URL with no characters\n * that would escape the `[...](url)` link target. Only `)` and whitespace\n * terminate the link target — `(`, `<`, `>` are fine inside it — so the\n * regex stays narrow; the gateway may emit URLs containing `(`\n * (e.g. `?ref=Acme%20(staging)`) and we don't want to reject them.\n */\nexport const BUILDER_SPACE_SETTINGS_URL =\n \"https://builder.io/account/space?utm_source=agent-native&utm_medium=product&utm_campaign=onboarding&utm_content=space_settings\";\n\n// Pseudo-href used to mark an in-app \"Start new chat\" CTA inside the markdown\n// error message. The chat renderer intercepts this href and renders a button\n// that dispatches the `agent-native:new-chat` CustomEvent instead of navigating.\nexport const NEW_CHAT_ACTION_HREF = \"agent-native:new-chat\";\n\nfunction isSafeUpgradeUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"https:\") return false;\n return !/[\\s)]/.test(url);\n } catch {\n return false;\n }\n}\n\nexport function formatChatErrorText(\n errorMessage: string,\n upgradeUrl?: string,\n errorCode?: string,\n): string {\n const normalized = normalizeChatError(errorMessage, errorCode);\n if (\n errorCode === \"gateway_not_enabled\" ||\n /space has not enabled the LLM gateway/i.test(normalized.message)\n ) {\n return `Error: ${normalized.message}\\n\\n[Open Builder space settings](${BUILDER_SPACE_SETTINGS_URL})`;\n }\n if (errorCode === \"builder_gateway_error\") {\n return `Error: ${normalized.message}\\n\\n[Start new chat](${NEW_CHAT_ACTION_HREF})`;\n }\n if (\n errorCode === \"context_length_exceeded\" ||\n errorCode === \"input_too_long\"\n ) {\n return `Error: ${normalized.message}\\n\\n[Start new chat](${NEW_CHAT_ACTION_HREF})`;\n }\n if (!upgradeUrl || !isSafeUpgradeUrl(upgradeUrl)) {\n return `Error: ${normalized.message}`;\n }\n return `Error: ${normalized.message}\\n\\n[Upgrade at builder.io](${upgradeUrl})`;\n}\n\nexport interface NormalizedChatError {\n message: string;\n details?: string;\n}\n\nfunction normalizeErrorCode(errorCode?: string): string {\n return String(errorCode ?? \"\")\n .trim()\n .toLowerCase();\n}\n\nfunction isProviderRateLimit(text: string, errorCode?: string): boolean {\n const code = normalizeErrorCode(errorCode);\n return (\n code === \"provider_rate_limited\" ||\n code === \"http_429\" ||\n code === \"rate_limited\" ||\n code === \"rate_limit_exceeded\" ||\n /^429 status code(?:\\s*\\(no body\\))?$/i.test(text) ||\n /\\b(?:http\\s*)?429\\b.*\\b(?:status|too many requests|rate[-_\\s]?limit|no body)\\b/i.test(\n text,\n ) ||\n /\\b(?:too many requests|rate[-_\\s]?limit(?:ed| exceeded)?)\\b/i.test(text)\n );\n}\n\nfunction isProviderAuthenticationError(\n text: string,\n errorCode?: string,\n): boolean {\n const code = normalizeErrorCode(errorCode);\n const lower = text.toLowerCase();\n return (\n code === \"authentication_error\" ||\n code === \"http_401\" ||\n /^401 status code(?:\\s*\\(no body\\))?$/i.test(text) ||\n /\\b(?:http\\s*)?401\\b.*\\b(?:status|unauthorized|authentication|auth|no body)\\b/i.test(\n text,\n ) ||\n lower.includes(\"missing authentication header\") ||\n lower.includes(\"invalid x-api-key\") ||\n lower.includes(\"invalid api key\") ||\n lower.includes(\"incorrect api key\") ||\n lower.includes(\"api key is invalid\") ||\n (lower.includes(\"authentication_error\") && lower.includes(\"api\"))\n );\n}\n\nfunction isConnectionError(text: string, errorCode?: string): boolean {\n const code = normalizeErrorCode(errorCode);\n return (\n code === \"provider_network_error\" ||\n code === \"connection_error\" ||\n code === \"network_error\" ||\n /^(?:provider_network_error|connection_error|network_error)$/i.test(\n text.trim(),\n )\n );\n}\n\nexport function normalizeChatError(\n errorMessage: string,\n errorCode?: string,\n): NormalizedChatError {\n const raw = String(errorMessage || \"Unknown error\");\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(raw);\n const text = looksHtml ? htmlToText(raw) : raw.trim();\n\n const code = normalizeErrorCode(errorCode);\n\n if (code === \"builder_model_unauthorized\") {\n return {\n message:\n \"The provider behind this model rejected the request. Pick a different model, then retry.\",\n details: text,\n };\n }\n\n if (code === \"builder_auth_error\") {\n return {\n message:\n \"Builder rejected the connected credentials. Reconnect Builder.io in Settings, then retry.\",\n details: text,\n };\n }\n\n // A model/parameter combination this provider will never accept. Retrying is\n // pointless and the raw sentence names an API surface the reader has no way\n // to act on, so say what they can actually change.\n if (code === \"provider_config_error\") {\n return {\n message:\n \"This model can't use tools with the current settings. Switch models in Settings, then retry.\",\n details: text,\n };\n }\n\n if (isProviderRateLimit(text, errorCode)) {\n return {\n message:\n \"The model provider is rate-limiting this chat right now. Wait a moment, then retry.\",\n details: text,\n };\n }\n\n if (isProviderAuthenticationError(text, errorCode)) {\n return {\n message:\n \"The model provider rejected the saved API key. Update the key in API Keys & Connections, then retry.\",\n details: text,\n };\n }\n\n if (isConnectionError(text, errorCode)) {\n const providerNetworkError =\n normalizeErrorCode(errorCode) === \"provider_network_error\" ||\n /provider_network_error/i.test(text);\n return {\n message: providerNetworkError\n ? \"The model provider could not be reached. Check your connection and retry.\"\n : \"The agent connection was interrupted. Check your connection and retry.\",\n details: text,\n };\n }\n\n if (/^Gateway error \\(no detail; raw event:/i.test(text)) {\n // The previous copy promised auto-recovery and suggested switching models,\n // but neither helps for this code: the server already retried once and\n // the client deliberately skips auto-continuation\n // (see `builder_gateway_error` in sse-event-processor.ts). The error is\n // almost always upstream, so retrying the same conversation with a\n // different model lands on the same wall.\n return {\n message:\n \"The model gateway returned no error details and the chat couldn't recover. Wait a moment and retry, or start a new chat if it keeps happening.\",\n details: text,\n };\n }\n\n if (/inactivity timeout/i.test(text)) {\n return {\n message:\n \"The agent connection timed out before it could finish. You can continue from the partial work or retry.\",\n details: text,\n };\n }\n\n if (/Invalid request body:\\s*tools\\.\\d+\\.input_schema\\.type/i.test(text)) {\n return {\n message:\n \"A tool schema was invalid, so the model rejected the request before it started. The invalid tool can be skipped and the request retried.\",\n details: text,\n };\n }\n\n if (looksHtml) {\n return {\n message:\n text.slice(0, 240) || \"The provider returned an HTML error page.\",\n details: text,\n };\n }\n\n return { message: text };\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n"]}
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
* Body: { json: any, fieldName?: string, type?: "map"|"array", requestSource?: string }
|
|
14
14
|
*/
|
|
15
15
|
export declare const postCollabJson: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
|
|
16
|
-
ok?: undefined;
|
|
17
16
|
error: string;
|
|
17
|
+
ok?: undefined;
|
|
18
18
|
} | {
|
|
19
19
|
error?: undefined;
|
|
20
20
|
ok: boolean;
|
|
@@ -29,7 +29,12 @@ export declare function resolveCredentialForScope(key: string, ctx: CredentialCo
|
|
|
29
29
|
* 5. org-scoped legacy settings credential
|
|
30
30
|
* 6. solo workspace-scoped app_secrets (`solo:<email>`)
|
|
31
31
|
*
|
|
32
|
-
* Steps 3-5
|
|
32
|
+
* Steps 3-5 use `ctx.orgId` when given, else the org resolved from
|
|
33
|
+
* `ctx.userEmail` (see `resolveEffectiveOrgId`), and are skipped only when the
|
|
34
|
+
* caller truly has no org. A membership lookup that could not be read throws
|
|
35
|
+
* `CredentialStoreUnavailableError` instead of silently reporting the
|
|
36
|
+
* credential as unset — "the store didn't answer" and "nothing is saved" are
|
|
37
|
+
* different outcomes callers must not conflate.
|
|
33
38
|
*/
|
|
34
39
|
export declare function resolveCredential(key: string, ctx: CredentialContext): Promise<string | undefined>;
|
|
35
40
|
/**
|
|
@@ -54,7 +59,9 @@ export declare function resolveCredential(key: string, ctx: CredentialContext):
|
|
|
54
59
|
* org the caller already belongs to), and never return the owning account, how
|
|
55
60
|
* many rows matched, or any part of the value. Without an active org there is
|
|
56
61
|
* no boundary to bound the probe to, so it declines to answer rather than
|
|
57
|
-
* revealing that some other tenant holds a key of the same name
|
|
62
|
+
* revealing that some other tenant holds a key of the same name — this
|
|
63
|
+
* includes callers whose `ctx.orgId` is unset AND whose org could not be
|
|
64
|
+
* resolved from `ctx.userEmail` (see `resolveEffectiveOrgId`).
|
|
58
65
|
*
|
|
59
66
|
* Returns null when nothing safe and useful can be said.
|
|
60
67
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,MAAM,MAAM,sBAAsB,GAAG,MAAM,GAAG,KAAK,CAAC;AA2CpD;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAC7C,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,iBAAiB,GAAG;IAAE,KAAK,EAAE,sBAAsB,CAAA;CAAE,GACzD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAO7B;AA6BD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,iBAAiB,GACrB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAoC7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,GAAG,EAAE,iBAAiB,GACrB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8BxB;AAwDD;;GAEG;AACH,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,iBAAiB,GACrB,OAAO,CAAC,OAAO,CAAC,CAElB;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,iBAAiB,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;CAAE,GAClD,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,iBAAiB,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;CAAE,GAClD,OAAO,CAAC,IAAI,CAAC,CAcf"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getDbExec } from "../db/client.js";
|
|
2
2
|
import { encryptSecretValue, decryptSecretValue, isEncryptedSecretValue, } from "../secrets/crypto.js";
|
|
3
3
|
import { readAppSecret } from "../secrets/storage.js";
|
|
4
|
+
import { assertCredentialStoreReadable } from "../server/credential-provider.js";
|
|
4
5
|
import { getSetting, putSetting, deleteSetting } from "../settings/store.js";
|
|
5
6
|
const SETTING_PREFIX = "credential:";
|
|
6
7
|
function userCredentialSettingKey(email, key) {
|
|
@@ -55,6 +56,32 @@ export async function resolveCredentialForScope(key, ctx) {
|
|
|
55
56
|
}
|
|
56
57
|
return readCredentialSetting(userCredentialSettingKey(ctx.userEmail, key));
|
|
57
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* `ctx.orgId` when the caller supplied one, otherwise the org resolved from
|
|
61
|
+
* `ctx.userEmail`'s membership. Interactive requests always supply `orgId`
|
|
62
|
+
* (session/`getOrgContext` backfill it); CLI runs, cron jobs, and any other
|
|
63
|
+
* caller built straight from `getCredentialContext()` outside a request event
|
|
64
|
+
* do not, and previously fell through as "no active org" — invisibly skipping
|
|
65
|
+
* every org-scoped credential a signed-in session could see. Mirrors the
|
|
66
|
+
* fallback already proven in `resolveSecretDetailed`
|
|
67
|
+
* (server/credential-provider.ts).
|
|
68
|
+
*/
|
|
69
|
+
async function resolveEffectiveOrgId(ctx) {
|
|
70
|
+
if (ctx.orgId)
|
|
71
|
+
return { orgId: ctx.orgId, lookupFailed: false };
|
|
72
|
+
try {
|
|
73
|
+
const { resolveOrgIdForEmail } = await import("../org/context.js");
|
|
74
|
+
return {
|
|
75
|
+
orgId: await resolveOrgIdForEmail(ctx.userEmail),
|
|
76
|
+
lookupFailed: false,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
catch (cause) {
|
|
80
|
+
// Membership was unreadable, not merely absent — must not collapse to
|
|
81
|
+
// "caller has no org", which would silently hide every org-scoped row.
|
|
82
|
+
return { orgId: null, lookupFailed: true, cause };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
58
85
|
/**
|
|
59
86
|
* Resolve a credential across the encrypted app_secrets store and the legacy
|
|
60
87
|
* settings-backed credential store. User overrides win, followed by the
|
|
@@ -71,7 +98,12 @@ export async function resolveCredentialForScope(key, ctx) {
|
|
|
71
98
|
* 5. org-scoped legacy settings credential
|
|
72
99
|
* 6. solo workspace-scoped app_secrets (`solo:<email>`)
|
|
73
100
|
*
|
|
74
|
-
* Steps 3-5
|
|
101
|
+
* Steps 3-5 use `ctx.orgId` when given, else the org resolved from
|
|
102
|
+
* `ctx.userEmail` (see `resolveEffectiveOrgId`), and are skipped only when the
|
|
103
|
+
* caller truly has no org. A membership lookup that could not be read throws
|
|
104
|
+
* `CredentialStoreUnavailableError` instead of silently reporting the
|
|
105
|
+
* credential as unset — "the store didn't answer" and "nothing is saved" are
|
|
106
|
+
* different outcomes callers must not conflate.
|
|
75
107
|
*/
|
|
76
108
|
export async function resolveCredential(key, ctx) {
|
|
77
109
|
if (!ctx?.userEmail)
|
|
@@ -85,15 +117,19 @@ export async function resolveCredential(key, ctx) {
|
|
|
85
117
|
});
|
|
86
118
|
if (userSetting)
|
|
87
119
|
return userSetting;
|
|
88
|
-
|
|
89
|
-
|
|
120
|
+
const orgLookup = await resolveEffectiveOrgId(ctx);
|
|
121
|
+
assertCredentialStoreReadable(orgLookup);
|
|
122
|
+
const { orgId } = orgLookup;
|
|
123
|
+
if (orgId) {
|
|
124
|
+
const orgSecret = await readScopedAppSecret(key, "org", orgId);
|
|
90
125
|
if (orgSecret)
|
|
91
126
|
return orgSecret;
|
|
92
|
-
const workspaceSecret = await readScopedAppSecret(key, "workspace",
|
|
127
|
+
const workspaceSecret = await readScopedAppSecret(key, "workspace", orgId);
|
|
93
128
|
if (workspaceSecret)
|
|
94
129
|
return workspaceSecret;
|
|
95
130
|
const orgSetting = await resolveCredentialForScope(key, {
|
|
96
131
|
...ctx,
|
|
132
|
+
orgId,
|
|
97
133
|
scope: "org",
|
|
98
134
|
});
|
|
99
135
|
if (orgSetting)
|
|
@@ -127,22 +163,28 @@ export async function resolveCredential(key, ctx) {
|
|
|
127
163
|
* org the caller already belongs to), and never return the owning account, how
|
|
128
164
|
* many rows matched, or any part of the value. Without an active org there is
|
|
129
165
|
* no boundary to bound the probe to, so it declines to answer rather than
|
|
130
|
-
* revealing that some other tenant holds a key of the same name
|
|
166
|
+
* revealing that some other tenant holds a key of the same name — this
|
|
167
|
+
* includes callers whose `ctx.orgId` is unset AND whose org could not be
|
|
168
|
+
* resolved from `ctx.userEmail` (see `resolveEffectiveOrgId`).
|
|
131
169
|
*
|
|
132
170
|
* Returns null when nothing safe and useful can be said.
|
|
133
171
|
*/
|
|
134
172
|
export async function describeCredentialScopeGap(keys, ctx) {
|
|
135
|
-
if (!ctx?.userEmail
|
|
173
|
+
if (!ctx?.userEmail)
|
|
174
|
+
return null;
|
|
175
|
+
const orgLookup = await resolveEffectiveOrgId(ctx);
|
|
176
|
+
if (orgLookup.lookupFailed || !orgLookup.orgId)
|
|
136
177
|
return null;
|
|
178
|
+
const scopedCtx = { ...ctx, orgId: orgLookup.orgId };
|
|
137
179
|
for (const key of keys) {
|
|
138
|
-
if (await hasForeignPersonalCredentialInOrg(key,
|
|
180
|
+
if (await hasForeignPersonalCredentialInOrg(key, scopedCtx)) {
|
|
139
181
|
return (`A "${key}" key is saved in this workspace with Personal scope. ` +
|
|
140
182
|
`Personal keys are readable only by their own owner's signed-in sessions, ` +
|
|
141
183
|
`and this run resolves credentials as the owner identity behind the ` +
|
|
142
184
|
`integration, job, or automation — so it needs "${key}" saved with ` +
|
|
143
185
|
`Workspace or Organization scope instead.`);
|
|
144
186
|
}
|
|
145
|
-
const holder = await findMemberOrgHoldingCredential(key,
|
|
187
|
+
const holder = await findMemberOrgHoldingCredential(key, scopedCtx);
|
|
146
188
|
if (holder) {
|
|
147
189
|
return (`A "${key}" key is saved in the ${holder} organization, but this ` +
|
|
148
190
|
`request resolved to a different organization you also belong to. ` +
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAkB,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE7E,MAAM,cAAc,GAAG,aAAa,CAAC;AASrC,SAAS,wBAAwB,CAAC,KAAa,EAAE,GAAW;IAC1D,OAAO,KAAK,KAAK,CAAC,WAAW,EAAE,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;AAC5D,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAa,EAAE,GAAW;IACzD,OA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CAA2C,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE;YACxD,KAAK,EAAE,SAAS;SACjB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,UAAU,CAAC,wBAAwB,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE;QAC7D,KAAK,EAAE,SAAS;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,GAAW,EACX,GAAmD;IAEnD,IAAI,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACb,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,IAAI,GAAG,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;QACjE,CAAC;QACD,MAAM,aAAa,CAAC,uBAAuB,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;QAC7D,OAAO;IACT,CAAC;IACD,MAAM,aAAa,CAAC,wBAAwB,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { getDbExec } from \"../db/client.js\";\nimport {\n encryptSecretValue,\n decryptSecretValue,\n isEncryptedSecretValue,\n} from \"../secrets/crypto.js\";\nimport { readAppSecret, type SecretRef } from \"../secrets/storage.js\";\nimport { getSetting, putSetting, deleteSetting } from \"../settings/store.js\";\n\nconst SETTING_PREFIX = \"credential:\";\n\nexport interface CredentialContext {\n userEmail: string;\n orgId?: string | null;\n}\n\nexport type CredentialStorageScope = \"user\" | \"org\";\n\nfunction userCredentialSettingKey(email: string, key: string): string {\n return `u:${email.toLowerCase()}:${SETTING_PREFIX}${key}`;\n}\n\nfunction orgCredentialSettingKey(orgId: string, key: string): string {\n return `o:${orgId}:${SETTING_PREFIX}${key}`;\n}\n\nasync function readCredentialSetting(\n settingKey: string,\n): Promise<string | undefined> {\n const setting = await getSetting(settingKey);\n if (!setting || typeof setting.value !== \"string\") return undefined;\n const stored = setting.value;\n // Values written by saveCredential are AES-256-GCM encrypted at rest.\n // Rows that predate encryption are plaintext — read them transparently\n // (the migrate-encrypt-credentials script re-encrypts them in place).\n if (!isEncryptedSecretValue(stored)) return stored;\n try {\n return decryptSecretValue(stored);\n } catch {\n // Key rotated, corrupt, or tampered row — treat as not set rather than\n // surfacing ciphertext or throwing into every credential lookup.\n return undefined;\n }\n}\n\nasync function readScopedAppSecret(\n key: string,\n scope: SecretRef[\"scope\"],\n scopeId: string,\n): Promise<string | undefined> {\n try {\n return (await readAppSecret({ key, scope, scopeId }))?.value;\n } catch {\n // Older databases may not have app_secrets yet. Keep the legacy\n // credential store available while the table bootstraps.\n return undefined;\n }\n}\n\n/**\n * Resolve a credential from one explicit legacy SQL credential scope.\n *\n * Prefer `resolveCredential()` for normal app-local credential lookup. This\n * helper exists for workspace connection refs, where a ref can explicitly say\n * \"use the org-scoped key\" and must not accidentally read a user override.\n */\nexport async function resolveCredentialForScope(\n key: string,\n ctx: CredentialContext & { scope: CredentialStorageScope },\n): Promise<string | undefined> {\n if (!ctx?.userEmail) return undefined;\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) return undefined;\n return readCredentialSetting(orgCredentialSettingKey(ctx.orgId, key));\n }\n return readCredentialSetting(userCredentialSettingKey(ctx.userEmail, key));\n}\n\n/**\n * Resolve a credential across the encrypted app_secrets store and the legacy\n * settings-backed credential store. User overrides win, followed by the\n * active org/workspace shared value.\n *\n * SECURITY: NEVER reads from process.env. Env vars are global to the\n * deployment and would leak across users in a multi-tenant app.\n *\n * Read order:\n * 1. user-scoped app_secrets\n * 2. user-scoped legacy settings credential\n * 3. org-scoped app_secrets\n * 4. legacy workspace-scoped app_secrets for the org\n * 5. org-scoped legacy settings credential\n * 6. solo workspace-scoped app_secrets (`solo:<email>`)\n *\n * Steps 3-5 are skipped without an active org.\n */\nexport async function resolveCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<string | undefined> {\n if (!ctx?.userEmail) return undefined;\n\n const userSecret = await readScopedAppSecret(key, \"user\", ctx.userEmail);\n if (userSecret) return userSecret;\n\n const userSetting = await resolveCredentialForScope(key, {\n ...ctx,\n scope: \"user\",\n });\n if (userSetting) return userSetting;\n\n if (ctx.orgId) {\n const orgSecret = await readScopedAppSecret(key, \"org\", ctx.orgId);\n if (orgSecret) return orgSecret;\n\n const workspaceSecret = await readScopedAppSecret(\n key,\n \"workspace\",\n ctx.orgId,\n );\n if (workspaceSecret) return workspaceSecret;\n\n const orgSetting = await resolveCredentialForScope(key, {\n ...ctx,\n scope: \"org\",\n });\n if (orgSetting) return orgSetting;\n }\n\n // Solo-workspace fallback: always checked, even when an org id was found\n // above. A credential written before the user joined/created an org lives\n // here, and must not become unreachable once that org exists. Last on\n // purpose — a current org-scoped value always wins over a pre-org one.\n return readScopedAppSecret(key, \"workspace\", `solo:${ctx.userEmail}`);\n}\n\n/**\n * Explain an empty credential lookup when a key of that name is saved in a\n * scope the caller cannot read.\n *\n * Two distinct causes produce the same \"the key is right there and it still\n * says it's missing\" report:\n *\n * - Non-interactive runs — integration/webhook deliveries, scheduled jobs,\n * automations, and inbound A2A calls — resolve credentials as an owner\n * identity rather than as the person who triggered them, so a teammate's\n * Personal key is invisible to them even though the vault visibly holds it.\n * - The key is saved in a DIFFERENT organization the caller also belongs to.\n * Credentials are per-organization, so gaining a second organization (or\n * having `active-org-id` repointed at one) orphans every key synced under\n * the first. Without this, the only symptom is a missing-env-var error that\n * names the key rather than the org mismatch that actually caused it.\n *\n * SECURITY: both probes are bounded to organizations the caller is a member\n * of, report only the scope kind (and, for the cross-org case, the name of an\n * org the caller already belongs to), and never return the owning account, how\n * many rows matched, or any part of the value. Without an active org there is\n * no boundary to bound the probe to, so it declines to answer rather than\n * revealing that some other tenant holds a key of the same name.\n *\n * Returns null when nothing safe and useful can be said.\n */\nexport async function describeCredentialScopeGap(\n keys: readonly string[],\n ctx: CredentialContext,\n): Promise<string | null> {\n if (!ctx?.userEmail || !ctx.orgId) return null;\n\n for (const key of keys) {\n if (await hasForeignPersonalCredentialInOrg(key, ctx)) {\n return (\n `A \"${key}\" key is saved in this workspace with Personal scope. ` +\n `Personal keys are readable only by their own owner's signed-in sessions, ` +\n `and this run resolves credentials as the owner identity behind the ` +\n `integration, job, or automation — so it needs \"${key}\" saved with ` +\n `Workspace or Organization scope instead.`\n );\n }\n\n const holder = await findMemberOrgHoldingCredential(key, ctx);\n if (holder) {\n return (\n `A \"${key}\" key is saved in the ${holder} organization, but this ` +\n `request resolved to a different organization you also belong to. ` +\n `Credentials are scoped per organization and are not shared between ` +\n `them, so this is an organization mismatch rather than a missing key. ` +\n `Either switch your active organization back to ${holder}, or save ` +\n `\"${key}\" in the organization this request runs in.`\n );\n }\n }\n return null;\n}\n\nasync function hasForeignPersonalCredentialInOrg(\n key: string,\n ctx: CredentialContext,\n): Promise<boolean> {\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT 1 FROM app_secrets s\n JOIN org_members m ON LOWER(m.email) = LOWER(s.scope_id)\n WHERE s.key = ? AND s.scope = 'user'\n AND m.org_id = ? AND LOWER(s.scope_id) <> ?\n LIMIT 1`,\n args: [key, ctx.orgId!, ctx.userEmail.toLowerCase()],\n });\n return rows.length > 0;\n } catch {\n // Missing app_secrets/org_members table, or any other read failure — a\n // diagnostic must never replace the real \"not configured\" error.\n return false;\n }\n}\n\n/**\n * Name an organization the caller is a member of that holds this key, other\n * than the one the request resolved to. Returns a quoted display name, or the\n * bare word `another` when the org row is unreadable — never an org id, which\n * would be useless to the person reading the error.\n */\nasync function findMemberOrgHoldingCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<string | null> {\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT o.name AS org_name\n FROM app_secrets s\n JOIN org_members m ON m.org_id = s.scope_id\n AND LOWER(m.email) = ?\n LEFT JOIN organizations o ON o.id = s.scope_id\n WHERE s.key = ?\n AND s.scope IN ('org', 'workspace')\n AND s.scope_id <> ?\n LIMIT 1`,\n args: [ctx.userEmail.toLowerCase(), key, ctx.orgId!],\n });\n if (rows.length === 0) return null;\n const name = (rows[0] as { org_name?: unknown }).org_name;\n return typeof name === \"string\" && name.trim()\n ? `\"${name.trim()}\"`\n : \"another\";\n } catch {\n return null;\n }\n}\n\n/**\n * Check if a credential is available for the given context.\n */\nexport async function hasCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<boolean> {\n return (await resolveCredential(key, ctx)) !== undefined;\n}\n\n/**\n * Save a credential. By default writes to the per-user store; pass\n * `scope: \"org\"` to write to the active org's shared credentials.\n */\nexport async function saveCredential(\n key: string,\n value: string,\n ctx: CredentialContext & { scope?: \"user\" | \"org\" },\n): Promise<void> {\n if (!ctx?.userEmail) {\n throw new Error(\"saveCredential requires CredentialContext with userEmail\");\n }\n // Encrypt at rest (AES-256-GCM) so a leaked DB backup / pg_dump / read\n // replica doesn't expose plaintext keys. resolveCredential decrypts\n // transparently on read.\n const encrypted = encryptSecretValue(value);\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) {\n throw new Error(\"saveCredential scope='org' requires orgId\");\n }\n await putSetting(orgCredentialSettingKey(ctx.orgId, key), {\n value: encrypted,\n });\n return;\n }\n await putSetting(userCredentialSettingKey(ctx.userEmail, key), {\n value: encrypted,\n });\n}\n\n/**\n * Delete a credential from the per-user (default) or per-org store.\n */\nexport async function deleteCredential(\n key: string,\n ctx: CredentialContext & { scope?: \"user\" | \"org\" },\n): Promise<void> {\n if (!ctx?.userEmail) {\n throw new Error(\n \"deleteCredential requires CredentialContext with userEmail\",\n );\n }\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) {\n throw new Error(\"deleteCredential scope='org' requires orgId\");\n }\n await deleteSetting(orgCredentialSettingKey(ctx.orgId, key));\n return;\n }\n await deleteSetting(userCredentialSettingKey(ctx.userEmail, key));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/credentials/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAkB,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kCAAkC,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE7E,MAAM,cAAc,GAAG,aAAa,CAAC;AASrC,SAAS,wBAAwB,CAAC,KAAa,EAAE,GAAW;IAC1D,OAAO,KAAK,KAAK,CAAC,WAAW,EAAE,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;AAC5D,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAa,EAAE,GAAW;IACzD,OAAO,KAAK,KAAK,IAAI,cAAc,GAAG,GAAG,EAAE,CAAC;AAC9C,CAAC;AAED,KAAK,UAAU,qBAAqB,CAClC,UAAkB;IAElB,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,UAAU,CAAC,CAAC;IAC7C,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACpE,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;IAC7B,sEAAsE;IACtE,uEAAuE;IACvE,sEAAsE;IACtE,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IACnD,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,uEAAuE;QACvE,iEAAiE;QACjE,OAAO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bExec } from \"../db/client.js\";\nimport {\n encryptSecretValue,\n decryptSecretValue,\n isEncryptedSecretValue,\n} from \"../secrets/crypto.js\";\nimport { readAppSecret, type SecretRef } from \"../secrets/storage.js\";\nimport { assertCredentialStoreReadable } from \"../server/credential-provider.js\";\nimport { getSetting, putSetting, deleteSetting } from \"../settings/store.js\";\n\nconst SETTING_PREFIX = \"credential:\";\n\nexport interface CredentialContext {\n userEmail: string;\n orgId?: string | null;\n}\n\nexport type CredentialStorageScope = \"user\" | \"org\";\n\nfunction userCredentialSettingKey(email: string, key: string): string {\n return `u:${email.toLowerCase()}:${SETTING_PREFIX}${key}`;\n}\n\nfunction orgCredentialSettingKey(orgId: string, key: string): string {\n return `o:${orgId}:${SETTING_PREFIX}${key}`;\n}\n\nasync function readCredentialSetting(\n settingKey: string,\n): Promise<string | undefined> {\n const setting = await getSetting(settingKey);\n if (!setting || typeof setting.value !== \"string\") return undefined;\n const stored = setting.value;\n // Values written by saveCredential are AES-256-GCM encrypted at rest.\n // Rows that predate encryption are plaintext — read them transparently\n // (the migrate-encrypt-credentials script re-encrypts them in place).\n if (!isEncryptedSecretValue(stored)) return stored;\n try {\n return decryptSecretValue(stored);\n } catch {\n // Key rotated, corrupt, or tampered row — treat as not set rather than\n // surfacing ciphertext or throwing into every credential lookup.\n return undefined;\n }\n}\n\nasync function readScopedAppSecret(\n key: string,\n scope: SecretRef[\"scope\"],\n scopeId: string,\n): Promise<string | undefined> {\n try {\n return (await readAppSecret({ key, scope, scopeId }))?.value;\n } catch {\n // Older databases may not have app_secrets yet. Keep the legacy\n // credential store available while the table bootstraps.\n return undefined;\n }\n}\n\n/**\n * Resolve a credential from one explicit legacy SQL credential scope.\n *\n * Prefer `resolveCredential()` for normal app-local credential lookup. This\n * helper exists for workspace connection refs, where a ref can explicitly say\n * \"use the org-scoped key\" and must not accidentally read a user override.\n */\nexport async function resolveCredentialForScope(\n key: string,\n ctx: CredentialContext & { scope: CredentialStorageScope },\n): Promise<string | undefined> {\n if (!ctx?.userEmail) return undefined;\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) return undefined;\n return readCredentialSetting(orgCredentialSettingKey(ctx.orgId, key));\n }\n return readCredentialSetting(userCredentialSettingKey(ctx.userEmail, key));\n}\n\n/**\n * `ctx.orgId` when the caller supplied one, otherwise the org resolved from\n * `ctx.userEmail`'s membership. Interactive requests always supply `orgId`\n * (session/`getOrgContext` backfill it); CLI runs, cron jobs, and any other\n * caller built straight from `getCredentialContext()` outside a request event\n * do not, and previously fell through as \"no active org\" — invisibly skipping\n * every org-scoped credential a signed-in session could see. Mirrors the\n * fallback already proven in `resolveSecretDetailed`\n * (server/credential-provider.ts).\n */\nasync function resolveEffectiveOrgId(\n ctx: CredentialContext,\n): Promise<{ orgId: string | null; lookupFailed: boolean; cause?: unknown }> {\n if (ctx.orgId) return { orgId: ctx.orgId, lookupFailed: false };\n try {\n const { resolveOrgIdForEmail } = await import(\"../org/context.js\");\n return {\n orgId: await resolveOrgIdForEmail(ctx.userEmail),\n lookupFailed: false,\n };\n } catch (cause) {\n // Membership was unreadable, not merely absent — must not collapse to\n // \"caller has no org\", which would silently hide every org-scoped row.\n return { orgId: null, lookupFailed: true, cause };\n }\n}\n\n/**\n * Resolve a credential across the encrypted app_secrets store and the legacy\n * settings-backed credential store. User overrides win, followed by the\n * active org/workspace shared value.\n *\n * SECURITY: NEVER reads from process.env. Env vars are global to the\n * deployment and would leak across users in a multi-tenant app.\n *\n * Read order:\n * 1. user-scoped app_secrets\n * 2. user-scoped legacy settings credential\n * 3. org-scoped app_secrets\n * 4. legacy workspace-scoped app_secrets for the org\n * 5. org-scoped legacy settings credential\n * 6. solo workspace-scoped app_secrets (`solo:<email>`)\n *\n * Steps 3-5 use `ctx.orgId` when given, else the org resolved from\n * `ctx.userEmail` (see `resolveEffectiveOrgId`), and are skipped only when the\n * caller truly has no org. A membership lookup that could not be read throws\n * `CredentialStoreUnavailableError` instead of silently reporting the\n * credential as unset — \"the store didn't answer\" and \"nothing is saved\" are\n * different outcomes callers must not conflate.\n */\nexport async function resolveCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<string | undefined> {\n if (!ctx?.userEmail) return undefined;\n\n const userSecret = await readScopedAppSecret(key, \"user\", ctx.userEmail);\n if (userSecret) return userSecret;\n\n const userSetting = await resolveCredentialForScope(key, {\n ...ctx,\n scope: \"user\",\n });\n if (userSetting) return userSetting;\n\n const orgLookup = await resolveEffectiveOrgId(ctx);\n assertCredentialStoreReadable(orgLookup);\n const { orgId } = orgLookup;\n\n if (orgId) {\n const orgSecret = await readScopedAppSecret(key, \"org\", orgId);\n if (orgSecret) return orgSecret;\n\n const workspaceSecret = await readScopedAppSecret(key, \"workspace\", orgId);\n if (workspaceSecret) return workspaceSecret;\n\n const orgSetting = await resolveCredentialForScope(key, {\n ...ctx,\n orgId,\n scope: \"org\",\n });\n if (orgSetting) return orgSetting;\n }\n\n // Solo-workspace fallback: always checked, even when an org id was found\n // above. A credential written before the user joined/created an org lives\n // here, and must not become unreachable once that org exists. Last on\n // purpose — a current org-scoped value always wins over a pre-org one.\n return readScopedAppSecret(key, \"workspace\", `solo:${ctx.userEmail}`);\n}\n\n/**\n * Explain an empty credential lookup when a key of that name is saved in a\n * scope the caller cannot read.\n *\n * Two distinct causes produce the same \"the key is right there and it still\n * says it's missing\" report:\n *\n * - Non-interactive runs — integration/webhook deliveries, scheduled jobs,\n * automations, and inbound A2A calls — resolve credentials as an owner\n * identity rather than as the person who triggered them, so a teammate's\n * Personal key is invisible to them even though the vault visibly holds it.\n * - The key is saved in a DIFFERENT organization the caller also belongs to.\n * Credentials are per-organization, so gaining a second organization (or\n * having `active-org-id` repointed at one) orphans every key synced under\n * the first. Without this, the only symptom is a missing-env-var error that\n * names the key rather than the org mismatch that actually caused it.\n *\n * SECURITY: both probes are bounded to organizations the caller is a member\n * of, report only the scope kind (and, for the cross-org case, the name of an\n * org the caller already belongs to), and never return the owning account, how\n * many rows matched, or any part of the value. Without an active org there is\n * no boundary to bound the probe to, so it declines to answer rather than\n * revealing that some other tenant holds a key of the same name — this\n * includes callers whose `ctx.orgId` is unset AND whose org could not be\n * resolved from `ctx.userEmail` (see `resolveEffectiveOrgId`).\n *\n * Returns null when nothing safe and useful can be said.\n */\nexport async function describeCredentialScopeGap(\n keys: readonly string[],\n ctx: CredentialContext,\n): Promise<string | null> {\n if (!ctx?.userEmail) return null;\n const orgLookup = await resolveEffectiveOrgId(ctx);\n if (orgLookup.lookupFailed || !orgLookup.orgId) return null;\n const scopedCtx: CredentialContext = { ...ctx, orgId: orgLookup.orgId };\n\n for (const key of keys) {\n if (await hasForeignPersonalCredentialInOrg(key, scopedCtx)) {\n return (\n `A \"${key}\" key is saved in this workspace with Personal scope. ` +\n `Personal keys are readable only by their own owner's signed-in sessions, ` +\n `and this run resolves credentials as the owner identity behind the ` +\n `integration, job, or automation — so it needs \"${key}\" saved with ` +\n `Workspace or Organization scope instead.`\n );\n }\n\n const holder = await findMemberOrgHoldingCredential(key, scopedCtx);\n if (holder) {\n return (\n `A \"${key}\" key is saved in the ${holder} organization, but this ` +\n `request resolved to a different organization you also belong to. ` +\n `Credentials are scoped per organization and are not shared between ` +\n `them, so this is an organization mismatch rather than a missing key. ` +\n `Either switch your active organization back to ${holder}, or save ` +\n `\"${key}\" in the organization this request runs in.`\n );\n }\n }\n return null;\n}\n\nasync function hasForeignPersonalCredentialInOrg(\n key: string,\n ctx: CredentialContext,\n): Promise<boolean> {\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT 1 FROM app_secrets s\n JOIN org_members m ON LOWER(m.email) = LOWER(s.scope_id)\n WHERE s.key = ? AND s.scope = 'user'\n AND m.org_id = ? AND LOWER(s.scope_id) <> ?\n LIMIT 1`,\n args: [key, ctx.orgId!, ctx.userEmail.toLowerCase()],\n });\n return rows.length > 0;\n } catch {\n // Missing app_secrets/org_members table, or any other read failure — a\n // diagnostic must never replace the real \"not configured\" error.\n return false;\n }\n}\n\n/**\n * Name an organization the caller is a member of that holds this key, other\n * than the one the request resolved to. Returns a quoted display name, or the\n * bare word `another` when the org row is unreadable — never an org id, which\n * would be useless to the person reading the error.\n */\nasync function findMemberOrgHoldingCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<string | null> {\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT o.name AS org_name\n FROM app_secrets s\n JOIN org_members m ON m.org_id = s.scope_id\n AND LOWER(m.email) = ?\n LEFT JOIN organizations o ON o.id = s.scope_id\n WHERE s.key = ?\n AND s.scope IN ('org', 'workspace')\n AND s.scope_id <> ?\n LIMIT 1`,\n args: [ctx.userEmail.toLowerCase(), key, ctx.orgId!],\n });\n if (rows.length === 0) return null;\n const name = (rows[0] as { org_name?: unknown }).org_name;\n return typeof name === \"string\" && name.trim()\n ? `\"${name.trim()}\"`\n : \"another\";\n } catch {\n return null;\n }\n}\n\n/**\n * Check if a credential is available for the given context.\n */\nexport async function hasCredential(\n key: string,\n ctx: CredentialContext,\n): Promise<boolean> {\n return (await resolveCredential(key, ctx)) !== undefined;\n}\n\n/**\n * Save a credential. By default writes to the per-user store; pass\n * `scope: \"org\"` to write to the active org's shared credentials.\n */\nexport async function saveCredential(\n key: string,\n value: string,\n ctx: CredentialContext & { scope?: \"user\" | \"org\" },\n): Promise<void> {\n if (!ctx?.userEmail) {\n throw new Error(\"saveCredential requires CredentialContext with userEmail\");\n }\n // Encrypt at rest (AES-256-GCM) so a leaked DB backup / pg_dump / read\n // replica doesn't expose plaintext keys. resolveCredential decrypts\n // transparently on read.\n const encrypted = encryptSecretValue(value);\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) {\n throw new Error(\"saveCredential scope='org' requires orgId\");\n }\n await putSetting(orgCredentialSettingKey(ctx.orgId, key), {\n value: encrypted,\n });\n return;\n }\n await putSetting(userCredentialSettingKey(ctx.userEmail, key), {\n value: encrypted,\n });\n}\n\n/**\n * Delete a credential from the per-user (default) or per-org store.\n */\nexport async function deleteCredential(\n key: string,\n ctx: CredentialContext & { scope?: \"user\" | \"org\" },\n): Promise<void> {\n if (!ctx?.userEmail) {\n throw new Error(\n \"deleteCredential requires CredentialContext with userEmail\",\n );\n }\n if (ctx.scope === \"org\") {\n if (!ctx.orgId) {\n throw new Error(\"deleteCredential scope='org' requires orgId\");\n }\n await deleteSetting(orgCredentialSettingKey(ctx.orgId, key));\n return;\n }\n await deleteSetting(userCredentialSettingKey(ctx.userEmail, key));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-safety.d.ts","sourceRoot":"","sources":["../../src/extensions/url-safety.ts"],"names":[],"mappings":"AA4FA,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAoB1D;AASD;;;;GAIG;AACH,wBAAsB,4BAA4B,CAChD,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,CAoBlB;
|
|
1
|
+
{"version":3,"file":"url-safety.d.ts","sourceRoot":"","sources":["../../src/extensions/url-safety.ts"],"names":[],"mappings":"AA4FA,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAoB1D;AASD;;;;GAIG;AACH,wBAAsB,4BAA4B,CAChD,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,CAoBlB;AA8ED,wBAAsB,wBAAwB,CAC5C,qBAAqB,GAAE,SAAS,MAAM,EAAO,GAC5C,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAyEzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,IAAI,GAAE,WAAgB,EACtB,OAAO,GAAE;IACP,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD;;;;;;OAMG;IACH,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC,GACL,OAAO,CAAC,QAAQ,CAAC,CA0DnB;AAQD,OAAO,EAAE,qBAAqB,IAAI,gBAAgB,EAAE,CAAC;AACrD,OAAO,EAAE,4BAA4B,IAAI,uBAAuB,EAAE,CAAC;AACnE,OAAO,EAAE,aAAa,IAAI,iBAAiB,EAAE,CAAC"}
|
|
@@ -175,6 +175,18 @@ export async function isBlockedExtensionUrlWithDns(url) {
|
|
|
175
175
|
function normalizeLookupHostname(hostname) {
|
|
176
176
|
return hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
177
177
|
}
|
|
178
|
+
function loopbackHostnameVariants(hostname) {
|
|
179
|
+
const normalized = normalizeLookupHostname(hostname);
|
|
180
|
+
if (normalized !== "localhost" &&
|
|
181
|
+
normalized !== "127.0.0.1" &&
|
|
182
|
+
normalized !== "::1") {
|
|
183
|
+
return [normalized];
|
|
184
|
+
}
|
|
185
|
+
// Local workspace manifests can identify the same child server as
|
|
186
|
+
// localhost, 127.0.0.1, or ::1. They are equivalent only for loopback; do
|
|
187
|
+
// not alias arbitrary private or public hostnames.
|
|
188
|
+
return ["localhost", "127.0.0.1", "::1"];
|
|
189
|
+
}
|
|
178
190
|
function normalizeAllowedPrivateOriginKeys(origins) {
|
|
179
191
|
const keys = new Set();
|
|
180
192
|
for (const origin of origins) {
|
|
@@ -184,7 +196,28 @@ function normalizeAllowedPrivateOriginKeys(origins) {
|
|
|
184
196
|
continue;
|
|
185
197
|
}
|
|
186
198
|
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
|
187
|
-
|
|
199
|
+
for (const hostname of loopbackHostnameVariants(parsed.hostname)) {
|
|
200
|
+
keys.add(`${hostname}:${port}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// coercion-ok: malformed deployment configuration is omitted, preserving the fail-closed private-IP guard.
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return keys;
|
|
208
|
+
}
|
|
209
|
+
function normalizeAllowedPrivateOriginOriginKeys(origins) {
|
|
210
|
+
const keys = new Set();
|
|
211
|
+
for (const origin of origins) {
|
|
212
|
+
try {
|
|
213
|
+
const parsed = new URL(origin);
|
|
214
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
|
218
|
+
for (const hostname of loopbackHostnameVariants(parsed.hostname)) {
|
|
219
|
+
keys.add(`${parsed.protocol}//${hostname}:${port}`);
|
|
220
|
+
}
|
|
188
221
|
}
|
|
189
222
|
catch {
|
|
190
223
|
// Ignore malformed deployment configuration and retain the private-IP guard.
|
|
@@ -273,21 +306,14 @@ export async function ssrfSafeFetch(url, init = {}, options = {}) {
|
|
|
273
306
|
const maxRedirects = options.maxRedirects ?? 3;
|
|
274
307
|
const dispatcher = (await createSsrfSafeDispatcher(options.allowedPrivateOrigins)) ??
|
|
275
308
|
undefined;
|
|
276
|
-
const allowedPrivateOrigins =
|
|
277
|
-
.map((origin) => {
|
|
278
|
-
try {
|
|
279
|
-
return new URL(origin).origin;
|
|
280
|
-
}
|
|
281
|
-
catch {
|
|
282
|
-
return "";
|
|
283
|
-
}
|
|
284
|
-
})
|
|
285
|
-
.filter(Boolean));
|
|
309
|
+
const allowedPrivateOrigins = normalizeAllowedPrivateOriginOriginKeys(options.allowedPrivateOrigins ?? []);
|
|
286
310
|
const isAllowedPrivateOrigin = (candidate) => {
|
|
287
311
|
if (allowedPrivateOrigins.size === 0)
|
|
288
312
|
return false;
|
|
289
313
|
try {
|
|
290
|
-
|
|
314
|
+
const parsed = new URL(candidate);
|
|
315
|
+
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
|
316
|
+
return allowedPrivateOrigins.has(`${parsed.protocol}//${normalizeLookupHostname(parsed.hostname)}:${port}`);
|
|
291
317
|
}
|
|
292
318
|
catch {
|
|
293
319
|
return false;
|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,UAAU,GAAG,UAAU,CAAC;QAElD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;QACpD,IAAI,QAAQ,CAAC,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACpD,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,CAAC,QAAQ;gBAAE,OAAO,QAAQ,CAAC;YAC/B,sEAAsE;YACtE,0BAA0B;YAC1B,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAC9C,UAAU,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,IAAI,CAAC;YAChD,SAAS;QACX,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,IAAI,KAAK,CACb,sCAAsC,YAAY,oBAAoB,GAAG,EAAE,CAC5E,CAAC;AACJ,CAAC;AAED,gFAAgF;AAChF,2EAA2E;AAC3E,2EAA2E;AAC3E,0EAA0E;AAC1E,gFAAgF;AAEhF,OAAO,EAAE,qBAAqB,IAAI,gBAAgB,EAAE,CAAC;AACrD,OAAO,EAAE,4BAA4B,IAAI,uBAAuB,EAAE,CAAC;AACnE,OAAO,EAAE,aAAa,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["const METADATA_HOSTS = [\n \"metadata.google.internal\",\n \"metadata.google.internal.\",\n];\n\nconst DNS_REBIND_SUFFIXES = [\n \".nip.io\",\n \".sslip.io\",\n \".xip.io\",\n \".localtest.me\",\n \".lvh.me\",\n];\n\nfunction isPrivateIpv4(a: number, b: number, c = 0, d = 0): boolean {\n if (![a, b, c, d].every((part) => part >= 0 && part <= 255)) return true;\n if (a === 127) return true;\n if (a === 10) return true;\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 169 && b === 254) return true;\n if (a === 0) return true;\n if (a === 100 && b >= 64 && b <= 127) return true;\n if (a === 192 && b === 0) return true;\n if (a === 198 && (b === 18 || b === 19)) return true;\n if (a === 192 && b === 0 && c === 2) return true;\n if (a === 198 && b === 51 && c === 100) return true;\n if (a === 203 && b === 0 && c === 113) return true;\n if (a >= 224) return true;\n return false;\n}\n\nfunction isPrivateIpv4MappedHex(host: string): boolean {\n const mapped = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);\n if (!mapped) return false;\n const high = Number.parseInt(mapped[1], 16);\n const low = Number.parseInt(mapped[2], 16);\n if (high < 0 || high > 0xffff || low < 0 || low > 0xffff) return false;\n const a = (high >> 8) & 0xff;\n const b = high & 0xff;\n const c = (low >> 8) & 0xff;\n const d = low & 0xff;\n return isPrivateIpv4(a, b, c, d);\n}\n\nfunction isPrivateHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (\n host === \"localhost\" ||\n host === \"::1\" ||\n host === \"::0\" ||\n host === \"::\"\n ) {\n return true;\n }\n if (METADATA_HOSTS.includes(host)) return true;\n\n // IPv6 ULA/link-local/multicast.\n if (/^f[cd]/.test(host) || /^fe[89ab]/.test(host)) return true;\n if (/^ff/i.test(host)) return true;\n\n // IPv4-mapped IPv6. URL parsing may preserve dotted form in some runtimes\n // or normalize it to hex, e.g. [::ffff:127.0.0.1] -> ::ffff:7f00:1.\n const v4mappedDotted = host.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (v4mappedDotted) {\n const [a, b, c, d] = v4mappedDotted[1].split(\".\").map(Number);\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n if (isPrivateIpv4MappedHex(host)) return true;\n\n // Dotted IPv4. URL parsing normalizes shorthand/octal/hex IPv4 forms to\n // dotted decimal before we reach this point.\n const parts = host.split(\".\");\n if (parts.length === 4 && parts.every((p) => /^\\d+$/.test(p))) {\n const [a, b, c, d] = parts.map(Number);\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n\n // Decimal integer IPv4.\n if (/^\\d+$/.test(host)) {\n const num = Number(host);\n if (num >= 0 && num <= 0xffffffff) {\n const a = (num >>> 24) & 0xff;\n const b = (num >>> 16) & 0xff;\n const c = (num >>> 8) & 0xff;\n const d = num & 0xff;\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n }\n\n return false;\n}\n\nexport function isBlockedExtensionUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return true;\n }\n const host = parsed.hostname.toLowerCase();\n if (isPrivateHost(host)) return true;\n if (\n DNS_REBIND_SUFFIXES.some((suffix) => {\n const bare = suffix.slice(1);\n return host === bare || host.endsWith(suffix);\n })\n ) {\n return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\nfunction isIpLiteralHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (host.includes(\":\")) return true;\n const parts = host.split(\".\");\n return parts.length === 4 && parts.every((p) => /^\\d+$/.test(p));\n}\n\n/**\n * Async SSRF guard for environments that can resolve DNS. The synchronous\n * guard catches literals and known rebinding domains; this closes the common\n * \"public hostname resolves to a private address\" gap before dispatch.\n */\nexport async function isBlockedExtensionUrlWithDns(\n url: string,\n): Promise<boolean> {\n if (isBlockedExtensionUrl(url)) return true;\n\n let hostname: string;\n try {\n hostname = new URL(url).hostname.toLowerCase();\n } catch {\n return true;\n }\n if (!hostname || isIpLiteralHost(hostname)) return false;\n\n try {\n const { lookup } = await import(\"node:dns/promises\");\n const records = await lookup(hostname, { all: true, verbatim: true });\n return records.some((record) => isPrivateHost(record.address));\n } catch {\n // Some edge runtimes do not expose DNS lookup. Keep the deterministic\n // parser-based protections instead of failing every outbound request.\n return false;\n }\n}\n\n/**\n * Build an undici Dispatcher whose connect-time DNS lookup runs through a\n * private-IP guard. This closes the TOCTOU gap where:\n * 1. We resolve hostname → public IP and pass.\n * 2. Between that lookup and the actual connect, DNS rebinding flips the\n * record to a private IP.\n * 3. fetch() resolves again and connects to the private IP.\n *\n * With a custom dispatcher, the same lookup that produces the IP also gates\n * the connect: if the IP is in the private set, the connect throws.\n *\n * Returns `null` if undici / node:dns are not available (e.g. some edge\n * runtimes); the caller should fall back to the regular `fetch` path —\n * `isBlockedExtensionUrlWithDns` will still have caught most rebinding cases.\n */\nfunction normalizeLookupHostname(hostname: string): string {\n return hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n}\n\nfunction normalizeAllowedPrivateOriginKeys(\n origins: readonly string[],\n): Set<string> {\n const keys = new Set<string>();\n for (const origin of origins) {\n try {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n continue;\n }\n const port = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n keys.add(`${normalizeLookupHostname(parsed.hostname)}:${port}`);\n } catch {\n // Ignore malformed deployment configuration and retain the private-IP guard.\n }\n }\n return keys;\n}\n\nexport async function createSsrfSafeDispatcher(\n allowedPrivateOrigins: readonly string[] = [],\n): Promise<unknown | null> {\n // Keep the optional undici import opaque to Vite/Rolldown. A static\n // `import(\"undici\")` makes browser builds try to resolve and bundle undici\n // even though this dispatcher is only useful in Node server runtimes.\n let undici: any;\n let dnsModule: any;\n try {\n const runtimeImport = new Function(\n \"specifier\",\n \"return import(specifier)\",\n ) as (specifier: string) => Promise<any>;\n undici = await runtimeImport(\"undici\");\n dnsModule = await import(\"node:dns\");\n } catch {\n return null;\n }\n\n const { Agent } = undici;\n const { lookup } = dnsModule;\n const allowedPrivateOriginKeys = normalizeAllowedPrivateOriginKeys(\n allowedPrivateOrigins,\n );\n if (!Agent || !lookup) return null;\n\n return new Agent({\n connect: {\n // Override DNS lookup at connect time so the IP we hand to undici's\n // socket is the one we authorized. Reject any record in the private\n // set BEFORE the TCP handshake.\n lookup: (\n hostname: string,\n options: any,\n callback: (\n err: NodeJS.ErrnoException | null,\n address?: string | { address: string; family: number }[],\n family?: number,\n ) => void,\n ) => {\n lookup(\n hostname,\n { all: true, verbatim: true },\n (err: NodeJS.ErrnoException | null, addresses: any) => {\n if (err) return callback(err);\n const list: { address: string; family: number }[] = Array.isArray(\n addresses,\n )\n ? addresses\n : [{ address: addresses, family: 4 }];\n for (const record of list) {\n const allowedOrigin = allowedPrivateOriginKeys.has(\n `${normalizeLookupHostname(hostname)}:${String(options?.port ?? \"\")}`,\n );\n if (isPrivateHost(record.address) && !allowedOrigin) {\n const e = new Error(\n `Connect blocked: ${hostname} resolved to private address ${record.address}`,\n ) as NodeJS.ErrnoException;\n e.code = \"EAI_BLOCKED\";\n return callback(e);\n }\n }\n // Mirror Node's lookup behavior: when `all` is true, return the\n // array; otherwise the first entry. undici's connect honors\n // `options.all`.\n if (options && options.all) {\n return callback(null, list as any);\n }\n const first = list[0];\n return callback(null, first.address, first.family);\n },\n );\n },\n },\n });\n}\n\n/**\n * SSRF-safe `fetch` for any server-side request to a user/agent-supplied URL.\n *\n * Applies the same protections the extension proxy uses, so every call site\n * that fetches an untrusted URL gets them without re-implementing the loop:\n * 1. Pre-flight DNS-aware private-address check (isBlockedExtensionUrlWithDns)\n * on the initial URL and on every redirect hop.\n * 2. A connect-time dispatcher that re-checks the resolved IP at TCP-connect\n * time (closes the DNS-rebinding TOCTOU) when undici is available.\n * 3. Manual redirect handling — a public URL cannot 30x-redirect into the\n * private network because each hop is re-validated before it is followed.\n *\n * Throws an Error whose message starts with \"SSRF blocked:\" when a target\n * (initial or via redirect) resolves to a private/internal address, or when the\n * redirect limit is exceeded. Otherwise returns the final Response.\n *\n * `httpsOnly` extends the per-hop validation to the URL scheme: redirects are\n * followed only to `https:` targets, so an HTTPS-only caller cannot be\n * downgraded to plain HTTP by a 30x from the (untrusted) origin.\n *\n * `assertUrlAllowed` lets callers layer a stricter destination policy (for\n * example, a credential's origin allowlist) on top of the SSRF checks. It runs\n * before the initial request and before every redirect hop, so sensitive\n * headers and bodies are never forwarded to a destination the caller rejects.\n */\nexport async function ssrfSafeFetch(\n url: string,\n init: RequestInit = {},\n options: {\n maxRedirects?: number;\n httpsOnly?: boolean;\n assertUrlAllowed?: (url: string) => void | Promise<void>;\n /**\n * Exact origins that may resolve to a private address. A workspace runs\n * every app on loopback behind one gateway, so sibling A2A calls are\n * private by construction; without this they are indistinguishable from an\n * SSRF attempt and get blocked. Only ever pass origins the deployment\n * itself configured (never a request-supplied value).\n */\n allowedPrivateOrigins?: readonly string[];\n } = {},\n): Promise<Response> {\n const maxRedirects = options.maxRedirects ?? 3;\n const dispatcher =\n (await createSsrfSafeDispatcher(options.allowedPrivateOrigins)) ??\n undefined;\n const allowedPrivateOrigins = new Set(\n (options.allowedPrivateOrigins ?? [])\n .map((origin) => {\n try {\n return new URL(origin).origin;\n } catch {\n return \"\";\n }\n })\n .filter(Boolean),\n );\n const isAllowedPrivateOrigin = (candidate: string): boolean => {\n if (allowedPrivateOrigins.size === 0) return false;\n try {\n return allowedPrivateOrigins.has(new URL(candidate).origin);\n } catch {\n return false;\n }\n };\n\n let currentUrl = url;\n for (let hop = 0; hop <= maxRedirects; hop++) {\n await options.assertUrlAllowed?.(currentUrl);\n if (options.httpsOnly && new URL(currentUrl).protocol !== \"https:\") {\n throw new Error(\n `SSRF blocked: refusing to fetch non-HTTPS address (${currentUrl})`,\n );\n }\n if (\n !isAllowedPrivateOrigin(currentUrl) &&\n (await isBlockedExtensionUrlWithDns(currentUrl))\n ) {\n throw new Error(\n `SSRF blocked: refusing to fetch private/internal address (${currentUrl})`,\n );\n }\n const fetchOpts: RequestInit & { dispatcher?: unknown } = {\n ...init,\n redirect: \"manual\",\n };\n if (dispatcher) fetchOpts.dispatcher = dispatcher;\n\n const response = await fetch(currentUrl, fetchOpts);\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get(\"location\");\n if (!location) return response;\n // Drain the redirect body so the hop's connection is released instead\n // of being held until GC.\n await response.body?.cancel().catch(() => {});\n currentUrl = new URL(location, currentUrl).href;\n continue;\n }\n return response;\n }\n throw new Error(\n `SSRF blocked: too many redirects (>${maxRedirects}) while fetching ${url}`,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Legacy aliases — predate the Tools → Extensions rename. Templates import\n// these via the legacy `@agent-native/core/tools/url-safety` subpath; keep\n// the names exported so they keep resolving until every consumer updates.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport { isBlockedExtensionUrl as isBlockedToolUrl };\nexport { isBlockedExtensionUrlWithDns as isBlockedToolUrlWithDns };\nexport { ssrfSafeFetch as ssrfSafeToolFetch };\n"]}
|
|
1
|
+
{"version":3,"file":"url-safety.js","sourceRoot":"","sources":["../../src/extensions/url-safety.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG;IACrB,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAEF,MAAM,mBAAmB,GAAG;IAC1B,SAAS;IACT,WAAW;IACX,SAAS;IACT,eAAe;IACf,SAAS;CACV,CAAC;AAEF,SAAS,aAAa,CAAC,CAAS,EAAE,CAAS,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC;IACvD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACzE,IAAI,CAAC,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IAC3B,IAAI,CAAC,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IAC1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;IACjD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACxC,IAAI,CA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AAI,iBAAiB,EAAE,CAAC","sourcesContent":["const METADATA_HOSTS = [\n \"metadata.google.internal\",\n \"metadata.google.internal.\",\n];\n\nconst DNS_REBIND_SUFFIXES = [\n \".nip.io\",\n \".sslip.io\",\n \".xip.io\",\n \".localtest.me\",\n \".lvh.me\",\n];\n\nfunction isPrivateIpv4(a: number, b: number, c = 0, d = 0): boolean {\n if (![a, b, c, d].every((part) => part >= 0 && part <= 255)) return true;\n if (a === 127) return true;\n if (a === 10) return true;\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 169 && b === 254) return true;\n if (a === 0) return true;\n if (a === 100 && b >= 64 && b <= 127) return true;\n if (a === 192 && b === 0) return true;\n if (a === 198 && (b === 18 || b === 19)) return true;\n if (a === 192 && b === 0 && c === 2) return true;\n if (a === 198 && b === 51 && c === 100) return true;\n if (a === 203 && b === 0 && c === 113) return true;\n if (a >= 224) return true;\n return false;\n}\n\nfunction isPrivateIpv4MappedHex(host: string): boolean {\n const mapped = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);\n if (!mapped) return false;\n const high = Number.parseInt(mapped[1], 16);\n const low = Number.parseInt(mapped[2], 16);\n if (high < 0 || high > 0xffff || low < 0 || low > 0xffff) return false;\n const a = (high >> 8) & 0xff;\n const b = high & 0xff;\n const c = (low >> 8) & 0xff;\n const d = low & 0xff;\n return isPrivateIpv4(a, b, c, d);\n}\n\nfunction isPrivateHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (\n host === \"localhost\" ||\n host === \"::1\" ||\n host === \"::0\" ||\n host === \"::\"\n ) {\n return true;\n }\n if (METADATA_HOSTS.includes(host)) return true;\n\n // IPv6 ULA/link-local/multicast.\n if (/^f[cd]/.test(host) || /^fe[89ab]/.test(host)) return true;\n if (/^ff/i.test(host)) return true;\n\n // IPv4-mapped IPv6. URL parsing may preserve dotted form in some runtimes\n // or normalize it to hex, e.g. [::ffff:127.0.0.1] -> ::ffff:7f00:1.\n const v4mappedDotted = host.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (v4mappedDotted) {\n const [a, b, c, d] = v4mappedDotted[1].split(\".\").map(Number);\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n if (isPrivateIpv4MappedHex(host)) return true;\n\n // Dotted IPv4. URL parsing normalizes shorthand/octal/hex IPv4 forms to\n // dotted decimal before we reach this point.\n const parts = host.split(\".\");\n if (parts.length === 4 && parts.every((p) => /^\\d+$/.test(p))) {\n const [a, b, c, d] = parts.map(Number);\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n\n // Decimal integer IPv4.\n if (/^\\d+$/.test(host)) {\n const num = Number(host);\n if (num >= 0 && num <= 0xffffffff) {\n const a = (num >>> 24) & 0xff;\n const b = (num >>> 16) & 0xff;\n const c = (num >>> 8) & 0xff;\n const d = num & 0xff;\n if (isPrivateIpv4(a, b, c, d)) return true;\n }\n }\n\n return false;\n}\n\nexport function isBlockedExtensionUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return true;\n }\n const host = parsed.hostname.toLowerCase();\n if (isPrivateHost(host)) return true;\n if (\n DNS_REBIND_SUFFIXES.some((suffix) => {\n const bare = suffix.slice(1);\n return host === bare || host.endsWith(suffix);\n })\n ) {\n return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\nfunction isIpLiteralHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (host.includes(\":\")) return true;\n const parts = host.split(\".\");\n return parts.length === 4 && parts.every((p) => /^\\d+$/.test(p));\n}\n\n/**\n * Async SSRF guard for environments that can resolve DNS. The synchronous\n * guard catches literals and known rebinding domains; this closes the common\n * \"public hostname resolves to a private address\" gap before dispatch.\n */\nexport async function isBlockedExtensionUrlWithDns(\n url: string,\n): Promise<boolean> {\n if (isBlockedExtensionUrl(url)) return true;\n\n let hostname: string;\n try {\n hostname = new URL(url).hostname.toLowerCase();\n } catch {\n return true;\n }\n if (!hostname || isIpLiteralHost(hostname)) return false;\n\n try {\n const { lookup } = await import(\"node:dns/promises\");\n const records = await lookup(hostname, { all: true, verbatim: true });\n return records.some((record) => isPrivateHost(record.address));\n } catch {\n // Some edge runtimes do not expose DNS lookup. Keep the deterministic\n // parser-based protections instead of failing every outbound request.\n return false;\n }\n}\n\n/**\n * Build an undici Dispatcher whose connect-time DNS lookup runs through a\n * private-IP guard. This closes the TOCTOU gap where:\n * 1. We resolve hostname → public IP and pass.\n * 2. Between that lookup and the actual connect, DNS rebinding flips the\n * record to a private IP.\n * 3. fetch() resolves again and connects to the private IP.\n *\n * With a custom dispatcher, the same lookup that produces the IP also gates\n * the connect: if the IP is in the private set, the connect throws.\n *\n * Returns `null` if undici / node:dns are not available (e.g. some edge\n * runtimes); the caller should fall back to the regular `fetch` path —\n * `isBlockedExtensionUrlWithDns` will still have caught most rebinding cases.\n */\nfunction normalizeLookupHostname(hostname: string): string {\n return hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n}\n\nfunction loopbackHostnameVariants(hostname: string): string[] {\n const normalized = normalizeLookupHostname(hostname);\n if (\n normalized !== \"localhost\" &&\n normalized !== \"127.0.0.1\" &&\n normalized !== \"::1\"\n ) {\n return [normalized];\n }\n // Local workspace manifests can identify the same child server as\n // localhost, 127.0.0.1, or ::1. They are equivalent only for loopback; do\n // not alias arbitrary private or public hostnames.\n return [\"localhost\", \"127.0.0.1\", \"::1\"];\n}\n\nfunction normalizeAllowedPrivateOriginKeys(\n origins: readonly string[],\n): Set<string> {\n const keys = new Set<string>();\n for (const origin of origins) {\n try {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n continue;\n }\n const port = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n for (const hostname of loopbackHostnameVariants(parsed.hostname)) {\n keys.add(`${hostname}:${port}`);\n }\n } catch {\n // coercion-ok: malformed deployment configuration is omitted, preserving the fail-closed private-IP guard.\n }\n }\n return keys;\n}\n\nfunction normalizeAllowedPrivateOriginOriginKeys(\n origins: readonly string[],\n): Set<string> {\n const keys = new Set<string>();\n for (const origin of origins) {\n try {\n const parsed = new URL(origin);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n continue;\n }\n const port = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n for (const hostname of loopbackHostnameVariants(parsed.hostname)) {\n keys.add(`${parsed.protocol}//${hostname}:${port}`);\n }\n } catch {\n // Ignore malformed deployment configuration and retain the private-IP guard.\n }\n }\n return keys;\n}\n\nexport async function createSsrfSafeDispatcher(\n allowedPrivateOrigins: readonly string[] = [],\n): Promise<unknown | null> {\n // Keep the optional undici import opaque to Vite/Rolldown. A static\n // `import(\"undici\")` makes browser builds try to resolve and bundle undici\n // even though this dispatcher is only useful in Node server runtimes.\n let undici: any;\n let dnsModule: any;\n try {\n const runtimeImport = new Function(\n \"specifier\",\n \"return import(specifier)\",\n ) as (specifier: string) => Promise<any>;\n undici = await runtimeImport(\"undici\");\n dnsModule = await import(\"node:dns\");\n } catch {\n return null;\n }\n\n const { Agent } = undici;\n const { lookup } = dnsModule;\n const allowedPrivateOriginKeys = normalizeAllowedPrivateOriginKeys(\n allowedPrivateOrigins,\n );\n if (!Agent || !lookup) return null;\n\n return new Agent({\n connect: {\n // Override DNS lookup at connect time so the IP we hand to undici's\n // socket is the one we authorized. Reject any record in the private\n // set BEFORE the TCP handshake.\n lookup: (\n hostname: string,\n options: any,\n callback: (\n err: NodeJS.ErrnoException | null,\n address?: string | { address: string; family: number }[],\n family?: number,\n ) => void,\n ) => {\n lookup(\n hostname,\n { all: true, verbatim: true },\n (err: NodeJS.ErrnoException | null, addresses: any) => {\n if (err) return callback(err);\n const list: { address: string; family: number }[] = Array.isArray(\n addresses,\n )\n ? addresses\n : [{ address: addresses, family: 4 }];\n for (const record of list) {\n const allowedOrigin = allowedPrivateOriginKeys.has(\n `${normalizeLookupHostname(hostname)}:${String(options?.port ?? \"\")}`,\n );\n if (isPrivateHost(record.address) && !allowedOrigin) {\n const e = new Error(\n `Connect blocked: ${hostname} resolved to private address ${record.address}`,\n ) as NodeJS.ErrnoException;\n e.code = \"EAI_BLOCKED\";\n return callback(e);\n }\n }\n // Mirror Node's lookup behavior: when `all` is true, return the\n // array; otherwise the first entry. undici's connect honors\n // `options.all`.\n if (options && options.all) {\n return callback(null, list as any);\n }\n const first = list[0];\n return callback(null, first.address, first.family);\n },\n );\n },\n },\n });\n}\n\n/**\n * SSRF-safe `fetch` for any server-side request to a user/agent-supplied URL.\n *\n * Applies the same protections the extension proxy uses, so every call site\n * that fetches an untrusted URL gets them without re-implementing the loop:\n * 1. Pre-flight DNS-aware private-address check (isBlockedExtensionUrlWithDns)\n * on the initial URL and on every redirect hop.\n * 2. A connect-time dispatcher that re-checks the resolved IP at TCP-connect\n * time (closes the DNS-rebinding TOCTOU) when undici is available.\n * 3. Manual redirect handling — a public URL cannot 30x-redirect into the\n * private network because each hop is re-validated before it is followed.\n *\n * Throws an Error whose message starts with \"SSRF blocked:\" when a target\n * (initial or via redirect) resolves to a private/internal address, or when the\n * redirect limit is exceeded. Otherwise returns the final Response.\n *\n * `httpsOnly` extends the per-hop validation to the URL scheme: redirects are\n * followed only to `https:` targets, so an HTTPS-only caller cannot be\n * downgraded to plain HTTP by a 30x from the (untrusted) origin.\n *\n * `assertUrlAllowed` lets callers layer a stricter destination policy (for\n * example, a credential's origin allowlist) on top of the SSRF checks. It runs\n * before the initial request and before every redirect hop, so sensitive\n * headers and bodies are never forwarded to a destination the caller rejects.\n */\nexport async function ssrfSafeFetch(\n url: string,\n init: RequestInit = {},\n options: {\n maxRedirects?: number;\n httpsOnly?: boolean;\n assertUrlAllowed?: (url: string) => void | Promise<void>;\n /**\n * Exact origins that may resolve to a private address. A workspace runs\n * every app on loopback behind one gateway, so sibling A2A calls are\n * private by construction; without this they are indistinguishable from an\n * SSRF attempt and get blocked. Only ever pass origins the deployment\n * itself configured (never a request-supplied value).\n */\n allowedPrivateOrigins?: readonly string[];\n } = {},\n): Promise<Response> {\n const maxRedirects = options.maxRedirects ?? 3;\n const dispatcher =\n (await createSsrfSafeDispatcher(options.allowedPrivateOrigins)) ??\n undefined;\n const allowedPrivateOrigins = normalizeAllowedPrivateOriginOriginKeys(\n options.allowedPrivateOrigins ?? [],\n );\n const isAllowedPrivateOrigin = (candidate: string): boolean => {\n if (allowedPrivateOrigins.size === 0) return false;\n try {\n const parsed = new URL(candidate);\n const port = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n return allowedPrivateOrigins.has(\n `${parsed.protocol}//${normalizeLookupHostname(parsed.hostname)}:${port}`,\n );\n } catch {\n return false;\n }\n };\n\n let currentUrl = url;\n for (let hop = 0; hop <= maxRedirects; hop++) {\n await options.assertUrlAllowed?.(currentUrl);\n if (options.httpsOnly && new URL(currentUrl).protocol !== \"https:\") {\n throw new Error(\n `SSRF blocked: refusing to fetch non-HTTPS address (${currentUrl})`,\n );\n }\n if (\n !isAllowedPrivateOrigin(currentUrl) &&\n (await isBlockedExtensionUrlWithDns(currentUrl))\n ) {\n throw new Error(\n `SSRF blocked: refusing to fetch private/internal address (${currentUrl})`,\n );\n }\n const fetchOpts: RequestInit & { dispatcher?: unknown } = {\n ...init,\n redirect: \"manual\",\n };\n if (dispatcher) fetchOpts.dispatcher = dispatcher;\n\n const response = await fetch(currentUrl, fetchOpts);\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get(\"location\");\n if (!location) return response;\n // Drain the redirect body so the hop's connection is released instead\n // of being held until GC.\n await response.body?.cancel().catch(() => {});\n currentUrl = new URL(location, currentUrl).href;\n continue;\n }\n return response;\n }\n throw new Error(\n `SSRF blocked: too many redirects (>${maxRedirects}) while fetching ${url}`,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Legacy aliases — predate the Tools → Extensions rename. Templates import\n// these via the legacy `@agent-native/core/tools/url-safety` subpath; keep\n// the names exported so they keep resolving until every consumer updates.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport { isBlockedExtensionUrl as isBlockedToolUrl };\nexport { isBlockedExtensionUrlWithDns as isBlockedToolUrlWithDns };\nexport { ssrfSafeFetch as ssrfSafeToolFetch };\n"]}
|
|
@@ -17,12 +17,12 @@ declare const _default: import("../../action.js").ActionDefinition<{
|
|
|
17
17
|
id?: undefined;
|
|
18
18
|
provider?: undefined;
|
|
19
19
|
} | {
|
|
20
|
+
error?: undefined;
|
|
20
21
|
configured?: undefined;
|
|
21
22
|
connectPath?: undefined;
|
|
22
23
|
url: string;
|
|
23
24
|
id: string;
|
|
24
25
|
provider: string;
|
|
25
|
-
error?: undefined;
|
|
26
26
|
}>;
|
|
27
27
|
export default _default;
|
|
28
28
|
//# sourceMappingURL=upload-image.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../../../src/integrations/adapters/slack.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EAUhB,MAAM,aAAa,CAAC;AAsErB,MAAM,WAAW,mBAAmB;IAClC,8DAA8D;IAC9D,eAAe,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC7E,kEAAkE;IAClE,cAAc,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACjE,oEAAoE;IACpE,oBAAoB,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CACxE;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,YAAY,CAC1B,OAAO,GAAE,mBAAwB,GAChC,eAAe,
|
|
1
|
+
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../../../src/integrations/adapters/slack.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EAUhB,MAAM,aAAa,CAAC;AAsErB,MAAM,WAAW,mBAAmB;IAClC,8DAA8D;IAC9D,eAAe,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC7E,kEAAkE;IAClE,cAAc,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACjE,oEAAoE;IACpE,oBAAoB,CAAC,EAAE,CAAC,QAAQ,EAAE,eAAe,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CACxE;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,YAAY,CAC1B,OAAO,GAAE,mBAAwB,GAChC,eAAe,CA6nBjB;AAkBD,wBAAsB,+BAA+B,CACnD,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS7B"}
|
|
@@ -5,7 +5,7 @@ import { getRequestContext } from "../../server/request-context.js";
|
|
|
5
5
|
import { getIntegrationRequestContext } from "../../server/request-context.js";
|
|
6
6
|
import { consumeIntegrationAwaitingInput } from "../awaiting-input-store.js";
|
|
7
7
|
import { createIntegrationControl } from "../controls-store.js";
|
|
8
|
-
import { getActiveIntegrationInstallationByKey,
|
|
8
|
+
import { getActiveIntegrationInstallationByKey, listActiveIntegrationInstallationsForTenant, listIntegrationInstallations, resolveIntegrationTokenBundle, } from "../installations-store.js";
|
|
9
9
|
import { hasActivePendingTask } from "../pending-tasks-store.js";
|
|
10
10
|
import { slackInstallationKey } from "../slack-oauth.js";
|
|
11
11
|
/** Slack's max message length */
|
|
@@ -510,13 +510,16 @@ export function slackAdapter(options = {}) {
|
|
|
510
510
|
channelId: target.destination,
|
|
511
511
|
threadTs: target.threadRef,
|
|
512
512
|
teamId: target.tenantId,
|
|
513
|
+
installationKey: target.installationKey,
|
|
513
514
|
},
|
|
514
515
|
tenantId: target.tenantId,
|
|
515
516
|
timestamp: Date.now(),
|
|
516
517
|
};
|
|
517
518
|
const token = await resolveBotToken(targetContext);
|
|
518
519
|
if (!token) {
|
|
519
|
-
console.error("[slack]
|
|
520
|
+
console.error("[slack] no bot token for outbound target" +
|
|
521
|
+
(target.tenantId ? ` (tenant ${target.tenantId})` : "") +
|
|
522
|
+
"; set SLACK_BOT_TOKEN or pass installationKey to name the app");
|
|
520
523
|
return;
|
|
521
524
|
}
|
|
522
525
|
const chunks = splitNonEmptyMessage(message.text, SLACK_MAX_LENGTH);
|
|
@@ -631,17 +634,31 @@ async function resolveManagedSlackBotToken(incoming) {
|
|
|
631
634
|
const enterpriseId = typeof incoming.platformContext.enterpriseId === "string"
|
|
632
635
|
? incoming.platformContext.enterpriseId
|
|
633
636
|
: undefined;
|
|
637
|
+
const installationKeyHint = typeof incoming.platformContext.installationKey === "string"
|
|
638
|
+
? incoming.platformContext.installationKey
|
|
639
|
+
: undefined;
|
|
634
640
|
if (!teamId && !enterpriseId)
|
|
635
641
|
return undefined;
|
|
636
642
|
try {
|
|
637
|
-
let installation =
|
|
638
|
-
? await getActiveIntegrationInstallationByKey("slack",
|
|
643
|
+
let installation = installationKeyHint
|
|
644
|
+
? await getActiveIntegrationInstallationByKey("slack", installationKeyHint)
|
|
639
645
|
: null;
|
|
640
|
-
if (!installation &&
|
|
641
|
-
installation = await
|
|
646
|
+
if (!installation && apiAppId) {
|
|
647
|
+
installation = await getActiveIntegrationInstallationByKey("slack", slackInstallationKey({ teamId, enterpriseId, apiAppId }));
|
|
642
648
|
}
|
|
643
|
-
if (!installation && !apiAppId
|
|
644
|
-
|
|
649
|
+
if (!installation && !apiAppId) {
|
|
650
|
+
// Without an app id the tenant can match several connected Slack apps.
|
|
651
|
+
// Sending as an arbitrary one posts under the wrong bot identity, so
|
|
652
|
+
// only proceed when the tenant resolves to exactly one installation.
|
|
653
|
+
const tenant = teamId ?? enterpriseId;
|
|
654
|
+
const candidates = await listActiveIntegrationInstallationsForTenant("slack", tenant);
|
|
655
|
+
if (candidates.length > 1) {
|
|
656
|
+
console.error(`[slack] ${candidates.length} connected Slack apps for tenant ${tenant}; ` +
|
|
657
|
+
`cannot choose one without an app id. Pass installationKey on the outbound target. ` +
|
|
658
|
+
`Candidates: ${candidates.map((c) => c.installationKey).join(", ")}`);
|
|
659
|
+
return undefined;
|
|
660
|
+
}
|
|
661
|
+
installation = candidates[0] ?? null;
|
|
645
662
|
}
|
|
646
663
|
const key = installation?.installationKey ??
|
|
647
664
|
slackInstallationKey({ teamId, enterpriseId, apiAppId });
|