Skip to content

custom domains - auth sync #2180

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 78 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
78 commits
Select commit Hold shift + click to select a range
c50509a
Custom Domains CRUD, Verification
Soxasora May 1, 2025
5e80c3f
Domains refactor, Domain Verification normalization
Soxasora May 2, 2025
4d24845
Domains normalization: Attempts, Records, Certificates
Soxasora May 3, 2025
b624c59
Domain Verification worker adjusted to new schema; use triggers to ch…
Soxasora May 4, 2025
89f1eb4
wip: Domain Verification worker, log all verification steps
Soxasora May 6, 2025
9d1c137
wip: clearer Domain Verification flow, surround AWS calls with try ca…
Soxasora May 6, 2025
dc119a8
Domain Verification schema updates
Soxasora May 6, 2025
67fb2c8
HOLD the domain and delete the certificate when a territory expires
Soxasora May 6, 2025
725ce81
delete the certificate from ACM when we're about to STOP a territory
Soxasora May 6, 2025
f3930f7
Domain resolver refactor, use transactions, add comments
Soxasora May 6, 2025
01e319e
Stages for Domain Verification attempts logging, fix certificate dele…
Soxasora May 6, 2025
e132ad0
separate ACM certificate requests and validation values
Soxasora May 7, 2025
cd9cb68
Domains UI/UX enhancements; core fixes to schema; general cleanup
Soxasora May 7, 2025
9e96d7c
delete any existing domain verification jobs if we're updating the do…
Soxasora May 8, 2025
82a71f5
Log AWS-related error messages; fix deleteCertificate recursion
Soxasora May 8, 2025
f95ab6a
fix missing await on async customDomainMiddleware
Soxasora May 8, 2025
4f49382
Merge branch 'master' into custom_domains_base
Soxasora May 8, 2025
2382f3b
hotfix: delete certificate from ACM also on domain removal
Soxasora May 9, 2025
c732135
Merge branch 'master' into custom_domains_base
huumn May 14, 2025
ca13d80
prepare for dnsmasq, light cleanup
Soxasora May 16, 2025
2a77fd1
fix DNS server typo
Soxasora May 16, 2025
072c1ae
don't ask ACM to delete a certificate in a db transaction
Soxasora May 16, 2025
7da660a
fix typo
Soxasora May 17, 2025
d0b9467
better handling of territory changes, ACM certificates and domains in…
Soxasora May 18, 2025
2c4ca44
address plpgsql syntax issues, move INSERT for pgboss.schedule in a f…
Soxasora May 18, 2025
52dd035
fallback to system's default DNS servers if dnsmasq is not available/…
Soxasora May 18, 2025
0a7eda2
better error handling of node:dns resolver
Soxasora May 20, 2025
e6bd73b
Merge branch 'master' into custom_domains_base
huumn May 21, 2025
76be3ae
hotfix: remove the port in dev for domain mapping
Soxasora May 21, 2025
e0e2dea
add aws container to domains profile
huumn May 21, 2025
807c2d3
move existingTXT on a more appropriate place, TODOs on prisma schema
Soxasora May 22, 2025
e8d97ba
territory redirects and rewrites for middleware, adjust navbar reacti…
Soxasora May 22, 2025
476c10b
30 seconds of interval between verification jobs, after 1 hour of dom…
Soxasora May 22, 2025
ef549a9
also get records when getting the existing domain, recreate the domai…
Soxasora May 22, 2025
1e3b1c6
hotfix: use validateSchema the correct way, change from domain to dom…
Soxasora May 22, 2025
25674c2
hide custom domains from the world but the admins
Soxasora May 22, 2025
eddd453
debounce next verification jobs with a singleton key, avoiding other …
Soxasora May 22, 2025
bbf2b0a
ELBv2 implementation to attach a certificate to a load balancer; Mock…
Soxasora May 23, 2025
f36eef4
use directly the interested ELB Listener ARN via env vars; get rid of…
Soxasora May 24, 2025
51aadf2
throw database and AWS-related errors; don't log the STAGE on critica…
Soxasora May 24, 2025
5bf8aba
remove unused certificate attachment to ELB checks
Soxasora May 24, 2025
1643c09
remove unused ELB env var, remove useless console.logs
Soxasora May 24, 2025
8826def
WIP: rewrite auth sync
Soxasora May 25, 2025
76d2da4
safer domain recognition by schema validation; no session handler wit…
Soxasora May 25, 2025
97020e0
tie domain to the token, use it in middleware to verify token origin;…
Soxasora May 25, 2025
109288f
verify and apply session token from Auth Sync to custom domain via mi…
Soxasora May 25, 2025
d579b55
eradicate TXT records from custom domains; adjust functions to expect…
Soxasora May 25, 2025
102b2f2
Merge branch 'master' into custom_domains_base
Soxasora May 25, 2025
9e2eaa2
Merge branch 'master' into custom_domains_authsync
Soxasora May 25, 2025
1b49eed
Merge branch 'custom_domains_base' into custom_domains_authsync
Soxasora May 25, 2025
093910b
pass CNAME record directly instead of the whole records map
Soxasora May 25, 2025
0ad0b33
don't delete the domain if resuming from HOLD
Soxasora May 25, 2025
b69ba0a
Merge branch 'custom_domains_base' into custom_domains_authsync
Soxasora May 25, 2025
fd34d16
manual redirect to / on logout for custom domains
Soxasora May 26, 2025
ebf2c8b
wip: custom domains documentation
Soxasora May 28, 2025
f361958
docs: explain all the triggers, ACM and ALB implementations, fix head…
Soxasora May 28, 2025
716f982
Merge branch 'custom_domains_base' into custom_domains_authsync
Soxasora May 28, 2025
171405b
Auth Sync Rewrite - Sync API endpoint and Middleware
Soxasora May 29, 2025
de48c27
hotfix: use correct URLs for redirects; don't parse JSON from JSON
Soxasora May 29, 2025
6a0b2cc
docs: clearer explanations
Soxasora May 30, 2025
5a57a77
Merge branch 'custom_domains_base' into custom_domains_authsync
Soxasora May 30, 2025
e65e8a5
switch to anon on auth sync signup to allow the creation of a new acc…
Soxasora May 31, 2025
4603878
docs: auth sync; enhance: 5 minute verification token and session cookie
Soxasora Jun 2, 2025
872691b
auth sync: responses with custom domain subname headers; redirect to …
Soxasora Jun 2, 2025
3b79145
cleanup: remove Auth Sync TODO from territory-domains.js
Soxasora Jun 2, 2025
932f4e3
prevent CSRF attacks, consume verification token transactionally
Soxasora Jun 10, 2025
236fb1b
cleanup: don't include state when redirecting back to custom domain; …
Soxasora Jun 10, 2025
c14ee46
cleanup: get csrfToken cookie once, bail if csrfToken cookie is not p…
Soxasora Jun 10, 2025
af2460b
fix: correct error redirect URL
Soxasora Jun 10, 2025
1346057
pivot: encode CSRF token in a state JWT for auth sync, and decode it …
Soxasora Jun 10, 2025
d22eb55
encode domain and redirectUri inside state JWE
Soxasora Jun 11, 2025
db374b9
Revert CSRF JWE, consume verification token transactionally
Soxasora Jun 11, 2025
7343cfe
security: couple domainName with JWTs to stop them from being used on…
Soxasora Jun 12, 2025
19a9df2
Revert "security: couple domainName with JWTs to stop them from being…
Soxasora Jun 13, 2025
ac03f32
use locally scoped configs for ACM and ELB APIs
Soxasora Jun 13, 2025
f6c1018
Merge branch 'custom_domains_base' into custom_domains_authsync
Soxasora Jun 13, 2025
5df12c9
cleanup: Auth Sync handler and middleware
Soxasora Jun 13, 2025
6054532
hotfix: don't expose prisma errors while consuming a verification token
Soxasora Jun 13, 2025
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
10 changes: 8 additions & 2 deletions middleware.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextResponse, URLPattern } from 'next/server'
import { getDomainMapping } from '@/lib/domains'
import { SESSION_COOKIE, cookieOptions } from '@/lib/auth'
import { encode } from 'next-auth/jwt'

