Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(slack): use chat sdk webhook primitives (#405)

josh70ebe69fd022
diff --git a/.changeset/happy-actors-search.md b/.changeset/happy-actors-search.md
new file mode 100644
index 000000000..ed425bd7a
--- /dev/null
+++ b/.changeset/happy-actors-search.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+use Chat SDK Slack webhook primitives for Slack channel parsing and verification
diff --git a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
index ec9b75606..019400acd 100644
--- a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
+++ b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
@@ -74,12 +74,19 @@ export default {
input: "@chat-adapter/slack/blocks",
outputPath: "blocks",
},
+ {
+ input: "@chat-adapter/slack/webhook",
+ outputPath: "webhook",
+ },
],
plugins: [createOptionalNativeStubPlugin(["bufferutil", "utf-8-validate"])],
copyDeclarations: createDeclarationCopier({
+ discoverExtraFiles: (distEntries) =>
+ distEntries.filter((entry) => /^types-.*\.d\.ts$/u.test(entry)),
files: [
{ source: "index.d.ts", output: "index.d.ts" },
{ source: "blocks.d.ts", output: "blocks.d.ts" },
+ { source: "webhook.d.ts", output: "webhook.d.ts" },
],
rewrites: {
chat: { kind: "vendored", compiledPath: "chat" },
diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.ts
index 447414aeb..7e3c86888 100644
--- a/packages/eve/src/public/channels/slack/inbound.test.ts
+++ b/packages/eve/src/public/channels/slack/inbound.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
-import { parseAppMentionEvent, parseDirectMessageEvent } from "#public/channels/slack/inbound.js";
+import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";
+import {
+ parseAppMentionEvent,
+ parseDirectMessageEvent,
+ slackMessageFromWebhookPayload,
+} from "#public/channels/slack/inbound.js";
describe("parseAppMentionEvent", () => {
it("returns a SlackMessage with mrkdwn re-rendered as GFM", () => {
@@ -261,4 +266,47 @@ describe("parseDirectMessageEvent", () => {
});
expect(result).toBeNull();
});
+
+ it("builds the Eve message from the shared Slack webhook payload", () => {
+ const payload = parseSlackWebhookBody(
+ JSON.stringify({
+ type: "event_callback",
+ team_id: "T01",
+ event: {
+ type: "message",
+ channel_type: "im",
+ subtype: "file_share",
+ user: "U01",
+ text: "here is a file",
+ channel: "D01",
+ ts: "1700000000.000100",
+ files: [
+ {
+ id: "F01",
+ mimetype: "image/png",
+ url_private: "https://files.slack.com/F01/diagram.png",
+ name: "diagram.png",
+ size: 2048,
+ },
+ ],
+ },
+ }),
+ );
+ expect(payload.kind).toBe("direct_message");
+ if (payload.kind !== "direct_message") throw new Error("expected direct_message");
+
+ const message = slackMessageFromWebhookPayload(payload);
+
+ expect(message?.channelId).toBe("D01");
+ expect(message?.attachments).toEqual([
+ {
+ id: "F01",
+ type: "image",
+ url: "https://files.slack.com/F01/diagram.png",
+ name: "diagram.png",
+ mimeType: "image/png",
+ size: 2048,
+ },
+ ]);
+ });
});
diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.ts
index 65f2d813e..683f3e9df 100644
--- a/packages/eve/src/public/channels/slack/inbound.ts
+++ b/packages/eve/src/public/channels/slack/inbound.ts
@@ -1,18 +1,24 @@
/**
* Inbound Slack event → harness shaping.
*
- * The channel calls these helpers on every inbound `app_mention` event
- * before handing it to the runtime:
+ * The channel calls these helpers on inbound Slack message events before
+ * handing them to the runtime:
*
- * 1. {@link parseAppMentionEvent} parses Slack's webhook envelope into
- * a channel-owned {@link SlackMessage}, with the body's text already
- * re-rendered as GFM markdown so the agent does not see raw
- * `<@U…>` / `<https://…|…>` fragments.
+ * 1. {@link slackMessageFromWebhookPayload} converts the shared Chat SDK
+ * webhook payload into a channel-owned {@link SlackMessage}. The legacy
+ * {@link parseAppMentionEvent} and {@link parseDirectMessageEvent}
+ * helpers keep their raw-envelope behavior for direct unit coverage.
* 2. The channel renders the actor, message, channel, and thread as one
* attributed model message so speaker identity cannot drift away from
* the content it describes.
*/
+import type {
+ SlackAppMentionPayload,
+ SlackDirectMessagePayload,
+ SlackFile,
+} from "#compiled/@chat-adapter/slack/webhook.js";
+
import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";
/**
@@ -44,9 +50,9 @@ export interface SlackAttachment {
/**
* Channel-owned representation of one inbound Slack message.
*
- * Returned by {@link parseAppMentionEvent} for the triggering mention.
- * Replaces the chat SDK `Message` type in the public callback surface
- * (e.g. `onAppMention(ctx, message)`).
+ * Returned for the triggering Slack event. Replaces the chat SDK
+ * `Message` type in the public callback surface (e.g.
+ * `onAppMention(ctx, message)`).
*/
export interface SlackMessage {
/** The original Slack text (mrkdwn). */
@@ -165,6 +171,34 @@ export function parseDirectMessageEvent(envelope: SlackEventCallback): SlackMess
return buildSlackMessage(message, envelope.team_id);
}
+export function slackMessageFromWebhookPayload(
+ payload: SlackAppMentionPayload | SlackDirectMessagePayload,
+): SlackMessage | null {
+ if (payload.kind === "direct_message") {
+ if (
+ typeof payload.subtype === "string" &&
+ payload.subtype.length > 0 &&
+ payload.subtype !== "file_share"
+ ) {
+ return null;
+ }
+ if (typeof payload.botId === "string" && payload.botId.length > 0) return null;
+ }
+
+ if (!payload.channelId || !payload.ts) return null;
+ return {
+ text: payload.text,
+ markdown: slackMrkdwnToGfm(payload.text),
+ ts: payload.ts,
+ threadTs: payload.threadTs,
+ channelId: payload.channelId,
+ teamId: payload.teamId,
+ author: parsePayloadAuthor(payload),
+ attachments: parsePayloadAttachments(payload.files),
+ raw: payload.raw,
+ };
+}
+
function buildSlackMessage(
event: SlackAppMentionEvent | SlackMessageEvent,
envelopeTeamId: string | undefined,
@@ -222,6 +256,17 @@ function toAttachment(file: Record<string, unknown>): SlackAttachment {
};
}
+function toPayloadAttachment(file: SlackFile): SlackAttachment {
+ return {
+ id: file.id,
+ type: file.type,
+ url: file.url,
+ name: file.name,
+ mimeType: file.mimeType,
+ size: file.size,
+ };
+}
+
function inferAttachmentType(mimeType: string | undefined): "image" | "file" | "video" | "audio" {
if (mimeType === undefined) return "file";
if (mimeType.startsWith("image/")) return "image";
@@ -230,6 +275,25 @@ function inferAttachmentType(mimeType: string | undefined): "image" | "file" | "
return "file";
}
+function parsePayloadAuthor(
+ payload: SlackAppMentionPayload | SlackDirectMessagePayload,
+): SlackAuthor | undefined {
+ if (!payload.userId) return undefined;
+ const raw = payload.raw;
+ return {
+ userId: payload.userId,
+ userName: typeof raw.username === "string" ? raw.username : undefined,
+ fullName: undefined,
+ isBot: typeof raw.bot_id === "string" && raw.bot_id.length > 0,
+ isMe: false,
+ };
+}
+
+function parsePayloadAttachments(files: readonly SlackFile[] | undefined): SlackAttachment[] {
+ if (!Array.isArray(files)) return [];
+ return files.map(toPayloadAttachment);
+}
+
/**
* Verified inbound identity used to attribute a model-visible Slack message.
*
diff --git a/packages/eve/src/public/channels/slack/interactions.test.ts b/packages/eve/src/public/channels/slack/interactions.test.ts
index 5e9f0d39e..b992fa89f 100644
--- a/packages/eve/src/public/channels/slack/interactions.test.ts
+++ b/packages/eve/src/public/channels/slack/interactions.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
+import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";
import { parseBlockActionsPayload } from "#public/channels/slack/interactions.js";
function makePayload(overrides: Record<string, unknown>): Record<string, unknown> {
@@ -37,4 +38,54 @@ describe("parseBlockActionsPayload", () => {
});
}
});
+
+ it("accepts the shared Slack webhook block_actions payload", () => {
+ const body = new URLSearchParams({
+ payload: JSON.stringify(
+ makePayload({
+ type: "block_actions",
+ actions: [
+ {
+ action_id: "priority",
+ type: "static_select",
+ selected_option: {
+ value: "high",
+ text: { type: "plain_text", text: "High" },
+ },
+ },
+ ],
+ message: {
+ ts: "1700000000.000200",
+ thread_ts: "1700000000.000100",
+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "Pick one" } }],
+ },
+ }),
+ ),
+ }).toString();
+ const payload = parseSlackWebhookBody(body, {
+ contentType: "application/x-www-form-urlencoded",
+ });
+ expect(payload.kind).toBe("block_actions");
+ if (payload.kind !== "block_actions") throw new Error("expected block_actions");
+
+ const parsed = parseBlockActionsPayload(payload);
+
+ expect(parsed).toMatchObject({
+ channelId: "C0123456789",
+ threadTs: "1700000000.000100",
+ teamId: "T0123456789",
+ });
+ expect(parsed?.messageBlocks).toHaveLength(1);
+ expect(parsed?.actions[0]).toMatchObject({
+ actionId: "priority",
+ label: "High",
+ messageTs: "1700000000.000200",
+ selectedOptionValue: "high",
+ user: {
+ id: "U0123456789",
+ username: "jane.doe",
+ name: "jane.doe",
+ },
+ });
+ });
});
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 6578bc772..346fb8c37 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -17,6 +17,12 @@
* work runs under `waitUntil` so the webhook ACK is immediate.
*/
+import {
+ parseSlackWebhookBody,
+ type SlackBlockActionsPayload,
+ type SlackViewSubmissionPayload,
+} from "#compiled/@chat-adapter/slack/webhook.js";
+
import { createLogger } from "#internal/logging.js";
import {
buildSlackBinding,
@@ -70,15 +76,20 @@ interface ParsedBlockActionsPayload {
* metadata the handler needs.
*/
export function parseBlockActionsPayload(
- body: Record<string, unknown>,
+ body: Record<string, unknown> | SlackBlockActionsPayload,
): ParsedBlockActionsPayload | null {
- const actions = body.actions;
+ if (isSharedBlockActionsPayload(body)) {
+ return parseSharedBlockActionsPayload(body);
+ }
+
+ const rawBody = body as Record<string, unknown>;
+ const actions = rawBody.actions;
if (!Array.isArray(actions)) return null;
// `channel` and `message` are Optional on block_actions payloads — only
// present when the action was triggered from a message in a channel.
- const channel = (body.channel as { id: string } | undefined)?.id;
- const message = body.message as
+ const channel = (rawBody.channel as { id: string } | undefined)?.id;
+ const message = rawBody.message as
| { ts: string; thread_ts?: string; blocks?: unknown[] }
| undefined;
const threadTs = message?.thread_ts ?? message?.ts;
@@ -86,8 +97,8 @@ export function parseBlockActionsPayload(
// `team` is Required but can be `null` for org-installed apps.
// `user` is Required and always carries `id`.
- const team = body.team as { id: string } | null;
- const userBlock = body.user as {
+ const team = rawBody.team as { id: string } | null;
+ const userBlock = rawBody.user as {
id: string;
team_id?: string;
username?: string;
@@ -119,6 +130,38 @@ export function parseBlockActionsPayload(
};
}
+function isSharedBlockActionsPayload(
+ body: Record<string, unknown> | SlackBlockActionsPayload,
+): body is SlackBlockActionsPayload {
+ return body.kind === "block_actions" && Array.isArray(body.actions);
+}
+
+function parseSharedBlockActionsPayload(
+ body: SlackBlockActionsPayload,
+): ParsedBlockActionsPayload | null {
+ if (!body.channelId || !body.threadTs) return null;
+
+ return {
+ actions: body.actions.map((action) => ({
+ actionId: action.actionId,
+ value: action.value,
+ blockId: action.blockId,
+ selectedOptionValue: action.selectedOptionValue,
+ messageTs: body.messageTs,
+ label: action.label,
+ user: {
+ id: action.user?.id ?? body.userId,
+ username: action.user?.username,
+ name: action.user?.name,
+ },
+ })),
+ channelId: body.channelId,
+ threadTs: body.threadTs,
+ teamId: body.teamId,
+ messageBlocks: body.messageBlocks ?? [],
+ };
+}
+
function extractSelectedOptionValue(action: Record<string, unknown>): string | undefined {
const selected = action.selected_option as { value?: unknown } | undefined;
return typeof selected?.value === "string" ? selected.value : undefined;
@@ -179,28 +222,29 @@ export async function handleInteractionPost(
deps: InteractionHandlerDeps,
): Promise<Response> {
const ack = new Response("ok", { status: 200 });
- const params = new URLSearchParams(rawBody);
- const payloadStr = params.get("payload");
- if (!payloadStr) return ack;
- let payload: Record<string, unknown>;
+ let payload;
try {
- payload = JSON.parse(payloadStr) as Record<string, unknown>;
+ payload = parseSlackWebhookBody(rawBody, {
+ contentType: "application/x-www-form-urlencoded",
+ });
} catch {
log.warn("failed to parse Slack interaction payload");
return ack;
}
- if (payload?.type === "view_submission") {
+ if (payload.kind === "view_submission") {
return handleViewSubmission(payload, ctx, deps);
}
+ if (payload.kind !== "block_actions") return ack;
+
const interaction = parseBlockActionsPayload(payload);
if (!interaction) return ack;
const freeformAction = interaction.actions.find((a) => isFreeformAction(a.actionId));
if (freeformAction) {
- await openFreeformModal({ payload, interaction, freeformAction, deps });
+ await openFreeformModal({ payload: payload.raw, interaction, freeformAction, deps });
return ack;
}
@@ -324,7 +368,7 @@ async function openFreeformModal(input: {
}
async function handleViewSubmission(
- payload: Record<string, unknown>,
+ payload: SlackViewSubmissionPayload,
ctx: {
send: SendFn<SlackChannelState>;
waitUntil: (task: Promise<unknown>) => void;
@@ -333,20 +377,11 @@ async function handleViewSubmission(
): Promise<Response> {
// Slack view submissions require an empty 200 body to close the modal.
const ack = new Response(null, { status: 200 });
- const view = payload.view as
- | {
- callback_id?: string;
- private_metadata?: string;
- state?: {
- values?: Record<string, Record<string, { value?: unknown }>>;
- };
- }
- | undefined;
- if (view?.callback_id !== HITL_FREEFORM_MODAL_CALLBACK_ID) return ack;
+ if (payload.callbackId !== HITL_FREEFORM_MODAL_CALLBACK_ID) return ack;
let metadata: HitlFreeformModalMetadata;
try {
- metadata = JSON.parse(view.private_metadata ?? "") as HitlFreeformModalMetadata;
+ metadata = JSON.parse(payload.privateMetadata ?? "") as HitlFreeformModalMetadata;
} catch {
log.warn("freeform view_submission carries invalid private_metadata");
return ack;
@@ -361,17 +396,18 @@ async function handleViewSubmission(
return ack;
}
- const raw =
- view.state?.values?.[HITL_FREEFORM_MODAL_BLOCK_ID]?.[HITL_FREEFORM_MODAL_ACTION_ID]?.value;
- const text = typeof raw === "string" ? raw : "";
+ const text = payload.values?.find(
+ (value) =>
+ value.blockId === HITL_FREEFORM_MODAL_BLOCK_ID &&
+ value.actionId === HITL_FREEFORM_MODAL_ACTION_ID,
+ )?.value ?? "";
if (text.length === 0) return ack;
// `user` is Required on view_submission payloads; `team_id` is on the
// user object in modern payloads but not guaranteed in all examples.
- const team = payload.team as { id?: string } | null | undefined;
- const user = payload.user as { id: string; team_id?: string; username?: string; name?: string };
- const triggeringUserId = user.id;
- const teamId = user.team_id ?? team?.id ?? null;
+ const user = payload.user;
+ const triggeringUserId = payload.userId;
+ const teamId = user?.teamId ?? payload.teamId ?? null;
ctx.waitUntil(
ctx
@@ -382,8 +418,8 @@ async function handleViewSubmission(
channelId: metadata.channelId,
teamId,
threadTs: metadata.threadTs,
- userId: user.id,
- userName: user.username ?? user.name,
+ userId: triggeringUserId,
+ userName: user?.username ?? user?.name,
}),
continuationToken: metadata.continuationToken,
state: {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 93ec408df..ac1b56c18 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -1,3 +1,5 @@
+import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";
+
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { CardElement } from "#compiled/chat/index.js";
@@ -25,11 +27,9 @@ import {
defaultOnDirectMessage,
} from "#public/channels/slack/defaults.js";
import {
- parseAppMentionEvent,
- parseDirectMessageEvent,
- type SlackEventCallback,
type SlackInboundContext,
type SlackMessage,
+ slackMessageFromWebhookPayload,
} from "#public/channels/slack/inbound.js";
import {
formatSlackInboundMessage,
@@ -677,40 +677,48 @@ async function handleEventPost(input: {
readonly credentials: SlackChannelCredentials | undefined;
readonly handledEvents: Set<string>;
}): Promise<Response> {
- let envelope: SlackEventCallback & { challenge?: string };
+ let payload;
try {
- envelope = JSON.parse(input.body) as SlackEventCallback & { challenge?: string };
+ payload = parseSlackWebhookBody(input.body, { headers: input.headers });
} catch (error) {
log.warn("inbound webhook body is not valid JSON", { error });
return new Response("ok");
}
- if (typeof envelope.challenge === "string") {
- return new Response(envelope.challenge, {
+ if (payload.kind === "url_verification") {
+ return new Response(payload.challenge, {
status: 200,
headers: { "content-type": "text/plain" },
});
}
- if (envelope.event_id) {
- if (input.handledEvents.has(envelope.event_id)) {
+ if (payload.kind === "unsupported") return new Response("ok");
+
+ if (payload.kind !== "app_mention" && payload.kind !== "direct_message") {
+ return new Response("ok");
+ }
+
+ if (payload.eventId) {
+ if (input.handledEvents.has(payload.eventId)) {
log.warn("received a duplicate event", {
- event_id: envelope.event_id,
- event_time: envelope.event_time,
- retry_num: input.headers.get("x-slack-retry-num") || "(null)",
- retry_reason: input.headers.get("x-slack-retry-reason") || "(null)",
+ event_id: payload.eventId,
+ event_time: payload.eventTime,
+ retry_num: payload.retry?.num ?? "(null)",
+ retry_reason: payload.retry?.reason ?? "(null)",
});
return new Response("ok");
}
- markEventHandled(envelope.event_id, input.handledEvents);
+ markEventHandled(payload.eventId, input.handledEvents);
}
- const mention = parseAppMentionEvent(envelope);
- if (mention) {
+ const message = slackMessageFromWebhookPayload(payload);
+ if (!message) return new Response("ok");
+
+ if (payload.kind === "app_mention") {
input.waitUntil(
dispatchInboundMessage({
kind: "app_mention",
- message: mention,
+ message,
handler: input.onAppMention,
send: input.send,
uploadPolicy: input.uploadPolicy,
@@ -721,12 +729,11 @@ async function handleEventPost(input: {
return new Response("ok");
}
- const dm = parseDirectMessageEvent(envelope);
- if (dm) {
+ if (payload.kind === "direct_message") {
input.waitUntil(
dispatchInboundMessage({
kind: "direct_message",
- message: dm,
+ message,
handler: input.onDirectMessage,
send: input.send,
uploadPolicy: input.uploadPolicy,
diff --git a/packages/eve/src/public/channels/slack/verify.ts b/packages/eve/src/public/channels/slack/verify.ts
index eda64500b..9c8e64c49 100644
--- a/packages/eve/src/public/channels/slack/verify.ts
+++ b/packages/eve/src/public/channels/slack/verify.ts
@@ -1,112 +1,52 @@
-/**
- * Slack inbound-webhook verification.
- *
- * The native channel replaces `createSlackAdapter`'s built-in HMAC
- * check with a self-contained verifier:
- *
- * 1. If the caller supplied a {@link SlackWebhookVerifier} (e.g.
- * Connect's OIDC-based forwarder), delegate to it.
- * 2. Otherwise, recompute the Slack v0 HMAC and compare with
- * `X-Slack-Signature`. Rejects requests older than five minutes to
- * foil replay attacks.
- *
- * Returns the verified raw body string on success so the caller can
- * parse it without re-reading the request stream.
- */
+import {
+ verifySlackRequest as verifySlackWebhookRequest,
+ type SlackWebhookVerifier,
+} from "#compiled/@chat-adapter/slack/webhook.js";
-import { createHmac, timingSafeEqual } from "node:crypto";
-
-import { createLogger } from "#internal/logging.js";
-
-const log = createLogger("slack.verify");
-
-/**
- * Caller-supplied inbound webhook verifier. Used as an alternative to
- * HMAC verification — e.g. Connect supplies a verifier that
- * authenticates Connect-forwarded webhooks with Vercel OIDC instead
- * of Slack's signing secret.
- *
- * Contract (matches the chat SDK's `SlackAdapterConfig.webhookVerifier`):
- *
- * - **Throw / reject** → the channel responds 401 to Slack.
- * - **Return a falsy value** (`null` / `undefined` / `false` / `""` /
- * `0`) → the channel responds 401 to Slack. This lets verifiers
- * signal rejection without throwing — e.g. Connect's `vercelOidc()`
- * returns `null` on a failed OIDC check.
- * - **Return a truthy non-string value** → verification accepted.
- * - **Return a string** → verification accepted, and the string
- * replaces the raw body for downstream parsing. Useful when the
- * verifier canonicalizes or substitutes the verified payload.
- */
-export type SlackWebhookVerifier = (request: Request, body: string) => unknown | Promise<unknown>;
+export type { SlackWebhookVerifier };
+/** Verification inputs for Eve's Slack webhook route. */
export interface SlackVerifyOptions {
readonly signingSecret: string | undefined;
readonly webhookVerifier: SlackWebhookVerifier | undefined;
- /** Max allowed clock skew, in seconds. Defaults to 5 minutes. */
readonly maxSkewSeconds?: number;
}
-/**
- * Verifies an inbound Slack webhook and returns its raw body.
- *
- * Throws when neither a signing secret nor a custom verifier is
- * available, when signature/timestamp checks fail, or when the
- * caller-supplied verifier rejects.
- */
+/** Verifies a Slack request with the Chat SDK webhook primitive. */
export async function verifySlackRequest(
request: Request,
options: SlackVerifyOptions,
): Promise<string> {
- const body = await request.text();
-
- if (options.webhookVerifier !== undefined) {
- const result = await options.webhookVerifier(request, body);
- if (!result) {
- throw new Error("slackChannel: inbound webhook verifier rejected the request.");
- }
- return typeof result === "string" ? result : body;
- }
-
- if (!options.signingSecret) {
+ if (options.webhookVerifier === undefined && !options.signingSecret) {
throw new Error(
"slackChannel: missing signing secret. Pass credentials.signingSecret, " +
"set SLACK_SIGNING_SECRET, or supply credentials.webhookVerifier.",
);
}
- const timestampHeader = request.headers.get("x-slack-request-timestamp") ?? "";
- const signatureHeader = request.headers.get("x-slack-signature") ?? "";
- if (!timestampHeader || !signatureHeader) {
- throw new Error("slackChannel: inbound request missing Slack signature headers.");
+ try {
+ return await verifySlackWebhookRequest(request, options);
+ } catch (error) {
+ throw normalizeSlackWebhookError(error);
}
+}
- const timestamp = Number(timestampHeader);
- if (!Number.isFinite(timestamp)) {
- throw new Error("slackChannel: inbound request has malformed timestamp.");
+function normalizeSlackWebhookError(error: unknown): Error {
+ const message = error instanceof Error ? error.message : String(error);
+ if (message.includes("verifier rejected")) {
+ return new Error("slackChannel: inbound webhook verifier rejected the request.");
}
-
- const maxSkew = options.maxSkewSeconds ?? 60 * 5;
- const now = Math.floor(Date.now() / 1000);
- if (Math.abs(now - timestamp) > maxSkew) {
- throw new Error("slackChannel: inbound request timestamp outside allowed skew.");
+ if (message.includes("signature headers")) {
+ return new Error("slackChannel: inbound request missing Slack signature headers.");
}
-
- const base = `v0:${timestampHeader}:${body}`;
- const expected = `v0=${createHmac("sha256", options.signingSecret).update(base).digest("hex")}`;
- if (!constantTimeCompare(expected, signatureHeader)) {
- throw new Error("slackChannel: inbound request signature mismatch.");
+ if (message.includes("timestamp is invalid")) {
+ return new Error("slackChannel: inbound request has malformed timestamp.");
}
-
- return body;
-}
-
-function constantTimeCompare(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- try {
- return timingSafeEqual(Buffer.from(a), Buffer.from(b));
- } catch (error) {
- log.debug("timingSafeEqual threw", { error });
- return false;
+ if (message.includes("timestamp is too old")) {
+ return new Error("slackChannel: inbound request timestamp outside allowed skew.");
+ }
+ if (message.includes("signature is invalid")) {
+ return new Error("slackChannel: inbound request signature mismatch.");
}
+ return error instanceof Error ? error : new Error(message);
}