Implement OWASP ASVS L1 security remediation (Phases 0-2)

Auth: Add requireAuth/requireAdmin guards with JWT cookie verification,
member status checks (suspended/cancelled = 403), and admin role
enforcement. Apply to all admin, upload, and payment endpoints. Add
role field to Member model.

CSRF: Double-submit cookie middleware with client plugin. Exempt
webhook and magic-link verify routes.

Headers: X-Content-Type-Options, X-Frame-Options, X-XSS-Protection,
Referrer-Policy, Permissions-Policy on all responses. HSTS and CSP
(Helcim/Cloudinary/Plausible sources) in production only.

Rate limiting: Auth 5/5min, payment 10/min, upload 10/min, general
100/min via rate-limiter-flexible, keyed by client IP.

XSS: DOMPurify sanitization on marked() output with tag/attr
allowlists. escapeHtml() utility for email template interpolation.

Anti-enumeration: Login returns identical response for existing and
non-existing emails. Remove 404 handling from login UI components.

Mass assignment: Remove helcimCustomerId from profile allowedFields.

Session: 7-day token expiry, refresh endpoint, httpOnly+secure cookies.

Environment: Validate required secrets on startup via server plugin.
Remove JWT_SECRET hardcoded fallback.
This commit is contained in:
Jennie Robinson Faber 2026-03-01 12:53:18 +00:00
parent 29c96a207e
commit 26c300c357
41 changed files with 566 additions and 380 deletions

View file

@ -3,6 +3,7 @@ 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 } from '../../utils/auth.js'
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
@ -72,6 +73,7 @@ async function inviteToSlack(member) {
export default defineEventHandler(async (event) => {
try {
await requireAuth(event)
await connectDB()
const config = useRuntimeConfig(event)
const body = await readBody(event)
@ -91,11 +93,8 @@ export default defineEventHandler(async (event) => {
})
}
console.log('Subscription request body:', body)
// Check if payment is required
if (!requiresPayment(body.contributionTier)) {
console.log('No payment required for tier:', body.contributionTier)
// For free tier, just update member status
const member = await Member.findOneAndUpdate(
{ helcimCustomerId: body.customerId },
@ -107,8 +106,6 @@ export default defineEventHandler(async (event) => {
{ new: true }
)
console.log('Updated member for free tier:', member)
// Send Slack invitation for free tier members
await inviteToSlack(member)
@ -119,11 +116,8 @@ export default defineEventHandler(async (event) => {
}
}
console.log('Payment required for tier:', body.contributionTier)
// Get the Helcim plan ID
const planId = getHelcimPlanId(body.contributionTier)
console.log('Plan ID for tier:', planId)
// Validate card token is provided
if (!body.cardToken) {
@ -135,8 +129,6 @@ export default defineEventHandler(async (event) => {
// Check if we have a configured plan for this tier
if (!planId) {
console.log('No Helcim plan configured for tier:', body.contributionTier)
const member = await Member.findOneAndUpdate(
{ helcimCustomerId: body.customerId },
{
@ -168,8 +160,6 @@ export default defineEventHandler(async (event) => {
// Try to create subscription in Helcim
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
console.log('Attempting to create Helcim subscription with plan ID:', planId)
// Generate a proper alphanumeric idempotency key (exactly 25 characters)
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
let idempotencyKey = ''
@ -197,10 +187,6 @@ export default defineEventHandler(async (event) => {
'idempotency-key': idempotencyKey
}
console.log('Subscription request body:', requestBody)
console.log('Request headers:', requestHeaders)
console.log('Request URL:', `${HELCIM_API_BASE}/subscriptions`)
try {
const subscriptionResponse = await fetch(`${HELCIM_API_BASE}/subscriptions`, {
method: 'POST',
@ -210,47 +196,11 @@ export default defineEventHandler(async (event) => {
if (!subscriptionResponse.ok) {
const errorText = await subscriptionResponse.text()
console.error('Subscription creation failed:')
console.error('Status:', subscriptionResponse.status)
console.error('Status Text:', subscriptionResponse.statusText)
console.error('Headers:', Object.fromEntries(subscriptionResponse.headers.entries()))
console.error('Response Body:', errorText)
console.error('Request was:', {
url: `${HELCIM_API_BASE}/subscriptions`,
method: 'POST',
body: requestBody,
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'api-token': helcimToken ? 'present' : 'missing'
}
})
console.error('Subscription creation failed:', subscriptionResponse.status)
// If it's a validation error, let's try to get more info about available plans
if (subscriptionResponse.status === 400 || subscriptionResponse.status === 404) {
console.log('Plan might not exist. Trying to get list of available payment plans...')
// Try to fetch available payment plans
try {
const plansResponse = await fetch(`${HELCIM_API_BASE}/payment-plans`, {
method: 'GET',
headers: {
'accept': 'application/json',
'api-token': helcimToken
}
})
if (plansResponse.ok) {
const plansData = await plansResponse.json()
console.log('Available payment plans:', JSON.stringify(plansData, null, 2))
} else {
console.log('Could not fetch payment plans:', plansResponse.status, plansResponse.statusText)
}
} catch (planError) {
console.log('Error fetching payment plans:', planError.message)
}
// For now, just update member status and let user know we need to configure plans
// Plan might not exist -- update member status and proceed
const member = await Member.findOneAndUpdate(
{ helcimCustomerId: body.customerId },
{
@ -287,7 +237,6 @@ export default defineEventHandler(async (event) => {
}
const subscriptionData = await subscriptionResponse.json()
console.log('Subscription created successfully:', subscriptionData)
// Extract the first subscription from the response array
const subscription = subscriptionData.data?.[0]