@effect/chat-slack 0.0.0 → 4.1.5

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.
Files changed (182) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +47 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/SlackChat.d.ts +500 -0
  88. package/dist/SlackChat.d.ts.map +1 -0
  89. package/dist/SlackChat.js +512 -0
  90. package/dist/SlackChat.js.map +1 -0
  91. package/dist/SlackWebApi.d.ts +74 -0
  92. package/dist/SlackWebApi.d.ts.map +1 -0
  93. package/dist/SlackWebApi.js +96 -0
  94. package/dist/SlackWebApi.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +169 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +836 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +36 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/emoji.d.ts +2 -0
  112. package/dist/internal/emoji.d.ts.map +1 -0
  113. package/dist/internal/emoji.js +207 -0
  114. package/dist/internal/emoji.js.map +1 -0
  115. package/dist/internal/emojiData.d.ts +54 -0
  116. package/dist/internal/emojiData.d.ts.map +1 -0
  117. package/dist/internal/emojiData.js +1965 -0
  118. package/dist/internal/emojiData.js.map +1 -0
  119. package/dist/internal/errors.d.ts +2 -0
  120. package/dist/internal/errors.d.ts.map +1 -0
  121. package/dist/internal/errors.js +190 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/escape.d.ts +14 -0
  124. package/dist/internal/escape.d.ts.map +1 -0
  125. package/dist/internal/escape.js +413 -0
  126. package/dist/internal/escape.js.map +1 -0
  127. package/dist/internal/interactions.d.ts +2 -0
  128. package/dist/internal/interactions.d.ts.map +1 -0
  129. package/dist/internal/interactions.js +389 -0
  130. package/dist/internal/interactions.js.map +1 -0
  131. package/dist/internal/json.d.ts +2 -0
  132. package/dist/internal/json.d.ts.map +1 -0
  133. package/dist/internal/json.js +30 -0
  134. package/dist/internal/json.js.map +1 -0
  135. package/dist/internal/length.d.ts +2 -0
  136. package/dist/internal/length.d.ts.map +1 -0
  137. package/dist/internal/length.js +33 -0
  138. package/dist/internal/length.js.map +1 -0
  139. package/dist/internal/mentions.d.ts +2 -0
  140. package/dist/internal/mentions.d.ts.map +1 -0
  141. package/dist/internal/mentions.js +229 -0
  142. package/dist/internal/mentions.js.map +1 -0
  143. package/dist/internal/normalize.d.ts +2 -0
  144. package/dist/internal/normalize.d.ts.map +1 -0
  145. package/dist/internal/normalize.js +211 -0
  146. package/dist/internal/normalize.js.map +1 -0
  147. package/dist/internal/options.d.ts +2 -0
  148. package/dist/internal/options.d.ts.map +1 -0
  149. package/dist/internal/options.js +6 -0
  150. package/dist/internal/options.js.map +1 -0
  151. package/dist/internal/richText.d.ts +2 -0
  152. package/dist/internal/richText.d.ts.map +1 -0
  153. package/dist/internal/richText.js +346 -0
  154. package/dist/internal/richText.js.map +1 -0
  155. package/dist/internal/text.d.ts +2 -0
  156. package/dist/internal/text.d.ts.map +1 -0
  157. package/dist/internal/text.js +239 -0
  158. package/dist/internal/text.js.map +1 -0
  159. package/dist/internal/webhook.d.ts +2 -0
  160. package/dist/internal/webhook.d.ts.map +1 -0
  161. package/dist/internal/webhook.js +142 -0
  162. package/dist/internal/webhook.js.map +1 -0
  163. package/package.json +62 -1
  164. package/src/SlackChat.ts +640 -0
  165. package/src/SlackWebApi.ts +135 -0
  166. package/src/index.ts +18 -0
  167. package/src/internal/actions.ts +203 -0
  168. package/src/internal/adapter.ts +961 -0
  169. package/src/internal/address.ts +50 -0
  170. package/src/internal/emoji.ts +223 -0
  171. package/src/internal/emojiData.ts +1965 -0
  172. package/src/internal/errors.ts +192 -0
  173. package/src/internal/escape.ts +428 -0
  174. package/src/internal/interactions.ts +391 -0
  175. package/src/internal/json.ts +35 -0
  176. package/src/internal/length.ts +41 -0
  177. package/src/internal/mentions.ts +224 -0
  178. package/src/internal/normalize.ts +221 -0
  179. package/src/internal/options.ts +22 -0
  180. package/src/internal/richText.ts +367 -0
  181. package/src/internal/text.ts +252 -0
  182. package/src/internal/webhook.ts +199 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * The `text` the adapter sends beside a `markdown` block on
