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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(infra): manage Convex Cloud custom domains safely
Rahman0d5cd75d4b32
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 76b9d760..16f94dd0 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `infra` manage Convex Cloud custom domains safely- `infra` add bounded Dokploy public env rollout**Fixed**diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex c14f71e0..972b7084 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2789,3 +2789,8 @@ MCP now exposes `fs_upload_file` with `_meta["openai/fileParams"]`, so ChatGPT c## 2026-09-05 — Session-scoped screenshot evidenceScreenshot evidence previously lived in unrelated scratch directories or only in MCP image responses. Added one derived session path policy, a private manifest, explicit image/report reads, and bounded registration/retention. Exec receives non-secret session directories; original bytes remain private and session responses compute paths instead of persisting absolute homes. Cleanup is lazy, lease-aware and fail-closed for unknown files; it does not run during builds or remove durable history. User/client isolation, retry de-duplication and existing integration changes are preserved. See SESSION-ARTIFACTS.md for limits and verification scope.++### 2026-09-06 — Convex Cloud custom-domain control+- Added a native `convex-cloud` CLI credential import that reads only `~/.convex/config.json`, refuses symlink/non-owner inputs, hardens the local credential directory/file to `0700/0600`, validates the token before saving, and never returns the credential.+- Added bounded exact-connection operations for listing/ensuring Convex custom domains and reading/updating canonical `convexCloud` / `convexSite` URLs. Canonical operations mint a scoped short-lived deploy key and revoke it in `finally`; custom canonical URLs must already be registered and verified.+- The operations stay behind `integration_execute` / `integration_manage`; no generic Convex HTTP escape hatch and no new global MCP tool were added.diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.tsindex 7f46c343..3b3f7aaf 100644--- a/lib/infra/connection-dispatch.ts+++ b/lib/infra/connection-dispatch.ts@@ -2,12 +2,20 @@ import { integrationManage } from "./connection-manage";import { integrationQuery, withIntegrationSelection, resolveIntegration } from "./connection-service";import { authorizeIntegration, composioConnectionCall } from "./connection-external";import { IntegrationError, identity, metadataOnly, type ConnectionSelector } from "./identity";+import { importConvexCliPersonalConnection } from "./convex-cli-import";+import { listConvexCustomDomains, ensureConvexCustomDomain, getConvexCanonicalUrls, setConvexCanonicalUrl } from "./convex-cloud";import { doctorInfraProvider, ensureDokployProject, listDokployApplications, listDokployProjects, listCloudflareZones, upsertCloudflareDns, upsertDokployPublicBuildEnv, upsertHostingerDns, listHostingerMailOrders, getHostingerMailPlan, listHostingerMail, listHostingerMailLogs, mutateHostingerMail } from "./clients";import { isInfraProviderId } from "./catalog";export const safeActionInput=(input:Record<string,unknown>)=>Object.fromEntries(Object.entries(input).filter(([key])=>key!=="workflow_id"));export const selectionFrom=(a:Record<string,unknown>):ConnectionSelector=>({user:typeof a.user==="string"?a.user:undefined,connection:typeof a.connection==="string"?a.connection:undefined,cwd:typeof a.cwd==="string"?a.cwd:undefined});export async function manageIntegrationAction(raw:Record<string,unknown>){const a=safeActionInput(raw);metadataOnly(a);+ if(a.action==="connection.import-convex-cli"){+ if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);+ if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection"].includes(k)))throw new IntegrationError("invalid_management_fields");+ if(a.provider!=="convex-cloud")throw new IntegrationError("provider_operation_mismatch");+ return importConvexCliPersonalConnection(selectionFrom(a));+ }if(a.action!=="connection.authorize")return integrationManage(a);if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection","authConfigId","brokerConnection","createManaged"].includes(k)))throw new IntegrationError("invalid_management_fields");@@ -28,6 +36,10 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){"dokploy.applications.list":{provider:"dokploy",fields:["projectId"],run:()=>listDokployApplications(String((args as Record<string,unknown>).projectId))},"dokploy.application.publicEnv.upsert":{provider:"dokploy",fields:["applicationId","key","value"],run:()=>upsertDokployPublicBuildEnv(args as {applicationId:string;key:string;value:string})},"dokploy.project.ensure":{provider:"dokploy",fields:["name"],run:()=>ensureDokployProject(String((args as Record<string,unknown>).name))},+ "convex.customDomains.list":{provider:"convex-cloud",fields:["deploymentName"],run:()=>listConvexCustomDomains(String((args as Record<string,unknown>).deploymentName))},+ "convex.customDomain.ensure":{provider:"convex-cloud",fields:["deploymentName","domain","requestDestination"],run:()=>ensureConvexCustomDomain(args as {deploymentName:string;domain:string;requestDestination:"convexCloud"|"convexSite"})},+ "convex.canonical.get":{provider:"convex-cloud",fields:["deploymentName"],run:()=>getConvexCanonicalUrls(String((args as Record<string,unknown>).deploymentName))},+ "convex.canonical.set":{provider:"convex-cloud",fields:["deploymentName","requestDestination","url"],run:()=>setConvexCanonicalUrl(args as {deploymentName:string;requestDestination:"convexCloud"|"convexSite";url?:string|null})},"cloudflare.zones.list":{provider:"cloudflare",fields:[],run:()=>listCloudflareZones()},"cloudflare.dns.upsert":{provider:"cloudflare",fields:["name","type","content","ttl","proxied"],run:()=>upsertCloudflareDns(args as Parameters<typeof upsertCloudflareDns>[0])},"hostinger.dns.upsert":{provider:"hostinger",fields:["name","type","content","ttl"],run:()=>upsertHostingerDns(args as Parameters<typeof upsertHostingerDns>[0])},diff --git a/lib/infra/convex-canonical.test.ts b/lib/infra/convex-canonical.test.tsnew file mode 100644index 00000000..5a06afaf--- /dev/null+++ b/lib/infra/convex-canonical.test.ts@@ -0,0 +1,158 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+const PAT = "pat_synthetic_12345678901234567890";+const DEPLOY_KEY = "prod:happy-otter-123|synthetic_deploy_key_1234567890";+let root: string;+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-canonical-"));+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");+ vi.resetModules();+});+afterEach(async () => {+ delete process.env.OS_INFRA_STORE;+ await fs.rm(root, { recursive: true, force: true });+ vi.resetModules();+});+async function seeded() {+ const { integrationManage } = await import("./connection-manage");+ await integrationManage({+ action: "user.create",+ user: "alice",+ confirm: true,+ });+ await integrationManage({+ action: "connection.create",+ user: "alice",+ provider: "convex-cloud",+ connection: "admin",+ authMethod: "personal",+ source: "direct",+ confirm: true,+ });+ const { withIntegrationSelection } = await import("./connection-service"),+ { setInfraProvider } = await import("./store");+ await withIntegrationSelection({ user: "alice", connection: "admin" }, () =>+ setInfraProvider("convex-cloud", { personalToken: PAT }),+ );+ return withIntegrationSelection;+}+const json = (body: unknown, status = 200) =>+ new Response(body === null ? null : JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+it("reads canonical URLs through a scoped short-lived deploy key and deletes it", async () => {+ const withSelection = await seeded();+ const seen: string[] = [];+ const fetchImpl = vi.fn(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ seen.push(url);+ if (url.endsWith("/create_deploy_key")) {+ expect(JSON.parse(String(init?.body)).allowedActions).toEqual([+ "deployment:env:view",+ "deployment:env:write",+ ]);+ return json({ deployKey: DEPLOY_KEY });+ }+ if (url.endsWith("/get_canonical_urls")) {+ expect(new Headers(init?.headers).get("authorization")).toBe(+ `Convex ${DEPLOY_KEY}`,+ );+ return json({+ convexCloudUrl: "https://happy-otter-123.convex.cloud",+ convexSiteUrl: "https://happy-otter-123.convex.site",+ });+ }+ if (url.endsWith("/delete_deploy_key")) return json(null);+ return json({ error: "unexpected" }, 500);+ },+ );+ const { getConvexCanonicalUrls } = await import("./convex-canonical");+ const result = await withSelection(+ { user: "alice", connection: "admin" },+ () => getConvexCanonicalUrls("happy-otter-123", fetchImpl),+ );+ expect(result).toMatchObject({+ convexCloudUrl: "https://happy-otter-123.convex.cloud",+ convexSiteUrl: "https://happy-otter-123.convex.site",+ });+ expect(seen.at(-1)).toMatch(/delete_deploy_key$/);+ expect(JSON.stringify(result)).not.toContain(DEPLOY_KEY);+});+it("sets canonical Cloud only after the matching custom domain is verified", async () => {+ const withSelection = await seeded();+ let canonical = {+ convexCloudUrl: "https://happy-otter-123.convex.cloud",+ convexSiteUrl: "https://happy-otter-123.convex.site",+ };+ const fetchImpl = vi.fn(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url.endsWith("/custom_domains"))+ return json({+ domains: [+ {+ domain: "api.example.com",+ deploymentName: "happy-otter-123",+ requestDestination: "convexCloud",+ creationTime: 1,+ verificationTime: 2,+ },+ ],+ });+ if (url.endsWith("/create_deploy_key"))+ return json({ deployKey: DEPLOY_KEY });+ if (url.endsWith("/update_canonical_url")) {+ expect(JSON.parse(String(init?.body))).toEqual({+ requestDestination: "convexCloud",+ url: "https://api.example.com",+ });+ canonical = { ...canonical, convexCloudUrl: "https://api.example.com" };+ return json(null);+ }+ if (url.endsWith("/get_canonical_urls")) return json(canonical);+ if (url.endsWith("/delete_deploy_key")) return json(null);+ return json({ error: "unexpected" }, 500);+ },+ );+ const { setConvexCanonicalUrl } = await import("./convex-canonical");+ const result = await withSelection(+ { user: "alice", connection: "admin" },+ () =>+ setConvexCanonicalUrl(+ {+ deploymentName: "happy-otter-123",+ requestDestination: "convexCloud",+ url: "https://api.example.com",+ },+ fetchImpl,+ ),+ );+ expect(result.canonical.convexCloudUrl).toBe("https://api.example.com");+});+it("deletes the ephemeral key even when the deployment API fails", async () => {+ const withSelection = await seeded();+ let deleted = false;+ const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.endsWith("/create_deploy_key"))+ return json({ deployKey: DEPLOY_KEY });+ if (url.endsWith("/get_canonical_urls"))+ return json({ error: "boom" }, 500);+ if (url.endsWith("/delete_deploy_key")) {+ deleted = true;+ return json(null);+ }+ return json({ error: "unexpected" }, 500);+ });+ const { getConvexCanonicalUrls } = await import("./convex-canonical");+ await expect(+ withSelection({ user: "alice", connection: "admin" }, () =>+ getConvexCanonicalUrls("happy-otter-123", fetchImpl),+ ),+ ).rejects.toMatchObject({ code: "convex_deployment_http_500" });+ expect(deleted).toBe(true);+});diff --git a/lib/infra/convex-canonical.ts b/lib/infra/convex-canonical.tsnew file mode 100644index 00000000..fb595784--- /dev/null+++ b/lib/infra/convex-canonical.ts@@ -0,0 +1,176 @@+import { randomUUID } from "node:crypto";+import { obj } from "./http";+import { IntegrationError } from "./identity";+import { readInfraProvider } from "./store";+import {+ convexAuthHeaders,+ convexCanonicalOrigin,+ convexCheckedJson,+ convexDeploymentName,+ convexDeploymentUrl,+ convexDestination,+ convexManagementUrl,+ parseConvexCanonical,+ parseConvexDomains,+ type ConvexRequestDestination,+ type FetchLike,+} from "./convex-cloud-core";++const EPHEMERAL_ACTIONS = [+ "deployment:env:view",+ "deployment:env:write",+] as const;+async function personalToken(): Promise<string> {+ const values = await readInfraProvider("convex-cloud"),+ token = values.personalToken;+ if (!token) throw new IntegrationError("convex_personal_token_required", 409);+ return token;+}+async function withEphemeralDeployKey<T>(+ deployment: string,+ token: string,+ fn: (deployKey: string) => Promise<T>,+ fetchImpl: FetchLike,+): Promise<T> {+ const name = `mso-canonical-${randomUUID()}`;+ const created = obj(+ await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "create_deploy_key"),+ {+ method: "POST",+ headers: convexAuthHeaders(token, "Bearer"),+ body: JSON.stringify({ name, allowedActions: [...EPHEMERAL_ACTIONS] }),+ },+ fetchImpl,+ ),+ );+ const deployKey = created.deployKey;+ if (+ typeof deployKey !== "string" ||+ deployKey.length < 20 ||+ /[\x00-\x20\x7f]/.test(deployKey)+ )+ throw new IntegrationError("invalid_convex_deploy_key_response", 502);+ let result: T | undefined, primary: unknown;+ try {+ result = await fn(deployKey);+ } catch (error) {+ primary = error;+ }+ try {+ await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "delete_deploy_key"),+ {+ method: "POST",+ headers: convexAuthHeaders(token, "Bearer"),+ body: JSON.stringify({ id: name }),+ },+ fetchImpl,+ );+ } catch {+ throw new IntegrationError(+ primary+ ? "convex_operation_and_ephemeral_cleanup_failed"+ : "convex_ephemeral_cleanup_failed",+ 502,+ );+ }+ if (primary) throw primary;+ return result as T;+}+export async function getConvexCanonicalUrls(+ name: string,+ fetchImpl: FetchLike = fetch,+) {+ const deployment = convexDeploymentName(name),+ token = await personalToken();+ const canonical = await withEphemeralDeployKey(+ deployment,+ token,+ async (deployKey) => {+ const body = await convexCheckedJson(+ "convex_deployment",+ convexDeploymentUrl(deployment, "get_canonical_urls"),+ { method: "GET", headers: convexAuthHeaders(deployKey, "Convex") },+ fetchImpl,+ );+ return parseConvexCanonical(body);+ },+ fetchImpl,+ );+ return { deploymentName: deployment, ...canonical };+}+export async function setConvexCanonicalUrl(+ input: {+ deploymentName: string;+ requestDestination: ConvexRequestDestination;+ url?: string | null;+ },+ fetchImpl: FetchLike = fetch,+) {+ const deployment = convexDeploymentName(input.deploymentName),+ requestDestination = convexDestination(input.requestDestination),+ url = convexCanonicalOrigin(input.url),+ token = await personalToken();+ if (url) {+ const body = await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "custom_domains"),+ { method: "GET", headers: convexAuthHeaders(token, "Bearer") },+ fetchImpl,+ );+ const host = new URL(url).hostname,+ custom = parseConvexDomains(body).find(+ (row) =>+ row.domain === host && row.requestDestination === requestDestination,+ );+ if (!custom)+ throw new IntegrationError("convex_canonical_domain_not_registered", 409);+ if (custom.verificationTime === null)+ throw new IntegrationError("convex_canonical_domain_not_verified", 409);+ }+ const canonical = await withEphemeralDeployKey(+ deployment,+ token,+ async (deployKey) => {+ await convexCheckedJson(+ "convex_deployment",+ convexDeploymentUrl(deployment, "update_canonical_url"),+ {+ method: "POST",+ headers: convexAuthHeaders(deployKey, "Convex"),+ body: JSON.stringify({ requestDestination, ...(url ? { url } : {}) }),+ },+ fetchImpl,+ );+ const body = await convexCheckedJson(+ "convex_deployment",+ convexDeploymentUrl(deployment, "get_canonical_urls"),+ { method: "GET", headers: convexAuthHeaders(deployKey, "Convex") },+ fetchImpl,+ );+ return parseConvexCanonical(body);+ },+ fetchImpl,+ );+ const selected =+ requestDestination === "convexCloud"+ ? canonical.convexCloudUrl+ : canonical.convexSiteUrl;+ if (url && selected !== url)+ throw new IntegrationError("convex_canonical_verification_failed", 502);+ if (!url) {+ const suffix =+ requestDestination === "convexCloud" ? ".convex.cloud" : ".convex.site";+ if (!new URL(selected).hostname.endsWith(suffix))+ throw new IntegrationError("convex_canonical_verification_failed", 502);+ }+ return {+ changed: true,+ deploymentName: deployment,+ requestDestination,+ canonical,+ };+}diff --git a/lib/infra/convex-cli-import.test.ts b/lib/infra/convex-cli-import.test.tsnew file mode 100644index 00000000..fa7c6e5c--- /dev/null+++ b/lib/infra/convex-cli-import.test.ts@@ -0,0 +1,82 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";++const PAT = "pat_synthetic_12345678901234567890";+let root: string;+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-cli-"));+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");+ vi.resetModules();+});+afterEach(async () => {+ delete process.env.OS_INFRA_STORE;+ await fs.rm(root, { recursive: true, force: true });+ vi.resetModules();+});+async function createPersonalConnection() {+ const { integrationManage } = await import("./connection-manage");+ await integrationManage({+ action: "user.create",+ user: "alice",+ confirm: true,+ });+ await integrationManage({+ action: "connection.create",+ user: "alice",+ provider: "convex-cloud",+ connection: "admin",+ authMethod: "personal",+ source: "direct",+ confirm: true,+ });+}+it("imports the local CLI token privately and hardens its permissions", async () => {+ await createPersonalConnection();+ const cliDir = path.join(root, "convex"),+ configPath = path.join(cliDir, "config.json");+ await fs.mkdir(cliDir, { mode: 0o775 });+ await fs.writeFile(configPath, JSON.stringify({ accessToken: PAT }), {+ mode: 0o664,+ });+ const { importConvexCliPersonalConnection } =+ await import("./convex-cli-import");+ const result = await importConvexCliPersonalConnection(+ { user: "alice", connection: "admin" },+ {+ configPath,+ doctor: async (id, values) => {+ expect(id).toBe("convex-cloud");+ expect(values.personalToken).toBe(PAT);+ return "personal access token authenticated";+ },+ },+ );+ expect((await fs.stat(cliDir)).mode & 0o777).toBe(0o700);+ expect((await fs.stat(configPath)).mode & 0o777).toBe(0o600);+ expect(JSON.stringify(result)).not.toContain(PAT);+ const { directConnectionValues } = await import("./connection-service");+ expect(+ (+ await directConnectionValues("convex-cloud", {+ user: "alice",+ connection: "admin",+ })+ ).personalToken,+ ).toBe(PAT);+});+it("refuses a symlinked CLI credential file", async () => {+ const cliDir = path.join(root, "convex"),+ target = path.join(root, "target.json"),+ configPath = path.join(cliDir, "config.json");+ await fs.mkdir(cliDir, { mode: 0o700 });+ await fs.writeFile(target, JSON.stringify({ accessToken: PAT }), {+ mode: 0o600,+ });+ await fs.symlink(target, configPath);+ const { readConvexCliAccessToken } = await import("./convex-cli-import");+ await expect(readConvexCliAccessToken(configPath)).rejects.toMatchObject({+ code: "unsafe_convex_cli_config",+ });+});diff --git a/lib/infra/convex-cli-import.ts b/lib/infra/convex-cli-import.tsnew file mode 100644index 00000000..29c9526c--- /dev/null+++ b/lib/infra/convex-cli-import.ts@@ -0,0 +1,94 @@+import { constants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { doctorAdditionalProvider } from "./additional-doctor";+import { credentialSnapshot, saveConnectionValues } from "./connection-service";+import { IntegrationError, type ConnectionSelector } from "./identity";++const MAX_CLI_CONFIG_BYTES = 64 * 1024;++export async function readConvexCliAccessToken(+ configPath = path.join(os.homedir(), ".convex", "config.json"),+): Promise<string> {+ const file = path.resolve(configPath),+ dir = path.dirname(file);+ let dst;+ try {+ dst = await fs.lstat(dir);+ } catch {+ throw new IntegrationError("convex_cli_config_not_found", 404);+ }+ if (+ dst.isSymbolicLink() ||+ !dst.isDirectory() ||+ (typeof process.getuid === "function" && dst.uid !== process.getuid())+ )+ throw new IntegrationError("unsafe_convex_cli_config");+ if ((dst.mode & 0o077) !== 0) await fs.chmod(dir, 0o700);+ let handle;+ try {+ handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (+ !stat.isFile() ||+ stat.nlink !== 1 ||+ stat.size < 2 ||+ stat.size > MAX_CLI_CONFIG_BYTES ||+ (typeof process.getuid === "function" && stat.uid !== process.getuid())+ )+ throw new IntegrationError("unsafe_convex_cli_config");+ if ((stat.mode & 0o077) !== 0) await handle.chmod(0o600);+ const parsed = JSON.parse(await handle.readFile("utf8")) as Record<+ string,+ unknown+ >;+ const token = parsed.accessToken;+ if (+ typeof token !== "string" ||+ token.length < 20 ||+ token.length > 8192 ||+ /[\x00-\x20\x7f]/.test(token)+ )+ throw new IntegrationError("convex_cli_access_token_missing", 409);+ return token;+ } catch (error) {+ if (error instanceof IntegrationError) throw error;+ if ((error as NodeJS.ErrnoException).code === "ELOOP")+ throw new IntegrationError("unsafe_convex_cli_config");+ throw new IntegrationError("invalid_convex_cli_config");+ } finally {+ await handle?.close();+ }+}++export async function importConvexCliPersonalConnection(+ selector: ConnectionSelector,+ options: {+ configPath?: string;+ doctor?: typeof doctorAdditionalProvider;+ } = {},+) {+ const snapshot = await credentialSnapshot("convex-cloud", selector),+ c = snapshot.connection;+ if (c.source !== "direct" || c.authMethod !== "personal")+ throw new IntegrationError("connection_auth_mismatch", 409);+ const token = await readConvexCliAccessToken(options.configPath),+ doctor = options.doctor ?? doctorAdditionalProvider;+ const detail = await doctor("convex-cloud", { personalToken: token });+ if (!detail) throw new IntegrationError("convex_cli_token_not_verified", 409);+ const connection = await saveConnectionValues(+ "convex-cloud",+ selector,+ { personalToken: token },+ { uid: c.uid, revision: c.revision },+ true,+ );+ return {+ ok: true,+ action: "connection.import-convex-cli",+ source: "convex-cli",+ permissions: { directory: "0700", file: "0600" },+ verification: detail,+ connection,+ };+}diff --git a/lib/infra/convex-cloud-core.ts b/lib/infra/convex-cloud-core.tsnew file mode 100644index 00000000..c5a3fd03--- /dev/null+++ b/lib/infra/convex-cloud-core.ts@@ -0,0 +1,127 @@+import { obj, request, TIMEOUT_MS } from "./http";+import { IntegrationError } from "./identity";++export type FetchLike = (+ input: RequestInfo | URL,+ init?: RequestInit,+) => Promise<Response>;+export type ConvexRequestDestination = "convexCloud" | "convexSite";+export type ConvexCustomDomain = {+ domain: string;+ deploymentName: string;+ requestDestination: ConvexRequestDestination;+ creationTime: number;+ verificationTime: number | null;+};+const DEPLOYMENT_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;+const HOST_RE =+ /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;++export function convexDeploymentName(value: unknown): string {+ if (typeof value !== "string")+ throw new IntegrationError("invalid_convex_deployment_name");+ const clean = value.trim().toLowerCase();+ if (!DEPLOYMENT_RE.test(clean))+ throw new IntegrationError("invalid_convex_deployment_name");+ return clean;+}+export function convexDestination(value: unknown): ConvexRequestDestination {+ if (value !== "convexCloud" && value !== "convexSite")+ throw new IntegrationError("invalid_convex_request_destination");+ return value;+}+export function convexDomainName(value: unknown): string {+ if (typeof value !== "string")+ throw new IntegrationError("invalid_convex_custom_domain");+ const clean = value.trim().toLowerCase().replace(/\.$/, "");+ if (!HOST_RE.test(clean))+ throw new IntegrationError("invalid_convex_custom_domain");+ return clean;+}+export function convexCanonicalOrigin(value: unknown): string | null {+ if (value === null || value === undefined || value === "") return null;+ if (typeof value !== "string")+ throw new IntegrationError("invalid_convex_canonical_url");+ let url: URL;+ try {+ url = new URL(value.trim());+ } catch {+ throw new IntegrationError("invalid_convex_canonical_url");+ }+ if (+ url.protocol !== "https:" ||+ url.username ||+ url.password ||+ url.search ||+ url.hash ||+ (url.pathname !== "/" && url.pathname !== "")+ )+ throw new IntegrationError("invalid_convex_canonical_url");+ return `https://${convexDomainName(url.hostname)}`;+}+export function convexAuthHeaders(token: string, scheme: "Bearer" | "Convex") {+ return {+ authorization: `${scheme} ${token}`,+ accept: "application/json",+ "content-type": "application/json",+ };+}+export function convexManagementUrl(name: string, suffix: string) {+ return `https://api.convex.dev/v1/deployments/${encodeURIComponent(convexDeploymentName(name))}/${suffix}`;+}+export function convexDeploymentUrl(name: string, suffix: string) {+ return `https://${convexDeploymentName(name)}.convex.cloud/api/v1/${suffix}`;+}+export async function convexCheckedJson(+ provider: string,+ url: string,+ init: RequestInit,+ fetchImpl: FetchLike,+): Promise<unknown> {+ let response;+ try {+ response = await request(url, init, TIMEOUT_MS, fetchImpl);+ } catch {+ throw new IntegrationError(`${provider}_request_failed`, 502);+ }+ if (!response.ok)+ throw new IntegrationError(+ `${provider}_http_${response.status}`,+ response.status >= 500 ? 502 : 409,+ );+ return response.body;+}+export function parseConvexDomains(value: unknown): ConvexCustomDomain[] {+ const rows = obj(value).domains;+ if (!Array.isArray(rows))+ throw new IntegrationError("invalid_convex_custom_domains_response", 502);+ return rows.map((raw) => {+ const row = obj(raw),+ requestDestination = convexDestination(row.requestDestination),+ domain = convexDomainName(row.domain),+ deploymentName = convexDeploymentName(row.deploymentName);+ const creationTime = Number(row.creationTime),+ verificationTime =+ row.verificationTime == null ? null : Number(row.verificationTime);+ if (+ !Number.isFinite(creationTime) ||+ (verificationTime !== null && !Number.isFinite(verificationTime))+ )+ throw new IntegrationError("invalid_convex_custom_domains_response", 502);+ return {+ domain,+ deploymentName,+ requestDestination,+ creationTime,+ verificationTime,+ };+ });+}+export function parseConvexCanonical(value: unknown) {+ const row = obj(value),+ convexCloudUrl = convexCanonicalOrigin(row.convexCloudUrl),+ convexSiteUrl = convexCanonicalOrigin(row.convexSiteUrl);+ if (!convexCloudUrl || !convexSiteUrl)+ throw new IntegrationError("invalid_convex_canonical_response", 502);+ return { convexCloudUrl, convexSiteUrl };+}diff --git a/lib/infra/convex-cloud.ts b/lib/infra/convex-cloud.tsnew file mode 100644index 00000000..54cd33ef--- /dev/null+++ b/lib/infra/convex-cloud.ts@@ -0,0 +1,8 @@+export {+ listConvexCustomDomains,+ ensureConvexCustomDomain,+} from "./convex-custom-domains";+export {+ getConvexCanonicalUrls,+ setConvexCanonicalUrl,+} from "./convex-canonical";diff --git a/lib/infra/convex-custom-domains.test.ts b/lib/infra/convex-custom-domains.test.tsnew file mode 100644index 00000000..5b0a31bd--- /dev/null+++ b/lib/infra/convex-custom-domains.test.ts@@ -0,0 +1,110 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+const PAT = "pat_synthetic_12345678901234567890";+let root: string;+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-domain-"));+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");+ vi.resetModules();+});+afterEach(async () => {+ delete process.env.OS_INFRA_STORE;+ await fs.rm(root, { recursive: true, force: true });+ vi.resetModules();+});+async function seeded() {+ const { integrationManage } = await import("./connection-manage");+ await integrationManage({+ action: "user.create",+ user: "alice",+ confirm: true,+ });+ await integrationManage({+ action: "connection.create",+ user: "alice",+ provider: "convex-cloud",+ connection: "admin",+ authMethod: "personal",+ source: "direct",+ confirm: true,+ });+ const { withIntegrationSelection } = await import("./connection-service"),+ { setInfraProvider } = await import("./store");+ await withIntegrationSelection({ user: "alice", connection: "admin" }, () =>+ setInfraProvider("convex-cloud", { personalToken: PAT }),+ );+ return withIntegrationSelection;+}+const json = (body: unknown, status = 200) =>+ new Response(body === null ? null : JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+it("idempotently creates a custom domain using the official destination contract", async () => {+ const withSelection = await seeded();+ let created = false;+ const fetchImpl = vi.fn(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ expect(new Headers(init?.headers).get("authorization")).toBe(+ `Bearer ${PAT}`,+ );+ if (url.endsWith("/custom_domains") && init?.method === "GET")+ return json({+ domains: created+ ? [+ {+ domain: "api.example.com",+ deploymentName: "happy-otter-123",+ requestDestination: "convexCloud",+ creationTime: 1,+ verificationTime: null,+ },+ ]+ : [],+ });+ if (url.endsWith("/create_custom_domain")) {+ expect(JSON.parse(String(init?.body))).toEqual({+ domain: "api.example.com",+ requestDestination: "convexCloud",+ });+ created = true;+ return json(null);+ }+ return json({ error: "unexpected" }, 500);+ },+ );+ const { ensureConvexCustomDomain } = await import("./convex-custom-domains");+ const first = await withSelection(+ { user: "alice", connection: "admin" },+ () =>+ ensureConvexCustomDomain(+ {+ deploymentName: "happy-otter-123",+ domain: "API.EXAMPLE.COM",+ requestDestination: "convexCloud",+ },+ fetchImpl,+ ),+ );+ expect(first).toMatchObject({+ changed: true,+ dns: { type: "CNAME", name: "api.example.com", content: "convex.domains" },+ });+ const second = await withSelection(+ { user: "alice", connection: "admin" },+ () =>+ ensureConvexCustomDomain(+ {+ deploymentName: "happy-otter-123",+ domain: "api.example.com",+ requestDestination: "convexCloud",+ },+ fetchImpl,+ ),+ );+ expect(second.changed).toBe(false);+ expect(JSON.stringify({ first, second })).not.toContain(PAT);+});diff --git a/lib/infra/convex-custom-domains.ts b/lib/infra/convex-custom-domains.tsnew file mode 100644index 00000000..c327eedb--- /dev/null+++ b/lib/infra/convex-custom-domains.ts@@ -0,0 +1,93 @@+import { IntegrationError } from "./identity";+import { readInfraProvider } from "./store";+import {+ convexAuthHeaders,+ convexCheckedJson,+ convexDeploymentName,+ convexDestination,+ convexDomainName,+ convexManagementUrl,+ parseConvexDomains,+ type ConvexRequestDestination,+ type FetchLike,+} from "./convex-cloud-core";++async function personalToken(): Promise<string> {+ const values = await readInfraProvider("convex-cloud"),+ token = values.personalToken;+ if (!token) throw new IntegrationError("convex_personal_token_required", 409);+ return token;+}+export async function listConvexCustomDomains(+ name: string,+ fetchImpl: FetchLike = fetch,+) {+ const deployment = convexDeploymentName(name),+ token = await personalToken();+ const body = await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "custom_domains"),+ { method: "GET", headers: convexAuthHeaders(token, "Bearer") },+ fetchImpl,+ );+ return { deploymentName: deployment, domains: parseConvexDomains(body) };+}+export async function ensureConvexCustomDomain(+ input: {+ deploymentName: string;+ domain: string;+ requestDestination: ConvexRequestDestination;+ },+ fetchImpl: FetchLike = fetch,+) {+ const deployment = convexDeploymentName(input.deploymentName),+ host = convexDomainName(input.domain),+ requestDestination = convexDestination(input.requestDestination),+ token = await personalToken();+ const beforeBody = await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "custom_domains"),+ { method: "GET", headers: convexAuthHeaders(token, "Bearer") },+ fetchImpl,+ );+ const before = parseConvexDomains(beforeBody),+ exact = before.find(+ (row) =>+ row.domain === host && row.requestDestination === requestDestination,+ );+ if (exact)+ return { changed: false, deploymentName: deployment, domain: exact };+ if (before.some((row) => row.domain === host))+ throw new IntegrationError(+ "convex_custom_domain_destination_conflict",+ 409,+ );+ await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "create_custom_domain"),+ {+ method: "POST",+ headers: convexAuthHeaders(token, "Bearer"),+ body: JSON.stringify({ domain: host, requestDestination }),+ },+ fetchImpl,+ );+ const afterBody = await convexCheckedJson(+ "convex_cloud",+ convexManagementUrl(deployment, "custom_domains"),+ { method: "GET", headers: convexAuthHeaders(token, "Bearer") },+ fetchImpl,+ );+ const created = parseConvexDomains(afterBody).find(+ (row) =>+ row.domain === host && row.requestDestination === requestDestination,+ );+ if (!created)+ throw new IntegrationError("convex_custom_domain_not_persisted", 502);+ return {+ changed: true,+ deploymentName: deployment,+ domain: created,+ dns: { type: "CNAME" as const, name: host, content: "convex.domains" },+ };+}diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.tsindex 40ace7a0..1b4f6f3b 100644--- a/lib/mcp/tools-integrations.ts+++ b/lib/mcp/tools-integrations.ts@@ -13,13 +13,13 @@ export const INTEGRATION_TOOLS:McpTool[]=[},{name:"integration_manage",title:"Manage Named Integrations",scope:"write",annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},audit:{action:"infra.write",targetArg:"user"},limit:{key:"integration.manage",max:30,windowMs:60000},description:"Manage native credential users, directory bindings and named provider connections. Actions require confirm=true. Direct credential values are forbidden: use integration_setup_open with user/provider/connection. Composio authorization keeps only external IDs/status and returns its transient URL privately to the UI. Native MCP authorization stays provider-owned.",- inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Explicit opt-in when duplicating a user; default copies metadata only."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,+ inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize","connection.import-convex-cli"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Explicit opt-in when duplicating a user; default copies metadata only."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>{const out=await manageIntegrationAction(a);if("privateUrl" in out){const{privateUrl,...safe}=out;return mcpDirect([{type:"text",text:"Authorization link available in the private integration UI."}],false,{result:safe},{integrationAuthorization:{url:privateUrl}});}return{result:out};},},{name:"integration_execute",title:"Use an Exact Integration Connection",scope:"exec",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},audit:{action:"infra.write",targetArg:"connection"},limit:{key:"integration.execute",max:30,windowMs:60000},description:"Execute using an explicit user/provider/named connection. Verify or inspect its route; bounded direct operations reject external backends. Composio tool execution requires an ACTIVE matching connected account and a toolkit-prefixed tool. Native-MCP returns the provider route without copying OAuth tokens. Non-verification operations require confirm=true. No credentials in arguments.",- inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.application.publicEnv.upsert","dokploy.project.ensure","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,+ inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.canonical.set","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await executeIntegrationAction(a)}),},];