@app-vitals/agent-admin 1.62.0 → 1.64.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.
@@ -6,13 +6,21 @@
6
6
 
7
7
  import { afterEach, beforeEach, describe, expect, it } from "bun:test";
8
8
  import type { PrismaClient } from "../prisma/client/client.ts";
9
+ import type { Clock } from "./clock.ts";
9
10
  import { createAdminPrismaClient } from "./prisma-client.ts";
10
11
  import {
12
+ isSlackConfigTokenRevokedError,
13
+ SlackConfigRefreshTokenInvalidError,
11
14
  SlackConfigTokenEncryptionUnavailableError,
15
+ SlackConfigTokenNotConfiguredError,
12
16
  SlackConfigTokenService,
13
17
  toSlackConfigTokenMetadata,
14
18
  } from "./slack-config-token.ts";
15
- import { makeStrictTokenCrypto } from "./token-crypto.ts";
19
+ import {
20
+ type SlackConfigTokenClient,
21
+ SlackConfigTokenError,
22
+ } from "./slack-provisioning-client.ts";
23
+ import { makeStrictTokenCrypto, type TokenCrypto } from "./token-crypto.ts";
16
24
 
17
25
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
18
26
  const describeOrSkip = TEST_DB ? describe : describe.skip;
@@ -206,3 +214,392 @@ describe("toSlackConfigTokenMetadata", () => {
206
214
  expect(out.accessTokenSet).toBe(true);
207
215
  });
208
216
  });
