@app-vitals/agent-admin 1.125.0 → 1.126.1

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.
@@ -0,0 +1,591 @@
1
+ /**
2
+ * admin/src/agent-github-apps.ts
3
+ * AgentGitHubAppService — the GitHub Apps an agent uses (multi-github-apps 1.1).
4
+ *
5
+ * An agent may have several apps; list order is priority ascending (lowest
6
+ * wins when two apps are installed on the same owner), tie-broken by
7
+ * createdAt, numeric appId, then id so the order is fully deterministic.
8
+ *
9
+ * Keys are write-only: the private key and client secret are encrypted with
10
+ * the same TokenCrypto (AES-256-GCM via SHIPWRIGHT_ENCRYPTION_KEY) as
11
+ * AgentEnvService and never appear on a read shape, which carries
12
+ * hasPrivateKey / hasClientSecret flags instead. Only listCredentials()
13
+ * decrypts, for server-side/runtime use.
14
+ *
15
+ * backfillAgentGitHubAppsFromEnv() copies each agent's legacy GH_APP_* env
16
+ * rows into this table. It runs at admin boot (after migrations) rather than
17
+ * in the migration SQL, because consumers' additive-migration guards reject
18
+ * INSERT statements. It is idempotent and leaves the AgentEnv rows untouched.
19
+ */
20
+
21
+ import type { Prisma, PrismaClient } from "../prisma/client/client.ts";
22
+ import { type Clock, SystemClock } from "./clock.ts";
23
+ import {
24
+ ConflictError,
25
+ NotFoundError,
26
+ UnprocessableEntityError,
27
+ } from "./errors.ts";
28
+ import { CLIENT_ID_RE, SLUG_RE } from "./installation-ports.ts";
29
+ import type { TokenCrypto } from "./token-crypto.ts";
30
+
31
+ // ─── Types ────────────────────────────────────────────────────────────────────
32
+
33
+ /** Read shape: metadata plus key flags. Never carries key material. */
34
+ export interface AgentGitHubAppView {
35
+ id: string;
36
+ agentId: string;
37
+ appId: string;
38
+ slug: string | null;
39
+ clientId: string | null;
40
+ installationId: string | null;
41
+ priority: number;
42
+ hasPrivateKey: boolean;
43
+ hasClientSecret: boolean;
44
+ createdAt: Date;
45
+ updatedAt: Date;
46
+ }
47
+
48
+ /** Decrypted credentials, for runtime/internal use only. Never log. */
49
+ export interface AgentGitHubAppCredentials {
50
+ id: string;
51
+ appId: string;
52
+ slug: string | null;
53
+ clientId: string | null;
54
+ installationId: string | null;
55
+ priority: number;
56
+ privateKey: string;
57
+ clientSecret: string | null;
58
+ }
59
+
60
+ export interface CreateAgentGitHubAppInput {
61
+ appId: string;
62
+ slug?: string | null;
63
+ clientId?: string | null;
64
+ /** PEM; encrypted before it is stored. */
65
+ privateKey: string;
66
+ /** Encrypted before it is stored. */
67
+ clientSecret?: string | null;
68
+ installationId?: string | null;
69
+ /** Defaults to one past the agent's current highest priority (0 when none). */
70
+ priority?: number;
71
+ }
72
+
73
+ /**
74
+ * Partial update. Omitted fields are unchanged; null clears a nullable field.
75
+ * privateKey/clientSecret replace the stored secret (write-only rotation).
76
+ */
77
+ export interface UpdateAgentGitHubAppInput {
78
+ slug?: string | null;
79
+ clientId?: string | null;
80
+ privateKey?: string;
81
+ clientSecret?: string | null;
82
+ installationId?: string | null;
83
+ priority?: number;
84
+ }
85
+
86
+ interface AgentGitHubAppRow {
87
+ id: string;
88
+ agentId: string;
89
+ appId: string;
90
+ slug: string | null;
91
+ clientId: string | null;
92
+ privateKeyEncrypted: string;
93
+ clientSecretEncrypted: string | null;
94
+ installationId: string | null;
95
+ priority: number;
96
+ createdAt: Date;
97
+ updatedAt: Date;
98
+ }
99
+
100
+ // ─── Pure helpers ─────────────────────────────────────────────────────────────
101
+
102
+ const POSITIVE_INT_RE = /^[1-9][0-9]*$/;
103
+
104
+ interface Sortable {
105
+ id: string;
106
+ appId: string;
107
+ priority: number;
108
+ createdAt: Date;
109
+ }
110
+
111
+ function compareAppIds(a: string, b: string): number {
112
+ const na = Number(a);
113
+ const nb = Number(b);
114
+ if (Number.isFinite(na) && Number.isFinite(nb) && na !== nb) return na - nb;
115
+ return a < b ? -1 : a > b ? 1 : 0;
116
+ }
117
+
118
+ /**
119
+ * Priority order (lowest first), tie-broken by createdAt, numeric appId, then
120
+ * id. Returns a new array; the input is not mutated.
121
+ */
122
+ export function sortAgentGitHubApps<T extends Sortable>(
123
+ apps: readonly T[],
124
+ ): T[] {
125
+ return [...apps].sort(
126
+ (a, b) =>
127
+ a.priority - b.priority ||
128
+ a.createdAt.getTime() - b.createdAt.getTime() ||
129
+ compareAppIds(a.appId, b.appId) ||
130
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
131
+ );
132
+ }
133
+
134
+ /** Serializer: metadata plus key flags. Never includes key material. */
135
+ export function toAgentGitHubAppView(
136
+ row: AgentGitHubAppRow,
137
+ ): AgentGitHubAppView {
138
+ return {
139
+ id: row.id,
140
+ agentId: row.agentId,
141
+ appId: row.appId,
142
+ slug: row.slug,
143
+ clientId: row.clientId,
144
+ installationId: row.installationId,
145
+ priority: row.priority,
146
+ hasPrivateKey: row.privateKeyEncrypted.length > 0,
147
+ hasClientSecret: (row.clientSecretEncrypted ?? "").length > 0,
148
+ createdAt: row.createdAt,
149
+ updatedAt: row.updatedAt,
150
+ };
151
+ }
152
+
153
+ /** The legacy env keys the backfill reads. */
154
+ export const GH_APP_ENV_KEYS = [
155
+ "GH_APP_ID",
156
+ "GH_APP_SLUG",
157
+ "GH_APP_CLIENT_ID",
158
+ "GH_APP_CLIENT_SECRET",
159
+ "GH_APP_PRIVATE_KEY",
160
+ "GH_APP_INSTALLATION_ID",
161
+ ] as const;
162
+
163
+ export interface GitHubAppBackfillData {
164
+ appId: string;
165
+ slug: string | null;
166
+ clientId: string | null;
167
+ privateKeyEncrypted: string;
168
+ clientSecretEncrypted: string | null;
169
+ installationId: string | null;
170
+ priority: number;
171
+ }
172
+
173
+ export type GitHubAppBackfillPlan =
174
+ | { kind: "none" }
175
+ | { kind: "skip"; appId: string | null; reason: string }
176
+ | { kind: "create"; data: GitHubAppBackfillData; warnings: string[] };
177
+
178
+ /**
179
+ * Decide what one agent's GH_APP_* env rows (still encrypted, as stored in
180
+ * AgentEnv) turn into. Per field:
181
+ * - GH_APP_ID: required, a positive integer; otherwise skip.
182
+ * - GH_APP_PRIVATE_KEY: required (a row without a key cannot mint tokens);
183
+ * otherwise skip. Copied as ciphertext, never decrypted.
184
+ * - GH_APP_CLIENT_SECRET: optional; copied as ciphertext, never decrypted.
185
+ * - GH_APP_SLUG / GH_APP_CLIENT_ID / GH_APP_INSTALLATION_ID: optional; a
186
+ * malformed value is dropped (null) with a warning, not a skip.
187
+ * The ciphertext copy is valid because AgentEnv and AgentGitHubApp share the
188
+ * same TokenCrypto. Only the non-secret fields are decrypted.
189
+ */
190
+ export function planGitHubAppBackfill(
191
+ rows: ReadonlyArray<{ key: string; value: string }>,
192
+ crypto: TokenCrypto,
193
+ ): GitHubAppBackfillPlan {
194
+ const byKey = new Map(rows.map((r) => [r.key, r.value]));
195
+ const plain = (key: string): string | undefined => {
196
+ const v = byKey.get(key);
197
+ if (v === undefined) return undefined;
198
+ const t = crypto.decrypt(v).trim();
199
+ return t === "" ? undefined : t;
200
+ };
201
+
202
+ if (!byKey.has("GH_APP_ID")) return { kind: "none" };
203
+ const appId = plain("GH_APP_ID");
204
+ if (!appId || !POSITIVE_INT_RE.test(appId)) {
205
+ return {
206
+ kind: "skip",
207
+ appId: null,
208
+ reason: "GH_APP_ID is not a positive integer",
209
+ };
210
+ }
211
+
212
+ const keyCipher = byKey.get("GH_APP_PRIVATE_KEY");
213
+ // Never decrypted: only an absent or empty stored value counts as missing.
214
+ if (keyCipher === undefined || keyCipher.trim() === "") {
215
+ return { kind: "skip", appId, reason: "GH_APP_PRIVATE_KEY missing" };
216
+ }
217
+
218
+ const warnings: string[] = [];
219
+ const optional = (
220
+ key: string,
221
+ re: RegExp,
222
+ warning: string,
223
+ ): string | null => {
224
+ const v = plain(key);
225
+ if (v === undefined) return null;
226
+ if (re.test(v)) return v;
227
+ warnings.push(warning);
228
+ return null;
229
+ };
230
+ const slug = optional(
231
+ "GH_APP_SLUG",
232
+ SLUG_RE,
233
+ "GH_APP_SLUG malformed, dropped",
234
+ );
235
+ const clientId = optional(
236
+ "GH_APP_CLIENT_ID",
237
+ CLIENT_ID_RE,
238
+ "GH_APP_CLIENT_ID malformed, dropped",
239
+ );
240
+ const installationId = optional(
241
+ "GH_APP_INSTALLATION_ID",
242
+ POSITIVE_INT_RE,
243
+ "GH_APP_INSTALLATION_ID not a positive integer, dropped",
244
+ );
245
+ const secretCipher = byKey.get("GH_APP_CLIENT_SECRET");
246
+
247
+ return {
248
+ kind: "create",
249
+ data: {
250
+ appId,
251
+ slug,
252
+ clientId,
253
+ privateKeyEncrypted: keyCipher,
254
+ clientSecretEncrypted:
255
+ secretCipher !== undefined && secretCipher !== "" ? secretCipher : null,
256
+ installationId,
257
+ priority: 0,
258
+ },
259
+ warnings,
260
+ };
261
+ }
262
+
263
+ // ─── Validation ───────────────────────────────────────────────────────────────
264
+
265
+ function assertPositiveInt(field: string, value: string): void {
266
+ if (!POSITIVE_INT_RE.test(value)) {
267
+ throw new UnprocessableEntityError(`${field} must be a positive integer`);
268
+ }
269
+ }
270
+
271
+ function normalizeOptional(
272
+ field: string,
273
+ value: string | null | undefined,
274
+ re: RegExp,
275
+ message: string,
276
+ ): string | null | undefined {
277
+ if (value === undefined || value === null) return value;
278
+ const v = value.trim();
279
+ if (v === "") return null;
280
+ if (!re.test(v)) throw new UnprocessableEntityError(`${field} ${message}`);
281
+ return v;
282
+ }
283
+
284
+ function assertPriority(priority: number): void {
285
+ if (!Number.isInteger(priority) || priority < 0) {
286
+ throw new UnprocessableEntityError(
287
+ "priority must be a non-negative integer",
288
+ );
289
+ }
290
+ }
291
+
292
+ function isUniqueViolation(err: unknown): boolean {
293
+ return (
294
+ typeof err === "object" &&
295
+ err !== null &&
296
+ (err as { code?: unknown }).code === "P2002"
297
+ );
298
+ }
299
+
300
+ // ─── Service ──────────────────────────────────────────────────────────────────
301
+
302
+ export class AgentGitHubAppService {
303
+ constructor(
304
+ private prisma: PrismaClient,
305
+ private crypto: TokenCrypto,
306
+ private clock: Clock = SystemClock(),
307
+ ) {}
308
+
309
+ private async assertAgent(agentId: string): Promise<void> {
310
+ const agent = await this.prisma.agent.findUnique({
311
+ where: { id: agentId },
312
+ select: { id: true },
313
+ });
314
+ if (!agent) throw new UnprocessableEntityError("agent not found");
315
+ }
316
+
317
+ /** Create an app for an agent. 409 when the agent already has this appId. */
318
+ async create(
319
+ agentId: string,
320
+ input: CreateAgentGitHubAppInput,
321
+ ): Promise<AgentGitHubAppView> {
322
+ const appId = input.appId?.trim() ?? "";
323
+ assertPositiveInt("appId", appId);
324
+ if (!input.privateKey?.trim()) {
325
+ throw new UnprocessableEntityError("privateKey is required");
326
+ }
327
+ const slug = normalizeOptional("slug", input.slug, SLUG_RE, "is malformed");
328
+ const clientId = normalizeOptional(
329
+ "clientId",
330
+ input.clientId,
331
+ CLIENT_ID_RE,
332
+ "is malformed",
333
+ );
334
+ const installationId = normalizeOptional(
335
+ "installationId",
336
+ input.installationId,
337
+ POSITIVE_INT_RE,
338
+ "must be a positive integer",
339
+ );
340
+ if (input.priority !== undefined) assertPriority(input.priority);
341
+ await this.assertAgent(agentId);
342
+
343
+ let priority = input.priority;
344
+ if (priority === undefined) {
345
+ const top = await this.prisma.agentGitHubApp.aggregate({
346
+ where: { agentId },
347
+ _max: { priority: true },
348
+ });
349
+ priority = top._max.priority === null ? 0 : top._max.priority + 1;
350
+ }
351
+
352
+ const now = this.clock.now();
353
+ try {
354
+ const row = await this.prisma.agentGitHubApp.create({
355
+ data: {
356
+ agentId,
357
+ appId,
358
+ slug: slug ?? null,
359
+ clientId: clientId ?? null,
360
+ privateKeyEncrypted: this.crypto.encrypt(input.privateKey),
361
+ clientSecretEncrypted: input.clientSecret
362
+ ? this.crypto.encrypt(input.clientSecret)
363
+ : null,
364
+ installationId: installationId ?? null,
365
+ priority,
366
+ createdAt: now,
367
+ updatedAt: now,
368
+ },
369
+ });
370
+ return toAgentGitHubAppView(row);
371
+ } catch (err) {
372
+ if (isUniqueViolation(err)) {
373
+ throw new ConflictError(
374
+ `agent already has GitHub App ${appId}; update it instead`,
375
+ );
376
+ }
377
+ throw err;
378
+ }
379
+ }
380
+
381
+ /** All of the agent's apps in priority order. */
382
+ async list(agentId: string): Promise<AgentGitHubAppView[]> {
383
+ const rows = await this.prisma.agentGitHubApp.findMany({
384
+ where: { agentId },
385
+ });
386
+ return sortAgentGitHubApps(rows).map(toAgentGitHubAppView);
387
+ }
388
+
389
+ /** One app, or null when it does not exist or belongs to another agent. */
390
+ async get(agentId: string, id: string): Promise<AgentGitHubAppView | null> {
391
+ const row = await this.prisma.agentGitHubApp.findFirst({
392
+ where: { id, agentId },
393
+ });
394
+ return row ? toAgentGitHubAppView(row) : null;
395
+ }
396
+
397
+ /** Partial update. 404 when the app does not exist for this agent. */
398
+ async update(
399
+ agentId: string,
400
+ id: string,
401
+ input: UpdateAgentGitHubAppInput,
402
+ ): Promise<AgentGitHubAppView> {
403
+ const slug = normalizeOptional("slug", input.slug, SLUG_RE, "is malformed");
404
+ const clientId = normalizeOptional(
405
+ "clientId",
406
+ input.clientId,
407
+ CLIENT_ID_RE,
408
+ "is malformed",
409
+ );
410
+ const installationId = normalizeOptional(
411
+ "installationId",
412
+ input.installationId,
413
+ POSITIVE_INT_RE,
414
+ "must be a positive integer",
415
+ );
416
+ if (input.priority !== undefined) assertPriority(input.priority);
417
+ if (input.privateKey !== undefined && !input.privateKey.trim()) {
418
+ throw new UnprocessableEntityError("privateKey must not be empty");
419
+ }
420
+
421
+ const data: Prisma.AgentGitHubAppUpdateManyMutationInput = {
422
+ updatedAt: this.clock.now(),
423
+ };
424
+ if (slug !== undefined) data.slug = slug;
425
+ if (clientId !== undefined) data.clientId = clientId;
426
+ if (installationId !== undefined) data.installationId = installationId;
427
+ if (input.priority !== undefined) data.priority = input.priority;
428
+ if (input.privateKey !== undefined) {
429
+ data.privateKeyEncrypted = this.crypto.encrypt(input.privateKey);
430
+ }
431
+ if (input.clientSecret !== undefined) {
432
+ data.clientSecretEncrypted = input.clientSecret
433
+ ? this.crypto.encrypt(input.clientSecret)
434
+ : null;
435
+ }
436
+
437
+ const result = await this.prisma.agentGitHubApp.updateMany({
438
+ where: { id, agentId },
439
+ data,
440
+ });
441
+ if (result.count === 0) throw new NotFoundError("GitHub App not found");
442
+ const row = await this.prisma.agentGitHubApp.findFirst({
443
+ where: { id, agentId },
444
+ });
445
+ if (!row) throw new NotFoundError("GitHub App not found");
446
+ return toAgentGitHubAppView(row);
447
+ }
448
+
449
+ /** Delete one app. Returns false when it did not exist for this agent. */
450
+ async delete(agentId: string, id: string): Promise<boolean> {
451
+ const result = await this.prisma.agentGitHubApp.deleteMany({
452
+ where: { id, agentId },
453
+ });
454
+ return result.count > 0;
455
+ }
456
+
457
+ /**
458
+ * Decrypted credentials for every app of the agent, in priority order.
459
+ * Internal/runtime use only; never expose over a read API or log.
460
+ */
461
+ async listCredentials(agentId: string): Promise<AgentGitHubAppCredentials[]> {
462
+ const rows = await this.prisma.agentGitHubApp.findMany({
463
+ where: { agentId },
464
+ });
465
+ return sortAgentGitHubApps(rows).map((row) => ({
466
+ id: row.id,
467
+ appId: row.appId,
468
+ slug: row.slug,
469
+ clientId: row.clientId,
470
+ installationId: row.installationId,
471
+ priority: row.priority,
472
+ privateKey: this.crypto.decrypt(row.privateKeyEncrypted),
473
+ clientSecret:
474
+ row.clientSecretEncrypted === null
475
+ ? null
476
+ : this.crypto.decrypt(row.clientSecretEncrypted),
477
+ }));
478
+ }
479
+ }
480
+
481
+ // ─── Backfill ─────────────────────────────────────────────────────────────────
482
+
483
+ export interface GitHubAppBackfillResult {
484
+ created: Array<{ agentId: string; appId: string; warnings: string[] }>;
485
+ alreadyPresent: Array<{ agentId: string; appId: string }>;
486
+ skipped: Array<{ agentId: string; appId: string | null; reason: string }>;
487
+ }
488
+
489
+ /**
490
+ * Copy each agent's enabled GH_APP_* AgentEnv rows into one AgentGitHubApp row
491
+ * (priority 0). Idempotent: an agent that already has a row for that appId is
492
+ * reported as alreadyPresent (a concurrent replica winning the race too); an
493
+ * agent that already has rows for other apps is skipped, since the table is
494
+ * then authoritative for it. Secrets are copied as ciphertext. AgentEnv rows
495
+ * are never modified. Skips are logged; per-agent errors are reported as
496
+ * skips and never abort the run.
497
+ */
498
+ export async function backfillAgentGitHubAppsFromEnv(deps: {
499
+ prisma: PrismaClient;
500
+ crypto: TokenCrypto;
501
+ logger?: Pick<Console, "log" | "warn">;
502
+ }): Promise<GitHubAppBackfillResult> {
503
+ const { prisma, crypto, logger = console } = deps;
504
+ const result: GitHubAppBackfillResult = {
505
+ created: [],
506
+ alreadyPresent: [],
507
+ skipped: [],
508
+ };
509
+
510
+ const rows = await prisma.agentEnv.findMany({
511
+ where: { enabled: true, key: { in: [...GH_APP_ENV_KEYS] } },
512
+ select: { agentId: true, key: true, value: true },
513
+ });
514
+ const byAgent = new Map<string, Array<{ key: string; value: string }>>();
515
+ for (const row of rows) {
516
+ const list = byAgent.get(row.agentId) ?? [];
517
+ list.push({ key: row.key, value: row.value });
518
+ byAgent.set(row.agentId, list);
519
+ }
520
+
521
+ for (const [agentId, agentRows] of [...byAgent].sort(([a], [b]) =>
522
+ a < b ? -1 : a > b ? 1 : 0,
523
+ )) {
524
+ let plan: GitHubAppBackfillPlan;
525
+ try {
526
+ plan = planGitHubAppBackfill(agentRows, crypto);
527
+ } catch (err) {
528
+ plan = {
529
+ kind: "skip",
530
+ appId: null,
531
+ reason: `could not read GH_APP_* env: ${err instanceof Error ? err.message : String(err)}`,
532
+ };
533
+ }
534
+ if (plan.kind === "none") continue;
535
+ if (plan.kind === "skip") {
536
+ result.skipped.push({ agentId, appId: plan.appId, reason: plan.reason });
537
+ continue;
538
+ }
539
+
540
+ const { data, warnings } = plan;
541
+ try {
542
+ const existing = await prisma.agentGitHubApp.findMany({
543
+ where: { agentId },
544
+ select: { appId: true },
545
+ });
546
+ if (existing.some((e) => e.appId === data.appId)) {
547
+ result.alreadyPresent.push({ agentId, appId: data.appId });
548
+ continue;
549
+ }
550
+ if (existing.length > 0) {
551
+ result.skipped.push({
552
+ agentId,
553
+ appId: data.appId,
554
+ reason: "agent already has other GitHub App rows",
555
+ });
556
+ continue;
557
+ }
558
+ await prisma.agentGitHubApp.create({ data: { agentId, ...data } });
559
+ result.created.push({ agentId, appId: data.appId, warnings });
560
+ } catch (err) {
561
+ if (isUniqueViolation(err)) {
562
+ result.alreadyPresent.push({ agentId, appId: data.appId });
563
+ } else {
564
+ // Code/name only: a Prisma error message can echo the row's arguments.
565
+ const code = (err as { code?: unknown }).code;
566
+ result.skipped.push({
567
+ agentId,
568
+ appId: data.appId,
569
+ reason: `insert failed: ${typeof code === "string" ? code : err instanceof Error ? err.name : "unknown error"}`,
570
+ });
571
+ }
572
+ }
573
+ }
574
+
575
+ for (const s of result.skipped) {
576
+ logger.warn(
577
+ `[agent-github-apps] backfill skipped agent ${s.agentId}${s.appId ? ` (app ${s.appId})` : ""}: ${s.reason}`,
578
+ );
579
+ }
580
+ for (const c of result.created) {
581
+ if (c.warnings.length > 0) {
582
+ logger.warn(
583
+ `[agent-github-apps] backfill created app ${c.appId} for agent ${c.agentId} with: ${c.warnings.join("; ")}`,
584
+ );
585
+ }
586
+ }
587
+ logger.log(
588
+ `[agent-github-apps] backfill done: ${result.created.length} created, ${result.alreadyPresent.length} already present, ${result.skipped.length} skipped`,
589
+ );
590
+ return result;
591
+ }