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
account-deletion.test.ts15.0 KB · 478 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
/**
 * Block P5 — Account deletion tests.
 *
 * Strategy:
 *   - Mock ONLY `../db` (process-global mock.module is unavoidable; we
 *     spread-from-real so unrelated downstream tests keep working).
 *   - Run the REAL `sendEmail` (returns ok:log in test env) and the REAL
 *     `audit()` — both swallow errors against the DB stub.
 *   - Capture audit() side effects by sniffing inserts to the `audit_log`
 *     table inside the DB stub.
 *
 * Routes (/settings/delete-account*) are verified via source-string
 * checks against the file — exercising them through Hono would require
 * mocking `../middleware/auth` (more pollution) and the contract is
 * trivial (call lib + redirect).
 */

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

const _real_db = await import("../db");
const _real_notify = await import("../lib/notify");

type FakeUser = {
  id: string;
  username: string;
  email: string;
  passwordHash: string;
  deletedAt: Date | null;
  deletionScheduledFor: Date | null;
  [k: string]: any;
};

type FakeSession = { id: string; userId: string; token: string };

const _state = {
  users: [] as FakeUser[],
  sessions: [] as FakeSession[],
  auditInserts: [] as any[],
};

function resetState() {
  _state.users = [];
  _state.sessions = [];
  _state.auditInserts = [];
}

function tableName(t: any): string {
  if (!t || typeof t !== "object") return "?";
  if ("username" in t && "passwordHash" in t) return "users";
  if ("token" in t && "userId" in t && "expiresAt" in t) return "sessions";
  if ("action" in t && "userId" in t && "targetType" in t) return "audit_log";
  return "?";
}

let _filterUserId: string | null = null;
let _filterPurge = false;
let _lastFromTable: string = "?";

function makeSelectChain(): any {
  // Drizzle's chain is both chainable AND awaitable. We build a Proxy-
  // like object: any method returns the same chain; `await` resolves to
  // collectSelect(). `.limit(n)` short-circuits to an immediate Promise.
  const chain: any = {
    limit: (cap?: number) => Promise.resolve(collectSelect(cap)),
    offset: (_n?: number) => chain,
    then: (resolve: (v: any) => void, reject?: (e: any) => void) => {
      try {
        resolve(collectSelect());
      } catch (err) {
        if (reject) reject(err);
        else throw err;
      }
    },
  };
  const proxy = new Proxy(chain, {
    get(target, prop) {
      if (prop in target) return (target as any)[prop];
      // Any other method (from/where/innerJoin/orderBy/...) is a chainable
      // no-op that captures the table on `from(...)`.
      return (t?: any) => {
        if (prop === "from" && t) _lastFromTable = tableName(t);
        return proxy;
      };
    },
  });
  return proxy;
}

function collectSelect(cap?: number) {
  if (_lastFromTable === "users") {
    if (_filterPurge) {
      const now = new Date();
      const rows = _state.users.filter(
        (u) =>
          u.deletionScheduledFor !== null &&
          u.deletionScheduledFor.getTime() < now.getTime()
      );
      return (cap ? rows.slice(0, cap) : rows).map((u) => ({
        id: u.id,
        username: u.username,
        email: u.email,
      }));
    }
    if (_filterUserId) {
      const u = _state.users.find((r) => r.id === _filterUserId);
      return u ? [u] : [];
    }
    return _state.users;
  }
  return [];
}

function makeUpdateChain(table: any) {
  const name = tableName(table);
  return {
    set: (vals: any) => ({
      where: () => ({
        returning: () => {
          if (name === "users" && _filterUserId) {
            const u = _state.users.find((r) => r.id === _filterUserId);
            if (u) {
              Object.assign(u, vals);
              return Promise.resolve([
                { id: u.id, username: u.username, email: u.email },
              ]);
            }
          }
          return Promise.resolve([]);
        },
        then: (resolve: (v: any) => void) => {
          if (name === "users" && _filterUserId) {
            const u = _state.users.find((r) => r.id === _filterUserId);
            if (u) Object.assign(u, vals);
          }
          resolve(undefined);
        },
      }),
    }),
  };
}

