Skip to content

custom domains - middleware and verification #2145

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 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
22 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
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
9 changes: 7 additions & 2 deletions .env.development
Original file line number Diff line number Diff line change
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,7 @@ AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
PERSISTENCE=1
SKIP_SSL_CERT_DOWNLOAD=1
LOCALSTACK_ENDPOINT=http://aws:4566

# tor proxy
TOR_PROXY=http://tor:7050/
Expand All @@ -190,4 +191,8 @@ CPU_SHARES_IMPORTANT=1024
CPU_SHARES_MODERATE=512
CPU_SHARES_LOW=256

NEXT_TELEMETRY_DISABLED=1
NEXT_TELEMETRY_DISABLED=1

# custom domains stuff
# DNS resolver for custom domain verification
DNS_RESOLVER=1.1.1.1
53 changes: 53 additions & 0 deletions api/acm/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import AWS from 'aws-sdk'

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

const config = {}

export async function requestCertificate (domain) {
// for local development, we use the LOCALSTACK_ENDPOINT
if (process.env.NODE_ENV === 'development') {
config.endpoint = process.env.LOCALSTACK_ENDPOINT
}

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) {
if (process.env.NODE_ENV === 'development') {
config.endpoint = process.env.LOCALSTACK_ENDPOINT
}
Copy link
Member

Choose a reason for hiding this comment

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

I think we can define this once in the file scoped config variable rather than checking it in every function

Copy link
Member Author

Choose a reason for hiding this comment

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

I feared AWS SDK (v2) reaction to undefined properties, but afaict it should ignore them, adjusted ^^

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) {
if (process.env.NODE_ENV === 'development') {
config.endpoint = process.env.LOCALSTACK_ENDPOINT
}
const acm = new AWS.ACM(config)
const result = await acm.deleteCertificate({ CertificateArn: certificateArn }).promise()
console.log(`delete certificate attempt for ${certificateArn}, result: ${JSON.stringify(result)}`)
return result
}
175 changes: 175 additions & 0 deletions api/resolvers/domain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { validateSchema, customDomainSchema } from '@/lib/validate'
import { GqlAuthenticationError, GqlInputError } from '@/lib/error'
import { randomBytes } from 'node:crypto'
import { getDomainMapping } from '@/lib/domains'
import { deleteDomainCertificate } from '@/lib/domain-verification'

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()
}

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')
}

domainName = domainName.trim() // protect against trailing spaces
if (domainName && !validateSchema(customDomainSchema, { domainName })) {
throw new GqlInputError('invalid domain format')
}

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

if (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 => {
// clean any existing domain verification job left
if (existing && existing.status === 'HOLD') {
await cleanDomainVerificationJobs(existing, tx)
}

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

// if on HOLD, get the existing TXT record
const existingTXT = existing && existing.status === 'HOLD'
? await tx.domainVerificationRecord.findUnique({
where: {
domainId_type_recordName: {
domainId: existing.id,
type: 'TXT',
recordName: '_snverify.' + existing.domainName
}
}
})
: null

// create the verification records
const verificationRecords = [
{
domainId: domain.id,
type: 'CNAME',
recordName: domainName,
recordValue: new URL(process.env.NEXT_PUBLIC_URL).host
},
{
domainId: domain.id,
type: 'TXT',
recordName: '_snverify.' + domainName,
recordValue: existingTXT // if we're resuming from HOLD, use the existing TXT record
? existingTXT.recordValue
: randomBytes(32).toString('base64')
}
]

// create the verification records
for (const record of verificationRecords) {
await tx.domainVerificationRecord.upsert({
where: {
domainId_type_recordName: {
domainId: domain.id,
type: record.type,
recordName: record.recordName
}
},
update: record,
create: record
})
}

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

return domain
})

return updatedDomain
} else {
try {
// Delete any existing domain verification jobs
if (existing) {
return await models.$transaction(async tx => {
// delete any existing domain verification job left
await cleanDomainVerificationJobs(existing, tx)

// deleting a domain will also delete the domain certificate
// but we need to make sure to delete the certificate from ACM
if (existing.certificate) {
await deleteDomainCertificate(existing.certificate.certificateArn)
}
Copy link
Member

Choose a reason for hiding this comment

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

Making network requests from inside an interactive tx is a bad idea. It consumes the db connection for the entire roundtrip.

I recommend deleting the certificate before entering the tx or after, depending on which makes sense.

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh! You're right, totally missed this. Going to push changes in a bit :)


// 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, TXT 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]
3 changes: 3 additions & 0 deletions api/resolvers/sub.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,9 @@ export default {

return sub.SubSubscription?.length > 0
},
domain: async (sub, args, { models }) => {
return models.domain.findUnique({ where: { subName: sub.name } })
},
createdAt: sub => sub.createdAt || sub.created_at
}
}
Expand Down
12 changes: 12 additions & 0 deletions api/ssrApollo.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,17 @@ export function getGetServerSideProps (

const client = await getSSRApolloClient({ req, res })

const isCustomDomain = req.headers.host !== process.env.NEXT_PUBLIC_URL.replace(/^https?:\/\//, '')
const subName = req.headers['x-stacker-news-subname'] || null
let domain = null
if (isCustomDomain && subName) {
domain = {
domainName: req.headers.host,
subName
// TODO: custom branding
}
}

let { data: { me } } = await client.query({ query: ME })

// required to redirect to /signup on page reload
Expand Down Expand Up @@ -216,6 +227,7 @@ export function getGetServerSideProps (
return {
props: {
...props,
domain,
me,
price,
blockHeight,
Expand Down
Loading