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:
parent
29c96a207e
commit
26c300c357
41 changed files with 566 additions and 380 deletions
|
|
@ -38,8 +38,6 @@ export default defineEventHandler(async (event) => {
|
|||
})
|
||||
}
|
||||
|
||||
// Debug: Log token (first few chars only)
|
||||
console.log('Using Helcim token:', helcimToken.substring(0, 10) + '...')
|
||||
|
||||
// Test the connection first with native fetch
|
||||
try {
|
||||
|
|
@ -55,8 +53,7 @@ export default defineEventHandler(async (event) => {
|
|||
throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`)
|
||||
}
|
||||
|
||||
const testData = await testResponse.json()
|
||||
console.log('Connection test passed:', testData)
|
||||
await testResponse.json()
|
||||
} catch (testError) {
|
||||
console.error('Connection test failed:', testError)
|
||||
throw createError({
|
||||
|
|
@ -113,18 +110,14 @@ export default defineEventHandler(async (event) => {
|
|||
)
|
||||
|
||||
// Set the session cookie server-side
|
||||
console.log('Setting auth-token cookie for member:', member.email)
|
||||
console.log('NODE_ENV:', process.env.NODE_ENV)
|
||||
setCookie(event, 'auth-token', token, {
|
||||
httpOnly: true, // Server-only for security
|
||||
secure: false, // Don't require HTTPS in development
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24, // 24 hours
|
||||
path: '/',
|
||||
domain: undefined // Let browser set domain automatically
|
||||
})
|
||||
console.log('Cookie set successfully')
|
||||
|
||||
return {
|
||||
success: true,
|
||||
customerId: customerData.id,
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
// Initialize HelcimPay.js session
|
||||
import { requireAuth } from "../../utils/auth.js";
|
||||
|
||||
const HELCIM_API_BASE = "https://api.helcim.com/v2";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await requireAuth(event);
|
||||
const config = useRuntimeConfig(event);
|
||||
const body = await readBody(event);
|
||||
|
||||
// Debug log the request body
|
||||
console.log("Initialize payment request body:", body);
|
||||
|
||||
const helcimToken =
|
||||
config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN;
|
||||
|
|
@ -43,8 +44,6 @@ export default defineEventHandler(async (event) => {
|
|||
requestBody.orderNumber = `${body.metadata.eventId}`;
|
||||
}
|
||||
|
||||
console.log("Helcim request body:", JSON.stringify(requestBody, null, 2));
|
||||
|
||||
// Initialize HelcimPay.js session
|
||||
const response = await fetch(`${HELCIM_API_BASE}/helcim-pay/initialize`, {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
// Update customer billing address
|
||||
import { requireAuth } from '../../utils/auth.js'
|
||||
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await requireAuth(event)
|
||||
const config = useRuntimeConfig(event)
|
||||
const body = await readBody(event)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
// Verify payment token from HelcimPay.js
|
||||
import { requireAuth } from '../../utils/auth.js'
|
||||
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await requireAuth(event)
|
||||
const config = useRuntimeConfig(event)
|
||||
const body = await readBody(event)
|
||||
|
||||
|
||||
// Validate required fields
|
||||
if (!body.cardToken || !body.customerId) {
|
||||
throw createError({
|
||||
|
|
@ -14,25 +17,57 @@ export default defineEventHandler(async (event) => {
|
|||
})
|
||||
}
|
||||
|
||||
console.log('Payment verification request:', {
|
||||
customerId: body.customerId,
|
||||
cardToken: body.cardToken ? 'present' : 'missing'
|
||||
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
|
||||
|
||||
if (!helcimToken) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Helcim API token not configured'
|
||||
})
|
||||
}
|
||||
|
||||
// Verify the card token by fetching the customer's cards from Helcim
|
||||
const response = await fetch(`${HELCIM_API_BASE}/customers/${body.customerId}/cards`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'api-token': helcimToken
|
||||
}
|
||||
})
|
||||
|
||||
// Since HelcimPay.js already verified the payment and we have the card token,
|
||||
// we can just return success. The card is already associated with the customer.
|
||||
console.log('Payment already verified through HelcimPay.js, returning success')
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
console.error('Payment verification failed:', response.status, errorText)
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: 'Payment verification failed with Helcim'
|
||||
})
|
||||
}
|
||||
|
||||
const cards = await response.json()
|
||||
|
||||
// Verify the card token exists for this customer
|
||||
const cardExists = Array.isArray(cards) && cards.some(card =>
|
||||
card.cardToken === body.cardToken || card.id
|
||||
)
|
||||
|
||||
if (!cardExists && Array.isArray(cards) && cards.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'No payment method found for this customer'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
cardToken: body.cardToken,
|
||||
message: 'Payment verified successfully through HelcimPay.js'
|
||||
message: 'Payment verified with Helcim'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error verifying payment:', error)
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || 'Failed to verify payment'
|
||||
statusMessage: error.statusMessage || 'Failed to verify payment'
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue