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

Draft
wants to merge 73 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 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
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
7 changes: 5 additions & 2 deletions .env.development
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PRISMA_SLOW_LOGS_MS=
GRAPHQL_SLOW_LOGS_MS=
NODE_ENV=development
COMPOSE_PROFILES='minimal,images,search,payments,wallets,email,capture'
COMPOSE_PROFILES='minimal,images,search,payments,wallets,email,capture,domains'

############################################################################
# OPTIONAL SECRETS #
Expand Down Expand Up @@ -114,7 +114,7 @@ NEXT_PUBLIC_EXTRA_LONG_POLL_INTERVAL=300000

# containers can't use localhost, so we need to use the container name
IMGPROXY_URL_DOCKER=http://imgproxy:8080
MEDIA_URL_DOCKER=http://s3:4566/uploads
MEDIA_URL_DOCKER=http://aws:4566/uploads

# postgres container stuff
POSTGRES_PASSWORD=password
Expand Down Expand Up @@ -177,6 +177,9 @@ AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
PERSISTENCE=1
SKIP_SSL_CERT_DOWNLOAD=1
# custom domain ACM, ELBv2
LOCALSTACK_ENDPOINT=http://aws:4566
ELB_LISTENER_ARN=arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/sndev-lb/1234567890abcdef/1234567890abcdef

# tor proxy
TOR_PROXY=http://tor:7050/
Expand Down
44 changes: 44 additions & 0 deletions api/acm/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import AWS from 'aws-sdk'

AWS.config.update({
region: 'us-east-1'
})

const config = {
// for local development, we use the LOCALSTACK_ENDPOINT
endpoint: process.env.NODE_ENV === 'development' ? process.env.LOCALSTACK_ENDPOINT : undefined
}

export async function requestCertificate (domain) {
const acm = new AWS.ACM(config)
const params = {
DomainName: domain,
ValidationMethod: 'DNS',
Tags: [
{
Key: 'ManagedBy',
Value: 'stacker.news'
}
]
}

const certificate = await acm.requestCertificate(params).promise()
return certificate.CertificateArn
}

export async function describeCertificate (certificateArn) {
const acm = new AWS.ACM(config)
const certificate = await acm.describeCertificate({ CertificateArn: certificateArn }).promise()
return certificate
}

export async function getCertificateStatus (certificateArn) {
const certificate = await describeCertificate(certificateArn)
return certificate.Certificate.Status
}

export async function deleteCertificate (certificateArn) {
const acm = new AWS.ACM(config)
const result = await acm.deleteCertificate({ CertificateArn: certificateArn }).promise()
return result
}
42 changes: 42 additions & 0 deletions api/elb/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import AWS from 'aws-sdk'
import { MockELBv2 } from './mocks'

const ELB_LISTENER_ARN = process.env.ELB_LISTENER_ARN

AWS.config.update({
region: 'us-east-1'
})

// attach a certificate to the elb listener
async function attachCertificateToElb (certificateArn) {
const elbv2 = process.env.NODE_ENV === 'development'
? new MockELBv2() // use the mocked elb for local development
: new AWS.ELBv2()

// attach the certificate
// AWS doesn't throw an error if the certificate is already attached to the listener
await elbv2.addListenerCertificates({
ListenerArn: ELB_LISTENER_ARN,
Certificates: [{ CertificateArn: certificateArn }]
}).promise()

return true
}

// detach a certificate from the elb listener
async function detachCertificateFromElb (certificateArn) {
const elbv2 = process.env.NODE_ENV === 'development'
? new MockELBv2() // use the mocked elb for local development
: new AWS.ELBv2()

// detach the certificate
// AWS doesn't throw an error if the certificate is not attached to the listener
await elbv2.removeListenerCertificates({
ListenerArn: ELB_LISTENER_ARN,
Certificates: [{ CertificateArn: certificateArn }]
}).promise()

return true
}

