@app-vitals/agent-admin 1.18.0 → 1.20.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.
@@ -6756,3 +6756,147 @@ describe("admin API — PATCH /agents/:id githubUsername (GHE-2.1)", () => {
6756
6756
  }
6757
6757
  });
6758
6758
  });
6759
+
6760
+ // ─── GHE-2.4: GET /agents/:id/github-access ──────────────────────────────────
6761
+
6762
+ describe("admin API — GET /agents/:id/github-access (GHE-2.4)", () => {
6763
+ const OPS = "gha-ops-token";
6764
+ const READER = "gha-read-token";
6765
+ const AGENT_KEY = "gha-agent-token";
6766
+ const ACCESS = {
6767
+ username: "octocat",
6768
+ outcome: "ok" as const,
6769
+ userVerified: true,
6770
+ orgs: [
6771
+ {
6772
+ org: "acme-eng",
6773
+ status: "ok" as const,
6774
+ repos: [
6775
+ { fullName: "acme-eng/api", level: "write" as const, canPush: true },
6776
+ ],
6777
+ unresolved: 0,
6778
+ },
6779
+ ],
6780
+ unresolved: 0,
6781
+ complete: true,
6782
+ checkedAt: "2026-11-09T12:00:00.000Z",
6783
+ };
6784
+
6785
+ function setup(opts: {
6786
+ githubUsername?: string | null;
6787
+ preview?: AdminDeps["githubAccessPreview"];
6788
+ }) {
6789
+ const base = makeMockDeps();
6790
+ const calls: string[] = [];
6791
+ const deps: AdminDeps = {
6792
+ ...base,
6793
+ adminApiKeys: parseAdminApiKeys(
6794
+ `root:${ADMIN_API_KEY}:*,operator:${OPS}:platform.ops,reader:${READER}:platform.read`,
6795
+ ),
6796
+ agentTokenService: {
6797
+ ...base.agentTokenService,
6798
+ validate: async (t: string) =>
6799
+ t === AGENT_KEY ? { agentId: AGENT_ID } : null,
6800
+ },
6801
+ agentService: {
6802
+ ...base.agentService,
6803
+ getDetail: async (id: string) => {
6804
+ const d = await base.agentService.getDetail(id);
6805
+ return d ? { ...d, githubUsername: opts.githubUsername ?? null } : d;
6806
+ },
6807
+ },
6808
+ githubAccessPreview:
6809
+ opts.preview ??
6810
+ (async (u) => {
6811
+ calls.push(u);
6812
+ return { status: "ok", access: ACCESS };
6813
+ }),
6814
+ };
6815
+ return { app: createAdminApp(deps), calls };
6816
+ }
6817
+
6818
+ const get = (
6819
+ app: ReturnType<typeof createAdminApp>,
6820
+ headers: Record<string, string>,
6821
+ id = AGENT_ID,
6822
+ ) => app.request(`/agents/${id}/github-access`, { headers });
6823
+ const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
6824
+
6825
+ it("platform admin gets the resolver output unchanged", async () => {
6826
+ const { app, calls } = setup({ githubUsername: "octocat" });
6827
+ const res = await get(app, asAdmin);
6828
+ expect(res.status).toBe(200);
6829
+ expect(await res.json()).toEqual({ status: "ok", access: ACCESS });
6830
+ expect(calls).toEqual(["octocat"]);
6831
+ });
6832
+
6833
+ it("403 for a session member, ops key, read key and agent key", async () => {
6834
+ const { app, calls } = setup({ githubUsername: "octocat" });
6835
+ const memberApp = createAdminApp({
6836
+ ...makeMockDeps(),
6837
+ callerScopeResolver: async () => ({
6838
+ kind: "scoped",
6839
+ accountId: "acct-a",
6840
+ agentIds: [AGENT_ID],
6841
+ }),
6842
+ });
6843
+ const cookie = await sign(
6844
+ {
6845
+ isAdmin: false,
6846
+ userId: "user-acct",
6847
+ email: "owner@acct-a.example.com",
6848
+ iat: Math.floor(Date.now() / 1000),
6849
+ exp: Math.floor(Date.now() / 1000) + 3600,
6850
+ },
6851
+ SESSION_SECRET,
6852
+ "HS256",
6853
+ );
6854
+ expect(
6855
+ (await get(memberApp, { Cookie: `admin_session=${cookie}` })).status,
6856
+ ).toBe(403);
6857
+ for (const key of [OPS, READER, AGENT_KEY]) {
6858
+ const res = await get(app, { Authorization: `Bearer ${key}` });
6859
+ expect(res.status).toBe(403);
6860
+ }
6861
+ expect(calls).toEqual([]);
6862
+ });
6863
+
6864
+ it("404 for an unknown agent", async () => {
6865
+ const { app, calls } = setup({ githubUsername: "octocat" });
6866
+ expect((await get(app, asAdmin, "no-such-agent")).status).toBe(404);
6867
+ expect(calls).toEqual([]);
6868
+ });
6869
+
6870
+ it("422 with a clear message when no githubUsername is bound", async () => {
6871
+ const { app, calls } = setup({ githubUsername: null });
6872
+ const res = await get(app, asAdmin);
6873
+ expect(res.status).toBe(422);
6874
+ expect(((await res.json()) as { error: string }).error).toContain(
6875
+ "githubUsername",
6876
+ );
6877
+ expect(calls).toEqual([]);
6878
+ });
6879
+
6880
+ it("unconfigured is a 200 status, not an error", async () => {
6881
+ const { app } = setup({
6882
+ githubUsername: "octocat",
6883
+ preview: async () => ({ status: "unconfigured" }),
6884
+ });
6885
+ const res = await get(app, asAdmin);
6886
+ expect(res.status).toBe(200);
6887
+ expect(await res.json()).toEqual({ status: "unconfigured" });
6888
+ });
6889
+
6890
+ it("user_not_found is passed through", async () => {
6891
+ const access = { ...ACCESS, outcome: "user_not_found" as const, orgs: [] };
6892
+ const { app } = setup({
6893
+ githubUsername: "ghost",
6894
+ preview: async () => ({ status: "user_not_found", access }),
6895
+ });
6896
+ const res = await get(app, asAdmin);
6897
+ expect(res.status).toBe(200);
6898
+ expect(((await res.json()) as { status: string }).status).toBe(
6899
+ "user_not_found",
6900
+ );
6901
+ });
6902
+ });
package/src/agents-api.ts CHANGED
@@ -107,6 +107,7 @@ import {
107
107
  NotFoundError,
108
108
  UnprocessableEntityError,
109
109
  } from "./errors.ts";