217
+
218
+ // ─── getAccessToken / withSlackConfigAccessToken ─────────────────────────────
219
+
220
+ class MutableClock implements Clock {
221
+ constructor(public current: Date) {}
222
+ now(): Date {
223
+ return new Date(this.current);
224
+ }
225
+ advance(ms: number): void {
226
+ this.current = new Date(this.current.getTime() + ms);
227
+ }
228
+ }
229
+
230
+ type RotateResult = Awaited<
231
+ ReturnType<SlackConfigTokenClient["rotateConfigToken"]>
232
+ >;
233
+
234
+ /** Rotate client double: hands out a fresh numbered pair per call. */
235
+ class FakeRotateClient implements SlackConfigTokenClient {
236
+ calls: string[] = [];
237
+ delayMs = 0;
238
+ failWith: SlackConfigTokenError | null = null;
239
+ constructor(private clock: Clock) {}
240
+ async rotateConfigToken(refreshToken: string): Promise<RotateResult> {
241
+ this.calls.push(refreshToken);
242
+ const n = this.calls.length;
243
+ if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
244
+ if (this.failWith) throw this.failWith;
245
+ const iat = Math.floor(this.clock.now().getTime() / 1000);
246
+ return {
247
+ accessToken: `rotated-access-${n}-SUPERSECRET`,
248
+ refreshToken: `rotated-refresh-${n}-SUPERSECRET`,
249
+ teamId: `T${n}`,
250
+ userId: `U${n}`,
251
+ iat,
252
+ exp: iat + 12 * 3600,
253
+ };
254
+ }
255
+ }
256
+
257
+ const MIN = 60_000;
258
+
259
+ describeOrSkip("SlackConfigTokenService.getAccessToken (integration)", () => {
260
+ let prisma: PrismaClient;
261
+ let crypto: TokenCrypto;
262
+ let clock: MutableClock;
263
+ let rotate: FakeRotateClient;
264
+ let service: SlackConfigTokenService;
265
+ let acctA: string;
266
+
267
+ const row = (accountId: string | null) =>
268
+ prisma.slackConfigToken.findFirstOrThrow({ where: { accountId } });
269
+
270
+ beforeEach(async () => {
271
+ prisma = createAdminPrismaClient(TEST_DB as string);
272
+ await prisma.slackConfigToken.deleteMany();
273
+ await prisma.agentTemplateItem.deleteMany();
274
+ await prisma.agentTemplate.deleteMany();
275
+ await prisma.agent.deleteMany();
276
+ await prisma.accountInvite.deleteMany();
277
+ await prisma.accountMember.deleteMany();
278
+ await prisma.account.deleteMany();
279
+ acctA = (await prisma.account.create({ data: { name: "A" } })).id;
280
+ crypto = makeStrictTokenCrypto(KEY) as TokenCrypto;
281
+ // Whole seconds so exp (unix seconds) round-trips exactly.
282
+ clock = new MutableClock(new Date("2030-01-01T00:00:00Z"));
283
+ rotate = new FakeRotateClient(clock);
284
+ service = new SlackConfigTokenService(prisma, crypto, clock, rotate);
285
+ });
286
+
287
+ afterEach(async () => {
288
+ await prisma.$disconnect();
289
+ });
290
+
291
+ it("cache hit: returns the stored access token without calling Slack", async () => {
292
+ await service.save(acctA, {
293
+ refreshToken: REFRESH,
294
+ accessToken: ACCESS,
295
+ accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * MIN),
296
+ });
297
+ expect(await service.getAccessToken(acctA)).toBe(ACCESS);
298
+ expect(rotate.calls).toEqual([]);
299
+ });
300
+
301
+ it("rotates when the cached token has 10 minutes or less left, persisting the new pair", async () => {
302
+ await service.save(null, {
303
+ refreshToken: REFRESH,
304
+ accessToken: ACCESS,
305
+ accessTokenExpiresAt: new Date(clock.now().getTime() + 10 * MIN),
306
+ });
307
+ clock.advance(MIN);
308
+ const token = await service.getAccessToken(null);
309
+ expect(token).toBe("rotated-access-1-SUPERSECRET");
310
+ expect(rotate.calls).toEqual([REFRESH]);
311
+
312
+ const r = await row(null);
313
+ expect(crypto.decrypt(r.refreshTokenEncrypted)).toBe(
314
+ "rotated-refresh-1-SUPERSECRET",
315
+ );
316
+ expect(crypto.decrypt(r.accessTokenEncrypted as string)).toBe(token);
317
+ expect(r.accessTokenExpiresAt).toEqual(
318
+ new Date(clock.now().getTime() + 12 * 3600 * 1000),
319
+ );
320
+ expect(r.slackTeamId).toBe("T1");
321
+ expect(r.slackUserId).toBe("U1");
322
+ expect(r.lastRotatedAt).toEqual(clock.now());
323
+ expect(r.lastError).toBeNull();
324
+
325
+ // The persisted token is now a cache hit.
326
+ expect(await service.getAccessToken(null)).toBe(token);
327
+ expect(rotate.calls.length).toBe(1);
328
+ });
329
+
330
+ it("rotates when no access token is cached", async () => {
331
+ await service.save(acctA, { refreshToken: REFRESH });
332
+ expect(await service.getAccessToken(acctA)).toBe(
333
+ "rotated-access-1-SUPERSECRET",
334
+ );
335
+ expect(rotate.calls).toEqual([REFRESH]);
336
+ });
337
+
338
+ it("uses the exact scope row only", async () => {
339
+ await service.save(null, { refreshToken: REFRESH });
340
+ await expect(service.getAccessToken(acctA)).rejects.toBeInstanceOf(
341
+ SlackConfigTokenNotConfiguredError,
342
+ );
343
+ expect(rotate.calls).toEqual([]);
344
+ });
345
+
346
+ it("serializes concurrent callers on a stale token: exactly one rotate, same token for all", async () => {
347
+ await service.save(acctA, {
348
+ refreshToken: REFRESH,
349
+ accessToken: ACCESS,
350
+ accessTokenExpiresAt: new Date(clock.now().getTime() - MIN),
351
+ });
352
+ rotate.delayMs = 150;
353
+ const results = await Promise.all(
354
+ Array.from({ length: 5 }, () => service.getAccessToken(acctA)),
355
+ );
356
+ expect(rotate.calls).toEqual([REFRESH]);
357
+ expect(new Set(results)).toEqual(new Set(["rotated-access-1-SUPERSECRET"]));
358
+ });
359
+
360
+ it("serializes across service instances (replicas) too", async () => {
361
+ await service.save(acctA, { refreshToken: REFRESH });
362
+ rotate.delayMs = 150;
363
+ const other = new SlackConfigTokenService(
364
+ createAdminPrismaClient(TEST_DB as string),
365
+ crypto,
366
+ clock,
367
+ rotate,
368
+ );
369
+ const results = await Promise.all([
370
+ service.getAccessToken(acctA),
371
+ other.getAccessToken(acctA),
372
+ service.getAccessToken(acctA),
373
+ ]);
374
+ expect(rotate.calls.length).toBe(1);
375
+ expect(new Set(results).size).toBe(1);
376
+ });
377
+
378
+ it("does not return the token when persisting the rotated pair fails", async () => {
379
+ // A crypto whose ciphertext for the new refresh token contains a NUL byte,
380
+ // which Postgres rejects in a TEXT column: a real write failure.
381
+ const failing: TokenCrypto = {
382
+ encrypt: (t) =>
383
+ t.startsWith("rotated-refresh-")
384
+ ? "bad\u0000cipher"
385
+ : crypto.encrypt(t),
386
+ decrypt: (t) => crypto.decrypt(t),
387
+ };
388
+ await service.save(acctA, { refreshToken: REFRESH });
389
+ const broken = new SlackConfigTokenService(prisma, failing, clock, rotate);
390
+ let caught: unknown;
391
+ try {
392
+ await broken.getAccessToken(acctA);
393
+ } catch (err) {
394
+ caught = err;
395
+ }
396
+ expect(caught).toBeInstanceOf(Error);
397
+ expect(String((caught as Error).message)).not.toContain("SUPERSECRET");
398
+ expect(rotate.calls.length).toBe(1);
399
+ // Rolled back: the original pair is still stored.
400
+ const r = await row(acctA);
401
+ expect(crypto.decrypt(r.refreshTokenEncrypted)).toBe(REFRESH);
402
+ expect(r.accessTokenEncrypted).toBeNull();
403
+ });
404
+
405
+ it("invalid_refresh_token records lastError and surfaces a regenerate error", async () => {
406
+ await service.save(acctA, {
407
+ refreshToken: REFRESH,
408
+ accessToken: ACCESS,
409
+ accessTokenExpiresAt: new Date(clock.now().getTime() - MIN),
410
+ });
411
+ const before = await row(acctA);
412
+ rotate.failWith = new SlackConfigTokenError(
413
+ "invalid_refresh_token",
414
+ "Slack tooling.tokens.rotate failed: invalid_refresh_token",
415
+ );
416
+ let caught: unknown;
417
+ try {
418
+ await service.getAccessToken(acctA);
419
+ } catch (err) {
420
+ caught = err;
421
+ }
422
+ expect(caught).toBeInstanceOf(SlackConfigRefreshTokenInvalidError);
423
+ const msg = (caught as Error).message;
424
+ expect(msg).toMatch(/regenerate/i);
425
+ expect(msg).not.toContain("SUPERSECRET");
426
+ const after = await row(acctA);
427
+ expect(after.lastError).toContain("invalid_refresh_token");
428
+ expect(after.lastError).not.toContain("SUPERSECRET");
429
+ // Token material untouched.
430
+ expect(after.refreshTokenEncrypted).toBe(before.refreshTokenEncrypted);
431
+ expect(after.accessTokenEncrypted).toBe(before.accessTokenEncrypted);
432
+ expect((await service.get(acctA))?.lastError).toBe(after.lastError);
433
+ });
434
+
435
+ it("other rotate errors record the code without touching tokens", async () => {
436
+ await service.save(null, { refreshToken: REFRESH });
437
+ const before = await row(null);
438
+ rotate.failWith = new SlackConfigTokenError(
439
+ "http_error",
440
+ "Slack tooling.tokens.rotate HTTP error: 503 Service Unavailable",
441
+ );
442
+ await expect(service.getAccessToken(null)).rejects.toThrow(/http_error/);
443
+ const after = await row(null);
444
+ expect(after.lastError).toContain("http_error");
445
+ expect(after.refreshTokenEncrypted).toBe(before.refreshTokenEncrypted);
446
+ });
447
+
448
+ it("a successful rotate clears a previous lastError", async () => {
449
+ await service.save(null, { refreshToken: REFRESH });
450
+ rotate.failWith = new SlackConfigTokenError("http_error", "boom");
451
+ await expect(service.getAccessToken(null)).rejects.toThrow();
452
+ rotate.failWith = null;
453
+ await service.getAccessToken(null);
454
+ expect((await row(null)).lastError).toBeNull();
455
+ });
456
+
457
+ it("forceRotate rotates even with a valid cached token", async () => {
458
+ await service.save(acctA, {
459
+ refreshToken: REFRESH,
460
+ accessToken: ACCESS,
461
+ accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * 3600 * 1000),
462
+ });
463
+ expect(await service.getAccessToken(acctA, { forceRotate: true })).toBe(
464
+ "rotated-access-1-SUPERSECRET",
465
+ );
466
+ expect(rotate.calls).toEqual([REFRESH]);
467
+ });
468
+
469
+ it("forceRotate with rejectedAccessToken reuses a token another caller already rotated to", async () => {
470
+ await service.save(acctA, { refreshToken: REFRESH, accessToken: ACCESS });
471
+ // Another caller already rotated past the rejected token.
472
+ await service.save(acctA, {
473
+ refreshToken: "test-refresh-NEWER",
474
+ accessToken: "test-access-NEWER",
475
+ accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * 3600 * 1000),
476
+ });
477
+ expect(
478
+ await service.getAccessToken(acctA, {
479
+ forceRotate: true,
480
+ rejectedAccessToken: ACCESS,
481
+ }),
482
+ ).toBe("test-access-NEWER");
483
+ expect(rotate.calls).toEqual([]);
484
+ // Rejected token is still the stored one -> rotate.
485
+ expect(
486
+ await service.getAccessToken(acctA, {
487
+ forceRotate: true,
488
+ rejectedAccessToken: "test-access-NEWER",
489
+ }),
490
+ ).toBe("rotated-access-1-SUPERSECRET");
491
+ expect(rotate.calls).toEqual(["test-refresh-NEWER"]);
492
+ });
493
+
494
+ it("clear errors for a missing row, a missing key and a missing rotate client", async () => {
495
+ await expect(service.getAccessToken(acctA)).rejects.toBeInstanceOf(
496
+ SlackConfigTokenNotConfiguredError,
497
+ );
498
+ await service.save(acctA, { refreshToken: REFRESH });
499
+ await expect(
500
+ new SlackConfigTokenService(prisma, null, clock, rotate).getAccessToken(
501
+ acctA,
502
+ ),
503
+ ).rejects.toBeInstanceOf(SlackConfigTokenEncryptionUnavailableError);
504
+ await expect(
505
+ new SlackConfigTokenService(prisma, crypto, clock).getAccessToken(acctA),
506
+ ).rejects.toThrow(/SlackConfigTokenClient/);
507
+ expect(rotate.calls).toEqual([]);
508
+ });
509
+
510
+ describe("withSlackConfigAccessToken", () => {
511
+ beforeEach(async () => {
512
+ await service.save(acctA, {
513
+ refreshToken: REFRESH,
514
+ accessToken: ACCESS,
515
+ accessTokenExpiresAt: new Date(
516
+ clock.now().getTime() + 11 * 3600 * 1000,
517
+ ),
518
+ });
519
+ });
520
+
521
+ it("runs fn with the cached token", async () => {
522
+ const seen: string[] = [];
523
+ const out = await service.withSlackConfigAccessToken(acctA, async (t) => {
524
+ seen.push(t);
525
+ return 42;
526
+ });
527
+ expect(out).toBe(42);
528
+ expect(seen).toEqual([ACCESS]);
529
+ expect(rotate.calls).toEqual([]);
530
+ });
531
+
532
+ it("on token_revoked force-rotates once and retries, then passes", async () => {
533
+ const seen: string[] = [];
534
+ const out = await service.withSlackConfigAccessToken(acctA, async (t) => {
535
+ seen.push(t);
536
+ if (t === ACCESS) {
537
+ // Shape thrown by HttpSlackProvisioningClient manifest calls.
538
+ throw new Error("Slack apps.manifest.update failed: token_revoked");
539
+ }
540
+ return "ok";
541
+ });
542
+ expect(out).toBe("ok");
543
+ expect(seen).toEqual([ACCESS, "rotated-access-1-SUPERSECRET"]);
544
+ expect(rotate.calls).toEqual([REFRESH]);
545
+ });
546
+
547
+ it("retries at most once: a second auth failure propagates, no loop", async () => {
548
+ let n = 0;
549
+ await expect(
550
+ service.withSlackConfigAccessToken(acctA, async () => {
551
+ n++;
552
+ throw new Error("Slack apps.manifest.delete failed: invalid_auth");
553
+ }),
554
+ ).rejects.toThrow(/invalid_auth/);
555
+ expect(n).toBe(2);
556
+ expect(rotate.calls.length).toBe(1);
557
+ });
558
+
559
+ it("does not retry on unrelated errors", async () => {
560
+ let n = 0;
561
+ await expect(
562
+ service.withSlackConfigAccessToken(acctA, async () => {
563
+ n++;
564
+ throw new Error(
565
+ "Slack apps.manifest.create failed: invalid_manifest",
566
+ );
567
+ }),
568
+ ).rejects.toThrow(/invalid_manifest/);
569
+ expect(n).toBe(1);
570
+ expect(rotate.calls).toEqual([]);
571
+ });
572
+ });
573
+ });
574
+
575
+ describe("isSlackConfigTokenRevokedError", () => {
576
+ it("matches manifest-call errors and coded errors for token_revoked / invalid_auth", () => {
577
+ expect(
578
+ isSlackConfigTokenRevokedError(
579
+ new Error("Slack apps.manifest.update failed: token_revoked"),
580
+ ),
581
+ ).toBe(true);
582
+ expect(
583
+ isSlackConfigTokenRevokedError(
584
+ new Error("Slack apps.manifest.create failed: invalid_auth"),
585
+ ),
586
+ ).toBe(true);
587
+ expect(
588
+ isSlackConfigTokenRevokedError(
589
+ new SlackConfigTokenError("token_revoked", "x"),
590
+ ),
591
+ ).toBe(true);
592
+ expect(
593
+ isSlackConfigTokenRevokedError(
594
+ new Error("Slack apps.manifest.create failed: invalid_manifest"),
595
+ ),
596
+ ).toBe(false);
597
+ expect(
598
+ isSlackConfigTokenRevokedError(
599
+ new Error("Slack apps.manifest.update failed: not_authed_revoked_x"),
600
+ ),
601
+ ).toBe(false);
602
+ expect(isSlackConfigTokenRevokedError("token_revoked")).toBe(false);
603
+ expect(isSlackConfigTokenRevokedError(null)).toBe(false);
604
+ });
605
+ });
@@ -7,13 +7,53 @@
7
7
  * Tokens are encrypted on write (AES-256-GCM via a strict TokenCrypto) and are
