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
email-verification.test.ts17.5 KB · 527 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
/**
 * Block P2 — email verification + welcome email tests.
 *
 * We stub `../db` via `mock.module` (K1 spread-from-real pattern) so the
 * lib's drizzle calls land on an in-memory fake instead of Neon. The email
 * sender is swapped out via the lib's `__setEmailForTests` test seam.
 *
 * Bun 1.3's `bun test` shares a single module registry across every test
 * file in a run and `mock.restore()` does NOT un-mock `mock.module(...)`
 * registrations. To stay neighbourly:
 *   - we capture the real `../db` module before overriding so unrelated
 *     downstream tests can fall back to it via the spread;
 *   - we re-install our mock in `beforeEach` so an earlier test file's
 *     `mock.module("../db", ...)` doesn't shadow ours mid-run;
 *   - we restore the real DB module in `afterAll` so the next file's
 *     suite sees the prod contract again.
 */

import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
import { Hono } from "hono";
import { createHash } from "node:crypto";

// Capture the real `../db` module so we can spread-from-real and so we
// can restore it in `afterAll` for downstream test files.
const _real_db = await import("../db");

// ---------------------------------------------------------------------------
// Fake DB — narrowly scoped to what `email-verification.ts` + the route call.
// ---------------------------------------------------------------------------

interface FakeUser {
  id: string;
  username: string;
  email: string;
  emailVerifiedAt: Date | null;
}

interface FakeToken {
  id: string;
  userId: string;
  email: string;
  tokenHash: string;
  expiresAt: Date;
  usedAt: Date | null;
  createdAt: Date;
}

const _state = {
  users: [] as FakeUser[],
  tokens: [] as FakeToken[],
  _lastFromTable: "" as "users" | "tokens" | "",
};

function resetState() {
  _state.users = [];
  _state.tokens = [];
  _state._lastFromTable = "";
}

function tableName(t: any): "users" | "tokens" | "" {
  if (!t || typeof t !== "object") return "";
  if ("emailVerifiedAt" in t && "passwordHash" in t) return "users";
  if ("emailVerifiedAt" in t && "username" in t) return "users";
  if ("tokenHash" in t && "expiresAt" in t && "email" in t) return "tokens";
  return "";
}

let _nextWhereFilter: ((row: any) => boolean) | null = null;
function setNextWhereFilter(fn: (row: any) => boolean) {
  _nextWhereFilter = fn;
}

// The drizzle chain is awaited two ways in code we proxy through:
//   await db.select(...).from(...).where(...).limit(N)
//   await db.select(...).from(...).where(...)              // no limit
// We support both by exposing both `.limit()` AND a thenable on the chain
// itself. The thenable yields the same shape `.limit(N)` would, with
// N=Infinity (no cap) — that's the convention drizzle uses for awaited
// chains without an explicit limit.
function resolveSelect(n: number = Infinity): any[] {
  const rows =
    _state._lastFromTable === "users"
      ? _state.users
      : _state._lastFromTable === "tokens"
        ? _state.tokens
        : [];
  const filtered = _nextWhereFilter ? rows.filter(_nextWhereFilter) : rows;
  _nextWhereFilter = null;
  return filtered.slice(0, n);
}

// We model the drizzle chain as a function-target Proxy that:
//   - returns itself for any chained method (`.from`, `.where`,
//     `.orderBy`, `.leftJoin`, `.innerJoin`, etc.) so chain calls compose;
//   - exposes a `then` that resolves to the current row array, making
//     `await selectChain` work without an explicit `.limit()`;
//   - exposes `.limit(N)` for callers that DO cap the row count.
//
// The proxy is built on a function target rather than `{}` so the
// resulting object reads as a thenable to V8's await machinery (some
// edge cases with `{}` + `then` were observed where the runtime read
// `then` through a different path and ignored it). Function targets
// always present a clean own-property `then` slot.
function makeSelectChain(): any {
  function chainFn() {}
  const handler: ProxyHandler<any> = {
    get(_t, prop, receiver) {
      if (prop === "then") {
        // Standard thenable contract: `(resolve, reject) => …`. We
        // resolve synchronously since the fake never actually waits on
        // anything — V8 promotes us into a microtask anyway.
        return (resolve: (v: any[]) => void) => resolve(resolveSelect());
      }
      if (prop === "limit") {
        return (n: number) => Promise.resolve(resolveSelect(n));
      }
      if (prop === "from") {
        return (table: any) => {
          _state._lastFromTable = tableName(table);
          return receiver;
        };
      }
      // Any other method (where / orderBy / groupBy / leftJoin / innerJoin
      // / rightJoin / etc.) returns the same proxy so we keep chaining.
      // Symbols / unknown non-string keys pass through as undefined.
      if (typeof prop !== "string") return undefined;
      return () => receiver;
    },
  };
  return new Proxy(chainFn, handler);
}

