@terreno/api 57.9.0 → 57.11.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/LICENSE +1 -0
- package/dist/api.js +44 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/notifiers/slackWebApi.d.ts +83 -0
- package/dist/notifiers/slackWebApi.js +453 -0
- package/dist/rbac/roleModel.js +28 -0
- package/dist/rbac/statements.d.ts +15 -0
- package/dist/rbac/statements.js +83 -1
- package/package.json +3 -3
- package/src/api.arrayOperations.test.ts +38 -0
- package/src/api.query.test.ts +15 -4
- package/src/api.ts +57 -7
- package/src/index.ts +1 -0
- package/src/notifiers/slackWebApi.test.ts +357 -0
- package/src/notifiers/slackWebApi.ts +567 -0
- package/src/rbac/roleModel.test.ts +85 -1
- package/src/rbac/roleModel.ts +40 -0
- package/src/rbac/statements.test.ts +60 -0
- package/src/rbac/statements.ts +91 -0
package/LICENSE
CHANGED
package/dist/api.js
CHANGED
|
@@ -154,7 +154,9 @@ const mergeDateRangeQueryParams = (model, query) => {
|
|
|
154
154
|
return result;
|
|
155
155
|
};
|
|
156
156
|
// Ensures query params are allowed. Also checks nested query params when using $and/$or.
|
|
157
|
-
|
|
157
|
+
// The error names the field, the model, and the allowed list so a missing `queryFields`
|
|
158
|
+
// entry is obvious from the client (syncdb raises it as QueryFieldNotAllowedError).
|
|
159
|
+
const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = [], modelName = "this model") => {
|
|
158
160
|
// Cast for iteration through complex query values
|
|
159
161
|
const complexValue = queryParamValue;
|
|
160
162
|
// Check the values of each of the complex query params. We don't support recursive queries here,
|
|
@@ -163,15 +165,19 @@ const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = []) =
|
|
|
163
165
|
// Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
|
|
164
166
|
for (const subQuery of complexValue) {
|
|
165
167
|
for (const subKey of Object.keys(subQuery)) {
|
|
166
|
-
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
|
|
168
|
+
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields, modelName);
|
|
167
169
|
}
|
|
168
170
|
}
|
|
169
171
|
return;
|
|
170
172
|
}
|
|
171
173
|
if (!queryFields.includes(queryParam)) {
|
|
174
|
+
const allowed = queryFields.length > 0 ? queryFields.join(", ") : "(none)";
|
|
172
175
|
throw new errors_1.BadRequestError({
|
|
173
176
|
code: "query-param-not-allowed",
|
|
174
|
-
detail: `${queryParam} is not allowed as a query param
|
|
177
|
+
detail: `${queryParam} is not allowed as a query param. ` +
|
|
178
|
+
`Add "${queryParam}" to queryFields on the ${modelName} modelRouter to filter on it. ` +
|
|
179
|
+
`Allowed: ${allowed}.`,
|
|
180
|
+
meta: { allowedQueryFields: [...queryFields], model: modelName, queryParam },
|
|
175
181
|
source: { parameter: queryParam },
|
|
176
182
|
title: "Query parameter not allowed",
|
|
177
183
|
});
|
|
@@ -381,6 +387,17 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
381
387
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
382
388
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
383
389
|
(0, openApi_1.listOpenApiMiddleware)(model, options, routePath),
|
|
390
|
+
// Runs before query validation so a field missing from queryFields is always
|
|
391
|
+
// reported with this error, whatever the validator's settings.
|
|
392
|
+
(req, _res, next) => {
|
|
393
|
+
for (const queryParam of Object.keys(req.query)) {
|
|
394
|
+
if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields, model.modelName);
|
|
398
|
+
}
|
|
399
|
+
next();
|
|
400
|
+
},
|
|
384
401
|
queryValidation,
|
|
385
402
|
], (0, exports.asyncHandler)(async (req, res) => {
|
|
386
403
|
let query = {};
|
|
@@ -391,7 +408,7 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
391
408
|
if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
|
|
392
409
|
continue;
|
|
393
410
|
}
|
|
394
|
-
checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
|
|
411
|
+
checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields, model.modelName);
|
|
395
412
|
// Not sure if this is necessary or if mongoose does the right thing.
|
|
396
413
|
if (req.query[queryParam] === "true") {
|
|
397
414
|
query[queryParam] = true;
|
|
@@ -853,13 +870,33 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
853
870
|
data: (0, transformers_1.serialize)(req, options, doc),
|
|
854
871
|
});
|
|
855
872
|
};
|
|
856
|
-
|
|
873
|
+
// Array routes are `/:id/:field`. A non-ObjectId id is another resource under the
|
|
874
|
+
// same prefix (for example POST /ai/observability/evaluators), so leave the router
|
|
875
|
+
// and let a later registration handle it.
|
|
876
|
+
const continueUnlessDocumentId = (req, next) => {
|
|
877
|
+
const id = req.params.id;
|
|
878
|
+
if (typeof id === "string" && (0, utils_1.isValidObjectId)(id)) {
|
|
879
|
+
return false;
|
|
880
|
+
}
|
|
881
|
+
next("router");
|
|
882
|
+
return true;
|
|
883
|
+
};
|
|
884
|
+
const arrayPost = async (req, res, next) => {
|
|
885
|
+
if (continueUnlessDocumentId(req, next)) {
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
857
888
|
return arrayOperation(req, res, "POST");
|
|
858
889
|
};
|
|
859
|
-
const arrayPatch = async (req, res) => {
|
|
890
|
+
const arrayPatch = async (req, res, next) => {
|
|
891
|
+
if (continueUnlessDocumentId(req, next)) {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
860
894
|
return arrayOperation(req, res, "PATCH");
|
|
861
895
|
};
|
|
862
|
-
const arrayDelete = async (req, res) => {
|
|
896
|
+
const arrayDelete = async (req, res, next) => {
|
|
897
|
+
if (continueUnlessDocumentId(req, next)) {
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
863
900
|
return arrayOperation(req, res, "DELETE");
|
|
864
901
|
};
|
|
865
902
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
package/dist/index.d.ts
CHANGED
|
@@ -50,6 +50,7 @@ export { NotificationsApp, type NotificationsAppOptions, } from "./notifications
|
|
|
50
50
|
export { type NotificationsBeforeSendChannel, type NotificationsBeforeSendContext, type NotificationsBeforeSendResult, notificationsBeforeSend, } from "./notifications/notificationsBeforeSend";
|
|
51
51
|
export * from "./notifiers/googleChatNotifier";
|
|
52
52
|
export * from "./notifiers/slackNotifier";
|
|
53
|
+
export * from "./notifiers/slackWebApi";
|
|
53
54
|
export * from "./notifiers/zoomNotifier";
|
|
54
55
|
export * from "./openApiBuilder";
|
|
55
56
|
export * from "./openApiCompat";
|
package/dist/index.js
CHANGED
|
@@ -101,6 +101,7 @@ var notificationsBeforeSend_1 = require("./notifications/notificationsBeforeSend
|
|
|
101
101
|
Object.defineProperty(exports, "notificationsBeforeSend", { enumerable: true, get: function () { return notificationsBeforeSend_1.notificationsBeforeSend; } });
|
|
102
102
|
__exportStar(require("./notifiers/googleChatNotifier"), exports);
|
|
103
103
|
__exportStar(require("./notifiers/slackNotifier"), exports);
|
|
104
|
+
__exportStar(require("./notifiers/slackWebApi"), exports);
|
|
104
105
|
__exportStar(require("./notifiers/zoomNotifier"), exports);
|
|
105
106
|
__exportStar(require("./openApiBuilder"), exports);
|
|
106
107
|
__exportStar(require("./openApiCompat"), exports);
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export interface SlackInviteFailure {
|
|
2
|
+
userId: string;
|
|
3
|
+
error: string;
|
|
4
|
+
}
|
|
5
|
+
export interface SlackInviteResult {
|
|
6
|
+
invitedUserIds: string[];
|
|
7
|
+
alreadyMemberUserIds: string[];
|
|
8
|
+
failures: SlackInviteFailure[];
|
|
9
|
+
}
|
|
10
|
+
export interface SlackChannelRef {
|
|
11
|
+
channelId: string;
|
|
12
|
+
name: string;
|
|
13
|
+
isPrivate: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface CreateSlackPrivateChannelOptions {
|
|
16
|
+
/** Slack channel name: lowercase letters, numbers, hyphens, underscores, max 80. */
|
|
17
|
+
name: string;
|
|
18
|
+
/** Slack member IDs to invite. The bot is already a member because it creates the channel. */
|
|
19
|
+
userIds?: string[];
|
|
20
|
+
initialMessage?: string;
|
|
21
|
+
/** Member IDs to @-mention in `initialMessage`. */
|
|
22
|
+
mentionUserIds?: string[];
|
|
23
|
+
/** Defaults to `SLACK_BOT_TOKEN`. One workspace token for every Terreno app. */
|
|
24
|
+
token?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface SlackPrivateChannelResult {
|
|
27
|
+
channelId: string;
|
|
28
|
+
name: string;
|
|
29
|
+
invites: SlackInviteResult;
|
|
30
|
+
messageTs?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface InviteSlackUsersOptions {
|
|
33
|
+
channelId: string;
|
|
34
|
+
userIds: string[];
|
|
35
|
+
token?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface PostSlackMessageOptions {
|
|
38
|
+
channelId: string;
|
|
39
|
+
text: string;
|
|
40
|
+
blocks?: Record<string, unknown>[];
|
|
41
|
+
mentionUserIds?: string[];
|
|
42
|
+
token?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface PostSlackMessageResult {
|
|
45
|
+
channelId: string;
|
|
46
|
+
messageTs: string;
|
|
47
|
+
}
|
|
48
|
+
export interface FindSlackChannelOptions {
|
|
49
|
+
name: string;
|
|
50
|
+
token?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Slack channel names are lowercase letters, numbers, hyphens, and underscores,
|
|
54
|
+
* at most 80 characters. Leading and trailing whitespace is removed and the
|
|
55
|
+
* value is lowercased. Any other character is rejected.
|
|
56
|
+
*/
|
|
57
|
+
export declare const normalizeSlackChannelName: (name: string) => string;
|
|
58
|
+
/**
|
|
59
|
+
* Create a private channel in the workspace for `SLACK_BOT_TOKEN`, invite
|
|
60
|
+
* members, and optionally post the first message.
|
|
61
|
+
*
|
|
62
|
+
* Requires bot scopes `groups:write`, `groups:write.invites`, and `chat:write`.
|
|
63
|
+
* `name_taken` throws a 409. Call `findSlackChannelByName` to reuse a channel
|
|
64
|
+
* the bot can already see.
|
|
65
|
+
*/
|
|
66
|
+
export declare const createSlackPrivateChannel: ({ name, userIds, initialMessage, mentionUserIds, token, }: CreateSlackPrivateChannelOptions) => Promise<SlackPrivateChannelResult>;
|
|
67
|
+
/**
|
|
68
|
+
* Invite staff to a channel the bot already belongs to. Private channels do
|
|
69
|
+
* not allow a bot to join itself; invite the app once, then call this.
|
|
70
|
+
*
|
|
71
|
+
* `groups:write.invites` covers private channels. `channels:write.invites`
|
|
72
|
+
* covers public channels. Member IDs that are already in the channel are
|
|
73
|
+
* reported on `alreadyMemberUserIds` and do not fail the call.
|
|
74
|
+
*/
|
|
75
|
+
export declare const inviteSlackUsersToChannel: ({ channelId, userIds, token, }: InviteSlackUsersOptions) => Promise<SlackInviteResult>;
|
|
76
|
+
/** Post as the bot with `chat:write`. The bot must already be in the channel. */
|
|
77
|
+
export declare const postSlackMessage: ({ channelId, text, blocks, mentionUserIds, token, }: PostSlackMessageOptions) => Promise<PostSlackMessageResult>;
|
|
78
|
+
/**
|
|
79
|
+
* Find a public channel, or a private channel the bot is already in.
|
|
80
|
+
* Returns undefined when the name is not visible to the bot. Archived
|
|
81
|
+
* channels are skipped. Requires `channels:read` and `groups:read`.
|
|
82
|
+
*/
|
|
83
|
+
export declare const findSlackChannelByName: ({ name, token, }: FindSlackChannelOptions) => Promise<SlackChannelRef | undefined>;
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.findSlackChannelByName = exports.postSlackMessage = exports.inviteSlackUsersToChannel = exports.createSlackPrivateChannel = exports.normalizeSlackChannelName = void 0;
|
|
37
|
+
const Sentry = __importStar(require("@sentry/bun"));
|
|
38
|
+
const axios_1 = __importStar(require("axios"));
|
|
39
|
+
const errors_1 = require("../errors");
|
|
40
|
+
const logger_1 = require("../logger");
|
|
41
|
+
const slackNotifier_1 = require("./slackNotifier");
|
|
42
|
+
const SLACK_API_URL = "https://slack.com/api";
|
|
43
|
+
const MAX_ATTEMPTS = 3;
|
|
44
|
+
const MAX_CHANNEL_PAGES = 25;
|
|
45
|
+
const INVITE_BATCH_SIZE = 1000;
|
|
46
|
+
const CHANNEL_NAME_PATTERN = /^[a-z0-9_-]{1,80}$/;
|
|
47
|
+
const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{8,}$/;
|
|
48
|
+
const FATAL_INVITE_ERRORS = new Set([
|
|
49
|
+
"cant_invite",
|
|
50
|
+
"channel_not_found",
|
|
51
|
+
"invalid_auth",
|
|
52
|
+
"is_archived",
|
|
53
|
+
"missing_scope",
|
|
54
|
+
"no_permission",
|
|
55
|
+
"not_authed",
|
|
56
|
+
"not_in_channel",
|
|
57
|
+
"token_revoked",
|
|
58
|
+
]);
|
|
59
|
+
/**
|
|
60
|
+
* Slack channel names are lowercase letters, numbers, hyphens, and underscores,
|
|
61
|
+
* at most 80 characters. Leading and trailing whitespace is removed and the
|
|
62
|
+
* value is lowercased. Any other character is rejected.
|
|
63
|
+
*/
|
|
64
|
+
const normalizeSlackChannelName = (name) => {
|
|
65
|
+
const normalized = name.trim().toLowerCase();
|
|
66
|
+
const punctuationOnly = /^[_-]+$/u.test(normalized);
|
|
67
|
+
if (!CHANNEL_NAME_PATTERN.test(normalized) || punctuationOnly) {
|
|
68
|
+
throw new errors_1.APIError({
|
|
69
|
+
code: "slack-channel-name-invalid",
|
|
70
|
+
detail: "Use 1-80 characters: lowercase letters, numbers, hyphens, and underscores.",
|
|
71
|
+
status: 400,
|
|
72
|
+
title: "Invalid Slack channel name",
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return normalized;
|
|
76
|
+
};
|
|
77
|
+
exports.normalizeSlackChannelName = normalizeSlackChannelName;
|
|
78
|
+
const requireSlackToken = (token) => {
|
|
79
|
+
const botToken = token ?? process.env.SLACK_BOT_TOKEN;
|
|
80
|
+
if (!botToken) {
|
|
81
|
+
throw new errors_1.APIError({
|
|
82
|
+
code: "slack-token-missing",
|
|
83
|
+
status: 500,
|
|
84
|
+
title: "SLACK_BOT_TOKEN is not set",
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return botToken;
|
|
88
|
+
};
|
|
89
|
+
const requireChannelId = (channelId) => {
|
|
90
|
+
const normalized = channelId.trim().toUpperCase();
|
|
91
|
+
if (!CHANNEL_ID_PATTERN.test(normalized)) {
|
|
92
|
+
throw new errors_1.APIError({
|
|
93
|
+
code: "slack-channel-id-invalid",
|
|
94
|
+
detail: channelId,
|
|
95
|
+
status: 400,
|
|
96
|
+
title: "Invalid Slack channel id",
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return normalized;
|
|
100
|
+
};
|
|
101
|
+
const partitionUserIds = (userIds) => {
|
|
102
|
+
const validUserIds = [];
|
|
103
|
+
const invalidUserIds = [];
|
|
104
|
+
const seen = new Set();
|
|
105
|
+
for (const rawId of userIds) {
|
|
106
|
+
const id = (0, slackNotifier_1.normalizeSlackUserId)(rawId);
|
|
107
|
+
if (!id) {
|
|
108
|
+
if (rawId.trim()) {
|
|
109
|
+
invalidUserIds.push(rawId);
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (seen.has(id)) {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
seen.add(id);
|
|
117
|
+
validUserIds.push(id);
|
|
118
|
+
}
|
|
119
|
+
return { invalidUserIds, validUserIds };
|
|
120
|
+
};
|
|
121
|
+
const retryAfterMs = (headers) => {
|
|
122
|
+
const retryAfterHeader = "retry-after";
|
|
123
|
+
const raw = headers && typeof headers.get === "function"
|
|
124
|
+
? headers.get(retryAfterHeader)
|
|
125
|
+
: headers?.[retryAfterHeader];
|
|
126
|
+
const seconds = Number(raw);
|
|
127
|
+
if (!Number.isFinite(seconds) || seconds < 0) {
|
|
128
|
+
return 1000;
|
|
129
|
+
}
|
|
130
|
+
return Math.min(seconds * 1000, 2000);
|
|
131
|
+
};
|
|
132
|
+
const delay = async (ms) => {
|
|
133
|
+
if (ms <= 0) {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
await new Promise((resolve) => {
|
|
137
|
+
setTimeout(resolve, ms);
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
const slackErrorCode = (data) => data?.error ?? "unknown_error";
|
|
141
|
+
const throwSlackApiError = (method, data) => {
|
|
142
|
+
const slackError = slackErrorCode(data);
|
|
143
|
+
logger_1.logger.warn("Slack Web API returned an error", { method, slackError });
|
|
144
|
+
const status = slackError === "name_taken" ? 409 : 502;
|
|
145
|
+
const title = slackError === "name_taken"
|
|
146
|
+
? "Slack channel name is already taken"
|
|
147
|
+
: "Slack API request failed";
|
|
148
|
+
throw new errors_1.APIError({
|
|
149
|
+
code: `slack-${slackError.replaceAll("_", "-")}`,
|
|
150
|
+
detail: `${method}: ${slackError}`,
|
|
151
|
+
status,
|
|
152
|
+
title,
|
|
153
|
+
});
|
|
154
|
+
};
|
|
155
|
+
const isRateLimited = (error, data) => {
|
|
156
|
+
if (data?.error === "ratelimited") {
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
return (0, axios_1.isAxiosError)(error) && error.response?.status === 429;
|
|
160
|
+
};
|
|
161
|
+
const callSlackApi = async ({ method, body, params, token, acceptApplicationError = false, }) => {
|
|
162
|
+
const botToken = requireSlackToken(token);
|
|
163
|
+
const headers = { Authorization: `Bearer ${botToken}` };
|
|
164
|
+
let lastTransportError;
|
|
165
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
166
|
+
try {
|
|
167
|
+
const response = body
|
|
168
|
+
? await axios_1.default.post(`${SLACK_API_URL}/${method}`, body, { headers })
|
|
169
|
+
: await axios_1.default.get(`${SLACK_API_URL}/${method}`, { headers, params });
|
|
170
|
+
const data = response.data;
|
|
171
|
+
if (!data) {
|
|
172
|
+
throwSlackApiError(method, undefined);
|
|
173
|
+
}
|
|
174
|
+
if (data?.error === "ratelimited" && attempt < MAX_ATTEMPTS) {
|
|
175
|
+
await delay(retryAfterMs(response.headers));
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (data?.ok || acceptApplicationError) {
|
|
179
|
+
return data;
|
|
180
|
+
}
|
|
181
|
+
throwSlackApiError(method, data);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if ((0, errors_1.isAPIError)(error)) {
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
if (isRateLimited(error) && attempt < MAX_ATTEMPTS) {
|
|
188
|
+
const response = (0, axios_1.isAxiosError)(error) ? error.response : undefined;
|
|
189
|
+
await delay(retryAfterMs(response?.headers));
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
lastTransportError = error;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const message = (0, errors_1.errorMessage)(lastTransportError);
|
|
197
|
+
logger_1.logger.error("Slack Web API transport failed", { message, method });
|
|
198
|
+
Sentry.captureException(lastTransportError);
|
|
199
|
+
throw new errors_1.APIError({
|
|
200
|
+
code: "slack-transport-failed",
|
|
201
|
+
detail: `${method}: ${message}`,
|
|
202
|
+
status: 502,
|
|
203
|
+
title: "Slack API request failed",
|
|
204
|
+
});
|
|
205
|
+
};
|
|
206
|
+
const mentionPrefix = (mentionUserIds) => {
|
|
207
|
+
const { validUserIds, invalidUserIds } = partitionUserIds(mentionUserIds ?? []);
|
|
208
|
+
for (const value of invalidUserIds) {
|
|
209
|
+
logger_1.logger.warn("Skipping Slack mention; value is not a Slack member id", { value });
|
|
210
|
+
}
|
|
211
|
+
return validUserIds.map((id) => `<@${id}>`).join(" ");
|
|
212
|
+
};
|
|
213
|
+
const inviteBatches = async (channelId, userIds, token) => {
|
|
214
|
+
const invitedUserIds = [];
|
|
215
|
+
const alreadyMemberUserIds = [];
|
|
216
|
+
const failures = [];
|
|
217
|
+
for (let index = 0; index < userIds.length; index += INVITE_BATCH_SIZE) {
|
|
218
|
+
const batch = userIds.slice(index, index + INVITE_BATCH_SIZE);
|
|
219
|
+
const data = await callSlackApi({
|
|
220
|
+
acceptApplicationError: true,
|
|
221
|
+
body: { channel: channelId, force: true, users: batch.join(",") },
|
|
222
|
+
method: "conversations.invite",
|
|
223
|
+
token,
|
|
224
|
+
});
|
|
225
|
+
const topLevelError = data.error ?? "";
|
|
226
|
+
if (!data.ok && FATAL_INVITE_ERRORS.has(topLevelError) && !data.errors?.length) {
|
|
227
|
+
throwSlackApiError("conversations.invite", data);
|
|
228
|
+
}
|
|
229
|
+
if (!data.ok && topLevelError === "already_in_channel" && !data.errors?.length) {
|
|
230
|
+
alreadyMemberUserIds.push(...batch);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (!data.ok && !data.errors?.length) {
|
|
234
|
+
throwSlackApiError("conversations.invite", data);
|
|
235
|
+
}
|
|
236
|
+
if (!data.errors?.length) {
|
|
237
|
+
invitedUserIds.push(...batch);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const accounted = new Set();
|
|
241
|
+
for (const entry of data.errors) {
|
|
242
|
+
const userId = entry.user ? (0, slackNotifier_1.normalizeSlackUserId)(entry.user) : undefined;
|
|
243
|
+
if (!userId) {
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
accounted.add(userId);
|
|
247
|
+
if (entry.error === "already_in_channel") {
|
|
248
|
+
alreadyMemberUserIds.push(userId);
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
failures.push({ error: entry.error ?? "unknown_error", userId });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (data.ok) {
|
|
255
|
+
invitedUserIds.push(...batch.filter((id) => !accounted.has(id)));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { alreadyMemberUserIds, failures, invitedUserIds };
|
|
259
|
+
};
|
|
260
|
+
/**
|
|
261
|
+
* Create a private channel in the workspace for `SLACK_BOT_TOKEN`, invite
|
|
262
|
+
* members, and optionally post the first message.
|
|
263
|
+
*
|
|
264
|
+
* Requires bot scopes `groups:write`, `groups:write.invites`, and `chat:write`.
|
|
265
|
+
* `name_taken` throws a 409. Call `findSlackChannelByName` to reuse a channel
|
|
266
|
+
* the bot can already see.
|
|
267
|
+
*/
|
|
268
|
+
const createSlackPrivateChannel = async ({ name, userIds = [], initialMessage, mentionUserIds, token, }) => {
|
|
269
|
+
const channelName = (0, exports.normalizeSlackChannelName)(name);
|
|
270
|
+
const { validUserIds, invalidUserIds } = partitionUserIds(userIds);
|
|
271
|
+
if (userIds.length > 0 && validUserIds.length === 0) {
|
|
272
|
+
throw new errors_1.APIError({
|
|
273
|
+
code: "slack-user-id-invalid",
|
|
274
|
+
status: 400,
|
|
275
|
+
title: "Slack invite requires member ids",
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
for (const value of invalidUserIds) {
|
|
279
|
+
logger_1.logger.warn("Skipping Slack invite; value is not a Slack member id", { value });
|
|
280
|
+
}
|
|
281
|
+
const created = await callSlackApi({
|
|
282
|
+
body: { is_private: true, name: channelName },
|
|
283
|
+
method: "conversations.create",
|
|
284
|
+
token,
|
|
285
|
+
});
|
|
286
|
+
const channelId = created.channel?.id?.toUpperCase();
|
|
287
|
+
if (!channelId) {
|
|
288
|
+
throw new errors_1.APIError({
|
|
289
|
+
code: "slack-channel-missing",
|
|
290
|
+
detail: "conversations.create",
|
|
291
|
+
status: 502,
|
|
292
|
+
title: "Slack API request failed",
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
let invites = {
|
|
296
|
+
alreadyMemberUserIds: [],
|
|
297
|
+
failures: invalidUserIds.map((value) => ({ error: "invalid_user_id", userId: value })),
|
|
298
|
+
invitedUserIds: [],
|
|
299
|
+
};
|
|
300
|
+
if (validUserIds.length > 0) {
|
|
301
|
+
try {
|
|
302
|
+
const invited = await inviteBatches(channelId, validUserIds, token);
|
|
303
|
+
invites = {
|
|
304
|
+
...invited,
|
|
305
|
+
failures: [...invites.failures, ...invited.failures],
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
if (!(0, errors_1.isAPIError)(error)) {
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
throw new errors_1.APIError({
|
|
313
|
+
code: error.code,
|
|
314
|
+
detail: error.detail,
|
|
315
|
+
meta: { channelId, channelName },
|
|
316
|
+
status: error.status,
|
|
317
|
+
title: error.title,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const text = initialMessage?.trim();
|
|
322
|
+
if (!text && !mentionUserIds?.length) {
|
|
323
|
+
return { channelId, invites, name: created.channel?.name ?? channelName };
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const posted = await (0, exports.postSlackMessage)({
|
|
327
|
+
channelId,
|
|
328
|
+
mentionUserIds,
|
|
329
|
+
text: text ?? "",
|
|
330
|
+
token,
|
|
331
|
+
});
|
|
332
|
+
return {
|
|
333
|
+
channelId,
|
|
334
|
+
invites,
|
|
335
|
+
messageTs: posted.messageTs,
|
|
336
|
+
name: created.channel?.name ?? channelName,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
if (!(0, errors_1.isAPIError)(error)) {
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
throw new errors_1.APIError({
|
|
344
|
+
code: "slack-initial-message-failed",
|
|
345
|
+
detail: error.detail,
|
|
346
|
+
meta: { channelId, channelName },
|
|
347
|
+
status: error.status,
|
|
348
|
+
title: "Slack initial message failed",
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
exports.createSlackPrivateChannel = createSlackPrivateChannel;
|
|
353
|
+
/**
|
|
354
|
+
* Invite staff to a channel the bot already belongs to. Private channels do
|
|
355
|
+
* not allow a bot to join itself; invite the app once, then call this.
|
|
356
|
+
*
|
|
357
|
+
* `groups:write.invites` covers private channels. `channels:write.invites`
|
|
358
|
+
* covers public channels. Member IDs that are already in the channel are
|
|
359
|
+
* reported on `alreadyMemberUserIds` and do not fail the call.
|
|
360
|
+
*/
|
|
361
|
+
const inviteSlackUsersToChannel = async ({ channelId, userIds, token, }) => {
|
|
362
|
+
const normalizedChannelId = requireChannelId(channelId);
|
|
363
|
+
const { validUserIds, invalidUserIds } = partitionUserIds(userIds);
|
|
364
|
+
if (validUserIds.length === 0) {
|
|
365
|
+
throw new errors_1.APIError({
|
|
366
|
+
code: "slack-user-id-invalid",
|
|
367
|
+
status: 400,
|
|
368
|
+
title: "Slack invite requires member ids",
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
const invited = await inviteBatches(normalizedChannelId, validUserIds, token);
|
|
372
|
+
return {
|
|
373
|
+
...invited,
|
|
374
|
+
failures: [
|
|
375
|
+
...invalidUserIds.map((value) => ({ error: "invalid_user_id", userId: value })),
|
|
376
|
+
...invited.failures,
|
|
377
|
+
],
|
|
378
|
+
};
|
|
379
|
+
};
|
|
380
|
+
exports.inviteSlackUsersToChannel = inviteSlackUsersToChannel;
|
|
381
|
+
/** Post as the bot with `chat:write`. The bot must already be in the channel. */
|
|
382
|
+
const postSlackMessage = async ({ channelId, text, blocks, mentionUserIds, token, }) => {
|
|
383
|
+
const normalizedChannelId = requireChannelId(channelId);
|
|
384
|
+
const prefix = mentionPrefix(mentionUserIds);
|
|
385
|
+
const body = text.trim();
|
|
386
|
+
if (!prefix && !body) {
|
|
387
|
+
throw new errors_1.APIError({
|
|
388
|
+
code: "slack-message-empty",
|
|
389
|
+
status: 400,
|
|
390
|
+
title: "Slack message text is required",
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
const payload = {
|
|
394
|
+
channel: normalizedChannelId,
|
|
395
|
+
text: prefix && body ? `${prefix} ${body}` : prefix || body,
|
|
396
|
+
};
|
|
397
|
+
if (blocks) {
|
|
398
|
+
payload.blocks = blocks;
|
|
399
|
+
}
|
|
400
|
+
const posted = await callSlackApi({
|
|
401
|
+
body: payload,
|
|
402
|
+
method: "chat.postMessage",
|
|
403
|
+
token,
|
|
404
|
+
});
|
|
405
|
+
if (!posted.ts) {
|
|
406
|
+
throw new errors_1.APIError({
|
|
407
|
+
code: "slack-message-missing",
|
|
408
|
+
detail: "chat.postMessage",
|
|
409
|
+
status: 502,
|
|
410
|
+
title: "Slack API request failed",
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
return { channelId: normalizedChannelId, messageTs: posted.ts };
|
|
414
|
+
};
|
|
415
|
+
exports.postSlackMessage = postSlackMessage;
|
|
416
|
+
/**
|
|
417
|
+
* Find a public channel, or a private channel the bot is already in.
|
|
418
|
+
* Returns undefined when the name is not visible to the bot. Archived
|
|
419
|
+
* channels are skipped. Requires `channels:read` and `groups:read`.
|
|
420
|
+
*/
|
|
421
|
+
const findSlackChannelByName = async ({ name, token, }) => {
|
|
422
|
+
const channelName = (0, exports.normalizeSlackChannelName)(name);
|
|
423
|
+
let cursor = "";
|
|
424
|
+
for (let page = 0; page < MAX_CHANNEL_PAGES; page++) {
|
|
425
|
+
const listed = await callSlackApi({
|
|
426
|
+
method: "conversations.list",
|
|
427
|
+
params: {
|
|
428
|
+
cursor,
|
|
429
|
+
exclude_archived: true,
|
|
430
|
+
limit: 200,
|
|
431
|
+
types: "public_channel,private_channel",
|
|
432
|
+
},
|
|
433
|
+
token,
|
|
434
|
+
});
|
|
435
|
+
const match = listed.channels?.find((channel) => {
|
|
436
|
+
const candidate = (channel.name_normalized ?? channel.name ?? "").toLowerCase();
|
|
437
|
+
return candidate === channelName && Boolean(channel.id);
|
|
438
|
+
});
|
|
439
|
+
if (match?.id) {
|
|
440
|
+
return {
|
|
441
|
+
channelId: match.id.toUpperCase(),
|
|
442
|
+
isPrivate: Boolean(match.is_private),
|
|
443
|
+
name: match.name ?? channelName,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
cursor = listed.response_metadata?.next_cursor ?? "";
|
|
447
|
+
if (!cursor) {
|
|
448
|
+
return undefined;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return undefined;
|
|
452
|
+
};
|
|
453
|
+
exports.findSlackChannelByName = findSlackChannelByName;
|