import { describe, it, expect, beforeAll } from 'vitest' import * as db from '../src/database.js' const pubkey = 'reconfirm-test-' + Date.now() const email = 'reconfirm-test-' + Date.now() + '@example.com' let token: string describe('Confirm link idempotency — already-confirmed token', () => { beforeAll(async () => { await db.migrate() }) it('creates and confirms a subscription for the first time', async () => { const sub = await db.insertSubscription(pubkey, email, 'daily') expect(sub).toBeTruthy() token = sub.key const result = await db.confirmSubscription(token) expect(result).toBeTruthy() expect(result!.sub.confirmed_at).toBeTruthy() expect(result!.alreadyConfirmed).toBe(false) }) it('returns a distinct result (not undefined) when confirming an already-confirmed token', async () => { // BUG: confirmSubscription used `WHERE confirmed_at IS NULL`, so // re-confirming an already-confirmed token matched zero rows and // the UPDATE returned nothing → parseSubscription returned undefined. // The caller then threw ActionError('invalid or expired') and the // user saw "Email not confirmed" — which is misleading. // // FIX: confirmSubscription now detects the already-confirmed case // and returns { sub, alreadyConfirmed: true } so the handler can // render an "already confirmed" info page instead of an error page. const result = await db.confirmSubscription(token) expect(result).not.toBeUndefined() expect(result!.alreadyConfirmed).toBe(true) expect(result!.sub.confirmed_at).toBeTruthy() }) it('returns undefined for a nonexistent token', async () => { const result = await db.confirmSubscription('nonexistent-token-' + Date.now()) expect(result).toBeUndefined() }) })