Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history

green-ecosystem.test.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

green-ecosystem.test.tsBlame798 lines · 2 contributors
3ef4c9dClaude1/**
2 * Tests for the green ecosystem: secret scanner, codeowners parser,
3 * auto-repair helpers, notification + audit log helpers, health routes,
4 * and rate limiting.
5 *
6 * These unit-level tests avoid DB + git subprocess work so they run fast.
7 */
8
9import { describe, it, expect } from "bun:test";
10import app from "../app";
11import { scanForSecrets, SECRET_PATTERNS } from "../lib/security-scan";
12import {
13 parseCodeowners,
14 ownersForPath,
40d3e3fClaude15 isTeamToken,
16 expandOwnerTokens,
3ef4c9dClaude17} from "../lib/codeowners";
18import { generateCommitMessage } from "../lib/ai-generators";
19import { isAiAvailable } from "../lib/ai-client";
6fc53bdClaude20import {
21 isAllowedEmoji,
22 isAllowedTarget,
23 ALLOWED_EMOJIS,
24 EMOJI_GLYPH,
25} from "../lib/reactions";
24cf2caClaude26import { sendEmail, absoluteUrl } from "../lib/email";
27import { __internal as notifyInternal } from "../lib/notify";
6563f0aClaude28import {
29 isValidSlug,
30 normalizeSlug,
31 orgRoleAtLeast,
32 isValidOrgRole,
33 isValidTeamRole,
34 __test as orgsInternal,
35} from "../lib/orgs";
7298a17Claude36import {
37 base32Encode,
38 base32Decode,
39 generateTotpSecret,
40 totpCode,
41 verifyTotpCode,
42 otpauthUrl,
43 generateRecoveryCodes,
44 hashRecoveryCode,
45} from "../lib/totp";
3ef4c9dClaude46
47describe("secret scanner", () => {
48 it("detects AWS access keys", () => {
49 const findings = scanForSecrets([
50 {
51 path: "config.env",
52 content: "AWS_ACCESS_KEY=AKIAZ2J4NPQR5LTMWXYZ\n",
53 },
54 ]);
55 expect(findings.length).toBeGreaterThan(0);
56 expect(findings.some((f) => /AWS/i.test(f.type))).toBe(true);
57 });
58
59 it("detects Anthropic API keys", () => {
60 const findings = scanForSecrets([
61 {
62 path: "app.ts",
63 content:
64 'const key = "sk-ant-api03-QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ-AAAAAA";',
65 },
66 ]);
67 expect(findings.some((f) => /anthropic/i.test(f.type))).toBe(true);
68 });
69
70 it("ignores binary/lock paths", () => {
71 const findings = scanForSecrets([
72 {
73 path: "package-lock.json",
74 content: "AKIAZ2J4NPQR5LTMWXYZ secret content",
75 },
76 ]);
77 expect(findings.length).toBe(0);
78 });
79
80 it("does not match placeholder strings in test fixtures", () => {
81 const findings = scanForSecrets([
82 {
83 path: "test.js",
84 content:
85 '// example: AKIA" + "XAMPLE_PLACEHOLDER_KEY_FIXTURE"\nconst k = "FAKE_TEST_PLACEHOLDER";',
86 },
87 ]);
88 // all findings should be filtered by the placeholder heuristic
89 expect(findings.every((f) => !/placeholder|fixture/i.test(f.snippet))).toBe(true);
90 });
91
92 it("has a rich library of rules", () => {
93 expect(SECRET_PATTERNS.length).toBeGreaterThanOrEqual(10);
94 });
95});
96
97describe("codeowners parser", () => {
98 it("parses simple rules", () => {
99 const rules = parseCodeowners(
100 "# top-level owner\n* @alice\nsrc/api/** @bob @carol\n/docs/ @alice\n"
101 );
102 expect(rules.length).toBe(3);
103 expect(rules[0].owners).toEqual(["alice"]);
104 expect(rules[1].owners).toEqual(["bob", "carol"]);
105 });
106
107 it("resolves last-matching rule wins", () => {
108 const rules = parseCodeowners("* @alice\nsrc/api/** @bob\n");
109 expect(ownersForPath("README.md", rules)).toEqual(["alice"]);
110 expect(ownersForPath("src/api/users.ts", rules)).toEqual(["bob"]);
111 });
112
113 it("anchors leading-slash patterns to repo root", () => {
114 const rules = parseCodeowners("/docs/ @alice\n");
115 expect(ownersForPath("docs/readme.md", rules)).toEqual(["alice"]);
116 expect(ownersForPath("src/docs/readme.md", rules)).toEqual([]);
117 });
118
119 it("ignores comments and blank lines", () => {
120 const rules = parseCodeowners(
121 "# comment\n\n \n# another\n* @ghost # trailing comment\n"
122 );
123 expect(rules.length).toBe(1);
124 expect(rules[0].owners).toEqual(["ghost"]);
125 });
40d3e3fClaude126
127 it("preserves @org/team tokens (B3)", () => {
128 const rules = parseCodeowners(
129 "api/** @acme/backend @alice\nweb/** @acme/frontend\n"
130 );
131 expect(rules[0].owners).toEqual(["acme/backend", "alice"]);
132 expect(rules[1].owners).toEqual(["acme/frontend"]);
133 expect(isTeamToken("acme/backend")).toBe(true);
134 expect(isTeamToken("alice")).toBe(false);
135 });
136
137 it("expandOwnerTokens passes plain usernames through and drops unknown teams gracefully", async () => {
138 // Real team lookup requires DB rows. Without DB the helper must still
139 // resolve without throwing; plain usernames must always pass through.
140 const result = await expandOwnerTokens([
141 "alice",
142 "bob",
143 "nonexistent-org-xyz/some-team",
144 ]);
145 expect(result).toContain("alice");
146 expect(result).toContain("bob");
147 // Unknown team silently drops (no throw, no crash).
148 expect(result).not.toContain("nonexistent-org-xyz/some-team");
149 });
3ef4c9dClaude150});
151
152describe("AI generator fallbacks", () => {
153 it("returns a safe fallback commit message when AI is unavailable", async () => {
154 if (isAiAvailable()) {
155 // API key is set — skip fallback assertion
156 return;
157 }
158 const msg = await generateCommitMessage("");
159 expect(msg.length).toBeGreaterThan(0);
160 expect(msg).toMatch(/^\S+/);
161 });
162});
163
164describe("health + metrics endpoints", () => {
165 it("GET /healthz returns 200", async () => {
166 const res = await app.request("/healthz");
167 expect(res.status).toBe(200);
168 const body = await res.json();
169 expect(body.ok).toBe(true);
170 });
171
172 it("GET /metrics returns process metrics", async () => {
173 const res = await app.request("/metrics");
174 expect(res.status).toBe(200);
175 const body = await res.json();
176 expect(typeof body.uptimeMs).toBe("number");
177 expect(typeof body.heapUsed).toBe("number");
178 });
179
180 it("response carries X-Request-Id header", async () => {
181 const res = await app.request("/healthz");
182 expect(res.headers.get("X-Request-Id")).toBeTruthy();
183 });
184});
185
186describe("rate limiting", () => {
187 it("rate-limit headers appear on /api requests", async () => {
188 const res = await app.request("/api/users/nonexistent/repos");
189 // Headers should exist even though user is missing
190 const limit = res.headers.get("X-RateLimit-Limit");
191 expect(limit).toBeTruthy();
192 });
193});
194
195describe("shortcuts + search page", () => {
196 it("GET /shortcuts is public", async () => {
197 const res = await app.request("/shortcuts");
198 expect(res.status).toBe(200);
199 const html = await res.text();
200 expect(html).toContain("Keyboard shortcuts");
201 });
202
203 it("GET /search with no query shows the type tabs", async () => {
204 const res = await app.request("/search");
205 expect(res.status).toBe(200);
206 const html = await res.text();
207 expect(html).toContain("Repositories");
208 expect(html).toContain("Users");
209 });
210});
ad6d4adClaude211
212describe("GateTest inbound hook", () => {
213 it("GET /api/hooks/ping is unauthenticated and reports service", async () => {
214 const res = await app.request("/api/hooks/ping");
215 expect(res.status).toBe(200);
216 const body = await res.json();
217 expect(body.ok).toBe(true);
218 expect(body.service).toBe("gluecron");
219 expect(Array.isArray(body.hooks)).toBe(true);
220 });
221
222 it("POST /api/hooks/gatetest rejects when no secret configured", async () => {
223 const prev = process.env.GATETEST_CALLBACK_SECRET;
224 const prevH = process.env.GATETEST_HMAC_SECRET;
225 delete process.env.GATETEST_CALLBACK_SECRET;
226 delete process.env.GATETEST_HMAC_SECRET;
227 const res = await app.request("/api/hooks/gatetest", {
228 method: "POST",
229 headers: { "content-type": "application/json" },
230 body: JSON.stringify({ repository: "a/b", sha: "x", status: "passed" }),
231 });
232 expect(res.status).toBe(401);
233 if (prev) process.env.GATETEST_CALLBACK_SECRET = prev;
234 if (prevH) process.env.GATETEST_HMAC_SECRET = prevH;
235 });
236
237 it("POST /api/hooks/gatetest rejects bad bearer token", async () => {
238 const prev = process.env.GATETEST_CALLBACK_SECRET;
ea52715copilot-swe-agent[bot]239 process.env.GATETEST_CALLBACK_SECRET = "gatetest-cb-fixture";
ad6d4adClaude240 const res = await app.request("/api/hooks/gatetest", {
241 method: "POST",
242 headers: {
243 "content-type": "application/json",
244 authorization: "Bearer wrong-token",
245 },
246 body: JSON.stringify({ repository: "a/b", sha: "x", status: "passed" }),
247 });
248 expect(res.status).toBe(401);
249 if (prev === undefined) delete process.env.GATETEST_CALLBACK_SECRET;
250 else process.env.GATETEST_CALLBACK_SECRET = prev;
251 });
252
253 it("POST /api/hooks/gatetest rejects malformed payload even when authed", async () => {
254 const prev = process.env.GATETEST_CALLBACK_SECRET;
ea52715copilot-swe-agent[bot]255 process.env.GATETEST_CALLBACK_SECRET = "gatetest-cb-fixture";
ad6d4adClaude256 const res = await app.request("/api/hooks/gatetest", {
257 method: "POST",
258 headers: {
259 "content-type": "application/json",
ea52715copilot-swe-agent[bot]260 authorization: "Bearer gatetest-cb-fixture",
ad6d4adClaude261 },
262 body: "not-json",
263 });
264 expect(res.status).toBe(400);
265 if (prev === undefined) delete process.env.GATETEST_CALLBACK_SECRET;
266 else process.env.GATETEST_CALLBACK_SECRET = prev;
267 });
268
269 it("POST /api/v1/gate-runs (backup) rejects without bearer", async () => {
270 const res = await app.request("/api/v1/gate-runs", {
271 method: "POST",
272 headers: { "content-type": "application/json" },
273 body: JSON.stringify({ repository: "a/b", sha: "x", status: "passed" }),
274 });
275 expect(res.status).toBe(401);
276 });
277});
6fc53bdClaude278
279describe("theme toggle", () => {
280 it("GET /theme/toggle sets a cookie and redirects", async () => {
281 const res = await app.request("/theme/toggle");
282 // 302 redirect; no cookie yet means we flip from the default (dark) → light
283 expect([301, 302, 303, 307]).toContain(res.status);
284 const setCookie = res.headers.get("set-cookie") || "";
285 expect(/theme=light/.test(setCookie)).toBe(true);
286 });
287
288 it("GET /theme/toggle flips an existing 'light' cookie back to dark", async () => {
289 const res = await app.request("/theme/toggle", {
290 headers: { cookie: "theme=light" },
291 });
292 const setCookie = res.headers.get("set-cookie") || "";
293 expect(/theme=dark/.test(setCookie)).toBe(true);
294 });
295
296 it("GET /theme/set?mode=light returns JSON when asked", async () => {
297 const res = await app.request("/theme/set?mode=light", {
298 headers: { accept: "application/json" },
299 });
300 expect(res.status).toBe(200);
301 const body = await res.json();
302 expect(body.ok).toBe(true);
303 expect(body.theme).toBe("light");
304 });
305
306 it("GET /theme/set rejects unknown modes", async () => {
307 const res = await app.request("/theme/set?mode=neon", {
308 headers: { accept: "application/json" },
309 });
310 expect(res.status).toBe(400);
311 });
312
74a8784Claude313 it("Layout pages include the pre-paint theme script + data-theme attribute", async () => {
314 // 2026-06-10: "/" now serves the self-contained Landing2030Page;
315 // the Layout theme contract is asserted on /help instead.
316 const res = await app.request("/help");
6fc53bdClaude317 const html = await res.text();
318 expect(html).toContain("data-theme");
319 expect(html).toContain("theme-icon-");
320 // The pre-paint script reads the cookie.
321 expect(html).toContain("document.cookie");
322 });
323});
324
325describe("reactions", () => {
326 it("allowed emojis and targets are self-consistent", () => {
327 expect(ALLOWED_EMOJIS.length).toBeGreaterThanOrEqual(6);
328 for (const e of ALLOWED_EMOJIS) {
329 expect(isAllowedEmoji(e)).toBe(true);
330 expect(EMOJI_GLYPH[e]).toBeTruthy();
331 }
332 expect(isAllowedEmoji("nope")).toBe(false);
333 expect(isAllowedTarget("issue")).toBe(true);
334 expect(isAllowedTarget("martian")).toBe(false);
335 });
336
337 it("POST /api/reactions/.../toggle requires auth", async () => {
338 const res = await app.request(
339 "/api/reactions/issue/00000000-0000-0000-0000-000000000000/thumbs_up/toggle",
340 { method: "POST" }
341 );
342 // Unauthenticated -> redirect to /login (302)
343 expect([301, 302, 303, 307]).toContain(res.status);
344 });
345
346 it("GET /api/reactions/:type/:id returns empty summary when no reactions exist", async () => {
347 const res = await app.request(
348 "/api/reactions/issue/00000000-0000-0000-0000-000000000000"
349 );
350 expect(res.status).toBe(200);
351 const body = await res.json();
352 expect(body.ok).toBe(true);
353 expect(Array.isArray(body.reactions)).toBe(true);
354 });
355
356 it("rejects unknown target type on the listing endpoint", async () => {
357 const res = await app.request(
358 "/api/reactions/martian/00000000-0000-0000-0000-000000000000"
359 );
360 expect(res.status).toBe(400);
361 });
362});
363
364describe("audit log UI", () => {
365 it("GET /settings/audit redirects unauthenticated users to /login", async () => {
366 const res = await app.request("/settings/audit");
367 expect([301, 302, 303, 307]).toContain(res.status);
368 const loc = res.headers.get("location") || "";
369 expect(loc.startsWith("/login")).toBe(true);
370 });
371});
24cf2caClaude372
373describe("email", () => {
374 it("sendEmail in log mode never throws and returns ok", async () => {
375 const prev = process.env.EMAIL_PROVIDER;
376 process.env.EMAIL_PROVIDER = "log";
377 const res = await sendEmail({
378 to: "test@gluecron.local",
379 subject: "hello",
380 text: "body",
381 });
382 expect(res.ok).toBe(true);
383 expect(res.provider).toBe("log");
384 if (prev === undefined) delete process.env.EMAIL_PROVIDER;
385 else process.env.EMAIL_PROVIDER = prev;
386 });
387
388 it("sendEmail rejects invalid recipient without throwing", async () => {
389 const res = await sendEmail({
390 to: "not-an-email",
391 subject: "x",
392 text: "y",
393 });
394 expect(res.ok).toBe(false);
395 expect(res.skipped).toBeTruthy();
396 });
397
398 it("sendEmail rejects empty subject/body without throwing", async () => {
399 const res = await sendEmail({ to: "a@b.co", subject: "", text: "" });
400 expect(res.ok).toBe(false);
401 });
402
403 it("absoluteUrl joins paths against APP_BASE_URL", () => {
404 const prev = process.env.APP_BASE_URL;
405 process.env.APP_BASE_URL = "https://gluecron.example/";
406 expect(absoluteUrl("/x")).toBe("https://gluecron.example/x");
407 expect(absoluteUrl("x")).toBe("https://gluecron.example/x");
408 expect(absoluteUrl("https://other/y")).toBe("https://other/y");
409 if (prev === undefined) delete process.env.APP_BASE_URL;
410 else process.env.APP_BASE_URL = prev;
411 });
412
413 it("notify email-eligible set only includes user-opt-in kinds", () => {
414 // Any kind in EMAIL_ELIGIBLE must map to a preference column
415 for (const k of notifyInternal.EMAIL_ELIGIBLE) {
416 expect(notifyInternal.prefFor(k)).not.toBeNull();
417 }
418 // gate_passed is not eligible (too spammy; only gate_failed is)
419 expect(notifyInternal.EMAIL_ELIGIBLE.has("gate_passed" as any)).toBe(false);
420 expect(notifyInternal.EMAIL_ELIGIBLE.has("deploy_failed" as any)).toBe(
421 false
422 );
423 });
424
425 it("notify email subject is tagged and truncated", () => {
426 const subj = notifyInternal.subjectFor("gate_failed", "x".repeat(300));
427 expect(subj.startsWith("[gate failed]")).toBe(true);
428 expect(subj.length).toBeLessThanOrEqual(180);
429 });
430});
431
432describe("settings email preferences", () => {
433 it("GET /settings redirects unauthenticated users to /login", async () => {
434 const res = await app.request("/settings");
435 expect([301, 302, 303, 307]).toContain(res.status);
436 const loc = res.headers.get("location") || "";
437 expect(loc.startsWith("/login")).toBe(true);
438 });
439
440 it("POST /settings/notifications redirects unauthenticated users to /login", async () => {
441 const res = await app.request("/settings/notifications", {
442 method: "POST",
443 headers: { "content-type": "application/x-www-form-urlencoded" },
444 body: "notify_email_on_mention=1",
445 });
446 expect([301, 302, 303, 307]).toContain(res.status);
447 const loc = res.headers.get("location") || "";
448 expect(loc.startsWith("/login")).toBe(true);
449 });
450});
6563f0aClaude451
452describe("orgs helpers (B1)", () => {
453 describe("isValidSlug", () => {
454 it("accepts simple slugs", () => {
455 expect(isValidSlug("acme")).toBe(true);
456 expect(isValidSlug("acme-corp")).toBe(true);
457 expect(isValidSlug("a1")).toBe(true);
458 expect(isValidSlug("a-b-c-1-2-3")).toBe(true);
459 });
460
461 it("rejects too-short or too-long", () => {
462 expect(isValidSlug("")).toBe(false);
463 expect(isValidSlug("a")).toBe(false);
464 expect(isValidSlug("a".repeat(40))).toBe(false);
465 });
466
467 it("rejects leading/trailing hyphen", () => {
468 expect(isValidSlug("-acme")).toBe(false);
469 expect(isValidSlug("acme-")).toBe(false);
470 });
471
472 it("rejects consecutive hyphens", () => {
473 expect(isValidSlug("foo--bar")).toBe(false);
474 });
475
476 it("rejects uppercase + invalid chars", () => {
477 expect(isValidSlug("Acme")).toBe(false);
478 expect(isValidSlug("acme_corp")).toBe(false);
479 expect(isValidSlug("acme.corp")).toBe(false);
480 expect(isValidSlug("acme corp")).toBe(false);
481 });
482
483 it("rejects reserved words", () => {
484 expect(isValidSlug("api")).toBe(false);
485 expect(isValidSlug("admin")).toBe(false);
486 expect(isValidSlug("settings")).toBe(false);
487 expect(isValidSlug("orgs")).toBe(false);
488 expect(isValidSlug("new")).toBe(false);
489 });
490 });
491
492 describe("normalizeSlug", () => {
493 it("lowercases and trims", () => {
494 expect(normalizeSlug(" ACME ")).toBe("acme");
495 expect(normalizeSlug("Acme-Corp")).toBe("acme-corp");
496 });
497 });
498
499 describe("orgRoleAtLeast", () => {
500 it("owner beats admin beats member", () => {
501 expect(orgRoleAtLeast("owner", "member")).toBe(true);
502 expect(orgRoleAtLeast("owner", "admin")).toBe(true);
503 expect(orgRoleAtLeast("owner", "owner")).toBe(true);
504 expect(orgRoleAtLeast("admin", "member")).toBe(true);
505 expect(orgRoleAtLeast("admin", "admin")).toBe(true);
506 expect(orgRoleAtLeast("admin", "owner")).toBe(false);
507 expect(orgRoleAtLeast("member", "admin")).toBe(false);
508 expect(orgRoleAtLeast("member", "owner")).toBe(false);
509 });
510
511 it("treats unknown role as rank 0", () => {
512 expect(orgRoleAtLeast("", "member")).toBe(false);
513 expect(orgRoleAtLeast("banana", "member")).toBe(false);
514 });
515 });
516
517 describe("role type guards", () => {
518 it("isValidOrgRole", () => {
519 expect(isValidOrgRole("owner")).toBe(true);
520 expect(isValidOrgRole("admin")).toBe(true);
521 expect(isValidOrgRole("member")).toBe(true);
522 expect(isValidOrgRole("maintainer")).toBe(false);
523 expect(isValidOrgRole("banana")).toBe(false);
524 });
525
526 it("isValidTeamRole", () => {
527 expect(isValidTeamRole("maintainer")).toBe(true);
528 expect(isValidTeamRole("member")).toBe(true);
529 expect(isValidTeamRole("owner")).toBe(false);
530 expect(isValidTeamRole("banana")).toBe(false);
531 });
532 });
533
534 describe("internal", () => {
535 it("rank table orders correctly", () => {
536 const r = orgsInternal.ORG_ROLE_RANK;
537 expect(r.owner).toBeGreaterThan(r.admin);
538 expect(r.admin).toBeGreaterThan(r.member);
539 });
540
541 it("reserved set contains the app's top-level paths", () => {
542 expect(orgsInternal.RESERVED_SLUGS.has("api")).toBe(true);
543 expect(orgsInternal.RESERVED_SLUGS.has("settings")).toBe(true);
544 expect(orgsInternal.RESERVED_SLUGS.has("login")).toBe(true);
545 });
546 });
547});
548
549describe("orgs routes (B1)", () => {
550 it("GET /orgs redirects unauthenticated users to /login", async () => {
551 const res = await app.request("/orgs");
552 expect([301, 302, 303, 307]).toContain(res.status);
553 const loc = res.headers.get("location") || "";
554 expect(loc.startsWith("/login")).toBe(true);
555 });
556
557 it("GET /orgs/new redirects unauthenticated users to /login", async () => {
558 const res = await app.request("/orgs/new");
559 expect([301, 302, 303, 307]).toContain(res.status);
560 const loc = res.headers.get("location") || "";
561 expect(loc.startsWith("/login")).toBe(true);
562 });
563
564 it("POST /orgs/new redirects unauthenticated users to /login", async () => {
565 const res = await app.request("/orgs/new", {
566 method: "POST",
567 headers: { "content-type": "application/x-www-form-urlencoded" },
568 body: "slug=acme&name=Acme",
569 });
570 expect([301, 302, 303, 307]).toContain(res.status);
571 const loc = res.headers.get("location") || "";
572 expect(loc.startsWith("/login")).toBe(true);
573 });
574
575 it("GET /orgs/:slug redirects unauthenticated users to /login", async () => {
576 const res = await app.request("/orgs/some-org");
577 expect([301, 302, 303, 307]).toContain(res.status);
578 const loc = res.headers.get("location") || "";
579 expect(loc.startsWith("/login")).toBe(true);
580 });
581
582 it("POST /orgs/:slug/people/add redirects unauthenticated users to /login", async () => {
583 const res = await app.request("/orgs/some-org/people/add", {
584 method: "POST",
585 headers: { "content-type": "application/x-www-form-urlencoded" },
586 body: "username=alice&role=member",
587 });
588 expect([301, 302, 303, 307]).toContain(res.status);
589 const loc = res.headers.get("location") || "";
590 expect(loc.startsWith("/login")).toBe(true);
591 });
592});
7437605Claude593
594describe("org-owned repos (B2)", () => {
595 it("GET /orgs/:slug/repos redirects unauthenticated users to /login", async () => {
596 const res = await app.request("/orgs/some-org/repos");
597 expect([301, 302, 303, 307]).toContain(res.status);
598 const loc = res.headers.get("location") || "";
599 expect(loc.startsWith("/login")).toBe(true);
600 });
601
602 it("GET /orgs/:slug/repos/new redirects unauthenticated users to /login", async () => {
603 const res = await app.request("/orgs/some-org/repos/new");
604 expect([301, 302, 303, 307]).toContain(res.status);
605 const loc = res.headers.get("location") || "";
606 expect(loc.startsWith("/login")).toBe(true);
607 });
608
609 it("POST /orgs/:slug/repos/new redirects unauthenticated users to /login", async () => {
610 const res = await app.request("/orgs/some-org/repos/new", {
611 method: "POST",
612 headers: { "content-type": "application/x-www-form-urlencoded" },
613 body: "name=web",
614 });
615 expect([301, 302, 303, 307]).toContain(res.status);
616 const loc = res.headers.get("location") || "";
617 expect(loc.startsWith("/login")).toBe(true);
618 });
619
620 it("POST /api/repos with orgSlug still validates required fields", async () => {
621 const res = await app.request("/api/repos", {
622 method: "POST",
623 headers: { "Content-Type": "application/json" },
624 body: JSON.stringify({ orgSlug: "acme" }),
625 });
626 // Missing name + owner → 400 before any DB access.
627 expect(res.status).toBe(400);
628 });
629
630 it("POST /api/repos rejects invalid repo names before DB access", async () => {
631 const res = await app.request("/api/repos", {
632 method: "POST",
633 headers: { "Content-Type": "application/json" },
634 body: JSON.stringify({
635 name: "bad name with spaces",
636 owner: "alice",
637 }),
638 });
639 expect(res.status).toBe(400);
640 });
641});
7298a17Claude642
643describe("TOTP / 2FA (B4)", () => {
644 it("base32 round-trips bytes", () => {
645 const bytes = new Uint8Array([0x74, 0x65, 0x73, 0x74]); // "test"
646 const enc = base32Encode(bytes);
647 const dec = base32Decode(enc);
648 expect(Array.from(dec)).toEqual(Array.from(bytes));
649 });
650
651 it("generateTotpSecret returns 32-char Base32", () => {
652 const s = generateTotpSecret();
653 expect(s.length).toBe(32);
654 expect(/^[A-Z2-7]+$/.test(s)).toBe(true);
655 });
656
657 it("totpCode is 6 digits", async () => {
658 const s = generateTotpSecret();
659 const c = await totpCode(s);
660 expect(/^\d{6}$/.test(c)).toBe(true);
661 });
662
663 it("verifyTotpCode accepts a freshly-generated code", async () => {
664 const s = generateTotpSecret();
665 const c = await totpCode(s);
666 expect(await verifyTotpCode(s, c)).toBe(true);
667 });
668
669 it("verifyTotpCode tolerates a ±30s drift", async () => {
670 const s = generateTotpSecret();
671 const now = Math.floor(Date.now() / 1000);
672 const past = await totpCode(s, now - 30);
673 const future = await totpCode(s, now + 30);
674 expect(await verifyTotpCode(s, past, now)).toBe(true);
675 expect(await verifyTotpCode(s, future, now)).toBe(true);
676 });
677
678 it("verifyTotpCode rejects a wrong code", async () => {
679 const s = generateTotpSecret();
680 expect(await verifyTotpCode(s, "000000")).toBe(false);
681 });
682
683 it("verifyTotpCode rejects non-6-digit input", async () => {
684 const s = generateTotpSecret();
685 expect(await verifyTotpCode(s, "abc")).toBe(false);
686 expect(await verifyTotpCode(s, "12345")).toBe(false);
687 expect(await verifyTotpCode(s, "1234567")).toBe(false);
688 });
689
690 it("otpauthUrl has the expected shape", () => {
691 const u = otpauthUrl({
692 secret: "JBSWY3DPEHPK3PXP",
693 accountName: "alice@example.com",
694 issuer: "gluecron",
695 });
696 expect(u.startsWith("otpauth://totp/")).toBe(true);
697 expect(u).toContain("secret=JBSWY3DPEHPK3PXP");
698 expect(u).toContain("issuer=gluecron");
699 expect(u).toContain("period=30");
700 expect(u).toContain("digits=6");
701 });
702
703 it("generateRecoveryCodes returns the expected count + format", () => {
704 const codes = generateRecoveryCodes(5);
705 expect(codes.length).toBe(5);
706 for (const c of codes) {
707 expect(/^[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/.test(c)).toBe(true);
708 }
709 // Uniqueness: ~70 bits of entropy each, collisions should be astronomical.
710 expect(new Set(codes).size).toBe(5);
711 });
712
713 it("hashRecoveryCode is deterministic + normalised", async () => {
714 const a = await hashRecoveryCode("ABCD-1234-efgh");
715 const b = await hashRecoveryCode("abcd-1234-efgh");
716 const c = await hashRecoveryCode(" abcd-1234-efgh ");
717 expect(a).toBe(b);
718 expect(a).toBe(c);
719 expect(a.length).toBe(64); // SHA-256 hex
720 });
721});
722
723describe("2FA routes (B4)", () => {
724 it("GET /settings/2fa redirects unauthenticated users to /login", async () => {
725 const res = await app.request("/settings/2fa");
726 expect([301, 302, 303, 307]).toContain(res.status);
727 const loc = res.headers.get("location") || "";
728 expect(loc.startsWith("/login")).toBe(true);
729 });
730
731 it("POST /settings/2fa/enroll redirects unauthenticated users to /login", async () => {
732 const res = await app.request("/settings/2fa/enroll", {
733 method: "POST",
734 headers: { "content-type": "application/x-www-form-urlencoded" },
735 body: "",
736 });
737 expect([301, 302, 303, 307]).toContain(res.status);
738 const loc = res.headers.get("location") || "";
739 expect(loc.startsWith("/login")).toBe(true);
740 });
741
742 it("GET /login/2fa redirects to /login when no session cookie", async () => {
743 const res = await app.request("/login/2fa");
744 expect([301, 302, 303, 307]).toContain(res.status);
745 const loc = res.headers.get("location") || "";
746 expect(loc.startsWith("/login")).toBe(true);
747 });
748});
2df1f8cClaude749
750describe("passkeys routes (B5)", () => {
751 it("GET /settings/passkeys redirects unauthenticated users to /login", async () => {
752 const res = await app.request("/settings/passkeys");
753 expect([301, 302, 303, 307]).toContain(res.status);
754 const loc = res.headers.get("location") || "";
755 expect(loc.startsWith("/login")).toBe(true);
756 });
757
758 it("POST /api/passkeys/register/options redirects unauthenticated users to /login", async () => {
759 const res = await app.request("/api/passkeys/register/options", {
760 method: "POST",
761 headers: { "content-type": "application/json" },
762 body: "{}",
763 });
764 expect([301, 302, 303, 307]).toContain(res.status);
765 const loc = res.headers.get("location") || "";
766 expect(loc.startsWith("/login")).toBe(true);
767 });
768
769 it("POST /api/passkeys/auth/verify returns 400 when body is invalid", async () => {
770 const res = await app.request("/api/passkeys/auth/verify", {
771 method: "POST",
772 headers: { "content-type": "application/json" },
773 body: "not json",
774 });
775 // Either 400 (bad JSON) or 503 (DB down) — never a 500.
776 expect([400, 503]).toContain(res.status);
777 });
778
779 it("POST /api/passkeys/auth/verify rejects missing fields", async () => {
780 const res = await app.request("/api/passkeys/auth/verify", {
781 method: "POST",
782 headers: { "content-type": "application/json" },
783 body: "{}",
784 });
785 expect([400, 503]).toContain(res.status);
786 });
787
788 it("POST /settings/passkeys/:id/delete redirects unauthenticated users to /login", async () => {
789 const res = await app.request("/settings/passkeys/abc/delete", {
790 method: "POST",
791 headers: { "content-type": "application/x-www-form-urlencoded" },
792 body: "",
793 });
794 expect([301, 302, 303, 307]).toContain(res.status);
795 const loc = res.headers.get("location") || "";
796 expect(loc.startsWith("/login")).toBe(true);
797 });
798});