@app-vitals/agent-admin 1.63.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.63.0",
3
+ "version": "1.64.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.137.0",
45
- "@app-vitals/agent-lib": "1.63.0",
45
+ "@app-vitals/agent-lib": "1.64.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -124,6 +124,7 @@ import { isPushEnabled } from "./push-sender.ts";
124
124
  import { PushService } from "./push-service.ts";
125
125
  import { parseRepoAccessConfig } from "./repo-access-config.ts";
126
126
  import { parseSelfServeConfig } from "./self-serve-config.ts";
127
+ import { SlackConfigTokenService } from "./slack-config-token.ts";
127
128
  import { HttpSlackProvisioningClient } from "./slack-provisioning-client.ts";
128
129
  import { SpecialtyTypes } from "./specialty-types.ts";
129
130
  import { runStartupPolicyReconcile } from "./startup-policy-reconcile.ts";
@@ -304,6 +305,12 @@ export async function startAdmin(
304
305
  : undefined;
305
306
  const slackClient = new HttpSlackProvisioningClient();
306
307
  const githubAppClient = new HttpGithubAppProvisioningClient();
308
+ const slackConfigTokenService = new SlackConfigTokenService(
309
+ prisma,
310
+ makeStrictTokenCrypto(),
311
+ undefined,
312
+ slackClient,
313
+ );
307
314
 
308
315
  // Chat-service client for deleteAgentFully() cleanup, shared by both delete
309
316
  // entry points (DELETE /agents/:id and the admin-ui danger zone) —
@@ -651,6 +658,11 @@ export async function startAdmin(
651
658
  specialtyRegistry,
652
659
  specialtyDefaults,
653
660
  templateService,
661
+ slackConfigToken: {
662
+ tokens: slackConfigTokenService,
663
+ rotateClient: slackClient,
664
+ encryptionConfigured: () => makeStrictTokenCrypto() !== null,
665
+ },
654
666
  templateReconcile: templateReconcileService,
655
667
  serviceIntegrations,
656
668
  chatService: deletionChatService,
@@ -104,6 +104,8 @@ export const SETTINGS_GHE_PATH = "/admin/settings/github-enterprise";
104
104
  export const SETTINGS_ACCOUNT_PATH = "/admin/account";
105
105
  export const SETTINGS_ACCOUNTS_PATH = "/admin/accounts";
106
106
  export const SETTINGS_TEMPLATES_PATH = "/admin/settings/templates";
107
+ export const SETTINGS_SLACK_CONFIG_TOKEN_PATH =
108
+ "/admin/settings/slack-config-token";
107
109
 
108
110
  export interface BuildSettingsNavOptions {
109
111
  /** Include the GitHub Enterprise item (its routes are registered). */
@@ -112,6 +114,8 @@ export interface BuildSettingsNavOptions {
112
114
  accounts?: boolean;
113
115
  /** Include the Templates item (its routes are registered). */
114
116
  templates?: boolean;
117
+ /** Include the Slack config token item (its routes are registered). */
118
+ slackConfigToken?: boolean;
115
119
  /** Extension-contributed items (SGL-2.1). */
116
120
  extraItems?: readonly SettingsNavContribution[];
117
121
  }
@@ -132,6 +136,13 @@ export function buildSettingsNav(
132
136
  adminOnly: true,
133
137
  });
134
138
  }
139
+ if (opts.slackConfigToken) {
140
+ // Not adminOnly, like Templates: account owners manage their own row.
141
+ platform.push({
142
+ label: "Slack config token",
143
+ path: SETTINGS_SLACK_CONFIG_TOKEN_PATH,
144
+ });
145
+ }
135
146
  if (opts.templates) {
136
147
  platform.push({ label: "Templates", path: SETTINGS_TEMPLATES_PATH });
137
148
  }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token-pages.ts
3
+ * Render function for Settings > Slack config token (SCT-3.1).
4
+ * Pure string -> string; routes live in admin-ui-slack-config-token.ts.
5
+ *
6
+ * The page only ever receives metadata (configured, last rotated, last error,
7
+ * team/user): there is no field through which a refresh or access token could
8
+ * reach the markup. The paste input is never pre-filled.
9
+ */
10
+
11
+ import { renderAdminPage } from "./admin-ui-layout.ts";
12
+ import {
13
+ buildSettingsNav,
14
+ renderSettingsLayout,
15
+ type SettingsNav,
16
+ } from "./admin-ui-settings-layout.ts";
17
+ import { escapeHtml } from "./admin-ui-styles.ts";
18
+
19
+ export const ADMIN_SLACK_CONFIG_TOKEN_PATH =
20
+ "/admin/settings/slack-config-token";
21
+
22
+ const BASE = ADMIN_SLACK_CONFIG_TOKEN_PATH;
23
+
24
+ export interface SlackConfigTokenScopeOption {
25
+ value: string;
26
+ label: string;
27
+ }
28
+
29
+ /** Display-only status of the row at the selected scope. */
30
+ export interface SlackConfigTokenStatusView {
31
+ lastRotatedAt: Date | null;
32
+ lastError: string | null;
33
+ slackTeamId: string | null;
34
+ slackUserId: string | null;
35
+ }
36
+
37
+ export interface SlackConfigTokenPageOpts {
38
+ userEmail: string;
39
+ isAdmin?: boolean;
40
+ nav?: SettingsNav;
41
+ /** Accounts the caller may pick; the deployment-wide option only for admins. */
42
+ accountOptions: SlackConfigTokenScopeOption[];
43
+ /** Selected scope ("" = deployment-wide). */
44
+ accountId: string;
45
+ /** Row at the selected scope, or null when not configured. */
46
+ status: SlackConfigTokenStatusView | null;
47
+ /** SHIPWRIGHT_ENCRYPTION_KEY is set; without it saving is refused. */
48
+ encryptionConfigured: boolean;
49
+ error?: string;
50
+ notice?: string;
51
+ }
52
+
53
+ function accountPicker(o: SlackConfigTokenPageOpts): string {
54
+ const opts = o.accountOptions
55
+ .map(
56
+ (a) =>
57
+ `<option value="${escapeHtml(a.value)}"${a.value === o.accountId ? " selected" : ""}>${escapeHtml(a.label)}</option>`,
58
+ )
59
+ .join("");
60
+ return `<form method="GET" action="${BASE}" style="display:flex;gap:8px;align-items:end;flex-wrap:wrap">
61
+ <label>Account <select name="accountId" class="form-input">${opts}</select></label>
62
+ <button type="submit" class="btn btn-secondary">Open</button>
63
+ </form>`;
64
+ }
65
+
66
+ function scopeField(o: SlackConfigTokenPageOpts): string {
67
+ return `<input type="hidden" name="accountId" value="${escapeHtml(o.accountId)}" />`;
68
+ }
69
+
70
+ const when = (d: Date | null): string =>
71
+ d ? escapeHtml(d.toISOString()) : "never";
72
+
73
+ function statusCard(o: SlackConfigTokenPageOpts): string {
74
+ const s = o.status;
75
+ if (!s) {
76
+ return `<p class="help-text">Not configured for this scope.</p>`;
77
+ }
78
+ const team =
79
+ s.slackTeamId || s.slackUserId
80
+ ? `${escapeHtml(s.slackTeamId ?? "?")} / ${escapeHtml(s.slackUserId ?? "?")}`
81
+ : "unknown";
82
+ return `<table class="data-table"><tbody>
83
+ <tr><th>Configured</th><td>Yes</td></tr>
84
+ <tr><th>Last rotated</th><td>${when(s.lastRotatedAt)}</td></tr>
85
+ <tr><th>Last error</th><td>${s.lastError ? escapeHtml(s.lastError) : "none"}</td></tr>
86
+ <tr><th>Team / user</th><td>${team}</td></tr>
87
+ </tbody></table>
88
+ <div style="display:flex;gap:8px;margin-top:12px">
89
+ <form method="POST" action="${BASE}/rotate">${scopeField(o)}<button type="submit" class="btn btn-secondary">Rotate now</button></form>
90
+ <form method="POST" action="${BASE}/clear">${scopeField(o)}<button type="submit" class="btn btn-danger">Clear token</button></form>
91
+ </div>`;
92
+ }
93
+
94
+ export function renderSlackConfigTokenPage(
95
+ o: SlackConfigTokenPageOpts,
96
+ ): string {
97
+ const error = o.error
98
+ ? `<div class="alert alert-error">${escapeHtml(o.error)}</div>`
99
+ : "";
100
+ const notice = o.notice
101
+ ? `<div class="alert alert-success">${escapeHtml(o.notice)}</div>`
102
+ : "";
103
+ const encryptionWarning = o.encryptionConfigured
104
+ ? ""
105
+ : `<div class="alert alert-error">SHIPWRIGHT_ENCRYPTION_KEY is not configured, so a Slack config token cannot be saved. Set it to a 64-character hex string (openssl rand -hex 32) and restart.</div>`;
106
+ return renderAdminPage({
107
+ title: "Slack config token — Settings — Shipwright Admin",
108
+ body: renderSettingsLayout({
109
+ userName: o.userEmail,
110
+ title: "Slack config token",
111
+ nav:
112
+ o.nav ??
113
+ buildSettingsNav({ githubEnterprise: true, slackConfigToken: true }),
114
+ active: BASE,
115
+ isAdmin: o.isAdmin ?? false,
116
+ body: `${error}${notice}${encryptionWarning}
117
+ <div class="card">
118
+ <p class="help-text">The Slack App Configuration token used to create and update agent Slack apps. A deployment-wide token is the default; an account's own token overrides it. Tokens are stored encrypted and never shown.</p>
119
+ ${accountPicker(o)}
120
+ </div>
121
+ <div class="card">
122
+ <div class="card-title">Status</div>
123
+ ${statusCard(o)}
124
+ </div>
125
+ <div class="card">
126
+ <div class="card-title">${o.status ? "Replace refresh token" : "Add refresh token"}</div>
127
+ <form method="POST" action="${BASE}/save" style="display:grid;gap:8px;max-width:480px">
128
+ ${scopeField(o)}
129
+ <label>Refresh token (xoxe-1-...) <input type="password" name="refreshToken" class="form-input" autocomplete="off" required placeholder="xoxe-1-..." /></label>
130
+ <p class="help-text">Generate it at api.slack.com/apps under Your App Configuration Tokens. It is validated by rotating it once; the rotated pair is stored.</p>
131
+ <div><button type="submit" class="btn btn-primary"${o.encryptionConfigured ? "" : " disabled"}>Validate and save</button></div>
132
+ </form>
133
+ </div>`,
134
+ }),
135
+ });
136
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token-pages.unit.test.ts
3
+ * Unit tests for renderSlackConfigTokenPage (SCT-3.1).
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import {
8
+ renderSlackConfigTokenPage,
9
+ type SlackConfigTokenPageOpts,
10
+ } from "./admin-ui-slack-config-token-pages.ts";
11
+
12
+ const base: SlackConfigTokenPageOpts = {
13
+ userEmail: "a@x.com",
14
+ isAdmin: true,
15
+ accountOptions: [{ value: "", label: "Deployment-wide" }],
16
+ accountId: "",
17
+ status: null,
18
+ encryptionConfigured: true,
19
+ };
20
+
21
+ describe("renderSlackConfigTokenPage", () => {
22
+ it("shows the unconfigured state without rotate/clear actions", () => {
23
+ const html = renderSlackConfigTokenPage(base);
24
+ expect(html).toContain("Not configured for this scope");
25
+ expect(html).toContain("Add refresh token");
26
+ expect(html).not.toContain("Rotate now");
27
+ expect(html).not.toContain("Clear token");
28
+ });
29
+
30
+ it("shows status metadata and actions when configured", () => {
31
+ const html = renderSlackConfigTokenPage({
32
+ ...base,
33
+ status: {
34
+ lastRotatedAt: new Date("2026-11-16T00:00:00Z"),
35
+ lastError: "invalid_refresh_token",
36
+ slackTeamId: "T123",
37
+ slackUserId: "U456",
38
+ },
39
+ });
40
+ expect(html).toContain("2026-11-16T00:00:00.000Z");
41
+ expect(html).toContain("invalid_refresh_token");
42
+ expect(html).toContain("T123 / U456");
43
+ expect(html).toContain("Rotate now");
44
+ expect(html).toContain("Clear token");
45
+ expect(html).toContain("Replace refresh token");
46
+ });
47
+
48
+ it("warns and disables save when the encryption key is missing", () => {
49
+ const html = renderSlackConfigTokenPage({
50
+ ...base,
51
+ encryptionConfigured: false,
52
+ });
53
+ expect(html).toContain("SHIPWRIGHT_ENCRYPTION_KEY is not configured");
54
+ expect(html).toContain(" disabled");
55
+ });
56
+
57
+ it("escapes error, notice and scope labels and marks the selected scope", () => {
58
+ const html = renderSlackConfigTokenPage({
59
+ ...base,
60
+ accountOptions: [{ value: "a1", label: "<b>Acme</b>" }],
61
+ accountId: "a1",
62
+ error: "<script>x</script>",
63
+ notice: "<i>n</i>",
64
+ });
65
+ expect(html).toContain("&lt;b&gt;Acme&lt;/b&gt;");
66
+ expect(html).toContain('<option value="a1" selected>');
67
+ expect(html).toContain("&lt;script&gt;x&lt;/script&gt;");
68
+ expect(html).toContain("&lt;i&gt;n&lt;/i&gt;");
69
+ });
70
+
71
+ it("never pre-fills the token input", () => {
72
+ const html = renderSlackConfigTokenPage({
73
+ ...base,
74
+ status: {
75
+ lastRotatedAt: null,
76
+ lastError: null,
77
+ slackTeamId: null,
78
+ slackUserId: null,
79
+ },
80
+ });
81
+ expect(html).toMatch(/name="refreshToken"[^>]*type|type="password"/);
82
+ expect(html).not.toMatch(/name="refreshToken"[^>]*value=/);
83
+ });
84
+ });
@@ -0,0 +1,287 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token.smoke.test.ts
3
+ * Smoke tests for /admin/settings/slack-config-token (SCT-3.1) via
4
+ * app.request(), over an in-memory token service and a fake rotate client.
5
+ * No DB, no network.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import type { MiddlewareHandler } from "hono";
10
+ import { Hono } from "hono";
11
+ import type { AdminUIEnv } from "./admin-ui.ts";
12
+ import { registerAdminSlackConfigTokenRoutes } from "./admin-ui-slack-config-token.ts";
13
+ import type { CallerScope } from "./caller-scope.ts";
14
+ import type { SlackConfigTokenMetadata } from "./slack-config-token.ts";
15
+ import { SlackConfigTokenError } from "./slack-provisioning-client.ts";
16
+
17
+ const PASTED = "xoxe-1-PASTED-REFRESH-SECRET";
18
+ const NEW_REFRESH = "xoxe-1-ROTATED-REFRESH-SECRET";
19
+ const NEW_ACCESS = "xoxe-ROTATED-ACCESS-SECRET";
20
+ const SECRETS = [PASTED, NEW_REFRESH, NEW_ACCESS];
21
+ const now = new Date("2026-11-16T00:00:00Z");
22
+
23
+ interface Opts {
24
+ isAdmin?: boolean;
25
+ scope?: CallerScope;
26
+ role?: "owner" | "member";
27
+ encryption?: boolean;
28
+ rotateFails?: string;
29
+ }
30
+
31
+ function setup(opts: Opts = {}) {
32
+ const rows = new Map<string | null, SlackConfigTokenMetadata>();
33
+ const saved: { accountId: string | null; refreshToken: string }[] = [];
34
+ const rotateCalls: string[] = [];
35
+ const forced: (string | null)[] = [];
36
+ const meta = (accountId: string | null): SlackConfigTokenMetadata => ({
37
+ id: `id-${accountId}`,
38
+ accountId,
39
+ refreshTokenSet: true,
40
+ accessTokenSet: true,
41
+ accessTokenExpiresAt: null,
42
+ slackTeamId: "T1",
43
+ slackUserId: "U1",
44
+ lastRotatedAt: now,
45
+ lastError: null,
46
+ createdAt: now,
47
+ updatedAt: now,
48
+ });
49
+ const app = new Hono<AdminUIEnv>();
50
+ const requireAuth = (async (c, next) => {
51
+ c.set("userEmail", "u@x.com");
52
+ c.set("isAdmin", opts.isAdmin ?? true);
53
+ await next();
54
+ }) as MiddlewareHandler<AdminUIEnv>;
55
+ registerAdminSlackConfigTokenRoutes(app, {
56
+ requireAuth,
57
+ tokens: {
58
+ get: async (id) => rows.get(id) ?? null,
59
+ save: async (id, input) => {
60
+ saved.push({ accountId: id, refreshToken: input.refreshToken });
61
+ rows.set(id, meta(id));
62
+ return meta(id);
63
+ },
64
+ clear: async (id) => {
65
+ rows.delete(id);
66
+ },
67
+ getAccessToken: async (id) => {
68
+ forced.push(id);
69
+ return NEW_ACCESS;
70
+ },
71
+ },
72
+ rotateClient: {
73
+ rotateConfigToken: async (t) => {
74
+ rotateCalls.push(t);
75
+ if (opts.rotateFails) {
76
+ throw new SlackConfigTokenError(opts.rotateFails, `bad ${t}`);
77
+ }
78
+ return {
79
+ accessToken: NEW_ACCESS,
80
+ refreshToken: NEW_REFRESH,
81
+ teamId: "T1",
82
+ userId: "U1",
83
+ iat: 1,
84
+ exp: 2,
85
+ };
86
+ },
87
+ },
88
+ encryptionConfigured: () => opts.encryption ?? true,
89
+ callerScopeResolver: async () =>
90
+ opts.scope ?? { kind: "scoped", accountId: null, agentIds: [] },
91
+ members: {
92
+ getByEmail: async () =>
93
+ ({
94
+ accountId: "acct-1",
95
+ role: opts.role ?? "owner",
96
+ }) as never,
97
+ },
98
+ accounts: {
99
+ listWithCounts: async () =>
100
+ [
101
+ { id: "acct-1", name: "Acme" },
102
+ { id: "acct-2", name: "Globex" },
103
+ ] as never,
104
+ getWithCounts: async (id: string) => ({ id, name: "Acme" }) as never,
105
+ },
106
+ html: (content, o) =>
107
+ new Response(content, {
108
+ status: o?.status ?? 200,
109
+ headers: { "Content-Type": "text/html" },
110
+ }),
111
+ });
112
+ return { app, rows, saved, rotateCalls, forced };
113
+ }
114
+
115
+ const BASE = "/admin/settings/slack-config-token";
116
+ const form = (fields: Record<string, string>) => ({
117
+ method: "POST",
118
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
119
+ body: new URLSearchParams(fields).toString(),
120
+ });
121
+ const owner: CallerScope = {
122
+ kind: "scoped",
123
+ accountId: "acct-1",
124
+ agentIds: [],
125
+ };
126
+ const expectNoSecrets = (s: string) => {
127
+ for (const secret of SECRETS) expect(s).not.toContain(secret);
128
+ };
129
+
130
+ describe("/admin/settings/slack-config-token smoke", () => {
131
+ it("renders the page with the scope picker for an admin", async () => {
132
+ const { app } = setup();
133
+ const res = await app.request(BASE);
134
+ expect(res.status).toBe(200);
135
+ const html = await res.text();
136
+ expect(html).toContain("Deployment-wide");
137
+ expect(html).toContain("Acme");
138
+ expect(html).toContain("Not configured");
139
+ });
140
+
141
+ it("admin saves the default row: validates by rotating, stores the rotated pair, no secrets in redirect or page", async () => {
142
+ const { app, saved, rotateCalls } = setup();
143
+ const res = await app.request(
144
+ `${BASE}/save`,
145
+ form({ accountId: "", refreshToken: PASTED }),
146
+ );
147
+ expect(res.status).toBe(302);
148
+ const loc = res.headers.get("location") as string;
149
+ expectNoSecrets(loc);
150
+ expect(rotateCalls).toEqual([PASTED]);
151
+ expect(saved).toEqual([{ accountId: null, refreshToken: NEW_REFRESH }]);
152
+ const html = await (await app.request(loc)).text();
153
+ expectNoSecrets(html);
154
+ expect(html).toContain("validated and saved");
155
+ expect(html).toContain("T1 / U1");
156
+ });
157
+
158
+ it("admin can save another account's row", async () => {
159
+ const { app, saved } = setup();
160
+ const res = await app.request(
161
+ `${BASE}/save`,
162
+ form({ accountId: "acct-2", refreshToken: PASTED }),
163
+ );
164
+ expect(res.status).toBe(302);
165
+ expect(res.headers.get("location")).toContain("accountId=acct-2");
166
+ expect(saved[0]?.accountId).toBe("acct-2");
167
+ });
168
+
169
+ it("invalid paste shows an error and stores nothing", async () => {
170
+ const { app, saved, rotateCalls } = setup({
171
+ rotateFails: "invalid_refresh_token",
172
+ });
173
+ const res = await app.request(
174
+ `${BASE}/save`,
175
+ form({ accountId: "", refreshToken: PASTED }),
176
+ );
177
+ expect(res.status).toBe(422);
178
+ const html = await res.text();
179
+ expect(html).toContain("invalid_refresh_token");
180
+ expectNoSecrets(html);
181
+ expect(saved).toHaveLength(0);
182
+ expect(rotateCalls).toHaveLength(1);
183
+ });
184
+
185
+ it("a paste without the xoxe-1- prefix is refused before any Slack call", async () => {
186
+ const { app, saved, rotateCalls } = setup();
187
+ const res = await app.request(
188
+ `${BASE}/save`,
189
+ form({ accountId: "", refreshToken: "xoxb-not-a-config-token" }),
190
+ );
191
+ expect(res.status).toBe(422);
192
+ expect(await res.text()).toContain("xoxe-1-");
193
+ expect(saved).toHaveLength(0);
194
+ expect(rotateCalls).toHaveLength(0);
195
+ });
196
+
197
+ it("refuses save with a clear message when the encryption key is unset", async () => {
198
+ const { app, saved, rotateCalls } = setup({ encryption: false });
199
+ const res = await app.request(
200
+ `${BASE}/save`,
201
+ form({ accountId: "", refreshToken: PASTED }),
202
+ );
203
+ expect(res.status).toBe(422);
204
+ expect(await res.text()).toContain("SHIPWRIGHT_ENCRYPTION_KEY");
205
+ expect(saved).toHaveLength(0);
206
+ expect(rotateCalls).toHaveLength(0);
207
+ });
208
+
209
+ it("clear removes the row", async () => {
210
+ const { app, rows } = setup();
211
+ await app.request(
212
+ `${BASE}/save`,
213
+ form({ accountId: "", refreshToken: PASTED }),
214
+ );
215
+ expect(rows.has(null)).toBe(true);
216
+ const res = await app.request(`${BASE}/clear`, form({ accountId: "" }));
217
+ expect(res.status).toBe(302);
218
+ expect(rows.has(null)).toBe(false);
219
+ });
220
+
221
+ it("rotate now forces a rotation and never exposes the access token", async () => {
222
+ const { app, forced } = setup();
223
+ const res = await app.request(
224
+ `${BASE}/rotate`,
225
+ form({ accountId: "acct-2" }),
226
+ );
227
+ expect(res.status).toBe(302);
228
+ expect(forced).toEqual(["acct-2"]);
229
+ expectNoSecrets(res.headers.get("location") as string);
230
+ });
231
+
232
+ it("account owner manages only their own account's row", async () => {
233
+ const { app, saved } = setup({ isAdmin: false, scope: owner });
234
+ const page = await app.request(BASE);
235
+ expect(page.status).toBe(200);
236
+ const html = await page.text();
237
+ expect(html).toContain("Acme");
238
+ expect(html).not.toContain("Deployment-wide");
239
+ const own = await app.request(
240
+ `${BASE}/save`,
241
+ form({ refreshToken: PASTED }),
242
+ );
243
+ expect(own.status).toBe(302);
244
+ expect(saved[0]?.accountId).toBe("acct-1");
245
+ const ownExplicit = await app.request(
246
+ `${BASE}/save`,
247
+ form({ accountId: "acct-1", refreshToken: PASTED }),
248
+ );
249
+ expect(ownExplicit.status).toBe(302);
250
+ });
251
+
252
+ it("owner gets 403 for another account and the deployment-wide row", async () => {
253
+ const { app, saved, rotateCalls } = setup({ isAdmin: false, scope: owner });
254
+ expect((await app.request(`${BASE}?accountId=acct-2`)).status).toBe(403);
255
+ for (const path of ["save", "clear", "rotate"]) {
256
+ const res = await app.request(
257
+ `${BASE}/${path}`,
258
+ form({ accountId: "acct-2", refreshToken: PASTED }),
259
+ );
260
+ expect(res.status).toBe(403);
261
+ }
262
+ expect(saved).toHaveLength(0);
263
+ expect(rotateCalls).toHaveLength(0);
264
+ });
265
+
266
+ it("plain account members get 403 on GET and every action", async () => {
267
+ const { app, saved } = setup({
268
+ isAdmin: false,
269
+ scope: owner,
270
+ role: "member",
271
+ });
272
+ expect((await app.request(BASE)).status).toBe(403);
273
+ for (const path of ["save", "clear", "rotate"]) {
274
+ const res = await app.request(
275
+ `${BASE}/${path}`,
276
+ form({ accountId: "acct-1", refreshToken: PASTED }),
277
+ );
278
+ expect(res.status).toBe(403);
279
+ }
280
+ expect(saved).toHaveLength(0);
281
+ });
282
+
283
+ it("callers without an account get 403", async () => {
284
+ const { app } = setup({ isAdmin: false });
285
+ expect((await app.request(BASE)).status).toBe(403);
286
+ });
287
+ });
@@ -0,0 +1,251 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token.ts
3
+ * GET/POST /admin/settings/slack-config-token — Settings > Slack config token
4
+ * (SCT-3.1). A thin UI over SlackConfigTokenService, scoped like the Templates
5
+ * editor: platform admins manage the deployment-wide row and any account's row
6
+ * (?accountId=); account owners manage only their own account's row; plain
7
+ * members, ownerless callers and other accounts get 403.
8
+ *
9
+ * Neither the rendered HTML nor any redirect URL carries token material: the
10
+ * pasted refresh token is validated by rotating it once, the rotated pair goes
11
+ * straight to the service, and only metadata is read back.
12
+ */
13
+
14
+ import type { Context, Hono, MiddlewareHandler } from "hono";
15
+ import { accountIdFromScope } from "./account-agent-create.ts";
16
+ import type { AccountMemberService } from "./account-members.ts";
17
+ import type { AccountService } from "./accounts.ts";
18
+ import type { AdminUIEnv } from "./admin-ui.ts";
19
+ import type { SettingsNav } from "./admin-ui-settings-layout.ts";
20
+ import {
21
+ ADMIN_SLACK_CONFIG_TOKEN_PATH as BASE,
22
+ renderSlackConfigTokenPage,
23
+ type SlackConfigTokenScopeOption,
24
+ } from "./admin-ui-slack-config-token-pages.ts";
25
+ import type { CallerScopeResolver } from "./caller-scope.ts";
26
+ import {
27
+ ApiError,
28
+ ForbiddenError,
29
+ UnprocessableEntityError,
30
+ } from "./errors.ts";
31
+ import type { SlackConfigTokenService } from "./slack-config-token.ts";
32
+ import type { SlackConfigTokenClient } from "./slack-provisioning-client.ts";
33
+
34
+ export interface AdminSlackConfigTokenRouteDeps {
35
+ requireAuth: MiddlewareHandler<AdminUIEnv>;
36
+ tokens: Pick<
37
+ SlackConfigTokenService,
38
+ "get" | "save" | "clear" | "getAccessToken"
39
+ >;
40
+ /** tooling.tokens.rotate client, used to validate a pasted refresh token. */
41
+ rotateClient: SlackConfigTokenClient;
42
+ /** SHIPWRIGHT_ENCRYPTION_KEY is configured; save is refused without it. */
43
+ encryptionConfigured: () => boolean;
44
+ callerScopeResolver: CallerScopeResolver;
45
+ /** Needed to tell account owners from plain members; absent = admins only. */
46
+ members?: Pick<AccountMemberService, "getByEmail">;
47
+ accounts?: Pick<AccountService, "listWithCounts" | "getWithCounts">;
48
+ settingsNav?: SettingsNav;
49
+ html: (content: string, opts?: { status?: number }) => Response;
50
+ }
51
+
52
+ type Actor = { kind: "admin" } | { kind: "account"; accountId: string };
53
+
54
+ const NOTICES: Record<string, string> = {
55
+ saved: "Slack config token validated and saved.",
56
+ cleared: "Slack config token cleared.",
57
+ rotated: "Slack config token rotated.",
58
+ };
59
+
60
+ const REFRESH_PREFIX = "xoxe-1-";
61
+
62
+ export function registerAdminSlackConfigTokenRoutes(
63
+ app: Hono<AdminUIEnv>,
64
+ deps: AdminSlackConfigTokenRouteDeps,
65
+ ): void {
66
+ async function resolveActor(c: Context<AdminUIEnv>): Promise<Actor> {
67
+ if (c.var.isAdmin === true) return { kind: "admin" };
68
+ const accountId = accountIdFromScope(
69
+ await deps.callerScopeResolver(c.var.userEmail, false),
70
+ );
71
+ if (accountId === null || !deps.members) {
72
+ throw new ForbiddenError("Admin or account owner access required");
73
+ }
74
+ const me = await deps.members.getByEmail(c.var.userEmail);
75
+ if (!me || me.role !== "owner" || me.accountId !== accountId) {
76
+ throw new ForbiddenError("Admin or account owner access required");
77
+ }
78
+ return { kind: "account", accountId };
79
+ }
80
+
81
+ /** Returns the account id to act on (null = deployment-wide); 403 otherwise. */
82
+ function resolveScope(actor: Actor, requested: string): string | null {
83
+ if (actor.kind === "account") {
84
+ if (requested !== "" && requested !== actor.accountId) {
85
+ throw new ForbiddenError(
86
+ "cannot manage another account's or the deployment-wide Slack config token",
87
+ );
88
+ }
89
+ return actor.accountId;
90
+ }
91
+ return requested === "" ? null : requested;
92
+ }
93
+
94
+ async function accountOptions(
95
+ actor: Actor,
96
+ ): Promise<SlackConfigTokenScopeOption[]> {
97
+ if (actor.kind === "account") {
98
+ const acct = await deps.accounts?.getWithCounts(actor.accountId);
99
+ return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
100
+ }
101
+ const accounts = (await deps.accounts?.listWithCounts()) ?? [];
102
+ return [
103
+ { value: "", label: "Deployment-wide (all accounts)" },
104
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
105
+ ];
106
+ }
107
+
108
+ async function renderPage(
109
+ c: Context<AdminUIEnv>,
110
+ actor: Actor,
111
+ accountId: string | null,
112
+ flash: { error?: string; notice?: string; status?: number } = {},
113
+ ): Promise<Response> {
114
+ const row = await deps.tokens.get(accountId);
115
+ return deps.html(
116
+ renderSlackConfigTokenPage({
117
+ userEmail: c.var.userEmail,
118
+ isAdmin: c.var.isAdmin === true,
119
+ ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
120
+ accountOptions: await accountOptions(actor),
121
+ accountId: accountId ?? "",
122
+ status: row
123
+ ? {
124
+ lastRotatedAt: row.lastRotatedAt,
125
+ lastError: row.lastError,
126
+ slackTeamId: row.slackTeamId,
127
+ slackUserId: row.slackUserId,
128
+ }
129
+ : null,
130
+ encryptionConfigured: deps.encryptionConfigured(),
131
+ ...(flash.error ? { error: flash.error } : {}),
132
+ ...(flash.notice ? { notice: flash.notice } : {}),
133
+ }),
134
+ { status: flash.status ?? 200 },
135
+ );
136
+ }
137
+
138
+ /** Slack's own error code, if it is a safe identifier; never a message. */
139
+ function rotateFailure(err: unknown): ApiError {
140
+ const code = (err as { code?: unknown } | null)?.code;
141
+ const safe =
142
+ typeof code === "string" && /^[a-z0-9_]{1,64}$/i.test(code)
143
+ ? code
144
+ : "unknown_error";
145
+ return new UnprocessableEntityError(
146
+ `Slack rejected the refresh token (${safe}). Nothing was saved.`,
147
+ );
148
+ }
149
+
150
+ async function mutate(
151
+ c: Context<AdminUIEnv>,
152
+ notice: string,
153
+ run: (accountId: string | null, form: FormData) => Promise<void>,
154
+ ): Promise<Response> {
155
+ let actor: Actor;
156
+ try {
157
+ actor = await resolveActor(c);
158
+ } catch {
159
+ return new Response("Forbidden", { status: 403 });
160
+ }
161
+ let form: FormData;
162
+ try {
163
+ form = await c.req.formData();
164
+ } catch {
165
+ form = new FormData();
166
+ }
167
+ let accountId: string | null;
168
+ try {
169
+ accountId = resolveScope(
170
+ actor,
171
+ (form.get("accountId")?.toString() ?? "").trim(),
172
+ );
173
+ } catch {
174
+ return new Response("Forbidden", { status: 403 });
175
+ }
176
+ try {
177
+ await run(accountId, form);
178
+ } catch (err) {
179
+ if (err instanceof ApiError) {
180
+ return renderPage(c, actor, accountId, {
181
+ error: err.message,
182
+ status: err.statusCode,
183
+ });
184
+ }
185
+ throw err;
186
+ }
187
+ const qs = new URLSearchParams({
188
+ ...(accountId !== null ? { accountId } : {}),
189
+ notice,
190
+ });
191
+ return c.redirect(`${BASE}?${qs}`, 302);
192
+ }
193
+
194
+ app.get(BASE, deps.requireAuth, async (c) => {
195
+ let actor: Actor;
196
+ let accountId: string | null;
197
+ try {
198
+ actor = await resolveActor(c);
199
+ accountId = resolveScope(actor, c.req.query("accountId")?.trim() ?? "");
200
+ } catch {
201
+ return new Response("Forbidden", { status: 403 });
202
+ }
203
+ const key = c.req.query("notice");
204
+ return renderPage(c, actor, accountId, {
205
+ ...(key && NOTICES[key] ? { notice: NOTICES[key] } : {}),
206
+ });
207
+ });
208
+
209
+ app.post(`${BASE}/save`, deps.requireAuth, (c) =>
210
+ mutate(c, "saved", async (accountId, form) => {
211
+ if (!deps.encryptionConfigured()) {
212
+ throw new UnprocessableEntityError(
213
+ "SHIPWRIGHT_ENCRYPTION_KEY is not configured; refusing to store a Slack config token unencrypted. Set it to a 64-character hex string (openssl rand -hex 32) and retry.",
214
+ );
215
+ }
216
+ const pasted = (form.get("refreshToken")?.toString() ?? "").trim();
217
+ if (!pasted.startsWith(REFRESH_PREFIX)) {
218
+ throw new UnprocessableEntityError(
219
+ `Paste a Slack App Configuration refresh token (it starts with ${REFRESH_PREFIX}).`,
220
+ );
221
+ }
222
+ let rotated: Awaited<
223
+ ReturnType<SlackConfigTokenClient["rotateConfigToken"]>
224
+ >;
225
+ try {
226
+ rotated = await deps.rotateClient.rotateConfigToken(pasted);
227
+ } catch (err) {
228
+ throw rotateFailure(err);
229
+ }
230
+ await deps.tokens.save(accountId, {
231
+ refreshToken: rotated.refreshToken,
232
+ accessToken: rotated.accessToken,
233
+ accessTokenExpiresAt: new Date(rotated.exp * 1000),
234
+ slackTeamId: rotated.teamId,
235
+ slackUserId: rotated.userId,
236
+ });
237
+ }),
238
+ );
239
+
240
+ app.post(`${BASE}/clear`, deps.requireAuth, (c) =>
241
+ mutate(c, "cleared", async (accountId) => {
242
+ await deps.tokens.clear(accountId);
243
+ }),
244
+ );
245
+
246
+ app.post(`${BASE}/rotate`, deps.requireAuth, (c) =>
247
+ mutate(c, "rotated", async (accountId) => {
248
+ await deps.tokens.getAccessToken(accountId, { forceRotate: true });
249
+ }),
250
+ );
251
+ }
package/src/admin-ui.ts CHANGED
@@ -100,6 +100,10 @@ import {
100
100
  type SettingsNav,
101
101
  withoutAccountItem,
102
102
  } from "./admin-ui-settings-layout.ts";
103
+ import {
104
+ type AdminSlackConfigTokenRouteDeps,
105
+ registerAdminSlackConfigTokenRoutes,
106
+ } from "./admin-ui-slack-config-token.ts";
103
107
  import { registerAdminTemplatesRoutes } from "./admin-ui-templates.ts";
104
108
  import type { AgentCronJobService } from "./agent-cron-jobs.ts";
105
109
  import type { DeleteAgentFullyDeps } from "./agent-deletion.ts";
@@ -474,6 +478,14 @@ export interface AdminUIDeps {
474
478
  AgentTemplateService,
475
479
  "list" | "replace" | "putItem" | "deleteItem" | "delete"
476
480
  >;
481
+ /**
482
+ * SCT-3.1: Settings > Slack config token. Optional; absent → no
483
+ * /admin/settings/slack-config-token routes and no nav entry.
484
+ */
485
+ slackConfigToken?: Pick<
486
+ AdminSlackConfigTokenRouteDeps,
487
+ "tokens" | "rotateClient" | "encryptionConfigured"
488
+ >;
477
489
  githubEnterpriseApi?: (
478
490
  path: string,
479
491
  init?: RequestInit,
@@ -913,6 +925,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
913
925
  accountServices,
914
926
  githubEnterpriseApi,
915
927
  templateService,
928
+ slackConfigToken,
916
929
  templateReconcile,
917
930
  agentsApi,
918
931
  specialtyRegistry = new SpecialtyTypes(),
@@ -962,6 +975,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
962
975
  const settingsNav = buildSettingsNav({
963
976
  githubEnterprise: Boolean(githubEnterpriseApi),
964
977
  templates: Boolean(templateService),
978
+ slackConfigToken: Boolean(slackConfigToken),
965
979
  accounts: accountNavEnabled,
966
980
  extraItems: deps.settingsNavItems ?? [],
967
981
  });
@@ -986,7 +1000,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
986
1000
 
987
1001
  // GHE-1.4: the admin-only "Settings" toolbar entry.
988
1002
  // SGL-2.2: shown to admins and to account members.
989
- if (githubEnterpriseApi || templateService || accountNavEnabled) {
1003
+ if (
1004
+ githubEnterpriseApi ||
1005
+ templateService ||
1006
+ slackConfigToken ||
1007
+ accountNavEnabled
1008
+ ) {
990
1009
  app.use("/admin/*", async (c, next) => {
991
1010
  const token = getCookie(c, SESSION_COOKIE);
992
1011
  const user = token ? await getSessionUser(token, sessionSecret) : null;
@@ -4066,7 +4085,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4066
4085
  // ─── Enterprise GitHub apps settings (GHE-1.4) ───────────────────────────
4067
4086
 
4068
4087
  // SGL-2.2: /admin/settings lands on the first nav item the viewer can see.
4069
- if (githubEnterpriseApi || templateService || accountNavEnabled) {
4088
+ if (
4089
+ githubEnterpriseApi ||
4090
+ templateService ||
4091
+ slackConfigToken ||
4092
+ accountNavEnabled
4093
+ ) {
4070
4094
  app.get("/admin/settings", requireAuth, async (c) => {
4071
4095
  // Admins without an account would 404 on the Account item; skip it.
4072
4096
  let nav = settingsNav;
@@ -4110,6 +4134,24 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4110
4134
  });
4111
4135
  }
4112
4136
 
4137
+ // ─── Slack config token settings (SCT-3.1) ───────────────────────────────
4138
+
4139
+ if (slackConfigToken) {
4140
+ registerAdminSlackConfigTokenRoutes(app, {
4141
+ requireAuth,
4142
+ ...slackConfigToken,
4143
+ settingsNav,
4144
+ callerScopeResolver,
4145
+ ...(accountServices
4146
+ ? {
4147
+ accounts: accountServices.accounts,
4148
+ members: accountServices.members,
4149
+ }
4150
+ : {}),
4151
+ html,
4152
+ });
4153
+ }
4154
+
4113
4155
  // ─── Account page (SSP-3.2) ───────────────────────────────────────────────
4114
4156
 
4115
4157
  if (accountServices) {