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
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
magic-link.test.ts20.9 KB · 596 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/**
 * Block Q2 — Magic-link sign-in.
 *
 * Covers `src/lib/magic-link.ts` (token primitives, start, consume) and
 * the `src/routes/magic-link.tsx` HTTP surface (GET/POST /login/magic,
 * GET /login/magic/callback).
 *
 * Strategy mirrors password-reset.test.ts:
 *   - The library tests stub the `db` module (K1 spread-from-real pattern)
 *     so they don't require Neon. Rows live in in-memory arrays keyed by
 *     `tableName(t)` derived from drizzle column metadata.
 *   - Email sending is replaced via `__setEmailForTests`.
 *   - The HTTP-surface tests use `app.request(...)` so the real Hono
 *     router + csrf middleware answer.
 *
 * All `mock.module(...)` calls capture the REAL module first and restore
 * in `afterAll` so we don't poison test files that run after us.
 */

import {
  describe,
  it,
  expect,
  mock,
  beforeEach,
  afterEach,
  afterAll,
} from "bun:test";

// Capture real modules BEFORE any mock.module() so afterAll can restore.
const _real_db = await import("../db");

// ---------------------------------------------------------------------------
// In-memory DB stub
// ---------------------------------------------------------------------------

interface FakeRow { [k: string]: any; }
interface FakeStore {
  users: FakeRow[];
  magic_link_tokens: FakeRow[];
  sessions: FakeRow[];
}

const store: FakeStore = { users: [], magic_link_tokens: [], sessions: [] };

function resetStore() {
  store.users = [];
  store.magic_link_tokens = [];
  store.sessions = [];
}

function tableName(t: any): keyof FakeStore | "?" {
  if (!t || typeof t !== "object") return "?";
  // magic_link_tokens: has tokenHash AND email (P1 reset tokens have no email)
  if ("tokenHash" in t && "email" in t && "usedAt" in t) return "magic_link_tokens";
  // sessions: token + expiresAt but no tokenHash
  if ("token" in t && "expiresAt" in t && !("tokenHash" in t)) return "sessions";
  // users: passwordHash + username
  if ("passwordHash" in t && "username" in t) return "users";
  return "?";
}

let _whereFilter: any = null;

function makeEq(lhs: any, rhs: any) {
  return { __op: "eq", lhs, rhs };
}

function colKey(lhs: any): string | null {
  if (!lhs || typeof lhs !== "object") return null;
  const name: string = lhs.name || "";
  const camel = name.replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase());
  return camel || null;
}

function applyFilter(rows: FakeRow[], where: any): FakeRow[] {
  if (!where) return rows;
  const k = colKey(where.lhs);
  if (!k) return rows;
  return rows.filter((r) => r[k] === where.rhs);
}

const _inserted: { table: string; values: any }[] = [];

let _lastSelectTable: keyof FakeStore | "?" = "?";
let _lastUpdateTable: keyof FakeStore | "?" = "?";
let _lastDeleteTable: keyof FakeStore | "?" = "?";

const selectChain: any = {
  from(t: any) { _lastSelectTable = tableName(t); return selectChain; },
  where(w: any) { _whereFilter = w; return selectChain; },
  orderBy() { return selectChain; },
  async limit(_n: number) {
    const tbl = _lastSelectTable;
    const where = _whereFilter;
    _whereFilter = null;
    if (tbl === "?") return [];
    const rows = applyFilter(store[tbl] as FakeRow[], where);
    return rows.slice(0, _n);
  },
};