110
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
110
111
  import { normalizeGithubUsername } from "./github-username.ts";
111
112
  import {
112
113
  AddAgentReposBodySchema,
@@ -255,6 +256,11 @@ export interface AdminDeps {
255
256
  AgentGitHubInstallationsService,
256
257
  "push" | "get"
257
258
  >;
259
+ /**
260
+ * GHE-2.4: backs GET /agents/:id/github-access. Optional (additive); absent
261
+ * means the enterprise Apps are not wired, reported as `unconfigured`.
262
+ */
263
+ githubAccessPreview?: GithubAccessPreviewFn;
258
264
  /**
259
265
  * Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
260
266
  * which has its own internal prisma.agent/prisma.agentEnv access — out of
@@ -545,6 +551,46 @@ const GitHubInstallationsSnapshotWrapperSchema = z
545
551
  .object({ snapshot: AgentGitHubInstallationsSnapshotSchema })
546
552
  .openapi("GitHubInstallationsSnapshotWrapper");
547
553
 
554
+ const GithubAccessOrgSchema = z.object({
555
+ org: z.string(),
556
+ status: z.enum([
557
+ "ok",
558
+ "lookup_app_not_installed",
559
+ "rate_limited",
560
+ "partial",
561
+ "error",
562
+ ]),
563
+ repos: z.array(
564
+ z.object({
565
+ fullName: z.string(),
566
+ level: z.enum(["admin", "maintain", "write", "triage", "read", "none"]),
567
+ canPush: z.boolean(),
568
+ }),
569
+ ),
570
+ unresolved: z.number().int(),
571
+ });
572
+
573
+ const GithubAccessPreviewSchema = z
574
+ .object({
575
+ status: z.enum(["ok", "user_not_found", "unconfigured"]).openapi({
576
+ description:
577
+ "`unconfigured` when the installer or lookup App is not set (no GitHub call was made).",
578
+ }),
579
+ access: z
580
+ .object({
581
+ username: z.string(),
582
+ outcome: z.enum(["ok", "user_not_found"]),
583
+ userVerified: z.boolean(),
584
+ orgs: z.array(GithubAccessOrgSchema),
585
+ unresolved: z.number().int(),
586
+ complete: z.boolean(),
587
+ checkedAt: z.string(),
588
+ })
589
+ .optional()
590
+ .openapi({ description: "Resolver output; absent when unconfigured." }),
591
+ })
592
+ .openapi("GithubAccessPreview");
593
+
548
594
  // ─── Route definitions ──────────────────────────────────────────────────────────
549
595
 
550
596
  const reconcileAgentsRoute = createRoute({
@@ -1418,6 +1464,26 @@ const getGitHubInstallationsRoute = createRoute({
1418
1464
  },
1419
1465
  });
1420
1466
 
1467
+ const getGithubAccessRoute = createRoute({
1468
+ method: "get",
1469
+ path: "/agents/{id}/github-access",
1470
+ summary: "Preview the repos the agent's bound GitHub user can reach",
1471
+ description:
1472
+ "Platform-admin only (session members, ops keys and agent keys get 403): the response lists repo names the bound user can reach. Read-only; nothing is stored. 404 for an unknown agent; 422 when no githubUsername is bound. Returns `status: unconfigured` (not an error, no GitHub call) when the enterprise Apps are not configured, and `status: user_not_found` when the user does not exist on GitHub; otherwise `access` is the resolver output (per-org status, repos with level and canPush, unresolved count, complete flag).",
1473
+ request: { params: AgentIdParamSchema },
1474
+ responses: {
1475
+ 200: {
1476
+ description: "Access preview",
1477
+ content: { "application/json": { schema: GithubAccessPreviewSchema } },
1478
+ },
1479
+ 401: { description: "Unauthorized", ...jsonError },
1480
+ 403: { description: "Platform admin required", ...jsonError },
1481
+ 404: { description: "Agent not found", ...jsonError },
1482
+ 422: { description: "Agent has no githubUsername", ...jsonError },
1483
+ 502: { description: "GitHub unavailable or refused", ...jsonError },
1484
+ },
1485
+ });
1486
+
1421
1487
  /** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
1422
1488
  export const cronRunStatsQuerySchema = z
1423
1489
  .object({
@@ -2849,6 +2915,28 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2849
2915
  return c.json({ bakedMarketplaces: stored }, 200);
2850
2916
  });
2851
2917
 
2918
+ // GET /agents/:id/github-access — GHE-2.4 read-only preview. Platform admin
2919
+ // only: never session members, ops/read keys or agent keys.
2920
+ app.openapi(getGithubAccessRoute, async (c) => {
2921
+ if (c.get("isAdmin") !== true) {
2922
+ throw new ForbiddenError(
2923
+ "Admin access required to preview GitHub access",
2924
+ );
2925
+ }
2926
+ const { id: agentId } = c.req.valid("param");
2927
+ const agent = await agentService.getDetail(agentId);
2928
+ if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
2929
+ if (!agent.githubUsername) {
2930
+ throw new UnprocessableEntityError(
2931
+ "agent has no githubUsername bound; set one with PATCH /agents/{id}",
2932
+ );
2933
+ }
2934
+ if (!deps.githubAccessPreview)
2935
+ return c.json({ status: "unconfigured" as const }, 200);
2936
+ const preview = await deps.githubAccessPreview(agent.githubUsername);
2937
+ return c.json(preview, 200);
2938
+ });
2939
+
2852
2940
  // GET /agents/:id/github-installations — latest snapshot, 404 if none yet
2853
2941
  app.openapi(getGitHubInstallationsRoute, async (c) => {
2854
2942
  const { id: agentId } = c.req.valid("param");
@@ -0,0 +1,364 @@
1
+ /**
2
+ * admin/src/github-access-preview.integration.test.ts
3
+ * Integration tests for GET /agents/:id/github-access (GHE-2.4): the full
4
+ * route against a real PostgreSQL DB (agents + stored enterprise Apps) and the
5
+ * GHE-1.2 / GHE-2.2 cassettes, replayed through an injected fetchFn.
6
+ *
7
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
8
+ */
9
+
10
+ import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
11
+ import { generateKeyPairSync } from "node:crypto";
12
+ import { readFileSync } from "node:fs";
13
+ import { sign } from "hono/jwt";
14
+ import type { PrismaClient } from "../prisma/client/client.ts";
15
+ import { AgentChatTokenService } from "./agent-chat-tokens.ts";
16
+ import { AgentCronJobService } from "./agent-cron-jobs.ts";
17
+ import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
18
+ import { AgentCronRunService } from "./agent-cron-runs.ts";
19
+ import { AgentEnvService } from "./agent-envs.ts";
20
+ import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
21
+ import { AgentMemberService } from "./agent-members.ts";
22
+ import { AgentPluginService } from "./agent-plugins.ts";
23
+ import { NoopAgentProvisioner } from "./agent-provisioner.ts";
24
+ import { AgentTokenService } from "./agent-tokens.ts";
25
+ import { AgentToolService } from "./agent-tools.ts";
26
+ import { AgentService } from "./agents.ts";
27
+ import type { AdminDeps } from "./agents-api.ts";
28
+ import { createAdminApp } from "./agents-api.ts";
29
+ import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
30
+ import { createGithubAccessPreview } from "./github-enterprise-api.ts";
31
+ import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
32
+ import { createAdminPrismaClient } from "./prisma-client.ts";
33
+ import type {
34
+ SpecialtyType,
35
+ SpecialtyTypeResolver,
36
+ } from "./specialty-types.ts";
37
+ import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
38
+
39
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
40
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
41
+
42
+ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
43
+ const REAL_KEY =
44
+ "0000000000000000000000000000000000000000000000000000000000000001";
45
+
46
+ async function makeSessionCookie(): Promise<string> {
47
+ return sign(
48
+ {
49
+ isAdmin: true,
50
+ userId: "user-123",
51
+ email: "admin@example.com",
52
+ name: "Admin User",
53
+ iat: Math.floor(Date.now() / 1000),
54
+ exp: Math.floor(Date.now() / 1000) + 3600,
55
+ },
56
+ SESSION_SECRET,
57
+ "HS256",
58
+ );
59
+ }
60
+
61
+ function makePrisma(): PrismaClient {
62
+ // TEST_DB is guaranteed set — the describe block is skipped otherwise.
63
+ return createAdminPrismaClient(TEST_DB as string);
64
+ }
65
+
66
+ const CODING_TYPE: SpecialtyType = {
67
+ name: "coding",
68
+ displayName: "Coding Agent",
69
+ templatesDir: "workspace/",
70
+ tools: ["Read", "Write", "Edit"],
71
+ requiredEnv: [],
72
+ };
73
+
74
+ function fakeSpecialtyTypes(): SpecialtyTypeResolver {
75
+ const byType: Record<string, SpecialtyType> = { coding: CODING_TYPE };
76
+ return {
77
+ getType(specialty: string): SpecialtyType {
78
+ return byType[specialty] ?? (byType.coding as SpecialtyType);
79
+ },
80
+ tryGetType(specialty: string): SpecialtyType | undefined {
81
+ return byType[specialty];
82
+ },
83
+ listTypes() {
84
+ return Object.entries(byType).map(([name, manifest]) => ({
85
+ name,
86
+ displayName: manifest.displayName,
87
+ }));
88
+ },
89
+ };
90
+ }
91
+
92
+ function makeDeps(prisma: PrismaClient): AdminDeps {
93
+ const savedKey = process.env.SHIPWRIGHT_ENCRYPTION_KEY;
94
+ process.env.SHIPWRIGHT_ENCRYPTION_KEY = REAL_KEY;
95
+ const crypto = makeTokenCrypto();
96
+ if (savedKey === undefined) {
97
+ delete process.env.SHIPWRIGHT_ENCRYPTION_KEY;
98
+ } else {
99
+ process.env.SHIPWRIGHT_ENCRYPTION_KEY = savedKey;
100
+ }
101
+
102
+ return {
103
+ agentService: new AgentService(prisma),
104
+ agentEnvService: new AgentEnvService(prisma, crypto),
105
+ agentCronJobService: new AgentCronJobService(prisma),
106
+ agentCronRunService: new AgentCronRunService(prisma),
107
+ agentCronRunStatsService: new AgentCronRunStatsService(prisma),
108
+ agentToolService: new AgentToolService(prisma),
109
+ agentTokenService: new AgentTokenService(prisma),
110
+ agentPluginService: new AgentPluginService(prisma),
111
+ agentMemberService: new AgentMemberService(prisma),
112
+ specialtyRegistry: fakeSpecialtyTypes(),
113
+ agentChatTokenService: new AgentChatTokenService(prisma),
114
+ agentGitHubInstallationsService: new AgentGitHubInstallationsService(
115
+ prisma,
116
+ ),
117
+ prisma,
118
+ provisioner: new NoopAgentProvisioner(),
119
+ serviceIntegrations: [
120
+ {
121
+ name: "task-store",
122
+ listTokensForAgent: async () => [],
123
+ revokeToken: async () => {},
124
+ },
125
+ ],
126
+ chatService: new NoopChatServiceProvisioningClient(),
127
+ slack: {
128
+ deleteApp: async () => {},
129
+ },
130
+ decrypt: (value: string) => crypto.decrypt(value),
131
+ sessionSecret: SESSION_SECRET,
132
+ };
133
+ }
134
+
135
+ type Cassette = Record<
136
+ string,
137
+ { status: number; headers?: Record<string, string>; body: unknown }
138
+ >;
139
+ const load = (f: string): Cassette =>
140
+ JSON.parse(
141
+ readFileSync(new URL(`./fixtures/${f}`, import.meta.url).pathname, "utf-8"),
142
+ );
143
+ const enterprise = load("github-enterprise-cassette.json");
144
+ const lookup = load("github-lookup-cassette.json");
145
+
146
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
147
+ modulusLength: 2048,
148
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
149
+ publicKeyEncoding: { type: "spki", format: "pem" },
150
+ });
151
+ const PEM_BODY = PEM.split("\n")[1] as string;
152
+ const ENC_KEY = "c".repeat(64);
153
+ const NOW = new Date("2026-11-09T12:00:00Z");
154
+
155
+ /** route -> [cassette, entry]. org-1 has the lookup App, org-2 does not. */
156
+ const ROUTES: Record<string, [Cassette, string]> = {
157
+ "GET /enterprises/acme/installation": [
158
+ enterprise,
159
+ "enterprise_installation_success",
160
+ ],
161
+ "POST /app/installations/4242/access_tokens": [
162
+ enterprise,
163
+ "access_token_success",
164
+ ],
165
+ "GET /enterprises/acme/apps/installable_organizations": [
166
+ enterprise,
167
+ "installable_orgs_success",
168
+ ],
169
+ "GET /orgs/org-1/installation": [lookup, "org_installation_success"],
170
+ "GET /orgs/org-2/installation": [lookup, "org_installation_404"],
171
+ "POST /app/installations/7001/access_tokens": [
172
+ lookup,
173
+ "lookup_token_success",
174
+ ],
175
+ "GET /installation/repositories": [lookup, "repos_success"],
176
+ "GET /users/octocat": [lookup, "user_success"],
177
+ "GET /repos/org-1/api/collaborators/octocat/permission": [
178
+ lookup,
179
+ "permission_maintain",
180
+ ],
181
+ "GET /repos/org-1/web/collaborators/octocat/permission": [
182
+ lookup,
183
+ "permission_triage",
184
+ ],
185
+ };
186
+
187
+ describeOrSkip("GET /agents/:id/github-access (integration)", () => {
188
+ let prisma: PrismaClient;
189
+ let cookie: string;
190
+ let calls: string[];
191
+ let logs: string[];
192
+
193
+ beforeEach(async () => {
194
+ prisma = makePrisma();
195
+ await prisma.gitHubEnterpriseApp.deleteMany();
196
+ await prisma.agentWorkQueueSnapshot.deleteMany();
197
+ await prisma.agentPlugin.deleteMany();
198
+ await prisma.agentToken.deleteMany();
199
+ await prisma.agentCronJob.deleteMany();
200
+ await prisma.agentTool.deleteMany();
201
+ await prisma.agentEnv.deleteMany();
202
+ await prisma.agentMember.deleteMany();
203
+ await prisma.agent.deleteMany();
204
+ cookie = await makeSessionCookie();
205
+ calls = [];
206
+ logs = [];
207
+ });
208
+
209
+ afterEach(async () => {
210
+ await prisma.$disconnect();
211
+ });
212
+
213
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
214
+ const u = new URL(input.toString());
215
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
216
+ calls.push(key);
217
+ const hit = ROUTES[key];
218
+ if (!hit) throw new Error(`no route for ${key}`);
219
+ const e = hit[0][hit[1]];
220
+ return new Response(JSON.stringify(e?.body), {
221
+ status: e?.status,
222
+ headers: { "Content-Type": "application/json", ...(e?.headers ?? {}) },
223
+ });
224
+ }) as typeof fetch;
225
+
226
+ async function seedApps() {
227
+ const svc = new GitHubEnterpriseAppService(
228
+ prisma,
229
+ makeStrictTokenCrypto(ENC_KEY),
230
+ );
231
+ await svc.save({
232
+ role: "installer",
233
+ appId: "12345",
234
+ slug: "example-installer",
235
+ enterpriseSlug: "acme",
236
+ privateKey: PEM,
237
+ });
238
+ await svc.save({
239
+ role: "lookup",
240
+ appId: "555",
241
+ slug: "example-lookup",
242
+ enterpriseSlug: null,
243
+ privateKey: PEM,
244
+ });
245
+ return svc;
246
+ }
247
+
248
+ function build(appService: GitHubEnterpriseAppService) {
249
+ return createAdminApp({
250
+ ...makeDeps(prisma),
251
+ githubAccessPreview: createGithubAccessPreview({
252
+ appService,
253
+ fetchFn,
254
+ apiBase: "https://ghe.test",
255
+ now: () => NOW,
256
+ }),
257
+ });
258
+ }
259
+
260
+ const get = (app: ReturnType<typeof build>, id: string) =>
261
+ app.request(`/agents/${id}/github-access`, {
262
+ headers: { Cookie: `admin_session=${cookie}` },
263
+ });
264
+
265
+ const svcNoApps = () =>
266
+ new GitHubEnterpriseAppService(prisma, makeStrictTokenCrypto(ENC_KEY));
267
+
268
+ it("returns the resolver output per org, with no key material anywhere", async () => {
269
+ const agent = await prisma.agent.create({
270
+ data: { name: "A", githubUsername: "octocat" },
271
+ });
272
+ const app = build(await seedApps());
273
+ const spies = (["log", "info", "warn", "error"] as const).map((m) =>
274
+ spyOn(console, m).mockImplementation((...a) => {
275
+ logs.push(a.map(String).join(" "));
276
+ }),
277
+ );
278
+ try {
279
+ const res = await get(app, agent.id);
280
+ expect(res.status).toBe(200);
281
+ const text = await res.text();
282
+ const json = JSON.parse(text);
283
+ expect(json.status).toBe("ok");
284
+ expect(json.access.complete).toBe(false); // org-2 has no lookup App
285
+ expect(json.access.orgs).toEqual([
286
+ {
287
+ org: "org-1",
288
+ status: "ok",
289
+ repos: [
290
+ { fullName: "acme-eng/api", level: "maintain", canPush: true },
291
+ { fullName: "acme-eng/web", level: "triage", canPush: false },
292
+ ],
293
+ unresolved: 0,
294
+ },
295
+ {
296
+ org: "org-2",
297
+ status: "lookup_app_not_installed",
298
+ repos: [],
299
+ unresolved: 0,
300
+ },
301
+ ]);
302
+ for (const out of [text, ...logs]) {
303
+ expect(out).not.toContain(PEM_BODY);
304
+ expect(out).not.toContain("BEGIN");
305
+ expect(out).not.toMatch(/ghs_|"token"/);
306
+ }
307
+ } finally {
308
+ for (const s of spies) s.mockRestore();
309
+ }
310
+ });
311
+
312
+ it("unconfigured: 200 status and no GitHub call", async () => {
313
+ const agent = await prisma.agent.create({
314
+ data: { name: "A", githubUsername: "octocat" },
315
+ });
316
+ const res = await get(build(svcNoApps()), agent.id);
317
+ expect(res.status).toBe(200);
318
+ expect(await res.json()).toEqual({ status: "unconfigured" });
319
+ expect(calls).toEqual([]);
320
+ });
321
+
322
+ it("only one App configured is still unconfigured", async () => {
323
+ const agent = await prisma.agent.create({
324
+ data: { name: "A", githubUsername: "octocat" },
325
+ });
326
+ const svc = svcNoApps();
327
+ await svc.save({
328
+ role: "lookup",
329
+ appId: "555",
330
+ slug: "example-lookup",
331
+ enterpriseSlug: null,
332
+ privateKey: PEM,
333
+ });
334
+ const res = await get(build(svc), agent.id);
335
+ expect(await res.json()).toEqual({ status: "unconfigured" });
336
+ expect(calls).toEqual([]);
337
+ });
338
+
339
+ it("user_not_found when the user does not exist on GitHub", async () => {
340
+ const agent = await prisma.agent.create({
341
+ data: { name: "A", githubUsername: "octocat" },
342
+ });
343
+ const saved = ROUTES["GET /users/octocat"];
344
+ ROUTES["GET /users/octocat"] = [lookup, "user_nonexistent"];
345
+ try {
346
+ const res = await get(build(await seedApps()), agent.id);
347
+ expect(res.status).toBe(200);
348
+ const json = await res.json();
349
+ expect(json.status).toBe("user_not_found");
350
+ expect(json.access.orgs).toEqual([]);
351
+ expect(calls.some((c) => c.includes("/permission"))).toBe(false);
352
+ } finally {
353
+ ROUTES["GET /users/octocat"] = saved as [Cassette, string];
354
+ }
355
+ });
356
+
357
+ it("404 for an unknown agent and 422 for an unbound one", async () => {
358
+ const unbound = await prisma.agent.create({ data: { name: "U" } });
359
+ const app = build(await seedApps());
360
+ expect((await get(app, "no-such-agent")).status).toBe(404);
361
+ expect((await get(app, unbound.id)).status).toBe(422);
362
+ expect(calls).toEqual([]);
363
+ });
364
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * admin/src/github-access-preview.ts
3
+ * Result type and port for GET /agents/:id/github-access (GHE-2.4): a
4
+ * read-only preview of the repos an agent's bound GitHub user can reach.
5
+ * The implementation lives in github-enterprise-api.ts (the only module that
6
+ * may read the App keys); agents-api.ts only sees this port.
7
+ */
8
+
9
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
10
+
11
+ export type GithubAccessPreview =
12
+ /** The installer or lookup App is not configured; GitHub was not called. */
13
+ | { status: "unconfigured" }
14
+ /** `access` is the resolver output, unchanged. */
15
+ | { status: "ok" | "user_not_found"; access: UserRepoAccessResult };
16
+
17
+ export type GithubAccessPreviewFn = (
18
+ username: string,
19
+ ) => Promise<GithubAccessPreview>;