An open-source, faster Devin alternative
TypeScript
feat: sync local development secrets (#625)
Mohamed Habib638454c4f0ad
diff --git a/cli/README.md b/cli/README.mdindex e026bd93..8c11d0ad 100644--- a/cli/README.md+++ b/cli/README.md@@ -50,6 +50,11 @@ Secret values are read from a hidden prompt, or from standard input in CI.They are write-only: list output contains names, scope, environment, andallowed origins, never values.+During development, put agent secrets in `opencomputer/.env.local`. The CLI+syncs only names referenced by `useSecret()` and limits each value to origins+declared by `defineConnection()`. It asks before the first upload, watches for+changes, and skips unrelated variables rather than granting wildcard access.+```bash# Project-level development secret. Allowed origins are inferred from code.opencomputer secrets set GITHUB_TOKENdiff --git a/cli/src/dev.test.ts b/cli/src/dev.test.tsindex 305f3696..057af379 100644--- a/cli/src/dev.test.ts+++ b/cli/src/dev.test.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { resolve } from "node:path";import test from "node:test";@@ -9,6 +9,7 @@ import {projectDashboardURL,publishDevelopment,publishProjectDevelopment,+ syncDevelopmentSecrets,} from "./dev.js";import { initializeAgentProject } from "./project.js";@@ -123,3 +124,145 @@ test("development publish synchronizes every configured project agent", async ()await rm(parent, { recursive: true, force: true });}});++test("development syncs declared .env.local secrets to inferred origins", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-secrets-"));+ try {+ const initialized = await initializeAgentProject(+ resolve(parent, "app"),+ undefined,+ { spa: false },+ );+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ await writeFile(+ resolve(initialized.agentRoot, "tools", "github.ts"),+ `import { bearer, defineConnection, defineTool, useSecret } from "@opencomputer/agent";++const github = defineConnection({+ id: "github-api",+ origin: "https://api.github.com",+ headers: { Authorization: bearer(useSecret("GITHUB_TOKEN")) },+});++export const repository = defineTool({+ name: "github_repository",+ description: "Read a GitHub repository",+ async run() { return await (await github.fetch("/repos/opencomputer/example")).json(); },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useTool } from "@opencomputer/agent";+import { repository } from "./tools/github.js";+export default function Agent() { useTool(repository); return "Use GitHub."; }+`,+ );+ const binding = {+ version: 1 as const,+ apiUrl: "https://app.opencomputer.dev",+ projectId: "prj_test",+ projectName: "Test",+ agentId: "test-agent",+ };+ const results = await publishProjectDevelopment(+ {+ async registerDeployment(value) {+ return {+ id: `${value.agentId}:${value.source.digest}`,+ agentId: value.agentId,+ alias: value.alias,+ createdAt: new Date(0).toISOString(),+ };+ },+ },+ initialized.root,+ binding,+ );+ await writeFile(+ resolve(initialized.root, "opencomputer", ".env.local"),+ "GITHUB_TOKEN=first-secret\n",+ );+ const uploads: Array<{+ name: string;+ value: string;+ allowedOrigins: string[];+ }> = [];+ let confirmations = 0;+ const client = {+ async putSecret(input: {+ projectId: string;+ name: string;+ value: string;+ environment: "development" | "production";+ agentId?: string;+ allowedOrigins: string[];+ }) {+ uploads.push(input);+ return {+ name: input.name,+ projectId: input.projectId,+ environment: input.environment,+ allowedOrigins: input.allowedOrigins,+ createdAt: new Date(0).toISOString(),+ updatedAt: new Date(0).toISOString(),+ };+ },+ };+ const confirm = async () => {+ confirmations += 1;+ return true;+ };+ assert.deepEqual(+ await syncDevelopmentSecrets(+ client,+ { apiUrl: binding.apiUrl },+ initialized.root,+ binding,+ results,+ { confirm },+ ),+ ["GITHUB_TOKEN"],+ );+ assert.deepEqual(uploads, [+ {+ projectId: "prj_test",+ name: "GITHUB_TOKEN",+ value: "first-secret",+ environment: "development",+ allowedOrigins: ["https://api.github.com"],+ },+ ]);+ await syncDevelopmentSecrets(+ client,+ { apiUrl: binding.apiUrl },+ initialized.root,+ binding,+ results,+ { confirm },+ );+ assert.equal(uploads.length, 1);+ await writeFile(+ resolve(initialized.root, "opencomputer", ".env.local"),+ "GITHUB_TOKEN=changed-secret\n",+ );+ await syncDevelopmentSecrets(+ client,+ { apiUrl: binding.apiUrl },+ initialized.root,+ binding,+ results,+ { confirm },+ );+ assert.equal(confirmations, 1);+ assert.equal(uploads.length, 2);+ assert.equal(uploads[1]?.value, "changed-secret");+ const state = await readFile(+ resolve(initialized.root, ".opencomputer", "dev-secrets.json"),+ "utf8",+ );+ assert.doesNotMatch(state, /first-secret|changed-secret/);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex 92d93eb9..21f195ab 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -1,7 +1,10 @@import { spawn, type ChildProcess } from "node:child_process";+import { createHash } from "node:crypto";import { watch, type FSWatcher } from "node:fs";-import { access, mkdir, rm, writeFile } from "node:fs/promises";+import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { resolve } from "node:path";+import { createInterface } from "node:readline/promises";+import { parseEnv } from "node:util";import type { OpenComputerClient } from "./api.js";import type { ResolvedConfig } from "./config.js";@@ -17,6 +20,187 @@ import { buildAgentArtifact, readProjectAgents } from "./project.js";const DEVELOPMENT_ALIAS = "development";const DEBOUNCE_MS = 180;+type DevelopmentResults = Awaited<+ ReturnType<typeof publishProjectDevelopment>+>;++interface SecretSyncState {+ version: 1;+ apiUrl: string;+ projectId: string;+ hashes: Record<string, string>;+}++function secretSyncStatePath(projectRoot: string): string {+ return resolve(projectRoot, ".opencomputer", "dev-secrets.json");+}++async function readSecretSyncState(+ projectRoot: string,+ config: ResolvedConfig,+ binding: ProjectBinding,+): Promise<SecretSyncState> {+ try {+ const value = JSON.parse(+ await readFile(secretSyncStatePath(projectRoot), "utf8"),+ ) as Partial<SecretSyncState>;+ if (+ value.version === 1 &&+ value.apiUrl === config.apiUrl &&+ value.projectId === binding.projectId &&+ value.hashes &&+ typeof value.hashes === "object"+ ) {+ return value as SecretSyncState;+ }+ } catch {+ // A missing or invalid state file requires fresh consent.+ }+ return {+ version: 1,+ apiUrl: config.apiUrl,+ projectId: binding.projectId,+ hashes: {},+ };+}++function secretOrigins(results: DevelopmentResults): Map<string, string[]> {+ const origins = new Map<string, Set<string>>();+ for (const { built } of results) {+ for (const connection of built.httpConnections) {+ for (const header of Object.values(connection.headers)) {+ if (typeof header === "string") continue;+ const current = origins.get(header.name) ?? new Set<string>();+ current.add(connection.origin);+ origins.set(header.name, current);+ }+ }+ }+ return new Map(+ [...origins].map(([name, values]) => [name, [...values].sort()]),+ );+}++function secretHash(value: string, origins: string[]): string {+ return createHash("sha256")+ .update(JSON.stringify({ value, origins }))+ .digest("hex");+}++async function confirmNewSecrets(+ secrets: Array<{ name: string; origins: string[] }>,+): Promise<boolean> {+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;+ process.stdout.write("\nSecrets found in opencomputer/.env.local:\n\n");+ for (const secret of secrets) {+ process.stdout.write(+ ` ${secret.name.padEnd(28)} → ${secret.origins.map((origin) => new URL(origin).host).join(", ")}\n`,+ );+ }+ const terminal = createInterface({+ input: process.stdin,+ output: process.stdout,+ });+ try {+ const answer = (+ await terminal.question("\nSync these development secrets? [Y/n] ")+ )+ .trim()+ .toLowerCase();+ return answer === "" || answer === "y" || answer === "yes";+ } finally {+ terminal.close();+ }+}++export async function syncDevelopmentSecrets(+ client: Pick<OpenComputerClient, "putSecret">,+ config: ResolvedConfig,+ projectRoot: string,+ binding: ProjectBinding,+ results: DevelopmentResults,+ options: {+ confirm?: (+ secrets: Array<{ name: string; origins: string[] }>,+ ) => Promise<boolean>;+ } = {},+): Promise<string[]> {+ const path = resolve(projectRoot, "opencomputer", ".env.local");+ let values: Record<string, string | undefined>;+ try {+ values = parseEnv(await readFile(path, "utf8"));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }++ const origins = secretOrigins(results);+ const referenced = [...origins]+ .filter(([name]) => typeof values[name] === "string" && values[name] !== "")+ .map(([name, allowedOrigins]) => ({+ name,+ value: values[name]!,+ origins: allowedOrigins,+ }));+ const unmatched = Object.keys(values)+ .filter(+ (name) =>+ typeof values[name] === "string" &&+ values[name] !== "" &&+ !origins.has(name),+ )+ .sort();+ for (const name of unmatched) {+ process.stderr.write(+ `Skipped ${name}: it is not referenced by a defineConnection() declaration.\n`,+ );+ }+ if (!referenced.length) return [];++ const state = await readSecretSyncState(projectRoot, config, binding);+ const pending = referenced.filter(+ (secret) =>+ state.hashes[secret.name] !== secretHash(secret.value, secret.origins),+ );+ if (!pending.length) return [];+ const newSecrets = pending.filter((secret) => !(secret.name in state.hashes));+ if (newSecrets.length) {+ const confirmed = await (options.confirm ?? confirmNewSecrets)(newSecrets);+ if (!confirmed) {+ process.stderr.write(+ "Development secret sync skipped. Use `opencomputer secrets set` or restart dev to approve it.\n",+ );+ return [];+ }+ }++ const synced: string[] = [];+ for (const secret of pending) {+ await client.putSecret({+ projectId: binding.projectId,+ name: secret.name,+ value: secret.value,+ environment: "development",+ allowedOrigins: secret.origins,+ });+ state.hashes[secret.name] = secretHash(secret.value, secret.origins);+ synced.push(secret.name);+ process.stdout.write(+ `Synced development secret ${secret.name} for ${secret.origins.join(", ")}\n`,+ );+ }+ await mkdir(resolve(projectRoot, ".opencomputer"), {+ recursive: true,+ mode: 0o700,+ });+ await writeFile(+ secretSyncStatePath(projectRoot),+ `${JSON.stringify(state, null, 2)}\n`,+ { mode: 0o600 },+ );+ return synced;+}+export async function publishDevelopment(client: Pick<OpenComputerClient, "registerDeployment">,root: string,@@ -73,6 +257,11 @@ function sourceChange(filename: string | Buffer | null): boolean {return !normalized.split("/").includes(".opencomputer");}+function secretFileChange(filename: string | Buffer | null): boolean {+ if (!filename) return false;+ return filename.toString().replaceAll("\\", "/") === ".env.local";+}+function waitForShutdown(web?: ChildProcess): Promise<void> {return new Promise((done) => {const cleanup = () => {@@ -163,6 +352,27 @@ export async function runCloudDevelopment(let publishing = false;let pending = false;const lastDigests = new Map<string, string>();+ let latestResults: DevelopmentResults = [];+ let secretSync = Promise.resolve();++ const syncSecrets = () => {+ secretSync = secretSync+ .then(async () => {+ await syncDevelopmentSecrets(+ client,+ config,+ projectRoot,+ binding,+ latestResults,+ );+ })+ .catch((error) => {+ process.stderr.write(+ `Secret sync failed: ${error instanceof Error ? error.message : String(error)}\n`,+ );+ });+ return secretSync;+ };const publish = async () => {if (publishing) {@@ -179,6 +389,7 @@ export async function runCloudDevelopment(projectRoot,binding,);+ latestResults = results;for (const result of results) {if (result.built.digest !== lastDigests.get(result.deployment.agentId)@@ -189,6 +400,7 @@ export async function runCloudDevelopment();}}+ await syncSecrets();} catch (error) {process.stderr.write(`Sync failed: ${error instanceof Error ? error.message : String(error)}\n`,@@ -206,9 +418,11 @@ export async function runCloudDevelopment(projectRoot,binding,);+ latestResults = initial;for (const result of initial) {lastDigests.set(result.deployment.agentId, result.built.digest);}+ await syncSecrets();const spa = await hasReactSpa(projectRoot);process.stdout.write(`Development (Cloud)\n` +@@ -226,6 +440,11 @@ export async function runCloudDevelopment(resolve(projectRoot, "opencomputer"),{ recursive: true },(_event, filename) => {+ if (secretFileChange(filename)) {+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => void syncSecrets(), DEBOUNCE_MS);+ return;+ }if (!sourceChange(filename)) return;if (timer) clearTimeout(timer);timer = setTimeout(() => void publish(), DEBOUNCE_MS);diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex a7e2204e..a1291175 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -68,7 +68,11 @@ test("init creates a multi-agent-ready project and React hello world app", async);assert.match(await readFile(resolve(root, "README.md"), "utf8"),- /Sync agent code to Development \(Cloud\)/,+ /Sync agent code to Development \(Cloud\)[\s\S]*opencomputer\/\.env\.local/,+ );+ assert.match(+ await readFile(resolve(root, "opencomputer", ".env.example"), "utf8"),+ /useSecret\(\)/,);assert.equal(await readFile(resolve(root, "NOTES.md"), "utf8"),@@ -96,6 +100,7 @@ test("init creates a multi-agent-ready project and React hello world app", async}assert.deepEqual(initialized.files, ["opencomputer/project.ts",+ "opencomputer/.env.example","opencomputer/agents/hello-world/agent.ts","package.json","vite.config.ts",@@ -141,6 +146,7 @@ test("init can create an agent-only project", async () => {assert.equal(packageJSON.devDependencies.vite, undefined);assert.deepEqual(initialized.files, ["opencomputer/project.ts",+ "opencomputer/.env.example","opencomputer/agents/hello-world/agent.ts","package.json","README.md",diff --git a/cli/src/project.ts b/cli/src/project.tsindex 752cdda1..cd52436b 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -329,6 +329,12 @@ export default function Agent() {`,);await updateGitignore(root);+ await writeFile(+ resolve(root, "opencomputer", ".env.example"),+ `# Development agent secrets belong in .env.local beside this file.+# Add only names referenced by useSecret() in a defineConnection() declaration.+`,+ );if (spa) await mkdir(resolve(root, "src"), { recursive: true });await writeFile(resolve(root, "opencomputer", "project.ts"),@@ -606,6 +612,10 @@ npm run devThe first run asks you to create a cloud project or select an existing one.That choice is saved for later development runs.++Development secrets can be placed in \`opencomputer/.env.local\`. Only values+referenced by \`useSecret()\` are synchronized, and their allowed origins are+inferred from \`defineConnection()\` declarations.`: `# Hello World OpenComputer agent@@ -619,6 +629,10 @@ npm run devThe first run asks you to create a cloud project or select an existing one.That choice is saved for later development runs.++Development secrets can be placed in \`opencomputer/.env.local\`. Only values+referenced by \`useSecret()\` are synchronized, and their allowed origins are+inferred from \`defineConnection()\` declarations.`,);@@ -641,6 +655,7 @@ That choice is saved for later development runs.manifest,files: ["opencomputer/project.ts",+ "opencomputer/.env.example","opencomputer/agents/hello-world/agent.ts",...appFiles,],diff --git a/docs/agents/secrets.mdx b/docs/agents/secrets.mdxindex 91339be0..db28aa0a 100644--- a/docs/agents/secrets.mdx+++ b/docs/agents/secrets.mdx@@ -46,6 +46,26 @@ Only a relative path is accepted. OpenComputer checks the declared origin,path prefix, method, agent, and environment before injecting the secret at theoutbound gateway.+## Synchronize development secrets++Place development-only values in `opencomputer/.env.local`:++```dotenv+GITHUB_TOKEN=github_pat_...+```++When `npm run dev` starts, the CLI considers only names referenced by+`useSecret()` in a `defineConnection()` declaration. It infers the allowed+origins from those declarations and asks before uploading each newly discovered+secret. Changed values are synchronized while the development process is+running.++Variables without a matching declaration are skipped. OpenComputer never+grants an unmatched value access to every host, and removing a local variable+does not delete its cloud value. Use `opencomputer secrets remove` when deletion+is intentional. The starter ignores `opencomputer/.env.local` and includes an+`opencomputer/.env.example` file for documenting required names without values.+## Set a project secretSecrets belong to a cloud project. If the app is not linked yet, this command