@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.
@@ -14,8 +14,12 @@ import { readFileSync } from "node:fs";
14
14
  import { sign } from "hono/jwt";
15
15
  import type { AdminUISlackClient } from "./admin-ui.ts";
16
16
  import type { AgentDetail } from "./agents.ts";
17
- import { SlackProvisioningService } from "./slack-provisioning-service.ts";
17
+ import {
18
+ isSlackConfigTokenRevokedError,
19
+ type SlackConfigTokenResolver,
20
+ } from "./slack-config-token.ts";
18
21
  import type { AppManifest } from "./slack-provisioning-client.ts";
22
+ import { SlackProvisioningService } from "./slack-provisioning-service.ts";
19
23
 
20
24
  // ─── Constants ────────────────────────────────────────────────────────────────
21
25
 
@@ -120,6 +124,7 @@ function makeService(opts?: {
120
124
  allowedTools: string[];
121
125
  } | null>;
122
126
  getDetail?: () => Promise<AgentDetail | null>;
127
+ slackConfigTokens?: SlackConfigTokenResolver;
123
128
  }): SlackProvisioningService {
124
129
  const patchCalls = opts?.patchCalls ?? [];
125
130
  const reconcileCalls = opts?.reconcileCalls ?? [];
@@ -184,9 +189,76 @@ function makeService(opts?: {
184
189
  sessionSecret: SESSION_SECRET,
185
190
  appBaseUrl: APP_BASE_URL,
186
191
  secretEnvVars: new Set(["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"]),
192
+ ...(opts?.slackConfigTokens
193
+ ? { slackConfigTokens: opts.slackConfigTokens }
194
+ : {}),
187
195
  });
188
196
  }
189
197
 
198
+ /** Records the token each createAppManifest call received; can reject the first. */
199
+ class TokenRecordingSlackClient extends RecordedSlackClient {
200
+ readonly tokens: string[] = [];
201
+ constructor(private readonly rejectFirstWith?: string) {
202
+ super(CASSETTE_PATH);
203
+ }
204
+ override async createAppManifest(xoxpToken: string, manifest: AppManifest) {
205
+ this.tokens.push(xoxpToken);
206
+ if (this.rejectFirstWith && this.tokens.length === 1) {
207
+ throw new Error(
208
+ `Slack apps.manifest.create failed: ${this.rejectFirstWith}`,
209
+ );
210
+ }
211
+ return super.createAppManifest(xoxpToken, manifest);
212
+ }
213
+ }
214
+
215
+ /** Stored-token resolver double: `scopes` are the rows that exist; mints sequential tokens. */
216
+ function makeStoredResolver(scopes: Array<string | null>) {
217
+ const mintedFor: Array<string | null> = [];
218
+ let n = 0;
219
+ const resolver = {
220
+ get: async (a: string | null) =>
221
+ scopes.includes(a) ? { accountId: a } : null,
222
+ resolveForAccount: async (a: string) =>
223
+ scopes.includes(a)
224
+ ? { accountId: a }
225
+ : scopes.includes(null)
226
+ ? { accountId: null }
227
+ : null,
228
+ withSlackConfigAccessToken: async <T>(
229
+ scope: string | null,
230
+ fn: (t: string) => Promise<T>,
231
+ ) => {
232
+ mintedFor.push(scope);
233
+ try {
234
+ return await fn(`minted-${++n}`);
235
+ } catch (err) {
236
+ if (!isSlackConfigTokenRevokedError(err)) throw err;
237
+ mintedFor.push(scope);
238
+ return fn(`minted-${++n}`);
239
+ }
240
+ },
241
+ } as unknown as SlackConfigTokenResolver;
242
+ return { resolver, mintedFor };
243
+ }
244
+
245
+ const agentInAccount = (accountId: string | null) => async () =>
246
+ ({
247
+ id: AGENT_ID,
248
+ name: "Test Agent",
249
+ accountId,
250
+ slackId: null,
251
+ selfHosted: false,
252
+ createdAt: new Date("2024-01-01"),
253
+ updatedAt: new Date("2024-01-01"),
254
+ repos: [],
255
+ reviewAuthorAllowlist: [],
256
+ patchAuthorAllowlist: [],
257
+ restrictSlackToMembers: false,
258
+ specialty: "coding",
259
+ missingRequiredEnv: [],
260
+ }) as unknown as AgentDetail;
261
+
190
262
  async function makeProvisionStateToken(
191
263
  overrides: Partial<{
192
264
  agentId: string;
@@ -355,6 +427,122 @@ describe("SlackProvisioningService.startConnect", () => {
355
427
  });
356
428
  });
357
429
 