export { attachCertificateToElb, detachCertificateFromElb }
120 changes: 120 additions & 0 deletions api/elb/mocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// mock Load Balancers and Listeners for testing
const mockedElb = {
loadBalancers: [
{
LoadBalancerArn: 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/sndev-lb/1234567890abcdef',
DNSName: 'sndev-lb.us-east-1.elb.amazonaws.com',
LoadBalancerName: 'sndev-lb',
Type: 'application'
}
],
listeners: [
{
ListenerArn: 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/sndev-lb/1234567890abcdef/1234567890abcdef',
LoadBalancerArn: 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/sndev-lb/1234567890abcdef',
Protocol: 'HTTPS',
Port: 443
}
],
certificates: []
}

// mock AWS.ELBv2 class
class MockELBv2 {
// mock describeLoadBalancers
// return the load balancers that match the names in the params
describeLoadBalancers (params) {
const { Names } = params
let loadBalancers = [...mockedElb.loadBalancers]

if (Names && Names.length > 0) {
loadBalancers = loadBalancers.filter(lb => Names.includes(lb.LoadBalancerName))
}

return {
promise: () => Promise.resolve({ LoadBalancers: loadBalancers })
}
}

// mock describeListeners
// return the listeners that match the load balancer arn in the params
describeListeners (params) {
const { LoadBalancerArn, Filters } = params
let listeners = [...mockedElb.listeners]

if (LoadBalancerArn) {
listeners = listeners.filter(listener => listener.LoadBalancerArn === LoadBalancerArn)
}

if (Filters && Filters.length > 0) {
Filters.forEach(filter => {
if (filter.Name === 'protocol' && filter.Values) {
listeners = listeners.filter(listener =>
filter.Values.includes(listener.Protocol)
)
}
})
}

return {
promise: () => Promise.resolve({ Listeners: listeners })
}
}

// mock describeListenerCertificates
// return the certificates that match the listener arn in the params
describeListenerCertificates (params) {
const { ListenerArn } = params
const certificates = mockedElb.certificates
.filter(cert => cert.ListenerArn === ListenerArn)
.map(cert => ({ CertificateArn: cert.CertificateArn }))

return {
promise: () => Promise.resolve({ Certificates: certificates })
}
}

// mock addListenerCertificates
// add the certificates to the mockedElb.certificates
addListenerCertificates (params) {
const { ListenerArn, Certificates } = params

Certificates.forEach(cert => {
// ELBv2 checks if the certificate is already attached to the listener
// and doesn't add it again if it is
const exists = mockedElb.certificates.some(
c => c.ListenerArn === ListenerArn && c.CertificateArn === cert.CertificateArn
)

if (!exists) {
mockedElb.certificates.push({
ListenerArn,
CertificateArn: cert.CertificateArn
})
}
})

return {
promise: () => Promise.resolve({})
}
}

// mock removeListenerCertificates
// remove the certificates from the mockedElb.certificates
// AWS doesn't throw an error if the certificate is not attached to the listener
removeListenerCertificates (params) {
const { ListenerArn, Certificates } = params

Certificates.forEach(cert => {
mockedElb.certificates = mockedElb.certificates.filter(
c => !(c.ListenerArn === ListenerArn && c.CertificateArn === cert.CertificateArn)
)
})

return {
promise: () => Promise.resolve({})
}
}
}

export { MockELBv2, mockedElb }
140 changes: 140 additions & 0 deletions api/resolvers/domain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { validateSchema, customDomainSchema } from '@/lib/validate'
import { GqlAuthenticationError, GqlInputError } from '@/lib/error'
import { getDomainMapping } from '@/lib/domains'
import { SN_ADMIN_IDS } from '@/lib/constants'

async function cleanDomainVerificationJobs (domain, models) {
// delete any existing domain verification job left
await models.$queryRaw`
DELETE FROM pgboss.job
WHERE name = 'domainVerification'
AND data->>'domainId' = ${domain.id}::TEXT`
}

