diff --git a/.env.example b/.env.example index 80cc0ffc..8f7fe53d 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,11 @@ EMBERLY_LICENSE_CHECKIN="true" # default. Set to false only if you run `bun run worker` as its own service. # EMBERLY_RUN_EVENT_WORKER="true" +# Who to trust for the visitor's IP address, used by rate limits. Set to +# "cloudflare" behind Cloudflare, otherwise the number of reverse proxies in +# front of the app. Cloudflare plus Traefik or nginx should use "cloudflare". +# TRUSTED_PROXY="1" + # Extra origins allowed to sign in, comma separated (e.g. custom domains) NEXTAUTH_TRUSTED_ORIGINS="" diff --git a/apps/dashboard/CHANGELOG.md b/CHANGELOG.md similarity index 99% rename from apps/dashboard/CHANGELOG.md rename to CHANGELOG.md index 7f384a39..be5cfac7 100644 --- a/apps/dashboard/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on "Keep a Changelog" and follows [Semantic Versioning](http ## [Unreleased] +## [3.2.2] - 2026-11-10 + +### Upgrading + +- **Set `TRUSTED_PROXY` if you're behind Cloudflare or more than one reverse proxy.** Rate limits now read the visitor's address only from what your own proxies set. Use `TRUSTED_PROXY=cloudflare` behind Cloudflare, or the number of reverse proxies in front of the app (the default is `1`). If it's wrong, visitors can end up sharing one rate limit. Keep the app's own port off the public internet. + +### Security + +- **Referral credits could be generated with throwaway accounts.** Credits were given at signup, with no email verification, payment or limit, and could be applied to real Stripe invoices where billing is on. A referred account now gets its credit after verifying its email. The referrer's credit comes after that account's first payment, is never more than the amount paid, needs a verified referrer, and stops after 10 rewarded referrals. Referrals between the same mailbox are refused, including plus-addressed and dotted Gmail variants. Reported by [kta1kri](https://github.com/kta1kri). +- **Rate limits trusted a header visitors can set.** Registration, password reset, resend verification, desktop sign-in, device sign-in, contact, file password and signed-out OCR limits used the first `X-Forwarded-For` value, so an attacker could change it on every request. They now use one helper that only trusts your proxies, configured with `TRUSTED_PROXY`. + ## [3.2.1] - 2026-10-27 ### Added diff --git a/apps/dashboard/app/api/auth/desktop/route.ts b/apps/dashboard/app/api/auth/desktop/route.ts index 7c0b2c0b..37f7e467 100644 --- a/apps/dashboard/app/api/auth/desktop/route.ts +++ b/apps/dashboard/app/api/auth/desktop/route.ts @@ -10,6 +10,7 @@ import { auditSuspiciousActivity, emitAuditEvent, } from '@/lib/events/audit-helper' +import { clientIp } from '@/lib/security/client-ip' const logger = loggers.auth @@ -66,10 +67,7 @@ export async function POST(req: Request) { const { emailOrUsername, password, twoFactorCode } = parsed.data // Extract IP for rate limiting and audit - const ip = - req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || - req.headers.get('x-real-ip') || - 'unknown' + const ip = clientIp(req.headers) ?? 'unknown' const failKey = `auth:desktop:fail:${ip}` // Helper: track a failed attempt and emit a security audit event at threshold 3 diff --git a/apps/dashboard/app/api/auth/password/forgot/route.ts b/apps/dashboard/app/api/auth/password/forgot/route.ts index 5dfcc920..f3dcb27e 100644 --- a/apps/dashboard/app/api/auth/password/forgot/route.ts +++ b/apps/dashboard/app/api/auth/password/forgot/route.ts @@ -8,75 +8,96 @@ import { PasswordResetEmail, sendTemplateEmail } from '@/lib/emails' import { events } from '@/lib/events' import { generateSecureToken } from '@/lib/auth/service' import { appUrl } from '@/lib/config/env' +import { clientIp } from '@/lib/security/client-ip' const requestSchema = z.object({ - email: z.string().email(), + email: z.string().email(), }) export async function POST(req: Request) { - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || '127.0.0.1' - - // Rate limit: 1 request per 10 minutes per IP - const { allowed } = await rateLimiter.check(`auth:password:forgot:${ip}`, 1, 600) - if (!allowed) { - return NextResponse.json({ error: 'Too many requests. Please try again in 10 minutes.' }, { status: 429 }) - } - - const body = await req.json().catch(() => null) - const parsed = requestSchema.safeParse(body) - - if (!parsed.success) { - return NextResponse.json({ error: 'Invalid request' }, { status: 400 }) - } - - const { email } = parsed.data - - const user = await prisma.user.findUnique({ - where: { email }, - select: { id: true, name: true, email: true }, + const ip = clientIp(req.headers) ?? 'unknown' + + // Rate limit: 1 request per 10 minutes per IP + const { allowed } = await rateLimiter.check( + `auth:password:forgot:${ip}`, + 1, + 600 + ) + if (!allowed) { + return NextResponse.json( + { error: 'Too many requests. Please try again in 10 minutes.' }, + { status: 429 } + ) + } + + const body = await req.json().catch(() => null) + const parsed = requestSchema.safeParse(body) + + if (!parsed.success) { + return NextResponse.json({ error: 'Invalid request' }, { status: 400 }) + } + + const { email } = parsed.data + + const user = await prisma.user.findUnique({ + where: { email }, + select: { id: true, name: true, email: true }, + }) + + if (!user?.email) { + // Do not reveal whether user exists + return NextResponse.json({ ok: true }) + } + + const { + token, + hashedToken, + expiresAt: expires, + } = generateSecureToken(30 * 60 * 1000) + + await prisma.user.update({ + where: { id: user.id }, + data: { + passwordResetToken: hashedToken, + passwordResetExpires: expires, + }, + }) + + const baseUrl = appUrl() + const resetUrl = `${baseUrl}/auth/reset?token=${token}&email=${encodeURIComponent(email)}` + + try { + await sendTemplateEmail({ + to: user.email, + subject: 'Reset your Emberly password', + template: PasswordResetEmail, + props: { + resetUrl, + expiresInMinutes: 30, + }, }) - - if (!user?.email) { - // Do not reveal whether user exists - return NextResponse.json({ ok: true }) - } - - const { token, hashedToken, expiresAt: expires } = generateSecureToken(30 * 60 * 1000) - - await prisma.user.update({ - where: { id: user.id }, - data: { - passwordResetToken: hashedToken, - passwordResetExpires: expires, - }, + } catch (error) { + console.error('Failed to send password reset email', error) + return NextResponse.json( + { error: 'Failed to send reset email' }, + { status: 500 } + ) + } + + // Emit auditable event (fire-and-forget) + void events + .emit('auth.password-reset-requested', { + userId: user.id, + email: user.email, + expiresAt: expires, + context: { ip: clientIp(req.headers) }, }) - - const baseUrl = appUrl() - const resetUrl = `${baseUrl}/auth/reset?token=${token}&email=${encodeURIComponent(email)}` - - try { - await sendTemplateEmail({ - to: user.email, - subject: 'Reset your Emberly password', - template: PasswordResetEmail, - props: { - resetUrl, - expiresInMinutes: 30, - }, - }) - } catch (error) { - console.error('Failed to send password reset email', error) - return NextResponse.json({ error: 'Failed to send reset email' }, { status: 500 }) - } - - // Emit auditable event (fire-and-forget) - void events.emit('auth.password-reset-requested', { - userId: user.id, - email: user.email, - expiresAt: expires, - context: { ip: req.headers.get('x-forwarded-for')?.split(',')[0] ?? undefined }, - }).catch((err) => console.error('[Events] Failed to emit auth.password-reset-requested', err)) - - return NextResponse.json({ ok: true }) + .catch((err) => + console.error( + '[Events] Failed to emit auth.password-reset-requested', + err + ) + ) + + return NextResponse.json({ ok: true }) } - diff --git a/apps/dashboard/app/api/auth/password/reset/route.ts b/apps/dashboard/app/api/auth/password/reset/route.ts index b3070c54..65adfcd4 100644 --- a/apps/dashboard/app/api/auth/password/reset/route.ts +++ b/apps/dashboard/app/api/auth/password/reset/route.ts @@ -14,6 +14,7 @@ import { import { events } from '@/lib/events' import { appUrl } from '@/lib/config/env' import { createNotification } from '@/lib/notifications' +import { clientIp } from '@/lib/security/client-ip' const requestSchema = z.object({ email: z.string().email(), @@ -22,7 +23,7 @@ const requestSchema = z.object({ }) export async function POST(req: Request) { - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || '127.0.0.1' + const ip = clientIp(req.headers) ?? 'unknown' // Rate limit: 5 attempts per 10 minutes per IP const { allowed } = await rateLimiter.check( @@ -132,7 +133,7 @@ export async function POST(req: Request) { userId: user.id, email: user.email, context: { - ip: req.headers.get('x-forwarded-for')?.split(',')[0] ?? undefined, + ip: clientIp(req.headers), }, }) .catch((err) => diff --git a/apps/dashboard/app/api/auth/register/route.ts b/apps/dashboard/app/api/auth/register/route.ts index e31ec5c4..a09b68e5 100644 --- a/apps/dashboard/app/api/auth/register/route.ts +++ b/apps/dashboard/app/api/auth/register/route.ts @@ -12,11 +12,13 @@ import { sendTemplateEmail, VerificationCodeEmail } from '@/lib/emails' import { events } from '@/lib/events' import { processReferralSignup } from '@/lib/referrals' import { generateSecureToken, generateShortCode } from '@/lib/auth/service' +import { clientIp } from '@/lib/security/client-ip' const registerSchema = z.object({ email: z.string().email(), password: z.string().min(8), - name: z.string() + name: z + .string() .min(2, 'Username must be at least 2 characters') .max(50, 'Username must be at most 50 characters') .trim() @@ -24,10 +26,7 @@ const registerSchema = z.object({ (name) => !name.includes('@'), 'Username cannot contain @ symbol (looks like an email)' ) - .refine( - (name) => !name.includes(' '), - 'Username cannot contain spaces' - ), + .refine((name) => !name.includes(' '), 'Username cannot contain spaces'), referralCode: z.string().optional(), // Referral code from query/body }) @@ -45,7 +44,7 @@ function generateUrlId() { export async function POST(req: Request) { try { // Rate limit: 5 registration attempts per minute per IP - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || 'unknown' + const ip = clientIp(req.headers) ?? 'unknown' const rateLimit = await rateLimiter.checkFixed(`register:${ip}`, 5, 60) if (!rateLimit.allowed) { return NextResponse.json( @@ -53,7 +52,9 @@ export async function POST(req: Request) { { status: 429, headers: { - 'Retry-After': String(Math.ceil((rateLimit.resetAt - Date.now()) / 1000)), + 'Retry-After': String( + Math.ceil((rateLimit.resetAt - Date.now()) / 1000) + ), 'X-RateLimit-Remaining': String(rateLimit.remaining), }, } @@ -70,10 +71,7 @@ export async function POST(req: Request) { const exists = await prisma.user.findFirst({ where: { - OR: [ - { email: body.email }, - { name: body.name }, - ] + OR: [{ email: body.email }, { name: body.name }], }, }) @@ -137,7 +135,9 @@ export async function POST(req: Request) { // Assign default Spark plan if it exists try { - const spark = await prisma.product.findFirst({ where: { slug: 'spark', active: true } }) + const spark = await prisma.product.findFirst({ + where: { slug: 'spark', active: true }, + }) if (spark) { await prisma.subscription.create({ data: { @@ -177,7 +177,10 @@ export async function POST(req: Request) { if (body.referralCode) { void (async () => { try { - const result = await processReferralSignup(user.id, body.referralCode!) + const result = await processReferralSignup( + user.id, + body.referralCode! + ) console.log(`[Referral] ${result.message}`) } catch (err) { console.error('Failed to process referral', err) @@ -186,11 +189,15 @@ export async function POST(req: Request) { } // Emit auditable account.created event (fire-and-forget) - void events.emit('account.created', { - userId: user.id, - email: user.email ?? body.email, - method: 'signup', - }).catch((err) => console.error('[Events] Failed to emit account.created', err)) + void events + .emit('account.created', { + userId: user.id, + email: user.email ?? body.email, + method: 'signup', + }) + .catch((err) => + console.error('[Events] Failed to emit account.created', err) + ) return NextResponse.json({ user: { @@ -217,4 +224,3 @@ export async function POST(req: Request) { ) } } - diff --git a/apps/dashboard/app/api/auth/resend-verification/route.ts b/apps/dashboard/app/api/auth/resend-verification/route.ts index 4506656f..5b6f2f46 100644 --- a/apps/dashboard/app/api/auth/resend-verification/route.ts +++ b/apps/dashboard/app/api/auth/resend-verification/route.ts @@ -6,120 +6,133 @@ import { z } from 'zod' import { rateLimiter } from '@/lib/cache/rate-limit' import { prisma } from '@emberly/db' import { sendTemplateEmail, VerificationCodeEmail } from '@/lib/emails' -import { generateSecureToken, generateShortCode, parseVerificationCodes } from '@/lib/auth/service' +import { + generateSecureToken, + generateShortCode, + parseVerificationCodes, +} from '@/lib/auth/service' +import { clientIp } from '@/lib/security/client-ip' const resendSchema = z.object({ - email: z.string().email(), + email: z.string().email(), }) export async function POST(req: Request) { - try { - // Rate limit: 3 resend attempts per 10 minutes per IP - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || 'unknown' - const rateLimit = await rateLimiter.checkFixed(`resend-verify:${ip}`, 3, 600) - if (!rateLimit.allowed) { - return NextResponse.json( - { error: 'Too many requests. Please try again later.' }, - { - status: 429, - headers: { - 'Retry-After': String(Math.ceil((rateLimit.resetAt - Date.now()) / 1000)), - }, - } - ) + try { + // Rate limit: 3 resend attempts per 10 minutes per IP + const ip = clientIp(req.headers) ?? 'unknown' + const rateLimit = await rateLimiter.checkFixed( + `resend-verify:${ip}`, + 3, + 600 + ) + if (!rateLimit.allowed) { + return NextResponse.json( + { error: 'Too many requests. Please try again later.' }, + { + status: 429, + headers: { + 'Retry-After': String( + Math.ceil((rateLimit.resetAt - Date.now()) / 1000) + ), + }, } + ) + } - const json = await req.json() - const body = resendSchema.parse(json) - - const user = await prisma.user.findUnique({ - where: { email: body.email }, - select: { - id: true, - name: true, - email: true, - emailVerified: true, - }, - }) - - // Always return success to prevent email enumeration - if (!user || user.emailVerified) { - return NextResponse.json({ - success: true, - message: 'If an unverified account exists with this email, a verification link has been sent.', - }) - } + const json = await req.json() + const body = resendSchema.parse(json) + + const user = await prisma.user.findUnique({ + where: { email: body.email }, + select: { + id: true, + name: true, + email: true, + emailVerified: true, + }, + }) + + // Always return success to prevent email enumeration + if (!user || user.emailVerified) { + return NextResponse.json({ + success: true, + message: + 'If an unverified account exists with this email, a verification link has been sent.', + }) + } - // Generate new verification token and short code - const { token: verificationToken, expiresAt: expiresDate } = generateSecureToken(60 * 60 * 1000) - const shortCode = generateShortCode() - - // Create verification code data - const verificationCodeData = JSON.stringify({ - code: verificationToken, - shortCode, - context: 'email-verification', - expiresAt: expiresDate.getTime(), - }) - - // Get existing codes, filter out old email-verification ones, add new - const existingUser = await prisma.user.findUnique({ - where: { id: user.id }, - select: { verificationCodes: true }, - }) - - const existingCodes = parseVerificationCodes<{ context: string }>( - existingUser?.verificationCodes ?? [] - ) - .filter((c) => c.context !== 'email-verification') - .map((c) => JSON.stringify(c)) - - await prisma.user.update({ - where: { id: user.id }, - data: { - verificationCodes: [...existingCodes, verificationCodeData], - }, - }) - - const baseUrl = appUrl() - const verifyUrl = `${baseUrl}/auth/verify-email?token=${verificationToken}` - - try { - await sendTemplateEmail({ - to: user.email!, - subject: 'Verify your Emberly email address', - template: VerificationCodeEmail, - props: { - code: shortCode, - verificationUrl: verifyUrl, - expiresInMinutes: 60, - }, - }) - } catch (err) { - console.error('Failed to send verification email', err) - return NextResponse.json( - { error: 'Failed to send verification email. Please try again.' }, - { status: 500 } - ) - } + // Generate new verification token and short code + const { token: verificationToken, expiresAt: expiresDate } = + generateSecureToken(60 * 60 * 1000) + const shortCode = generateShortCode() + + // Create verification code data + const verificationCodeData = JSON.stringify({ + code: verificationToken, + shortCode, + context: 'email-verification', + expiresAt: expiresDate.getTime(), + }) + + // Get existing codes, filter out old email-verification ones, add new + const existingUser = await prisma.user.findUnique({ + where: { id: user.id }, + select: { verificationCodes: true }, + }) + + const existingCodes = parseVerificationCodes<{ context: string }>( + existingUser?.verificationCodes ?? [] + ) + .filter((c) => c.context !== 'email-verification') + .map((c) => JSON.stringify(c)) + + await prisma.user.update({ + where: { id: user.id }, + data: { + verificationCodes: [...existingCodes, verificationCodeData], + }, + }) + + const baseUrl = appUrl() + const verifyUrl = `${baseUrl}/auth/verify-email?token=${verificationToken}` - return NextResponse.json({ - success: true, - message: 'If an unverified account exists with this email, a verification link has been sent.', - }) - } catch (error) { - if (error instanceof z.ZodError) { - return NextResponse.json( - { error: error.issues[0].message }, - { status: 400 } - ) - } + try { + await sendTemplateEmail({ + to: user.email!, + subject: 'Verify your Emberly email address', + template: VerificationCodeEmail, + props: { + code: shortCode, + verificationUrl: verifyUrl, + expiresInMinutes: 60, + }, + }) + } catch (err) { + console.error('Failed to send verification email', err) + return NextResponse.json( + { error: 'Failed to send verification email. Please try again.' }, + { status: 500 } + ) + } - console.error('Resend verification error:', error) - return NextResponse.json( - { error: 'Internal server error' }, - { status: 500 } - ) + return NextResponse.json({ + success: true, + message: + 'If an unverified account exists with this email, a verification link has been sent.', + }) + } catch (error) { + if (error instanceof z.ZodError) { + return NextResponse.json( + { error: error.issues[0].message }, + { status: 400 } + ) } -} + console.error('Resend verification error:', error) + return NextResponse.json( + { error: 'Internal server error' }, + { status: 500 } + ) + } +} diff --git a/apps/dashboard/app/api/auth/verify-email/route.ts b/apps/dashboard/app/api/auth/verify-email/route.ts index 00d74325..971d34ae 100644 --- a/apps/dashboard/app/api/auth/verify-email/route.ts +++ b/apps/dashboard/app/api/auth/verify-email/route.ts @@ -5,168 +5,186 @@ import { prisma } from '@emberly/db' import { sendTemplateEmail, WelcomeEmail } from '@/lib/emails' import { emitAuditEvent } from '@/lib/events/audit-helper' import { parseVerificationCodes } from '@/lib/auth/service' +import { creditVerifiedReferral } from '@/lib/referrals' interface VerificationCode { - code: string - shortCode?: string - context: string - expiresAt: number + code: string + shortCode?: string + context: string + expiresAt: number } async function verifyToken(token: string) { - // Find users with verification codes and check for matching token or short code - const users = await prisma.user.findMany({ - where: { - emailVerified: null, - verificationCodes: { isEmpty: false }, - }, - select: { - id: true, - email: true, - name: true, - verificationCodes: true, - }, - }) - - let matchedUser: { id: string; email: string | null; name: string | null; verificationCodes: string[] } | null = null - let matchedCode: VerificationCode | null = null - - for (const user of users) { - const codes = parseVerificationCodes(user.verificationCodes) - // Check both the full token (for URL clicks) and short code (for manual entry) - const validCode = codes.find( - (c) => - c.context === 'email-verification' && - (c.code === token || c.shortCode === token) && - c.expiresAt > Date.now() - ) - if (validCode) { - matchedUser = user - matchedCode = validCode - break - } - } - - if (!matchedUser || !matchedCode) { - return null + // Find users with verification codes and check for matching token or short code + const users = await prisma.user.findMany({ + where: { + emailVerified: null, + verificationCodes: { isEmpty: false }, + }, + select: { + id: true, + email: true, + name: true, + verificationCodes: true, + }, + }) + + let matchedUser: { + id: string + email: string | null + name: string | null + verificationCodes: string[] + } | null = null + let matchedCode: VerificationCode | null = null + + for (const user of users) { + const codes = parseVerificationCodes( + user.verificationCodes + ) + // Check both the full token (for URL clicks) and short code (for manual entry) + const validCode = codes.find( + (c) => + c.context === 'email-verification' && + (c.code === token || c.shortCode === token) && + c.expiresAt > Date.now() + ) + if (validCode) { + matchedUser = user + matchedCode = validCode + break } + } + + if (!matchedUser || !matchedCode) { + return null + } + + // Remove the used verification code and mark email as verified + const remainingCodes = parseVerificationCodes( + matchedUser.verificationCodes + ) + .filter( + (c) => + !(c.context === 'email-verification' && c.code === matchedCode!.code) + ) + .map((c) => JSON.stringify(c)) + + const verifiedUser = await prisma.user.update({ + where: { id: matchedUser.id }, + data: { + emailVerified: new Date(), + verificationCodes: remainingCodes, + }, + select: { + id: true, + email: true, + name: true, + }, + }) + + if (verifiedUser.email) { + // Emit audit event (fire-and-forget) + void emitAuditEvent('account.email-verified', { + userId: verifiedUser.id, + email: verifiedUser.email, + }) + } - // Remove the used verification code and mark email as verified - const remainingCodes = parseVerificationCodes(matchedUser.verificationCodes) - .filter((c) => !(c.context === 'email-verification' && c.code === matchedCode!.code)) - .map((c) => JSON.stringify(c)) + await creditVerifiedReferral(verifiedUser.id).catch((err) => + console.error('Failed to credit referral after verification', err) + ) - const verifiedUser = await prisma.user.update({ - where: { id: matchedUser.id }, - data: { - emailVerified: new Date(), - verificationCodes: remainingCodes, - }, - select: { - id: true, - email: true, - name: true, + // Send welcome email after successful verification + void (async () => { + try { + if (!verifiedUser.email) return + const dashboardUrl = `${appUrl()}/dashboard` + + await sendTemplateEmail({ + to: verifiedUser.email, + subject: 'Welcome to Emberly!', + template: WelcomeEmail, + props: { + name: verifiedUser.name || undefined, + verificationUrl: dashboardUrl, }, - }) + }) - if (verifiedUser.email) { - // Emit audit event (fire-and-forget) - void emitAuditEvent('account.email-verified', { - userId: verifiedUser.id, - email: verifiedUser.email, - }) + console.log( + `[Auth] Welcome email sent to ${verifiedUser.email} after email verification` + ) + } catch (err) { + console.error('Failed to send welcome email after verification', err) } + })() - // Send welcome email after successful verification - void (async () => { - try { - if (!verifiedUser.email) return - const dashboardUrl = `${appUrl()}/dashboard` - - await sendTemplateEmail({ - to: verifiedUser.email, - subject: 'Welcome to Emberly!', - template: WelcomeEmail, - props: { - name: verifiedUser.name || undefined, - verificationUrl: dashboardUrl, - }, - }) - - console.log(`[Auth] Welcome email sent to ${verifiedUser.email} after email verification`) - } catch (err) { - console.error('Failed to send welcome email after verification', err) - } - })() - - return matchedUser + return matchedUser } export async function GET(req: Request) { - try { - const { searchParams } = new URL(req.url) - const token = searchParams.get('token') - - if (!token) { - return NextResponse.json( - { error: 'Missing verification token' }, - { status: 400 } - ) - } - - const result = await verifyToken(token) - - if (!result) { - return NextResponse.json( - { error: 'Invalid or expired verification token' }, - { status: 400 } - ) - } - - return NextResponse.json({ - success: true, - message: 'Email verified successfully! You can now access your account.', - }) - } catch (error) { - console.error('Email verification error:', error) - return NextResponse.json( - { error: 'Internal server error' }, - { status: 500 } - ) + try { + const { searchParams } = new URL(req.url) + const token = searchParams.get('token') + + if (!token) { + return NextResponse.json( + { error: 'Missing verification token' }, + { status: 400 } + ) } + + const result = await verifyToken(token) + + if (!result) { + return NextResponse.json( + { error: 'Invalid or expired verification token' }, + { status: 400 } + ) + } + + return NextResponse.json({ + success: true, + message: 'Email verified successfully! You can now access your account.', + }) + } catch (error) { + console.error('Email verification error:', error) + return NextResponse.json( + { error: 'Internal server error' }, + { status: 500 } + ) + } } export async function POST(req: Request) { - try { - const json = await req.json() - const token = json.token || json.code - - if (!token) { - return NextResponse.json( - { error: 'Missing verification token' }, - { status: 400 } - ) - } - - const result = await verifyToken(token) - - if (!result) { - return NextResponse.json( - { error: 'Invalid or expired verification token' }, - { status: 400 } - ) - } - - return NextResponse.json({ - success: true, - message: 'Email verified successfully! You can now access your account.', - }) - } catch (error) { - console.error('Email verification error:', error) - return NextResponse.json( - { error: 'Internal server error' }, - { status: 500 } - ) + try { + const json = await req.json() + const token = json.token || json.code + + if (!token) { + return NextResponse.json( + { error: 'Missing verification token' }, + { status: 400 } + ) } -} + const result = await verifyToken(token) + + if (!result) { + return NextResponse.json( + { error: 'Invalid or expired verification token' }, + { status: 400 } + ) + } + + return NextResponse.json({ + success: true, + message: 'Email verified successfully! You can now access your account.', + }) + } catch (error) { + console.error('Email verification error:', error) + return NextResponse.json( + { error: 'Internal server error' }, + { status: 500 } + ) + } +} diff --git a/apps/dashboard/app/api/contact/route.ts b/apps/dashboard/app/api/contact/route.ts index 7d07c643..03e5d354 100644 --- a/apps/dashboard/app/api/contact/route.ts +++ b/apps/dashboard/app/api/contact/route.ts @@ -1,78 +1,98 @@ -import { NextResponse } from "next/server" +import { NextResponse } from 'next/server' -import { rateLimiter } from "@/lib/cache/rate-limit" -import { BasicEmail, sendTemplateEmail } from "@/lib/emails" +import { rateLimiter } from '@/lib/cache/rate-limit' +import { BasicEmail, sendTemplateEmail } from '@/lib/emails' import { notifyDiscord } from '@/lib/events/utils/discord-webhook' import { getIntegrations } from '@/lib/config' +import { clientIp } from '@/lib/security/client-ip' export async function POST(req: Request) { - try { - // Rate limit: 3 contact submissions per minute per IP - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || 'unknown' - const rateLimit = await rateLimiter.checkFixed(`contact:${ip}`, 3, 60) - if (!rateLimit.allowed) { - return NextResponse.json( - { message: "Too many submissions. Please try again later." }, - { - status: 429, - headers: { - 'Retry-After': String(Math.ceil((rateLimit.resetAt - Date.now()) / 1000)), - }, - } - ) + try { + // Rate limit: 3 contact submissions per minute per IP + const ip = clientIp(req.headers) ?? 'unknown' + const rateLimit = await rateLimiter.checkFixed(`contact:${ip}`, 3, 60) + if (!rateLimit.allowed) { + return NextResponse.json( + { message: 'Too many submissions. Please try again later.' }, + { + status: 429, + headers: { + 'Retry-After': String( + Math.ceil((rateLimit.resetAt - Date.now()) / 1000) + ), + }, } + ) + } - const data = await req.json() - const { name, email, subject, message } = data || {} + const data = await req.json() + const { name, email, subject, message } = data || {} - if (!name || !email || !message) { - return NextResponse.json({ message: "Missing required fields" }, { status: 400 }) - } + if (!name || !email || !message) { + return NextResponse.json( + { message: 'Missing required fields' }, + { status: 400 } + ) + } - const safeName = String(name).slice(0, 200) - const safeEmail = String(email).slice(0, 200) - const safeSubject = subject ? String(subject).slice(0, 200) : "(no subject)" - const safeMessage = String(message).slice(0, 2000) + const safeName = String(name).slice(0, 200) + const safeEmail = String(email).slice(0, 200) + const safeSubject = subject ? String(subject).slice(0, 200) : '(no subject)' + const safeMessage = String(message).slice(0, 2000) - // Admin Discord alert (admin-facing, system channel — fire-and-forget) - const integrations = await getIntegrations() - const adminWebhookUrl = integrations.discord?.webhookUrl || process.env.DISCORD_WEBHOOK_URL - if (adminWebhookUrl) { - notifyDiscord({ - webhookUrl: adminWebhookUrl, - embeds: [{ - title: '📬 New Contact Form Submission', - color: 0x6366f1, - fields: [ - { name: 'Name', value: safeName, inline: true }, - { name: 'Email', value: safeEmail, inline: true }, - { name: 'Subject', value: safeSubject, inline: false }, - { name: 'Message', value: safeMessage.slice(0, 1024), inline: false }, - ], - }], - }).catch(() => { /* non-critical */ }) - } + // Admin Discord alert (admin-facing, system channel — fire-and-forget) + const integrations = await getIntegrations() + const adminWebhookUrl = + integrations.discord?.webhookUrl || process.env.DISCORD_WEBHOOK_URL + if (adminWebhookUrl) { + notifyDiscord({ + webhookUrl: adminWebhookUrl, + embeds: [ + { + title: '📬 New Contact Form Submission', + color: 0x6366f1, + fields: [ + { name: 'Name', value: safeName, inline: true }, + { name: 'Email', value: safeEmail, inline: true }, + { name: 'Subject', value: safeSubject, inline: false }, + { + name: 'Message', + value: safeMessage.slice(0, 1024), + inline: false, + }, + ], + }, + ], + }).catch(() => { + /* non-critical */ + }) + } - // Auto-reply confirmation to the submitter (fire-and-forget) - sendTemplateEmail({ - to: safeEmail, - subject: "We received your message — Emberly", - template: BasicEmail, - props: { - title: "We received your message", - headline: `Hi ${safeName}, thanks for reaching out!`, - body: [ - "We've received your message and will get back to you as soon as possible.", - `Your message: "${safeMessage.slice(0, 200)}${safeMessage.length > 200 ? '…' : ''}"`, - ], - footerNote: "If you didn't submit this form, you can safely ignore this email.", - }, - }).catch(() => { /* non-critical */ }) + // Auto-reply confirmation to the submitter (fire-and-forget) + sendTemplateEmail({ + to: safeEmail, + subject: 'We received your message — Emberly', + template: BasicEmail, + props: { + title: 'We received your message', + headline: `Hi ${safeName}, thanks for reaching out!`, + body: [ + "We've received your message and will get back to you as soon as possible.", + `Your message: "${safeMessage.slice(0, 200)}${safeMessage.length > 200 ? '…' : ''}"`, + ], + footerNote: + "If you didn't submit this form, you can safely ignore this email.", + }, + }).catch(() => { + /* non-critical */ + }) - return NextResponse.json({ ok: true }) - } catch (err: any) { - console.error("/api/contact error", err) - return NextResponse.json({ message: err?.message || "Server error" }, { status: 500 }) - } + return NextResponse.json({ ok: true }) + } catch (err: any) { + console.error('/api/contact error', err) + return NextResponse.json( + { message: err?.message || 'Server error' }, + { status: 500 } + ) + } } - diff --git a/apps/dashboard/app/api/device/code/route.ts b/apps/dashboard/app/api/device/code/route.ts index 41fffd90..28c5f9ac 100644 --- a/apps/dashboard/app/api/device/code/route.ts +++ b/apps/dashboard/app/api/device/code/route.ts @@ -9,6 +9,7 @@ import { POLL_INTERVAL_SECONDS, createDeviceAuthorization, } from '@/lib/device-auth' +import { clientIp } from '@/lib/security/client-ip' const Body = z.object({ clientId: z.string(), @@ -16,7 +17,7 @@ const Body = z.object({ }) export async function POST(req: Request) { - const ip = req.headers.get('x-forwarded-for')?.split(',')[0] || 'unknown' + const ip = clientIp(req.headers) ?? 'unknown' const { allowed } = await rateLimiter.check(`device:code:${ip}`, 10, 600) if (!allowed) return apiError( @@ -33,9 +34,7 @@ export async function POST(req: Request) { parsed.data.clientId, parsed.data.deviceName ) - const base = ( - appUrl() - ).replace(/\/$/, '') + const base = appUrl().replace(/\/$/, '') return apiResponse({ deviceCode, diff --git a/apps/dashboard/app/api/payments/webhook/route.ts b/apps/dashboard/app/api/payments/webhook/route.ts index 16125a5b..221590f0 100644 --- a/apps/dashboard/app/api/payments/webhook/route.ts +++ b/apps/dashboard/app/api/payments/webhook/route.ts @@ -15,6 +15,7 @@ import { deleteLinodeBucket } from '@/lib/storage/providers/linode' import { deleteOVHStorageContainer } from '@/lib/storage/providers/ovhcloud' import { provisionBucketForUserSubscription } from '@/lib/storage/bucket-provisioning' import { stripeWebhookSecret } from '@/lib/config/env' +import { rewardReferrerForPayment } from '@/lib/referrals' const logger = loggers.api @@ -337,6 +338,16 @@ export async function POST(req: Request) { ) } + if (session.payment_status === 'paid') { + await rewardReferrerForPayment( + user.id, + session.amount_total || 0, + session.id + ).catch((err) => + logger.error('[Webhook] Referral reward failed', err) + ) + } + // Emit payment event - admin Discord notification is handled by event system await events.emit('billing.payment-succeeded', { userId: user.id, @@ -422,6 +433,14 @@ export async function POST(req: Request) { // Log invoice payment const amountPaid = invoice.amount_paid || 0 + await rewardReferrerForPayment( + user.id, + amountPaid, + invoice.id + ).catch((err) => + logger.error('[Webhook] Referral reward failed', err) + ) + // Emit billing event await events.emit('billing.payment-succeeded', { userId: user.id, diff --git a/apps/dashboard/components/auth/register-form.tsx b/apps/dashboard/components/auth/register-form.tsx index b954f599..1435fc35 100644 --- a/apps/dashboard/components/auth/register-form.tsx +++ b/apps/dashboard/components/auth/register-form.tsx @@ -109,7 +109,7 @@ export function RegisterForm() {