const selectChain: any = makeSelectChain();

const insertChain: any = {
  values(v: any) {
    if (_state._lastFromTable === "tokens") {
      _state.tokens.push({
        id: `tok-${_state.tokens.length + 1}`,
        userId: v.userId,
        email: v.email,
        tokenHash: v.tokenHash,
        expiresAt:
          v.expiresAt instanceof Date ? v.expiresAt : new Date(v.expiresAt),
        usedAt: null,
        createdAt: new Date(),
      });
    }
    return Promise.resolve();
  },
};

const updateChain: any = {
  _pendingSet: null as any,
  set(values: any) {
    updateChain._pendingSet = values;
    return updateChain;
  },
  async where(_clause: any) {
    const target =
      _state._lastFromTable === "tokens"
        ? _state.tokens
        : _state._lastFromTable === "users"
          ? _state.users
          : [];
    const filter = _nextWhereFilter || (() => true);
    _nextWhereFilter = null;
    for (const row of target) {
      if (filter(row)) Object.assign(row, updateChain._pendingSet);
    }
  },
};

const _fakeDb = {
  db: {
    select: (_proj?: any) => {
      _state._lastFromTable = "";
      return selectChain;
    },
    insert: (t: any) => {
      _state._lastFromTable = tableName(t);
      return insertChain;
    },
    update: (t: any) => {
      _state._lastFromTable = tableName(t);
      updateChain._pendingSet = null;
      return updateChain;
    },
    delete: (_t: any) => ({ where: async () => {} }),
  },
  getDb: () => _fakeDb.db,
};

// Spread the real module first so functions like `getDb` keep working
// when downstream code paths reach for them — only the names we override
// take the fake. Same K1 pattern account-deletion.test.ts uses.
mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));

function _reinstallDbMock() {
  mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));
}

// ---------------------------------------------------------------------------
// Email recorder — installed via the lib's test seam.
// ---------------------------------------------------------------------------

interface RecordedEmail {
  to: string;
  subject: string;
  text: string;
  html?: string;
}
const _emails: RecordedEmail[] = [];
async function recordEmail(msg: RecordedEmail) {
  _emails.push({ ...msg });
  return { ok: true as const, provider: "log" as const };
}

// Load the lib AFTER mock.module so the import picks up the fake DB.
const {
  generateVerificationToken,
  hashToken,
  startEmailVerification,
  consumeVerificationToken,
  sendWelcomeEmail,
  renderVerificationEmail,
  renderWelcomeEmail,
  __setEmailForTests,
} = await import("../lib/email-verification");

const { default: emailVerificationRoutes, __resetResendRateLimitForTests } =
  await import("../routes/email-verification");
const authRoutesModule = await import("../routes/auth");
const authRoutes = authRoutesModule.default;

function buildApp() {
  const app = new Hono();
  app.route("/", emailVerificationRoutes);
  return app;
}

let _restoreEmail: ReturnType<typeof __setEmailForTests> | null = null;

beforeEach(() => {
  _reinstallDbMock();
  resetState();
  _emails.length = 0;
  __resetResendRateLimitForTests();
  _restoreEmail = __setEmailForTests(recordEmail);
});

afterAll(() => {
  if (_restoreEmail) __setEmailForTests(_restoreEmail);
  resetState();
  _emails.length = 0;
  // Restore the real DB module so downstream test files see prod semantics.
  mock.module("../db", () => _real_db);
});

// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------

describe("generateVerificationToken", () => {
  it("produces a 64-char hex plaintext and a matching sha256 hash", () => {
    const { plaintext, hash } = generateVerificationToken();
    expect(plaintext).toMatch(/^[0-9a-f]{64}$/);
    expect(hash).toMatch(/^[0-9a-f]{64}$/);
    expect(hash).toBe(createHash("sha256").update(plaintext).digest("hex"));
    expect(hashToken(plaintext)).toBe(hash);
  });

  it("returns different tokens on successive calls", () => {
    const a = generateVerificationToken();
    const b = generateVerificationToken();
    expect(a.plaintext).not.toBe(b.plaintext);
    expect(a.hash).not.toBe(b.hash);
  });
});