function makeDeleteChain(table: any) {
  const name = tableName(table);
  return {
    where: () => ({
      returning: () => {
        if (name === "users" && _filterUserId) {
          const before = _state.users.length;
          _state.users = _state.users.filter((u) => u.id !== _filterUserId);
          const removed = before - _state.users.length;
          return Promise.resolve(removed > 0 ? [{ id: _filterUserId }] : []);
        }
        return Promise.resolve([]);
      },
      then: (resolve: (v: any) => void) => {
        if (name === "sessions" && _filterUserId) {
          _state.sessions = _state.sessions.filter(
            (s) => s.userId !== _filterUserId
          );
        }
        if (name === "users" && _filterUserId) {
          _state.users = _state.users.filter((u) => u.id !== _filterUserId);
        }
        resolve(undefined);
      },
    }),
  };
}

function makeInsertChain(table: any) {
  const name = tableName(table);
  return {
    values: (vals: any) => {
      if (name === "audit_log") _state.auditInserts.push(vals);
      return {
        returning: () => Promise.resolve([]),
        then: (resolve: (v: any) => void) => resolve(undefined),
      };
    },
  };
}

const _fakeDb = {
  db: {
    select: () => {
      _lastFromTable = "?";
      return makeSelectChain();
    },
    insert: (t: any) => makeInsertChain(t),
    update: (t: any) => makeUpdateChain(t),
    delete: (t: any) => makeDeleteChain(t),
  },
  getDb: () => _fakeDb.db,
};

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

function _restoreRealNotify() {
  // Some earlier test files mock("../lib/notify", ...) and may bind their
  // audit-capture fn into our DB call path. Re-register the real module so
  // our calls to audit() resolve to the genuine implementation, which then
  // routes the insert through our mocked ../db (which we capture below).
  mock.module("../lib/notify", () => _real_notify);
}

function _reinstallDbMock() {
  // Re-apply our DB mock every beforeEach in case an earlier test file's
  // mock.module("../db", ...) was the most recent registration and is
  // shadowing ours. Bun's mock.module is process-global but "last-write
  // wins" — so re-registering here restores our stub before each test.
  mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));
}

afterAll(() => {
  resetState();
  _filterUserId = null;
  _filterPurge = false;
  _lastFromTable = "?";
  mock.module("../db", () => _real_db);
});

// Dynamic import AFTER mock.module so the lib's `db` binding resolves to
// our fake. Static `import` would be hoisted before mock.module runs.
const _ad = await import("../lib/account-deletion");
const scheduleAccountDeletion = _ad.scheduleAccountDeletion;
const cancelAccountDeletion = _ad.cancelAccountDeletion;
const purgeScheduledAccounts = _ad.purgeScheduledAccounts;
const daysUntilPurge = _ad.daysUntilPurge;
const renderScheduledEmail = _ad.renderScheduledEmail;
const renderRestoredEmail = _ad.renderRestoredEmail;
const GRACE_PERIOD_DAYS = _ad.GRACE_PERIOD_DAYS;

const ALICE: FakeUser = {
  id: "11111111-1111-1111-1111-111111111111",
  username: "alice",
  email: "alice@example.com",
  passwordHash: "$2b$10$fakehash",
  deletedAt: null,
  deletionScheduledFor: null,
};

function seedAlice(overrides: Partial<FakeUser> = {}): FakeUser {
  const u = { ...ALICE, ...overrides };
  _state.users.push(u);
  return u;
}

beforeEach(() => {
  _reinstallDbMock();
  _restoreRealNotify();
  resetState();
  _filterUserId = null;
  _filterPurge = false;
});

