@app-vitals/agent-admin 1.64.0 → 1.65.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.
@@ -49,6 +49,11 @@ import type { AgentProvisioner } from "./agent-provisioner.ts";
49
49
  import type { ChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
50
50
  import { NotFoundError } from "./errors.ts";
51
51
  import type { DeletionServiceIntegration } from "./service-integration.ts";
52
+ import {
53
+ hasStoredSlackConfigToken,
54
+ type SlackConfigTokenResolver,
55
+ withSlackConfigToken,
56
+ } from "./slack-config-token.ts";
52
57
  import type { SlackProvisioningClient } from "./slack-provisioning-client.ts";
53
58
 
54
59
  // ─── Step identifiers ─────────────────────────────────────────────────────────
@@ -113,8 +118,17 @@ interface DeleteAgentPrisma {
113
118
  anthropicFederationRuleId: true;
114
119
  anthropicServiceAccountId: true;
115
120
  k8sServiceAccountName: true;
121
+ accountId: true;
116
122
  };
117
- }): Promise<({ id: string; name: string } & LeftoverIdentity) | null>;
123
+ }): Promise<
124
+ | ({
125
+ id: string;
126
+ name: string;
127
+ /** Owning account; picks the stored Slack config token row. */
128
+ accountId?: string | null;
129
+ } & LeftoverIdentity)
130
+ | null
131
+ >;
118
132
  delete(args: { where: { id: string } }): Promise<unknown>;
119
133
  };
