@vercel/slack-bolt 1.4.0 → 1.4.1

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.
@@ -1,980 +0,0 @@
1
- import { __esm } from './chunk-B5E7QPZP.mjs';
2
- import path2 from 'path';
3
- import { parse, stringify } from 'yaml';
4
- import crypto from 'crypto';
5
- import fs from 'fs';
6
-
7
- // src/internal/manifest/index.ts
8
- function rewriteUrl(originalUrl, branchUrl, bypassSecret) {
9
- const pathStart = originalUrl.indexOf("/", originalUrl.indexOf("//") + 2);
10
- const pathAndQuery = pathStart !== -1 ? originalUrl.slice(pathStart) : "/";
11
- const url = new URL(pathAndQuery, `https://${branchUrl}`);
12
- if (bypassSecret) {
13
- url.searchParams.set("x-vercel-protection-bypass", bypassSecret);
14
- }
15
- return url.toString();
16
- }
17
- function createManifestDescription(params) {
18
- const shortSha = params.commitSha?.slice(0, 7) ?? "unknown";
19
- const safeCommitMsg = params.commitMessage ?? "";
20
- const safeCommitAuthor = params.commitAuthor ?? "unknown";
21
- const deploymentInfo = `
22
- :globe_with_meridians: *Deployment URL:* ${params.branchUrl}
23
- :seedling: *Branch:* ${params.branch}
24
- :technologist: *Commit:* ${shortSha} ${safeCommitMsg}
25
- :bust_in_silhouette: *Last updated by:* ${safeCommitAuthor}
26
-
27
- _Automatically created by \u25B2 Vercel_
28
- `;
29
- const maxLongDesc = 4e3;
30
- const combined = params.existingDescription + deploymentInfo;
31
- let longDescription;
32
- if (combined.length > maxLongDesc) {
33
- const available = Math.max(0, maxLongDesc - deploymentInfo.length);
34
- longDescription = (params.existingDescription.slice(0, available) + deploymentInfo).slice(0, maxLongDesc);
35
- } else {
36
- longDescription = combined;
37
- }
38
- const maxDisplayName = 35;
39
- const cleanBranch = params.branch.replace(/^refs\/heads\//, "").replace(/\//g, "-");
40
- let displayName = `${params.existingName} (${cleanBranch})`;
41
- if (displayName.length > maxDisplayName) {
42
- const prefix = `${params.existingName} (`;
43
- const suffix = ")";
44
- const availableForBranch = maxDisplayName - prefix.length - suffix.length;
45
- displayName = availableForBranch > 0 ? `${prefix}${cleanBranch.slice(0, availableForBranch)}${suffix}` : displayName.slice(0, maxDisplayName);
46
- }
47
- return { longDescription, displayName };
48
- }
49
- function createNewManifest(params) {
50
- const manifest = structuredClone(params.originalManifest);
51
- if (manifest.settings?.event_subscriptions?.request_url) {
52
- manifest.settings.event_subscriptions.request_url = rewriteUrl(
53
- manifest.settings.event_subscriptions.request_url,
54
- params.branchUrl,
55
- params.bypassSecret
56
- );
57
- }
58
- if (manifest.settings?.interactivity?.request_url) {
59
- manifest.settings.interactivity.request_url = rewriteUrl(
60
- manifest.settings.interactivity.request_url,
61
- params.branchUrl,
62
- params.bypassSecret
63
- );
64
- }
65
- if (manifest.features?.slash_commands) {
66
- for (const cmd of manifest.features.slash_commands) {
67
- if (cmd.url) {
68
- cmd.url = rewriteUrl(cmd.url, params.branchUrl, params.bypassSecret);
69
- }
70
- }
71
- }
72
- if (manifest.oauth_config?.redirect_urls) {
73
- manifest.oauth_config.redirect_urls = manifest.oauth_config.redirect_urls.map(
74
- (originalUrl) => rewriteUrl(originalUrl, params.branchUrl)
75
- );
76
- }
77
- const { longDescription, displayName } = createManifestDescription({
78
- existingDescription: manifest.display_information.long_description ?? "",
79
- existingName: manifest.features?.bot_user?.display_name ?? manifest.display_information.name,
80
- branchUrl: params.branchUrl,
81
- branch: params.branch,
82
- commitSha: params.commitSha,
83
- commitMessage: params.commitMessage,
84
- commitAuthor: params.commitAuthor
85
- });
86
- manifest.display_information.long_description = longDescription;
87
- manifest.display_information.name = displayName;
88
- if (manifest.features?.bot_user) {
89
- manifest.features.bot_user.display_name = displayName;
90
- }
91
- return manifest;
92
- }
93
- var init_manifest = __esm({
94
- "src/internal/manifest/index.ts"() {
95
- }
96
- });
97
- function isYaml(filePath) {
98
- const ext = path2.extname(filePath).toLowerCase();
99
- return ext === ".yaml" || ext === ".yml";
100
- }
101
- function parseManifest(raw, filePath) {
102
- if (isYaml(filePath)) {
103
- return parse(raw);
104
- }
105
- return JSON.parse(raw);
106
- }
107
- function stringifyManifest(manifest, filePath) {
108
- if (isYaml(filePath)) {
109
- return stringify(manifest);
110
- }
111
- return JSON.stringify(manifest, null, 2);
112
- }
113
- var init_parse = __esm({
114
- "src/internal/manifest/parse.ts"() {
115
- }
116
- });
117
-
118
- // src/internal/vercel/errors.ts
119
- var HTTPError;
120
- var init_errors = __esm({
121
- "src/internal/vercel/errors.ts"() {
122
- HTTPError = class _HTTPError extends Error {
123
- constructor(message, status, statusText, body) {
124
- const parts = [`${message}: ${status} ${statusText}`];
125
- if (body) parts.push(body);
126
- super(parts.join(" - "));
127
- this.status = status;
128
- this.statusText = statusText;
129
- this.body = body;
130
- }
131
- static async fromResponse(message, response) {
132
- let body;
133
- try {
134
- const text = await response.text();
135
- if (text) body = text;
136
- } catch {
137
- }
138
- return new _HTTPError(message, response.status, response.statusText, body);
139
- }
140
- };
141
- }
142
- });
143
-
144
- // src/internal/slack/errors.ts
145
- var SlackManifestCreateError, SlackManifestUpdateError, SlackManifestExportError;
146
- var init_errors2 = __esm({
147
- "src/internal/slack/errors.ts"() {
148
- SlackManifestCreateError = class extends Error {
149
- constructor(message, errors) {
150
- super(message);
151
- this.errors = errors;
152
- }
153
- };
154
- SlackManifestUpdateError = class extends Error {
155
- constructor(message, errors) {
156
- super(message);
157
- this.errors = errors;
158
- }
159
- };
160
- SlackManifestExportError = class extends Error {
161
- };
162
- }
163
- });
164
-
165
- // src/internal/slack/index.ts
166
- async function createSlackApp({
167
- token,
168
- manifest
169
- }) {
170
- const response = await fetch("https://slack.com/api/apps.manifest.create", {
171
- method: "POST",
172
- headers: {
173
- Authorization: `Bearer ${token}`,
174
- "Content-Type": "application/json; charset=utf-8"
175
- },
176
- body: JSON.stringify({ manifest: JSON.stringify(manifest) })
177
- });
178
- if (!response.ok) {
179
- throw new HTTPError(
180
- "Failed to create Slack app",
181
- response.status,
182
- response.statusText
183
- );
184
- }
185
- const data = await response.json();
186
- if (!data.ok) {
187
- throw new SlackManifestCreateError(
188
- data?.error ?? "Unknown error",
189
- data?.errors
190
- );
191
- }
192
- return data;
193
- }
194
- async function updateSlackApp({
195
- token,
196
- appId,
197
- manifest
198
- }) {
199
- const response = await fetch("https://slack.com/api/apps.manifest.update", {
200
- method: "POST",
201
- headers: {
202
- Authorization: `Bearer ${token}`,
203
- "Content-Type": "application/json; charset=utf-8"
204
- },
205
- body: JSON.stringify({
206
- app_id: appId,
207
- manifest: JSON.stringify(manifest)
208
- })
209
- });
210
- if (!response.ok) {
211
- throw new HTTPError(
212
- "Failed to update Slack app",
213
- response.status,
214
- response.statusText
215
- );
216
- }
217
- const data = await response.json();
218
- if (!data.ok) {
219
- throw new SlackManifestUpdateError(
220
- data?.error ?? "Unknown error",
221
- data?.errors
222
- );
223
- }
224
- return data;
225
- }
226
- async function exportSlackApp({
227
- token,
228
- appId
229
- }) {
230
- const response = await fetch("https://slack.com/api/apps.manifest.export", {
231
- method: "POST",
232
- headers: {
233
- Authorization: `Bearer ${token}`,
234
- "Content-Type": "application/json; charset=utf-8"
235
- },
236
- body: JSON.stringify({ app_id: appId })
237
- });
238
- if (!response.ok) {
239
- throw new HTTPError(
240
- "Failed to export Slack app",
241
- response.status,
242
- response.statusText
243
- );
244
- }
245
- const data = await response.json();
246
- if (!data.ok) {
247
- throw new SlackManifestExportError(data?.error ?? "Unknown error");
248
- }
249
- return data;
250
- }
251
- async function upsertSlackApp({
252
- token,
253
- appId,
254
- manifest
255
- }) {
256
- if (appId) {
257
- try {
258
- await exportSlackApp({ token, appId });
259
- const app2 = await updateSlackApp({ token, appId, manifest });
260
- return { isNew: false, app: app2 };
261
- } catch {
262
- }
263
- }
264
- const app = await createSlackApp({ token, manifest });
265
- return { isNew: true, app };
266
- }
267
- async function deleteSlackApp({
268
- token,
269
- appId
270
- }) {
271
- const response = await fetch("https://slack.com/api/apps.manifest.delete", {
272
- method: "POST",
273
- headers: {
274
- Authorization: `Bearer ${token}`,
275
- "Content-Type": "application/json; charset=utf-8"
276
- },
277
- body: JSON.stringify({ app_id: appId })
278
- });
279
- if (!response.ok) {
280
- throw new HTTPError(
281
- "Failed to delete Slack app",
282
- response.status,
283
- response.statusText
284
- );
285
- }
286
- const data = await response.json();
287
- if (!data.ok) {
288
- throw new Error(data.error ?? "Unknown error");
289
- }
290
- }
291
- async function rotateConfigToken({
292
- refreshToken
293
- }) {
294
- const response = await fetch("https://slack.com/api/tooling.tokens.rotate", {
295
- method: "POST",
296
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
297
- body: new URLSearchParams({ refresh_token: refreshToken })
298
- });
299
- if (!response.ok) {
300
- throw new HTTPError(
301
- "Failed to rotate configuration token",
302
- response.status,
303
- response.statusText
304
- );
305
- }
306
- const data = await response.json();
307
- if (!data.ok || !data.token || !data.refresh_token) {
308
- throw new Error(data.error ?? "Unknown error rotating token");
309
- }
310
- return {
311
- token: data.token,
312
- refreshToken: data.refresh_token,
313
- exp: data.exp ?? 0
314
- };
315
- }
316
- async function authTest({
317
- token
318
- }) {
319
- const response = await fetch("https://slack.com/api/auth.test", {
320
- method: "POST",
321
- headers: {
322
- Authorization: `Bearer ${token}`,
323
- "Content-Type": "application/json; charset=utf-8"
324
- }
325
- });
326
- if (!response.ok) {
327
- throw new HTTPError(
328
- "Auth test failed",
329
- response.status,
330
- response.statusText
331
- );
332
- }
333
- const data = await response.json();
334
- if (!data.ok) {
335
- throw new Error(data.error ?? "Unknown error");
336
- }
337
- return {
338
- userId: data.user_id ?? "",
339
- teamId: data.team_id ?? ""
340
- };
341
- }
342
- async function verifyServiceTokenAccess(params) {
343
- try {
344
- await exportSlackApp({ token: params.serviceToken, appId: params.appId });
345
- return { hasAccess: true };
346
- } catch {
347
- return { hasAccess: false };
348
- }
349
- }
350
- async function installApp(params) {
351
- const { serviceToken, appId, botScopes, outgoingDomains } = params;
352
- if (!serviceToken) {
353
- return {
354
- status: "missing_service_token"
355
- };
356
- }
357
- const response = await fetch("https://slack.com/api/apps.developerInstall", {
358
- method: "POST",
359
- headers: {
360
- Authorization: `Bearer ${serviceToken}`,
361
- "Content-Type": "application/json; charset=utf-8"
362
- },
363
- body: JSON.stringify({
364
- app_id: appId,
365
- bot_scopes: botScopes,
366
- outgoing_domains: outgoingDomains ?? []
367
- })
368
- });
369
- if (!response.ok) {
370
- return {
371
- status: "slack_api_error",
372
- error: response.statusText
373
- };
374
- }
375
- const data = await response.json();
376
- if (data.error) {
377
- switch (data.error) {
378
- case "app_approval_request_eligible":
379
- return {
380
- status: "app_approval_request_eligible"
381
- };
382
- case "app_approval_request_pending":
383
- return {
384
- status: "app_approval_request_pending"
385
- };
386
- case "app_approval_request_denied":
387
- return {
388
- status: "app_approval_request_denied"
389
- };
390
- case "invalid_app_id": {
391
- if (serviceToken) {
392
- const { hasAccess } = await verifyServiceTokenAccess({
393
- serviceToken,
394
- appId
395
- });
396
- if (!hasAccess) {
397
- return { status: "no_access" };
398
- }
399
- }
400
- return { status: "invalid_app_id" };
401
- }
402
- default:
403
- return {
404
- status: "unknown_error"
405
- };
406
- }
407
- }
408
- return {
409
- status: "installed",
410
- botToken: data.api_access_tokens?.bot,
411
- appLevelToken: data.api_access_tokens?.app_level,
412
- userToken: data.api_access_tokens?.user
413
- };
414
- }
415
- var init_slack = __esm({
416
- "src/internal/slack/index.ts"() {
417
- init_errors();
418
- init_errors2();
419
- init_errors2();
420
- }
421
- });
422
- async function getProject({
423
- projectId,
424
- token,
425
- teamId
426
- }) {
427
- const url = new URL(
428
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}`
429
- );
430
- if (teamId) url.searchParams.set("teamId", teamId);
431
- const response = await fetch(url, {
432
- method: "GET",
433
- headers: {
434
- Authorization: `Bearer ${token}`
435
- }
436
- });
437
- if (!response.ok) {
438
- throw await HTTPError.fromResponse(
439
- "Failed to access Vercel project",
440
- response
441
- );
442
- }
443
- }
444
- async function updateProtectionBypass({
445
- projectId,
446
- token,
447
- teamId
448
- }) {
449
- const newSecret = crypto.randomBytes(16).toString("hex");
450
- const note = "Created by @vercel/slack-bolt";
451
- const url = new URL(
452
- `https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/protection-bypass`
453
- );
454
- if (teamId) url.searchParams.set("teamId", teamId);
455
- const response = await fetch(url, {
456
- method: "PATCH",
457
- headers: {
458
- Authorization: `Bearer ${token}`,
459
- "Content-Type": "application/json"
460
- },
461
- body: JSON.stringify({
462
- generate: {
463
- secret: newSecret,
464
- note
465
- }
466
- })
467
- });
468
- if (!response.ok) {
469
- throw await HTTPError.fromResponse(
470
- "Failed to update protection bypass",
471
- response
472
- );
473
- }
474
- return newSecret;
475
- }
476
- async function addEnvironmentVariables({
477
- projectId,
478
- token,
479
- teamId,
480
- envs,
481
- upsert = true
482
- }) {
483
- const url = new URL(
484
- `https://api.vercel.com/v10/projects/${encodeURIComponent(projectId)}/env`
485
- );
486
- if (teamId) url.searchParams.set("teamId", teamId);
487
- if (upsert) url.searchParams.set("upsert", "true");
488
- const response = await fetch(url, {
489
- method: "POST",
490
- headers: {
491
- Authorization: `Bearer ${token}`,
492
- "Content-Type": "application/json"
493
- },
494
- body: JSON.stringify(envs)
495
- });
496
- if (!response.ok) {
497
- throw await HTTPError.fromResponse(
498
- "Failed to create environment variables",
499
- response
500
- );
501
- }
502
- return response.json();
503
- }
504
- async function cancelDeployment({
505
- deploymentId,
506
- token,
507
- teamId
508
- }) {
509
- const url = new URL(
510
- `https://api.vercel.com/v12/deployments/${encodeURIComponent(deploymentId)}/cancel`
511
- );
512
- if (teamId) url.searchParams.set("teamId", teamId);
513
- const response = await fetch(url, {
514
- method: "PATCH",
515
- headers: { Authorization: `Bearer ${token}` }
516
- });
517
- if (!response.ok) {
518
- throw await HTTPError.fromResponse("Failed to cancel deployment", response);
519
- }
520
- }
521
- async function createDeployment({
522
- deploymentId,
523
- projectId,
524
- token,
525
- teamId
526
- }) {
527
- const url = new URL("https://api.vercel.com/v13/deployments");
528
- if (teamId) url.searchParams.set("teamId", teamId);
529
- url.searchParams.set("forceNew", "1");
530
- const response = await fetch(url, {
531
- method: "POST",
532
- headers: {
533
- Authorization: `Bearer ${token}`,
534
- "Content-Type": "application/json"
535
- },
536
- body: JSON.stringify({
537
- deploymentId,
538
- name: projectId,
539
- project: projectId
540
- })
541
- });
542
- if (!response.ok) {
543
- throw await HTTPError.fromResponse("Failed to create deployment", response);
544
- }
545
- const data = await response.json();
546
- return { id: data.id, url: data.url };
547
- }
548
- async function getActiveBranches({
549
- projectId,
550
- token,
551
- teamId
552
- }) {
553
- const params = new URLSearchParams({ active: "1", limit: "100" });
554
- if (teamId) params.set("teamId", teamId);
555
- const response = await fetch(
556
- `https://api.vercel.com/v5/projects/${encodeURIComponent(projectId)}/branches?${params}`,
557
- { headers: { Authorization: `Bearer ${token}` } }
558
- );
559
- if (!response.ok) {
560
- throw await HTTPError.fromResponse(
561
- "Failed to fetch active branches",
562
- response
563
- );
564
- }
565
- const data = await response.json();
566
- return new Set(data.branches?.map((b) => b.branch) ?? []);
567
- }
568
- async function getEnvironmentVariables({
569
- projectId,
570
- token,
571
- teamId
572
- }) {
573
- const url = new URL(
574
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env`
575
- );
576
- if (teamId) url.searchParams.set("teamId", teamId);
577
- const response = await fetch(url, {
578
- headers: { Authorization: `Bearer ${token}` }
579
- });
580
- if (!response.ok) {
581
- throw await HTTPError.fromResponse(
582
- "Failed to fetch environment variables",
583
- response
584
- );
585
- }
586
- const data = await response.json();
587
- return data.envs ?? [];
588
- }
589
- async function getEnvironmentVariable({
590
- projectId,
591
- envId,
592
- token,
593
- teamId
594
- }) {
595
- const url = new URL(
596
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`
597
- );
598
- if (teamId) url.searchParams.set("teamId", teamId);
599
- const response = await fetch(url, {
600
- headers: { Authorization: `Bearer ${token}` }
601
- });
602
- if (!response.ok) {
603
- throw await HTTPError.fromResponse(
604
- "Failed to fetch environment variable",
605
- response
606
- );
607
- }
608
- const data = await response.json();
609
- return data.value ?? null;
610
- }
611
- async function deleteEnvironmentVariable({
612
- projectId,
613
- envId,
614
- token,
615
- teamId
616
- }) {
617
- const url = new URL(
618
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`
619
- );
620
- if (teamId) url.searchParams.set("teamId", teamId);
621
- const response = await fetch(url, {
622
- method: "DELETE",
623
- headers: { Authorization: `Bearer ${token}` }
624
- });
625
- if (!response.ok) {
626
- throw await HTTPError.fromResponse(
627
- "Failed to delete environment variable",
628
- response
629
- );
630
- }
631
- }
632
- var init_vercel = __esm({
633
- "src/internal/vercel/index.ts"() {
634
- init_errors();
635
- }
636
- });
637
-
638
- // src/logger.ts
639
- function isDebug() {
640
- return process.env.VERCEL_SLACK_DEBUG === "1" || process.env.VERCEL_SLACK_DEBUG === "true";
641
- }
642
- function isSensitiveKey(key) {
643
- const lower = key.toLowerCase();
644
- if (SENSITIVE_BODY_KEYS.has(lower)) return true;
645
- return SENSITIVE_KEY_PATTERNS.some((pattern) => lower.includes(pattern));
646
- }
647
- function redactValue(value) {
648
- if (value.length <= 4) return "****";
649
- return `****${value.slice(-4)}`;
650
- }
651
- function redactSensitiveFields(obj) {
652
- if (Array.isArray(obj)) {
653
- return obj.map((item) => redactSensitiveFields(item));
654
- }
655
- if (obj !== null && typeof obj === "object") {
656
- const result = {};
657
- for (const [key, val] of Object.entries(obj)) {
658
- if (isSensitiveKey(key) && typeof val === "string") {
659
- result[key] = redactValue(val);
660
- } else {
661
- result[key] = redactSensitiveFields(val);
662
- }
663
- }
664
- return result;
665
- }
666
- return obj;
667
- }
668
- function redactBody(body) {
669
- try {
670
- const parsed = JSON.parse(body);
671
- const redacted = redactSensitiveFields(parsed);
672
- return JSON.stringify(redacted);
673
- } catch {
674
- return `<non-JSON body, ${body.length} bytes>`;
675
- }
676
- }
677
- function formatHeaders(headers) {
678
- const entries = headers instanceof Headers ? [...headers.entries()] : Object.entries(headers ?? {});
679
- const redacted = entries.map(
680
- ([k, v]) => REDACTED_HEADERS.has(k.toLowerCase()) ? [k, `****${v.slice(-4)}`] : [k, v]
681
- );
682
- return JSON.stringify(Object.fromEntries(redacted));
683
- }
684
- function enableFetchDebugLogging() {
685
- if (globalThis.fetch.__debugPatched) return;
686
- const originalFetch = globalThis.fetch;
687
- const patched = async (input, init) => {
688
- const method = init?.method ?? "GET";
689
- const url = input instanceof Request ? input.url : input.toString();
690
- const start = performance.now();
691
- log.debug(`-> ${method} ${url}`);
692
- log.debug(` headers: ${formatHeaders(init?.headers)}`);
693
- if (typeof init?.body === "string")
694
- log.debug(` body: ${redactBody(init.body)}`);
695
- const response = await originalFetch(input, init);
696
- const ms = (performance.now() - start).toFixed(0);
697
- log.debug(`<- ${response.status} ${response.statusText} (${ms}ms)`);
698
- log.debug(` headers: ${formatHeaders(response.headers)}`);
699
- const clone = response.clone();
700
- try {
701
- const body = await clone.text();
702
- if (body) log.debug(` body: ${redactBody(body)}`);
703
- } catch {
704
- }
705
- return response;
706
- };
707
- patched.__debugPatched = true;
708
- globalThis.fetch = patched;
709
- }
710
- var BOLD, RESET, DIM, GREEN, YELLOW, log, REDACTED_HEADERS, SENSITIVE_BODY_KEYS, SENSITIVE_KEY_PATTERNS, startMessage;
711
- var init_logger = __esm({
712
- "src/logger.ts"() {
713
- BOLD = "\x1B[1m";
714
- RESET = "\x1B[0m";
715
- DIM = "\x1B[2m";
716
- GREEN = "\x1B[32m";
717
- YELLOW = "\x1B[33m";
718
- log = {
719
- step: (msg) => console.log(` ${msg} ...`),
720
- success: (msg) => console.log(`${GREEN}\u2713${RESET} ${msg}`),
721
- info: (msg) => console.log(` ${msg}`),
722
- warning: (msg) => console.log(`${YELLOW}\u26A0${RESET} ${msg}`),
723
- error: (...args) => console.error(...args),
724
- debug: (...args) => {
725
- if (isDebug()) {
726
- const msg = args.map((a) => typeof a === "string" ? a : String(a)).join(" ");
727
- console.debug(`${DIM}${msg}${RESET}`);
728
- }
729
- }
730
- };
731
- REDACTED_HEADERS = /* @__PURE__ */ new Set(["authorization"]);
732
- SENSITIVE_BODY_KEYS = /* @__PURE__ */ new Set([
733
- "token",
734
- "bot",
735
- "app_level",
736
- "user",
737
- "secret",
738
- "client_secret",
739
- "signing_secret",
740
- "verification_token",
741
- "bot_token",
742
- "user_token",
743
- "app_level_token",
744
- "value",
745
- "access_token",
746
- "refresh_token",
747
- "password"
748
- ]);
749
- SENSITIVE_KEY_PATTERNS = ["token", "secret", "password", "credential"];
750
- startMessage = (version, branch, commit, appId) => {
751
- const lines = [`\u25B2 @vercel/slack-bolt ${version ?? ""}`];
752
- if (branch) lines.push(` - Branch: ${branch}`);
753
- if (commit) lines.push(` - Commit: ${commit.slice(0, 7)}`);
754
- if (appId) lines.push(` - App ID: ${appId}`);
755
- return `${BOLD}${lines.join("\n")}${RESET}
756
- `;
757
- };
758
- }
759
- });
760
- var preview;
761
- var init_preview = __esm({
762
- "src/preview.ts"() {
763
- init_manifest();
764
- init_parse();
765
- init_slack();
766
- init_vercel();
767
- init_logger();
768
- preview = async (params, context) => {
769
- const {
770
- branch,
771
- projectId,
772
- deploymentUrl,
773
- teamId,
774
- commitAuthor,
775
- commitMessage: commitMsg,
776
- commitSha,
777
- slackAppId,
778
- slackConfigurationToken,
779
- slackServiceToken,
780
- manifestPath,
781
- vercelApiToken
782
- } = params;
783
- const cli = context === "cli";
784
- const branchUrl = params.branchUrl ?? deploymentUrl;
785
- let bypassSecret = params.automationBypassSecret;
786
- if (!bypassSecret) {
787
- if (cli) log.step("Generating automation bypass secret");
788
- bypassSecret = await updateProtectionBypass({
789
- projectId,
790
- token: vercelApiToken,
791
- teamId
792
- });
793
- if (cli) log.success("Automation bypass secret generated");
794
- }
795
- if (cli) log.step(`Reading manifest from ${manifestPath}`);
796
- const rawFileManifest = fs.readFileSync(
797
- path2.join(process.cwd(), manifestPath),
798
- "utf8"
799
- );
800
- const manifest = parseManifest(rawFileManifest, manifestPath);
801
- const newManifest = createNewManifest({
802
- originalManifest: manifest,
803
- branchUrl,
804
- bypassSecret,
805
- branch,
806
- commitSha,
807
- commitMessage: commitMsg,
808
- commitAuthor
809
- });
810
- fs.writeFileSync(
811
- path2.join(process.cwd(), manifestPath),
812
- stringifyManifest(newManifest, manifestPath),
813
- "utf8"
814
- );
815
- if (cli) log.success(`Manifest updated for ${branchUrl}`);
816
- if (cli) log.step("Creating or updating Slack app");
817
- const { isNew, app } = await upsertSlackApp({
818
- token: slackConfigurationToken,
819
- appId: slackAppId,
820
- manifest: newManifest
821
- });
822
- if (isNew) {
823
- const credentialEnvs = [];
824
- if (app.app_id) {
825
- credentialEnvs.push({
826
- key: "SLACK_APP_ID",
827
- value: app.app_id,
828
- type: "encrypted",
829
- target: ["preview"],
830
- gitBranch: branch,
831
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
832
- });
833
- }
834
- if (app.credentials?.client_id) {
835
- credentialEnvs.push({
836
- key: "SLACK_CLIENT_ID",
837
- value: app.credentials.client_id,
838
- type: "encrypted",
839
- target: ["preview"],
840
- gitBranch: branch,
841
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
842
- });
843
- }
844
- if (app.credentials?.client_secret) {
845
- credentialEnvs.push({
846
- key: "SLACK_CLIENT_SECRET",
847
- value: app.credentials.client_secret,
848
- type: "encrypted",
849
- target: ["preview"],
850
- gitBranch: branch,
851
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
852
- });
853
- }
854
- if (app.credentials?.signing_secret) {
855
- credentialEnvs.push({
856
- key: "SLACK_SIGNING_SECRET",
857
- value: app.credentials.signing_secret,
858
- type: "encrypted",
859
- target: ["preview"],
860
- gitBranch: branch,
861
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
862
- });
863
- }
864
- if (credentialEnvs.length > 0) {
865
- await addEnvironmentVariables({
866
- projectId,
867
- token: vercelApiToken,
868
- teamId,
869
- envs: credentialEnvs
870
- });
871
- }
872
- }
873
- if (cli)
874
- log.success(`${isNew ? "Created" : "Updated"} Slack app ${app.app_id}`);
875
- if (cli) log.step("Installing Slack app");
876
- const { status, botToken, appLevelToken, userToken } = await installApp({
877
- serviceToken: slackServiceToken,
878
- appId: app.app_id,
879
- botScopes: manifest.oauth_config?.scopes?.bot ?? []
880
- });
881
- if (isNew) {
882
- const tokenEnvs = [];
883
- if (botToken) {
884
- tokenEnvs.push({
885
- key: "SLACK_BOT_TOKEN",
886
- value: botToken,
887
- type: "encrypted",
888
- target: ["preview"],
889
- gitBranch: branch,
890
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
891
- });
892
- }
893
- if (appLevelToken) {
894
- tokenEnvs.push({
895
- key: "SLACK_APP_LEVEL_TOKEN",
896
- value: appLevelToken,
897
- type: "encrypted",
898
- target: ["preview"],
899
- gitBranch: branch,
900
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
901
- });
902
- }
903
- if (userToken) {
904
- tokenEnvs.push({
905
- key: "SLACK_USER_TOKEN",
906
- value: userToken,
907
- type: "encrypted",
908
- target: ["preview"],
909
- gitBranch: branch,
910
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
911
- });
912
- }
913
- if (tokenEnvs.length > 0) {
914
- await addEnvironmentVariables({
915
- projectId,
916
- token: vercelApiToken,
917
- teamId,
918
- envs: tokenEnvs
919
- });
920
- }
921
- }
922
- if (cli) {
923
- switch (status) {
924
- case "missing_service_token":
925
- log.warning(
926
- "SLACK_SERVICE_TOKEN is not set \u2014 app must be installed manually"
927
- );
928
- log.info("https://docs.slack.dev/authentication/tokens/#service");
929
- break;
930
- case "installed":
931
- log.success(`Installed Slack app ${app.app_id}`);
932
- break;
933
- case "app_approval_request_eligible":
934
- log.warning("App requires approval before it can be installed");
935
- break;
936
- case "app_approval_request_pending":
937
- log.warning("App is pending approval before it can be installed");
938
- break;
939
- case "app_approval_request_denied":
940
- log.warning("App approval request was denied");
941
- break;
942
- case "no_access":
943
- log.warning(
944
- `SLACK_SERVICE_TOKEN does not have access to app ${app.app_id}. This usually means the service token and configuration token were created by different users. Ensure both tokens are generated by the same Slack user.
945
- https://docs.slack.dev/authentication/tokens/#service`
946
- );
947
- break;
948
- case "invalid_app_id":
949
- log.warning(
950
- "Invalid app ID. This is a bug in the @vercel/slack-bolt package. Please open an issue at https://github.com/vercel/slack-bolt/issues"
951
- );
952
- break;
953
- case "slack_api_error":
954
- log.warning("Slack API error while installing the app");
955
- break;
956
- case "unknown_error":
957
- log.warning("Unknown error while installing the app");
958
- break;
959
- }
960
- console.log();
961
- if (app.app_id) {
962
- log.info(`View app: https://api.slack.com/apps/${app.app_id}`);
963
- }
964
- if (isNew && app.oauth_authorize_url) {
965
- log.info(`Install URL: ${app.oauth_authorize_url}`);
966
- }
967
- console.log();
968
- }
969
- return {
970
- isNew,
971
- installStatus: status,
972
- app
973
- };
974
- };
975
- }
976
- });
977
-
978
- export { addEnvironmentVariables, authTest, cancelDeployment, createDeployment, deleteEnvironmentVariable, deleteSlackApp, enableFetchDebugLogging, getActiveBranches, getEnvironmentVariable, getEnvironmentVariables, getProject, init_logger, init_preview, init_slack, init_vercel, log, preview, rotateConfigToken, startMessage };
979
- //# sourceMappingURL=chunk-LARZABX3.mjs.map
980
- //# sourceMappingURL=chunk-LARZABX3.mjs.map