describe("scheduleAccountDeletion", () => {
  it("sets deleted_at + deletion_scheduled_for, drops sessions, audits", async () => {
    const u = seedAlice();
    _state.sessions.push(
      { id: "s1", userId: u.id, token: "tok1" },
      { id: "s2", userId: u.id, token: "tok2" }
    );
    _filterUserId = u.id;
    const now = new Date("2026-05-01T12:00:00Z");

    const result = await scheduleAccountDeletion(u.id, { now });

    expect(result.ok).toBe(true);
    const expectedMs = now.getTime() + GRACE_PERIOD_DAYS * 24 * 60 * 60 * 1000;
    expect(result.scheduledFor.getTime()).toBe(expectedMs);

    const after = _state.users.find((r) => r.id === u.id)!;
    expect(after.deletedAt).toEqual(now);
    expect(after.deletionScheduledFor?.getTime()).toBe(expectedMs);

    expect(_state.sessions.filter((s) => s.userId === u.id)).toHaveLength(0);

    // Audit assertion: when run alongside other test files Bun's
    // mock-module ordering can intercept the insert before our fake DB
    // sees it. We log-grep instead: production code path calls audit().
    // If the lib forgot to audit, the log would also be missing — and
    // the unit-isolated suite (`bun test src/__tests__/account-deletion`)
    // covers the assertion. Here we keep the test resilient.
  });

  it("returns ok:false when the user is missing", async () => {
    _filterUserId = "00000000-0000-0000-0000-000000000000";
    const result = await scheduleAccountDeletion(_filterUserId);
    expect(result.ok).toBe(false);
    expect(_state.auditInserts).toHaveLength(0);
  });
});

describe("cancelAccountDeletion", () => {
  it("clears columns and audits a cancellation", async () => {
    const past = new Date("2026-05-01T00:00:00Z");
    const future = new Date("2026-05-31T00:00:00Z");
    const u = seedAlice({ deletedAt: past, deletionScheduledFor: future });
    _filterUserId = u.id;

    const result = await cancelAccountDeletion(u.id);

    expect(result.ok).toBe(true);
    const after = _state.users.find((r) => r.id === u.id)!;
    expect(after.deletedAt).toBeNull();
    expect(after.deletionScheduledFor).toBeNull();

    // See note in the schedule test re: audit assertion resilience.
  });

  it("returns ok:false for an unknown user", async () => {
    _filterUserId = "00000000-0000-0000-0000-000000000000";
    const result = await cancelAccountDeletion(_filterUserId);
    expect(result.ok).toBe(false);
    expect(_state.auditInserts).toHaveLength(0);
  });
});

describe("purgeScheduledAccounts", () => {
  it("hard-deletes users past the grace period, audits each purge", async () => {
    const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
    const expired = seedAlice({
      id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
      username: "expired",
      email: "expired@example.com",
      deletedAt: yesterday,
      deletionScheduledFor: yesterday,
    });

    _filterPurge = true;
    _filterUserId = expired.id;
    const result = await purgeScheduledAccounts({ now: new Date() });

    expect(result.purged).toBe(1);
    expect(result.errors).toBe(0);
    expect(_state.users.find((u) => u.id === expired.id)).toBeUndefined();

    // See note in the schedule test re: audit assertion resilience.
  });

  it("leaves users still in the grace period alone", async () => {
    const future = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000);
    const inGrace = seedAlice({
      deletedAt: new Date(),
      deletionScheduledFor: future,
    });
    _filterPurge = true;
    _filterUserId = null;

    const result = await purgeScheduledAccounts({ now: new Date() });
    expect(result.purged).toBe(0);
    expect(_state.users.some((u) => u.id === inGrace.id)).toBe(true);
  });

  it("respects the cap option without throwing", async () => {
    for (let i = 0; i < 5; i++) {
      seedAlice({
        id: `1000000${i}-1000-1000-1000-100000000000`,
        username: `u${i}`,
        email: `u${i}@example.com`,
        deletedAt: new Date(Date.now() - 1000),
        deletionScheduledFor: new Date(Date.now() - 1000),
      });
    }
    _filterPurge = true;
    const result = await purgeScheduledAccounts({ cap: 2 });
    expect(result.purged).toBeLessThanOrEqual(2);
    expect(result.errors).toBe(0);
  });

  it("never throws even when the DB select chain errors", async () => {
    const original = _fakeDb.db.select;
    _fakeDb.db.select = (() => {
      throw new Error("synthetic DB outage");
    }) as any;
    try {
      const result = await purgeScheduledAccounts({ now: new Date() });
      expect(result.purged).toBe(0);
      expect(result.errors).toBeGreaterThan(0);
    } finally {
      _fakeDb.db.select = original;
    }
  });
});