const fakeDb: any = {
  select(_s?: any) { return selectChain; },
  insert(t: any) {
    const tbl = tableName(t);
    return {
      async values(v: any) {
        const row = { ...v, id: v.id || crypto.randomUUID() };
        if (!row.createdAt) row.createdAt = new Date();
        if (tbl !== "?") (store[tbl] as FakeRow[]).push(row);
        _inserted.push({ table: tbl, values: row });
        return { rows: [row] };
      },
      returning() {
        return {
          async values(v: any) {
            const row = { ...v, id: v.id || crypto.randomUUID() };
            if (!row.createdAt) row.createdAt = new Date();
            if (tbl !== "?") (store[tbl] as FakeRow[]).push(row);
            _inserted.push({ table: tbl, values: row });
            return [row];
          },
        };
      },
    };
  },
  update(t: any) {
    _lastUpdateTable = tableName(t);
    return {
      set(s: any) {
        const tbl = _lastUpdateTable;
        return {
          async where(w: any) {
            if (tbl === "?") return;
            const rows = applyFilter(store[tbl] as FakeRow[], w);
            for (const r of rows) Object.assign(r, s);
          },
        };
      },
    };
  },
  delete(t: any) {
    _lastDeleteTable = tableName(t);
    return {
      async where(w: any) {
        const tbl = _lastDeleteTable;
        if (tbl === "?") return;
        const remaining = (store[tbl] as FakeRow[]).filter(
          (r) => !applyFilter([r], w).length
        );
        (store[tbl] as FakeRow[]).length = 0;
        (store[tbl] as FakeRow[]).push(...remaining);
      },
    };
  },
};

mock.module("../db", () => ({ ..._real_db, db: fakeDb }));

const _real_drizzle = await import("drizzle-orm");
mock.module("drizzle-orm", () => ({
  ..._real_drizzle,
  eq: (lhs: any, rhs: any) => makeEq(lhs, rhs),
}));

// ---------------------------------------------------------------------------
// Email seam
// ---------------------------------------------------------------------------

const _emails: { to: string; subject: string; text: string; html?: string }[] = [];

import {
  generateMagicLinkToken,
  startMagicLinkSignIn,
  consumeMagicLinkToken,
  buildMagicLinkUrl,
  __setEmailForTests,
} from "../lib/magic-link";

__setEmailForTests((msg: any) => {
  _emails.push({ to: msg.to, subject: msg.subject, text: msg.text, html: msg.html });
  return { ok: true, provider: "log" as const };
});

afterAll(() => {
  __setEmailForTests(null);
  mock.module("../db", () => _real_db);
  mock.module("drizzle-orm", () => _real_drizzle);
});

beforeEach(() => {
  resetStore();
  _inserted.length = 0;
  _emails.length = 0;
});

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

