nanoclaw
A lightweight alternative to OpenClaw that runs in containers for security. Connects to WhatsApp, Telegram, Slack, Discord, Gmail and other messaging apps,, has memory, scheduled jobs, and runs directly on Anthropic's Agents SDK
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/nanocoai/nanoclaw with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/nanocoai/nanoclaw'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/nanocoai-nanoclaw)HTML
<a href="/listings/nanocoai-nanoclaw"><img src="/api/listings/nanocoai-nanoclaw/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2 cd nanoclaw-v2 bash nanoclaw.sh
`nanoclaw.sh` walks you from a fresh machine to a named agent you can message. It installs Node, pnpm, and Docker if missing, installs a credential gateway and registers your Anthropic credential with it, builds the agent container, and pairs your first channel (Slack, Telegram, Discord, WhatsApp, iMessage, or a local CLI). If a step fails, Claude Code is invoked automatically to diagnose and resume from where it broke.
<details> <summary><strong>Migrating from NanoClaw v1?</strong></summary>
Run from a fresh v2 checkout next to your v1 install:
git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2 cd nanoclaw-v2 bash migrate-v2.sh
`migrate-v2.sh` finds your v1 install (sibling directory, or `NANOCLAW_V1_PATH=/path/to/nanoclaw`), migrates state into the v2 checkout, then `exec`s into Claude Code to finish the parts that need judgment (owner seeding, shared-memory migration, fork-customisation replay).
Run the script directly, not from inside a Claude session — the deterministic side needs interactive prompts and real shell I/O for Node/pnpm bootstrap, Docker, the credential gateway, and the container build.
**What it does:** merges `.env`, seeds the v2 DB from `registered_groups`, copies group folders + session data + scheduled tasks, installs the channel adapters you select, copies channel auth state (including the Baileys keystore for WhatsApp — LID mapping is now resolved per-message by the Baileys v7 adapter, not migrated), builds the agent container.
**What it doesn't:** flip the system service. Pick *"switch to v2"* at the prompt, or do it manually after testing — your v1 install is left untouched.
See [docs/v1-to-v2-changes.md](docs/v1-to-v2-changes.md) for what's different and [docs/migration-dev.md](docs/migration-dev.md) for development notes.
</details>
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 277 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <p align="center">
- <img src="assets/nanoclaw-logo.png" alt="NanoClaw" width="400">
- </p>
- <p align="center">
- An AI assistant that runs agents securely in their own containers. Lightweight, built to be easily understood and completely customized for your needs.
- </p>
- <p align="center">
- <a href="https://nanoclaw.dev">nanoclaw.dev</a> •
- <a href="https://docs.nanoclaw.dev">docs</a> •
- <a href="README_zh.md">中文</a> •
- <a href="README_ja.md">日本語</a> •
- <a href="README_ko.md">한국어</a> •
- <a href="https://discord.gg/VDdww8qS42"><img src="https://img.shields.io/discord/1470188214710046894?label=Discord&logo=discord&v=2" alt="Discord" valign="middle"></a> •
- <a href="repo-tokens"><img src="repo-tokens/badge.svg" alt="repo tokens" valign="middle"></a>
- </p>
- ---
- <div align="center">
- ### <img src="https://img.shields.io/badge/NEW!-2EB67D?style=for-the-badge" alt="NEW!" valign="middle"> Agents in Slack: one app per agent <img src="assets/slack-icon.svg" alt="" width="22" valign="middle">
- Setup provisions each agent its own Slack app: manifest, avatar, and workspace install, no tokens to paste.
- Spawn teammates from chat: every one gets its own bot identity, container, and memory, with shared rooms and canvases.
- [](#quick-start)
- </div>
- ---
- ## Why I Built NanoClaw
- [OpenClaw](https://github.com/openclaw/openclaw) is an impressive project, but I wouldn't have been able to sleep if I had given complex software I didn't understand full access to my life. OpenClaw has nearly half a million lines of code, 53 config files, and 70+ dependencies. Its security is at the application level (allowlists, pairing codes) rather than true OS-level isolation. Everything runs in one Node process with shared memory.
- NanoClaw provides that same core functionality, but in a codebase small enough to understand: one process and a handful of files. Agents run in their own Linux containers with filesystem isolation, not merely behind permission checks.
- ## Quick Start
- ```bash
- git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2
- cd nanoclaw-v2
- bash nanoclaw.sh
- ```
- `nanoclaw.sh` walks you from a fresh machine to a named agent you can message. It installs Node, pnpm, and Docker if missing, installs a credential gateway and registers your Anthropic credential with it, builds the agent container, and pairs your first channel (Slack, Telegram, Discord, WhatsApp, iMessage, or a local CLI). If a step fails, Claude Code is invoked automatically to diagnose and resume from where it broke.
- <details>
- <summary><strong>Migrating from NanoClaw v1?</strong></summary>
- Run from a fresh v2 checkout next to your v1 install:
- ```bash
- git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2
- cd nanoclaw-v2
- bash migrate-v2.sh
- ```
- `migrate-v2.sh` finds your v1 install (sibling directory, or `NANOCLAW_V1_PATH=/path/to/nanoclaw`), migrates state into the v2 checkout, then `exec`s into Claude Code to finish the parts that need judgment (owner seeding, shared-memory migration, fork-customisation replay).
- Run the script directly, not from inside a Claude session — the deterministic side needs interactive prompts and real shell I/O for Node/pnpm bootstrap, Docker, the credential gateway, and the container build.
- **What it does:** merges `.env`, seeds the v2 DB from `registered_groups`, copies group folders + session data + scheduled tasks, installs the channel adapters you select, copies channel auth state (including the Baileys keystore for WhatsApp — LID mapping is now resolved per-message by the Baileys v7 adapter, not migrated), builds the agent container.
- **What it doesn't:** flip the system service. Pick *"switch to v2"* at the prompt, or do it manually after testing — your v1 install is left untouched.
- See [docs/v1-to-v2-changes.md](docs/v1-to-v2-changes.md) for what's different and [docs/migration-dev.md](docs/migration-dev.md) for development notes.
- </details>
- ## Philosophy
- **Small enough to understand.** One process, a few source files and no microservices. If you want to understand the full NanoClaw codebase, just ask Claude Code to walk you through it.
- **Secure by isolation.** Agents run in Linux containers and they can only see what's explicitly mounted. Bash access is safe because commands run inside the container, not on your host.
- **Built for the individual user.** NanoClaw isn't a monolithic framework; it's software that fits each user's exact needs. Instead of becoming bloatware, NanoClaw is designed to be bespoke. You make your own fork and have Claude Code modify it to match your needs.
- **Customization = code changes.** No configuration sprawl. Want different behavior? Modify the code. The codebase is small enough that it's safe to make changes.
- **AI-native, hybrid by design.** The install and onboarding flow is an optimized scripted path, fast and deterministic. When a step needs judgment, whether a failed install, a guided decision, or a customization, control hands off to Claude Code seamlessly. Beyond setup there's no monitoring dashboard or debugging UI either: describe the problem in chat and Claude Code handles it.
- **Skills over features.** Trunk ships the registry and infrastructure, not specific channel adapters or alternative agent providers. Channels (Discord, Slack, Telegram, WhatsApp, …) live on a long-lived `channels` branch; alternative providers (OpenCode, Codex, Cursor) ship inside their own skill's `payload/` folder. You run `/add-telegram`, `/add-opencode`, etc. and the skill copies exactly the module(s) you need into your fork. No feature you didn't ask for.
- **Best harness, best model.** NanoClaw natively uses Claude Code via Anthropic's official Claude Agent SDK, so you get the latest Claude models and Claude Code's full toolset, including the ability to modify and expand your own NanoClaw fork. Other providers are drop-in options: `/add-codex` for OpenAI's Codex (ChatGPT subscription or API key), `/add-opencode` for OpenRouter, Google, DeepSeek and more via OpenCode, `/add-cursor` for Cursor's local Agent SDK (Cursor account or API key), and `/add-ollama-provider` for local open-weight models. Provider is configurable per agent group.
- ## What It Supports
- - **Multi-channel messaging** — WhatsApp, Telegram, Discord, Slack, Microsoft Teams, iMessage, Matrix, Google Chat, Webex, Linear, GitHub, WeChat, and email via Resend. Installed on demand with `/add-<channel>` skills. Run one or many at the same time.
- - **Flexible isolation** — connect each channel to its own agent for full privacy, share one agent across many channels for unified memory with separate conversations, or fold multiple channels into a single shared session so one conversation spans many surfaces. Pick per channel via `/manage-channels`. See [docs/isolation-model.md](docs/isolation-model.md).
- - **Per-agent workspace** — each agent group has its own `CLAUDE.md`, its own memory, its own container, and only the mounts you allow. Nothing crosses the boundary unless you wire it to.
- - **Scheduled tasks**: recurring jobs executed by the agent, with optional [script gates](docs/scheduled-tasks.md) that avoid waking it when there is no work
- - **Web access** — search and fetch content from the web
- - **Container isolation** — agents are sandboxed in Docker containers (macOS/Linux/WSL2)
- - **Credential security** — agents never hold raw API keys. Outbound requests route through a credential gateway that injects credentials at request time and enforces per-agent policies and rate limits. Which gateway is yours to pick: setup installs one (currently [OneCLI's Agent Vault](https://github.com/onecli/onecli)) behind a provider seam.
- - **Agent templates**: stamp a ready-to-run agent (instructions + MCP tools + skills, no secrets) from a reusable bundle via `ncl groups create --template <ref>`. Templates load from the local `templates/` folder; populate it by hand or by copying from the [public library](https://github.com/nanocoai/nanoclaw-templates). See [docs/templates.md](docs/templates.md).
- ## Accounts and what leaves your machine
- NanoClaw has no user accounts. The only thing it reports is anonymous setup diagnostics, and
- `NANOCLAW_NO_DIAGNOSTICS=1` turns those off. Your agents, messages, files and keys never leave
- your machine.
- One opt-in exception: you can [fetch a prebuilt agent image](docs/hardened-image.md) instead of
- building it locally. Fetching ours needs a free account, so we see your email address and when
- you ask for an image — nothing about your agents, and nothing after the image lands. Building
- locally needs no account and contacts nothing, and is the default. The same account unlocks the
- [perks](#perks) below.
- ## Perks
- The free account also opens the **community portal** at [portal.nanoclaw.dev](https://portal.nanoclaw.dev),
- a dashboard where you switch on what the account offers. Today that is Echo's hardened agent
- image and a managed Slack app for your agent, created and installed for you with no tokens to
- paste. Everything else in NanoClaw works without it.
- Setup opens the portal once. You sign in in the browser, approve the terminal you are running
- setup from, and enable the perk; the wizard notices and continues on its own. Enabling Echo is
- where you agree to Echo's terms, including whether you want product and security email. Close
- the page without enabling anything and setup carries on without the perk, then offers it once
- more later.
- What stays on your machine: the sign-in record and install token in `~/.config/nanoclaw/account.json`,
- one device key per machine in `~/.config/nanoclaw/device-key.json`, and this checkout's journal in
- `data/community-portal.json` (which perks are on, setup progress, the credentials a perk handed
- you), all mode `0600`. The install token never passes through the browser: the browser sees only
- the one-time sign-in code, and the token reaches this machine from the account service directly.
- The host keeps one outbound connection to the portal so a perk you change in the browser reaches
- the running agent; it sends nothing about your agents, messages or files.
- Revisit a step with `pnpm exec tsx setup/portal.ts --stage echo` or `--stage slack`. To sign a
- machine out, forget it under **Devices** in the portal: its token stops working and the host
- disconnects. Files, recovery commands and troubleshooting: [docs/community-portal.md](docs/community-portal.md).
- ## Usage
- Talk to your assistant with the trigger word (default: `@Andy`):
- ```
- @Andy send an overview of the sales pipeline every weekday morning at 9am (has access to my Obsidian vault folder)
- @Andy review the git history for the past week each Friday and update the README if there's drift
- @Andy every Monday at 8am, compile news on AI developments from Hacker News and TechCrunch and message me a briefing
- ```
- From a channel you own or administer, you can manage groups and tasks:
- ```
- @Andy list all scheduled tasks across groups
- @Andy pause the Monday briefing task
- @Andy join the Family Chat group
- ```
- ## Customizing
- NanoClaw doesn't use configuration files. To make changes, just tell Claude Code what you want:
- - "Change the trigger word to @Bob"
- - "Remember in the future to make responses shorter and more direct"
- - "Add a custom greeting when I say good morning"
- - "Store conversation summaries weekly"
- Or run `/customize` for guided changes.
- The codebase is small enough that Claude can safely modify it.
- ## Contributing
- **Don't add features. Add skills.**
- If you want to add a new channel or agent provider, don't add it to trunk. New channel adapters land on the `channels` branch; a new agent provider keeps its code in its skill's `payload/` folder on `main`. Users install them in their own fork with `/add-<name>` skills, which copy the relevant module(s) into the standard paths, wire the registration, and pin dependencies.
- This keeps trunk as pure registry and infra, and every fork stays lean — users get the channels and providers they asked for and nothing else.
- ### RFS (Request for Skills)
- No channel or provider skills are currently requested — propose one via an issue.
- ## Requirements
- - macOS or Linux (Windows via WSL2)
- - Node.js 22.23.4+, 24.22.1+ or 26.12.1+ and pnpm 10+ (the installer will install or update both if needed)
- - jq (the installer adds it if missing; channel skills use it)
- - [Docker Desktop](https://docker.com/products/docker-desktop) (macOS/Windows) or Docker Engine (Linux)
- - [Claude Code](https://claude.ai/download) for `/customize`, `/debug`, error recovery during setup, and all `/add-<channel>` skills
- ## Architecture
- ```
- messaging apps → host process (router) → inbound.db → container (Bun, Claude Agent SDK) → outbound.db → host process (delivery) → messaging apps
- ```
- A single Node host orchestrates per-session agent containers. When a message arrives, the host routes it via the entity model (user → messaging group → agent group → session), writes it to the session's `inbound.db`, and wakes the container. The agent-runner inside the container polls `inbound.db`, runs the agent, and writes responses to `outbound.db`. The host polls `outbound.db` and delivers back through the channel adapter.
- Two SQLite files per session, each with exactly one writer — no cross-mount contention, no IPC, no stdin piping. Channels and alternative providers self-register at startup; trunk ships the registry and the Chat SDK bridge, while the adapters themselves are skill-installed per fork.
- For the full architecture writeup see [docs/architecture.md](docs/architecture.md); for the three-level isolation model see [docs/isolation-model.md](docs/isolation-model.md).
- Key files:
- - `src/index.ts` — entry point: DB init, channel adapters, delivery polls, sweep
- - `src/router.ts` — inbound routing: messaging group → agent group → session → `inbound.db`
- - `src/delivery.ts` — polls `outbound.db`, delivers via adapter, handles system actions
- - `src/host-sweep.ts` — 60s sweep: stale detection, due-message wake, recurrence
- - `src/session-manager.ts` — resolves sessions, opens `inbound.db` / `outbound.db`
- - `src/container-runner.ts` — spawns per-agent-group containers, leases the session's gateway contribution
- - `src/db/` — central DB (users, roles, agent groups, messaging groups, wiring, migrations)
- - `src/channels/` — channel adapter infra (adapters installed via `/add-<channel>` skills)
- - `src/providers/` — host-side provider config (`claude` baked in; others via skills)
- - `container/agent-runner/` — Bun agent-runner: poll loop, MCP tools, provider abstraction
- - `groups/<folder>/` — per-agent-group filesystem (`CLAUDE.md`, skills, container config)
- ## FAQ
- **Why Docker?**
- Docker provides cross-platform support (macOS, Linux and Windows via WSL2) and a mature ecosystem.
- **Can I run this on Linux or Windows?**
- Yes. Docker is the default runtime and works on macOS, Linux, and Windows (via WSL2). Just run `bash nanoclaw.sh`.
- **Is this secure?**
- Agents run in containers, not behind application-level permission checks. They can only access explicitly mounted directories. Credentials never enter the container — outbound API requests route through the installed credential gateway, which injects authentication at the proxy level and supports rate limits and access policies. You should still review what you're running, but the codebase is small enough that you actually can. See the [security documentation](https://docs.nanoclaw.dev/concepts/security) for the full security model.
- **Why no configuration files?**
- We don't want configuration sprawl. Every user should customize NanoClaw so that the code does exactly what they want, rather than configuring a generic system. If you prefer having config files, you can tell Claude to add them.
- **Can I use third-party or open-source models?**
- Yes. The supported path is `/add-opencode` (OpenRouter, OpenAI, Google, DeepSeek, and more via OpenCode config) or `/add-ollama-provider` (local open-weight models via Ollama). Both are configurable per agent group, so different agents can run on different backends in the same install.
- For one-off experiments, any Claude API-compatible endpoint also works via `.env`:
- ```bash
- ANTHROPIC_BASE_URL=https://your-api-endpoint.com
- ANTHROPIC_AUTH_TOKEN=your-token-here
- ```
- **How do I debug issues?**
- Ask Claude Code. "Why isn't the scheduler running?" "What's in the recent logs?" "Why did this message not get a response?" That's the AI-native approach that underlies NanoClaw.
- **Why isn't the setup working for me?**
- If a step fails, `nanoclaw.sh` hands off to Claude Code to diagnose and resume. If that doesn't resolve it, run `claude`, then `/debug`. If Claude identifies an issue likely to affect other users, open a PR against the relevant setup step or skill.
- **How do I uninstall NanoClaw?**
- ```bash
- bash nanoclaw.sh --uninstall
- ```
- Every install is tagged with a per-checkout id, so the uninstaller removes only what belongs to that copy: the background service, containers and image, app data and logs, your agents' files, and this copy's gateway agents. Shared things — the gateway service and your credentials, other NanoClaw copies on the machine — are left alone. It shows exactly what it found and asks for confirmation per group; nothing is deleted until you say yes. Use `--dry-run` to preview without changing anything, or `--yes` to skip the prompts. Your `.env` is backed up before removal. To finish, delete the checkout folder itself.
- **What changes will be accepted into the codebase?**
- Only security fixes, bug fixes, and clear improvements will be accepted to the base configuration. That's all.
- Everything else (new capabilities, OS compatibility, hardware support, enhancements) should be contributed as skills: channel code on the `channels` registry branch, everything else (agent providers included) as a self-contained skill. See [docs/customizing.md](docs/customizing.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
- This keeps the base system minimal and lets every user customize their installation without inheriting features they don't want.
- ## Community
- Questions? Ideas? [Join the Discord](https://discord.gg/VDdww8qS42).
- ## Changelog
- See [CHANGELOG.md](CHANGELOG.md) for breaking changes, or the [full release history](https://docs.nanoclaw.dev/changelog) on the documentation site.
- ## License
- MIT
- <img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=47894bd5-353b-42fe-bb97-74144e6df0bf" />
.claude/skills/add-codex/payload/container/agent-runner/src/providers/codex-app-server.test.ts · Bundled script · 542 lines · 2 findings marked
- import { describe, expect, it, afterEach } from 'bun:test';
- import fs from 'fs';
- import os from 'os';
- import path from 'path';
- import {
- type AppServer,
- CODEX_APP_SERVER_ARGS,
- attachCodexAutoApproval,
- buildCodexConfigPlan,
- buildCodexProcessEnv,
- codexInferenceSection,
- renderCodexConfigToml,
- startOrResumeCodexThread,
- tomlBasicString,
- writeCodexConfigToml,
- } from './codex-app-server.js';
- import { CodexProvider } from './codex.js';
- const MEMORY_SESSION_HOOK = {
- command: 'bun /app/src/memory/hook.ts',
- legacyCommands: ['bun /app/src/memory-hook.ts'],
- sources: ['startup', 'clear', 'compact'],
- } as const;
- let tmpHome: string | null = null;
- const originalHome = process.env.HOME;
- afterEach(() => {
- process.env.HOME = originalHome;
- if (tmpHome) {
- fs.rmSync(tmpHome, { recursive: true, force: true });
- tmpHome = null;
- }
- });
- describe('Codex config TOML', () => {
- it('builds every declared configuration capability before rendering', () => {
- const mcpServers = { nanoclaw: { command: 'bun', args: ['run', 'server.ts'] } };
- const plan = buildCodexConfigPlan(mcpServers, { model: 'gpt-5', effort: 'medium', fastMode: true });
- expect(plan).toEqual({
- executionPolicy: {
- sandboxMode: 'danger-full-access',
- approvalPolicy: 'never',
- projectDocumentMaxBytes: 32768,
- },
- inference: { model: 'gpt-5', effort: 'medium', fastMode: true },
- memory: { memories: false, useMemories: false, generateMemories: false },
- mcpServers,
- });
- expect(renderCodexConfigToml(plan)).toContain('[mcp_servers.nanoclaw]');
- });
- it('renders the exact bytes, pinning line order and the trailing newline', () => {
- const content = renderCodexConfigToml(
- buildCodexConfigPlan(
- {
- nanoclaw: { command: 'bun', args: ['run', '/app/src/mcp-tools/index.ts'], env: { FOO: 'bar' } },
- docs: { type: 'http', url: 'https://mcp.example.com/mcp', headers: { 'X-Api-Version': '2024-06' } },
- },
- { model: 'gpt-5', effort: 'medium', fastMode: true },
- ),
- );
- expect(content).toBe(
- [
- 'sandbox_mode = "danger-full-access"',
- 'approval_policy = "never"',
- 'project_doc_max_bytes = 32768',
- 'mcp_optional_startup_grace_ms = 0',
- 'model = "gpt-5"',
- 'model_reasoning_effort = "medium"',
- 'service_tier = "fast"',
- '',
- '[features]',
- 'memories = false',
- '',
- '[memories]',
- 'use_memories = false',
- 'generate_memories = false',
- '',
- '[mcp_servers.nanoclaw]',
- 'required = true',
- 'command = "bun"',
- 'args = ["run", "/app/src/mcp-tools/index.ts"]',
- '[mcp_servers.nanoclaw.env]',
- 'FOO = "bar"',
- '',
- '[mcp_servers.docs]',
- 'url = "https://mcp.example.com/mcp"',
- '[mcp_servers.docs.http_headers]',
- '"X-Api-Version" = "2024-06"',
- '',
- ].join('\n'),
- );
- });
- // Core's speed property → Codex's service tier. `fast` is the only value
- // with a Codex rendering; `standard` (the core default) and anything else
- // emit no tier line, so Codex's own default serving tier stays in force.
- it('renders service_tier = "fast" only for speed fast', () => {
- const fast = renderCodexConfigToml({
- ...buildCodexConfigPlan({}, {}),
- inference: codexInferenceSection({ speed: 'fast' }),
- });
- expect(fast).toContain('service_tier = "fast"');
- // The tier is a plain top-level key: no feature flag rides along with it.
- expect(fast).not.toContain('fast_mode');
- const standard = renderCodexConfigToml({
- ...buildCodexConfigPlan({}, {}),
- inference: codexInferenceSection({ speed: 'standard' }),
- });
- expect(standard).not.toContain('service_tier');
- const unset = renderCodexConfigToml(buildCodexConfigPlan({}, {}));
- expect(unset).not.toContain('service_tier');
- });
- it('treats speed as a fast-or-default flag — other tier names are dropped, not passed through', () => {
- expect(codexInferenceSection({ speed: 'ultrafast' }).fastMode).toBeUndefined();
- const rendered = renderCodexConfigToml({
- ...buildCodexConfigPlan({}, {}),
- inference: codexInferenceSection({ speed: 'ultrafast' }),
- });
- expect(rendered).not.toContain('service_tier');
- expect(rendered).not.toContain('ultrafast');
- });
- it('escapes basic strings', () => {
- expect(tomlBasicString('a "quoted" \\\\ value')).toBe('"a \\"quoted\\" \\\\\\\\ value"');
- });
- it('escapes control characters TOML forbids raw', () => {
- expect(tomlBasicString('bell\u0007tab\tdel\u007f')).toBe('"bell\\u0007tab\\u0009del\\u007F"');
- });
- it('rejects newlines', () => {
- expect(() => tomlBasicString('bad\nvalue')).toThrow(/newline/);
- });
- it('hardcodes danger-full-access + never and writes model, effort, fast mode, and MCP servers', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- writeCodexConfigToml(
- {
- nanoclaw: {
- command: 'bun',
- args: ['run', '/app/src/mcp-tools/index.ts'],
- env: { FOO: 'bar' },
- },
- docs: {
- type: 'http',
- url: 'https://mcp.example.com/mcp',
- headers: { 'X-Api-Version': '2024-06' },
- },
- },
- MEMORY_SESSION_HOOK,
- { model: 'gpt-5', effort: 'medium', fastMode: true },
- );
- const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
- expect(content).toContain('sandbox_mode = "danger-full-access"');
- expect(content).toContain('approval_policy = "never"');
- expect(content).toContain('project_doc_max_bytes = 32768');
- expect(content).toContain('model = "gpt-5"');
- expect(content).toContain('model_reasoning_effort = "medium"');
- expect(content).toContain('service_tier = "fast"');
- expect(content).toContain('[features]\nmemories = false');
- expect(content).toContain('[memories]\nuse_memories = false\ngenerate_memories = false');
- expect(content).not.toContain('[sandbox_workspace_write]');
- expect(content).not.toContain('writable_roots =');
- expect(content).toContain('[mcp_servers.nanoclaw]');
- expect(content).toContain('command = "bun"');
- expect(content).toContain('args = ["run", "/app/src/mcp-tools/index.ts"]');
- expect(content).toContain('[mcp_servers.nanoclaw.env]');
- expect(content).toContain('FOO = "bar"');
- expect(content).toContain(
- '[mcp_servers.docs]\nurl = "https://mcp.example.com/mcp"\n[mcp_servers.docs.http_headers]\n"X-Api-Version" = "2024-06"',
- );
- const hooks = JSON.parse(fs.readFileSync(path.join(tmpHome, '.codex', 'hooks.json'), 'utf-8'));
- expect(hooks.hooks.SessionStart).toEqual([
- {
- matcher: 'startup|clear|compact',
- hooks: [{ type: 'command', command: 'bun /app/src/memory/hook.ts', timeout: 10 }],
- },
- ]);
- expect(CODEX_APP_SERVER_ARGS).toContain('--dangerously-bypass-hook-trust');
- });
- it('emits cwd for a stdio server above the env sub-table, and omits it when absent', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- writeCodexConfigToml(
- {
- probe: {
- command: '/workspace/agent/plugins/sdr/run.js',
- args: ['--flag'],
- env: { FOO: 'bar' },
- cwd: '/workspace/agent/plugin-data/sdr',
- },
- plain: { command: 'bun' },
- },
- MEMORY_SESSION_HOOK,
- );
- const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
- expect(content).toContain(
- 'command = "/workspace/agent/plugins/sdr/run.js"\n' +
- 'cwd = "/workspace/agent/plugin-data/sdr"\n' +
- 'args = ["--flag"]\n' +
- '[mcp_servers.probe.env]',
- );
- const plainTable = content.split('[mcp_servers.plain]')[1].split('[mcp_servers.')[0];
- expect(plainTable).toContain('command = "bun"');
- expect(plainTable).not.toContain('cwd =');
- });
- it('quotes non-bare server names and env keys so they cannot open new tables', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- writeCodexConfigToml(
- {
- 'docs] [mcp_servers.evil]': {
- type: 'http',
- url: 'https://mcp.example.com/mcp',
- headers: { 'X-V': '1' },
- },
- plain: { command: 'bun', env: { 'BAD KEY': 'v' } },
- },
- MEMORY_SESSION_HOOK,
- );
- const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
- expect(content).toContain('[mcp_servers."docs] [mcp_servers.evil]"]');
- expect(content).toContain('[mcp_servers."docs] [mcp_servers.evil]".http_headers]');
- expect(content).not.toContain('\n[mcp_servers.evil]');
- expect(content).toContain('[mcp_servers.plain.env]');
- expect(content).toContain('"BAD KEY" = "v"');
- });
- it('fails closed on a server name containing a newline', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- expect(() =>
- writeCodexConfigToml(
- { 'docs]\n[mcp_servers.evil]': { type: 'http', url: 'https://mcp.example.com/mcp' } },
- MEMORY_SESSION_HOOK,
- ),
- ).toThrow(/newline/);
- });
- it('preserves unrelated hooks and refreshes only the NanoClaw memory entry', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- const hooksPath = path.join(tmpHome, '.codex', 'hooks.json');
- fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
- fs.writeFileSync(
- hooksPath,
- JSON.stringify({
- version: 1,
- hooks: {
- Stop: [{ hooks: [{ type: 'command', command: 'custom-stop' }] }],
- SessionStart: [
- { matcher: 'resume', hooks: [{ type: 'command', command: 'custom-resume' }] },
- {
- matcher: '.*',
- hooks: [
- { type: 'command', command: 'bun /app/src/memory-hook.ts' },
- { type: 'command', command: 'custom-start' },
- ],
- },
- ],
- },
- }),
- );
- writeCodexConfigToml({}, MEMORY_SESSION_HOOK);
- writeCodexConfigToml({}, MEMORY_SESSION_HOOK);
- const config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8'));
- expect(config.version).toBe(1);
- expect(config.hooks.Stop).toHaveLength(1);
- expect(config.hooks.SessionStart).toContainEqual({
- matcher: '.*',
- hooks: [{ type: 'command', command: 'custom-start' }],
- });
- expect(
- config.hooks.SessionStart.filter((entry: { hooks?: Array<{ command?: string }> }) =>
- entry.hooks?.some((hook) => hook.command === 'bun /app/src/memory/hook.ts'),
- ),
- ).toEqual([
- {
- matcher: 'startup|clear|compact',
- hooks: [{ type: 'command', command: 'bun /app/src/memory/hook.ts', timeout: 10 }],
- },
- ]);
- });
- it('replaces config.toml before malformed hooks.json fails', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- const codexDir = path.join(tmpHome, '.codex');
- const configPath = path.join(codexDir, 'config.toml');
- const hooksPath = path.join(codexDir, 'hooks.json');
- fs.mkdirSync(codexDir, { recursive: true });
- fs.writeFileSync(configPath, 'stale config');
- fs.writeFileSync(hooksPath, '{');
- expect(() => writeCodexConfigToml({}, MEMORY_SESSION_HOOK, { model: 'gpt-5' })).toThrow();
- expect(fs.readFileSync(configPath, 'utf-8')).toContain('model = "gpt-5"');
- expect(fs.readFileSync(configPath, 'utf-8')).not.toContain('stale config');
- expect(fs.readFileSync(hooksPath, 'utf-8')).toBe('{');
- });
- it('replaces config.toml before an existing empty hooks.json fails', () => {
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
- process.env.HOME = tmpHome;
- const codexDir = path.join(tmpHome, '.codex');
- const configPath = path.join(codexDir, 'config.toml');
- const hooksPath = path.join(codexDir, 'hooks.json');
- fs.mkdirSync(codexDir, { recursive: true });
- fs.writeFileSync(configPath, 'stale config');
- fs.writeFileSync(hooksPath, '');
- expect(() => writeCodexConfigToml({}, MEMORY_SESSION_HOOK, { model: 'gpt-5' })).toThrow();
- expect(fs.readFileSync(configPath, 'utf-8')).toContain('model = "gpt-5"');
- expect(fs.readFileSync(configPath, 'utf-8')).not.toContain('stale config');
- expect(fs.readFileSync(hooksPath, 'utf-8')).toBe('');
- });
- });
- describe('Codex thread SessionStart source', () => {
- it('sets startup only for a new thread', async () => {
- const { server, requests } = autoRespondingServer();
- await startOrResumeCodexThread(server, undefined, { cwd: '/workspace/agent' });
- expect(requests[0].method).toBe('thread/start');
- expect(requests[0].params.personality).toBe('friendly');
- expect(requests[0].params.config).toEqual({ bypass_hook_trust: true });
- expect(requests[0].params.sessionStartSource).toBe('startup');
- });
- it('does not send startup when resuming', async () => {
- const { server, requests } = autoRespondingServer();
- await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent', personality: 'pragmatic' });
- expect(requests[0].method).toBe('thread/resume');
- expect(requests[0].params.personality).toBe('pragmatic');
- expect(requests[0].params.config).toEqual({ bypass_hook_trust: true });
- expect(requests[0].params.sessionStartSource).toBeUndefined();
- });
- });
- // With the nanoclaw server required, Codex fails thread/start and thread/resume
- // when it cannot start. The resume failure must surface as an error, not be
- // read as a stale thread: that would start a new thread and silently drop the
- // conversation. Error strings are verbatim from codex 0.155.1, the pinned
- // version (0.146.0 words the failure without the repeated tail).
- describe('Codex thread resume failures', () => {
- const REQUIRED_MCP_FAILURE =
- 'error resuming thread: Fatal error: Failed to initialize session: required MCP servers failed to initialize: ' +
- 'nanoclaw: handshaking with MCP server failed: connection closed: initialize response: ' +
- 'connection closed: initialize response';
- const REQUIRED_MCP_TIMEOUT =
- 'error resuming thread: Fatal error: Failed to initialize session: required MCP servers failed to initialize: ' +
- 'nanoclaw: timed out handshaking with MCP server after 29.99999975s';
- const STALE_THREAD = 'no rollout found for thread id 01a0caf8-0000-7000-a000-000000000000';
- for (const [label, message] of [
- ['fails to start', REQUIRED_MCP_FAILURE],
- ['times out', REQUIRED_MCP_TIMEOUT],
- ] as const) {
- it(`keeps the thread when the required nanoclaw server ${label}`, async () => {
- const { server, requests } = autoRespondingServer({ 'thread/resume': message });
- const err = await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent' }).catch(
- (e: unknown) => e,
- );
- expect(err).toBeInstanceOf(Error);
- expect((err as Error).message).toBe(`thread/resume failed: ${message}`);
- expect(requests.map((r) => r.method)).toEqual(['thread/resume']);
- expect(new CodexProvider().isSessionInvalid(err)).toBe(false);
- });
- }
- it('still starts a fresh thread when the stored thread is gone', async () => {
- const { server, requests } = autoRespondingServer({ 'thread/resume': STALE_THREAD });
- const threadId = await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent' });
- expect(requests.map((r) => r.method)).toEqual(['thread/resume', 'thread/start']);
- expect(threadId).toBe('thread-new');
- expect(new CodexProvider().isSessionInvalid(new Error(STALE_THREAD))).toBe(true);
- });
- });
- describe('Codex auto-approval', () => {
- // NanoClaw (container isolation + OneCLI) is the boundary, so the handler accepts
- // every request unconditionally — even paths/commands a sandbox policy would refuse.
- it('grants full filesystem + network for permission requests', () => {
- const { server, writes } = fakeServer();
- attachCodexAutoApproval(server);
- server.serverRequestHandlers[0]({
- id: 1,
- method: 'item/permissions/requestApproval',
- params: { permissions: { fileSystem: { read: ['/workspace/agent'], write: ['/workspace/agent'] } } },
- });
- const result = JSON.parse(writes[0]).result as {
- permissions: { fileSystem: { read: string[]; write: string[] }; network: { enabled: boolean } };
- scope: string;
- };
- expect(result.scope).toBe('turn');
- expect(result.permissions.fileSystem.read).toEqual(['/']);
- expect(result.permissions.fileSystem.write).toEqual(['/']);
- expect(result.permissions.network.enabled).toBe(true);
- });
- it('accepts file-change and command-exec approvals regardless of path', () => {
- const { server, writes } = fakeServer();
- attachCodexAutoApproval(server);
- server.serverRequestHandlers[0]({
- id: 2,
- method: 'item/fileChange/requestApproval',
- params: { grantRoot: '/etc' },
- });
- server.serverRequestHandlers[0]({
- id: 3,
- method: 'item/commandExecution/requestApproval',
- params: { command: 'rm -rf /', cwd: '/' },
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 441 on GitHub
- });
- expect(JSON.parse(writes[0]).result).toEqual({ decision: 'accept' });
- expect(JSON.parse(writes[1]).result).toEqual({ decision: 'accept' });
- });
- it('approves legacy patch and command-exec approvals regardless of path', () => {
- const { server, writes } = fakeServer();
- attachCodexAutoApproval(server);
- server.serverRequestHandlers[0]({
- id: 4,
- method: 'applyPatchApproval',
- params: { fileChanges: { '/etc/passwd': {} } },
- });
- server.serverRequestHandlers[0]({
- id: 5,
- method: 'execCommandApproval',
- params: { command: 'rm -rf /', cwd: '/' },
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 460 on GitHub
- });
- expect(JSON.parse(writes[0]).result).toEqual({ decision: 'approved' });
- expect(JSON.parse(writes[1]).result).toEqual({ decision: 'approved' });
- });
- it('fails closed for unknown server requests', () => {
- const { server, writes } = fakeServer();
- attachCodexAutoApproval(server);
- server.serverRequestHandlers[0]({ id: 6, method: 'new/unknown/request' });
- const response = JSON.parse(writes[0]);
- expect(response.error.message).toContain('Unhandled Codex app-server request');
- });
- });
- describe('Codex process env', () => {
- it('forwards proxy/runtime env without leaking secret-like host env', () => {
- const env = buildCodexProcessEnv({
- PATH: '/bin',
- HOME: '/home/node',
- CODEX_HOME: '/home/node/.codex',
- HTTPS_PROXY: 'http://proxy',
- OPENAI_API_KEY: 'sk-test',
- ONECLI_API_KEY: 'onecli-secret',
- SOME_TOKEN: 'token',
- });
- expect(env.PATH).toBe('/bin');
- expect(env.HOME).toBe('/home/node');
- expect(env.CODEX_HOME).toBe('/home/node/.codex');
- expect(env.HTTPS_PROXY).toBe('http://proxy');
- expect(env.OPENAI_API_KEY).toBeUndefined();
- expect(env.ONECLI_API_KEY).toBeUndefined();
- expect(env.SOME_TOKEN).toBeUndefined();
- });
- });
- function fakeServer(): { server: AppServer; writes: string[] } {
- const writes: string[] = [];
- const server = {
- process: { stdin: { write: (line: string) => writes.push(line) } },
- readline: { close: () => {} },
- pending: new Map(),
- notificationHandlers: [],
- exitHandlers: [],
- serverRequestHandlers: [],
- } as unknown as AppServer;
- return { server, writes };
- }
- function autoRespondingServer(errors: Record<string, string> = {}): {
- server: AppServer;
- requests: Array<{ id: number; method: string; params: Record<string, unknown> }>;
- } {
- const requests: Array<{ id: number; method: string; params: Record<string, unknown> }> = [];
- let server: AppServer;
- server = {
- process: {
- stdin: {
- write: (line: string) => {
- const request = JSON.parse(line) as { id: number; method: string; params: Record<string, unknown> };
- requests.push(request);
- const error = errors[request.method];
- if (error) {
- server.pending.get(request.id)?.resolve({ id: request.id, error: { code: -32603, message: error } });
- return;
- }
- const threadId = (request.params.threadId as string | undefined) ?? 'thread-new';
- server.pending.get(request.id)?.resolve({ id: request.id, result: { thread: { id: threadId } } });
- },
- },
- },
- readline: { close: () => {} },
- pending: new Map(),
- notificationHandlers: [],
- exitHandlers: [],
- serverRequestHandlers: [],
- } as unknown as AppServer;
- return { server, requests };
- }
.claude/skills/add-cursor/payload/container/agent-runner/src/providers/cursor.gateway-proxy.test.ts · Bundled script · 625 lines · 1 finding marked
- /**
- * Proves the Cursor provider's network paths reach the credential gateway.
- *
- * The container never holds the Cursor key: the host injects the placeholder
- * `CURSOR_API_KEY`, the SDK sends it as a bearer header, and the gateway proxy
- * (HTTPS_PROXY) swaps in the vaulted key on its routes. That only holds if
- * every request actually transits the proxy carrying the placeholder. This
- * test stands up a fake CONNECT proxy and a fake TLS origin on localhost,
- * spawns the real provider + real `@cursor/sdk` in a child whose env mirrors
- * the container (HTTPS_PROXY, the gateway CA via SSL_CERT_FILE, and a decoy
- * CURSOR_API_KEY that must never appear on the wire), and asserts:
- *
- * - the user-key exchange (global fetch) arrives through the proxy with the
- * placeholder bearer;
- * - the agent runtime's Connect RPCs (connect-node over HTTP/1.1, i.e.
- * node:https) arrive through the same proxy carrying the exchanged token;
- * - nothing carries the decoy key, and no CONNECT targets anything but
- * Cursor's two API hosts;
- * - every TCP connection the origin accepted came out of a proxy tunnel,
- * and the child opened no TLS session of its own.
- *
- * The second case has the fake origin answer `GetServerConfig` with
- * `http2Config: FORCE_ALL_ENABLED`, which is how Cursor's server overrides the
- * client's HTTP/1.1 pin. Under Bun `node:http2` ignores HTTPS_PROXY, so the
- * provider's guard (`installHttp2ProxyGuard` in providers/cursor.ts) must
- * refuse the session before it dials. The child loads the provider barrel
- * first, exactly as the agent-runner does, so the http2 ESM namespace already
- * exists when the guard installs — the case where only its TLS-level hook can
- * hold — and reports that condition back for the assertion. No network is used
- * here — the CONNECT tunnel terminates at the local fake origin, so DNS for
- * Cursor's hosts is never consulted; if the guard ever failed, the refusal
- * assertion fails first.
- *
- * The last block exercises the guard on its own, in-process: no-op without a
- * proxy, refusal of `http2.connect` and of any ALPN-h2 TLS dial to a non-proxy
- * origin, CONNECT tunnelling of `node:https`, NO_PROXY, idempotence, restore.
- */
- import fs from 'fs';
- import http2 from 'http2';
- import https from 'https';
- import net from 'net';
- import os from 'os';
- import path from 'path';
- import tls from 'tls';
- import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
- import { CURSOR_API_KEY_PLACEHOLDER, http2ProxyBypassError, installHttp2ProxyGuard } from './cursor.js';
- // Throwaway self-signed certificate for the fake origin, valid for
- // api2.cursor.sh / api.cursor.com / localhost until 2126. Test fixture only —
- // it is also the "gateway CA" the child trusts via SSL_CERT_FILE, the same
- // variable the gateway sets for its own bundle.
- const FIXTURE_CERT = `-----BEGIN CERTIFICATE-----
- MIIB4jCCAYegAwIBAgIUdQfCJX6l6nTbL+9ujNqBbDQswdEwCgYIKoZIzj0EAwIw
- JzElMCMGA1UEAwwcbmFub2NsYXctY3Vyc29yLWdhdGV3YXktdGVzdDAgFw0yNjA5
- MDMxMzI1NDhaGA8yMTI2MDgxMDEzMjU0OFowJzElMCMGA1UEAwwcbmFub2NsYXct
- Y3Vyc29yLWdhdGV3YXktdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNIm
- FcIH4v+fbiAWNoooI3v3TJrPnsf61V39UYZLi5GRkpreP7r6pfhD5Wf2G49R/U8r
- ZWpbkO6T0bg2tc6qcdijgY4wgYswOgYDVR0RBDMwMYIOYXBpMi5jdXJzb3Iuc2iC
- DmFwaS5jdXJzb3IuY29tgglsb2NhbGhvc3SHBH8AAAEwDAYDVR0TBAUwAwEB/zAL
- BgNVHQ8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFAdUNoI+
- 19cTO4TLXVIkzpZENEXlMAoGCCqGSM49BAMCA0kAMEYCIQD2xdyTKJQYyHWQk18/
- OdWutH9D/rNOHSEbDLcvtkVdzwIhAPCSq17lUJHPxVL6hlvZTnL7uEFIQiSwE9wV
- Ysok+36W
- -----END CERTIFICATE-----
- `;
- const FIXTURE_KEY = `-----BEGIN PRIVATE KEY-----
- Dismissed after review: Contains what looks like a hardcoded PEM private key
- Line 67 on GitHub
- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrDGZowwCSq/kUaF7
- cx5EYmlJx7J/DwVs5lm2zDTD0L6hRANCAATSJhXCB+L/n24gFjaKKCN790yaz57H
- +tVd/VGGS4uRkZKa3j+6+qX4Q+Vn9huPUf1PK2VqW5Duk9G4NrXOqnHY
- -----END PRIVATE KEY-----
- `;
- const EXCHANGED_TOKEN = 'nanoclaw-test-exchanged-access-token';
- const DECOY_KEY = 'cursor_decoy_real_key_that_must_never_reach_the_wire';
- const PROBE_MODEL = 'nanoclaw-gateway-probe-model';
- const CURSOR_HOSTS = new Set(['api2.cursor.sh:443', 'api.cursor.com:443']);
- const SERVER_CONFIG_PATH = '/aiserver.v1.ServerConfigService/GetServerConfig';
- const PRIVACY_MODE_PATH = '/aiserver.v1.DashboardService/GetUserPrivacyMode';
- // aiserver.v1.GetServerConfigResponse field 7 `http2_config` (enum, varint):
- // tag 0x38, value 2 = HTTP2_CONFIG_FORCE_ALL_ENABLED.
- const FORCE_HTTP2_PROTO = new Uint8Array([0x38, 0x02]);
- const FORCE_HTTP2_JSON = { http2Config: 'HTTP2_CONFIG_FORCE_ALL_ENABLED' };
- const REFUSAL =
- /Cursor SDK attempted an HTTP\/2 connection to https:\/\/api2\.cursor\.sh(?::443)? that would bypass the configured proxy; refusing \(see \/add-cursor troubleshooting\)/;
- interface SeenRequest {
- method: string;
- host: string;
- path: string;
- authorization: string | null;
- contentLength: string | null;
- transferEncoding: string | null;
- }
- interface ProbeSummary {
- events: Array<Record<string, unknown>>;
- tlsDials: Array<{ host: string; port: string; alpn: unknown }>;
- http2EsmSnapshotStale: boolean;
- argv: string[];
- env: Record<string, string>;
- }
- /**
- * `refuse-rpcs`: every Connect RPC is 401 — the SDK re-exchanges once and then
- * fails closed, which ends the child quickly and shows the placeholder on a
- * second exchange. `force-http2`: the two RPCs the SDK makes before building
- * its agent transport succeed, and the server config forces HTTP/2.
- */
- let originMode: 'refuse-rpcs' | 'force-http2' = 'refuse-rpcs';
- const seenRequests: SeenRequest[] = [];
- const connectTargets: string[] = [];
- const nonConnectLines: string[] = [];
- // Remote port of every TCP connection the origin accepted, and the local port
- // of every upstream socket the proxy opened: a connection whose remote port
- // the proxy never used came from somewhere else.
- const originConnections: number[] = [];
- const proxyUpstreamPorts = new Set<number>();
- let origin: ReturnType<typeof Bun.serve>;
- let originFront: net.Server;
- let originFrontPort: number;
- let proxy: net.Server;
- let proxyPort: number;
- let tempRoot: string;
- let certPath: string;
- function directOriginConnections(): number[] {
- return originConnections.filter((port) => !proxyUpstreamPorts.has(port));
- }
- function connectResponse(request: Request, proto: Uint8Array, json: unknown): Response {
- const contentType = request.headers.get('content-type') ?? 'application/proto';
- if (contentType.includes('json')) return Response.json(json);
- return new Response(proto, { headers: { 'content-type': contentType } });
- }
- function startOriginFront(): Promise<number> {
- originFront = net.createServer((socket) => {
- originConnections.push(socket.remotePort ?? -1);
- const upstream = net.connect({ host: '127.0.0.1', port: origin.port! });
- socket.pipe(upstream);
- upstream.pipe(socket);
- upstream.on('error', () => socket.destroy());
- socket.on('error', () => upstream.destroy());
- });
- return new Promise((resolve) => {
- originFront.listen(0, '127.0.0.1', () => resolve((originFront.address() as net.AddressInfo).port));
- });
- }
- function startProxy(): Promise<number> {
- proxy = net.createServer((client) => {
- let head = '';
- const onData = (chunk: Buffer): void => {
- head += chunk.toString('latin1');
- const end = head.indexOf('\r\n\r\n');
- if (end === -1) return;
- client.off('data', onData);
- const requestLine = head.slice(0, head.indexOf('\r\n'));
- const match = /^CONNECT (\S+) HTTP\/1\.[01]$/.exec(requestLine);
- if (!match) {
- nonConnectLines.push(requestLine);
- client.end('HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n');
- return;
- }
- connectTargets.push(match[1]!);
- // Every tunnel lands on the fake origin, whatever host was asked for:
- // the proxy is the only thing that ever resolves Cursor's names here.
- const upstream = net.connect({ host: '127.0.0.1', port: originFrontPort }, () => {
- proxyUpstreamPorts.add(upstream.localPort!);
- client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
- const rest = head.slice(end + 4);
- if (rest) upstream.write(Buffer.from(rest, 'latin1'));
- client.pipe(upstream);
- upstream.pipe(client);
- });
- upstream.on('error', () => client.destroy());
- client.on('error', () => upstream.destroy());
- };
- client.on('data', onData);
- client.on('error', () => {});
- });
- return new Promise((resolve) => {
- proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
- });
- }
- beforeAll(async () => {
- tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cursor-gateway-proxy-'));
- certPath = path.join(tempRoot, 'gateway-ca.pem');
- fs.writeFileSync(certPath, FIXTURE_CERT);
- origin = Bun.serve({
- hostname: '127.0.0.1',
- port: 0,
- tls: { cert: FIXTURE_CERT, key: FIXTURE_KEY },
- fetch(request) {
- const url = new URL(request.url);
- seenRequests.push({
- method: request.method,
- host: request.headers.get('host') ?? url.host,
- path: url.pathname,
- authorization: request.headers.get('authorization'),
- contentLength: request.headers.get('content-length'),
- transferEncoding: request.headers.get('transfer-encoding'),
- });
- if (url.pathname === '/auth/exchange_user_api_key') {
- return Response.json({ accessToken: EXCHANGED_TOKEN });
- }
- if (url.pathname === '/v1/models') {
- // The SDK validates the requested model against this list before it
- // builds the agent transport; the probe's model must be on it.
- return Response.json({ items: [{ id: PROBE_MODEL }] });
- }
- if (originMode === 'force-http2') {
- if (url.pathname === PRIVACY_MODE_PATH) return connectResponse(request, new Uint8Array(), {});
- if (url.pathname === SERVER_CONFIG_PATH) return connectResponse(request, FORCE_HTTP2_PROTO, FORCE_HTTP2_JSON);
- }
- return Response.json({ code: 'unauthenticated', message: 'nanoclaw gateway probe' }, { status: 401 });
- },
- });
- originFrontPort = await startOriginFront();
- proxyPort = await startProxy();
- });
- beforeEach(() => {
- seenRequests.length = 0;
- connectTargets.length = 0;
- nonConnectLines.length = 0;
- originConnections.length = 0;
- proxyUpstreamPorts.clear();
- });
- afterAll(() => {
- proxy?.close();
- originFront?.close();
- origin?.stop(true);
- fs.rmSync(tempRoot, { recursive: true, force: true });
- });
- async function runProbe(): Promise<ProbeSummary> {
- const home = path.join(tempRoot, 'home');
- const agentDir = path.join(tempRoot, 'agent');
- fs.mkdirSync(home, { recursive: true });
- fs.mkdirSync(path.join(agentDir, 'memory', 'system'), { recursive: true });
- fs.writeFileSync(path.join(agentDir, 'memory', 'index.md'), '# probe\n');
- fs.writeFileSync(path.join(agentDir, 'memory', 'system', 'definition.md'), '# probe\n');
- const env: Record<string, string> = {};
- for (const [key, value] of Object.entries(process.env)) {
- if (value === undefined) continue;
- if (/^(https?_proxy|no_proxy|all_proxy|ssl_cert_file|node_extra_ca_certs|cursor_)/i.test(key)) continue;
- env[key] = value;
- }
- Object.assign(env, {
- HOME: home,
- NANOCLAW_AGENT_DIR: agentDir,
- NANOCLAW_CONVERSATIONS_DIR: path.join(agentDir, 'conversations'),
- // What the gateway contributes at spawn: proxy + CA bundle pointer.
- HTTPS_PROXY: `http://127.0.0.1:${proxyPort}`,
- SSL_CERT_FILE: certPath,
- // What the host adapter contributes is the placeholder; a decoy stands in
- // its place here so any code path that read the env instead of passing
- // the placeholder would show up on the wire.
- CURSOR_API_KEY: DECOY_KEY,
- });
- const runnerRoot = path.resolve(import.meta.dir, '..', '..');
- const child = Bun.spawn(['bun', path.join(import.meta.dir, 'cursor-gateway-probe.ts')], {
- cwd: runnerRoot,
- env,
- stdout: 'pipe',
- stderr: 'pipe',
- });
- const killer = setTimeout(() => child.kill(), 45_000);
- const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
- await child.exited;
- clearTimeout(killer);
- const line = stdout.trim().split('\n').at(-1) ?? '';
- try {
- return JSON.parse(line);
- } catch {
- throw new Error(`probe produced no summary\nstdout: ${stdout}\nstderr: ${stderr}`);
- }
- }
- function logWire(label: string, summary: ProbeSummary): void {
- // What crossed the wire, for the log: every tunnel target and every
- // request the fake origin saw (method, path, bearer, body framing).
- console.error(
- `[cursor-gateway-proxy:${label}] tunnels=${JSON.stringify(connectTargets)} requests=${JSON.stringify(
- seenRequests.map((request) => ({
- ...request,
- authorization: request.authorization?.replace(/Bearer (\S{6})\S*/, 'Bearer $1…') ?? null,
- })),
- )} events=${JSON.stringify(summary.events)} tlsDials=${JSON.stringify(summary.tlsDials)}`,
- );
- }
- /** The invariants that must hold on every run, whatever the origin answers. */
- function expectGatewayInvariants(summary: ProbeSummary): void {
- // The child ran with the decoy in its env and finished on its own.
- expect(summary.env.CURSOR_API_KEY).toBe(DECOY_KEY);
- expect(summary.events.some((event) => event.type === 'result' || event.type === 'thrown')).toBe(true);
- expect(summary.argv.some((arg) => arg.includes(DECOY_KEY) || arg.includes(CURSOR_API_KEY_PLACEHOLDER))).toBe(false);
- // Everything left the container through CONNECT tunnels to Cursor's hosts.
- expect(connectTargets.length).toBeGreaterThan(0);
- expect(connectTargets.filter((target) => !CURSOR_HOSTS.has(target))).toEqual([]);
- expect(nonConnectLines).toEqual([]);
- // The user-key exchange (global fetch) carried the placeholder, never the decoy.
- const exchanges = seenRequests.filter((request) => request.path === '/auth/exchange_user_api_key');
- expect(exchanges.length).toBeGreaterThan(0);
- for (const exchange of exchanges) {
- expect(exchange.method).toBe('POST');
- expect(exchange.host).toBe('api2.cursor.sh');
- expect(exchange.authorization).toBe(`Bearer ${CURSOR_API_KEY_PLACEHOLDER}`);
- }
- // The agent runtime's Connect RPCs (connect-node → node:https) rode the
- // same tunnel with the token the exchange returned.
- const rpcs = seenRequests.filter((request) => request.path.startsWith('/aiserver.v1.'));
- expect(rpcs.length).toBeGreaterThan(0);
- for (const rpc of rpcs) {
- expect(rpc.host).toBe('api2.cursor.sh');
- expect(rpc.authorization).toBe(`Bearer ${EXCHANGED_TOKEN}`);
- }
- // No request of any kind carried the decoy.
- for (const request of seenRequests) {
- expect(request.authorization ?? '').not.toContain(DECOY_KEY);
- }
- // Every connection the origin accepted came out of a proxy tunnel, and the
- // child never opened a TLS session of its own (an HTTP/2 dial would be one).
- expect(originConnections.length).toBeGreaterThan(0);
- expect(directOriginConnections()).toEqual([]);
- expect(summary.tlsDials).toEqual([]);
- }
- describe('Cursor traffic through the credential gateway proxy', () => {
- it('sends the key exchange and the agent RPCs through HTTPS_PROXY with only the placeholder', async () => {
- originMode = 'refuse-rpcs';
- const summary = await runProbe();
- logWire('http1', summary);
- expectGatewayInvariants(summary);
- }, 60_000);
- it('refuses the HTTP/2 transport when the server forces it, without a direct connection', async () => {
- originMode = 'force-http2';
- const summary = await runProbe();
- logWire('force-http2', summary);
- expectGatewayInvariants(summary);
- // The SDK asked for the server config through the tunnel and was told to
- // use HTTP/2 — the input that overrides the client's HTTP/1.1 pin.
- expect(seenRequests.some((request) => request.path === SERVER_CONFIG_PATH)).toBe(true);
- // The production condition held: the http2 ESM namespace predates the
- // guard, so the refusal below came from the TLS-level hook.
- expect(summary.http2EsmSnapshotStale).toBe(true);
- // The guard refused the HTTP/2 session with the documented error, and the
- // run failed closed on it rather than reaching Cursor directly.
- const texts = summary.events.flatMap((event) =>
- [event.message, event.text, event.error].filter((value): value is string => typeof value === 'string'),
- );
- expect(texts.some((text) => REFUSAL.test(text))).toBe(true);
- expect(summary.events.some((event) => event.type === 'result' && event.isError === true)).toBe(true);
- }, 60_000);
- });
- // ─── the guard on its own ───────────────────────────────────────────────
- // Port 1 on 127.0.0.1 has no listener, so a dial the guard permits fails
- // asynchronously with ECONNREFUSED — distinguishable from the guard's
- // synchronous refusal — and every permitted dial here stays on localhost.
- const PROXY_ENV = { HTTPS_PROXY: 'http://127.0.0.1:1' };
- const REFUSED = 'that would bypass the configured proxy; refusing (see /add-cursor troubleshooting)';
- let restore: (() => void) | null = null;
- afterEach(() => {
- restore?.();
- restore = null;
- });
- /** Swallow the asynchronous ECONNREFUSED of a permitted dial and close it. */
- function settle(dial: { on(event: 'error', handler: (err: Error) => void): unknown; destroy(): unknown }): void {
- dial.on('error', () => {});
- dial.destroy();
- }
- describe('installHttp2ProxyGuard (client-side refusal, in-process)', () => {
- it('installs nothing when no proxy is configured', () => {
- const before = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
- expect(installHttp2ProxyGuard({})).toBeNull();
- expect(installHttp2ProxyGuard({ NO_PROXY: '*', HTTP_PROXY: 'http://127.0.0.1:1' })).toBeNull();
- expect(http2.connect).toBe(before.http2);
- expect(tls.connect).toBe(before.tls);
- expect(https.Agent.prototype.createConnection).toBe(before.https);
- });
- it('refuses http2.connect to any origin but the proxy', () => {
- restore = installHttp2ProxyGuard(PROXY_ENV);
- expect(() => http2.connect('https://api2.cursor.sh')).toThrow(
- http2ProxyBypassError('https://api2.cursor.sh').message,
- );
- expect(() => http2.connect(new URL('https://api.cursor.com:8443/x'))).toThrow(
- `Cursor SDK attempted an HTTP/2 connection to https://api.cursor.com:8443/x ${REFUSED}`,
- );
- // The proxy itself is the one permitted destination.
- settle(http2.connect('http://127.0.0.1:1'));
- });
- it('refuses a TLS dial with ALPN h2 to any origin but the proxy and passes every other dial through', () => {
- restore = installHttp2ProxyGuard(PROXY_ENV);
- expect(() => tls.connect({ host: 'api2.cursor.sh', port: 443, ALPNProtocols: ['h2'] })).toThrow(
- `Cursor SDK attempted an HTTP/2 connection to https://api2.cursor.sh:443 ${REFUSED}`,
- );
- expect(() => tls.connect(443, 'api2.cursor.sh', { ALPNProtocols: ['h2'] })).toThrow(REFUSED);
- expect(() => tls.connect({ host: 'api2.cursor.sh', port: 443, ALPNProtocols: ['http/1.1', 'h2'] })).toThrow(
- REFUSED,
- );
- // Non-h2 TLS to the proxy itself is not a bypass.
- settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['http/1.1'] }));
- settle(tls.connect({ host: '127.0.0.1', port: 1 }));
- // An h2 dial to the proxy itself is permitted.
- settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] }));
- });
- it('honors NO_PROXY for hosts the operator excluded from the proxy', () => {
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'http://10.0.0.1:3128', NO_PROXY: '127.0.0.1,.example' });
- settle(http2.connect('https://127.0.0.1:1'));
- settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] }));
- expect(() => http2.connect('https://api2.cursor.sh')).toThrow(REFUSED);
- });
- it('honors a NO_PROXY port only for that port', () => {
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'http://10.0.0.1:3128', NO_PROXY: '127.0.0.1:1,[::1]:2' });
- settle(http2.connect('https://127.0.0.1:1'));
- expect(() => http2.connect('https://127.0.0.1:2')).toThrow(REFUSED);
- expect(() => tls.connect({ host: '127.0.0.1', port: 443, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
- settle(tls.connect({ host: '::1', port: 2, ALPNProtocols: ['h2'] }));
- expect(() => tls.connect({ host: '::1', port: 3, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
- });
- it('refuses every HTTP/2 dial when the proxy setting cannot be parsed', () => {
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'not a url' });
- expect(() => http2.connect('https://127.0.0.1:1')).toThrow(REFUSED);
- expect(() => tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
- });
- // Bun 1.3 has no https.Agent.createConnection; its node:https client already
- // honors HTTPS_PROXY, which the child-process cases cover. Bun 1.4's method
- // dials the origin, and this is the wrap that sends it through CONNECT.
- it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
- 'tunnels node:https through the proxy instead of dialing the origin',
- async () => {
- const connects: string[] = [];
- const proxy = net.createServer((client) => {
- let buf = '';
- const onData = (chunk: Buffer): void => {
- buf += chunk.toString('latin1');
- if (!buf.includes('\r\n\r\n')) return;
- client.off('data', onData);
- connects.push(buf.slice(0, buf.indexOf('\r\n')));
- client.end('HTTP/1.1 200 Connection Established\r\n\r\n');
- };
- client.on('data', onData);
- });
- const port = await new Promise<number>((resolve) => {
- proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
- });
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
- await new Promise<void>((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('timed out waiting for the proxy tunnel')), 5_000);
- const done = (): void => {
- clearTimeout(timer);
- resolve();
- };
- const req = https.get('https://api2.cursor.sh/v1/models');
- req.on('error', done);
- req.on('response', (res) => {
- res.resume();
- done();
- });
- });
- proxy.close();
- expect(connects).toEqual(['CONNECT api2.cursor.sh:443 HTTP/1.1']);
- },
- );
- it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
- 'sends Proxy-Authorization when the proxy URL carries userinfo',
- async () => {
- const headers: string[] = [];
- const proxy = net.createServer((client) => {
- let buf = '';
- const onData = (chunk: Buffer): void => {
- buf += chunk.toString('latin1');
- if (!buf.includes('\r\n\r\n')) return;
- client.off('data', onData);
- headers.push(buf.slice(0, buf.indexOf('\r\n\r\n')));
- client.end('HTTP/1.1 200 Connection Established\r\n\r\n');
- };
- client.on('data', onData);
- });
- const port = await new Promise<number>((resolve) => {
- proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
- });
- const request = (): Promise<void> =>
- new Promise((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('timed out waiting for the proxy tunnel')), 5_000);
- const done = (): void => {
- clearTimeout(timer);
- resolve();
- };
- const req = https.get('https://api2.cursor.sh/v1/models');
- req.on('error', done);
- req.on('response', (res) => {
- res.resume();
- done();
- });
- });
- const basic = (user: string, password: string): string =>
- `Proxy-Authorization: Basic ${Buffer.from(`${user}:${password}`, 'utf8').toString('base64')}`;
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://proxyuser:s3cret@127.0.0.1:${port}` });
- await request();
- restore();
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://proxyuser:p%40ss@127.0.0.1:${port}` });
- await request();
- restore();
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
- await request();
- proxy.close();
- expect(headers[0]).toContain('CONNECT api2.cursor.sh:443 HTTP/1.1');
- expect(headers[0]).toContain(basic('proxyuser', 's3cret'));
- expect(headers[1]).toContain(basic('proxyuser', 'p@ss'));
- expect(headers[2]).not.toContain('Proxy-Authorization');
- },
- );
- /** One https.get through the guard; resolves with its error, rejects on a response or a hang. */
- function failedRequest(): Promise<Error> {
- return new Promise((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('timed out: the tunnel never settled')), 5_000);
- const req = https.get('https://api2.cursor.sh/v1/models');
- req.on('error', (err) => {
- clearTimeout(timer);
- resolve(err);
- });
- req.on('response', (res) => {
- clearTimeout(timer);
- res.resume();
- reject(new Error('expected the tunnel to fail'));
- });
- });
- }
- async function listen(proxy: net.Server): Promise<number> {
- return new Promise((resolve) => {
- proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
- });
- }
- it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
- 'fails the request when the proxy hangs up before answering CONNECT',
- async () => {
- const proxy = net.createServer((client) => {
- client.once('data', () => client.end('HTTP/1.1 200'));
- });
- const port = await listen(proxy);
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
- const err = await failedRequest();
- proxy.close();
- expect(err.message).toContain('closed before answering CONNECT');
- },
- );
- it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
- 'refuses to send CONNECT and proxy credentials in the clear to an https:// proxy',
- async () => {
- const received: string[] = [];
- const proxy = net.createServer((client) => {
- client.on('data', (chunk: Buffer) => received.push(chunk.toString('latin1')));
- });
- const port = await listen(proxy);
- restore = installHttp2ProxyGuard({ HTTPS_PROXY: `https://proxyuser:s3cret@127.0.0.1:${port}` });
- const err = await failedRequest();
- proxy.close();
- expect(err.message).toContain('needs an http:// proxy');
- expect(received.join('')).toBe('');
- },
- );
- it('is idempotent and restores the originals', () => {
- const originals = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
- restore = installHttp2ProxyGuard(PROXY_ENV);
- const guarded = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
- expect(guarded.http2).not.toBe(originals.http2);
- expect(guarded.tls).not.toBe(originals.tls);
- if (typeof originals.https === 'function') expect(guarded.https).not.toBe(originals.https);
- const again = installHttp2ProxyGuard(PROXY_ENV);
- expect(http2.connect).toBe(guarded.http2);
- expect(tls.connect).toBe(guarded.tls);
- if (typeof originals.https === 'function') expect(https.Agent.prototype.createConnection).toBe(guarded.https);
- again?.();
- expect(http2.connect).toBe(guarded.http2);
- expect(tls.connect).toBe(guarded.tls);
- if (typeof originals.https === 'function') expect(https.Agent.prototype.createConnection).toBe(guarded.https);
- restore();
- restore = null;
- expect(http2.connect).toBe(originals.http2);
- expect(tls.connect).toBe(originals.tls);
- expect(https.Agent.prototype.createConnection).toBe(originals.https);
- });
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.