430
+ describe("SlackProvisioningService.startConnect — stored Slack config token", () => {
431
+ it("no pasted token + stored default row → mints a token and creates the app", async () => {
432
+ const client = new TokenRecordingSlackClient();
433
+ const { resolver, mintedFor } = makeStoredResolver([null]);
434
+ const service = makeService({
435
+ slackClient: client,
436
+ getDetail: agentInAccount("acct-1"),
437
+ slackConfigTokens: resolver,
438
+ });
439
+ const result = await service.startConnect(
440
+ AGENT_ID,
441
+ undefined,
442
+ CONNECT_SLACK_CALLBACK,
443
+ );
444
+ expect(result.ok).toBe(true);
445
+ expect(client.tokens).toEqual(["minted-1"]);
446
+ expect(mintedFor).toEqual([null]);
447
+ });
448
+
449
+ it("account row overrides the default row", async () => {
450
+ const { resolver, mintedFor } = makeStoredResolver([null, "acct-1"]);
451
+ const service = makeService({
452
+ slackClient: new TokenRecordingSlackClient(),
453
+ getDetail: agentInAccount("acct-1"),
454
+ slackConfigTokens: resolver,
455
+ });
456
+ await service.startConnect(AGENT_ID, "", CONNECT_SLACK_CALLBACK);
457
+ expect(mintedFor).toEqual(["acct-1"]);
458
+ });
459
+
460
+ it("a pasted token wins and the resolver is not used", async () => {
461
+ const client = new TokenRecordingSlackClient();
462
+ const { resolver, mintedFor } = makeStoredResolver([null]);
463
+ const service = makeService({
464
+ slackClient: client,
465
+ slackConfigTokens: resolver,
466
+ });
467
+ const result = await service.startConnect(
468
+ AGENT_ID,
469
+ "xoxe.xoxp-1-pasted",
470
+ CONNECT_SLACK_CALLBACK,
471
+ );
472
+ expect(result.ok).toBe(true);
473
+ expect(client.tokens).toEqual(["xoxe.xoxp-1-pasted"]);
474
+ expect(mintedFor).toEqual([]);
475
+ });
476
+
477
+ it("a pasted token still needs the xoxe.xoxp- prefix even when a stored token exists", async () => {
478
+ const client = new TokenRecordingSlackClient();
479
+ const { resolver } = makeStoredResolver([null]);
480
+ const service = makeService({
481
+ slackClient: client,
482
+ slackConfigTokens: resolver,
483
+ });
484
+ const result = await service.startConnect(
485
+ AGENT_ID,
486
+ "xoxb-nope",
487
+ CONNECT_SLACK_CALLBACK,
488
+ );
489
+ expect(result.ok).toBe(false);
490
+ expect(client.tokens).toEqual([]);
491
+ });
492
+
493
+ it("neither pasted nor stored → today's prefix error", async () => {
494
+ const { resolver } = makeStoredResolver([]);
495
+ const service = makeService({ slackConfigTokens: resolver });
496
+ const result = await service.startConnect(
497
+ AGENT_ID,
498
+ undefined,
499
+ CONNECT_SLACK_CALLBACK,
500
+ );
501
+ expect(result.ok).toBe(false);
502
+ if (result.ok) throw new Error("expected error result");
503
+ expect(result.error).toContain("xoxe.xoxp-");
504
+ });
505
+
506
+ it("token_revoked on the manifest call → one forced rotate + retry succeeds", async () => {
507
+ const client = new TokenRecordingSlackClient("token_revoked");
508
+ const { resolver, mintedFor } = makeStoredResolver([null]);
509
+ const service = makeService({
510
+ slackClient: client,
511
+ slackConfigTokens: resolver,
512
+ });
513
+ const result = await service.startConnect(
514
+ AGENT_ID,
515
+ undefined,
516
+ CONNECT_SLACK_CALLBACK,
517
+ );
518
+ expect(result.ok).toBe(true);
519
+ expect(client.tokens).toEqual(["minted-1", "minted-2"]);
520
+ expect(mintedFor).toHaveLength(2);
521
+ });
522
+
523
+ it("createAppManifest (legacy wizard) mints a token when none is pasted, and prefers a pasted one", async () => {
524
+ const client = new TokenRecordingSlackClient();
525
+ const { resolver } = makeStoredResolver([null]);
526
+ const service = makeService({
527
+ slackClient: client,
528
+ slackConfigTokens: resolver,
529
+ });
530
+ await service.createAppManifest(
531
+ "wiz",
532
+ undefined,
533
+ LEGACY_PROVISION_COMPLETE,
534
+ null,
535
+ );
536
+ await service.createAppManifest(
537
+ "wiz",
538
+ "xoxe.xoxp-1-p",
539
+ LEGACY_PROVISION_COMPLETE,
540
+ null,
541
+ );
542
+ expect(client.tokens).toEqual(["minted-1", "xoxe.xoxp-1-p"]);
543
+ });
544
+ });
545
+
358
546
  describe("SlackProvisioningService.completeConnect", () => {
359
547
  it("valid state token + code → exchanges OAuth code (cassette) and stores SLACK_BOT_TOKEN, returns needs_app_token", async () => {
360
548
  const patchCalls: PatchCall[] = [];
@@ -21,6 +21,11 @@ import type { AdminUISlackClient } from "./admin-ui.ts";
21
21
  import type { AgentCronJobService } from "./agent-cron-jobs.ts";
22
22
  import type { AgentEnvService } from "./agent-envs.ts";
23
23
  import type { AgentService } from "./agents.ts";
24
+ import {
25
+ hasStoredSlackConfigToken,
26
+ type SlackConfigTokenResolver,
27
+ withSlackConfigToken,
28
+ } from "./slack-config-token.ts";
24
29
  import { buildAgentManifest } from "./slack-provisioning-client.ts";
25
30
 
26
31
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -115,6 +120,12 @@ interface SlackProvisioningServiceDeps {
115
120
  appBaseUrl: string;
116
121
  /** Env var keys that must be stored as secrets — mirrors SECRET_ENV_VARS. */
117
122
  secretEnvVars: Set<string>;
123
+ /**
124
+ * Optional stored Slack config token resolver (SCT-4.1). When present, a
125
+ * token minted from the agent's account row (else the default row) is used
126
+ * whenever no xoxpToken was pasted. Absent keeps the paste-only behavior.
127
+ */
128
+ slackConfigTokens?: SlackConfigTokenResolver;
118
129
  }
119
130
 
120
131
  // ─── Service ──────────────────────────────────────────────────────────────────
@@ -142,11 +153,23 @@ export class SlackProvisioningService {
142
153
  */
143
154
  async createAppManifest(
144
155
  agentName: string,
145
- xoxpToken: string,
156
+ xoxpToken: string | undefined,
146
157
  redirectUri: string,
158
+ /**
159
+ * Account whose stored Slack config token applies when `xoxpToken` is
160
+ * absent (its own row, else the deployment-wide default). Ignored when a
161
+ * token was pasted.
162
+ */
163
+ accountId?: string | null,
147
164
  ): Promise<SlackAppManifestResult> {
148
165
  const manifest = buildAgentManifest(agentName, redirectUri);
149
- return this.deps.slackClient.createAppManifest(xoxpToken, manifest);
166
+ // A pasted token wins (no retry); a stored one is minted per call, with one
167
+ // forced rotate + retry if Slack reports token_revoked / invalid_auth.
168
+ return withSlackConfigToken(
169
+ this.deps.slackConfigTokens,
170
+ { pasted: xoxpToken, accountId },
171
+ (token) => this.deps.slackClient.createAppManifest(token, manifest),
172
+ );
150
173
  }
151
174
 
152
175
  /**
@@ -213,24 +236,35 @@ export class SlackProvisioningService {
213
236
  redirectUri: string,
214
237
  ghConnectError?: string,
215
238
  ): Promise<StartConnectResult> {
216
- if (!xoxpToken?.startsWith("xoxe.xoxp-")) {
217
- return {
218
- ok: false,
219
- error: "Slack app configuration token must start with xoxe.xoxp-",
220
- };
221
- }
239
+ const prefixError = {
240
+ ok: false,
241
+ error: "Slack app configuration token must start with xoxe.xoxp-",
242
+ } as const;
243
+ // A pasted token must be well-formed; the prefix check never applies to a
244
+ // minted token. Without a resolver this is the original up-front check.
245
+ const pasted = xoxpToken?.trim() || undefined;
246
+ if (pasted && !pasted.startsWith("xoxe.xoxp-")) return prefixError;
247
+ if (!pasted && !this.deps.slackConfigTokens) return prefixError;
222
248
 
223
249
  const agent = await this.deps.agentService.getDetail(agentId);
224
250
  if (!agent) {
225
251
  return { ok: false, error: "Agent not found." };
226
252
  }
253
+ const accountId = agent.accountId ?? null;
254
+ if (
255
+ !pasted &&
256
+ !(await hasStoredSlackConfigToken(this.deps.slackConfigTokens, accountId))
257
+ ) {
258
+ return prefixError;
259
+ }
227
260
 
228
261
  let slackResult: SlackAppManifestResult;
229
262
  try {
230
263
  slackResult = await this.createAppManifest(
231
264
  agent.name,
232
- xoxpToken,
265
+ pasted,
233
266
  redirectUri,
267
+ accountId,
234
268
  );
235
269
  } catch (err) {
236
270
  const msg =