{referralCode && (

- 🎉 Invited by a friend — you'll both get credits when you join! + 🎉 Invited by a friend — verify your email to get your credits!

)} diff --git a/apps/dashboard/components/profile/index.tsx b/apps/dashboard/components/profile/index.tsx index 2bdc3066..85ff8e85 100644 --- a/apps/dashboard/components/profile/index.tsx +++ b/apps/dashboard/components/profile/index.tsx @@ -505,8 +505,8 @@ export function ProfileClient({ Referral Program

- Earn $10 billing credits for each friend who signs up using your - referral link. They also get $10 credit! + Earn up to $10 in billing credits when a friend you refer makes + their first payment. They get $10 when they verify their email.

diff --git a/apps/dashboard/components/profile/referrals.tsx b/apps/dashboard/components/profile/referrals.tsx index e84ee74b..c1efee7e 100644 --- a/apps/dashboard/components/profile/referrals.tsx +++ b/apps/dashboard/components/profile/referrals.tsx @@ -84,14 +84,18 @@ export function ProfileReferrals() { } const result = await res.json() - setStats((prev) => prev ? { ...prev, referralCode: result.referralCode } : null) + setStats((prev) => + prev ? { ...prev, referralCode: result.referralCode } : null + ) setCustomCode('') toast({ title: 'Success!', description: 'Your referral code has been created', }) } catch (error) { - setCodeError(error instanceof Error ? error.message : 'Failed to create code') + setCodeError( + error instanceof Error ? error.message : 'Failed to create code' + ) toast({ title: 'Error', description: codeError, @@ -170,7 +174,9 @@ export function ProfileReferrals() {

Create Your Referral Code

- Set a custom referral code to share with friends. When they sign up using your link, you both receive $10 in billing credits! + Set a custom referral code to share with friends. They get $10 in + billing credits when they verify their email, and you get up to $10 + when they make their first payment.

@@ -202,7 +208,9 @@ export function ProfileReferrals() {
-

• 3-30 characters (letters, numbers, dashes, underscores)

+

+ • 3-30 characters (letters, numbers, dashes, underscores) +

• Example: my-name or username123

@@ -216,12 +224,22 @@ export function ProfileReferrals() {
-
How Billing Credits Work
+
+ How Billing Credits Work +
    -
  • Credits are automatically applied to your next purchase
  • -
  • They reduce the amount you owe on subscriptions or add-ons
  • -
  • Credits are applied at checkout before payment
  • -
  • Any remaining balance is charged to your payment method
  • +
  • + Credits are automatically applied to your next purchase +
  • +
  • + They reduce the amount you owe on subscriptions or add-ons +
  • +
  • + Credits are applied at checkout before payment +
  • +
  • + Any remaining balance is charged to your payment method +
@@ -235,7 +253,9 @@ export function ProfileReferrals() {

Your Referral Code

- Share your unique referral code with friends. When they sign up using your link, you both receive $10 in billing credits! + Share your unique referral code with friends. They get $10 in billing + credits when they verify their email, and you get up to $10 when they + make their first payment.

@@ -243,33 +263,33 @@ export function ProfileReferrals() { {stats.referralCode}
- - + +
@@ -277,16 +297,23 @@ export function ProfileReferrals() { {/* Stats Section */}
-
Billing Credits
-
${stats.totalCredits.toFixed(2)} +
+ Billing Credits +
+
+ ${stats.totalCredits.toFixed(2)}
- {stats.totalCredits > 0 ? 'Applied to next purchase' : 'Earned from referrals'} + {stats.totalCredits > 0 + ? 'Applied to next purchase' + : 'Earned from referrals'}
-
Total Referrals
+
+ Total Referrals +
{stats.referralCount}
Users who joined @@ -297,10 +324,9 @@ export function ProfileReferrals() {
Credited
{stats.creditedCount}
- {stats.lastCreditedAt + {stats.lastCreditedAt ? `Last on ${new Date(stats.lastCreditedAt).toLocaleDateString()}` - : 'No credits yet' - } + : 'No credits yet'}
@@ -308,12 +334,22 @@ export function ProfileReferrals() { {/* How it Works Section */}
-
How Billing Credits Work
+
+ How Billing Credits Work +
    -
  • Credits are automatically applied to your next purchase
  • -
  • They reduce the amount you owe on subscriptions or add-ons
  • -
  • Credits are applied at checkout before payment
  • -
  • Any remaining balance is charged to your payment method
  • +
  • + Credits are automatically applied to your next purchase +
  • +
  • + They reduce the amount you owe on subscriptions or add-ons +
  • +
  • + Credits are applied at checkout before payment +
  • +
  • + Any remaining balance is charged to your payment method +
@@ -329,8 +365,12 @@ export function ProfileReferrals() { className="p-3 rounded-lg bg-muted/30 dark:bg-black/5 border border-border/50 dark:border-border/20 flex items-center justify-between" >
-
{referral.name || 'Unknown'}
-
{referral.email}
+
+ {referral.name || 'Unknown'} +
+
+ {referral.email} +
{new Date(referral.createdAt).toLocaleDateString()} @@ -351,4 +391,3 @@ export function ProfileReferrals() {
) } - diff --git a/apps/dashboard/lib/api/handler.ts b/apps/dashboard/lib/api/handler.ts index 654b155d..206b7f96 100644 --- a/apps/dashboard/lib/api/handler.ts +++ b/apps/dashboard/lib/api/handler.ts @@ -5,6 +5,7 @@ import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { loggers } from '@/lib/logger' import { LoggingContext } from '@/lib/logger/middleware' +import { clientIp } from '@/lib/security/client-ip' const logger = loggers.api @@ -60,7 +61,7 @@ export function withApiHandler( method: req.method, url: req.url, userAgent: req.headers.get('user-agent'), - ip: req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip'), + ip: clientIp(req.headers), }) if (options.requireAuth || options.requireAdmin) { diff --git a/apps/dashboard/lib/auth/login-context.ts b/apps/dashboard/lib/auth/login-context.ts index 4b0d6c3e..04c3b2cc 100644 --- a/apps/dashboard/lib/auth/login-context.ts +++ b/apps/dashboard/lib/auth/login-context.ts @@ -1,6 +1,7 @@ import { headers } from 'next/headers' import { describeDevice } from '@/lib/utils/user-agent' +import { clientIp } from '@/lib/security/client-ip' export interface RequestLoginContext { ip?: string @@ -38,11 +39,7 @@ export async function getRequestLoginContext( return { timeZone: validTimeZone(clientTimeZone) } } - const ip = - h.get('cf-connecting-ip') || - h.get('x-forwarded-for')?.split(',')[0]?.trim() || - h.get('x-real-ip') || - undefined + const ip = clientIp(h) const country = h.get('cf-ipcountry') || h.get('x-vercel-ip-country') || undefined diff --git a/apps/dashboard/lib/files/password-guard.ts b/apps/dashboard/lib/files/password-guard.ts index 313e29d5..75bedd8c 100644 --- a/apps/dashboard/lib/files/password-guard.ts +++ b/apps/dashboard/lib/files/password-guard.ts @@ -1,6 +1,7 @@ import { compare } from 'bcryptjs' import { randomBytes, scrypt } from 'crypto' import { promisify } from 'util' +import { clientIp } from '@/lib/security/client-ip' const scryptAsync = promisify(scrypt) as ( password: string, @@ -55,15 +56,8 @@ function bucket(key: string, now: number): Attempts { return entry } -/** The caller's address, as reported by Cloudflare or the reverse proxy. */ export function clientAddress(headers?: Headers | null): string { - if (!headers) return 'unknown' - return ( - headers.get('cf-connecting-ip') || - headers.get('x-forwarded-for')?.split(',')[0]?.trim() || - headers.get('x-real-ip') || - 'unknown' - ) + return clientIp(headers) ?? 'unknown' } /** Why a new file password can't be used, or null when it's fine. */ diff --git a/apps/dashboard/lib/logger/index.ts b/apps/dashboard/lib/logger/index.ts index cf697163..805fb715 100644 --- a/apps/dashboard/lib/logger/index.ts +++ b/apps/dashboard/lib/logger/index.ts @@ -1,6 +1,7 @@ import { NextRequest } from 'next/server' import pino, { Logger as PinoLogger } from 'pino' +import { clientIp } from '@/lib/security/client-ip' export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' @@ -216,10 +217,7 @@ export class Logger { method: req.method, url: req.url, userAgent: req.headers.get('user-agent') || undefined, - ip: - req.headers.get('x-forwarded-for') || - req.headers.get('x-real-ip') || - undefined, + ip: clientIp(req.headers), ...context, } diff --git a/apps/dashboard/lib/referrals/index.ts b/apps/dashboard/lib/referrals/index.ts index 7bae07af..07075f8c 100644 --- a/apps/dashboard/lib/referrals/index.ts +++ b/apps/dashboard/lib/referrals/index.ts @@ -2,6 +2,7 @@ * Referral/Affiliate system utilities */ +import type { Prisma } from '@emberly/db' import { prisma } from '@emberly/db' import { addPerkRole } from '@/lib/perks' @@ -12,8 +13,44 @@ export const REFERRAL_CONFIG = { REFERRER_CREDIT: 10, // $10 credit for each successful referral REFERREE_CREDIT: 10, // $10 credit for new users who sign up via referral REFERRAL_CODE_LENGTH: 8, + MAX_CREDITED_REFERRALS: 10, } as const +interface ReferralStatsData { + count?: number + credited?: number + lastCreditedAt?: string | null + pendingSignupCredit?: boolean + pendingReferrerReward?: boolean +} + +function readStats(value: unknown): ReferralStatsData { + const parsed = typeof value === 'string' ? JSON.parse(value) : value + return (parsed ?? {}) as ReferralStatsData +} + +/** Treats plus-addressing, and Gmail's ignored dots, as the same inbox. */ +function normalizeMailbox(email: string) { + const [local, domain] = email.trim().toLowerCase().split('@') + const name = local.split('+')[0] + const gmail = domain === 'gmail.com' || domain === 'googlemail.com' + return `${gmail ? name.replace(/\./g, '') : name}@${gmail ? 'gmail.com' : domain}` +} + +export function isSameMailbox(a?: string | null, b?: string | null) { + return !!a && !!b && normalizeMailbox(a) === normalizeMailbox(b) +} + +export function referrerReward(amountPaidCents: number) { + return Math.min(REFERRAL_CONFIG.REFERRER_CREDIT, amountPaidCents / 100) +} + +async function lockUsers(tx: Prisma.TransactionClient, ids: string[]) { + for (const id of [...ids].sort()) { + await tx.$queryRaw`SELECT id FROM "User" WHERE id = ${id} FOR UPDATE` + } +} + /** * Generate a unique referral code for a user */ @@ -36,18 +73,20 @@ export async function generateReferralCode(userId: string): Promise { while (!isUnique && attempts < maxAttempts) { code = generateRandomCode(REFERRAL_CONFIG.REFERRAL_CODE_LENGTH) - + const existing = await prisma.user.findUnique({ where: { referralCode: code }, select: { id: true }, }) - + isUnique = !existing attempts++ } if (!isUnique) { - throw new Error('Failed to generate unique referral code after multiple attempts') + throw new Error( + 'Failed to generate unique referral code after multiple attempts' + ) } // Save the referral code @@ -75,7 +114,10 @@ export async function getReferralCode(userId: string): Promise { /** * Set a custom referral code for a user */ -export async function setCustomReferralCode(userId: string, code: string): Promise<{ referralCode: string }> { +export async function setCustomReferralCode( + userId: string, + code: string +): Promise<{ referralCode: string }> { // Validate code format const validatedCode = validateReferralCode(code) @@ -86,7 +128,9 @@ export async function setCustomReferralCode(userId: string, code: string): Promi }) if (existing && existing.id !== userId) { - throw new Error('This referral code is already taken. Please choose another.') + throw new Error( + 'This referral code is already taken. Please choose another.' + ) } // Update user's referral code @@ -114,11 +158,22 @@ function validateReferralCode(code: string): string { } if (!/^[a-z0-9-_]+$/.test(sanitized)) { - throw new Error('Referral code can only contain letters, numbers, dashes, and underscores') + throw new Error( + 'Referral code can only contain letters, numbers, dashes, and underscores' + ) } // Prevent reserved codes - const reserved = ['admin', 'api', 'auth', 'dashboard', 'settings', 'profile', 'billing', 'null'] + const reserved = [ + 'admin', + 'api', + 'auth', + 'dashboard', + 'settings', + 'profile', + 'billing', + 'null', + ] if (reserved.includes(sanitized)) { throw new Error('This referral code is reserved. Please choose another.') } @@ -127,7 +182,9 @@ function validateReferralCode(code: string): string { const bannedBrands = ['emberly', 'embrly'] for (const b of bannedBrands) { if (sanitized.includes(b)) { - throw new Error('Referral code may not contain brand or trademarked names. Please choose another.') + throw new Error( + 'Referral code may not contain brand or trademarked names. Please choose another.' + ) } } @@ -154,79 +211,180 @@ export async function getReferralStats(userId: string) { throw new Error('User not found') } - const stats = typeof user.referralStats === 'string' - ? JSON.parse(user.referralStats) - : user.referralStats + const stats = + typeof user.referralStats === 'string' + ? JSON.parse(user.referralStats) + : user.referralStats return { referralCode: user.referralCode, totalCredits: user.referralCredits, referralCount: user._count.referrals, creditedCount: stats.credited || 0, - lastCreditedAt: stats.lastCreditedAt ? new Date(stats.lastCreditedAt) : null, + lastCreditedAt: stats.lastCreditedAt + ? new Date(stats.lastCreditedAt) + : null, } } /** - * Process a referral signup - * Called when a new user signs up with a referral code + * Records who referred a new signup. Nothing is credited yet: the new account + * earns its credit by verifying its email, and the referrer earns theirs when + * that account first pays. */ export async function processReferralSignup( newUserId: string, referralCode: string ): Promise<{ success: boolean; message: string }> { try { - // Find the referrer - const referrer = await prisma.user.findUnique({ - where: { referralCode }, - select: { id: true, referralCredits: true, referralStats: true }, - }) - - if (!referrer) { + const [referrer, newUser] = await Promise.all([ + prisma.user.findUnique({ + where: { referralCode }, + select: { id: true, email: true }, + }), + prisma.user.findUnique({ + where: { id: newUserId }, + select: { email: true, referralStats: true }, + }), + ]) + + if (!referrer || !newUser) { return { success: false, message: 'Invalid referral code' } } - // Update new user with referrer + if ( + referrer.id === newUserId || + isSameMailbox(referrer.email, newUser.email) + ) { + return { success: false, message: 'You cannot refer yourself' } + } + await prisma.user.update({ where: { id: newUserId }, data: { referrerUserId: referrer.id, - referralCredits: REFERRAL_CONFIG.REFERREE_CREDIT, + referralStats: { + ...readStats(newUser.referralStats), + pendingSignupCredit: true, + pendingReferrerReward: true, + }, }, }) - // Update referrer credits - const stats = typeof referrer.referralStats === 'string' - ? JSON.parse(referrer.referralStats) - : referrer.referralStats + return { success: true, message: 'Referral recorded' } + } catch (error) { + console.error('Failed to process referral signup:', error) + return { success: false, message: 'Failed to process referral' } + } +} - const updatedStats = { - count: (stats.count || 0) + 1, - credited: (stats.credited || 0) + 1, - lastCreditedAt: new Date().toISOString(), - } +/** Gives a referred account its credit, once, after its email is verified. */ +export async function creditVerifiedReferral(userId: string): Promise { + await prisma.$transaction(async (tx) => { + await lockUsers(tx, [userId]) + const user = await tx.user.findUnique({ + where: { id: userId }, + select: { + emailVerified: true, + referrerUserId: true, + referralStats: true, + }, + }) + if (!user?.emailVerified || !user.referrerUserId) return - await prisma.user.update({ - where: { id: referrer.id }, + const { pendingSignupCredit, ...stats } = readStats(user.referralStats) + if (!pendingSignupCredit) return + + await tx.user.update({ + where: { id: userId }, data: { - referralCredits: referrer.referralCredits + REFERRAL_CONFIG.REFERRER_CREDIT, - referralStats: updatedStats, + referralCredits: { increment: REFERRAL_CONFIG.REFERREE_CREDIT }, + referralStats: stats, }, }) + await tx.creditTransaction.create({ + data: { + userId, + type: 'earned_referral', + amountCents: REFERRAL_CONFIG.REFERREE_CREDIT * 100, + description: 'Signed up with a referral link', + relatedUserId: user.referrerUserId, + }, + }) + }) +} - // Award AFFILIATE perk if this is their first referral - if ((stats.credited || 0) === 0) { - await addPerkRole(referrer.id, 'AFFILIATE') - } +/** + * Pays the referrer, once, when the account they referred first pays. The + * reward never exceeds what was actually paid, and is capped per referrer. + */ +export async function rewardReferrerForPayment( + userId: string, + amountPaidCents: number, + relatedOrderId?: string +): Promise { + if (amountPaidCents <= 0) return + + const link = await prisma.user.findUnique({ + where: { id: userId }, + select: { referrerUserId: true }, + }) + const referrerId = link?.referrerUserId + if (!referrerId) return + + const firstReward = await prisma.$transaction(async (tx) => { + await lockUsers(tx, [userId, referrerId]) + const [user, referrer] = await Promise.all([ + tx.user.findUnique({ + where: { id: userId }, + select: { referralStats: true }, + }), + tx.user.findUnique({ + where: { id: referrerId }, + select: { emailVerified: true, referralStats: true }, + }), + ]) + if (!user || !referrer) return false + + const { pendingReferrerReward, ...stats } = readStats(user.referralStats) + if (!pendingReferrerReward || !referrer.emailVerified) return false + + await tx.user.update({ + where: { id: userId }, + data: { referralStats: stats }, + }) - return { - success: true, - message: `Referral credited! Both users receive $${REFERRAL_CONFIG.REFERREE_CREDIT} billing credit.`, - } - } catch (error) { - console.error('Failed to process referral signup:', error) - return { success: false, message: 'Failed to process referral' } - } + const referrerStats = readStats(referrer.referralStats) + const credited = referrerStats.credited || 0 + if (credited >= REFERRAL_CONFIG.MAX_CREDITED_REFERRALS) return false + + const reward = referrerReward(amountPaidCents) + await tx.user.update({ + where: { id: referrerId }, + data: { + referralCredits: { increment: reward }, + referralStats: { + ...referrerStats, + count: (referrerStats.count || 0) + 1, + credited: credited + 1, + lastCreditedAt: new Date().toISOString(), + }, + }, + }) + await tx.creditTransaction.create({ + data: { + userId: referrerId, + type: 'earned_referral', + amountCents: Math.round(reward * 100), + description: 'A referred account made its first payment', + relatedUserId: userId, + relatedOrderId, + }, + }) + return credited === 0 + }) + + if (firstReward) await addPerkRole(referrerId, 'AFFILIATE') } /** diff --git a/apps/dashboard/lib/security/client-ip.ts b/apps/dashboard/lib/security/client-ip.ts new file mode 100644 index 00000000..d04c08dd --- /dev/null +++ b/apps/dashboard/lib/security/client-ip.ts @@ -0,0 +1,21 @@ +/** + * The caller's address, read only from what our own proxies set. Clients can + * send any X-Forwarded-For they like and proxies append to it, so the leftmost + * entries can't be trusted. TRUSTED_PROXY is "cloudflare", or the number of + * proxies in front of the app (default 1). + */ +export function clientIp(headers?: Headers | null): string | undefined { + if (!headers) return undefined + + const trusted = process.env.TRUSTED_PROXY?.trim().toLowerCase() + if (trusted === 'cloudflare') { + return headers.get('cf-connecting-ip')?.trim() || undefined + } + + const hops = Math.max(1, Number.parseInt(trusted ?? '', 10) || 1) + const chain = (headers.get('x-forwarded-for') ?? '') + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean) + return chain[Math.max(0, chain.length - hops)] +} diff --git a/apps/dashboard/tests/referrals.test.ts b/apps/dashboard/tests/referrals.test.ts new file mode 100644 index 00000000..0d7050bd --- /dev/null +++ b/apps/dashboard/tests/referrals.test.ts @@ -0,0 +1,186 @@ +import { beforeEach, describe, expect, mock, test } from 'bun:test' + +type Row = Record +const users = new Map() +const transactions: Row[] = [] +const perks: string[] = [] + +function applyUpdate(row: Row, data: Row) { + for (const [key, value] of Object.entries(data)) { + row[key] = + value && typeof value === 'object' && 'increment' in value + ? row[key] + value.increment + : value + } +} + +const client = { + $queryRaw: async () => [], + user: { + findUnique: async ({ where }: { where: Row }) => + where.id + ? (users.get(where.id) ?? null) + : ([...users.values()].find( + (u) => u.referralCode === where.referralCode + ) ?? null), + update: async ({ where, data }: { where: Row; data: Row }) => { + applyUpdate(users.get(where.id)!, data) + }, + }, + creditTransaction: { + create: async ({ data }: { data: Row }) => { + transactions.push(data) + }, + }, +} + +mock.module('@emberly/db', () => ({ + prisma: { ...client, $transaction: (run: any) => run(client) }, +})) +mock.module('@/lib/perks', () => ({ + addPerkRole: async (id: string, role: string) => { + perks.push(`${id}:${role}`) + }, +})) + +const { + creditVerifiedReferral, + isSameMailbox, + processReferralSignup, + referrerReward, + rewardReferrerForPayment, +} = await import('@/lib/referrals') +const { clientIp } = await import('@/lib/security/client-ip') + +function user(id: string, extra: Row = {}) { + users.set(id, { + id, + email: `${id}@example.com`, + emailVerified: null, + referralCredits: 0, + referralStats: { count: 0, credited: 0, lastCreditedAt: null }, + ...extra, + }) + return users.get(id)! +} + +describe('referral credits', () => { + beforeEach(() => { + users.clear() + transactions.length = 0 + perks.length = 0 + user('ref', { referralCode: 'CODE', emailVerified: new Date() }) + }) + + // Reported by kta1kri: unverified throwaway signups minted $10 each + test('signing up credits nobody', async () => { + const puppet = user('new') + await processReferralSignup('new', 'CODE') + expect(puppet.referrerUserId).toBe('ref') + expect(puppet.referralCredits).toBe(0) + expect(users.get('ref')!.referralCredits).toBe(0) + expect(perks).toEqual([]) + }) + + test('the new account is credited once, only after verifying', async () => { + const puppet = user('new') + await processReferralSignup('new', 'CODE') + await creditVerifiedReferral('new') + expect(puppet.referralCredits).toBe(0) + + puppet.emailVerified = new Date() + await creditVerifiedReferral('new') + await creditVerifiedReferral('new') + expect(puppet.referralCredits).toBe(10) + expect(users.get('ref')!.referralCredits).toBe(0) + }) + + test('the referrer is paid once, on the first real payment', async () => { + user('new') + await processReferralSignup('new', 'CODE') + await rewardReferrerForPayment('new', 0) + expect(users.get('ref')!.referralCredits).toBe(0) + + await rewardReferrerForPayment('new', 2000, 'inv_1') + await rewardReferrerForPayment('new', 2000, 'inv_2') + expect(users.get('ref')!.referralCredits).toBe(10) + expect(perks).toEqual(['ref:AFFILIATE']) + }) + + test('the reward never exceeds the amount paid', () => { + expect(referrerReward(399)).toBe(3.99) + expect(referrerReward(5000)).toBe(10) + }) + + test('an unverified referrer earns nothing', async () => { + users.get('ref')!.emailVerified = null + user('new') + await processReferralSignup('new', 'CODE') + await rewardReferrerForPayment('new', 2000) + expect(users.get('ref')!.referralCredits).toBe(0) + }) + + test('rewards stop at the cap', async () => { + users.get('ref')!.referralStats.credited = 10 + user('new') + await processReferralSignup('new', 'CODE') + await rewardReferrerForPayment('new', 2000) + expect(users.get('ref')!.referralCredits).toBe(0) + }) + + test('accounts credited under the old rules are not paid again', async () => { + const legacy = user('old', { + referrerUserId: 'ref', + referralCredits: 10, + emailVerified: new Date(), + }) + await creditVerifiedReferral('old') + await rewardReferrerForPayment('old', 2000) + expect(legacy.referralCredits).toBe(10) + expect(users.get('ref')!.referralCredits).toBe(0) + }) + + test('the same mailbox cannot refer itself', async () => { + expect(isSameMailbox('a.b+x@gmail.com', 'ab@googlemail.com')).toBe(true) + expect(isSameMailbox('a+x@example.com', 'A@example.com')).toBe(true) + expect(isSameMailbox('a.b@example.com', 'ab@example.com')).toBe(false) + + users.get('ref')!.email = 'me@example.com' + const puppet = user('new', { email: 'me+1@example.com' }) + const result = await processReferralSignup('new', 'CODE') + expect(result.success).toBe(false) + expect(puppet.referrerUserId).toBeUndefined() + }) +}) + +describe('clientIp', () => { + const headers = (init: Record) => new Headers(init) + + beforeEach(() => { + delete process.env.TRUSTED_PROXY + }) + + test('ignores addresses the client added to the header', () => { + expect( + clientIp(headers({ 'x-forwarded-for': '1.1.1.1, 203.0.113.9' })) + ).toBe('203.0.113.9') + }) + + test('counts back by the number of proxies', () => { + process.env.TRUSTED_PROXY = '2' + expect( + clientIp(headers({ 'x-forwarded-for': '1.1.1.1, 203.0.113.9, 10.0.0.1' })) + ).toBe('203.0.113.9') + }) + + test('only believes Cloudflare when told to', () => { + const request = headers({ + 'cf-connecting-ip': '198.51.100.7', + 'x-forwarded-for': '203.0.113.9', + }) + expect(clientIp(request)).toBe('203.0.113.9') + process.env.TRUSTED_PROXY = 'cloudflare' + expect(clientIp(request)).toBe('198.51.100.7') + expect(clientIp(headers({ 'x-forwarded-for': '1.1.1.1' }))).toBeUndefined() + }) +}) diff --git a/apps/docs/content/docs/self-hosting/environment.mdx b/apps/docs/content/docs/self-hosting/environment.mdx index 6b2fa2e0..7b1dfbd6 100644 --- a/apps/docs/content/docs/self-hosting/environment.mdx +++ b/apps/docs/content/docs/self-hosting/environment.mdx @@ -37,6 +37,7 @@ With Docker Compose, `DATABASE_URL` and `REDIS_URL` are set for you. Set `POSTGR | `EMBERLY_LICENSE_KEY` | — | Your license key. Optional: you can also paste it in **Admin → Settings → License & branding**. See [License & Branding](/self-hosting/licensing). | | `EMBERLY_LICENSE_CHECKIN` | `true` | Set to `false` on servers that can't reach licenses.embrly.ca | | `EMBERLY_RUN_EVENT_WORKER` | `true` | Runs background jobs (emails, notifications, Discord alerts, OCR, malware scans) in the app process. Only set it to `false` if you run `bun run worker` as its own service. | +| `TRUSTED_PROXY` | `1` | Who to trust for the visitor's IP address, used by rate limits. Set `cloudflare` if the site is behind Cloudflare, otherwise the number of reverse proxies in front of the app. Keep the app itself off the public internet, or visitors can fake their address. | | `NEXTAUTH_TRUSTED_ORIGINS` | — | Extra origins allowed to sign in, comma separated | | `NEXTAUTH_COOKIE_DOMAIN` | — | Share the session across subdomains, e.g. `.example.com` | | `EMBERLY_SKIP_MIGRATIONS` | `false` | Docker only: skip running migrations when the container starts | diff --git a/dokploy/docker-compose.yml b/dokploy/docker-compose.yml index 0d5e2c77..03b30ffe 100644 --- a/dokploy/docker-compose.yml +++ b/dokploy/docker-compose.yml @@ -1,6 +1,6 @@ services: emberly: - image: ghcr.io/emberlyoss/emberly:latest + image: ghcr.io/emberlyoss/emberly:3.2.1 restart: unless-stopped expose: - 3000 @@ -10,6 +10,7 @@ services: DATABASE_URL: postgresql://emberly:${POSTGRES_PASSWORD}@postgres:5432/emberly REDIS_URL: redis://redis:6379 EMBERLY_RUN_EVENT_WORKER: ${EMBERLY_RUN_EVENT_WORKER:-true} + TRUSTED_PROXY: ${TRUSTED_PROXY:-1} volumes: - emberly-data:/data depends_on: diff --git a/dokploy/emberly.svg b/dokploy/emberly.svg new file mode 100644 index 00000000..754ccd7f --- /dev/null +++ b/dokploy/emberly.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dokploy/meta.json b/dokploy/meta.json new file mode 100644 index 00000000..8fa81ece --- /dev/null +++ b/dokploy/meta.json @@ -0,0 +1,16 @@ +{ + "id": "emberly", + "name": "Emberly", + "version": "3.2.1", + "description": "Emberly is a self-hosted file sharing platform with short links, pastes, custom domains and ShareX, Flameshot and desktop app support. Deploy it on Dokploy with Docker Compose, PostgreSQL and Redis in a few clicks.", + "logo": "emberly.svg", + "links": { + "github": "https://github.com/EmberlyOSS/Emberly", + "website": "https://embrly.ca", + "docs": "https://docs.embrly.ca" + }, + "tags": ["file-sharing", "storage", "media-system"], + "seoTitle": "Emberly Docker Compose Setup", + "seoDescription": "Self-hosted file sharing, short links and pastes. Deploy Emberly with Docker Compose on Dokploy in minutes.", + "newConfig": true +}