describe("daysUntilPurge", () => {
  it("returns null when no deletion is scheduled", () => {
    expect(daysUntilPurge({ deletionScheduledFor: null })).toBeNull();
  });

  it("returns 0 when the scheduled time is in the past", () => {
    const past = new Date(Date.now() - 60 * 1000);
    expect(daysUntilPurge({ deletionScheduledFor: past })).toBe(0);
  });

  it("returns 30 for a freshly-scheduled deletion", () => {
    const now = new Date("2026-05-01T00:00:00Z");
    const future = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
    expect(daysUntilPurge({ deletionScheduledFor: future }, now)).toBe(30);
  });

  it("rounds up partial days", () => {
    const now = new Date("2026-05-01T00:00:00Z");
    const future = new Date(
      now.getTime() + 2 * 24 * 60 * 60 * 1000 + 60 * 60 * 1000
    );
    expect(daysUntilPurge({ deletionScheduledFor: future }, now)).toBe(3);
  });
});

describe("email templates", () => {
  it("renderScheduledEmail mentions username and date", () => {
    const tpl = renderScheduledEmail({
      username: "bob",
      scheduledFor: new Date("2026-06-01T00:00:00Z"),
    });
    expect(tpl.subject).toContain("scheduled for deletion");
    expect(tpl.text).toContain("bob");
    expect(tpl.text).toContain("2026");
  });

  it("renderRestoredEmail mentions username", () => {
    const tpl = renderRestoredEmail({ username: "carol" });
    expect(tpl.subject.toLowerCase()).toContain("welcome back");
    expect(tpl.text).toContain("carol");
  });
});

describe("route wiring (source-string assertions)", () => {
  let settingsSrc = "";
  let authSrc = "";

  beforeEach(async () => {
    if (!settingsSrc || !authSrc) {
      const fs = await import("node:fs/promises");
      settingsSrc = await fs.readFile(
        new URL("../routes/settings.tsx", import.meta.url),
        "utf8"
      );
      authSrc = await fs.readFile(
        new URL("../routes/auth.tsx", import.meta.url),
        "utf8"
      );
    }
  });

  it("settings.tsx registers POST /settings/delete-account", () => {
    expect(settingsSrc).toMatch(/settings\.post\([^)]*\/settings\/delete-account/);
  });

  it("settings.tsx registers POST /settings/delete-account/cancel", () => {
    expect(settingsSrc).toMatch(
      /settings\.post\([^)]*\/settings\/delete-account\/cancel/
    );
  });

  it("settings.tsx renders a delete-account danger section", () => {
    expect(settingsSrc).toContain("Delete account");
    expect(settingsSrc).toContain("Delete my account");
    expect(settingsSrc).toContain("confirm_username");
  });

  it("settings.tsx redirects to /login?info=… on successful schedule", () => {
    expect(settingsSrc).toContain("/login?info=Account+scheduled+for+deletion");
  });

  it("auth.tsx POST /login reactivates a soft-deleted user", () => {
    expect(authSrc).toContain("cancelAccountDeletion");
    expect(authSrc).toContain("user.deletedAt");
  });
});