feat(launch): security and correctness fixes for 2026-05-01 launch
Day-of-launch deep-dive audit and remediation. 11 issues fixed across security, correctness, and reliability. Tests: 698 → 758 passing (+60), 0 failing, 2 skipped. CRITICAL (security) Fix #1 — HELCIM_API_TOKEN removed from runtimeConfig.public; dead useHelcim.js deleted. Production token MUST BE ROTATED post-deploy (was previously exposed in window.__NUXT__ payload). Fix #2 — /api/helcim/customer gated with origin check + per-IP/email rate limit + magic-link email verification (replaces unauthenticated setAuthCookie). Adds payment-bridge token for paid-tier signup so users can complete Helcim checkout before email verify. New utils: server/utils/{magicLink,rateLimit}.js. UX: signup success copy now prompts user to check email. Fix #3 — /api/events/[id]/payment deleted (dead code with unauth member-spoof bypass — processHelcimPayment was a permanent stub). Removes processHelcimPayment export and eventPaymentSchema. Fix #4 — /api/helcim/initialize-payment re-derives ticket amount server-side via calculateTicketPrice and calculateSeriesTicketPrice. Adds new series_ticket metadata type (was being shoved through event_ticket with seriesId in metadata.eventId). Fix #5 — /api/helcim/customer upgrades existing status:guest members in place rather than rejecting with 409. Lowercases email at lookup; preserves _id so prior event registrations stay linked. HIGH (correctness / reliability) Fix #6 — Daily reconciliation cron via Netlify scheduled function (@daily). New: netlify.toml, netlify/functions/reconcile-payments.mjs, server/api/internal/reconcile-payments.post.js. Shared-secret auth via NUXT_RECONCILE_TOKEN env var. Inline 3-retry exponential backoff on Helcim transactions API. Fix #7 — validateBeforeSave: false on event subdoc saves (waitlist endpoints) to dodge legacy location validators. Fix #8 — /api/series/[id]/tickets/purchase always upserts a guest Member when caller is unauthenticated, mirrors event-ticket flow byte-for-byte. SeriesPassPurchase.vue adds guest-account hint and client auth refresh on signedIn:true response. Fix #9 — /api/members/cancel-subscription leaves status active per ratified bylaws (was pending_payment). Adds lastCancelledAt audit field on Member model. Indirectly fixes false-positive detectStuckPendingPayment admin alert for cancelled members. Fix #10 — /api/auth/verify uses validateBody with strict() Zod schema (verifyMagicLinkSchema, max 2000 chars). Fix #11 — 8 vitest cases for cancel-subscription handler (was uncovered). Specs and audit at docs/superpowers/specs/2026-04-25-fix-*.md and docs/superpowers/plans/2026-04-25-launch-readiness-fixes.md. LAUNCH_READINESS.md updated with new test count, 3 deploy-time tasks (rotate Helcim token, set NUXT_RECONCILE_TOKEN, verify Netlify scheduled function), and Fixed-2026-04-25 fix log.
This commit is contained in:
parent
0f2f1d1cbf
commit
208638e374
37 changed files with 1980 additions and 340 deletions
269
tests/server/api/reconcile-payments-route.test.js
Normal file
269
tests/server/api/reconcile-payments-route.test.js
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
import Member from '../../../server/models/member.js'
|
||||
import Payment from '../../../server/models/payment.js'
|
||||
import { listHelcimCustomerTransactions } from '../../../server/utils/helcim.js'
|
||||
import { upsertPaymentFromHelcim } from '../../../server/utils/payments.js'
|
||||
import reconcileHandler from '../../../server/api/internal/reconcile-payments.post.js'
|
||||
import { createMockEvent } from '../helpers/createMockEvent.js'
|
||||
|
||||
vi.mock('../../../server/models/member.js', () => ({
|
||||
default: { find: vi.fn() }
|
||||
}))
|
||||
vi.mock('../../../server/models/payment.js', () => ({
|
||||
default: { findOne: vi.fn() }
|
||||
}))
|
||||
vi.mock('../../../server/utils/mongoose.js', () => ({ connectDB: vi.fn() }))
|
||||
vi.mock('../../../server/utils/helcim.js', () => ({
|
||||
listHelcimCustomerTransactions: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../server/utils/payments.js', () => ({
|
||||
upsertPaymentFromHelcim: vi.fn()
|
||||
}))
|
||||
|
||||
// Override useRuntimeConfig from setup.js for these tests
|
||||
const RECONCILE_TOKEN = 'test-reconcile-secret-32-characters-long-xx'
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('useRuntimeConfig', () => ({
|
||||
jwtSecret: 'test-jwt-secret',
|
||||
helcimApiToken: 'test-helcim-token',
|
||||
reconcileToken: RECONCILE_TOKEN
|
||||
}))
|
||||
})
|
||||
|
||||
function leanResolver(value) {
|
||||
return { lean: vi.fn().mockResolvedValue(value) }
|
||||
}
|
||||
|
||||
describe('POST /api/internal/reconcile-payments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('rejects requests without the shared-secret token', async () => {
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments'
|
||||
})
|
||||
|
||||
await expect(reconcileHandler(event)).rejects.toMatchObject({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Unauthorized'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects requests with the wrong token', async () => {
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': 'not-the-right-secret' }
|
||||
})
|
||||
|
||||
await expect(reconcileHandler(event)).rejects.toMatchObject({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Unauthorized'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects when reconcileToken is not configured on the server', async () => {
|
||||
vi.stubGlobal('useRuntimeConfig', () => ({
|
||||
jwtSecret: 'test-jwt-secret',
|
||||
helcimApiToken: 'test-helcim-token',
|
||||
reconcileToken: ''
|
||||
}))
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': 'anything' }
|
||||
})
|
||||
|
||||
await expect(reconcileHandler(event)).rejects.toMatchObject({
|
||||
statusCode: 401
|
||||
})
|
||||
})
|
||||
|
||||
it('queries members with helcimCustomerId and returns a summary', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{
|
||||
_id: 'm1',
|
||||
email: 'a@example.com',
|
||||
helcimCustomerId: 'cust-1',
|
||||
helcimSubscriptionId: 'sub-1',
|
||||
billingCadence: 'monthly'
|
||||
}
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([
|
||||
{ id: 'tx-paid', status: 'paid', amount: 10, currency: 'CAD' },
|
||||
{ id: 'tx-other', status: 'other', amount: 0, currency: 'CAD' },
|
||||
{ id: 'tx-failed', status: 'failed', amount: 10, currency: 'CAD' }
|
||||
])
|
||||
upsertPaymentFromHelcim.mockResolvedValueOnce({ created: true, payment: { _id: 'p1' } })
|
||||
upsertPaymentFromHelcim.mockResolvedValueOnce({ created: false, payment: { _id: 'p2' } })
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
|
||||
const result = await reconcileHandler(event)
|
||||
|
||||
// Verify the query shape: filter by helcimCustomerId existence + projection
|
||||
expect(Member.find).toHaveBeenCalledWith(
|
||||
{ helcimCustomerId: { $exists: true, $ne: null } },
|
||||
expect.objectContaining({
|
||||
helcimCustomerId: 1,
|
||||
helcimSubscriptionId: 1,
|
||||
billingCadence: 1
|
||||
})
|
||||
)
|
||||
|
||||
// upsert called for paid + failed (status='other' is skipped)
|
||||
expect(upsertPaymentFromHelcim).toHaveBeenCalledTimes(2)
|
||||
|
||||
expect(result).toMatchObject({
|
||||
membersScanned: 1,
|
||||
txExamined: 3,
|
||||
created: 1,
|
||||
existed: 1,
|
||||
skipped: 1,
|
||||
memberErrors: 0,
|
||||
apply: true
|
||||
})
|
||||
})
|
||||
|
||||
it('does NOT pass sendConfirmation: true (no duplicate confirmation emails)', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([
|
||||
{ id: 'tx-paid', status: 'paid', amount: 10, currency: 'CAD' }
|
||||
])
|
||||
upsertPaymentFromHelcim.mockResolvedValue({ created: true, payment: { _id: 'p1' } })
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
await reconcileHandler(event)
|
||||
|
||||
// The cron must not pass sendConfirmation. Either no opts or sendConfirmation falsy.
|
||||
const opts = upsertPaymentFromHelcim.mock.calls[0][2]
|
||||
if (opts) {
|
||||
expect(opts.sendConfirmation).toBeFalsy()
|
||||
}
|
||||
})
|
||||
|
||||
it('continues iterating when listHelcimCustomerTransactions throws for one member', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' },
|
||||
{ _id: 'm2', helcimCustomerId: 'cust-2' },
|
||||
{ _id: 'm3', helcimCustomerId: 'cust-3' }
|
||||
]))
|
||||
// m1 succeeds first try, m2 fails all 3 retries, m3 succeeds first try.
|
||||
listHelcimCustomerTransactions
|
||||
.mockResolvedValueOnce([{ id: 'tx1', status: 'paid', amount: 5 }])
|
||||
.mockRejectedValueOnce(new Error('helcim 503'))
|
||||
.mockRejectedValueOnce(new Error('helcim 503'))
|
||||
.mockRejectedValueOnce(new Error('helcim 503'))
|
||||
.mockResolvedValueOnce([{ id: 'tx3', status: 'paid', amount: 7 }])
|
||||
upsertPaymentFromHelcim.mockResolvedValue({ created: true, payment: { _id: 'p' } })
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
const promise = reconcileHandler(event)
|
||||
// Drain m2's exponential backoff (250 + 500 + 1000ms)
|
||||
await vi.advanceTimersByTimeAsync(2000)
|
||||
const result = await promise
|
||||
|
||||
expect(result.membersScanned).toBe(3)
|
||||
expect(result.memberErrors).toBe(1)
|
||||
expect(result.created).toBe(2) // m1 + m3 succeeded
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('retries transient Helcim errors with exponential backoff (3 attempts)', async () => {
|
||||
vi.useFakeTimers()
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions
|
||||
.mockRejectedValueOnce(new Error('boom 1'))
|
||||
.mockRejectedValueOnce(new Error('boom 2'))
|
||||
.mockResolvedValueOnce([{ id: 'tx-paid', status: 'paid', amount: 9 }])
|
||||
upsertPaymentFromHelcim.mockResolvedValue({ created: true, payment: { _id: 'p1' } })
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
const promise = reconcileHandler(event)
|
||||
// Advance through the 250ms + 500ms backoff windows
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
const result = await promise
|
||||
|
||||
expect(listHelcimCustomerTransactions).toHaveBeenCalledTimes(3)
|
||||
expect(result.memberErrors).toBe(0)
|
||||
expect(result.created).toBe(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('counts memberErrors when all 3 retry attempts fail', async () => {
|
||||
vi.useFakeTimers()
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockRejectedValue(new Error('persistent 503'))
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
const promise = reconcileHandler(event)
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
const result = await promise
|
||||
|
||||
expect(listHelcimCustomerTransactions).toHaveBeenCalledTimes(3)
|
||||
expect(result.memberErrors).toBe(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('honors ?apply=false dry-run mode (Payment.findOne, no upsert)', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([
|
||||
{ id: 'tx-existing', status: 'paid', amount: 10 },
|
||||
{ id: 'tx-new', status: 'paid', amount: 12 }
|
||||
])
|
||||
Payment.findOne
|
||||
.mockResolvedValueOnce({ _id: 'p-existing' })
|
||||
.mockResolvedValueOnce(null)
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments?apply=false',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
const result = await reconcileHandler(event)
|
||||
|
||||
expect(upsertPaymentFromHelcim).not.toHaveBeenCalled()
|
||||
expect(Payment.findOne).toHaveBeenCalledTimes(2)
|
||||
expect(result).toMatchObject({
|
||||
apply: false,
|
||||
created: 1, // would-create
|
||||
existed: 1
|
||||
})
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue