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.
- 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.
@@ -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}
- {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() {