export default {
Query: {
domain: async (parent, { subName }, { models }) => {
return models.domain.findUnique({
where: { subName },
include: { records: true, attempts: true, certificate: true }
})
},
domainMapping: async (parent, { domainName }, { models }) => {
const mapping = await getDomainMapping(domainName)
return mapping
}
},
Mutation: {
setDomain: async (parent, { subName, domainName }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}

if (!SN_ADMIN_IDS.includes(Number(me.id))) {
throw new Error('not an admin')
}

const sub = await models.sub.findUnique({ where: { name: subName } })
if (!sub) {
throw new GqlInputError('sub not found')
}

if (sub.userId !== me.id) {
throw new GqlInputError('you do not own this sub')
}

// we need to get the existing domain if we're updating or re-verifying
const existing = await models.domain.findUnique({
where: { subName },
include: { records: true }
})

if (domainName) {
// validate the domain name
domainName = domainName.trim() // protect against trailing spaces
await validateSchema(customDomainSchema, { domainName })

// updating the domain name and recovering from HOLD is allowed
if (existing && existing.domainName === domainName && existing.status !== 'HOLD') {
throw new GqlInputError('domain already set')
}

// we should always make sure to get a new updatedAt timestamp
// to know when should we put the domain in HOLD during verification
const initializeDomain = {
domainName,
updatedAt: new Date(),
status: 'PENDING'
}

const updatedDomain = await models.$transaction(async tx => {
// we're changing the domain name, delete the domain if it exists
if (existing) {
// delete any existing domain verification job left
await cleanDomainVerificationJobs(existing, tx)
// delete the domain if we're not resuming from HOLD
if (existing.status !== 'HOLD') {
await tx.domain.delete({ where: { subName } })
}
}

const domain = await tx.domain.create({
data: {
...initializeDomain,
sub: { connect: { name: subName } }
}
})

// create the CNAME verification record
await tx.domainVerificationRecord.create({
data: {
domainId: domain.id,
type: 'CNAME',
recordName: domainName,
recordValue: new URL(process.env.NEXT_PUBLIC_URL).host
}
})

// create the job to verify the domain in 30 seconds
await tx.$executeRaw`
INSERT INTO pgboss.job (name, data, retrylimit, retrydelay, startafter, keepuntil, singletonkey)
VALUES ('domainVerification',
jsonb_build_object('domainId', ${domain.id}::INTEGER),
3,
60,
now() + interval '30 seconds',
now() + interval '2 days',
'domainVerification:' || ${domain.id}::TEXT -- domain <-> job isolation
)`

return domain
})

return updatedDomain
} else {
try {
if (existing) {
return await models.$transaction(async tx => {
// delete any existing domain verification job left
await cleanDomainVerificationJobs(existing, tx)
// delete the domain
return await tx.domain.delete({ where: { subName } })
})
}
return null
} catch (error) {
console.error(error)
throw new GqlInputError('failed to delete domain')
}
}
}
},
Domain: {
records: async (domain) => {
if (!domain.records) return []

// O(1) lookups by type, simpler checks for CNAME and ACM validation records
return Object.fromEntries(domain.records.map(record => [record.type, record]))
}
}
}
3 changes: 2 additions & 1 deletion api/resolvers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { GraphQLScalarType, Kind } from 'graphql'
import { createIntScalar } from 'graphql-scalar'
import paidAction from './paidAction'
import vault from './vault'
import domain from './domain'

const date = new GraphQLScalarType({
name: 'Date',
Expand Down Expand Up @@ -56,4 +57,4 @@ const limit = createIntScalar({

export default [user, item, message, wallet, lnurl, notifications, invite, sub,
upload, search, growth, rewards, referrals, price, admin, blockHeight, chainFee,
{ JSONObject }, { Date: date }, { Limit: limit }, paidAction, vault]
domain, { JSONObject }, { Date: date }, { Limit: limit }, paidAction, vault]
Loading