8
8
  * never returned by any read path: reads return metadata plus `*Set` flags.
9
9
  * save() refuses when no encryption key is configured (no plain-text fallback).
10
+ *
11
+ * getAccessToken() is the only path that decrypts. It serves the cached access
12
+ * token while it has more than 10 minutes left; otherwise it rotates via
13
+ * tooling.tokens.rotate under a row lock (SELECT ... FOR UPDATE) so replicas
14
+ * serialize, persists the new pair, and returns the access token only after
15
+ * that write commits. Slack rotation revokes the access token issued with the
16
+ * refresh token used, so a second rotate would break the first caller's token;
17
+ * the lock plus the cache re-check prevents that.
10
18
  */
11
19
 
12
20
  import type { PrismaClient } from "../prisma/client/client.ts";
13
21
  import { type Clock, SystemClock } from "./clock.ts";
14
- import { UnprocessableEntityError } from "./errors.ts";
22
+ import {
23
+ BadGatewayError,
24
+ NotFoundError,
25
+ UnprocessableEntityError,
26
+ } from "./errors.ts";
27
+ import type { SlackConfigTokenClient } from "./slack-provisioning-client.ts";
15
28
  import type { TokenCrypto } from "./token-crypto.ts";
16
29
 
30
+ /** A cached access token is reused only while it has more than this left. */
31
+ export const SLACK_CONFIG_ACCESS_TOKEN_MIN_REMAINING_MS = 10 * 60 * 1000;
32
+
33
+ /**
34
+ * Interactive transaction timeout for a rotation. The row lock is held across
35
+ * the Slack call, so this must exceed it; waiters queue on the lock inside
36
+ * their own transaction, so it also bounds how long they wait.
37
+ */
38
+ const ROTATE_TX_TIMEOUT_MS = 30_000;
39
+ const ROTATE_TX_MAX_WAIT_MS = 10_000;
40
+
41
+ export interface GetSlackConfigAccessTokenOptions {
42
+ /**
43
+ * Rotate even when the cached access token is still valid. Used for the one
44
+ * retry after Slack rejected the token (token_revoked / invalid_auth).
45
+ */
46
+ forceRotate?: boolean;
47
+ /**
48
+ * With forceRotate: the access token Slack rejected. If, once the row lock is
49
+ * held, the stored access token is a different still-valid token, another
50
+ * caller already rotated past the rejected one and that token is returned
51
+ * without a second rotate (which would revoke it). Without this, forceRotate
52
+ * always rotates.
53
+ */
54
+ rejectedAccessToken?: string;
55
+ }
56
+
17
57
  export interface SlackConfigTokenMetadata {
18
58
  id: string;
19
59
  /** null = deployment-wide default. */
@@ -81,6 +121,67 @@ export function toSlackConfigTokenMetadata(
81
121
  };
82
122
  }