const referrerPattern = new URLPattern({ pathname: ':pathname(*)/r/:referrer([\\w_]+)' })
const itemPattern = new URLPattern({ pathname: '/items/:id(\\d+){/:other(\\w+)}?' })
Expand Down Expand Up @@ -85,8 +86,13 @@ async function redirectToAuthSync (request, searchParams, domain, csrfToken, sig

const syncUrl = new URL('/api/auth/sync', SN_MAIN_DOMAIN)
syncUrl.searchParams.set('domain', domain)
// store the csrfToken in the search params
syncUrl.searchParams.set('state', csrfToken)
// encode the csrfToken as state JWT using NEXTAUTH_SECRET
const randomState = await encode({
token: { csrf: csrfToken },
secret: process.env.NEXTAUTH_SECRET
})
// set the state in the search params
syncUrl.searchParams.set('state', randomState)

// if we're signing up, we need to set the signup flag
if (signup) {
Expand Down
34 changes: 22 additions & 12 deletions pages/api/auth/sync.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Auth Sync API
import models from '@/api/models'
import { randomBytes } from 'node:crypto'
import { encode as encodeJWT, getToken } from 'next-auth/jwt'
import { encode as encodeJWT, decode, getToken } from 'next-auth/jwt'
import { validateSchema, customDomainSchema } from '@/lib/validate'

const SN_MAIN_DOMAIN = new URL(process.env.NEXT_PUBLIC_URL)
Expand Down Expand Up @@ -117,14 +117,14 @@ function handleNoSession (res, domainName, state, redirectUri, signup = false) {
res.redirect(302, loginRedirectUrl.href)
}

async function createVerificationToken (token, csrfToken) {
async function createVerificationToken (token, state) {
try {
// a 5 minutes verification token using the session token's user id
const verificationToken = await models.verificationToken.create({
data: {
identifier: token.id.toString(),
// store csrf token with the verification token, to prevent CSRF attacks
token: `${randomBytes(32).toString('hex')}|${csrfToken}`,
// store encoded state JWT with the verification token to prevent CSRF attacks
token: `${randomBytes(32).toString('hex')}|${state}`,
Copy link
Member Author

@Soxasora Soxasora Jun 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too much, switched to token in URL as it shouldn't be logged.

Tie a CSRF token to a verification token There were some obstacles because of the cross-domain nature, but I think I found a middle ground to safely use CSRF to tie the verification token to the user. Knowing that: - messing with next auth is not preferable and thus can't use its protections - we need to protect the token from being stolen - middleware doesn't support node We have another option, which is to **encode** the CSRF token in a _state JWE_ and store it alongside the verification token.

When going to the sync endpoint, we

  • detect login -> encode CSRF token in state JWE -> /api/auth/sync/?...&state=encodedState

The sync endpoint will then

  • create a token like token|encodedState -> redirect back with just the token

Middleware at this point will

  • POST /api/auth/sync with body: {token, csrfToken} -> retrieve the verification token object from DB -> decode the encodedState -> match decodedState with csrfToken

If everything is okay, it returns the final ephemeral JWT.

Everything happens blazingly fast, if someone steals the verification token and/or the state, they can’t go that far without the CSRF token that sits and never moves in the user’s browser (well, except for the POST, but that's secure).


side note: still checking for less hacky ways/can make it less hacky

expires: new Date(Date.now() + 1000 * 60 * 5) // 5 minutes
}
})
Expand Down Expand Up @@ -152,14 +152,15 @@ async function redirectToDomain (res, domainName, verificationToken, redirectUri
}

async function consumeVerificationToken (verificationToken, csrfToken) {
// sync tokens are stored as token|csrfToken
const tokenWithState = `${verificationToken}|${csrfToken}`
// sync tokens are stored as token
try {
// find and delete the verification token
const identifier = await models.$transaction(async tx => {
const token = await tx.verificationToken.findFirst({
where: {
token: tokenWithState,
token: {
startsWith: verificationToken
},
expires: { gt: new Date() }
}
})
Expand All @@ -168,12 +169,20 @@ async function consumeVerificationToken (verificationToken, csrfToken) {
return null
}

// delete the verification token, we don't need it anymore
await tx.verificationToken.delete({
where: {
token: tokenWithState
}
// since we touched this token, we can delete it
// so that if state is compromised, it's not used again
await tx.verificationToken.delete({ where: { id: token.id } })

// check if the state is valid
const encodedState = token.token.split('|')[1]
const decodedState = await decode({
token: encodedState,
secret: process.env.NEXTAUTH_SECRET
})
// if the state is invalid, we can't use this token
if (decodedState.csrf !== csrfToken) {
return null
}

return token.identifier
})
Expand All @@ -186,6 +195,7 @@ async function consumeVerificationToken (verificationToken, csrfToken) {
// return the user id
return { status: 'OK', userId: Number(identifier) }
} catch (error) {
console.error('cannot validate verification token', error)
return { status: 'ERROR', reason: 'cannot validate verification token' }
}
}
Expand Down