120
134
  agentEnv: {
@@ -149,12 +163,20 @@ export interface DeleteAgentFullyDeps {
149
163
  * crypto and is trivially unit-testable.
150
164
  */
151
165
  decrypt(value: string): string;
166
+ /**
167
+ * Optional stored Slack config token resolver. When present and a token
168
+ * resolves for the agent's account (else the default), the Slack app is
169
+ * deleted with a minted access token if no token was pasted. Absent keeps the
170
+ * paste-only behavior.
171
+ */
172
+ slackConfigTokens?: SlackConfigTokenResolver;
152
173
  }
153
174
 
154
175
  interface DeleteAgentFullyOpts {
155
176
  /**
156
177
  * Slack user token (xoxp-) authorizing the Slack app deletion. Supplied
157
- * per-request (same UX as the sync-manifest flow) — when omitted, a Slack app
178
+ * per-request (same UX as the sync-manifest flow) and wins over a stored
179
+ * Slack config token. When omitted and no stored token resolves, a Slack app
158
180
  * (if present) is NOT auto-deleted and instead becomes a manual checklist
159
181
  * entry. Its absence is never a failure.
160
182
  */
@@ -190,6 +212,7 @@ export async function deleteAgentFully(
190
212
  anthropicFederationRuleId: true,
191
213
  anthropicServiceAccountId: true,
192
214
  k8sServiceAccountName: true,
215
+ accountId: true,
193
216
  } as const;
194
217
  const agent = await deps.prisma.agent.findUnique({
195
218
  where: { id: agentId },
@@ -266,14 +289,25 @@ export async function deleteAgentFully(
266
289
  const manualSlackSteps: ManualStep[] = [];
267
290
  if (slackAppIdRow) {
268
291
  const slackAppId = deps.decrypt(slackAppIdRow.value);
269
- if (opts.xoxpToken) {
292
+ const pasted = opts.xoxpToken?.trim() || undefined;
293
+ if (
294
+ pasted ||
295
+ (await hasStoredSlackConfigToken(
296
+ deps.slackConfigTokens,
297
+ agent.accountId ?? null,
298
+ ))
299
+ ) {
270
300
  await runStep("slack-app", async () => {
271
- await deps.slack.deleteApp(opts.xoxpToken as string, slackAppId);
301
+ await withSlackConfigToken(
302
+ deps.slackConfigTokens,
303
+ { pasted, accountId: agent.accountId ?? null },
304
+ (token) => deps.slack.deleteApp(token, slackAppId),
305
+ );
272
306
  });
273
307
  } else {
274
308
  manualSlackSteps.push({
275
309
  key: "SLACK_APP_ID",
276
- message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied. Delete it manually at api.slack.com/apps or retry with a token.`,
310
+ message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied and no stored Slack config token applies. Delete it manually at api.slack.com/apps or retry with a token.`,
277
311
  });
278
312
  }
279
313
  }
@@ -28,6 +28,7 @@ interface AgentRow {
28
28
  anthropicFederationRuleId?: string | null;
29
29
  anthropicServiceAccountId?: string | null;
30
30
  k8sServiceAccountName?: string | null;
31
+ accountId?: string | null;
31
32
  }
32
33
 
33
34
  /** Minimal in-memory Prisma double tracking whether the Agent row exists. */
@@ -47,6 +48,7 @@ class FakePrisma {
47
48
  anthropicFederationRuleId: true;
48
49
  anthropicServiceAccountId: true;
49
50
  k8sServiceAccountName: true;
51
+ accountId: true;
50
52
  };
51
53
  }) => {
52
54
  if (this.deleted || !this.row) return null;
@@ -56,6 +58,7 @@ class FakePrisma {
56
58
  anthropicFederationRuleId: this.row.anthropicFederationRuleId ?? null,
57
59
  anthropicServiceAccountId: this.row.anthropicServiceAccountId ?? null,
58
60
  k8sServiceAccountName: this.row.k8sServiceAccountName ?? null,
61
+ accountId: this.row.accountId ?? null,
59
62
  };
60
63
  },
61
64
  delete: async (_args: { where: { id: string } }): Promise<unknown> => {
@@ -97,6 +100,8 @@ function makeDeps(opts: {
97
100
  }>;
98
101
  /** Give the provisioner a removeAnthropicIdentity (absent by default). */
99
102
  withIdentityRemoval?: boolean;
103
+ /** Stored Slack config token resolver (absent by default). */
104
+ slackConfigTokens?: DeleteAgentFullyDeps["slackConfigTokens"];
100
105
  }): { deps: DeleteAgentFullyDeps; log: CallLog } {
101
106
  const log: CallLog = {
102
107
  deprovision: [],
@@ -160,6 +165,9 @@ function makeDeps(opts: {
160
165
  },
161
166
  // Identity decrypt: env values in these tests are stored "plaintext".
162
167
  decrypt: (value) => value,
168
+ ...(opts.slackConfigTokens
169
+ ? { slackConfigTokens: opts.slackConfigTokens }
170
+ : {}),
163
171
  };
164
172
 
165
173
  return { deps, log };
@@ -348,6 +356,139 @@ describe("deleteAgentFully — Slack app without a token", () => {
348
356
  });
349
357
  });
350
358
 
359
+ // ─── Stored Slack config token (SCT-4.1) ─────────────────────────────────────
360
+
361
+ /** Fake resolver: `rows` are the scopes with a stored token. */
362
+ function fakeStored(rows: Array<string | null>, rejectFirst = false) {
363
+ const minted: Array<{ scope: string | null; token: string }> = [];
364
+ let rotations = 0;
365
+ const resolver = {
366
+ get: async (accountId: string | null) =>
367
+ rows.includes(accountId) ? { accountId } : null,
368
+ resolveForAccount: async (accountId: string) =>
369
+ rows.includes(accountId)
370
+ ? { accountId }
371
+ : rows.includes(null)
372
+ ? { accountId: null }
373
+ : null,
374
+ withSlackConfigAccessToken: async <T>(
375
+ scope: string | null,
376
+ fn: (t: string) => Promise<T>,
377
+ ) => {
378
+ const first = `minted-${scope ?? "default"}-${++rotations}`;
379
+ minted.push({ scope, token: first });
380
+ try {
381
+ return await fn(first);
382
+ } catch (err) {
383
+ if (!rejectFirst) throw err;
384
+ const second = `minted-${scope ?? "default"}-${++rotations}`;
385
+ minted.push({ scope, token: second });
386
+ return fn(second);
387
+ }
388
+ },
389
+ } as unknown as DeleteAgentFullyDeps["slackConfigTokens"];
390
+ return { resolver, minted };
391
+ }
392
+
393
+ describe("deleteAgentFully — stored Slack config token", () => {
394
+ const withApp = (accountId: string | null) =>
395
+ new FakePrisma({ ...AGENT, accountId }, [
396
+ { key: "SLACK_APP_ID", value: "A777", secret: true },
397
+ ]);
398
+
399
+ it("deletes the Slack app with a minted token when none is pasted", async () => {
400
+ const { resolver, minted } = fakeStored([null]);
401
+ const { deps, log } = makeDeps({
402
+ prisma: withApp("acct-1"),
403
+ slackConfigTokens: resolver,
404
+ });
405
+ const result = await deleteAgentFully(AGENT.id, deps);
406
+ expect(result.agentDeleted).toBe(true);
407
+ expect(result.completed).toContain("slack-app");
408
+ expect(result.manualStepsRequired.map((s) => s.key)).not.toContain(
409
+ "SLACK_APP_ID",
410
+ );
411
+ expect(log.slackDeleted).toEqual([
412
+ { token: "minted-default-1", appId: "A777" },
413
+ ]);
414
+ expect(minted).toHaveLength(1);
415
+ });
416
+
417
+ it("uses the account row over the default row", async () => {
418
+ const { resolver, minted } = fakeStored([null, "acct-1"]);
419
+ const { deps, log } = makeDeps({
420
+ prisma: withApp("acct-1"),
421
+ slackConfigTokens: resolver,
422
+ });
423
+ await deleteAgentFully(AGENT.id, deps);
424
+ expect(minted[0]?.scope).toBe("acct-1");
425
+ expect(log.slackDeleted[0]?.token).toBe("minted-acct-1-1");
426
+ });
427
+
428
+ it("a pasted token wins over the stored one", async () => {
429
+ const { resolver, minted } = fakeStored([null]);
430
+ const { deps, log } = makeDeps({
431
+ prisma: withApp(null),
432
+ slackConfigTokens: resolver,
433
+ });
434
+ await deleteAgentFully(AGENT.id, deps, { xoxpToken: "xoxp-paste" });
435
+ expect(log.slackDeleted).toEqual([{ token: "xoxp-paste", appId: "A777" }]);
436
+ expect(minted).toEqual([]);
437
+ });
438
+
439
+ it("keeps the manual step when neither a pasted nor a stored token exists", async () => {
440
+ const { resolver } = fakeStored([]);
441
+ const { deps, log } = makeDeps({
442
+ prisma: withApp("acct-1"),
443
+ slackConfigTokens: resolver,
444
+ });
445
+ const result = await deleteAgentFully(AGENT.id, deps);
446
+ expect(log.slackDeleted).toEqual([]);
447
+ expect(result.manualStepsRequired.map((s) => s.key)).toContain(
448
+ "SLACK_APP_ID",
449
+ );
450
+ });
451
+
452
+ it("retries once with a rotated token when Slack reports token_revoked", async () => {
453
+ const { resolver } = fakeStored([null], true);
454
+ const prisma = withApp(null);
455
+ const { deps, log } = makeDeps({ prisma, slackConfigTokens: resolver });
456
+ let calls = 0;
457
+ deps.slack = {
458
+ deleteApp: async (token, appId) => {
459
+ log.slackDeleted.push({ token, appId });
460
+ if (++calls === 1)
461
+ throw new Error("Slack apps.manifest.delete failed: token_revoked");
462
+ },
463
+ };
464
+ const result = await deleteAgentFully(AGENT.id, deps);
465
+ expect(result.agentDeleted).toBe(true);
466
+ expect(log.slackDeleted.map((c) => c.token)).toEqual([
467
+ "minted-default-1",
468
+ "minted-default-2",
469
+ ]);
470
+ });
471
+
472
+ it("records slack-app failed when minting the token fails", async () => {
473
+ const resolver = {
474
+ get: async () => ({ accountId: null }),
475
+ resolveForAccount: async () => ({ accountId: null }),
476
+ withSlackConfigAccessToken: async () => {
477
+ throw new Error("rotation failed");
478
+ },
479
+ } as unknown as DeleteAgentFullyDeps["slackConfigTokens"];
480
+ const { deps } = makeDeps({
481
+ prisma: withApp(null),
482
+ slackConfigTokens: resolver,
483
+ });
484
+ const result = await deleteAgentFully(AGENT.id, deps);
485
+ expect(result.agentDeleted).toBe(false);
486
+ expect(result.failed).toEqual([
487
+ { step: "slack-app", error: "rotation failed" },
488
+ ]);
489
+ });
490
+ });
491
+
351
492
  // ─── Edge: unknown agent ─────────────────────────────────────────────────────
352
493
 
353
494
  describe("deleteAgentFully — unknown agent", () => {
@@ -24,11 +24,11 @@ import type { AgentTokenService } from "./agent-tokens.ts";
24
24
  import type { AdminDeps } from "./agents-api.ts";
25
25
  import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
26
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
27
+ import { accessFor, envWith } from "./github-installation.fixtures.ts";
27
28
  import {
28
29
  createGithubInstallationRepos,
29
30
  createGithubSync,
30
31
  } from "./github-installation-wiring.ts";
31
- import { accessFor, envWith } from "./github-installation.fixtures.ts";
32
32
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
33
33
  import {
34
34
  repoLostAccessBlockReason,
@@ -2162,6 +2162,112 @@ describe("admin API — delete agent", () => {
2162
2162
  expect(slackCalls).toEqual([{ token: "xoxp-user-token", appId: "A123" }]);
2163
2163
  });
2164
2164
 
2165
+ describe("DELETE /agents/:id with a stored Slack config token (SCT-4.1)", () => {
2166
+ const setup = (opts: {
2167
+ rejectFirst?: boolean;
2168
+ accountId?: string | null;
2169
+ }) => {
2170
+ const slackCalls: Array<{ token: string; appId: string }> = [];
2171
+ const mintedFor: Array<string | null> = [];
2172
+ let n = 0;
2173
+ const slackConfigTokens = {
2174
+ get: async (a: string | null) =>
2175
+ a === null ? { accountId: null } : null,
2176
+ resolveForAccount: async (a: string) =>
2177
+ a === "acct-1" ? { accountId: "acct-1" } : { accountId: null },
2178
+ withSlackConfigAccessToken: async <T>(
2179
+ scope: string | null,
2180
+ fn: (t: string) => Promise<T>,
2181
+ ) => {
2182
+ mintedFor.push(scope);
2183
+ try {
2184
+ return await fn(`minted-${++n}`);
2185
+ } catch (err) {
2186
+ if (!/token_revoked/.test(String(err))) throw err;
2187
+ mintedFor.push(scope);
2188
+ return fn(`minted-${++n}`);
2189
+ }
2190
+ },
2191
+ } as unknown as NonNullable<AdminDeps["slackConfigTokens"]>;
2192
+ const base = makeMockDeps();
2193
+ const deps: AdminDeps = {
2194
+ ...base,
2195
+ prisma: {
2196
+ ...base.prisma,
2197
+ agent: {
2198
+ ...base.prisma.agent,
2199
+ findUnique: async () => ({
2200
+ id: AGENT_ID,
2201
+ name: "Test Agent",
2202
+ accountId: opts.accountId ?? null,
2203
+ }),
2204
+ },
2205
+ agentEnv: {
2206
+ findMany: async () => [
2207
+ { key: "SLACK_APP_ID", value: "A123", secret: true },
2208
+ ],
2209
+ },
2210
+ } as unknown as AdminDeps["prisma"],
2211
+ slack: {
2212
+ deleteApp: async (token: string, appId: string) => {
2213
+ slackCalls.push({ token, appId });
2214
+ if (opts.rejectFirst && slackCalls.length === 1) {
2215
+ throw new Error(
2216
+ "Slack apps.manifest.delete failed: token_revoked",
2217
+ );
2218
+ }
2219
+ },
2220
+ },
2221
+ slackConfigTokens,
2222
+ };
2223
+ return { app: createAdminApp(deps), slackCalls, mintedFor };
2224
+ };
2225
+ const del = async (
2226
+ app: ReturnType<typeof createAdminApp>,
2227
+ body?: Record<string, string>,
2228
+ ) => {
2229
+ const cookie = await makeSessionCookie();
2230
+ return app.request(`/agents/${AGENT_ID}`, {
2231
+ method: "DELETE",
2232
+ ...(body ? { body: JSON.stringify(body) } : {}),
2233
+ headers: {
2234
+ ...(body ? { "Content-Type": "application/json" } : {}),
2235
+ Cookie: `admin_session=${cookie}`,
2236
+ },
2237
+ });
2238
+ };
2239
+
2240
+ it("no body → the Slack app is deleted with a minted token", async () => {
2241
+ const { app, slackCalls } = setup({});
2242
+ const res = await del(app);
2243
+ const body = await res.json();
2244
+ expect(body.agentDeleted).toBe(true);
2245
+ expect(body.completed).toContain("slack-app");
2246
+ expect(body.manualStepsRequired).toEqual([]);
2247
+ expect(slackCalls).toEqual([{ token: "minted-1", appId: "A123" }]);
2248
+ });
2249
+
2250
+ it("the agent's account row is used (not the default)", async () => {
2251
+ const { app, mintedFor } = setup({ accountId: "acct-1" });
2252
+ await del(app);
2253
+ expect(mintedFor).toEqual(["acct-1"]);
2254
+ });
2255
+
2256
+ it("a pasted xoxpToken wins over the stored token", async () => {
2257
+ const { app, slackCalls, mintedFor } = setup({});
2258
+ await del(app, { xoxpToken: "xoxp-user-token" });
2259
+ expect(slackCalls).toEqual([{ token: "xoxp-user-token", appId: "A123" }]);
2260
+ expect(mintedFor).toEqual([]);
2261
+ });
2262
+
2263
+ it("token_revoked → one forced rotate + retry, deletion succeeds", async () => {
2264
+ const { app, slackCalls } = setup({ rejectFirst: true });
2265
+ const body = await (await del(app)).json();
2266
+ expect(body.agentDeleted).toBe(true);
2267
+ expect(slackCalls.map((c) => c.token)).toEqual(["minted-1", "minted-2"]);
2268
+ });
2269
+ });
2270
+
2165
2271
  it("DELETE /agents/:id unknown id → 404 (no deprovision)", async () => {
2166
2272
  const cookie = await makeSessionCookie();
2167
2273
  const provisioner = new RecordingProvisioner();
package/src/agents-api.ts CHANGED
@@ -61,13 +61,13 @@ import { deleteAgentFully } from "./agent-deletion.ts";
61
61
  import type { AgentEnvService } from "./agent-envs.ts";
62
62
  import type { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
63
63
  import { AgentMarketplaceService } from "./agent-marketplaces.ts";
64
- import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
65
64
  import type { AgentMemberService } from "./agent-members.ts";
66
65
  import type { AgentPluginService } from "./agent-plugins.ts";
67
66
  import {
68
67
  type AgentProvisioner,
69
68
  hasPerAgentIdentity,
70
69
  } from "./agent-provisioner.ts";
70
+ import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
71
71
  import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
72
72
  import type { AgentTokenService } from "./agent-tokens.ts";
73
73
  import type { AgentToolService } from "./agent-tools.ts";
@@ -111,7 +111,9 @@ import {
111
111
  UnprocessableEntityError,
112
112
  } from "./errors.ts";
113
113
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
114
+ import type { GithubSyncService } from "./github-sync.ts";
114
115
  import { normalizeGithubUsername } from "./github-username.ts";
116
+ import type { InstallationReposService } from "./installation-repos-service.ts";
115
117
  import {
116
118
  AddAgentReposBodySchema,
117
119
  AgentChatTokenUsageDailySchema,
@@ -167,8 +169,6 @@ import {
167
169
  UpsertAgentMarketplaceBodySchema,
168
170
  UpsertChatTokenDailyBodySchema,
169
171
  } from "./openapi-schemas.ts";
170
- import type { InstallationReposService } from "./installation-repos-service.ts";
171
- import type { GithubSyncService } from "./github-sync.ts";
172
172
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
173
173
  import {
174
174
  blockRepoRemovalWork,
@@ -327,6 +327,12 @@ export interface AdminDeps {
327
327
  chatService: DeleteAgentFullyDeps["chatService"];
328
328
  slack: DeleteAgentFullyDeps["slack"];
329
329
  decrypt: DeleteAgentFullyDeps["decrypt"];
330
+ /**
331
+ * Optional stored Slack config token resolver (SCT-4.1; additive). When set,
332
+ * DELETE /agents/:id deletes the Slack app with a minted token if no
333
+ * xoxpToken is supplied. Absent keeps the paste-only behavior.
334
+ */
335
+ slackConfigTokens?: DeleteAgentFullyDeps["slackConfigTokens"];
330
336
  sessionSecret: string;
331
337
  /** Parsed SHIPWRIGHT_ADMIN_API_KEYS — optional; absent means env key auth is disabled. */
332
338
  adminApiKeys?: Map<string, AdminApiKey>;
@@ -960,7 +966,7 @@ const deleteAgentRoute = createRoute({
960
966
  path: "/agents/{id}",
961
967
  summary: "Delete an agent",
962
968
  description:
963
- "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
969
+ "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied, or a stored Slack config token resolves for the agent's account (else the deployment default) — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
964
970
  request: {
965
971
  params: AgentIdParamSchema,
966
972
  body: {
@@ -2089,6 +2095,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2089
2095
  chatService,
2090
2096
  slack,
2091
2097
  decrypt,
2098
+ slackConfigTokens,
2092
2099
  sessionSecret,
2093
2100
  adminApiKeys,
2094
2101
  sentryClient,
@@ -2556,6 +2563,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2556
2563
  chatService,
2557
2564
  slack,
2558
2565
  decrypt,
2566
+ ...(slackConfigTokens ? { slackConfigTokens } : {}),
2559
2567
  },
2560
2568
  { xoxpToken: body?.xoxpToken },
2561
2569
  );
@@ -207,8 +207,10 @@ export const CreateAgentBodySchema = z
207
207
 
208
208
  /**
209
209
  * DELETE /agents/:id request body. Entirely optional — omit it (or the
210
- * xoxpToken field) to skip automatic Slack app deletion; a present Slack app
211
- * then becomes a manual checklist entry instead of a hard failure.
210
+ * xoxpToken field) to use the stored Slack config token when one resolves for
211
+ * the agent's account (else the deployment default). With neither a pasted nor
212
+ * a stored token, a present Slack app becomes a manual checklist entry instead
213
+ * of a hard failure. A pasted xoxpToken wins over the stored token.
212
214
  */
213
215
  export const DeleteAgentBodySchema = z
214
216
  .object({
@@ -0,0 +1,108 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ hasStoredSlackConfigToken,
4
+ type SlackConfigTokenResolver,
5
+ withSlackConfigToken,
6
+ } from "./slack-config-token.ts";
7
+
8
+ interface Row {
9
+ accountId: string | null;
10
+ }
11
+
12
+ /** Fake resolver: rows by scope; records which scope minted tokens. */
13
+ function fake(rows: Row[]) {
14
+ const used: Array<string | null> = [];
15
+ const resolver = {
16
+ get: async (accountId: string | null) =>
17
+ rows.find((r) => r.accountId === accountId) ?? null,
18
+ resolveForAccount: async (accountId: string) =>
19
+ rows.find((r) => r.accountId === accountId) ??
20
+ rows.find((r) => r.accountId === null) ??
21
+ null,
22
+ withSlackConfigAccessToken: async <T>(
23
+ accountId: string | null,
24
+ fn: (t: string) => Promise<T>,
25
+ ) => {
26
+ used.push(accountId);
27
+ return fn(`minted-${accountId ?? "default"}`);
28
+ },
29
+ } as unknown as SlackConfigTokenResolver;
30
+ return { resolver, used };
31
+ }
32
+
33
+ describe("hasStoredSlackConfigToken", () => {
34
+ test("false without a resolver or rows", async () => {
35
+ expect(await hasStoredSlackConfigToken(undefined, "a1")).toBe(false);
36
+ expect(await hasStoredSlackConfigToken(fake([]).resolver, "a1")).toBe(
37
+ false,
38
+ );
39
+ });
40
+ test("true for the account row, the default row, and null account + default", async () => {
41
+ expect(
42
+ await hasStoredSlackConfigToken(
43
+ fake([{ accountId: "a1" }]).resolver,
44
+ "a1",
45
+ ),
46
+ ).toBe(true);
47
+ expect(
48
+ await hasStoredSlackConfigToken(
49
+ fake([{ accountId: null }]).resolver,
50
+ "a1",
51
+ ),
52
+ ).toBe(true);
53
+ expect(
54
+ await hasStoredSlackConfigToken(
55
+ fake([{ accountId: null }]).resolver,
56
+ null,
57
+ ),
58
+ ).toBe(true);
59
+ expect(
60
+ await hasStoredSlackConfigToken(
61
+ fake([{ accountId: "a1" }]).resolver,
62
+ null,
63
+ ),
64
+ ).toBe(false);
65
+ });
66
+ });
67
+
68
+ describe("withSlackConfigToken", () => {
69
+ test("a pasted token wins and never touches the resolver", async () => {
70
+ const { resolver, used } = fake([{ accountId: "a1" }]);
71
+ const got = await withSlackConfigToken(
72
+ resolver,
73
+ { pasted: " xoxe.xoxp-paste ", accountId: "a1" },
74
+ async (t) => t,
75
+ );
76
+ expect(got).toBe("xoxe.xoxp-paste");
77
+ expect(used).toEqual([]);
78
+ });
79
+ test("account row overrides the default row", async () => {
80
+ const { resolver, used } = fake([{ accountId: null }, { accountId: "a1" }]);
81
+ const got = await withSlackConfigToken(
82
+ resolver,
83
+ { accountId: "a1" },
84
+ async (t) => t,
85
+ );
86
+ expect(got).toBe("minted-a1");
87
+ expect(used).toEqual(["a1"]);
88
+ });
89
+ test("falls back to the default row", async () => {
90
+ const { resolver, used } = fake([{ accountId: null }]);
91
+ expect(
92
+ await withSlackConfigToken(resolver, { accountId: "a9" }, async (t) => t),
93
+ ).toBe("minted-default");
94
+ expect(used).toEqual([null]);
95
+ });
96
+ test("throws when nothing resolves", async () => {
97
+ await expect(
98
+ withSlackConfigToken(
99
+ fake([]).resolver,
100
+ { accountId: "a1" },
101
+ async (t) => t,
102
+ ),
103
+ ).rejects.toThrow(/No .*Slack config token/);
104
+ await expect(
105
+ withSlackConfigToken(undefined, {}, async (t) => t),
106
+ ).rejects.toThrow(/No .*Slack config token/);
107
+ });
108
+ });
@@ -431,3 +431,54 @@ export class SlackConfigTokenService {
431
431
  return crypto.decrypt(row.accessTokenEncrypted);
432
432
  }
433
433
  }
434
+
435
+ /**
436
+ * The slice of SlackConfigTokenService the create / connect / sync / delete
437
+ * flows need. Flows take it as an optional dependency: absent means no stored
438
+ * token and today's paste-only behavior.
439
+ */
440
+ export type SlackConfigTokenResolver = Pick<
441
+ SlackConfigTokenService,
442
+ "get" | "resolveForAccount" | "withSlackConfigAccessToken"
443
+ >;
444
+
445
+ async function resolveStoredScope(
446
+ resolver: SlackConfigTokenResolver | undefined,
447
+ accountId: string | null | undefined,
448
+ ): Promise<SlackConfigTokenMetadata | null> {
449
+ if (!resolver) return null;
450
+ return accountId ? resolver.resolveForAccount(accountId) : resolver.get(null);
451
+ }
452
+
453
+ /**
454
+ * True when a stored config token applies to this account: its own row, else
455
+ * the deployment-wide default row (a null account only sees the default).
456
+ */
457
+ export async function hasStoredSlackConfigToken(
458
+ resolver: SlackConfigTokenResolver | undefined,
459
+ accountId: string | null | undefined,
460
+ ): Promise<boolean> {
461
+ return (await resolveStoredScope(resolver, accountId)) !== null;
462
+ }
463
+
464
+ /**
465
+ * Run `fn` with a Slack config token: a pasted token wins (used as-is, no
466
+ * retry); otherwise mint an access token from the account's stored row, else
467
+ * the default row, with the revoked-token retry-once of
468
+ * withSlackConfigAccessToken. Throws SlackConfigTokenNotConfiguredError when
469
+ * neither exists, so callers check hasStoredSlackConfigToken() first when they
470
+ * have a paste-only fallback.
471
+ */
472
+ export async function withSlackConfigToken<T>(
473
+ resolver: SlackConfigTokenResolver | undefined,
474
+ opts: { pasted?: string | undefined; accountId?: string | null | undefined },
475
+ fn: (token: string) => Promise<T>,
476
+ ): Promise<T> {
477
+ const pasted = opts.pasted?.trim();
478
+ if (pasted) return fn(pasted);
479
+ const row = await resolveStoredScope(resolver, opts.accountId);
480
+ if (!row || !resolver) {
481
+ throw new SlackConfigTokenNotConfiguredError(opts.accountId ?? null);
482
+ }
483
+ return resolver.withSlackConfigAccessToken(row.accountId, fn);
484
+ }