@maroonedsoftware/slack 2.1.0 → 3.0.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
@@ -27,6 +27,7 @@ pnpm add @maroonedsoftware/slack
27
27
  | `verifySlackSignature(input)` | Pure helper that validates Slack's v0 HMAC scheme + replay window. No request/context coupling. |
28
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
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. |
30
31
 
31
32
  ## Configuration
32
33
 
@@ -135,6 +136,32 @@ router.post('/slack/events', async (ctx) => {
135
136
 
136
137
  `dispatchEvent` returns `{ challenge }` for the `url_verification` handshake and `undefined` for everything else (event handlers run for their side effects). Unregistered event types are logged at debug and acked — Slack retries any non-2xx, so dropping unknown events on the floor is intentional.
137
138
 
139
+ #### Handling redelivery
140
+
141
+ Slack redelivers an `event_callback` (with an `X-Slack-Retry-Num` header) whenever your ack is slow or non-2xx, so an event can be handled more than once. Two ways to make delivery idempotent, most-durable first:
142
+
143
+ **Recommended — validate, enqueue, ack.** Do the minimum in the request (verify + parse), then enqueue a job keyed by `event_id` and ack `200` immediately. Deduplication is the queue's job: `@maroonedsoftware/jobbroker` maps to pg-boss's `singletonKey`, so enqueuing the same `event_id` twice collapses to one job that runs once, outside the request path.
144
+
145
+ ```ts
146
+ // Inside the route, after verifying the signature and parsing the body:
147
+ const body = JSON.parse(raw);
148
+ if (body.type === 'url_verification') { ctx.body = { challenge: body.challenge }; return; }
149
+ if (body.type === 'event_callback') {
150
+ await jobBroker.send('slack.event', body, { singletonKey: slackEventIdempotencyKey(body) });
151
+ }
152
+ ctx.status = 200; ctx.body = ''; // ack fast; a worker calls dispatchEvent later
153
+ ```
154
+
155
+ **Edge dedup — one store, one arg.** When you'd rather handle events inline, pass an `IdempotencyStore` and `dispatchEvent` runs the handler at most once per `event_id` (keyed by `slackEventIdempotencyKey`). A duplicate/dropped redelivery skips the handler and acks. Omit the option and behaviour is unchanged. The `url_verification` handshake is never de-duplicated.
156
+
157
+ ```ts
158
+ import { IdempotencyStore } from '@maroonedsoftware/cache';
159
+
160
+ const result = await ctx.container.get(SlackDispatcher).dispatchEvent(JSON.parse(raw), {
161
+ idempotency: ctx.container.get(IdempotencyStore),
162
+ });
163
+ ```
164
+
138
165
  ### Slash commands
139
166
 
140
167
  ```ts
package/dist/index.js CHANGED
@@ -115,6 +115,12 @@ SlackSignaturePolicy = _ts_decorate2([
115
115
  Injectable2()
116
116
  ], SlackSignaturePolicy);
117
117
 
118
+ // src/slack.event.handler.ts
119
+ function slackEventIdempotencyKey(envelope) {
120
+ return envelope.team_id ? `slack:event:${envelope.team_id}:${envelope.event_id}` : `slack:event:${envelope.event_id}`;
121
+ }
122
+ __name(slackEventIdempotencyKey, "slackEventIdempotencyKey");
123
+
118
124
  // src/slack.interaction.handler.ts
119
125
  var interactionRouteKey = /* @__PURE__ */ __name((payload) => {
120
126
  switch (payload.type) {
@@ -193,13 +199,21 @@ var SlackDispatcher = class {
193
199
  * Dispatch a parsed Events API body.
194
200
  *
195
201
  * - Returns `{ challenge }` for `url_verification` — the caller serializes
196
- * it as the response body.
202
+ * it as the response body. This handshake is NEVER de-duplicated: it must
203
+ * always echo the challenge.
197
204
  * - For `event_callback`, looks up a handler in {@link SlackEventHandlerMap}
198
205
  * keyed by `event.type` and invokes it. Returns `undefined`. Slack retries
199
206
  * any non-2xx so unknown event types are logged at debug and acked.
200
207
  * - For any other top-level type, logs and returns `undefined`.
208
+ *
209
+ * Pass `options.idempotency` to de-duplicate `event_callback` deliveries: Slack
210
+ * redelivers events (with an `X-Slack-Retry-Num` header) on a slow/failed ack,
211
+ * so wrapping the handler in an {@link IdempotencyStore} keyed by
212
+ * {@link slackEventIdempotencyKey} runs it at most once per `event_id`. A
213
+ * `duplicate`/`dropped` outcome skips the handler and acks (returns `undefined`).
214
+ * When `options.idempotency` is omitted, behaviour is unchanged.
201
215
  */
202
- async dispatchEvent(body) {
216
+ async dispatchEvent(body, options) {
203
217
  if (body.type === "url_verification") {
204
218
  return {
205
219
  challenge: body.challenge
@@ -207,19 +221,33 @@ var SlackDispatcher = class {
207
221
  }
208
222
  if (body.type === "event_callback") {
209
223
  const envelope = body;
210
- const handler = this.events.get(envelope.event.type);
211
- if (handler) {
212
- await handler.handle(envelope.event, {
213
- teamId: envelope.team_id,
214
- eventId: envelope.event_id,
215
- eventTime: envelope.event_time,
216
- envelope
217
- });
218
- } else {
219
- this.logger.debug("No Slack event handler registered for event type", {
220
- type: envelope.event.type
221
- });
224
+ const handleEvent = /* @__PURE__ */ __name(async () => {
225
+ const handler = this.events.get(envelope.event.type);
226
+ if (handler) {
227
+ await handler.handle(envelope.event, {
228
+ teamId: envelope.team_id,
229
+ eventId: envelope.event_id,
230
+ eventTime: envelope.event_time,
231
+ envelope
232
+ });
233
+ } else {
234
+ this.logger.debug("No Slack event handler registered for event type", {
235
+ type: envelope.event.type
236
+ });
237
+ }
238
+ }, "handleEvent");
239
+ if (options?.idempotency) {
240
+ const key = slackEventIdempotencyKey(envelope);
241
+ const outcome = await options.idempotency.deduplicate(key, handleEvent);
242
+ if (outcome.status === "dropped") {
243
+ this.logger.warn("Slack event dead-lettered after repeated failures", {
244
+ key,
245
+ attempts: outcome.attempts
246
+ });
247
+ }
248
+ return void 0;
222
249
  }
250
+ await handleEvent();
223
251
  return void 0;
224
252
  }
225
253
  this.logger.debug("Unhandled Slack events payload type", {
@@ -425,6 +453,7 @@ export {
425
453
  adaptLogger,
426
454
  interactionRouteKey,
427
455
  redactSlackUrl,
456
+ slackEventIdempotencyKey,
428
457
  verifySlackSignature
429
458
  };
430
459
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/slack.config.ts","../src/slack.error.ts","../src/slack.signature.ts","../src/slack.signature.policy.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';\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 * container.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 /** App-level signing secret used to verify request signatures. */\n signingSecret: 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\n@Injectable()\nexport abstract class SlackConfig implements SlackConfig {}\n","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Domain error raised by the Slack package for non-HTTP failures (e.g.\n * incoming-webhook POST failed, unknown handler dispatch).\n *\n * Extends {@link ServerkitError} so `errorMiddleware` renders a 500 with\n * `{ message, details }` if one of these escapes a route handler. Inside\n * route handlers, throw `httpError(...)` directly for status-coded responses.\n */\nexport class SlackError extends ServerkitError {}\n\n/**\n * Type guard for {@link SlackError}. Narrows `unknown` to `SlackError` so\n * `details`, `internalDetails`, and the chainable setters are accessible\n * without further checks. Returns `true` for any subclass.\n */\nexport const IsSlackError = (error: unknown): error is SlackError => error instanceof SlackError;\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_timestamp'\n | 'invalid_timestamp'\n | 'stale_timestamp'\n | 'missing_signature'\n | '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 /** App signing secret (`SlackConfig.signingSecret`). */\n signingSecret: string;\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 (!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 = 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 * 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 { 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 }\n | SlackEventCallback\n | { 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 * const commands = new SlackCommandHandlerMap();\n * commands.set('/deploy', container.get(DeployCommandHandler));\n * container.register(SlackCommandHandlerMap, { useValue: commands });\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 * const handlers = new SlackEventHandlerMap();\n * handlers.set('app_mention', container.get(MyAppMentionHandler));\n * container.register(SlackEventHandlerMap, { useValue: handlers });\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 * const interactions = new SlackInteractionHandlerMap();\n * interactions.set('block_actions:approve_button', container.get(ApproveHandler));\n * interactions.set('view_submission:create_ticket_modal', container.get(CreateTicketHandler));\n * container.register(SlackInteractionHandlerMap, { useValue: interactions });\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.\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 async dispatchEvent(body: SlackEventsRequest): 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 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 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 { ChatPostMessageArguments, ChatPostMessageResponse, ChatUpdateArguments, ChatUpdateResponse, ChatDeleteArguments, ChatDeleteResponse, ViewsOpenArguments, ViewsOpenResponse } 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 constructor(\n private readonly config: SlackConfig,\n private readonly logger: Logger,\n ) {\n this.web = new WebClient(config.botToken, { logger: adaptLogger(logger) });\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 const response = await fetch(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 if (!response.ok) {\n const body = await response.text().catch(() => '');\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 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","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 = (fn: (message: unknown, ...optionalParams: unknown[]) => void) => (...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;;;;;;;;AAsCpB,IAAeC,cAAf,MAAeA;SAAAA;;;AAAoC;;;;;;ACvC1D,SAASC,sBAAsB;AAUxB,IAAMC,aAAN,cAAyBC,eAAAA;EAVhC,OAUgCA;;;AAAgB;AAOzC,IAAMC,eAAe,wBAACC,UAAwCA,iBAAiBH,YAA1D;;;ACjB5B,SAASI,YAAYC,uBAAuB;AAC5C,SAASC,gBAAgB;AAIlB,IAAMC,0CAA0C;AAsEhD,IAAMC,uBAAuB,wBAACC,UAAAA;AACnC,QAAM,EACJC,eACAC,SACAC,WACAC,WACAC,gBAAgBP,yCAChBQ,MAAMC,KAAKC,MA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AAK,6CAA6C;QAAEC,QAAQhB,SAASgB;QAAQZ;QAAMpC,KAAK8C;MAAQ,CAAA;AAC5G,YAAM,IAAIf,WAAW,+BAA+BC,SAASgB,MAAM,EAAE,EAAEC,oBAAoB;QAAED,QAAQhB,SAASgB;QAAQZ;QAAMpC,KAAK8C;MAAQ,CAAA;IAC3I;EACF;AACF;;;;;;;;;","names":["Injectable","SlackConfig","ServerkitError","SlackError","ServerkitError","IsSlackError","error","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","interactionRouteKey","payload","type","id","actions","action_id","undefined","view","callback_id","Injectable","Logger","SlackCommandHandlerMap","Map","SlackEventHandlerMap","SlackInteractionHandlerMap","SlackDispatcher","events","commands","interactions","logger","dispatchEvent","body","type","challenge","envelope","handler","get","event","handle","teamId","team_id","eventId","event_id","eventTime","event_time","debug","undefined","dispatchCommand","payload","command","dispatchInteraction","key","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","config","logger","WebClient","botToken","adaptLogger","postMessage","args","chat","updateMessage","update","deleteMessage","delete","openView","views","open","postWebhook","payload","target","incomingWebhookUrl","SlackError","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","requestTimeoutMs","ok","text","catch","safeUrl","warn","status","withInternalDetails"]}
1
+ {"version":3,"sources":["../src/slack.config.ts","../src/slack.error.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';\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 * container.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 /** App-level signing secret used to verify request signatures. */\n signingSecret: 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\n@Injectable()\nexport abstract class SlackConfig implements SlackConfig {}\n","import { ServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Domain error raised by the Slack package for non-HTTP failures (e.g.\n * incoming-webhook POST failed, unknown handler dispatch).\n *\n * Extends {@link ServerkitError} so `errorMiddleware` renders a 500 with\n * `{ message, details }` if one of these escapes a route handler. Inside\n * route handlers, throw `httpError(...)` directly for status-coded responses.\n */\nexport class SlackError extends ServerkitError {}\n\n/**\n * Type guard for {@link SlackError}. Narrows `unknown` to `SlackError` so\n * `details`, `internalDetails`, and the chainable setters are accessible\n * without further checks. Returns `true` for any subclass.\n */\nexport const IsSlackError = (error: unknown): error is SlackError => error instanceof SlackError;\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_timestamp'\n | 'invalid_timestamp'\n | 'stale_timestamp'\n | 'missing_signature'\n | '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 /** App signing secret (`SlackConfig.signingSecret`). */\n signingSecret: string;\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 (!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 = 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 }\n | SlackEventCallback\n | { 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 * const commands = new SlackCommandHandlerMap();\n * commands.set('/deploy', container.get(DeployCommandHandler));\n * container.register(SlackCommandHandlerMap, { useValue: commands });\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 * const handlers = new SlackEventHandlerMap();\n * handlers.set('app_mention', container.get(MyAppMentionHandler));\n * container.register(SlackEventHandlerMap, { useValue: handlers });\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 * const interactions = new SlackInteractionHandlerMap();\n * interactions.set('block_actions:approve_button', container.get(ApproveHandler));\n * interactions.set('view_submission:create_ticket_modal', container.get(CreateTicketHandler));\n * container.register(SlackInteractionHandlerMap, { useValue: interactions });\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 { ChatPostMessageArguments, ChatPostMessageResponse, ChatUpdateArguments, ChatUpdateResponse, ChatDeleteArguments, ChatDeleteResponse, ViewsOpenArguments, ViewsOpenResponse } 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 constructor(\n private readonly config: SlackConfig,\n private readonly logger: Logger,\n ) {\n this.web = new WebClient(config.botToken, { logger: adaptLogger(logger) });\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 const response = await fetch(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 if (!response.ok) {\n const body = await response.text().catch(() => '');\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 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","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 = (fn: (message: unknown, ...optionalParams: unknown[]) => void) => (...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;;;;;;;;AAsCpB,IAAeC,cAAf,MAAeA;SAAAA;;;AAAoC;;;;;;ACvC1D,SAASC,sBAAsB;AAUxB,IAAMC,aAAN,cAAyBC,eAAAA;EAVhC,OAUgCA;;;AAAgB;AAOzC,IAAMC,eAAe,wBAACC,UAAwCA,iBAAiBH,YAA1D;;;ACjB5B,SAASI,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,CAACG,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,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OAAOkC,KAAK,6CAA6C;QAAEC,QAAQhB,SAASgB;QAAQZ;QAAMpC,KAAK8C;MAAQ,CAAA;AAC5G,YAAM,IAAIf,WAAW,+BAA+BC,SAASgB,MAAM,EAAE,EAAEC,oBAAoB;QAAED,QAAQhB,SAASgB;QAAQZ;QAAMpC,KAAK8C;MAAQ,CAAA;IAC3I;EACF;AACF;;;;;;;;;","names":["Injectable","SlackConfig","ServerkitError","SlackError","ServerkitError","IsSlackError","error","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","config","logger","WebClient","botToken","adaptLogger","postMessage","args","chat","updateMessage","update","deleteMessage","delete","openView","views","open","postWebhook","payload","target","incomingWebhookUrl","SlackError","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","requestTimeoutMs","ok","text","catch","safeUrl","warn","status","withInternalDetails"]}
@@ -1,4 +1,5 @@
1
1
  import { Logger } from '@maroonedsoftware/logger';
2
+ import type { IdempotencyStore } from '@maroonedsoftware/cache';
2
3
  import type { SlackEventCallback, SlackEventHandler } from './slack.event.handler.js';
3
4
  import type { SlackCommandHandler, SlackCommandPayload, SlackCommandResponse } from './slack.command.handler.js';
4
5
  import { SlackInteractionHandler, type SlackInteractionPayload, type SlackInteractionResponse } from './slack.interaction.handler.js';
@@ -98,13 +99,23 @@ export declare class SlackDispatcher {
98
99
  * Dispatch a parsed Events API body.
99
100
  *
100
101
  * - Returns `{ challenge }` for `url_verification` — the caller serializes
101
- * it as the response body.
102
+ * it as the response body. This handshake is NEVER de-duplicated: it must
103
+ * always echo the challenge.
102
104
  * - For `event_callback`, looks up a handler in {@link SlackEventHandlerMap}
103
105
  * keyed by `event.type` and invokes it. Returns `undefined`. Slack retries
104
106
  * any non-2xx so unknown event types are logged at debug and acked.
105
107
  * - For any other top-level type, logs and returns `undefined`.
108
+ *
109
+ * Pass `options.idempotency` to de-duplicate `event_callback` deliveries: Slack
110
+ * redelivers events (with an `X-Slack-Retry-Num` header) on a slow/failed ack,
111
+ * so wrapping the handler in an {@link IdempotencyStore} keyed by
112
+ * {@link slackEventIdempotencyKey} runs it at most once per `event_id`. A
113
+ * `duplicate`/`dropped` outcome skips the handler and acks (returns `undefined`).
114
+ * When `options.idempotency` is omitted, behaviour is unchanged.
106
115
  */
107
- dispatchEvent(body: SlackEventsRequest): Promise<SlackEventsResponse>;
116
+ dispatchEvent(body: SlackEventsRequest, options?: {
117
+ idempotency?: IdempotencyStore;
118
+ }): Promise<SlackEventsResponse>;
108
119
  /**
109
120
  * Dispatch a parsed slash-command payload.
110
121
  *
@@ -1 +1 @@
1
- {"version":3,"file":"slack.dispatcher.d.ts","sourceRoot":"","sources":["../src/slack.dispatcher.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAClD,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AACtF,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACjH,OAAO,EAEL,uBAAuB,EACvB,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,EAC9B,MAAM,gCAAgC,CAAC;AAExC;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAC1B;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAC/D,kBAAkB,GAClB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC;AAE7C;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;GASG;AACH,qBACa,sBAAuB,SAAQ,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC;CAAG;AAE/E;;;;;;;;;;;GAWG;AACH,qBACa,oBAAqB,SAAQ,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC;CAAG;AAE3E;;;;;;;;;;;;;;GAcG;AACH,qBACa,0BAA2B,SAAQ,GAAG,CAAC,MAAM,EAAE,uBAAuB,CAAC;CAAG;AAEvF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBACa,eAAe;IAExB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,Q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IG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;GASG;AACH,qBACa,sBAAuB,SAAQ,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC;CAAG;AAE/E;;;;;;;;;;;GAWG;AACH,qBACa,oBAAqB,SAAQ,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC;CAAG;AAE3E;;;;;;;;;;;;;;GAcG;AACH,qBACa,0BAA2B,SAAQ,GAAG,CAAC,MAAM,EAAE,uBAAuB,CAAC;CAAG;AAEvF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBACa,eAAe;IAExB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAHN,MAAM,EAAE,oBAAoB,EAC5B,QAAQ,EAAE,sBAAsB,EAChC,YAAY,EAAE,0BAA0B,EACxC,MAAM,EAAE,MAAM;IAGjC;;;;;;;;;;;;;;;;;OAiBG;IACG,aAAa,CAAC,IAAI,EAAE,kBAAkB,EAAE,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,gBAAgB,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAsCzH;;;;;;;OAOG;IACG,eAAe,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IASzF;;;;OAIG;IACG,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;CAatG"}
@@ -33,6 +33,18 @@ export type SlackEventCallback = {
33
33
  event_context?: string;
34
34
  [key: string]: unknown;
35
35
  };
36
+ /**
37
+ * Derive a stable, collision-free idempotency key for a Slack event delivery.
38
+ *
39
+ * Slack redelivers an `event_callback` (with an `X-Slack-Retry-Num` header) when
40
+ * the initial ack is slow or non-2xx. The assigned `event_id` is stable across
41
+ * those redeliveries, so it keys de-duplication. We scope it by `team_id` where
42
+ * present so ids from different workspaces can never collide.
43
+ *
44
+ * @param envelope - The `event_callback` envelope (only `event_id` / `team_id` are read).
45
+ * @returns `slack:event:{team_id}:{event_id}`, or `slack:event:{event_id}` when no team id.
46
+ */
47
+ export declare function slackEventIdempotencyKey(envelope: Pick<SlackEventCallback, 'event_id' | 'team_id'>): string;
36
48
  /**
37
49
  * Handler for a single Slack event type (e.g. `app_mention`, `message`,
38
50
  * `reaction_added`). Registered in {@link SlackEventHandlerMap}.
@@ -1 +1 @@
1
- {"version":3,"file":"slack.event.handler.d.ts","sourceRoot":"","sources":["../src/slack.event.handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAC;IAChB,8CAA8C;IAC9C,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,EAAE,kBAAkB,CAAC;CAC9B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,gBAAgB,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,OAAO,EAAE,CAAC;IAC3B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF;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G,SAAS,CAAC,GAAG,MAAM,CAE3G;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB,CAAC,MAAM,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACvI,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/slack",
3
- "version": "2.1.0",
3
+ "version": "3.0.0",
4
4
  "description": "Slack utilities for ServerKit.",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -44,20 +44,25 @@
44
44
  "@slack/web-api": "^7.18.0",
45
45
  "injectkit": "^1.6.0",
46
46
  "luxon": "^3.7.2",
47
- "@maroonedsoftware/logger": "1.1.3",
48
47
  "@maroonedsoftware/errors": "1.8.0",
48
+ "@maroonedsoftware/logger": "1.1.3",
49
49
  "@maroonedsoftware/policies": "0.5.3"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/luxon": "^3.7.2",
53
+ "@maroonedsoftware/cache": "0.4.0",
53
54
  "@maroonedsoftware/comms": "0.2.3",
54
55
  "@repo/config-eslint": "0.2.1",
55
56
  "@repo/config-typescript": "0.1.0"
56
57
  },
57
58
  "peerDependencies": {
59
+ "@maroonedsoftware/cache": "0.4.0",
58
60
  "@maroonedsoftware/comms": "0.2.3"
59
61
  },
60
62
  "peerDependenciesMeta": {
63
+ "@maroonedsoftware/cache": {
64
+ "optional": true
65
+ },
61
66
  "@maroonedsoftware/comms": {
62
67
  "optional": true
63
68
  }