@agent-native/core 0.101.2 → 0.101.4
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 +1 -1
- package/corpus/core/CHANGELOG.md +25 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/client/RunStuckBanner.tsx +12 -5
- package/corpus/core/src/client/sse-event-processor.ts +36 -1
- package/corpus/core/src/client/use-run-stuck-detection.ts +162 -25
- package/corpus/core/src/credentials/index.ts +41 -8
- package/corpus/core/src/deploy/build.ts +78 -25
- package/corpus/core/src/extensions/fetch-tool.ts +33 -3
- package/corpus/core/src/notifications/channels.ts +20 -6
- package/corpus/core/src/secrets/crypto.ts +26 -10
- package/corpus/core/src/secrets/storage.ts +16 -3
- package/corpus/core/src/server/agent-chat-plugin.ts +60 -7
- package/corpus/core/src/server/derived-secret.ts +5 -1
- package/corpus/templates/analytics/changelog/2026-07-14-long-running-cross-app-analyses-now-continue-reliably-in-the.md +6 -0
- package/corpus/templates/analytics/server/plugins/agent-chat.ts +8 -4
- package/corpus/templates/chat/changelog/2026-07-14-chat-opens-reliably-on-hosted-deployments-instead-of-failing.md +6 -0
- package/corpus/templates/clips/app/components/player/media-duration.ts +24 -0
- package/corpus/templates/clips/app/components/player/share-dialog.tsx +44 -81
- package/corpus/templates/clips/app/components/player/video-player.tsx +9 -18
- package/corpus/templates/clips/app/i18n/ar-SA.ts +0 -8
- package/corpus/templates/clips/app/i18n/de-DE.ts +0 -9
- package/corpus/templates/clips/app/i18n/en-US.ts +0 -8
- package/corpus/templates/clips/app/i18n/es-ES.ts +0 -9
- package/corpus/templates/clips/app/i18n/fr-FR.ts +0 -9
- package/corpus/templates/clips/app/i18n/hi-IN.ts +0 -8
- package/corpus/templates/clips/app/i18n/ja-JP.ts +0 -9
- package/corpus/templates/clips/app/i18n/ko-KR.ts +0 -9
- package/corpus/templates/clips/app/i18n/pt-BR.ts +0 -9
- package/corpus/templates/clips/app/i18n/zh-CN.ts +0 -7
- package/corpus/templates/clips/app/i18n/zh-TW.ts +0 -7
- package/corpus/templates/clips/changelog/2026-07-14-paused-time-no-longer-counts-toward-chrome-extension-recordi.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-14-share-dialogs-show-separate-links-for-people-and-agents.md +6 -0
- package/corpus/templates/clips/chrome-extension/src/offscreen.ts +30 -4
- package/corpus/templates/clips/chrome-extension/src/recording-duration.ts +32 -0
- package/corpus/templates/dispatch/changelog/2026-07-14-dispatch-now-distinguishes-connected-agents-from-locally-mou.md +6 -0
- package/corpus/templates/slides/actions/_uploaded-files.ts +13 -2
- package/corpus/templates/slides/actions/import-docx.ts +3 -9
- package/corpus/templates/slides/actions/import-file.ts +11 -14
- package/corpus/templates/slides/actions/import-pptx.ts +3 -9
- package/corpus/templates/slides/changelog/2026-07-14-powerpoint-template-uploads-now-work-in-hosted-slides-deploy.md +6 -0
- package/corpus/templates/slides/server/handlers/uploads.ts +100 -50
- package/corpus/templates/slides/server/lib/tenant-files.ts +38 -11
- package/corpus/templates/slides/server/lib/uploaded-reference-storage.ts +108 -0
- package/dist/client/RunStuckBanner.d.ts.map +1 -1
- package/dist/client/RunStuckBanner.js +9 -5
- package/dist/client/RunStuckBanner.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +33 -1
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/client/use-run-stuck-detection.d.ts +4 -4
- package/dist/client/use-run-stuck-detection.d.ts.map +1 -1
- package/dist/client/use-run-stuck-detection.js +104 -19
- package/dist/client/use-run-stuck-detection.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/credentials/index.d.ts +12 -7
- package/dist/credentials/index.d.ts.map +1 -1
- package/dist/credentials/index.js +33 -8
- package/dist/credentials/index.js.map +1 -1
- package/dist/deploy/build.d.ts +15 -14
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +64 -23
- package/dist/deploy/build.js.map +1 -1
- package/dist/extensions/fetch-tool.d.ts +13 -1
- package/dist/extensions/fetch-tool.d.ts.map +1 -1
- package/dist/extensions/fetch-tool.js +9 -2
- package/dist/extensions/fetch-tool.js.map +1 -1
- package/dist/notifications/channels.js +20 -4
- package/dist/notifications/channels.js.map +1 -1
- package/dist/observability/routes.d.ts +1 -1
- package/dist/progress/routes.d.ts +1 -1
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/secrets/crypto.d.ts +15 -7
- package/dist/secrets/crypto.d.ts.map +1 -1
- package/dist/secrets/crypto.js +23 -10
- package/dist/secrets/crypto.js.map +1 -1
- package/dist/secrets/storage.d.ts.map +1 -1
- package/dist/secrets/storage.js +16 -3
- package/dist/secrets/storage.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +20 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +38 -4
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/derived-secret.d.ts +1 -1
- package/dist/server/derived-secret.d.ts.map +1 -1
- package/dist/server/derived-secret.js.map +1 -1
- package/package.json +2 -2
- package/corpus/templates/clips/app/components/sharing/slack-share-hint.tsx +0 -68
|
@@ -10,15 +10,27 @@
|
|
|
10
10
|
* the raw secret never enters the model's context.
|
|
11
11
|
*/
|
|
12
12
|
import type { ActionEntry } from "../agent/production-agent.js";
|
|
13
|
+
import type { ResolvedKeyReference } from "../secrets/substitution.js";
|
|
13
14
|
export interface FetchToolOptions {
|
|
14
15
|
/** Resolve ${keys.NAME} references. Injected by the plugin at setup time. */
|
|
15
16
|
resolveKeys?: (text: string) => Promise<{
|
|
16
17
|
resolved: string;
|
|
17
18
|
usedKeys: string[];
|
|
18
19
|
secretValues?: string[];
|
|
20
|
+
/**
|
|
21
|
+
* Optional: which scope (user/org/workspace) each used key actually
|
|
22
|
+
* resolved at. Populated by resolvers like
|
|
23
|
+
* `resolveKeyReferencesWithRequestScopes` so `validateUrl` can look up
|
|
24
|
+
* the allowlist at the scope the value came from rather than assuming
|
|
25
|
+
* user scope. Backwards compatible — callers that omit this (or a
|
|
26
|
+
* resolver that doesn't report it) are unaffected.
|
|
27
|
+
*/
|
|
28
|
+
resolvedKeys?: ResolvedKeyReference[];
|
|
19
29
|
}>;
|
|
20
30
|
/** Validate URL against per-key allowlists. */
|
|
21
|
-
validateUrl?: (url: string, usedKeys: string[]
|
|
31
|
+
validateUrl?: (url: string, usedKeys: string[],
|
|
32
|
+
/** Accumulated `resolvedKeys` from every `resolveKeys` call this request made, when the resolver reported them. */
|
|
33
|
+
resolvedKeys?: ResolvedKeyReference[]) => Promise<boolean>;
|
|
22
34
|
}
|
|
23
35
|
/**
|
|
24
36
|
* Create the fetch tool entry for the agent tool registry.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-tool.d.ts","sourceRoot":"","sources":["../../src/extensions/fetch-tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"fetch-tool.d.ts","sourceRoot":"","sources":["../../src/extensions/fetch-tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AA6DvE,MAAM,WAAW,gBAAgB;IAC/B,6EAA6E;IAC7E,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;QACtC,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;QACxB;;;;;;;WAOG;QACH,YAAY,CAAC,EAAE,oBAAoB,EAAE,CAAC;KACvC,CAAC,CAAC;IACH,+CAA+C;IAC/C,WAAW,CAAC,EAAE,CACZ,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAAE;IAClB,mHAAmH;IACnH,YAAY,CAAC,EAAE,oBAAoB,EAAE,KAClC,OAAO,CAAC,OAAO,CAAC,CAAC;CACvB;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,GAAE,gBAAqB,GAC1B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CA8V7B"}
|
|
@@ -153,21 +153,25 @@ export function createFetchToolEntry(opts = {}) {
|
|
|
153
153
|
let resolvedBody = rawBody;
|
|
154
154
|
const allUsedKeys = [];
|
|
155
155
|
const allSecretValues = [];
|
|
156
|
+
const allResolvedKeys = [];
|
|
156
157
|
if (opts.resolveKeys) {
|
|
157
158
|
try {
|
|
158
159
|
const urlResult = await opts.resolveKeys(rawUrl);
|
|
159
160
|
resolvedUrl = urlResult.resolved;
|
|
160
161
|
allUsedKeys.push(...urlResult.usedKeys);
|
|
161
162
|
allSecretValues.push(...(urlResult.secretValues ?? []));
|
|
163
|
+
allResolvedKeys.push(...(urlResult.resolvedKeys ?? []));
|
|
162
164
|
const headerResult = await opts.resolveKeys(rawHeaders);
|
|
163
165
|
resolvedHeaders = headerResult.resolved;
|
|
164
166
|
allUsedKeys.push(...headerResult.usedKeys);
|
|
165
167
|
allSecretValues.push(...(headerResult.secretValues ?? []));
|
|
168
|
+
allResolvedKeys.push(...(headerResult.resolvedKeys ?? []));
|
|
166
169
|
if (rawBody) {
|
|
167
170
|
const bodyResult = await opts.resolveKeys(rawBody);
|
|
168
171
|
resolvedBody = bodyResult.resolved;
|
|
169
172
|
allUsedKeys.push(...bodyResult.usedKeys);
|
|
170
173
|
allSecretValues.push(...(bodyResult.secretValues ?? []));
|
|
174
|
+
allResolvedKeys.push(...(bodyResult.resolvedKeys ?? []));
|
|
171
175
|
}
|
|
172
176
|
}
|
|
173
177
|
catch (err) {
|
|
@@ -175,6 +179,9 @@ export function createFetchToolEntry(opts = {}) {
|
|
|
175
179
|
}
|
|
176
180
|
}
|
|
177
181
|
const secretValues = collectSecretValues(allSecretValues);
|
|
182
|
+
const resolvedKeys = allResolvedKeys.length
|
|
183
|
+
? allResolvedKeys
|
|
184
|
+
: undefined;
|
|
178
185
|
// Block SSRF targets regardless of key usage
|
|
179
186
|
if (await isBlockedExtensionUrlWithDns(resolvedUrl)) {
|
|
180
187
|
return `Requests to private/internal addresses are not allowed: "${rawUrl}".`;
|
|
@@ -182,7 +189,7 @@ export function createFetchToolEntry(opts = {}) {
|
|
|
182
189
|
// Validate URL against per-key allowlists
|
|
183
190
|
if (opts.validateUrl && allUsedKeys.length > 0) {
|
|
184
191
|
try {
|
|
185
|
-
const allowed = await opts.validateUrl(resolvedUrl, allUsedKeys);
|
|
192
|
+
const allowed = await opts.validateUrl(resolvedUrl, allUsedKeys, resolvedKeys);
|
|
186
193
|
if (!allowed) {
|
|
187
194
|
return `URL "${rawUrl}" is not in the allowlist for the referenced keys. Check your key settings.`;
|
|
188
195
|
}
|
|
@@ -236,7 +243,7 @@ export function createFetchToolEntry(opts = {}) {
|
|
|
236
243
|
return "Redirect to private/internal address blocked.";
|
|
237
244
|
}
|
|
238
245
|
if (redirectUrl && opts.validateUrl && allUsedKeys.length > 0) {
|
|
239
|
-
const allowed = await opts.validateUrl(redirectUrl, allUsedKeys);
|
|
246
|
+
const allowed = await opts.validateUrl(redirectUrl, allUsedKeys, resolvedKeys);
|
|
240
247
|
if (!allowed) {
|
|
241
248
|
return "Redirect URL is not in the allowlist for the referenced keys.";
|
|
242
249
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-tool.js","sourceRoot":"","sources":["../../src/extensions/fetch-tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EACL,mBAAmB,EACnB,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,EACzB,aAAa,EACb,YAAY,EACZ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AAC;gBACxB,CAAC;YACH,CAAC;YACD,QAAQ,EAAE,IAAI;SACf;KACF,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACtD,OAAO,UAAU,KAAK,MAAM,IAAI,UAAU,KAAK,GAAG,IAAI,UAAU,KAAK,KAAK,CAAC;AAC7E,CAAC","sourcesContent":["/**\n * Fetch tool — outbound HTTP for automations and agent use.\n *\n * NOTE: this is an *agent* tool (LLM function call), not an *extension* (the\n * sandboxed Alpine.js mini-app primitive). It lives in this directory because\n * it shares SSRF-safe URL/proxy helpers with the extension iframe proxy.\n *\n * Supports ${keys.NAME} reference substitution in URL, headers, and body.\n * Values are resolved server-side AFTER the model emits the tool call —\n * the raw secret never enters the model's context.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport {\n collectSecretValues,\n MAX_EXTENSION_PROXY_RESPONSE_SIZE,\n normalizeExtensionProxyMethod,\n readResponseTextWithLimit,\n redactSecrets,\n redactString,\n sanitizeOutboundHeaders,\n} from \"./proxy-security.js\";\nimport {\n createSsrfSafeDispatcher,\n isBlockedExtensionUrlWithDns,\n} from \"./url-safety.js\";\nimport {\n formatWebContentResult,\n parseWebContentSearchOptions,\n processWebContent,\n} from \"./web-content.js\";\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Headers that mimic a current Chrome on macOS so anti-bot middleware (Cloudflare,\n * PerimeterX, Akamai) treats the request as a real user. We only fill in fields\n * the caller hasn't supplied — explicit headers (e.g. an `Authorization` header\n * for an API call) always win.\n *\n * `Accept-Encoding` deliberately omits `zstd` because Node's undici fetch only\n * decompresses `gzip`, `deflate`, and `br`. Advertising `zstd` would let some\n * servers send bytes we can't decode.\n */\nconst BROWSER_DEFAULT_HEADERS: Record<string, string> = {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n Accept:\n \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Sec-Ch-Ua\":\n '\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n \"Sec-Ch-Ua-Mobile\": \"?0\",\n \"Sec-Ch-Ua-Platform\": '\"macOS\"',\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n \"Upgrade-Insecure-Requests\": \"1\",\n};\n\nfunction applyBrowserDefaults(\n headers: Record<string, string>,\n): Record<string, string> {\n const seen = new Set(Object.keys(headers).map((k) => k.toLowerCase()));\n const merged = { ...headers };\n for (const [name, value] of Object.entries(BROWSER_DEFAULT_HEADERS)) {\n if (!seen.has(name.toLowerCase())) merged[name] = value;\n }\n return merged;\n}\n\nexport interface FetchToolOptions {\n /** Resolve ${keys.NAME} references. Injected by the plugin at setup time. */\n resolveKeys?: (text: string) => Promise<{\n resolved: string;\n usedKeys: string[];\n secretValues?: string[];\n }>;\n /** Validate URL against per-key allowlists. */\n validateUrl?: (url: string, usedKeys: string[]) => Promise<boolean>;\n}\n\n/**\n * Create the fetch tool entry for the agent tool registry.\n */\nexport function createFetchToolEntry(\n opts: FetchToolOptions = {},\n): Record<string, ActionEntry> {\n return {\n \"web-request\": {\n tool: {\n description: `Make an outbound HTTP request to any EXTERNAL URL — APIs, webhooks, and arbitrary web pages (HTML, RSS, JSON, etc.). Use this to fetch the contents of a URL the user pastes in chat. Sends realistic Chrome-on-macOS headers by default (User-Agent, Accept, Sec-Fetch-*) so most sites that block obvious bots will respond normally; pass an explicit header to override any default. Supports \\${keys.NAME} placeholders in url, headers, and body — these are resolved server-side from the user's saved keys (the raw value never enters your context). Example: \\${keys.SLACK_WEBHOOK} in the url field. IMPORTANT: Never use this to call internal /_agent-native/ endpoints or localhost action URLs — use the registered actions directly (e.g. \\`search-records\\`, \\`provider-api-request\\`, \\`update-resource\\`). Actions are already available as native tools; calling them via HTTP is slower and bypasses validation.`,\n parameters: {\n type: \"object\" as const,\n properties: {\n url: {\n type: \"string\",\n description:\n 'Full URL. May contain ${keys.NAME} references, e.g. \"${keys.SLACK_WEBHOOK}\".',\n },\n method: {\n type: \"string\",\n description: \"HTTP method. Default: GET.\",\n enum: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\"],\n },\n headers: {\n type: \"string\",\n description:\n 'JSON object of headers. May contain ${keys.NAME} references. Example: \\'{\"Authorization\": \"Bearer ${keys.API_TOKEN}\"}\\'.',\n },\n body: {\n type: \"string\",\n description:\n \"Request body (for POST/PUT/PATCH). May contain ${keys.NAME} references.\",\n },\n timeout_ms: {\n type: \"number\",\n description: `Timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: 30000.`,\n },\n maxChars: {\n type: \"number\",\n description:\n \"Maximum response body characters to return. Default: 32000. Max: 200000. Increase when you need to read a large document, API response, or dataset.\",\n },\n responseMode: {\n type: \"string\",\n description:\n \"How to return the response. Default: auto (HTML pages become clean markdown; JSON/text stays raw). Use raw for exact bytes, markdown/text for extracted readable content, links for just links, metadata for page metadata, or matches with search.\",\n enum: [\n \"auto\",\n \"raw\",\n \"text\",\n \"markdown\",\n \"links\",\n \"metadata\",\n \"matches\",\n ],\n },\n extract: {\n type: \"string\",\n description:\n \"HTML extraction strategy. Default: readability. Use all-visible for visible body text/markdown, or none to convert the full HTML document.\",\n enum: [\"readability\", \"all-visible\", \"none\"],\n },\n includeLinks: {\n type: \"boolean\",\n description:\n \"Whether extracted HTML responses should include a compact links list. Default: true for extracted pages.\",\n },\n search: {\n type: \"object\",\n description:\n \"Optional post-fetch search over extracted content by default. Supports {query, queries, terms, regex, regexFlags, source:'extracted'|'raw', maxMatches, contextChars, caseSensitive}. Regex is safety-checked and bounded; prefer query/terms for simple grep-like searches.\",\n properties: {\n query: { type: \"string\" },\n queries: { type: \"array\", items: { type: \"string\" } },\n terms: { type: \"array\", items: { type: \"string\" } },\n regex: { type: \"string\" },\n regexFlags: { type: \"string\" },\n source: { type: \"string\", enum: [\"extracted\", \"raw\"] },\n maxMatches: { type: \"number\" },\n contextChars: { type: \"number\" },\n caseSensitive: { type: \"boolean\" },\n },\n } as any,\n saveToFile: {\n type: \"string\",\n description:\n \"Workspace file path to save the full response body to instead of returning it in context (e.g. 'analysis/page.html'). When set, returns only a compact summary {savedTo, status, bytes, preview}. Useful for large web pages or API responses that would overflow context.\",\n },\n },\n required: [\"url\"],\n },\n },\n run: async (args: Record<string, unknown>) => {\n const startTime = Date.now();\n const rawUrl = String(args.url ?? \"\");\n const method = normalizeExtensionProxyMethod(args.method || \"GET\");\n if (!method) {\n return \"Unsupported HTTP method. Allowed methods: GET, POST, PUT, PATCH, DELETE, HEAD.\";\n }\n const rawHeaders =\n typeof args.headers === \"string\"\n ? args.headers\n : JSON.stringify(args.headers ?? {});\n const rawBody =\n typeof args.body === \"string\"\n ? args.body\n : args.body === undefined || args.body === null\n ? undefined\n : JSON.stringify(args.body);\n const timeoutMs = Math.min(\n Number(args.timeout_ms) || DEFAULT_TIMEOUT_MS,\n 30_000,\n );\n const requestedMaxChars = Number(args.maxChars);\n const maxChars =\n Number.isFinite(requestedMaxChars) && requestedMaxChars > 0\n ? Math.min(requestedMaxChars, 200_000)\n : 32_000;\n\n // Resolve key references\n let resolvedUrl = rawUrl;\n let resolvedHeaders = rawHeaders;\n let resolvedBody = rawBody;\n const allUsedKeys: string[] = [];\n const allSecretValues: string[] = [];\n\n if (opts.resolveKeys) {\n try {\n const urlResult = await opts.resolveKeys(rawUrl);\n resolvedUrl = urlResult.resolved;\n allUsedKeys.push(...urlResult.usedKeys);\n allSecretValues.push(...(urlResult.secretValues ?? []));\n\n const headerResult = await opts.resolveKeys(rawHeaders);\n resolvedHeaders = headerResult.resolved;\n allUsedKeys.push(...headerResult.usedKeys);\n allSecretValues.push(...(headerResult.secretValues ?? []));\n\n if (rawBody) {\n const bodyResult = await opts.resolveKeys(rawBody);\n resolvedBody = bodyResult.resolved;\n allUsedKeys.push(...bodyResult.usedKeys);\n allSecretValues.push(...(bodyResult.secretValues ?? []));\n }\n } catch (err: any) {\n return `Error resolving key references: ${err?.message ?? err}`;\n }\n }\n const secretValues = collectSecretValues(allSecretValues);\n\n // Block SSRF targets regardless of key usage\n if (await isBlockedExtensionUrlWithDns(resolvedUrl)) {\n return `Requests to private/internal addresses are not allowed: \"${rawUrl}\".`;\n }\n\n // Validate URL against per-key allowlists\n if (opts.validateUrl && allUsedKeys.length > 0) {\n try {\n const allowed = await opts.validateUrl(resolvedUrl, allUsedKeys);\n if (!allowed) {\n return `URL \"${rawUrl}\" is not in the allowlist for the referenced keys. Check your key settings.`;\n }\n } catch (err: any) {\n return `URL validation error: ${err?.message ?? err}`;\n }\n }\n\n // Parse headers, then merge in browser-like defaults for any header the\n // caller didn't already specify. Real-browser headers (User-Agent,\n // Accept, Sec-Fetch-*) are what gets you past Cloudflare / PerimeterX /\n // generic UA-sniffing middleware on sites the user pastes in chat;\n // explicit caller headers always win so API calls keep their auth\n // headers untouched.\n let headers: Record<string, string>;\n try {\n headers = sanitizeOutboundHeaders(JSON.parse(resolvedHeaders));\n } catch {\n return `Invalid headers JSON: ${rawHeaders}`;\n }\n headers = applyBrowserDefaults(headers);\n\n // Make the request\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const dispatcher = (await createSsrfSafeDispatcher()) ?? undefined;\n const fetchOpts: RequestInit & { dispatcher?: unknown } = {\n method,\n headers,\n signal: controller.signal,\n redirect: \"manual\",\n };\n if (dispatcher) fetchOpts.dispatcher = dispatcher;\n if (resolvedBody && [\"POST\", \"PUT\", \"PATCH\"].includes(method)) {\n fetchOpts.body = resolvedBody;\n if (!headers[\"content-type\"] && !headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n }\n\n const response = await fetch(resolvedUrl, fetchOpts);\n const elapsed = Date.now() - startTime;\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get(\"location\");\n const redirectUrl = location\n ? new URL(location, resolvedUrl).href\n : null;\n if (\n redirectUrl &&\n (await isBlockedExtensionUrlWithDns(redirectUrl))\n ) {\n return \"Redirect to private/internal address blocked.\";\n }\n if (redirectUrl && opts.validateUrl && allUsedKeys.length > 0) {\n const allowed = await opts.validateUrl(redirectUrl, allUsedKeys);\n if (!allowed) {\n return \"Redirect URL is not in the allowlist for the referenced keys.\";\n }\n }\n return `HTTP ${response.status} ${response.statusText}\\n\\nRedirect: ${\n redirectUrl ? redactString(redirectUrl, secretValues) : \"(none)\"\n }`;\n }\n\n // Check if caller wants to save to workspace file (before truncation).\n const saveToFilePath =\n typeof (args as Record<string, unknown>).saveToFile === \"string\"\n ? ((args as Record<string, unknown>).saveToFile as string).trim()\n : \"\";\n\n let body: string;\n try {\n // When saving to file allow larger reads (20MB), otherwise cap at proxy limit.\n const readLimit = saveToFilePath\n ? 20 * 1024 * 1024\n : MAX_EXTENSION_PROXY_RESPONSE_SIZE;\n const result = await readResponseTextWithLimit(response, readLimit);\n body = result.text;\n } catch {\n body = \"(could not read response body)\";\n }\n body = redactString(body, secretValues);\n const contentType =\n response.headers.get(\"content-type\")?.split(\";\")[0].trim() ??\n \"text/plain\";\n let displayBody: string;\n let processedMode = \"raw\";\n try {\n const processed = processWebContent({\n url: resolvedUrl,\n body,\n contentType,\n responseMode: String(args.responseMode ?? \"auto\"),\n extract: String(args.extract ?? \"readability\"),\n includeLinks:\n args.includeLinks === undefined\n ? true\n : parseBooleanArg(args.includeLinks),\n search: parseWebContentSearchOptions(args.search),\n maxChars,\n });\n processedMode = processed.mode;\n displayBody = formatWebContentResult(processed);\n } catch (err: any) {\n return `web-request post-processing error: ${err?.message ?? String(err)}`;\n }\n\n // Audit log\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → ${response.status} (${elapsed}ms, keys: ${allUsedKeys.join(\",\") || \"none\"})`,\n );\n\n // saveToFile: write full body to workspace and return compact summary.\n if (saveToFilePath) {\n try {\n const { writeWorkspaceFile, SAVE_TO_FILE_MAX_BYTES } =\n await import(\"../workspace-files/store.js\");\n const { getRequestOrgId, getRequestUserEmail } =\n await import(\"../server/request-context.js\");\n const orgId = getRequestOrgId();\n const email = getRequestUserEmail();\n const scope = orgId\n ? { scope: \"org\" as const, scopeId: orgId }\n : email\n ? { scope: \"user\" as const, scopeId: email }\n : null;\n if (!scope)\n throw new Error(\"No authenticated context for saveToFile\");\n await writeWorkspaceFile(\n scope,\n saveToFilePath,\n body,\n contentType,\n {\n maxFileBytes: SAVE_TO_FILE_MAX_BYTES,\n },\n );\n const bytes = Buffer.byteLength(body, \"utf8\");\n const preview = displayBody.slice(0, 2000);\n return JSON.stringify({\n savedToFile: true,\n savedTo: saveToFilePath,\n status: response.status,\n bytes,\n contentType,\n responseMode: processedMode,\n preview:\n preview.length < displayBody.length ? `${preview}…` : preview,\n });\n } catch (saveErr: any) {\n return `saveToFile error: ${saveErr?.message ?? String(saveErr)}\\n\\nHTTP ${response.status} ${response.statusText}\\n\\n${body.slice(0, maxChars)}`;\n }\n }\n\n return `HTTP ${response.status} ${response.statusText}\\n\\n${displayBody}`;\n } catch (err: any) {\n const elapsed = Date.now() - startTime;\n if (err?.name === \"AbortError\") {\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → TIMEOUT (${elapsed}ms)`,\n );\n return `Request timed out after ${timeoutMs}ms.`;\n }\n const message = redactSecrets(\n err?.message ?? String(err),\n secretValues,\n );\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → ERROR: ${message} (${elapsed}ms)`,\n );\n return `Request failed: ${message}`;\n } finally {\n clearTimeout(timeout);\n }\n },\n readOnly: true,\n },\n };\n}\n\nfunction parseBooleanArg(value: unknown): boolean {\n if (typeof value === \"boolean\") return value;\n const normalized = String(value).trim().toLowerCase();\n return normalized === \"true\" || normalized === \"1\" || normalized === \"yes\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch-tool.js","sourceRoot":"","sources":["../../src/extensions/fetch-tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EACL,mBAAmB,EACnB,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,EACzB,aAAa,EACb,YAAY,EACZ,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;;;;;;;GASG;AACH,MAAM,uBAAuB,GAA2B;IACtD,YAAY,EACV,uHAAuH;IACzH,MAAM,EACJ,kGAAkG;IACpG,iBAAiB,EAAE,gBAAgB;IACnC,iBAAiB,EAAE,mBAAmB;IACtC,WAAW,EACT,mEAAmE;IACrE,kBAAkB,EAAE,IAAI;IACxB,oBAAoB,EAAE,SAAS;IAC/B,gBAAgB,EAAE,UAAU;IAC5B,gBAAgB,EAAE,UAAU;IAC5B,gBAAgB,EAAE,MAAM;IACxB,gBAAgB,EAAE,IAAI;IACtB,2BAA2B,EAAE,GAAG;CACjC,CAAC;AAEF,SAAS,oBAAoB,CAC3B,OAA+B;IAE/B,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;IACvE,MAAM,MAAM,GAA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\n * NOTE: this is an *agent* tool (LLM function call), not an *extension* (the\n * sandboxed Alpine.js mini-app primitive). It lives in this directory because\n * it shares SSRF-safe URL/proxy helpers with the extension iframe proxy.\n *\n * Supports ${keys.NAME} reference substitution in URL, headers, and body.\n * Values are resolved server-side AFTER the model emits the tool call —\n * the raw secret never enters the model's context.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ResolvedKeyReference } from \"../secrets/substitution.js\";\nimport {\n collectSecretValues,\n MAX_EXTENSION_PROXY_RESPONSE_SIZE,\n normalizeExtensionProxyMethod,\n readResponseTextWithLimit,\n redactSecrets,\n redactString,\n sanitizeOutboundHeaders,\n} from \"./proxy-security.js\";\nimport {\n createSsrfSafeDispatcher,\n isBlockedExtensionUrlWithDns,\n} from \"./url-safety.js\";\nimport {\n formatWebContentResult,\n parseWebContentSearchOptions,\n processWebContent,\n} from \"./web-content.js\";\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Headers that mimic a current Chrome on macOS so anti-bot middleware (Cloudflare,\n * PerimeterX, Akamai) treats the request as a real user. We only fill in fields\n * the caller hasn't supplied — explicit headers (e.g. an `Authorization` header\n * for an API call) always win.\n *\n * `Accept-Encoding` deliberately omits `zstd` because Node's undici fetch only\n * decompresses `gzip`, `deflate`, and `br`. Advertising `zstd` would let some\n * servers send bytes we can't decode.\n */\nconst BROWSER_DEFAULT_HEADERS: Record<string, string> = {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n Accept:\n \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Sec-Ch-Ua\":\n '\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n \"Sec-Ch-Ua-Mobile\": \"?0\",\n \"Sec-Ch-Ua-Platform\": '\"macOS\"',\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n \"Upgrade-Insecure-Requests\": \"1\",\n};\n\nfunction applyBrowserDefaults(\n headers: Record<string, string>,\n): Record<string, string> {\n const seen = new Set(Object.keys(headers).map((k) => k.toLowerCase()));\n const merged = { ...headers };\n for (const [name, value] of Object.entries(BROWSER_DEFAULT_HEADERS)) {\n if (!seen.has(name.toLowerCase())) merged[name] = value;\n }\n return merged;\n}\n\nexport interface FetchToolOptions {\n /** Resolve ${keys.NAME} references. Injected by the plugin at setup time. */\n resolveKeys?: (text: string) => Promise<{\n resolved: string;\n usedKeys: string[];\n secretValues?: string[];\n /**\n * Optional: which scope (user/org/workspace) each used key actually\n * resolved at. Populated by resolvers like\n * `resolveKeyReferencesWithRequestScopes` so `validateUrl` can look up\n * the allowlist at the scope the value came from rather than assuming\n * user scope. Backwards compatible — callers that omit this (or a\n * resolver that doesn't report it) are unaffected.\n */\n resolvedKeys?: ResolvedKeyReference[];\n }>;\n /** Validate URL against per-key allowlists. */\n validateUrl?: (\n url: string,\n usedKeys: string[],\n /** Accumulated `resolvedKeys` from every `resolveKeys` call this request made, when the resolver reported them. */\n resolvedKeys?: ResolvedKeyReference[],\n ) => Promise<boolean>;\n}\n\n/**\n * Create the fetch tool entry for the agent tool registry.\n */\nexport function createFetchToolEntry(\n opts: FetchToolOptions = {},\n): Record<string, ActionEntry> {\n return {\n \"web-request\": {\n tool: {\n description: `Make an outbound HTTP request to any EXTERNAL URL — APIs, webhooks, and arbitrary web pages (HTML, RSS, JSON, etc.). Use this to fetch the contents of a URL the user pastes in chat. Sends realistic Chrome-on-macOS headers by default (User-Agent, Accept, Sec-Fetch-*) so most sites that block obvious bots will respond normally; pass an explicit header to override any default. Supports \\${keys.NAME} placeholders in url, headers, and body — these are resolved server-side from the user's saved keys (the raw value never enters your context). Example: \\${keys.SLACK_WEBHOOK} in the url field. IMPORTANT: Never use this to call internal /_agent-native/ endpoints or localhost action URLs — use the registered actions directly (e.g. \\`search-records\\`, \\`provider-api-request\\`, \\`update-resource\\`). Actions are already available as native tools; calling them via HTTP is slower and bypasses validation.`,\n parameters: {\n type: \"object\" as const,\n properties: {\n url: {\n type: \"string\",\n description:\n 'Full URL. May contain ${keys.NAME} references, e.g. \"${keys.SLACK_WEBHOOK}\".',\n },\n method: {\n type: \"string\",\n description: \"HTTP method. Default: GET.\",\n enum: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\"],\n },\n headers: {\n type: \"string\",\n description:\n 'JSON object of headers. May contain ${keys.NAME} references. Example: \\'{\"Authorization\": \"Bearer ${keys.API_TOKEN}\"}\\'.',\n },\n body: {\n type: \"string\",\n description:\n \"Request body (for POST/PUT/PATCH). May contain ${keys.NAME} references.\",\n },\n timeout_ms: {\n type: \"number\",\n description: `Timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: 30000.`,\n },\n maxChars: {\n type: \"number\",\n description:\n \"Maximum response body characters to return. Default: 32000. Max: 200000. Increase when you need to read a large document, API response, or dataset.\",\n },\n responseMode: {\n type: \"string\",\n description:\n \"How to return the response. Default: auto (HTML pages become clean markdown; JSON/text stays raw). Use raw for exact bytes, markdown/text for extracted readable content, links for just links, metadata for page metadata, or matches with search.\",\n enum: [\n \"auto\",\n \"raw\",\n \"text\",\n \"markdown\",\n \"links\",\n \"metadata\",\n \"matches\",\n ],\n },\n extract: {\n type: \"string\",\n description:\n \"HTML extraction strategy. Default: readability. Use all-visible for visible body text/markdown, or none to convert the full HTML document.\",\n enum: [\"readability\", \"all-visible\", \"none\"],\n },\n includeLinks: {\n type: \"boolean\",\n description:\n \"Whether extracted HTML responses should include a compact links list. Default: true for extracted pages.\",\n },\n search: {\n type: \"object\",\n description:\n \"Optional post-fetch search over extracted content by default. Supports {query, queries, terms, regex, regexFlags, source:'extracted'|'raw', maxMatches, contextChars, caseSensitive}. Regex is safety-checked and bounded; prefer query/terms for simple grep-like searches.\",\n properties: {\n query: { type: \"string\" },\n queries: { type: \"array\", items: { type: \"string\" } },\n terms: { type: \"array\", items: { type: \"string\" } },\n regex: { type: \"string\" },\n regexFlags: { type: \"string\" },\n source: { type: \"string\", enum: [\"extracted\", \"raw\"] },\n maxMatches: { type: \"number\" },\n contextChars: { type: \"number\" },\n caseSensitive: { type: \"boolean\" },\n },\n } as any,\n saveToFile: {\n type: \"string\",\n description:\n \"Workspace file path to save the full response body to instead of returning it in context (e.g. 'analysis/page.html'). When set, returns only a compact summary {savedTo, status, bytes, preview}. Useful for large web pages or API responses that would overflow context.\",\n },\n },\n required: [\"url\"],\n },\n },\n run: async (args: Record<string, unknown>) => {\n const startTime = Date.now();\n const rawUrl = String(args.url ?? \"\");\n const method = normalizeExtensionProxyMethod(args.method || \"GET\");\n if (!method) {\n return \"Unsupported HTTP method. Allowed methods: GET, POST, PUT, PATCH, DELETE, HEAD.\";\n }\n const rawHeaders =\n typeof args.headers === \"string\"\n ? args.headers\n : JSON.stringify(args.headers ?? {});\n const rawBody =\n typeof args.body === \"string\"\n ? args.body\n : args.body === undefined || args.body === null\n ? undefined\n : JSON.stringify(args.body);\n const timeoutMs = Math.min(\n Number(args.timeout_ms) || DEFAULT_TIMEOUT_MS,\n 30_000,\n );\n const requestedMaxChars = Number(args.maxChars);\n const maxChars =\n Number.isFinite(requestedMaxChars) && requestedMaxChars > 0\n ? Math.min(requestedMaxChars, 200_000)\n : 32_000;\n\n // Resolve key references\n let resolvedUrl = rawUrl;\n let resolvedHeaders = rawHeaders;\n let resolvedBody = rawBody;\n const allUsedKeys: string[] = [];\n const allSecretValues: string[] = [];\n const allResolvedKeys: ResolvedKeyReference[] = [];\n\n if (opts.resolveKeys) {\n try {\n const urlResult = await opts.resolveKeys(rawUrl);\n resolvedUrl = urlResult.resolved;\n allUsedKeys.push(...urlResult.usedKeys);\n allSecretValues.push(...(urlResult.secretValues ?? []));\n allResolvedKeys.push(...(urlResult.resolvedKeys ?? []));\n\n const headerResult = await opts.resolveKeys(rawHeaders);\n resolvedHeaders = headerResult.resolved;\n allUsedKeys.push(...headerResult.usedKeys);\n allSecretValues.push(...(headerResult.secretValues ?? []));\n allResolvedKeys.push(...(headerResult.resolvedKeys ?? []));\n\n if (rawBody) {\n const bodyResult = await opts.resolveKeys(rawBody);\n resolvedBody = bodyResult.resolved;\n allUsedKeys.push(...bodyResult.usedKeys);\n allSecretValues.push(...(bodyResult.secretValues ?? []));\n allResolvedKeys.push(...(bodyResult.resolvedKeys ?? []));\n }\n } catch (err: any) {\n return `Error resolving key references: ${err?.message ?? err}`;\n }\n }\n const secretValues = collectSecretValues(allSecretValues);\n const resolvedKeys = allResolvedKeys.length\n ? allResolvedKeys\n : undefined;\n\n // Block SSRF targets regardless of key usage\n if (await isBlockedExtensionUrlWithDns(resolvedUrl)) {\n return `Requests to private/internal addresses are not allowed: \"${rawUrl}\".`;\n }\n\n // Validate URL against per-key allowlists\n if (opts.validateUrl && allUsedKeys.length > 0) {\n try {\n const allowed = await opts.validateUrl(\n resolvedUrl,\n allUsedKeys,\n resolvedKeys,\n );\n if (!allowed) {\n return `URL \"${rawUrl}\" is not in the allowlist for the referenced keys. Check your key settings.`;\n }\n } catch (err: any) {\n return `URL validation error: ${err?.message ?? err}`;\n }\n }\n\n // Parse headers, then merge in browser-like defaults for any header the\n // caller didn't already specify. Real-browser headers (User-Agent,\n // Accept, Sec-Fetch-*) are what gets you past Cloudflare / PerimeterX /\n // generic UA-sniffing middleware on sites the user pastes in chat;\n // explicit caller headers always win so API calls keep their auth\n // headers untouched.\n let headers: Record<string, string>;\n try {\n headers = sanitizeOutboundHeaders(JSON.parse(resolvedHeaders));\n } catch {\n return `Invalid headers JSON: ${rawHeaders}`;\n }\n headers = applyBrowserDefaults(headers);\n\n // Make the request\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const dispatcher = (await createSsrfSafeDispatcher()) ?? undefined;\n const fetchOpts: RequestInit & { dispatcher?: unknown } = {\n method,\n headers,\n signal: controller.signal,\n redirect: \"manual\",\n };\n if (dispatcher) fetchOpts.dispatcher = dispatcher;\n if (resolvedBody && [\"POST\", \"PUT\", \"PATCH\"].includes(method)) {\n fetchOpts.body = resolvedBody;\n if (!headers[\"content-type\"] && !headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n }\n\n const response = await fetch(resolvedUrl, fetchOpts);\n const elapsed = Date.now() - startTime;\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get(\"location\");\n const redirectUrl = location\n ? new URL(location, resolvedUrl).href\n : null;\n if (\n redirectUrl &&\n (await isBlockedExtensionUrlWithDns(redirectUrl))\n ) {\n return \"Redirect to private/internal address blocked.\";\n }\n if (redirectUrl && opts.validateUrl && allUsedKeys.length > 0) {\n const allowed = await opts.validateUrl(\n redirectUrl,\n allUsedKeys,\n resolvedKeys,\n );\n if (!allowed) {\n return \"Redirect URL is not in the allowlist for the referenced keys.\";\n }\n }\n return `HTTP ${response.status} ${response.statusText}\\n\\nRedirect: ${\n redirectUrl ? redactString(redirectUrl, secretValues) : \"(none)\"\n }`;\n }\n\n // Check if caller wants to save to workspace file (before truncation).\n const saveToFilePath =\n typeof (args as Record<string, unknown>).saveToFile === \"string\"\n ? ((args as Record<string, unknown>).saveToFile as string).trim()\n : \"\";\n\n let body: string;\n try {\n // When saving to file allow larger reads (20MB), otherwise cap at proxy limit.\n const readLimit = saveToFilePath\n ? 20 * 1024 * 1024\n : MAX_EXTENSION_PROXY_RESPONSE_SIZE;\n const result = await readResponseTextWithLimit(response, readLimit);\n body = result.text;\n } catch {\n body = \"(could not read response body)\";\n }\n body = redactString(body, secretValues);\n const contentType =\n response.headers.get(\"content-type\")?.split(\";\")[0].trim() ??\n \"text/plain\";\n let displayBody: string;\n let processedMode = \"raw\";\n try {\n const processed = processWebContent({\n url: resolvedUrl,\n body,\n contentType,\n responseMode: String(args.responseMode ?? \"auto\"),\n extract: String(args.extract ?? \"readability\"),\n includeLinks:\n args.includeLinks === undefined\n ? true\n : parseBooleanArg(args.includeLinks),\n search: parseWebContentSearchOptions(args.search),\n maxChars,\n });\n processedMode = processed.mode;\n displayBody = formatWebContentResult(processed);\n } catch (err: any) {\n return `web-request post-processing error: ${err?.message ?? String(err)}`;\n }\n\n // Audit log\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → ${response.status} (${elapsed}ms, keys: ${allUsedKeys.join(\",\") || \"none\"})`,\n );\n\n // saveToFile: write full body to workspace and return compact summary.\n if (saveToFilePath) {\n try {\n const { writeWorkspaceFile, SAVE_TO_FILE_MAX_BYTES } =\n await import(\"../workspace-files/store.js\");\n const { getRequestOrgId, getRequestUserEmail } =\n await import(\"../server/request-context.js\");\n const orgId = getRequestOrgId();\n const email = getRequestUserEmail();\n const scope = orgId\n ? { scope: \"org\" as const, scopeId: orgId }\n : email\n ? { scope: \"user\" as const, scopeId: email }\n : null;\n if (!scope)\n throw new Error(\"No authenticated context for saveToFile\");\n await writeWorkspaceFile(\n scope,\n saveToFilePath,\n body,\n contentType,\n {\n maxFileBytes: SAVE_TO_FILE_MAX_BYTES,\n },\n );\n const bytes = Buffer.byteLength(body, \"utf8\");\n const preview = displayBody.slice(0, 2000);\n return JSON.stringify({\n savedToFile: true,\n savedTo: saveToFilePath,\n status: response.status,\n bytes,\n contentType,\n responseMode: processedMode,\n preview:\n preview.length < displayBody.length ? `${preview}…` : preview,\n });\n } catch (saveErr: any) {\n return `saveToFile error: ${saveErr?.message ?? String(saveErr)}\\n\\nHTTP ${response.status} ${response.statusText}\\n\\n${body.slice(0, maxChars)}`;\n }\n }\n\n return `HTTP ${response.status} ${response.statusText}\\n\\n${displayBody}`;\n } catch (err: any) {\n const elapsed = Date.now() - startTime;\n if (err?.name === \"AbortError\") {\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → TIMEOUT (${elapsed}ms)`,\n );\n return `Request timed out after ${timeoutMs}ms.`;\n }\n const message = redactSecrets(\n err?.message ?? String(err),\n secretValues,\n );\n console.log(\n `[fetch-tool] ${method} ${rawUrl} → ERROR: ${message} (${elapsed}ms)`,\n );\n return `Request failed: ${message}`;\n } finally {\n clearTimeout(timeout);\n }\n },\n readOnly: true,\n },\n };\n}\n\nfunction parseBooleanArg(value: unknown): boolean {\n if (typeof value === \"boolean\") return value;\n const normalized = String(value).trim().toLowerCase();\n return normalized === \"true\" || normalized === \"1\" || normalized === \"yes\";\n}\n"]}
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
* `metadata.emailRecipients`.
|
|
28
28
|
*/
|
|
29
29
|
import { ssrfSafeFetch } from "../extensions/url-safety.js";
|
|
30
|
-
import {
|
|
30
|
+
import { resolveKeyReferencesWithRequestScopes, validateUrlAllowlist, getKeyAllowlist, } from "../secrets/substitution.js";
|
|
31
31
|
import { sendEmail } from "../server/email.js";
|
|
32
32
|
import { registerNotificationChannel } from "./registry.js";
|
|
33
33
|
let _registered = false;
|
|
@@ -153,19 +153,35 @@ function createEmailChannel() {
|
|
|
153
153
|
};
|
|
154
154
|
}
|
|
155
155
|
async function resolveWebhookRequest(urlTemplate, authTemplate, owner, label) {
|
|
156
|
-
// Resolve `${keys.NAME}` references
|
|
156
|
+
// Resolve `${keys.NAME}` references through the same request-scope
|
|
157
|
+
// cascade already used by extension fetches (extensions/routes.ts) and
|
|
158
|
+
// automation connector headers (automation/index.ts): user scope first
|
|
159
|
+
// (a personal override always wins), then the active org scope — where
|
|
160
|
+
// the Dispatch vault syncs workspace secrets — then workspace scope.
|
|
161
|
+
// Org/workspace vault rows are write-gated (org-admin + Dispatch vault
|
|
162
|
+
// UI), so reading them here is safe by default; this is unrelated to the
|
|
163
|
+
// opt-in-only user→workspace fallback in resolveKeyReferences (audit 05
|
|
164
|
+
// H2 in secrets/substitution.ts), which stays off. In headless contexts
|
|
165
|
+
// (e.g. a scheduled monitor check) getRequestOrgId() may be unset, in
|
|
166
|
+
// which case the cascade checks user + solo-workspace scopes only — a
|
|
167
|
+
// strict superset of the previous user-scope-only behavior.
|
|
157
168
|
// Missing keys throw — the error surfaces in logs and the channel is marked
|
|
158
169
|
// un-delivered, but other channels still run.
|
|
159
|
-
const { resolved: url } = await
|
|
170
|
+
const { resolved: url } = await resolveKeyReferencesWithRequestScopes(urlTemplate, owner);
|
|
160
171
|
const headers = {
|
|
161
172
|
"Content-Type": "application/json",
|
|
162
173
|
};
|
|
163
174
|
if (authTemplate) {
|
|
164
|
-
const { resolved: auth } = await
|
|
175
|
+
const { resolved: auth } = await resolveKeyReferencesWithRequestScopes(authTemplate, owner);
|
|
165
176
|
headers.Authorization = auth;
|
|
166
177
|
}
|
|
167
178
|
// If the user set an allowlist on a referenced key, enforce it here —
|
|
168
179
|
// origin-level check, same rule the automations fetch-tool applies.
|
|
180
|
+
// NOTE: this still checks the allowlist at user scope only (unlike the
|
|
181
|
+
// fetch tool's validateUrl, which now consults getResolvedKeyAllowlist at
|
|
182
|
+
// the scope the key actually resolved at — see agent-chat-plugin.ts). A
|
|
183
|
+
// key that resolves at org/workspace scope with an allowlist configured
|
|
184
|
+
// on that org/workspace row will not have it enforced here.
|
|
169
185
|
const keyNames = Array.from(new Set(Array.from(urlTemplate.matchAll(/\$\{keys\.([A-Za-z0-9_-]+)\}/g), (m) => String(m[1]))));
|
|
170
186
|
const allowlists = await Promise.all(keyNames.map((name) => getKeyAllowlist(name, "user", owner)));
|
|
171
187
|
keyNames.forEach((name, i) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/notifications/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,eAAe,GAChB,MAAM,4BAA4B,CAAC;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OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,KAAK;SACT,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAC7B,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,gBAAgB,CAAC,GAAa;IAC3C,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;IACrC,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,GAAG,GAAG,IAAI,CAAC;IACjB,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,CAAC;QACH,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACxB,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAClC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,OAAO,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Built-in notification channels.\n *\n * Webhook and Slack are always registered. Delivery uses (in order):\n * 1. per-notification `metadata.webhookUrl` / `metadata.slackWebhookUrl`\n * 2. the matching `NOTIFICATIONS_*` env URL (workspace default)\n * If neither is set, that channel no-ops for the emission.\n *\n * Extra channels can be registered at any time via\n * `registerNotificationChannel()` from a server plugin.\n *\n * NOTIFICATIONS_WEBHOOK_URL → default POST JSON URL when metadata omits one.\n * Supports `${keys.NAME}` substitution — the raw\n * value never enters the agent context.\n * NOTIFICATIONS_WEBHOOK_AUTH → optional `Authorization` header value (also\n * supports `${keys.NAME}`).\n * NOTIFICATIONS_SLACK_WEBHOOK_URL\n * → default Slack incoming webhook when metadata\n * omits `slackWebhookUrl`.\n * Supports `${keys.NAME}` substitution.\n * NOTIFICATIONS_EMAIL_CHANNEL=1\n * → enable the built-in email channel for\n * per-notification recipients.\n * NOTIFICATIONS_EMAIL_RECIPIENTS\n * → comma-separated fallback recipients for email\n * notifications that do not pass\n * `metadata.emailRecipients`.\n */\n\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\nimport {\n resolveKeyReferences,\n validateUrlAllowlist,\n getKeyAllowlist,\n} from \"../secrets/substitution.js\";\nimport { sendEmail } from \"../server/email.js\";\nimport { registerNotificationChannel } from \"./registry.js\";\nimport type { NotificationChannel, NotificationInput } from \"./types.js\";\n\nlet _registered = false;\n\nexport function registerBuiltinNotificationChannels(): void {\n if (_registered) return;\n _registered = true;\n\n registerNotificationChannel(\n createWebhookChannel(process.env.NOTIFICATIONS_WEBHOOK_URL),\n );\n registerNotificationChannel(\n createSlackWebhookChannel(process.env.NOTIFICATIONS_SLACK_WEBHOOK_URL),\n );\n // Email is always registered so per-notification `metadata.emailRecipients`\n // work without a workspace-wide env flag (same pattern as webhook/slack).\n registerNotificationChannel(createEmailChannel());\n}\n\nfunction createWebhookChannel(\n envUrlTemplate: string | undefined,\n): NotificationChannel {\n const authTemplate = process.env.NOTIFICATIONS_WEBHOOK_AUTH;\n return {\n name: \"webhook\",\n async deliver(input, meta) {\n const overrideUrlTemplate = deliveryMetadataString(\n input.metadata,\n \"webhookUrl\",\n );\n const urlTemplate =\n overrideUrlTemplate ??\n metadataString(input.metadata, \"webhookUrl\") ??\n envUrlTemplate?.trim();\n // No-op when neither a per-notification nor workspace URL is set —\n // mirrors email's empty-recipients behavior so notify-all stays quiet.\n if (!urlTemplate) return false;\n const { url, headers } = await resolveWebhookRequest(\n urlTemplate,\n overrideUrlTemplate ? undefined : authTemplate,\n meta.owner,\n \"webhook\",\n );\n const res = await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n severity: input.severity,\n title: input.title,\n body: input.body,\n metadata: scrubDeliveryMetadata(input.metadata),\n owner: meta.owner,\n emittedAt: new Date().toISOString(),\n }),\n },\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(\n `[notifications] webhook ${new URL(url).origin} returned ${res.status}${\n (await readErrorSnippet(res)) || \"\"\n }`,\n );\n }\n },\n };\n}\n\nfunction createSlackWebhookChannel(\n envUrlTemplate: string | undefined,\n): NotificationChannel {\n const authTemplate = process.env.NOTIFICATIONS_SLACK_WEBHOOK_AUTH;\n return {\n name: \"slack\",\n async deliver(input, meta) {\n const overrideUrlTemplate = deliveryMetadataString(\n input.metadata,\n \"slackWebhookUrl\",\n );\n const urlTemplate =\n overrideUrlTemplate ??\n metadataString(input.metadata, \"slackWebhookUrl\") ??\n envUrlTemplate?.trim();\n if (!urlTemplate) return false;\n const { url, headers } = await resolveWebhookRequest(\n urlTemplate,\n overrideUrlTemplate ? undefined : authTemplate,\n meta.owner,\n \"Slack webhook\",\n );\n const res = await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n text: slackText(input.severity, input.title, input.body),\n blocks: [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${escapeSlack(input.title)}*`,\n },\n },\n ...(input.body\n ? [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: escapeSlack(input.body),\n },\n },\n ]\n : []),\n {\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `Severity: \\`${input.severity}\\` Owner: ${escapeSlack(meta.owner)}`,\n },\n ],\n },\n ],\n }),\n },\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(\n `[notifications] Slack webhook ${new URL(url).origin} returned ${res.status}${\n (await readErrorSnippet(res)) || \"\"\n }`,\n );\n }\n },\n };\n}\n\nfunction createEmailChannel(): NotificationChannel {\n return {\n name: \"email\",\n async deliver(input) {\n const recipients = notificationEmailRecipients(input.metadata);\n if (recipients.length === 0) return false;\n const subject =\n typeof input.metadata?.emailSubject === \"string\" &&\n input.metadata.emailSubject.trim()\n ? input.metadata.emailSubject.trim()\n : `[${input.severity}] ${input.title}`;\n const text = `${input.title}\\n\\n${input.body ?? \"\"}`;\n const html = [\n `<p><strong>${escapeHtml(input.title)}</strong></p>`,\n input.body ? `<p>${escapeHtml(input.body)}</p>` : \"\",\n ].join(\"\");\n\n await Promise.all(\n recipients.map((to) =>\n sendEmail({\n to,\n subject,\n text,\n html,\n }),\n ),\n );\n },\n };\n}\n\nasync function resolveWebhookRequest(\n urlTemplate: string,\n authTemplate: string | undefined,\n owner: string,\n label: string,\n): Promise<{ url: string; headers: Record<string, string> }> {\n // Resolve `${keys.NAME}` references against the owner's user-scope secrets.\n // Missing keys throw — the error surfaces in logs and the channel is marked\n // un-delivered, but other channels still run.\n const { resolved: url } = await resolveKeyReferences(\n urlTemplate,\n \"user\",\n owner,\n );\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (authTemplate) {\n const { resolved: auth } = await resolveKeyReferences(\n authTemplate,\n \"user\",\n owner,\n );\n headers.Authorization = auth;\n }\n\n // If the user set an allowlist on a referenced key, enforce it here —\n // origin-level check, same rule the automations fetch-tool applies.\n const keyNames = Array.from(\n new Set(\n Array.from(urlTemplate.matchAll(/\\$\\{keys\\.([A-Za-z0-9_-]+)\\}/g), (m) =>\n String(m[1]),\n ),\n ),\n );\n const allowlists = await Promise.all(\n keyNames.map((name) => getKeyAllowlist(name, \"user\", owner)),\n );\n keyNames.forEach((name, i) => {\n if (!validateUrlAllowlist(url, allowlists[i])) {\n throw new Error(\n `[notifications] ${label} URL ${new URL(url).origin} is not in the allowlist for key \"${name}\"`,\n );\n }\n });\n return { url, headers };\n}\n\nfunction metadataString(\n metadata: NotificationInput[\"metadata\"],\n key: string,\n): string | undefined {\n const value = metadata?.[key];\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction deliveryMetadataString(\n metadata: NotificationInput[\"metadata\"],\n key: string,\n): string | undefined {\n const delivery = metadata?.delivery;\n if (!delivery || typeof delivery !== \"object\" || Array.isArray(delivery)) {\n return undefined;\n }\n const value = (delivery as Record<string, unknown>)[key];\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction scrubDeliveryMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!metadata) return undefined;\n const entries = Object.entries(metadata).filter(\n ([key]) =>\n key !== \"delivery\" && key !== \"webhookUrl\" && key !== \"slackWebhookUrl\",\n );\n return entries.length ? Object.fromEntries(entries) : undefined;\n}\n\nfunction notificationEmailRecipients(\n metadata: Record<string, unknown> | undefined,\n): string[] {\n const fromMetadata = stringArray(metadata?.emailRecipients);\n const fromEnv = commaList(process.env.NOTIFICATIONS_EMAIL_RECIPIENTS);\n const seen = new Set<string>();\n const recipients: string[] = [];\n for (const raw of [...fromMetadata, ...fromEnv]) {\n const email = raw.trim().toLowerCase();\n if (!email || seen.has(email)) continue;\n seen.add(email);\n recipients.push(email);\n }\n return recipients;\n}\n\nfunction stringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\");\n}\n\nfunction commaList(value: string | undefined): string[] {\n return value\n ? value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean)\n : [];\n}\n\nfunction slackText(\n severity: string,\n title: string,\n body: string | undefined,\n): string {\n return `[${severity}] ${title}${body ? `\\n${body}` : \"\"}`;\n}\n\nfunction escapeSlack(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\n/**\n * Read up to ~1 KB from the body for error context. Streams chunks so a\n * misbehaving endpoint returning a large error page doesn't pin that whole\n * payload in memory per failed webhook.\n */\nasync function readErrorSnippet(res: Response): Promise<string> {\n const reader = res.body?.getReader();\n if (!reader) return \"\";\n const decoder = new TextDecoder();\n const MAX = 1024;\n let buf = \"\";\n try {\n while (buf.length < MAX) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n }\n reader.cancel().catch(() => {});\n } catch {\n return \"\";\n }\n if (!buf) return \"\";\n return `: ${buf.slice(0, 200)}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/notifications/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EACL,qCAAqC,EACrC,oBAAoB,EACpB,eAAe,GAChB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAG5D,IAAI,WAAW,GAAG,KAAK,CAAC;AAExB,MAAM,UAAU,mCAAmC;IACjD,IAAI,WAAW;QAAE,OAAO;IACxB,WAAW,GAAG,IAAI,CAAC;IAEnB,2BAA2B,CACzB,oBAAoB,CAAC,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAC5D,CAAC;IACF,2BAA2B,CACzB,yBAAyB,CAAC,OAAO,CAAC,G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,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAC7B,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,gBAAgB,CAAC,GAAa;IAC3C,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;IACrC,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,GAAG,GAAG,IAAI,CAAC;IACjB,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,CAAC;QACH,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACxB,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAClC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,OAAO,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Built-in notification channels.\n *\n * Webhook and Slack are always registered. Delivery uses (in order):\n * 1. per-notification `metadata.webhookUrl` / `metadata.slackWebhookUrl`\n * 2. the matching `NOTIFICATIONS_*` env URL (workspace default)\n * If neither is set, that channel no-ops for the emission.\n *\n * Extra channels can be registered at any time via\n * `registerNotificationChannel()` from a server plugin.\n *\n * NOTIFICATIONS_WEBHOOK_URL → default POST JSON URL when metadata omits one.\n * Supports `${keys.NAME}` substitution — the raw\n * value never enters the agent context.\n * NOTIFICATIONS_WEBHOOK_AUTH → optional `Authorization` header value (also\n * supports `${keys.NAME}`).\n * NOTIFICATIONS_SLACK_WEBHOOK_URL\n * → default Slack incoming webhook when metadata\n * omits `slackWebhookUrl`.\n * Supports `${keys.NAME}` substitution.\n * NOTIFICATIONS_EMAIL_CHANNEL=1\n * → enable the built-in email channel for\n * per-notification recipients.\n * NOTIFICATIONS_EMAIL_RECIPIENTS\n * → comma-separated fallback recipients for email\n * notifications that do not pass\n * `metadata.emailRecipients`.\n */\n\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\nimport {\n resolveKeyReferencesWithRequestScopes,\n validateUrlAllowlist,\n getKeyAllowlist,\n} from \"../secrets/substitution.js\";\nimport { sendEmail } from \"../server/email.js\";\nimport { registerNotificationChannel } from \"./registry.js\";\nimport type { NotificationChannel, NotificationInput } from \"./types.js\";\n\nlet _registered = false;\n\nexport function registerBuiltinNotificationChannels(): void {\n if (_registered) return;\n _registered = true;\n\n registerNotificationChannel(\n createWebhookChannel(process.env.NOTIFICATIONS_WEBHOOK_URL),\n );\n registerNotificationChannel(\n createSlackWebhookChannel(process.env.NOTIFICATIONS_SLACK_WEBHOOK_URL),\n );\n // Email is always registered so per-notification `metadata.emailRecipients`\n // work without a workspace-wide env flag (same pattern as webhook/slack).\n registerNotificationChannel(createEmailChannel());\n}\n\nfunction createWebhookChannel(\n envUrlTemplate: string | undefined,\n): NotificationChannel {\n const authTemplate = process.env.NOTIFICATIONS_WEBHOOK_AUTH;\n return {\n name: \"webhook\",\n async deliver(input, meta) {\n const overrideUrlTemplate = deliveryMetadataString(\n input.metadata,\n \"webhookUrl\",\n );\n const urlTemplate =\n overrideUrlTemplate ??\n metadataString(input.metadata, \"webhookUrl\") ??\n envUrlTemplate?.trim();\n // No-op when neither a per-notification nor workspace URL is set —\n // mirrors email's empty-recipients behavior so notify-all stays quiet.\n if (!urlTemplate) return false;\n const { url, headers } = await resolveWebhookRequest(\n urlTemplate,\n overrideUrlTemplate ? undefined : authTemplate,\n meta.owner,\n \"webhook\",\n );\n const res = await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n severity: input.severity,\n title: input.title,\n body: input.body,\n metadata: scrubDeliveryMetadata(input.metadata),\n owner: meta.owner,\n emittedAt: new Date().toISOString(),\n }),\n },\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(\n `[notifications] webhook ${new URL(url).origin} returned ${res.status}${\n (await readErrorSnippet(res)) || \"\"\n }`,\n );\n }\n },\n };\n}\n\nfunction createSlackWebhookChannel(\n envUrlTemplate: string | undefined,\n): NotificationChannel {\n const authTemplate = process.env.NOTIFICATIONS_SLACK_WEBHOOK_AUTH;\n return {\n name: \"slack\",\n async deliver(input, meta) {\n const overrideUrlTemplate = deliveryMetadataString(\n input.metadata,\n \"slackWebhookUrl\",\n );\n const urlTemplate =\n overrideUrlTemplate ??\n metadataString(input.metadata, \"slackWebhookUrl\") ??\n envUrlTemplate?.trim();\n if (!urlTemplate) return false;\n const { url, headers } = await resolveWebhookRequest(\n urlTemplate,\n overrideUrlTemplate ? undefined : authTemplate,\n meta.owner,\n \"Slack webhook\",\n );\n const res = await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n text: slackText(input.severity, input.title, input.body),\n blocks: [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `*${escapeSlack(input.title)}*`,\n },\n },\n ...(input.body\n ? [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: escapeSlack(input.body),\n },\n },\n ]\n : []),\n {\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `Severity: \\`${input.severity}\\` Owner: ${escapeSlack(meta.owner)}`,\n },\n ],\n },\n ],\n }),\n },\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(\n `[notifications] Slack webhook ${new URL(url).origin} returned ${res.status}${\n (await readErrorSnippet(res)) || \"\"\n }`,\n );\n }\n },\n };\n}\n\nfunction createEmailChannel(): NotificationChannel {\n return {\n name: \"email\",\n async deliver(input) {\n const recipients = notificationEmailRecipients(input.metadata);\n if (recipients.length === 0) return false;\n const subject =\n typeof input.metadata?.emailSubject === \"string\" &&\n input.metadata.emailSubject.trim()\n ? input.metadata.emailSubject.trim()\n : `[${input.severity}] ${input.title}`;\n const text = `${input.title}\\n\\n${input.body ?? \"\"}`;\n const html = [\n `<p><strong>${escapeHtml(input.title)}</strong></p>`,\n input.body ? `<p>${escapeHtml(input.body)}</p>` : \"\",\n ].join(\"\");\n\n await Promise.all(\n recipients.map((to) =>\n sendEmail({\n to,\n subject,\n text,\n html,\n }),\n ),\n );\n },\n };\n}\n\nasync function resolveWebhookRequest(\n urlTemplate: string,\n authTemplate: string | undefined,\n owner: string,\n label: string,\n): Promise<{ url: string; headers: Record<string, string> }> {\n // Resolve `${keys.NAME}` references through the same request-scope\n // cascade already used by extension fetches (extensions/routes.ts) and\n // automation connector headers (automation/index.ts): user scope first\n // (a personal override always wins), then the active org scope — where\n // the Dispatch vault syncs workspace secrets — then workspace scope.\n // Org/workspace vault rows are write-gated (org-admin + Dispatch vault\n // UI), so reading them here is safe by default; this is unrelated to the\n // opt-in-only user→workspace fallback in resolveKeyReferences (audit 05\n // H2 in secrets/substitution.ts), which stays off. In headless contexts\n // (e.g. a scheduled monitor check) getRequestOrgId() may be unset, in\n // which case the cascade checks user + solo-workspace scopes only — a\n // strict superset of the previous user-scope-only behavior.\n // Missing keys throw — the error surfaces in logs and the channel is marked\n // un-delivered, but other channels still run.\n const { resolved: url } = await resolveKeyReferencesWithRequestScopes(\n urlTemplate,\n owner,\n );\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (authTemplate) {\n const { resolved: auth } = await resolveKeyReferencesWithRequestScopes(\n authTemplate,\n owner,\n );\n headers.Authorization = auth;\n }\n\n // If the user set an allowlist on a referenced key, enforce it here —\n // origin-level check, same rule the automations fetch-tool applies.\n // NOTE: this still checks the allowlist at user scope only (unlike the\n // fetch tool's validateUrl, which now consults getResolvedKeyAllowlist at\n // the scope the key actually resolved at — see agent-chat-plugin.ts). A\n // key that resolves at org/workspace scope with an allowlist configured\n // on that org/workspace row will not have it enforced here.\n const keyNames = Array.from(\n new Set(\n Array.from(urlTemplate.matchAll(/\\$\\{keys\\.([A-Za-z0-9_-]+)\\}/g), (m) =>\n String(m[1]),\n ),\n ),\n );\n const allowlists = await Promise.all(\n keyNames.map((name) => getKeyAllowlist(name, \"user\", owner)),\n );\n keyNames.forEach((name, i) => {\n if (!validateUrlAllowlist(url, allowlists[i])) {\n throw new Error(\n `[notifications] ${label} URL ${new URL(url).origin} is not in the allowlist for key \"${name}\"`,\n );\n }\n });\n return { url, headers };\n}\n\nfunction metadataString(\n metadata: NotificationInput[\"metadata\"],\n key: string,\n): string | undefined {\n const value = metadata?.[key];\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction deliveryMetadataString(\n metadata: NotificationInput[\"metadata\"],\n key: string,\n): string | undefined {\n const delivery = metadata?.delivery;\n if (!delivery || typeof delivery !== \"object\" || Array.isArray(delivery)) {\n return undefined;\n }\n const value = (delivery as Record<string, unknown>)[key];\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction scrubDeliveryMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!metadata) return undefined;\n const entries = Object.entries(metadata).filter(\n ([key]) =>\n key !== \"delivery\" && key !== \"webhookUrl\" && key !== \"slackWebhookUrl\",\n );\n return entries.length ? Object.fromEntries(entries) : undefined;\n}\n\nfunction notificationEmailRecipients(\n metadata: Record<string, unknown> | undefined,\n): string[] {\n const fromMetadata = stringArray(metadata?.emailRecipients);\n const fromEnv = commaList(process.env.NOTIFICATIONS_EMAIL_RECIPIENTS);\n const seen = new Set<string>();\n const recipients: string[] = [];\n for (const raw of [...fromMetadata, ...fromEnv]) {\n const email = raw.trim().toLowerCase();\n if (!email || seen.has(email)) continue;\n seen.add(email);\n recipients.push(email);\n }\n return recipients;\n}\n\nfunction stringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\");\n}\n\nfunction commaList(value: string | undefined): string[] {\n return value\n ? value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean)\n : [];\n}\n\nfunction slackText(\n severity: string,\n title: string,\n body: string | undefined,\n): string {\n return `[${severity}] ${title}${body ? `\\n${body}` : \"\"}`;\n}\n\nfunction escapeSlack(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\n/**\n * Read up to ~1 KB from the body for error context. Streams chunks so a\n * misbehaving endpoint returning a large error page doesn't pin that whole\n * payload in memory per failed webhook.\n */\nasync function readErrorSnippet(res: Response): Promise<string> {\n const reader = res.body?.getReader();\n if (!reader) return \"\";\n const decoder = new TextDecoder();\n const MAX = 1024;\n let buf = \"\";\n try {\n while (buf.length < MAX) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n }\n reader.cancel().catch(() => {});\n } catch {\n return \"\";\n }\n if (!buf) return \"\";\n return `: ${buf.slice(0, 200)}`;\n}\n"]}
|
|
@@ -49,8 +49,8 @@ export declare function handleUpdateResource(event: any): Promise<import("./stor
|
|
|
49
49
|
}>;
|
|
50
50
|
/** DELETE /_agent-native/resources/:id — delete a resource */
|
|
51
51
|
export declare function handleDeleteResource(event: any): Promise<{
|
|
52
|
-
error: string;
|
|
53
52
|
ok?: undefined;
|
|
53
|
+
error: string;
|
|
54
54
|
} | {
|
|
55
55
|
error?: undefined;
|
|
56
56
|
ok: boolean;
|
package/dist/secrets/crypto.d.ts
CHANGED
|
@@ -14,10 +14,15 @@
|
|
|
14
14
|
* `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then `SECRETS_ENCRYPTION_KEY`,
|
|
15
15
|
* then `BETTER_AUTH_SECRET`. The app-scoped key lets a local multi-app
|
|
16
16
|
* workspace read one app's encrypted production data without replacing the
|
|
17
|
-
* shared local auth secret.
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
17
|
+
* shared local auth secret. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`)
|
|
18
|
+
* typically set none of those literal env vars per app; in that case the
|
|
19
|
+
* shared-key variant falls back further to material derived from the
|
|
20
|
+
* workspace-wide `A2A_SECRET` (see `getWorkspaceA2ADerivedSecret`), so sibling
|
|
21
|
+
* apps in the same workspace still land on the same shared key without any
|
|
22
|
+
* extra configuration. In production we refuse to start without configured
|
|
23
|
+
* key material — a CWD-derived fallback would be effectively static (e.g.
|
|
24
|
+
* `/var/task` on Lambda), so anyone with read access to the DB could decrypt
|
|
25
|
+
* every secret.
|
|
21
26
|
*
|
|
22
27
|
* Encrypted values are tagged `v1:<iv-hex>:<ct-hex>:<tag-hex>`. The `v1:` prefix
|
|
23
28
|
* lets readers distinguish ciphertext from legacy plaintext during migration.
|
|
@@ -32,9 +37,12 @@ export declare function getSecretEncryptionKey(): Buffer;
|
|
|
32
37
|
* Derive the preferred workspace-shared key used by `app_secrets` rows.
|
|
33
38
|
* Unlike generic column-level encryption, workspace vault data should decrypt
|
|
34
39
|
* in sibling apps, so `SECRETS_ENCRYPTION_KEY` / `BETTER_AUTH_SECRET` take
|
|
35
|
-
* precedence.
|
|
36
|
-
*
|
|
37
|
-
*
|
|
40
|
+
* precedence. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`) that set
|
|
41
|
+
* neither literal var still get stable shared material derived from the
|
|
42
|
+
* workspace-wide `A2A_SECRET` before falling further back. The app-scoped key
|
|
43
|
+
* remains a compatibility fallback for deployments that have not configured
|
|
44
|
+
* shared material yet; once the shared key is configured, writes use it and
|
|
45
|
+
* reads still fall back to old rows.
|
|
38
46
|
*/
|
|
39
47
|
export declare function getSharedSecretEncryptionKey(): Buffer;
|
|
40
48
|
/** Whether this deployment has stable workspace-shared key material. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/secrets/crypto.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/secrets/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAqFH;;;;GAIG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAkB/C;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CAUrD;AAED,wEAAwE;AACxE,wBAAgB,oCAAoC,IAAI,OAAO,CAE9D;AAiCD,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAUD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEtE"}
|
package/dist/secrets/crypto.js
CHANGED
|
@@ -14,14 +14,20 @@
|
|
|
14
14
|
* `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then `SECRETS_ENCRYPTION_KEY`,
|
|
15
15
|
* then `BETTER_AUTH_SECRET`. The app-scoped key lets a local multi-app
|
|
16
16
|
* workspace read one app's encrypted production data without replacing the
|
|
17
|
-
* shared local auth secret.
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
17
|
+
* shared local auth secret. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`)
|
|
18
|
+
* typically set none of those literal env vars per app; in that case the
|
|
19
|
+
* shared-key variant falls back further to material derived from the
|
|
20
|
+
* workspace-wide `A2A_SECRET` (see `getWorkspaceA2ADerivedSecret`), so sibling
|
|
21
|
+
* apps in the same workspace still land on the same shared key without any
|
|
22
|
+
* extra configuration. In production we refuse to start without configured
|
|
23
|
+
* key material — a CWD-derived fallback would be effectively static (e.g.
|
|
24
|
+
* `/var/task` on Lambda), so anyone with read access to the DB could decrypt
|
|
25
|
+
* every secret.
|
|
21
26
|
*
|
|
22
27
|
* Encrypted values are tagged `v1:<iv-hex>:<ct-hex>:<tag-hex>`. The `v1:` prefix
|
|
23
28
|
* lets readers distinguish ciphertext from legacy plaintext during migration.
|
|
24
29
|
*/
|
|
30
|
+
import { getWorkspaceA2ADerivedSecret } from "../server/derived-secret.js";
|
|
25
31
|
function getNodeCrypto() {
|
|
26
32
|
if (typeof window !== "undefined" ||
|
|
27
33
|
typeof process === "undefined" ||
|
|
@@ -63,7 +69,9 @@ function appScopedEncryptionKey() {
|
|
|
63
69
|
function sharedEncryptionKeyMaterial() {
|
|
64
70
|
if (typeof process === "undefined")
|
|
65
71
|
return undefined;
|
|
66
|
-
return process.env.SECRETS_ENCRYPTION_KEY ||
|
|
72
|
+
return (process.env.SECRETS_ENCRYPTION_KEY ||
|
|
73
|
+
process.env.BETTER_AUTH_SECRET ||
|
|
74
|
+
getWorkspaceA2ADerivedSecret("secrets-encryption"));
|
|
67
75
|
}
|
|
68
76
|
function deriveSecretEncryptionKey(explicit, errorMessage, warningMessage) {
|
|
69
77
|
const { createHash } = requireNodeCrypto();
|
|
@@ -103,14 +111,19 @@ export function getSecretEncryptionKey() {
|
|
|
103
111
|
* Derive the preferred workspace-shared key used by `app_secrets` rows.
|
|
104
112
|
* Unlike generic column-level encryption, workspace vault data should decrypt
|
|
105
113
|
* in sibling apps, so `SECRETS_ENCRYPTION_KEY` / `BETTER_AUTH_SECRET` take
|
|
106
|
-
* precedence.
|
|
107
|
-
*
|
|
108
|
-
*
|
|
114
|
+
* precedence. Hosted workspace deploys (`AGENT_NATIVE_WORKSPACE`) that set
|
|
115
|
+
* neither literal var still get stable shared material derived from the
|
|
116
|
+
* workspace-wide `A2A_SECRET` before falling further back. The app-scoped key
|
|
117
|
+
* remains a compatibility fallback for deployments that have not configured
|
|
118
|
+
* shared material yet; once the shared key is configured, writes use it and
|
|
119
|
+
* reads still fall back to old rows.
|
|
109
120
|
*/
|
|
110
121
|
export function getSharedSecretEncryptionKey() {
|
|
111
122
|
return deriveSecretEncryptionKey(sharedEncryptionKeyMaterial() || appScopedEncryptionKey(), "[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. " +
|
|
112
|
-
"Set SECRETS_ENCRYPTION_KEY, BETTER_AUTH_SECRET, or the app-scoped *_SECRETS_ENCRYPTION_KEY in the deploy environment
|
|
113
|
-
"
|
|
123
|
+
"Set SECRETS_ENCRYPTION_KEY, BETTER_AUTH_SECRET, or the app-scoped *_SECRETS_ENCRYPTION_KEY in the deploy environment " +
|
|
124
|
+
"— or, on a hosted workspace deploy, ensure A2A_SECRET is set so shared material can be derived from it.", "[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. " +
|
|
125
|
+
"Set SECRETS_ENCRYPTION_KEY or BETTER_AUTH_SECRET in every workspace app so sibling apps share vault rows, " +
|
|
126
|
+
"or rely on A2A_SECRET-derived material on hosted workspace deploys.");
|
|
114
127
|
}
|
|
115
128
|
/** Whether this deployment has stable workspace-shared key material. */
|
|
116
129
|
export function hasSharedSecretEncryptionKeyMaterial() {
|