Skip to content
Merged

Dev #135

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=""

Expand Down
11 changes: 11 additions & 0 deletions apps/dashboard/CHANGELOG.md → CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions apps/dashboard/app/api/auth/desktop/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
auditSuspiciousActivity,
emitAuditEvent,
} from '@/lib/events/audit-helper'
import { clientIp } from '@/lib/security/client-ip'

const logger = loggers.auth

Expand Down Expand Up @@ -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
Expand Down
149 changes: 85 additions & 64 deletions apps/dashboard/app/api/auth/password/forgot/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}

5 changes: 3 additions & 2 deletions apps/dashboard/app/api/auth/password/reset/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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(
Expand Down Expand Up @@ -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) =>
Expand Down
44 changes: 25 additions & 19 deletions apps/dashboard/app/api/auth/register/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,21 @@ 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()
.refine(
(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
})

Expand All @@ -45,15 +44,17 @@ 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(
{ error: 'Too many registration attempts. Please try again later.' },
{
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),
},
}
Expand All @@ -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 }],
},
})

Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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)
Expand All @@ -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: {
Expand All @@ -217,4 +224,3 @@ export async function POST(req: Request) {
)
}
}

Loading
Loading