describe("renderVerificationEmail / renderWelcomeEmail", () => {
  it("verification email subject + html escape username", () => {
    const m = renderVerificationEmail({
      username: "<bob>",
      link: "https://example.com/verify-email?token=abc",
    });
    expect(m.subject).toBe("Confirm your email for Gluecron");
    expect(m.text).toContain("Hi <bob>");
    expect(m.html).toContain("&lt;bob&gt;");
    expect(m.html).toContain("https://example.com/verify-email?token=abc");
  });

  it("welcome email mentions all four next-step links", () => {
    const m = renderWelcomeEmail({ username: "alice" });
    expect(m.subject).toContain("Welcome to Gluecron");
    expect(m.text).toContain("Welcome aboard, alice!");
    expect(m.text).toContain("/new");
    expect(m.text).toContain("/import");
    expect(m.text).toContain("/demo");
    expect(m.text).toContain("/install");
    expect(m.html).toContain("Welcome aboard,");
  });
});

// ---------------------------------------------------------------------------
// startEmailVerification + consumeVerificationToken (DB path)
// ---------------------------------------------------------------------------

describe("startEmailVerification", () => {
  it("inserts a token row and sends a verification email", async () => {
    _state.users.push({
      id: "u1",
      username: "alice",
      email: "alice@example.com",
      emailVerifiedAt: null,
    });
    setNextWhereFilter((u: FakeUser) => u.id === "u1");
    const r = await startEmailVerification("u1", "alice@example.com");
    expect(r.ok).toBe(true);
    expect(_state.tokens.length).toBe(1);
    expect(_state.tokens[0].userId).toBe("u1");
    expect(_state.tokens[0].email).toBe("alice@example.com");
    expect(_state.tokens[0].tokenHash).toMatch(/^[0-9a-f]{64}$/);
    expect(_emails.length).toBe(1);
    expect(_emails[0].to).toBe("alice@example.com");
    expect(_emails[0].subject).toBe("Confirm your email for Gluecron");
    expect(_emails[0].text).toContain("alice");
  });
});

describe("consumeVerificationToken", () => {
  it("rejects garbage / empty input", async () => {
    expect((await consumeVerificationToken("")).ok).toBe(false);
    expect(
      (await consumeVerificationToken("not-a-real-token")).ok
    ).toBe(false);
  });

  it("happy path: marks token used + sets users.emailVerifiedAt", async () => {
    _state.users.push({
      id: "u2",
      username: "bob",
      email: "bob@example.com",
      emailVerifiedAt: null,
    });
    const { plaintext, hash } = generateVerificationToken();
    _state.tokens.push({
      id: "t-1",
      userId: "u2",
      email: "bob@example.com",
      tokenHash: hash,
      expiresAt: new Date(Date.now() + 1000 * 60 * 60),
      usedAt: null,
      createdAt: new Date(),
    });
    setNextWhereFilter(
      (t: FakeToken) =>
        t.tokenHash === hash &&
        t.usedAt === null &&
        t.expiresAt.getTime() > Date.now()
    );
    const r = await consumeVerificationToken(plaintext);
    expect(r.ok).toBe(true);
    expect(r.userId).toBe("u2");
    expect(_state.tokens[0].usedAt).toBeInstanceOf(Date);
    expect(_state.users[0].emailVerifiedAt).toBeInstanceOf(Date);
  });

  it("rejects expired tokens", async () => {
    const { plaintext, hash } = generateVerificationToken();
    _state.tokens.push({
      id: "t-2",
      userId: "u3",
      email: "expired@example.com",
      tokenHash: hash,
      expiresAt: new Date(Date.now() - 1000),
      usedAt: null,
      createdAt: new Date(),
    });
    setNextWhereFilter(
      (t: FakeToken) =>
        t.tokenHash === hash &&
        t.usedAt === null &&
        t.expiresAt.getTime() > Date.now()
    );
    const r = await consumeVerificationToken(plaintext);
    expect(r.ok).toBe(false);
  });

  it("rejects already-used tokens", async () => {
    const { plaintext, hash } = generateVerificationToken();
    _state.tokens.push({
      id: "t-3",
      userId: "u4",
      email: "used@example.com",
      tokenHash: hash,
      expiresAt: new Date(Date.now() + 1000 * 60 * 60),
      usedAt: new Date(),
      createdAt: new Date(),
    });
    setNextWhereFilter(
      (t: FakeToken) =>
        t.tokenHash === hash &&
        t.usedAt === null &&
        t.expiresAt.getTime() > Date.now()
    );
    const r = await consumeVerificationToken(plaintext);
    expect(r.ok).toBe(false);
  });
});

