Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat: one-click install and connect converge on a shared shell-app domain step (#136)

Abdurrahman Fakhrul7a2115e18a94
diff --git a/.env.example b/.env.example
index 012e72fb..6900e216 100644
--- a/.env.example
+++ b/.env.example
@@ -205,6 +205,8 @@ OS_SESSION_SECRET=
# Then deploy the template and run: mso mapp enable 9router
# Private persistent routing settings + receipts live outside the code checkout.
# OS_MANAGED_DOMAINS_STORE=~/.mso/private/managed-domains.json
+# Shell-app public domains (POST /api/v1/shell-apps/<id>/domain) persist their phase here.
+# OS_SHELL_APP_DOMAINS_STORE=~/.mso/private/shell-app-domains.json
# Advanced local CLI transport; mso domain normally derives these from its selected env and port.
# MSO_DOMAIN_ENV=/absolute/path/to/.env.local
# MSO_DOMAIN_LOCAL_ORIGIN=http://127.0.0.1:4005
diff --git a/app/api/v1/shell-apps/[id]/domain/route.test.ts b/app/api/v1/shell-apps/[id]/domain/route.test.ts
new file mode 100644
index 00000000..42e8ba8b
--- /dev/null
+++ b/app/api/v1/shell-apps/[id]/domain/route.test.ts
@@ -0,0 +1,98 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { AppDomainRecord } from "@/lib/surfaces/app-domain-provision";
+
+const mocks = vi.hoisted(() => ({ session: vi.fn(), ensure: vi.fn(), inspect: vi.fn(), audit: vi.fn(), rate: vi.fn() }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.session }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rate }));
+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));
+vi.mock("@/lib/surfaces/app-domain-provision", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/surfaces/app-domain-provision")>("@/lib/surfaces/app-domain-provision");
+ return { ...actual, ensureShellAppDomain: mocks.ensure, inspectShellAppDomain: mocks.inspect };
+});
+import { GET, POST } from "./route";
+
+const owner = { session: { device_id: "dev-owner" }, role: "owner" };
+const params = (id = "private-editor") => ({ params: Promise.resolve({ id }) });
+const request = (body?: unknown, id = "private-editor") => new NextRequest(`https://cockpit.example.test/api/v1/shell-apps/${id}/domain`,
+ body === undefined ? undefined : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+const body = { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } };
+const ready: AppDomainRecord = { appId: "private-editor", hostname: "editor.example.net", phase: "ready", provider: "cloudflare",
+ dnsAction: "created", routeAction: "unchanged", localOrigin: "http://127.0.0.1:9131", verifiedAt: 1, updatedAt: 2 };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.session.mockResolvedValue(owner);
+ mocks.rate.mockReturnValue(false);
+ mocks.ensure.mockResolvedValue(ready);
+ mocks.inspect.mockResolvedValue(ready);
+});
+
+describe("shell-app domain authority", () => {
+ it.each([null, "viewer", "operator"])("denies both verbs for %s", async role => {
+ mocks.session.mockResolvedValue(role ? { session: { device_id: "fixture" }, role } : null);
+ expect((await GET(request(), params())).status).toBe(role ? 403 : 401);
+ expect((await POST(request(body), params())).status).toBe(role ? 403 : 401);
+ expect(mocks.ensure).not.toHaveBeenCalled(); expect(mocks.inspect).not.toHaveBeenCalled(); expect(mocks.audit).not.toHaveBeenCalled();
+ });
+
+ it("answers 401 for a session without an approved device", async () => {
+ mocks.session.mockResolvedValue({ session: {}, role: "owner" });
+ expect((await POST(request(body), params())).status).toBe(401);
+ });
+
+ it("rate limits before the write and audits nothing on a refused call", async () => {
+ mocks.rate.mockReturnValue(true);
+ expect((await POST(request(body), params())).status).toBe(429);
+ expect(mocks.rate).toHaveBeenCalledWith("shell-app-domain:dev-owner", 10, 60_000);
+ expect(mocks.ensure).not.toHaveBeenCalled(); expect(mocks.audit).not.toHaveBeenCalled();
+ });
+
+ it("provisions through the library and audits only identity and phase metadata", async () => {
+ const response = await POST(request(body), params());
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store, private");
+ expect(await response.json()).toEqual(ready);
+ expect(mocks.ensure).toHaveBeenCalledWith("private-editor", body);
+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "infra.write", actor: "dev-owner",
+ target: "private-editor", ok: true, detail: "shell-app.domain.ready", meta: { hostname: "editor.example.net", provider: "cloudflare" } }));
+ });
+
+ it("returns null for an unprovisioned app without auditing a read", async () => {
+ mocks.inspect.mockResolvedValue(null);
+ const response = await GET(request(), params());
+ expect(response.status).toBe(200); expect(await response.json()).toBeNull();
+ expect(mocks.inspect).toHaveBeenCalledWith("private-editor");
+ expect(response.headers.get("cache-control")).toBe("no-store, private");
+ });
+
+ it.each([
+ ["invalid_hostname", 400],
+ ["invalid_target", 400],
+ ["unsupported_provider", 400],
+ ["domain_conflict", 409],
+ ["provider_unavailable", 503],
+ ])("maps %s to %i and audits the failure", async (code, status) => {
+ const { AppDomainError } = await vi.importActual<typeof import("@/lib/surfaces/app-domain-provision")>("@/lib/surfaces/app-domain-provision");
+ mocks.ensure.mockRejectedValueOnce(new AppDomainError(code as never, status as never, "reason"));
+ const response = await POST(request(body), params());
+ expect(response.status).toBe(status);
+ expect(await response.json()).toEqual({ error: code });
+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ ok: false, detail: `shell-app.domain.${code}` }));
+ });
+
+ it("fails closed on an unexpected library error without leaking its message", async () => {
+ mocks.ensure.mockRejectedValueOnce(new Error("apiToken=super-secret leaked"));
+ const response = await POST(request(body), params());
+ expect(response.status).toBe(503);
+ expect(JSON.stringify(await response.json())).not.toContain("super-secret");
+ });
+
+ it("rejects a non-JSON body without reaching the library", async () => {
+ const response = await POST(new NextRequest("https://cockpit.example.test/api/v1/shell-apps/private-editor/domain",
+ { method: "POST", body: "hostname=evil" }), params());
+ expect(response.status).toBe(415);
+ expect(mocks.ensure).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/shell-apps/[id]/domain/route.ts b/app/api/v1/shell-apps/[id]/domain/route.ts
new file mode 100644
index 00000000..958a9371
--- /dev/null
+++ b/app/api/v1/shell-apps/[id]/domain/route.ts
@@ -0,0 +1,62 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { roleAtLeast } from "@/lib/auth/roles";
+import { IS_DEMO } from "@/lib/demo";
+import { audit } from "@/lib/host/audit-api";
+import { rateLimited } from "@/lib/host/limits-api";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { AppDomainError, ensureShellAppDomain, inspectShellAppDomain, type DomainProviderId } from "@/lib/surfaces/app-domain-provision";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private" };
+type Context = { params: Promise<{ id: string }> };
+
+/** Gate order is shared by both verbs: session -> owner -> demo -> rate limit -> lib -> audit. */
+async function gate(request: NextRequest, scope: string, limit: number) {
+ const context = await getSessionContext();
+ if (!context?.session.device_id) return { error: NextResponse.json({ error: "unauthorized" }, { status: 401, headers }) };
+ if (!roleAtLeast(context.role, "owner")) return { error: NextResponse.json({ error: "owner_required" }, { status: 403, headers }) };
+ if (IS_DEMO) return { error: NextResponse.json({ error: "owner_required" }, { status: 403, headers }) };
+ if (rateLimited(`${scope}:${context.session.device_id}`, limit, 60_000)) return { error: NextResponse.json({ error: "rate_limited" }, { status: 429, headers }) };
+ return { context, request };
+}
+function failure(error: unknown) {
+ if (error instanceof AppDomainError) return NextResponse.json({ error: error.code }, { status: error.status, headers });
+ // SetupError-style body/parse rejections keep their own bounded code and status.
+ const bounded = error as { code?: unknown; status?: unknown };
+ if (typeof bounded?.code === "string" && bounded.code.length <= 64 && typeof bounded.status === "number" && bounded.status >= 400 && bounded.status < 500) {
+ return NextResponse.json({ error: bounded.code }, { status: bounded.status, headers });
+ }
+ return NextResponse.json({ error: "provider_unavailable" }, { status: 503, headers });
+}
+
+export async function GET(request: NextRequest, context: Context) {
+ const allowed = await gate(request, "shell-app-domain-read", 60);
+ if (allowed.error) return allowed.error;
+ const { id } = await context.params;
+ try { return NextResponse.json(await inspectShellAppDomain(id), { headers }); }
+ catch (error) { return failure(error); }
+}
+
+export async function POST(request: NextRequest, context: Context) {
+ const allowed = await gate(request, "shell-app-domain", 10);
+ if (allowed.error) return allowed.error;
+ const actor = allowed.context.session.device_id!, { id } = await context.params;
+ try {
+ const body = await readSetupJson(request, 8 * 1024);
+ const record = await ensureShellAppDomain(id, {
+ provider: body.provider as DomainProviderId,
+ hostname: String(body.hostname ?? ""),
+ target: body.target as never,
+ ...(body.zoneName === undefined ? {} : { zoneName: String(body.zoneName) }),
+ });
+ void audit({ action: "infra.write", actor, target: id, ok: record.phase !== "blocked",
+ detail: `shell-app.domain.${record.phase}`, meta: { hostname: record.hostname, provider: String(record.provider) } });
+ return NextResponse.json(record, { headers });
+ } catch (error) {
+ const code = error instanceof AppDomainError ? error.code : (error as { code?: unknown })?.code;
+ void audit({ action: "infra.write", actor, target: id, ok: false, detail: `shell-app.domain.${typeof code === "string" ? code : "failed"}` });
+ return failure(error);
+ }
+}
diff --git a/bin/mso b/bin/mso
index cd5ee54b..e740c079 100755
--- a/bin/mso
+++ b/bin/mso
@@ -66,7 +66,7 @@
#
# Apps
# apps App-store runtime apps
-# mapp * Managed apps; catalog / shell-list / shell-save <JSON|@file> for connections
+# mapp * Managed apps; shell-list / shell-save <JSON|@file> / shell-domain <id> / shell-domain-save <id> <JSON|@file> review external connections and their public domain
# term * Interactive PTY sessions (open | input | resize | stream | close)
#
# AI + state
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index f1d87f24..e26641e7 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,11 +8,16 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `app-store` converge install and connect on one domain step
+- `shell-apps` provision public domains for shell apps
+- `infra` add managed domain provider abstraction
- `cli` print the mso ai reply text instead of SSE frames
- `infra` add Linear provider and route Composio key kinds by header
**Fixed**
+- `composio` refuse Connect consumer keys on the Platform provider
+- `app-domain` wire the real provider module and single-source the domain contract
- `deps` pin vite 8.2.4 to clear GHSA-587h-7wmj-h5pm
## 2026-10-20
diff --git a/docs/CLI.md b/docs/CLI.md
index b52a5065..b49780f3 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -106,7 +106,7 @@ Commands:
Apps
apps App-store runtime apps
- mapp * Managed apps; catalog / shell-list / shell-save <JSON|@file> for connections
+ mapp * Managed apps; shell-list / shell-save <JSON|@file> / shell-domain <id> / shell-domain-save <id> <JSON|@file> review external connections and their public domain
term * Interactive PTY sessions (open | input | resize | stream | close)
AI + state
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 8c0e9091..15cca5ea 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,23 @@
+## 2026-10-21: Shell-app domain provisioning (phase 1, worker B)
+
+New `lib/surfaces/app-domain-provision.ts` provisions a public hostname for a shell-app entry:
+loopback probe → DNS write → route → verify, persisting every phase in an owner-only
+`~/.mso/private/shell-app-domains.json` (0600/0700, `O_NOFOLLOW`, uid-checked, locked) so a failed
+run resumes at the phase it reached instead of restarting from `pending`. Hostnames equal to,
+domain-matching, or containing the cockpit name, names inside `OS_SESSION_COOKIE_DOMAIN`, and
+anything `externalSurfaceSharesSession` blocks are rejected with a precise error — never
+substituted. Owner-only `POST`/`GET /api/v1/shell-apps/[id]/domain` mirror the existing shell-app
+gate order, rate limit, `Cache-Control: no-store, private` and audit trail. New CLI verbs
+`mso mapp shell-domain <id>` and `mso mapp shell-domain-save <id> <JSON|@file>` keep every route
+reachable from a shell.
+
+Contract 1 is `lib/infra/managed-domain-providers.ts`; provisioning imports its three boundary
+functions directly, so there is no injection seam in the shipped composition root. The genuine
+`provider_unavailable` case is a configured provider with no stored credentials, which that
+module raises itself. `lib/contracts/app-domain.ts` is the single server-side spelling of the
+provider union and record shape; the browser copy in
+`frontend/slices/app-store/lib/app-domain.ts` mirrors it and a parity test fails on drift.
+
## 2026-10-21: `mso ai` shows the reply text, not the SSE frames
`mso ai` sent the right OaMsg `text` after #133, but it still printed the raw response body, so an owner read `event: delta` / `data: "…"` frames instead of an answer. `scripts/mso-sse-text.mjs` now consumes that stream: `delta` frames become stdout text, an `error` frame fails the turn with a non-zero exit, unknown events stay silent, and a non-SSE or empty body can no longer pass as a successful empty answer. The verb pipes through the reader; the entrypoint header, generated `docs/CLI.md` and the runtime help all say so.
@@ -5,6 +25,8 @@
Coverage pins both halves of the boundary instead of only the memory helper: `app/api/assistant/normalize-content.test.ts` asserts the route turns an OpenAI-shaped `{content}` into `{text}` before recall and the streamer, and keeps streaming when neither shape carries a prompt; `scripts/mso-ai-cli-contract.test.ts` asserts the verb posts `text` and renders through the reader; `scripts/mso-sse-text.test.ts` covers delta concatenation, JSON escapes, CRLF framing, unknown events, error frames and non-SSE or empty bodies.
Evidence at the committed candidate: 13/13 targeted tests, `tsc --noEmit`, `eslint . --max-warnings=0`, architecture (entrypoint 203/220), cycles, docs and generated-CLI-docs checks all PASS; a live one-turn call through the worktree CLI printed a multi-line reply and exited 0. `bun run pr:local` and `bun run pr:security` are BLOCKED on this host (no `zip`, no Docker, no browser fixtures), so the PR stays Draft until hosted checks supply that evidence.
+provider union and record shape; the browser copy in
+`frontend/slices/app-store/lib/app-domain.ts` mirrors it and a parity test fails on drift.
## 2026-10-18: MSO deep QA stopped at the user's request
diff --git a/frontend/slices/app-store/components/app-domain-step.test.tsx b/frontend/slices/app-store/components/app-domain-step.test.tsx
new file mode 100644
index 00000000..da6165bd
--- /dev/null
+++ b/frontend/slices/app-store/components/app-domain-step.test.tsx
@@ -0,0 +1,150 @@
+import { describe, expect, it } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ DOMAIN_POLL_DEADLINE_MS,
+ directAddressFrom,
+ pollAppDomain,
+ providerBlockReason,
+ type AppDomainRecord,
+} from "../lib/app-domain";
+import { DomainEscapeHatch, DomainPhaseSummary, DomainProviderPicker } from "./app-domain-step";
+
+// No DOM renderer is installed here (environment "node", no jsdom or
+// @testing-library, and this round may not add a dep), so the step is exercised
+// the way this repo already does it: render its pure pieces to static markup,
+// and drive the poll loop through its injected clock/fetch seams.
+
+const record = (phase: AppDomainRecord["phase"], extra: Partial<AppDomainRecord> = {}): AppDomainRecord => ({
+ appId: "hermes",
+ hostname: "hermes.example.com",
+ phase,
+ provider: "cloudflare",
+ updatedAt: 1,
+ ...extra,
+});
+
+describe("provider picker", () => {
+ it("keeps every provider in the list and disables an incapable one with a reason", () => {
+ const html = renderToStaticMarkup(<DomainProviderPicker recordType="A" value="cloudflare" onSelect={() => {}}/>);
+ for (const label of ["Cloudflare", "Hostinger", "Dokploy", "Custom (you manage DNS)"]) expect(html).toContain(label);
+ // Dokploy owns the ingress and writes no DNS without a configured public IP.
+ expect(html).toContain("Unavailable: Dokploy owns the ingress");
+ expect(html).toMatch(/<input[^>]*disabled[^>]*value="dokploy"/);
+ expect(html).not.toMatch(/<input[^>]*disabled[^>]*value="cloudflare"/);
+ expect(html).not.toMatch(/<input[^>]*disabled[^>]*value="custom"/);
+ });
+
+ it("explains the CNAME case and disables the same providers by capability", () => {
+ const html = renderToStaticMarkup(<DomainProviderPicker recordType="CNAME" value={null} onSelect={() => {}}/>);
+ expect(html).toContain("record type is CNAME");
+ expect(html).toContain("Unavailable: ");
+ });
+
+ it("reports capability as a reason instead of dropping the row", () => {
+ expect(providerBlockReason("dokploy", "A")).toContain("ingress");
+ expect(providerBlockReason("cloudflare", "A")).toBeNull();
+ expect(providerBlockReason("hostinger", "CNAME")).toBeNull();
+ // `custom` is manual DNS, not an incapable provider.
+ expect(providerBlockReason("custom", "A")).toBeNull();
+ });
+});
+
+describe("wait state", () => {
+ const fakeClock = (start = 0) => {
+ let clock = start;
+ return {
+ now: () => clock,
+ sleep: async (ms: number) => { clock += ms; },
+ advanced: () => clock,
+ };
+ };
+ const respond = (body: AppDomainRecord | null, status = 200) => async () =>
+ new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+
+ it("polls with backoff and hard-stops at the bounded deadline", async () => {
+ const clock = fakeClock();
+ const calls: number[] = [];
+ const outcome = await pollAppDomain({
+ appId: "hermes",
+ now: clock.now,
+ sleep: clock.sleep,
+ fetchImpl: (async () => { calls.push(clock.now()); return respond(record("pending"))(); }) as unknown as typeof fetch,
+ });
+ expect(outcome.status).toBe("deadline");
+ expect(outcome.record?.phase).toBe("pending");
+ expect(calls.length).toBeGreaterThan(2);
+ expect(clock.advanced()).toBeLessThanOrEqual(DOMAIN_POLL_DEADLINE_MS);
+ // Backoff, not a tight loop: the gap between the first and last request grows.
+ expect(calls[2] - calls[1]).toBeGreaterThan(calls[1] - calls[0]);
+ });
+
+ it("stops as soon as the record settles", async () => {
+ const clock = fakeClock();
+ let call = 0;
+ const outcome = await pollAppDomain({
+ appId: "hermes",
+ now: clock.now,
+ sleep: clock.sleep,
+ fetchImpl: (async () => respond(record(++call >= 3 ? "ready" : "dns-ready"))()) as unknown as typeof fetch,
+ });
+ expect(outcome.status).toBe("settled");
+ expect(outcome.status === "settled" ? outcome.record.phase : null).toBe("ready");
+ expect(call).toBe(3);
+ });
+
+ it("stops on an aborted signal instead of polling on", async () => {
+ const clock = fakeClock();
+ const controller = new AbortController();
+ let call = 0;
+ const outcome = await pollAppDomain({
+ appId: "hermes",
+ signal: controller.signal,
+ now: clock.now,
+ sleep: async (ms: number) => { clock.now(); controller.abort(); await new Promise<void>(resolve => { void ms; resolve(); }); },
+ fetchImpl: (async () => { call++; return respond(record("pending"))(); }) as unknown as typeof fetch,
+ });
+ expect(outcome.status).toBe("cancelled");
+ expect(call).toBe(1);
+ });
+
+ it("prints the phase verbatim so the operator can see where it stopped", () => {
+ const html = renderToStaticMarkup(<DomainPhaseSummary record={record("route-ready")}/>);
+ expect(html).toContain("route-ready");
+ expect(html).toContain("hermes.example.com");
+ });
+});
+
+describe("blocked phase", () => {
+ it("renders the blocked reason", () => {
+ const html = renderToStaticMarkup(<DomainPhaseSummary record={record("blocked", { error: "Cloudflare refused: zone not found for example.com" })}/>);
+ expect(html).toContain("blocked");
+ expect(html).toContain("Cloudflare refused: zone not found for example.com");
+ expect(html).toMatch(/role="alert"/);
+ });
+});
+
+describe("IP-and-port escape hatch", () => {
+ it("is always present and says it opens a new tab, not an embed", () => {
+ const html = renderToStaticMarkup(<DomainEscapeHatch appTitle="Hermes" address="http://192.168.1.10:5678"/>)!;
+ expect(html).toContain("Open directly by IP and port instead");
+ expect(html).toContain("new browser tab");
+ expect(html).toContain("does not embed it");
+ expect(html).not.toContain("<iframe");
+ expect(html).toContain('target="_blank"');
+ expect(html).toContain('rel="noopener noreferrer"');
+ });
+
+ it("stays honest when no IP-and-port address is known", () => {
+ const html = renderToStaticMarkup(<DomainEscapeHatch appTitle="Hermes" address="https://hermes.example.com"/>)!;
+ expect(html).toContain("Open directly by IP and port instead");
+ expect(html).not.toContain("<a ");
+ expect(html).not.toContain("<iframe");
+ });
+
+ it("never turns a hostname into a direct address", () => {
+ expect(directAddressFrom("https://hermes.example.com")).toBeNull();
+ expect(directAddressFrom("http://192.168.1.10:5678")).toBe("http://192.168.1.10:5678");
+ expect(directAddressFrom("ftp://192.168.1.10:21")).toBeNull();
+ expect(directAddressFrom(null)).toBeNull();
+ });
+});
diff --git a/frontend/slices/app-store/components/app-domain-step.tsx b/frontend/slices/app-store/components/app-domain-step.tsx
new file mode 100644
index 00000000..71280eb7
--- /dev/null
+++ b/frontend/slices/app-store/components/app-domain-step.tsx
@@ -0,0 +1,186 @@
+"use client";
+
+import { useCallback, useEffect, useId, useRef, useState, type FormEvent } from "react";
+import { FormDrawer } from "@/features/appshell";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ DOMAIN_POLL_DEADLINE_MS,
+ DOMAIN_PROVIDER_IDS,
+ directAddressFrom,
+ domainProviderCapabilities,
+ pollAppDomain,
+ providerBlockReason,
+ providerLabel,
+ targetFor,
+ type AppDomainRecord,
+ type DomainProviderId,
+} from "../lib/app-domain";
+
+// ONE domain step, used by both entry paths (Install a managed app, Connect an
+// existing one). Never fork it: the two paths differ only in what they pass in.
+// Three steps, in order: hostname, provider, wait/result.
+//
+// The provider list is COMPLETE and never filtered. A provider that cannot write
+// the record type this target needs is rendered disabled WITH the reason — the
+// operator must see that Cloudflare is not an option here because Dokploy owns
+// the ingress, not have the row silently disappear.
+const errorText: Record<string, string> = {
+ invalid_hostname: "That hostname is not usable for this app. Use a lowercase DNS name you control.",
+ invalid_target: "The record target is not a public IPv4 address or a DNS name.",
+ unsupported_provider: "That provider cannot write records for this hostname.",
+ domain_conflict: "That hostname already belongs to another app or an existing site.",
+ provider_unavailable: "The provider is not configured on this host, or its API refused the write.",
+};
+const deadlineSeconds = Math.round(DOMAIN_POLL_DEADLINE_MS / 1000);
+
+/** Step 2 on its own: the full provider list, incapable entries disabled in
+ * place. Separate from the drawer so the rules stay renderable and testable. */
+export function DomainProviderPicker({ recordType, value, disabled, onSelect }: {
+ recordType: "A" | "CNAME"; value: DomainProviderId | null; disabled?: boolean; onSelect: (id: DomainProviderId) => void;
+}) {
+ return <fieldset className="space-y-1.5">
+ <legend className="text-sm font-medium">DNS provider</legend>
+ <div className="space-y-2">
+ {DOMAIN_PROVIDER_IDS.map(id => {
+ const reason = providerBlockReason(id, recordType);
+ const capability = domainProviderCapabilities(id);
+ return <label key={id} className="flex items-start gap-2 rounded-md border p-2 text-sm">
+ <input type="radio" name={`provider-${recordType}`} className="mt-1" value={id} checked={value === id}
+ disabled={Boolean(reason) || disabled} onChange={() => onSelect(id)} />
+ <span className="min-w-0 space-y-0.5">
+ <span className="block">{providerLabel(id)}</span>
+ <span className="block text-xs text-muted-foreground">
+ {`${capability.aRecord ? "A" : "no A"} · ${capability.cname ? "CNAME" : "no CNAME"} · ${capability.ingress ? "owns ingress" : "DNS only"} · ${capability.txt ? "TXT verification" : "no TXT verification"}`}
+ </span>
+ {reason ? <span className="block text-xs text-destructive">Unavailable: {reason}</span> : null}
+ </span>
+ </label>;
+ })}
+ </div>
+ {recordType === "CNAME" && <p className="text-xs text-muted-foreground">This app is addressed by a hostname, so the record type is CNAME.</p>}
+ </fieldset>;
+}
+
+/** Step 3 result. `phase` is printed verbatim: that string is how the operator
+ * reports where a run stopped. */
+export function DomainPhaseSummary({ record }: { record: AppDomainRecord }) {
+ return <div className="space-y-1 rounded-lg border p-3 text-sm">
+ <p>Phase: <span className="font-mono">{record.phase}</span></p>
+ <p className="break-all text-xs text-muted-foreground">{record.hostname} · {record.provider ?? "no provider"}{record.dnsAction ? ` · DNS ${record.dnsAction}` : ""}{record.routeAction ? ` · route ${record.routeAction}` : ""}</p>
+ {record.localOrigin && <p className="break-all text-xs text-muted-foreground">Checked locally at {record.localOrigin}</p>}
+ {record.phase === "blocked" && <p role="alert" className="text-sm text-destructive">{record.error ?? "Publication is blocked; the provider gave no reason."}</p>}
+ </div>;
+}
+
+/** The escape hatch, always rendered. It opens a new tab; it never claims that
+ * MSO can embed an address. Only an IP:port address is offered, because that is
+ * the case the iframe guard in components/external-app-frame.tsx refuses. */
+export function DomainEscapeHatch({ appTitle, address }: { appTitle: string; address?: string | null }) {
+ const direct = directAddressFrom(address);
+ return <div className="space-y-1 rounded-lg border border-dashed p-3">
+ <p className="text-sm font-medium">Open directly by IP and port instead</p>
+ <p className="text-xs text-muted-foreground">This opens {appTitle} in a new browser tab and does not embed it. An HTTP address is never loaded inside MSO.</p>
+ {direct
+ ? <Button asChild variant="outline" size="sm"><a href={direct} target="_blank" rel="noopener noreferrer">Open {direct}</a></Button>
+ : <p className="text-xs text-muted-foreground">No IP-and-port address is known for this app yet. Use its address from the connection list.</p>}
+ </div>;
+}
+
+export function AppDomainStep({ appId, appTitle, defaultHostname, appAddress, onDone }: {
+ appId: string;
+ appTitle: string;
+ defaultHostname: string;
+ /** The app's current address. Drives the target record and the escape hatch. */
+ appAddress?: string | null;
+ onDone: () => void;
+}) {
+ const prefix = useId();
+ const [hostname, setHostname] = useState(defaultHostname);
+ const [provider, setProvider] = useState<DomainProviderId | null>(null);
+ const [record, setRecord] = useState<AppDomainRecord | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [waiting, setWaiting] = useState(false);
+ const [stopped, setStopped] = useState<"" | "cancelled" | "deadline">("");
+ const [error, setError] = useState("");
+ const controller = useRef<AbortController | null>(null);
+ const target = targetFor(appAddress ?? "");
+ const chosen = provider ?? DOMAIN_PROVIDER_IDS.find(id => providerBlockReason(id, target?.kind === "cname" ? "CNAME" : "A") === null) ?? null;
+
+ const startPoll = useCallback(() => {
+ controller.current?.abort();
+ const next = new AbortController();
+ controller.current = next;
+ setWaiting(true);
+ setStopped("");
+ void pollAppDomain({ appId, signal: next.signal, onRecord: setRecord }).then(outcome => {
+ setWaiting(false);
+ if (outcome.status === "cancelled") { setStopped("cancelled"); return; }
+ if (outcome.status === "deadline") {
+ setStopped("deadline");
+ if (outcome.error) setError(outcome.error);
+ }
+ });
+ }, [appId]);
+ useEffect(() => () => controller.current?.abort(), []);
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ if (busy || !chosen) return;
+ setError("");
+ if (!target) { setError("This app has no IPv4 or DNS address yet. Connect it with an address before publishing a name for it."); return; }
+ setBusy(true);
+ try {
+ const response = await fetch(`/api/v1/shell-apps/${encodeURIComponent(appId)}/domain`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider: chosen, hostname: hostname.trim(), target }),
+ });
+ const payload = await response.json() as AppDomainRecord & { error?: string };
+ if (!response.ok) throw new Error(errorText[payload.error ?? ""] ?? "Could not publish this domain.");
+ setRecord(payload);
+ startPoll();
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : "Could not publish this domain.");
+ } finally { setBusy(false); }
+ };
+
+ const cancelWait = () => { controller.current?.abort(); setWaiting(false); setStopped("cancelled"); };
+
+ return <FormDrawer open onOpenChange={open => { if (!open && !busy) onDone(); }} size="md">
+ <FormDrawer.Header>
+ <FormDrawer.Title>Domain for {appTitle}</FormDrawer.Title>
+ <FormDrawer.Description>Point a hostname you control at this app. DNS is written only after the app answers on this host, so the name never serves an unready service.</FormDrawer.Description>
+ </FormDrawer.Header>
+ <form onSubmit={submit} className="min-h-0 space-y-4 overflow-y-auto px-4 pb-4">
+ <div className="space-y-1.5">
+ <Label htmlFor={`${prefix}-hostname`}>Hostname</Label>
+ <Input id={`${prefix}-hostname`} value={hostname} placeholder="app.example.com" required maxLength={253}
+ onChange={event => setHostname(event.target.value)} disabled={Boolean(record)} />
+ <p className="text-xs text-muted-foreground">Must not be MSO&apos;s own cockpit host or share its sign-in cookie domain.</p>
+ </div>
+
+ <DomainProviderPicker recordType={target?.kind === "cname" ? "CNAME" : "A"} value={chosen}
+ disabled={Boolean(record)} onSelect={setProvider}/>
+
+ {record && <DomainPhaseSummary record={record}/>}
+
+ {waiting && <p role="status" className="text-xs text-muted-foreground">Waiting for the provider to confirm. Retries with backoff, gives up after {deadlineSeconds} seconds.</p>}
+ {stopped === "cancelled" && <p role="status" className="text-xs text-muted-foreground">Stopped waiting at your request. Last phase: <span className="font-mono">{record?.phase ?? "none"}</span>.</p>}
+ {stopped === "deadline" && <p role="status" className="text-xs text-muted-foreground">Stopped at the {deadlineSeconds}-second deadline. Last phase: <span className="font-mono">{record?.phase ?? "none"}</span>. Nothing was published silently; check the provider, then check again.</p>}
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+
+ <DomainEscapeHatch appTitle={appTitle} address={appAddress}/>
+
+ <div className="flex flex-wrap justify-end gap-2">
+ {waiting && <Button type="button" variant="outline" onClick={cancelWait}>Cancel waiting</Button>}
+ {stopped && !waiting && <Button type="button" variant="outline" disabled={busy} onClick={startPoll}>Check again</Button>}
+ <Button type="button" variant="ghost" disabled={busy} onClick={onDone}>Close</Button>
+ <Button type="submit" disabled={busy || waiting || !chosen || Boolean(record && record.phase !== "blocked")}>
+ {busy ? "Publishing…" : record?.phase === "blocked" ? "Try again" : "Publish domain"}
+ </Button>
+ </div>
+ </form>
+ </FormDrawer>;
+}
diff --git a/frontend/slices/app-store/components/connect-app-form.tsx b/frontend/slices/app-store/components/connect-app-form.tsx
index 2ab75fc9..5aa433cd 100644
--- a/frontend/slices/app-store/components/connect-app-form.tsx
+++ b/frontend/slices/app-store/components/connect-app-form.tsx
@@ -8,19 +8,29 @@ import { Switch } from "@/components/ui/switch";
import type { ConnectedAppManifest } from "@/lib/contracts/connected-app-manifest";
import type { ShellAppDefinition } from "@/lib/contracts/shell-app";
import { useShellApps } from "../lib/shell-apps";
+import { hostnameFromUrl } from "../lib/app-domain";
+import { AppDomainStep } from "./app-domain-step";
export function ConnectAppForm({ existing, manifest, onClose }: { existing?: ShellAppDefinition; manifest?: ConnectedAppManifest; onClose: () => void }) {
const prefix = useId(), { mutate } = useShellApps();
const [app, setApp] = useState<ShellAppDefinition>(existing ?? { id: manifest?.id ?? "", title: manifest?.title ?? "", description: manifest?.description ?? "", url: "", mode: manifest?.presentation ?? "embed" });
const [busy, setBusy] = useState(false), [error, setError] = useState("");
+ // Set once the registry accepted the app. The flow does NOT close here: a
+ // connected app with no name is reachable only by an address, so the SAME
+ // domain step the Install path uses is offered next. Skipping it is one click.
+ const [connected, setConnected] = useState<{ id: string; title: string; url: string } | null>(null);
const change = (key: keyof ShellAppDefinition, value: string) => setApp(current => ({ ...current, [key]: value }));
const submit = async (event: FormEvent) => {
event.preventDefault(); if (busy) return;
setBusy(true); setError("");
- try { await mutate(manifest ? { action: "import", manifest, binding: { id: app.id, url: app.url, mode: app.mode } } : { action: existing ? "update" : "add", app }); onClose(); }
+ try {
+ await mutate(manifest ? { action: "import", manifest, binding: { id: app.id, url: app.url, mode: app.mode } } : { action: existing ? "update" : "add", app });
+ setConnected({ id: app.id, title: app.title, url: app.url });
+ }
catch (reason) { setError(reason instanceof Error ? reason.message : "Could not connect app."); }
finally { setBusy(false); }
};
+ if (connected) return <AppDomainStep appId={connected.id} appTitle={connected.title} defaultHostname={hostnameFromUrl(connected.url)} appAddress={connected.url} onDone={onClose}/>;
return <FormDrawer open onOpenChange={open => { if (!open && !busy) onClose(); }} size="md">
<FormDrawer.Header><FormDrawer.Title>{existing ? "Edit connected app" : "Connect a running app"}</FormDrawer.Title><FormDrawer.Description>Add your own tool or an existing service to this shell. The application keeps running on its host.</FormDrawer.Description></FormDrawer.Header>
<form onSubmit={submit} className="min-h-0 space-y-4 overflow-y-auto px-4 pb-4">
diff --git a/frontend/slices/app-store/components/managed-apps-catalog.tsx b/frontend/slices/app-store/components/managed-apps-catalog.tsx
index b6d13077..4ded2555 100644
--- a/frontend/slices/app-store/components/managed-apps-catalog.tsx
+++ b/frontend/slices/app-store/components/managed-apps-catalog.tsx
@@ -1,10 +1,12 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { openWindow } from "@/features/appshell";
import type { AppCatalogEntry } from "@/lib/contracts/app-catalog";
import type { ManagedAppView } from "@/lib/managed-apps/types";
import { Button } from "@/components/ui/button";
import { ConnectAppForm } from "./connect-app-form";
+import { AppDomainStep } from "./app-domain-step";
+import { hostnameFromUrl } from "../lib/app-domain";
type CatalogState = { status: "remote" | "stale" | "unavailable"; entries: AppCatalogEntry[] };
@@ -12,7 +14,12 @@ export function ManagedAppsCatalog({ query }: { query: string }) {
const [apps, setApps] = useState<ManagedAppView[]>([]);
const [catalog, setCatalog] = useState<CatalogState | null>(null);
const [selected, setSelected] = useState<Extract<AppCatalogEntry, { kind: "connected" }> | null>(null);
+ const [domainFor, setDomainFor] = useState<{ id: string; title: string; address: string | null } | null>(null);
const [error, setError] = useState("");
+ // Set the moment the operator asks to set an app up. Install runs in its own
+ // MSO window; when this catalog next reads the host and finds that app
+ // installed, the domain step is offered — the same step the connect path uses.
+ const awaiting = useRef<{ id: string; title: string } | null>(null);
useEffect(() => {
const controller = new AbortController();
const loadApps = async () => {
@@ -22,6 +29,12 @@ export function ManagedAppsCatalog({ query }: { query: string }) {
const data = await response.json() as { apps: ManagedAppView[] };
setApps(data.apps);
setError("");
+ const pending = awaiting.current;
+ const installed = pending ? data.apps.find(app => app.id === pending.id) : undefined;
+ if (pending && installed?.installed) {
+ awaiting.current = null;
+ setDomainFor({ id: installed.id, title: pending.title, address: installed.publicDashboardUrl });
+ }
} catch (reason) {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Could not load apps.");
}
@@ -68,7 +81,13 @@ export function ManagedAppsCatalog({ query }: { query: string }) {
<h4 className="font-medium">{app.name}</h4><p className="text-xs text-muted-foreground">{app.installed ? app.state : "Not installed"}</p>
<p className="text-sm text-muted-foreground">{app.description}</p>
{app.diagnostic && <p className="text-xs text-muted-foreground">{app.diagnostic}</p>}
- <Button size="sm" variant="outline" onClick={() => openWindow(app.id, app.name)}>{app.installed ? "Open and manage" : "Set up"}</Button>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" onClick={() => {
+ if (!app.installed) awaiting.current = { id: app.id, title: app.name };
+ openWindow(app.id, app.name);
+ }}>{app.installed ? "Open and manage" : "Set up"}</Button>
+ {app.installed && <Button size="sm" variant="ghost" onClick={() => setDomainFor({ id: app.id, title: app.name, address: app.publicDashboardUrl })}>Add domain</Button>}
+ </div>
</article>)}</div>
{connected.length > 0 && <div className="space-y-3">
<h3 className="font-medium">Connect a running tool</h3>
@@ -81,5 +100,6 @@ export function ManagedAppsCatalog({ query }: { query: string }) {
</div>}
<p className="text-xs text-muted-foreground">Managed setup uses the reviewed installer and checks this host. Connected tools keep their own service and sign-in; a domain is optional.</p>
{selected && <ConnectAppForm manifest={selected.manifest} onClose={() => setSelected(null)}/>}
+ {domainFor && <AppDomainStep appId={domainFor.id} appTitle={domainFor.title} defaultHostname={hostnameFromUrl(domainFor.address)} appAddress={domainFor.address} onDone={() => setDomainFor(null)}/>}
</section>;
}
diff --git a/frontend/slices/app-store/lib/app-domain-parity.test.ts b/frontend/slices/app-store/lib/app-domain-parity.test.ts
new file mode 100644
index 00000000..64fdcb70
--- /dev/null
+++ b/frontend/slices/app-store/lib/app-domain-parity.test.ts
@@ -0,0 +1,30 @@
+import { expect, it } from "vitest";
+import {
+ DOMAIN_PROVIDER_IDS as SERVER_PROVIDER_IDS,
+ type AppDomainRecord as ServerRecord,
+ type DomainProviderCapability as ServerCapability,
+} from "@/lib/contracts/app-domain";
+import {
+ DOMAIN_PROVIDER_IDS as MIRROR_PROVIDER_IDS,
+ type AppDomainRecord as MirrorRecord,
+ type DomainProviderCapability as MirrorCapability,
+} from "./app-domain";
+
+// The browser copy in `./app-domain.ts` cannot import the server contract, so this
+// is the check that keeps it a mirror rather than a fork. Field NAMES only: the
+// compiler already proves assignability; this proves neither side renamed a field.
+const fields = (shape: Record<string, unknown>) => Object.keys(shape).sort();
+
+it("mirrors the provider union in the same order", () => {
+ expect([...MIRROR_PROVIDER_IDS]).toEqual([...SERVER_PROVIDER_IDS]);
+});
+
+it("mirrors every record and capability field name", () => {
+ const record: MirrorRecord = { appId: "", hostname: "", phase: "ready", provider: "custom", dnsAction: "unchanged",
+ routeAction: "unchanged", error: "", localOrigin: "", verifiedAt: 0, updatedAt: 0 };
+ const capability: MirrorCapability = { id: "custom", aRecord: false, cname: false, txt: false, ingress: false };
+ expect(Object.keys(record satisfies ServerRecord).sort()).toEqual(fields(record));
+ expect(Object.keys(capability satisfies ServerCapability).sort()).toEqual(fields(capability));
+ expect(fields(record)).toEqual(["appId", "dnsAction", "error", "hostname", "localOrigin", "phase", "provider", "routeAction", "updatedAt", "verifiedAt"]);
+ expect(fields(capability)).toEqual(["aRecord", "cname", "id", "ingress", "txt"]);
+});
diff --git a/frontend/slices/app-store/lib/app-domain.ts b/frontend/slices/app-store/lib/app-domain.ts
new file mode 100644
index 00000000..435d3fbe
--- /dev/null
+++ b/frontend/slices/app-store/lib/app-domain.ts
@@ -0,0 +1,144 @@
+// Shared domain-step logic for both shell-app entry paths (install + connect).
+// MIRROR — source of truth: `lib/contracts/app-domain.ts`. The browser may not
+// import that module (it is server-side), so `DomainProviderId`,
+// `DomainProviderCapability`, `AppDomainPhase`, `AppDomainTarget` and
+// `AppDomainRecord` are restated here with the SAME field names and SAME union
+// members. `app-domain-parity.test.ts` fails when they drift; never add a field
+// the server does not return.
+export const DOMAIN_PROVIDER_IDS = ["cloudflare", "hostinger", "dokploy", "custom"] as const;
+export type DomainProviderId = (typeof DOMAIN_PROVIDER_IDS)[number];
+export type DomainProviderCapability = {
+ id: DomainProviderId;
+ aRecord: boolean;
+ cname: boolean;
+ txt: boolean;
+ ingress: boolean;
+};
+export type AppDomainTarget = { kind: "ipv4"; value: string } | { kind: "cname"; value: string };
+export type AppDomainPhase = "pending" | "dns-ready" | "route-ready" | "ready" | "blocked";
+export type AppDomainRecord = {
+ appId: string;
+ hostname: string;
+ phase: AppDomainPhase;
+ provider: DomainProviderId | null;
+ dnsAction?: "created" | "updated" | "unchanged";
+ routeAction?: "created" | "unchanged";
+ error?: string;
+ localOrigin?: string;
+ verifiedAt?: number;
+ updatedAt: number;
+};
+
+// `custom` is not "cannot write": it means the operator writes the record. It
+// stays selectable and the step prints what to create; marking it incapable
+// would delete the only manual-DNS path. Everything else must be truthful about
+// what it can create.
+const CAPABILITIES: Record<DomainProviderId, DomainProviderCapability> = {
+ cloudflare: { id: "cloudflare", aRecord: true, cname: true, txt: true, ingress: false },
+ hostinger: { id: "hostinger", aRecord: true, cname: true, txt: true, ingress: false },
+ dokploy: { id: "dokploy", aRecord: false, cname: false, txt: false, ingress: true },
+ custom: { id: "custom", aRecord: false, cname: false, txt: false, ingress: false },
+};
+
+export const domainProviderCapabilities = (id: DomainProviderId): DomainProviderCapability => CAPABILITIES[id];
+export const providerLabel = (id: DomainProviderId): string =>
+ id === "custom" ? "Custom (you manage DNS)" : id.charAt(0).toUpperCase() + id.slice(1);
+
+/** `recordType` is what the operator's target needs written. */
+export function providerBlockReason(id: DomainProviderId, recordType: "A" | "CNAME"): string | null {
+ if (id === "custom") return null;
+ const capability = domainProviderCapabilities(id);
+ if (recordType === "A" ? capability.aRecord : capability.cname) return null;
+ return id === "dokploy"
+ ? "Dokploy owns the ingress, not the DNS zone. Without a configured public IPv4 it cannot create this record, so nothing would be published."
+ : `${providerLabel(id)} cannot create ${recordType} records.`;
+}
+
+export function targetFor(value: string): AppDomainTarget | null {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ const octets = trimmed.split(".");
+ if (octets.length === 4 && octets.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)) return { kind: "ipv4", value: trimmed };
+ return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(trimmed) ? { kind: "cname", value: trimmed } : null;
+}
+
+/** Only an IP:port address is a *direct* address. A hostname stays a domain step. */
+export function directAddressFrom(url: string | null | undefined): string | null {
+ if (!url) return null;
+ try {
+ const parsed = new URL(url);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
+ return targetFor(parsed.hostname)?.kind === "ipv4" ? `${parsed.protocol}//${parsed.host}` : null;
+ } catch { return null; }
+}
+
+/** Default hostname offered in the step: the app's own host when it is a real name. */
+export function hostnameFromUrl(url: string | null | undefined): string {
+ if (!url) return "";
+ try {
+ const hostname = new URL(url).hostname;
+ return targetFor(hostname)?.kind === "cname" ? hostname : "";
+ } catch { return ""; }
+}
+
+export const DOMAIN_POLL_DEADLINE_MS = 120_000;
+const BASE_DELAY_MS = 1_000;
+const MAX_DELAY_MS = 8_000;
+
+export type AppDomainPollOutcome =
+ | { status: "settled"; record: AppDomainRecord }
+ | { status: "deadline"; record: AppDomainRecord | null; error?: string }
+ | { status: "cancelled"; record: AppDomainRecord | null };
+
+type Fetcher = (input: string, init?: RequestInit) => Promise<Response>;
+type PollOptions = {
+ appId: string;
+ signal?: AbortSignal;
+ onRecord?: (record: AppDomainRecord) => void;
+ /** Injection seams so the loop is testable without fake DOM timers. */
+ fetchImpl?: Fetcher;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+ deadlineMs?: number;
+};
+
+const sleepFor = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
+
+// Bounded poll: exponential backoff, a hard deadline, and a hard stop the moment
+// the record settles (ready/blocked) or the caller cancels. It never loops past
+// the deadline even if every request hangs — the deadline check runs before each
+// request and the wait is clamped to the remaining budget.
+export async function pollAppDomain(options: PollOptions): Promise<AppDomainPollOutcome> {
+ const fetcher = options.fetchImpl ?? ((input, init) => fetch(input, init));
+ const now = options.now ?? Date.now;
+ const sleep = options.sleep ?? sleepFor;
+ const deadline = now() + (options.deadlineMs ?? DOMAIN_POLL_DEADLINE_MS);
+ let record: AppDomainRecord | null = null;
+ let error: string | undefined;
+ let delay = BASE_DELAY_MS;
+ while (true) {
+ if (options.signal?.aborted) return { status: "cancelled", record };
+ if (now() >= deadline) return { status: "deadline", record, error };
+ try {
+ const response = await fetcher(`/api/v1/shell-apps/${encodeURIComponent(options.appId)}/domain`, { cache: "no-store", signal: options.signal });
+ if (response.ok) {
+ const next = await response.json() as AppDomainRecord | null;
+ if (next?.phase) {
+ record = next;
+ error = undefined;
+ options.onRecord?.(next);
+ if (next.phase === "ready" || next.phase === "blocked") return { status: "settled", record: next };
+ }
+ } else {
+ error = `Domain status returned ${response.status}.`;
+ }
+ } catch (cause) {
+ if (options.signal?.aborted) return { status: "cancelled", record };
+ error = cause instanceof Error ? cause.message : "Could not read domain status.";
+ }
+ const wait = Math.min(delay, deadline - now());
+ if (wait <= 0) return { status: "deadline", record, error };
+ await sleep(wait);
+ delay = Math.min(delay * 2, MAX_DELAY_MS);
+ }
+}
diff --git a/lib/contracts/app-domain.ts b/lib/contracts/app-domain.ts
new file mode 100644
index 00000000..0fb8f436
--- /dev/null
+++ b/lib/contracts/app-domain.ts
@@ -0,0 +1,30 @@
+// Single server-side source of truth for the shell-app domain shape. The provider layer
+// (`lib/infra/managed-domain-providers.ts`) and the provisioning layer
+// (`lib/surfaces/app-domain-provision.ts`) import these; neither re-declares them.
+// The browser cannot import this module, so `frontend/slices/app-store/lib/app-domain.ts`
+// mirrors it — same field names, same union members — and a parity test fails on drift.
+export const DOMAIN_PROVIDER_IDS = ["cloudflare", "hostinger", "dokploy", "custom"] as const;
+export type DomainProviderId = (typeof DOMAIN_PROVIDER_IDS)[number];
+export type DomainProviderCapability = {
+ id: DomainProviderId;
+ /** Provider can create/update an A record pointing at a public IPv4. */
+ aRecord: boolean;
+ /** Provider can create/update a CNAME. */
+ cname: boolean;
+ /** Provider can create/update a TXT challenge record (ownership proof). */
+ txt: boolean;
+ /** Provider owns the ingress (proxy/tunnel), so no separate route step is needed. */
+ ingress: boolean;
+};
+export type AppDomainPhase = "pending" | "dns-ready" | "route-ready" | "ready" | "blocked";
+export type AppDomainTarget = { kind: "ipv4"; value: string } | { kind: "cname"; value: string };
+export type AppDomainRecord = {
+ appId: string; hostname: string; phase: AppDomainPhase; provider: DomainProviderId | null;
+ dnsAction?: "created" | "updated" | "unchanged"; routeAction?: "created" | "unchanged";
+ /** Set when phase === "blocked": a bounded, redacted operator-facing reason. */
+ error?: string;
+ /** Loopback origin probed before any public DNS write. */
+ localOrigin?: string; verifiedAt?: number; updatedAt: number;
+};
+export type EnsureShellAppDomainInput = { provider: DomainProviderId; hostname: string; target: AppDomainTarget; zoneName?: string };
+export type AppDomainErrorCode = "invalid_hostname" | "invalid_target" | "unsupported_provider" | "domain_conflict" | "provider_unavailable" | "app_not_found";
diff --git a/lib/infra/cloudflare.ts b/lib/infra/cloudflare.ts
index 02aac94b..299f9c10 100644
--- a/lib/infra/cloudflare.ts
+++ b/lib/infra/cloudflare.ts
@@ -59,19 +59,34 @@ function validateDns(name: string, type: string, content: string): void {
if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
}
-export async function upsertCloudflareDns(input: { name: string; type: string; content: string; proxied?: boolean; ttl?: number }): Promise<{ action: string; id: string; name: string; type: string }> {
+/** Read-only lookup of the exact records a write would touch; ambiguity is an error, never first-match. */
+export async function inspectCloudflareDns(input: { name: string; type: string }): Promise<Array<{ id: string; name: string; type: string; content: string; ttl: number; proxied: boolean }>> {
const name = input.name.trim().replace(/\.$/, "").toLowerCase();
- const type = input.type.trim().toUpperCase();
- const content = input.content.trim();
- validateDns(name, type, content);
- if (input.ttl !== undefined && (!Number.isInteger(input.ttl) || input.ttl !== 1 && (input.ttl < 60 || input.ttl > 86400))) throw new Error("Cloudflare TTL must be 1 (auto) or 60-86400");
- const zone = await zoneFor(name);
+ const { exact } = await exactCloudflareRecords(await zoneFor(name), name, input.type.trim().toUpperCase());
+ return exact.map((row) => ({
+ id: String(row.id ?? ""), name: String(row.name ?? ""), type: String(row.type ?? ""),
+ content: String(row.content ?? ""), ttl: Number(row.ttl), proxied: Boolean(row.proxied),
+ }));
+}
+
+async function exactCloudflareRecords(zone: { id: string; token: string }, name: string, type: string) {
const base = `${API}/zones/${encodeURIComponent(zone.id)}/dns_records`;
const find = await request(`${base}?type=${encodeURIComponent(type)}&name.exact=${encodeURIComponent(name)}`, { headers: headers(zone.token) });
const found = parsed(find.body);
if (!find.ok || !found.success || !Array.isArray(found.result)) throw new Error(`Cloudflare record lookup HTTP ${find.status}`);
const exact = found.result.map(obj).filter((r) => String(r.name ?? "").toLowerCase() === name && String(r.type ?? "").toUpperCase() === type);
if (exact.length > 1) throw new Error(`refusing ambiguous DNS change: ${exact.length} ${type} records already exist for ${name}`);
+ return { base, exact };
+}
+
+export async function upsertCloudflareDns(input: { name: string; type: string; content: string; proxied?: boolean; ttl?: number }): Promise<{ action: string; id: string; name: string; type: string }> {
+ const name = input.name.trim().replace(/\.$/, "").toLowerCase();
+ const type = input.type.trim().toUpperCase();
+ const content = input.content.trim();
+ validateDns(name, type, content);
+ if (input.ttl !== undefined && (!Number.isInteger(input.ttl) || input.ttl !== 1 && (input.ttl < 60 || input.ttl > 86400))) throw new Error("Cloudflare TTL must be 1 (auto) or 60-86400");
+ const zone = await zoneFor(name);
+ const { base, exact } = await exactCloudflareRecords(zone, name, type);
const proxied = ["A", "AAAA", "CNAME"].includes(type) ? input.proxied === true : undefined;
const payload = { type, name, content, ttl: proxied ? 1 : input.ttl ?? 1, ...(proxied === undefined ? {} : { proxied }) };
if (exact.length === 1) {
diff --git a/lib/infra/composio.test.ts b/lib/infra/composio.test.ts
index 63c54f0f..fd7a390c 100644
--- a/lib/infra/composio.test.ts
+++ b/lib/infra/composio.test.ts
@@ -29,3 +29,11 @@ describe("composio credential routing", () => {
await expect(doctorComposio({ apiKey: "uak_synthetic_user_key" })).rejects.toThrow("Composio rejected this user key (401)");
});
});
+
+describe("composio connect consumer keys", () => {
+ it("refuses a ck_ Connect key instead of sending it to the Platform API", () => {
+ expect(() => composioAuthHeader({ apiKey: "ck_consumer_key" })).toThrow(/Project MCP/);
+ expect(() => composioAuthHeader({ orgApiKey: "ck_consumer_key" })).toThrow(/Project MCP/);
+ expect(() => composioAuthHeader({ apiKey: "ak_project" })).not.toThrow();
+ });
+});
diff --git a/lib/infra/composio.ts b/lib/infra/composio.ts
index 1e2600ef..c4341b24 100644
--- a/lib/infra/composio.ts
+++ b/lib/infra/composio.ts
@@ -5,16 +5,28 @@ import { request } from "./http";
const API = "https://backend.composio.dev/api/v3.1";
/**
- * Composio has four key kinds and each needs its own header. Project and scoped
- * project keys use x-api-key; organization keys use x-org-api-key; a user key
- * (uak_..., written by `composio login`) uses x-user-api-key. Sending a user key
- * as x-api-key is rejected with 401, which used to make every save fail.
+ * Composio keys live on two different products and only one of them is this
+ * provider. Platform keys (ak_ project, uak_ user from `composio login`, org
+ * keys) authenticate against backend.composio.dev/api/v3.1. A ck_ Connect
+ * consumer key belongs to the Connect MCP product at connect.composio.dev/mcp
+ * and is rejected by every Platform route with 401, so storing it here can
+ * never work. Connect MCP keys belong in the Project MCP provider, which speaks
+ * streamable HTTP and already accepts them.
*/
+export function composioConnectKey(value: string | undefined): boolean {
+ return Boolean(value?.trim().startsWith("ck_"));
+}
+
+export const COMPOSIO_CONNECT_KEY_MESSAGE =
+ "Composio Connect key (ck_…) is not a Platform key. Use Integrations → Project MCP with https://connect.composio.dev/mcp. Platform keys start ak_ or uak_.";
+
export function composioAuthHeader(values: InfraProviderValues): { header: Record<string, string>; kind: "organization" | "user" | "project" } | null {
const orgKey = values.orgApiKey?.trim();
+ if (composioConnectKey(orgKey)) throw new Error(COMPOSIO_CONNECT_KEY_MESSAGE);
if (orgKey) return { header: { "x-org-api-key": orgKey }, kind: "organization" };
const key = values.apiKey?.trim();
if (!key) return null;
+ if (composioConnectKey(key)) throw new Error(COMPOSIO_CONNECT_KEY_MESSAGE);
if (key.startsWith("uak_")) return { header: { "x-user-api-key": key }, kind: "user" };
return { header: { "x-api-key": key }, kind: "project" };
}
diff --git a/lib/infra/connection-external.ts b/lib/infra/connection-external.ts
index 89eaffe8..99d36f49 100644
--- a/lib/infra/connection-external.ts
+++ b/lib/infra/connection-external.ts
@@ -4,10 +4,11 @@ import { selectConnection, IntegrationError, assertNotBusy, type ConnectionSelec
import { composioDefinition, nativeDefinition } from "./connection-registry";
import { summaryIn } from "./connection-service";
import { request, obj } from "./http";
-import { composioAuthHeader } from "./composio";
+import { composioAuthHeader, composioConnectKey } from "./composio";
const BASE="https://backend.composio.dev/api/v3.1";
async function api(values:Record<string,string>,endpoint:string,body?:unknown){
- const auth=composioAuthHeader(values);if(!auth)throw new IntegrationError("composio_project_key_required",409);
+ let auth;try{auth=composioAuthHeader(values);}catch(e){throw new IntegrationError("composio_connect_key_wrong_provider",409);}
+ if(!auth)throw new IntegrationError("composio_project_key_required",409);
let result;try{result=await request(BASE+endpoint,{method:body===undefined?"GET":"POST",headers:{...auth.header,accept:"application/json","content-type":"application/json"},...(body===undefined?{}:{body:JSON.stringify(body)})});}catch{throw new IntegrationError("composio_unreachable",502);}
if(!result.ok)throw new IntegrationError(`composio_http_${result.status}`,502);return obj(result.body);
}
@@ -17,6 +18,7 @@ async function context(provider:string,selection:ConnectionSelector,brokerId?:st
if(c.source!=="composio")throw new IntegrationError("composio_source_required");
const broker=selectConnection(d,"composio",{user:r.user,connection:brokerId??c.external?.brokerConnection,source:"direct",authMethod:"project"}).connection;
if(!broker.values.apiKey&&!broker.values.orgApiKey)throw new IntegrationError("composio_project_key_required",409);
+ if(composioConnectKey(broker.values.apiKey)||composioConnectKey(broker.values.orgApiKey))throw new IntegrationError("composio_connect_key_wrong_provider",409);
return{d,r,c,broker,definition:composioDefinition(provider)!};
}
async function authorizeUnlocked(provider:string,selection:ConnectionSelector,options:{authConfigId?:string;brokerConnection?:string;createManaged?:boolean}={}){
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index 159f0926..49296663 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -24,7 +24,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
popup.addEventListener("keydown",event=>{if(event.key==="ArrowDown")move(event,1);else if(event.key==="ArrowUp")move(event,-1);else if(event.key==="Home"){event.preventDefault();options[0]?.[1].focus()}else if(event.key==="End"){event.preventDefault();options.at(-1)?.[1].focus()}else if(event.key==="Escape"){event.preventDefault();close(true)}});
wrap.addEventListener("focusout",()=>setTimeout(()=>{if(!wrap.contains(document.activeElement))close()},0));wrap.append(caption,trigger,popup);paint();return{wrap,get value(){return value},set value(next){value=next;paint()}};
};
- const textError=e=>({user_required:"Select a credential owner first.",connection_ambiguous:"Choose a named connection; more than one account exists.",connection_has_folder_binding:"Remove or change this connection's folder binding before deleting it.",integration_has_variables:"Remove Integration Variables that point to this owner or connection first.",invalid_variable_key:"Variable names use uppercase A-Z, 0-9 and underscore.",connection_busy:"This connection is being used. Retry after that operation finishes.",choose_auth_config_id:"Several Composio auth configs match. Enter the intended auth config ID.",matching_auth_config_required:"Select a matching Composio auth config, or explicitly permit managed OAuth setup.",composio_project_key_required:"Configure a Composio project key under this same credential owner first.",external_source_requires_own_executor:"This connection uses an external backend; a local API key will not be substituted.",user_has_shared_dependents:"Unshare this owner’s shared connections before deleting the owner.",connection_has_shared_dependents:"Unshare dependent accounts before deleting this connection.",shared_alias_readonly:"Shared connections are read-only. Rotate credentials from the owner connection.",shared_alias_cannot_share:"A shared connection cannot be shared again. Share from its owner instead.",external_connections_cannot_share:"Only direct MSO credentials can be shared between credential owners.",shared_alias_use_unshare:"Use Unshare to remove a shared connection without touching its owner.",owner_required:"Sign in as an Owner before changing connections."}[e.code||e.message]||e.message||"Operation failed.");
+ const textError=e=>({user_required:"Select a credential owner first.",connection_ambiguous:"Choose a named connection; more than one account exists.",connection_has_folder_binding:"Remove or change this connection's folder binding before deleting it.",integration_has_variables:"Remove Integration Variables that point to this owner or connection first.",invalid_variable_key:"Variable names use uppercase A-Z, 0-9 and underscore.",connection_busy:"This connection is being used. Retry after that operation finishes.",choose_auth_config_id:"Several Composio auth configs match. Enter the intended auth config ID.",matching_auth_config_required:"Select a matching Composio auth config, or explicitly permit managed OAuth setup.",composio_project_key_required:"Configure a Composio project key under this same credential owner first.",composio_connect_key_wrong_provider:"This is a Composio Connect consumer key (ck_…), not a Platform key. It only works under Integrations → Project MCP with the endpoint https://connect.composio.dev/mcp. Platform keys start with ak_ (project) or uak_ (user).",external_source_requires_own_executor:"This connection uses an external backend; a local API key will not be substituted.",user_has_shared_dependents:"Unshare this owner’s shared connections before deleting the owner.",connection_has_shared_dependents:"Unshare dependent accounts before deleting this connection.",shared_alias_readonly:"Shared connections are read-only. Rotate credentials from the owner connection.",shared_alias_cannot_share:"A shared connection cannot be shared again. Share from its owner instead.",external_connections_cannot_share:"Only direct MSO credentials can be shared between credential owners.",shared_alias_use_unshare:"Use Unshare to remove a shared connection without touching its owner.",owner_required:"Sign in as an Owner before changing connections."}[e.code||e.message]||e.message||"Operation failed.");
function remember(){if(bridge.remember)bridge.remember({user,provider:provider.id})}
async function reload(){const version=++sequence;if(!bridge.query){draw();return}try{const next=await bridge.query({view:"snapshot",...(user?{user}:{})});if(disposed||version!==sequence)return;snapshot=next;user=next.user||user;draw();remember()}catch(e){if(!disposed){draw();status.textContent=textError(e)}}}
async function change(args,after=reload){if(!bridge.manage)return;try{status.textContent="Saving connection metadata…";await bridge.manage({...args,confirm:true});await after()}catch(e){status.textContent=textError(e)}}
diff --git a/lib/infra/hostinger.ts b/lib/infra/hostinger.ts
index 27950eff..158c69ec 100644
--- a/lib/infra/hostinger.ts
+++ b/lib/infra/hostinger.ts
@@ -30,6 +30,15 @@ async function rootFor(fullDomain: string, token: string): Promise<{ root: strin
return { root: roots[0], name: fullDomain === roots[0] ? "@" : fullDomain.slice(0, -(roots[0].length + 1)) };
}
+/** Read-only zone view for a hostname MSO may edit: portfolio apex, local record name and rows. */
+export async function readHostingerZone(fullDomain: string, token: string): Promise<{ root: string; name: string; url: string; rows: Record<string, unknown>[] }> {
+ const { root, name } = await rootFor(fullDomain, token);
+ const url = `${API}/dns/v1/zones/${encodeURIComponent(root)}`;
+ const zone = await request(url, { headers: headers(token) });
+ if (!zone.ok || !Array.isArray(zone.body)) throw new Error(`Hostinger zone HTTP ${zone.status}`);
+ return { root, name, url, rows: zone.body.map((row) => ({ ...obj(row) })) };
+}
+
export async function upsertHostingerDns(input: { name: string; type: string; content: string; ttl?: number }): Promise<{ action: string; name: string; type: string }> {
const values = await readInfraProvider("hostinger");
if (!values.apiToken) throw new Error("Hostinger is not configured; run `mso provider set hostinger`");
@@ -40,12 +49,8 @@ export async function upsertHostingerDns(input: { name: string; type: string; co
if (type === "A" && isIP(content) !== 4) throw new Error("A record content must be an IPv4 address");
if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
if (input.ttl !== undefined && (!Number.isInteger(input.ttl) || input.ttl < 60 || input.ttl > 2147483647)) throw new Error("Hostinger TTL must be an integer from 60 to 2147483647");
- const { root, name } = await rootFor(fullDomain, values.apiToken);
- const url = `${API}/dns/v1/zones/${encodeURIComponent(root)}`;
+ const { name, url, rows } = await readHostingerZone(fullDomain, values.apiToken);
const auth = headers(values.apiToken);
- const zone = await request(url, { headers: auth });
- if (!zone.ok || !Array.isArray(zone.body)) throw new Error(`Hostinger zone HTTP ${zone.status}`);
- const rows = zone.body.map((row) => ({ ...obj(row) }));
const exact = rows.filter((row) => String(row.name ?? "") === name && String(row.type ?? "").toUpperCase() === type);
if (exact.length > 1) throw new Error(`refusing ambiguous Hostinger DNS change: ${exact.length} ${type} rows exist for ${fullDomain}`);
const conflicts = rows.filter((row) => String(row.name ?? "") === name && ((type === "CNAME" && ["A", "AAAA"].includes(String(row.type ?? "").toUpperCase())) || (["A", "AAAA"].includes(type) && String(row.type ?? "").toUpperCase() === "CNAME")));
diff --git a/lib/infra/managed-domain-providers.test.ts b/lib/infra/managed-domain-providers.test.ts
new file mode 100644
index 00000000..4d195158
--- /dev/null
+++ b/lib/infra/managed-domain-providers.test.ts
@@ -0,0 +1,209 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DomainRecordRequest } from "./managed-domain-providers";
+
+const readInfraProvider = vi.fn();
+const listCloudflareZones = vi.fn();
+const upsertCloudflareDns = vi.fn();
+const inspectCloudflareDns = vi.fn();
+const upsertHostingerDns = vi.fn();
+const readHostingerZone = vi.fn();
+const request = vi.fn();
+
+vi.mock("./store", () => ({ readInfraProvider }));
+vi.mock("./cloudflare", () => ({ listCloudflareZones, upsertCloudflareDns, inspectCloudflareDns }));
+vi.mock("./hostinger", () => ({ upsertHostingerDns, readHostingerZone }));
+// The cast sits on its own const, not on the awaited call: Semgrep's TypeScript
+// parser cannot read a generic type argument on `await importOriginal<...>()`,
+// and `--strict` turns that parse warning into a failed scan despite 0 findings.
+vi.mock("./http", async (importOriginal) => {
+ const actual = await importOriginal() as typeof import("./http");
+ return { ...actual, request };
+});
+
+const { domainProviderCapabilities, ensureDomainRecords, inspectDomainRecords } = await import("./managed-domain-providers");
+const TOKEN = "synthetic-provider-token-0000000001";
+const ZONE = "example.com";
+const base: DomainRecordRequest = { provider: "cloudflare", zoneName: ZONE, hostnames: ["app.example.com"], target: { kind: "ipv4", value: "203.0.113.10" } };
+const reply = (body: unknown, status = 200) => ({ ok: status >= 200 && status < 300, status, body, text: JSON.stringify(body) });
+const cfRecord = (content: string) => [{ id: "d".repeat(32), name: "app.example.com", type: "A", content, ttl: 1, proxied: false }];
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ readInfraProvider.mockResolvedValue({ apiToken: TOKEN });
+ listCloudflareZones.mockResolvedValue([{ id: "a".repeat(32), name: ZONE }]);
+ upsertCloudflareDns.mockResolvedValue({ action: "created", id: "d".repeat(32), name: "app.example.com", type: "A" });
+ inspectCloudflareDns.mockResolvedValue([]);
+ upsertHostingerDns.mockResolvedValue({ action: "created", name: "app.example.com", type: "A" });
+ readHostingerZone.mockResolvedValue({ root: ZONE, name: "app", url: "", rows: [] });
+ request.mockImplementation(async (url: string) => url.includes("/portfolio") ? reply([{ domain: ZONE }]) : reply({ success: true, result: [] }));
+});
+
+describe("domainProviderCapabilities", () => {
+ it("reports ingress only for dokploy and no writes for custom", () => {
+ expect(domainProviderCapabilities("cloudflare")).toEqual({ id: "cloudflare", aRecord: true, cname: true, txt: true, ingress: false });
+ expect(domainProviderCapabilities("hostinger")).toEqual({ id: "hostinger", aRecord: true, cname: true, txt: true, ingress: false });
+ expect(domainProviderCapabilities("dokploy")).toEqual({ id: "dokploy", aRecord: true, cname: false, txt: false, ingress: true });
+ expect(domainProviderCapabilities("custom")).toEqual({ id: "custom", aRecord: false, cname: false, txt: false, ingress: false });
+ });
+ it("rejects an unknown provider id instead of inventing a capability", () => {
+ expect(() => domainProviderCapabilities("route53" as never)).toThrow("unknown domain provider");
+ });
+});
+
+describe("custom provider", () => {
+ it("never writes and reports unchanged so the caller can surface manual instructions", async () => {
+ expect(await ensureDomainRecords({ ...base, provider: "custom" })).toEqual({ provider: "custom", action: "unchanged", records: [{ hostname: "app.example.com", type: "A" }] });
+ expect(await inspectDomainRecords({ ...base, provider: "custom" })).toBe("unchanged");
+ expect(readInfraProvider).not.toHaveBeenCalled();
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+});
+
+describe("cloudflare provider", () => {
+ it("delegates every hostname to the existing upsert helper", async () => {
+ upsertCloudflareDns.mockResolvedValue({ action: "updated", id: "d".repeat(32), name: "app.example.com", type: "A" });
+ const result = await ensureDomainRecords({ ...base, hostnames: ["app.example.com", "api.example.com"] });
+ expect(upsertCloudflareDns).toHaveBeenCalledWith({ name: "app.example.com", type: "A", content: "203.0.113.10" });
+ expect(upsertCloudflareDns).toHaveBeenCalledWith({ name: "api.example.com", type: "A", content: "203.0.113.10" });
+ expect(result.action).toBe("updated");
+ expect(result.records).toHaveLength(2);
+ expect(result.records[0]).toEqual({ hostname: "app.example.com", type: "A", recordId: "d".repeat(32) });
+ });
+ it("inspects through the read-only helper and compares the target without writing", async () => {
+ expect(await inspectDomainRecords(base)).toBe("created");
+ inspectCloudflareDns.mockResolvedValue(cfRecord("203.0.113.10"));
+ expect(await inspectDomainRecords(base)).toBe("unchanged");
+ inspectCloudflareDns.mockResolvedValue(cfRecord("198.51.100.1"));
+ expect(await inspectDomainRecords(base)).toBe("updated");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("propagates the pinned-zone rejection from the Cloudflare helper", async () => {
+ upsertCloudflareDns.mockRejectedValue(new Error("configured Cloudflare zoneId is not accessible to this token"));
+ await expect(ensureDomainRecords(base)).rejects.toThrow("zoneId is not accessible");
+ });
+});
+
+describe("hostinger provider", () => {
+ it("delegates validation and ambiguity to upsertHostingerDns", async () => {
+ expect(await ensureDomainRecords({ ...base, provider: "hostinger" })).toEqual({ provider: "hostinger", action: "created", records: [{ hostname: "app.example.com", type: "A" }] });
+ expect(upsertHostingerDns).toHaveBeenCalledWith({ name: "app.example.com", type: "A", content: "203.0.113.10" });
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ });
+ it("inspects zone rows relative to the portfolio apex and rejects a foreign apex", async () => {
+ readHostingerZone.mockResolvedValue({ root: ZONE, name: "app", url: "", rows: [{ name: "app", type: "A", records: [{ content: "203.0.113.10" }] }] });
+ expect(await inspectDomainRecords({ ...base, provider: "hostinger" })).toBe("unchanged");
+ readHostingerZone.mockResolvedValue({ root: ZONE, name: "app", url: "", rows: [{ name: "app", type: "A", records: [{ content: "198.51.100.1" }] }] });
+ expect(await inspectDomainRecords({ ...base, provider: "hostinger" })).toBe("updated");
+ readHostingerZone.mockResolvedValue({ root: ZONE, name: "@", url: "", rows: [] });
+ expect(await inspectDomainRecords({ ...base, provider: "hostinger", hostnames: [ZONE] })).toBe("created");
+ readHostingerZone.mockResolvedValue({ root: "other.test", name: "@", url: "", rows: [] });
+ await expect(inspectDomainRecords({ ...base, provider: "hostinger" })).rejects.toThrow("outside zone");
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("propagates a portfolio rejection from the Hostinger helper before any write", async () => {
+ upsertHostingerDns.mockRejectedValue(new Error("app.example.com is not in the Hostinger domain portfolio"));
+ await expect(ensureDomainRecords({ ...base, provider: "hostinger" })).rejects.toThrow("not in the Hostinger domain portfolio");
+ });
+});
+
+describe("dokploy provider", () => {
+ const dokploy = { apiUrl: "https://panel.example.com/api", apiKey: "k".repeat(32), publicIp: "203.0.113.10" };
+
+ it("writes A records through the Cloudflare zone owner when publicIp is configured", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : id === "cloudflare" ? { apiToken: TOKEN } : {});
+ expect(await ensureDomainRecords({ ...base, provider: "dokploy" })).toMatchObject({ provider: "dokploy", action: "created" });
+ expect(upsertCloudflareDns).toHaveBeenCalledWith({ name: "app.example.com", type: "A", content: "203.0.113.10" });
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("writes through Hostinger when only Hostinger owns the zone", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : id === "hostinger" ? { apiToken: TOKEN } : {});
+ await ensureDomainRecords({ ...base, provider: "dokploy" });
+ expect(upsertHostingerDns).toHaveBeenCalledWith({ name: "app.example.com", type: "A", content: "203.0.113.10" });
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ });
+ it("fails closed without publicIp or with a target that differs from it", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? { apiUrl: dokploy.apiUrl, apiKey: dokploy.apiKey } : { apiToken: TOKEN });
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy" })).rejects.toThrow("no publicIp configured");
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : { apiToken: TOKEN });
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy", target: { kind: "ipv4", value: "203.0.113.99" } })).rejects.toThrow("must equal the configured publicIp");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ });
+ it("fails closed when no zone provider is configured", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : {});
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy" })).rejects.toThrow("Dokploy cannot write DNS for example.com");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("rejects ambiguous zone ownership across Cloudflare and Hostinger", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : { apiToken: TOKEN });
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy" })).rejects.toThrow("ambiguous DNS ownership");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("refuses a CNAME because Dokploy ingress publishes A records only", async () => {
+ readInfraProvider.mockImplementation(async (id: string) => id === "dokploy" ? dokploy : { apiToken: TOKEN });
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy", target: { kind: "cname", value: "edge.example.net" } })).rejects.toThrow("A records only");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ });
+});
+
+describe("missing credentials and ambiguity", () => {
+ it.each(["cloudflare", "hostinger"] as const)("rejects %s without a token and writes nothing", async (provider) => {
+ readInfraProvider.mockResolvedValue({});
+ await expect(ensureDomainRecords({ ...base, provider })).rejects.toThrow("is not configured");
+ await expect(inspectDomainRecords({ ...base, provider })).rejects.toThrow("is not configured");
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("rejects missing Dokploy credentials before resolving a zone writer", async () => {
+ readInfraProvider.mockResolvedValue({});
+ await expect(ensureDomainRecords({ ...base, provider: "dokploy" })).rejects.toThrow("Dokploy is not configured");
+ expect(listCloudflareZones).not.toHaveBeenCalled();
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ });
+ it("rejects two candidate records for one name instead of first-match", async () => {
+ inspectCloudflareDns.mockRejectedValue(new Error("refusing ambiguous DNS change: 2 A records already exist for app.example.com"));
+ await expect(inspectDomainRecords(base)).rejects.toThrow("refusing ambiguous DNS change: 2 A records");
+ readHostingerZone.mockResolvedValue({ root: ZONE, name: "app", url: "", rows: [{ name: "app", type: "A", records: [{ content: "203.0.113.10" }] }, { name: "app", type: "A", records: [{ content: "203.0.113.11" }] }] });
+ await expect(inspectDomainRecords({ ...base, provider: "hostinger" })).rejects.toThrow("refusing ambiguous DNS change: 2 A rows");
+ upsertHostingerDns.mockRejectedValue(new Error("refusing ambiguous Hostinger DNS change: 2 A rows exist for app.example.com"));
+ await expect(ensureDomainRecords({ ...base, provider: "hostinger" })).rejects.toThrow("ambiguous");
+ });
+});
+
+describe("redaction", () => {
+ it("never lets credential material reach a thrown error, on write or inspection", async () => {
+ upsertCloudflareDns.mockRejectedValue(new Error(`Cloudflare DNS POST HTTP 403 for Authorization: Bearer ${TOKEN}`));
+ const write = await ensureDomainRecords(base).catch((caught: Error) => caught);
+ expect(write).toBeInstanceOf(Error);
+ expect(String(write)).not.toContain(TOKEN);
+ expect(String(write)).toContain("[redacted]");
+ inspectCloudflareDns.mockRejectedValue(new Error(`lookup failed with token ${TOKEN}`));
+ expect(String(await inspectDomainRecords(base).catch((caught: Error) => caught))).not.toContain(TOKEN);
+ });
+});
+
+describe("request validation", () => {
+ it.each([
+ [{ hostnames: ["app.other.test"] }, "outside zone"],
+ [{ target: { kind: "ipv4", value: "not-an-ip" } }, "IPv4"],
+ [{ target: { kind: "ipv4", value: "2001:db8::1" } }, "IPv4"],
+ [{ target: { kind: "cname", value: "not a host" } }, "CNAME target"],
+ [{ hostnames: [] }, "at least one hostname"],
+ [{ provider: "route53" }, "unknown domain provider"],
+ [{ zoneName: "not a zone" }, "invalid zone name"],
+ ] as const)("rejects invalid input %#", async (patch, message) => {
+ await expect(ensureDomainRecords({ ...base, ...(patch as object) } as DomainRecordRequest)).rejects.toThrow(message);
+ expect(upsertCloudflareDns).not.toHaveBeenCalled();
+ expect(upsertHostingerDns).not.toHaveBeenCalled();
+ });
+ it("normalizes case and a trailing dot, de-duplicates, and normalizes a CNAME target", async () => {
+ await ensureDomainRecords({ ...base, zoneName: "Example.COM.", hostnames: ["App.Example.com.", "app.example.com"] });
+ expect(upsertCloudflareDns).toHaveBeenCalledTimes(1);
+ expect(upsertCloudflareDns).toHaveBeenCalledWith({ name: "app.example.com", type: "A", content: "203.0.113.10" });
+ await ensureDomainRecords({ ...base, target: { kind: "cname", value: "Edge.Example.NET." } });
+ expect(upsertCloudflareDns).toHaveBeenLastCalledWith({ name: "app.example.com", type: "CNAME", content: "edge.example.net" });
+ });
+});
diff --git a/lib/infra/managed-domain-providers.ts b/lib/infra/managed-domain-providers.ts
new file mode 100644
index 00000000..6112d625
--- /dev/null
+++ b/lib/infra/managed-domain-providers.ts
@@ -0,0 +1,178 @@
+import { isIP } from "node:net";
+import { inspectCloudflareDns, listCloudflareZones, upsertCloudflareDns } from "./cloudflare";
+import { readHostingerZone, upsertHostingerDns } from "./hostinger";
+import { readInfraProvider } from "./store";
+import { HOST_RE, obj, request } from "./http";
+import type { AppDomainTarget, DomainProviderCapability, DomainProviderId } from "@/lib/contracts/app-domain";
+import { redactText } from "@/lib/security/redact-text";
+
+export type DomainRecordRequest = {
+ provider: DomainProviderId;
+ zoneName: string;
+ hostnames: string[];
+ target: AppDomainTarget;
+};
+
+export type DomainRecordResult = {
+ provider: DomainProviderId;
+ action: "created" | "updated" | "unchanged";
+ records: Array<{ hostname: string; type: "A" | "CNAME"; recordId?: string }>;
+};
+
+type Action = DomainRecordResult["action"];
+type RecordType = "A" | "CNAME";
+type Writer = "cloudflare" | "hostinger";
+type Normalized = { provider: DomainProviderId; zoneName: string; hostnames: string[]; type: RecordType; content: string };
+
+const CAPABILITIES: Record<DomainProviderId, Omit<DomainProviderCapability, "id">> = {
+ cloudflare: { aRecord: true, cname: true, txt: true, ingress: false },
+ hostinger: { aRecord: true, cname: true, txt: true, ingress: false },
+ dokploy: { aRecord: true, cname: false, txt: false, ingress: true },
+ custom: { aRecord: false, cname: false, txt: false, ingress: false },
+};
+
+const HOSTINGER_API = "https://developers.hostinger.com/api";
+const normalizeName = (value: string) => value.trim().toLowerCase().replace(/\.$/, "");
+const SECRET_KEYS = ["apiToken", "apiKey", "mailApiToken"] as const;
+
+/**
+ * Provider error text reaches a caller only after redaction. `redactText` catches `token: …`
+ * shapes; a bare credential echoed without a label is scrubbed literally as well.
+ */
+async function fail(error: unknown): Promise<never> {
+ let message = error instanceof Error ? error.message : String(error);
+ const values = await Promise.all((["cloudflare", "hostinger", "dokploy"] as const)
+ .map(async (id) => (await readInfraProvider(id).catch(() => ({}))) as Record<string, string>));
+ for (const provider of values) {
+ for (const key of SECRET_KEYS) {
+ const secret = provider[key];
+ if (secret && secret.length >= 8) message = message.split(secret).join("[redacted]");
+ }
+ }
+ throw new Error(redactText(message, 500));
+}
+
+export function domainProviderCapabilities(id: DomainProviderId): DomainProviderCapability {
+ const capability = CAPABILITIES[id];
+ if (!capability) throw new Error(`unknown domain provider: ${String(id)}`);
+ return { id, ...capability };
+}
+
+function normalizeRequest(input: DomainRecordRequest): Normalized {
+ const { provider } = input;
+ if (!Object.hasOwn(CAPABILITIES, provider)) throw new Error(`unknown domain provider: ${String(provider)}`);
+ const zoneName = normalizeName(String(input.zoneName ?? ""));
+ if (!HOST_RE.test(zoneName)) throw new Error("invalid zone name");
+ const hostnames = [...new Set(input.hostnames.map(normalizeName))];
+ if (!hostnames.length) throw new Error("at least one hostname is required");
+ for (const hostname of hostnames) {
+ if (!HOST_RE.test(hostname)) throw new Error(`invalid hostname: ${hostname}`);
+ if (hostname !== zoneName && !hostname.endsWith(`.${zoneName}`)) throw new Error(`${hostname} is outside zone ${zoneName}`);
+ }
+ const target = input.target;
+ if (target?.kind === "ipv4") {
+ if (typeof target.value !== "string" || isIP(target.value) !== 4) throw new Error("A record target must be an IPv4 address");
+ return { provider, zoneName, hostnames, type: "A", content: target.value };
+ }
+ if (target?.kind === "cname") {
+ const content = normalizeName(String(target.value ?? ""));
+ if (!HOST_RE.test(content)) throw new Error("CNAME target must be a hostname");
+ return { provider, zoneName, hostnames, type: "CNAME", content };
+ }
+ throw new Error("target must be ipv4 or cname");
+}
+
+const aggregate = (actions: Action[]): Action =>
+ actions.includes("created") ? "created" : actions.includes("updated") ? "updated" : "unchanged";
+
+/**
+ * Dokploy publishes ingress only, so DNS is written by whichever configured provider owns the
+ * zone. Zero or several owners fail closed rather than picking one.
+ */
+async function dokployZoneProvider(zoneName: string): Promise<Writer> {
+ const [cloudflare, hostinger] = await Promise.all([readInfraProvider("cloudflare"), readInfraProvider("hostinger")]);
+ const owners: Writer[] = [];
+ if (cloudflare.apiToken && (await listCloudflareZones(cloudflare)).some((zone) => zone.name === zoneName)) owners.push("cloudflare");
+ if (hostinger.apiToken) {
+ const res = await request(`${HOSTINGER_API}/domains/v1/portfolio`, { headers: { authorization: `Bearer ${hostinger.apiToken}`, accept: "application/json" } });
+ if (!res.ok || !Array.isArray(res.body)) throw new Error(`Hostinger portfolio HTTP ${res.status}`);
+ if (res.body.map(obj).some((row) => String(row.domain ?? "") === zoneName)) owners.push("hostinger");
+ }
+ if (!owners.length) throw new Error(`Dokploy cannot write DNS for ${zoneName}: configure Cloudflare or Hostinger for that zone, or use the custom provider`);
+ if (owners.length > 1) throw new Error(`refusing ambiguous DNS ownership for ${zoneName}: both Cloudflare and Hostinger manage it`);
+ return owners[0]!;
+}
+
+/** Missing credentials fail closed here, before any helper can fall through to a partial write. */
+async function resolveWriter(req: Normalized): Promise<Writer> {
+ if (req.provider === "cloudflare" || req.provider === "hostinger") {
+ const values = await readInfraProvider(req.provider);
+ if (!values.apiToken) throw new Error(`${req.provider === "cloudflare" ? "Cloudflare" : "Hostinger"} is not configured; run \`mso provider set ${req.provider}\``);
+ return req.provider;
+ }
+ const values = await readInfraProvider("dokploy");
+ if (!values.apiUrl || !values.apiKey) throw new Error("Dokploy is not configured; run `mso provider set dokploy`");
+ if (req.type !== "A") throw new Error("Dokploy ingress publishes IPv4 A records only; select Cloudflare or Hostinger for a CNAME");
+ if (!values.publicIp) throw new Error("Dokploy has no publicIp configured; set it in the Dokploy connection or use the custom provider");
+ if (req.content !== values.publicIp) throw new Error("Dokploy A record target must equal the configured publicIp");
+ return dokployZoneProvider(req.zoneName);
+}
+
+async function inspectHostingerRecord(zoneName: string, hostname: string, type: RecordType, content: string): Promise<Action> {
+ const values = await readInfraProvider("hostinger");
+ if (!values.apiToken) throw new Error("Hostinger is not configured; run `mso provider set hostinger`");
+ const { root, rows } = await readHostingerZone(hostname, values.apiToken);
+ if (root !== zoneName) throw new Error(`${hostname} is outside zone ${zoneName}`);
+ const local = hostname === root ? "@" : hostname.slice(0, -(root.length + 1));
+ const exact = rows.filter((row) => String(row.name ?? "") === local && String(row.type ?? "").toUpperCase() === type);
+ if (exact.length > 1) throw new Error(`refusing ambiguous DNS change: ${exact.length} ${type} rows exist for ${hostname}`);
+ if (!exact.length) return "created";
+ const targets = Array.isArray(exact[0].records) ? exact[0].records.map(obj).map((row) => normalizeName(String(row.content ?? ""))) : [];
+ return targets.length === 1 && targets[0] === normalizeName(content) ? "unchanged" : "updated";
+}
+
+export async function ensureDomainRecords(input: DomainRecordRequest): Promise<DomainRecordResult> {
+ const req = normalizeRequest(input);
+ if (req.provider === "custom") {
+ return { provider: "custom", action: "unchanged", records: req.hostnames.map((hostname) => ({ hostname, type: req.type })) };
+ }
+ try {
+ const writer = await resolveWriter(req);
+ const actions: Action[] = [];
+ const records: DomainRecordResult["records"] = [];
+ for (const hostname of req.hostnames) {
+ if (writer === "cloudflare") {
+ const result = await upsertCloudflareDns({ name: hostname, type: req.type, content: req.content });
+ actions.push(result.action as Action);
+ records.push({ hostname, type: req.type, ...(result.id ? { recordId: result.id } : {}) });
+ } else {
+ const result = await upsertHostingerDns({ name: hostname, type: req.type, content: req.content });
+ actions.push(result.action as Action);
+ records.push({ hostname, type: req.type });
+ }
+ }
+ return { provider: req.provider, action: aggregate(actions), records };
+ } catch (error) {
+ return fail(error);
+ }
+}
+
+export async function inspectDomainRecords(input: DomainRecordRequest): Promise<DomainRecordResult["action"]> {
+ const req = normalizeRequest(input);
+ if (req.provider === "custom") return "unchanged";
+ try {
+ const writer = await resolveWriter(req);
+ const actions: Action[] = [];
+ for (const hostname of req.hostnames) {
+ if (writer === "hostinger") {
+ actions.push(await inspectHostingerRecord(req.zoneName, hostname, req.type, req.content));
+ continue;
+ }
+ const records = await inspectCloudflareDns({ name: hostname, type: req.type });
+ actions.push(!records.length ? "created" : normalizeName(records[0]!.content) === normalizeName(req.content) ? "unchanged" : "updated");
+ }
+ return aggregate(actions);
+ } catch (error) {
+ return fail(error);
+ }
+}
diff --git a/lib/security-store-path.ts b/lib/security-store-path.ts
index ff327535..69ea220f 100644
--- a/lib/security-store-path.ts
+++ b/lib/security-store-path.ts
@@ -11,7 +11,7 @@ const STORE_ENV = [
"OS_A2A_STORE", "OS_A2A_TASK_STORE", "OS_A2A_CREDENTIAL_STORE", "OS_A2A_INBOUND_TOKEN_STORE",
"OS_A2A_LOCAL_AUTH_STORE", "OS_LOCAL_AGENT_MESSAGE_STORE", "OS_LOCAL_AGENT_PRESENCE_STORE",
"OS_CONFIG_STORE", "OS_PREFS_PATH", "OS_SKILL_MEMORY_STORE", "MSO_SURFACE_APPS_FILE",
- "OS_MANAGED_DOMAINS_STORE",
+ "OS_MANAGED_DOMAINS_STORE", "OS_SHELL_APP_DOMAINS_STORE",
] as const;
const DIRECTORY_ENV = ["OS_TOOL_FORGE_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSIONS_DIR", "OS_PROJECT_AGENT_TASKS_DIR", "OS_AGENT_PROFILES_DIR"] as const;
const expand = (value: string) => path.resolve(expandOwnerStorePath(value));
diff --git a/lib/surfaces/app-domain-provision.test.ts b/lib/surfaces/app-domain-provision.test.ts
new file mode 100644
index 00000000..74944886
--- /dev/null
+++ b/lib/surfaces/app-domain-provision.test.ts
@@ -0,0 +1,208 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+// The provider layer is a real module import now, so the test drives it through
+// `vi.mock` instead of an injected seam. Only the three boundary functions are
+// replaced; the provisioning rules around them stay under test.
+const providers = vi.hoisted(() => ({
+ domainProviderCapabilities: vi.fn(),
+ ensureDomainRecords: vi.fn(),
+ inspectDomainRecords: vi.fn(),
+}));
+vi.mock("@/lib/infra/managed-domain-providers", () => providers);
+import { AppDomainError, ensureShellAppDomain, inspectShellAppDomain } from "./app-domain-provision";
+
+const app = {
+ id: "private-editor", title: "Editor", description: "", origin: "https://editor.example.net", startPath: "/",
+ renderer: "iframe", presentation: "inline", environment: "production", placements: ["shell"],
+ sessionUpstream: "http://127.0.0.1:9131",
+} as const;
+/** Default happy-path provider, then any per-test overrides on top. */
+const useProviders = (overrides: Partial<typeof providers> = {}) => {
+ providers.domainProviderCapabilities.mockReturnValue({ id: "cloudflare", aRecord: true, cname: true, txt: true, ingress: false });
+ providers.ensureDomainRecords.mockResolvedValue({ provider: "cloudflare", action: "created", records: [] });
+ providers.inspectDomainRecords.mockResolvedValue("unchanged");
+ Object.assign(providers, overrides);
+ return providers;
+};
+let directory: string;
+const store = () => path.join(directory, "shell-app-domains.json");
+
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-app-domain-"));
+ vi.stubEnv("OS_SHELL_APP_DOMAINS_STORE", store());
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));
+ vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "");
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302 })));
+ useProviders();
+});
+afterEach(async () => {
+ vi.resetAllMocks();
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ await fs.rm(directory, { recursive: true, force: true });
+});
+
+it("probes loopback before writing DNS and only reports ready after verification", async () => {
+ useProviders({
+ ensureDomainRecords: vi.fn(async () => {
+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
+ expect(await inspectShellAppDomain(app.id)).toMatchObject({ phase: "pending", localOrigin: "http://127.0.0.1:9131" });
+ return { provider: "cloudflare" as const, action: "created" as const, records: [] };
+ }),
+ inspectDomainRecords: vi.fn(async () => {
+ expect(await inspectShellAppDomain(app.id)).toMatchObject({ phase: "route-ready", dnsAction: "created" });
+ return "unchanged" as const;
+ }),
+ });
+ const record = await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ expect(record).toMatchObject({ appId: app.id, hostname: "editor.example.net", phase: "ready", provider: "cloudflare",
+ dnsAction: "created", routeAction: "unchanged", localOrigin: "http://127.0.0.1:9131", verifiedAt: expect.any(Number) });
+ expect(record.error).toBeUndefined();
+ expect(providers.ensureDomainRecords.mock.calls[0][0]).toEqual({
+ provider: "cloudflare", zoneName: "example.net", hostnames: ["editor.example.net"], target: { kind: "ipv4", value: "203.0.113.10" },
+ });
+ const stat = await fs.stat(store());
+ expect(stat.mode & 0o777).toBe(0o600);
+ expect(stat.uid).toBe(process.getuid?.());
+ expect(JSON.parse(await fs.readFile(store(), "utf8"))).toMatchObject({ version: 1, revision: 4 });
+});
+
+it("publishes no DNS and no route when the loopback origin is not serving the app", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 502 }));
+ const record = await ensureShellAppDomain(app.id, { provider: "hostinger", hostname: "editor.example.net", target: { kind: "cname", value: "origin.example.net" } });
+ expect(record.phase).toBe("blocked");
+ expect(record.error).toContain("does not serve shell app");
+ expect(record.verifiedAt).toBeUndefined();
+ expect(providers.ensureDomainRecords).not.toHaveBeenCalled();
+ expect(providers.inspectDomainRecords).not.toHaveBeenCalled();
+});
+
+it("resumes at the reached phase instead of repeating the DNS write or the probe", async () => {
+ providers.inspectDomainRecords.mockResolvedValue("created");
+ const interrupted = await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ expect(interrupted).toMatchObject({ phase: "blocked", dnsAction: "created", routeAction: "unchanged" });
+ expect(interrupted.error).toContain("DNS verification pending");
+
+ vi.mocked(fetch).mockClear();
+ providers.ensureDomainRecords.mockClear();
+ providers.inspectDomainRecords.mockReset();
+ providers.inspectDomainRecords.mockResolvedValue("unchanged");
+ const resumed = await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ expect(resumed.phase).toBe("ready");
+ expect(providers.ensureDomainRecords).not.toHaveBeenCalled();
+ expect(vi.mocked(fetch)).not.toHaveBeenCalled();
+ expect(providers.inspectDomainRecords).toHaveBeenCalledTimes(1);
+});
+
+it("never reports a blocked record ready on a later inspect", async () => {
+ providers.ensureDomainRecords.mockRejectedValue(new Error("Cloudflare HTTP 403"));
+ expect((await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } })).phase).toBe("blocked");
+ expect(await inspectShellAppDomain(app.id)).toMatchObject({ phase: "blocked", error: "Cloudflare HTTP 403" });
+});
+
+it("surfaces manual instructions for the custom provider and does not fabricate ready", async () => {
+ const record = await ensureShellAppDomain(app.id, { provider: "custom", hostname: "editor.example.net", target: { kind: "cname", value: "origin.example.net" } });
+ expect(record.phase).toBe("blocked");
+ expect(record.error).toContain("create CNAME editor.example.net -> origin.example.net");
+});
+
+it.each([
+ ["the cockpit hostname", "mso.example.com"],
+ ["a cockpit subdomain", "admin.mso.example.com"],
+ ["a cockpit parent", "com.example"],
+ ["an uppercase name", "Editor.example.net"],
+ ["an IPv4 literal", "203.0.113.10"],
+ ["a single label", "editor"],
+ ["a trailing dot", "editor.example.net."],
+])("rejects %s with a precise error and writes nothing", async (_label, hostname) => {
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname, target: { kind: "ipv4", value: "203.0.113.10" } }))
+ .rejects.toMatchObject({ code: "invalid_hostname", status: 400 });
+ expect(providers.ensureDomainRecords).not.toHaveBeenCalled();
+ expect(vi.mocked(fetch)).not.toHaveBeenCalled();
+ await expect(fs.stat(store())).rejects.toMatchObject({ code: "ENOENT" });
+});
+
+it("rejects a name inside OS_SESSION_COOKIE_DOMAIN instead of widening the session", async () => {
+ vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", ".apps.example.net");
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.apps.example.net", target: { kind: "ipv4", value: "203.0.113.10" } }))
+ .rejects.toThrow(/OS_SESSION_COOKIE_DOMAIN apps\.example\.net/);
+});
+
+it("refuses a hostname another shell app already owns", async () => {
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app, { ...app, id: "second-app", origin: "https://second.example.net" }]));
+ await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ await expect(ensureShellAppDomain("second-app", { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } }))
+ .rejects.toMatchObject({ code: "domain_conflict", status: 409 });
+ expect((await inspectShellAppDomain("second-app"))).toBeNull();
+});
+
+it("rejects unknown providers, invalid targets, foreign zones, and unknown apps before any probe", async () => {
+ const target = { kind: "ipv4" as const, value: "203.0.113.10" };
+ await expect(ensureShellAppDomain(app.id, { provider: "route53" as never, hostname: "editor.example.net", target })).rejects.toMatchObject({ code: "unsupported_provider" });
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "not-an-ip" } })).rejects.toMatchObject({ code: "invalid_target" });
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target, zoneName: "other.test" })).rejects.toThrow(/outside zone other\.test/);
+ await expect(ensureShellAppDomain("missing-app", { provider: "cloudflare", hostname: "editor.example.net", target })).rejects.toMatchObject({ code: "app_not_found", status: 404 });
+ expect(vi.mocked(fetch)).not.toHaveBeenCalled();
+ expect(providers.ensureDomainRecords).not.toHaveBeenCalled();
+});
+
+it("fails closed when the provider cannot write the required record type", async () => {
+ useProviders({ domainProviderCapabilities: vi.fn(() => ({ id: "dokploy" as const, aRecord: true, cname: false, txt: false, ingress: true })) });
+ await expect(ensureShellAppDomain(app.id, { provider: "dokploy", hostname: "editor.example.net", target: { kind: "cname", value: "origin.example.net" } }))
+ .rejects.toMatchObject({ code: "unsupported_provider" });
+});
+
+it("blocks with the provider's own missing-credential reason instead of a module error", async () => {
+ // The genuine `provider_unavailable` case: a configured provider with no stored
+ // credentials. The lib/infra module raises it; the record keeps the redacted text.
+ useProviders({ domainProviderCapabilities: vi.fn(() => ({ id: "cloudflare" as const, aRecord: true, cname: true, txt: true, ingress: false })),
+ ensureDomainRecords: vi.fn(async () => { throw new Error("Cloudflare is not configured; run `mso provider set cloudflare`"); }) });
+ const record = await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ expect(record).toMatchObject({ phase: "blocked" });
+ expect(record.error).toContain("Cloudflare is not configured");
+});
+
+it("refuses an app with no loopback origin and refuses to reset corrupted state", async () => {
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, origin: "https://editor.example.net", sessionUpstream: undefined }]));
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } }))
+ .rejects.toThrow(/no loopback origin/);
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));
+ await fs.writeFile(store(), "{broken", { mode: 0o600 });
+ await expect(ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } })).rejects.toThrow();
+ await expect(inspectShellAppDomain(app.id)).rejects.toThrow();
+ expect(await fs.readFile(store(), "utf8")).toBe("{broken");
+});
+
+it("refuses a group-readable state file without repairing it", async () => {
+ await ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } });
+ await fs.chmod(store(), 0o644);
+ await expect(inspectShellAppDomain(app.id)).rejects.toThrow(/unsafe shell-app domain state file/);
+ expect((await fs.stat(store())).mode & 0o777).toBe(0o644);
+});
+
+it("serializes concurrent provisioning of two apps without losing either record", async () => {
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app, { ...app, id: "second-app", origin: "https://second.example.net" }]));
+ let active = 0, peak = 0;
+ providers.inspectDomainRecords.mockImplementation(async () => {
+ active++; peak = Math.max(peak, active);
+ await new Promise(resolve => setTimeout(resolve, 15));
+ active--; return "unchanged" as const;
+ });
+ const results = await Promise.all([
+ ensureShellAppDomain(app.id, { provider: "cloudflare", hostname: "editor.example.net", target: { kind: "ipv4", value: "203.0.113.10" } }),
+ ensureShellAppDomain("second-app", { provider: "cloudflare", hostname: "second.example.net", target: { kind: "ipv4", value: "203.0.113.11" } }),
+ ]);
+ expect(results.map(row => row.phase)).toEqual(["ready", "ready"]);
+ expect(peak).toBe(1);
+ expect((await inspectShellAppDomain(app.id))?.hostname).toBe("editor.example.net");
+ expect((await inspectShellAppDomain("second-app"))?.hostname).toBe("second.example.net");
+});
+
+it("exposes an AppDomainError carrying the contract error code", async () => {
+ const error = new AppDomainError("domain_conflict", 409, "taken");
+ expect(error).toMatchObject({ name: "AppDomainError", code: "domain_conflict", status: 409, message: "taken" });
+});
diff --git a/lib/surfaces/app-domain-provision.ts b/lib/surfaces/app-domain-provision.ts
new file mode 100644
index 00000000..32b83b7a
--- /dev/null
+++ b/lib/surfaces/app-domain-provision.ts
@@ -0,0 +1,139 @@
+import { isIP } from "node:net";
+import { sessionCookieDomain } from "@/lib/auth/session-cookie";
+import { DOMAIN_PROVIDER_IDS, type AppDomainErrorCode, type AppDomainRecord, type AppDomainTarget, type EnsureShellAppDomainInput } from "@/lib/contracts/app-domain";
+import type { SurfaceApp } from "@/lib/contracts/surface-app";
+import { domainProviderCapabilities, ensureDomainRecords, inspectDomainRecords } from "@/lib/infra/managed-domain-providers";
+import { redactText } from "@/lib/security/redact-text";
+import { configuredSurfaceApps } from "./config";
+import { externalSurfaceSharesSession } from "./cookie-policy";
+import { isHostname, readAppDomainState, mutateAppDomainState, withAppDomainOperation } from "./app-domain-store";
+
+export type { AppDomainErrorCode, AppDomainPhase, AppDomainRecord, AppDomainTarget, DomainProviderId } from "@/lib/contracts/app-domain";
+export class AppDomainError extends Error {
+ constructor(readonly code: AppDomainErrorCode, readonly status: 400 | 404 | 409 | 503, message: string) { super(message); this.name = "AppDomainError"; }
+}
+const ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const LOOPBACK = ["127.0.0.1", "localhost", "[::1]"];
+
+function cockpitHostnames(): string[] {
+ const hosts = [process.env.OS_PUBLIC_ORIGIN, process.env.OS_MCP_UI_ORIGIN].flatMap(value => {
+ try { return value ? [new URL(value).hostname.replace(/\.$/, "").toLowerCase()] : []; } catch { return []; }
+ });
+ if (!hosts.length) throw new AppDomainError("provider_unavailable", 503, "MSO cockpit origin is not configured; refusing to publish a public name");
+ return hosts;
+}
+/** Rejects an unsafe name with a precise reason. Never substitutes a different hostname. */
+function assertHostname(value: unknown): string {
+ if (!isHostname(value)) throw new AppDomainError("invalid_hostname", 400, "invalid DNS hostname");
+ for (const cockpit of cockpitHostnames()) {
+ if (cockpit === value || value.endsWith(`.${cockpit}`) || cockpit.endsWith(`.${value}`)) {
+ throw new AppDomainError("invalid_hostname", 400, `${value} overlaps the MSO cockpit hostname ${cockpit}`);
+ }
+ }
+ const shared = sessionCookieDomain(new Request(`https://${value}/`, { headers: { host: value } }));
+ if (shared) throw new AppDomainError("invalid_hostname", 400, `${value} is inside OS_SESSION_COOKIE_DOMAIN ${shared} and would receive the MSO session cookie`);
+ if (externalSurfaceSharesSession(`https://${value}`, cockpitHostnames())) {
+ throw new AppDomainError("invalid_hostname", 400, `${value} shares the MSO session scope; use a separate host address`);
+ }
+ return value;
+}
+/** A zone apex legitimately CONTAINS the cockpit name, so only name syntax is checked here. */
+function zoneFor(hostname: string, supplied: unknown): string {
+ const labels = hostname.split(".");
+ if (supplied === undefined && labels.length < 3) throw new AppDomainError("invalid_hostname", 400, `cannot derive a DNS zone from ${hostname}; supply zoneName`);
+ const zoneName = supplied === undefined ? labels.slice(1).join(".") : supplied;
+ if (!isHostname(zoneName)) throw new AppDomainError("invalid_hostname", 400, "invalid DNS zone name");
+ if (hostname === zoneName || !hostname.endsWith(`.${zoneName}`)) throw new AppDomainError("invalid_hostname", 400, `${hostname} is outside zone ${String(zoneName)}`);
+ return zoneName;
+}
+function assertTarget(value: unknown): AppDomainTarget {
+ const target = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ if (target.kind === "ipv4" && typeof target.value === "string" && isIP(target.value) === 4) return { kind: "ipv4", value: target.value };
+ if (target.kind === "cname" && isHostname(target.value)) return { kind: "cname", value: target.value };
+ throw new AppDomainError("invalid_target", 400, "target must be a public IPv4 address or a DNS hostname");
+}
+/** The loopback origin that must answer before a public name exists. */
+function localOriginOf(app: SurfaceApp): string {
+ if (app.sessionUpstream) return app.sessionUpstream;
+ const origin = new URL(app.origin);
+ if (LOOPBACK.includes(origin.hostname) && origin.port) return origin.origin;
+ throw new AppDomainError("invalid_target", 400, `shell app ${app.id} has no loopback origin to probe; connect it with a loopback target before publishing a public name`);
+}
+async function shellApp(appId: string): Promise<SurfaceApp> {
+ if (!ID.test(appId)) throw new AppDomainError("app_not_found", 404, "unknown shell app");
+ const app = (await configuredSurfaceApps()).find(entry => entry.id === appId && entry.placements?.includes("shell"));
+ if (!app) throw new AppDomainError("app_not_found", 404, `no shell app ${appId}`);
+ return app;
+}
+async function probeLocal(origin: string, hostname: string, appId: string): Promise<void> {
+ let response: Response;
+ try {
+ response = await fetch(new URL("/", origin), { headers: { host: hostname }, redirect: "manual", cache: "no-store", signal: AbortSignal.timeout(8_000) });
+ } catch (error) {
+ throw new Error(`local origin ${origin} is not reachable for ${hostname}: ${error instanceof Error ? error.message : "request failed"}`);
+ }
+ await response.body?.cancel();
+ // 401/403 still prove the route exists: MSO's proxy answers unauthenticated requests itself.
+ const status = response.status;
+ if (!((status >= 200 && status < 400) || status === 401 || status === 403)) {
+ throw new Error(`local origin ${origin} does not serve shell app ${appId} at ${hostname} (HTTP ${status}); repair local routing before publishing DNS`);
+ }
+}
+
+/**
+ * Order is load-bearing: probe loopback -> write DNS -> confirm route -> verify. Every phase
+ * transition is persisted before the next step, so a failed run resumes where it stopped
+ * instead of restarting from `pending`, and a public name never points at an unready service.
+ */
+export async function ensureShellAppDomain(appId: string, input: EnsureShellAppDomainInput): Promise<AppDomainRecord> {
+ const hostname = assertHostname(input.hostname), target = assertTarget(input.target);
+ if (!(DOMAIN_PROVIDER_IDS as readonly string[]).includes(String(input.provider))) throw new AppDomainError("unsupported_provider", 400, `unknown domain provider: ${String(input.provider)}`);
+ const app = await shellApp(appId), localOrigin = localOriginOf(app), zoneName = zoneFor(hostname, input.zoneName);
+ const capability = domainProviderCapabilities(input.provider);
+ if (input.provider !== "custom") {
+ if (target.kind === "ipv4" && !capability.aRecord) throw new AppDomainError("unsupported_provider", 400, `${input.provider} cannot write A records`);
+ if (target.kind === "cname" && !capability.cname) throw new AppDomainError("unsupported_provider", 400, `${input.provider} cannot write CNAME records`);
+ }
+ const request = { provider: input.provider, zoneName, hostnames: [hostname], target };
+
+ return withAppDomainOperation(async () => {
+ const apps = (await readAppDomainState()).apps, previous = apps[appId];
+ const owner = Object.values(apps).find(row => row.hostname === hostname && row.appId !== appId);
+ if (owner) throw new AppDomainError("domain_conflict", 409, `${hostname} is already assigned to shell app ${owner.appId}`);
+ // Same name and provider is a resume, not a rebind; a different name starts over.
+ const resuming = previous?.hostname === hostname && previous.provider === input.provider;
+ if (resuming && previous.phase === "ready") return { ...previous };
+ const current: AppDomainRecord = resuming ? { ...previous } : { appId, hostname, phase: "pending", provider: input.provider, updatedAt: Date.now() };
+ delete current.error; delete current.verifiedAt;
+ const persist = async (patch: Partial<AppDomainRecord>) => {
+ Object.assign(current, patch, { updatedAt: Date.now() });
+ await mutateAppDomainState(next => { next.apps[appId] = structuredClone(current); });
+ };
+ try {
+ // A persisted dnsAction proves the probe and the DNS write already completed; repeating
+ // them on resume would re-publish a record and re-probe a service that already answered.
+ if (!previous?.dnsAction || !resuming) {
+ await persist({ phase: "pending", localOrigin });
+ await probeLocal(localOrigin, hostname, appId);
+ const dns = await ensureDomainRecords(request);
+ await persist({ phase: "dns-ready", dnsAction: dns.action, localOrigin });
+ if (input.provider === "custom") {
+ throw new Error(`operator-maintained DNS: create ${target.kind === "ipv4" ? "A" : "CNAME"} ${hostname} -> ${target.value}, then switch to a writable provider so MSO can verify it`);
+ }
+ }
+ // The loopback proxy route was proved by the probe above; only dokploy adds its own ingress.
+ await persist({ phase: "route-ready", routeAction: current.routeAction ?? "unchanged", localOrigin });
+ const verified = await inspectDomainRecords(request);
+ if (verified !== "unchanged") throw new Error(`DNS verification pending for ${hostname}: provider reports ${verified}; retry once propagation completes`);
+ await persist({ phase: "ready", verifiedAt: Date.now() });
+ } catch (error) {
+ await persist({ phase: "blocked", error: redactText(error instanceof Error ? error.message : "domain provisioning failed", 512) });
+ }
+ return { ...current };
+ });
+}
+
+export async function inspectShellAppDomain(appId: string): Promise<AppDomainRecord | null> {
+ if (!ID.test(appId)) throw new AppDomainError("app_not_found", 404, "unknown shell app");
+ return (await readAppDomainState()).apps[appId] ?? null;
+}
diff --git a/lib/surfaces/app-domain-store.test.ts b/lib/surfaces/app-domain-store.test.ts
new file mode 100644
index 00000000..276b2b7f
--- /dev/null
+++ b/lib/surfaces/app-domain-store.test.ts
@@ -0,0 +1,69 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { appDomainStorePath, isHostname, mutateAppDomainState, parseAppDomainState, readAppDomainState, withAppDomainOperation } from "./app-domain-store";
+
+let directory: string;
+const file = () => path.join(directory, "shell-app-domains.json");
+const save = () => mutateAppDomainState(next => {
+ next.apps.editor = { appId: "editor", hostname: "editor.example.net", phase: "dns-ready", provider: "cloudflare", updatedAt: 1 };
+});
+
+beforeEach(async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), "mso-app-domain-store-"));
+ vi.stubEnv("OS_SHELL_APP_DOMAINS_STORE", file());
+});
+afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(directory, { recursive: true, force: true }); });
+
+it("starts empty, then writes a 0600 owner file under the owner root", async () => {
+ expect(appDomainStorePath()).toBe(file());
+ expect(await readAppDomainState()).toEqual({ version: 1, revision: 0, apps: {} });
+ await save();
+ const state = await readAppDomainState(), stat = await fs.stat(file());
+ expect(state).toMatchObject({ version: 1, revision: 1, apps: { editor: { phase: "dns-ready" } } });
+ expect(stat.mode & 0o777).toBe(0o600);
+ expect(stat.uid).toBe(process.getuid?.());
+});
+
+it("refuses group-readable state and a symlinked state file without repairing either", async () => {
+ await save();
+ await fs.chmod(file(), 0o644);
+ await expect(readAppDomainState()).rejects.toThrow(/unsafe/);
+ expect((await fs.stat(file())).mode & 0o777).toBe(0o644);
+ const target = path.join(directory, "unrelated.txt");
+ await fs.writeFile(target, "untouched", { mode: 0o600 });
+ await fs.unlink(file());
+ await fs.symlink(target, file());
+ await expect(readAppDomainState()).rejects.toThrow();
+ await expect(save()).rejects.toThrow();
+ expect(await fs.readFile(target, "utf8")).toBe("untouched");
+});
+
+it("rejects malformed snapshots instead of resetting them", async () => {
+ await fs.writeFile(file(), JSON.stringify({ version: 1, revision: 0, apps: { editor: { appId: "other" } } }), { mode: 0o600 });
+ await expect(readAppDomainState()).rejects.toThrow(/invalid shell-app domain state/);
+ await expect(withAppDomainOperation(save)).rejects.toThrow();
+});
+
+it("validates the documented record shape and rejects unknown fields", () => {
+ const row = { appId: "editor", hostname: "editor.example.net", phase: "ready", provider: null, updatedAt: 1 };
+ expect(parseAppDomainState({ version: 1, revision: 0, apps: { editor: row } }).apps.editor).toEqual(row);
+ for (const broken of [{ ...row, phase: "live" }, { ...row, provider: "route53" }, { ...row, hostname: "Editor.example.net" },
+ { ...row, error: "x".repeat(513) }, { ...row, credential: "no" }, { ...row, updatedAt: 1.5 }]) {
+ expect(() => parseAppDomainState({ version: 1, revision: 0, apps: { editor: broken } })).toThrow();
+ }
+ expect(isHostname("editor.example.net")).toBe(true);
+ for (const bad of ["editor", "editor.example.net.", "203.0.113.10", "", "editor..example.net", "ed itor.example.net"]) expect(isHostname(bad)).toBe(false);
+});
+
+it("serializes concurrent operations", async () => {
+ let active = 0, peak = 0;
+ await Promise.all([1, 2, 3].map(() => withAppDomainOperation(async () => {
+ peak = Math.max(peak, ++active);
+ await new Promise(resolve => setTimeout(resolve, 5));
+ active--;
+ })));
+ expect(peak).toBe(1);
+ await expect(withAppDomainOperation(async () => { throw new Error("provider failed"); })).rejects.toThrow("provider failed");
+});
diff --git a/lib/surfaces/app-domain-store.ts b/lib/surfaces/app-domain-store.ts
new file mode 100644
index 00000000..806919aa
--- /dev/null
+++ b/lib/surfaces/app-domain-store.ts
@@ -0,0 +1,90 @@
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { isIP } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import type { AppDomainRecord } from "@/lib/contracts/app-domain";
+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+
+/** Owner-only store beside `managed-domains.json`: 0600 file, 0700 parent, O_NOFOLLOW, uid-checked. */
+const MAX_BYTES = 64 * 1024;
+const PHASES = new Set(["pending", "dns-ready", "route-ready", "ready", "blocked"]);
+const PROVIDERS = new Set(["cloudflare", "hostinger", "dokploy", "custom"]);
+const FIELDS = ["appId", "hostname", "phase", "provider", "dnsAction", "routeAction", "error", "localOrigin", "verifiedAt", "updatedAt"];
+const DNS_ACTIONS = ["created", "updated", "unchanged"], ROUTE_ACTIONS = ["created", "unchanged"];
+const ID = /^[a-z0-9][a-z0-9-]{0,63}$/, LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
+export type AppDomainState = { version: 1; revision: number; apps: Record<string, AppDomainRecord> };
+
+export const appDomainStorePath = () => expandOwnerStorePath(process.env.OS_SHELL_APP_DOMAINS_STORE
+ ?? path.join(os.homedir(), ".mso", "private", "shell-app-domains.json"));
+const empty = (): AppDomainState => ({ version: 1, revision: 0, apps: {} });
+
+export function isHostname(value: unknown): value is string {
+ return typeof value === "string" && value.length <= 253 && isIP(value) === 0 && value === value.toLowerCase()
+ && !value.endsWith(".") && value.includes(".") && value.split(".").every(label => LABEL.test(label));
+}
+function asRecord(value: unknown): AppDomainRecord {
+ const row = (value && typeof value === "object" && !Array.isArray(value) ? value : null) as Record<string, unknown> | null;
+ if (!row || Object.keys(row).some(key => !FIELDS.includes(key)) || typeof row.appId !== "string" || !ID.test(row.appId)
+ || !isHostname(row.hostname) || !PHASES.has(String(row.phase)) || !Number.isSafeInteger(row.updatedAt)
+ || (row.provider !== null && !PROVIDERS.has(String(row.provider)))) throw new Error("invalid shell-app domain state");
+ if (row.dnsAction !== undefined && !DNS_ACTIONS.includes(String(row.dnsAction))) throw new Error("invalid shell-app domain DNS action");
+ if (row.routeAction !== undefined && !ROUTE_ACTIONS.includes(String(row.routeAction))) throw new Error("invalid shell-app domain route action");
+ if (row.error !== undefined && (typeof row.error !== "string" || row.error.length > 512)) throw new Error("invalid shell-app domain diagnostic");
+ if (row.localOrigin !== undefined && (typeof row.localOrigin !== "string" || row.localOrigin.length > 253)) throw new Error("invalid shell-app domain loopback origin");
+ if (row.verifiedAt !== undefined && !Number.isSafeInteger(row.verifiedAt)) throw new Error("invalid shell-app domain verification timestamp");
+ return row as AppDomainRecord;
+}
+export function parseAppDomainState(value: unknown): AppDomainState {
+ const raw = (value && typeof value === "object" && !Array.isArray(value) ? value : null) as Record<string, unknown> | null;
+ if (!raw || Object.keys(raw).some(key => !["version", "revision", "apps"].includes(key)) || raw.version !== 1
+ || !Number.isSafeInteger(raw.revision) || Number(raw.revision) < 0
+ || !raw.apps || typeof raw.apps !== "object" || Array.isArray(raw.apps)) throw new Error("invalid shell-app domain state");
+ const apps: Record<string, AppDomainRecord> = {};
+ for (const [id, row] of Object.entries(raw.apps as Record<string, unknown>)) {
+ const parsed = asRecord(row);
+ if (parsed.appId !== id) throw new Error("invalid shell-app domain state");
+ apps[id] = parsed;
+ }
+ return { version: 1, revision: Number(raw.revision), apps };
+}
+async function writeState(file: string, state: AppDomainState): Promise<void> {
+ const text = JSON.stringify(parseAppDomainState(state), null, 2) + "\n";
+ if (Buffer.byteLength(text) > MAX_BYTES) throw new Error("shell-app domain state capacity exceeded");
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temporary, "wx", 0o600);
+ try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
+ await fs.rename(temporary, file);
+ } finally { await fs.unlink(temporary).catch(() => undefined); }
+}
+/** Never repairs or replaces an unsafe object at the state filename. */
+export async function readAppDomainState(): Promise<AppDomainState> {
+ const pinned = await pinSecurityStorePath(appDomainStorePath());
+ let handle;
+ try {
+ handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error("unsafe shell-app domain state file");
+ return parseAppDomainState(JSON.parse(await handle.readFile("utf8")));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();
+ throw error;
+ } finally { await handle?.close(); await pinned.directory.close(); }
+}
+export function mutateAppDomainState(change: (state: AppDomainState) => void): Promise<void> {
+ return withSecurityStoreLock(appDomainStorePath(), async () => {
+ const pinned = await pinSecurityStorePath(appDomainStorePath());
+ try {
+ const next = structuredClone(await readAppDomainState());
+ change(next); next.revision++;
+ await writeState(pinned.file, next);
+ await pinned.directory.sync();
+ } finally { await pinned.directory.close(); }
+ });
+}
+/** Serializes whole provisioning runs so two apps never interleave their phases. */
+export const withAppDomainOperation = <T>(run: () => Promise<T>): Promise<T> =>
+ withSecurityStoreLock(`${appDomainStorePath()}.operation`, run, { busyTimeoutMs: 5_000 });
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index c66da372..387d6fe8 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -41,6 +41,8 @@ case "$cmd" in
catalog) jget "/api/v1/app-catalog" ;;
shell-list) jget "/api/v1/shell-apps" ;;
shell-save) shell_input="${1:?JSON or @file required}"; if [ "${shell_input:0:1}" = "@" ]; then shell_input=$(cat -- "${shell_input:1}"); fi; jpost "/api/v1/shell-apps" "$shell_input" ;;
+ shell-domain) jget "/api/v1/shell-apps/$(enc "${1:?id}")/domain" ;;
+ shell-domain-save) shell_input="${2:?JSON or @file required}"; if [ "${shell_input:0:1}" = "@" ]; then shell_input=$(cat -- "${shell_input:1}"); fi; jpost "/api/v1/shell-apps/$(enc "${1:?id}")/domain" "$shell_input" ;;
list) jget "/api/v1/managed-apps" ;;
show) jget "/api/v1/managed-apps/$(enc "${1:?id}")" ;;
logs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/logs" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 7bf88519..ff07236f 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -32,7 +32,7 @@ U_agent_groups="agent-groups list|show <id>|create --input <JSON|@file>|save <id
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
-U_mapp="mapp enable <id> [install-key=value...]|start|stop|restart <id>|catalog|shell-list|shell-save <JSON|@file>|list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
+U_mapp="mapp enable <id> [install-key=value...]|start|stop|restart <id>|catalog|shell-list|shell-save <JSON|@file>|shell-domain <id>|shell-domain-save <id> <JSON|@file>|list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
U_service="service status|start|stop|restart|logs [n]"
diff --git a/scripts/e2e/shell-apps.mjs b/scripts/e2e/shell-apps.mjs
index cb544057..75b4dcc6 100644
--- a/scripts/e2e/shell-apps.mjs
+++ b/scripts/e2e/shell-apps.mjs
@@ -35,7 +35,16 @@ try {
await page.mouse.wheel(0, 1000);
await expect(form.getByRole("button", { name: "Connect app", exact: true })).toBeInViewport({ ratio: 1 });
await form.getByRole("button", { name: "Connect app", exact: true }).click();
- await expect(form).toHaveCount(0);
+ // A connected app with no name is reachable only by an address, so the flow
+ // offers the domain step instead of closing. The drawer closes on its own
+ // Close button (or a dismiss), never automatically.
+ const domain = page.getByRole("dialog");
+ await expect(domain.getByRole("heading", { name: "Domain for Fixture tool", exact: true })).toBeVisible();
+ await expect(domain.getByLabel("Hostname", { exact: true })).toHaveValue("tool.example.test");
+ await expect(domain.getByText("Open directly by IP and port instead", { exact: true })).toBeVisible();
+ await expect(domain.getByText("An HTTP address is never loaded inside MSO.")).toBeVisible();
+ await domain.locator("form").getByRole("button", { name: "Close", exact: true }).click();
+ await expect(domain).toHaveCount(0);
const card = page.getByRole("article").filter({ has: page.getByRole("heading", { name: "Fixture tool", exact: true }) });
await expect(card).toBeVisible();
await card.getByRole("button", { name: "Open", exact: true }).click();
@@ -56,7 +65,11 @@ try {
await card.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("dialog").getByLabel("App URL", { exact: true }).fill("http://192.0.2.10:5678/");
await page.getByRole("button", { name: "Save changes", exact: true }).click();
- await expect(page.getByRole("dialog")).toHaveCount(0);
+ // A save also lands on the domain step; dismiss it, the edit is already stored.
+ const savedDomain = page.getByRole("dialog");
+ await expect(savedDomain.getByRole("heading", { name: "Domain for Fixture tool", exact: true })).toBeVisible();
+ await savedDomain.locator("form").getByRole("button", { name: "Close", exact: true }).click();
+ await expect(savedDomain).toHaveCount(0);
await card.getByRole("button", { name: "Open", exact: true }).click();
await expect(page.getByRole("link", { name: "Open Fixture tool", exact: true })).toHaveAttribute("href", "http://192.0.2.10:5678/");
await expect(iframe).toHaveCount(0);
@@ -87,7 +100,13 @@ try {
await form.locator("form").hover(); await page.mouse.wheel(0, 1200);
await expect(form.getByRole("button", { name: "Connect app", exact: true })).toBeInViewport({ ratio: 1 });
await form.getByRole("button", { name: "Connect app", exact: true }).click();
- await expect(form).toHaveCount(0);
+ const importedDomain = page.getByRole("dialog");
+ await expect(importedDomain.getByRole("heading", { name: "Domain for Imported tool", exact: true })).toBeVisible();
+ await expect(importedDomain.getByLabel("Hostname", { exact: true })).toHaveValue("tool.example.test");
+ await expect(importedDomain.getByText("Open directly by IP and port instead", { exact: true })).toBeVisible();
+ await expect(importedDomain.getByText("An HTTP address is never loaded inside MSO.")).toBeVisible();
+ await importedDomain.locator("form").getByRole("button", { name: "Close", exact: true }).click();
+ await expect(importedDomain).toHaveCount(0);
const imported = page.getByRole("article").filter({ has: page.getByRole("heading", { name: "Imported tool", exact: true }) });
await expect(imported).toContainText("Fixture developer (self-declared)");
await page.reload();