async function sha256Hex(input: string): Promise<string> {
  const buf = new TextEncoder().encode(input);
  const digest = await crypto.subtle.digest("SHA-256", buf);
  return Array.from(new Uint8Array(digest))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

function seedUser(overrides: Partial<FakeRow> = {}): FakeRow {
  const u: FakeRow = {
    id: crypto.randomUUID(),
    username: "ada",
    email: "ada@example.com",
    passwordHash: "$2b$10$oldhashplaceholder0123456789012345678901234567890123",
    emailVerifiedAt: null,
    updatedAt: new Date(),
    ...overrides,
  };
  store.users.push(u);
  return u;
}

function seedToken(overrides: Partial<FakeRow> = {}): { row: FakeRow; plaintext: string } {
  const { plaintext, hash } = generateMagicLinkToken();
  const row: FakeRow = {
    id: crypto.randomUUID(),
    email: "ada@example.com",
    userId: null,
    tokenHash: hash,
    expiresAt: new Date(Date.now() + 60_000),
    usedAt: null,
    requestIp: null,
    createdAt: new Date(),
    ...overrides,
  };
  store.magic_link_tokens.push(row);
  return { row, plaintext };
}

// Give the fire-and-forget email send a tick to land in the recorder.
async function flushMicrotasks() {
  await new Promise((r) => setTimeout(r, 5));
}

// ---------------------------------------------------------------------------
// generateMagicLinkToken
// ---------------------------------------------------------------------------

describe("generateMagicLinkToken", () => {
  it("emits 64 hex chars of plaintext + a matching sha256 hash", async () => {
    const { plaintext, hash } = generateMagicLinkToken();
    expect(plaintext).toMatch(/^[0-9a-f]{64}$/);
    expect(hash).toMatch(/^[0-9a-f]{64}$/);
    expect(hash).toBe(await sha256Hex(plaintext));
  });

  it("emits unique plaintexts on repeated calls", () => {
    const a = generateMagicLinkToken();
    const b = generateMagicLinkToken();
    expect(a.plaintext).not.toBe(b.plaintext);
    expect(a.hash).not.toBe(b.hash);
  });
});

// ---------------------------------------------------------------------------
// startMagicLinkSignIn
// ---------------------------------------------------------------------------

describe("startMagicLinkSignIn", () => {
  it("creates a token row linked to an existing user and queues an email", async () => {
    const u = seedUser({ email: "ada@example.com", username: "ada" });
    const res = await startMagicLinkSignIn("ada@example.com", { requestIp: "127.0.0.1" });
    expect(res.ok).toBe(true);
    await flushMicrotasks();

    expect(store.magic_link_tokens.length).toBe(1);
    const row = store.magic_link_tokens[0]!;
    expect(row.userId).toBe(u.id);
    expect(row.email).toBe("ada@example.com");
    expect(row.tokenHash).toMatch(/^[0-9a-f]{64}$/);
    expect(row.expiresAt instanceof Date).toBe(true);
    expect(row.requestIp).toBe("127.0.0.1");

    expect(_emails.length).toBe(1);
    expect(_emails[0]!.to).toBe("ada@example.com");
    expect(_emails[0]!.subject).toBe("Your Gluecron sign-in link");
    expect(_emails[0]!.text).toContain("expires in 15 minutes");
    expect(_emails[0]!.text).toContain("/login/magic/callback?token=");
    expect(_emails[0]!.html).toContain("Sign in");
  });

  it("returns ok for non-existent email AND still mints a token row (userId=null) so consume can auto-create", async () => {
    const res = await startMagicLinkSignIn("ghost@example.com");
    expect(res.ok).toBe(true);
    await flushMicrotasks();

    expect(store.magic_link_tokens.length).toBe(1);
    const row = store.magic_link_tokens[0]!;
    expect(row.userId).toBeFalsy();
    expect(row.email).toBe("ghost@example.com");
    expect(_emails.length).toBe(1);
    expect(_emails[0]!.to).toBe("ghost@example.com");
  });

  it("does NOT mint a token when autoCreate=false and email is unknown", async () => {
    const res = await startMagicLinkSignIn("ghost@example.com", { autoCreate: false });
    expect(res.ok).toBe(true);
    await flushMicrotasks();
    expect(store.magic_link_tokens.length).toBe(0);
    expect(_emails.length).toBe(0);
  });

  it("returns ok for garbage inputs without throwing", async () => {
    expect((await startMagicLinkSignIn("")).ok).toBe(true);
    expect((await startMagicLinkSignIn("not-an-email")).ok).toBe(true);
    expect(store.magic_link_tokens.length).toBe(0);
    expect(_emails.length).toBe(0);
  });

  it("normalizes email case before lookup", async () => {
    seedUser({ email: "ada@example.com", username: "ada" });
    const res = await startMagicLinkSignIn("ADA@Example.COM");
    expect(res.ok).toBe(true);
    await flushMicrotasks();
    expect(store.magic_link_tokens.length).toBe(1);
    expect(store.magic_link_tokens[0]!.email).toBe("ada@example.com");
  });

  it("enforces the per-email rate limit (3 mints / hour)", async () => {
    seedUser({ email: "ada@example.com" });
    for (let i = 0; i < 3; i++) {
      const r = await startMagicLinkSignIn("ada@example.com");
      expect(r.ok).toBe(true);
    }
    await flushMicrotasks();
    expect(store.magic_link_tokens.length).toBe(3);

    // 4th call still returns ok (generic) but does NOT create another token.
    const r4 = await startMagicLinkSignIn("ada@example.com");
    expect(r4.ok).toBe(true);
    await flushMicrotasks();
    expect(store.magic_link_tokens.length).toBe(3);
  });
});

// ---------------------------------------------------------------------------
// consumeMagicLinkToken
// ---------------------------------------------------------------------------

describe("consumeMagicLinkToken", () => {
  it("rejects garbage tokens with reason=invalid", async () => {
    const res = await consumeMagicLinkToken("not-a-real-token");
    expect(res.ok).toBe(false);
    expect(res.reason).toBe("invalid");
  });

  it("rejects an empty token", async () => {
    const res = await consumeMagicLinkToken("");
    expect(res.ok).toBe(false);
    expect(res.reason).toBe("invalid");
  });

  it("rejects expired tokens", async () => {
    const u = seedUser();
    const { plaintext } = seedToken({
      userId: u.id,
      expiresAt: new Date(Date.now() - 60_000),
    });
    const res = await consumeMagicLinkToken(plaintext);
    expect(res.ok).toBe(false);
    expect(res.reason).toBe("expired");
  });

  it("rejects already-used tokens", async () => {
    const u = seedUser();
    const { plaintext } = seedToken({
      userId: u.id,
      usedAt: new Date(Date.now() - 1000),
    });
    const res = await consumeMagicLinkToken(plaintext);
    expect(res.ok).toBe(false);
    expect(res.reason).toBe("used");
  });

  it("happy path with existing user: returns userId, marks token used, no account created", async () => {
    const u = seedUser({ email: "ada@example.com", username: "ada" });
    const { row, plaintext } = seedToken({ userId: u.id, email: "ada@example.com" });

    const res = await consumeMagicLinkToken(plaintext);
    expect(res.ok).toBe(true);
    expect(res.userId).toBe(u.id);
    expect(res.createdAccount).toBe(false);

    const updated = store.magic_link_tokens.find((r) => r.id === row.id)!;
    expect(updated.usedAt instanceof Date).toBe(true);

    // No new user row.
    expect(store.users.length).toBe(1);
  });

  it("happy path with no existing user: creates account, returns userId + createdAccount=true", async () => {
    const { plaintext } = seedToken({ userId: null, email: "ghost@example.com" });

    const res = await consumeMagicLinkToken(plaintext);
    expect(res.ok).toBe(true);
    expect(res.userId).toBeTruthy();
    expect(res.createdAccount).toBe(true);

    // A fresh user row was minted for the email.
    expect(store.users.length).toBe(1);
    const created = store.users[0]!;
    expect(created.email).toBe("ghost@example.com");
    expect(created.username).toMatch(/^user-[a-z0-9]{8,}$/);
    // The placeholder password hash exists but is not the plaintext.
    expect(created.passwordHash).toBeTruthy();
    expect(created.passwordHash).not.toBe(plaintext);
    // The click verified the address.
    expect(created.emailVerifiedAt instanceof Date).toBe(true);
  });

  it("invalidates all other unused magic-link tokens for the same email on success", async () => {
    const u = seedUser({ email: "ada@example.com", username: "ada" });
    const { plaintext } = seedToken({ userId: u.id, email: "ada@example.com" });
    // Two more outstanding tokens for the same email — should be burned.
    const t2 = seedToken({ userId: u.id, email: "ada@example.com" });
    const t3 = seedToken({ userId: u.id, email: "ada@example.com" });
    // A token for a DIFFERENT email — must NOT be touched.
    const otherUser = seedUser({ email: "bob@example.com", username: "bob" });
    const tOther = seedToken({ userId: otherUser.id, email: "bob@example.com" });

    const res = await consumeMagicLinkToken(plaintext);
    expect(res.ok).toBe(true);

    // Every ada@example.com row is now used.
    const adaRows = store.magic_link_tokens.filter((r) => r.email === "ada@example.com");
    expect(adaRows.length).toBe(3);
    for (const r of adaRows) expect(r.usedAt instanceof Date).toBe(true);

    // The bob@example.com row is untouched.
    const bobRow = store.magic_link_tokens.find((r) => r.id === tOther.row.id)!;
    expect(bobRow.usedAt).toBe(null);

    // A second consume of one of the burned siblings is rejected as used.
    const second = await consumeMagicLinkToken(t2.plaintext);
    expect(second.ok).toBe(false);
    expect(second.reason).toBe("used");
    // Same for t3.
    const third = await consumeMagicLinkToken(t3.plaintext);
    expect(third.ok).toBe(false);
    expect(third.reason).toBe("used");
  });
});

// ---------------------------------------------------------------------------
// buildMagicLinkUrl
// ---------------------------------------------------------------------------

describe("buildMagicLinkUrl", () => {
  it("includes the token in the callback path", () => {
    const u = buildMagicLinkUrl("abc123");
    expect(u).toContain("/login/magic/callback?token=abc123");
  });
});

// ---------------------------------------------------------------------------
// HTTP surface — pull in the app AFTER the module mocks are installed.
// ---------------------------------------------------------------------------

const app = (await import("../app")).default;

describe("GET /login/magic", () => {
  it("renders the email-entry form with a CSRF input", async () => {
    const res = await app.request("/login/magic");
    expect(res.status).toBe(200);
    const html = await res.text();
    expect(html).toContain("Sign in with a magic link");
    expect(html).toContain('name="email"');
    expect(html).toContain('name="_csrf"');
    expect(html).toContain("Send me a sign-in link");
  });

  it("?sent=1 renders the generic success page", async () => {
    const res = await app.request("/login/magic?sent=1");
    expect(res.status).toBe(200);
    const html = await res.text();
    expect(html).toContain("Check your inbox");
    expect(html).toContain("expires in 15 minutes");
  });
});

describe("POST /login/magic", () => {
  it("always redirects to ?sent=1 regardless of whether the email exists", async () => {
    seedUser({ email: "ada@example.com" });
    const res1 = await app.request("/login/magic", {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({ email: "ada@example.com" }),
    });
    expect(res1.status).toBe(302);
    expect(res1.headers.get("location")).toContain("/login/magic?sent=1");

    const res2 = await app.request("/login/magic", {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({ email: "ghost@example.com" }),
    });
    expect(res2.status).toBe(302);
    expect(res2.headers.get("location")).toContain("/login/magic?sent=1");
  });
});

describe("GET /login/magic/callback", () => {
  it("happy path with existing user → 302 to /dashboard with a session cookie", async () => {
    const u = seedUser({ email: "ada@example.com", username: "ada" });
    const { plaintext } = seedToken({ userId: u.id, email: "ada@example.com" });

    const res = await app.request(`/login/magic/callback?token=${encodeURIComponent(plaintext)}`);
    expect(res.status).toBe(302);
    expect(res.headers.get("location")).toBe("/dashboard");
    const setCookie = res.headers.get("set-cookie") || "";
    expect(setCookie).toContain("session=");
  });

  it("happy path with no existing user → 302 to /onboarding?welcome=1 and creates account", async () => {
    const { plaintext } = seedToken({ userId: null, email: "ghost@example.com" });

    const res = await app.request(`/login/magic/callback?token=${encodeURIComponent(plaintext)}`);
    expect(res.status).toBe(302);
    expect(res.headers.get("location")).toBe("/onboarding?welcome=1");
    expect(res.headers.get("set-cookie") || "").toContain("session=");

    expect(store.users.length).toBe(1);
    expect(store.users[0]!.email).toBe("ghost@example.com");
  });

  it("invalid/garbage token → renders the dead-link page", async () => {
    const res = await app.request("/login/magic/callback?token=garbage");
    expect(res.status).toBe(200);
    const html = await res.text();
    expect(html).toContain("This link is no longer valid");
    expect(html).toContain("/login/magic");
  });

  it("no token query → renders the dead-link page", async () => {
    const res = await app.request("/login/magic/callback");
    expect(res.status).toBe(200);
    const html = await res.text();
    expect(html).toContain("This link is no longer valid");
  });

  it("expired token → renders the dead-link page", async () => {
    const u = seedUser();
    const { plaintext } = seedToken({
      userId: u.id,
      expiresAt: new Date(Date.now() - 60_000),
    });
    const res = await app.request(`/login/magic/callback?token=${encodeURIComponent(plaintext)}`);
    expect(res.status).toBe(200);
    const html = await res.text();
    expect(html).toContain("This link is no longer valid");
  });
});

// ---------------------------------------------------------------------------
// Rate limit — temporarily flip out of "test" env so the in-memory limiter
// is actually enforced.
// ---------------------------------------------------------------------------

describe("rate limit on /login/magic", () => {
  const _origNodeEnv = process.env.NODE_ENV;
  const _origBunEnv = process.env.BUN_ENV;

  afterEach(() => {
    process.env.NODE_ENV = _origNodeEnv;
    process.env.BUN_ENV = _origBunEnv;
  });

  it("returns 429 after 5 requests inside the 60s window", async () => {
    process.env.NODE_ENV = "development";
    process.env.BUN_ENV = "development";

    const headers = {
      "content-type": "application/x-www-form-urlencoded",
      "x-forwarded-for": "203.0.113.77",
    } as Record<string, string>;
    const body = () => new URLSearchParams({ email: "ghost@example.com" });

    for (let i = 0; i < 5; i++) {
      const res = await app.request("/login/magic", { method: "POST", headers, body: body() });
      expect(res.status).toBe(302);
    }
    const sixth = await app.request("/login/magic", { method: "POST", headers, body: body() });
    expect(sixth.status).toBe(429);
  });
});