83
123
 
124
+ /** No SlackConfigToken row exists for the requested scope. */
125
+ export class SlackConfigTokenNotConfiguredError extends NotFoundError {
126
+ constructor(accountId: string | null) {
127
+ super(
128
+ accountId === null
129
+ ? "No deployment-wide Slack config token is configured"
130
+ : `No Slack config token is configured for account ${accountId}`,
131
+ );
132
+ this.name = "SlackConfigTokenNotConfiguredError";
133
+ }
134
+ }
135
+
136
+ /** Slack rejected the stored refresh token; a human must regenerate it. */
137
+ export class SlackConfigRefreshTokenInvalidError extends UnprocessableEntityError {
138
+ constructor() {
139
+ super(
140
+ "The stored Slack config refresh token is no longer valid (invalid_refresh_token). Regenerate the App Configuration token in Slack (api.slack.com/apps, Your App Configuration Tokens) and save the new refresh token in agent admin settings.",
141
+ );
142
+ this.name = "SlackConfigRefreshTokenInvalidError";
143
+ }
144
+ }
145
+
146
+ /** tooling.tokens.rotate failed for any other reason. Carries the Slack/HTTP code only. */
147
+ export class SlackConfigTokenRotateFailedError extends BadGatewayError {
148
+ constructor(public readonly code: string) {
149
+ super(`Slack config token rotation failed: ${code}`);
150
+ this.name = "SlackConfigTokenRotateFailedError";
151
+ }
152
+ }
153
+
154
+ const REVOKED_CODES = new Set(["token_revoked", "invalid_auth"]);
155
+
156
+ /**
157
+ * True when `err` is Slack rejecting an access token (token_revoked or
158
+ * invalid_auth). Matches a `.code` (SlackConfigTokenError) and the plain
159
+ * `Error("Slack <method> failed: <code>")` that HttpSlackProvisioningClient's
160
+ * manifest calls throw.
161
+ */
162
+ export function isSlackConfigTokenRevokedError(err: unknown): boolean {
163
+ if (typeof err !== "object" || err === null) return false;
164
+ const code = (err as { code?: unknown }).code;
165
+ if (typeof code === "string" && REVOKED_CODES.has(code)) return true;
166
+ const message = (err as { message?: unknown }).message;
167
+ if (typeof message !== "string") return false;
168
+ const m = /\bfailed: ([a-z_]+)\s*$/.exec(message);
169
+ return !!m && REVOKED_CODES.has(m[1] as string);
170
+ }
171
+
172
+ function rotateErrorCode(err: unknown): string {
173
+ const code = (err as { code?: unknown } | null)?.code;
174
+ // Codes come from Slack's `error` field or the client's own constants; keep
175
+ // only a safe identifier so lastError can never carry token material.
176
+ return typeof code === "string" && /^[a-z0-9_]{1,64}$/i.test(code)
177
+ ? code
178
+ : "unknown_error";
179
+ }
180
+
181
+ type RotateOutcome =
182
+ | { kind: "token"; accessToken: string }
183
+ | { kind: "rotateFailed"; code: string };
184
+
84
185
  function isUniqueViolation(err: unknown): boolean {
85
186
  return (
86
187
  typeof err === "object" &&
@@ -95,6 +196,8 @@ export class SlackConfigTokenService {
95
196
  /** Strict crypto (see makeStrictTokenCrypto); null when no encryption key is configured. */
96
197
  private crypto: TokenCrypto | null,
97
198
  private clock: Clock = SystemClock(),
199
+ /** tooling.tokens.rotate client; required by getAccessToken() only. */
200
+ private rotateClient?: SlackConfigTokenClient,
98
201
  ) {}
99
202
 
100
203
  /**
@@ -178,4 +281,153 @@ export class SlackConfigTokenService {
178
281
  async clear(accountId: string | null): Promise<void> {
179
282
  await this.prisma.slackConfigToken.deleteMany({ where: { accountId } });
180
283
  }
284
+
285
+ /**
286
+ * Server-side only: a usable Slack config access token for exactly this
287
+ * scope (no fallback to the default; callers resolve the scope first, e.g.
288
+ * via resolveForAccount). Never logged; errors never contain token values.
289
+ */
290
+ async getAccessToken(
291
+ accountId: string | null,
292
+ opts: GetSlackConfigAccessTokenOptions = {},
293
+ ): Promise<string> {
294
+ const crypto = this.crypto;
295
+ if (!crypto) throw new SlackConfigTokenEncryptionUnavailableError();
296
+ const rotateClient = this.rotateClient;
297
+ if (!rotateClient) {
298
+ throw new Error(
299
+ "SlackConfigTokenService was constructed without a SlackConfigTokenClient; getAccessToken() cannot rotate",
300
+ );
301
+ }
302
+
303
+ const forceRotate = opts.forceRotate === true;
304
+ if (!forceRotate) {
305
+ const row = await this.prisma.slackConfigToken.findFirst({
306
+ where: { accountId },
307
+ });
308
+ if (!row) throw new SlackConfigTokenNotConfiguredError(accountId);
309
+ const cached = this.cachedAccessToken(row, crypto);
310
+ if (cached) return cached;
311
+ }
312
+
313
+ const outcome = await this.prisma.$transaction(
314
+ async (tx): Promise<RotateOutcome> => {
315
+ const locked =
316
+ accountId === null
317
+ ? await tx.$queryRaw<
318
+ { id: string }[]
319
+ >`SELECT id FROM "SlackConfigToken" WHERE "accountId" IS NULL FOR UPDATE`
320
+ : await tx.$queryRaw<
321
+ { id: string }[]
322
+ >`SELECT id FROM "SlackConfigToken" WHERE "accountId" = ${accountId} FOR UPDATE`;
323
+ const id = locked[0]?.id;
324
+ if (!id) throw new SlackConfigTokenNotConfiguredError(accountId);
325
+ const row = await tx.slackConfigToken.findUniqueOrThrow({
326
+ where: { id },
327
+ });
328
+
329
+ // Re-check under the lock: another caller (or replica) may have
330
+ // rotated while we waited. A forced rotate reuses that token only if
331
+ // it is not the one Slack just rejected.
332
+ const cached = this.cachedAccessToken(row, crypto);
333
+ if (cached) {
334
+ if (!forceRotate) return { kind: "token", accessToken: cached };
335
+ if (
336
+ opts.rejectedAccessToken !== undefined &&
337
+ cached !== opts.rejectedAccessToken
338
+ ) {
339
+ return { kind: "token", accessToken: cached };
340
+ }
341
+ }
342
+
343
+ let rotated: Awaited<
344
+ ReturnType<SlackConfigTokenClient["rotateConfigToken"]>
345
+ >;
346
+ try {
347
+ rotated = await rotateClient.rotateConfigToken(
348
+ crypto.decrypt(row.refreshTokenEncrypted),
349
+ );
350
+ } catch (err) {
351
+ // Record the failure and commit it; throwing here would roll the
352
+ // lastError write back. Token columns are left untouched.
353
+ const code = rotateErrorCode(err);
354
+ await tx.slackConfigToken.update({
355
+ where: { id },
356
+ data: { lastError: code, updatedAt: this.clock.now() },
357
+ });
358
+ return { kind: "rotateFailed", code };
359
+ }
360
+
361
+ // Persist before returning: if this write (or the commit) fails, the
362
+ // caller gets an error, never an access token we failed to store.
363
+ // Slack refresh tokens are not single-use, so the still-stored old
364
+ // refresh token keeps working for the next attempt.
365
+ const now = this.clock.now();
366
+ try {
367
+ await tx.slackConfigToken.update({
368
+ where: { id },
369
+ data: {
370
+ refreshTokenEncrypted: crypto.encrypt(rotated.refreshToken),
371
+ accessTokenEncrypted: crypto.encrypt(rotated.accessToken),
372
+ accessTokenExpiresAt: new Date(rotated.exp * 1000),
373
+ slackTeamId: rotated.teamId,
374
+ slackUserId: rotated.userId,
375
+ lastRotatedAt: now,
376
+ lastError: null,
377
+ updatedAt: now,
378
+ },
379
+ });
380
+ } catch (err) {
381
+ throw new Error(
382
+ "Failed to persist the rotated Slack config token; the access token was discarded",
383
+ { cause: err },
384
+ );
385
+ }
386
+ return { kind: "token", accessToken: rotated.accessToken };
387
+ },
388
+ { timeout: ROTATE_TX_TIMEOUT_MS, maxWait: ROTATE_TX_MAX_WAIT_MS },
389
+ );
390
+
391
+ if (outcome.kind === "rotateFailed") {
392
+ if (outcome.code === "invalid_refresh_token") {
393
+ throw new SlackConfigRefreshTokenInvalidError();
394
+ }
395
+ throw new SlackConfigTokenRotateFailedError(outcome.code);
396
+ }
397
+ return outcome.accessToken;
398
+ }
399
+
400
+ /**
401
+ * Run `fn` with this scope's access token. If Slack rejects the token
402
+ * (token_revoked / invalid_auth), force exactly one rotate and retry `fn`
403
+ * once; a second failure propagates. No loop.
404
+ */
405
+ async withSlackConfigAccessToken<T>(
406
+ accountId: string | null,
407
+ fn: (accessToken: string) => Promise<T>,
408
+ ): Promise<T> {
409
+ const accessToken = await this.getAccessToken(accountId);
410
+ try {
411
+ return await fn(accessToken);
412
+ } catch (err) {
413
+ if (!isSlackConfigTokenRevokedError(err)) throw err;
414
+ const fresh = await this.getAccessToken(accountId, {
415
+ forceRotate: true,
416
+ rejectedAccessToken: accessToken,
417
+ });
418
+ return fn(fresh);
419
+ }
420
+ }
421
+
422
+ /** Decrypted cached access token if it has more than the minimum left. */
423
+ private cachedAccessToken(
424
+ row: SlackConfigTokenRow,
425
+ crypto: TokenCrypto,
426
+ ): string | null {
427
+ if (!row.accessTokenEncrypted || !row.accessTokenExpiresAt) return null;
428
+ const remaining =
429
+ row.accessTokenExpiresAt.getTime() - this.clock.now().getTime();
430
+ if (remaining <= SLACK_CONFIG_ACCESS_TOKEN_MIN_REMAINING_MS) return null;
431
+ return crypto.decrypt(row.accessTokenEncrypted);
432
+ }
181
433
  }