An open-source, faster Devin alternative
TypeScript
Deployment egress allowlist from opencomputer.toml; CLI 0.7.20
Slack U06GFN8DJ7Pb0925fa2bae9
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 05abbe2a..db053740 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.7.19",+ "version": "0.7.20","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.7.19",+ "version": "0.7.20","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",@@ -14,6 +14,7 @@"esbuild": "^0.28.2","opencode-ai": "1.18.4","react": "^19.2.8",+ "smol-toml": "1.9.1","typescript": "^5.9.0"},"bin": {@@ -3157,6 +3158,18 @@"node": ">=8"}},+ "node_modules/smol-toml": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",+ "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "url": "https://github.com/sponsors/cyyynthia"+ }+ },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",diff --git a/cli/package.json b/cli/package.jsonindex de0677a6..e04a6851 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.7.19",+ "version": "0.7.20","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {@@ -49,6 +49,7 @@"esbuild": "^0.28.2","opencode-ai": "1.18.4","react": "^19.2.8",+ "smol-toml": "1.9.1","typescript": "^5.9.0"},"devDependencies": {diff --git a/cli/src/api.ts b/cli/src/api.tsindex 2e9ba8f2..0180b877 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -1448,6 +1448,7 @@ export class OpenComputerClient {memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;region?: string;+ egress?: { domains: string[]; cidrs: string[] };projectDeployment?: {id: string;digest: string;diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex ba70a716..4780ad2a 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -77,6 +77,7 @@ async function registerBuiltDeployment(memory: built.memory,models: built.models,...(built.region ? { region: built.region } : {}),+ ...(built.egress ? { egress: built.egress } : {}),...(projectDeployment ? { projectDeployment } : {}),source: {digest: built.digest,diff --git a/cli/src/egress.ts b/cli/src/egress.tsnew file mode 100644index 00000000..566f20bc--- /dev/null+++ b/cli/src/egress.ts@@ -0,0 +1,84 @@+/**+ * The `[egress]` allowlist in `opencomputer.toml` (work 057). One `allow`+ * list of domains, `*.` wildcards, IPs and CIDRs, split here into the two+ * lists the service takes. The service validates the same way.+ */+export interface DeploymentEgress {+ /** Exact or `*.` wildcard domains; matched on TLS SNI, port 443 only. */+ domains: string[];+ /** IPv4/IPv6 CIDRs (a bare address becomes /32 or /128); any port. */+ cidrs: string[];+}++export const EGRESS_MAX_ENTRIES = 64;++const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;+const IPV4 =+ /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;++/** A lowercased domain or `*.` wildcard, or null when it is not one. */+export function egressDomain(value: string): string | null {+ const lowered = value.trim().toLowerCase().replace(/\.$/, "");+ const wildcard = lowered.startsWith("*.");+ const host = wildcard ? lowered.slice(2) : lowered;+ if (host.length > 253 || IPV4.test(host)) return null;+ const labels = host.split(".");+ if (labels.length < 2 || !labels.every((label) => LABEL.test(label))) return null;+ if (/^\d+$/.test(labels[labels.length - 1]!)) return null;+ return wildcard ? `*.${host}` : host;+}++function ipv6(address: string): boolean {+ if (!address.includes(":") || !/^[0-9a-f:.]+$/.test(address)) return false;+ try {+ new URL(`http://[${address}]/`);+ return true;+ } catch {+ return false;+ }+}++/** An IP or CIDR as a CIDR (a bare address gets /32 or /128), or null. */+export function egressCidr(value: string): string | null {+ const [address = "", prefix, extra] = value.trim().toLowerCase().split("/");+ if (extra !== undefined) return null;+ const max = IPV4.test(address) ? 32 : ipv6(address) ? 128 : null;+ if (max === null) return null;+ if (prefix === undefined) return `${address}/${max}`;+ if (!/^\d{1,3}$/.test(prefix) || Number(prefix) > max) return null;+ return `${address}/${Number(prefix)}`;+}++/**+ * Splits `allow` into domains and CIDRs, deduplicated and sorted. Throws+ * with the offending entry; an empty list is valid and allows only the+ * platform's own hosts.+ */+export function splitEgressAllow(allow: unknown): DeploymentEgress {+ if (!Array.isArray(allow)) {+ throw new Error(+ 'opencomputer.toml [egress] allow must be a list, e.g. allow = ["api.github.com", "10.0.0.0/8"]',+ );+ }+ const domains = new Set<string>();+ const cidrs = new Set<string>();+ for (const entry of allow) {+ const text = typeof entry === "string" ? entry : "";+ const cidr = egressCidr(text);+ const domain = cidr ? null : egressDomain(text);+ if (cidr) cidrs.add(cidr);+ else if (domain) domains.add(domain);+ else {+ throw new Error(+ `opencomputer.toml [egress] allow entry ${JSON.stringify(entry)} is not a domain ` ++ '("api.github.com", "*.example.com"), IP address or CIDR; leave out schemes, ports and paths',+ );+ }+ }+ if (domains.size > EGRESS_MAX_ENTRIES || cidrs.size > EGRESS_MAX_ENTRIES) {+ throw new Error(+ `opencomputer.toml [egress] allow takes at most ${EGRESS_MAX_ENTRIES} domains and ${EGRESS_MAX_ENTRIES} IPs/CIDRs`,+ );+ }+ return { domains: [...domains].sort(), cidrs: [...cidrs].sort() };+}diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex e9a956d7..8101950b 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -3084,3 +3084,63 @@ test("opencomputer.toml region is optional, accepts Modal regions, and rejects aawait rm(root, { recursive: true, force: true });}});++test("opencomputer.toml [egress] allow is split into domains and CIDRs and validated", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-"));+ const manifest = (extra: string) =>+ writeFile(+ resolve(root, "opencomputer.toml"),+ `schema = 1\nid = "cypen"\nname = "Cypen"\n${extra}`,+ );+ try {+ await manifest("");+ assert.equal((await readManifest(root)).egress, undefined);+ await manifest(+ [+ 'region = "au"',+ "[egress]",+ "allow = [",+ ' "*.Cypen.io",',+ ' "api.github.com.",',+ ' "203.0.113.10",',+ ' "10.20.0.0/16",',+ ' "2001:db8::/32",',+ ' "api.github.com",',+ "]",+ "",+ ].join("\n"),+ );+ const read = await readManifest(root);+ assert.equal(read.region, "au");+ assert.deepEqual(read.egress, {+ domains: ["*.cypen.io", "api.github.com"],+ cidrs: ["10.20.0.0/16", "2001:db8::/32", "203.0.113.10/32"],+ });+ await manifest('[egress]\nallow = []\n');+ assert.deepEqual((await readManifest(root)).egress, { domains: [], cidrs: [] });+ await manifest("[egress]\n");+ assert.deepEqual((await readManifest(root)).egress, { domains: [], cidrs: [] });+ await manifest('[egress]\nallow = ["https://api.github.com"]\n');+ await assert.rejects(readManifest(root), /allow entry "https:\/\/api.github.com" is not a domain/);+ await manifest('[egress]\nallow = ["api.github.com:443"]\n');+ await assert.rejects(readManifest(root), /is not a domain/);+ await manifest('[egress]\nallow = ["10.0.0.0/33"]\n');+ await assert.rejects(readManifest(root), /is not a domain/);+ await manifest('[egress]\nallow = ["*"]\n');+ await assert.rejects(readManifest(root), /is not a domain/);+ await manifest('[egress]\nallow = "api.github.com"\n');+ await assert.rejects(readManifest(root), /allow must be a list/);+ await manifest('[egress]\ndeny = ["a.com"]\n');+ await assert.rejects(readManifest(root), /unknown key "deny"/);+ await manifest('egress = ["a.com"]\n');+ await assert.rejects(readManifest(root), /egress must be a table/);+ await manifest(+ `[egress]\nallow = [${Array.from({ length: 65 }, (_, i) => `"h${i}.com"`).join(", ")}]\n`,+ );+ await assert.rejects(readManifest(root), /at most 64 domains/);+ await manifest('[egress\nallow = []\n');+ await assert.rejects(readManifest(root), /not valid TOML/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/project.ts b/cli/src/project.tsindex 1d635516..ea4b263f 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -12,6 +12,7 @@ import { readFileSync } from "node:fs";import { basename, dirname, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { Cron } from "croner";+import { parse as parseToml } from "smol-toml";import { build as bundle } from "esbuild";import ts from "typescript";@@ -27,6 +28,7 @@ import {type MemoryDefinitionInput,type MemoryProvider,} from "./memory.js";+import { type DeploymentEgress, splitEgressAllow } from "./egress.js";/*** Regions a deployment may name in `opencomputer.toml` (work 057): Modal's@@ -64,6 +66,8 @@ export interface AgentManifest {name: string;/** Where the deployment's sessions run; absent means the platform default. */region?: DeploymentRegion;+ /** `[egress] allow`, split; absent means an open network. */+ egress?: DeploymentEgress;}export interface BuiltAgentArtifact {@@ -76,6 +80,7 @@ export interface BuiltAgentArtifact {memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;region?: DeploymentRegion;+ egress?: DeploymentEgress;body: Buffer;digest: string;elapsedMs: number;@@ -294,19 +299,6 @@ export async function writeManifest();}-function tomlString(source: string, key: string): string | undefined {- const match = source.match(- new RegExp(`^\\s*${key}\\s*=\\s*("(?:[^"\\\\]|\\\\.)*")\\s*$`, "m"),- );- if (!match?.[1]) return undefined;- try {- const value: unknown = JSON.parse(match[1]);- return typeof value === "string" ? value : undefined;- } catch {- return undefined;- }-}-export async function readManifest(root: string): Promise<AgentManifest> {if (!(await exists(resolve(root, "opencomputer.toml")))) {const id = agentIdFromName(basename(root));@@ -320,16 +312,31 @@ export async function readManifest(root: string): Promise<AgentManifest> {};}const source = await readFile(resolve(root, "opencomputer.toml"), "utf8");- const schema = Number(source.match(/^\s*schema\s*=\s*(\d+)\s*$/m)?.[1]);- const id = tomlString(source, "id");- const name = tomlString(source, "name");- if (schema !== 1 || !id || !name || !AGENT_ID_PATTERN.test(id)) {+ let toml: Record<string, unknown>;+ try {+ toml = parseToml(source);+ } catch (error) {+ if (/^\s*region\s*=\s*[^"\s]/m.test(source)) {+ throw new Error('opencomputer.toml region must be a quoted string, e.g. region = "au"');+ }+ throw new Error(+ `opencomputer.toml is not valid TOML: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,+ );+ }+ const { schema, id, name, region } = toml;+ if (+ schema !== 1 ||+ typeof id !== "string" ||+ typeof name !== "string" ||+ !id ||+ !name ||+ !AGENT_ID_PATTERN.test(id)+ ) {throw new Error("opencomputer.toml must contain schema = 1 and a valid id and name",);}- const region = tomlString(source, "region");- if (/^\s*region\s*=/m.test(source) && region === undefined) {+ if (region !== undefined && typeof region !== "string") {throw new Error('opencomputer.toml region must be a quoted string, e.g. region = "au"');}if (@@ -340,14 +347,31 @@ export async function readManifest(root: string): Promise<AgentManifest> {`opencomputer.toml region ${JSON.stringify(region)} is not supported; use one of: ${DEPLOYMENT_REGIONS.join(", ")}`,);}+ const egress = manifestEgress(toml.egress);return {schema: 1,id,name,...(region ? { region: region as DeploymentRegion } : {}),+ ...(egress ? { egress } : {}),};}+/** The `[egress]` table, or undefined when the manifest has none. */+function manifestEgress(table: unknown): DeploymentEgress | undefined {+ if (table === undefined) return undefined;+ if (typeof table !== "object" || table === null || Array.isArray(table)) {+ throw new Error("opencomputer.toml egress must be a table: [egress]");+ }+ const unknown = Object.keys(table).filter((key) => key !== "allow");+ if (unknown.length) {+ throw new Error(+ `opencomputer.toml [egress] has unknown key ${JSON.stringify(unknown[0])}; only allow is supported`,+ );+ }+ return splitEgressAllow((table as { allow?: unknown }).allow ?? []);+}+export async function findAgentRoot(startDirectory = process.cwd(),): Promise<string | undefined> {@@ -3961,6 +3985,7 @@ export async function buildAgentArtifact(memory,models,...(manifest.region ? { region: manifest.region } : {}),+ ...(manifest.egress ? { egress: manifest.egress } : {}),body,digest: createHash("sha256").update(body).digest("hex"),elapsedMs: Math.round(performance.now() - startedAt),diff --git a/cli/src/template.ts b/cli/src/template.tsindex 67127d1a..a588597c 100644--- a/cli/src/template.ts+++ b/cli/src/template.ts@@ -54,6 +54,7 @@ export interface TemplateBuildArtifact {memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;region?: string;+ egress?: { domains: string[]; cidrs: string[] };}export interface TemplateBuildBundle {@@ -334,6 +335,7 @@ export async function buildTemplateProject(memory: built.memory,models: built.models,...(built.region ? { region: built.region } : {}),+ ...(built.egress ? { egress: built.egress } : {}),});for (const connection of built.connections)compiledConnections.add(connection);diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 4ff571e2..881f2562 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -3109,6 +3109,7 @@ describe("managed agents proxy", () => {],createdAt: "2026-07-30T00:00:00.000Z",region: "au",+ egress: { domains: ["*.cypen.io"], cidrs: ["10.0.0.0/8"] },artifact: { bucket: "private-bucket" },imageArn: "arn:aws:private",},@@ -3168,6 +3169,7 @@ describe("managed agents proxy", () => {},],region: "au",+ egress: { domains: ["*.cypen.io"], cidrs: ["10.0.0.0/8"] },source: {digest,size: source.length,@@ -3234,9 +3236,9 @@ describe("managed agents proxy", () => {});expect(JSON.parse(String((fetchSpy.mock.calls[2]?.[1] as RequestInit).body)),- ).toMatchObject({ region: "au" });+ ).toMatchObject({ region: "au", egress: { domains: ["*.cypen.io"], cidrs: ["10.0.0.0/8"] } });const published = await response.json();- expect(published).toMatchObject({ region: "au" });+ expect(published).toMatchObject({ region: "au", egress: { domains: ["*.cypen.io"], cidrs: ["10.0.0.0/8"] } });expect(JSON.stringify(published)).not.toMatch(/bucket|imageArn|arn:aws|uploads\.test/i,);diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex a4e56c9c..680e9826 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -316,7 +316,9 @@ async function publicErrorResponse(? "The cursor is invalid or was issued for different filters. Start again from the first page.": backendCode === "unsupported_region"? 'The region in opencomputer.toml is not supported. Use a Modal region, such as "us", "eu-west" or "au".'- : "The agent request was invalid.";+ : backendCode === "invalid_egress"+ ? 'The [egress] allow list in opencomputer.toml is invalid. Use domains ("api.github.com", "*.example.com"), IP addresses or CIDRs, at most 64 of each.'+ : "The agent request was invalid.";} else if (upstream.status === 401 || upstream.status === 403) {message = "The agent request was not authorized.";} else if (upstream.status === 404) {@@ -565,6 +567,13 @@ function publicMemoryDeclaration(value: unknown): Record<string, unknown> {};}+/** A deployment's egress allowlist as the service returns it, or undefined. */+function publicEgress(value: unknown): { domains: string[]; cidrs: string[] } | undefined {+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;+ const egress = value as { domains?: unknown; cidrs?: unknown };+ return { domains: strings(egress.domains), cidrs: strings(egress.cidrs) };+}+function publicDeployment(value: unknown): Record<string, unknown> {const deployment = record(value) ?? {};return {@@ -575,6 +584,7 @@ function publicDeployment(value: unknown): Record<string, unknown> {connections: strings(deployment.connections),createdAt: deployment.createdAt,...(typeof deployment.region === "string" ? { region: deployment.region } : {}),+ ...(publicEgress(deployment.egress) ? { egress: publicEgress(deployment.egress)! } : {}),...(Array.isArray(deployment.models)? {models: deployment.models.flatMap((value) => {@@ -2628,6 +2638,8 @@ async function deploySourceAgent(models,// Validated by the service, which answers 400 unsupported_region (work 057)....(body.region !== undefined ? { region: body.region } : {}),+ // Validated by the service, which answers 400 invalid_egress (work 057).+ ...(body.egress !== undefined ? { egress: body.egress } : {}),...(body.projectDeployment && typeof body.projectDeployment === "object"? { projectDeployment: body.projectDeployment }: {}),diff --git a/docs/agents/deployments.mdx b/docs/agents/deployments.mdxindex 8b871977..035e51ee 100644--- a/docs/agents/deployments.mdx+++ b/docs/agents/deployments.mdx@@ -46,6 +46,85 @@ the United States. To run it elsewhere, set `region` in the agent's`opencomputer.toml` and deploy again. See [Regions](/agents/regions) for theallowed values and what a region covers.+## Restrict outbound network++By default, an agent's sandbox can reach any address on the internet. To allow+only the hosts the agent needs, add an `[egress]` table to the agent's+`opencomputer.toml` and deploy again:++```toml+schema = 1+id = "support"+name = "Support"++[egress]+allow = [+ "api.github.com", # exact domain+ "*.example.com", # wildcard: example.com and every subdomain+ "203.0.113.10", # IP address+ "10.20.0.0/16", # CIDR+]+```++Every process in the sandbox is held to the list: commands, `sandbox_exec`,+background jobs, and anything they start. Connections to anything else are+refused.++### What each entry allows++| Entry | Allows |+| --- | --- |+| `"api.github.com"` | HTTPS (TLS on port 443) to that host |+| `"*.example.com"` | HTTPS to `example.com` and any subdomain |+| `"203.0.113.10"`, `"2001:db8::1"` | any protocol and port to that address |+| `"10.20.0.0/16"`, `"2001:db8::/32"` | any protocol and port to that range |++- **Domains cover HTTPS on port 443 only.** Plain `http://`, other ports, and+ non-TLS protocols to a domain are refused. To reach those, list the+ destination's IP address or CIDR instead.+- **Domains are matched on the TLS server name.** The connection goes to the+ allowed host whatever IP address the client picks, so pointing an allowed+ name at another address does not reach that address.+- **DNS lookups are not filtered.** Names outside the list still resolve; the+ connection is what is refused. Resolvers other than the sandbox's own are+ blocked.+- **Platform hosts are always allowed.** The sandbox can always reach+ OpenComputer and the storage it loads your agent from, so you never list+ them.++`allow = []` (or an `[egress]` table with no `allow`) allows nothing beyond the+platform hosts. Without an `[egress]` table the network stays open.++### Rules++- Up to 64 domains and 64 IP addresses or CIDRs.+- Domains take no scheme, port or path. `"https://api.github.com"` and+ `"api.github.com:443"` are rejected. A bare `"*"` is rejected; remove the+ `[egress]` table instead.+- A bare IP address means that single address (`/32` or `/128`).++An invalid entry stops the deploy before anything is uploaded:++```text+opencomputer.toml [egress] allow entry "https://api.github.com" is not a domain ("api.github.com", "*.example.com"), IP address or CIDR; leave out schemes, ports and paths+```++The API rejects it too, with `400 invalid_egress`, if you call+`POST /v1/deployments` directly. There the allowlist is+`"egress": { "domains": [...], "cidrs": [...] }`; the CLI splits `allow` into+these two lists for you.++### Changing the list++A change applies to sandboxes started after the deploy. A sandbox that is+already running keeps the list it started with until it stops. Each agent in a+project has its own `opencomputer.toml`, so agents in one project can have+different lists.++The list covers the agent's sandbox. Model calls, and MCP servers the agent+connects to, are made by OpenComputer outside the sandbox and are not held to+it.+## Select an agent and environmentClients identify an agent with `agent-id@alias`: