Adds end-to-end custom apex domain support: workspace-scoped
registration via OpenSRS (Tucows), authoritative DNS via Google
Cloud DNS, and one-call attach that wires registrar nameservers,
DNS records, and Coolify app routing in a single transactional
flow.
Schema (additive, idempotent — run /api/admin/migrate after deploy)
- vibn_workspaces.dns_provider TEXT DEFAULT 'cloud_dns'
Per-workspace DNS backend choice. Future: 'cira_dzone' for
strict CA-only residency on .ca.
- vibn_domains
One row per registered/intended apex. Tracks status
(pending|active|failed|expired), registrar order id, encrypted
registrar manage-user creds (AES-256-GCM, VIBN_SECRETS_KEY),
period, dates, dns_provider/zone_id/nameservers, and a
created_by audit field.
- vibn_domain_events
Append-only lifecycle audit (register.attempt/success/fail,
attach.success, ns.update, lock.toggle, etc).
- vibn_billing_ledger
Workspace-scoped money ledger (CAD by default) with
ref_type/ref_id back to the originating row.
OpenSRS XML client (lib/opensrs.ts)
- Mode-gated host/key (OPENSRS_MODE=test → horizon sandbox,
rejectUnauthorized:false; live → rr-n1-tor, strict TLS).
- MD5 double-hash signature.
- Pure Node https module (no undici dep).
- Verbs: lookupDomain, getDomainPrice, checkDomain, registerDomain,
updateDomainNameservers, setDomainLock, getResellerBalance.
- TLD policy: minPeriodFor() bumps .ai to 2y; CPR/legalType
plumbed through for .ca; registrations default to UNLOCKED so
immediate NS updates succeed without a lock toggle.
DNS provider abstraction (lib/dns/{provider,cloud-dns}.ts)
- DnsProvider interface (createZone/getZone/setRecords/deleteZone)
so the workspace residency knob can swap backends later.
- cloudDnsProvider implementation against Google Cloud DNS using
the existing vibn-workspace-provisioner SA (roles/dns.admin).
- Idempotent zone creation, additions+deletions diff for rrsets.
Shared GCP auth (lib/gcp-auth.ts)
- Single getGcpAccessToken() helper used by Cloud DNS today and
future GCP integrations. Prefers GOOGLE_SERVICE_ACCOUNT_KEY_B64,
falls back to ADC.
Workspace-scoped helpers (lib/domains.ts)
- listDomainsForWorkspace, getDomainForWorkspace, createDomainIntent,
markDomainRegistered, markDomainFailed, markDomainAttached,
recordDomainEvent, recordLedgerEntry.
Attach orchestrator (lib/domain-attach.ts)
Single function attachDomain() reused by REST + MCP. For one
apex it:
1. Resolves target → Coolify app uuid OR raw IP OR CNAME.
2. Ensures Cloud DNS managed zone exists.
3. Writes A / CNAME records (apex + requested subdomains).
4. Updates registrar nameservers, with auto unlock-retry-relock
fallback for TLDs that reject NS changes while locked.
5. PATCHes the Coolify application's domain list so Traefik
routes the new hostname.
6. Persists dns_provider/zone_id/nameservers and emits an
attach.success domain_event.
AttachError carries a stable .tag + http status so the caller
can map registrar/dns/coolify failures cleanly.
REST endpoints
- POST /api/workspaces/[slug]/domains/search
- GET /api/workspaces/[slug]/domains
- POST /api/workspaces/[slug]/domains
- GET /api/workspaces/[slug]/domains/[domain]
- POST /api/workspaces/[slug]/domains/[domain]/attach
All routes go through requireWorkspacePrincipal (session OR
Authorization: Bearer vibn_sk_...). Register is idempotent:
re-issuing for an existing intent re-attempts at OpenSRS without
duplicating the row or charging twice.
MCP bridge (app/api/mcp/route.ts → version 2.2.0)
Adds five tools backed by the same library code:
- domains.search (batch availability + pricing)
- domains.list (workspace-owned)
- domains.get (single + recent events)
- domains.register (idempotent OpenSRS register)
- domains.attach (full Cloud DNS + registrar + Coolify)
Sandbox smoke tests (scripts/smoke-opensrs-*.ts)
Standalone Node scripts validating each new opensrs.ts call against
horizon.opensrs.net: balance + lookup + check, TLD policy
(.ca/.ai/.io/.com), full register flow, NS update with systemdns
nameservers, and the lock/unlock toggle that backs the attach
fallback path.
Post-deploy checklist
1. POST https://vibnai.com/api/admin/migrate
-H "x-admin-secret: $ADMIN_MIGRATE_SECRET"
2. Set OPENSRS_* env vars on the vibn-frontend Coolify app
(RESELLER_USERNAME, API_KEY_LIVE, API_KEY_TEST, HOST_LIVE,
HOST_TEST, PORT, MODE). Without them, only domains.list/get
work; search/register/attach return 500.
3. GCP_PROJECT_ID is read from env or defaults to master-ai-484822.
4. Live attach end-to-end against a real apex is queued as a
follow-up — sandbox path is fully proven.
Not in this commit (deliberate)
- The 100+ unrelated in-flight files (mvp-setup wizard, justine
homepage rework, BuildLivePlanPanel, etc) — kept local to keep
blast radius minimal.
Made-with: Cursor
261 lines
8.9 KiB
TypeScript
261 lines
8.9 KiB
TypeScript
/**
|
|
* Shared domain-attach workflow used by the REST endpoint and the MCP tool.
|
|
*
|
|
* Extracted from the route handler so there's exactly one code path that
|
|
* writes DNS, updates the registrar, mutates Coolify, and persists the
|
|
* vibn_domains row. All failures are `AttachError` with a status + tag
|
|
* the caller can map to an HTTP response.
|
|
*/
|
|
|
|
import {
|
|
getApplicationInProject,
|
|
listServers,
|
|
setApplicationDomains,
|
|
TenantError,
|
|
} from '@/lib/coolify';
|
|
import { cloudDnsProvider } from '@/lib/dns/cloud-dns';
|
|
import type { DnsRecord } from '@/lib/dns/provider';
|
|
import {
|
|
markDomainAttached,
|
|
recordDomainEvent,
|
|
type VibnDomain,
|
|
} from '@/lib/domains';
|
|
import { setDomainLock, updateDomainNameservers, OpenSrsError } from '@/lib/opensrs';
|
|
import { parseDomainsString } from '@/lib/naming';
|
|
import type { VibnWorkspace } from '@/lib/workspaces';
|
|
|
|
export interface AttachInput {
|
|
appUuid?: string;
|
|
ip?: string;
|
|
cname?: string;
|
|
subdomains?: string[];
|
|
updateRegistrarNs?: boolean;
|
|
}
|
|
|
|
export interface AttachResult {
|
|
domain: VibnDomain;
|
|
zone: { apex: string; zoneId: string; nameservers: string[] };
|
|
records: Array<{ name: string; type: string; rrdatas: string[] }>;
|
|
registrarNsUpdate: { responseCode: string; responseText: string } | null;
|
|
coolifyUpdate: { appUuid: string; domains: string[] } | null;
|
|
}
|
|
|
|
/**
|
|
* Status codes follow the HTTP convention so callers can pass them straight
|
|
* to NextResponse.
|
|
*/
|
|
export class AttachError extends Error {
|
|
constructor(
|
|
public readonly status: number,
|
|
public readonly tag: string,
|
|
message: string,
|
|
public readonly extra?: Record<string, unknown>,
|
|
) {
|
|
super(message);
|
|
this.name = 'AttachError';
|
|
}
|
|
}
|
|
|
|
const DEFAULT_SUBS = ['@', 'www'];
|
|
|
|
export async function attachDomain(
|
|
workspace: VibnWorkspace,
|
|
domainRow: VibnDomain,
|
|
input: AttachInput,
|
|
): Promise<AttachResult> {
|
|
if (domainRow.status !== 'active') {
|
|
throw new AttachError(409, 'not_active', `Domain is not active (status=${domainRow.status})`);
|
|
}
|
|
if (!input.appUuid && !input.ip && !input.cname) {
|
|
throw new AttachError(400, 'no_target', 'One of `appUuid`, `ip`, or `cname` is required');
|
|
}
|
|
|
|
const apex = domainRow.domain;
|
|
const subs = normalizeSubdomains(input.subdomains);
|
|
if (subs.length === 0) {
|
|
throw new AttachError(400, 'no_subdomains', '`subdomains` must contain at least one entry');
|
|
}
|
|
|
|
// Resolve the upstream target
|
|
let targetIps: string[] | null = null;
|
|
let targetCname: string | null = null;
|
|
let coolifyAppUuid: string | null = null;
|
|
|
|
if (input.appUuid) {
|
|
if (!workspace.coolify_project_uuid) {
|
|
throw new AttachError(503, 'no_project', 'Workspace has no Coolify project yet');
|
|
}
|
|
try {
|
|
await getApplicationInProject(input.appUuid, workspace.coolify_project_uuid);
|
|
} catch (err) {
|
|
if (err instanceof TenantError) {
|
|
throw new AttachError(403, 'tenant_mismatch', err.message);
|
|
}
|
|
throw new AttachError(404, 'app_not_found', 'Coolify app not found in this workspace');
|
|
}
|
|
coolifyAppUuid = input.appUuid;
|
|
|
|
const serverUuid = workspace.coolify_server_uuid;
|
|
if (!serverUuid) {
|
|
throw new AttachError(503, 'no_server', 'Workspace has no Coolify server — cannot resolve public IP');
|
|
}
|
|
const servers = await listServers();
|
|
const server = servers.find(s => s.uuid === serverUuid);
|
|
if (!server || !server.ip) {
|
|
throw new AttachError(502, 'server_ip_unknown', `Coolify server ${serverUuid} has no public IP`);
|
|
}
|
|
targetIps = [server.ip];
|
|
} else if (input.ip) {
|
|
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(input.ip)) {
|
|
throw new AttachError(400, 'bad_ip', '`ip` must be a valid IPv4 address');
|
|
}
|
|
targetIps = [input.ip];
|
|
} else if (input.cname) {
|
|
const cname = input.cname.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
|
|
if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(cname)) {
|
|
throw new AttachError(400, 'bad_cname', '`cname` must be a valid hostname');
|
|
}
|
|
targetCname = cname.endsWith('.') ? cname : `${cname}.`;
|
|
if (subs.includes('@')) {
|
|
throw new AttachError(400, 'cname_apex', 'CNAME on apex (@) is not allowed — use `ip` for the apex');
|
|
}
|
|
}
|
|
|
|
// 1. Ensure Cloud DNS zone exists
|
|
let zone;
|
|
try {
|
|
zone = await cloudDnsProvider.createZone(apex);
|
|
} catch (err) {
|
|
throw new AttachError(502, 'zone_create_failed', err instanceof Error ? err.message : String(err));
|
|
}
|
|
|
|
// 2. Write rrsets
|
|
const records: DnsRecord[] = subs.flatMap<DnsRecord>(sub => {
|
|
if (targetIps) return [{ name: sub, type: 'A', rrdatas: targetIps, ttl: 300 }];
|
|
if (targetCname) return [{ name: sub, type: 'CNAME', rrdatas: [targetCname], ttl: 300 }];
|
|
return [];
|
|
});
|
|
|
|
try {
|
|
await cloudDnsProvider.setRecords(apex, records);
|
|
} catch (err) {
|
|
throw new AttachError(502, 'rrset_write_failed', err instanceof Error ? err.message : String(err));
|
|
}
|
|
|
|
// 3. Registrar-side nameserver update
|
|
//
|
|
// Some TLDs reject NS changes while the domain is locked (response 405).
|
|
// We unlock → update NS → relock so the end state is "locked with the
|
|
// right nameservers". If the initial NS update returns 405 we retry once
|
|
// with the unlock sandwich.
|
|
let registrarNsUpdate: { responseCode: string; responseText: string } | null = null;
|
|
const updateNs = input.updateRegistrarNs !== false;
|
|
if (updateNs && zone.nameservers.length >= 2) {
|
|
try {
|
|
registrarNsUpdate = await updateDomainNameservers(apex, zone.nameservers);
|
|
} catch (err) {
|
|
const locked405 =
|
|
err instanceof OpenSrsError &&
|
|
err.code === '405' &&
|
|
/status prohibits operation/i.test(err.message);
|
|
if (!locked405) {
|
|
if (err instanceof OpenSrsError) {
|
|
throw new AttachError(
|
|
502,
|
|
'registrar_ns_failed',
|
|
`Registrar NS update failed (${err.code}): ${err.message}`,
|
|
{ zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
|
|
);
|
|
}
|
|
throw new AttachError(502, 'registrar_ns_failed', err instanceof Error ? err.message : String(err));
|
|
}
|
|
// Locked → unlock, update, relock.
|
|
try {
|
|
await setDomainLock(apex, false);
|
|
registrarNsUpdate = await updateDomainNameservers(apex, zone.nameservers);
|
|
} catch (retryErr) {
|
|
throw new AttachError(
|
|
502,
|
|
'registrar_ns_failed',
|
|
`Registrar NS retry failed: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`,
|
|
{ zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
|
|
);
|
|
} finally {
|
|
// Best-effort relock — if this fails we log but don't fail the attach.
|
|
try {
|
|
await setDomainLock(apex, true);
|
|
} catch (relockErr) {
|
|
console.warn('[attach] relock failed for', apex, relockErr);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 4. Coolify domain list
|
|
let coolifyUpdate: { appUuid: string; domains: string[] } | null = null;
|
|
if (coolifyAppUuid && workspace.coolify_project_uuid) {
|
|
try {
|
|
const app = await getApplicationInProject(coolifyAppUuid, workspace.coolify_project_uuid);
|
|
const current = parseDomainsString(app.domains ?? app.fqdn ?? '');
|
|
const toAdd = subs.map(s => (s === '@' ? apex : `${s}.${apex}`));
|
|
const merged = uniq([...current, ...toAdd]);
|
|
await setApplicationDomains(coolifyAppUuid, merged, { forceOverride: true });
|
|
coolifyUpdate = { appUuid: coolifyAppUuid, domains: merged };
|
|
} catch (err) {
|
|
throw new AttachError(
|
|
502,
|
|
'coolify_domains_failed',
|
|
`DNS is wired but Coolify domain-list update failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
{ zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
|
|
);
|
|
}
|
|
}
|
|
|
|
// 5. Persist + event
|
|
const updated = await markDomainAttached({
|
|
domainId: domainRow.id,
|
|
dnsProvider: cloudDnsProvider.id,
|
|
dnsZoneId: zone.zoneId,
|
|
dnsNameservers: zone.nameservers,
|
|
});
|
|
|
|
await recordDomainEvent({
|
|
domainId: domainRow.id,
|
|
workspaceId: workspace.id,
|
|
type: 'attach.success',
|
|
payload: {
|
|
zone: zone.zoneId,
|
|
nameservers: zone.nameservers,
|
|
records: records.map(r => ({ name: r.name, type: r.type, rrdatas: r.rrdatas })),
|
|
coolifyAppUuid,
|
|
registrarNsUpdate,
|
|
},
|
|
});
|
|
|
|
return {
|
|
domain: updated,
|
|
zone,
|
|
records: records.map(r => ({ name: r.name, type: r.type, rrdatas: r.rrdatas })),
|
|
registrarNsUpdate,
|
|
coolifyUpdate,
|
|
};
|
|
}
|
|
|
|
function normalizeSubdomains(input?: string[]): string[] {
|
|
const raw = input && input.length > 0 ? input : DEFAULT_SUBS;
|
|
const out: string[] = [];
|
|
for (const s of raw) {
|
|
if (typeof s !== 'string') continue;
|
|
const clean = s.trim().toLowerCase();
|
|
if (!clean) continue;
|
|
if (clean === '@' || /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/.test(clean)) {
|
|
out.push(clean);
|
|
}
|
|
}
|
|
return uniq(out);
|
|
}
|
|
|
|
function uniq<T>(xs: T[]): T[] {
|
|
return Array.from(new Set(xs));
|
|
}
|