Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

feat: tiered app-serving defaults — /d/ path serving with no config, one-var subdomain upgrade

Josh Francea6b8a2db3840
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index 3a3453774..ae6585065 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -170,8 +170,16 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
{
name: "AWS_DEPLOY_GATE_SECRET",
service: "core",
- required: { when: { kind: "env-present", service: "core", name: "AWS_DEPLOY_APPS_DOMAIN" } },
- description: "HMAC key protecting public AWS deployment-app URLs.",
+ required: {
+ when: {
+ kind: "any",
+ conditions: [
+ { kind: "env-present", service: "core", name: "AWS_DEPLOY_APPS_DOMAIN" },
+ { kind: "env-present", service: "core", name: "DEPLOY_APPS_DOMAIN" },
+ ],
+ },
+ },
+ description: "HMAC key protecting public deployment-app URLs on the apps domain.",
generate: MINT_LOCALLY,
},
{
diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml
index 87cf7292f..b8c56dfa2 100644
--- a/deploy/helm/values.yaml
+++ b/deploy/helm/values.yaml
@@ -33,6 +33,7 @@ secretEnv:
PORTER_DEPLOY_CLUSTER_ID: ""
PORTER_SANDBOX_IMAGE: "ghcr.io/porter-dev/qm-sandbox:latest"
PORTER_DEPLOY_RUNNER_IMAGE: "ghcr.io/porter-dev/qm-app-runner:latest"
+ DEPLOY_APPS_DOMAIN: ""
PORTER_DEPLOY_APPS_DOMAIN: ""
AUTH_ALLOWED_EMAILS: ""
AUTH_CLIENT_ID: ""
diff --git a/deploy/stacks/acme/.env.example b/deploy/stacks/acme/.env.example
index fe1c0c709..23f380973 100644
--- a/deploy/stacks/acme/.env.example
+++ b/deploy/stacks/acme/.env.example
@@ -63,8 +63,8 @@ SKILL_SIGNING_SECRET=
# DATABASE_CA_CERT=
-# HMAC key protecting public AWS deployment-app URLs. (core)
-# Needed when env.core.AWS_DEPLOY_APPS_DOMAIN is set.
+# HMAC key protecting public deployment-app URLs on the apps domain. (core)
+# Needed when env.core.AWS_DEPLOY_APPS_DOMAIN is set or env.core.DEPLOY_APPS_DOMAIN is set.
# Generate with: openssl rand -hex 32
# AWS_DEPLOY_GATE_SECRET=
diff --git a/docs/porter.md b/docs/porter.md
index 354d38dae..2073d7303 100644
--- a/docs/porter.md
+++ b/docs/porter.md
@@ -98,6 +98,17 @@ principal with `AmazonEKSClusterAdminPolicy`, then `aws eks update-kubeconfig`.
## Giving published apps stable hostnames
+App serving is tiered so the zero-config path works first. With nothing set, every
+published app is reachable signed-in at `/d/<app>/` on the portal, private to its owner
+and whoever the deployment is shared with; proxied HTML is served under a sandbox CSP so
+app code cannot act on the portal's origin. Setting `DEPLOY_APPS_DOMAIN` to a wildcard
+domain you control (e.g. `apps.example.com`, with `*.apps.example.com` pointed at the
+instance) upgrades every app to its own origin — `https://<app>.apps.example.com/` — with
+portal single sign-on, the request-access flow, and live editing; the portal derives its
+cookie and returnTo settings from it, and boot probes the wildcard record and prints the
+exact DNS record to add when it is missing. The per-provider variables below remain as
+explicit overrides.
+
Published apps get their address from the cluster, not from qm. Declare the sandbox load
balancer with a root domain at cluster creation and **Porter names every published app
itself**: `<app>.<root domain>`, served on a wildcard Let's Encrypt certificate that Porter
@@ -233,7 +244,10 @@ PORTER_DEPLOY_APPS_DOMAIN=apps.example.com # optional; overrides the assigned
Set it only to choose the name yourself; the wildcard record it relies on is the one Porter
already created. Deployments are **private** by default, matching the other providers;
-`PORTER_DEPLOY_VISIBILITY=public` opts a deployment's domain into public ingress.
+`PORTER_DEPLOY_VISIBILITY=public` opts a deployment's domain into public ingress. Note the
+cluster-assigned hostname is Porter ingress only — qm's sign-on gate, request-access flow,
+and live editing need `DEPLOY_APPS_DOMAIN` (a domain you control, not a shared platform
+domain like `onporter.run`).
## Forcing sandbox egress through the proxy
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index 39c3ccbad..889db26b8 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -98,10 +98,16 @@ or every visitor (and every crawler that accepts HTML) shares the socket
address's one bucket.
Because playground authority must never leave this origin, the portal refuses
-to boot with `PORTAL_PLAYGROUND` alongside `PORTAL_COOKIE_DOMAIN`,
-`PORTAL_APPS_DOMAIN`, or `PORTAL_DEPLOYMENTS_ENABLED` — a domain-wide cookie or
-the deployment proxy would hand anonymous sessions to surfaces that never see
-the `anon` flag. Anonymous sessions are also refused the `/connect/*` and
+to boot with `PORTAL_PLAYGROUND` alongside `PORTAL_COOKIE_DOMAIN`, an apps
+domain (`PORTAL_APPS_DOMAIN` / `DEPLOY_APPS_DOMAIN`), or an explicit
+`PORTAL_DEPLOYMENTS_ENABLED=1` — a domain-wide cookie or the deployment proxy
+would hand anonymous sessions to surfaces that never see the `anon` flag. The
+deployment proxy (`/d/<app>/`), on by default for signed-in portals, turns
+itself off under the playground, and anonymous sessions are refused it at
+request time too. Outside the playground, `PORTAL_APPS_DOMAIN` defaults to
+`DEPLOY_APPS_DOMAIN` and `PORTAL_COOKIE_DOMAIN` to the parent domain the portal
+host shares with the apps domain, so one core-side variable configures both
+processes. Anonymous sessions are also refused the `/connect/*` and
`/drop/*` flows, so a visitor can't attach real OAuth tokens or dropped secrets
to a throwaway principal that a cleared cookie orphans.
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index b71eaf813..e7f9e19f7 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -56,8 +56,10 @@ const SESSION_SECRET = process.env.PORTAL_SESSION_SECRET;
const SESSION_TTL_S = Number(process.env.PORTAL_SESSION_TTL_S ?? 28800);
const SESSION_MAX_TTL_S = Number(process.env.PORTAL_SESSION_MAX_TTL_S ?? Math.max(86400, SESSION_TTL_S));
const SESSION_RENEW_AFTER_S = Math.floor(SESSION_TTL_S / 2);
-const COOKIE_DOMAIN = process.env.PORTAL_COOKIE_DOMAIN || undefined;
-const APPS_DOMAIN = process.env.PORTAL_APPS_DOMAIN || undefined;
+const APPS_DOMAIN = process.env.PORTAL_APPS_DOMAIN || process.env.DEPLOY_APPS_DOMAIN || undefined;
+const COOKIE_DOMAIN =
+ process.env.PORTAL_COOKIE_DOMAIN ||
+ (APPS_DOMAIN ? commonParentDomain(hostOf(process.env.PORTAL_PUBLIC_URL ?? ""), APPS_DOMAIN) : undefined);
const IS_PROD = process.env.NODE_ENV === "production";
const SECURE_COOKIES = PUBLIC_URL.startsWith("https://");
const ORIGIN = (() => {
@@ -70,8 +72,10 @@ const ORIGIN = (() => {
const LOCAL_AUTH_BYPASS_REQUESTED = process.env.PORTAL_LOCAL_AUTH_BYPASS === "1";
const LOCAL_AUTH_BYPASS = LOCAL_AUTH_BYPASS_REQUESTED && !IS_PROD && isLocalPortalUrl(PUBLIC_URL);
const LOCAL_AUTH_PRINCIPAL = process.env.PORTAL_DEV_PRINCIPAL || process.env.USER || "dev-admin";
-const DEPLOYMENTS_ENABLED = process.env.PORTAL_DEPLOYMENTS_ENABLED === "1";
const PLAYGROUND = process.env.PORTAL_PLAYGROUND === "1";
+const DEPLOYMENTS_ENABLED = process.env.PORTAL_DEPLOYMENTS_ENABLED
+ ? process.env.PORTAL_DEPLOYMENTS_ENABLED === "1"
+ : !PLAYGROUND;
function playgroundIntEnv(name: string, fallback: number): number {
const raw = process.env[name]?.trim();
if (!raw) return fallback;
@@ -299,6 +303,15 @@ function hostOf(raw: string): string {
}
}
+export function commonParentDomain(a: string, b: string): string | undefined {
+ const as = a.toLowerCase().split(".").filter(Boolean);
+ const bs = b.toLowerCase().split(".").filter(Boolean);
+ let n = 0;
+ while (n < as.length && n < bs.length && as[as.length - 1 - n] === bs[bs.length - 1 - n]) n++;
+ if (n < 2) return undefined;
+ return as.slice(as.length - n).join(".");
+}
+
export function hostIsWithinDomain(host: string, domain: string): boolean {
const h = host.toLowerCase();
const d = domain.toLowerCase().replace(/^\./, "");
@@ -1055,6 +1068,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
}
if (isDeployment) {
+ if (session.anon) return json(res, 403, { error: "forbidden", message: "sign in to view deployed apps" });
const rest = pathname.slice(`/${seg}/`.length);
const slash = rest.indexOf("/");
const id = decodeURIComponent(slash === -1 ? rest : rest.slice(0, slash));
@@ -1232,7 +1246,7 @@ export function bootChecks(): void {
}
if (COOKIE_DOMAIN || APPS_DOMAIN) {
problems.push(
- "PORTAL_PLAYGROUND requires PORTAL_COOKIE_DOMAIN and PORTAL_APPS_DOMAIN unset — a domain-wide cookie would carry anonymous sessions to app subdomains, which never see the anon flag",
+ "PORTAL_PLAYGROUND requires PORTAL_COOKIE_DOMAIN and the apps domain (PORTAL_APPS_DOMAIN / DEPLOY_APPS_DOMAIN) unset — a domain-wide cookie would carry anonymous sessions to app subdomains, which never see the anon flag",
);
}
if (DEPLOYMENTS_ENABLED) {
@@ -1243,7 +1257,7 @@ export function bootChecks(): void {
}
if (APPS_DOMAIN && !COOKIE_DOMAIN) {
problems.push(
- "PORTAL_APPS_DOMAIN requires PORTAL_COOKIE_DOMAIN (app returnTo without a domain-wide session cookie loops sign-in forever)",
+ `the apps domain (${APPS_DOMAIN}) shares no parent domain with the portal host, so no session cookie can cover both — set PORTAL_COOKIE_DOMAIN explicitly or serve the portal and apps under one parent domain (app returnTo without a domain-wide session cookie loops sign-in forever)`,
);
}
if (COOKIE_DOMAIN && !hostIsWithinDomain(hostOf(PUBLIC_URL), COOKIE_DOMAIN)) {
diff --git a/plugins/portal/test/apps-domain-defaults.test.ts b/plugins/portal/test/apps-domain-defaults.test.ts
new file mode 100644
index 000000000..6bdaace83
--- /dev/null
+++ b/plugins/portal/test/apps-domain-defaults.test.ts
@@ -0,0 +1,52 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { createServer, type IncomingMessage } from "node:http";
+import type { AddressInfo } from "node:net";
+
+const upstream = createServer((req: IncomingMessage, res) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ url: req.url }));
+});
+await new Promise<void>((r) => upstream.listen(0, r));
+const upstreamUrl = `http://localhost:${(upstream.address() as AddressInfo).port}`;
+
+process.env.PORTAL_PUBLIC_URL = "https://qm.example.com";
+process.env.PORTAL_SESSION_SECRET = "apps-domain-defaults-portal-secret";
+process.env.CORE_SIGNING_SECRET = "apps-domain-defaults-core-secret";
+process.env.WEB_UI_UPSTREAM = upstreamUrl;
+process.env.ADMIN_UPSTREAM = upstreamUrl;
+process.env.CORE_API_URL = upstreamUrl;
+delete process.env.PORTAL_APPS_DOMAIN;
+delete process.env.PORTAL_COOKIE_DOMAIN;
+process.env.DEPLOY_APPS_DOMAIN = "apps.qm.example.com";
+
+const { commonParentDomain, bootChecks } = await import("../src/index.ts");
+
+test.after(() => {
+ upstream.close();
+});
+
+test("commonParentDomain finds the deepest shared dot-suffix, never a bare TLD", () => {
+ assert.equal(commonParentDomain("qm.example.com", "apps.qm.example.com"), "qm.example.com");
+ assert.equal(commonParentDomain("portal.example.com", "apps.example.com"), "example.com");
+ assert.equal(commonParentDomain("example.com", "apps.example.com"), "example.com");
+ assert.equal(commonParentDomain("a.example.com", "b.other.net"), undefined);
+ assert.equal(commonParentDomain("a.example.com", "b.acme.com"), undefined, "a bare TLD is not a cookie domain");
+ assert.equal(commonParentDomain("", "apps.example.com"), undefined);
+});
+
+test("DEPLOY_APPS_DOMAIN alone yields a working portal apps setup — cookie domain derived, boot clean", () => {
+ assert.doesNotThrow(() => bootChecks());
+});
+
+test("an apps domain that shares no parent with the portal host refuses to boot with a cookie-domain explanation", () => {
+ const command = "import('./src/index.ts').then(m => m.bootChecks())";
+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", command], {
+ cwd: process.cwd(),
+ env: { ...process.env, DEPLOY_APPS_DOMAIN: "apps.unrelated.net" },
+ encoding: "utf8",
+ });
+ assert.notEqual(r.status, 0);
+ assert.match(r.stderr, /shares no parent domain/);
+});
diff --git a/plugins/portal/test/playground.test.ts b/plugins/portal/test/playground.test.ts
index cd3a4ae90..95fd7d72f 100644
--- a/plugins/portal/test/playground.test.ts
+++ b/plugins/portal/test/playground.test.ts
@@ -159,6 +159,7 @@ test("boot refuses playground configurations that leak or brick", () => {
};
delete baseEnv.PORTAL_COOKIE_DOMAIN;
delete baseEnv.PORTAL_APPS_DOMAIN;
+ delete baseEnv.DEPLOY_APPS_DOMAIN;
delete baseEnv.PORTAL_DEPLOYMENTS_ENABLED;
delete baseEnv.PORTAL_PLAYGROUND_MINTS_PER_IP;
delete baseEnv.PORTAL_PLAYGROUND_MINT_WINDOW_S;
@@ -171,7 +172,11 @@ test("boot refuses playground configurations that leak or brick", () => {
[{ PORTAL_PLAYGROUND_MINTS_PER_IP: "lots" }, /between 1 and 64/],
[{ PORTAL_PLAYGROUND_MINT_WINDOW_S: "30" }, /between 60 and 86400/],
[{ PORTAL_PLAYGROUND_MINT_WINDOW_S: "172800" }, /between 60 and 86400/],
- [{ PORTAL_COOKIE_DOMAIN: "qm.example.com" }, /PORTAL_COOKIE_DOMAIN and PORTAL_APPS_DOMAIN unset/],
+ [{ PORTAL_COOKIE_DOMAIN: "qm.example.com" }, /the apps domain \(PORTAL_APPS_DOMAIN \/ DEPLOY_APPS_DOMAIN\) unset/],
+ [
+ { DEPLOY_APPS_DOMAIN: "apps.qm.example.com" },
+ /the apps domain \(PORTAL_APPS_DOMAIN \/ DEPLOY_APPS_DOMAIN\) unset/,
+ ],
[{ PORTAL_DEPLOYMENTS_ENABLED: "1" }, /PORTAL_DEPLOYMENTS_ENABLED unset/],
];
for (const [extra, pattern] of bad) {
diff --git a/plugins/portal/test/router.test.ts b/plugins/portal/test/router.test.ts
index 668fe5bfa..337520076 100644
--- a/plugins/portal/test/router.test.ts
+++ b/plugins/portal/test/router.test.ts
@@ -333,9 +333,9 @@ test("new human path /drop/:id: form GET reaches the core /v1 drop form with x-d
assert.equal(ob.headers["x-drop-owner"], "owner@acme");
});
-test("deployments are OFF by default (404 even with a session)", async () => {
+test("deployments are ON by default — /d/ proxies to core for a signed-in session", async () => {
const r = await fetch(`${base}/d/some-app/`, { headers: { cookie: sessionCookie("U1") } });
- assert.equal(r.status, 404);
+ assert.notEqual(r.status, 404, "the /d/ route exists without PORTAL_DEPLOYMENTS_ENABLED");
});
test("auth/login sets the tmp cookie and 302s to the IdP with PKCE+state+nonce", async () => {
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 97af0ad29..50446884f 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -68,8 +68,26 @@ async function proxyDeployment(ctx: BaseCtx): Promise<void> {
}
}
}
+ if (
+ deps.deployAppsDomain &&
+ deps.deployGateSecret &&
+ deps.deployAppsSessionSecret &&
+ method === "GET" &&
+ String(req.headers["sec-fetch-dest"] ?? "") === "document"
+ ) {
+ const d = await app.getDeployment(id).catch(() => null);
+ const slug = d?.name ?? d?.id;
+ if (d && slug && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug)) {
+ res.writeHead(302, {
+ location: `https://${slug}.${deps.deployAppsDomain}${subPath}${url.search}`,
+ "cache-control": "no-store",
+ });
+ res.end();
+ return;
+ }
+ }
const reach = await app.reachDeployment(id, principal);
- return proxyReach(ctx, reach, subPath);
+ return proxyReach(ctx, reach, subPath, { sandboxHtml: true });
}
function adminDeploymentProxyParts(pathname: string): { id: string; subPath: string } | null {
@@ -116,7 +134,7 @@ async function proxyAdminDeployment(ctx: BaseCtx): Promise<void> {
scopeLabel: deployment.ownerScopeId,
});
const reach = await app.reachDeployment(parts.id, "", { bypassAcl: true });
- return proxyReach(ctx, reach, parts.subPath);
+ return proxyReach(ctx, reach, parts.subPath, { sandboxHtml: true });
}
const GATEWAY_AUTH_HEADERS = [
@@ -170,8 +188,11 @@ function forwardableHeaders(req: BaseCtx["req"]): Record<string, string | string
return out;
}
+const APP_SANDBOX_CSP = "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads";
+
function gatewaySafeResponseHeaders(
headers: Record<string, string | string[] | number | undefined>,
+ sandboxHtml = false,
): Record<string, string | string[]> {
const normalized: Record<string, string | string[] | undefined> = {};
for (const [rawName, value] of Object.entries(headers)) {
@@ -187,6 +208,12 @@ function gatewaySafeResponseHeaders(
if (kept.length) out["set-cookie"] = kept;
else delete out["set-cookie"];
}
+ if (sandboxHtml && String(out["content-type"] ?? "").includes("text/html")) {
+ const existing = out["content-security-policy"];
+ out["content-security-policy"] = existing
+ ? [...(Array.isArray(existing) ? existing : [existing]), APP_SANDBOX_CSP]
+ : APP_SANDBOX_CSP;
+ }
return out;
}
@@ -252,6 +279,7 @@ function proxyReachHttp2(
subPath: string,
headers: Record<string, string | string[]>,
bufferedBody: Buffer | null,
+ sandboxHtml: boolean,
): void {
const { req, res, deps, url, method } = ctx;
const { host, port, tls } = endpoint.endpoint;
@@ -356,7 +384,7 @@ function proxyReachHttp2(
markUpstreamUp(`${host}:${port}`);
armThrottleShield(`${host}:${port}`, Number(responseHeaders[":status"] ?? 0), up);
const status = Number(responseHeaders[":status"] ?? 502);
- const safeHeaders = gatewaySafeResponseHeaders(responseHeaders);
+ const safeHeaders = gatewaySafeResponseHeaders(responseHeaders, sandboxHtml);
res.writeHead(status, safeHeaders);
up.pipe(res, { end: false });
});
@@ -446,6 +474,7 @@ async function proxyReach(
ctx: BaseCtx,
reach: Awaited<ReturnType<App["reachDeployment"]>>,
subPath: string,
+ opts?: { sandboxHtml?: boolean },
): Promise<void> {
const { req, res, deps, url, method } = ctx;
if (res.destroyed) return;
@@ -491,7 +520,7 @@ async function proxyReach(
}
if (res.destroyed) return;
if (reach.endpoint.httpVersion === "2") {
- proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody);
+ proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody, opts?.sandboxHtml ?? false);
return;
}
const htmlNav = wantsWarmingPage(req, method);
@@ -500,7 +529,7 @@ async function proxyReach(
markUpstreamUp(upstreamKey);
upRes.on("error", () => res.destroy());
armThrottleShield(upstreamKey, upRes.statusCode ?? 0, upRes);
- const headers = gatewaySafeResponseHeaders(upRes.headers);
+ const headers = gatewaySafeResponseHeaders(upRes.headers, opts?.sandboxHtml ?? false);
res.writeHead(upRes.statusCode ?? 502, headers);
upRes.pipe(res);
});
@@ -1154,11 +1183,14 @@ async function deploymentOwnerUrl(ctx: ApiCtx): Promise<void> {
if (!sub) return sendJson(res, 403, { error: "forbidden", message: "an identified caller is required" });
const gateSecret = deps.deployGateSecret;
const appsDomain = deps.deployAppsDomain;
- if (!gateSecret || !appsDomain)
- return sendJson(res, 503, { error: "unavailable", message: "deployment subdomains are not configured" });
const deployment = await app.getDeployment(params.id!);
if (!deployment) return sendJson(res, 404, { error: "not_found" });
const slug = deployment.name ?? deployment.id;
+ if (!gateSecret || !appsDomain)
+ return sendJson(res, 503, {
+ error: "unavailable",
+ message: `app subdomains are not configured — this app is reachable signed-in at /d/${slug}/; set DEPLOY_APPS_DOMAIN (with AWS_DEPLOY_GATE_SECRET) to enable per-app subdomains and live editing`,
+ });
if (!(await app.canManageDeployment(deployment.id, sub, ctx.capability?.scopeId)))
return sendJson(res, 403, { error: "forbidden", message: "only someone who manages this app can edit it live" });
const exp = Date.now() + OWNER_LINK_TTL_MS;
diff --git a/src/config.ts b/src/config.ts
index 28fd74f78..0b0d58704 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -159,6 +159,7 @@ export interface Config {
porterSandbox: PorterSandboxEnv;
porterDeploy: PorterDeployEnv;
awsDeploy: AwsDeployEnv;
+ deployAppsDomain?: string;
flyDeploy: FlyDeployEnv;
}
@@ -451,16 +452,62 @@ interface AwsDeployEnv {
dataRoleArn?: string;
}
-function deployAppsEnv(env: NodeJS.ProcessEnv): { deployAppsSessionSecret?: string; deployAppsLoginUrl?: string } {
+function deployAppsEnv(
+ env: NodeJS.ProcessEnv,
+ defaultLoginUrl: string | undefined,
+): { deployAppsSessionSecret?: string; deployAppsLoginUrl?: string } {
const secret = env.DEPLOY_APPS_SESSION_SECRET;
- const loginUrl = env.DEPLOY_APPS_LOGIN_URL;
- if (!!secret !== !!loginUrl) {
- throw new Error("DEPLOY_APPS_SESSION_SECRET and DEPLOY_APPS_LOGIN_URL must be set together");
+ const loginUrl = env.DEPLOY_APPS_LOGIN_URL ?? (secret ? defaultLoginUrl : undefined);
+ if (loginUrl && !secret) {
+ throw new Error("DEPLOY_APPS_LOGIN_URL requires DEPLOY_APPS_SESSION_SECRET");
+ }
+ if (secret && !loginUrl) {
+ throw new Error("DEPLOY_APPS_SESSION_SECRET needs a sign-in address — set DEPLOY_APPS_LOGIN_URL or PUBLIC_WEB_URL");
}
if (!secret || !loginUrl) return {};
return { deployAppsSessionSecret: secret, deployAppsLoginUrl: loginUrl.replace(/\/$/, "") };
}
+const SHARED_PLATFORM_SUFFIXES = [
+ "onporter.run",
+ "withporter.run",
+ "porter.run",
+ "fly.dev",
+ "herokuapp.com",
+ "onrender.com",
+ "railway.app",
+ "vercel.app",
+ "netlify.app",
+ "ondigitalocean.app",
+ "azurewebsites.net",
+ "elasticbeanstalk.com",
+ "amazonaws.com",
+ "cloudfront.net",
+ "github.io",
+ "pages.dev",
+ "workers.dev",
+];
+
+function sharedPlatformSuffixOf(domain: string): string | undefined {
+ const host = domain.toLowerCase();
+ return SHARED_PLATFORM_SUFFIXES.find((suffix) => host === suffix || host.endsWith(`.${suffix}`));
+}
+
+function deployAppsDomainEnv(env: NodeJS.ProcessEnv, deployProvider: string): string | undefined {
+ const canonical = env.DEPLOY_APPS_DOMAIN?.trim();
+ if (canonical) {
+ const suffix = sharedPlatformSuffixOf(canonical);
+ if (suffix) {
+ throw new Error(
+ `DEPLOY_APPS_DOMAIN (${canonical}) is under ${suffix}, a shared platform domain that cannot carry per-app subdomains — attach a custom domain you control (set DEPLOY_APPS_DOMAIN=apps.<your-domain> with a wildcard DNS record pointing at this instance), or unset it to keep serving apps signed-in at /d/<app>/.`,
+ );
+ }
+ return canonical;
+ }
+ if (deployProvider === "porter" && env.PORTER_DEPLOY_APPS_DOMAIN) return env.PORTER_DEPLOY_APPS_DOMAIN;
+ return env.AWS_DEPLOY_APPS_DOMAIN;
+}
+
function awsDeployEnv(env: NodeJS.ProcessEnv): AwsDeployEnv {
const csv = (s: string | undefined): string[] | undefined =>
s
@@ -729,6 +776,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
codexOAuthConfigured && codexAuthCandidate
? { ...env, CODEX_AUTH_FILE: codexAuthCandidate }
: { ...env, CODEX_AUTH_FILE: undefined };
+ const deployAppsDomain = deployAppsDomainEnv(env, env.DEPLOY_PROVIDER ?? "docker");
const missingSecrets = validateCoreSecretEnv(secretEnv);
if (missingSecrets.length) {
throw new Error(`missing or insecure required core secrets: ${missingSecrets.join(", ")}`);
@@ -770,9 +818,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
"[config] SANDBOX_BACKEND=porter without PORTER_SANDBOX_EGRESS_PROXY_URL — sandboxes run with NO egress enforcement (fail-open); set PORTER_SANDBOX_EGRESS_PROXY_URL to the egress proxy to force sandbox traffic through it.",
);
}
- if (env.DEPLOY_PROVIDER === "porter" && !env.PORTER_DEPLOY_APPS_DOMAIN) {
+ if (env.DEPLOY_PROVIDER === "porter" && !env.PORTER_DEPLOY_APPS_DOMAIN && !env.DEPLOY_APPS_DOMAIN) {
console.warn(
- "[config] DEPLOY_PROVIDER=porter without PORTER_DEPLOY_APPS_DOMAIN — every publish will be refused because the app would have no address; enable sandbox ingress on the cluster, point a wildcard DNS record at it, and set PORTER_DEPLOY_APPS_DOMAIN.",
+ "[config] DEPLOY_PROVIDER=porter without an apps domain — published apps use hostnames assigned by the cluster and are reachable signed-in at /d/<app>/; set DEPLOY_APPS_DOMAIN to a domain you control to serve each app on its own subdomain.",
);
}
for (const [selected, label] of [
@@ -1062,7 +1110,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
deployGitDir: env.DEPLOY_GIT_DIR ? resolve(env.DEPLOY_GIT_DIR) : join(dataDir, "deploy-git"),
deployDialTimeoutMs:
numEnvStrict("DEPLOY_DIAL_TIMEOUT_MS", env.DEPLOY_DIAL_TIMEOUT_MS) ?? CONFIG_DEFAULTS.deployDialTimeoutMs,
- ...deployAppsEnv(env),
+ ...deployAppsEnv(env, publicUrl),
deepIdleMachineMs:
numEnvStrict("DEEP_IDLE_MACHINE_MS", env.DEEP_IDLE_MACHINE_MS) ?? CONFIG_DEFAULTS.deepIdleMachineMs,
devIdleMachineMs: numEnvStrict("DEV_IDLE_MACHINE_MS", env.DEV_IDLE_MACHINE_MS) ?? CONFIG_DEFAULTS.devIdleMachineMs,
@@ -1097,8 +1145,15 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
spritesSandbox: spritesSandboxEnv(env),
smolmachinesSandbox: smolmachinesSandboxEnv(env),
porterSandbox: porterSandboxEnv(env),
- porterDeploy: porterDeployEnv(env),
- awsDeploy: awsDeployEnv(env),
+ porterDeploy: {
+ ...porterDeployEnv(env),
+ ...(deployAppsDomain && !env.PORTER_DEPLOY_APPS_DOMAIN ? { appsDomain: deployAppsDomain } : {}),
+ },
+ awsDeploy: {
+ ...awsDeployEnv(env),
+ ...(deployAppsDomain && !env.AWS_DEPLOY_APPS_DOMAIN ? { appsDomain: deployAppsDomain } : {}),
+ },
+ ...(deployAppsDomain ? { deployAppsDomain } : {}),
flyDeploy: flyDeployEnv(env),
};
}
diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.ts
index 6f36f7375..0f6781da7 100644
--- a/src/deployment/secret-schema.ts
+++ b/src/deployment/secret-schema.ts
@@ -56,7 +56,7 @@ const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => b
"porter-deploy": (env) => env.DEPLOY_PROVIDER === "porter",
"fly-sandbox": (env) => env.SANDBOX_BACKEND === "fly",
"fly-deploy": (env) => env.DEPLOY_PROVIDER === "fly",
- "aws-deploy-gate": (env) => Boolean(env.AWS_DEPLOY_APPS_DOMAIN),
+ "aws-deploy-gate": (env) => Boolean(env.AWS_DEPLOY_APPS_DOMAIN || env.DEPLOY_APPS_DOMAIN),
"google-oauth": (env) => Boolean(env.GOOGLE_OAUTH_CLIENT_ID),
"dropbox-oauth": (env) => Boolean(env.DROPBOX_OAUTH_CLIENT_ID),
"linear-oauth": (env) => Boolean(env.LINEAR_OAUTH_CLIENT_ID),
diff --git a/src/index.ts b/src/index.ts
index 112835997..817889b5c 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,3 +1,5 @@
+import { randomBytes } from "node:crypto";
+import { lookup } from "node:dns/promises";
import { loadConfig } from "./config.ts";
import { buildApp, serverDeps, stopWithBackstop } from "./wiring.ts";
import { createServer } from "./api/server.ts";
@@ -31,6 +33,17 @@ server.listen(config.port, () => {
);
});
+if (config.deployAppsDomain) {
+ const domain = config.deployAppsDomain;
+ const probe = `qm-probe-${randomBytes(4).toString("hex")}.${domain}`;
+ void lookup(probe).catch(() => {
+ console.warn(
+ `[qm] app subdomains are configured but *.${domain} does not resolve (probed ${probe}) — ` +
+ `add a wildcard DNS record for *.${domain} pointing at this instance's ingress, or apps will only be reachable at /d/<app>/`,
+ );
+ });
+}
+
if (config.deployProvider === "docker") {
void dockerDaemonFailure().then((failure) => {
if (failure)
diff --git a/src/wiring.ts b/src/wiring.ts
index 932d69516..7b3fa3b7e 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1777,7 +1777,7 @@ export function serverDeps(
brokeredServices: () => built.brokeredTools.map((tool) => tool.service),
deploymentLayer: built.deploymentLayerStore,
deployDialTimeoutMs: config.deployDialTimeoutMs,
- ...(config.awsDeploy.appsDomain ? { deployAppsDomain: config.awsDeploy.appsDomain } : {}),
+ ...(config.deployAppsDomain ? { deployAppsDomain: config.deployAppsDomain } : {}),
...(config.awsDeploy.gateSecret ? { deployGateSecret: config.awsDeploy.gateSecret } : {}),
...(config.deployAppsSessionSecret ? { deployAppsSessionSecret: config.deployAppsSessionSecret } : {}),
...(config.deployAppsLoginUrl ? { deployAppsLoginUrl: config.deployAppsLoginUrl } : {}),
diff --git a/test/config.test.ts b/test/config.test.ts
index 76db42942..77b2a350e 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -510,3 +510,76 @@ test("SANDBOX_BACKEND=porter locates the API and shares the deploy provider's to
assert.equal(inCluster.porterSandbox.ttlSec, 120);
assert.equal(inCluster.porterDeploy.token, "tok");
});
+
+test("DEPLOY_APPS_DOMAIN is the one-var apps setup: it feeds the gate and defaults every provider's domain", () => {
+ const config = loadConfig({
+ DEPLOY_PROVIDER: "porter",
+ PORTER_DEPLOY_API_TOKEN: "tok",
+ PORTER_DEPLOY_PROJECT_ID: "7",
+ PORTER_DEPLOY_CLUSTER_ID: "9",
+ DEPLOY_APPS_DOMAIN: "apps.example.com",
+ AWS_DEPLOY_GATE_SECRET: "0123456789abcdef0123456789abcdef",
+ });
+ assert.equal(config.deployAppsDomain, "apps.example.com");
+ assert.equal(config.porterDeploy.appsDomain, "apps.example.com");
+ assert.equal(config.awsDeploy.appsDomain, "apps.example.com");
+ const overridden = loadConfig({
+ DEPLOY_PROVIDER: "porter",
+ PORTER_DEPLOY_API_TOKEN: "tok",
+ PORTER_DEPLOY_PROJECT_ID: "7",
+ PORTER_DEPLOY_CLUSTER_ID: "9",
+ DEPLOY_APPS_DOMAIN: "apps.example.com",
+ PORTER_DEPLOY_APPS_DOMAIN: "apps.other.example.com",
+ AWS_DEPLOY_GATE_SECRET: "0123456789abcdef0123456789abcdef",
+ });
+ assert.equal(overridden.porterDeploy.appsDomain, "apps.other.example.com");
+ assert.equal(overridden.deployAppsDomain, "apps.example.com");
+});
+
+test("the active provider's own apps domain reaches the gate when DEPLOY_APPS_DOMAIN is unset", () => {
+ const porter = loadConfig({
+ DEPLOY_PROVIDER: "porter",
+ PORTER_DEPLOY_API_TOKEN: "tok",
+ PORTER_DEPLOY_PROJECT_ID: "7",
+ PORTER_DEPLOY_CLUSTER_ID: "9",
+ PORTER_DEPLOY_APPS_DOMAIN: "apps.example.com",
+ });
+ assert.equal(porter.deployAppsDomain, "apps.example.com");
+ assert.equal(porter.awsDeploy.appsDomain, "apps.example.com");
+ const aws = loadConfig({
+ AWS_DEPLOY_APPS_DOMAIN: "apps.example.com",
+ AWS_DEPLOY_GATE_SECRET: "0123456789abcdef0123456789abcdef",
+ });
+ assert.equal(aws.deployAppsDomain, "apps.example.com");
+ assert.equal(loadConfig({}).deployAppsDomain, undefined);
+});
+
+test("DEPLOY_APPS_DOMAIN refuses shared platform domains that cannot carry per-app subdomains", () => {
+ assert.throws(() => loadConfig({ DEPLOY_APPS_DOMAIN: "myapp.onporter.run" }), /shared platform domain/);
+ assert.throws(() => loadConfig({ DEPLOY_APPS_DOMAIN: "myapp.fly.dev" }), /shared platform domain/);
+ assert.equal(
+ loadConfig({ DEPLOY_APPS_DOMAIN: "apps.example.com", AWS_DEPLOY_GATE_SECRET: "0123456789abcdef0123456789abcdef" })
+ .deployAppsDomain,
+ "apps.example.com",
+ );
+});
+
+test("the deploy-apps sign-in address defaults to the public web URL", () => {
+ const derived = loadConfig({
+ DEPLOY_APPS_SESSION_SECRET: "s",
+ PUBLIC_WEB_URL: "https://qm.example.com/",
+ });
+ assert.equal(derived.deployAppsLoginUrl, "https://qm.example.com");
+ assert.equal(derived.deployAppsSessionSecret, "s");
+ const explicit = loadConfig({
+ DEPLOY_APPS_SESSION_SECRET: "s",
+ DEPLOY_APPS_LOGIN_URL: "https://portal.example.com/",
+ PUBLIC_WEB_URL: "https://qm.example.com",
+ });
+ assert.equal(explicit.deployAppsLoginUrl, "https://portal.example.com");
+ assert.throws(() => loadConfig({ DEPLOY_APPS_SESSION_SECRET: "s" }), /DEPLOY_APPS_LOGIN_URL or PUBLIC_WEB_URL/);
+ assert.throws(
+ () => loadConfig({ DEPLOY_APPS_LOGIN_URL: "https://portal.example.com" }),
+ /requires DEPLOY_APPS_SESSION_SECRET/,
+ );
+});
diff --git a/test/deploy-path-serving.test.ts b/test/deploy-path-serving.test.ts
new file mode 100644
index 000000000..39ce1aca6
--- /dev/null
+++ b/test/deploy-path-serving.test.ts
@@ -0,0 +1,171 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createServer as createHttpServer, request as httpRequest } from "node:http";
+import type { AddressInfo, Server } from "node:net";
+import { createApp } from "../src/api/app.ts";
+import { createInsecureTestServer } from "../src/api/server.ts";
+import { createDeployStore } from "../src/deploy/deploy-store.ts";
+import { createDeployService } from "../src/deploy/deploy-service.ts";
+import { createAclStore } from "../src/acl/acl-store.ts";
+import { createDirectoryStore } from "../src/directory/directory-store.ts";
+import { createIdentityService } from "../src/identity/identity-service.ts";
+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
+import { scopeId } from "../src/types.ts";
+
+const auditLog = { record() {}, events: async () => [], tail: async () => [] };
+
+function httpGet(
+ port: number,
+ path: string,
+ headers: Record<string, string>,
+): Promise<{ status: number; headers: Record<string, string | string[] | undefined>; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = httpRequest({ host: "localhost", port, path, method: "GET", headers }, (res) => {
+ let body = "";
+ res.on("data", (c) => (body += c));
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+}
+
+async function fixture(
+ deps: Parameters<typeof createInsecureTestServer>[1],
+ upstreamContentType = "text/html; charset=utf-8",
+) {
+ const upstream = createHttpServer((_req, res) => {
+ res.writeHead(200, { "content-type": upstreamContentType });
+ res.end("UPSTREAM OK");
+ });
+ upstream.listen(0);
+ const upstreamPort = (upstream.address() as AddressInfo).port;
+ const deployStore = createDeployStore();
+ const deploy = createDeployService({
+ deployStore,
+ provider: {
+ profile: { managedScaleToZero: false },
+ apply: async () => ({ host: "127.0.0.1", port: upstreamPort }),
+ destroy: async () => {},
+ },
+ auditLog,
+ acl: createAclStore(),
+ deployDir: mkdtempSync(join(tmpdir(), "path-serving-")),
+ });
+ const app = createApp({
+ deploy,
+ acl: createAclStore(),
+ directory: createDirectoryStore(),
+ sessions: createMemorySessionStore(),
+ identity: createIdentityService(),
+ } as unknown as Parameters<typeof createApp>[0]);
+ await app.deploy({
+ ownerScopeId: scopeId("personal", "[email protected]"),
+ createdBy: "[email protected]",
+ entrypoint: "x",
+ files: [],
+ name: "mysite",
+ });
+ const server = createInsecureTestServer(app, deps);
+ server.listen(0);
+ const port = (server.address() as AddressInfo).port;
+ const close = async () => {
+ await new Promise<void>((r) => (server as unknown as Server).close(() => r()));
+ await new Promise<void>((r) => upstream.close(() => r()));
+ };
+ return { port, close };
+}
+
+test("/d/ path serving sandboxes proxied HTML so an app cannot act on the portal's origin", async () => {
+ const f = await fixture({});
+ try {
+ const page = await httpGet(f.port, "/d/mysite/", { "x-as-principal": "[email protected]" });
+ assert.equal(page.status, 200);
+ const csp = page.headers["content-security-policy"];
+ assert.match(String(csp), /^sandbox /, "proxied HTML carries a sandbox CSP");
+ assert.doesNotMatch(String(csp), /allow-same-origin/, "the sandbox must deny the portal origin to app code");
+ } finally {
+ await f.close();
+ }
+});
+
+test("/d/ path serving leaves non-HTML responses unsandboxed", async () => {
+ const f = await fixture({}, "application/json");
+ try {
+ const data = await httpGet(f.port, "/d/mysite/api", { "x-as-principal": "[email protected]" });
+ assert.equal(data.status, 200);
+ assert.equal(data.headers["content-security-policy"], undefined);
+ } finally {
+ await f.close();
+ }
+});
+
+test("subdomain serving stays unsandboxed — each app already has its own origin", async () => {
+ const f = await fixture({
+ deployAppsDomain: "apps.example.com",
+ deployGateSecret: "gate-secret",
+ deployAppsSessionSecret: "portal-session-secret",
+ deployAppsLoginUrl: "https://portal.example.com",
+ });
+ try {
+ const page = await httpGet(f.port, "/", { Host: "mysite.apps.example.com", Accept: "text/html" });
+ assert.equal(page.status, 302, "signed-out visitors bounce to sign-in, with no sandbox header");
+ assert.equal(page.headers["content-security-policy"], undefined);
+ } finally {
+ await f.close();
+ }
+});
+
+test("a /d/ document navigation upgrades to the app's subdomain once one is configured", async () => {
+ const f = await fixture({
+ deployAppsDomain: "apps.example.com",
+ deployGateSecret: "gate-secret",
+ deployAppsSessionSecret: "portal-session-secret",
+ deployAppsLoginUrl: "https://portal.example.com",
+ });
+ try {
+ const nav = await httpGet(f.port, "/d/mysite/page?a=1", {
+ "x-as-principal": "[email protected]",
+ "sec-fetch-dest": "document",
+ Accept: "text/html",
+ });
+ assert.equal(nav.status, 302);
+ assert.equal(nav.headers.location, "https://mysite.apps.example.com/page?a=1");
+
+ const sub = await httpGet(f.port, "/d/mysite/app.js", { "x-as-principal": "[email protected]" });
+ assert.equal(sub.status, 200, "subresource fetches keep proxying so open tabs never break");
+ } finally {
+ await f.close();
+ }
+});
+
+test("without a subdomain configuration /d/ document navigations proxy in place", async () => {
+ const f = await fixture({});
+ try {
+ const nav = await httpGet(f.port, "/d/mysite/", {
+ "x-as-principal": "[email protected]",
+ "sec-fetch-dest": "document",
+ Accept: "text/html",
+ });
+ assert.equal(nav.status, 200);
+ assert.equal(nav.body, "UPSTREAM OK");
+ } finally {
+ await f.close();
+ }
+});
+
+test("owner-url without a subdomain configuration explains the /d/ path and the enabling env var", async () => {
+ const f = await fixture({});
+ try {
+ const r = await httpGet(f.port, "/v1/deployments/mysite/[email protected]", {});
+ assert.equal(r.status, 503);
+ const { message } = JSON.parse(r.body) as { message: string };
+ assert.match(message, /\/d\/mysite\//);
+ assert.match(message, /DEPLOY_APPS_DOMAIN/);
+ } finally {
+ await f.close();
+ }
+});