Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/hot-steaks-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chat-adapter/slack": minor
---

add lightweight Slack webhook primitives subpath
4 changes: 4 additions & 0 deletions packages/adapter-slack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./webhook": {
"types": "./dist/webhook.d.ts",
"import": "./dist/webhook.js"
}
},
"files": [
Expand Down
10 changes: 8 additions & 2 deletions packages/adapter-slack/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,11 @@ describe("handleWebhook - interactive payloads", () => {
try {
const state = createMockState();
const chatInstance = createMockChatInstance(state);
const timeoutAdapter = createSlackAdapter({
botToken: "xoxb-test-token",
logger: mockLogger,
webhookVerifier: () => true,
});
(
chatInstance.processOptionsLoad as ReturnType<typeof vi.fn>
).mockImplementation(
Expand All @@ -961,7 +966,7 @@ describe("handleWebhook - interactive payloads", () => {
);
})
);
await adapter.initialize(chatInstance);
await timeoutAdapter.initialize(chatInstance);

const payload = JSON.stringify({
type: "block_suggestion",
Expand All @@ -976,7 +981,8 @@ describe("handleWebhook - interactive payloads", () => {
contentType: "application/x-www-form-urlencoded",
});

const responsePromise = adapter.handleWebhook(request);
const responsePromise = timeoutAdapter.handleWebhook(request);
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(2500);
const response = await responsePromise;

Expand Down
74 changes: 12 additions & 62 deletions packages/adapter-slack/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { createHmac, timingSafeEqual } from "node:crypto";
import { timingSafeEqual } from "node:crypto";
import {
AdapterRateLimitError,
AuthenticationError,
Expand Down Expand Up @@ -73,6 +73,7 @@ import {
type SlackModalResponse,
selectOptionToSlackOption,
} from "./modals";
import { verifySlackRequest } from "./webhook/index";

const SLACK_USER_ID_PATTERN = /^[A-Z0-9_]+$/;
const SLACK_USER_ID_EXACT_PATTERN = /^U[A-Z0-9]+$/;
Expand Down Expand Up @@ -1133,34 +1134,17 @@ export class SlackAdapter implements Adapter<SlackThreadId, unknown> {
});
}

let body = await request.text();
this.logger.debug("Slack webhook raw body", { body });

// Verify request using dynamic verifier or signature.
if (this.webhookVerifier) {
try {
const verified = await this.webhookVerifier(request, body);
if (!verified) {
this.logger.warn("Webhook verifier rejected request");
return new Response("Invalid signature", { status: 401 });
}
// If the verifier returns a string, use it as the verified body for
// downstream parsing. Other truthy values (boolean, object) are
// treated as a pure verification signal.
if (typeof verified === "string") {
body = verified;
}
} catch (error) {
this.logger.warn("Webhook verifier rejected request", { error });
return new Response("Invalid signature", { status: 401 });
}
} else {
const timestamp = request.headers.get("x-slack-request-timestamp");
const signature = request.headers.get("x-slack-signature");
if (!this.verifySignature(body, timestamp, signature)) {
return new Response("Invalid signature", { status: 401 });
}
let body: string;
try {
body = await verifySlackRequest(request, {
signingSecret: this.signingSecret,
webhookVerifier: this.webhookVerifier,
});
} catch (error) {
this.logger.warn("Webhook verifier rejected request", { error });
return new Response("Invalid signature", { status: 401 });
}
this.logger.debug("Slack webhook raw body", { body });

// Check if this is a form-urlencoded payload
const contentType = request.headers.get("content-type") || "";
Expand Down Expand Up @@ -2060,40 +2044,6 @@ export class SlackAdapter implements Adapter<SlackThreadId, unknown> {
}
}

protected verifySignature(
body: string,
timestamp: string | null,
signature: string | null
): boolean {
if (!(timestamp && signature && this.signingSecret)) {
return false;
}

// Check timestamp is recent (within 5 minutes)
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - Number.parseInt(timestamp, 10)) > 300) {
return false;
}

// Compute expected signature
const sigBasestring = `v0:${timestamp}:${body}`;
const expectedSignature =
"v0=" +
createHmac("sha256", this.signingSecret)
.update(sigBasestring)
.digest("hex");

// Compare signatures using timing-safe comparison
try {
return timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
} catch {
return false;
}
}

/**
* Handle message events from Slack.
* Bot message filtering (isMe) is handled centrally by the Chat class.
Expand Down
6 changes: 2 additions & 4 deletions packages/adapter-slack/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import type { Logger } from "chat";
import type { SlackWebhookVerifier } from "./webhook/index";

export type SlackAdapterMode = "webhook" | "socket";

Expand Down Expand Up @@ -90,8 +91,5 @@ export interface SlackAdapterConfig {
* equivalent freshness signal) to prevent replay of captured signed
* requests.
*/
webhookVerifier?: (
request: Request,
body: string
) => unknown | Promise<unknown>;
webhookVerifier?: SlackWebhookVerifier;
}
25 changes: 25 additions & 0 deletions packages/adapter-slack/src/webhook/boundary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";

describe("webhook import boundary", () => {
it("does not import the full adapter or runtime packages", async () => {
const files = ["index.ts", "parse.ts", "types.ts", "utils.ts", "verify.ts"];
const source = (
await Promise.all(
files.map((file) =>
readFile(new URL(`./${file}`, import.meta.url), {
encoding: "utf8",
})
)
)
).join("\n");

expect(source).not.toContain('from "chat"');
expect(source).not.toContain("from '@chat-adapter/shared'");
expect(source).not.toContain('from "@chat-adapter/shared"');
expect(source).not.toContain('from "@slack/web-api"');
expect(source).not.toContain('from "@slack/socket-mode"');
expect(source).not.toContain('from "../index"');
expect(source).not.toContain("node:crypto");
});
});
Loading