@app-vitals/agent-admin 1.23.0 → 1.24.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.23.0",
3
+ "version": "1.24.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.135.0",
45
- "@app-vitals/agent-lib": "1.23.0",
45
+ "@app-vitals/agent-lib": "1.24.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -7,7 +7,10 @@
7
7
  * never renders a key (the status API only reports `keySet`).
8
8
  */
9
9
 
10
- import { GHE_WARNINGS, type GheWarningCode } from "./github-enterprise-warnings.ts";
10
+ import {
11
+ GHE_WARNINGS,
12
+ type GheWarningCode,
13
+ } from "./github-enterprise-warnings.ts";
11
14
  import { renderAdminPage } from "./admin-ui-layout.ts";
12
15
  import { escapeHtml, renderAdminToolbar } from "./admin-ui-styles.ts";
13
16
 
@@ -79,14 +82,39 @@ function validationBadge(status: string | null): string {
79
82
  const ROLE_COPY = {
80
83
  installer: {
81
84
  title: "Installer app",
82
- help: "Installs agents' GitHub Apps on the enterprise's organizations. Needs the enterprise_organization_installations (write) permission.",
85
+ descriptor:
86
+ "Auto-installs agents' GitHub Apps on your enterprise's organizations.",
87
+ steps: [
88
+ "In GitHub, open your enterprise's Settings → GitHub Apps → New GitHub App (an enterprise-owned App).",
89
+ "Under Enterprise permissions, grant both <code>enterprise_organization_installations</code> and <code>enterprise_organization_installation_repositories</code> at <strong>Read and write</strong>.",
90
+ "Create the App. The App ID is on the App's settings page; the App slug is the last part of its public URL (<code>github.com/apps/&lt;slug&gt;</code>).",
91
+ "The enterprise slug is the last part of your enterprise's URL (<code>github.com/enterprises/&lt;slug&gt;</code>).",
92
+ "Under Private keys, choose Generate a private key and paste the downloaded PEM below.",
93
+ ],
83
94
  },
84
95
  lookup: {
85
96
  title: "Lookup app",
86
- help: "Read-only App used to see which organizations the platform can look up. Needs the metadata (read) permission. It must be installed on all repositories of each organization, not selected repositories only.",
97
+ descriptor:
98
+ "Read-only App that gives the platform repository access lookups. Optional.",
99
+ steps: [
100
+ "In GitHub, open your organization's Settings &rarr; Developer settings &rarr; GitHub Apps &rarr; New GitHub App.",
101
+ "Grant Repository <code>Metadata</code> at <strong>Read</strong> and Organization <code>Members</code> at <strong>Read</strong>.",
102
+ "Create the App. The App ID is on the App's settings page; the App slug is the last part of its public URL (<code>github.com/apps/&lt;slug&gt;</code>).",
103
+ "It must be installed on all repositories of each organization, not selected repositories only.",
104
+ "Under Private keys, choose Generate a private key and paste the downloaded PEM below.",
105
+ ],
87
106
  },
88
107
  } as const;
89
108
 
109
+ const IGNORED_OPTIONS =
110
+ "Ignore these options: callback URL, request user authorization, expire user authorization tokens, device flow, and webhook (uncheck Active).";
111
+
112
+ function guidance(role: "installer" | "lookup"): string {
113
+ const copy = ROLE_COPY[role];
114
+ return `<ol class="help-text gh-ent-steps" style="font-size:12px;margin:8px 0;padding-left:20px">${copy.steps.map((x) => `<li>${x}</li>`).join("")}</ol>
115
+ <p class="help-text gh-ent-ignore" style="font-size:12px;margin:8px 0">${IGNORED_OPTIONS}</p>`;
116
+ }
117
+
90
118
  function statusLine(app: GheApp): string {
91
119
  const validated = app.lastValidatedAt
92
120
  ? ` &middot; ${escapeHtml(formatTime(app.lastValidatedAt))}`
@@ -110,9 +138,14 @@ function postButton(
110
138
  return `<form method="POST" action="${action}" style="display:inline;margin:0"><button type="submit" class="btn ${cls}" style="font-size:12px;padding:4px 10px">${label}</button></form>`;
111
139
  }
112
140
 
113
- function warningsBlock(role: "installer" | "lookup", codes: string[] | undefined): string {
141
+ function warningsBlock(
142
+ role: "installer" | "lookup",
143
+ codes: string[] | undefined,
144
+ ): string {
114
145
  return (codes ?? [])
115
- .filter((c): c is GheWarningCode => c in GHE_WARNINGS && c.startsWith(`${role}_`))
146
+ .filter(
147
+ (c): c is GheWarningCode => c in GHE_WARNINGS && c.startsWith(`${role}_`),
148
+ )
116
149
  .map(
117
150
  (c) =>
118
151
  `<div class="help-text gh-ent-warning" style="font-size:12px;margin-top:4px">Warning: ${escapeHtml(GHE_WARNINGS[c])}</div>`,
@@ -138,13 +171,15 @@ function appCard(
138
171
  : "";
139
172
  return `<div class="card">
140
173
  <div class="card-title">${copy.title}</div>
141
- <p class="help-text" style="font-size:12px">${copy.help}</p>
174
+ <p class="help-text" style="font-size:12px">${copy.descriptor}</p>
175
+ ${guidance(role)}
142
176
  ${summary}
143
- <form method="POST" action="${action}" style="display:grid;gap:8px;max-width:480px">
177
+ <form method="POST" action="${action}" enctype="multipart/form-data" style="display:grid;gap:8px;max-width:480px">
144
178
  <label>App ID <input name="appId" class="form-input" required inputmode="numeric" pattern="[0-9]+" /></label>
145
179
  <label>App slug <input name="slug" class="form-input" required /></label>
146
180
  ${enterprise}
147
- <label>Private key (PEM) <textarea name="privateKey" class="form-input" rows="4" required autocomplete="off" spellcheck="false" placeholder="Paste the private key. It is stored encrypted and never shown again."></textarea></label>
181
+ <label>Private key (PEM) <textarea name="privateKey" class="form-input" rows="4" autocomplete="off" spellcheck="false" placeholder="Paste the private key. It is stored encrypted and never shown again."></textarea></label>
182
+ <label>Or upload the .pem file <input type="file" name="privateKeyFile" accept=".pem,application/x-pem-file" class="form-input" /></label>
148
183
  <div><button type="submit" class="btn btn-primary">${app ? "Replace credentials" : "Save credentials"}</button></div>
149
184
  </form>
150
185
  </div>`;
@@ -221,10 +256,9 @@ export function renderGithubEnterpriseSettingsPage(
221
256
  const notice = opts.notice
222
257
  ? `<div class="alert alert-success">${escapeHtml(opts.notice)}</div>`
223
258
  : "";
224
- const emptyState = status.configured
225
- ? ""
226
- : `<div class="card"><div class="card-title">Not configured</div>
227
- <p>This feature is optional. Without it, agents are provisioned exactly as before. Configure an installer app to install agents' GitHub Apps on your enterprise's organizations from here, and a lookup app to see which organizations are reachable. Paste the credentials of Apps you created in GitHub below.</p>
259
+ const intro = `<div class="card">
260
+ <p>Configure an installer app to auto-install agent apps on your enterprise's organizations, and a lookup app for repository access. Both are optional.</p>
261
+ <p class="help-text gh-ent-required" style="margin-top:8px"><strong>A GitHub Enterprise Cloud enterprise is required.</strong> These Apps are created in and scoped to an enterprise.</p>
228
262
  </div>`;
229
263
 
230
264
  return renderAdminPage({
@@ -232,7 +266,7 @@ export function renderGithubEnterpriseSettingsPage(
232
266
  body: `${renderAdminToolbar(opts.userEmail, BASE)}
233
267
  <div class="vos-page">
234
268
  <div class="page-header"><h1 class="page-title">GitHub Enterprise apps</h1></div>
235
- ${error}${notice}${emptyState}
269
+ ${error}${notice}${intro}
236
270
  ${appCard("installer", status.installer, opts.warnings)}
237
271
  ${appCard("lookup", status.lookup, opts.warnings)}
238
272
  ${orgsCard(opts)}
@@ -48,10 +48,45 @@ describe("renderGithubEnterpriseSettingsPage", () => {
48
48
  );
49
49
  expect(html).toContain('name="enterpriseSlug"');
50
50
  expect(html).toContain('name="privateKey"');
51
+ expect(html).toContain('name="privateKeyFile"');
52
+ expect(html).toContain('enctype="multipart/form-data"');
51
53
  expect(html).not.toContain("/validate");
52
54
  expect(html).not.toContain("Organizations</div>");
53
55
  });
54
56
 
57
+ test("intro and enterprise-required notice render; old wording is gone", () => {
58
+ for (const status of [
59
+ empty,
60
+ { configured: true, installer: app(), lookup: null },
61
+ ]) {
62
+ const html = renderGithubEnterpriseSettingsPage({ ...base, status });
63
+ expect(html).toContain("auto-install agent apps");
64
+ expect(html).toContain("lookup app for repository access");
65
+ expect(html).toContain("GitHub Enterprise Cloud enterprise is required");
66
+ expect(html).not.toContain("exactly as before");
67
+ }
68
+ });
69
+
70
+ test("each card lists permissions, field locations and options to ignore", () => {
71
+ const html = renderGithubEnterpriseSettingsPage({ ...base, status: empty });
72
+ expect(html.match(/gh-ent-steps/g)?.length).toBe(2);
73
+ expect(html.match(/gh-ent-ignore/g)?.length).toBe(2);
74
+ expect(html).toContain("enterprise_organization_installations");
75
+ expect(html).toContain("Read and write");
76
+ expect(html).toContain("<code>Metadata</code>");
77
+ expect(html).toContain("<code>Members</code>");
78
+ expect(html).toContain("github.com/enterprises/");
79
+ expect(html).toContain("Generate a private key");
80
+ for (const opt of [
81
+ "callback URL",
82
+ "request user authorization",
83
+ "device flow",
84
+ "webhook",
85
+ ]) {
86
+ expect(html).toContain(opt);
87
+ }
88
+ });
89
+
55
90
  test("only the installer form asks for an enterprise slug", () => {
56
91
  const html = renderGithubEnterpriseSettingsPage({ ...base, status: empty });
57
92
  expect(html.match(/name="enterpriseSlug"/g)?.length).toBe(1);
@@ -106,7 +141,11 @@ describe("renderGithubEnterpriseSettingsPage", () => {
106
141
  test("warnings render on the matching card only, as non-error notes", () => {
107
142
  const html = renderGithubEnterpriseSettingsPage({
108
143
  ...base,
109
- status: { configured: true, installer: app(), lookup: app({ role: "lookup", enterpriseSlug: null }) },
144
+ status: {
145
+ configured: true,
146
+ installer: app(),
147
+ lookup: app({ role: "lookup", enterpriseSlug: null }),
148
+ },
110
149
  warnings: ["installer_repositories_write"],
111
150
  });
112
151
  expect(html).toContain("enterprise_organization_installation_repositories");
@@ -158,6 +158,79 @@ describe("GET /admin/settings/github-enterprise", () => {
158
158
  expect(html).toContain("optional");
159
159
  expect(html).toContain("Installer app");
160
160
  });
161
+
162
+ it("renders setup guidance on both cards and the enterprise notice", async () => {
163
+ const { app } = setup();
164
+ const html = await (await app.request(BASE)).text();
165
+ expect(html).toContain("GitHub Enterprise Cloud enterprise is required");
166
+ expect(html).not.toContain("exactly as before");
167
+ expect(html.match(/gh-ent-steps/g)?.length).toBe(2);
168
+ expect(html.match(/gh-ent-ignore/g)?.length).toBe(2);
169
+ });
170
+ });
171
+
172
+ const upload = (fields: Record<string, string>, file?: File) => {
173
+ const body = new FormData();
174
+ for (const [k, v] of Object.entries(fields)) body.set(k, v);
175
+ if (file) body.set("privateKeyFile", file);
176
+ return { method: "POST", body };
177
+ };
178
+
179
+ describe("private key upload", () => {
180
+ it("stores the same key as the paste path and never renders it", async () => {
181
+ const pasted = setup();
182
+ await pasted.app.request(
183
+ `${BASE}/apps/lookup`,
184
+ form({ appId: "42", slug: "acme-lookup", privateKey: PEM }),
185
+ );
186
+ const uploaded = setup();
187
+ const res = await uploaded.app.request(
188
+ `${BASE}/apps/lookup`,
189
+ upload(
190
+ { appId: "42", slug: "acme-lookup" },
191
+ new File([PEM], "key.pem", { type: "application/x-pem-file" }),
192
+ ),
193
+ );
194
+ expect(res.status).toBe(302);
195
+ expect(await uploaded.appService.get("lookup")).toEqual(
196
+ await pasted.appService.get("lookup"),
197
+ );
198
+ expect(await uploaded.appService.getPrivateKey("lookup")).toBe(
199
+ await pasted.appService.getPrivateKey("lookup"),
200
+ );
201
+ const html = await (await uploaded.app.request(BASE)).text();
202
+ expect(html).not.toContain("PRIVATE KEY");
203
+ });
204
+
205
+ it("rejects a non-PEM file and stores nothing", async () => {
206
+ const { app, appService } = setup();
207
+ const res = await app.request(
208
+ `${BASE}/apps/lookup`,
209
+ upload(
210
+ { appId: "42", slug: "acme-lookup" },
211
+ new File(["not-a-pem-SECRET"], "key.pem"),
212
+ ),
213
+ );
214
+ expect(res.status).toBe(400);
215
+ const html = await res.text();
216
+ expect(html).toContain("not a PEM private key");
217
+ expect(html).not.toContain("not-a-pem-SECRET");
218
+ expect(await appService.get("lookup")).toBeNull();
219
+ });
220
+
221
+ it("rejects an oversized file and stores nothing", async () => {
222
+ const { app, appService } = setup();
223
+ const res = await app.request(
224
+ `${BASE}/apps/lookup`,
225
+ upload(
226
+ { appId: "42", slug: "acme-lookup" },
227
+ new File([PEM + "A".repeat(20 * 1024)], "key.pem"),
228
+ ),
229
+ );
230
+ expect(res.status).toBe(400);
231
+ expect(await res.text()).toContain("too large");
232
+ expect(await appService.get("lookup")).toBeNull();
233
+ });
161
234
  });
162
235
 
163
236
  describe("form posts", () => {
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { Context, Hono, MiddlewareHandler } from "hono";
11
+ import { readPrivateKeyField } from "./github-enterprise-pem-upload.ts";
11
12
  import { warningCodeFor } from "./github-enterprise-warnings.ts";
12
13
  import type { AdminUIEnv } from "./admin-ui.ts";
13
14
  import {
@@ -158,12 +159,14 @@ export function registerAdminGithubEnterpriseRoutes(
158
159
  if (!isRole(role)) return new Response("Not Found", { status: 404 });
159
160
  const form = await readForm(c);
160
161
  const enterpriseSlug = field(form, "enterpriseSlug");
162
+ const key = await readPrivateKeyField(form);
163
+ if (!key.ok) return renderPage(c, { error: key.error, status: 400 });
161
164
  const r = await call(c, "PUT", `/github-enterprise/apps/${role}`, {
162
165
  appId: field(form, "appId"),
163
166
  slug: field(form, "slug"),
164
167
  ...(enterpriseSlug ? { enterpriseSlug } : {}),
165
- // Pasted as-is; never trimmed away from or echoed back to the page.
166
- privateKey: form.get("privateKey")?.toString() ?? "",
168
+ // Pasted or uploaded; never echoed back to the page.
169
+ privateKey: key.pem,
167
170
  });
168
171
  return r.ok ? back(c, "saved") : fail(c, r);
169
172
  });
@@ -17,6 +17,10 @@ import { AgentPluginService } from "./agent-plugins.ts";
17
17
  import { AgentService } from "./agents.ts";
18
18
  import { createAgentRuntimeApp } from "./api.ts";
19
19
  import { parseAdminApiKeys } from "./api-auth.ts";
20
+ import type { MiddlewareHandler } from "hono";
21
+ import { Hono } from "hono";
22
+ import { type AdminUIEnv } from "./admin-ui.ts";
23
+ import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
20
24
  import { createGithubEnterpriseApp } from "./github-enterprise-api.ts";
21
25
  import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
22
26
  import { createAdminPrismaClient } from "./prisma-client.ts";
@@ -122,6 +126,55 @@ describeOrSkip("github-enterprise API (integration)", () => {
122
126
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(0);
123
127
  });
124
128
 
129
+ it("a .pem upload through the settings UI saves the same row as pasting", async () => {
130
+ const api = build();
131
+ const ui = new Hono<AdminUIEnv>();
132
+ registerAdminGithubEnterpriseRoutes(ui, {
133
+ requireAuth: (async (c, next) => {
134
+ c.set("userEmail", "admin@x.com");
135
+ c.set("isAdmin", true);
136
+ await next();
137
+ }) as MiddlewareHandler<AdminUIEnv>,
138
+ html: (content, o) => new Response(content, { status: o?.status ?? 200 }),
139
+ api: (path, init) =>
140
+ api.request(path, {
141
+ ...init,
142
+ headers: { ...(init?.headers ?? {}), ...ADMIN },
143
+ }),
144
+ });
145
+ const base = "/admin/settings/github-enterprise/apps/lookup";
146
+ const fields = { appId: "777", slug: "example-lookup" };
147
+ const snapshot = async () => {
148
+ const row = await prisma.gitHubEnterpriseApp.findUnique({
149
+ where: { role: "lookup" },
150
+ });
151
+ return {
152
+ appId: row?.appId,
153
+ slug: row?.slug,
154
+ enterpriseSlug: row?.enterpriseSlug,
155
+ key: await appService.getPrivateKey("lookup"),
156
+ };
157
+ };
158
+
159
+ const body = new FormData();
160
+ for (const [k, v] of Object.entries(fields)) body.set(k, v);
161
+ body.set("privateKey", PEM);
162
+ expect((await ui.request(base, { method: "POST", body })).status).toBe(302);
163
+ const pasted = await snapshot();
164
+
165
+ await prisma.gitHubEnterpriseApp.deleteMany();
166
+ const upload = new FormData();
167
+ for (const [k, v] of Object.entries(fields)) upload.set(k, v);
168
+ upload.set("privateKeyFile", new File([PEM], "key.pem"));
169
+ const res = await ui.request(base, { method: "POST", body: upload });
170
+ expect(res.status).toBe(302);
171
+ expect(await snapshot()).toEqual(pasted);
172
+ const row = await prisma.gitHubEnterpriseApp.findUnique({
173
+ where: { role: "lookup" },
174
+ });
175
+ expect(row?.privateKeyEncrypted).not.toContain(PEM_BODY);
176
+ });
177
+
125
178
  it("PUT then validate persists the result; the key is encrypted and never returned", async () => {
126
179
  const app = build();
127
180
  const saved = await put(app);
@@ -81,4 +81,28 @@ describe("GitHub Enterprise key isolation", () => {
81
81
  expect(src).not.toMatch(/enterprise/i);
82
82
  }
83
83
  });
84
+
85
+ it("the upload route and parser never touch the key-bearing service", () => {
86
+ for (const rel of [
87
+ "admin/src/admin-ui-github-enterprise.ts",
88
+ "admin/src/github-enterprise-pem-upload.ts",
89
+ ]) {
90
+ const src = readFileSync(join(REPO, rel), "utf-8");
91
+ expect(src).not.toMatch(/\.getPrivateKey\(|privateKeyEncrypted/);
92
+ expect(src).not.toMatch(/github-enterprise-apps/);
93
+ // Uploaded content is never logged.
94
+ expect(src).not.toMatch(/console\.|logger\./);
95
+ }
96
+ });
97
+
98
+ it("the upload field name is only handled by the pem-upload parser", () => {
99
+ const handlers = files
100
+ .map((f) => relative(REPO, f))
101
+ .filter((rel) =>
102
+ /get\(["']privateKeyFile["']\)/.test(
103
+ readFileSync(join(REPO, rel), "utf-8"),
104
+ ),
105
+ );
106
+ expect(handlers).toEqual(["admin/src/github-enterprise-pem-upload.ts"]);
107
+ });
84
108
  });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * admin/src/github-enterprise-pem-upload.ts
3
+ * Parses the private-key field of the GHE settings form (GHE-1.12): a pasted
4
+ * value or an uploaded .pem file. Pure and key-service free; errors are fixed
5
+ * strings that never include any submitted content.
6
+ */
7
+
8
+ /** A PEM private key is ~1.7 KB (RSA 2048) to ~3.3 KB (RSA 4096); 16 KB is generous. */
9
+ export const MAX_PEM_BYTES = 16 * 1024;
10
+
11
+ const PEM_PRIVATE_KEY =
12
+ /^-----BEGIN (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]+-----END (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----$/;
13
+
14
+ export type PemResult =
15
+ | { ok: true; pem: string }
16
+ | { ok: false; error: string };
17
+
18
+ /** Returns the key from the uploaded file when one was chosen, else the pasted text. */
19
+ export async function readPrivateKeyField(form: FormData): Promise<PemResult> {
20
+ const file = form.get("privateKeyFile");
21
+ if (file instanceof File && file.size > 0) {
22
+ if (file.size > MAX_PEM_BYTES) {
23
+ return {
24
+ ok: false,
25
+ error: `The key file is too large (limit ${MAX_PEM_BYTES / 1024} KB).`,
26
+ };
27
+ }
28
+ return checkPem(await file.text(), "The file is not a PEM private key.");
29
+ }
30
+ const pasted = form.get("privateKey")?.toString() ?? "";
31
+ if (!pasted.trim()) {
32
+ return { ok: false, error: "Paste a private key or choose a .pem file." };
33
+ }
34
+ // Multipart and browser textareas submit CRLF; the API validates the key.
35
+ return { ok: true, pem: normalizeNewlines(pasted) };
36
+ }
37
+
38
+ function checkPem(text: string, error: string): PemResult {
39
+ return PEM_PRIVATE_KEY.test(text.trim())
40
+ ? { ok: true, pem: normalizeNewlines(text) }
41
+ : { ok: false, error };
42
+ }
43
+
44
+ /** Both paths store LF so an upload and a paste save identical rows. */
45
+ function normalizeNewlines(text: string): string {
46
+ return text.replace(/\r\n/g, "\n");
47
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * admin/src/github-enterprise-pem-upload.unit.test.ts
3
+ * Unit tests for the paste-or-upload private key parsing (GHE-1.12).
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import { generateKeyPairSync } from "node:crypto";
8
+ import {
9
+ MAX_PEM_BYTES,
10
+ readPrivateKeyField,
11
+ } from "./github-enterprise-pem-upload.ts";
12
+
13
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
14
+ modulusLength: 2048,
15
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
16
+ publicKeyEncoding: { type: "spki", format: "pem" },
17
+ });
18
+
19
+ const formWith = (entries: Record<string, string | File>) => {
20
+ const f = new FormData();
21
+ for (const [k, v] of Object.entries(entries)) f.set(k, v);
22
+ return f;
23
+ };
24
+ const pemFile = (body: string) =>
25
+ new File([body], "app.private-key.pem", { type: "application/x-pem-file" });
26
+
27
+ describe("readPrivateKeyField", () => {
28
+ it("returns an uploaded valid PEM unchanged", async () => {
29
+ const r = await readPrivateKeyField(
30
+ formWith({ privateKeyFile: pemFile(PEM) }),
31
+ );
32
+ expect(r).toEqual({ ok: true, pem: PEM });
33
+ });
34
+
35
+ it("accepts RSA and EC private key headers", async () => {
36
+ for (const kind of ["RSA ", "EC ", ""]) {
37
+ const body = `-----BEGIN ${kind}PRIVATE KEY-----\nQUJD\n-----END ${kind}PRIVATE KEY-----`;
38
+ const r = await readPrivateKeyField(
39
+ formWith({ privateKeyFile: pemFile(body) }),
40
+ );
41
+ expect(r.ok).toBe(true);
42
+ }
43
+ });
44
+
45
+ it("prefers the file over pasted text", async () => {
46
+ const r = await readPrivateKeyField(
47
+ formWith({ privateKeyFile: pemFile(PEM), privateKey: "pasted" }),
48
+ );
49
+ expect(r).toEqual({ ok: true, pem: PEM });
50
+ });
51
+
52
+ it("passes pasted text through unchanged when no file is chosen", async () => {
53
+ const r = await readPrivateKeyField(
54
+ formWith({ privateKey: PEM, privateKeyFile: new File([], "") }),
55
+ );
56
+ expect(r).toEqual({ ok: true, pem: PEM });
57
+ });
58
+
59
+ it("stores CRLF uploads and pastes identically (LF)", async () => {
60
+ const crlf = PEM.replace(/\n/g, "\r\n");
61
+ const up = await readPrivateKeyField(
62
+ formWith({ privateKeyFile: pemFile(crlf) }),
63
+ );
64
+ const paste = await readPrivateKeyField(formWith({ privateKey: crlf }));
65
+ expect(up).toEqual({ ok: true, pem: PEM });
66
+ expect(paste).toEqual(up);
67
+ });
68
+
69
+ it("rejects a non-PEM file without echoing its content", async () => {
70
+ const r = await readPrivateKeyField(
71
+ formWith({ privateKeyFile: pemFile("hunter2-SECRET not a key") }),
72
+ );
73
+ expect(r.ok).toBe(false);
74
+ if (!r.ok) {
75
+ expect(r.error).toContain("not a PEM private key");
76
+ expect(r.error).not.toContain("hunter2");
77
+ }
78
+ });
79
+
80
+ it("rejects a public key or certificate PEM", async () => {
81
+ for (const kind of ["PUBLIC KEY", "CERTIFICATE"]) {
82
+ const r = await readPrivateKeyField(
83
+ formWith({
84
+ privateKeyFile: pemFile(
85
+ `-----BEGIN ${kind}-----\nQUJD\n-----END ${kind}-----`,
86
+ ),
87
+ }),
88
+ );
89
+ expect(r.ok).toBe(false);
90
+ }
91
+ });
92
+
93
+ it("rejects an oversized file", async () => {
94
+ const big = `${PEM}${"A".repeat(MAX_PEM_BYTES)}`;
95
+ const r = await readPrivateKeyField(
96
+ formWith({ privateKeyFile: pemFile(big) }),
97
+ );
98
+ expect(r.ok).toBe(false);
99
+ if (!r.ok) expect(r.error).toContain("too large");
100
+ });
101
+
102
+ it("rejects when neither a file nor text is provided", async () => {
103
+ const r = await readPrivateKeyField(formWith({ privateKey: " " }));
104
+ expect(r.ok).toBe(false);
105
+ });
106
+ });