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(infra): collapse Convex into one provider with a real self-hosted kind

rahmanef631c323375d11d
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 72876ffe..b351d720 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,17 +4,31 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → Account → About shows as “What's new”.
+## 2026-10-27
+
+**Build**
+
+- `deps` bump the actions-minor-patch group with 3 updates (#159)
+- `deps` bump the production-minor-patch group with 16 updates (#157)
+- `deps-dev` bump the test-toolchain group with 2 updates (#156)
+
+## 2026-10-26
+
+**Docs**
+
+- `license` switch to PolyForm Noncommercial and add per-repo references (#155)
+
## 2026-10-25
**Added**
- `agent` one live activity row and env-tunable turn budgets (#154)
-**Docs**
+## 2026-10-24
-- `license` switch to PolyForm Noncommercial and add per-repo references
+**Added**
-## 2026-10-24
+- `infra` collapse Convex into one provider with a real self-hosted kind
**Fixed**
@@ -1460,29 +1474,3 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- `responsive` harden mobile and landscape layouts
- `git` isolate push-gate test repositories
- `settings` improve MCP UI and activity scrolling
-
-## 2026-08-21
-
-**Added**
-
-- `projects` add opt-in function capabilities
-
-## 2026-08-20
-
-**Added**
-
-- `mcp` global project/skill discovery, drop image generation
-- `mcp` import ChatGPT generated files
-- `mcp` add provider-backed image generation
-
-**Fixed**
-
-- `mcp` lossless scan continuation and exact-id project resolution
-- `mcp` one project validator, dirent budgets, resumable caps
-- `mcp` contain, bound and uniquely identify project discovery
-- `mcp` make ChatGPT file imports region agnostic
-- `mcp` allow ChatGPT India South Central file storage
-- `mcp` allow ChatGPT New Zealand file storage
-- `mcp` allow ChatGPT Australia file storage
-- `mcp` allow ChatGPT regional file storage
-- `mcp` report rejected file host safely
diff --git a/lib/infra/additional-doctor.test.ts b/lib/infra/additional-doctor.test.ts
index 3074e7e3..218a700f 100644
--- a/lib/infra/additional-doctor.test.ts
+++ b/lib/infra/additional-doctor.test.ts
@@ -99,6 +99,25 @@ describe("additional native credential providers", () => {
await expect(result).rejects.toThrow("Convex HTTP 403");
await expect(result).rejects.not.toThrow(KEY);
});
+ it("distinguishes an unreachable self-hosted deployment from a rejected admin key", async () => {
+ // curl exit 35: the TCP/TLS connection produced no HTTP response at all.
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("fetch failed"); }));
+ const unreachable = doctorAdditionalProvider("convex", { apiUrl: "http://localhost:3210", adminKey: KEY });
+ await expect(unreachable).rejects.toThrow(/unreachable.*no HTTP response/i);
+ await expect(unreachable).rejects.not.toThrow(KEY);
+ // Reachable, but the deployment rejected the key.
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));
+ const rejected = doctorAdditionalProvider("convex", { apiUrl: "http://localhost:3210", adminKey: KEY });
+ await expect(rejected).rejects.toThrow(/admin key rejected/i);
+ await expect(rejected).rejects.toThrow("Convex HTTP 401");
+ await expect(rejected).rejects.not.toThrow(KEY);
+ // The two operator actions must not collapse into one message.
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("fetch failed"); }));
+ const first = await doctorAdditionalProvider("convex", { apiUrl: "http://localhost:3210", adminKey: KEY }).catch((error: Error) => error.message);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 403 })));
+ const second = await doctorAdditionalProvider("convex", { apiUrl: "http://localhost:3210", adminKey: KEY }).catch((error: Error) => error.message);
+ expect(first).not.toBe(second);
+ });
it("rejects arbitrary Convex targets before sending any key", async () => {
const mock = vi.fn(); vi.stubGlobal("fetch", mock);
for (const apiUrl of ["http://169.254.169.254/", "https://owner:[email protected]", "https://example.com/?credential=x"])
diff --git a/lib/infra/additional-doctor.ts b/lib/infra/additional-doctor.ts
index d1e8307c..edae43cd 100644
--- a/lib/infra/additional-doctor.ts
+++ b/lib/infra/additional-doctor.ts
@@ -1,46 +1,12 @@
import { listMcpServerTools } from "@/lib/host/project-mcp-client";
import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "./mcp-policy";
-import { safeProviderFetch } from "@/lib/host/ssrf";
import { obj, request, TIMEOUT_MS } from "./http";
+import { canonicalProviderId } from "./catalog";
+import { doctorConvex } from "./convex-doctor";
import { doctorDoku } from "./doku-doctor";
-const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
-
-function present(value: string | undefined): value is string {
- return typeof value === "string" && value.trim().length > 0;
-}
-
-/** A bounded SSRF-safe transport for an explicitly configured Convex endpoint. */
-function convexFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
- const requestInput = new Request(input, { ...init, redirect: "error" });
- const host = new URL(requestInput.url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
- if (LOOPBACK_HOSTS.has(host)) return fetch(requestInput);
- return safeProviderFetch(requestInput);
-}
-
-function selfHostedAdminKeyCheckUrl(rawUrl: string): string {
- let url: URL;
- try {
- url = new URL(rawUrl.trim());
- } catch {
- throw new Error("Convex invalid deployment URL");
- }
- if (url.username || url.password || url.search || url.hash) throw new Error("Convex invalid deployment URL");
- const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
- if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(host))) {
- throw new Error("Convex invalid deployment URL");
- }
- url.pathname = "/api/check_admin_key";
- return url.toString();
-}
-
-function cloudDeploymentInfoUrl(name: string): string {
- const clean = name.trim().toLowerCase();
- // Deployment names are hostname labels, not URLs. This keeps the request fixed
- // to Convex Cloud and avoids accepting an attacker-controlled authority.
- if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(clean)) throw new Error("Convex Cloud invalid deployment name");
- return `https://${clean}.convex.cloud/api/v1/deployment_info`;
-}
+const present = (value: string | undefined): value is string =>
+ typeof value === "string" && value.trim().length > 0;
async function checked(provider: string, url: string, headers: HeadersInit, fetchImpl?: typeof fetch): Promise<Awaited<ReturnType<typeof request>>> {
let response;
@@ -50,7 +16,6 @@ async function checked(provider: string, url: string, headers: HeadersInit, fetc
return response;
}
-
function countRows(body: unknown): number {
if (Array.isArray(body)) return body.length;
const value = obj(body);
@@ -64,7 +29,9 @@ function countRows(body: unknown): number {
* checked endpoint, not every permission needed by a later operation.
*/
export async function doctorAdditionalProvider(id: string, values: Record<string, string>): Promise<string | null> {
- switch (id) {
+ // `convex-cloud` is the pre-collapse id; it resolves to the one Convex doctor.
+ const provider = canonicalProviderId(id);
+ switch (provider) {
case "mcp": {
if (!present(values.endpoint) || !present(values.accessToken)) return null;
const url = normalizeMcpEndpoint(values.endpoint);
@@ -177,26 +144,9 @@ export async function doctorAdditionalProvider(id: string, values: Record<string
}
case "doku":
return doctorDoku(values);
- case "convex-cloud": {
- const deployKey = values.deployKey;
- const deploymentName = values.deploymentName;
- if (present(deployKey) || present(deploymentName)) {
- if (!present(deployKey) || !present(deploymentName)) return null;
- await checked("Convex Cloud", cloudDeploymentInfoUrl(deploymentName), { authorization: `Convex ${deployKey}`, accept: "application/json" });
- return "authenticated; deployment access verified";
- }
- // The official OpenAPI explicitly declares PAT authentication here.
- // Discard token inventory immediately; only authentication status escapes.
- if (present(values.personalToken)) {
- await checked("Convex Cloud", "https://api.convex.dev/v1/list_personal_access_tokens?limit=1", { authorization: `Bearer ${values.personalToken}`, accept: "application/json" });
- return "personal access token authenticated; account read access verified";
- }
- return null;
- }
case "convex": {
- if (!present(values.apiUrl) || !present(values.adminKey)) return null;
- await checked("Convex", selfHostedAdminKeyCheckUrl(values.apiUrl), { authorization: `Convex ${values.adminKey}`, accept: "application/json" }, convexFetch);
- return "authenticated; deployment access verified";
+ // One provider, two shapes. Read the kind from the values, not from the id.
+ return doctorConvex(values);
}
default:
throw new Error("unknown additional provider");
diff --git a/lib/infra/additional-providers.test.ts b/lib/infra/additional-providers.test.ts
new file mode 100644
index 00000000..542d12c7
--- /dev/null
+++ b/lib/infra/additional-providers.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { ADDITIONAL_GUIDANCE, ADDITIONAL_PROVIDERS } from "./additional-providers";
+import { getInfraProviderDefinition } from "./catalog";
+import { INFRA_PROVIDER_IDS } from "./types";
+import { setupFields, setupMethods } from "./setup-guidance";
+
+describe("one Convex provider definition", () => {
+ it("is a single entry that accepts BOTH credential shapes", () => {
+ expect(Object.keys(ADDITIONAL_PROVIDERS).filter((id) => id.includes("convex"))).toEqual(["convex"]);
+ const fields = getInfraProviderDefinition("convex").fields;
+ const keys = fields.map((field) => field.key);
+ // Cloud shape + self-hosted shape live in ONE schema.
+ expect(keys).toEqual(["deploymentKind", "personalToken", "deployKey", "deploymentName", "apiUrl", "adminKey"]);
+ expect(fields.filter((field) => field.secret).map((field) => field.key)).toEqual(["personalToken", "deployKey", "adminKey"]);
+ expect(fields.find((field) => field.key === "deploymentKind")?.secret).toBe(false);
+ });
+
+ it("keeps the existing method ids so a connection still declares HOW it authenticates", () => {
+ expect(setupMethods("convex").map((method) => method.id)).toEqual(["personal", "deployment", "admin"]);
+ expect(setupFields("convex", "personal").map((field) => field.key)).toEqual(["personalToken"]);
+ expect(setupFields("convex", "deployment").map((field) => field.key)).toEqual(["deployKey", "deploymentName"]);
+ expect(setupFields("convex", "admin").map((field) => field.key)).toEqual(["apiUrl", "adminKey"]);
+ expect(() => setupFields("convex", "organization")).toThrow();
+ });
+
+ it("is the only convex id in the provider list, with a read alias for the old one", () => {
+ expect(INFRA_PROVIDER_IDS.filter((id) => id.startsWith("convex"))).toEqual(["convex"]);
+ // Guidance exists for the surviving id, not the retired one.
+ expect(ADDITIONAL_GUIDANCE).toHaveProperty("convex");
+ expect(ADDITIONAL_GUIDANCE).not.toHaveProperty("convex-cloud");
+ expect(ADDITIONAL_GUIDANCE.convex.steps.length).toBeGreaterThan(1);
+ });
+});
diff --git a/lib/infra/additional-providers.ts b/lib/infra/additional-providers.ts
index 7433a103..7d55d8dd 100644
--- a/lib/infra/additional-providers.ts
+++ b/lib/infra/additional-providers.ts
@@ -44,25 +44,20 @@ export const ADDITIONAL_PROVIDERS = {
feature: false,
fields: [{ key: "teamId", label: "Team ID", secret: false, required: false, description: "Optional connection-specific configuration; retained during JSON transfer." }, { key: "apiKey", label: "API token", secret: true, required: true, description: "A Vercel API token. Access is limited by the token owner and any team permissions." }],
},
- "convex-cloud": {
- id: "convex-cloud",
- title: "Convex Cloud",
- description: "Store a Convex Cloud personal token or verify a deployment key for a named deployment.",
+ convex: {
+ id: "convex",
+ title: "Convex",
+ description: "One Convex provider for both deployment kinds: Convex Cloud (personal token or deployment key) and self-hosted (deployment URL + admin key).",
feature: false,
fields: [
+ // Non-secret routing fact, never a credential. Legacy rows omit it and are
+ // inferred from apiUrl at read time (catalog.convexDeploymentKind).
+ { key: "deploymentKind", label: "Deployment kind", secret: false, required: false, placeholder: "cloud", description: "cloud or self-hosted. Optional and non-secret: it is inferred as self-hosted when a deployment URL is stored, cloud otherwise." },
{ key: "personalToken", label: "Personal access token", secret: true, required: false, description: "Convex Cloud personal access token. Validated through the PAT-authenticated read-only account endpoint." },
{ key: "deployKey", label: "Deployment key", secret: true, required: false, description: "Convex deployment key used with the deployment name below." },
{ key: "deploymentName", label: "Deployment name", secret: false, required: false, description: "Convex deployment hostname prefix. Required together with a deployment key; method-specific requirements are enforced by the UI." },
- ],
- },
- convex: {
- id: "convex",
- title: "Self-hosted Convex",
- description: "Verify a self-hosted Convex deployment using its admin key.",
- feature: false,
- fields: [
- { key: "apiUrl", label: "Deployment URL", secret: false, required: true, description: "HTTPS deployment URL; HTTP is allowed only for a loopback deployment on this VPS." },
- { key: "adminKey", label: "Admin key", secret: true, required: true, description: "Convex admin key for this deployment." },
+ { key: "apiUrl", label: "Self-hosted deployment URL", secret: false, required: false, description: "HTTPS deployment URL; HTTP is allowed only for a loopback deployment on this VPS." },
+ { key: "adminKey", label: "Self-hosted admin key", secret: true, required: false, description: "Convex admin key for this deployment." },
],
},
resend: {
@@ -187,8 +182,7 @@ export const ADDITIONAL_GUIDANCE = {
mcp: { url: "https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization", reference: "https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization", steps: ["Sign in to the target application's account that the assistant should use.", "Create a dedicated expiring MCP token with the least required scope. For Baton: Settings → External access → MCP → Advanced token management.", "Enter the exact MCP URL and token only in this private MSO form. Set an optional exact tool allowlist.", "Bind the project MCP declaration to this named MSO user/connection; MSO verifies tool discovery, while the downstream server enforces its token identity and live project roles."] },
github: { url: "https://github.com/settings/personal-access-tokens/new", reference: "https://docs.github.com/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens", steps: ["Prefer GitHub OAuth from the Integrations connection source picker. Use this manual token path only when an explicit direct fallback is required.", "Open GitHub fine-grained token settings while signed in to the intended account.", "Set an expiry and grant only the intended repositories and minimum permissions. Use a classic token only when the required operation cannot be expressed with a fine-grained token.", "Copy the token once into this private form. This connection never substitutes for an OAuth/provider-MCP identity and organization policy can still limit access."] },
vercel: { url: "https://vercel.com/account/tokens", reference: "https://vercel.com/docs/rest-api#creating-an-access-token", steps: ["Open Account Settings → Tokens in Vercel.", "Create a token with an expiry appropriate for this integration.", "Use the account or team that owns the intended Vercel resources.", "Copy the token into this form; its permissions are determined by that account or team membership."] },
- "convex-cloud": { url: "https://dashboard.convex.dev", reference: "https://docs.convex.dev/management-api", steps: ["Open the Convex dashboard for the intended account or deployment.", "Create the personal access token or deployment key appropriate to the operation you intend to perform.", "For a deployment key, also enter its exact deployment name.", "Copy the credential once and keep it scoped to the minimum needed access."] },
- convex: { url: "https://docs.convex.dev/self-hosting", reference: "https://docs.convex.dev/self-hosting", steps: ["Open the administration settings for your self-hosted Convex deployment.", "Generate an admin key using the official self-hosting instructions; never use a cloud project key for a different deployment.", "Enter the deployment's HTTPS URL; loopback HTTP is only suitable for a deployment on this VPS.", "Copy the admin key into this form and restrict network access to the deployment." ] },
+ convex: { url: "https://docs.convex.dev/self-hosting", reference: "https://docs.convex.dev/self-hosting", steps: ["Choose the deployment kind first: a Convex Cloud deployment (personal access token or deployment key + name) or a self-hosted deployment (URL + admin key).", "For Convex Cloud, open the dashboard for the intended account or deployment and copy the personal access token or deployment key.", "For a self-hosted deployment, open its administration settings and generate an admin key using the official self-hosting instructions; never reuse a cloud project key for a different deployment.", "Enter the deployment's HTTPS URL (loopback HTTP is only suitable for a deployment on this VPS) and copy the credential once, scoped to the minimum needed access."] },
resend: { url: "https://resend.com/api-keys", reference: "https://resend.com/docs/dashboard/api-keys/introduction", steps: ["Open API Keys in the Resend dashboard.", "Create a key for the intended environment.", "Choose Full access only when domain management is required. Sending-only keys cannot pass the domain-list check.", "Copy the key once; verified domains and account policy still control sending access."] },
stripe: { url: "https://dashboard.stripe.com/apikeys", reference: "https://docs.stripe.com/keys", steps: ["Open Developers → API keys in the intended Stripe account.", "Use a restricted key when its available permissions cover the integration.", "Confirm whether you are using test or live mode before copying the secret key.", "Copy the key once and rotate it promptly if it is exposed."] },
clerk: { url: "https://dashboard.clerk.com", reference: "https://clerk.com/docs/guides/development/api-keys", steps: ["Open the intended Clerk instance in the Clerk dashboard.", "Find its secret key in the API Keys or Developers settings.", "Keep the key server-side and limit access to the intended instance.", "Copy it into this form; this check only confirms Backend API authentication."] },
diff --git a/lib/infra/catalog.ts b/lib/infra/catalog.ts
index 6010982c..a8dc9cee 100644
--- a/lib/infra/catalog.ts
+++ b/lib/infra/catalog.ts
@@ -1,7 +1,7 @@
import { GOOGLE_PROVIDERS, GOOGLE_APP_PROVIDER, isGoogleProvider, normalizeGoogleConfig } from "./google-native-config";
import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "./mcp-policy";
import { ADDITIONAL_PROVIDERS, type AdditionalProviderId } from "./additional-providers";
-import { INFRA_PROVIDER_IDS, type InfraProviderDefinition, type InfraProviderId, type InfraProviderValues } from "./types";
+import { CONVEX_DEPLOYMENT_KINDS, CONVEX_LEGACY_PROVIDER_ID, INFRA_PROVIDER_IDS, type ConvexDeploymentKind, type InfraProviderDefinition, type InfraProviderId, type InfraProviderValues } from "./types";
const additional = Object.fromEntries(Object.entries(ADDITIONAL_PROVIDERS).map(([id, value]) => [id, { ...value, fields: value.fields.map(f => ({ ...f })) }])) as Record<AdditionalProviderId, InfraProviderDefinition>;
const google = Object.fromEntries(GOOGLE_PROVIDERS.map(p => [p.id, p])) as Record<"google-oauth-app" | "google-search-console" | "google-analytics", InfraProviderDefinition>;
@@ -54,7 +54,55 @@ const definitions: Record<InfraProviderId, InfraProviderDefinition> = {
};
export const isInfraProviderId = (value: string): value is InfraProviderId =>
- (INFRA_PROVIDER_IDS as readonly string[]).includes(value);
+ (INFRA_PROVIDER_IDS as readonly string[]).includes(value) || value === CONVEX_LEGACY_PROVIDER_ID;
+
+/**
+ * The ONE place the retired `convex-cloud` id becomes `convex`. Every read path
+ * (store lookup, dispatch, registry, summaries) funnels through here, so a stored
+ * `connections["convex-cloud"]` row and a legacy `providers["convex-cloud"]` row
+ * keep resolving after the collapse. Write paths never produce the alias.
+ */
+export const canonicalProviderId = (value: string): string =>
+ value === CONVEX_LEGACY_PROVIDER_ID ? "convex" : value;
+/** Same mapping, but narrows to InfraProviderId and rejects unknown ids. */
+export const resolveProviderId = (value: string): InfraProviderId | null => {
+ const id = canonicalProviderId(value);
+ return isInfraProviderId(id) ? id : null;
+};
+
+/**
+ * A stored connection's deployment kind, at READ time. A legacy row has no
+ * `deploymentKind`: presence of `apiUrl` means self-hosted, anything else means
+ * cloud. Unknown stored values degrade to cloud — never a third kind, and never a
+ * throw on a list response. Write paths reject unknown values in
+ * `normalizeInfraValues`, which is where the explicit enum check lives.
+ */
+export function convexDeploymentKind(values: Record<string, string>): ConvexDeploymentKind {
+ const declared = values.deploymentKind;
+ if (declared === "self-hosted" || declared === "cloud") return declared;
+ return values.apiUrl ? "self-hosted" : "cloud";
+}
+export function isConvexDeploymentKind(value: unknown): value is ConvexDeploymentKind {
+ return typeof value === "string" && (CONVEX_DEPLOYMENT_KINDS as readonly string[]).includes(value);
+}
+
+/** Secret keys a Convex connection may carry. Values move between THESE keys only. */
+export const CONVEX_SECRET_KEYS = ["personalToken", "deployKey", "adminKey"] as const;
+const CONVEX_PUBLIC_KEYS = ["deploymentName", "apiUrl"] as const;
+
+/**
+ * The exact value projection used when a legacy `convex-cloud` row becomes a
+ * `convex` row: declared secret keys keep their values, declared non-secret keys
+ * keep theirs, and `deploymentKind` is derived from the credential SHAPE. No
+ * value is ever copied into a field that is not already a schema field.
+ */
+export function convexMigratedValues(values: Record<string, string>): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const key of CONVEX_SECRET_KEYS) if (values[key]) out[key] = values[key];
+ for (const key of CONVEX_PUBLIC_KEYS) if (values[key]) out[key] = values[key];
+ out.deploymentKind = values.apiUrl ? "self-hosted" : "cloud";
+ return out;
+}
export const getInfraProviderDefinition = (id: InfraProviderId): InfraProviderDefinition => definitions[id];
export const listInfraProviderDefinitions = (): InfraProviderDefinition[] => INFRA_PROVIDER_IDS.map((id) => definitions[id]);
@@ -62,8 +110,10 @@ export const listInfraProviderDefinitions = (): InfraProviderDefinition[] => INF
const IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
const HEX32_RE = /^[0-9a-f]{32}$/i;
-export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, unknown>): InfraProviderValues {
- const def = definitions[id];
+export function normalizeInfraValues(id: InfraProviderId | string, raw: Record<string, unknown>): InfraProviderValues {
+ const provider = resolveProviderId(id);
+ if (!provider) throw new Error("unknown infrastructure provider");
+ const def = definitions[provider];
const allowed = new Set(def.fields.map((field) => field.key));
const out: InfraProviderValues = {};
for (const [key, value] of Object.entries(raw)) {
@@ -72,7 +122,7 @@ export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, un
if (clean.length > 4096 || /[\x00-\x1f\x7f]/.test(clean)) throw new Error("Invalid integration field format");
if (clean) out[key] = clean;
}
- if (id === "dokploy" && out.apiUrl) {
+ if (provider === "dokploy" && out.apiUrl) {
let parsed: URL;
try { parsed = new URL(out.apiUrl); } catch { throw new Error("Dokploy API URL must be an absolute http(s) URL"); }
if (parsed.username || parsed.password) throw new Error("Dokploy API URL must not contain credentials");
@@ -88,54 +138,61 @@ export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, un
if (out.apiKey && out.apiKey.length < 20) throw new Error("Dokploy API key is too short");
if (out.publicIp && !IPV4_RE.test(out.publicIp)) throw new Error("Dokploy publicIp must be a valid IPv4 address");
}
- if (id === "cloudflare") {
+ if (provider === "cloudflare") {
if (out.apiToken && out.apiToken.length < 24) throw new Error("Cloudflare API token is too short");
if (out.zoneId && !HEX32_RE.test(out.zoneId)) throw new Error("Cloudflare zoneId must be 32 hexadecimal characters");
if (out.accountId && out.accountId.length < 16) throw new Error("Cloudflare accountId is too short");
}
- if (id === "composio") {
+ if (provider === "composio") {
for (const value of Object.values(out)) if (value.length < 16 || value.length > 4096 || /[\s\x00-\x1f\x7f]/.test(value)) throw new Error("Composio keys must be opaque single-line values (16–4096 characters)");
}
- if (id === "convex-cloud" && out.deploymentName && !/^[a-z0-9][a-z0-9-]{1,62}$/.test(out.deploymentName)) throw new Error("Invalid deployment name");
- if (id === "convex" && out.apiUrl) {
- let url: URL; try { url = new URL(out.apiUrl); } catch { throw new Error("Invalid deployment URL"); }
- if (url.username || url.password || url.search || url.hash || (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) throw new Error("Invalid deployment URL");
+ if (provider === "convex") {
+ // One provider, both shapes. deploymentKind is a closed enum and never a
+ // credential; reject anything else rather than inferring a third value.
+ // Field-level only: normalizeInfraValues sees partial updates (a single
+ // rotated key), so cross-field shape coherence belongs to the doctor.
+ if (out.deploymentKind !== undefined && !isConvexDeploymentKind(out.deploymentKind)) throw new Error("Convex deploymentKind must be cloud or self-hosted");
+ if (out.deploymentName && !/^[a-z0-9][a-z0-9-]{1,62}$/.test(out.deploymentName)) throw new Error("Invalid deployment name");
+ if (out.apiUrl) {
+ let url: URL; try { url = new URL(out.apiUrl); } catch { throw new Error("Invalid deployment URL"); }
+ if (url.username || url.password || url.search || url.hash || (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) throw new Error("Invalid deployment URL");
+ }
}
- if (id === "mcp") {
+ if (provider === "mcp") {
if (out.endpoint) out.endpoint = normalizeMcpEndpoint(out.endpoint);
if (out.accessToken && (out.accessToken.length < 16 || /\s/.test(out.accessToken))) throw new Error("MCP token must be an opaque single-line value");
parseMcpToolAllowlist(out.allowedTools);
}
- if (id === "telegram") {
+ if (provider === "telegram") {
if (out.botToken && !/^\d{5,16}:[A-Za-z0-9_-]{20,}$/.test(out.botToken)) throw new Error("Telegram bot token format is invalid");
if (out.webhookSecret && !/^[A-Za-z0-9_-]{1,256}$/.test(out.webhookSecret)) throw new Error("Telegram webhook secret must use only letters, digits, underscore or hyphen");
}
- if (id === "discord") {
+ if (provider === "discord") {
if (out.botToken && (out.botToken.length < 24 || out.botToken.length > 256 || /[\s\x00-\x1f\x7f]/.test(out.botToken))) throw new Error("Discord bot token format is invalid");
if (out.applicationId && !/^\d{15,22}$/.test(out.applicationId)) throw new Error("Discord applicationId must be a snowflake");
if (out.publicKey && !/^[0-9a-f]{64}$/i.test(out.publicKey)) throw new Error("Discord publicKey must be 64 hexadecimal characters");
}
- if (id === "doku") {
+ if (provider === "doku") {
for(const key of ["environment","paymentEnvironment"])if(out[key]&&!["sandbox","production"].includes(out[key]))throw new Error("DOKU environment must be sandbox or production");
for(const key of ["paymentClientId","mcpClientId"])if(out[key]&&(out[key].length<3||out[key].length>256||/[\s\x00-\x1f\x7f]/.test(out[key])))throw new Error("DOKU Client ID must be an opaque single-line value");
for(const key of ["paymentSecretKey","mcpApiKey"])if(out[key]&&(out[key].length<8||/[\s\x00-\x1f\x7f]/.test(out[key])))throw new Error("DOKU secret/API key must be an opaque single-line value");
}
- if (id === "openai-app") {
+ if (provider === "openai-app") {
if (out.appId) {
const normalized = out.appId.startsWith("plugin_asdk_app_") ? out.appId.slice("plugin_".length) : out.appId;
if (normalized.startsWith("asdk_app_v_") || !/^asdk_app_[A-Za-z0-9][A-Za-z0-9_-]*$/.test(normalized)) throw new Error("OpenAI App ID must be canonical asdk_app_… or browser URL form plugin_asdk_app_…");
out.appId = normalized;
}
}
- if (id === "hostinger") {
+ if (provider === "hostinger") {
if (out.apiToken && out.apiToken.length < 24) throw new Error("Hostinger API token is too short");
if (out.mailApiToken && out.mailApiToken.length < 24) throw new Error("Hostinger Mail API token is too short");
if (out.mailOrderId && !/^[A-Za-z0-9._-]{3,128}$/.test(out.mailOrderId)) throw new Error("Invalid Hostinger Mail order ID");
}
- if (id === "linear") {
+ if (provider === "linear") {
// Personal API keys are opaque single-line values; the doctor proves the rest.
if (out.apiKey && (out.apiKey.length < 20 || out.apiKey.length > 4096 || /[\s\x00-\x1f\x7f]/.test(out.apiKey))) throw new Error("Linear API key must be an opaque single-line value (20–4096 characters)");
}
- if (id === GOOGLE_APP_PROVIDER || isGoogleProvider(id)) return normalizeGoogleConfig(id, out);
+ if (provider === GOOGLE_APP_PROVIDER || isGoogleProvider(id)) return normalizeGoogleConfig(id, out);
return out;
}
diff --git a/lib/infra/connection-dispatch-convex.test.ts b/lib/infra/connection-dispatch-convex.test.ts
new file mode 100644
index 00000000..3a18c15d
--- /dev/null
+++ b/lib/infra/connection-dispatch-convex.test.ts
@@ -0,0 +1,99 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+
+/**
+ * Issue #152, acceptance criterion 5: on the self-hosted kind NO operation may
+ * silently 404. Every Convex operation must either run or be refused by NAME with
+ * a machine-readable reason the UI can grey out.
+ */
+
+let root = "";
+let execute: typeof import("./connection-dispatch").executeIntegrationAction;
+
+const CLOUD_PAT = "pat_synthetic_cloud_dispatch_1234567";
+const ADMIN_KEY = "synthetic_self_hosted_admin_dispatch_1234";
+const operations = ["convex.customDomains.list", "convex.customDomain.ensure", "convex.canonical.get", "convex.canonical.set", "convex.env.presence", "convex.project.deploy", "convex.snapshot.import"];
+
+async function seed(user: string, connection: string, method: string, values: Record<string, string>) {
+ const { integrationManage } = await import("./connection-manage");
+ const service = await import("./connection-service");
+ const { readIntegrationState } = await import("./connection-storage");
+ if (!(await readIntegrationState()).users[user])
+ await integrationManage({ action: "user.create", confirm: true, user });
+ await integrationManage({ action: "connection.create", confirm: true, user, provider: "convex", connection, authMethod: method, source: "direct" });
+ const snapshot = await service.credentialSnapshot("convex", { user, connection });
+ await service.saveConnectionValues("convex", { user, connection }, values, snapshot.connection, true);
+}
+
+beforeAll(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-dispatch-"));
+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");
+ // Kind is INFERRED from shape: apiUrl ⇒ self-hosted, otherwise cloud. That is
+ // the same rule a pre-collapse row relies on.
+ await seed("cloud", "admin", "personal", { personalToken: CLOUD_PAT });
+ await seed("cloud", "prod", "deployment", { deployKey: "prod:happy-otter-123|synthetic_cloud_dispatch_key_123", deploymentName: "happy-otter-123" });
+ await seed("self", "self", "admin", { apiUrl: "https://api.internal.example", adminKey: ADMIN_KEY });
+ execute = (await import("./connection-dispatch")).executeIntegrationAction;
+});
+
+afterAll(async () => {
+ delete process.env.OS_INFRA_STORE;
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+const args: Record<string, Record<string, unknown>> = {
+ "convex.customDomains.list": { deploymentName: "happy-otter-123" },
+ "convex.customDomain.ensure": { deploymentName: "happy-otter-123", domain: "api.example.test", requestDestination: "convexCloud" },
+ "convex.canonical.get": { deploymentName: "happy-otter-123" },
+ "convex.canonical.set": { deploymentName: "happy-otter-123", requestDestination: "convexCloud", url: null },
+ "convex.env.presence": { deploymentName: "happy-otter-123", names: ["AUTH_SECRET"] },
+ "convex.project.deploy": { deploymentName: "happy-otter-123", projectPath: "/srv/project" },
+ "convex.snapshot.import": { deploymentName: "happy-otter-123", projectPath: "/srv/project", snapshotPath: "/tmp/s.zip", mode: "append" },
+};
+
+async function attempt(user: string, connection: string, operation: string) {
+ try {
+ await execute({ user, provider: "convex", connection, operation, confirm: true, arguments: args[operation] });
+ return { ran: true as const };
+ } catch (error) {
+ const value = error as Error & { code?: string; operation?: string; deploymentKind?: string; reason?: string | null; status?: number };
+ return { ran: false as const, code: value.code, message: value.message, operation: value.operation, deploymentKind: value.deploymentKind, reason: value.reason, status: value.status };
+ }
+}
+
+describe("self-hosted Convex operations never silently 404", () => {
+ it.each(operations)("classifies %s for the self-hosted kind", async (operation) => {
+ const outcome = await attempt("self", "self", operation);
+ // Either it genuinely ran, or it is refused EXPLICITLY for this kind.
+ if (!outcome.ran) {
+ expect(outcome.code).toBe("convex_operation_unsupported_for_kind");
+ expect(outcome.status).toBe(409);
+ expect(outcome.operation).toBe(operation);
+ expect(outcome.deploymentKind).toBe("self-hosted");
+ expect(outcome.reason?.length).toBeGreaterThan(0);
+ // Never the old silent failure mode.
+ expect(outcome.code).not.toBe("provider_operation_mismatch");
+ expect(outcome.message).not.toMatch(/404|not_found/);
+ }
+ });
+
+ it("does not refuse the same operations for the cloud kind by kind-gating", async () => {
+ // Cloud is expected to reach the real runner (which fails on the fake
+ // deployment), never the kind gate.
+ for (const operation of operations) {
+ const outcome = await attempt("cloud", "admin", operation);
+ expect(outcome.ran || outcome.code !== "convex_operation_unsupported_for_kind").toBe(true);
+ }
+ });
+
+ it("keeps the alias id working for dispatch", async () => {
+ const outcome = await attempt("cloud", "admin", "convex.customDomains.list");
+ // The only thing that matters here: the retired provider id is not rejected
+ // as an unknown/mismatched provider.
+ expect(outcome.ran || (outcome.code !== "provider_operation_mismatch")).toBe(true);
+ });
+});
diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.ts
index dcdab958..79e8c32c 100644
--- a/lib/infra/connection-dispatch.ts
+++ b/lib/infra/connection-dispatch.ts
@@ -8,8 +8,9 @@ import { callComposioConnectTool, listComposioConnectTools } from "./composio-co
import { IntegrationError, identity, metadataOnly, type ConnectionSelector } from "./identity";
import { importConvexCliPersonalConnection } from "./convex-cli-import";
import { listConvexCustomDomains, ensureConvexCustomDomain, getConvexCanonicalUrls, setConvexCanonicalUrl, getConvexEnvPresence, deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud";
+import { CONVEX_OPERATION_SUPPORT } from "./types";
import { doctorInfraProvider, ensureDokployProject, listDokployApplications, listDokployDeployments, readDokployDeploymentLogs, listDokployGitProviders, listDokployGithubRepositories, ensureDokployGithubApplication, ensureDokployApplicationDomain, recoverDokployPublicGithubToHttpsGit, deployDokployApplication, configureDokployDockerfileBuild, listDokployProjects, listCloudflareZones, upsertCloudflareDns, upsertDokployPublicBuildEnv, upsertHostingerDns, listHostingerMailOrders, getHostingerMailPlan, listHostingerMail, listHostingerMailLogs, mutateHostingerMail } from "./clients";
-import { isInfraProviderId } from "./catalog";
+import { isInfraProviderId, canonicalProviderId, resolveProviderId, convexDeploymentKind } from "./catalog";
import { callNamedMcpConnectionTool, listNamedMcpConnectionTools } from "./mcp-connection";
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});
@@ -22,7 +23,7 @@ export async function manageIntegrationAction(raw:Record<string,unknown>){
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");
+ if(a.provider!=="convex"&&a.provider!=="convex-cloud")throw new IntegrationError("provider_operation_mismatch");
return importConvexCliPersonalConnection(selectionFrom(a));
}
if(a.action==="connection.authorize"&&isGoogleProvider(String(a.provider))){
@@ -53,10 +54,11 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){
}else metadataOnly(a);
if(Object.keys(a).some(k=>!["user","provider","connection","operation","arguments","tool","confirm"].includes(k)))throw new IntegrationError("invalid_execution_fields");
const user=identity(a.user,"user"),provider=identity(a.provider,"provider"),connection=identity(a.connection,"connection"),selection={user,connection};
+ const canonical=canonicalProviderId(provider);
const route=await resolveIntegration(provider,selection);
if(operation==="route")return route;
if(operation==="verify"&&(isGoogleProvider(provider)||provider===GOOGLE_APP_PROVIDER))return nativeGoogleStatus(provider,selection);
- if(operation==="verify")return withIntegrationSelection(selection,()=>{if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider");return doctorInfraProvider(provider);});
+ if(operation==="verify")return withIntegrationSelection(selection,()=>{if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider");return doctorInfraProvider(resolveProviderId(provider)!);});
if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);
const args=a.arguments??{};if(!args||typeof args!=="object"||Array.isArray(args))throw new IntegrationError("invalid_tool_arguments");
if(isGoogleProvider(provider)){
@@ -81,13 +83,13 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){
"dokploy.dockerfile":{provider:"dokploy",fields:["applicationId","dockerfile","dockerContextPath"],run:()=>configureDokployDockerfileBuild(args as {applicationId:string;dockerfile?:string;dockerContextPath?:string})},
"dokploy.application.publicEnv.upsert":{provider:"dokploy",fields:["applicationId","key","value","redeploy"],run:()=>upsertDokployPublicBuildEnv(args as {applicationId:string;key:string;value:string;redeploy?:boolean})},
"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.env.presence":{provider:"convex-cloud",fields:["deploymentName","names"],run:()=>getConvexEnvPresence(args as {deploymentName:string;names:string[]})},
- "convex.canonical.set":{provider:"convex-cloud",fields:["deploymentName","requestDestination","url"],run:()=>setConvexCanonicalUrl(args as {deploymentName:string;requestDestination:"convexCloud"|"convexSite";url?:string|null})},
- "convex.project.deploy":{provider:"convex-cloud",fields:["deploymentName","projectPath"],run:()=>deployConvexCloudProject(args as {deploymentName:string;projectPath:string})},
- "convex.snapshot.import":{provider:"convex-cloud",fields:["deploymentName","projectPath","snapshotPath","mode"],run:()=>importConvexCloudSnapshot(args as {deploymentName:string;projectPath:string;snapshotPath:string;mode:"replace-all"|"append"})},
+ "convex.customDomains.list":{provider:"convex",fields:["deploymentName"],run:()=>listConvexCustomDomains(String((args as Record<string,unknown>).deploymentName))},
+ "convex.customDomain.ensure":{provider:"convex",fields:["deploymentName","domain","requestDestination"],run:()=>ensureConvexCustomDomain(args as {deploymentName:string;domain:string;requestDestination:"convexCloud"|"convexSite"})},
+ "convex.canonical.get":{provider:"convex",fields:["deploymentName"],run:()=>getConvexCanonicalUrls(String((args as Record<string,unknown>).deploymentName))},
+ "convex.env.presence":{provider:"convex",fields:["deploymentName","names"],run:()=>getConvexEnvPresence(args as {deploymentName:string;names:string[]})},
+ "convex.canonical.set":{provider:"convex",fields:["deploymentName","requestDestination","url"],run:()=>setConvexCanonicalUrl(args as {deploymentName:string;requestDestination:"convexCloud"|"convexSite";url?:string|null})},
+ "convex.project.deploy":{provider:"convex",fields:["deploymentName","projectPath"],run:()=>deployConvexCloudProject(args as {deploymentName:string;projectPath:string})},
+ "convex.snapshot.import":{provider:"convex",fields:["deploymentName","projectPath","snapshotPath","mode"],run:()=>importConvexCloudSnapshot(args as {deploymentName:string;projectPath:string;snapshotPath:string;mode:"replace-all"|"append"})},
"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])},
@@ -100,9 +102,24 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){
"mcp.tool":{provider:"mcp",fields:["name","arguments"],run:()=>callNamedMcpConnectionTool(selection,String((args as Record<string,unknown>).name??""),((args as Record<string,unknown>).arguments&&typeof (args as Record<string,unknown>).arguments==="object"&&!Array.isArray((args as Record<string,unknown>).arguments)?(args as Record<string,unknown>).arguments:{} ) as Record<string,unknown>)},
};
- const verb=verbs[operation];if(!verb||verb.provider!==provider)throw new IntegrationError("provider_operation_mismatch");
+ const verb=verbs[operation];if(!verb||verb.provider!==canonical)throw new IntegrationError("provider_operation_mismatch");
if(route.source!=="direct")throw new IntegrationError("external_source_requires_own_executor",409);
if(Object.keys(args).some(k=>!verb.fields.includes(k)))throw new IntegrationError("invalid_tool_arguments");
+ // Self-hosted Convex shares the provider id but not every operation. Refuse the
+ // ones CONVEX_OPERATION_SUPPORT marks unsupported for this kind by NAME instead
+ // of letting the runner fail obscurely or the operation disappear as a 404.
+ if(canonical==="convex"){
+ const support=CONVEX_OPERATION_SUPPORT.find(row=>row.operation===operation);
+ if(support){
+ const kind=convexDeploymentKind(await directConnectionValues(canonical,selection));
+ const availability=kind==="self-hosted"?support.selfHosted:support.cloud;
+ if(availability!=="supported"){
+ const error=new IntegrationError("convex_operation_unsupported_for_kind",409);
+ Object.assign(error,{operation,deploymentKind:kind,reason:support.reason??null});
+ throw error;
+ }
+ }
+ }
return withIntegrationSelection(selection,async()=>({identity:route,result:await verb.run()}));
}
export const queryIntegrationAction=(input:Record<string,unknown>)=>integrationQuery(safeActionInput(input));
diff --git a/lib/infra/connection-registry.test.ts b/lib/infra/connection-registry.test.ts
index faf17402..fada4c46 100644
--- a/lib/infra/connection-registry.test.ts
+++ b/lib/infra/connection-registry.test.ts
@@ -1,5 +1,7 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { connectionCatalog, connectionMethods, connectionSources } from "./connection-registry";
+import { canonicalProviderId, convexDeploymentKind, normalizeInfraValues, resolveProviderId } from "./catalog";
+import { INFRA_PROVIDER_IDS, CONVEX_OPERATION_SUPPORT } from "./types";
describe("integration connection registry", () => {
it("presents GitHub OAuth routes before the explicit manual token fallback", () => {
@@ -16,4 +18,87 @@ describe("integration connection registry", () => {
it("does not reorder unrelated providers", () => {
expect(connectionSources("vercel")).toEqual(["direct", "composio", "native-mcp"]);
});
+
+ it("collapses Convex to ONE provider id, keeping every pre-collapse method", () => {
+ const ids = [...INFRA_PROVIDER_IDS];
+ expect(ids.filter((id) => id === "convex")).toHaveLength(1);
+ expect(ids).not.toContain("convex-cloud");
+ // One catalog entry, and its methods still declare HOW it authenticates.
+ const rows = connectionCatalog().filter((row) => row.id === "convex");
+ expect(rows).toHaveLength(1);
+ expect(rows[0].sources.find((s) => s.id === "direct")!.methods.map((m) => m.id)).toEqual(["personal", "deployment", "admin"]);
+ });
+
+ it("resolves the convex-cloud alias to convex in exactly one place", () => {
+ expect(canonicalProviderId("convex-cloud")).toBe("convex");
+ expect(canonicalProviderId("convex")).toBe("convex");
+ expect(canonicalProviderId("dokploy")).toBe("dokploy");
+ expect(resolveProviderId("convex-cloud")).toBe("convex");
+ expect(resolveProviderId("not-a-provider")).toBeNull();
+ // The alias is readable but is NOT advertised as a provider id.
+ expect(INFRA_PROVIDER_IDS).not.toContain("convex-cloud");
+ });
+
+ it("validates deploymentKind as a closed enum and rejects a third value", () => {
+ expect(normalizeInfraValues("convex", { deploymentKind: "cloud", personalToken: "pat_synthetic_1234567890" }).deploymentKind).toBe("cloud");
+ expect(normalizeInfraValues("convex", { deploymentKind: "self-hosted", apiUrl: "https://api.example.test", adminKey: "synthetic_admin_key_123456" }).deploymentKind).toBe("self-hosted");
+ expect(() => normalizeInfraValues("convex", { deploymentKind: "cloudy" })).toThrow(/deploymentKind/);
+ expect(() => normalizeInfraValues("convex", { deploymentKind: "" })).not.toThrow();
+ });
+
+ it("infers the kind from apiUrl when deploymentKind is absent", () => {
+ // Legacy rows predate the field entirely.
+ expect(convexDeploymentKind({ apiUrl: "https://api.example.test", adminKey: "k" })).toBe("self-hosted");
+ expect(convexDeploymentKind({ personalToken: "pat" })).toBe("cloud");
+ expect(convexDeploymentKind({ deployKey: "key", deploymentName: "happy-otter-123" })).toBe("cloud");
+ // An explicit value wins over the inference, and no third kind is invented.
+ expect(convexDeploymentKind({ deploymentKind: "cloud", apiUrl: "https://api.example.test" })).toBe("cloud");
+ expect(convexDeploymentKind({ deploymentKind: "bogus" })).toBe("cloud");
+ });
+
+ it("persists the non-secret kind on write and keeps the credential secret", async () => {
+ const { promises: fs } = await import("node:fs");
+ const os = await import("node:os");
+ const path = await import("node:path");
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-kind-"));
+ const previous = process.env.OS_INFRA_STORE;
+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");
+ vi.resetModules();
+ try {
+ const { setInfraProvider, readInfraProvider } = await import("./store");
+ const ADMIN = "synthetic_self_hosted_admin_key_123456";
+ await setInfraProvider("convex", { apiUrl: "https://api.example.test", adminKey: ADMIN });
+ expect(await readInfraProvider("convex")).toMatchObject({ deploymentKind: "self-hosted", adminKey: ADMIN });
+ // The derived kind is non-secret; the admin key is still stored as a secret
+ // field and never surfaces through the summary.
+ const { summarizeInfraProvider } = await import("./store");
+ const summary = summarizeInfraProvider("convex", await readInfraProvider("convex"));
+ expect(summary.values.apiUrl).toBe("https://api.example.test");
+ expect(JSON.stringify(summary)).not.toContain(ADMIN);
+ } finally {
+ if (previous === undefined) delete process.env.OS_INFRA_STORE; else process.env.OS_INFRA_STORE = previous;
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("classifies every Convex operation for BOTH deployment kinds", () => {
+ for (const row of CONVEX_OPERATION_SUPPORT) {
+ expect(["supported", "unsupported"]).toContain(row.cloud);
+ expect(["supported", "unsupported"]).toContain(row.selfHosted);
+ // Nothing silently disappears: an unsupported kind always carries a reason.
+ if (row.cloud === "unsupported" || row.selfHosted === "unsupported") expect(row.reason?.length).toBeGreaterThan(0);
+ // The cloud kind keeps every operation it had before the collapse.
+ expect(row.cloud).toBe("supported");
+ }
+ // Every operation the dispatcher knows is classified; no silent 404 path.
+ expect(CONVEX_OPERATION_SUPPORT.map((row) => row.operation).sort()).toEqual([
+ "convex.canonical.get",
+ "convex.canonical.set",
+ "convex.customDomain.ensure",
+ "convex.customDomains.list",
+ "convex.env.presence",
+ "convex.project.deploy",
+ "convex.snapshot.import",
+ ]);
+ });
});
diff --git a/lib/infra/connection-registry.ts b/lib/infra/connection-registry.ts
index a045ad33..fa9ccee4 100644
--- a/lib/infra/connection-registry.ts
+++ b/lib/infra/connection-registry.ts
@@ -1,8 +1,20 @@
import { GOOGLE_READ_OPERATIONS } from "./google-api-catalog";
import { isGoogleProvider, GOOGLE_APP_PROVIDER, googleRedirectUri, googlePublicOrigin } from "./google-native-config";
-import { listInfraProviderDefinitions, getInfraProviderDefinition, isInfraProviderId } from "./catalog";
+import { canonicalProviderId, convexDeploymentKind, listInfraProviderDefinitions, getInfraProviderDefinition, resolveProviderId } from "./catalog";
import { setupFields, setupGuidance, setupMethods, type SetupMethod } from "./setup-guidance";
import { IntegrationError, type ConnectionSource, type IntegrationConnection } from "./identity";
+/** Convex keeps every pre-collapse method id; `admin` is the self-hosted shape. */
+const CONVEX_METHODS = ["personal", "deployment", "admin"] as const;
+/**
+ * The stored method id for a values bag, used by the legacy projection and
+ * credential deletion. Inference matches `convexDeploymentKind`: an `apiUrl`
+ * means the self-hosted (`admin`) shape even on a row that predates the field.
+ */
+export function convexMethod(values: Record<string, string>): SetupMethod {
+ if (convexDeploymentKind(values) === "self-hosted") return "admin";
+ return values.deployKey || values.deploymentName ? "deployment" : "personal";
+}
+export const convexMethods = () => [...CONVEX_METHODS];
const COMPOSIO: Record<string, {toolkit:string; managed:boolean; methods:string[]}> = {
github:{toolkit:"github",managed:true,methods:["oauth2"]}, vercel:{toolkit:"vercel",managed:false,methods:["oauth2","api-key"]},
cloudflare:{toolkit:"cloudflare",managed:false,methods:["api-key"]}, resend:{toolkit:"resend",managed:false,methods:["api-key"]},
@@ -14,19 +26,28 @@ const NATIVE: Record<string,{url:string;reference:string}> = {
supabase:{url:"https://mcp.supabase.com/mcp",reference:"https://supabase.com/docs/guides/getting-started/mcp"},
};
export function providerDefinition(provider:string) {
- if (!isInfraProviderId(provider)) throw new IntegrationError("unknown_provider",404);
- return getInfraProviderDefinition(provider);
+ const id = resolveProviderId(provider);
+ if (!id) throw new IntegrationError("unknown_provider",404);
+ return getInfraProviderDefinition(id);
}
export function connectionMethods(provider:string, source:ConnectionSource) {
- const p=providerDefinition(provider);
- if(source==="direct") return setupMethods(p.id).map(m=>({id:m.id as string,label:provider==="github"?"Personal access token fallback":m.label,scope:provider===GOOGLE_APP_PROVIDER?"client-configuration":isGoogleProvider(provider)?"read-only-account":provider==="convex-cloud"?(m.id==="deployment"?"deployment":"account"):provider==="composio"?m.id:provider==="dokploy"?"server":provider==="hostinger"&&m.id==="mail"?"mail-order":provider==="doku"?"merchant":"account",fields:setupFields(p.id,m.id),guidance:setupGuidance(p.id,m.id)}));
+ const p=providerDefinition(provider), id=p.id;
+ if(source==="direct") return setupMethods(p.id).map(m=>({id:m.id as string,label:provider==="github"?"Personal access token fallback":m.label,scope:id===GOOGLE_APP_PROVIDER?"client-configuration":isGoogleProvider(id)?"read-only-account":id==="convex"?(m.id==="admin"?"self-hosted":m.id==="deployment"?"deployment":"account"):id==="composio"?m.id:id==="dokploy"?"server":id==="hostinger"&&m.id==="mail"?"mail-order":id==="doku"?"merchant":"account",fields:setupFields(p.id,m.id),guidance:setupGuidance(p.id,m.id)}));
if(source==="composio" && COMPOSIO[provider]) return COMPOSIO[provider].methods.map(id=>({id,label:id==="oauth2"?"OAuth2":"Hosted API key",scope:"account",fields:[],guidance:{url:"https://platform.composio.dev",reference:`https://docs.composio.dev/toolkits/${COMPOSIO[provider].toolkit}`,steps:["Configure a Composio project key under this same credential user.","Choose a matching authentication configuration for this provider and method.","Open the hosted authorization link. Enter credentials only on the provider/Composio page.","Return and refresh status. MSO stores routing identifiers, not provider OAuth tokens."]}}));
if(source==="native-mcp" && NATIVE[provider])return[{id:"provider-oauth",label:"Provider-owned MCP / OAuth",scope:"account",fields:[],guidance:{url:NATIVE[provider].reference,reference:NATIVE[provider].reference,steps:["Connect the provider-owned MCP server in your client.","Complete authorization in that provider's browser flow.","Use this named MSO connection to identify the intended provider route; the authenticated MCP session remains client-owned.","MSO does not copy provider access/refresh tokens or silently fall back to a local key."]}}];
throw new IntegrationError("unsupported_connection_source");
}
export function connectionMethod(provider:string,source:ConnectionSource,method?:string){
- const methods=connectionMethods(provider,source), selected=method?methods.find(m=>m.id===method):methods[0];
- if(!selected)throw new IntegrationError("unsupported_auth_method");return selected;
+ // A caller may still hold the retired convex id; resolve it before any lookup.
+ const canonical=canonicalProviderId(provider), methods=connectionMethods(canonical,source);
+ const selected=method?methods.find(m=>m.id===method):methods[0];
+ if(selected)return selected;
+ // A store written before the collapse recorded the self-hosted Convex row as
+ // authMethod "direct". Keep that stored id readable WITHOUT advertising a fourth
+ // method in the picker — setupMethods stays the advertised list.
+ if(canonical==="convex"&&source==="direct"&&method==="direct")
+ return {id:"direct",label:"Self-hosted Convex (legacy) direct credential",scope:"self-hosted",fields:setupFields(canonical,"direct"),guidance:setupGuidance(canonical,"direct")};
+ throw new IntegrationError("unsupported_auth_method");
}
export function connectionSources(provider:string){
const oauthFirst = provider === "github";
@@ -46,7 +67,7 @@ export function connectionSummary(user:string,c:IntegrationConnection,isDefault=
export const composioDefinition=(provider:string)=>COMPOSIO[provider];
export const nativeDefinition=(provider:string)=>NATIVE[provider];
export function legacyMethod(provider:string,values:Record<string,string>):SetupMethod {
- return provider==="composio"?(values.orgApiKey?"organization":"project"):provider==="convex-cloud"?(values.deployKey?"deployment":"personal"):provider==="doku"?(values.paymentClientId||values.paymentSecretKey?"payment":"mcp"):"direct";
+ return provider==="composio"?(values.orgApiKey?"organization":"project"):canonicalProviderId(provider)==="convex"?convexMethod(values):provider==="doku"?(values.paymentClientId||values.paymentSecretKey?"payment":"mcp"):"direct";
}
function googleCatalogInfo(provider:string){
diff --git a/lib/infra/connection-storage.ts b/lib/infra/connection-storage.ts
index e8e4d163..91704c22 100644
--- a/lib/infra/connection-storage.ts
+++ b/lib/infra/connection-storage.ts
@@ -7,7 +7,7 @@ import path from "node:path";
import os from "node:os";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import { connectionMethod, legacyMethod } from "./connection-registry";
-import { isInfraProviderId } from "./catalog";
+import { canonicalProviderId, isInfraProviderId } from "./catalog";
import { emptyIntegrationState, IntegrationError, identity, type IntegrationState, type IntegrationConnection } from "./identity";
export const INFRA_STORE_PATH=expandOwnerStorePath(process.env.OS_INFRA_STORE??path.join(os.homedir(),".mso","private","infra-providers.json"));
const MAX=1024*1024;
@@ -34,8 +34,8 @@ function projected(raw:Record<string,unknown>|undefined):IntegrationState{
const profile={id:"legacy",uid:"legacy",label:"Existing MSO credentials",defaults:{} as Record<string,string>,connections:{} as Record<string,Record<string,IntegrationConnection>>};
for(const [provider,v] of Object.entries(providers)){
if(!isInfraProviderId(provider)||!v||typeof v!=="object"||Array.isArray(v)||Object.values(v).some(x=>typeof x!=="string"))throw new IntegrationError("legacy_migration_requires_review");
- const values=v as Record<string,string>;const selected=legacyMethod(provider,values);
- const methods=provider==="composio"?[...(values.apiKey?["project"]:[]),...(values.orgApiKey?["organization"]:[])]:provider==="convex-cloud"?[...(values.personalToken?["personal"]:[]),...(values.deployKey||values.deploymentName?["deployment"]:[])]:provider==="doku"?[...(values.paymentClientId||values.paymentSecretKey?["payment"]:[]),...(values.mcpClientId||values.mcpApiKey?["mcp"]:[])]:["direct"];
+ const values=v as Record<string,string>;const selected=legacyMethod(provider,values),convex=canonicalProviderId(provider)==="convex";
+ const methods=provider==="composio"?[...(values.apiKey?["project"]:[]),...(values.orgApiKey?["organization"]:[])]:convex?[...(values.apiUrl?["admin"]:[]),...(values.personalToken?["personal"]:[]),...(values.deployKey||values.deploymentName?["deployment"]:[])]:provider==="doku"?[...(values.paymentClientId||values.paymentSecretKey?["payment"]:[]),...(values.mcpClientId||values.mcpApiKey?["mcp"]:[])]:["direct"];
if(!methods.length)methods.push(selected);
profile.connections[provider]={};
for(const method of methods){const def=connectionMethod(provider,"direct",method),id=methods.length===1?"default":method;
@@ -51,6 +51,7 @@ async function write(d:IntegrationState){
const temp=`${INFRA_STORE_PATH}.${randomUUID()}.tmp`;try{await fs.writeFile(temp,text,{mode:0o600,flag:"wx"});await fs.rename(temp,INFRA_STORE_PATH);}finally{await fs.unlink(temp).catch(()=>{});}
}
export async function readIntegrationState(){return projected((await readRaw())?.raw);}
+
export async function mutateIntegrationState<T>(fn:(d:IntegrationState)=>T|Promise<T>):Promise<T>{
return withSecurityStoreLock(INFRA_STORE_PATH,async()=>{const previous=await readRaw(),d=projected(previous?.raw);const out=await fn(d);
if(previous&&previous.raw.version!==2){
diff --git a/lib/infra/convex-doctor.ts b/lib/infra/convex-doctor.ts
new file mode 100644
index 00000000..948b6237
--- /dev/null
+++ b/lib/infra/convex-doctor.ts
@@ -0,0 +1,84 @@
+import { safeProviderFetch } from "@/lib/host/ssrf";
+import { request, TIMEOUT_MS } from "./http";
+
+/**
+ * Convex has ONE provider and two credential shapes. The doctor therefore picks
+ * its probe from the stored SHAPE, never from a provider id:
+ * - `apiUrl` present ⇒ self-hosted deployment (admin key at /api/check_admin_key)
+ * - otherwise ⇒ Convex Cloud (deployment key + name, or a personal access token)
+ *
+ * "Deployment unreachable" and "admin key rejected" are deliberately different
+ * messages: an operator fixes a different thing in each case. `Convex HTTP <status>`
+ * is preserved so the existing connection-health classifier still reads `invalid`.
+ */
+
+const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
+
+const present = (value: string | undefined): value is string =>
+ typeof value === "string" && value.trim().length > 0;
+
+/** A bounded SSRF-safe transport for an explicitly configured Convex endpoint. */
+function convexFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const requestInput = new Request(input, { ...init, redirect: "error" });
+ const host = new URL(requestInput.url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ if (LOOPBACK_HOSTS.has(host)) return fetch(requestInput);
+ return safeProviderFetch(requestInput);
+}
+
+export function selfHostedAdminKeyCheckUrl(rawUrl: string): string {
+ let url: URL;
+ try { url = new URL(rawUrl.trim()); } catch { throw new Error("Convex invalid deployment URL"); }
+ if (url.username || url.password || url.search || url.hash) throw new Error("Convex invalid deployment URL");
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(host)))
+ throw new Error("Convex invalid deployment URL");
+ url.pathname = "/api/check_admin_key";
+ return url.toString();
+}
+
+function cloudDeploymentInfoUrl(name: string): string {
+ const clean = name.trim().toLowerCase();
+ // Deployment names are hostname labels, not URLs. This keeps the request fixed
+ // to Convex Cloud and avoids accepting an attacker-controlled authority.
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(clean)) throw new Error("Convex Cloud invalid deployment name");
+ return `https://${clean}.convex.cloud/api/v1/deployment_info`;
+}
+
+async function checked(provider: string, url: string, headers: HeadersInit, fetchImpl?: typeof fetch) {
+ let response;
+ try { response = await request(url, { headers }, TIMEOUT_MS, fetchImpl); }
+ catch { throw new Error(`${provider} request failed`); }
+ if (!response.ok) throw new Error(`${provider} HTTP ${response.status}`);
+ return response;
+}
+
+async function checkedSelfHosted(url: string, headers: HeadersInit) {
+ let response;
+ try { response = await request(url, { headers }, TIMEOUT_MS, convexFetch); }
+ catch { throw new Error("Convex deployment unreachable: no HTTP response (DNS, TLS or connection failed)"); }
+ if (response.status === 401 || response.status === 403) throw new Error(`Convex HTTP ${response.status}; deployment reachable, admin key rejected`);
+ if (!response.ok) throw new Error(`Convex HTTP ${response.status}`);
+ return response;
+}
+
+export async function doctorConvex(values: Record<string, string>): Promise<string | null> {
+ // Self-hosted first: a stored deployment URL is the unambiguous shape marker,
+ // and it is also the inference a pre-collapse row relies on.
+ if (values.apiUrl) {
+ if (!present(values.adminKey)) return null;
+ await checkedSelfHosted(selfHostedAdminKeyCheckUrl(values.apiUrl), { authorization: `Convex ${values.adminKey}`, accept: "application/json" });
+ return "authenticated; deployment access verified";
+ }
+ if (present(values.deployKey) || present(values.deploymentName)) {
+ if (!present(values.deployKey) || !present(values.deploymentName)) return null;
+ await checked("Convex Cloud", cloudDeploymentInfoUrl(values.deploymentName), { authorization: `Convex ${values.deployKey}`, accept: "application/json" });
+ return "authenticated; deployment access verified";
+ }
+ // The official OpenAPI explicitly declares PAT authentication here. Only
+ // authentication status escapes; the token inventory is discarded.
+ if (present(values.personalToken)) {
+ await checked("Convex Cloud", "https://api.convex.dev/v1/list_personal_access_tokens?limit=1", { authorization: `Bearer ${values.personalToken}`, accept: "application/json" });
+ return "personal access token authenticated; account read access verified";
+ }
+ return null;
+}
diff --git a/lib/infra/convex-migrate.test.ts b/lib/infra/convex-migrate.test.ts
new file mode 100644
index 00000000..575e16e4
--- /dev/null
+++ b/lib/infra/convex-migrate.test.ts
@@ -0,0 +1,193 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * Acceptance criterion 2: a pre-existing `convex-cloud` connection survives the
+ * provider collapse with its secret still usable and the operator re-entering
+ * nothing. Every assertion below is about behaviour — the migration never prints,
+ * returns, or re-encrypts a credential value.
+ */
+
+const PAT = "pat_synthetic_migration_1234567890";
+const DEPLOY_KEY = "prod:happy-otter-123|synthetic_migration_key_123456";
+const ADMIN_KEY = "synthetic_self_hosted_admin_key_123456";
+let root = "", file = "", original = "";
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-migrate-"));
+ file = path.join(root, "infra.json");
+ process.env.OS_INFRA_STORE = file;
+ vi.resetModules();
+ // A store written BEFORE the collapse: connections still live under
+ // "convex-cloud", and the file carries no `deploymentKind` anywhere.
+ original = JSON.stringify({
+ version: 2,
+ instanceId: "synthetic-instance",
+ defaultUser: "alice",
+ users: {
+ alice: {
+ id: "alice", uid: "alice-uid", label: "Alice",
+ defaults: { "convex-cloud": "admin" },
+ connections: {
+ "convex-cloud": {
+ admin: {
+ id: "admin", uid: "uid-admin", label: "Admin", provider: "convex-cloud", source: "direct",
+ authMethod: "personal", scope: "account", revision: 3, values: { personalToken: PAT },
+ createdAt: 10, updatedAt: 20, verifiedAt: 30,
+ },
+ prod: {
+ id: "prod", uid: "uid-prod", label: "Prod", provider: "convex-cloud", source: "direct",
+ authMethod: "deployment", scope: "deployment", revision: 1,
+ values: { deployKey: DEPLOY_KEY, deploymentName: "happy-otter-123" },
+ createdAt: 11, updatedAt: 21, lastCheck: { revision: 1, checkedAt: 40, result: "verified" },
+ },
+ },
+ },
+ },
+ bob: {
+ id: "bob", uid: "bob-uid", label: "Bob",
+ defaults: {},
+ connections: {
+ "convex-cloud": {
+ self: {
+ id: "self", uid: "uid-self", label: "Self-hosted", provider: "convex-cloud", source: "direct",
+ authMethod: "direct", scope: "account", revision: 1,
+ values: { apiUrl: "https://api.internal.example", adminKey: ADMIN_KEY },
+ createdAt: 12, updatedAt: 22,
+ },
+ },
+ },
+ },
+ },
+ bindings: [{ path: "/srv/project", user: "alice", connections: { "convex-cloud": "prod" } }],
+ }, null, 2);
+ await fs.writeFile(file, original, { mode: 0o600 });
+});
+
+afterEach(async () => {
+ delete process.env.OS_INFRA_STORE;
+ await fs.rm(root, { recursive: true, force: true });
+ vi.resetModules();
+});
+
+async function migrate() {
+ return import("./convex-migrate");
+}
+
+describe("convex forward migration", () => {
+ it("moves every legacy row into the one convex provider and keeps the secret usable", async () => {
+ const { migrateConvexConnections } = await migrate();
+ const plan = await migrateConvexConnections();
+ expect(plan.changed).toBe(true);
+ expect(plan.conflicts).toEqual([]);
+
+ const { readIntegrationState } = await import("./connection-storage");
+ const state = await readIntegrationState();
+ const alice = state.users.alice.connections.convex;
+ expect(Object.keys(alice).sort()).toEqual(["admin", "prod"]);
+ // The secret VALUE survives, byte for byte, and is never re-entered.
+ expect(alice.admin.values.personalToken).toBe(PAT);
+ expect(alice.prod.values.deployKey).toBe(DEPLOY_KEY);
+ expect(alice.prod.values.deploymentName).toBe("happy-otter-123");
+ // Identity and history are preserved, not reset.
+ expect(alice.admin).toMatchObject({ id: "admin", uid: "uid-admin", label: "Admin", provider: "convex", revision: 3, createdAt: 10, updatedAt: 20, verifiedAt: 30 });
+ expect(alice.prod.lastCheck).toEqual({ revision: 1, checkedAt: 40, result: "verified" });
+ // The self-hosted row keeps its own shape and is marked as such.
+ expect(state.users.bob.connections.convex.self.values).toEqual({ apiUrl: "https://api.internal.example", adminKey: ADMIN_KEY, deploymentKind: "self-hosted" });
+ expect(alice.admin.values.deploymentKind).toBe("cloud");
+ expect(alice.prod.authMethod).toBe("deployment");
+ expect(state.users.bob.connections.convex.self.authMethod).toBe("admin");
+ });
+
+ it("carries defaults and folder bindings to the canonical provider", async () => {
+ const { migrateConvexConnections } = await migrate();
+ await migrateConvexConnections();
+ const { readIntegrationState } = await import("./connection-storage");
+ const state = await readIntegrationState();
+ expect(state.users.alice.defaults.convex).toBe("admin");
+ expect(state.users.alice.defaults["convex-cloud"]).toBeUndefined();
+ expect(state.bindings[0].connections).toEqual({ convex: "prod" });
+ });
+
+ it("is idempotent: a second run changes nothing", async () => {
+ const { migrateConvexConnections } = await migrate();
+ await migrateConvexConnections();
+ const first = await fs.readFile(file, "utf8");
+ const second = await migrateConvexConnections();
+ expect(second.changed).toBe(false);
+ expect(second.entries).toEqual([]);
+ expect(await fs.readFile(file, "utf8")).toBe(first);
+ });
+
+ it("dry run reports the plan and writes absolutely nothing", async () => {
+ const { dryRunConvexMigration } = await migrate();
+ const plan = await dryRunConvexMigration();
+ expect(plan.applicable).toBe(true);
+ expect(plan.entries.map((entry) => [entry.user, entry.connection, entry.deploymentKind])).toEqual([
+ ["alice", "admin", "cloud"],
+ ["alice", "prod", "cloud"],
+ ["bob", "self", "self-hosted"],
+ ]);
+ // Secret KEY NAMES only — the credential itself never enters the report.
+ expect(plan.entries[0].secretKeys).toEqual(["personalToken"]);
+ expect(JSON.stringify(plan)).not.toContain(PAT);
+ expect(JSON.stringify(plan)).not.toContain(DEPLOY_KEY);
+ expect(JSON.stringify(plan)).not.toContain(ADMIN_KEY);
+ // The stored bytes did not move.
+ expect(await fs.readFile(file, "utf8")).toBe(original);
+ });
+
+ it("reports a conflict instead of overwriting either row", async () => {
+ const { mutateIntegrationState } = await import("./connection-storage");
+ await mutateIntegrationState((state) => {
+ state.users.alice.connections.convex = {
+ prod: {
+ id: "prod", uid: "uid-existing", label: "Existing", provider: "convex", source: "direct",
+ authMethod: "deployment", scope: "deployment", revision: 1,
+ values: { deployKey: "synthetic_existing_key_1234567890", deploymentName: "other-deployment" },
+ createdAt: 5, updatedAt: 6,
+ },
+ };
+ });
+ const { dryRunConvexMigration, migrateConvexConnections } = await migrate();
+ const plan = await dryRunConvexMigration();
+ expect(plan.applicable).toBe(false);
+ expect(plan.conflicts.map((row) => [row.user, row.connection])).toEqual([["alice", "prod"]]);
+
+ await expect(migrateConvexConnections()).rejects.toMatchObject({ code: "convex_migration_conflict" });
+
+ // Neither side was touched: the existing `convex` row is intact and the
+ // legacy row is still where the operator left it.
+ const { readIntegrationState } = await import("./connection-storage");
+ const state = await readIntegrationState();
+ expect(state.users.alice.connections.convex.prod.values.deploymentName).toBe("other-deployment");
+ expect(state.users.alice.connections["convex-cloud"].prod.values.deploymentName).toBe("happy-otter-123");
+ });
+
+ it("never runs implicitly at import time and never reaches the network", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ // Importing the module alone must not read or write the store.
+ await migrate();
+ expect(await fs.readFile(file, "utf8")).toBe(original);
+ expect(fetchMock).not.toHaveBeenCalled();
+ const { migrateConvexConnections } = await migrate();
+ await migrateConvexConnections();
+ expect(fetchMock).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+
+ it("never writes a credential into the non-secret deploymentKind field", async () => {
+ const { migrateConvexConnections } = await migrate();
+ await migrateConvexConnections();
+ const { readIntegrationState } = await import("./connection-storage");
+ const state = await readIntegrationState();
+ for (const profile of Object.values(state.users)) {
+ for (const row of Object.values(profile.connections.convex ?? {})) {
+ expect(["cloud", "self-hosted"]).toContain(row.values.deploymentKind);
+ }
+ }
+ });
+});
diff --git a/lib/infra/convex-migrate.ts b/lib/infra/convex-migrate.ts
new file mode 100644
index 00000000..4f881844
--- /dev/null
+++ b/lib/infra/convex-migrate.ts
@@ -0,0 +1,130 @@
+import { readIntegrationState, mutateIntegrationState } from "./connection-storage";
+import { convexMigratedValues } from "./catalog";
+import type { IntegrationConnection, IntegrationState } from "./identity";
+import { CONVEX_LEGACY_PROVIDER_ID, type ConvexDeploymentKind } from "./types";
+
+/**
+ * Forward migration for issue #152: fold every stored `convex-cloud` connection
+ * into the single `convex` provider, WITHOUT re-entering a secret.
+ *
+ * Contract:
+ * - explicit — nothing runs at import time and nothing is scheduled;
+ * - offline — no network call, ever. A migration that reaches the network cannot
+ * be retried safely after a partial write;
+ * - secret-safe — a value moves only between keys the provider schema declares,
+ * and `deploymentKind` is derived from the credential SHAPE (does an `apiUrl`
+ * exist?), never from a credential value;
+ * - idempotent — a second run finds no `convex-cloud` rows and reports
+ * `changed: false`, so it writes nothing;
+ * - conflict-reporting — when both provider keys already hold the same connection
+ * id, neither row is overwritten and the pair is reported for an operator.
+ */
+
+export type ConvexMigrationEntry = {
+ user: string;
+ connection: string;
+ /** Secret KEY NAMES that will move. Never a secret value. */
+ secretKeys: string[];
+ deploymentKind: ConvexDeploymentKind;
+ action: "move" | "conflict";
+};
+export type ConvexMigrationConflict = ConvexMigrationEntry & { action: "conflict" };
+export type ConvexMigrationPlan = {
+ changed: boolean;
+ /** `true` when the plan can be applied without an operator decision. */
+ applicable: boolean;
+ entries: ConvexMigrationEntry[];
+ conflicts: ConvexMigrationConflict[];
+};
+
+const SECRET_KEYS = ["personalToken", "deployKey", "adminKey"] as const;
+
+function legacyRows(state: IntegrationState) {
+ const out: { user: string; rows: Record<string, IntegrationConnection> }[] = [];
+ for (const [user, profile] of Object.entries(state.users)) {
+ const rows = profile.connections?.[CONVEX_LEGACY_PROVIDER_ID];
+ if (rows && Object.keys(rows).length) out.push({ user, rows });
+ }
+ return out;
+}
+
+export function planConvexMigration(state: IntegrationState | null): ConvexMigrationPlan {
+ if (!state) return { changed: false, applicable: true, entries: [], conflicts: [] };
+ const entries: ConvexMigrationEntry[] = [];
+ for (const { user, rows } of legacyRows(state)) {
+ const existing = state.users[user]?.connections.convex ?? {};
+ for (const [connection, row] of Object.entries(rows)) {
+ const values = row.values ?? {};
+ entries.push({
+ user,
+ connection,
+ secretKeys: SECRET_KEYS.filter((key) => Boolean(values[key])),
+ deploymentKind: values.apiUrl ? "self-hosted" : "cloud",
+ action: Object.hasOwn(existing, connection) ? "conflict" : "move",
+ });
+ }
+ }
+ const conflicts = entries.filter((entry): entry is ConvexMigrationConflict => entry.action === "conflict");
+ return { changed: entries.length > 0, applicable: conflicts.length === 0, entries, conflicts };
+}
+
+/** Dry run: reports what WOULD move. Reads only; writes nothing. */
+export async function dryRunConvexMigration(): Promise<ConvexMigrationPlan> {
+ return planConvexMigration(await readIntegrationState());
+}
+
+/**
+ * Apply the migration. Refuses as a whole when any conflict is present, because a
+ * partial fold could silently drop one of the two colliding connections.
+ */
+export async function migrateConvexConnections(): Promise<ConvexMigrationPlan> {
+ const before = planConvexMigration(await readIntegrationState());
+ if (!before.changed) return before;
+ if (!before.applicable)
+ throw Object.assign(new Error("convex_migration_conflict"), {
+ code: "convex_migration_conflict",
+ status: 409,
+ conflicts: before.conflicts,
+ });
+ return mutateIntegrationState((state) => {
+ const plan = planConvexMigration(state);
+ for (const entry of plan.entries) {
+ const profile = state.users[entry.user];
+ const row = profile?.connections[CONVEX_LEGACY_PROVIDER_ID]?.[entry.connection];
+ if (!profile || !row) continue;
+ const values = convexMigratedValues(row.values);
+ profile.connections.convex = {
+ ...(profile.connections.convex ?? {}),
+ [entry.connection]: {
+ ...row,
+ id: entry.connection,
+ provider: "convex",
+ authMethod: values.deploymentKind === "self-hosted" ? "admin" : row.authMethod === "deployment" ? "deployment" : "personal",
+ values,
+ },
+ };
+ if (profile.defaults[CONVEX_LEGACY_PROVIDER_ID] === entry.connection && !profile.defaults.convex)
+ profile.defaults.convex = entry.connection;
+ }
+ // Drop the legacy key only when every row moved. A leftover row is a conflict,
+ // already refused above, so this cannot silently lose a connection.
+ for (const profile of Object.values(state.users)) {
+ const rows = profile.connections[CONVEX_LEGACY_PROVIDER_ID];
+ if (!rows) continue;
+ const remaining = Object.fromEntries(Object.entries(rows).filter(([id]) => !profile.connections.convex?.[id]));
+ if (Object.keys(remaining).length) profile.connections[CONVEX_LEGACY_PROVIDER_ID] = remaining;
+ else delete profile.connections[CONVEX_LEGACY_PROVIDER_ID];
+ if (!profile.connections[CONVEX_LEGACY_PROVIDER_ID] && profile.defaults[CONVEX_LEGACY_PROVIDER_ID])
+ delete profile.defaults[CONVEX_LEGACY_PROVIDER_ID];
+ }
+ // Folder bindings point at the provider id too; carry them across so a bound
+ // project keeps resolving without the operator re-mapping it.
+ for (const binding of state.bindings) {
+ const bound = binding.connections[CONVEX_LEGACY_PROVIDER_ID];
+ if (bound === undefined) continue;
+ if (binding.connections.convex === undefined) binding.connections.convex = bound;
+ delete binding.connections[CONVEX_LEGACY_PROVIDER_ID];
+ }
+ return plan;
+ });
+}
diff --git a/lib/infra/setup-guidance.ts b/lib/infra/setup-guidance.ts
index fea33a5b..77aa033e 100644
--- a/lib/infra/setup-guidance.ts
+++ b/lib/infra/setup-guidance.ts
@@ -1,11 +1,33 @@
import { GOOGLE_APP_PROVIDER, isGoogleProvider, googleGuidance } from "./google-native-config";
import { ADDITIONAL_GUIDANCE, type AdditionalProviderId } from "./additional-providers";
-import { getInfraProviderDefinition } from "./catalog";
-import type { InfraProviderId } from "./types";
+import { getInfraProviderDefinition, resolveProviderId } from "./catalog";
+import type { InfraProviderId, InfraProviderRef } from "./types";
-export const SETUP_METHOD_IDS = ["direct", "project", "organization", "personal", "deployment", "mail", "payment", "mcp", "oauth-app", "oauth2"] as const;
+export const SETUP_METHOD_IDS = ["direct", "project", "organization", "personal", "deployment", "admin", "mail", "payment", "mcp", "oauth-app", "oauth2"] as const;
export type SetupMethod = typeof SETUP_METHOD_IDS[number];
-export function setupFields(provider: InfraProviderId, method: SetupMethod) {
+/** One Convex product, two credential shapes; every pre-collapse method id survives. */
+const CONVEX_FIELD_KEYS: Record<string, string[] | null> = {
+ personal: ["personalToken"],
+ deployment: ["deployKey", "deploymentName"],
+ admin: ["apiUrl", "adminKey"],
+ direct: null, // pre-collapse self-hosted rows keep their declared requirements
+};
+function convexFields(provider: InfraProviderId, method: SetupMethod) {
+ if (!(method in CONVEX_FIELD_KEYS)) throw new Error("Choose a Convex personal token, deployment key or self-hosted admin key");
+ const keys = CONVEX_FIELD_KEYS[method];
+ // Method fields stay CREDENTIAL fields only. `deploymentKind` is a non-secret
+ // routing fact on the provider definition; it is not asked for per method and is
+ // inferred from the shape the operator actually supplies.
+ return getInfraProviderDefinition(provider).fields
+ .filter(f => keys === null || keys.includes(f.key))
+ .map(f => ({ ...f, required: keys === null ? f.required : true }));
+}
+export function setupFields(provider: InfraProviderRef, method: SetupMethod) {
+ const canonical = resolveProviderId(provider);
+ if (!canonical) throw new Error("Unsupported authentication method");
+ return fieldsFor(canonical, method);
+}
+function fieldsFor(provider: InfraProviderId, method: SetupMethod) {
if (provider === GOOGLE_APP_PROVIDER || isGoogleProvider(provider)) {
if (method !== (provider === GOOGLE_APP_PROVIDER ? "oauth-app" : "oauth2")) throw new Error("Unsupported Google authentication method");
return getInfraProviderDefinition(provider).fields;
@@ -20,11 +42,7 @@ export function setupFields(provider: InfraProviderId, method: SetupMethod) {
const keys = method === "payment" ? ["paymentClientId", "paymentSecretKey", "paymentEnvironment"] : ["mcpClientId", "mcpApiKey", "environment"];
return getInfraProviderDefinition(provider).fields.filter(f => keys.includes(f.key)).map(f => ({ ...f, required: true }));
}
- if (provider === "convex-cloud") {
- if (!["personal", "deployment"].includes(method)) throw new Error("Choose a Convex personal token or deployment key");
- const keys = method === "personal" ? ["personalToken"] : ["deployKey", "deploymentName"];
- return getInfraProviderDefinition(provider).fields.filter(f => keys.includes(f.key)).map(f => ({ ...f, required: true }));
- }
+ if (provider === "convex") return convexFields(provider, method);
if (provider === "composio") {
if (!["project", "organization"].includes(method)) throw new Error("Choose a Composio project/user or organization key");
return getInfraProviderDefinition(provider).fields.filter(f => f.key === (method === "project" ? "apiKey" : "orgApiKey")).map(f => ({ ...f, required: true }));
@@ -32,25 +50,31 @@ export function setupFields(provider: InfraProviderId, method: SetupMethod) {
if (method !== "direct") throw new Error("Unsupported authentication method");
return getInfraProviderDefinition(provider).fields;
}
-export function setupMethod(provider: InfraProviderId, method?: string): SetupMethod {
- const value = method ?? (provider === GOOGLE_APP_PROVIDER ? "oauth-app" : isGoogleProvider(provider) ? "oauth2" : provider === "composio" ? "project" : provider === "convex-cloud" ? "personal" : provider === "doku" ? "mcp" : "direct");
+export function setupMethod(provider: InfraProviderRef, method?: string): SetupMethod {
+ const canonical = resolveProviderId(provider) ?? throwUnsupported();
+ const value = method ?? (canonical === GOOGLE_APP_PROVIDER ? "oauth-app" : isGoogleProvider(canonical) ? "oauth2" : canonical === "composio" ? "project" : canonical === "convex" ? "personal" : canonical === "doku" ? "mcp" : "direct");
if (!(SETUP_METHOD_IDS as readonly string[]).includes(value)) throw new Error("Unsupported authentication method");
- setupFields(provider, value as SetupMethod);
+ fieldsFor(canonical, value as SetupMethod);
return value as SetupMethod;
}
-export function setupMethods(provider: InfraProviderId): Array<{id: SetupMethod; label: string}> {
- if (provider === GOOGLE_APP_PROVIDER) return [{ id: "oauth-app", label: "Google OAuth app (configuration only)" }];
- if (isGoogleProvider(provider)) return [{ id: "oauth2", label: "Native Google OAuth · read-only" }];
- if (provider === "hostinger") return [{ id: "direct", label: "Account API token" }, { id: "mail", label: "Scoped Mail API token" }];
- if (provider === "composio") return [{ id: "project", label: "Project API key" }, { id: "organization", label: "Organization API key" }];
- if (provider === "convex-cloud") return [{ id: "personal", label: "Personal access token" }, { id: "deployment", label: "Deployment key" }];
- if (provider === "doku") return [{id:"payment",label:"Payment REST · Client ID + Secret Key"},{id:"mcp",label:"MCP · Client ID + API Key"}];
+const throwUnsupported = (): never => { throw new Error("Unsupported authentication method"); };
+export function setupMethods(provider: InfraProviderRef): Array<{id: SetupMethod; label: string}> {
+ const canonical = resolveProviderId(provider) ?? throwUnsupported();
+ const id = canonical;
+ if (id === GOOGLE_APP_PROVIDER) return [{ id: "oauth-app", label: "Google OAuth app (configuration only)" }];
+ if (isGoogleProvider(id)) return [{ id: "oauth2", label: "Native Google OAuth · read-only" }];
+ if (id === "hostinger") return [{ id: "direct", label: "Account API token" }, { id: "mail", label: "Scoped Mail API token" }];
+ if (id === "composio") return [{ id: "project", label: "Project API key" }, { id: "organization", label: "Organization API key" }];
+ if (id === "convex") return [{ id: "personal", label: "Convex Cloud · personal access token" }, { id: "deployment", label: "Convex Cloud · deployment key" }, { id: "admin", label: "Self-hosted · deployment URL + admin key" }];
+ if (id === "doku") return [{id:"payment",label:"Payment REST · Client ID + Secret Key"},{id:"mcp",label:"MCP · Client ID + API Key"}];
return [{ id: "direct", label: "Direct credential" }];
}
-export function setupGuidance(provider: InfraProviderId, method: SetupMethod) {
- if (provider === GOOGLE_APP_PROVIDER || isGoogleProvider(provider)) return googleGuidance(provider);
- if(provider==="doku")return method==="payment"?{url:"https://dashboard.doku.com/bo/developer/api-keys",reference:"https://developers.doku.com/get-started-with-doku-api/signature-component/non-snap/signature-component-from-request-header",steps:["Open DOKU Back Office → Developer → API Keys.","Use Client ID + Secret Key for the signed Non-SNAP payment API; the API Key is not a substitute for the HMAC Secret Key.","Choose sandbox first unless this project is explicitly approved for live payments.","Enter credentials only in this private setup form. MSO verifies them with a signed read-only status lookup before saving."]}:{url:"https://developers.doku.com/accept-payments/doku-mcp-server",reference:"https://developers.doku.com/accept-payments/doku-mcp-server",steps:["Open DOKU's official MCP Server guide and choose Sandbox first unless this project is explicitly approved for production payments.","Use the DOKU MCP Client ID + MCP API Key; do not substitute the Payment REST Secret Key.","Enter them only in this private setup form; do not paste them into chat, Baton notes, RR, Git, or project MCP JSON.","MSO calls the fixed official DOKU MCP endpoint with a read-only MCP initialize request before saving the connection."]};
- if (provider in ADDITIONAL_GUIDANCE) return ADDITIONAL_GUIDANCE[provider as AdditionalProviderId];
+export function setupGuidance(provider: InfraProviderRef, method: SetupMethod) {
+ const canonical = resolveProviderId(provider) ?? throwUnsupported();
+ const id = canonical;
+ if (id === GOOGLE_APP_PROVIDER || isGoogleProvider(id)) return googleGuidance(id);
+ if(id==="doku")return method==="payment"?{url:"https://dashboard.doku.com/bo/developer/api-keys",reference:"https://developers.doku.com/get-started-with-doku-api/signature-component/non-snap/signature-component-from-request-header",steps:["Open DOKU Back Office → Developer → API Keys.","Use Client ID + Secret Key for the signed Non-SNAP payment API; the API Key is not a substitute for the HMAC Secret Key.","Choose sandbox first unless this project is explicitly approved for live payments.","Enter credentials only in this private setup form. MSO verifies them with a signed read-only status lookup before saving."]}:{url:"https://developers.doku.com/accept-payments/doku-mcp-server",reference:"https://developers.doku.com/accept-payments/doku-mcp-server",steps:["Open DOKU's official MCP Server guide and choose Sandbox first unless this project is explicitly approved for production payments.","Use the DOKU MCP Client ID + MCP API Key; do not substitute the Payment REST Secret Key.","Enter them only in this private setup form; do not paste them into chat, Baton notes, RR, Git, or project MCP JSON.","MSO calls the fixed official DOKU MCP endpoint with a read-only MCP initialize request before saving the connection."]};
+ if (id in ADDITIONAL_GUIDANCE) return ADDITIONAL_GUIDANCE[id as AdditionalProviderId];
const guides = {
composio: {
url: "https://platform.composio.dev",
diff --git a/lib/infra/store.ts b/lib/infra/store.ts
index 45476922..e346642e 100644
--- a/lib/infra/store.ts
+++ b/lib/infra/store.ts
@@ -1,47 +1,84 @@
import { clearGoogleRuntime } from "./google-native-state";
import { assertNoVariableReferences } from "./connection-variables";
import {randomUUID} from "node:crypto";
-import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
+import { getInfraProviderDefinition, canonicalProviderId, convexDeploymentKind, normalizeInfraValues, resolveProviderId } from "./catalog";
+import { CONVEX_LEGACY_PROVIDER_ID } from "./types";
import { mutateIntegrationState } from "./connection-storage";
import { currentIntegrationSelection, directConnectionValues, createConnectionIn } from "./connection-service";
import { legacyMethod, connectionMethod } from "./connection-registry";
import { selectConnection, IntegrationError, assertNotBusy } from "./identity";
-import type { InfraProviderId, InfraProviderSummary, InfraProviderValues } from "./types";
+import type { InfraProviderId, InfraProviderRef, InfraProviderSummary, InfraProviderValues } from "./types";
export { INFRA_STORE_PATH } from "./connection-storage";
const mask=(value:string)=>value?"configured":"";
-export const readInfraProvider=(id:InfraProviderId)=>directConnectionValues(id);
-export async function setInfraProvider(id:InfraProviderId,raw:Record<string,unknown>):Promise<InfraProviderValues>{
+/**
+ * Read a provider's values. `convex-cloud` is a READ ALIAS for `convex`: a row
+ * written before the collapse may still live under the retired key, so a
+ * `connection_not_found` on the canonical id retries the legacy key. Any other
+ * error propagates unchanged — the alias never hides a real failure.
+ */
+export const readInfraProvider=async(id:InfraProviderId|string):Promise<InfraProviderValues>=>{
+ const canonical=canonicalProviderId(id);
+ try{return await directConnectionValues(canonical);}catch(error){
+ if(canonical===id||!(error instanceof IntegrationError)||error.code!=="connection_not_found")throw error;
+ return directConnectionValues(id);
+ }
+};
+export async function setInfraProvider(id:InfraProviderRef,raw:Record<string,unknown>):Promise<InfraProviderValues>{
return mutateIntegrationState(state=>{
+ const provider=resolveProviderId(id);if(!provider)throw new IntegrationError("unknown_provider",404);
const selector=currentIntegrationSelection();
if(!Object.keys(state.users).length&&!selector.user){state.users.legacy={id:"legacy",uid:randomUUID(),label:"Existing MSO credentials",defaults:{},connections:{}};state.defaultUser="legacy";}
+ // A row written before the collapse may still live under the retired key.
+ // Resolve it there instead of creating a duplicate "default" connection.
+ const legacyKey = provider === "convex" ? CONVEX_LEGACY_PROVIDER_ID : null;
+ const pick = () => {
+ try { return selectConnection(state,provider,selector); }
+ catch (error) {
+ if (!legacyKey || !(error instanceof IntegrationError) || error.code !== "connection_not_found") throw error;
+ return selectConnection(state,legacyKey,selector);
+ }
+ };
let selected;
- try{selected=selectConnection(state,id,selector);}catch(e){
+ try{selected=pick();}catch(e){
if(!(e instanceof IntegrationError)||e.code!=="connection_not_found"||selector.connection)throw e;
const user=selector.user??state.defaultUser;if(!user)throw new IntegrationError("user_required");
- const c=createConnectionIn(state,{user,provider:id,connection:"default",authMethod:legacyMethod(id,raw as Record<string,string>),makeDefault:true});selected={user,connection:c};
+ const c=createConnectionIn(state,{user,provider,connection:"default",authMethod:legacyMethod(provider,raw as Record<string,string>),makeDefault:true});selected={user,connection:c};
}
const c=selected.connection;assertNotBusy(c);if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden");
- const method=connectionMethod(id,c.source,c.authMethod),normalized=normalizeInfraValues(id,raw);
- if(Object.keys(normalized).some(k=>!method.fields.some(f=>f.key===k)))throw new IntegrationError("connection_auth_mismatch",409);
+ const method=connectionMethod(provider,c.source,c.authMethod),normalized=normalizeInfraValues(provider,raw);
+ // `deploymentKind` is a non-secret routing fact, not a method credential, so it
+ // is never part of the method's credential field set.
+ if(Object.keys(normalized).some(k=>k!=="deploymentKind"&&!method.fields.some(f=>f.key===k)))throw new IntegrationError("connection_auth_mismatch",409);
+ // Persist the non-secret deployment kind on the Convex write path. It is
+ // DERIVED from the credential shape the operator just supplied, so an old row
+ // that never had it gains the field on its next rotation — and a row that
+ // already has it keeps behaving identically. Never a credential value.
+ if(provider==="convex")normalized.deploymentKind=convexDeploymentKind(normalized);
const values={...c.values,...normalized};if(method.fields.some(f=>f.required&&!values[f.key]))throw new IntegrationError("required_fields_missing");
clearGoogleRuntime(c);c.values=values;c.revision++;c.updatedAt=Date.now();delete c.verifiedAt;return{...values};
});
}
-export async function removeInfraProvider(id:InfraProviderId){
- await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);assertNoVariableReferences(state,r.user,id,r.connection.id);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);const profile=state.users[r.user];
- const remaining=Object.fromEntries(Object.entries(profile.connections[id]).filter(([key])=>key!==r.connection.id));
- profile.connections=Object.fromEntries(Object.entries(profile.connections).map(([key,rows])=>[key,key===id?remaining:rows]));
- profile.defaults=Object.fromEntries(Object.entries(profile.defaults).filter(([key,value])=>key!==id||value!==r.connection.id));});
+export async function removeInfraProvider(id:InfraProviderRef){
+ const provider=resolveProviderId(id);if(!provider)throw new IntegrationError("unknown_provider",404);
+ await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,provider,selection);assertNotBusy(r.connection);assertNoVariableReferences(state,r.user,provider,r.connection.id);if(state.bindings.some(b=>b.user===r.user&&b.connections[provider]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(provider==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);const profile=state.users[r.user];
+ const remaining=Object.fromEntries(Object.entries(profile.connections[provider]).filter(([key])=>key!==r.connection.id));
+ profile.connections=Object.fromEntries(Object.entries(profile.connections).map(([key,rows])=>[key,key===provider?remaining:rows]));
+ profile.defaults=Object.fromEntries(Object.entries(profile.defaults).filter(([key,value])=>key!==provider||value!==r.connection.id));});
}
-export function summarizeInfraProvider(id: InfraProviderId, values: InfraProviderValues): InfraProviderSummary {
- const def = getInfraProviderDefinition(id);
+export function summarizeInfraProvider(id: InfraProviderRef, values: InfraProviderValues): InfraProviderSummary {
+ const canonical = resolveProviderId(id);
+ if (!canonical) throw new Error("unknown infrastructure provider");
+ const def = getInfraProviderDefinition(canonical);
const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
- if (id === "composio" && !values.apiKey && !values.orgApiKey) missing.push("project or organization API key");
- if (id === "hostinger" && !values.apiToken && !(values.mailApiToken && values.mailOrderId)) missing.push("account token or scoped Mail API token + order ID");
- if(id==="doku"&&!(values.paymentClientId&&values.paymentSecretKey&&values.paymentEnvironment)&&!(values.mcpClientId&&values.mcpApiKey&&values.environment))missing.push("Payment Client ID + Secret Key or MCP Client ID + API Key, plus environment");
- if (id === "convex-cloud" && !values.personalToken && !(values.deployKey && values.deploymentName)) missing.push("personal token or deployment key and name");
+ if (canonical === "composio" && !values.apiKey && !values.orgApiKey) missing.push("project or organization API key");
+ if (canonical === "hostinger" && !values.apiToken && !(values.mailApiToken && values.mailOrderId)) missing.push("account token or scoped Mail API token + order ID");
+ if(canonical==="doku"&&!(values.paymentClientId&&values.paymentSecretKey&&values.paymentEnvironment)&&!(values.mcpClientId&&values.mcpApiKey&&values.environment))missing.push("Payment Client ID + Secret Key or MCP Client ID + API Key, plus environment");
+ if (canonical === "convex") {
+ const kind = convexDeploymentKind(values);
+ if (kind === "self-hosted" ? !(values.apiUrl && values.adminKey) : !values.personalToken && !(values.deployKey && values.deploymentName)) missing.push(kind === "self-hosted" ? "self-hosted deployment URL and admin key" : "Convex Cloud personal token or deployment key and name");
+ }
const safeValues = Object.fromEntries(def.fields
.filter((field) => values[field.key])
.map((field) => [field.key, field.secret ? mask(values[field.key]) : values[field.key]]));
- return { id, title: def.title, description: def.description, feature: def.feature, configured: missing.length === 0, missing, values: safeValues, fields: def.fields };
+ return { id: canonical, title: def.title, description: def.description, feature: def.feature, configured: missing.length === 0, missing, values: safeValues, fields: def.fields };
}
diff --git a/lib/infra/types.ts b/lib/infra/types.ts
index 50b77d61..6f28b452 100644
--- a/lib/infra/types.ts
+++ b/lib/infra/types.ts
@@ -1,6 +1,98 @@
-export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex-cloud", "convex", "resend", "stripe", "clerk", "supabase", "telegram", "discord", "doku", "linear", "mcp", "openai-app", "google-oauth-app", "google-search-console", "google-analytics"] as const;
+export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex", "resend", "stripe", "clerk", "supabase", "telegram", "discord", "doku", "linear", "mcp", "openai-app", "google-oauth-app", "google-search-console", "google-analytics"] as const;
export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];
+/**
+ * One Convex product, two credential shapes. `deploymentKind` is NON-SECRET and
+ * records which shape a connection uses; a legacy row without it is inferred from
+ * `apiUrl` at read time (see `convexDeploymentKind` in ./catalog).
+ */
+export const CONVEX_DEPLOYMENT_KINDS = ["cloud", "self-hosted"] as const;
+export type ConvexDeploymentKind = (typeof CONVEX_DEPLOYMENT_KINDS)[number];
+
+/** Legacy provider id. READ ALIAS ONLY — never a member of INFRA_PROVIDER_IDS. */
+export const CONVEX_LEGACY_PROVIDER_ID = "convex-cloud";
+/**
+ * Any id a caller may still hold: the current set, plus the retired `convex-cloud`
+ * read alias. Entry points that store or summarize credentials accept this and
+ * canonicalize internally, so an old CLI invocation or stored row resolves.
+ */
+export type InfraProviderRef = InfraProviderId | typeof CONVEX_LEGACY_PROVIDER_ID;
+
+export const CONVEX_OPERATION_IDS = [
+ "convex.customDomains.list",
+ "convex.customDomain.ensure",
+ "convex.canonical.get",
+ "convex.canonical.set",
+ "convex.env.presence",
+ "convex.project.deploy",
+ "convex.snapshot.import",
+] as const;
+export type ConvexOperationId = (typeof CONVEX_OPERATION_IDS)[number];
+export type ConvexOperationAvailability = "supported" | "unsupported";
+export type ConvexOperationSupport = {
+ operation: ConvexOperationId;
+ cloud: ConvexOperationAvailability;
+ selfHosted: ConvexOperationAvailability;
+ /** Present exactly when the operation is refused for a kind, so a UI can grey it out. */
+ reason?: string;
+};
+
+/**
+ * Machine-readable per-kind capability map. `lib/infra/connection-dispatch.ts`
+ * refuses with `convex_operation_unsupported_for_kind` instead of a silent 404,
+ * and the provider UI can disable the greyed-out rows from this same table.
+ *
+ * Every operation is unsupported for `self-hosted` today for ONE structural
+ * reason: MSO's runner reaches a deployment by minting an ephemeral deploy key
+ * through the Convex Cloud management API (api.convex.dev), and a self-hosted
+ * deployment exposes no such key-minting endpoint. Registering them as
+ * "supported" would only replace today's 404 with a mid-run failure.
+ */
+export const CONVEX_OPERATION_SUPPORT: readonly ConvexOperationSupport[] = [
+ {
+ operation: "convex.customDomains.list",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Custom domains are registered through the Convex Cloud management API; a self-hosted deployment serves its own reverse proxy.",
+ },
+ {
+ operation: "convex.customDomain.ensure",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Custom domains are registered through the Convex Cloud management API; a self-hosted deployment serves its own reverse proxy.",
+ },
+ {
+ operation: "convex.canonical.get",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Canonical URL registration is a Convex Cloud feature; a self-hosted deployment is addressed by its own origin.",
+ },
+ {
+ operation: "convex.canonical.set",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Canonical URL registration is a Convex Cloud feature; a self-hosted deployment is addressed by its own origin.",
+ },
+ {
+ operation: "convex.env.presence",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Reads environment names with an ephemeral deploy key minted by the Convex Cloud management API; no self-hosted equivalent is wired yet.",
+ },
+ {
+ operation: "convex.project.deploy",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Deploys with an ephemeral deploy key minted by the Convex Cloud management API; self-hosted deploys need the deployment URL + admin key passed to the CLI instead.",
+ },
+ {
+ operation: "convex.snapshot.import",
+ cloud: "supported",
+ selfHosted: "unsupported",
+ reason: "Imports with an ephemeral deploy key minted by the Convex Cloud management API; self-hosted imports need the deployment URL + admin key passed to the CLI instead.",
+ },
+];
+
export type InfraProviderValues = Record<string, string>;
export type LegacyInfraStore = { providers?: Partial<Record<InfraProviderId, InfraProviderValues>> };
export type InfraField = {