Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(convex): write env over HTTP with the deployment key, and fix the regional host
Abdurrahman Fakhrulb8c19de54a2e
diff --git a/lib/infra/convex-cloud-core.ts b/lib/infra/convex-cloud-core.tsindex c5a3fd03..e08333cc 100644--- a/lib/infra/convex-cloud-core.ts+++ b/lib/infra/convex-cloud-core.ts@@ -69,8 +69,20 @@ export function convexAuthHeaders(token: string, scheme: "Bearer" | "Convex") {export function convexManagementUrl(name: string, suffix: string) {return `https://api.convex.dev/v1/deployments/${encodeURIComponent(convexDeploymentName(name))}/${suffix}`;}-export function convexDeploymentUrl(name: string, suffix: string) {- return `https://${convexDeploymentName(name)}.convex.cloud/api/v1/${suffix}`;+/** A Convex deployment can live outside the US region, and the host then carries it:+ * `laudable-bat-171.ap-southeast-2.convex.cloud`. Omitting the region answers 404, which is how+ * this was found — verified live against an ap-southeast-2 prod deployment on 2026-11-02.+ * `region` is optional so existing US callers are unchanged. */+const REGION_RE = /^[a-z]{2}(?:-[a-z]+)+-\d{1,2}$/;+export function convexDeploymentUrl(name: string, suffix: string, region?: string) {+ const host = region ? `${convexDeploymentName(name)}.${convexRegion(region)}` : convexDeploymentName(name);+ return `https://${host}.convex.cloud/api/v1/${suffix}`;+}+export function convexRegion(value: unknown): string {+ if (typeof value !== "string") throw new IntegrationError("invalid_convex_region");+ const clean = value.trim().toLowerCase();+ if (!REGION_RE.test(clean)) throw new IntegrationError("invalid_convex_region");+ return clean;}export async function convexCheckedJson(provider: string,@@ -81,14 +93,24 @@ export async function convexCheckedJson(let response;try {response = await request(url, init, TIMEOUT_MS, fetchImpl);- } catch {- throw new IntegrationError(`${provider}_request_failed`, 502);+ } catch (cause) {+ // Keep the cause as redactable detail: dropping it made a live env-write failure+ // indistinguishable from a network error, and hid the value-redaction test's subject.+ const error = new IntegrationError(`${provider}_request_failed`, 502);+ const detail = cause instanceof Error ? cause.message : String(cause);+ if (detail) Object.assign(error, { detail });+ throw error;}- if (!response.ok)- throw new IntegrationError(+ if (!response.ok) {+ const error = new IntegrationError(`${provider}_http_${response.status}`,response.status >= 500 ? 502 : 409,);+ // Bodies carry the server's reason, which is what a caller needs; the transport used to drop it.+ const detail = typeof response.body === "string" ? response.body : JSON.stringify(response.body ?? "");+ if (detail && detail !== "{}") Object.assign(error, { detail: detail.slice(0, 500) });+ throw error;+ }return response.body;}export function parseConvexDomains(value: unknown): ConvexCustomDomain[] {diff --git a/lib/infra/convex-cloud.ts b/lib/infra/convex-cloud.tsindex 4b9ee505..638e5936 100644--- a/lib/infra/convex-cloud.ts+++ b/lib/infra/convex-cloud.ts@@ -8,6 +8,6 @@ export {} from "./convex-canonical";export { getConvexEnvPresence } from "./convex-env-presence";-export { setConvexEnv } from "./convex-env-set";+export { setConvexEnv, setConvexEnvs, removeConvexEnvs } from "./convex-env-write";export { deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud-runner";diff --git a/lib/infra/convex-env-set.test.ts b/lib/infra/convex-env-set.test.tsdeleted file mode 100644index c5b582e4..00000000--- a/lib/infra/convex-env-set.test.ts+++ /dev/null@@ -1,197 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { promises as fs } from "node:fs";-import os from "node:os";-import path from "node:path";--const PAT = "pat_synthetic_12345678901234567890", KEY = "prod:happy-otter-123|synthetic_deploy_key_1234567890";-let root: string, project: string;--beforeEach(async () => {- root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-env-set-"));- process.env.OS_INFRA_STORE = path.join(root, "infra.json");- process.env.OS_FS_READ_ROOTS = root;- process.env.OS_FS_WRITE_ROOTS = root;- project = path.join(root, "project");- await fs.mkdir(path.join(project, "convex"), { recursive: true });- await fs.mkdir(path.join(project, "node_modules", ".bin"), { recursive: true });- await fs.writeFile(path.join(project, "node_modules", ".bin", "convex"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });- vi.resetModules();-});--afterEach(async () => {- delete process.env.OS_INFRA_STORE;- delete process.env.OS_FS_READ_ROOTS;- delete process.env.OS_FS_WRITE_ROOTS;- await fs.rm(root, { recursive: true, force: true });- vi.resetModules();-});--async function seeded(connectionValues: Record<string, string> = { personalToken: PAT }) {- const { integrationManage } = await import("./connection-manage");- await integrationManage({ action: "user.create", user: "alice", confirm: true });- await integrationManage({ action: "connection.create", user: "alice", provider: "convex-cloud", connection: "admin", authMethod: "personal", source: "direct", confirm: true });- const { withIntegrationSelection } = await import("./connection-service");- const { setInfraProvider } = await import("./store");- await withIntegrationSelection({ user: "alice", connection: "admin" }, () => setInfraProvider("convex-cloud", connectionValues));- return withIntegrationSelection;-}--const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });--it("successfully sets env variable and always revokes the deploy key", async () => {- const withSelection = await seeded();- let deleted = false;- const SECRET_VAL = "super-secret-client-id-xyz";- const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {- const url = String(input);- if (url.endsWith("/create_deploy_key")) {- expect(JSON.parse(String(init?.body))).toMatchObject({ allowedActions: ["deployment:env:view", "deployment:env:write"] });- return json({ deployKey: KEY });- }- if (url.endsWith("/delete_deploy_key")) { deleted = true; return json({}); }- return json({ error: "unexpected" }, 500);- });- let secretFilePath = "";- const runCli = vi.fn(async (_exe, args, options) => {- // The value must never be an argv element: /proc/<pid>/cmdline is world-readable while the CLI- // runs. It travels in a 0600 file via --from-file, and that file is removed afterwards.- expect(args).toEqual(["env", "set", "--from-file", expect.stringMatching(/mso-convex-env-/)]);- expect(args.join(" ")).not.toContain(SECRET_VAL);- secretFilePath = args[3];- const onDisk = await fs.readFile(secretFilePath, "utf8");- expect(onDisk).toBe(`AUTH_GOOGLE_ID=${SECRET_VAL}\n`);- const mode = (await fs.stat(secretFilePath)).mode & 0o777;- expect(mode, "the temp file must not be readable by other users").toBe(0o600);- expect(options.env.CONVEX_DEPLOY_KEY).toBe(KEY);- return { code: 0, stdout: "successfully set AUTH_GOOGLE_ID", stderr: "", durationMs: 10 };- });-- const { setConvexEnv } = await import("./convex-env-set");- const result = await withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "happy-otter-123", name: "AUTH_GOOGLE_ID", value: SECRET_VAL, projectPath: project }, { fetchImpl, runCli })- );- expect(result).toEqual({ deploymentName: "happy-otter-123", name: "AUTH_GOOGLE_ID", set: true });- expect(deleted).toBe(true);- await expect(fs.stat(secretFilePath)).rejects.toMatchObject({ code: "ENOENT" });- expect(JSON.stringify(result)).not.toContain(SECRET_VAL);- expect(JSON.stringify(result)).not.toContain(KEY);-});--it("always revokes deploy key even when writing fails and redacts value from error", async () => {- const withSelection = await seeded();- let deleted = false;- const SECRET_VAL = "leaked-secret-value-123";- const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {- const url = String(input);- if (url.endsWith("/create_deploy_key")) return json({ deployKey: KEY });- if (url.endsWith("/delete_deploy_key")) { deleted = true; return json({}); }- return json({ error: "unexpected" }, 500);- });- const runCli = vi.fn(async () => ({ code: 1, stdout: "", stderr: `failed to set variable with ${SECRET_VAL}`, durationMs: 10 }));-- const { setConvexEnv } = await import("./convex-env-set");- let caught: unknown;- try {- await withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "happy-otter-123", name: "AUTH_GOOGLE_ID", value: SECRET_VAL, projectPath: project }, { fetchImpl, runCli })- );- } catch (error) { caught = error; }-- expect(deleted).toBe(true);- expect(caught).toBeDefined();- expect((caught as { code: string }).code).toBe("convex_cloud_env_set_failed");- expect(JSON.stringify(caught)).not.toContain(SECRET_VAL);- expect(JSON.stringify(caught)).not.toContain(KEY);-});--it("redacts secret value when child process throws an unexpected error", async () => {- const withSelection = await seeded();- let deleted = false;- const SECRET_VAL = "unhandled-secret-content";- const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {- const url = String(input);- if (url.endsWith("/create_deploy_key")) return json({ deployKey: KEY });- if (url.endsWith("/delete_deploy_key")) { deleted = true; return json({}); }- return json({ error: "unexpected" }, 500);- });- const runCli = vi.fn(async () => { throw new Error(`crash with ${SECRET_VAL}`); });-- const { setConvexEnv } = await import("./convex-env-set");- let caught: unknown;- try {- await withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "happy-otter-123", name: "AUTH_GOOGLE_ID", value: SECRET_VAL, projectPath: project }, { fetchImpl, runCli })- );- } catch (error) { caught = error; }-- expect(deleted).toBe(true);- expect(caught).toBeDefined();- expect((caught as Error).message).not.toContain(SECRET_VAL);-});--it("refuses malformed or invalid env names without calling cloud APIs", async () => {- const withSelection = await seeded();- const fetchImpl = vi.fn();- const { setConvexEnv } = await import("./convex-env-set");-- for (const badName of ["", "BAD-NAME", "123_START_NUM", "has spaces", "a".repeat(129)]) {- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "happy-otter-123", name: badName, value: "valid-value", projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "invalid_convex_env_name" });- }- expect(fetchImpl).not.toHaveBeenCalled();-});--it("refuses values larger than 8KiB without calling cloud APIs", async () => {- const withSelection = await seeded();- const fetchImpl = vi.fn();- const { setConvexEnv } = await import("./convex-env-set");- const tooLarge = "x".repeat(8 * 1024 + 1);-- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "happy-otter-123", name: "VALID_NAME", value: tooLarge, projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "convex_env_value_too_large" });- expect(fetchImpl).not.toHaveBeenCalled();-});--it("refuses when deploymentName is missing from input and connection", async () => {- const withSelection = await seeded();- const fetchImpl = vi.fn();- const { setConvexEnv } = await import("./convex-env-set");-- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "", name: "VALID_NAME", value: "test-val", projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "convex_deployment_name_required", status: 409 });-- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: " ", name: "VALID_NAME", value: "test-val", projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "convex_deployment_name_required", status: 409 });-- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ name: "VALID_NAME", value: "test-val", projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "convex_deployment_name_required", status: 409 });- expect(fetchImpl).not.toHaveBeenCalled();-});--it("refuses malformed deploymentName with invalid_convex_deployment_name", async () => {- const withSelection = await seeded();- const fetchImpl = vi.fn();- const { setConvexEnv } = await import("./convex-env-set");-- await expect(- withSelection({ user: "alice", connection: "admin" }, () =>- setConvexEnv({ deploymentName: "-invalid-start", name: "VALID_NAME", value: "test-val", projectPath: project }, { fetchImpl })- )- ).rejects.toMatchObject({ code: "invalid_convex_deployment_name" });- expect(fetchImpl).not.toHaveBeenCalled();-});diff --git a/lib/infra/convex-env-set.ts b/lib/infra/convex-env-set.tsdeleted file mode 100644index 8db2cc4e..00000000--- a/lib/infra/convex-env-set.ts+++ /dev/null@@ -1,177 +0,0 @@-import { randomUUID } from "node:crypto";-import { promises as fs } from "node:fs";-import os from "node:os";-import path from "node:path";-import { obj } from "./http";-import { IntegrationError } from "./identity";-import { readInfraProvider } from "./store";-import { currentIntegrationSelection } from "./connection-service";-import {- convexAuthHeaders,- convexCheckedJson,- convexDeploymentName,- convexManagementUrl,- type FetchLike,-} from "./convex-cloud-core";-import {- convexCliEnv,- convexProjectContext,- redactConvexCliText,- runConvexCli,- type RunConvexCli,-} from "./convex-cloud-cli-runner";--export type ConvexEnvSetDeps = {- fetchImpl?: FetchLike;- runCli?: RunConvexCli;-};--const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;-const MAX_ENV_VALUE_BYTES = 8 * 1024;-const ENV_SET_TIMEOUT_MS = 60_000;--function validateEnvName(value: unknown): string {- if (typeof value !== "string" || !ENV_NAME.test(value.trim()))- throw new IntegrationError("invalid_convex_env_name");- return value.trim();-}--function validateEnvValue(value: unknown): string {- if (typeof value !== "string")- throw new IntegrationError("invalid_convex_env_value");- if (Buffer.byteLength(value, "utf8") > MAX_ENV_VALUE_BYTES)- throw new IntegrationError("convex_env_value_too_large");- return value;-}--function redactValueFromError(error: unknown, value: string): void {- if (!error || !value || typeof error !== "object") return;- const anyErr = error as Record<string, unknown>;- if (typeof anyErr.message === "string" && anyErr.message.includes(value)) {- anyErr.message = anyErr.message.split(value).join("[REDACTED_VALUE]");- }- if (typeof anyErr.detail === "string" && anyErr.detail.includes(value)) {- anyErr.detail = anyErr.detail.split(value).join("[REDACTED_VALUE]");- }-}--export async function setConvexEnv(- input: {- deploymentName?: string;- name: string;- value: string;- projectPath?: string;- },- deps: ConvexEnvSetDeps = {},-) {- const name = validateEnvName(input.name);- const value = validateEnvValue(input.value);-- const providerValues = await readInfraProvider("convex-cloud");- const token = providerValues.personalToken;- if (!token) throw new IntegrationError("convex_personal_token_required", 409);-- const candidateDeployment =- typeof input.deploymentName === "string" && input.deploymentName.trim().length > 0- ? input.deploymentName.trim()- : typeof providerValues.deploymentName === "string" && providerValues.deploymentName.trim().length > 0- ? providerValues.deploymentName.trim()- : "";-- if (!candidateDeployment)- throw new IntegrationError("convex_deployment_name_required", 409);-- const deployment = convexDeploymentName(candidateDeployment);- const keyName = `mso-env-set-${randomUUID()}`;- const fetchImpl = deps.fetchImpl ?? fetch;- const execute = deps.runCli ?? runConvexCli;-- const created = obj(- await convexCheckedJson(- "convex_cloud",- convexManagementUrl(deployment, "create_deploy_key"),- {- method: "POST",- headers: convexAuthHeaders(token, "Bearer"),- body: JSON.stringify({- name: keyName,- allowedActions: ["deployment:env:view", "deployment:env:write"],- }),- },- fetchImpl,- ),- );-- const deployKey = created.deployKey;- if (- typeof deployKey !== "string" ||- deployKey.length < 20 ||- /[\x00-\x20\x7f]/.test(deployKey)- )- throw new IntegrationError("invalid_convex_deploy_key_response", 502);-- let primary: unknown;- let secretFile: string | undefined;- try {- const projectPath = input.projectPath ?? currentIntegrationSelection().cwd;- const { project, executable } = await convexProjectContext(projectPath);- // The value must NOT travel as an argv element: any process on the host can read- // /proc/<pid>/cmdline while the CLI runs, and `env set NAME <value>` puts the secret there.- // `--from-file` keeps it in a 0600 file that is removed in the finally below.- secretFile = path.join(os.tmpdir(), `mso-convex-env-${randomUUID()}`);- await fs.writeFile(secretFile, `${name}=${value}\n`, { mode: 0o600, flag: "wx" });- const result = await execute(executable, ["env", "set", "--from-file", secretFile], {- cwd: project,- env: convexCliEnv(deployKey),- timeoutMs: ENV_SET_TIMEOUT_MS,- });- if (result.code !== 0) {- const redacted = redactConvexCliText(- [result.stderr, result.stdout].filter(Boolean).join("\n"),- deployKey,- )- .split(value)- .join("[REDACTED_VALUE]");- const error = new IntegrationError("convex_cloud_env_set_failed", 502);- Object.assign(error, {- detail: redacted || `convex env set exited ${result.code}`,- });- throw error;- }- } catch (error) {- primary = error;- } finally {- if (secretFile) await fs.rm(secretFile, { force: true }).catch(() => undefined);- }-- try {- await convexCheckedJson(- "convex_cloud",- convexManagementUrl(deployment, "delete_deploy_key"),- {- method: "POST",- headers: convexAuthHeaders(token, "Bearer"),- body: JSON.stringify({ id: keyName }),- },- fetchImpl,- );- } catch {- throw new IntegrationError(- primary- ? "convex_operation_and_ephemeral_cleanup_failed"- : "convex_ephemeral_cleanup_failed",- 502,- );- }-- if (primary) {- redactValueFromError(primary, value);- throw primary;- }-- return {- deploymentName: deployment,- name,- set: true,- };-}diff --git a/lib/infra/convex-env-write.test.ts b/lib/infra/convex-env-write.test.tsnew file mode 100644index 00000000..cccdb1d2--- /dev/null+++ b/lib/infra/convex-env-write.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it, vi } from "vitest";++// Contract for writing Convex deployment env vars over HTTP.+//+// Two things here were learned the hard way against a live deployment (laudable-bat-171,+// ap-southeast-2, 2026-11-02) rather than from docs:+//+// 1. A deployment deploy key authenticates `update_environment_variables` directly. Minting an+// ephemeral key from a personal token, and shelling out to `convex env set`, were both+// unnecessary — and the CLI path additionally required a project checkout that a credential+// connection does not have.+// 2. A deployment outside the US needs its region in the host or every call answers 404.++const KEY = "prod:laudable-bat-171|" + "A".repeat(40);++async function seeded(values: Record<string, string> = {}) {+ vi.resetModules();+ const store = await import("./store");+ vi.spyOn(store, "readInfraProvider").mockResolvedValue({+ deployKey: KEY,+ deploymentName: "laudable-bat-171",+ ...values,+ });+ return import("./convex-env-write");+}++function okJson() {+ return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });+}++describe("convex env write", () => {+ it("writes with the deployment key itself, over HTTP, to the region-qualified host", async () => {+ const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());++ const result = await setConvexEnv({ name: "AUTH_GOOGLE_ID", value: "s3cret" }, fetchImpl as never);++ expect(result).toEqual({ deploymentName: "laudable-bat-171", name: "AUTH_GOOGLE_ID", set: true });+ const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];+ // The region must be in the hostname; without it a non-US deployment answers 404.+ expect(url).toBe("https://laudable-bat-171.ap-southeast-2.convex.cloud/api/v1/update_environment_variables");+ expect((init.headers as Record<string, string>).authorization).toBe(`Convex ${KEY}`);+ expect(JSON.parse(String(init.body))).toEqual({ changes: [{ name: "AUTH_GOOGLE_ID", value: "s3cret" }] });+ });++ it("falls back to the US host when no region is configured", async () => {+ const { setConvexEnv } = await seeded();+ const fetchImpl = vi.fn(async () => okJson());+ await setConvexEnv({ name: "A", value: "b" }, fetchImpl as never);+ expect((fetchImpl.mock.calls[0] as unknown as [string])[0])+ .toBe("https://laudable-bat-171.convex.cloud/api/v1/update_environment_variables");+ });++ it("never returns the value", async () => {+ const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const result = await setConvexEnv({ name: "A", value: "do-not-echo-me" }, (async () => okJson()) as never);+ expect(JSON.stringify(result)).not.toContain("do-not-echo-me");+ });++ it("redacts the value when the server echoes it back in a rejection", async () => {+ // The realistic shape: Convex answers 4xx with a body quoting what it refused.+ const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = async () =>+ new Response(JSON.stringify({ code: "BadRequest", message: "invalid value s3cret-value" }), {+ status: 400,+ headers: { "content-type": "application/json" },+ });++ const error = await setConvexEnv({ name: "A", value: "s3cret-value" }, fetchImpl as never).catch((e) => e);+ expect(error.code).toBe("convex_deployment_http_400");+ // Whatever the shape, the secret must not be reachable from the error.+ expect(JSON.stringify({ ...error, message: error.message })).not.toContain("s3cret-value");+ expect(String(error.detail)).toContain("[REDACTED_VALUE]");+ });++ it("refuses a value over 8 KiB without making a request", async () => {+ const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());+ await expect(setConvexEnv({ name: "A", value: "x".repeat(8 * 1024 + 1) }, fetchImpl as never))+ .rejects.toMatchObject({ code: "convex_env_value_too_large" });+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it("refuses an invalid name without making a request", async () => {+ const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());+ await expect(setConvexEnv({ name: "1BAD NAME", value: "v" }, fetchImpl as never))+ .rejects.toMatchObject({ code: "invalid_convex_env_name" });+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it("names the missing field when the connection has no deployment", async () => {+ vi.resetModules();+ const store = await import("./store");+ vi.spyOn(store, "readInfraProvider").mockResolvedValue({ deployKey: KEY, deploymentName: "" });+ const { setConvexEnv } = await import("./convex-env-write");+ await expect(setConvexEnv({ name: "A", value: "v" }, (async () => okJson()) as never))+ .rejects.toMatchObject({ code: "convex_deployment_name_required", status: 409 });+ });++ it("requires a deploy key", async () => {+ vi.resetModules();+ const store = await import("./store");+ vi.spyOn(store, "readInfraProvider").mockResolvedValue({ deploymentName: "d" });+ const { setConvexEnv } = await import("./convex-env-write");+ await expect(setConvexEnv({ name: "A", value: "v" }, (async () => okJson()) as never))+ .rejects.toMatchObject({ code: "convex_deploy_key_required", status: 409 });+ });++ it("sends a batch as one request", async () => {+ const { setConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());+ const result = await setConvexEnvs(+ { changes: [{ name: "A", value: "1" }, { name: "B", value: "2" }] },+ fetchImpl as never,+ );+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ expect(result.names).toEqual(["A", "B"]);+ expect(JSON.parse(String((fetchImpl.mock.calls[0] as unknown as [string, RequestInit])[1].body)))+ .toEqual({ changes: [{ name: "A", value: "1" }, { name: "B", value: "2" }] });+ });++ it("deletes with delete:true and no value, which is the shape the API accepts", async () => {+ const { removeConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());+ await removeConvexEnvs({ names: ["A", "A", "B"] }, fetchImpl as never);+ expect(JSON.parse(String((fetchImpl.mock.calls[0] as unknown as [string, RequestInit])[1].body)))+ .toEqual({ changes: [{ name: "A", delete: true }, { name: "B", delete: true }] });+ });++ it("rejects an over-wide batch instead of sending it", async () => {+ const { setConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });+ const fetchImpl = vi.fn(async () => okJson());+ const changes = Array.from({ length: 33 }, (_, i) => ({ name: `K${i}`, value: "v" }));+ await expect(setConvexEnvs({ changes }, fetchImpl as never))+ .rejects.toMatchObject({ code: "invalid_convex_env_changes" });+ expect(fetchImpl).not.toHaveBeenCalled();+ });+});diff --git a/lib/infra/convex-env-write.ts b/lib/infra/convex-env-write.tsnew file mode 100644index 00000000..943ccf5d--- /dev/null+++ b/lib/infra/convex-env-write.ts@@ -0,0 +1,143 @@+// Write, update and delete Convex deployment environment variables.+//+// DESIGN CORRECTION, from a live deployment (`laudable-bat-171`, 2026-11-02). An earlier version of+// this file minted an ephemeral deploy key from the personal token and shelled out to+// `convex env set --from-file`. Both halves were unnecessary:+//+// POST https://<deployment>.convex.cloud/api/v1/update_environment_variables+// authorization: Convex <deploy key> <- the key itself, no minting needed+// { "changes": [ { "name": "K", "value": "V" } ] }+//+// Verified against the live deployment: create 200, update 200, delete 200, list reflects each+// change. A deployment deploy key (`prod:<name>|…`) carries `deployment:env:write` for its own+// deployment, so no personal token, no ephemeral key, and no CLI project checkout are required.+//+// That matters beyond convenience: the CLI path required a project directory with+// `node_modules/.bin/convex`, which a credential connection does not have. The HTTP path works for+// the thing the connection actually is.+//+// Value redaction stays: callers must never see the value back, in output or in an error.+import { IntegrationError } from "./identity";+import { readInfraProvider } from "./store";+import {+ convexAuthHeaders,+ convexCheckedJson,+ convexDeploymentName,+ convexDeploymentUrl,+ type FetchLike,+} from "./convex-cloud-core";++const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;+/** Convex caps a single value at 8 KiB. */+const MAX_ENV_VALUE_BYTES = 8 * 1024;++function envName(value: unknown): string {+ if (typeof value !== "string" || !ENV_NAME.test(value.trim()))+ throw new IntegrationError("invalid_convex_env_name");+ return value.trim();+}++function envValue(value: unknown): string {+ if (typeof value !== "string") throw new IntegrationError("invalid_convex_env_value");+ if (Buffer.byteLength(value, "utf8") > MAX_ENV_VALUE_BYTES)+ throw new IntegrationError("convex_env_value_too_large");+ return value;+}++/** Keep a caller-supplied secret out of anything that can be surfaced. */+function redact(error: unknown, value: string): void {+ if (!error || !value || typeof error !== "object") return;+ const target = error as Record<string, unknown>;+ for (const key of ["message", "detail"] as const) {+ if (typeof target[key] === "string" && (target[key] as string).includes(value))+ target[key] = (target[key] as string).split(value).join("[REDACTED_VALUE]");+ }+}++/** Run a request and scrub every given secret out of whatever it throws.+ * Wrapping here rather than around each call site keeps the guarantee in one place: the transport+ * rethrows a normalised error, so a call-site-local catch would otherwise miss the value. */+async function withRedaction(secrets: string[], run: () => Promise<void>): Promise<void> {+ try {+ await run();+ } catch (error) {+ for (const secret of secrets) redact(error, secret);+ throw error;+ }+}++async function deploymentFor(input: { deploymentName?: string }): Promise<{ name: string; key: string; region?: string }> {+ const values = await readInfraProvider("convex-cloud");+ const key = values.deployKey;+ if (!key) throw new IntegrationError("convex_deploy_key_required", 409);+ const chosen =+ (typeof input.deploymentName === "string" && input.deploymentName.trim()) ||+ (typeof values.deploymentName === "string" && values.deploymentName.trim()) ||+ "";+ if (!chosen) throw new IntegrationError("convex_deployment_name_required", 409);+ // A non-US deployment needs its region in the host; without it every call answers 404.+ const region = typeof values.deploymentRegion === "string" && values.deploymentRegion.trim()+ ? values.deploymentRegion.trim()+ : undefined;+ return { name: convexDeploymentName(chosen), key, region };+}++/** One POST carrying every change. `delete` removes a name; `value` sets it. */+async function postChanges(+ deployment: string,+ key: string,+ changes: Array<{ name: string; value?: string; delete?: true }>,+ fetchImpl: FetchLike,+ region?: string,+): Promise<void> {+ await convexCheckedJson(+ "convex_deployment",+ convexDeploymentUrl(deployment, "update_environment_variables", region),+ {+ method: "POST",+ headers: convexAuthHeaders(key, "Convex"),+ body: JSON.stringify({ changes }),+ },+ fetchImpl,+ );+}++export type ConvexEnvChange = { name: string; value: string };++/** Set one value. Never returns it. */+export async function setConvexEnv(+ input: { deploymentName?: string; name: string; value: string },+ fetchImpl: FetchLike = fetch,+) {+ const name = envName(input.name);+ const value = envValue(input.value);+ const { name: deployment, key, region } = await deploymentFor(input);+ await withRedaction([value], () => postChanges(deployment, key, [{ name, value }], fetchImpl, region));+ return { deploymentName: deployment, name, set: true as const };+}++/** Set several at once — one request, which is what Convex's API is shaped for. */+export async function setConvexEnvs(+ input: { deploymentName?: string; changes: ConvexEnvChange[] },+ fetchImpl: FetchLike = fetch,+) {+ if (!Array.isArray(input.changes) || input.changes.length < 1 || input.changes.length > 32)+ throw new IntegrationError("invalid_convex_env_changes");+ const changes = input.changes.map((row) => ({ name: envName(row.name), value: envValue(row.value) }));+ const { name: deployment, key, region } = await deploymentFor(input);+ await withRedaction(changes.map((row) => row.value), () => postChanges(deployment, key, changes, fetchImpl, region));+ return { deploymentName: deployment, names: changes.map((row) => row.name), set: true as const };+}++/** Remove names. Convex deletes on `delete: true` with no value. */+export async function removeConvexEnvs(+ input: { deploymentName?: string; names: string[] },+ fetchImpl: FetchLike = fetch,+) {+ if (!Array.isArray(input.names) || input.names.length < 1 || input.names.length > 32)+ throw new IntegrationError("invalid_convex_env_names");+ const names = [...new Set(input.names.map(envName))];+ const { name: deployment, key, region } = await deploymentFor(input);+ await postChanges(deployment, key, names.map((name) => ({ name, delete: true as const })), fetchImpl, region);+ return { deploymentName: deployment, names, removed: true as const };+}