An open-source, faster Devin alternative
TypeScript
SDK: support secretStore on checkpoint fork and snapshot create (#126)
Mohamed Habib686f04539d35
diff --git a/docs/reference/python-sdk/secrets.mdx b/docs/reference/python-sdk/secrets.mdxindex 1c7582e3..c04c9a7e 100644--- a/docs/reference/python-sdk/secrets.mdx+++ b/docs/reference/python-sdk/secrets.mdx@@ -144,15 +144,42 @@ api_result = await sandbox.commands.run(## Using Secrets with Snapshots and Checkpoints-Attach a secret store when forking from a snapshot or checkpoint — even if the original didn't have one:+### Snapshot template with secrets++Attach a secret store when creating a sandbox from a pre-built snapshot — even if the snapshot was built without one:++```python+from opencomputer import Sandbox, Snapshots, Image++# Pre-build a snapshot with dependencies+snapshots = Snapshots()+await snapshots.create(+ name='data-pipeline',+ image=Image.base().apt_install(['python3-pip']).pip_install(['pandas']),+)++# Create sandboxes from the snapshot, each with their own credentials+worker1 = await Sandbox.create(+ snapshot='data-pipeline',+ secret_store='worker-1-keys',+)+worker2 = await Sandbox.create(+ snapshot='data-pipeline',+ secret_store='worker-2-keys',+)+```++### Checkpoint fork with secrets++Attach or layer a secret store when forking from a checkpoint:```python-# Bake a base environment+# Bake a base environment with git credentialsbase = await Sandbox.create(secret_store='git-creds')await base.exec.run('git clone https://github.com/org/repo /app')cp = await base.create_checkpoint('repo-cloned')-# Fork with different credentials per sandbox+# Fork with different credentials per sandbox (layered on top of git-creds)worker = await Sandbox.create_from_checkpoint(cp['id'],secret_store='worker-keys', # layered on top of git-credsdiff --git a/docs/reference/typescript-sdk/secrets.mdx b/docs/reference/typescript-sdk/secrets.mdxindex d1ed367e..2564d3e6 100644--- a/docs/reference/typescript-sdk/secrets.mdx+++ b/docs/reference/typescript-sdk/secrets.mdx@@ -155,15 +155,42 @@ const apiResult = await sandbox.commands.run(## Using Secrets with Snapshots and Checkpoints-Attach a secret store when forking from a snapshot or checkpoint — even if the original didn't have one:+### Snapshot template with secrets++Attach a secret store when creating a sandbox from a pre-built snapshot — even if the snapshot was built without one:++```typescript+import { Sandbox, Snapshots, Image } from '@opencomputer/sdk/node';++// Pre-build a snapshot with dependencies+const snapshots = new Snapshots();+await snapshots.create({+ name: 'data-pipeline',+ image: Image.base().aptInstall(['python3-pip']).pipInstall(['pandas']),+});++// Create sandboxes from the snapshot, each with their own credentials+const worker1 = await Sandbox.create({+ snapshot: 'data-pipeline',+ secretStore: 'worker-1-keys',+});+const worker2 = await Sandbox.create({+ snapshot: 'data-pipeline',+ secretStore: 'worker-2-keys',+});+```++### Checkpoint fork with secrets++Attach or layer a secret store when forking from a checkpoint:```typescript-// Bake a base environment+// Bake a base environment with git credentialsconst base = await Sandbox.create({ secretStore: 'git-creds' });await base.exec.run('git clone https://github.com/org/repo /app', { cwd: '/' });const cp = await base.createCheckpoint('repo-cloned');-// Fork with different credentials per sandbox+// Fork with different credentials per sandbox (layered on top of git-creds)const worker = await Sandbox.createFromCheckpoint(cp.id, {secretStore: 'worker-keys', // layered on top of git-creds});diff --git a/docs/sandboxes/secrets.mdx b/docs/sandboxes/secrets.mdxindex e26269ce..01c63de4 100644--- a/docs/sandboxes/secrets.mdx+++ b/docs/sandboxes/secrets.mdx@@ -204,6 +204,60 @@ await SecretStore.delete(store['id'])You can attach a secret store when creating a sandbox from a snapshot or checkpoint, even if the original didn't have one. This is useful for baking a base environment (e.g., installed dependencies) and then giving each fork its own scoped credentials.+### Snapshot template with secrets++Pre-build a snapshot once, then create sandboxes from it with different credentials:++<CodeGroup>++```typescript TypeScript+import { Sandbox, Snapshots, Image } from '@opencomputer/sdk/node';++// Pre-build a reusable snapshot+const snapshots = new Snapshots();+await snapshots.create({+ name: 'data-pipeline',+ image: Image.base().aptInstall(['python3-pip']).pipInstall(['pandas']),+});++// Create sandboxes from the snapshot, each with their own credentials+const worker1 = await Sandbox.create({+ snapshot: 'data-pipeline',+ secretStore: 'worker-1-keys',+});+const worker2 = await Sandbox.create({+ snapshot: 'data-pipeline',+ secretStore: 'worker-2-keys',+});+```++```python Python+from opencomputer import Sandbox, Snapshots, Image++# Pre-build a reusable snapshot+snapshots = Snapshots()+await snapshots.create(+ name='data-pipeline',+ image=Image.base().apt_install(['python3-pip']).pip_install(['pandas']),+)++# Create sandboxes from the snapshot, each with their own credentials+worker1 = await Sandbox.create(+ snapshot='data-pipeline',+ secret_store='worker-1-keys',+)+worker2 = await Sandbox.create(+ snapshot='data-pipeline',+ secret_store='worker-2-keys',+)+```++</CodeGroup>++### Checkpoint fork with secrets++Layer a new secret store on top of an existing checkpoint's store:+<CodeGroup>```typescript TypeScript@@ -212,7 +266,7 @@ const base = await Sandbox.create({ secretStore: 'git-creds' });await base.exec.run('git clone https://github.com/org/repo /app');const cp = await base.createCheckpoint('repo-cloned');-// Fork with sandbox-specific API credentials+// Fork with sandbox-specific API credentials (layered on top of git-creds)const worker1 = await Sandbox.createFromCheckpoint(cp.id, {secretStore: 'worker-1-keys',});@@ -227,7 +281,7 @@ base = await Sandbox.create(secret_store='git-creds')await base.exec.run('git clone https://github.com/org/repo /app')cp = await base.create_checkpoint('repo-cloned')-# Fork with sandbox-specific API credentials+# Fork with sandbox-specific API credentials (layered on top of git-creds)worker1 = await Sandbox.create_from_checkpoint(cp['id'],secret_store='worker-1-keys',)diff --git a/sdks/python/examples/test_secret_store_fork.py b/sdks/python/examples/test_secret_store_fork.pynew file mode 100644index 00000000..120df559--- /dev/null+++ b/sdks/python/examples/test_secret_store_fork.py@@ -0,0 +1,333 @@+#!/usr/bin/env python3+"""+Test secret store inheritance on fork / create_from_checkpoint.++Creates two secret stores, a sandbox with store A, checkpoints it,+then forks with store B attached. Also tests snapshot + secretStore path.+Verifies:+ 1. Secret env vars from both stores are present (layered merge)+ 2. Secrets are sealed in-guest (osb_sealed_* tokens, not plaintext)+ 3. Actual secret VALUES resolve correctly through the proxy (httpbin echo)+ 4. Store B's value wins on collision (SHARED_KEY override)+ 5. Snapshot + secretStore path works end-to-end++Usage:+ OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... python examples/test_secret_store_fork.py+"""++import asyncio+import os+import sys+import time++from opencomputer import Sandbox, SecretStore, Snapshots, Image++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}\u2713 {msg}{RESET}")+++def red(msg: str, detail: str = "") -> None:+ suffix = f" \u2014 {detail}" if detail else ""+ print(f"{RED}\u2717 {msg}{suffix}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(desc, detail)+ failed += 1+++async def main() -> None:+ global passed, failed++ suffix = int(time.time() * 1000)+ store_a_name = f"fork-test-a-{suffix}"+ store_b_name = f"fork-test-b-{suffix}"++ # Random-ish values for httpbin verification+ git_token_val = f"git_{os.urandom(12).hex()}"+ shared_key_a_val = f"shared_a_{os.urandom(12).hex()}"+ shared_key_b_val = f"shared_b_{os.urandom(12).hex()}"+ api_key_val = f"api_{os.urandom(12).hex()}"++ store_a_id: str | None = None+ store_b_id: str | None = None+ base_sandbox: Sandbox | None = None+ forked_sandbox: Sandbox | None = None+ snapshot_sandbox: Sandbox | None = None+ snapshot_name: str | None = None++ try:+ # -- Setup: two secret stores -----------------------------------------+ bold("\n=== 1. Setup: create two secret stores ===\n")++ store_a = await SecretStore.create(+ name=store_a_name,+ egress_allowlist=["github.com", "httpbin.org"],+ )+ store_a_id = store_a["id"]+ print(f" Store A: {store_a_id} ({store_a_name})")++ await SecretStore.set_secret(store_a_id, "GIT_TOKEN", git_token_val,+ allowed_hosts=["github.com", "httpbin.org"])+ await SecretStore.set_secret(store_a_id, "SHARED_KEY", shared_key_a_val,+ allowed_hosts=["httpbin.org"])+ dim(f"GIT_TOKEN = {git_token_val}")+ dim(f"SHARED_KEY(A) = {shared_key_a_val}")+ green("Store A created: GIT_TOKEN + SHARED_KEY, egress=[github.com, httpbin.org]")++ store_b = await SecretStore.create(+ name=store_b_name,+ egress_allowlist=["api.anthropic.com", "httpbin.org"],+ )+ store_b_id = store_b["id"]+ print(f" Store B: {store_b_id} ({store_b_name})")++ await SecretStore.set_secret(store_b_id, "API_KEY", api_key_val,+ allowed_hosts=["api.anthropic.com", "httpbin.org"])+ await SecretStore.set_secret(store_b_id, "SHARED_KEY", shared_key_b_val,+ allowed_hosts=["httpbin.org"])+ dim(f"API_KEY = {api_key_val}")+ dim(f"SHARED_KEY(B) = {shared_key_b_val} (should override A)")+ green("Store B created: API_KEY + SHARED_KEY(override), egress=[api.anthropic.com, httpbin.org]")++ # -- Layer 1: sandbox with store A -------------------------------------+ bold("\n=== 2. Create base sandbox with store A ===\n")++ base_sandbox = await Sandbox.create(secret_store=store_a_name, timeout=120)+ print(f" Base sandbox: {base_sandbox.sandbox_id}")+ await asyncio.sleep(5)++ env_base = (await base_sandbox.exec.run("env")).stdout+ check("Base has GIT_TOKEN", "GIT_TOKEN" in env_base)+ check("Base has SHARED_KEY", "SHARED_KEY" in env_base)+ check("Base does NOT have API_KEY", "API_KEY" not in env_base)++ # Verify sealed+ base_git_echo = (await base_sandbox.exec.run('printf %s "$GIT_TOKEN"')).stdout.strip()+ check(+ "Base: GIT_TOKEN is sealed (not plaintext)",+ base_git_echo.startswith("osb_sealed_") and git_token_val not in base_git_echo,+ f'got "{base_git_echo[:40]}..."',+ )++ # Verify values via httpbin+ base_httpbin = (await base_sandbox.exec.run(+ 'curl -sS -m 10 https://httpbin.org/headers '+ '-H "X-Git: $GIT_TOKEN" -H "X-Shared: $SHARED_KEY"'+ )).stdout+ check("Base: GIT_TOKEN value resolves via httpbin",+ git_token_val in base_httpbin,+ f"httpbin did not echo back {git_token_val}")+ check("Base: SHARED_KEY(A) value resolves via httpbin",+ shared_key_a_val in base_httpbin,+ f"httpbin did not echo back {shared_key_a_val}")++ # -- Checkpoint --------------------------------------------------------+ bold("\n=== 3. Create checkpoint from base ===\n")++ cp = await base_sandbox.create_checkpoint("fork-test-cp")+ print(f" Checkpoint: {cp['id']}")++ for _ in range(30):+ cps = await base_sandbox.list_checkpoints()+ found = next((c for c in cps if c["id"] == cp["id"]), None)+ if found and found.get("status") == "ready":+ break+ await asyncio.sleep(2)+ green("Checkpoint ready")++ # -- Layer 2: fork with store B ----------------------------------------+ bold("\n=== 4. Fork from checkpoint with store B (secretStore inheritance) ===\n")++ forked_sandbox = await Sandbox.create_from_checkpoint(+ cp["id"],+ secret_store=store_b_name,+ timeout=120,+ )+ print(f" Forked sandbox: {forked_sandbox.sandbox_id}")+ await asyncio.sleep(5)++ # -- 4a. Check env vars exist ------------------------------------------+ bold("\n=== 4a. Verify secret env vars present ===\n")++ env_fork = (await forked_sandbox.exec.run("env")).stdout+ check("Fork has GIT_TOKEN (inherited from store A)", "GIT_TOKEN" in env_fork)+ check("Fork has API_KEY (from store B)", "API_KEY" in env_fork)+ check("Fork has SHARED_KEY (merged)", "SHARED_KEY" in env_fork)+ check("Fork has HTTP_PROXY (secrets proxy active)", "HTTP_PROXY" in env_fork)++ sealed_count = env_fork.count("osb_sealed_")+ check(+ f"Fork has 3 sealed secrets (got {sealed_count})",+ sealed_count == 3,+ "expected GIT_TOKEN(A) + SHARED_KEY(B override) + API_KEY(B)",+ )++ # -- 4b. Verify secrets are sealed -------------------------------------+ bold("\n=== 4b. Verify secrets are sealed in-guest ===\n")++ fork_git_echo = (await forked_sandbox.exec.run('printf %s "$GIT_TOKEN"')).stdout.strip()+ check("Fork: GIT_TOKEN is sealed",+ fork_git_echo.startswith("osb_sealed_") and git_token_val not in fork_git_echo,+ f'got "{fork_git_echo[:40]}..."')++ fork_api_echo = (await forked_sandbox.exec.run('printf %s "$API_KEY"')).stdout.strip()+ check("Fork: API_KEY is sealed",+ fork_api_echo.startswith("osb_sealed_") and api_key_val not in fork_api_echo,+ f'got "{fork_api_echo[:40]}..."')++ fork_shared_echo = (await forked_sandbox.exec.run('printf %s "$SHARED_KEY"')).stdout.strip()+ check("Fork: SHARED_KEY is sealed",+ fork_shared_echo.startswith("osb_sealed_") and shared_key_b_val not in fork_shared_echo,+ f'got "{fork_shared_echo[:40]}..."')++ # -- 4c. Verify actual VALUES via httpbin ------------------------------+ bold("\n=== 4c. Verify actual secret values via httpbin (proxy substitution) ===\n")++ fork_httpbin = (await forked_sandbox.exec.run(+ 'curl -sS -m 10 https://httpbin.org/headers '+ '-H "X-Git: $GIT_TOKEN" '+ '-H "X-Api: $API_KEY" '+ '-H "X-Shared: $SHARED_KEY"'+ )).stdout+ dim(f"httpbin response (first 500 chars):")+ dim(fork_httpbin.replace("\n", " ")[:500])++ check("Fork: GIT_TOKEN value correct (inherited from A)",+ git_token_val in fork_httpbin,+ f"httpbin did not echo back {git_token_val}")+ check("Fork: API_KEY value correct (from B)",+ api_key_val in fork_httpbin,+ f"httpbin did not echo back {api_key_val}")+ check("Fork: SHARED_KEY has B's value (B override wins on collision)",+ shared_key_b_val in fork_httpbin,+ f"httpbin did not echo back B's value {shared_key_b_val}")+ check("Fork: SHARED_KEY does NOT have A's value (overridden by B)",+ shared_key_a_val not in fork_httpbin,+ f"httpbin echoed A's value {shared_key_a_val} -- override did not work")++ # -- 5. Snapshot/template path -----------------------------------------+ bold("\n=== 5. Create snapshot template, fork with secretStore ===\n")++ snapshots = Snapshots()+ snapshot_name = f"fork-secret-test-{suffix}"+ dim(f'Creating snapshot "{snapshot_name}" from base image...')+ await snapshots.create(+ name=snapshot_name,+ image=Image.base().run_commands("echo 'template-ready' > /home/sandbox/marker.txt"),+ )++ for _ in range(30):+ info = await snapshots.get(snapshot_name)+ if info.get("status") == "ready":+ break+ await asyncio.sleep(2)+ green(f'Snapshot "{snapshot_name}" ready')++ snapshot_sandbox = await Sandbox.create(+ snapshot=snapshot_name,+ secret_store=store_b_name,+ timeout=120,+ )+ print(f" Snapshot-forked sandbox: {snapshot_sandbox.sandbox_id}")+ await asyncio.sleep(5)++ # Verify template content+ marker = (await snapshot_sandbox.exec.run("cat /home/sandbox/marker.txt")).stdout.strip()+ check("Snapshot fork: template content present (/home/sandbox/marker.txt)",+ marker == "template-ready",+ f'got "{marker}"')++ # Verify secrets+ env_snap = (await snapshot_sandbox.exec.run("env")).stdout+ check("Snapshot fork: has API_KEY (from store B)", "API_KEY" in env_snap)+ check("Snapshot fork: has SHARED_KEY (from store B)", "SHARED_KEY" in env_snap)+ check("Snapshot fork: has HTTP_PROXY (secrets proxy active)", "HTTP_PROXY" in env_snap)++ snap_api_echo = (await snapshot_sandbox.exec.run('printf %s "$API_KEY"')).stdout.strip()+ check("Snapshot fork: API_KEY is sealed",+ snap_api_echo.startswith("osb_sealed_") and api_key_val not in snap_api_echo,+ f'got "{snap_api_echo[:40]}..."')++ # Verify values via httpbin+ snap_httpbin = (await snapshot_sandbox.exec.run(+ 'curl -sS -m 10 https://httpbin.org/headers '+ '-H "X-Api: $API_KEY" '+ '-H "X-Shared: $SHARED_KEY"'+ )).stdout+ dim(f"httpbin response (first 500 chars):")+ dim(snap_httpbin.replace("\n", " ")[:500])++ check("Snapshot fork: API_KEY value correct via httpbin",+ api_key_val in snap_httpbin,+ f"httpbin did not echo back {api_key_val}")+ check("Snapshot fork: SHARED_KEY has B's value via httpbin",+ shared_key_b_val in snap_httpbin,+ f"httpbin did not echo back {shared_key_b_val}")++ # -- Summary -----------------------------------------------------------+ bold(f"\n=== Results: {passed} passed, {failed} failed ===\n")++ finally:+ bold("=== Cleanup ===")+ if snapshot_sandbox:+ try:+ await snapshot_sandbox.kill()+ except Exception:+ pass+ if forked_sandbox:+ try:+ await forked_sandbox.kill()+ except Exception:+ pass+ if base_sandbox:+ try:+ await base_sandbox.kill()+ except Exception:+ pass+ if snapshot_name:+ try:+ s = Snapshots()+ await s.delete(snapshot_name)+ except Exception:+ pass+ if store_b_id:+ try:+ await SecretStore.delete(store_b_id)+ except Exception:+ pass+ if store_a_id:+ try:+ await SecretStore.delete(store_a_id)+ except Exception:+ pass+ green("Cleanup done")++ sys.exit(1 if failed > 0 else 0)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.pyindex 54d1298f..d6bdbc06 100644--- a/sdks/python/opencomputer/__init__.py+++ b/sdks/python/opencomputer/__init__.py@@ -28,4 +28,4 @@ __all__ = ["Snapshots",]-__version__ = "0.5.1"+__version__ = "0.5.2"diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex ee3adf3f..5444e130 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -335,6 +335,8 @@ class Sandbox:timeout: int = 300,api_key: str | None = None,api_url: str | None = None,+ envs: dict[str, str] | None = None,+ secret_store: str | None = None,) -> Sandbox:"""Create a new sandbox from an existing checkpoint (fork).@@ -343,6 +345,10 @@ class Sandbox:timeout: Sandbox timeout in seconds (default 300).api_key: API key (or OPENCOMPUTER_API_KEY env var).api_url: API URL (or OPENCOMPUTER_API_URL env var).+ envs: Environment variables to override on the fork.+ secret_store: Secret store name to attach. If the checkpoint+ already has a store, secrets are merged (new store wins+ on collision, egress allowlists aggregate)."""url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")url = url.rstrip("/")@@ -356,9 +362,15 @@ class Sandbox:client = httpx.AsyncClient(base_url=api_base, headers=headers, timeout=120.0)+ body: dict[str, Any] = {"timeout": timeout}+ if envs:+ body["envs"] = envs+ if secret_store:+ body["secretStore"] = secret_store+resp = await client.post(f"/sandboxes/from-checkpoint/{checkpoint_id}",- json={"timeout": timeout},+ json=body,)resp.raise_for_status()data = resp.json()diff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.tomlindex 8d75e0b5..ca417555 100644--- a/sdks/python/pyproject.toml+++ b/sdks/python/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "opencomputer-sdk"-version = "0.4.9"+version = "0.5.2"description = "Python SDK for OpenComputer - cloud sandbox platform"readme = "README.md"requires-python = ">=3.10"diff --git a/sdks/typescript/examples/test-secret-store-fork.ts b/sdks/typescript/examples/test-secret-store-fork.tsnew file mode 100644index 00000000..135771c7--- /dev/null+++ b/sdks/typescript/examples/test-secret-store-fork.ts@@ -0,0 +1,436 @@+/**+ * Test secret store inheritance on fork / createFromCheckpoint.+ *+ * Creates two secret stores, a sandbox with store A, checkpoints it,+ * then forks with store B attached. Verifies:+ * 1. Secret env vars from both stores are present (layered merge)+ * 2. Secrets are sealed in-guest (osb_sealed_* tokens, not plaintext)+ * 3. Actual secret VALUES resolve correctly through the proxy (httpbin echo)+ * 4. Store B's value wins on collision (SHARED_KEY override)+ * 5. Egress allowlists aggregate across layers+ *+ * Usage:+ * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-secret-store-fork.ts+ */++import { Sandbox, SecretStore } from "../src/index";+import { Snapshots, Image } from "../src/node";+import { randomBytes } from "node:crypto";++// Random values so we can verify exact substitution via httpbin+const GIT_TOKEN_VAL = `git_${randomBytes(12).toString("hex")}`;+const SHARED_KEY_A_VAL = `shared_a_${randomBytes(12).toString("hex")}`;+const SHARED_KEY_B_VAL = `shared_b_${randomBytes(12).toString("hex")}`;+const API_KEY_VAL = `api_${randomBytes(12).toString("hex")}`;++let storeAId: string | null = null;+let storeBId: string | null = null;+let baseSandbox: Sandbox | null = null;+let forkedSandbox: Sandbox | null = null;+let snapshotSandbox: Sandbox | null = null;+let snapshotName: string | null = null;+let passed = 0;+let failed = 0;++const green = (s: string) => console.log(`\x1b[32m✓ ${s}\x1b[0m`);+const red = (s: string, detail?: string) =>+ console.log(`\x1b[31m✗ ${s}${detail ? ` — ${detail}` : ""}\x1b[0m`);+const bold = (s: string) => console.log(`\x1b[1m${s}\x1b[0m`);+const dim = (s: string) => console.log(`\x1b[2m ${s}\x1b[0m`);++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) {+ green(desc);+ passed++;+ } else {+ red(desc, detail);+ failed++;+ }+}++async function main() {+ const suffix = Date.now();+ const storeAName = `fork-test-a-${suffix}`;+ const storeBName = `fork-test-b-${suffix}`;++ try {+ // ── Setup: two secret stores ──────────────────────────────────────+ bold("\n=== 1. Setup: create two secret stores ===\n");++ // Store A: egress to httpbin.org (for value verification) + github.com+ const storeA = await SecretStore.create({+ name: storeAName,+ egressAllowlist: ["github.com", "httpbin.org"],+ });+ storeAId = storeA.id;+ console.log(` Store A: ${storeAId} (${storeAName})`);++ await SecretStore.setSecret(storeAId, "GIT_TOKEN", GIT_TOKEN_VAL, {+ allowedHosts: ["github.com", "httpbin.org"],+ });+ await SecretStore.setSecret(storeAId, "SHARED_KEY", SHARED_KEY_A_VAL, {+ allowedHosts: ["httpbin.org"],+ });+ dim(`GIT_TOKEN = ${GIT_TOKEN_VAL}`);+ dim(`SHARED_KEY(A) = ${SHARED_KEY_A_VAL}`);+ green(+ "Store A created: GIT_TOKEN + SHARED_KEY, egress=[github.com, httpbin.org]",+ );++ // Store B: egress to httpbin.org (for value verification) + api.anthropic.com+ const storeB = await SecretStore.create({+ name: storeBName,+ egressAllowlist: ["api.anthropic.com", "httpbin.org"],+ });+ storeBId = storeB.id;+ console.log(` Store B: ${storeBId} (${storeBName})`);++ await SecretStore.setSecret(storeBId, "API_KEY", API_KEY_VAL, {+ allowedHosts: ["api.anthropic.com", "httpbin.org"],+ });+ await SecretStore.setSecret(storeBId, "SHARED_KEY", SHARED_KEY_B_VAL, {+ allowedHosts: ["httpbin.org"],+ });+ dim(`API_KEY = ${API_KEY_VAL}`);+ dim(`SHARED_KEY(B) = ${SHARED_KEY_B_VAL} (should override A)`);+ green(+ "Store B created: API_KEY + SHARED_KEY(override), egress=[api.anthropic.com, httpbin.org]",+ );++ // ── Layer 1: sandbox with store A ─────────────────────────────────+ bold("\n=== 2. Create base sandbox with store A ===\n");++ baseSandbox = await Sandbox.create({+ secretStore: storeAName,+ timeout: 120,+ });+ console.log(` Base sandbox: ${baseSandbox.sandboxId}`);+ await new Promise((r) => setTimeout(r, 5000));++ const envBase = (await baseSandbox.exec.run("env")).stdout;+ check("Base has GIT_TOKEN", envBase.includes("GIT_TOKEN"));+ check("Base has SHARED_KEY", envBase.includes("SHARED_KEY"));+ check("Base does NOT have API_KEY", !envBase.includes("API_KEY"));++ // Verify secrets are sealed (not plaintext) in base+ const baseGitEcho = (+ await baseSandbox.exec.run('printf %s "$GIT_TOKEN"')+ ).stdout.trim();+ check(+ "Base: GIT_TOKEN is sealed (not plaintext)",+ baseGitEcho.startsWith("osb_sealed_") &&+ !baseGitEcho.includes(GIT_TOKEN_VAL),+ `got "${baseGitEcho.slice(0, 40)}..."`,+ );++ // Verify actual value via httpbin+ const baseHttpbin = (+ await baseSandbox.exec.run(+ `curl -sS -m 10 https://httpbin.org/headers -H "X-Git: $GIT_TOKEN" -H "X-Shared: $SHARED_KEY"`,+ )+ ).stdout;+ check(+ "Base: GIT_TOKEN value resolves correctly via httpbin",+ baseHttpbin.includes(GIT_TOKEN_VAL),+ `httpbin did not echo back ${GIT_TOKEN_VAL}`,+ );+ check(+ "Base: SHARED_KEY(A) value resolves correctly via httpbin",+ baseHttpbin.includes(SHARED_KEY_A_VAL),+ `httpbin did not echo back ${SHARED_KEY_A_VAL}`,+ );++ // ── Checkpoint ────────────────────────────────────────────────────+ bold("\n=== 3. Create checkpoint from base ===\n");++ const cp = await baseSandbox.createCheckpoint("fork-test-cp");+ console.log(` Checkpoint: ${cp.id}`);++ for (let i = 0; i < 30; i++) {+ const cps = await baseSandbox.listCheckpoints();+ const found = cps.find((c: { id: string }) => c.id === cp.id);+ if (found && (found as any).status === "ready") break;+ await new Promise((r) => setTimeout(r, 2000));+ }+ green("Checkpoint ready");++ // ── Layer 2: fork with store B ────────────────────────────────────+ bold(+ "\n=== 4. Fork from checkpoint with store B (secretStore inheritance) ===\n",+ );++ forkedSandbox = await Sandbox.createFromCheckpoint(cp.id, {+ secretStore: storeBName,+ timeout: 120,+ });+ console.log(` Forked sandbox: ${forkedSandbox.sandboxId}`);+ await new Promise((r) => setTimeout(r, 5000));++ // ── Network debug for checkpoint fork ──────────────────────────────+ bold("\n=== 4-debug. Network state inside checkpoint fork ===\n");++ const netDebug = await forkedSandbox.exec.run(+ 'echo "=== IP ===" && ip addr show eth0 2>&1 && ' ++ 'echo "=== ROUTE ===" && ip route 2>&1 && ' ++ 'echo "=== ARP ===" && ip neigh 2>&1 && ' ++ 'echo "=== HTTP_PROXY ===" && echo "$HTTP_PROXY" && ' ++ 'echo "=== PROXY REACH ===" && curl -sS --connect-timeout 5 -o /dev/null -w "http_code=%{http_code}" "$HTTP_PROXY" 2>&1 || echo "UNREACHABLE" && ' ++ 'echo "=== PING GW ===" && ping -c 1 -W 2 $(ip route | grep default | awk "{print \\$3}") 2>&1 || echo "PING_FAIL"',+ );+ dim("Network debug output:");+ for (const line of netDebug.stdout.split("\n")) {+ dim(line);+ }+ if (netDebug.stderr) {+ dim("stderr: " + netDebug.stderr);+ }++ // ── 4a. Check env vars exist ──────────────────────────────────────+ bold("\n=== 4a. Verify secret env vars present ===\n");++ const envFork = (await forkedSandbox.exec.run("env")).stdout;+ check(+ "Fork has GIT_TOKEN (inherited from store A)",+ envFork.includes("GIT_TOKEN"),+ );+ check("Fork has API_KEY (from store B)", envFork.includes("API_KEY"));+ check("Fork has SHARED_KEY (merged)", envFork.includes("SHARED_KEY"));+ check(+ "Fork has HTTP_PROXY (secrets proxy active)",+ envFork.includes("HTTP_PROXY"),+ );++ const sealedCount = (envFork.match(/osb_sealed_/g) || []).length;+ check(+ `Fork has 3 sealed secrets (got ${sealedCount})`,+ sealedCount === 3,+ "expected GIT_TOKEN(A) + SHARED_KEY(B override) + API_KEY(B)",+ );++ // ── 4b. Verify secrets are sealed (not plaintext) ─────────────────+ bold("\n=== 4b. Verify secrets are sealed in-guest ===\n");++ const forkGitEcho = (+ await forkedSandbox.exec.run('printf %s "$GIT_TOKEN"')+ ).stdout.trim();+ check(+ "Fork: GIT_TOKEN is sealed",+ forkGitEcho.startsWith("osb_sealed_") &&+ !forkGitEcho.includes(GIT_TOKEN_VAL),+ `got "${forkGitEcho.slice(0, 40)}..."`,+ );++ const forkApiEcho = (+ await forkedSandbox.exec.run('printf %s "$API_KEY"')+ ).stdout.trim();+ check(+ "Fork: API_KEY is sealed",+ forkApiEcho.startsWith("osb_sealed_") &&+ !forkApiEcho.includes(API_KEY_VAL),+ `got "${forkApiEcho.slice(0, 40)}..."`,+ );++ const forkSharedEcho = (+ await forkedSandbox.exec.run('printf %s "$SHARED_KEY"')+ ).stdout.trim();+ check(+ "Fork: SHARED_KEY is sealed",+ forkSharedEcho.startsWith("osb_sealed_") &&+ !forkSharedEcho.includes(SHARED_KEY_B_VAL),+ `got "${forkSharedEcho.slice(0, 40)}..."`,+ );++ // ── 4c. Verify actual VALUES via httpbin ──────────────────────────+ bold(+ "\n=== 4c. Verify actual secret values via httpbin (proxy substitution) ===\n",+ );++ const forkHttpbin = (+ await forkedSandbox.exec.run(+ `curl -sS -m 10 https://httpbin.org/headers ` ++ `-H "X-Git: $GIT_TOKEN" ` ++ `-H "X-Api: $API_KEY" ` ++ `-H "X-Shared: $SHARED_KEY"`,+ )+ ).stdout;+ dim(`httpbin response (first 500 chars):`);+ dim(forkHttpbin.replace(/\s+/g, " ").slice(0, 500));++ check(+ "Fork: GIT_TOKEN value correct (inherited from A)",+ forkHttpbin.includes(GIT_TOKEN_VAL),+ `httpbin did not echo back ${GIT_TOKEN_VAL}`,+ );+ check(+ "Fork: API_KEY value correct (from B)",+ forkHttpbin.includes(API_KEY_VAL),+ `httpbin did not echo back ${API_KEY_VAL}`,+ );+ check(+ "Fork: SHARED_KEY has B's value (B override wins on collision)",+ forkHttpbin.includes(SHARED_KEY_B_VAL),+ `httpbin did not echo back B's value ${SHARED_KEY_B_VAL}`,+ );+ check(+ "Fork: SHARED_KEY does NOT have A's value (overridden by B)",+ !forkHttpbin.includes(SHARED_KEY_A_VAL),+ `httpbin echoed A's value ${SHARED_KEY_A_VAL} — override did not work`,+ );++ // ── 4d. Verify egress aggregation ─────────────────────────────────+ bold("\n=== 4d. Verify egress allowlist aggregation ===\n");++ // github.com (from A) and api.anthropic.com (from B) should both be reachable+ const githubResult = await forkedSandbox.exec.run(+ `curl -sS -m 10 -o /dev/null -w '%{http_code}' https://github.com/ 2>&1 || echo "BLOCKED"`,+ );+ check(+ "Fork: github.com reachable (from store A egress)",+ !githubResult.stdout.includes("BLOCKED") &&+ !githubResult.stdout.includes("000"),+ `got "${githubResult.stdout.trim()}"`,+ );++ const anthropicResult = await forkedSandbox.exec.run(+ `curl -sS -m 10 -o /dev/null -w '%{http_code}' https://api.anthropic.com/ 2>&1 || echo "BLOCKED"`,+ );+ check(+ "Fork: api.anthropic.com reachable (from store B egress)",+ !anthropicResult.stdout.includes("BLOCKED") &&+ !anthropicResult.stdout.includes("000"),+ `got "${anthropicResult.stdout.trim()}"`,+ );++ // ── 5. Snapshot/template path: create snapshot, fork with secretStore ──+ bold("\n=== 5. Create snapshot template, fork with secretStore ===\n");++ const snapshots = new Snapshots();+ snapshotName = `fork-secret-test-${suffix}`;+ dim(`Creating snapshot "${snapshotName}" from base image...`);+ await snapshots.create({+ name: snapshotName,+ image: Image.base().runCommands(+ "echo 'template-ready' > /home/sandbox/marker.txt",+ ),+ });++ // Poll until snapshot is ready+ for (let i = 0; i < 30; i++) {+ const info = await snapshots.get(snapshotName);+ if (info.status === "ready") break;+ await new Promise((r) => setTimeout(r, 2000));+ }+ green(`Snapshot "${snapshotName}" ready`);++ // Fork from snapshot with store B attached+ snapshotSandbox = await Sandbox.create({+ snapshot: snapshotName,+ secretStore: storeBName,+ timeout: 120,+ });+ console.log(` Snapshot-forked sandbox: ${snapshotSandbox.sandboxId}`);+ await new Promise((r) => setTimeout(r, 5000));++ // Verify the template content survived+ const marker = (+ await snapshotSandbox.exec.run("cat /home/sandbox/marker.txt")+ ).stdout.trim();+ check(+ "Snapshot fork: template content present (/home/sandbox/marker.txt)",+ marker === "template-ready",+ `got "${marker}"`,+ );++ // Verify secrets from store B are available+ const envSnap = (await snapshotSandbox.exec.run("env")).stdout;+ check(+ "Snapshot fork: has API_KEY (from store B)",+ envSnap.includes("API_KEY"),+ );+ check(+ "Snapshot fork: has SHARED_KEY (from store B)",+ envSnap.includes("SHARED_KEY"),+ );+ check(+ "Snapshot fork: has HTTP_PROXY (secrets proxy active)",+ envSnap.includes("HTTP_PROXY"),+ );++ // Verify secrets are sealed+ const snapApiEcho = (+ await snapshotSandbox.exec.run('printf %s "$API_KEY"')+ ).stdout.trim();+ check(+ "Snapshot fork: API_KEY is sealed",+ snapApiEcho.startsWith("osb_sealed_") &&+ !snapApiEcho.includes(API_KEY_VAL),+ `got "${snapApiEcho.slice(0, 40)}..."`,+ );++ // Verify actual values via httpbin+ const snapHttpbin = (+ await snapshotSandbox.exec.run(+ `curl -sS -m 10 https://httpbin.org/headers ` ++ `-H "X-Api: $API_KEY" ` ++ `-H "X-Shared: $SHARED_KEY"`,+ )+ ).stdout;+ dim(`httpbin response (first 500 chars):`);+ dim(snapHttpbin.replace(/\s+/g, " ").slice(0, 500));++ check(+ "Snapshot fork: API_KEY value correct via httpbin",+ snapHttpbin.includes(API_KEY_VAL),+ `httpbin did not echo back ${API_KEY_VAL}`,+ );+ check(+ "Snapshot fork: SHARED_KEY has B's value via httpbin",+ snapHttpbin.includes(SHARED_KEY_B_VAL),+ `httpbin did not echo back ${SHARED_KEY_B_VAL}`,+ );++ // ── Summary ───────────────────────────────────────────────────────+ bold(`\n=== Results: ${passed} passed, ${failed} failed ===\n`);+ } finally {+ bold("=== Cleanup ===");+ if (snapshotSandbox) {+ try {+ await snapshotSandbox.shutdown();+ } catch {}+ }+ if (forkedSandbox) {+ try {+ await forkedSandbox.shutdown();+ } catch {}+ }+ if (baseSandbox) {+ try {+ await baseSandbox.shutdown();+ } catch {}+ }+ if (snapshotName) {+ try {+ const snapshots = new Snapshots();+ await snapshots.delete(snapshotName);+ } catch {}+ }+ if (storeBId) {+ try {+ await SecretStore.delete(storeBId);+ } catch {}+ }+ if (storeAId) {+ try {+ await SecretStore.delete(storeAId);+ } catch {}+ }+ green("Cleanup done");+ }++ process.exit(failed > 0 ? 1 : 0);+}++main().catch((err) => {+ console.error("Fatal:", err);+ process.exit(1);+});diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex cbffb02a..91c00cc9 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.5.13",+ "version": "0.5.14","description": "TypeScript SDK for OpenComputer - cloud sandbox platform","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 5aec9300..00eec816 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -338,12 +338,14 @@ export class Sandbox {(this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");}- static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout"> = {}): Promise<Sandbox> {+ static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout" | "envs" | "secretStore"> = {}): Promise<Sandbox> {const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";const body: Record<string, unknown> = {};if (opts.timeout != null) body.timeout = opts.timeout;+ if (opts.envs) body.envs = opts.envs;+ if (opts.secretStore) body.secretStore = opts.secretStore;const resp = await fetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {method: "POST",