Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(slack): let slackChannel target another Slack API host (#3605)

Philipp Comans0aad786e7b78
diff --git a/.changeset/slack-api-base-url-option.md b/.changeset/slack-api-base-url-option.md
new file mode 100644
index 000000000..43b6facdf
--- /dev/null
+++ b/.changeset/slack-api-base-url-option.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`slackChannel` and `callSlackApi` accept an `api` option, `{ apiBaseUrl?, fileBaseUrl?, fetch? }`, that sends Slack Web API calls and attachment downloads to another host. `fileBaseUrl` defaults to `apiBaseUrl`, `fetch` is called only for URLs on those hosts, each base must be an absolute http or https URL with no query string or fragment, and omitting `api` keeps `https://slack.com/api/` and the global `fetch`.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index e3d69facd..f91fdd880 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -407,6 +407,7 @@ import { connectSlackCredentials } from "@vercel/connect/eve";
const { botToken } = connectSlackCredentials("slack/my-agent");
const response = await callSlackApi({
+ api: { apiBaseUrl: process.env.SLACK_API_BASE_URL },
botToken,
context: { teamId: "T0123456789" },
operation: "reactions.get",
@@ -418,8 +419,34 @@ if (!response.ok) throw new Error(String(response.error));
`callSlackApi` resolves function-form tokens (secret managers, Connect
rotation) with the supplied `context` at call time and form-encodes the body — the only safe default,
since Slack's JSON support is partial (`conversations.replies` rejects
-JSON). `resolveSlackBotToken` materializes a `SlackBotToken` to a string
-when you need the bearer token itself.
+JSON). It takes the same
+[`api`](#point-the-channel-at-a-different-slack-api-host) the channel takes, checked and
+confined the same way, so a call made without a channel carries the same guarantees. An
+`apiBaseUrl` of `undefined` keeps Slack's own host.
+
+`resolveSlackBotToken` materializes a `SlackBotToken` to a string when you need the
+bearer token itself.
+
+### Point the channel at a different Slack API host
+
+```ts
+slackChannel({
+ api: {
+ apiBaseUrl: "https://slack-simulator.example/api/slack",
+ fetch: (input, init) => {
+ const headers = new Headers(init?.headers);
+ headers.set("x-vercel-protection-bypass", process.env.SLACK_SIMULATOR_BYPASS_SECRET ?? "");
+ return fetch(input, { ...init, headers });
+ },
+ fileBaseUrl: "https://slack-simulator.example/files",
+ },
+ credentials: { botToken: process.env.SLACK_BOT_TOKEN },
+});
+```
+
+The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method names resolve against, and defaults to `https://slack.com/api/`. `fileBaseUrl` adds a base for attachment downloads and falls back to `apiBaseUrl`: a download URL under it is fetched with the bot token, in addition to `files.slack.com` and Enterprise Grid file URLs. Every other URL passes through to the model provider unchanged. Both bases must be absolute `http:` or `https:` URLs carrying no query string or fragment; `slackChannel()` throws on one that is not, naming the option. A missing trailing slash is added, so `https://sim.example/api` sends `chat.postMessage` to `https://sim.example/api/chat.postMessage`.
+
+`api.fetch` says how the traffic travels. It replaces the global `fetch` for calls to the configured bases — use it to attach the per-call header a host behind an authenticating proxy requires, as the example does for a simulator behind Vercel Deployment Protection. eve confines it to those bases' origins, so that header reaches the simulator alone: `files.slack.com`, and any other host Slack names in a response or an inbound payload, keep the global `fetch`. A wrapper therefore attaches its credential unconditionally. With no base configured every call already goes to Slack's own hosts, and `api.fetch` carries all of them, which is what observes or stubs the traffic in a test.
### Delivery
@@ -521,6 +548,8 @@ Inbound files behind authenticated Slack URLs are staged with `fetchFile`. See [
Private file downloads resolve credentials from the session's app installation workspace and require the Slack bot token's `files:read` scope. Add the scope and reinstall the Slack app before sending attachments.
+Downloads cover Slack's own file hosts plus URLs under a configured [`api.fileBaseUrl`](#point-the-channel-at-a-different-slack-api-host), and travel on `api.fetch` when one is configured.
+
Staged files live in the session sandbox under `/workspace/attachments`. Session history keeps a reference to that path, not a second copy of the Slack file. If the backend can no longer reattach the original sandbox, eve cannot restore the attachment bytes from history; later turns receive a missing-file result. Store files outside the sandbox when the agent must retain them independently of sandbox availability.
## What to read next
diff --git a/packages/eve/src/public/channels/slack/activity-plan.ts b/packages/eve/src/public/channels/slack/activity-plan.ts
index 8ea4e800f..4bb29c375 100644
--- a/packages/eve/src/public/channels/slack/activity-plan.ts
+++ b/packages/eve/src/public/channels/slack/activity-plan.ts
@@ -1,6 +1,7 @@
import type { ChannelActivityRenderer } from "#channel/activity-renderer.js";
import type { ActivitySnapshotV1, ActivityWorkStateV1 } from "#protocol/activity.js";
import { callSlackApi, type SlackBotToken } from "#public/channels/slack/api.js";
+import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
export const SLACK_ACTIVITY_PLAN_RENDERER_ID = "slack.experimental.plan.v1";
type Phase = "running" | "completed" | "failed" | "rejected" | "cancelled" | "blocked";
@@ -18,6 +19,7 @@ interface PlanState {
}
export function createSlackPlanRenderer(
+ apiOptions: SlackTransportOptions | undefined,
botToken: SlackBotToken | undefined,
): ChannelActivityRenderer {
return {
@@ -61,6 +63,7 @@ export function createSlackPlanRenderer(
...view.parents.map(taskChunk),
],
},
+ apiOptions,
botToken,
installation,
);
@@ -81,6 +84,7 @@ export function createSlackPlanRenderer(
await checked(
"chat.appendStream",
{ channel, ts: current.ts, chunks: updates },
+ apiOptions,
botToken,
installation,
);
@@ -89,7 +93,13 @@ export function createSlackPlanRenderer(
...view.entities.map((entity) => [entity.id, entityVersion(entity)]),
]);
if (view.settled) {
- await checked("chat.stopStream", { channel, ts: current.ts }, botToken, installation);
+ await checked(
+ "chat.stopStream",
+ { channel, ts: current.ts },
+ apiOptions,
+ botToken,
+ installation,
+ );
const blocks = [
{
type: "plan",
@@ -105,6 +115,7 @@ export function createSlackPlanRenderer(
await checked(
"chat.update",
{ channel, ts: current.ts, text: view.parents.map((p) => p.name).join(", "), blocks },
+ apiOptions,
botToken,
installation,
);
@@ -230,10 +241,12 @@ function safeId(id: string) {
async function api(
operation: string,
body: unknown,
+ apiOptions: SlackTransportOptions | undefined,
botToken: SlackBotToken | undefined,
installation: unknown,
) {
return callSlackApi({
+ api: apiOptions,
operation,
body,
botToken,
@@ -243,10 +256,11 @@ async function api(
async function checked(
operation: string,
body: unknown,
+ apiOptions: SlackTransportOptions | undefined,
token: SlackBotToken | undefined,
installation: unknown,
) {
- const response = await api(operation, body, token, installation);
+ const response = await api(operation, body, apiOptions, token, installation);
if (!response.ok)
throw new Error(`Slack ${operation} failed: ${response.error ?? "unknown_error"}`);
}
diff --git a/packages/eve/src/public/channels/slack/activity.ts b/packages/eve/src/public/channels/slack/activity.ts
index 78ff5f6a7..e6bf7971c 100644
--- a/packages/eve/src/public/channels/slack/activity.ts
+++ b/packages/eve/src/public/channels/slack/activity.ts
@@ -6,6 +6,7 @@ import type {
ActivityWorkStateV1,
} from "#protocol/activity.js";
import { callSlackApi, type SlackBotToken } from "#public/channels/slack/api.js";
+import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
import {
createSlackPlanRenderer,
SLACK_ACTIVITY_PLAN_RENDERER_ID,
@@ -104,6 +105,7 @@ export function hasSlackActivityStatus(
}
export function buildSlackActivityRenderers(input: {
+ readonly api?: SlackTransportOptions;
readonly botToken: SlackBotToken | undefined;
readonly renderers: readonly SlackActivityRenderer[];
}): readonly ChannelActivityRenderer[] {
@@ -116,13 +118,13 @@ export function buildSlackActivityRenderers(input: {
throw new TypeError(`Duplicate Slack activity renderer "${renderer.id}".`);
ids.add(renderer.id);
if (renderer.id === SLACK_ACTIVITY_MESSAGE_RENDERER_ID) {
- return createSlackActivityRenderer(input.botToken);
+ return createSlackActivityRenderer(input.api, input.botToken);
}
if (renderer.id === SLACK_ACTIVITY_PLAN_RENDERER_ID) {
- return createSlackPlanRenderer(input.botToken);
+ return createSlackPlanRenderer(input.api, input.botToken);
}
if (renderer.id === SLACK_ACTIVITY_STATUS_RENDERER_ID) {
- return createSlackStatusRenderer(input.botToken);
+ return createSlackStatusRenderer(input.api, input.botToken);
}
assertCustomSlackActivityRenderer(renderer);
return createCustomSlackActivityRenderer(renderer);
@@ -203,7 +205,10 @@ function experimentalSlackActivityDestination(
};
}
-function createSlackStatusRenderer(botToken: SlackBotToken | undefined): ChannelActivityRenderer {
+function createSlackStatusRenderer(
+ api: SlackTransportOptions | undefined,
+ botToken: SlackBotToken | undefined,
+): ChannelActivityRenderer {
return {
id: SLACK_ACTIVITY_STATUS_RENDERER_ID,
async dispose({ destination, state }) {
@@ -213,6 +218,7 @@ function createSlackStatusRenderer(botToken: SlackBotToken | undefined): Channel
const threadTs = destination["threadTs"];
if (typeof channelId !== "string" || typeof threadTs !== "string" || threadTs === "") return;
const response = await callSlackApi({
+ api,
body: { channel_id: channelId, status: "", thread_ts: threadTs },
botToken,
context: {
@@ -234,6 +240,7 @@ function createSlackStatusRenderer(botToken: SlackBotToken | undefined): Channel
const body: Record<string, unknown> = { channel_id: channelId, status, thread_ts: threadTs };
if (status !== "") body.loading_messages = [status];
const response = await callSlackApi({
+ api,
body,
botToken,
context: {
@@ -251,7 +258,10 @@ function createSlackStatusRenderer(botToken: SlackBotToken | undefined): Channel
};
}
-function createSlackActivityRenderer(botToken: SlackBotToken | undefined): ChannelActivityRenderer {
+function createSlackActivityRenderer(
+ api: SlackTransportOptions | undefined,
+ botToken: SlackBotToken | undefined,
+): ChannelActivityRenderer {
return {
id: SLACK_ACTIVITY_MESSAGE_RENDERER_ID,
async dispose() {},
@@ -272,6 +282,7 @@ function createSlackActivityRenderer(botToken: SlackBotToken | undefined): Chann
const current =
previous[rootTurnId] ??
(await recoverActivityMessage({
+ api,
botToken,
channelId,
installationTeamId,
@@ -283,6 +294,7 @@ function createSlackActivityRenderer(botToken: SlackBotToken | undefined): Chann
continue;
}
let response = await writeActivityMessage({
+ api,
botToken,
channelId,
current,
@@ -297,6 +309,7 @@ function createSlackActivityRenderer(botToken: SlackBotToken | undefined): Chann
response.error === "message_not_found"
) {
response = await writeActivityMessage({
+ api,
botToken,
channelId,
installationTeamId,
@@ -320,6 +333,7 @@ function createSlackActivityRenderer(botToken: SlackBotToken | undefined): Chann
}
async function writeActivityMessage(input: {
+ readonly api: SlackTransportOptions | undefined;
readonly botToken: SlackBotToken | undefined;
readonly channelId: string;
readonly current?: { readonly ts: string };
@@ -341,6 +355,7 @@ async function writeActivityMessage(input: {
thread_ts: input.threadTs,
}
: { channel: input.channelId, text: input.text, ts: input.current.ts },
+ api: input.api,
botToken: input.botToken,
context: {
teamId: typeof input.installationTeamId === "string" ? input.installationTeamId : undefined,
@@ -350,6 +365,7 @@ async function writeActivityMessage(input: {
}
async function recoverActivityMessage(input: {
+ readonly api: SlackTransportOptions | undefined;
readonly botToken: SlackBotToken | undefined;
readonly channelId: string;
readonly installationTeamId: unknown;
@@ -367,6 +383,7 @@ async function recoverActivityMessage(input: {
};
if (cursor !== undefined) body.cursor = cursor;
const response = await callSlackApi({
+ api: input.api,
body,
botToken: input.botToken,
context: {
diff --git a/packages/eve/src/public/channels/slack/api-errors.ts b/packages/eve/src/public/channels/slack/api-errors.ts
deleted file mode 100644
index aa50df7a0..000000000
--- a/packages/eve/src/public/channels/slack/api-errors.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Records whether a Slack Web API call got a response.
- *
- * Slack retries an interaction whose acknowledgement is not a 2xx, so a
- * handler answering a click has to swallow a call Slack answered badly
- * and rethrow a call that never arrived. Those two are indistinguishable
- * once thrown: the transport consumes the response body before it reads
- * the status, so a body cut off partway raises the same `TypeError` as a
- * connection that was never made. Nothing on the error says which it
- * was, so every Slack call eve makes goes out through here and the
- * answer is recorded while the call runs.
- *
- * Separate from `api.ts` because that file sits on the 700-line cap
- * `internal/structural-tests/file-length.test.ts` enforces.
- */
-
-import {
- callSlackApi as callSlackApiPrimitive,
- type SlackApiOptions,
- type SlackApiResponse,
-} from "#compiled/@chat-adapter/slack/api.js";
-
-/** Errors raised after Slack's response arrived. */
-const slackResponseErrors = new WeakSet<object>();
-
-/**
- * POSTs to a Slack Web API method and records the response arriving.
- *
- * The transport is handed a `fetch` that observes the response, so
- * everything thrown from that moment on — a non-2xx, a body that is not
- * the JSON envelope, a body cut off mid-read — is marked for
- * {@link isSlackResponseError}. A failure before then stays unmarked and
- * reaches the caller, which is what fails the interaction request.
- */
-export async function callSlackApiTrackingResponse(
- operation: string,
- body: Record<string, unknown>,
- options: SlackApiOptions,
-): Promise<SlackApiResponse> {
- let responded = false;
- const observe: typeof globalThis.fetch = async (input, init) => {
- const response = await (options.fetch ?? globalThis.fetch)(input, init);
- responded = true;
- return response;
- };
- try {
- return await callSlackApiPrimitive(operation, body, { ...options, fetch: observe });
- } catch (error) {
- if (responded && typeof error === "object" && error !== null) {
- slackResponseErrors.add(error);
- }
- throw error;
- }
-}
-
-/**
- * True when Slack answered the call, false when the call never got a
- * response. A caller that must acknowledge Slack swallows the first and
- * rethrows the second; see {@link callSlackApiTrackingResponse} for why
- * the error itself cannot be asked.
- */
-export function isSlackResponseError(error: unknown): boolean {
- return typeof error === "object" && error !== null && slackResponseErrors.has(error);
-}
diff --git a/packages/eve/src/public/channels/slack/api.test.ts b/packages/eve/src/public/channels/slack/api.test.ts
index 237fb1e6d..1a051b451 100644
--- a/packages/eve/src/public/channels/slack/api.test.ts
+++ b/packages/eve/src/public/channels/slack/api.test.ts
@@ -8,6 +8,7 @@ import {
resolveSlackBotToken,
type SlackBotTokenContext,
} from "#public/channels/slack/api.js";
+import { resolveSlackTransportOptions } from "#public/channels/slack/transport.js";
interface FetchCall {
url: string;
@@ -999,3 +1000,62 @@ describe("Slack bot token context", () => {
expect(botToken).toHaveBeenCalledTimes(1);
});
});
+
+describe("api transport options", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+ const okFetch = () => vi.fn<typeof fetch>(async () => Response.json({ ok: true }));
+
+ it("calls Slack's own host when api is omitted", async () => {
+ const globalFetch = okFetch();
+ vi.stubGlobal("fetch", globalFetch);
+
+ await callSlackApi({ body: {}, botToken: "xoxb-test", operation: "auth.test" });
+
+ expect(String(globalFetch.mock.calls[0]?.[0])).toBe("https://slack.com/api/auth.test");
+ });
+
+ it("checks and resolves a base it is handed directly", async () => {
+ const globalFetch = okFetch();
+ vi.stubGlobal("fetch", globalFetch);
+ const apiFetch = okFetch();
+
+ // No trailing slash and never passed through resolveSlackTransportOptions:
+ // the call resolves its own options.
+ await callSlackApi({
+ api: { apiBaseUrl: "http://localhost:3000/api/slack", fetch: apiFetch },
+ body: {},
+ botToken: "xoxb-test",
+ operation: "auth.test",
+ });
+
+ expect(String(apiFetch.mock.calls[0]?.[0])).toBe("http://localhost:3000/api/slack/auth.test");
+ expect(globalFetch).not.toHaveBeenCalled();
+ });
+
+ it("confines a fetch it is handed directly", async () => {
+ const globalFetch = okFetch();
+ vi.stubGlobal("fetch", globalFetch);
+ const apiFetch = okFetch();
+ const api = { apiBaseUrl: "http://localhost:3000/api/slack", fetch: apiFetch };
+
+ await callSlackApi({ api, body: {}, botToken: "xoxb-test", operation: "auth.test" });
+ await (resolveSlackTransportOptions(api)?.fetch ?? fetch)("https://files.slack.com/upload/abc");
+
+ expect(globalFetch.mock.calls.map((call) => String(call[0]))).toEqual([
+ "https://files.slack.com/upload/abc",
+ ]);
+ });
+
+ it("names the option a base it cannot reach belongs to", async () => {
+ await expect(
+ callSlackApi({
+ api: { apiBaseUrl: "/api/slack" },
+ body: {},
+ botToken: "xoxb-test",
+ operation: "auth.test",
+ }),
+ ).rejects.toThrow(/api\.apiBaseUrl must be an absolute http or https URL/);
+ });
+});
diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.ts
index 93d9af3d7..628de4ffd 100644
--- a/packages/eve/src/public/channels/slack/api.ts
+++ b/packages/eve/src/public/channels/slack/api.ts
@@ -29,11 +29,15 @@ import {
import { isCardElement, type CardElement, type FileUpload } from "#compiled/chat/index.js";
import { createLogger, logError } from "#internal/logging.js";
-import { callSlackApiTrackingResponse } from "#public/channels/slack/api-errors.js";
import { cardToBlocks, cardToFallbackText } from "#public/channels/slack/blocks.js";
import { resolveSlackInboundMrkdwn } from "#public/channels/slack/inbound-content.js";
import { truncateTypingStatus } from "#public/channels/slack/limits.js";
import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";
+import {
+ callSlackApiTrackingResponse,
+ slackApiOptions,
+ type SlackTransportOptions,
+} from "#public/channels/slack/transport.js";
const log = createLogger("slack.api");
@@ -85,8 +89,12 @@ export type SlackApiResponse = SlackPrimitiveApiResponse;
* and form-encoded. Form is the only safe default: Slack's JSON support
* is partial (e.g. `conversations.replies` rejects JSON). Returns the
* raw JSON response; callers inspect `response.ok` themselves.
+ *
+ * `api` takes the same value {@link slackChannel} does and is checked and
+ * confined here, so a call made without a channel carries the same guarantees.
*/
export async function callSlackApi(input: {
+ readonly api?: SlackTransportOptions;
readonly botToken: SlackBotToken | undefined;
readonly context?: SlackBotTokenContext;
readonly operation: string;
@@ -95,7 +103,7 @@ export async function callSlackApi(input: {
return callSlackApiTrackingResponse(
input.operation,
normalizeSlackApiBody(input.body),
- createSlackApiOptions(input.botToken, input.context),
+ slackApiOptions(input.api, () => resolveSlackBotToken(input.botToken, input.context)),
);
}
@@ -105,10 +113,11 @@ export async function callSlackApi(input: {
* credentials are picked up without rebuilding the binding.
*/
function createSlackRequester(
+ api: SlackTransportOptions | undefined,
botToken: SlackBotToken | undefined,
context: SlackBotTokenContext,
): (operation: string, body: unknown) => Promise<SlackApiResponse> {
- return (operation, body) => callSlackApi({ botToken, context, operation, body });
+ return (operation, body) => callSlackApi({ api, botToken, context, operation, body });
}
/**
@@ -359,6 +368,7 @@ export interface SlackWorkspaceHandle {
/** Builds the workspace-scoped API handle used by generic event callbacks. */
export function buildSlackWorkspaceHandle(input: {
+ readonly api?: SlackTransportOptions;
readonly botToken: SlackBotToken | undefined;
/** Workspace whose app installation supplies the bot token. */
readonly installationTeamId?: string;
@@ -367,7 +377,7 @@ export function buildSlackWorkspaceHandle(input: {
}): SlackWorkspaceHandle {
return {
teamId: input.teamId,
- request: createSlackRequester(input.botToken, { teamId: input.installationTeamId }),
+ request: createSlackRequester(input.api, input.botToken, { teamId: input.installationTeamId }),
};
}
@@ -392,6 +402,7 @@ interface SlackBinding {
*/
export function buildSlackBinding(input: {
/** Slack app id used to identify this app's fetched thread replies. */
+ readonly api?: SlackTransportOptions;
readonly appId?: string;
readonly botToken: SlackBotToken | undefined;
/** Slack bot user id used to identify this app's fetched thread replies. */
@@ -405,7 +416,9 @@ export function buildSlackBinding(input: {
readonly onThreadTsChanged?: (ts: string) => void;
}): SlackBinding {
const context = { teamId: input.installationTeamId };
- const request = createSlackRequester(input.botToken, context);
+ const token = () => resolveSlackBotToken(input.botToken, context);
+ const apiOptions = slackApiOptions(input.api, token);
+ const request = createSlackRequester(input.api, input.botToken, context);
let messages: readonly SlackThreadMessage[] = [];
let currentThreadTs = input.threadTs;
let refreshInFlight: Promise<void> | undefined;
@@ -424,7 +437,7 @@ export function buildSlackBinding(input: {
const threadTs = options?.threadTs ?? currentThreadTs;
const uploads = files.map((file) => toSlackFileUpload(file, options?.snippetType));
return uploadSlackFiles(uploads, {
- ...createSlackApiOptions(input.botToken, context),
+ ...apiOptions,
channelId: channelId || undefined,
initialComment: options?.initialComment,
threadTs: threadTs || undefined,
@@ -443,7 +456,7 @@ export function buildSlackBinding(input: {
}
try {
const response = await fetchSlackThreadReplies({
- ...createSlackApiOptions(input.botToken, context),
+ ...apiOptions,
channel: input.channelId,
limit: 50,
ts: currentThreadTs,
@@ -501,7 +514,7 @@ export function buildSlackBinding(input: {
}
const response = await postSlackMessage(
- buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken, context),
+ buildPostMessageOptions(message, input.channelId, currentThreadTs, apiOptions),
);
const id = response.id;
handleMessageTs(id);
@@ -520,13 +533,7 @@ export function buildSlackBinding(input: {
async postEphemeral(userId, rawMessage) {
const message = normalizePostInput(rawMessage);
const response = await postSlackEphemeral({
- ...buildPostMessageOptions(
- message,
- input.channelId,
- currentThreadTs,
- input.botToken,
- context,
- ),
+ ...buildPostMessageOptions(message, input.channelId, currentThreadTs, apiOptions),
user: userId,
});
return { id: response.id, raw: response.raw };
@@ -540,7 +547,7 @@ export function buildSlackBinding(input: {
}
const message = normalizePostInput(rawMessage);
const response = await postSlackMessage(
- buildPostMessageOptions(message, imChannelId, "", input.botToken, context),
+ buildPostMessageOptions(message, imChannelId, "", apiOptions),
);
return { id: response.id, raw: response.raw };
},
@@ -608,11 +615,10 @@ function buildPostMessageOptions(
message: SlackPostInput,
channelId: string,
threadTs: string,
- botToken: SlackBotToken | undefined,
- context: SlackBotTokenContext,
+ apiOptions: SlackApiOptions,
): SlackMessageOptions {
const base: SlackMessageOptions = {
- ...createSlackApiOptions(botToken, context),
+ ...apiOptions,
channel: channelId,
threadTs: threadTs || undefined,
unfurlLinks: false,
@@ -637,13 +643,6 @@ function buildPostMessageOptions(
return base;
}
-function createSlackApiOptions(
- botToken: SlackBotToken | undefined,
- context: SlackBotTokenContext = {},
-): SlackApiOptions {
- return { token: () => resolveSlackBotToken(botToken, context) };
-}
-
function normalizeSlackApiBody(body: unknown): Record<string, unknown> {
if (body && typeof body === "object" && !Array.isArray(body)) {
return body as Record<string, unknown>;
diff --git a/packages/eve/src/public/channels/slack/attachments.test.ts b/packages/eve/src/public/channels/slack/attachments.test.ts
index 232203319..9916b407b 100644
--- a/packages/eve/src/public/channels/slack/attachments.test.ts
+++ b/packages/eve/src/public/channels/slack/attachments.test.ts
@@ -7,6 +7,10 @@ import {
createSlackFetchFile,
} from "#public/channels/slack/attachments.js";
import type { SlackAttachment } from "#public/channels/slack/inbound.js";
+import {
+ resolveSlackTransportOptions,
+ type SlackTransportOptions,
+} from "#public/channels/slack/transport.js";
import { DEFAULT_UPLOAD_POLICY, mergeUploadPolicy } from "#public/channels/upload-policy.js";
const DISABLED_POLICY = mergeUploadPolicy("disabled");
@@ -252,6 +256,86 @@ describe("createSlackFetchFile", () => {
await expect(result).rejects.toThrow(/files:read.*reinstall/is);
await expect(result).rejects.not.toThrow("PRIVATE");
});
+
+ const fetchFileFor = (api?: SlackTransportOptions) =>
+ createSlackFetchFile({ api: resolveSlackTransportOptions(api), botToken: "xoxb-test-token" });
+ const pngFetch = () =>
+ vi.fn<typeof fetch>(
+ async () => new Response(new Uint8Array([7]), { headers: { "content-type": "image/png" } }),
+ );
+
+ it("downloads a file under the configured file base with api.fetch", async () => {
+ const globalSpy = vi.spyOn(globalThis, "fetch");
+ const apiFetch = pngFetch();
+
+ const result = await fetchFileFor({
+ apiBaseUrl: "http://localhost:3000/api/slack",
+ fetch: apiFetch,
+ fileBaseUrl: "http://localhost:3000/files",
+ })("http://localhost:3000/files/F01/cat.png");
+
+ expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
+ expect(apiFetch).toHaveBeenCalledWith("http://localhost:3000/files/F01/cat.png", {
+ headers: { authorization: "Bearer xoxb-test-token" },
+ });
+ expect(globalSpy).not.toHaveBeenCalled();
+ });
+
+ it("falls the download base back to apiBaseUrl, and widens it by path prefix only", async () => {
+ const apiFetch = pngFetch();
+ const underApiBase = fetchFileFor({
+ apiBaseUrl: "http://localhost:3000/api/slack",
+ fetch: apiFetch,
+ });
+
+ const result = await underApiBase("http://localhost:3000/api/slack/files/F01/cat.png");
+
+ expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
+ expect(await underApiBase("http://localhost:3000/files/F01/cat.png")).toBeNull();
+ expect(await fetchFileFor()("http://localhost:3000/files/F01/cat.png")).toBeNull();
+ // `https://slack.com/api/` is the default base: it must not turn every
+ // `https://slack.com/…` link into a bot-token-authenticated download.
+ expect(
+ await fetchFileFor({ apiBaseUrl: "https://slack.com/api/" })(
+ "https://slack.com/files/secret.png",
+ ),
+ ).toBeNull();
+ });
+
+ it("downloads from Slack's own file host on the global fetch, past a stand-in's api.fetch", async () => {
+ const globalFetch = pngFetch();
+ vi.stubGlobal("fetch", globalFetch);
+ const apiFetch = pngFetch();
+
+ const result = await fetchFileFor({
+ apiBaseUrl: "http://localhost:3000/api/slack",
+ fetch: apiFetch,
+ })("https://files.slack.com/files-pri/T01-F01/cat.png");
+
+ expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
+ expect(globalFetch).toHaveBeenCalledWith("https://files.slack.com/files-pri/T01-F01/cat.png", {
+ headers: { authorization: "Bearer xoxb-test-token" },
+ });
+ // A stand-in's api.fetch attaches that stand-in's credentials, and this URL
+ // arrives in an inbound payload.
+ expect(apiFetch).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+
+ it("downloads from Slack's own file host on api.fetch when no base is configured", async () => {
+ const globalSpy = vi.spyOn(globalThis, "fetch");
+ const apiFetch = pngFetch();
+
+ const result = await fetchFileFor({ fetch: apiFetch })(
+ "https://files.slack.com/files-pri/T01-F01/cat.png",
+ );
+
+ expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
+ expect(apiFetch).toHaveBeenCalledWith("https://files.slack.com/files-pri/T01-F01/cat.png", {
+ headers: { authorization: "Bearer xoxb-test-token" },
+ });
+ expect(globalSpy).not.toHaveBeenCalled();
+ });
});
describe("collectInboundFileParts", () => {
diff --git a/packages/eve/src/public/channels/slack/attachments.ts b/packages/eve/src/public/channels/slack/attachments.ts
index 9c89c3e68..ef25eb5a0 100644
--- a/packages/eve/src/public/channels/slack/attachments.ts
+++ b/packages/eve/src/public/channels/slack/attachments.ts
@@ -9,6 +9,11 @@ import {
type SlackThread,
} from "#public/channels/slack/api.js";
import type { SlackAttachment, SlackMessage } from "#public/channels/slack/inbound.js";
+import {
+ isConfiguredSlackFileUrl,
+ resolveSlackTransportOptions,
+ type SlackTransportOptions,
+} from "#public/channels/slack/transport.js";
import {
evaluateFilePart,
formatUploadPolicyViolation,
@@ -163,21 +168,24 @@ export function buildSlackTurnMessage(
* Creates a `fetchFile` function for the Slack channel.
*
* Returns `null` for URLs that don't belong to Slack so they pass
- * through to the model provider unchanged. Fetches Slack file URLs
- * with the bot token.
+ * through to the model provider unchanged. Fetches Slack file URLs, and
+ * URLs under a configured `api.fileBaseUrl`, with the bot token, on
+ * `api.fetch` when one is configured.
*/
export function createSlackFetchFile(input: {
+ readonly api?: SlackTransportOptions;
readonly botToken?: SlackBotToken;
}): (url: string, context?: FetchFileContext) => Promise<FetchFileResult | null> {
+ const api = resolveSlackTransportOptions(input.api);
return async (url, context) => {
- if (!isSlackFileUrl(url)) {
+ if (!isConfiguredSlackFileUrl(api, url) && !isSlackFileUrl(url)) {
return null;
}
const installationTeamId = context?.state.installationTeamId;
const token = await resolveSlackBotToken(input.botToken, {
teamId: typeof installationTeamId === "string" ? installationTeamId : undefined,
});
- const response = await fetch(url, {
+ const response = await (api?.fetch ?? fetch)(url, {
headers: { authorization: `Bearer ${token}` },
});
if (!response.ok) {
diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.ts
index 286eee5e7..f129439d7 100644
--- a/packages/eve/src/public/channels/slack/index.ts
+++ b/packages/eve/src/public/channels/slack/index.ts
@@ -76,6 +76,8 @@ export {
type SlackUploadFilesResult,
} from "#public/channels/slack/api.js";
+export { type SlackFetch, type SlackTransportOptions } from "#public/channels/slack/transport.js";
+
export { defaultSlackAuth } from "#public/channels/slack/defaults.js";
export {
diff --git a/packages/eve/src/public/channels/slack/input-response.ts b/packages/eve/src/public/channels/slack/input-response.ts
index d9b4ea593..ab1d56605 100644
--- a/packages/eve/src/public/channels/slack/input-response.ts
+++ b/packages/eve/src/public/channels/slack/input-response.ts
@@ -10,6 +10,7 @@ import type {
SlackInputResponseSubmission,
SlackChannelState,
} from "#public/channels/slack/slackChannel.js";
+import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
const log = createLogger("slack.interactions");
@@ -29,6 +30,7 @@ export function approvalResponderStatePatch(
export async function authorizeInputResponse(input: {
readonly channelId: string;
readonly deps: {
+ readonly api: SlackTransportOptions | undefined;
readonly config: SlackChannelConfig;
readonly onInputResponse: NonNullable<SlackChannelConfig["onInputResponse"]>;
};
@@ -45,6 +47,7 @@ export async function authorizeInputResponse(input: {
userName: input.submission.user.username ?? input.submission.user.name,
});
const { thread, slack } = buildSlackBinding({
+ api: input.deps.api,
botToken: input.deps.config.credentials?.botToken,
channelId: input.channelId,
threadTs: input.threadTs,
diff --git a/packages/eve/src/public/channels/slack/interaction-cards.ts b/packages/eve/src/public/channels/slack/interaction-cards.ts
index d34b46b90..e097c7d7b 100644
--- a/packages/eve/src/public/channels/slack/interaction-cards.ts
+++ b/packages/eve/src/public/channels/slack/interaction-cards.ts
@@ -184,6 +184,7 @@ async function updateAnsweredCard(input: {
readonly messageTs: string;
}): Promise<void> {
await callSlackApi({
+ api: input.deps.api,
botToken: input.deps.config.credentials?.botToken,
context: { teamId: input.installationTeamId },
operation: "chat.update",
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 0d3d62d23..9a9ab51d8 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -11,7 +11,10 @@ import {
} from "#compiled/@chat-adapter/slack/webhook.js";
import { createLogger } from "#internal/logging.js";
-import { isSlackResponseError } from "#public/channels/slack/api-errors.js";
+import {
+ isSlackResponseError,
+ type SlackTransportOptions,
+} from "#public/channels/slack/transport.js";
import {
buildSlackBinding,
buildSlackWorkspaceHandle,
@@ -231,6 +234,7 @@ function readInstallationTeamId(value: unknown): string | undefined {
/** Channel-supplied dependencies for {@link handleInteractionPost}. */
export interface InteractionHandlerDeps {
+ readonly api: SlackTransportOptions | undefined;
readonly config: SlackChannelConfig;
readonly onInputResponse: NonNullable<SlackChannelConfig["onInputResponse"]>;
}
@@ -269,7 +273,7 @@ export async function handleInteractionPost(
}
if (payload.kind === "slash_command") {
- dispatchSlashCommand(payload, ctx, deps.config);
+ dispatchSlashCommand(payload, ctx, deps);
return new Response(null, { status: 200 });
}
@@ -328,6 +332,7 @@ export async function handleInteractionPost(
if (customActions.length > 0) {
const actionUser = customActions[0]!.user;
const { thread, slack } = buildSlackBinding({
+ api: deps.api,
botToken: deps.config.credentials?.botToken,
channelId: interaction.channelId,
threadTs: interaction.threadTs,
@@ -439,26 +444,15 @@ function dispatchShortcut(
return;
}
- const shortcutCtx: SlackShortcutContext = buildShortcutContext({
- config: deps.config,
- installationTeamId,
- teamId: shortcut.teamId,
- });
- dispatchInteractionHook(() => onShortcut(shortcut, shortcutCtx), ctx, "shortcut handler failed");
-}
-
-function buildShortcutContext(input: {
- readonly config: SlackChannelConfig;
- readonly installationTeamId: string | undefined;
- readonly teamId: string | undefined;
-}): SlackShortcutContext {
- return {
+ const shortcutCtx: SlackShortcutContext = {
slack: buildSlackWorkspaceHandle({
- botToken: input.config.credentials?.botToken,
- installationTeamId: input.installationTeamId,
- teamId: input.teamId,
+ api: deps.api,
+ botToken: deps.config.credentials?.botToken,
+ installationTeamId,
+ teamId: shortcut.teamId,
}),
};
+ dispatchInteractionHook(() => onShortcut(shortcut, shortcutCtx), ctx, "shortcut handler failed");
}
function dispatchInteractionHook(
@@ -574,6 +568,7 @@ async function openFreeformModal(input: {
// above resolves outside the try so a throwing resolver joins that case.
try {
await callSlackApi({
+ api: input.deps.api,
botToken: token,
operation: "views.open",
body: { trigger_id: triggerId, view },
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 04d8c6448..ebcdc3463 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -4199,6 +4199,63 @@ describe("slackChannel() HITL interaction pipeline", () => {
});
});
+describe("slackChannel() api option", () => {
+ it("sends every handle's call to the configured base and never to the global fetch", async () => {
+ const globalFetch = vi.fn();
+ vi.stubGlobal("fetch", globalFetch);
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ });
+ const apiFetch = vi.fn<typeof fetch>(async () =>
+ Response.json({ ok: true, ts: "1700000001.000001" }),
+ );
+ const channel = slackChannel({
+ api: {
+ apiBaseUrl: "http://localhost:3000/api/slack",
+ fetch: apiFetch,
+ },
+ credentials: { botToken: "xoxb-test", signingSecret: SIGNING_SECRET },
+ onAppMention: () => ({ auth: null }),
+ onInteraction: async (_action, ctx) => {
+ await ctx.slack.request("auth.test", {});
+ },
+ onShortcut: async (_shortcut, ctx) => {
+ await ctx.slack.request("auth.test", {});
+ },
+ });
+
+ await firePost(channel, buildSignedRequest({ body: buildMentionBody().body }));
+ await firePost(
+ channel,
+ buildSignedInteractionRequest({
+ type: "block_actions",
+ team: { id: "T01" },
+ user: { id: "U01", username: "ada", team_id: "T01" },
+ channel: { id: "C01" },
+ message: { ts: "1700000000.000010", thread_ts: "1700000000.000001", blocks: [] },
+ actions: [{ action_id: "custom", value: "v" }],
+ }),
+ );
+ await firePost(
+ channel,
+ buildSignedInteractionRequest({
+ type: "message_action",
+ callback_id: "summarize_message",
+ trigger_id: "trigger-123",
+ team: { id: "T01" },
+ user: { id: "U01", username: "ada" },
+ channel: { id: "C01" },
+ message: { text: "summarize this", ts: "1700000000.000010" },
+ }),
+ );
+
+ const urls = apiFetch.mock.calls.map((call) => String(call[0]));
+ expect(globalFetch).not.toHaveBeenCalled();
+ expect(urls.length).toBeGreaterThan(0);
+ expect(urls.filter((url) => !url.startsWith("http://localhost:3000/api/slack/"))).toEqual([]);
+ });
+});
+
describe("slackChannel() webhookVerifier credentials path", () => {
const ORIGINAL_SIGNING_SECRET = process.env.SLACK_SIGNING_SECRET;
const ORIGINAL_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 337ea38f4..32ae546c9 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -31,6 +31,10 @@ import {
type SlackThread,
type SlackWorkspaceHandle,
} from "#public/channels/slack/api.js";
+import {
+ resolveSlackTransportOptions,
+ type SlackTransportOptions,
+} from "#public/channels/slack/transport.js";
import {
buildSlackTurnMessage,
collectInboundFileParts,
@@ -643,6 +647,8 @@ export type SlackApprovalChannelResolver = (
) => SlackApprovalChannel | Promise<SlackApprovalChannel>;
export interface SlackChannelConfig {
+ /** Slack API transport overrides: base URLs and a custom fetch. */
+ readonly api?: SlackTransportOptions;
readonly credentials?: SlackChannelCredentials;
readonly botName?: string;
@@ -829,9 +835,11 @@ const clearSlackTurnState: NonNullable<SlackChannelEvents["turn.started"]> = asy
function rebuildSlackContext(
state: SlackChannelState,
session: SessionHandle,
+ api: SlackTransportOptions | undefined,
credentials: SlackChannelCredentials | undefined,
): SlackChannelContext {
const { thread, slack } = buildSlackBinding({
+ api,
botToken: credentials?.botToken,
channelId: state.channelId ?? "",
threadTs: state.threadTs ?? "",
@@ -869,9 +877,14 @@ export interface SlackChannel extends Channel<
* fields keep their defaults.
*/
export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
+ const api = resolveSlackTransportOptions(config.api);
const uploadPolicy = mergeUploadPolicy(config.uploadPolicy);
- const slackFetchFile = createSlackFetchFile({ botToken: config.credentials?.botToken });
+ const slackFetchFile = createSlackFetchFile({
+ api,
+ botToken: config.credentials?.botToken,
+ });
const activityRenderers = buildSlackActivityRenderers({
+ api,
botToken: config.credentials?.botToken,
renderers: config.activity?.renderers ?? [],
});
@@ -977,7 +990,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
audience: ({ state }) => state.audience ?? "unknown",
context(state, session) {
- return rebuildSlackContext(state, session, config.credentials);
+ return rebuildSlackContext(state, session, api, config.credentials);
},
deliver(payload, channel) {
@@ -1012,10 +1025,11 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
return handleInteractionPost(
body,
{ from, resolveSession, waitUntil },
- { config, onInputResponse },
+ { api, config, onInputResponse },
);
}
return handleEventPost({
+ api,
body,
from,
resolveSession,
@@ -1029,7 +1043,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
],
receive(input, { from }) {
- return receiveOnSlack(input, { from, credentials: config.credentials });
+ return receiveOnSlack(input, { from, api, credentials: config.credentials });
},
events: mergedEvents,
@@ -1068,6 +1082,7 @@ async function receiveOnSlack(
},
deps: {
readonly from: ChannelFrom<SlackChannelState>;
+ readonly api: SlackTransportOptions | undefined;
readonly credentials: SlackChannelCredentials | undefined;
/** Installation workspace inherited from an inbound trigger. */
readonly installationTeamId?: string;
@@ -1098,6 +1113,7 @@ async function receiveOnSlack(
let threadTs = requestedThreadTs;
if (initialMessage) {
const { thread } = buildSlackBinding({
+ api: deps.api,
botToken: deps.credentials?.botToken,
channelId,
threadTs: "",
@@ -1181,6 +1197,7 @@ function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {
* Returns `200 OK` in every case because Slack only requires an immediate ACK.
*/
async function handleEventPost(input: {
+ readonly api: SlackTransportOptions | undefined;
readonly body: string;
readonly from: ChannelFrom<SlackChannelState>;
readonly resolveSession: ChannelResolveSession;
@@ -1228,6 +1245,7 @@ async function handleEventPost(input: {
const dispatchMessageWith =
(handler: NonNullable<SlackChannelConfig["onAppMention"]>) => () =>
dispatchSlackMessage({
+ api: input.api,
appId,
botUserId,
receivingBotUserId,
@@ -1246,6 +1264,7 @@ async function handleEventPost(input: {
if (handler !== undefined) {
dispatch = () =>
dispatchSlackMessage({
+ api: input.api,
appId,
botUserId,
receivingBotUserId,
@@ -1275,6 +1294,7 @@ async function handleEventPost(input: {
if (botUserId === undefined || !message.text.includes(`<@${botUserId}`)) {
dispatch = () =>
dispatchSlackMessage({
+ api: input.api,
appId,
botUserId,
receivingBotUserId,
@@ -1298,6 +1318,7 @@ async function handleEventPost(input: {
if (dispatch === null && onEvent !== undefined) {
dispatch = () =>
dispatchSlackEvent({
+ api: input.api,
from: input.from,
resolveSession: input.resolveSession,
credentials: config.credentials,
@@ -1342,6 +1363,7 @@ function isSelfAuthoredSlackMessage(
}
async function dispatchSlackMessage(input: {
+ readonly api: SlackTransportOptions | undefined;
readonly appId: string | undefined;
readonly botUserId: string | undefined;
readonly receivingBotUserId: string | undefined;
@@ -1357,6 +1379,7 @@ async function dispatchSlackMessage(input: {
}): Promise<void> {
const continuationToken = slackContinuationToken(input.message.channelId, input.message.threadTs);
const { thread, slack } = buildSlackBinding({
+ api: input.api,
appId: input.appId,
botToken: input.credentials?.botToken,
botUserId: input.botUserId,
@@ -1442,6 +1465,7 @@ async function dispatchSlackMessage(input: {
/** Runs a generic Events API handler with an imperative Slack operation surface. */
async function dispatchSlackEvent(input: {
+ readonly api: SlackTransportOptions | undefined;
readonly from: ChannelFrom<SlackChannelState>;
readonly resolveSession: ChannelResolveSession;
readonly credentials: SlackChannelCredentials | undefined;
@@ -1474,6 +1498,7 @@ async function dispatchSlackEvent(input: {
{ auth, message, target, title, taskDeliveryPolicy },
{
from: input.from,
+ api: input.api,
credentials: input.credentials,
installationTeamId: input.installationTeamId,
teamId,
@@ -1483,6 +1508,7 @@ async function dispatchSlackEvent(input: {
},
),
slack: buildSlackWorkspaceHandle({
+ api: input.api,
botToken: input.credentials?.botToken,
installationTeamId: input.installationTeamId,
teamId,
diff --git a/packages/eve/src/public/channels/slack/slash-command.ts b/packages/eve/src/public/channels/slack/slash-command.ts
index 98ed773f2..e5d497438 100644
--- a/packages/eve/src/public/channels/slack/slash-command.ts
+++ b/packages/eve/src/public/channels/slack/slash-command.ts
@@ -7,6 +7,7 @@ import type {
SlackSlashCommand,
SlackSlashCommandContext,
} from "#public/channels/slack/slackChannel.js";
+import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
const log = createLogger("slack.slash-command");
@@ -18,10 +19,10 @@ type SlashCommandPayload = Extract<
export function dispatchSlashCommand(
payload: SlashCommandPayload,
ctx: { readonly waitUntil: (task: Promise<unknown>) => void },
- config: SlackChannelConfig,
+ deps: { readonly api: SlackTransportOptions | undefined; readonly config: SlackChannelConfig },
): void {
const command = parseSlashCommandPayload(payload);
- const onSlashCommand = config.onSlashCommand;
+ const onSlashCommand = deps.config.onSlashCommand;
if (onSlashCommand === undefined) {
log.warn("Slack slash command ignored because onSlashCommand is not configured", {
command: command.command,
@@ -31,7 +32,8 @@ export function dispatchSlashCommand(
const commandCtx: SlackSlashCommandContext = {
slack: buildSlackWorkspaceHandle({
- botToken: config.credentials?.botToken,
+ api: deps.api,
+ botToken: deps.config.credentials?.botToken,
installationTeamId: command.teamId,
teamId: command.teamId,
}),
diff --git a/packages/eve/src/public/channels/slack/transport.test.ts b/packages/eve/src/public/channels/slack/transport.test.ts
new file mode 100644
index 000000000..6562e82d3
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/transport.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { resolveSlackTransportOptions } from "#public/channels/slack/transport.js";
+
+describe("resolveSlackTransportOptions", () => {
+ it("leaves an omitted api undefined", () => {
+ expect(resolveSlackTransportOptions(undefined)).toBeUndefined();
+ });
+
+ it("appends the trailing slash a directory base needs, and falls fileBaseUrl back", () => {
+ expect(resolveSlackTransportOptions({ apiBaseUrl: "https://sim.example/api" })).toEqual({
+ apiBaseUrl: "https://sim.example/api/",
+ fetch: undefined,
+ fileBaseUrl: "https://sim.example/api/",
+ });
+ });
+
+ it("resolves a fileBaseUrl of its own", () => {
+ expect(
+ resolveSlackTransportOptions({
+ apiBaseUrl: "https://sim.example/api/",
+ fileBaseUrl: "https://sim.example/files",
+ })?.fileBaseUrl,
+ ).toBe("https://sim.example/files/");
+ });
+
+ it("names the option a base that is not an absolute http URL belongs to", () => {
+ expect(() => resolveSlackTransportOptions({ apiBaseUrl: "/api/slack" })).toThrow(
+ /api\.apiBaseUrl must be an absolute http or https URL/,
+ );
+ expect(() => resolveSlackTransportOptions({ fileBaseUrl: "ftp://sim.example/files" })).toThrow(
+ /api\.fileBaseUrl must be an absolute http or https URL/,
+ );
+ });
+
+ it("names the option a base carrying a query or fragment belongs to", () => {
+ expect(() =>
+ resolveSlackTransportOptions({ apiBaseUrl: "https://sim.example/api?key=abc" }),
+ ).toThrow(/api\.apiBaseUrl must carry no query string or fragment/);
+ expect(() =>
+ resolveSlackTransportOptions({
+ apiBaseUrl: "https://sim.example/api",
+ fileBaseUrl: "https://sim.example/files#top",
+ }),
+ ).toThrow(/api\.fileBaseUrl must carry no query string or fragment/);
+ });
+});
+
+describe("the fetch resolveSlackTransportOptions returns", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ /** Records which transport a URL travelled on. */
+ function transports(api: Parameters<typeof resolveSlackTransportOptions>[0]) {
+ const seen: string[] = [];
+ const supplied = vi.fn(async (input: Parameters<typeof fetch>[0]) => {
+ seen.push(`supplied ${String(input instanceof Request ? input.url : input)}`);
+ return new Response("");
+ });
+ vi.stubGlobal("fetch", async (input: Parameters<typeof fetch>[0]) => {
+ seen.push(`global ${String(input instanceof Request ? input.url : input)}`);
+ return new Response("");
+ });
+ const resolved = resolveSlackTransportOptions({ ...api, fetch: supplied as never });
+ return { seen, fetch: resolved?.fetch };
+ }
+
+ it("carries a call to the configured api base", async () => {
+ const { seen, fetch: confined } = transports({ apiBaseUrl: "https://sim.example/api" });
+ await confined?.("https://sim.example/api/chat.postMessage");
+ expect(seen).toEqual(["supplied https://sim.example/api/chat.postMessage"]);
+ });
+
+ it("leaves a host the stand-in names on the global fetch", async () => {
+ const { seen, fetch: confined } = transports({ apiBaseUrl: "https://sim.example/api" });
+ // The `upload_url` from `files.getUploadURLExternal` and a `url_private` download
+ // are addressed by data, so a credential-attaching wrapper must not see them.
+ await confined?.("https://files.slack.com/upload/abc");
+ await confined?.(new Request("https://attacker.example/steal"));
+ expect(seen).toEqual([
+ "global https://files.slack.com/upload/abc",
+ "global https://attacker.example/steal",
+ ]);
+ });
+
+ it("carries a call to a fileBaseUrl on another origin", async () => {
+ const { seen, fetch: confined } = transports({
+ apiBaseUrl: "https://sim.example/api",
+ fileBaseUrl: "https://files.sim.example/",
+ });
+ await confined?.("https://files.sim.example/F123/report.csv");
+ expect(seen).toEqual(["supplied https://files.sim.example/F123/report.csv"]);
+ });
+
+ it("leaves Slack's own host alone when only a file base is configured", async () => {
+ const { seen, fetch: confined } = transports({ fileBaseUrl: "https://sim.example/files" });
+ await confined?.("https://sim.example/files/F01/cat.png");
+ // apiBaseUrl was never configured, so slack.com is not a host the wrapper
+ // was given a credential for.
+ await confined?.("https://slack.com/api/chat.postMessage");
+ expect(seen).toEqual([
+ "supplied https://sim.example/files/F01/cat.png",
+ "global https://slack.com/api/chat.postMessage",
+ ]);
+ });
+
+ it("carries every Slack host when no base is configured", async () => {
+ const { seen, fetch: confined } = transports({});
+ await confined?.("https://slack.com/api/chat.postMessage");
+ await confined?.("https://files.slack.com/a/b/report.csv");
+ expect(seen).toEqual([
+ "supplied https://slack.com/api/chat.postMessage",
+ "supplied https://files.slack.com/a/b/report.csv",
+ ]);
+ });
+
+ it("stays undefined when no fetch is supplied", () => {
+ expect(
+ resolveSlackTransportOptions({ apiBaseUrl: "https://sim.example/api" })?.fetch,
+ ).toBeUndefined();
+ });
+});
+
+describe("resolving an already-resolved value", () => {
+ it("returns it unchanged rather than re-wrapping", () => {
+ const once = resolveSlackTransportOptions({ apiBaseUrl: "https://sim.example/api" });
+ expect(resolveSlackTransportOptions(once)).toBe(once);
+ });
+
+ it("leaves the confinement single-layered", async () => {
+ const seen: string[] = [];
+ const supplied = async (input: Parameters<typeof fetch>[0]) => {
+ seen.push(String(input));
+ return new Response("");
+ };
+ const once = resolveSlackTransportOptions({
+ apiBaseUrl: "https://sim.example/api",
+ fetch: supplied as never,
+ });
+ const twice = resolveSlackTransportOptions(once);
+ expect(twice?.fetch).toBe(once?.fetch);
+ await twice?.fetch?.("https://sim.example/api/chat.postMessage");
+ expect(seen).toEqual(["https://sim.example/api/chat.postMessage"]);
+ });
+});
diff --git a/packages/eve/src/public/channels/slack/transport.ts b/packages/eve/src/public/channels/slack/transport.ts
new file mode 100644
index 000000000..80bf458ca
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/transport.ts
@@ -0,0 +1,187 @@
+/**
+ * The seam between eve and the vendored Slack transport: the host and fetch
+ * every outbound call travels on, and the record of whether a thrown error
+ * means Slack answered.
+ */
+
+import {
+ callSlackApi as callSlackApiPrimitive,
+ type SlackApiOptions,
+ type SlackApiResponse,
+} from "#compiled/@chat-adapter/slack/api.js";
+
+/** Fetch implementation used for Slack traffic. */
+export type SlackFetch = typeof globalThis.fetch;
+
+/**
+ * Slack API transport overrides. The base URLs say where a call may go:
+ * `apiBaseUrl` defaults to `https://slack.com/api/`, and `fileBaseUrl` falls back to
+ * `apiBaseUrl` for attachment downloads. Both are absolute http or https URLs
+ * carrying no query string or fragment.
+ *
+ * `fetch` says how the traffic travels: it replaces the global fetch, which attaches
+ * the per-call header a host behind an authenticating proxy requires, and observes or
+ * stubs the calls. It is confined to the configured bases' origins, so a wrapper may
+ * attach a credential without checking each destination itself. With no base
+ * configured every call goes to Slack's own hosts and it sees all of them.
+ */
+export interface SlackTransportOptions {
+ readonly apiBaseUrl?: string;
+ readonly fetch?: SlackFetch;
+ readonly fileBaseUrl?: string;
+}
+
+/** Options this module has already checked, confined and resolved. */
+const resolvedTransports = new WeakSet<object>();
+
+/**
+ * Checks the configured bases and resolves each to the directory href that method
+ * names and file paths resolve against, throwing on one eve cannot reach.
+ * `fileBaseUrl` absorbs its fallback here, `fetch` is confined here, and every
+ * outbound call then reads a resolved string.
+ *
+ * Resolving an already-resolved value returns it unchanged, so `slackChannel()`
+ * can resolve once at construction — where a bad base belongs — while an entry
+ * point reached without a channel resolves for itself.
+ */
+export function resolveSlackTransportOptions(
+ api: SlackTransportOptions | undefined,
+): SlackTransportOptions | undefined {
+ if (api === undefined) return undefined;
+ if (resolvedTransports.has(api)) return api;
+ const apiBaseUrl = slackBaseHref(api.apiBaseUrl, "api.apiBaseUrl");
+ const fileBaseUrl =
+ api.fileBaseUrl === undefined ? apiBaseUrl : slackBaseHref(api.fileBaseUrl, "api.fileBaseUrl");
+ const resolved = {
+ apiBaseUrl,
+ fetch: confineFetch(api.fetch, apiBaseUrl, fileBaseUrl),
+ fileBaseUrl,
+ };
+ resolvedTransports.add(resolved);
+ return resolved;
+}
+
+/**
+ * Confines a caller-supplied `fetch` to the origins of the configured bases. Traffic
+ * to any other host travels on the global fetch.
+ *
+ * Two credentialed calls are addressed by data rather than by config: the `upload_url`
+ * that `files.getUploadURLExternal` answers with, and the `url_private` a download
+ * arrives on. Both let the host on the far end name where eve sends the next request,
+ * so a `fetch` that attaches credentials for a stand-in carries them wherever that
+ * stand-in points. eve knows which hosts were configured, so the confinement belongs
+ * here and a wrapper attaches its credential unconditionally.
+ *
+ * With no base configured every call already goes to Slack's own hosts, and the
+ * supplied fetch sees all of them.
+ */
+function confineFetch(
+ custom: SlackFetch | undefined,
+ apiBaseUrl: string | undefined,
+ fileBaseUrl: string | undefined,
+): SlackFetch | undefined {
+ if (custom === undefined) return undefined;
+ const bases = [apiBaseUrl, fileBaseUrl].filter((base) => base !== undefined);
+ if (bases.length === 0) return custom;
+ const origins = new Set(bases.map((base) => new URL(base).origin));
+ return (target, init) => {
+ const origin = URL.parse(target instanceof Request ? target.url : String(target))?.origin;
+ return origin !== undefined && origins.has(origin)
+ ? custom(target, init)
+ : globalThis.fetch(target, init);
+ };
+}
+
+/**
+ * The options an outbound Slack Web API call is made with. Resolves `api`, so a
+ * caller cannot reach the transport with a base that was never checked or a fetch
+ * that was never confined.
+ */
+export function slackApiOptions(
+ api: SlackTransportOptions | undefined,
+ token: SlackApiOptions["token"],
+): SlackApiOptions {
+ const resolved = resolveSlackTransportOptions(api);
+ return { apiUrl: resolved?.apiBaseUrl, fetch: resolved?.fetch, token };
+}
+
+/**
+ * True when a configured file base serves `url`, which makes it downloadable with
+ * the bot token. The match is a path prefix, so an `apiBaseUrl` of
+ * `https://slack.com/api/` authorizes downloads under that path alone.
+ */
+export function isConfiguredSlackFileUrl(
+ api: SlackTransportOptions | undefined,
+ url: string,
+): boolean {
+ const base = api?.fileBaseUrl;
+ if (base === undefined) return false;
+ return URL.parse(url)?.href.startsWith(base) === true;
+}
+
+/** Method names and file paths resolve relative to the base, so it names a directory. */
+function slackBaseHref(base: string | undefined, option: string): string | undefined {
+ if (base === undefined) return undefined;
+ const parsed = URL.parse(base);
+ if (parsed === null || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) {
+ throw new TypeError(`${option} must be an absolute http or https URL. Received: ${base}`);
+ }
+ if (parsed.search !== "" || parsed.hash !== "") {
+ throw new TypeError(`${option} must carry no query string or fragment. Received: ${base}`);
+ }
+ return parsed.href.endsWith("/") ? parsed.href : `${parsed.href}/`;
+}
+
+/** Errors raised after Slack's response arrived. */
+const slackResponseErrors = new WeakSet<object>();
+
+/**
+ * POSTs to a Slack Web API method and records the response arriving.
+ *
+ * Slack retries an interaction whose acknowledgement is not a 2xx, so a
+ * handler answering a click has to swallow a call Slack answered badly
+ * and rethrow a call that never arrived. Those two are indistinguishable
+ * once thrown: the transport consumes the response body before it reads
+ * the status, so a body cut off partway raises the same `TypeError` as a
+ * connection that was never made. Nothing on the error says which it
+ * was, so the answer is recorded here while the call runs. `callSlackApi`
+ * posts through here, which covers `ctx.slack.request` and the
+ * `views.open` that opens the freeform modal; the message, upload and
+ * thread-fetch helpers in `api.ts` post through the vendored transport.
+ *
+ * The transport is handed a `fetch` that observes the response, so
+ * everything thrown from that moment on — a non-2xx, a body that is not
+ * the JSON envelope, a body cut off mid-read — is marked for
+ * {@link isSlackResponseError}. A failure before then stays unmarked and
+ * reaches the caller, which is what fails the interaction request.
+ */
+export async function callSlackApiTrackingResponse(
+ operation: string,
+ body: Record<string, unknown>,
+ options: SlackApiOptions,
+): Promise<SlackApiResponse> {
+ let responded = false;
+ const observe: typeof globalThis.fetch = async (input, init) => {
+ const response = await (options.fetch ?? globalThis.fetch)(input, init);
+ responded = true;
+ return response;
+ };
+ try {
+ return await callSlackApiPrimitive(operation, body, { ...options, fetch: observe });
+ } catch (error) {
+ if (responded && typeof error === "object" && error !== null) {
+ slackResponseErrors.add(error);
+ }
+ throw error;
+ }
+}
+
+/**
+ * True when Slack answered the call, false when the call never got a
+ * response. A caller that must acknowledge Slack swallows the first and
+ * rethrows the second; see {@link callSlackApiTrackingResponse} for why
+ * the error itself cannot be asked.
+ */
+export function isSlackResponseError(error: unknown): boolean {
+ return typeof error === "object" && error !== null && slackResponseErrors.has(error);
+}