Skip to content
  1. Home
  2. workspace
Checking…
Demo view — sanitized data only. Sign in over HTTPS to create projects and manage the workspace.

AI Engineering Workspace

Partial

Chat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.

Project files

read-only

app/src/app/api/cloud/domains/route.ts

1import dns from "node:dns/promises";
2import crypto from "node:crypto";
3import { asSystem, db, now } from "@/lib/db";
4import { auditT, nodeOf, notFound, tenant } from "@/lib/tenant";
5import { nodeState, uid } from "@/lib/cloud";
6import { enqueue } from "@/lib/apps";
7import { emergencyStopped } from "@/lib/gates";
8import { checkHostname, dnsInstructions, evaluateDns, renderCaddyfile, verifyName } from "@/lib/proxy-core.mjs";
9export const dynamic = "force-dynamic";
10const E = (error: string, status: number) => Response.json({ error }, { status });
11const resolver = () => { const r = new dns.Resolver({ timeout: 3000, tries: 1 }); r.setServers(["8.8.8.8", "1.1.1.1"]); return r; };
12const safe = async <T,>(p: Promise<T>, d: T) => { try { return await p; } catch { return d; } };
13async function siteList(orgId: string, nodeId: string) {
14 const ds = await db().prepare("SELECT * FROM domains WHERE org_id=? AND node_id=? AND status='verified' ORDER BY hostname").all(orgId, nodeId) as any[]; const sites: any[] = []; const skipped: string[] = [];
15 for (const d of ds) { if (d.redirect_to) { sites.push({ hostname: d.hostname, redirectTo: d.redirect_to }); continue; } if (!d.deployment_id) { skipped.push(`${d.hostname}: not mapped to an application`); continue; }
16 const a = await db().prepare("SELECT port,status FROM app_deployments WHERE id=? AND org_id=? AND node_id=?").get(d.deployment_id, orgId, nodeId) as any; if (!a || a.status !== "running") { skipped.push(`${d.hostname}: mapped application is not running`); continue; } sites.push({ hostname: d.hostname, port: a.port, deploymentId: d.deployment_id }); }
17 return { sites, skipped };
18}
19async function applyNode(ctx: any, nodeId: string) {
20 const n = await nodeOf(ctx, nodeId); if (!n || n.revoked_at) return E("node not found or revoked", 404); if (nodeState(n) !== "online") return E("server is offline", 409); if (!n.exec_authorized) return E("this server is not authorized for remote execution", 409);
21 if (await db().prepare("SELECT 1 x FROM node_jobs WHERE node_id=? AND kind='proxy.apply' AND status IN ('queued','delivered') AND created_at > ?").get(n.id, new Date(Date.now() - 600_000).toISOString())) return E("a proxy update is already in progress", 409);
22 const { sites, skipped } = await siteList(ctx.orgId, n.id); const job = await enqueue(ctx.orgId, n.id, "proxy.apply" as any, { sites }); await auditT(ctx, "domain.apply", n.id, { sites: sites.length }); return Response.json({ ok: true, jobId: job, sites: sites.length, skipped });
23}
24export async function GET() {
25 const g = await tenant("viewer"); if (g.res) return g.res; const o = g.ctx.orgId;
26 const nodes = await db().prepare("SELECT id,label,public_host,hostname,metrics,last_seen,enroll_used_at,revoked_at FROM nodes WHERE org_id=? AND revoked_at IS NULL AND enroll_used_at IS NOT NULL").all(o) as any[]; const nm = new Map(nodes.map(n => [n.id, n]));
27 const apps = await db().prepare("SELECT id,node_id,name,port,status FROM app_deployments WHERE org_id=? AND status<>'removed'").all(o);
28 const rows = (await db().prepare("SELECT * FROM domains WHERE org_id=? ORDER BY created_at DESC").all(o) as any[]).map(d => { const n = nm.get(d.node_id); const target = n?.public_host || n?.hostname || null; return { id: d.id, hostname: d.hostname, node_id: d.node_id, deployment_id: d.deployment_id, status: d.status, dns_status: d.dns_status, is_primary: !!d.is_primary, redirect_to: d.redirect_to, tls_status: d.tls_status, tls_expires: d.tls_expires, proxy_status: d.proxy_status, instructions: dnsInstructions(d.hostname, d.verify_token, target) }; });
29 const servers = nodes.map(n => { const m = n.metrics ? JSON.parse(n.metrics) : null; return { id: n.id, label: n.label, state: nodeState(n), public_host: n.public_host, caddy: !!m?.caps?.caddy }; });
30 const preview: Record<string, string> = {}; for (const n of nodes) { const { sites } = await siteList(o, n.id); preview[n.id] = renderCaddyfile(sites); }
31 return Response.json({ domains: rows, servers, apps, preview, renewal: "Certificates are issued and renewed automatically by Caddy on the server (about 30 days before expiry). Status is reported by the agent when the proxy is updated.", proxy: "Caddy" });
32}
33export async function POST(req: Request) {
34 const g = await tenant("developer", { write: true }); if (g.res) return g.res; const ctx = g.ctx; const b = await req.json().catch(() => ({})); const d = db(); const act = String(b.action ?? "");
35 if (act === "apply" && await emergencyStopped()) return E("emergency stop is engaged: new work is blocked", 503);
36 if (act === "add") {
37 const h = checkHostname(b.hostname); if (!h.ok) return E(h.error, 422); const n = await nodeOf(ctx, String(b.nodeId)); if (!n || n.revoked_at || !n.enroll_used_at) return notFound();
38 if (await asSystem(() => d.prepare("SELECT 1 x FROM domains WHERE hostname=?").get(h.hostname))) return E("this domain is already connected to an account", 409);
39 let dep: string | null = null; if (b.deploymentId) { const a = await d.prepare("SELECT id FROM app_deployments WHERE id=? AND org_id=? AND node_id=? AND status<>'removed'").get(String(b.deploymentId), ctx.orgId, n.id) as any; if (!a) return E("application not found on that server", 404); dep = a.id; }
40 const id = uid("dom_"), token = "zlv_" + crypto.randomBytes(16).toString("hex");
41 try { await d.prepare("INSERT INTO domains(id,org_id,node_id,deployment_id,hostname,verify_token,created_by,created_at) VALUES(?,?,?,?,?,?,?,?)").run(id, ctx.orgId, n.id, dep, h.hostname, token, ctx.email, now()); } catch { return E("this domain is already connected to an account", 409); }
42 await auditT(ctx, "domain.add", id, { hostname: h.hostname }); return Response.json({ id, instructions: dnsInstructions(h.hostname, token, n.public_host || n.hostname) }, { status: 201 });
43 }
44 const dom = await d.prepare("SELECT * FROM domains WHERE id=? AND org_id=?").get(String(b.id ?? b.domainId), ctx.orgId) as any;
45 if (act === "apply") return applyNode(ctx, String(b.nodeId ?? dom?.node_id)); if (!dom) return notFound();
46 const n = await nodeOf(ctx, dom.node_id) as any;
47 if (act === "verify") {
48 const r = resolver(); const target = n?.public_host || n?.hostname || ""; const isIp = /^[\d.]+$|:/.test(target);
49 const [txt, a, a6, cn, tgt] = await Promise.all([safe(r.resolveTxt(verifyName(dom.hostname)), [] as string[][]), safe(r.resolve4(dom.hostname), [] as string[]), safe(r.resolve6(dom.hostname), [] as string[]), safe(r.resolveCname(dom.hostname), [] as string[]), isIp ? Promise.resolve([] as string[]) : safe(r.resolve4(target), [] as string[])]);
50 const ev = evaluateDns({ txt: txt.map(x => x.join("")), a: [...a, ...a6], cname: cn }, dom.verify_token, target, tgt);
51 await d.prepare("UPDATE domains SET dns_status=?, status=?, verified_at=? WHERE id=?").run(ev.dns, ev.owned ? "verified" : "pending", ev.owned ? (dom.verified_at ?? now()) : null, dom.id); await auditT(ctx, "domain.verify", dom.id, { result: ev.dns }); return Response.json({ ok: true, ...ev });
52 }
53 if (act === "map") { let dep: string | null = null; if (b.deploymentId) { const a = await d.prepare("SELECT id FROM app_deployments WHERE id=? AND org_id=? AND node_id=? AND status<>'removed'").get(String(b.deploymentId), ctx.orgId, dom.node_id) as any; if (!a) return E("application not found on the domain's server", 404); dep = a.id; } await d.prepare("UPDATE domains SET deployment_id=?, proxy_status='not-applied' WHERE id=?").run(dep, dom.id); await auditT(ctx, "domain.map", dom.id); return Response.json({ ok: true }); }
54 if (act === "primary") { if (!dom.deployment_id) return E("map the domain to an application first", 409); await d.prepare("UPDATE domains SET is_primary=0 WHERE org_id=? AND deployment_id=?").run(ctx.orgId, dom.deployment_id); await d.prepare("UPDATE domains SET is_primary=1, redirect_to=NULL WHERE id=?").run(dom.id); return Response.json({ ok: true }); }
55 if (act === "redirect") { if (b.enabled === false) { await d.prepare("UPDATE domains SET redirect_to=NULL WHERE id=?").run(dom.id); return Response.json({ ok: true }); }
56 const p = await d.prepare("SELECT hostname FROM domains WHERE org_id=? AND deployment_id=? AND is_primary=1 AND status='verified' AND id<>?").get(ctx.orgId, dom.deployment_id, dom.id) as any; if (!p) return E("choose a verified primary domain for this application first", 409); await d.prepare("UPDATE domains SET redirect_to=?, is_primary=0 WHERE id=?").run(p.hostname, dom.id); return Response.json({ ok: true, redirectTo: p.hostname }); }
57 if (act === "remove") { if (ctx.role !== "admin" && ctx.role !== "owner") return E("requires admin role", 403); await d.prepare("DELETE FROM domains WHERE id=? AND org_id=?").run(dom.id, ctx.orgId); await d.prepare("UPDATE domains SET redirect_to=NULL WHERE org_id=? AND redirect_to=?").run(ctx.orgId, dom.hostname); await auditT(ctx, "domain.remove", dom.id, { hostname: dom.hostname }); return Response.json({ ok: true, note: "Run 'Apply to server' to remove the site from the proxy." }); }
58 return E("unknown action", 400);
59}
60

Conversation

Partial
Sign in to start AI sessions.

Task checklist

  • Application shell deployed
  • Persistent projects
  • Agent runtime
  • Sandboxed terminal

Execution activity

No agent sessions. Git HEAD fb22adb on master.

Approval requests

None pending.