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): deterministic Convex project linker and per-project provider view

rahmanef6363f9981f6084
diff --git a/app/api/v1/infra/providers/route-project.test.ts b/app/api/v1/infra/providers/route-project.test.ts
new file mode 100644
index 00000000..f6c896de
--- /dev/null
+++ b/app/api/v1/infra/providers/route-project.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({ view: vi.fn(), limited: vi.fn(), legacy: vi.fn() }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: vi.fn(async () => ({ role: "owner", session: { device_id: "dev-owner" } })) }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.limited }));
+vi.mock("@/lib/infra/connection-service", () => ({
+ withIntegrationSelection: (_selector: unknown, fn: () => unknown) => fn(),
+ projectProviderQuery: mocks.view,
+}));
+vi.mock("@/lib/infra", () => ({
+ INFRA_PROVIDER_IDS: ["dokploy"],
+ isInfraProviderId: (id: string) => id === "dokploy",
+ readInfraProvider: async () => ({}),
+ removeInfraProvider: async () => undefined,
+ setInfraProvider: async () => ({}),
+ summarizeInfraProvider: (id: string) => ({ id }),
+}));
+import { GET } from "./route";
+
+const SECRET = "synthetic_secret_deploy_key_do_not_leak";
+const request = (query = "") => new NextRequest("http://localhost/api/v1/infra/providers" + query, { headers: { host: "localhost" } });
+
+describe("/api/v1/infra/providers project view", () => {
+ it("returns cloud and self-hosted rows together for one project, without duplication", async () => {
+ mocks.limited.mockReturnValue(false);
+ mocks.view.mockResolvedValue({
+ project: "containerabc/baton",
+ providers: [
+ { user: "owner", provider: "convex", connection: "baton", label: "Baton", kind: "cloud", scope: "deployment", state: "linked-healthy", projects: ["containerabc/baton", "containerabc/mimin"], projectCount: 2, verifiedAt: 1 },
+ { user: "owner", provider: "convex", connection: "zianinn", label: "Zianinn", kind: "self-hosted", scope: "server", state: "deployment-unreachable", projects: ["containerabc/baton"], projectCount: 1, verifiedAt: null },
+ ],
+ });
+ const res = await GET(request("?project=containerabc%2Fbaton"));
+ expect(res.status).toBe(200);
+ expect(res.headers.get("cache-control")).toBe("no-store, private");
+ const body = await res.json();
+ expect(body.providers.map((row: { kind: string }) => row.kind)).toEqual(["cloud", "self-hosted"]);
+ expect(body.providers.filter((row: { connection: string }) => row.connection === "baton")).toHaveLength(1);
+ expect(body.providers[0].projectCount).toBe(2);
+ expect(new Set(body.providers.flatMap((row: { projects: string[] }) => row.projects)).size).toBe(2);
+ expect(mocks.view).toHaveBeenCalledWith({ project: "containerabc/baton", selector: { user: undefined, connection: undefined, cwd: undefined } });
+ });
+
+ it("keeps the three states distinct instead of collapsing down into invalid", async () => {
+ mocks.limited.mockReturnValue(false);
+ mocks.view.mockResolvedValue({
+ project: "c/p",
+ providers: ["linked-healthy", "deployment-unreachable", "credential-rejected"].map((state, index) => ({
+ user: "owner", provider: "convex", connection: `c${index}`, label: `c${index}`, kind: "cloud", scope: "deployment", state, projects: ["c/p"], projectCount: 1, verifiedAt: null,
+ })),
+ });
+ const body = await (await GET(request("?project=c%2Fp"))).json();
+ expect(new Set(body.providers.map((row: { state: string }) => row.state))).toEqual(new Set(["linked-healthy", "deployment-unreachable", "credential-rejected"]));
+ });
+
+ it("never serializes a credential in a filtered response", async () => {
+ mocks.limited.mockReturnValue(false);
+ mocks.view.mockResolvedValue({ project: "c/p", providers: [{ user: "owner", provider: "convex", connection: "baton", label: "Baton", kind: "cloud", scope: "deployment", state: "linked-healthy", projects: ["c/p"], projectCount: 1, verifiedAt: null }] });
+ const text = await (await GET(request("?project=c%2Fp"))).text();
+ expect(text).not.toContain(SECRET);
+ expect(text).not.toContain("deployKey");
+ expect(text).not.toContain("values");
+ });
+
+ it("rejects a non-owner before any lookup", async () => {
+ mocks.limited.mockReturnValue(false);
+ mocks.view.mockReset();
+ const { getSessionContext } = await import("@/lib/auth/require-session");
+ vi.mocked(getSessionContext).mockResolvedValueOnce({ role: "operator", session: { device_id: "dev-op" } } as never);
+ expect((await GET(request("?project=c%2Fp"))).status).toBe(401);
+ expect(mocks.view).not.toHaveBeenCalled();
+ });
+
+ it("rate-limits and rejects a malformed project id before any lookup", async () => {
+ mocks.view.mockReset();
+ mocks.limited.mockReturnValueOnce(true);
+ expect((await GET(request("?project=c%2Fp"))).status).toBe(429);
+ mocks.limited.mockReturnValueOnce(false);
+ const bad = await GET(request("?project=../../etc%2Fpasswd"));
+ expect(bad.status).toBe(400);
+ expect(await bad.text()).not.toContain("passwd");
+ expect(mocks.view).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/infra/providers/route.ts b/app/api/v1/infra/providers/route.ts
index f96a707e..19c3fc0d 100644
--- a/app/api/v1/infra/providers/route.ts
+++ b/app/api/v1/infra/providers/route.ts
@@ -1,5 +1,7 @@
-import { withIntegrationSelection } from "@/lib/infra/connection-service";
+import { withIntegrationSelection, projectProviderQuery } from "@/lib/infra/connection-service";
import { selectionFrom } from "@/lib/infra/connection-dispatch";
+import { projectKey } from "@/lib/infra/convex-project-link";
+import { rateLimited } from "@/lib/host/limits-api";
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
import { audit } from "@/lib/host/audit-api";
@@ -8,15 +10,29 @@ import { INFRA_PROVIDER_IDS, isInfraProviderId, readInfraProvider, removeInfraPr
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private", "Pragma": "no-cache", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };
+
async function ownerContext() {
const context = await getSessionContext();
return context?.role === "owner" ? context : null;
}
export async function GET(req:NextRequest) {
- if (!(await ownerContext())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- const providers = await withIntegrationSelection(selectionFrom(Object.fromEntries(req.nextUrl.searchParams)),()=>Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))));
- return NextResponse.json({ providers });
+ const context = await ownerContext();
+ if (!context) return NextResponse.json({ error: "Unauthorized" }, { status: 401, headers });
+ if (rateLimited(`infra.providers:${context.session.device_id ?? "unknown"}`, 60, 60_000))
+ return NextResponse.json({ error: "rate_limited" }, { status: 429, headers });
+ const params = Object.fromEntries(req.nextUrl.searchParams);
+ const query = params.project;
+ if (query !== undefined) {
+ // Per-project view: cloud and self-hosted rows together, credentials never included.
+ let project: string;
+ try { project = projectKey(query); } catch { return NextResponse.json({ error: "invalid_project_id" }, { status: 400, headers }); }
+ const view = await withIntegrationSelection(selectionFrom(params),()=>projectProviderQuery({ project, selector: selectionFrom(params) }));
+ return NextResponse.json(view, { headers });
+ }
+ const providers = await withIntegrationSelection(selectionFrom(params),()=>Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))));
+ return NextResponse.json({ providers }, { headers });
}
export async function POST(req: NextRequest) {
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b351d720..0f254295 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
## 2026-10-27
+**Added**
+
+- `infra` collapse Convex into one provider with a real self-hosted kind
+
**Build**
- `deps` bump the actions-minor-patch group with 3 updates (#159)
@@ -28,7 +32,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `infra` collapse Convex into one provider with a real self-hosted kind
+- `infra` deterministic Convex project linker and per-project provider view
**Fixed**
diff --git a/lib/infra/connection-service.ts b/lib/infra/connection-service.ts
index 925435ee..03dfe1f9 100644
--- a/lib/infra/connection-service.ts
+++ b/lib/infra/connection-service.ts
@@ -6,6 +6,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
import { connectionCatalog, connectionMethod, connectionSummary, nativeDefinition } from "./connection-registry";
import { readIntegrationState, mutateIntegrationState } from "./connection-storage";
import { IntegrationError, identity, connectionLabel, selectConnection, resolveUser, folderBinding, metadataOnly, assertNotBusy, resolveSharedConnection, type ConnectionSelector, type IntegrationState, type IntegrationConnection, type ConnectionSource } from "./identity";
+import { projectKey } from "./convex-project-link";
import { normalizeInfraValues, isInfraProviderId } from "./catalog";
const CONTEXT=new AsyncLocalStorage<{selector:ConnectionSelector; pinned:Map<string,Record<string,string>>}>();
export function withIntegrationSelection<T>(selector:ConnectionSelector,fn:()=>T){return CONTEXT.run({selector,pinned:new Map()},fn);}
@@ -60,11 +61,55 @@ export async function saveConnectionValues(provider:string,selector:ConnectionSe
return summaryIn(state,r.user,c);
});
}
+/**
+ * Per-project view over the SAME store. A connection carries zero or more project
+ * associations, so "one deployment, several projects" is representable without a
+ * duplicate row. No `kind` filter: cloud and self-hosted rows come back together.
+ *
+ * `state` keeps "the deployment is down" (`deployment-unreachable`) apart from "the
+ * credential was rejected" (`credential-rejected`) — different operator fixes.
+ */
+export type ProjectProviderState = "linked-healthy" | "deployment-unreachable" | "credential-rejected" | "unverified";
+export type ProjectProviderRow = {
+ user: string; provider: string; connection: string; label: string;
+ kind: "cloud" | "self-hosted" | null; scope: string; state: ProjectProviderState;
+ projects: string[]; projectCount: number; verifiedAt: number | null;
+};
+const deploymentKind=(provider:string):ProjectProviderRow["kind"]=>provider==="convex-cloud"?"cloud":provider==="convex"?"self-hosted":null;
+const healthOf=(state:string):ProjectProviderState=>state==="verified"?"linked-healthy":state==="unavailable"?"deployment-unreachable":state==="invalid"?"credential-rejected":"unverified";
+const isProjectKey=(value:unknown):value is string=>{try{projectKey(value);return true;}catch{return false;}};
+export async function projectProviderQuery(input:{project?:string;selector?:ConnectionSelector}={}){
+ const state=await readIntegrationState(),project=input.project;
+ const users=input.selector?.user?[identity(input.selector.user,"user")]:Object.keys(state.users);
+ const rows:ProjectProviderRow[]=users.filter(u=>Object.hasOwn(state.users,u)).flatMap(user=>
+ Object.values(state.users[user].connections).flatMap(connections=>
+ Object.values(connections).map(c=>{
+ // The store validator does not own this additive field, so re-validate here:
+ // a hand-edited or foreign state file cannot smuggle an arbitrary string out.
+ const summary=summaryIn(state,user,c),projects=[...new Set((c.projects??[]).filter(isProjectKey))].sort();
+ return{user,provider:c.provider,connection:c.id,label:summary.label,kind:deploymentKind(c.provider),scope:c.scope,state:healthOf(String(summary.state)),projects,projectCount:projects.length,verifiedAt:c.verifiedAt??null};
+ })
+ )
+ ).filter(row=>!project||row.projects.includes(project));
+ return{...(project?{project}:{}),providers:rows.sort((a,b)=>a.provider.localeCompare(b.provider)||a.connection.localeCompare(b.connection))};
+}
+/** Idempotent association write; the linker decides, this only stores. */
+export async function setConnectionProjects(userInput:string,provider:string,connectionId:string,projects:string[]){
+ const want=[...new Set(projects.map(projectKey))].sort();
+ return mutateIntegrationState(state=>{
+ const user=identity(userInput,"user"),r=selectConnection(state,provider,{user,connection:identity(connectionId,"connection")});
+ if(r.connection.sharedFrom)throw new IntegrationError("shared_alias_readonly",409);
+ const previous=[...(r.connection.projects??[])].sort();
+ if(JSON.stringify(previous)!==JSON.stringify(want)){r.connection.projects=want;r.connection.updatedAt=Date.now();}
+ return{user,provider,connection:r.connection.id,projects:want,changed:JSON.stringify(previous)!==JSON.stringify(want)};
+ });
+}
export async function integrationQuery(input:Record<string,unknown>){
- metadataOnly(input);const allowed=["view","user","provider","connection","cwd","source","authMethod"];
+ metadataOnly(input);const allowed=["view","user","provider","connection","cwd","source","authMethod","project"];
if(Object.keys(input).some(k=>!allowed.includes(k)))throw new IntegrationError("invalid_query_fields");
const selection=input as ConnectionSelector,view=input.view??"snapshot";
if(view==="catalog")return{catalog:connectionCatalog()};
+ if(view==="projects")return projectProviderQuery({project:input.project===undefined?undefined:projectKey(input.project),selector:selection});
if(view==="resolve")return resolveIntegration(identity(input.provider,"provider"),selection);
if(view==="request"){
const provider=identity(input.provider,"provider");const catalog=connectionCatalog().find(p=>p.id===provider);if(!catalog)throw new IntegrationError("unknown_provider",404);
diff --git a/lib/infra/convex-project-link-store.test.ts b/lib/infra/convex-project-link-store.test.ts
new file mode 100644
index 00000000..ffff5ce9
--- /dev/null
+++ b/lib/infra/convex-project-link-store.test.ts
@@ -0,0 +1,155 @@
+// Store-backed half: project associations and the per-project query surface.
+// Split from convex-project-link.test.ts to keep both files under the physical-line ratchet.
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+const root = await mkdtemp(path.join(os.tmpdir(), "mso-convex-link-store-"));
+const store = path.join(root, "infra-providers.json");
+const SECRET = "synthetic_deploy_key_must_never_leak";
+vi.stubEnv("OS_FS_READ_ROOTS", root);
+vi.stubEnv("OS_INFRA_STORE", store);
+
+type Row = { projects?: string[]; lastCheck?: unknown };
+type State = {
+ users: { owner: { connections: Record<string, Record<string, Row>> } };
+};
+const BASE_STATE = {
+ version: 2,
+ instanceId: "3f1c0f9e-0000-4000-8000-000000000000",
+ defaultUser: "owner",
+ users: {
+ owner: {
+ id: "owner", uid: "owner-uid", label: "Owner",
+ defaults: { "convex-cloud": "baton" },
+ connections: {
+ "convex-cloud": {
+ baton: {
+ id: "baton", uid: "uid-baton", label: "Baton production", provider: "convex-cloud",
+ source: "direct", authMethod: "deployment", scope: "deployment",
+ revision: 1, values: { deployKey: SECRET, deploymentName: "veracious-rooster-179" },
+ createdAt: 1, updatedAt: 1, verifiedAt: 2,
+ lastCheck: { revision: 1, checkedAt: 2, result: "verified" },
+ },
+ },
+ convex: {
+ zianinn: {
+ id: "zianinn", uid: "uid-zianinn", label: "Zianinn self-hosted", provider: "convex",
+ source: "direct", authMethod: "direct", scope: "server",
+ revision: 1, values: { apiUrl: "https://api-zianinn.rahmanef.com", adminKey: SECRET },
+ createdAt: 1, updatedAt: 1,
+ lastCheck: { revision: 1, checkedAt: 2, result: "unavailable" },
+ },
+ },
+ },
+ },
+ },
+ bindings: [],
+};
+
+function state(projects: boolean): State {
+ const next = structuredClone(BASE_STATE) as unknown as State;
+ const rows = next.users.owner.connections;
+ if (projects) {
+ rows["convex-cloud"].baton.projects = ["containerabc/baton", "containerabc/mimin"];
+ rows.convex.zianinn.projects = ["containerabc/baton"];
+ }
+ return next;
+}
+const writeState = async (projects: boolean) => writeFile(store, JSON.stringify(state(projects), null, 2), { mode: 0o600 });
+
+let fetchSpy: ReturnType<typeof vi.fn>;
+beforeAll(() => { fetchSpy = vi.fn(() => Promise.reject(new Error("network is forbidden"))); globalThis.fetch = fetchSpy as unknown as typeof fetch; });
+afterAll(async () => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); });
+
+describe("per-project query surface", () => {
+ it("parses an old state file with no project field and still behaves", async () => {
+ await writeState(false);
+ const { projectProviderQuery } = await import("./connection-service");
+ const view = await projectProviderQuery();
+ expect(view.providers).toHaveLength(2);
+ expect(view.providers.every((row) => row.projects.length === 0 && row.projectCount === 0)).toBe(true);
+ expect((await projectProviderQuery({ project: "containerabc/baton" })).providers).toEqual([]);
+ });
+
+ it("lists two projects on one deployment without duplicating the connection", async () => {
+ await writeState(true);
+ const { projectProviderQuery } = await import("./connection-service");
+ const shared = await projectProviderQuery({ project: "containerabc/mimin" });
+ expect(shared.providers.map((row) => row.connection)).toEqual(["baton"]);
+ expect(shared.providers[0]).toMatchObject({ projectCount: 2, projects: ["containerabc/baton", "containerabc/mimin"] });
+ const baton = await projectProviderQuery({ project: "containerabc/baton" });
+ expect(baton.providers.map((row) => row.connection)).toEqual(["zianinn", "baton"]);
+ expect(baton.providers.filter((row) => row.connection === "baton")).toHaveLength(1);
+ // Cloud and self-hosted rows arrive together: no kind filter.
+ expect(baton.providers.map((row) => row.kind).sort()).toEqual(["cloud", "self-hosted"]);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("keeps deployment-down apart from credential-rejected in the data shape", async () => {
+ await writeState(true);
+ const { projectProviderQuery } = await import("./connection-service");
+ const rows = (await projectProviderQuery({ project: "containerabc/baton" })).providers;
+ expect(rows.find((row) => row.connection === "baton")?.state).toBe("linked-healthy");
+ expect(rows.find((row) => row.connection === "zianinn")?.state).toBe("deployment-unreachable");
+ const rejected: State = state(true);
+ rejected.users.owner.connections.convex.zianinn.lastCheck = { revision: 1, checkedAt: 2, result: "invalid" };
+ await writeFile(store, JSON.stringify(rejected), { mode: 0o600 });
+ const after = (await projectProviderQuery({ project: "containerabc/baton" })).providers;
+ expect(after.find((row) => row.connection === "zianinn")?.state).toBe("credential-rejected");
+ expect(after.find((row) => row.connection === "baton")?.state).toBe("linked-healthy");
+ });
+
+ it("associates one deployment with several projects idempotently and never returns the credential", async () => {
+ await writeState(false);
+ const { projectProviderQuery, setConnectionProjects } = await import("./connection-service");
+ await setConnectionProjects("owner", "convex-cloud", "baton", ["containerabc/baton", "containerabc/mimin", "containerabc/baton"]);
+ const again = await setConnectionProjects("owner", "convex-cloud", "baton", ["containerabc/mimin", "containerabc/baton"]);
+ expect(again).toMatchObject({ projects: ["containerabc/baton", "containerabc/mimin"], changed: false });
+ const view = await projectProviderQuery({ project: "containerabc/baton" });
+ expect(view.providers).toHaveLength(1);
+ expect(view.providers[0].projectCount).toBe(2);
+ for (const result of [view, await projectProviderQuery()]) {
+ expect(JSON.stringify(result)).not.toContain(SECRET);
+ expect(JSON.stringify(result)).not.toContain("deployKey");
+ expect(JSON.stringify(result)).not.toContain("adminKey");
+ }
+ });
+
+ it("rejects an association that is not a project id", async () => {
+ await writeState(false);
+ const { setConnectionProjects } = await import("./connection-service");
+ await expect(setConnectionProjects("owner", "convex-cloud", "baton", ["../../etc/passwd"])).rejects.toMatchObject({ code: "invalid_project_id" });
+ await expect(setConnectionProjects("owner", "convex-cloud", "baton", ["no-container"])).rejects.toMatchObject({ code: "invalid_project_id" });
+ });
+
+ it("drops a malformed stored association instead of echoing it back", async () => {
+ const dirty: State = state(false);
+ dirty.users.owner.connections["convex-cloud"].baton.projects = ["containerabc/baton", "../../etc/passwd"];
+ await writeFile(store, JSON.stringify(dirty), { mode: 0o600 });
+ const { projectProviderQuery } = await import("./connection-service");
+ const view = await projectProviderQuery();
+ expect(view.providers.find((row) => row.connection === "baton")?.projects).toEqual(["containerabc/baton"]);
+ expect(JSON.stringify(view)).not.toContain("passwd");
+ });
+
+ it("links a real folder against the store with no fetch and no secret in the result", async () => {
+ await writeState(true);
+ const { projectProviderQuery } = await import("./connection-service");
+ const { readProjectConvexUsage, linkConvexProject } = await import("./convex-project-link");
+ const dir = path.join(root, "store-linked");
+ await mkdir(path.join(dir, "convex"), { recursive: true });
+ await writeFile(path.join(dir, ".env.local"), `CONVEX_DEPLOYMENT=prod:veracious-rooster-179\nCONVEX_DEPLOY_KEY=${SECRET}\n`);
+ const rows = (await projectProviderQuery()).providers;
+ const result = linkConvexProject(await readProjectConvexUsage(dir), rows.map((row) => ({
+ user: row.user, provider: row.provider, connection: row.connection,
+ deploymentName: row.connection === "baton" ? "veracious-rooster-179" : null,
+ origin: row.connection === "zianinn" ? "https://api-zianinn.rahmanef.com" : null,
+ })));
+ expect(result.outcome).toBe("linked");
+ expect(JSON.stringify(result)).not.toContain(SECRET);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/infra/convex-project-link.test.ts b/lib/infra/convex-project-link.test.ts
new file mode 100644
index 00000000..1910fb70
--- /dev/null
+++ b/lib/infra/convex-project-link.test.ts
@@ -0,0 +1,108 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ DEPLOYMENT_ENV_KEYS,
+ deploymentIdentifiers,
+ linkConvexProject,
+ readProjectConvexUsage,
+ type LinkableConnection,
+} from "./convex-project-link";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "mso-convex-link-"));
+vi.stubEnv("OS_FS_READ_ROOTS", root);
+
+const CLOUD: LinkableConnection = { user: "owner", provider: "convex", connection: "baton", deploymentName: "veracious-rooster-179" };
+const SELF: LinkableConnection = { user: "owner", provider: "convex", connection: "zianinn", origin: "https://api-zianinn.rahmanef.com" };
+const OTHER: LinkableConnection = { user: "owner", provider: "convex", connection: "other", deploymentName: "another-deployment" };
+
+async function project(name: string, env?: string, options: { convex?: boolean } = {}): Promise<string> {
+ const dir = path.join(root, name);
+ await mkdir(dir, { recursive: true });
+ if (options.convex !== false) await mkdir(path.join(dir, "convex"), { recursive: true });
+ if (env) await writeFile(path.join(dir, ".env.local"), env);
+ return dir;
+}
+
+beforeAll(() => { globalThis.fetch = vi.fn(() => Promise.reject(new Error("network is forbidden in the linker"))); });
+afterAll(async () => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); });
+
+describe("deterministic Convex project linker", () => {
+ it("links a cloud deployment name with no fetch and no secret retained", async () => {
+ const dir = await project("cloud", "CONVEX_DEPLOYMENT=prod:veracious-rooster-179\nCONVEX_DEPLOY_KEY=prod:veracious-rooster-179|SYNTHETIC_SECRET_VALUE\n");
+ const usage = await readProjectConvexUsage(dir);
+ const result = linkConvexProject(usage, [CLOUD, SELF, OTHER]);
+ expect(result.outcome).toBe("linked");
+ expect(result.reason).toBe("single-match");
+ expect(result.matched).toEqual([CLOUD]);
+ expect(result.identifiers.deploymentNames).toEqual(["veracious-rooster-179"]);
+ expect(JSON.stringify([usage, result])).not.toContain("SYNTHETIC_SECRET_VALUE");
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it("links a self-hosted origin from CONVEX_SELF_HOSTED_URL and from a public URL var", async () => {
+ const selfHosted = linkConvexProject(await readProjectConvexUsage(await project("self", "CONVEX_SELF_HOSTED_URL=https://api-zianinn.rahmanef.com\n")), [CLOUD, SELF]);
+ expect(selfHosted.outcome).toBe("linked");
+ expect(selfHosted.matched).toEqual([SELF]);
+ expect(selfHosted.identifiers.origins).toEqual(["https://api-zianinn.rahmanef.com"]);
+ const publicUrl = linkConvexProject(await readProjectConvexUsage(await project("public", "NEXT_PUBLIC_CONVEX_URL=https://api-zianinn.rahmanef.com/api\n")), [SELF]);
+ expect(publicUrl.outcome).toBe("linked");
+ expect(publicUrl.matched).toHaveLength(1);
+ });
+
+ it("links a cloud URL-only repo by deployment hostname", async () => {
+ const result = linkConvexProject(await readProjectConvexUsage(await project("url", "VITE_CONVEX_URL=https://veracious-rooster-179.convex.cloud\n")), [CLOUD, SELF]);
+ expect(result.outcome).toBe("linked");
+ expect(result.matched).toEqual([CLOUD]);
+ });
+
+ it("reports unmatched when the repo uses Convex but resolves no identifier", async () => {
+ const result = linkConvexProject(await readProjectConvexUsage(await project("bare", undefined)), [CLOUD, SELF]);
+ expect(result).toMatchObject({ outcome: "unmatched", reason: "no-identifier", matched: [] });
+ });
+
+ it("reports unmatched when an identifier resolves but no stored connection matches", async () => {
+ const result = linkConvexProject(await readProjectConvexUsage(await project("nomatch", "CONVEX_DEPLOYMENT=dev:unknown-deployment\n")), [CLOUD, SELF]);
+ expect(result).toMatchObject({ outcome: "unmatched", reason: "no-match", matched: [] });
+ });
+
+ it("keeps \"no Convex usage\" distinct from unmatched", async () => {
+ const usage = await readProjectConvexUsage(await project("plain", "CONVEX_DEPLOYMENT=prod:veracious-rooster-179\n", { convex: false }));
+ const result = linkConvexProject(usage, [CLOUD]);
+ expect(result.outcome).toBe("no-convex-usage");
+ expect(result.reason).toBe("not-a-convex-project");
+ expect(result.outcome).not.toBe("unmatched");
+ });
+
+ it("reports conflict when two stored connections match the same identifier", async () => {
+ const twin: LinkableConnection = { user: "other", provider: "convex", connection: "twin", deploymentName: "veracious-rooster-179" };
+ const result = linkConvexProject(await readProjectConvexUsage(await project("twin", "CONVEX_DEPLOYMENT=prod:veracious-rooster-179\n")), [CLOUD, twin]);
+ expect(result).toMatchObject({ outcome: "conflict", reason: "multiple-matches" });
+ expect(result.matched).toHaveLength(2);
+ });
+
+ it("reports conflict when a cloud name and a self-hosted URL disagree in one repo", async () => {
+ const dir = await project("mixed", "CONVEX_DEPLOYMENT=prod:veracious-rooster-179\nCONVEX_SELF_HOSTED_URL=https://api-zianinn.rahmanef.com\n");
+ const result = linkConvexProject(await readProjectConvexUsage(dir), [CLOUD, SELF]);
+ expect(result).toMatchObject({ outcome: "conflict", reason: "identifier-disagreement" });
+ });
+
+ it("reports conflict when a repo names two different cloud deployments", async () => {
+ const dir = await project("two-names", "CONVEX_DEPLOYMENT=prod:veracious-rooster-179\nNEXT_PUBLIC_CONVEX_URL=https://another-deployment.convex.cloud\n");
+ expect(linkConvexProject(await readProjectConvexUsage(dir), [CLOUD, OTHER])).toMatchObject({ outcome: "conflict" });
+ });
+
+ it("reads only the allowlisted identifier keys from an env file", () => {
+ const identifiers = deploymentIdentifiers([
+ "CONVEX_DEPLOYMENT=prod:veracious-rooster-179",
+ "CONVEX_SELF_HOSTED_URL=https://api-zianinn.rahmanef.com",
+ "CONVEX_DEPLOY_KEY=SYNTHETIC_SECRET_VALUE",
+ "SOME_PASSWORD=SYNTHETIC_SECRET_VALUE",
+ ].join("\n"));
+ expect(Object.keys(identifiers).sort()).toEqual(["deploymentNames", "origins"]);
+ expect(JSON.stringify(identifiers)).not.toContain("SYNTHETIC_SECRET_VALUE");
+ expect(DEPLOYMENT_ENV_KEYS).not.toContain("CONVEX_DEPLOY_KEY");
+ });
+});
+
diff --git a/lib/infra/convex-project-link.ts b/lib/infra/convex-project-link.ts
new file mode 100644
index 00000000..6c97e557
--- /dev/null
+++ b/lib/infra/convex-project-link.ts
@@ -0,0 +1,186 @@
+// Deterministic folder → deployment linker. NO network, NO model, NO secret read.
+//
+// The input is deployment IDENTIFIERS only — `convex/` presence plus the six public
+// env names a Convex project already writes. Everything else in a project `.env` is
+// discarded while the line is being scanned, so a token never enters a return value.
+// Matching is a pure string comparison against identifiers MSO already stores on a
+// connection (cloud deployment NAME or self-hosted ORIGIN).
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { readBoundedRegularFile } from "@/lib/host/bounded-read";
+import { IntegrationError } from "./identity";
+import { convexDeploymentName } from "./convex-cloud-core";
+
+/** Env names that identify a deployment and carry no credential. */
+export const DEPLOYMENT_ENV_KEYS = [
+ "CONVEX_DEPLOYMENT",
+ "CONVEX_SELF_HOSTED_URL",
+ "PUBLIC_CONVEX_URL",
+ "NEXT_PUBLIC_CONVEX_URL",
+ "VITE_CONVEX_URL",
+] as const;
+
+const ENV_FILES = [".env.local", ".env"];
+const MAX_ENV_BYTES = 64 * 1024;
+const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
+const KNOWN = new Set<string>(DEPLOYMENT_ENV_KEYS);
+const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[^/\\\x00-\x1f]{1,200}$/;
+
+export type DeploymentIdentifiers = { deploymentNames: string[]; origins: string[] };
+
+export type LinkableConnection = {
+ user: string;
+ provider: string;
+ connection: string;
+ /** Cloud deployment name stored on the connection, if any. */
+ deploymentName?: string | null;
+ /** Self-hosted deployment origin stored on the connection, if any. */
+ origin?: string | null;
+};
+
+export type ConvexLinkOutcome = "linked" | "unmatched" | "conflict" | "no-convex-usage";
+
+export type ConvexLinkResult = {
+ outcome: ConvexLinkOutcome;
+ reason:
+ | "single-match"
+ | "no-identifier"
+ | "no-match"
+ | "multiple-matches"
+ | "identifier-disagreement"
+ | "not-a-convex-project";
+ identifiers: DeploymentIdentifiers;
+ matched: LinkableConnection[];
+};
+
+/** Project ids are exactly what `lib/host/project-list.ts` emits: `<containerId>/<name>`. */
+export function projectKey(value: unknown): string {
+ if (typeof value !== "string" || !PROJECT_ID.test(value))
+ throw new IntegrationError("invalid_project_id");
+ return value;
+}
+
+function cleanValue(raw: string): string {
+ const value = raw.trim();
+ if (value.length > 1 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))))
+ return value.slice(1, -1).trim();
+ return value.replace(/\s+#.*$/, "").trim();
+}
+
+/** `${protocol}//${host}` with a lower-case host; null when not an absolute http(s) URL. */
+function originOf(value: string): string | null {
+ let url: URL;
+ try { url = new URL(value.trim()); } catch { return null; }
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+ if (url.username || url.password) return null;
+ return `${url.protocol}//${url.host.toLowerCase()}`;
+}
+
+function addName(into: Set<string>, value: string): void {
+ try { into.add(convexDeploymentName(value)); } catch { /* not a deployment name: ignore */ }
+}
+
+/**
+ * Pure extraction over one env file's text. Only the allowlisted identifier keys are
+ * ever read; every other assignment is skipped without its value being retained.
+ */
+export function deploymentIdentifiers(text: string): DeploymentIdentifiers {
+ const deploymentNames = new Set<string>(), origins = new Set<string>();
+ for (const line of text.split(/\r?\n/)) {
+ const match = ASSIGNMENT.exec(line);
+ if (!match || !KNOWN.has(match[1])) continue;
+ const key = match[1], value = cleanValue(match[2]);
+ if (!value) continue;
+ if (key === "CONVEX_DEPLOYMENT") {
+ // `dev:name` / `prod:name` identify a cloud deployment; `local:...` and
+ // `anonymous-...` do not name a stored deployment, so they add nothing.
+ const separator = value.indexOf(":");
+ const prefix = separator < 0 ? "" : value.slice(0, separator).toLowerCase();
+ if (prefix === "local" || (!prefix && value.startsWith("anonymous-"))) continue;
+ addName(deploymentNames, separator < 0 ? value : value.slice(separator + 1));
+ continue;
+ }
+ if (key === "CONVEX_SELF_HOSTED_URL") {
+ const origin = originOf(value);
+ if (origin) origins.add(origin);
+ continue;
+ }
+ const url = (() => { try { return new URL(value.trim()); } catch { return null; } })();
+ if (!url || /\s/.test(value.trim())) continue;
+ const host = url.hostname.toLowerCase();
+ const suffix = [".convex.cloud", ".convex.site"].find((s) => host.endsWith(s));
+ // A cloud URL names a deployment; any other http(s) URL is a self-hosted origin.
+ if (suffix) addName(deploymentNames, host.slice(0, -suffix.length));
+ else { const origin = originOf(value); if (origin) origins.add(origin); }
+ }
+ return { deploymentNames: [...deploymentNames].sort(), origins: [...origins].sort() };
+}
+
+function merge(into: DeploymentIdentifiers, next: DeploymentIdentifiers): void {
+ into.deploymentNames = [...new Set([...into.deploymentNames, ...next.deploymentNames])].sort();
+ into.origins = [...new Set([...into.origins, ...next.origins])].sort();
+}
+
+export type ProjectConvexUsage = { convexDirectory: boolean; identifiers: DeploymentIdentifiers };
+
+/** Reads `convex/` presence and the identifier env files. Bounded, symlink-safe, no secrets retained. */
+export async function readProjectConvexUsage(folder: string): Promise<ProjectConvexUsage> {
+ const identifiers: DeploymentIdentifiers = { deploymentNames: [], origins: [] };
+ const directory = await fs.lstat(path.resolve(folder)).catch(() => null);
+ if (!directory?.isDirectory()) return { convexDirectory: false, identifiers };
+ const convexDir = await fs.lstat(path.join(path.resolve(folder), "convex")).catch(() => null);
+ for (const name of ENV_FILES) {
+ const text = await readBoundedRegularFile(path.join(path.resolve(folder), name), MAX_ENV_BYTES);
+ if (text) merge(identifiers, deploymentIdentifiers(text));
+ }
+ return { convexDirectory: Boolean(convexDir?.isDirectory()), identifiers };
+}
+
+function connectionKeys(row: LinkableConnection): { names: string[]; origins: string[] } {
+ const names = new Set<string>();
+ if (row.deploymentName) addName(names, row.deploymentName);
+ const origin = row.origin ? originOf(row.origin) : null;
+ return { names: [...names], origins: origin ? [origin] : [] };
+}
+
+/**
+ * Match the folder's identifiers against stored connections.
+ *
+ * `no-convex-usage` (no `convex/` at all) is deliberately NOT `unmatched`: an operator
+ * must be able to tell "this repo does not use Convex" from "this repo uses Convex but
+ * I could not resolve which stored deployment it points at".
+ */
+export function linkConvexProject(
+ usage: ProjectConvexUsage,
+ connections: LinkableConnection[],
+): ConvexLinkResult {
+ const identifiers: DeploymentIdentifiers = {
+ deploymentNames: [...new Set(usage.identifiers.deploymentNames)].sort(),
+ origins: [...new Set(usage.identifiers.origins)].sort(),
+ };
+ if (!usage.convexDirectory)
+ return { outcome: "no-convex-usage", reason: "not-a-convex-project", identifiers, matched: [] };
+
+ const names = new Set(identifiers.deploymentNames), origins = new Set(identifiers.origins);
+ const matched: LinkableConnection[] = [], seen = new Set<string>();
+ for (const row of connections) {
+ const keys = connectionKeys(row);
+ if (!keys.names.some((name) => names.has(name)) && !keys.origins.some((origin) => origins.has(origin))) continue;
+ const key = `${row.user}:${row.provider}:${row.connection}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ matched.push(row);
+ }
+
+ if (!names.size && !origins.size)
+ return { outcome: "unmatched", reason: "no-identifier", identifiers, matched };
+ // A cloud deployment name AND a self-hosted origin, or several of either, disagree
+ // about which single deployment this repo targets. So does matching two connections.
+ if ((names.size > 0 && origins.size > 0) || names.size > 1 || origins.size > 1)
+ return { outcome: "conflict", reason: "identifier-disagreement", identifiers, matched };
+ if (matched.length > 1)
+ return { outcome: "conflict", reason: "multiple-matches", identifiers, matched };
+ if (matched.length === 1)
+ return { outcome: "linked", reason: "single-match", identifiers, matched };
+ return { outcome: "unmatched", reason: "no-match", identifiers, matched };
+}
diff --git a/lib/infra/identity.ts b/lib/infra/identity.ts
index f103e44e..db7cf074 100644
--- a/lib/infra/identity.ts
+++ b/lib/infra/identity.ts
@@ -9,6 +9,9 @@ export type ExternalIdentity = { toolkit?: string; connectedAccountId?: string;
export type IntegrationConnection = {
id: string; uid: string; label: string; provider: string; source: ConnectionSource; authMethod: string;
scope: string; revision: number; values: Record<string,string>; /** Read-only alias of another direct connection. */ sharedFrom?: { user: string; connection: string; provider: string }; external?: ExternalIdentity;
+ /** Projects (`lib/host/project-list.ts` ids) this deployment belongs to. Additive:
+ * absent means "no project association yet", an old store file keeps parsing. */
+ projects?: string[];
/** Private runtime authorization; never copied into metadata or portable bundles. */
googleOAuth?: GoogleGrant; googlePending?: GooglePending;
createdAt: number; updatedAt: number; verifiedAt?: number;