@maroonedsoftware/slack 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,19 +15,19 @@ pnpm add @maroonedsoftware/slack
15
15
 
16
16
  ## Exports
17
17
 
18
- | Symbol | Purpose |
19
- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
- | `SlackConfig` | Abstract `@Injectable()` token; carries `botToken`, optional `signingSecret`, `appToken`, `incomingWebhookUrl`, `signatureMaxAgeSeconds`, `requestTimeoutMs`, `apiBaseUrl`, `fetch`. Consumer registers a concrete value. |
21
- | `SlackClient` | Wraps `@slack/web-api`'s `WebClient`; routes its diagnostics through ServerKit's `Logger`. Methods: `postMessage`, `updateMessage`, `deleteMessage`, `openView`, `postWebhook`, `openSocketModeUrl`. Underlying SDK reachable at `.web`. |
22
- | `SlackDispatcher` | Three-method service: `dispatchEvent`, `dispatchCommand`, `dispatchInteraction`. |
23
- | `SlackEventHandlerMap` | `Map<eventType, SlackEventHandler>` — register one handler per Slack event type (`app_mention`, `message`, …). |
24
- | `SlackCommandHandlerMap` | `Map<commandKeyword, SlackCommandHandler>` — register one handler per slash command (`/deploy`, …). |
25
- | `SlackInteractionHandlerMap` | `Map<routingKey, SlackInteractionHandler>` — keys are `${type}:${identifier}`; see [interaction routing](#interaction-routing). |
26
- | `SlackError` | `ServerkitError` subclass for non-HTTP domain failures (signature mismatch, webhook POST failed, …). |
27
- | `verifySlackSignature(input)` | Pure helper that validates Slack's v0 HMAC scheme + replay window. No request/context coupling. |
28
- | `SlackSignaturePolicy` | `@maroonedsoftware/policies` form of `verifySlackSignature` (registered under `SLACK_SIGNATURE_POLICY`). Delegates to the helper but answers as a `PolicyResult`, so it slots into ServerKit's policy pipeline. |
29
- | `interactionRouteKey(payload)` | Helper that produces the `SlackInteractionHandlerMap` key for a given payload. |
30
- | `slackEventIdempotencyKey(envelope)` | Pure helper that derives a stable de-dup key (`slack:event:{team_id}:{event_id}`) for an `event_callback` envelope. |
18
+ | Symbol | Purpose |
19
+ | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
+ | `SlackConfig` | Abstract `@Injectable()` token; carries `botToken`, optional `signingSecret`, `appToken`, `incomingWebhookUrl`, `signatureMaxAgeSeconds`, `requestTimeoutMs`, `apiBaseUrl`, `fetch`, `retries`, `rejectRateLimitedCalls`. Consumer registers a concrete value. |
21
+ | `SlackClient` | Wraps `@slack/web-api`'s `WebClient`; routes its diagnostics through ServerKit's `Logger`. Methods: `postMessage`, `updateMessage`, `deleteMessage`, `openView`, `postWebhook`, `openSocketModeUrl`. Underlying SDK reachable at `.web`. |
22
+ | `SlackDispatcher` | Three-method service: `dispatchEvent`, `dispatchCommand`, `dispatchInteraction`. |
23
+ | `SlackEventHandlerMap` | `Map<eventType, SlackEventHandler>` — register one handler per Slack event type (`app_mention`, `message`, …). |
24
+ | `SlackCommandHandlerMap` | `Map<commandKeyword, SlackCommandHandler>` — register one handler per slash command (`/deploy`, …). |
25
+ | `SlackInteractionHandlerMap` | `Map<routingKey, SlackInteractionHandler>` — keys are `${type}:${identifier}`; see [interaction routing](#interaction-routing). |
26
+ | `SlackError` | `ServerkitError` subclass for non-HTTP domain failures (signature mismatch, webhook POST failed, …). |
27
+ | `verifySlackSignature(input)` | Pure helper that validates Slack's v0 HMAC scheme + replay window. No request/context coupling. |
28
+ | `SlackSignaturePolicy` | `@maroonedsoftware/policies` form of `verifySlackSignature` (registered under `SLACK_SIGNATURE_POLICY`). Delegates to the helper but answers as a `PolicyResult`, so it slots into ServerKit's policy pipeline. |
29
+ | `interactionRouteKey(payload)` | Helper that produces the `SlackInteractionHandlerMap` key for a given payload. |
30
+ | `slackEventIdempotencyKey(envelope)` | Pure helper that derives a stable de-dup key (`slack:event:{team_id}:{event_id}`) for an `event_callback` envelope. |
31
31
 
32
32
  ## Configuration
33
33
 
@@ -65,6 +65,8 @@ registry.register(SlackConfig).useValue(slackConfig);
65
65
  | `apiBaseUrl` | no | Forwarded to `WebClient` as `slackApiUrl`. |
66
66
  | `requestTimeoutMs` | no | Timeout for `postWebhook` (default 10s). |
67
67
  | `fetch` | no | The transport for every outbound call. See [bringing your own fetch](#bringing-your-own-fetch). |
68
+ | `retries` | no | Forwarded to `WebClient` as `retryConfig: { retries }`. Defaults to the SDK's ten retries over about thirty minutes; see below. |
69
+ | `rejectRateLimitedCalls` | no | Forwarded to `WebClient`: reject a rate-limited call instead of pausing every call until `Retry-After` has passed. |
68
70
  | `incomingWebhookUrl` | no | `SlackClient.postWebhook` default URL when no per-call URL is supplied. |
69
71
  | `signatureMaxAgeSeconds` | no | Replay-protection window for your signature verifier (default `300`). |
70
72
 
@@ -95,6 +97,14 @@ await slack.web.users.info({ user: 'U123' });
95
97
  registry.register(SlackConfig).useValue({ ...appConfig.getAs<SlackConfig>('slack'), fetch: host.fetch });
96
98
  ```
97
99
 
100
+ ### Owning retries
101
+
102
+ `WebClient` retries a failed call (a transport error, a non-200, a rate limit it waited out) ten times over about thirty minutes by default, in the background. When something else already owns retrying (a job queue, or a host that abandons a call at its own deadline), those retries carry on after the caller has given up and can deliver a message long after it stopped being true. Set `retries: 0`, and `rejectRateLimitedCalls: true` if a rate limit should fail the call rather than pause it:
103
+
104
+ ```ts
105
+ registry.register(SlackConfig).useValue({ ...slackConfig, fetch: host.fetch, retries: 0, rejectRateLimitedCalls: true });
106
+ ```
107
+
98
108
  ### The app token
99
109
 
100
110
  Socket Mode authenticates with an app-level token (`xapp-...`, scope `connections:write`), not the bot token. `openSocketModeUrl()` trades it for a single-use WebSocket URL via `apps.connections.open`, over the same `fetch` and base URL. Call it again for every reconnect. It throws `SlackError` when `appToken` is not set, or when Slack does not hand back a URL.
@@ -1 +1 @@
1
- {"version":3,"file":"slack.client.d.ts","sourceRoot":"","sources":["../../src/client/slack.client.ts"],"names":[],"mappings":"AACA,OAAO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386
  slackApiUrl: this.config.apiBaseUrl
387
+ } : {},
388
+ ...this.config.retries !== void 0 ? {
389
+ retryConfig: {
390
+ retries: this.config.retries
391
+ }
392
+ } : {},
393
+ ...this.config.rejectRateLimitedCalls !== void 0 ? {
394
+ rejectRateLimitedCalls: this.config.rejectRateLimitedCalls
387
395
  } : {}
388
396
  };
389
397
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/slack.config.ts","../src/slack.signature.ts","../src/slack.signature.policy.ts","../src/slack.event.handler.ts","../src/slack.interaction.handler.ts","../src/slack.dispatcher.ts","../src/client/slack.client.ts","../src/client/slack.logger.adapter.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport { Injectable } from 'injectkit';\nimport type { FetchFunction } from '@slack/web-api';\n\n/**\n * Configuration for the Slack package. Declared as an abstract `@Injectable()`\n * class so it doubles as a DI token (mirrors the `Logger` pattern in\n * `@maroonedsoftware/logger`).\n *\n * Consumers register a concrete value at bootstrap, typically resolved from\n * `AppConfig`:\n *\n * ```ts\n * const slackConfig = appConfig.getAs<SlackConfig>('slack');\n * registry.register(SlackConfig).useValue(slackConfig);\n * ```\n *\n * Services in this package take `SlackConfig` directly in their constructor.\n */\nexport interface SlackConfig {\n /** Bot user OAuth token (`xoxb-...`). Required for Web API calls. */\n botToken: string;\n /**\n * App-level signing secret used to verify request signatures. Needed only when Slack calls you\n * over HTTP; a Socket Mode app can leave it unset, and signature verification then fails closed\n * with `missing_signing_secret`.\n */\n signingSecret?: string;\n /**\n * App-level token (`xapp-...`) with the `connections:write` scope. Needed only for Socket Mode,\n * where {@link import('./client/slack.client.js').SlackClient.openSocketModeUrl} trades it for a\n * WebSocket URL.\n */\n appToken?: string;\n /** Optional incoming webhook URL used as the default target for `SlackClient.postWebhook`. */\n incomingWebhookUrl?: string;\n /**\n * Maximum age (in seconds) for request timestamps before signature\n * verification rejects them as replays. Defaults to `300` (5 minutes).\n */\n signatureMaxAgeSeconds?: number;\n /**\n * Per-request timeout (in milliseconds) for outbound `SlackClient.postWebhook`\n * calls. Defaults to\n * {@link import('./client/slack.client.js').SLACK_DEFAULT_REQUEST_TIMEOUT_MS} (10s).\n */\n requestTimeoutMs?: number;\n /**\n * Base URL for Web API calls, forwarded to `@slack/web-api` as `slackApiUrl`. Defaults to the\n * SDK's own (`https://slack.com/api/`).\n */\n apiBaseUrl?: string;\n /**\n * The `fetch` every outbound call goes through: the Web API client, `postWebhook`, and\n * `openSocketModeUrl`. Defaults to the global `fetch`.\n *\n * Set it when the caller owns the transport: a host that routes outbound HTTP through its own\n * allowlist, rate limits or proxy, or a test. The client passes an `AbortSignal` carrying its\n * timeout; an implementation that enforces its own deadline as well may ignore it.\n */\n fetch?: SlackFetch;\n}\n\n/**\n * The `fetch` shape the client needs. It is `@slack/web-api`'s own `FetchFunction`, so one\n * function serves both the Web API client and the webhook POSTs; the global `fetch` satisfies it.\n */\nexport type SlackFetch = FetchFunction;\n\n@Injectable()\nexport abstract class SlackConfig implements SlackConfig {}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { DateTime } from 'luxon';\nimport { SlackError } from './slack.error.js';\n\n/** Default replay-protection window in seconds (5 minutes — matches Slack's recommendation). */\nexport const SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS = 300;\n\n/**\n * Reason codes attached to {@link SlackError.internalDetails} when verification\n * fails. Useful for callers that want to log structured reasons without\n * pattern-matching on error messages.\n */\nexport type SlackSignatureFailureReason =\n 'missing_signing_secret' | 'missing_timestamp' | 'invalid_timestamp' | 'stale_timestamp' | 'missing_signature' | 'invalid_signature';\n\n/**\n * Inputs to {@link verifySlackSignature}. All values are taken verbatim from\n * the request — the helper does no header lookups or body reads of its own.\n */\nexport type VerifySlackSignatureInput = {\n /**\n * App signing secret (`SlackConfig.signingSecret`). Optional in the config because a Socket\n * Mode app never verifies a request; verification without one fails with\n * `missing_signing_secret` rather than checking against an empty key.\n */\n signingSecret: string | undefined;\n /** Raw, unparsed request body — exactly as Slack sent it. */\n rawBody: string;\n /** Value of the `X-Slack-Request-Timestamp` header. */\n timestamp: string | undefined;\n /** Value of the `X-Slack-Signature` header (e.g. `\"v0=abc123…\"`). */\n signature: string | undefined;\n /**\n * Maximum age in seconds before the request is rejected as a replay.\n * Defaults to {@link SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS}.\n */\n maxAgeSeconds?: number;\n /**\n * Override for the current Unix time in seconds. Mostly useful for tests;\n * defaults to `Math.floor(DateTime.now().toSeconds())`.\n */\n now?: number;\n};\n\n/**\n * Verifies a Slack request signature against the app signing secret.\n *\n * Implements Slack's v0 scheme:\n * 1. Reject the request if `X-Slack-Request-Timestamp` is missing, non-numeric,\n * or older than `maxAgeSeconds` (replay protection).\n * 2. Compute `v0=` + `HMAC-SHA256(signingSecret, \"v0:{timestamp}:{rawBody}\")`\n * as hex.\n * 3. Compare against the provided `X-Slack-Signature` value using a\n * constant-time compare.\n *\n * Pure: no request/context coupling. The caller extracts the headers and raw\n * body from whatever transport it's using and passes them in.\n *\n * @throws {@link SlackError} on any failure. The error's `internalDetails.reason`\n * is one of {@link SlackSignatureFailureReason}; map to HTTP 401 at the route boundary.\n *\n * @example\n * ```ts\n * try {\n * verifySlackSignature({\n * signingSecret: config.signingSecret,\n * rawBody,\n * timestamp: req.headers['x-slack-request-timestamp'],\n * signature: req.headers['x-slack-signature'],\n * });\n * } catch (err) {\n * throw httpError(401).withCause(err);\n * }\n * ```\n */\nexport const verifySlackSignature = (input: VerifySlackSignatureInput): void => {\n const {\n signingSecret,\n rawBody,\n timestamp,\n signature,\n maxAgeSeconds = SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS,\n now = Math.floor(DateTime.now().toSeconds()),\n } = input;\n\n if (!signingSecret) {\n throw new SlackError('Slack signature verification needs SlackConfig.signingSecret, which is not set').withInternalDetails({\n reason: 'missing_signing_secret' satisfies SlackSignatureFailureReason,\n });\n }\n\n if (!timestamp) {\n throw new SlackError('Slack request missing X-Slack-Request-Timestamp header').withInternalDetails({\n reason: 'missing_timestamp' satisfies SlackSignatureFailureReason,\n });\n }\n\n const ts = Number(timestamp);\n if (!Number.isFinite(ts) || !Number.isInteger(ts)) {\n throw new SlackError('Slack request timestamp is not a valid integer').withInternalDetails({\n reason: 'invalid_timestamp' satisfies SlackSignatureFailureReason,\n timestamp,\n });\n }\n\n if (Math.abs(now - ts) > maxAgeSeconds) {\n throw new SlackError('Slack request timestamp is outside the allowed window').withInternalDetails({\n reason: 'stale_timestamp' satisfies SlackSignatureFailureReason,\n timestamp: ts,\n now,\n maxAgeSeconds,\n });\n }\n\n if (!signature) {\n throw new SlackError('Slack request missing X-Slack-Signature header').withInternalDetails({\n reason: 'missing_signature' satisfies SlackSignatureFailureReason,\n });\n }\n\n // Sign with the raw header value verbatim (not the parsed `ts`): Slack computes\n // its signature over the exact `X-Slack-Request-Timestamp` string it sent, so a\n // non-canonical-but-numeric header (e.g. leading zeros) must round-trip as-is.\n const expected = `v0=${createHmac('sha256', signingSecret).update(`v0:${timestamp}:${rawBody}`).digest('hex')}`;\n const expectedBuf = Buffer.from(expected, 'utf8');\n const providedBuf = Buffer.from(signature, 'utf8');\n\n // timingSafeEqual throws on length mismatch — short-circuit so the caller\n // gets a uniform \"invalid_signature\" error instead of a crypto exception.\n if (expectedBuf.length !== providedBuf.length || !timingSafeEqual(expectedBuf, providedBuf)) {\n throw new SlackError('Slack request signature does not match').withInternalDetails({\n reason: 'invalid_signature' satisfies SlackSignatureFailureReason,\n });\n }\n};\n","import { BinaryLike } from 'node:crypto';\nimport { Injectable } from 'injectkit';\nimport { Policy, PolicyEnvelope, PolicyResult } from '@maroonedsoftware/policies';\nimport { SlackConfig } from './slack.config.js';\nimport { IsSlackError } from './slack.error.js';\nimport { verifySlackSignature, type SlackSignatureFailureReason } from './slack.signature.js';\n\n/**\n * Policy name under which {@link SlackSignaturePolicy} is registered. Use as the\n * key when wiring your `PolicyRegistryMap`, and pass to `PolicyService.check`.\n */\nexport const SLACK_SIGNATURE_POLICY = 'slack.signature.valid' as const;\n\n/** Header carrying the request timestamp Slack signs into the HMAC. */\nexport const SLACK_REQUEST_TIMESTAMP_HEADER = 'X-Slack-Request-Timestamp';\n/** Header carrying the `v0=`-prefixed request signature. */\nexport const SLACK_SIGNATURE_HEADER = 'X-Slack-Signature';\n\n/**\n * Configuration the {@link SlackSignaturePolicy} reads. A structural subset of\n * {@link SlackConfig}, so a `SlackConfig` value satisfies it directly — e.g.\n * `requireSignature<SlackSignatureOptions>('slack')` with the Slack config\n * stored under that `AppConfig` key.\n */\nexport type SlackSignatureOptions = Pick<SlackConfig, 'signingSecret' | 'signatureMaxAgeSeconds'>;\n\n/**\n * Context for {@link SlackSignaturePolicy}: the raw request bytes, a\n * case-insensitive header accessor, and the {@link SlackSignatureOptions}.\n *\n * Structurally compatible with `@maroonedsoftware/koa`'s\n * `SignaturePolicyContext<SlackSignatureOptions>`, so the koa `requireSignature`\n * middleware can drive this policy without the slack package depending on koa —\n * register `SlackSignaturePolicy` under the signature policy name and point the\n * middleware at the `AppConfig` key holding the Slack config.\n */\nexport interface SlackSignaturePolicyContext {\n /** Raw, unparsed request body — exactly as Slack sent it (from `ctx.rawBody`). */\n rawBody: BinaryLike;\n /**\n * Case-insensitive request header accessor (Koa's `ctx.get`); returns `''`\n * when the header is absent.\n */\n getHeader: (name: string) => string;\n /** Slack signing configuration. */\n options: SlackSignatureOptions;\n}\n\n/**\n * Policy form of {@link verifySlackSignature}: verifies a Slack request against\n * the app signing secret using Slack's v0 scheme (HMAC over\n * `v0:{timestamp}:{rawBody}`, `v0=`-prefixed, with timestamp replay\n * protection).\n *\n * Delegates to {@link verifySlackSignature} so the crypto/timestamp logic has a\n * single source of truth, but answers as a {@link PolicyResult} rather than\n * throwing: allows on success, denies on failure with the helper's\n * {@link SlackSignatureFailureReason} as the denial `reason` and its diagnostics\n * (timestamps, window) on `internalDetails` — never the signing secret, never\n * on the wire. The replay window is anchored to `envelope.now` so all policies\n * in an evaluation share one clock.\n *\n * Registered by default under {@link SLACK_SIGNATURE_POLICY}.\n *\n * @example\n * ```ts\n * // Direct evaluation in a route handler:\n * const result = await policyService.check(SLACK_SIGNATURE_POLICY, {\n * rawBody: ctx.rawBody,\n * getHeader: name => ctx.get(name),\n * options: ctx.container.get(SlackConfig),\n * });\n * if (isPolicyResultDenied(result)) throw httpError(401);\n * ```\n */\n@Injectable()\nexport class SlackSignaturePolicy extends Policy<SlackSignaturePolicyContext> {\n async evaluate(context: SlackSignaturePolicyContext, envelope: PolicyEnvelope): Promise<PolicyResult> {\n const { rawBody, getHeader, options } = context;\n\n // Slack signs the raw text body; `ctx.rawBody` may arrive as a Buffer.\n const body = typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody as Uint8Array).toString('utf8');\n\n try {\n verifySlackSignature({\n signingSecret: options.signingSecret,\n rawBody: body,\n timestamp: getHeader(SLACK_REQUEST_TIMESTAMP_HEADER),\n signature: getHeader(SLACK_SIGNATURE_HEADER),\n maxAgeSeconds: options.signatureMaxAgeSeconds,\n now: Math.floor(envelope.now.toSeconds()),\n });\n return this.allow();\n } catch (error) {\n if (!IsSlackError(error)) throw error;\n\n const internalDetails = error.internalDetails ?? {};\n const reason =\n typeof internalDetails.reason === 'string' ? internalDetails.reason : ('invalid_signature' satisfies SlackSignatureFailureReason);\n return this.deny(reason, undefined, { message: error.message, ...internalDetails });\n }\n }\n}\n","/**\n * Metadata accompanying every dispatched Slack event. Includes the wrapping\n * envelope fields (team/event IDs) plus the raw `event_callback` payload for\n * handlers that need fields the typed `event` object doesn't expose.\n */\nexport type SlackEventContext = {\n /** Slack workspace / team ID from the envelope. */\n teamId: string;\n /** Unique event ID Slack assigns to each delivery. */\n eventId: string;\n /** Unix timestamp the event was generated. */\n eventTime: number;\n /** Original `event_callback` envelope, untouched. */\n envelope: SlackEventCallback;\n};\n\n/**\n * Slack `event_callback` envelope. The shape is documented at\n * https://api.slack.com/types/event. We type the wrapper but leave the inner\n * `event` as `Record<string, unknown>` because the union of all Slack event\n * payloads is large and consumers typically narrow per handler.\n */\nexport type SlackEventCallback = {\n type: 'event_callback';\n team_id: string;\n api_app_id: string;\n event: { type: string } & Record<string, unknown>;\n event_id: string;\n event_time: number;\n authorizations?: unknown[];\n is_ext_shared_channel?: boolean;\n event_context?: string;\n [key: string]: unknown;\n};\n\n/**\n * Derive a stable, collision-free idempotency key for a Slack event delivery.\n *\n * Slack redelivers an `event_callback` (with an `X-Slack-Retry-Num` header) when\n * the initial ack is slow or non-2xx. The assigned `event_id` is stable across\n * those redeliveries, so it keys de-duplication. We scope it by `team_id` where\n * present so ids from different workspaces can never collide.\n *\n * @param envelope - The `event_callback` envelope (only `event_id` / `team_id` are read).\n * @returns `slack:event:{team_id}:{event_id}`, or `slack:event:{event_id}` when no team id.\n */\nexport function slackEventIdempotencyKey(envelope: Pick<SlackEventCallback, 'event_id' | 'team_id'>): string {\n return envelope.team_id ? `slack:event:${envelope.team_id}:${envelope.event_id}` : `slack:event:${envelope.event_id}`;\n}\n\n/**\n * Handler for a single Slack event type (e.g. `app_mention`, `message`,\n * `reaction_added`). Registered in {@link SlackEventHandlerMap}.\n *\n * Handlers should ack quickly — Slack retries any event that doesn't get a\n * 2xx response within ~3 seconds. For slow work, enqueue a job\n * (`@maroonedsoftware/jobbroker`) inside `handle` and return immediately.\n */\nexport interface SlackEventHandler<TEvent extends { type: string } & Record<string, unknown> = { type: string } & Record<string, unknown>> {\n handle(event: TEvent, context: SlackEventContext): Promise<void>;\n}\n","/**\n * The supported interactive payload types Slack POSTs to the interactivity\n * endpoint. Each maps to a different identifier shape (see\n * {@link interactionRouteKey}).\n */\nexport type SlackInteractionType = 'block_actions' | 'view_submission' | 'view_closed' | 'shortcut' | 'message_action' | string;\n\n/**\n * Loose typing for the interactive payload; consumers narrow per handler.\n * Slack's payloads vary by type, but every variant has a `type` field plus\n * one of: `actions[].action_id`, `view.callback_id`, or top-level `callback_id`.\n */\nexport type SlackInteractionPayload = {\n type: SlackInteractionType;\n team?: { id: string; domain?: string };\n user?: { id: string; name?: string };\n trigger_id?: string;\n response_url?: string;\n actions?: Array<{ action_id: string; block_id?: string; value?: string; [key: string]: unknown }>;\n view?: { id: string; callback_id: string; [key: string]: unknown };\n callback_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Optional response Slack accepts for `view_submission` / `view_closed`\n * payloads (e.g. to display validation errors or update a modal).\n */\nexport type SlackInteractionResponse = {\n response_action?: 'errors' | 'update' | 'push' | 'clear';\n errors?: Record<string, string>;\n view?: unknown;\n [key: string]: unknown;\n};\n\n/**\n * Handler for one interactive payload, keyed in {@link SlackInteractionHandlerMap}\n * by `${type}:${identifier}` — see {@link interactionRouteKey}.\n */\nexport interface SlackInteractionHandler {\n handle(payload: SlackInteractionPayload): Promise<SlackInteractionResponse | void>;\n}\n\n/**\n * Computes the routing key used by {@link SlackDispatcher.dispatchInteraction}\n * to look a handler up in {@link SlackInteractionHandlerMap}.\n *\n * - `block_actions` → `block_actions:<first action.action_id>`\n * - `view_submission` / `view_closed` → `<type>:<view.callback_id>`\n * - `shortcut` / `message_action` → `<type>:<callback_id>`\n * - any other type with a `callback_id` → `<type>:<callback_id>`\n *\n * @returns The routing key, or `undefined` if the payload doesn't carry an\n * identifier we can route on (e.g. a `block_actions` payload with no actions).\n */\nexport const interactionRouteKey = (payload: SlackInteractionPayload): string | undefined => {\n switch (payload.type) {\n case 'block_actions': {\n const id = payload.actions?.[0]?.action_id;\n return id ? `block_actions:${id}` : undefined;\n }\n case 'view_submission':\n case 'view_closed': {\n const id = payload.view?.callback_id;\n return id ? `${payload.type}:${id}` : undefined;\n }\n case 'shortcut':\n case 'message_action': {\n return payload.callback_id ? `${payload.type}:${payload.callback_id}` : undefined;\n }\n default: {\n return payload.callback_id ? `${payload.type}:${payload.callback_id}` : undefined;\n }\n }\n};\n","import { Injectable } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport type { IdempotencyStore } from '@maroonedsoftware/cache';\nimport { slackEventIdempotencyKey } from './slack.event.handler.js';\nimport type { SlackEventCallback, SlackEventHandler } from './slack.event.handler.js';\nimport type { SlackCommandHandler, SlackCommandPayload, SlackCommandResponse } from './slack.command.handler.js';\nimport {\n interactionRouteKey,\n SlackInteractionHandler,\n type SlackInteractionPayload,\n type SlackInteractionResponse,\n} from './slack.interaction.handler.js';\n\n/**\n * Body shape Slack POSTs to the Events API endpoint. The handshake variant\n * (`url_verification`) is sent once during app configuration; the rest of the\n * traffic is `event_callback` envelopes (or other future top-level types).\n */\nexport type SlackEventsRequest =\n { type: 'url_verification'; challenge: string; token?: string } | SlackEventCallback | { type: string; [key: string]: unknown };\n\n/**\n * Response Slack expects for the `url_verification` handshake. For\n * `event_callback` and unknown event types, the dispatcher returns\n * `undefined` and the caller should ack with HTTP 200.\n */\nexport type SlackEventsResponse = { challenge: string } | undefined;\n\n/**\n * Injectable map of command keyword (e.g. `/deploy`) → {@link SlackCommandHandler}.\n *\n * @example\n * ```ts\n * registry.register(DeployCommandHandler).useClass(DeployCommandHandler).asSingleton();\n *\n * registry\n * .register(SlackCommandHandlerMap)\n * .useMap(SlackCommandHandlerMap)\n * .set('/deploy', DeployCommandHandler);\n * ```\n */\n@Injectable()\nexport class SlackCommandHandlerMap extends Map<string, SlackCommandHandler> {}\n\n/**\n * Injectable map of Slack event type → {@link SlackEventHandler}. Consumers\n * register handlers at bootstrap and place an instance of this map in their\n * DI container; {@link SlackDispatcher.dispatchEvent} resolves it per request.\n *\n * @example\n * ```ts\n * registry.register(MyAppMentionHandler).useClass(MyAppMentionHandler).asSingleton();\n *\n * registry\n * .register(SlackEventHandlerMap)\n * .useMap(SlackEventHandlerMap)\n * .set('app_mention', MyAppMentionHandler);\n * ```\n */\n@Injectable()\nexport class SlackEventHandlerMap extends Map<string, SlackEventHandler> {}\n\n/**\n * Injectable map of interaction routing keys → {@link SlackInteractionHandler}.\n *\n * Keys are produced by `interactionRouteKey(payload)`, which combines the\n * payload `type` with the relevant identifier (`action_id`, `callback_id`,\n * etc.). Register handlers under the same key shape:\n *\n * @example\n * ```ts\n * registry.register(ApproveHandler).useClass(ApproveHandler).asSingleton();\n * registry.register(CreateTicketHandler).useClass(CreateTicketHandler).asSingleton();\n *\n * registry\n * .register(SlackInteractionHandlerMap)\n * .useMap(SlackInteractionHandlerMap)\n * .set('block_actions:approve_button', ApproveHandler)\n * .set('view_submission:create_ticket_modal', CreateTicketHandler);\n * ```\n */\n@Injectable()\nexport class SlackInteractionHandlerMap extends Map<string, SlackInteractionHandler> {}\n\n/**\n * Single entry point for dispatching parsed Slack payloads to registered\n * handlers. Transport-agnostic: the consumer is responsible for receiving\n * the HTTP request, verifying the signature, parsing the body, calling the\n * appropriate `dispatch*` method, and serializing the response.\n *\n * @example Koa route\n * ```ts\n * router.post('/slack/events', async (ctx) => {\n * const raw = await rawBody(ctx.req, { encoding: 'utf8' });\n * verifySlackSignature({\n * signingSecret: ctx.container.get(SlackConfig).signingSecret,\n * rawBody: raw,\n * timestamp: ctx.get('x-slack-request-timestamp'),\n * signature: ctx.get('x-slack-signature'),\n * });\n * const result = await ctx.container.get(SlackDispatcher).dispatchEvent(JSON.parse(raw));\n * if (result) ctx.body = result;\n * else { ctx.status = 200; ctx.body = ''; }\n * });\n * ```\n */\n@Injectable()\nexport class SlackDispatcher {\n constructor(\n private readonly events: SlackEventHandlerMap,\n private readonly commands: SlackCommandHandlerMap,\n private readonly interactions: SlackInteractionHandlerMap,\n private readonly logger: Logger,\n ) {}\n\n /**\n * Dispatch a parsed Events API body.\n *\n * - Returns `{ challenge }` for `url_verification` — the caller serializes\n * it as the response body. This handshake is NEVER de-duplicated: it must\n * always echo the challenge.\n * - For `event_callback`, looks up a handler in {@link SlackEventHandlerMap}\n * keyed by `event.type` and invokes it. Returns `undefined`. Slack retries\n * any non-2xx so unknown event types are logged at debug and acked.\n * - For any other top-level type, logs and returns `undefined`.\n *\n * Pass `options.idempotency` to de-duplicate `event_callback` deliveries: Slack\n * redelivers events (with an `X-Slack-Retry-Num` header) on a slow/failed ack,\n * so wrapping the handler in an {@link IdempotencyStore} keyed by\n * {@link slackEventIdempotencyKey} runs it at most once per `event_id`. A\n * `duplicate`/`dropped` outcome skips the handler and acks (returns `undefined`).\n * When `options.idempotency` is omitted, behaviour is unchanged.\n */\n async dispatchEvent(body: SlackEventsRequest, options?: { idempotency?: IdempotencyStore }): Promise<SlackEventsResponse> {\n if (body.type === 'url_verification') {\n return { challenge: (body as { challenge: string }).challenge };\n }\n\n if (body.type === 'event_callback') {\n const envelope = body as SlackEventCallback;\n const handleEvent = async (): Promise<void> => {\n const handler = this.events.get(envelope.event.type);\n if (handler) {\n await handler.handle(envelope.event, {\n teamId: envelope.team_id,\n eventId: envelope.event_id,\n eventTime: envelope.event_time,\n envelope,\n });\n } else {\n this.logger.debug('No Slack event handler registered for event type', { type: envelope.event.type });\n }\n };\n\n if (options?.idempotency) {\n const key = slackEventIdempotencyKey(envelope);\n const outcome = await options.idempotency.deduplicate(key, handleEvent);\n if (outcome.status === 'dropped') {\n this.logger.warn('Slack event dead-lettered after repeated failures', { key, attempts: outcome.attempts });\n }\n return undefined;\n }\n\n await handleEvent();\n return undefined;\n }\n\n this.logger.debug('Unhandled Slack events payload type', { type: body.type });\n return undefined;\n }\n\n /**\n * Dispatch a parsed slash-command payload.\n *\n * Looks up a handler in {@link SlackCommandHandlerMap} keyed by\n * `payload.command` (e.g. `/deploy`). If the handler returns a response,\n * the caller serializes it as JSON; otherwise the caller acks with `200 ''`\n * and the handler is expected to follow up via `payload.response_url`.\n */\n async dispatchCommand(payload: SlackCommandPayload): Promise<SlackCommandResponse | void> {\n const handler = this.commands.get(payload.command);\n if (!handler) {\n this.logger.debug('No Slack command handler registered', { command: payload.command });\n return undefined;\n }\n return await handler.handle(payload);\n }\n\n /**\n * Dispatch a parsed interactive payload (block actions, view submission,\n * shortcut, etc.). Computes a routing key via {@link interactionRouteKey}\n * and looks it up in {@link SlackInteractionHandlerMap}.\n */\n async dispatchInteraction(payload: SlackInteractionPayload): Promise<SlackInteractionResponse | void> {\n const key = interactionRouteKey(payload);\n if (!key) {\n this.logger.debug('Slack interaction payload missing routable identifier', { type: payload.type });\n return undefined;\n }\n const handler = this.interactions.get(key);\n if (!handler) {\n this.logger.debug('No Slack interaction handler registered', { key });\n return undefined;\n }\n return await handler.handle(payload);\n }\n}\n","import { Injectable } from 'injectkit';\nimport { WebClient } from '@slack/web-api';\nimport type {\n WebClientOptions,\n ChatPostMessageArguments,\n ChatPostMessageResponse,\n ChatUpdateArguments,\n ChatUpdateResponse,\n ChatDeleteArguments,\n ChatDeleteResponse,\n ViewsOpenArguments,\n ViewsOpenResponse,\n} from '@slack/web-api';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { SlackConfig } from '../slack.config.js';\nimport { SlackError } from '../slack.error.js';\nimport { adaptLogger } from './slack.logger.adapter.js';\n\n/** Default per-request timeout (ms) applied to outbound `postWebhook` calls. */\nexport const SLACK_DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\n/**\n * Redacts a Slack webhook / `response_url` so it is safe to log. The final path\n * segment is the secret token (and the query string can carry secrets too), so\n * both are stripped, leaving only the host and path prefix.\n */\nexport const redactSlackUrl = (raw: string): string => {\n try {\n const url = new URL(raw);\n const segments = url.pathname.split('/').filter(Boolean);\n if (segments.length > 0) segments[segments.length - 1] = '***';\n return `${url.origin}/${segments.join('/')}`;\n } catch {\n return '***';\n }\n};\n\n/**\n * Payload for an incoming-webhook POST. Mirrors the subset of fields Slack's\n * incoming webhooks accept (text, blocks, attachments, response shaping).\n * The body is JSON-stringified verbatim, so any extra fields are preserved.\n */\nexport type IncomingWebhookPayload = {\n text?: string;\n blocks?: unknown[];\n attachments?: unknown[];\n thread_ts?: string;\n response_type?: 'in_channel' | 'ephemeral';\n replace_original?: boolean;\n delete_original?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n [key: string]: unknown;\n};\n\n/**\n * Thin DI-friendly wrapper around `@slack/web-api`'s `WebClient`. Constructed\n * once per request scope (or as a singleton, depending on how the consumer\n * registers it) and exposes typed passthroughs for the most common Web API\n * methods plus a `postWebhook` helper for incoming-webhook URLs and the\n * `response_url` returned by slash commands and interactive payloads.\n *\n * Reach for {@link SlackClient.web} directly for anything else the underlying\n * client supports.\n *\n * @example\n * ```ts\n * await container.get(SlackClient).postMessage({ channel: '#ops', text: 'hello' });\n * await container.get(SlackClient).postWebhook({ text: 'follow-up' }, payload.response_url);\n * ```\n */\n@Injectable()\nexport class SlackClient {\n /** Underlying `@slack/web-api` client. */\n readonly web: WebClient;\n\n /** Web API client authenticated with the app token, built on first use by {@link openSocketModeUrl}. */\n private appWeb?: WebClient;\n\n constructor(\n private readonly config: SlackConfig,\n private readonly logger: Logger,\n ) {\n this.web = new WebClient(config.botToken, this.webClientOptions());\n }\n\n /** Options shared by every `WebClient` this class builds, passing only what the config sets. */\n private webClientOptions(): WebClientOptions {\n return {\n logger: adaptLogger(this.logger),\n ...(this.config.fetch ? { fetch: this.config.fetch } : {}),\n ...(this.config.apiBaseUrl ? { slackApiUrl: this.config.apiBaseUrl } : {}),\n };\n }\n\n /** Posts a message via `chat.postMessage`. */\n postMessage(args: ChatPostMessageArguments): Promise<ChatPostMessageResponse> {\n return this.web.chat.postMessage(args);\n }\n\n /** Updates a message via `chat.update`. */\n updateMessage(args: ChatUpdateArguments): Promise<ChatUpdateResponse> {\n return this.web.chat.update(args);\n }\n\n /** Deletes a message via `chat.delete`. */\n deleteMessage(args: ChatDeleteArguments): Promise<ChatDeleteResponse> {\n return this.web.chat.delete(args);\n }\n\n /** Opens a modal view via `views.open`. */\n openView(args: ViewsOpenArguments): Promise<ViewsOpenResponse> {\n return this.web.views.open(args);\n }\n\n /**\n * POSTs a payload to a Slack incoming-webhook-style URL — either the\n * configured `incomingWebhookUrl` or an explicit URL (e.g. the\n * `response_url` from a slash command or interactive payload).\n *\n * @throws {@link SlackError} if no URL is available or the response is non-2xx.\n */\n async postWebhook(payload: IncomingWebhookPayload, url?: string): Promise<void> {\n const target = url ?? this.config.incomingWebhookUrl;\n if (!target) {\n throw new SlackError('SlackClient.postWebhook called but no incomingWebhookUrl is configured and no url was provided');\n }\n // `target` is a response_url / incoming-webhook URL whose last path segment\n // is a secret — redact it before it reaches the log or internalDetails.\n const safeUrl = redactSlackUrl(target);\n const fetcher = this.config.fetch ?? fetch;\n\n let response: Awaited<ReturnType<typeof fetcher>>;\n try {\n response = await fetcher(target, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.config.requestTimeoutMs ?? SLACK_DEFAULT_REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n // Deliberately not `withCause(error)`: the cause's message can quote the URL, and the URL\n // holds the secret.\n const reason = (error instanceof Error ? error.message : String(error)).split(target).join(safeUrl);\n this.logger.warn('Slack webhook POST did not reach Slack', { url: safeUrl, reason });\n throw new SlackError('Slack webhook POST did not reach Slack').withInternalDetails({ url: safeUrl, reason });\n }\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n this.logger.warn('Slack webhook POST returned non-OK status', { status: response.status, body, url: safeUrl });\n throw new SlackError(`Slack webhook POST returned ${response.status}`).withInternalDetails({ status: response.status, body, url: safeUrl });\n }\n }\n\n /**\n * Opens a Socket Mode connection slot via `apps.connections.open` and returns the WebSocket URL\n * to connect to. Authenticates with `appToken`, not the bot token, over the same `fetch` and base\n * URL as every other call. Each URL is single-use, so call this again for every reconnect.\n *\n * @throws {@link SlackError} if `appToken` is not configured or Slack does not hand back a URL.\n */\n async openSocketModeUrl(): Promise<string> {\n const appToken = this.config.appToken;\n if (!appToken) {\n throw new SlackError('SlackClient.openSocketModeUrl called but no appToken (xapp-...) is configured');\n }\n this.appWeb ??= new WebClient(appToken, this.webClientOptions());\n\n let result: { ok?: boolean; url?: string; error?: string };\n try {\n result = await this.appWeb.apps.connections.open();\n } catch (error) {\n // The SDK throws on `ok: false`, carrying Slack's error code in `data.error`. Its errors do\n // not quote the token, but only the code and message are kept, to be safe.\n const code = (error as { data?: { error?: unknown } }).data?.error;\n const reason = error instanceof Error ? error.message.split(appToken).join('<token>') : String(error);\n this.logger.warn('Slack apps.connections.open failed', { error: code, reason });\n throw new SlackError('Slack apps.connections.open failed').withInternalDetails({ error: code, reason });\n }\n\n if (!result.ok || !result.url) {\n this.logger.warn('Slack apps.connections.open returned no URL', { error: result.error });\n throw new SlackError('Slack apps.connections.open returned no URL').withInternalDetails({ error: result.error });\n }\n return result.url;\n }\n}\n","import type { Logger as SlackLogger, LogLevel } from '@slack/web-api';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Adapts a ServerKit {@link Logger} to the `@slack/web-api` {@link SlackLogger}\n * interface so the WebClient can route its diagnostics through the host\n * application's logger.\n *\n * The Slack SDK's logger calls `logger.info(...args)` with a variable number\n * of arguments and no separate \"primary message\"; the adapter forwards them\n * to ServerKit's `(message, ...optionalParams)` shape, with an empty-string\n * primary when no args are passed.\n *\n * `setLevel`, `setName`, and `getLevel` are stored locally — ServerKit\n * loggers do not expose these knobs but the SDK expects them on its logger.\n *\n * @param logger - The ServerKit logger to forward calls to.\n * @param name - Initial value for the SDK logger's name. Defaults to `'slack-web-api'`.\n * @returns A `@slack/web-api`-compatible logger object.\n */\nexport const adaptLogger = (logger: Logger, name = 'slack-web-api'): SlackLogger => {\n const state = { name, level: 'info' as LogLevel };\n const forward =\n (fn: (message: unknown, ...optionalParams: unknown[]) => void) =>\n (...msg: unknown[]) => {\n const [first, ...rest] = msg;\n fn(first ?? '', ...rest);\n };\n return {\n debug: forward(logger.debug.bind(logger)),\n info: forward(logger.info.bind(logger)),\n warn: forward(logger.warn.bind(logger)),\n error: forward(logger.error.bind(logger)),\n setLevel: (level: LogLevel) => {\n state.level = level;\n },\n getLevel: () => state.level,\n setName: (n: string) => {\n state.name = n;\n },\n };\n};\n"],"mappings":";;;;;;;;;AACA,SAASA,kBAAkB;;;;;;;;AAqEpB,IAAeC,cAAf,MAAeA;SAAAA;;;AAAo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["Injectable","SlackConfig","createHmac","timingSafeEqual","DateTime","SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS","verifySlackSignature","input","signingSecret","rawBody","timestamp","signature","maxAgeSeconds","now","Math","floor","DateTime","toSeconds","SlackError","withInternalDetails","reason","ts","Number","isFinite","isInteger","abs","expected","createHmac","update","digest","expectedBuf","Buffer","from","providedBuf","length","timingSafeEqual","Injectable","Policy","SLACK_SIGNATURE_POLICY","SLACK_REQUEST_TIMESTAMP_HEADER","SLACK_SIGNATURE_HEADER","SlackSignaturePolicy","Policy","evaluate","context","envelope","rawBody","getHeader","options","body","Buffer","from","toString","verifySlackSignature","signingSecret","timestamp","signature","maxAgeSeconds","signatureMaxAgeSeconds","now","Math","floor","toSeconds","allow","error","IsSlackError","internalDetails","reason","deny","undefined","message","slackEventIdempotencyKey","envelope","team_id","event_id","interactionRouteKey","payload","type","id","actions","action_id","undefined","view","callback_id","Injectable","Logger","SlackCommandHandlerMap","Map","SlackEventHandlerMap","SlackInteractionHandlerMap","SlackDispatcher","events","commands","interactions","logger","dispatchEvent","body","options","type","challenge","envelope","handleEvent","handler","get","event","handle","teamId","team_id","eventId","event_id","eventTime","event_time","debug","idempotency","key","slackEventIdempotencyKey","outcome","deduplicate","status","warn","attempts","undefined","dispatchCommand","payload","command","dispatchInteraction","interactionRouteKey","Injectable","WebClient","Logger","adaptLogger","logger","name","state","level","forward","fn","msg","first","rest","debug","bind","info","warn","error","setLevel","getLevel","setName","n","SLACK_DEFAULT_REQUEST_TIMEOUT_MS","redactSlackUrl","raw","url","URL","segments","pathname","split","filter","Boolean","length","origin","join","SlackClient","web","appWeb","config","logger","WebClient","botToken","webClientOptions","adaptLogger","fetch","apiBaseUrl","slackApiUrl","postMessage","args","chat","updateMessage","update","deleteMessage","delete","openView","views","open","postWebhook","payload","target","incomingWebhookUrl","SlackError","safeUrl","fetcher","response","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","requestTimeoutMs","error","reason","Error","message","String","warn","withInternalDetails","ok","text","catch","status","openSocketModeUrl","appToken","result","apps","connections","code","data"]}
1
+ {"version":3,"sources":["../src/slack.config.ts","../src/slack.signature.ts","../src/slack.signature.policy.ts","../src/slack.event.handler.ts","../src/slack.interaction.handler.ts","../src/slack.dispatcher.ts","../src/client/slack.client.ts","../src/client/slack.logger.adapter.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport { Injectable } from 'injectkit';\nimport type { FetchFunction } from '@slack/web-api';\n\n/**\n * Configuration for the Slack package. Declared as an abstract `@Injectable()`\n * class so it doubles as a DI token (mirrors the `Logger` pattern in\n * `@maroonedsoftware/logger`).\n *\n * Consumers register a concrete value at bootstrap, typically resolved from\n * `AppConfig`:\n *\n * ```ts\n * const slackConfig = appConfig.getAs<SlackConfig>('slack');\n * registry.register(SlackConfig).useValue(slackConfig);\n * ```\n *\n * Services in this package take `SlackConfig` directly in their constructor.\n */\nexport interface SlackConfig {\n /** Bot user OAuth token (`xoxb-...`). Required for Web API calls. */\n botToken: string;\n /**\n * App-level signing secret used to verify request signatures. Needed only when Slack calls you\n * over HTTP; a Socket Mode app can leave it unset, and signature verification then fails closed\n * with `missing_signing_secret`.\n */\n signingSecret?: string;\n /**\n * App-level token (`xapp-...`) with the `connections:write` scope. Needed only for Socket Mode,\n * where {@link import('./client/slack.client.js').SlackClient.openSocketModeUrl} trades it for a\n * WebSocket URL.\n */\n appToken?: string;\n /** Optional incoming webhook URL used as the default target for `SlackClient.postWebhook`. */\n incomingWebhookUrl?: string;\n /**\n * Maximum age (in seconds) for request timestamps before signature\n * verification rejects them as replays. Defaults to `300` (5 minutes).\n */\n signatureMaxAgeSeconds?: number;\n /**\n * Per-request timeout (in milliseconds) for outbound `SlackClient.postWebhook`\n * calls. Defaults to\n * {@link import('./client/slack.client.js').SLACK_DEFAULT_REQUEST_TIMEOUT_MS} (10s).\n */\n requestTimeoutMs?: number;\n /**\n * Base URL for Web API calls, forwarded to `@slack/web-api` as `slackApiUrl`. Defaults to the\n * SDK's own (`https://slack.com/api/`).\n */\n apiBaseUrl?: string;\n /**\n * The `fetch` every outbound call goes through: the Web API client, `postWebhook`, and\n * `openSocketModeUrl`. Defaults to the global `fetch`.\n *\n * Set it when the caller owns the transport: a host that routes outbound HTTP through its own\n * allowlist, rate limits or proxy, or a test. The client passes an `AbortSignal` carrying its\n * timeout; an implementation that enforces its own deadline as well may ignore it.\n */\n fetch?: SlackFetch;\n /**\n * How many times the Web API client retries a call that failed: a transport error, a non-200, or\n * a rate limit it waited out. Forwarded to `@slack/web-api` as `retryConfig: { retries }`.\n * Defaults to the SDK's own policy, ten retries over about thirty minutes.\n *\n * Set `0` when the caller owns retrying (a job queue, or a host that abandons a call at its own\n * deadline): the SDK's retries otherwise carry on in the background after the caller has given\n * up, and can deliver a message long after it stopped being true.\n */\n retries?: number;\n /**\n * Reject a rate-limited Web API call with `WebAPIRateLimitedError` instead of pausing every call\n * until Slack's `Retry-After` has passed. Forwarded as-is. Defaults to `false`, the SDK's own.\n */\n rejectRateLimitedCalls?: boolean;\n}\n\n/**\n * The `fetch` shape the client needs. It is `@slack/web-api`'s own `FetchFunction`, so one\n * function serves both the Web API client and the webhook POSTs; the global `fetch` satisfies it.\n */\nexport type SlackFetch = FetchFunction;\n\n@Injectable()\nexport abstract class SlackConfig implements SlackConfig {}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { DateTime } from 'luxon';\nimport { SlackError } from './slack.error.js';\n\n/** Default replay-protection window in seconds (5 minutes — matches Slack's recommendation). */\nexport const SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS = 300;\n\n/**\n * Reason codes attached to {@link SlackError.internalDetails} when verification\n * fails. Useful for callers that want to log structured reasons without\n * pattern-matching on error messages.\n */\nexport type SlackSignatureFailureReason =\n 'missing_signing_secret' | 'missing_timestamp' | 'invalid_timestamp' | 'stale_timestamp' | 'missing_signature' | 'invalid_signature';\n\n/**\n * Inputs to {@link verifySlackSignature}. All values are taken verbatim from\n * the request — the helper does no header lookups or body reads of its own.\n */\nexport type VerifySlackSignatureInput = {\n /**\n * App signing secret (`SlackConfig.signingSecret`). Optional in the config because a Socket\n * Mode app never verifies a request; verification without one fails with\n * `missing_signing_secret` rather than checking against an empty key.\n */\n signingSecret: string | undefined;\n /** Raw, unparsed request body — exactly as Slack sent it. */\n rawBody: string;\n /** Value of the `X-Slack-Request-Timestamp` header. */\n timestamp: string | undefined;\n /** Value of the `X-Slack-Signature` header (e.g. `\"v0=abc123…\"`). */\n signature: string | undefined;\n /**\n * Maximum age in seconds before the request is rejected as a replay.\n * Defaults to {@link SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS}.\n */\n maxAgeSeconds?: number;\n /**\n * Override for the current Unix time in seconds. Mostly useful for tests;\n * defaults to `Math.floor(DateTime.now().toSeconds())`.\n */\n now?: number;\n};\n\n/**\n * Verifies a Slack request signature against the app signing secret.\n *\n * Implements Slack's v0 scheme:\n * 1. Reject the request if `X-Slack-Request-Timestamp` is missing, non-numeric,\n * or older than `maxAgeSeconds` (replay protection).\n * 2. Compute `v0=` + `HMAC-SHA256(signingSecret, \"v0:{timestamp}:{rawBody}\")`\n * as hex.\n * 3. Compare against the provided `X-Slack-Signature` value using a\n * constant-time compare.\n *\n * Pure: no request/context coupling. The caller extracts the headers and raw\n * body from whatever transport it's using and passes them in.\n *\n * @throws {@link SlackError} on any failure. The error's `internalDetails.reason`\n * is one of {@link SlackSignatureFailureReason}; map to HTTP 401 at the route boundary.\n *\n * @example\n * ```ts\n * try {\n * verifySlackSignature({\n * signingSecret: config.signingSecret,\n * rawBody,\n * timestamp: req.headers['x-slack-request-timestamp'],\n * signature: req.headers['x-slack-signature'],\n * });\n * } catch (err) {\n * throw httpError(401).withCause(err);\n * }\n * ```\n */\nexport const verifySlackSignature = (input: VerifySlackSignatureInput): void => {\n const {\n signingSecret,\n rawBody,\n timestamp,\n signature,\n maxAgeSeconds = SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS,\n now = Math.floor(DateTime.now().toSeconds()),\n } = input;\n\n if (!signingSecret) {\n throw new SlackError('Slack signature verification needs SlackConfig.signingSecret, which is not set').withInternalDetails({\n reason: 'missing_signing_secret' satisfies SlackSignatureFailureReason,\n });\n }\n\n if (!timestamp) {\n throw new SlackError('Slack request missing X-Slack-Request-Timestamp header').withInternalDetails({\n reason: 'missing_timestamp' satisfies SlackSignatureFailureReason,\n });\n }\n\n const ts = Number(timestamp);\n if (!Number.isFinite(ts) || !Number.isInteger(ts)) {\n throw new SlackError('Slack request timestamp is not a valid integer').withInternalDetails({\n reason: 'invalid_timestamp' satisfies SlackSignatureFailureReason,\n timestamp,\n });\n }\n\n if (Math.abs(now - ts) > maxAgeSeconds) {\n throw new SlackError('Slack request timestamp is outside the allowed window').withInternalDetails({\n reason: 'stale_timestamp' satisfies SlackSignatureFailureReason,\n timestamp: ts,\n now,\n maxAgeSeconds,\n });\n }\n\n if (!signature) {\n throw new SlackError('Slack request missing X-Slack-Signature header').withInternalDetails({\n reason: 'missing_signature' satisfies SlackSignatureFailureReason,\n });\n }\n\n // Sign with the raw header value verbatim (not the parsed `ts`): Slack computes\n // its signature over the exact `X-Slack-Request-Timestamp` string it sent, so a\n // non-canonical-but-numeric header (e.g. leading zeros) must round-trip as-is.\n const expected = `v0=${createHmac('sha256', signingSecret).update(`v0:${timestamp}:${rawBody}`).digest('hex')}`;\n const expectedBuf = Buffer.from(expected, 'utf8');\n const providedBuf = Buffer.from(signature, 'utf8');\n\n // timingSafeEqual throws on length mismatch — short-circuit so the caller\n // gets a uniform \"invalid_signature\" error instead of a crypto exception.\n if (expectedBuf.length !== providedBuf.length || !timingSafeEqual(expectedBuf, providedBuf)) {\n throw new SlackError('Slack request signature does not match').withInternalDetails({\n reason: 'invalid_signature' satisfies SlackSignatureFailureReason,\n });\n }\n};\n","import { BinaryLike } from 'node:crypto';\nimport { Injectable } from 'injectkit';\nimport { Policy, PolicyEnvelope, PolicyResult } from '@maroonedsoftware/policies';\nimport { SlackConfig } from './slack.config.js';\nimport { IsSlackError } from './slack.error.js';\nimport { verifySlackSignature, type SlackSignatureFailureReason } from './slack.signature.js';\n\n/**\n * Policy name under which {@link SlackSignaturePolicy} is registered. Use as the\n * key when wiring your `PolicyRegistryMap`, and pass to `PolicyService.check`.\n */\nexport const SLACK_SIGNATURE_POLICY = 'slack.signature.valid' as const;\n\n/** Header carrying the request timestamp Slack signs into the HMAC. */\nexport const SLACK_REQUEST_TIMESTAMP_HEADER = 'X-Slack-Request-Timestamp';\n/** Header carrying the `v0=`-prefixed request signature. */\nexport const SLACK_SIGNATURE_HEADER = 'X-Slack-Signature';\n\n/**\n * Configuration the {@link SlackSignaturePolicy} reads. A structural subset of\n * {@link SlackConfig}, so a `SlackConfig` value satisfies it directly — e.g.\n * `requireSignature<SlackSignatureOptions>('slack')` with the Slack config\n * stored under that `AppConfig` key.\n */\nexport type SlackSignatureOptions = Pick<SlackConfig, 'signingSecret' | 'signatureMaxAgeSeconds'>;\n\n/**\n * Context for {@link SlackSignaturePolicy}: the raw request bytes, a\n * case-insensitive header accessor, and the {@link SlackSignatureOptions}.\n *\n * Structurally compatible with `@maroonedsoftware/koa`'s\n * `SignaturePolicyContext<SlackSignatureOptions>`, so the koa `requireSignature`\n * middleware can drive this policy without the slack package depending on koa —\n * register `SlackSignaturePolicy` under the signature policy name and point the\n * middleware at the `AppConfig` key holding the Slack config.\n */\nexport interface SlackSignaturePolicyContext {\n /** Raw, unparsed request body — exactly as Slack sent it (from `ctx.rawBody`). */\n rawBody: BinaryLike;\n /**\n * Case-insensitive request header accessor (Koa's `ctx.get`); returns `''`\n * when the header is absent.\n */\n getHeader: (name: string) => string;\n /** Slack signing configuration. */\n options: SlackSignatureOptions;\n}\n\n/**\n * Policy form of {@link verifySlackSignature}: verifies a Slack request against\n * the app signing secret using Slack's v0 scheme (HMAC over\n * `v0:{timestamp}:{rawBody}`, `v0=`-prefixed, with timestamp replay\n * protection).\n *\n * Delegates to {@link verifySlackSignature} so the crypto/timestamp logic has a\n * single source of truth, but answers as a {@link PolicyResult} rather than\n * throwing: allows on success, denies on failure with the helper's\n * {@link SlackSignatureFailureReason} as the denial `reason` and its diagnostics\n * (timestamps, window) on `internalDetails` — never the signing secret, never\n * on the wire. The replay window is anchored to `envelope.now` so all policies\n * in an evaluation share one clock.\n *\n * Registered by default under {@link SLACK_SIGNATURE_POLICY}.\n *\n * @example\n * ```ts\n * // Direct evaluation in a route handler:\n * const result = await policyService.check(SLACK_SIGNATURE_POLICY, {\n * rawBody: ctx.rawBody,\n * getHeader: name => ctx.get(name),\n * options: ctx.container.get(SlackConfig),\n * });\n * if (isPolicyResultDenied(result)) throw httpError(401);\n * ```\n */\n@Injectable()\nexport class SlackSignaturePolicy extends Policy<SlackSignaturePolicyContext> {\n async evaluate(context: SlackSignaturePolicyContext, envelope: PolicyEnvelope): Promise<PolicyResult> {\n const { rawBody, getHeader, options } = context;\n\n // Slack signs the raw text body; `ctx.rawBody` may arrive as a Buffer.\n const body = typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody as Uint8Array).toString('utf8');\n\n try {\n verifySlackSignature({\n signingSecret: options.signingSecret,\n rawBody: body,\n timestamp: getHeader(SLACK_REQUEST_TIMESTAMP_HEADER),\n signature: getHeader(SLACK_SIGNATURE_HEADER),\n maxAgeSeconds: options.signatureMaxAgeSeconds,\n now: Math.floor(envelope.now.toSeconds()),\n });\n return this.allow();\n } catch (error) {\n if (!IsSlackError(error)) throw error;\n\n const internalDetails = error.internalDetails ?? {};\n const reason =\n typeof internalDetails.reason === 'string' ? internalDetails.reason : ('invalid_signature' satisfies SlackSignatureFailureReason);\n return this.deny(reason, undefined, { message: error.message, ...internalDetails });\n }\n }\n}\n","/**\n * Metadata accompanying every dispatched Slack event. Includes the wrapping\n * envelope fields (team/event IDs) plus the raw `event_callback` payload for\n * handlers that need fields the typed `event` object doesn't expose.\n */\nexport type SlackEventContext = {\n /** Slack workspace / team ID from the envelope. */\n teamId: string;\n /** Unique event ID Slack assigns to each delivery. */\n eventId: string;\n /** Unix timestamp the event was generated. */\n eventTime: number;\n /** Original `event_callback` envelope, untouched. */\n envelope: SlackEventCallback;\n};\n\n/**\n * Slack `event_callback` envelope. The shape is documented at\n * https://api.slack.com/types/event. We type the wrapper but leave the inner\n * `event` as `Record<string, unknown>` because the union of all Slack event\n * payloads is large and consumers typically narrow per handler.\n */\nexport type SlackEventCallback = {\n type: 'event_callback';\n team_id: string;\n api_app_id: string;\n event: { type: string } & Record<string, unknown>;\n event_id: string;\n event_time: number;\n authorizations?: unknown[];\n is_ext_shared_channel?: boolean;\n event_context?: string;\n [key: string]: unknown;\n};\n\n/**\n * Derive a stable, collision-free idempotency key for a Slack event delivery.\n *\n * Slack redelivers an `event_callback` (with an `X-Slack-Retry-Num` header) when\n * the initial ack is slow or non-2xx. The assigned `event_id` is stable across\n * those redeliveries, so it keys de-duplication. We scope it by `team_id` where\n * present so ids from different workspaces can never collide.\n *\n * @param envelope - The `event_callback` envelope (only `event_id` / `team_id` are read).\n * @returns `slack:event:{team_id}:{event_id}`, or `slack:event:{event_id}` when no team id.\n */\nexport function slackEventIdempotencyKey(envelope: Pick<SlackEventCallback, 'event_id' | 'team_id'>): string {\n return envelope.team_id ? `slack:event:${envelope.team_id}:${envelope.event_id}` : `slack:event:${envelope.event_id}`;\n}\n\n/**\n * Handler for a single Slack event type (e.g. `app_mention`, `message`,\n * `reaction_added`). Registered in {@link SlackEventHandlerMap}.\n *\n * Handlers should ack quickly — Slack retries any event that doesn't get a\n * 2xx response within ~3 seconds. For slow work, enqueue a job\n * (`@maroonedsoftware/jobbroker`) inside `handle` and return immediately.\n */\nexport interface SlackEventHandler<TEvent extends { type: string } & Record<string, unknown> = { type: string } & Record<string, unknown>> {\n handle(event: TEvent, context: SlackEventContext): Promise<void>;\n}\n","/**\n * The supported interactive payload types Slack POSTs to the interactivity\n * endpoint. Each maps to a different identifier shape (see\n * {@link interactionRouteKey}).\n */\nexport type SlackInteractionType = 'block_actions' | 'view_submission' | 'view_closed' | 'shortcut' | 'message_action' | string;\n\n/**\n * Loose typing for the interactive payload; consumers narrow per handler.\n * Slack's payloads vary by type, but every variant has a `type` field plus\n * one of: `actions[].action_id`, `view.callback_id`, or top-level `callback_id`.\n */\nexport type SlackInteractionPayload = {\n type: SlackInteractionType;\n team?: { id: string; domain?: string };\n user?: { id: string; name?: string };\n trigger_id?: string;\n response_url?: string;\n actions?: Array<{ action_id: string; block_id?: string; value?: string; [key: string]: unknown }>;\n view?: { id: string; callback_id: string; [key: string]: unknown };\n callback_id?: string;\n [key: string]: unknown;\n};\n\n/**\n * Optional response Slack accepts for `view_submission` / `view_closed`\n * payloads (e.g. to display validation errors or update a modal).\n */\nexport type SlackInteractionResponse = {\n response_action?: 'errors' | 'update' | 'push' | 'clear';\n errors?: Record<string, string>;\n view?: unknown;\n [key: string]: unknown;\n};\n\n/**\n * Handler for one interactive payload, keyed in {@link SlackInteractionHandlerMap}\n * by `${type}:${identifier}` — see {@link interactionRouteKey}.\n */\nexport interface SlackInteractionHandler {\n handle(payload: SlackInteractionPayload): Promise<SlackInteractionResponse | void>;\n}\n\n/**\n * Computes the routing key used by {@link SlackDispatcher.dispatchInteraction}\n * to look a handler up in {@link SlackInteractionHandlerMap}.\n *\n * - `block_actions` → `block_actions:<first action.action_id>`\n * - `view_submission` / `view_closed` → `<type>:<view.callback_id>`\n * - `shortcut` / `message_action` → `<type>:<callback_id>`\n * - any other type with a `callback_id` → `<type>:<callback_id>`\n *\n * @returns The routing key, or `undefined` if the payload doesn't carry an\n * identifier we can route on (e.g. a `block_actions` payload with no actions).\n */\nexport const interactionRouteKey = (payload: SlackInteractionPayload): string | undefined => {\n switch (payload.type) {\n case 'block_actions': {\n const id = payload.actions?.[0]?.action_id;\n return id ? `block_actions:${id}` : undefined;\n }\n case 'view_submission':\n case 'view_closed': {\n const id = payload.view?.callback_id;\n return id ? `${payload.type}:${id}` : undefined;\n }\n case 'shortcut':\n case 'message_action': {\n return payload.callback_id ? `${payload.type}:${payload.callback_id}` : undefined;\n }\n default: {\n return payload.callback_id ? `${payload.type}:${payload.callback_id}` : undefined;\n }\n }\n};\n","import { Injectable } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport type { IdempotencyStore } from '@maroonedsoftware/cache';\nimport { slackEventIdempotencyKey } from './slack.event.handler.js';\nimport type { SlackEventCallback, SlackEventHandler } from './slack.event.handler.js';\nimport type { SlackCommandHandler, SlackCommandPayload, SlackCommandResponse } from './slack.command.handler.js';\nimport {\n interactionRouteKey,\n SlackInteractionHandler,\n type SlackInteractionPayload,\n type SlackInteractionResponse,\n} from './slack.interaction.handler.js';\n\n/**\n * Body shape Slack POSTs to the Events API endpoint. The handshake variant\n * (`url_verification`) is sent once during app configuration; the rest of the\n * traffic is `event_callback` envelopes (or other future top-level types).\n */\nexport type SlackEventsRequest =\n { type: 'url_verification'; challenge: string; token?: string } | SlackEventCallback | { type: string; [key: string]: unknown };\n\n/**\n * Response Slack expects for the `url_verification` handshake. For\n * `event_callback` and unknown event types, the dispatcher returns\n * `undefined` and the caller should ack with HTTP 200.\n */\nexport type SlackEventsResponse = { challenge: string } | undefined;\n\n/**\n * Injectable map of command keyword (e.g. `/deploy`) → {@link SlackCommandHandler}.\n *\n * @example\n * ```ts\n * registry.register(DeployCommandHandler).useClass(DeployCommandHandler).asSingleton();\n *\n * registry\n * .register(SlackCommandHandlerMap)\n * .useMap(SlackCommandHandlerMap)\n * .set('/deploy', DeployCommandHandler);\n * ```\n */\n@Injectable()\nexport class SlackCommandHandlerMap extends Map<string, SlackCommandHandler> {}\n\n/**\n * Injectable map of Slack event type → {@link SlackEventHandler}. Consumers\n * register handlers at bootstrap and place an instance of this map in their\n * DI container; {@link SlackDispatcher.dispatchEvent} resolves it per request.\n *\n * @example\n * ```ts\n * registry.register(MyAppMentionHandler).useClass(MyAppMentionHandler).asSingleton();\n *\n * registry\n * .register(SlackEventHandlerMap)\n * .useMap(SlackEventHandlerMap)\n * .set('app_mention', MyAppMentionHandler);\n * ```\n */\n@Injectable()\nexport class SlackEventHandlerMap extends Map<string, SlackEventHandler> {}\n\n/**\n * Injectable map of interaction routing keys → {@link SlackInteractionHandler}.\n *\n * Keys are produced by `interactionRouteKey(payload)`, which combines the\n * payload `type` with the relevant identifier (`action_id`, `callback_id`,\n * etc.). Register handlers under the same key shape:\n *\n * @example\n * ```ts\n * registry.register(ApproveHandler).useClass(ApproveHandler).asSingleton();\n * registry.register(CreateTicketHandler).useClass(CreateTicketHandler).asSingleton();\n *\n * registry\n * .register(SlackInteractionHandlerMap)\n * .useMap(SlackInteractionHandlerMap)\n * .set('block_actions:approve_button', ApproveHandler)\n * .set('view_submission:create_ticket_modal', CreateTicketHandler);\n * ```\n */\n@Injectable()\nexport class SlackInteractionHandlerMap extends Map<string, SlackInteractionHandler> {}\n\n/**\n * Single entry point for dispatching parsed Slack payloads to registered\n * handlers. Transport-agnostic: the consumer is responsible for receiving\n * the HTTP request, verifying the signature, parsing the body, calling the\n * appropriate `dispatch*` method, and serializing the response.\n *\n * @example Koa route\n * ```ts\n * router.post('/slack/events', async (ctx) => {\n * const raw = await rawBody(ctx.req, { encoding: 'utf8' });\n * verifySlackSignature({\n * signingSecret: ctx.container.get(SlackConfig).signingSecret,\n * rawBody: raw,\n * timestamp: ctx.get('x-slack-request-timestamp'),\n * signature: ctx.get('x-slack-signature'),\n * });\n * const result = await ctx.container.get(SlackDispatcher).dispatchEvent(JSON.parse(raw));\n * if (result) ctx.body = result;\n * else { ctx.status = 200; ctx.body = ''; }\n * });\n * ```\n */\n@Injectable()\nexport class SlackDispatcher {\n constructor(\n private readonly events: SlackEventHandlerMap,\n private readonly commands: SlackCommandHandlerMap,\n private readonly interactions: SlackInteractionHandlerMap,\n private readonly logger: Logger,\n ) {}\n\n /**\n * Dispatch a parsed Events API body.\n *\n * - Returns `{ challenge }` for `url_verification` — the caller serializes\n * it as the response body. This handshake is NEVER de-duplicated: it must\n * always echo the challenge.\n * - For `event_callback`, looks up a handler in {@link SlackEventHandlerMap}\n * keyed by `event.type` and invokes it. Returns `undefined`. Slack retries\n * any non-2xx so unknown event types are logged at debug and acked.\n * - For any other top-level type, logs and returns `undefined`.\n *\n * Pass `options.idempotency` to de-duplicate `event_callback` deliveries: Slack\n * redelivers events (with an `X-Slack-Retry-Num` header) on a slow/failed ack,\n * so wrapping the handler in an {@link IdempotencyStore} keyed by\n * {@link slackEventIdempotencyKey} runs it at most once per `event_id`. A\n * `duplicate`/`dropped` outcome skips the handler and acks (returns `undefined`).\n * When `options.idempotency` is omitted, behaviour is unchanged.\n */\n async dispatchEvent(body: SlackEventsRequest, options?: { idempotency?: IdempotencyStore }): Promise<SlackEventsResponse> {\n if (body.type === 'url_verification') {\n return { challenge: (body as { challenge: string }).challenge };\n }\n\n if (body.type === 'event_callback') {\n const envelope = body as SlackEventCallback;\n const handleEvent = async (): Promise<void> => {\n const handler = this.events.get(envelope.event.type);\n if (handler) {\n await handler.handle(envelope.event, {\n teamId: envelope.team_id,\n eventId: envelope.event_id,\n eventTime: envelope.event_time,\n envelope,\n });\n } else {\n this.logger.debug('No Slack event handler registered for event type', { type: envelope.event.type });\n }\n };\n\n if (options?.idempotency) {\n const key = slackEventIdempotencyKey(envelope);\n const outcome = await options.idempotency.deduplicate(key, handleEvent);\n if (outcome.status === 'dropped') {\n this.logger.warn('Slack event dead-lettered after repeated failures', { key, attempts: outcome.attempts });\n }\n return undefined;\n }\n\n await handleEvent();\n return undefined;\n }\n\n this.logger.debug('Unhandled Slack events payload type', { type: body.type });\n return undefined;\n }\n\n /**\n * Dispatch a parsed slash-command payload.\n *\n * Looks up a handler in {@link SlackCommandHandlerMap} keyed by\n * `payload.command` (e.g. `/deploy`). If the handler returns a response,\n * the caller serializes it as JSON; otherwise the caller acks with `200 ''`\n * and the handler is expected to follow up via `payload.response_url`.\n */\n async dispatchCommand(payload: SlackCommandPayload): Promise<SlackCommandResponse | void> {\n const handler = this.commands.get(payload.command);\n if (!handler) {\n this.logger.debug('No Slack command handler registered', { command: payload.command });\n return undefined;\n }\n return await handler.handle(payload);\n }\n\n /**\n * Dispatch a parsed interactive payload (block actions, view submission,\n * shortcut, etc.). Computes a routing key via {@link interactionRouteKey}\n * and looks it up in {@link SlackInteractionHandlerMap}.\n */\n async dispatchInteraction(payload: SlackInteractionPayload): Promise<SlackInteractionResponse | void> {\n const key = interactionRouteKey(payload);\n if (!key) {\n this.logger.debug('Slack interaction payload missing routable identifier', { type: payload.type });\n return undefined;\n }\n const handler = this.interactions.get(key);\n if (!handler) {\n this.logger.debug('No Slack interaction handler registered', { key });\n return undefined;\n }\n return await handler.handle(payload);\n }\n}\n","import { Injectable } from 'injectkit';\nimport { WebClient } from '@slack/web-api';\nimport type {\n WebClientOptions,\n ChatPostMessageArguments,\n ChatPostMessageResponse,\n ChatUpdateArguments,\n ChatUpdateResponse,\n ChatDeleteArguments,\n ChatDeleteResponse,\n ViewsOpenArguments,\n ViewsOpenResponse,\n} from '@slack/web-api';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { SlackConfig } from '../slack.config.js';\nimport { SlackError } from '../slack.error.js';\nimport { adaptLogger } from './slack.logger.adapter.js';\n\n/** Default per-request timeout (ms) applied to outbound `postWebhook` calls. */\nexport const SLACK_DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\n/**\n * Redacts a Slack webhook / `response_url` so it is safe to log. The final path\n * segment is the secret token (and the query string can carry secrets too), so\n * both are stripped, leaving only the host and path prefix.\n */\nexport const redactSlackUrl = (raw: string): string => {\n try {\n const url = new URL(raw);\n const segments = url.pathname.split('/').filter(Boolean);\n if (segments.length > 0) segments[segments.length - 1] = '***';\n return `${url.origin}/${segments.join('/')}`;\n } catch {\n return '***';\n }\n};\n\n/**\n * Payload for an incoming-webhook POST. Mirrors the subset of fields Slack's\n * incoming webhooks accept (text, blocks, attachments, response shaping).\n * The body is JSON-stringified verbatim, so any extra fields are preserved.\n */\nexport type IncomingWebhookPayload = {\n text?: string;\n blocks?: unknown[];\n attachments?: unknown[];\n thread_ts?: string;\n response_type?: 'in_channel' | 'ephemeral';\n replace_original?: boolean;\n delete_original?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n [key: string]: unknown;\n};\n\n/**\n * Thin DI-friendly wrapper around `@slack/web-api`'s `WebClient`. Constructed\n * once per request scope (or as a singleton, depending on how the consumer\n * registers it) and exposes typed passthroughs for the most common Web API\n * methods plus a `postWebhook` helper for incoming-webhook URLs and the\n * `response_url` returned by slash commands and interactive payloads.\n *\n * Reach for {@link SlackClient.web} directly for anything else the underlying\n * client supports.\n *\n * @example\n * ```ts\n * await container.get(SlackClient).postMessage({ channel: '#ops', text: 'hello' });\n * await container.get(SlackClient).postWebhook({ text: 'follow-up' }, payload.response_url);\n * ```\n */\n@Injectable()\nexport class SlackClient {\n /** Underlying `@slack/web-api` client. */\n readonly web: WebClient;\n\n /** Web API client authenticated with the app token, built on first use by {@link openSocketModeUrl}. */\n private appWeb?: WebClient;\n\n constructor(\n private readonly config: SlackConfig,\n private readonly logger: Logger,\n ) {\n this.web = new WebClient(config.botToken, this.webClientOptions());\n }\n\n /** Options shared by every `WebClient` this class builds, passing only what the config sets. */\n private webClientOptions(): WebClientOptions {\n return {\n logger: adaptLogger(this.logger),\n ...(this.config.fetch ? { fetch: this.config.fetch } : {}),\n ...(this.config.apiBaseUrl ? { slackApiUrl: this.config.apiBaseUrl } : {}),\n ...(this.config.retries !== undefined ? { retryConfig: { retries: this.config.retries } } : {}),\n ...(this.config.rejectRateLimitedCalls !== undefined ? { rejectRateLimitedCalls: this.config.rejectRateLimitedCalls } : {}),\n };\n }\n\n /** Posts a message via `chat.postMessage`. */\n postMessage(args: ChatPostMessageArguments): Promise<ChatPostMessageResponse> {\n return this.web.chat.postMessage(args);\n }\n\n /** Updates a message via `chat.update`. */\n updateMessage(args: ChatUpdateArguments): Promise<ChatUpdateResponse> {\n return this.web.chat.update(args);\n }\n\n /** Deletes a message via `chat.delete`. */\n deleteMessage(args: ChatDeleteArguments): Promise<ChatDeleteResponse> {\n return this.web.chat.delete(args);\n }\n\n /** Opens a modal view via `views.open`. */\n openView(args: ViewsOpenArguments): Promise<ViewsOpenResponse> {\n return this.web.views.open(args);\n }\n\n /**\n * POSTs a payload to a Slack incoming-webhook-style URL — either the\n * configured `incomingWebhookUrl` or an explicit URL (e.g. the\n * `response_url` from a slash command or interactive payload).\n *\n * @throws {@link SlackError} if no URL is available or the response is non-2xx.\n */\n async postWebhook(payload: IncomingWebhookPayload, url?: string): Promise<void> {\n const target = url ?? this.config.incomingWebhookUrl;\n if (!target) {\n throw new SlackError('SlackClient.postWebhook called but no incomingWebhookUrl is configured and no url was provided');\n }\n // `target` is a response_url / incoming-webhook URL whose last path segment\n // is a secret — redact it before it reaches the log or internalDetails.\n const safeUrl = redactSlackUrl(target);\n const fetcher = this.config.fetch ?? fetch;\n\n let response: Awaited<ReturnType<typeof fetcher>>;\n try {\n response = await fetcher(target, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.config.requestTimeoutMs ?? SLACK_DEFAULT_REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n // Deliberately not `withCause(error)`: the cause's message can quote the URL, and the URL\n // holds the secret.\n const reason = (error instanceof Error ? error.message : String(error)).split(target).join(safeUrl);\n this.logger.warn('Slack webhook POST did not reach Slack', { url: safeUrl, reason });\n throw new SlackError('Slack webhook POST did not reach Slack').withInternalDetails({ url: safeUrl, reason });\n }\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n this.logger.warn('Slack webhook POST returned non-OK status', { status: response.status, body, url: safeUrl });\n throw new SlackError(`Slack webhook POST returned ${response.status}`).withInternalDetails({ status: response.status, body, url: safeUrl });\n }\n }\n\n /**\n * Opens a Socket Mode connection slot via `apps.connections.open` and returns the WebSocket URL\n * to connect to. Authenticates with `appToken`, not the bot token, over the same `fetch` and base\n * URL as every other call. Each URL is single-use, so call this again for every reconnect.\n *\n * @throws {@link SlackError} if `appToken` is not configured or Slack does not hand back a URL.\n */\n async openSocketModeUrl(): Promise<string> {\n const appToken = this.config.appToken;\n if (!appToken) {\n throw new SlackError('SlackClient.openSocketModeUrl called but no appToken (xapp-...) is configured');\n }\n this.appWeb ??= new WebClient(appToken, this.webClientOptions());\n\n let result: { ok?: boolean; url?: string; error?: string };\n try {\n result = await this.appWeb.apps.connections.open();\n } catch (error) {\n // The SDK throws on `ok: false`, carrying Slack's error code in `data.error`. Its errors do\n // not quote the token, but only the code and message are kept, to be safe.\n const code = (error as { data?: { error?: unknown } }).data?.error;\n const reason = error instanceof Error ? error.message.split(appToken).join('<token>') : String(error);\n this.logger.warn('Slack apps.connections.open failed', { error: code, reason });\n throw new SlackError('Slack apps.connections.open failed').withInternalDetails({ error: code, reason });\n }\n\n if (!result.ok || !result.url) {\n this.logger.warn('Slack apps.connections.open returned no URL', { error: result.error });\n throw new SlackError('Slack apps.connections.open returned no URL').withInternalDetails({ error: result.error });\n }\n return result.url;\n }\n}\n","import type { Logger as SlackLogger, LogLevel } from '@slack/web-api';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Adapts a ServerKit {@link Logger} to the `@slack/web-api` {@link SlackLogger}\n * interface so the WebClient can route its diagnostics through the host\n * application's logger.\n *\n * The Slack SDK's logger calls `logger.info(...args)` with a variable number\n * of arguments and no separate \"primary message\"; the adapter forwards them\n * to ServerKit's `(message, ...optionalParams)` shape, with an empty-string\n * primary when no args are passed.\n *\n * `setLevel`, `setName`, and `getLevel` are stored locally — ServerKit\n * loggers do not expose these knobs but the SDK expects them on its logger.\n *\n * @param logger - The ServerKit logger to forward calls to.\n * @param name - Initial value for the SDK logger's name. Defaults to `'slack-web-api'`.\n * @returns A `@slack/web-api`-compatible logger object.\n */\nexport const adaptLogger = (logger: Logger, name = 'slack-web-api'): SlackLogger => {\n const state = { name, level: 'info' as LogLevel };\n const forward =\n (fn: (message: unknown, ...optionalParams: unknown[]) => void) =>\n (...msg: unknown[]) => {\n const [first, ...rest] = msg;\n fn(first ?? '', ...rest);\n };\n return {\n debug: forward(logger.debug.bind(logger)),\n info: forward(logger.info.bind(logger)),\n warn: forward(logger.warn.bind(logger)),\n error: forward(logger.error.bind(logger)),\n setLevel: (level: LogLevel) => {\n state.level = level;\n },\n getLevel: () => state.level,\n setName: (n: string) => {\n state.name = n;\n },\n };\n};\n"],"mappings":";;;;;;;;;AACA,SAASA,kBAAkB;;;;;;;;AAoFpB,IAAeC,cAAf,MAAeA;SAAAA;;;AAAoC;;;;;;ACrF1D,SAASC,YAAYC,uBAAuB;AAC5C,SAASC,gBAAgB;AAIlB,IAAMC,0CAA0C;AAsEhD,IAAMC,uBAAuB,wBAACC,UAAAA;AACnC,QAAM,EACJC,eACAC,SACAC,WACAC,WACAC,gBAAgBP,yCAChBQ,MAAMC,KAAKC,MAAMC,SAASH,IAAG,EAAGI,UAAS,CAAA,EAAG,IAC1CV;AAEJ,MAAI,CAACC,eAAe;AAClB,UAAM,IAAIU,WAAW,gFAAA,EAAkFC,oBAAoB;MACzHC,QAAQ;IACV,CAAA;EACF;AAEA,MAAI,CAACV,WAAW;AACd,UAAM,IAAIQ,WAAW,wDAAA,EAA0DC,oBAAoB;MACjGC,QAAQ;IACV,CAAA;EACF;AAEA,QAAMC,KAAKC,OAAOZ,SAAAA;AAClB,MAAI,CAACY,OAAOC,SAASF,EAAAA,KAAO,CAACC,OAAOE,UAAUH,EAAAA,GAAK;AACjD,UAAM,IAAIH,WAAW,gDAAA,EAAkDC,oBAAoB;MACzFC,QAAQ;MACRV;IACF,CAAA;EACF;AAEA,MAAII,KAAKW,IAAIZ,MAAMQ,EAAAA,IAAMT,eAAe;AACtC,UAAM,IAAIM,WAAW,uDAAA,EAAyDC,oBAAoB;MAChGC,QAAQ;MACRV,WAAWW;MACXR;MACAD;IACF,CAAA;EACF;AAEA,MAAI,CAACD,WAAW;AACd,UAAM,IAAIO,WAAW,gDAAA,EAAkDC,oBAAoB;MACzFC,QAAQ;IACV,CAAA;EACF;AAKA,QAA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QAAQF,MAAMG,QAAQpD,MAAM6D,QAAAA,EAAUxD,KAAK,SAAA,IAAagD,OAAOJ,KAAAA;AAC/F,WAAKvC,OAAO4C,KAAK,sCAAsC;QAAEL,OAAOgB;QAAMf;MAAO,CAAA;AAC7E,YAAM,IAAId,WAAW,oCAAA,EAAsCmB,oBAAoB;QAAEN,OAAOgB;QAAMf;MAAO,CAAA;IACvG;AAEA,QAAI,CAACY,OAAON,MAAM,CAACM,OAAOlE,KAAK;AAC7B,WAAKc,OAAO4C,KAAK,+CAA+C;QAAEL,OAAOa,OAAOb;MAAM,CAAA;AACtF,YAAM,IAAIb,WAAW,6CAAA,EAA+CmB,oBAAoB;QAAEN,OAAOa,OAAOb;MAAM,CAAA;IAChH;AACA,WAAOa,OAAOlE;EAChB;AACF;;;;;;;;;","names":["Injectable","SlackConfig","createHmac","timingSafeEqual","DateTime","SLACK_SIGNATURE_DEFAULT_MAX_AGE_SECONDS","verifySlackSignature","input","signingSecret","rawBody","timestamp","signature","maxAgeSeconds","now","Math","floor","DateTime","toSeconds","SlackError","withInternalDetails","reason","ts","Number","isFinite","isInteger","abs","expected","createHmac","update","digest","expectedBuf","Buffer","from","providedBuf","length","timingSafeEqual","Injectable","Policy","SLACK_SIGNATURE_POLICY","SLACK_REQUEST_TIMESTAMP_HEADER","SLACK_SIGNATURE_HEADER","SlackSignaturePolicy","Policy","evaluate","context","envelope","rawBody","getHeader","options","body","Buffer","from","toString","verifySlackSignature","signingSecret","timestamp","signature","maxAgeSeconds","signatureMaxAgeSeconds","now","Math","floor","toSeconds","allow","error","IsSlackError","internalDetails","reason","deny","undefined","message","slackEventIdempotencyKey","envelope","team_id","event_id","interactionRouteKey","payload","type","id","actions","action_id","undefined","view","callback_id","Injectable","Logger","SlackCommandHandlerMap","Map","SlackEventHandlerMap","SlackInteractionHandlerMap","SlackDispatcher","events","commands","interactions","logger","dispatchEvent","body","options","type","challenge","envelope","handleEvent","handler","get","event","handle","teamId","team_id","eventId","event_id","eventTime","event_time","debug","idempotency","key","slackEventIdempotencyKey","outcome","deduplicate","status","warn","attempts","undefined","dispatchCommand","payload","command","dispatchInteraction","interactionRouteKey","Injectable","WebClient","Logger","adaptLogger","logger","name","state","level","forward","fn","msg","first","rest","debug","bind","info","warn","error","setLevel","getLevel","setName","n","SLACK_DEFAULT_REQUEST_TIMEOUT_MS","redactSlackUrl","raw","url","URL","segments","pathname","split","filter","Boolean","length","origin","join","SlackClient","web","appWeb","config","logger","WebClient","botToken","webClientOptions","adaptLogger","fetch","apiBaseUrl","slackApiUrl","retries","undefined","retryConfig","rejectRateLimitedCalls","postMessage","args","chat","updateMessage","update","deleteMessage","delete","openView","views","open","postWebhook","payload","target","incomingWebhookUrl","SlackError","safeUrl","fetcher","response","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","requestTimeoutMs","error","reason","Error","message","String","warn","withInternalDetails","ok","text","catch","status","openSocketModeUrl","appToken","result","apps","connections","code","data"]}
@@ -56,6 +56,21 @@ export interface SlackConfig {
56
56
  * timeout; an implementation that enforces its own deadline as well may ignore it.
57
57
  */
58
58
  fetch?: SlackFetch;
59
+ /**
60
+ * How many times the Web API client retries a call that failed: a transport error, a non-200, or
61
+ * a rate limit it waited out. Forwarded to `@slack/web-api` as `retryConfig: { retries }`.
62
+ * Defaults to the SDK's own policy, ten retries over about thirty minutes.
63
+ *
64
+ * Set `0` when the caller owns retrying (a job queue, or a host that abandons a call at its own
65
+ * deadline): the SDK's retries otherwise carry on in the background after the caller has given
66
+ * up, and can deliver a message long after it stopped being true.
67
+ */
68
+ retries?: number;
69
+ /**
70
+ * Reject a rate-limited Web API call with `WebAPIRateLimitedError` instead of pausing every call
71
+ * until Slack's `Retry-After` has passed. Forwarded as-is. Defaults to `false`, the SDK's own.
72
+ */
73
+ rejectRateLimitedCalls?: boolean;
59
74
  }
60
75
  /**
61
76
  * The `fetch` shape the client needs. It is `@slack/web-api`'s own `FetchFunction`, so one
@@ -1 +1 @@
1
- {"version":3,"file":"slack.config.d.ts","sourceRoot":"","sources":["../src/slack.config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,WAAW;IAC1B,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8FAA8F;IAC9F,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,aAAa,CAAC;AAEvC,8BACsB,WAAY,YAAW,WAAW;CAAG"}
1
+ {"version":3,"file":"slack.config.d.ts","sourceRoot":"","sources":["../src/slack.config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,WAAW;IAC1B,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8FAA8F;IAC9F,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,aAAa,CAAC;AAEvC,8BACsB,WAAY,YAAW,WAAW;CAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/slack",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "Slack utilities for ServerKit.",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -56,8 +56,8 @@
56
56
  "devDependencies": {
57
57
  "@types/luxon": "^3.7.5",
58
58
  "@maroonedsoftware/cache": "0.5.0",
59
- "@repo/config-eslint": "0.2.1",
60
59
  "@maroonedsoftware/comms": "0.2.11",
60
+ "@repo/config-eslint": "0.2.1",
61
61
  "@repo/config-typescript": "0.1.0"
62
62
  },
63
63
  "peerDependencies": {