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.
238 lines
No EOL
7.6 KiB
JavaScript
238 lines
No EOL
7.6 KiB
JavaScript
// Create a Helcim subscription
|
|
import { getHelcimPlanId, requiresPayment } from '../../config/contributions.js'
|
|
import Member from '../../models/member.js'
|
|
import { connectDB } from '../../utils/mongoose.js'
|
|
import { getSlackService } from '../../utils/slack.ts'
|
|
import { requireAuth, getPaymentBridgeMember } from '../../utils/auth.js'
|
|
import { createHelcimSubscription, generateIdempotencyKey, listHelcimCustomerTransactions } from '../../utils/helcim.js'
|
|
import { sendWelcomeEmail } from '../../utils/resend.js'
|
|
import { upsertPaymentFromHelcim } from '../../utils/payments.js'
|
|
|
|
// Function to invite member to Slack
|
|
async function inviteToSlack(member) {
|
|
try {
|
|
const slackService = getSlackService()
|
|
if (!slackService) {
|
|
console.warn('Slack service not configured, skipping invitation')
|
|
return
|
|
}
|
|
|
|
console.log(`Processing Slack invitation for ${member.email}...`)
|
|
|
|
const inviteResult = await slackService.inviteUserToSlack(
|
|
member.email,
|
|
member.name
|
|
)
|
|
|
|
if (inviteResult.success) {
|
|
const update = {}
|
|
if (inviteResult.status === 'existing_user_added_to_channel' ||
|
|
inviteResult.status === 'user_already_in_channel' ||
|
|
inviteResult.status === 'new_user_invited_to_workspace') {
|
|
update.slackInviteStatus = 'sent'
|
|
update.slackUserId = inviteResult.userId
|
|
update.slackInvited = true
|
|
} else {
|
|
update.slackInviteStatus = 'pending'
|
|
update.slackInvited = false
|
|
}
|
|
await Member.findByIdAndUpdate(
|
|
member._id,
|
|
{ $set: update },
|
|
{ runValidators: false }
|
|
)
|
|
|
|
// Send notification to vetting channel
|
|
await slackService.notifyNewMember(
|
|
member.name,
|
|
member.email,
|
|
member.circle,
|
|
member.contributionAmount,
|
|
inviteResult.status
|
|
)
|
|
|
|
console.log(`Successfully processed Slack invitation for ${member.email}: ${inviteResult.status}`)
|
|
} else {
|
|
await Member.findByIdAndUpdate(
|
|
member._id,
|
|
{ $set: { slackInviteStatus: 'failed' } },
|
|
{ runValidators: false }
|
|
)
|
|
|
|
console.error(`Failed to process Slack invitation for ${member.email}: ${inviteResult.error}`)
|
|
// Don't throw error - subscription creation should still succeed
|
|
}
|
|
} catch (error) {
|
|
console.error('Error during Slack invitation process:', error)
|
|
|
|
try {
|
|
await Member.findByIdAndUpdate(
|
|
member._id,
|
|
{ $set: { slackInviteStatus: 'failed' } },
|
|
{ runValidators: false }
|
|
)
|
|
} catch (saveError) {
|
|
console.error('Failed to update member Slack status:', saveError)
|
|
}
|
|
|
|
// Don't throw error - subscription creation should still succeed
|
|
}
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
// Membership signup completes subscription before email verify; allow the
|
|
// payment-bridge cookie set by /api/helcim/customer to satisfy auth here.
|
|
const bridgeMember = await getPaymentBridgeMember(event)
|
|
if (!bridgeMember) {
|
|
await requireAuth(event)
|
|
}
|
|
await connectDB()
|
|
const body = await validateBody(event, helcimSubscriptionSchema)
|
|
|
|
// Only send welcome email when a member transitions from pending_payment
|
|
// to active for the first time — not on tier upgrades (active → active).
|
|
const priorMember = await Member.findOne(
|
|
{ helcimCustomerId: body.customerId },
|
|
{ status: 1 }
|
|
)
|
|
const isFirstActivation = priorMember?.status === 'pending_payment'
|
|
|
|
// Check if payment is required
|
|
if (!requiresPayment(body.contributionAmount)) {
|
|
// For free tier, just update member status
|
|
const member = await Member.findOneAndUpdate(
|
|
{ helcimCustomerId: body.customerId },
|
|
{
|
|
status: 'active',
|
|
contributionAmount: body.contributionAmount,
|
|
subscriptionStartDate: new Date()
|
|
},
|
|
{ new: true }
|
|
)
|
|
|
|
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
|
|
|
await inviteToSlack(member)
|
|
if (isFirstActivation) await sendWelcomeEmail(member)
|
|
|
|
return {
|
|
success: true,
|
|
subscription: null,
|
|
member: {
|
|
id: member._id,
|
|
email: member.email,
|
|
name: member.name,
|
|
circle: member.circle,
|
|
contributionAmount: member.contributionAmount,
|
|
status: member.status
|
|
}
|
|
}
|
|
}
|
|
|
|
// Validate card token is provided
|
|
if (!body.cardToken) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Payment information is required for a paid contribution'
|
|
})
|
|
}
|
|
|
|
const cadence = body.cadence
|
|
const paymentPlanId = getHelcimPlanId(cadence)
|
|
const recurringAmount = cadence === 'annual'
|
|
? body.contributionAmount * 12
|
|
: body.contributionAmount
|
|
|
|
if (!paymentPlanId) {
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: cadence === 'annual'
|
|
? 'Annual plan id not configured'
|
|
: 'Monthly plan id not configured',
|
|
})
|
|
}
|
|
|
|
const idempotencyKey = generateIdempotencyKey()
|
|
|
|
const subscriptionPayload = {
|
|
dateActivated: new Date().toISOString().split('T')[0],
|
|
paymentPlanId: parseInt(paymentPlanId),
|
|
customerCode: body.customerCode,
|
|
recurringAmount,
|
|
paymentMethod: 'card',
|
|
}
|
|
|
|
const subscriptionData = await createHelcimSubscription(subscriptionPayload, idempotencyKey)
|
|
|
|
// Extract the first subscription from the response array
|
|
const subscription = subscriptionData.data?.[0]
|
|
if (!subscription) {
|
|
throw createError({ statusCode: 500, statusMessage: 'Subscription creation failed' })
|
|
}
|
|
|
|
const nextBillingDate = subscription.nextBillingDate
|
|
? new Date(subscription.nextBillingDate)
|
|
: null
|
|
|
|
// Update member in database
|
|
const member = await Member.findOneAndUpdate(
|
|
{ helcimCustomerId: body.customerId },
|
|
{ $set: {
|
|
contributionAmount: body.contributionAmount,
|
|
helcimSubscriptionId: subscription.id,
|
|
helcimCustomerId: body.customerId,
|
|
paymentMethod: 'card',
|
|
billingCadence: cadence,
|
|
subscriptionStartDate: new Date(),
|
|
status: 'active',
|
|
...(nextBillingDate && !Number.isNaN(nextBillingDate.getTime())
|
|
? { nextBillingDate }
|
|
: {}),
|
|
} },
|
|
{ new: true, runValidators: false }
|
|
)
|
|
|
|
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
|
|
|
try {
|
|
const txs = await listHelcimCustomerTransactions(body.customerCode)
|
|
const latestPaid = txs.find((t) => t.status === 'paid')
|
|
if (latestPaid) {
|
|
await upsertPaymentFromHelcim(member, latestPaid, {
|
|
paymentType: cadence,
|
|
sendConfirmation: true
|
|
})
|
|
}
|
|
} catch (err) {
|
|
console.error('[payments] initial charge log failed, will be picked up by reconciliation:', err?.message || err)
|
|
}
|
|
|
|
await inviteToSlack(member)
|
|
if (isFirstActivation) await sendWelcomeEmail(member)
|
|
|
|
return {
|
|
success: true,
|
|
subscription: {
|
|
subscriptionId: subscription.id,
|
|
status: subscription.status,
|
|
nextBillingDate: subscription.nextBillingDate
|
|
},
|
|
member: {
|
|
id: member._id,
|
|
email: member.email,
|
|
name: member.name,
|
|
circle: member.circle,
|
|
contributionAmount: member.contributionAmount,
|
|
status: member.status
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (error.statusCode) throw error
|
|
console.error('Error creating Helcim subscription:', error)
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'An unexpected error occurred'
|
|
})
|
|
}
|
|
}) |