3
+ * `chat.postMessage` and `chat.update`. Slack decides who a message
4
+ * mentions from this field, not from the blocks, so the adapter always
5
+ * builds it itself: Slack's own would carry every token intact.
6
+ */
7
+ import type { Action } from "effect/chat/ChatUi"
8
+ import * as Actions from "./actions.ts"
9
+ import * as Escape from "./escape.ts"
10
+ import { codePoints } from "./length.ts"
11
+ import { escapeMarkdown } from "./richText.ts"
12
+
13
+ /**
14
+ * The budget for `text` on `chat.postMessage`, in code points. Slack cuts a
15
+ * longer one there without an error, and the cut can split an entity or a
16
+ * token.
17
+ *
18
+ * @internal
19
+ */
20
+ export const postTextLength = 16_000
21
+
22
+ /**
23
+ * The budget for `text` on `chat.update`, in UTF-8 bytes. Slack refuses a
24
+ * `text` over 4,000 bytes with `msg_too_long`.
25
+ *
26
+ * Provisional: whether Slack checks the 4,000 before or after it rewrites the
27
+ * text (it wraps a URL in `<…>`) is not known yet, so this keeps a reserve.
28
+ *
29
+ * @internal
30
+ */
31
+ export const updateTextBytes = 3_800
32
+
33
+ /** @internal */
34
+ export interface Budget {
35
+ readonly unit: "codePoints" | "utf8"
36
+ readonly limit: number
37
+ }
38
+
39
+ /** @internal */
40
+ export const postBudget: Budget = { unit: "codePoints", limit: postTextLength }
41
+
42
+ /** @internal */
43
+ export const updateBudget: Budget = { unit: "utf8", limit: updateTextBytes }
44
+
45
+ /** @internal */
46
+ export const utf8Bytes = (text: string): number => {
47
+ let count = 0
48
+ for (let i = 0; i < text.length; i++) {
49
+ const code = text.charCodeAt(i)
50
+ if (code < 0x80) count += 1
51
+ else if (code < 0x800) count += 2
52
+ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
53
+ const low = text.charCodeAt(i + 1)
54
+ if (low >= 0xdc00 && low <= 0xdfff) {
55
+ count += 4
56
+ i++
57
+ } else {
58
+ count += 3
59
+ }
60
+ } else {
61
+ // A lone surrogate goes out as U+FFFD, which is three bytes too.
62
+ count += 3
63
+ }
64
+ }
65
+ return count
66
+ }
67
+
68
+ /** @internal */
69
+ export const cost = (text: string, unit: Budget["unit"]): number => unit === "utf8" ? utf8Bytes(text) : codePoints(text)
70
+
71
+ const marker = "…"
72
+ const separator = " "
73
+
74
+ let segmenter: Intl.Segmenter | undefined
75
+
76
+ const entity = /&(?:lt|gt|amp);/g
77
+
78
+ /** @internal */
79
+ export interface Built {
80
+ readonly text: string
81
+ /** Allowed tokens that a cut had no room for. */
82
+ readonly dropped: number
83
+ }
84
+
85
+ /**
86
+ * Builds the `text` for a Markdown body and cuts it to `budget`.
87
+ *
88
+ * - Every `<`, `>` and `&` is an entity, in code too. The tokens the notify
89
+ * options allow, outside code, stay intact, as they do in the block.
90
+ * - Past the budget, the text is cut on a grapheme cluster boundary that
91
+ * splits no entity and no token, and ends in `…`. Each allowed token not
92
+ * in the kept part is appended once, in order, after a space. The marker
93
+ * and the spaces come out of the budget.
94
+ * - When the tokens alone don't fit, those that fit are kept and the rest
95
+ * counted in `dropped`.
96
+ *
97
+ * @internal
98
+ */
99
+ export const build = (markdown: string, notify: Escape.Notify, budget: Budget): Built => {
100
+ const spans: Array<readonly [number, number]> = []
101
+ const text = Escape.escape(markdown, notify, {
102
+ flush: true,
103
+ entities: true,
104
+ onToken: (start, end) => spans.push([start, end])
105
+ }).sent
106
+ const tokens = spans.map(([start, end]) => text.slice(start, end))
107
+ if (cost(text, budget.unit) <= budget.limit) return { text, dropped: 0 }
108
+
109
+ // Offsets inside an entity or a token, where no cut may fall.
110
+ const inside = new Uint8Array(text.length + 1)
111
+ const atomic = (start: number, end: number) => inside.fill(1, start + 1, end)
112
+ for (const [start, end] of spans) atomic(start, end)
113
+ entity.lastIndex = 0
114
+ for (let match = entity.exec(text); match !== null; match = entity.exec(text)) {
115
+ atomic(match.index, match.index + match[0].length)
116
+ }
117
+
118
+ // The tail is the marker plus each distinct token not yet in the head.
119
+ const distinct = [...new Set(tokens)]
120
+ const unit = budget.unit
121
+ const tokenCost = (token: string) => cost(separator + token, unit)
122
+ let tail = cost(marker, unit)
123
+ for (const token of distinct) tail += tokenCost(token)
124
+
125
+ // Every code point boundary outside an entity or a token where the head
126
+ // and the tail fit, from the start until the head alone is over.
127
+ const candidates: Array<number> = []
128
+ const inHead = new Set<string>()
129
+ let head = 0
130
+ let span = 0
131
+ let i = 0
132
+ for (;;) {
133
+ for (; span < spans.length && spans[span][1] <= i; span++) {
134
+ const token = tokens[span]
135
+ if (!inHead.has(token)) {
136
+ inHead.add(token)
137
+ tail -= tokenCost(token)
138
+ }
139
+ }
140
+ if (inside[i] === 0 && head + tail <= budget.limit) candidates.push(i)
141
+ if (i >= text.length) break
142
+ const code = text.charCodeAt(i)
143
+ const pair = code >= 0xd800 && code <= 0xdbff && i + 1 < text.length &&
144
+ text.charCodeAt(i + 1) >= 0xdc00 && text.charCodeAt(i + 1) <= 0xdfff
145
+ // A lone surrogate goes out as U+FFFD, three bytes.
146
+ head += unit === "codePoints" ? 1 : pair ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3
147
+ i += pair ? 2 : 1
148
+ if (head > budget.limit) break
149
+ }
150
+
151
+ // The last of them on a grapheme cluster boundary.
152
+ segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" })
153
+ let best = -1
154
+ let candidate = 0
155
+ // Iterate boundaries: Bun's containing() reports incorrect offsets for astral text.
156
+ for (const { index } of segmenter.segment(text)) {
157
+ while (candidate < candidates.length && candidates[candidate] < index) candidate++
158
+ if (candidate === candidates.length) break
159
+ if (candidates[candidate] === index) best = index
160
+ }
161
+
162
+ if (best >= 0) {
163
+ const kept = text.slice(0, best)
164
+ let out = kept + marker
165
+ for (const token of distinct) if (!kept.includes(token)) out += separator + token
166
+ return { text: out, dropped: 0 }
167
+ }
168
+ // Not even the tokens fit: keep those that do, in order.
169
+ let out = marker
170
+ let used = cost(marker, unit)
171
+ let dropped = 0
172
+ for (const token of distinct) {
173
+ const extra = tokenCost(token)
174
+ if (used + extra <= budget.limit) {
175
+ out += separator + token
176
+ used += extra
177
+ } else {
178
+ dropped++
179
+ }
180
+ }
181
+ return { text: out, dropped }
182
+ }
183
+
184
+ /** @internal */
185
+ export interface Body {
186
+ /** The Markdown as sent in the block, for the length check. */
187
+ readonly sent: string
188
+ readonly blocks: ReadonlyArray<unknown>
189
+ readonly text: string
190
+ readonly dropped: number
191
+ }
192
+
193
+ /**
194
+ * The content of a `chat.postMessage` or `chat.update`: the Markdown as one
195
+ * `markdown` block, escaped as `markdown_text` was, then the elements as
196
+ * one `actions` block, and the `text` from `build`.
197
+ *
198
+ * With elements and no Markdown there is no `markdown` block, and `text`
199
+ * is the button labels joined by a space, escaped. Slack's own fallback,
200
+ * which appends the word "button" to each label, never appears.
201
+ *
202
+ * @internal
203
+ */
204
+ export const body = (
205
+ markdown: string,
206
+ notify: Escape.Notify,
207
+ budget: Budget,
208
+ actions: ReadonlyArray<Action> = []
209
+ ): Body => {
210
+ if (markdown === "" && actions.length > 0) {
211
+ const built = build(Actions.labels(actions), {}, budget)
212
+ return withActions({ sent: "", blocks: [], text: built.text, dropped: built.dropped }, actions)
213
+ }
214
+ const sent = Escape.escape(markdown, notify, { flush: true }).sent
215
+ const built = build(markdown, notify, budget)
216
+ return withActions(
217
+ { sent, blocks: [{ type: "markdown", text: sent }], text: built.text, dropped: built.dropped },
218
+ actions
219
+ )
220
+ }
221
+
222
+ /**
223
+ * `body` with the elements' `actions` block last, when there are any.
224
+ *
225
+ * @internal
226
+ */
227
+ export const withActions = (body: Body, actions: ReadonlyArray<Action>): Body =>
228
+ actions.length === 0 ? body : { ...body, blocks: [...body.blocks, Actions.block(actions)] }
229
+
230
+ /**
231
+ * Whether `body` has an `actions` block, which is content enough without
232
+ * `text`.
233
+ *
234
+ * @internal
235
+ */
236
+ export const hasActions = (body: Body): boolean =>
237
+ body.blocks.some((block) => (block as { readonly type?: unknown }).type === "actions")
238
+
239
+ /**
240
+ * The content of a post with files and no Markdown: the file names joined by
241
+ * ", ", escaped as Markdown in the block so they render as written, and with
242
+ * entities in `text`. No token in a name is allowed. It stays as the
243
+ * message.
244
+ *
245
+ * @internal
246
+ */
247
+ export const placeholder = (names: ReadonlyArray<string>, budget: Budget): Body => {
248
+ const joined = names.join(", ")
249
+ const sent = Escape.escape(escapeMarkdown(joined), {}, { flush: true }).sent
250
+ const built = build(joined, {}, budget)
251
+ return { sent, blocks: [{ type: "markdown", text: sent }], text: built.text, dropped: built.dropped }
252
+ }
@@ -0,0 +1,199 @@
1
+ import * as ByteSize from "effect/ByteSize"
2
+ import type { ChatError } from "effect/chat/ChatError"
3
+ import type * as ChatEvent from "effect/chat/ChatEvent"
4
+ import type { NotAccepted } from "effect/chat/ChatHandler"
5
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
6
+ import * as Clock from "effect/Clock"
7
+ import * as Mac from "effect/crypto/Mac"
8
+ import type * as Duration from "effect/Duration"
9
+ import * as Effect from "effect/Effect"
10
+ import * as Hex from "effect/encoding/Hex"
11
+ import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"
12
+ import type * as HttpServerRequest from "effect/http/HttpServerRequest"
13
+ import * as HttpServerResponse from "effect/http/HttpServerResponse"
14
+ import * as Option from "effect/Option"
15
+ import * as Redacted from "effect/Redacted"
16
+ import * as Result from "effect/Result"
17
+ import * as Schema from "effect/Schema"
18
+ import * as Json from "./json.ts"
19
+ import { normalize } from "./normalize.ts"
20
+
21
+ /** How far a request's timestamp may be from now, as Slack recommends. */
22
+ const maxSkewSeconds = 60 * 5
23
+
24
+ const encoder = new TextEncoder()
25
+ const decoder = new TextDecoder()
26
+
27
+ /** The default of `maxBodyBytes`. @internal */
28
+ export const defaultMaxBodyBytes = 1024 * 1024
29
+
30
+ /**
31
+ * Checks Slack's `v0` request signature: an HMAC-SHA256 of
32
+ * `v0:{timestamp}:{body}` with the signing secret, and a timestamp within
33
+ * five minutes of now.
34
+ *
35
+ * @internal
36
+ */
37
+ export const makeVerifier = Effect.fnUntraced(function*(signingSecret: Redacted.Redacted) {
38
+ const mac = yield* Mac.Mac
39
+ // Invalid signing secrets are configuration defects, not route errors.
40
+ const key = yield* Mac.key(Mac.hmacSha256, encoder.encode(Redacted.value(signingSecret))).pipe(Effect.orDie)
41
+ return (headers: { readonly [key: string]: string | undefined }, body: Uint8Array): Effect.Effect<boolean> =>
42
+ Effect.gen(function*() {
43
+ const timestamp = headers["x-slack-request-timestamp"]
44
+ const signature = headers["x-slack-signature"]
45
+ if (timestamp === undefined || signature === undefined || !/^\d+$/.test(timestamp)) return false
46
+ const tag = signature.startsWith("v0=") ? Hex.decode(signature.slice(3)) : undefined
47
+ if (tag === undefined || Result.isFailure(tag) || tag.success.length === 0) return false
48
+ const now = yield* Clock.currentTimeMillis
49
+ if (Math.abs(now / 1000 - Number(timestamp)) > maxSkewSeconds) return false
50
+ const prefix = encoder.encode(`v0:${timestamp}:`)
51
+ const message = new Uint8Array(prefix.length + body.length)
52
+ message.set(prefix)
53
+ message.set(body, prefix.length)
54
+ // Crypto failures fail closed, like a mismatched signature.
55
+ return yield* mac.verify(key, tag.success, message).pipe(Effect.catch(() => Effect.succeed(false)))
56
+ })
57
+ })
58
+
59
+ /**
60
+ * The body, or `None` past `maxBodySize` or when it can't be read, both
61
+ * answered 413. The length is checked again because the request caches its
62
+ * body: one read earlier under a larger limit comes back as it was.
63
+ */
64
+ const readBody = (
65
+ request: HttpServerRequest.HttpServerRequest,
66
+ maxBodySize: ByteSize.ByteSize
67
+ ): Effect.Effect<Option.Option<Uint8Array>> =>
68
+ request.arrayBuffer.pipe(
69
+ Effect.map((buffer) =>
70
+ buffer.byteLength > ByteSize.toNumberUnsafe(maxBodySize) ? Option.none() : Option.some(new Uint8Array(buffer))
71
+ ),
72
+ Effect.catch(() => Effect.succeedNone),
73
+ Effect.provideService(HttpIncomingMessage.MaxBodySize, maxBodySize)
74
+ )
75
+
76
+ /** A slash command's form fields, as its payload. A repeated field keeps its first value. */
77
+ const commandFields = (form: URLSearchParams): Record<string, string> => {
78
+ const fields: Record<string, string> = {}
79
+ for (const [key, value] of form) if (!Object.hasOwn(fields, key)) Json.setOwn(fields, key, value)
80
+ return fields
81
+ }
82
+
83
+ const ok = HttpServerResponse.empty({ status: 200 })
84
+ const status = (code: number) => HttpServerResponse.empty({ status: code })
85
+
86
+ /**
87
+ * What is logged with each 503 of the Events API route.
88
+ *
89
+ * @internal
90
+ */
91
+ export const unavailable = {
92
+ botUser: "slack webhook: the bot user could not be read, answered 503",
93
+ notAccepted: "slack webhook: the handler refused the event, answered 503",
94
+ deadline: "slack webhook: the request passed its deadline, answered 503"
95
+ } as const
96
+
97
+ /** @internal */
98
+ export interface Options {
99
+ readonly verify: (headers: { readonly [key: string]: string | undefined }, body: Uint8Array) => Effect.Effect<boolean>
100
+ readonly appId: string
101
+ readonly teamId: string
102
+ readonly botUserId: Effect.Effect<string, ChatError>
103
+ readonly handle: (event: ChatEvent.ChatEvent) => Effect.Effect<void, NotAccepted>
104
+ readonly deadline: Duration.Duration
105
+ readonly maxBodySize: ByteSize.ByteSize
106
+ }
107
+
108
+ /**
109
+ * One Events API request.
110
+ *
111
+ * - 413 past the body limit, 401 for a bad signature, 400 for a body that
112
+ * is not JSON.
113
+ * - `url_verification` is answered with its challenge.
114
+ * - An envelope for another app or workspace, or of another type, is
115
+ * answered 200 and dropped, so Slack does not retry it.
116
+ * - 503 when the bot user can't be read, the handler fails `NotAccepted`,
117
+ * or the whole request (including its body and verification) takes longer
118
+ * than the deadline. Slack then retries. Each is logged with its own
119
+ * message, since the status alone does not say which it was.
120
+ *
121
+ * @internal
122
+ */
123
+ export const handleRequest = (
124
+ request: HttpServerRequest.HttpServerRequest,
125
+ options: Options
126
+ ): Effect.Effect<HttpServerResponse.HttpServerResponse> =>
127
+ Effect.gen(function*() {
128
+ const body = yield* readBody(request, options.maxBodySize)
129
+ if (Option.isNone(body)) return status(413)
130
+ if (!(yield* options.verify(request.headers, body.value))) return status(401)
131
+ const envelope = Json.parse(decoder.decode(body.value))
132
+ if (!Json.isObject(envelope)) return status(400)
133
+ if (envelope.type === "url_verification") {
134
+ return typeof envelope.challenge === "string"
135
+ ? HttpServerResponse.text(envelope.challenge)
136
+ : status(400)
137
+ }
138
+ if (envelope.type !== "event_callback" || envelope.api_app_id !== options.appId) return ok
139
+ const botUserId = yield* Effect.catch(
140
+ Effect.asSome(options.botUserId),
141
+ (error) => Effect.as(Effect.logError(unavailable.botUser, error), Option.none<string>())
142
+ )
143
+ if (Option.isNone(botUserId)) return status(503)
144
+ const events = normalize(envelope, { teamId: options.teamId, botUserId: botUserId.value })
145
+ return yield* Effect.forEach(events, options.handle, { discard: true }).pipe(
146
+ Effect.as(ok),
147
+ Effect.catchTag("NotAccepted", () => Effect.as(Effect.logWarning(unavailable.notAccepted), status(503)))
148
+ )
149
+ }).pipe(
150
+ Effect.timeoutOption(options.deadline),
151
+ Effect.flatMap(Option.match({
152
+ onNone: () => Effect.as(Effect.logWarning(unavailable.deadline), status(503)),
153
+ onSome: Effect.succeed
154
+ }))
155
+ )
156
+
157
+ /** @internal */
158
+ export interface InteractivityOptions {
159
+ readonly verify: Options["verify"]
160
+ readonly appId: string
161
+ readonly interaction: (
162
+ payload: unknown,
163
+ options: { readonly deadline: Duration.Duration }
164
+ ) => Effect.Effect<Schema.Json | undefined | ChatInteraction.Late>
165
+ readonly deadline: Duration.Duration
166
+ readonly maxBodySize: ByteSize.ByteSize
167
+ }
168
+
169
+ const isLate = Schema.is(ChatInteraction.Late)
170
+
171
+ /**
172
+ * One Interactivity request: a form-encoded body whose `payload` field
173
+ * holds the JSON, or a slash command's, whose fields are the payload.
174
+ *
175
+ * - 413 past the body limit, 401 for a bad signature, 400 for a body with
176
+ * neither a `payload` that is a JSON object nor a `command`.
177
+ * - A payload or command for another app is answered 200 and dropped.
178
+ * - `Late` is answered 503, which keeps a modal open. Anything else is a
179
+ * 200, with the body as JSON when there is one.
180
+ *
181
+ * @internal
182
+ */
183
+ export const handleInteractivity = (
184
+ request: HttpServerRequest.HttpServerRequest,
185
+ options: InteractivityOptions
186
+ ): Effect.Effect<HttpServerResponse.HttpServerResponse> =>
187
+ Effect.gen(function*() {
188
+ const body = yield* readBody(request, options.maxBodySize)
189
+ if (Option.isNone(body)) return status(413)
190
+ if (!(yield* options.verify(request.headers, body.value))) return status(401)
191
+ const form = new URLSearchParams(decoder.decode(body.value))
192
+ const field = form.get("payload")
193
+ const payload = field !== null ? Json.parse(field) : form.has("command") ? commandFields(form) : undefined
194
+ if (!Json.isObject(payload)) return status(400)
195
+ if (payload.api_app_id !== options.appId) return ok
196
+ const answer = yield* options.interaction(payload, { deadline: options.deadline })
197
+ if (answer === undefined) return ok
198
+ return isLate(answer) ? status(503) : HttpServerResponse.jsonUnsafe(answer)
199
+ })