-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathSlackClientFactory.ts
276 lines (254 loc) · 10.3 KB
/
SlackClientFactory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { Datastore, TeamEntry } from "./datastore/Models";
import { WebClient, WebClientOptions, LogLevel, Logger as SlackLogger, WebAPIPlatformError } from "@slack/web-api";
import { Logger } from "matrix-appservice-bridge";
import { TeamInfoResponse, AuthTestResponse, UsersInfoResponse } from "./SlackResponses";
import { HttpsProxyAgent } from 'https-proxy-agent';
const webLog = new Logger("slack-api");
const log = new Logger("SlackClientFactory");
/**
* How long should we wait before checking if a token is still valid.
*/
const AUTH_INTERVAL_MS = 5 * 60000;
/**
* This class holds clients for slack teams and individuals users
* who are puppeting their accounts.
*/
interface RequiredConfigOptions {
slack_client_opts?: WebClientOptions;
slack_proxy?: string;
auth_interval_ms?: number;
}
interface StoredClient {
lastTestTs: number;
client: WebClient;
}
export class SlackClientFactory {
private teamClients: Map<string, StoredClient> = new Map();
private puppets: Map<string, {client: WebClient, id: string}> = new Map();
constructor(
private datastore: Datastore,
private config: RequiredConfigOptions = {},
private onRemoteCall?: (method: string) => void,
private updatePuppetCount?: (teamId: string, delta: number) => void
) {
}
public async createClient(token: string): Promise<WebClient> {
const opts = this.config.slack_client_opts ? this.config.slack_client_opts : {};
if (this.config.slack_proxy) {
opts.agent = new HttpsProxyAgent(this.config.slack_proxy);
}
return new WebClient(token, {
logger: {
getLevel: () => LogLevel.DEBUG,
setLevel: () => {}, // We don't care about these.
setName: () => {},
debug: (msg: string) => {
// non-ideal way to detect calls to slack.
webLog.debug.bind(webLog);
if (!this.onRemoteCall) { return; }
const match = /apiCall\('([\w.]+)'\) start/.exec(msg);
if (match && match[1]) {
this.onRemoteCall(match[1]);
}
webLog.debug(msg);
},
warn: webLog.warn.bind(webLog),
info: webLog.info.bind(webLog),
error: webLog.error.bind(webLog),
} as SlackLogger,
logLevel: LogLevel.DEBUG,
...opts,
});
}
/**
* Gets a team entry from the datastore and checks if the token
* is safe to use.
* @param teamId The slack teamId to check.
* @throws If the team is not safe to use
*/
public async isTeamStatusOkay(teamId: string): Promise<void> {
const storedTeam = await this.datastore.getTeam(teamId);
if (!storedTeam) {
throw Error(`Team ${teamId} is not ready: No team found in store`);
}
if (storedTeam.status === "bad_auth") {
throw Error(`Team ${teamId} is not usable: Team previously failed to auth and is disabled`);
}
if (storedTeam.status === "archived") {
throw Error(`Team ${teamId} is not usable: Team is archived`);
}
if (!storedTeam.bot_token) {
throw Error(`Team ${teamId} is not usable: No token stored`);
}
}
public get teamClientCount(): number {
return this.teamClients.size;
}
/**
* Gets a WebClient for a given teamId. If one has already been
* created, the cached client is returned.
* @param teamId The slack team_id.
* @throws If the team client fails to be created.
*/
public async getTeamClient(teamId: string): Promise<WebClient> {
if (this.teamClients.has(teamId)) {
const set = this.teamClients.get(teamId);
// Check the auth on the client every AUTH_INTERVAL_MS, and if it fails, refetch the team.
if (set && Date.now() - set.lastTestTs < (this.config.auth_interval_ms || AUTH_INTERVAL_MS)) {
// set has not expired
return set.client;
} else if (set) {
// set has expired
try {
const testRes = await set.client.auth.test();
if (!testRes.ok) {
throw Error(testRes.error);
}
set.lastTestTs = Date.now();
this.teamClients.set(teamId, set);
return set.client;
} catch (ex) {
// Fall through.
log.error(`Failed to authenticate ${teamId}: ${ex}`);
}
}
// no set, or invalid client
}
const teamEntry = await this.datastore.getTeam(teamId);
if (!teamEntry) {
// We might have cached this in the past, throw it away.
this.teamClients.delete(teamId);
throw Error(`No team found in store for ${teamId}`);
}
// Check that the team is actually usable.
await this.isTeamStatusOkay(teamId);
log.info("Creating new team client for", teamId);
try {
const { slackClient, team, user } = await this.createTeamClient(teamEntry.bot_token!);
// Call this to get our identity.
teamEntry.domain = team.domain;
teamEntry.name = team.name;
teamEntry.bot_id = user.user!.profile!.bot_id!;
teamEntry.user_id = user.user!.id!;
teamEntry.status = "ok";
this.teamClients.set(teamId, {
client: slackClient,
lastTestTs: Date.now(),
});
return slackClient;
} catch (ex) {
log.warn(`Failed to authenticate for ${teamId}`, ex);
// This team was previously working at one point, and now
// isn't.
teamEntry.status = "bad_auth";
throw ex;
} finally {
log.debug(`Team status is ${teamEntry.status}`);
await this.datastore.upsertTeam(teamEntry);
}
}
/**
* Checks a token, and inserts the team into the database if
* the team exists.
* @param token A Slack access token for a bot
* @returns The teamId of the owner team
*/
public async upsertTeamByToken(token: string): Promise<string> {
let teamRes: {id: string, name: string, domain: string};
let botId: string;
let userId: string;
try {
const { team , auth, user} = await this.createTeamClient(token);
// Call this to get our identity.
userId = auth.user_id;
botId = user.user!.profile!.bot_id!;
teamRes = team;
} catch (ex) {
log.warn(`Failed to authenticate`, ex);
throw ex;
}
const existingTeam = (await this.datastore.getTeam(teamRes.id));
const teamEntry: TeamEntry = {
id: teamRes!.id,
scopes: existingTeam ? existingTeam.scopes : "", // Unknown
domain: teamRes!.domain,
name: teamRes!.name,
user_id: userId,
bot_id: botId,
status: "ok",
bot_token: token,
};
await this.datastore.upsertTeam(teamEntry);
return teamRes!.id;
}
public async getClientForUserWithId(teamId: string, matrixUser: string): Promise<{client: WebClient, id: string}|null> {
const key = `${teamId}:${matrixUser}`;
if (this.puppets.has(key)) {
return this.puppets.get(key) || null;
}
const token = await this.datastore.getPuppetTokenByMatrixId(teamId, matrixUser);
if (!token) {
return null;
}
const client = new WebClient(token);
let id: string;
try {
const res = (await client.auth.test()) as AuthTestResponse;
id = res.user_id;
} catch (ex) {
log.warn("Failed to auth puppeted client for user:", ex);
return null;
}
this.puppets.set(key, {id, client});
return {id, client};
}
public async getClientForSlackUser(teamId: string, slackId: string): Promise<{client: WebClient, id: string}|null> {
const user = await this.datastore.getPuppetMatrixUserBySlackId(teamId, slackId);
if (user) {
return this.getClientForUserWithId(teamId, user);
}
return null;
}
public async getClientForUser(teamId: string, matrixUser: string): Promise<WebClient|null> {
const res = await this.getClientForUserWithId(teamId, matrixUser);
return res !== null ? res.client : null;
}
public async getClientsForUser(matrixUser: string): Promise<WebClient[]> {
const clients: WebClient[] = [];
// This is not particularly great for performance, but I'm not in the
// mood for yet-another-refactor.
for (const [teamIdUserId, client] of this.puppets.entries()) {
// This is safe, teams don't contain a @.
// Users may only start with one.
if (teamIdUserId.endsWith(matrixUser)) {
clients.push(client.client);
}
}
return clients;
}
public async createTeamClient(token: string): Promise<{
slackClient: WebClient,
team: { id: string, name: string, domain: string },
auth: AuthTestResponse,
user: UsersInfoResponse,
}> {
try {
const slackClient = await this.createClient(token);
const teamInfo = (await slackClient.team.info()) as TeamInfoResponse;
const auth = (await slackClient.auth.test()) as AuthTestResponse;
const user = (await slackClient.users.info({user: auth.user_id})) as UsersInfoResponse;
log.debug("Created new team client for", teamInfo.team.name);
if (this.updatePuppetCount) {
this.updatePuppetCount(teamInfo.team.id, 1);
}
return { slackClient, team: teamInfo.team, auth, user };
} catch (ex) {
const error = ex as WebAPIPlatformError;
log.error("Could not create team client: " + (error.data?.error || ex));
throw Error("Could not create team client");
}
}
public async dropTeamClient(teamId: string): Promise<void> {
this.teamClients.delete(teamId);
}
}