// ---------------------------------------------------------------------------
// sendWelcomeEmail
// ---------------------------------------------------------------------------

describe("sendWelcomeEmail", () => {
  it("sends a welcome email for the resolved user", async () => {
    _state.users.push({
      id: "u5",
      username: "carol",
      email: "carol@example.com",
      emailVerifiedAt: new Date(),
    });
    setNextWhereFilter((u: FakeUser) => u.id === "u5");
    await sendWelcomeEmail("u5");
    expect(_emails.length).toBe(1);
    expect(_emails[0].to).toBe("carol@example.com");
    expect(_emails[0].subject).toContain("Welcome to Gluecron");
    expect(_emails[0].text).toContain("carol");
  });

  it("no-ops + does not throw for unknown user", async () => {
    setNextWhereFilter(() => false);
    await sendWelcomeEmail("nope");
    expect(_emails.length).toBe(0);
  });
});

// ---------------------------------------------------------------------------
// GET /verify-email — HTTP-level
// ---------------------------------------------------------------------------

describe("GET /verify-email", () => {
  it("valid token → 302 /dashboard?verified=1 + fires welcome email", async () => {
    _state.users.push({
      id: "u6",
      username: "dave",
      email: "dave@example.com",
      emailVerifiedAt: null,
    });
    const { plaintext, hash } = generateVerificationToken();
    _state.tokens.push({
      id: "t-6",
      userId: "u6",
      email: "dave@example.com",
      tokenHash: hash,
      expiresAt: new Date(Date.now() + 1000 * 60 * 60),
      usedAt: null,
      createdAt: new Date(),
    });
    setNextWhereFilter(
      (t: FakeToken) =>
        t.tokenHash === hash &&
        t.usedAt === null &&
        t.expiresAt.getTime() > Date.now()
    );
    const app = buildApp();
    const res = await app.request(
      `/verify-email?token=${encodeURIComponent(plaintext)}`
    );
    expect(res.status).toBe(302);
    expect(res.headers.get("location")).toBe("/dashboard?verified=1");
    // Welcome email is fire-and-forget — give the microtask queue a tick.
    await new Promise((r) => setTimeout(r, 10));
    expect(_emails.some((e) => e.subject.includes("Welcome"))).toBe(true);
  });

  it("invalid token → 200 with 'Link expired' page", async () => {
    const app = buildApp();
    const res = await app.request("/verify-email?token=not-a-real-token");
    expect(res.status).toBe(200);
    const body = await res.text();
    expect(body).toContain("Link expired");
  });
});

// ---------------------------------------------------------------------------
// Rate limit smoke
// ---------------------------------------------------------------------------

describe("POST /verify-email/resend rate limit", () => {
  it("__resetResendRateLimitForTests is exported + idempotent", async () => {
    const mod = await import("../routes/email-verification");
    expect(typeof mod.__resetResendRateLimitForTests).toBe("function");
    mod.__resetResendRateLimitForTests();
    mod.__resetResendRateLimitForTests();
  });
});

// ---------------------------------------------------------------------------
// Register POST wires through to startEmailVerification
// ---------------------------------------------------------------------------

describe("POST /register → startEmailVerification wiring", () => {
  it("startEmailVerification produces a token row (the wire-up's payload)", async () => {
    _state.users.push({
      id: "u-reg",
      username: "newbie",
      email: "newbie@example.com",
      emailVerifiedAt: null,
    });
    setNextWhereFilter((u: FakeUser) => u.id === "u-reg");
    const r = await startEmailVerification("u-reg", "newbie@example.com");
    expect(r.ok).toBe(true);
    expect(_state.tokens.length).toBe(1);
    expect(_state.tokens[0].userId).toBe("u-reg");
    expect(typeof startEmailVerification).toBe("function");
  });

  it("auth.tsx /register handler imports email-verification", async () => {
    const m = await import("../lib/email-verification");
    expect(typeof m.startEmailVerification).toBe("function");
    expect(typeof m.consumeVerificationToken).toBe("function");
    expect(typeof m.sendWelcomeEmail).toBe("function");
    expect(authRoutes).toBeDefined();
  });
});