Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nanocoai-nanoclaw/badge.svg)](/listings/nanocoai-nanoclaw)

HTML

<a href="/listings/nanocoai-nanoclaw"><img src="/api/listings/nanocoai-nanoclaw/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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.

  1. <p align="center">
  2. <img src="assets/nanoclaw-logo.png" alt="NanoClaw" width="400">
  3. </p>
  4. <p align="center">
  5. An AI assistant that runs agents securely in their own containers. Lightweight, built to be easily understood and completely customized for your needs.
  6. </p>
  7. <p align="center">
  8. <a href="https://nanoclaw.dev">nanoclaw.dev</a>&nbsp; • &nbsp;
  9. <a href="https://docs.nanoclaw.dev">docs</a>&nbsp; • &nbsp;
  10. <a href="README_zh.md">中文</a>&nbsp; • &nbsp;
  11. <a href="README_ja.md">日本語</a>&nbsp; • &nbsp;
  12. <a href="README_ko.md">한국어</a>&nbsp; • &nbsp;
  13. <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>&nbsp; • &nbsp;
  14. <a href="repo-tokens"><img src="repo-tokens/badge.svg" alt="repo tokens" valign="middle"></a>
  15. </p>
  16. ---
  17. <div align="center">
  18. ### <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">
  19. Setup provisions each agent its own Slack app: manifest, avatar, and workspace install, no tokens to paste.
  20. Spawn teammates from chat: every one gets its own bot identity, container, and memory, with shared rooms and canvases.
  21. [![Quick Start](https://img.shields.io/badge/Quick%20Start%20%E2%86%92-4A154B?style=for-the-badge)](#quick-start)
  22. </div>
  23. ---
  24. ## Why I Built NanoClaw
  25. [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.
  26. 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.
  27. ## Quick Start
  28. ```bash
  29. git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2
  30. cd nanoclaw-v2
  31. bash nanoclaw.sh
  32. ```
  33. `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.
  34. <details>
  35. <summary><strong>Migrating from NanoClaw v1?</strong></summary>
  36. Run from a fresh v2 checkout next to your v1 install:
  37. ```bash
  38. git clone https://github.com/nanocoai/nanoclaw.git nanoclaw-v2
  39. cd nanoclaw-v2
  40. bash migrate-v2.sh
  41. ```
  42. `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).
  43. 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.
  44. **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.
  45. **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.
  46. 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.
  47. </details>
  48. ## Philosophy
  49. **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.
  50. **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.
  51. **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.
  52. **Customization = code changes.** No configuration sprawl. Want different behavior? Modify the code. The codebase is small enough that it's safe to make changes.
  53. **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.
  54. **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.
  55. **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.
  56. ## What It Supports
  57. - **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.
  58. - **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).
  59. - **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.
  60. - **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
  61. - **Web access** — search and fetch content from the web
  62. - **Container isolation** — agents are sandboxed in Docker containers (macOS/Linux/WSL2)
  63. - **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.
  64. - **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).
  65. ## Accounts and what leaves your machine
  66. NanoClaw has no user accounts. The only thing it reports is anonymous setup diagnostics, and
  67. `NANOCLAW_NO_DIAGNOSTICS=1` turns those off. Your agents, messages, files and keys never leave
  68. your machine.
  69. One opt-in exception: you can [fetch a prebuilt agent image](docs/hardened-image.md) instead of
  70. building it locally. Fetching ours needs a free account, so we see your email address and when
  71. you ask for an image — nothing about your agents, and nothing after the image lands. Building
  72. locally needs no account and contacts nothing, and is the default. The same account unlocks the
  73. [perks](#perks) below.
  74. ## Perks
  75. The free account also opens the **community portal** at [portal.nanoclaw.dev](https://portal.nanoclaw.dev),
  76. a dashboard where you switch on what the account offers. Today that is Echo's hardened agent
  77. image and a managed Slack app for your agent, created and installed for you with no tokens to
  78. paste. Everything else in NanoClaw works without it.
  79. Setup opens the portal once. You sign in in the browser, approve the terminal you are running
  80. setup from, and enable the perk; the wizard notices and continues on its own. Enabling Echo is
  81. where you agree to Echo's terms, including whether you want product and security email. Close
  82. the page without enabling anything and setup carries on without the perk, then offers it once
  83. more later.
  84. What stays on your machine: the sign-in record and install token in `~/.config/nanoclaw/account.json`,
  85. one device key per machine in `~/.config/nanoclaw/device-key.json`, and this checkout's journal in
  86. `data/community-portal.json` (which perks are on, setup progress, the credentials a perk handed
  87. you), all mode `0600`. The install token never passes through the browser: the browser sees only
  88. the one-time sign-in code, and the token reaches this machine from the account service directly.
  89. The host keeps one outbound connection to the portal so a perk you change in the browser reaches
  90. the running agent; it sends nothing about your agents, messages or files.
  91. Revisit a step with `pnpm exec tsx setup/portal.ts --stage echo` or `--stage slack`. To sign a
  92. machine out, forget it under **Devices** in the portal: its token stops working and the host
  93. disconnects. Files, recovery commands and troubleshooting: [docs/community-portal.md](docs/community-portal.md).
  94. ## Usage
  95. Talk to your assistant with the trigger word (default: `@Andy`):
  96. ```
  97. @Andy send an overview of the sales pipeline every weekday morning at 9am (has access to my Obsidian vault folder)
  98. @Andy review the git history for the past week each Friday and update the README if there's drift
  99. @Andy every Monday at 8am, compile news on AI developments from Hacker News and TechCrunch and message me a briefing
  100. ```
  101. From a channel you own or administer, you can manage groups and tasks:
  102. ```
  103. @Andy list all scheduled tasks across groups
  104. @Andy pause the Monday briefing task
  105. @Andy join the Family Chat group
  106. ```
  107. ## Customizing
  108. NanoClaw doesn't use configuration files. To make changes, just tell Claude Code what you want:
  109. - "Change the trigger word to @Bob"
  110. - "Remember in the future to make responses shorter and more direct"
  111. - "Add a custom greeting when I say good morning"
  112. - "Store conversation summaries weekly"
  113. Or run `/customize` for guided changes.
  114. The codebase is small enough that Claude can safely modify it.
  115. ## Contributing
  116. **Don't add features. Add skills.**
  117. 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.
  118. 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.
  119. ### RFS (Request for Skills)
  120. No channel or provider skills are currently requested — propose one via an issue.
  121. ## Requirements
  122. - macOS or Linux (Windows via WSL2)
  123. - Node.js 22.23.4+, 24.22.1+ or 26.12.1+ and pnpm 10+ (the installer will install or update both if needed)
  124. - jq (the installer adds it if missing; channel skills use it)
  125. - [Docker Desktop](https://docker.com/products/docker-desktop) (macOS/Windows) or Docker Engine (Linux)
  126. - [Claude Code](https://claude.ai/download) for `/customize`, `/debug`, error recovery during setup, and all `/add-<channel>` skills
  127. ## Architecture
  128. ```
  129. messaging apps → host process (router) → inbound.db → container (Bun, Claude Agent SDK) → outbound.db → host process (delivery) → messaging apps
  130. ```
  131. 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.
  132. 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.
  133. 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).
  134. Key files:
  135. - `src/index.ts` — entry point: DB init, channel adapters, delivery polls, sweep
  136. - `src/router.ts` — inbound routing: messaging group → agent group → session → `inbound.db`
  137. - `src/delivery.ts` — polls `outbound.db`, delivers via adapter, handles system actions
  138. - `src/host-sweep.ts` — 60s sweep: stale detection, due-message wake, recurrence
  139. - `src/session-manager.ts` — resolves sessions, opens `inbound.db` / `outbound.db`
  140. - `src/container-runner.ts` — spawns per-agent-group containers, leases the session's gateway contribution
  141. - `src/db/` — central DB (users, roles, agent groups, messaging groups, wiring, migrations)
  142. - `src/channels/` — channel adapter infra (adapters installed via `/add-<channel>` skills)
  143. - `src/providers/` — host-side provider config (`claude` baked in; others via skills)
  144. - `container/agent-runner/` — Bun agent-runner: poll loop, MCP tools, provider abstraction
  145. - `groups/<folder>/` — per-agent-group filesystem (`CLAUDE.md`, skills, container config)
  146. ## FAQ
  147. **Why Docker?**
  148. Docker provides cross-platform support (macOS, Linux and Windows via WSL2) and a mature ecosystem.
  149. **Can I run this on Linux or Windows?**
  150. Yes. Docker is the default runtime and works on macOS, Linux, and Windows (via WSL2). Just run `bash nanoclaw.sh`.
  151. **Is this secure?**
  152. 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.
  153. **Why no configuration files?**
  154. 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.
  155. **Can I use third-party or open-source models?**
  156. 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.
  157. For one-off experiments, any Claude API-compatible endpoint also works via `.env`:
  158. ```bash
  159. ANTHROPIC_BASE_URL=https://your-api-endpoint.com
  160. ANTHROPIC_AUTH_TOKEN=your-token-here
  161. ```
  162. **How do I debug issues?**
  163. 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.
  164. **Why isn't the setup working for me?**
  165. 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.
  166. **How do I uninstall NanoClaw?**
  167. ```bash
  168. bash nanoclaw.sh --uninstall
  169. ```
  170. 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.
  171. **What changes will be accepted into the codebase?**
  172. Only security fixes, bug fixes, and clear improvements will be accepted to the base configuration. That's all.
  173. 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).
  174. This keeps the base system minimal and lets every user customize their installation without inheriting features they don't want.
  175. ## Community
  176. Questions? Ideas? [Join the Discord](https://discord.gg/VDdww8qS42).
  177. ## Changelog
  178. See [CHANGELOG.md](CHANGELOG.md) for breaking changes, or the [full release history](https://docs.nanoclaw.dev/changelog) on the documentation site.
  179. ## License
  180. MIT
  181. <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
  1. import { describe, expect, it, afterEach } from 'bun:test';
  2. import fs from 'fs';
  3. import os from 'os';
  4. import path from 'path';
  5. import {
  6. type AppServer,
  7. CODEX_APP_SERVER_ARGS,
  8. attachCodexAutoApproval,
  9. buildCodexConfigPlan,
  10. buildCodexProcessEnv,
  11. codexInferenceSection,
  12. renderCodexConfigToml,
  13. startOrResumeCodexThread,
  14. tomlBasicString,
  15. writeCodexConfigToml,
  16. } from './codex-app-server.js';
  17. import { CodexProvider } from './codex.js';
  18. const MEMORY_SESSION_HOOK = {
  19. command: 'bun /app/src/memory/hook.ts',
  20. legacyCommands: ['bun /app/src/memory-hook.ts'],
  21. sources: ['startup', 'clear', 'compact'],
  22. } as const;
  23. let tmpHome: string | null = null;
  24. const originalHome = process.env.HOME;
  25. afterEach(() => {
  26. process.env.HOME = originalHome;
  27. if (tmpHome) {
  28. fs.rmSync(tmpHome, { recursive: true, force: true });
  29. tmpHome = null;
  30. }
  31. });
  32. describe('Codex config TOML', () => {
  33. it('builds every declared configuration capability before rendering', () => {
  34. const mcpServers = { nanoclaw: { command: 'bun', args: ['run', 'server.ts'] } };
  35. const plan = buildCodexConfigPlan(mcpServers, { model: 'gpt-5', effort: 'medium', fastMode: true });
  36. expect(plan).toEqual({
  37. executionPolicy: {
  38. sandboxMode: 'danger-full-access',
  39. approvalPolicy: 'never',
  40. projectDocumentMaxBytes: 32768,
  41. },
  42. inference: { model: 'gpt-5', effort: 'medium', fastMode: true },
  43. memory: { memories: false, useMemories: false, generateMemories: false },
  44. mcpServers,
  45. });
  46. expect(renderCodexConfigToml(plan)).toContain('[mcp_servers.nanoclaw]');
  47. });
  48. it('renders the exact bytes, pinning line order and the trailing newline', () => {
  49. const content = renderCodexConfigToml(
  50. buildCodexConfigPlan(
  51. {
  52. nanoclaw: { command: 'bun', args: ['run', '/app/src/mcp-tools/index.ts'], env: { FOO: 'bar' } },
  53. docs: { type: 'http', url: 'https://mcp.example.com/mcp', headers: { 'X-Api-Version': '2024-06' } },
  54. },
  55. { model: 'gpt-5', effort: 'medium', fastMode: true },
  56. ),
  57. );
  58. expect(content).toBe(
  59. [
  60. 'sandbox_mode = "danger-full-access"',
  61. 'approval_policy = "never"',
  62. 'project_doc_max_bytes = 32768',
  63. 'mcp_optional_startup_grace_ms = 0',
  64. 'model = "gpt-5"',
  65. 'model_reasoning_effort = "medium"',
  66. 'service_tier = "fast"',
  67. '',
  68. '[features]',
  69. 'memories = false',
  70. '',
  71. '[memories]',
  72. 'use_memories = false',
  73. 'generate_memories = false',
  74. '',
  75. '[mcp_servers.nanoclaw]',
  76. 'required = true',
  77. 'command = "bun"',
  78. 'args = ["run", "/app/src/mcp-tools/index.ts"]',
  79. '[mcp_servers.nanoclaw.env]',
  80. 'FOO = "bar"',
  81. '',
  82. '[mcp_servers.docs]',
  83. 'url = "https://mcp.example.com/mcp"',
  84. '[mcp_servers.docs.http_headers]',
  85. '"X-Api-Version" = "2024-06"',
  86. '',
  87. ].join('\n'),
  88. );
  89. });
  90. // Core's speed property → Codex's service tier. `fast` is the only value
  91. // with a Codex rendering; `standard` (the core default) and anything else
  92. // emit no tier line, so Codex's own default serving tier stays in force.
  93. it('renders service_tier = "fast" only for speed fast', () => {
  94. const fast = renderCodexConfigToml({
  95. ...buildCodexConfigPlan({}, {}),
  96. inference: codexInferenceSection({ speed: 'fast' }),
  97. });
  98. expect(fast).toContain('service_tier = "fast"');
  99. // The tier is a plain top-level key: no feature flag rides along with it.
  100. expect(fast).not.toContain('fast_mode');
  101. const standard = renderCodexConfigToml({
  102. ...buildCodexConfigPlan({}, {}),
  103. inference: codexInferenceSection({ speed: 'standard' }),
  104. });
  105. expect(standard).not.toContain('service_tier');
  106. const unset = renderCodexConfigToml(buildCodexConfigPlan({}, {}));
  107. expect(unset).not.toContain('service_tier');
  108. });
  109. it('treats speed as a fast-or-default flag — other tier names are dropped, not passed through', () => {
  110. expect(codexInferenceSection({ speed: 'ultrafast' }).fastMode).toBeUndefined();
  111. const rendered = renderCodexConfigToml({
  112. ...buildCodexConfigPlan({}, {}),
  113. inference: codexInferenceSection({ speed: 'ultrafast' }),
  114. });
  115. expect(rendered).not.toContain('service_tier');
  116. expect(rendered).not.toContain('ultrafast');
  117. });
  118. it('escapes basic strings', () => {
  119. expect(tomlBasicString('a "quoted" \\\\ value')).toBe('"a \\"quoted\\" \\\\\\\\ value"');
  120. });
  121. it('escapes control characters TOML forbids raw', () => {
  122. expect(tomlBasicString('bell\u0007tab\tdel\u007f')).toBe('"bell\\u0007tab\\u0009del\\u007F"');
  123. });
  124. it('rejects newlines', () => {
  125. expect(() => tomlBasicString('bad\nvalue')).toThrow(/newline/);
  126. });
  127. it('hardcodes danger-full-access + never and writes model, effort, fast mode, and MCP servers', () => {
  128. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  129. process.env.HOME = tmpHome;
  130. writeCodexConfigToml(
  131. {
  132. nanoclaw: {
  133. command: 'bun',
  134. args: ['run', '/app/src/mcp-tools/index.ts'],
  135. env: { FOO: 'bar' },
  136. },
  137. docs: {
  138. type: 'http',
  139. url: 'https://mcp.example.com/mcp',
  140. headers: { 'X-Api-Version': '2024-06' },
  141. },
  142. },
  143. MEMORY_SESSION_HOOK,
  144. { model: 'gpt-5', effort: 'medium', fastMode: true },
  145. );
  146. const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
  147. expect(content).toContain('sandbox_mode = "danger-full-access"');
  148. expect(content).toContain('approval_policy = "never"');
  149. expect(content).toContain('project_doc_max_bytes = 32768');
  150. expect(content).toContain('model = "gpt-5"');
  151. expect(content).toContain('model_reasoning_effort = "medium"');
  152. expect(content).toContain('service_tier = "fast"');
  153. expect(content).toContain('[features]\nmemories = false');
  154. expect(content).toContain('[memories]\nuse_memories = false\ngenerate_memories = false');
  155. expect(content).not.toContain('[sandbox_workspace_write]');
  156. expect(content).not.toContain('writable_roots =');
  157. expect(content).toContain('[mcp_servers.nanoclaw]');
  158. expect(content).toContain('command = "bun"');
  159. expect(content).toContain('args = ["run", "/app/src/mcp-tools/index.ts"]');
  160. expect(content).toContain('[mcp_servers.nanoclaw.env]');
  161. expect(content).toContain('FOO = "bar"');
  162. expect(content).toContain(
  163. '[mcp_servers.docs]\nurl = "https://mcp.example.com/mcp"\n[mcp_servers.docs.http_headers]\n"X-Api-Version" = "2024-06"',
  164. );
  165. const hooks = JSON.parse(fs.readFileSync(path.join(tmpHome, '.codex', 'hooks.json'), 'utf-8'));
  166. expect(hooks.hooks.SessionStart).toEqual([
  167. {
  168. matcher: 'startup|clear|compact',
  169. hooks: [{ type: 'command', command: 'bun /app/src/memory/hook.ts', timeout: 10 }],
  170. },
  171. ]);
  172. expect(CODEX_APP_SERVER_ARGS).toContain('--dangerously-bypass-hook-trust');
  173. });
  174. it('emits cwd for a stdio server above the env sub-table, and omits it when absent', () => {
  175. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  176. process.env.HOME = tmpHome;
  177. writeCodexConfigToml(
  178. {
  179. probe: {
  180. command: '/workspace/agent/plugins/sdr/run.js',
  181. args: ['--flag'],
  182. env: { FOO: 'bar' },
  183. cwd: '/workspace/agent/plugin-data/sdr',
  184. },
  185. plain: { command: 'bun' },
  186. },
  187. MEMORY_SESSION_HOOK,
  188. );
  189. const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
  190. expect(content).toContain(
  191. 'command = "/workspace/agent/plugins/sdr/run.js"\n' +
  192. 'cwd = "/workspace/agent/plugin-data/sdr"\n' +
  193. 'args = ["--flag"]\n' +
  194. '[mcp_servers.probe.env]',
  195. );
  196. const plainTable = content.split('[mcp_servers.plain]')[1].split('[mcp_servers.')[0];
  197. expect(plainTable).toContain('command = "bun"');
  198. expect(plainTable).not.toContain('cwd =');
  199. });
  200. it('quotes non-bare server names and env keys so they cannot open new tables', () => {
  201. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  202. process.env.HOME = tmpHome;
  203. writeCodexConfigToml(
  204. {
  205. 'docs] [mcp_servers.evil]': {
  206. type: 'http',
  207. url: 'https://mcp.example.com/mcp',
  208. headers: { 'X-V': '1' },
  209. },
  210. plain: { command: 'bun', env: { 'BAD KEY': 'v' } },
  211. },
  212. MEMORY_SESSION_HOOK,
  213. );
  214. const content = fs.readFileSync(path.join(tmpHome, '.codex', 'config.toml'), 'utf-8');
  215. expect(content).toContain('[mcp_servers."docs] [mcp_servers.evil]"]');
  216. expect(content).toContain('[mcp_servers."docs] [mcp_servers.evil]".http_headers]');
  217. expect(content).not.toContain('\n[mcp_servers.evil]');
  218. expect(content).toContain('[mcp_servers.plain.env]');
  219. expect(content).toContain('"BAD KEY" = "v"');
  220. });
  221. it('fails closed on a server name containing a newline', () => {
  222. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  223. process.env.HOME = tmpHome;
  224. expect(() =>
  225. writeCodexConfigToml(
  226. { 'docs]\n[mcp_servers.evil]': { type: 'http', url: 'https://mcp.example.com/mcp' } },
  227. MEMORY_SESSION_HOOK,
  228. ),
  229. ).toThrow(/newline/);
  230. });
  231. it('preserves unrelated hooks and refreshes only the NanoClaw memory entry', () => {
  232. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  233. process.env.HOME = tmpHome;
  234. const hooksPath = path.join(tmpHome, '.codex', 'hooks.json');
  235. fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
  236. fs.writeFileSync(
  237. hooksPath,
  238. JSON.stringify({
  239. version: 1,
  240. hooks: {
  241. Stop: [{ hooks: [{ type: 'command', command: 'custom-stop' }] }],
  242. SessionStart: [
  243. { matcher: 'resume', hooks: [{ type: 'command', command: 'custom-resume' }] },
  244. {
  245. matcher: '.*',
  246. hooks: [
  247. { type: 'command', command: 'bun /app/src/memory-hook.ts' },
  248. { type: 'command', command: 'custom-start' },
  249. ],
  250. },
  251. ],
  252. },
  253. }),
  254. );
  255. writeCodexConfigToml({}, MEMORY_SESSION_HOOK);
  256. writeCodexConfigToml({}, MEMORY_SESSION_HOOK);
  257. const config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8'));
  258. expect(config.version).toBe(1);
  259. expect(config.hooks.Stop).toHaveLength(1);
  260. expect(config.hooks.SessionStart).toContainEqual({
  261. matcher: '.*',
  262. hooks: [{ type: 'command', command: 'custom-start' }],
  263. });
  264. expect(
  265. config.hooks.SessionStart.filter((entry: { hooks?: Array<{ command?: string }> }) =>
  266. entry.hooks?.some((hook) => hook.command === 'bun /app/src/memory/hook.ts'),
  267. ),
  268. ).toEqual([
  269. {
  270. matcher: 'startup|clear|compact',
  271. hooks: [{ type: 'command', command: 'bun /app/src/memory/hook.ts', timeout: 10 }],
  272. },
  273. ]);
  274. });
  275. it('replaces config.toml before malformed hooks.json fails', () => {
  276. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  277. process.env.HOME = tmpHome;
  278. const codexDir = path.join(tmpHome, '.codex');
  279. const configPath = path.join(codexDir, 'config.toml');
  280. const hooksPath = path.join(codexDir, 'hooks.json');
  281. fs.mkdirSync(codexDir, { recursive: true });
  282. fs.writeFileSync(configPath, 'stale config');
  283. fs.writeFileSync(hooksPath, '{');
  284. expect(() => writeCodexConfigToml({}, MEMORY_SESSION_HOOK, { model: 'gpt-5' })).toThrow();
  285. expect(fs.readFileSync(configPath, 'utf-8')).toContain('model = "gpt-5"');
  286. expect(fs.readFileSync(configPath, 'utf-8')).not.toContain('stale config');
  287. expect(fs.readFileSync(hooksPath, 'utf-8')).toBe('{');
  288. });
  289. it('replaces config.toml before an existing empty hooks.json fails', () => {
  290. tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-home-'));
  291. process.env.HOME = tmpHome;
  292. const codexDir = path.join(tmpHome, '.codex');
  293. const configPath = path.join(codexDir, 'config.toml');
  294. const hooksPath = path.join(codexDir, 'hooks.json');
  295. fs.mkdirSync(codexDir, { recursive: true });
  296. fs.writeFileSync(configPath, 'stale config');
  297. fs.writeFileSync(hooksPath, '');
  298. expect(() => writeCodexConfigToml({}, MEMORY_SESSION_HOOK, { model: 'gpt-5' })).toThrow();
  299. expect(fs.readFileSync(configPath, 'utf-8')).toContain('model = "gpt-5"');
  300. expect(fs.readFileSync(configPath, 'utf-8')).not.toContain('stale config');
  301. expect(fs.readFileSync(hooksPath, 'utf-8')).toBe('');
  302. });
  303. });
  304. describe('Codex thread SessionStart source', () => {
  305. it('sets startup only for a new thread', async () => {
  306. const { server, requests } = autoRespondingServer();
  307. await startOrResumeCodexThread(server, undefined, { cwd: '/workspace/agent' });
  308. expect(requests[0].method).toBe('thread/start');
  309. expect(requests[0].params.personality).toBe('friendly');
  310. expect(requests[0].params.config).toEqual({ bypass_hook_trust: true });
  311. expect(requests[0].params.sessionStartSource).toBe('startup');
  312. });
  313. it('does not send startup when resuming', async () => {
  314. const { server, requests } = autoRespondingServer();
  315. await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent', personality: 'pragmatic' });
  316. expect(requests[0].method).toBe('thread/resume');
  317. expect(requests[0].params.personality).toBe('pragmatic');
  318. expect(requests[0].params.config).toEqual({ bypass_hook_trust: true });
  319. expect(requests[0].params.sessionStartSource).toBeUndefined();
  320. });
  321. });
  322. // With the nanoclaw server required, Codex fails thread/start and thread/resume
  323. // when it cannot start. The resume failure must surface as an error, not be
  324. // read as a stale thread: that would start a new thread and silently drop the
  325. // conversation. Error strings are verbatim from codex 0.155.1, the pinned
  326. // version (0.146.0 words the failure without the repeated tail).
  327. describe('Codex thread resume failures', () => {
  328. const REQUIRED_MCP_FAILURE =
  329. 'error resuming thread: Fatal error: Failed to initialize session: required MCP servers failed to initialize: ' +
  330. 'nanoclaw: handshaking with MCP server failed: connection closed: initialize response: ' +
  331. 'connection closed: initialize response';
  332. const REQUIRED_MCP_TIMEOUT =
  333. 'error resuming thread: Fatal error: Failed to initialize session: required MCP servers failed to initialize: ' +
  334. 'nanoclaw: timed out handshaking with MCP server after 29.99999975s';
  335. const STALE_THREAD = 'no rollout found for thread id 01a0caf8-0000-7000-a000-000000000000';
  336. for (const [label, message] of [
  337. ['fails to start', REQUIRED_MCP_FAILURE],
  338. ['times out', REQUIRED_MCP_TIMEOUT],
  339. ] as const) {
  340. it(`keeps the thread when the required nanoclaw server ${label}`, async () => {
  341. const { server, requests } = autoRespondingServer({ 'thread/resume': message });
  342. const err = await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent' }).catch(
  343. (e: unknown) => e,
  344. );
  345. expect(err).toBeInstanceOf(Error);
  346. expect((err as Error).message).toBe(`thread/resume failed: ${message}`);
  347. expect(requests.map((r) => r.method)).toEqual(['thread/resume']);
  348. expect(new CodexProvider().isSessionInvalid(err)).toBe(false);
  349. });
  350. }
  351. it('still starts a fresh thread when the stored thread is gone', async () => {
  352. const { server, requests } = autoRespondingServer({ 'thread/resume': STALE_THREAD });
  353. const threadId = await startOrResumeCodexThread(server, 'thread-existing', { cwd: '/workspace/agent' });
  354. expect(requests.map((r) => r.method)).toEqual(['thread/resume', 'thread/start']);
  355. expect(threadId).toBe('thread-new');
  356. expect(new CodexProvider().isSessionInvalid(new Error(STALE_THREAD))).toBe(true);
  357. });
  358. });
  359. describe('Codex auto-approval', () => {
  360. // NanoClaw (container isolation + OneCLI) is the boundary, so the handler accepts
  361. // every request unconditionally — even paths/commands a sandbox policy would refuse.
  362. it('grants full filesystem + network for permission requests', () => {
  363. const { server, writes } = fakeServer();
  364. attachCodexAutoApproval(server);
  365. server.serverRequestHandlers[0]({
  366. id: 1,
  367. method: 'item/permissions/requestApproval',
  368. params: { permissions: { fileSystem: { read: ['/workspace/agent'], write: ['/workspace/agent'] } } },
  369. });
  370. const result = JSON.parse(writes[0]).result as {
  371. permissions: { fileSystem: { read: string[]; write: string[] }; network: { enabled: boolean } };
  372. scope: string;
  373. };
  374. expect(result.scope).toBe('turn');
  375. expect(result.permissions.fileSystem.read).toEqual(['/']);
  376. expect(result.permissions.fileSystem.write).toEqual(['/']);
  377. expect(result.permissions.network.enabled).toBe(true);
  378. });
  379. it('accepts file-change and command-exec approvals regardless of path', () => {
  380. const { server, writes } = fakeServer();
  381. attachCodexAutoApproval(server);
  382. server.serverRequestHandlers[0]({
  383. id: 2,
  384. method: 'item/fileChange/requestApproval',
  385. params: { grantRoot: '/etc' },
  386. });
  387. server.serverRequestHandlers[0]({
  388. id: 3,
  389. method: 'item/commandExecution/requestApproval',
  390. 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
  391. });
  392. expect(JSON.parse(writes[0]).result).toEqual({ decision: 'accept' });
  393. expect(JSON.parse(writes[1]).result).toEqual({ decision: 'accept' });
  394. });
  395. it('approves legacy patch and command-exec approvals regardless of path', () => {
  396. const { server, writes } = fakeServer();
  397. attachCodexAutoApproval(server);
  398. server.serverRequestHandlers[0]({
  399. id: 4,
  400. method: 'applyPatchApproval',
  401. params: { fileChanges: { '/etc/passwd': {} } },
  402. });
  403. server.serverRequestHandlers[0]({
  404. id: 5,
  405. method: 'execCommandApproval',
  406. 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
  407. });
  408. expect(JSON.parse(writes[0]).result).toEqual({ decision: 'approved' });
  409. expect(JSON.parse(writes[1]).result).toEqual({ decision: 'approved' });
  410. });
  411. it('fails closed for unknown server requests', () => {
  412. const { server, writes } = fakeServer();
  413. attachCodexAutoApproval(server);
  414. server.serverRequestHandlers[0]({ id: 6, method: 'new/unknown/request' });
  415. const response = JSON.parse(writes[0]);
  416. expect(response.error.message).toContain('Unhandled Codex app-server request');
  417. });
  418. });
  419. describe('Codex process env', () => {
  420. it('forwards proxy/runtime env without leaking secret-like host env', () => {
  421. const env = buildCodexProcessEnv({
  422. PATH: '/bin',
  423. HOME: '/home/node',
  424. CODEX_HOME: '/home/node/.codex',
  425. HTTPS_PROXY: 'http://proxy',
  426. OPENAI_API_KEY: 'sk-test',
  427. ONECLI_API_KEY: 'onecli-secret',
  428. SOME_TOKEN: 'token',
  429. });
  430. expect(env.PATH).toBe('/bin');
  431. expect(env.HOME).toBe('/home/node');
  432. expect(env.CODEX_HOME).toBe('/home/node/.codex');
  433. expect(env.HTTPS_PROXY).toBe('http://proxy');
  434. expect(env.OPENAI_API_KEY).toBeUndefined();
  435. expect(env.ONECLI_API_KEY).toBeUndefined();
  436. expect(env.SOME_TOKEN).toBeUndefined();
  437. });
  438. });
  439. function fakeServer(): { server: AppServer; writes: string[] } {
  440. const writes: string[] = [];
  441. const server = {
  442. process: { stdin: { write: (line: string) => writes.push(line) } },
  443. readline: { close: () => {} },
  444. pending: new Map(),
  445. notificationHandlers: [],
  446. exitHandlers: [],
  447. serverRequestHandlers: [],
  448. } as unknown as AppServer;
  449. return { server, writes };
  450. }
  451. function autoRespondingServer(errors: Record<string, string> = {}): {
  452. server: AppServer;
  453. requests: Array<{ id: number; method: string; params: Record<string, unknown> }>;
  454. } {
  455. const requests: Array<{ id: number; method: string; params: Record<string, unknown> }> = [];
  456. let server: AppServer;
  457. server = {
  458. process: {
  459. stdin: {
  460. write: (line: string) => {
  461. const request = JSON.parse(line) as { id: number; method: string; params: Record<string, unknown> };
  462. requests.push(request);
  463. const error = errors[request.method];
  464. if (error) {
  465. server.pending.get(request.id)?.resolve({ id: request.id, error: { code: -32603, message: error } });
  466. return;
  467. }
  468. const threadId = (request.params.threadId as string | undefined) ?? 'thread-new';
  469. server.pending.get(request.id)?.resolve({ id: request.id, result: { thread: { id: threadId } } });
  470. },
  471. },
  472. },
  473. readline: { close: () => {} },
  474. pending: new Map(),
  475. notificationHandlers: [],
  476. exitHandlers: [],
  477. serverRequestHandlers: [],
  478. } as unknown as AppServer;
  479. return { server, requests };
  480. }
.claude/skills/add-cursor/payload/container/agent-runner/src/providers/cursor.gateway-proxy.test.ts · Bundled script · 625 lines · 1 finding marked
  1. /**
  2. * Proves the Cursor provider's network paths reach the credential gateway.
  3. *
  4. * The container never holds the Cursor key: the host injects the placeholder
  5. * `CURSOR_API_KEY`, the SDK sends it as a bearer header, and the gateway proxy
  6. * (HTTPS_PROXY) swaps in the vaulted key on its routes. That only holds if
  7. * every request actually transits the proxy carrying the placeholder. This
  8. * test stands up a fake CONNECT proxy and a fake TLS origin on localhost,
  9. * spawns the real provider + real `@cursor/sdk` in a child whose env mirrors
  10. * the container (HTTPS_PROXY, the gateway CA via SSL_CERT_FILE, and a decoy
  11. * CURSOR_API_KEY that must never appear on the wire), and asserts:
  12. *
  13. * - the user-key exchange (global fetch) arrives through the proxy with the
  14. * placeholder bearer;
  15. * - the agent runtime's Connect RPCs (connect-node over HTTP/1.1, i.e.
  16. * node:https) arrive through the same proxy carrying the exchanged token;
  17. * - nothing carries the decoy key, and no CONNECT targets anything but
  18. * Cursor's two API hosts;
  19. * - every TCP connection the origin accepted came out of a proxy tunnel,
  20. * and the child opened no TLS session of its own.
  21. *
  22. * The second case has the fake origin answer `GetServerConfig` with
  23. * `http2Config: FORCE_ALL_ENABLED`, which is how Cursor's server overrides the
  24. * client's HTTP/1.1 pin. Under Bun `node:http2` ignores HTTPS_PROXY, so the
  25. * provider's guard (`installHttp2ProxyGuard` in providers/cursor.ts) must
  26. * refuse the session before it dials. The child loads the provider barrel
  27. * first, exactly as the agent-runner does, so the http2 ESM namespace already
  28. * exists when the guard installs — the case where only its TLS-level hook can
  29. * hold — and reports that condition back for the assertion. No network is used
  30. * here — the CONNECT tunnel terminates at the local fake origin, so DNS for
  31. * Cursor's hosts is never consulted; if the guard ever failed, the refusal
  32. * assertion fails first.
  33. *
  34. * The last block exercises the guard on its own, in-process: no-op without a
  35. * proxy, refusal of `http2.connect` and of any ALPN-h2 TLS dial to a non-proxy
  36. * origin, CONNECT tunnelling of `node:https`, NO_PROXY, idempotence, restore.
  37. */
  38. import fs from 'fs';
  39. import http2 from 'http2';
  40. import https from 'https';
  41. import net from 'net';
  42. import os from 'os';
  43. import path from 'path';
  44. import tls from 'tls';
  45. import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
  46. import { CURSOR_API_KEY_PLACEHOLDER, http2ProxyBypassError, installHttp2ProxyGuard } from './cursor.js';
  47. // Throwaway self-signed certificate for the fake origin, valid for
  48. // api2.cursor.sh / api.cursor.com / localhost until 2126. Test fixture only —
  49. // it is also the "gateway CA" the child trusts via SSL_CERT_FILE, the same
  50. // variable the gateway sets for its own bundle.
  51. const FIXTURE_CERT = `-----BEGIN CERTIFICATE-----
  52. MIIB4jCCAYegAwIBAgIUdQfCJX6l6nTbL+9ujNqBbDQswdEwCgYIKoZIzj0EAwIw
  53. JzElMCMGA1UEAwwcbmFub2NsYXctY3Vyc29yLWdhdGV3YXktdGVzdDAgFw0yNjA5
  54. MDMxMzI1NDhaGA8yMTI2MDgxMDEzMjU0OFowJzElMCMGA1UEAwwcbmFub2NsYXct
  55. Y3Vyc29yLWdhdGV3YXktdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNIm
  56. FcIH4v+fbiAWNoooI3v3TJrPnsf61V39UYZLi5GRkpreP7r6pfhD5Wf2G49R/U8r
  57. ZWpbkO6T0bg2tc6qcdijgY4wgYswOgYDVR0RBDMwMYIOYXBpMi5jdXJzb3Iuc2iC
  58. DmFwaS5jdXJzb3IuY29tgglsb2NhbGhvc3SHBH8AAAEwDAYDVR0TBAUwAwEB/zAL
  59. BgNVHQ8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFAdUNoI+
  60. 19cTO4TLXVIkzpZENEXlMAoGCCqGSM49BAMCA0kAMEYCIQD2xdyTKJQYyHWQk18/
  61. OdWutH9D/rNOHSEbDLcvtkVdzwIhAPCSq17lUJHPxVL6hlvZTnL7uEFIQiSwE9wV
  62. Ysok+36W
  63. -----END CERTIFICATE-----
  64. `;
  65. const FIXTURE_KEY = `-----BEGIN PRIVATE KEY-----
    • Dismissed after review: Contains what looks like a hardcoded PEM private key
    • Line 67 on GitHub
  66. MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrDGZowwCSq/kUaF7
  67. cx5EYmlJx7J/DwVs5lm2zDTD0L6hRANCAATSJhXCB+L/n24gFjaKKCN790yaz57H
  68. +tVd/VGGS4uRkZKa3j+6+qX4Q+Vn9huPUf1PK2VqW5Duk9G4NrXOqnHY
  69. -----END PRIVATE KEY-----
  70. `;
  71. const EXCHANGED_TOKEN = 'nanoclaw-test-exchanged-access-token';
  72. const DECOY_KEY = 'cursor_decoy_real_key_that_must_never_reach_the_wire';
  73. const PROBE_MODEL = 'nanoclaw-gateway-probe-model';
  74. const CURSOR_HOSTS = new Set(['api2.cursor.sh:443', 'api.cursor.com:443']);
  75. const SERVER_CONFIG_PATH = '/aiserver.v1.ServerConfigService/GetServerConfig';
  76. const PRIVACY_MODE_PATH = '/aiserver.v1.DashboardService/GetUserPrivacyMode';
  77. // aiserver.v1.GetServerConfigResponse field 7 `http2_config` (enum, varint):
  78. // tag 0x38, value 2 = HTTP2_CONFIG_FORCE_ALL_ENABLED.
  79. const FORCE_HTTP2_PROTO = new Uint8Array([0x38, 0x02]);
  80. const FORCE_HTTP2_JSON = { http2Config: 'HTTP2_CONFIG_FORCE_ALL_ENABLED' };
  81. const REFUSAL =
  82. /Cursor SDK attempted an HTTP\/2 connection to https:\/\/api2\.cursor\.sh(?::443)? that would bypass the configured proxy; refusing \(see \/add-cursor troubleshooting\)/;
  83. interface SeenRequest {
  84. method: string;
  85. host: string;
  86. path: string;
  87. authorization: string | null;
  88. contentLength: string | null;
  89. transferEncoding: string | null;
  90. }
  91. interface ProbeSummary {
  92. events: Array<Record<string, unknown>>;
  93. tlsDials: Array<{ host: string; port: string; alpn: unknown }>;
  94. http2EsmSnapshotStale: boolean;
  95. argv: string[];
  96. env: Record<string, string>;
  97. }
  98. /**
  99. * `refuse-rpcs`: every Connect RPC is 401 — the SDK re-exchanges once and then
  100. * fails closed, which ends the child quickly and shows the placeholder on a
  101. * second exchange. `force-http2`: the two RPCs the SDK makes before building
  102. * its agent transport succeed, and the server config forces HTTP/2.
  103. */
  104. let originMode: 'refuse-rpcs' | 'force-http2' = 'refuse-rpcs';
  105. const seenRequests: SeenRequest[] = [];
  106. const connectTargets: string[] = [];
  107. const nonConnectLines: string[] = [];
  108. // Remote port of every TCP connection the origin accepted, and the local port
  109. // of every upstream socket the proxy opened: a connection whose remote port
  110. // the proxy never used came from somewhere else.
  111. const originConnections: number[] = [];
  112. const proxyUpstreamPorts = new Set<number>();
  113. let origin: ReturnType<typeof Bun.serve>;
  114. let originFront: net.Server;
  115. let originFrontPort: number;
  116. let proxy: net.Server;
  117. let proxyPort: number;
  118. let tempRoot: string;
  119. let certPath: string;
  120. function directOriginConnections(): number[] {
  121. return originConnections.filter((port) => !proxyUpstreamPorts.has(port));
  122. }
  123. function connectResponse(request: Request, proto: Uint8Array, json: unknown): Response {
  124. const contentType = request.headers.get('content-type') ?? 'application/proto';
  125. if (contentType.includes('json')) return Response.json(json);
  126. return new Response(proto, { headers: { 'content-type': contentType } });
  127. }
  128. function startOriginFront(): Promise<number> {
  129. originFront = net.createServer((socket) => {
  130. originConnections.push(socket.remotePort ?? -1);
  131. const upstream = net.connect({ host: '127.0.0.1', port: origin.port! });
  132. socket.pipe(upstream);
  133. upstream.pipe(socket);
  134. upstream.on('error', () => socket.destroy());
  135. socket.on('error', () => upstream.destroy());
  136. });
  137. return new Promise((resolve) => {
  138. originFront.listen(0, '127.0.0.1', () => resolve((originFront.address() as net.AddressInfo).port));
  139. });
  140. }
  141. function startProxy(): Promise<number> {
  142. proxy = net.createServer((client) => {
  143. let head = '';
  144. const onData = (chunk: Buffer): void => {
  145. head += chunk.toString('latin1');
  146. const end = head.indexOf('\r\n\r\n');
  147. if (end === -1) return;
  148. client.off('data', onData);
  149. const requestLine = head.slice(0, head.indexOf('\r\n'));
  150. const match = /^CONNECT (\S+) HTTP\/1\.[01]$/.exec(requestLine);
  151. if (!match) {
  152. nonConnectLines.push(requestLine);
  153. client.end('HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n');
  154. return;
  155. }
  156. connectTargets.push(match[1]!);
  157. // Every tunnel lands on the fake origin, whatever host was asked for:
  158. // the proxy is the only thing that ever resolves Cursor's names here.
  159. const upstream = net.connect({ host: '127.0.0.1', port: originFrontPort }, () => {
  160. proxyUpstreamPorts.add(upstream.localPort!);
  161. client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
  162. const rest = head.slice(end + 4);
  163. if (rest) upstream.write(Buffer.from(rest, 'latin1'));
  164. client.pipe(upstream);
  165. upstream.pipe(client);
  166. });
  167. upstream.on('error', () => client.destroy());
  168. client.on('error', () => upstream.destroy());
  169. };
  170. client.on('data', onData);
  171. client.on('error', () => {});
  172. });
  173. return new Promise((resolve) => {
  174. proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
  175. });
  176. }
  177. beforeAll(async () => {
  178. tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cursor-gateway-proxy-'));
  179. certPath = path.join(tempRoot, 'gateway-ca.pem');
  180. fs.writeFileSync(certPath, FIXTURE_CERT);
  181. origin = Bun.serve({
  182. hostname: '127.0.0.1',
  183. port: 0,
  184. tls: { cert: FIXTURE_CERT, key: FIXTURE_KEY },
  185. fetch(request) {
  186. const url = new URL(request.url);
  187. seenRequests.push({
  188. method: request.method,
  189. host: request.headers.get('host') ?? url.host,
  190. path: url.pathname,
  191. authorization: request.headers.get('authorization'),
  192. contentLength: request.headers.get('content-length'),
  193. transferEncoding: request.headers.get('transfer-encoding'),
  194. });
  195. if (url.pathname === '/auth/exchange_user_api_key') {
  196. return Response.json({ accessToken: EXCHANGED_TOKEN });
  197. }
  198. if (url.pathname === '/v1/models') {
  199. // The SDK validates the requested model against this list before it
  200. // builds the agent transport; the probe's model must be on it.
  201. return Response.json({ items: [{ id: PROBE_MODEL }] });
  202. }
  203. if (originMode === 'force-http2') {
  204. if (url.pathname === PRIVACY_MODE_PATH) return connectResponse(request, new Uint8Array(), {});
  205. if (url.pathname === SERVER_CONFIG_PATH) return connectResponse(request, FORCE_HTTP2_PROTO, FORCE_HTTP2_JSON);
  206. }
  207. return Response.json({ code: 'unauthenticated', message: 'nanoclaw gateway probe' }, { status: 401 });
  208. },
  209. });
  210. originFrontPort = await startOriginFront();
  211. proxyPort = await startProxy();
  212. });
  213. beforeEach(() => {
  214. seenRequests.length = 0;
  215. connectTargets.length = 0;
  216. nonConnectLines.length = 0;
  217. originConnections.length = 0;
  218. proxyUpstreamPorts.clear();
  219. });
  220. afterAll(() => {
  221. proxy?.close();
  222. originFront?.close();
  223. origin?.stop(true);
  224. fs.rmSync(tempRoot, { recursive: true, force: true });
  225. });
  226. async function runProbe(): Promise<ProbeSummary> {
  227. const home = path.join(tempRoot, 'home');
  228. const agentDir = path.join(tempRoot, 'agent');
  229. fs.mkdirSync(home, { recursive: true });
  230. fs.mkdirSync(path.join(agentDir, 'memory', 'system'), { recursive: true });
  231. fs.writeFileSync(path.join(agentDir, 'memory', 'index.md'), '# probe\n');
  232. fs.writeFileSync(path.join(agentDir, 'memory', 'system', 'definition.md'), '# probe\n');
  233. const env: Record<string, string> = {};
  234. for (const [key, value] of Object.entries(process.env)) {
  235. if (value === undefined) continue;
  236. if (/^(https?_proxy|no_proxy|all_proxy|ssl_cert_file|node_extra_ca_certs|cursor_)/i.test(key)) continue;
  237. env[key] = value;
  238. }
  239. Object.assign(env, {
  240. HOME: home,
  241. NANOCLAW_AGENT_DIR: agentDir,
  242. NANOCLAW_CONVERSATIONS_DIR: path.join(agentDir, 'conversations'),
  243. // What the gateway contributes at spawn: proxy + CA bundle pointer.
  244. HTTPS_PROXY: `http://127.0.0.1:${proxyPort}`,
  245. SSL_CERT_FILE: certPath,
  246. // What the host adapter contributes is the placeholder; a decoy stands in
  247. // its place here so any code path that read the env instead of passing
  248. // the placeholder would show up on the wire.
  249. CURSOR_API_KEY: DECOY_KEY,
  250. });
  251. const runnerRoot = path.resolve(import.meta.dir, '..', '..');
  252. const child = Bun.spawn(['bun', path.join(import.meta.dir, 'cursor-gateway-probe.ts')], {
  253. cwd: runnerRoot,
  254. env,
  255. stdout: 'pipe',
  256. stderr: 'pipe',
  257. });
  258. const killer = setTimeout(() => child.kill(), 45_000);
  259. const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
  260. await child.exited;
  261. clearTimeout(killer);
  262. const line = stdout.trim().split('\n').at(-1) ?? '';
  263. try {
  264. return JSON.parse(line);
  265. } catch {
  266. throw new Error(`probe produced no summary\nstdout: ${stdout}\nstderr: ${stderr}`);
  267. }
  268. }
  269. function logWire(label: string, summary: ProbeSummary): void {
  270. // What crossed the wire, for the log: every tunnel target and every
  271. // request the fake origin saw (method, path, bearer, body framing).
  272. console.error(
  273. `[cursor-gateway-proxy:${label}] tunnels=${JSON.stringify(connectTargets)} requests=${JSON.stringify(
  274. seenRequests.map((request) => ({
  275. ...request,
  276. authorization: request.authorization?.replace(/Bearer (\S{6})\S*/, 'Bearer $1…') ?? null,
  277. })),
  278. )} events=${JSON.stringify(summary.events)} tlsDials=${JSON.stringify(summary.tlsDials)}`,
  279. );
  280. }
  281. /** The invariants that must hold on every run, whatever the origin answers. */
  282. function expectGatewayInvariants(summary: ProbeSummary): void {
  283. // The child ran with the decoy in its env and finished on its own.
  284. expect(summary.env.CURSOR_API_KEY).toBe(DECOY_KEY);
  285. expect(summary.events.some((event) => event.type === 'result' || event.type === 'thrown')).toBe(true);
  286. expect(summary.argv.some((arg) => arg.includes(DECOY_KEY) || arg.includes(CURSOR_API_KEY_PLACEHOLDER))).toBe(false);
  287. // Everything left the container through CONNECT tunnels to Cursor's hosts.
  288. expect(connectTargets.length).toBeGreaterThan(0);
  289. expect(connectTargets.filter((target) => !CURSOR_HOSTS.has(target))).toEqual([]);
  290. expect(nonConnectLines).toEqual([]);
  291. // The user-key exchange (global fetch) carried the placeholder, never the decoy.
  292. const exchanges = seenRequests.filter((request) => request.path === '/auth/exchange_user_api_key');
  293. expect(exchanges.length).toBeGreaterThan(0);
  294. for (const exchange of exchanges) {
  295. expect(exchange.method).toBe('POST');
  296. expect(exchange.host).toBe('api2.cursor.sh');
  297. expect(exchange.authorization).toBe(`Bearer ${CURSOR_API_KEY_PLACEHOLDER}`);
  298. }
  299. // The agent runtime's Connect RPCs (connect-node → node:https) rode the
  300. // same tunnel with the token the exchange returned.
  301. const rpcs = seenRequests.filter((request) => request.path.startsWith('/aiserver.v1.'));
  302. expect(rpcs.length).toBeGreaterThan(0);
  303. for (const rpc of rpcs) {
  304. expect(rpc.host).toBe('api2.cursor.sh');
  305. expect(rpc.authorization).toBe(`Bearer ${EXCHANGED_TOKEN}`);
  306. }
  307. // No request of any kind carried the decoy.
  308. for (const request of seenRequests) {
  309. expect(request.authorization ?? '').not.toContain(DECOY_KEY);
  310. }
  311. // Every connection the origin accepted came out of a proxy tunnel, and the
  312. // child never opened a TLS session of its own (an HTTP/2 dial would be one).
  313. expect(originConnections.length).toBeGreaterThan(0);
  314. expect(directOriginConnections()).toEqual([]);
  315. expect(summary.tlsDials).toEqual([]);
  316. }
  317. describe('Cursor traffic through the credential gateway proxy', () => {
  318. it('sends the key exchange and the agent RPCs through HTTPS_PROXY with only the placeholder', async () => {
  319. originMode = 'refuse-rpcs';
  320. const summary = await runProbe();
  321. logWire('http1', summary);
  322. expectGatewayInvariants(summary);
  323. }, 60_000);
  324. it('refuses the HTTP/2 transport when the server forces it, without a direct connection', async () => {
  325. originMode = 'force-http2';
  326. const summary = await runProbe();
  327. logWire('force-http2', summary);
  328. expectGatewayInvariants(summary);
  329. // The SDK asked for the server config through the tunnel and was told to
  330. // use HTTP/2 — the input that overrides the client's HTTP/1.1 pin.
  331. expect(seenRequests.some((request) => request.path === SERVER_CONFIG_PATH)).toBe(true);
  332. // The production condition held: the http2 ESM namespace predates the
  333. // guard, so the refusal below came from the TLS-level hook.
  334. expect(summary.http2EsmSnapshotStale).toBe(true);
  335. // The guard refused the HTTP/2 session with the documented error, and the
  336. // run failed closed on it rather than reaching Cursor directly.
  337. const texts = summary.events.flatMap((event) =>
  338. [event.message, event.text, event.error].filter((value): value is string => typeof value === 'string'),
  339. );
  340. expect(texts.some((text) => REFUSAL.test(text))).toBe(true);
  341. expect(summary.events.some((event) => event.type === 'result' && event.isError === true)).toBe(true);
  342. }, 60_000);
  343. });
  344. // ─── the guard on its own ───────────────────────────────────────────────
  345. // Port 1 on 127.0.0.1 has no listener, so a dial the guard permits fails
  346. // asynchronously with ECONNREFUSED — distinguishable from the guard's
  347. // synchronous refusal — and every permitted dial here stays on localhost.
  348. const PROXY_ENV = { HTTPS_PROXY: 'http://127.0.0.1:1' };
  349. const REFUSED = 'that would bypass the configured proxy; refusing (see /add-cursor troubleshooting)';
  350. let restore: (() => void) | null = null;
  351. afterEach(() => {
  352. restore?.();
  353. restore = null;
  354. });
  355. /** Swallow the asynchronous ECONNREFUSED of a permitted dial and close it. */
  356. function settle(dial: { on(event: 'error', handler: (err: Error) => void): unknown; destroy(): unknown }): void {
  357. dial.on('error', () => {});
  358. dial.destroy();
  359. }
  360. describe('installHttp2ProxyGuard (client-side refusal, in-process)', () => {
  361. it('installs nothing when no proxy is configured', () => {
  362. const before = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
  363. expect(installHttp2ProxyGuard({})).toBeNull();
  364. expect(installHttp2ProxyGuard({ NO_PROXY: '*', HTTP_PROXY: 'http://127.0.0.1:1' })).toBeNull();
  365. expect(http2.connect).toBe(before.http2);
  366. expect(tls.connect).toBe(before.tls);
  367. expect(https.Agent.prototype.createConnection).toBe(before.https);
  368. });
  369. it('refuses http2.connect to any origin but the proxy', () => {
  370. restore = installHttp2ProxyGuard(PROXY_ENV);
  371. expect(() => http2.connect('https://api2.cursor.sh')).toThrow(
  372. http2ProxyBypassError('https://api2.cursor.sh').message,
  373. );
  374. expect(() => http2.connect(new URL('https://api.cursor.com:8443/x'))).toThrow(
  375. `Cursor SDK attempted an HTTP/2 connection to https://api.cursor.com:8443/x ${REFUSED}`,
  376. );
  377. // The proxy itself is the one permitted destination.
  378. settle(http2.connect('http://127.0.0.1:1'));
  379. });
  380. it('refuses a TLS dial with ALPN h2 to any origin but the proxy and passes every other dial through', () => {
  381. restore = installHttp2ProxyGuard(PROXY_ENV);
  382. expect(() => tls.connect({ host: 'api2.cursor.sh', port: 443, ALPNProtocols: ['h2'] })).toThrow(
  383. `Cursor SDK attempted an HTTP/2 connection to https://api2.cursor.sh:443 ${REFUSED}`,
  384. );
  385. expect(() => tls.connect(443, 'api2.cursor.sh', { ALPNProtocols: ['h2'] })).toThrow(REFUSED);
  386. expect(() => tls.connect({ host: 'api2.cursor.sh', port: 443, ALPNProtocols: ['http/1.1', 'h2'] })).toThrow(
  387. REFUSED,
  388. );
  389. // Non-h2 TLS to the proxy itself is not a bypass.
  390. settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['http/1.1'] }));
  391. settle(tls.connect({ host: '127.0.0.1', port: 1 }));
  392. // An h2 dial to the proxy itself is permitted.
  393. settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] }));
  394. });
  395. it('honors NO_PROXY for hosts the operator excluded from the proxy', () => {
  396. restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'http://10.0.0.1:3128', NO_PROXY: '127.0.0.1,.example' });
  397. settle(http2.connect('https://127.0.0.1:1'));
  398. settle(tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] }));
  399. expect(() => http2.connect('https://api2.cursor.sh')).toThrow(REFUSED);
  400. });
  401. it('honors a NO_PROXY port only for that port', () => {
  402. restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'http://10.0.0.1:3128', NO_PROXY: '127.0.0.1:1,[::1]:2' });
  403. settle(http2.connect('https://127.0.0.1:1'));
  404. expect(() => http2.connect('https://127.0.0.1:2')).toThrow(REFUSED);
  405. expect(() => tls.connect({ host: '127.0.0.1', port: 443, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
  406. settle(tls.connect({ host: '::1', port: 2, ALPNProtocols: ['h2'] }));
  407. expect(() => tls.connect({ host: '::1', port: 3, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
  408. });
  409. it('refuses every HTTP/2 dial when the proxy setting cannot be parsed', () => {
  410. restore = installHttp2ProxyGuard({ HTTPS_PROXY: 'not a url' });
  411. expect(() => http2.connect('https://127.0.0.1:1')).toThrow(REFUSED);
  412. expect(() => tls.connect({ host: '127.0.0.1', port: 1, ALPNProtocols: ['h2'] })).toThrow(REFUSED);
  413. });
  414. // Bun 1.3 has no https.Agent.createConnection; its node:https client already
  415. // honors HTTPS_PROXY, which the child-process cases cover. Bun 1.4's method
  416. // dials the origin, and this is the wrap that sends it through CONNECT.
  417. it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
  418. 'tunnels node:https through the proxy instead of dialing the origin',
  419. async () => {
  420. const connects: string[] = [];
  421. const proxy = net.createServer((client) => {
  422. let buf = '';
  423. const onData = (chunk: Buffer): void => {
  424. buf += chunk.toString('latin1');
  425. if (!buf.includes('\r\n\r\n')) return;
  426. client.off('data', onData);
  427. connects.push(buf.slice(0, buf.indexOf('\r\n')));
  428. client.end('HTTP/1.1 200 Connection Established\r\n\r\n');
  429. };
  430. client.on('data', onData);
  431. });
  432. const port = await new Promise<number>((resolve) => {
  433. proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
  434. });
  435. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
  436. await new Promise<void>((resolve, reject) => {
  437. const timer = setTimeout(() => reject(new Error('timed out waiting for the proxy tunnel')), 5_000);
  438. const done = (): void => {
  439. clearTimeout(timer);
  440. resolve();
  441. };
  442. const req = https.get('https://api2.cursor.sh/v1/models');
  443. req.on('error', done);
  444. req.on('response', (res) => {
  445. res.resume();
  446. done();
  447. });
  448. });
  449. proxy.close();
  450. expect(connects).toEqual(['CONNECT api2.cursor.sh:443 HTTP/1.1']);
  451. },
  452. );
  453. it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
  454. 'sends Proxy-Authorization when the proxy URL carries userinfo',
  455. async () => {
  456. const headers: string[] = [];
  457. const proxy = net.createServer((client) => {
  458. let buf = '';
  459. const onData = (chunk: Buffer): void => {
  460. buf += chunk.toString('latin1');
  461. if (!buf.includes('\r\n\r\n')) return;
  462. client.off('data', onData);
  463. headers.push(buf.slice(0, buf.indexOf('\r\n\r\n')));
  464. client.end('HTTP/1.1 200 Connection Established\r\n\r\n');
  465. };
  466. client.on('data', onData);
  467. });
  468. const port = await new Promise<number>((resolve) => {
  469. proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
  470. });
  471. const request = (): Promise<void> =>
  472. new Promise((resolve, reject) => {
  473. const timer = setTimeout(() => reject(new Error('timed out waiting for the proxy tunnel')), 5_000);
  474. const done = (): void => {
  475. clearTimeout(timer);
  476. resolve();
  477. };
  478. const req = https.get('https://api2.cursor.sh/v1/models');
  479. req.on('error', done);
  480. req.on('response', (res) => {
  481. res.resume();
  482. done();
  483. });
  484. });
  485. const basic = (user: string, password: string): string =>
  486. `Proxy-Authorization: Basic ${Buffer.from(`${user}:${password}`, 'utf8').toString('base64')}`;
  487. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://proxyuser:s3cret@127.0.0.1:${port}` });
  488. await request();
  489. restore();
  490. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://proxyuser:p%40ss@127.0.0.1:${port}` });
  491. await request();
  492. restore();
  493. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
  494. await request();
  495. proxy.close();
  496. expect(headers[0]).toContain('CONNECT api2.cursor.sh:443 HTTP/1.1');
  497. expect(headers[0]).toContain(basic('proxyuser', 's3cret'));
  498. expect(headers[1]).toContain(basic('proxyuser', 'p@ss'));
  499. expect(headers[2]).not.toContain('Proxy-Authorization');
  500. },
  501. );
  502. /** One https.get through the guard; resolves with its error, rejects on a response or a hang. */
  503. function failedRequest(): Promise<Error> {
  504. return new Promise((resolve, reject) => {
  505. const timer = setTimeout(() => reject(new Error('timed out: the tunnel never settled')), 5_000);
  506. const req = https.get('https://api2.cursor.sh/v1/models');
  507. req.on('error', (err) => {
  508. clearTimeout(timer);
  509. resolve(err);
  510. });
  511. req.on('response', (res) => {
  512. clearTimeout(timer);
  513. res.resume();
  514. reject(new Error('expected the tunnel to fail'));
  515. });
  516. });
  517. }
  518. async function listen(proxy: net.Server): Promise<number> {
  519. return new Promise((resolve) => {
  520. proxy.listen(0, '127.0.0.1', () => resolve((proxy.address() as net.AddressInfo).port));
  521. });
  522. }
  523. it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
  524. 'fails the request when the proxy hangs up before answering CONNECT',
  525. async () => {
  526. const proxy = net.createServer((client) => {
  527. client.once('data', () => client.end('HTTP/1.1 200'));
  528. });
  529. const port = await listen(proxy);
  530. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `http://127.0.0.1:${port}` });
  531. const err = await failedRequest();
  532. proxy.close();
  533. expect(err.message).toContain('closed before answering CONNECT');
  534. },
  535. );
  536. it.skipIf(typeof https.Agent.prototype.createConnection !== 'function')(
  537. 'refuses to send CONNECT and proxy credentials in the clear to an https:// proxy',
  538. async () => {
  539. const received: string[] = [];
  540. const proxy = net.createServer((client) => {
  541. client.on('data', (chunk: Buffer) => received.push(chunk.toString('latin1')));
  542. });
  543. const port = await listen(proxy);
  544. restore = installHttp2ProxyGuard({ HTTPS_PROXY: `https://proxyuser:s3cret@127.0.0.1:${port}` });
  545. const err = await failedRequest();
  546. proxy.close();
  547. expect(err.message).toContain('needs an http:// proxy');
  548. expect(received.join('')).toBe('');
  549. },
  550. );
  551. it('is idempotent and restores the originals', () => {
  552. const originals = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
  553. restore = installHttp2ProxyGuard(PROXY_ENV);
  554. const guarded = { http2: http2.connect, tls: tls.connect, https: https.Agent.prototype.createConnection };
  555. expect(guarded.http2).not.toBe(originals.http2);
  556. expect(guarded.tls).not.toBe(originals.tls);
  557. if (typeof originals.https === 'function') expect(guarded.https).not.toBe(originals.https);
  558. const again = installHttp2ProxyGuard(PROXY_ENV);
  559. expect(http2.connect).toBe(guarded.http2);
  560. expect(tls.connect).toBe(guarded.tls);
  561. if (typeof originals.https === 'function') expect(https.Agent.prototype.createConnection).toBe(guarded.https);
  562. again?.();
  563. expect(http2.connect).toBe(guarded.http2);
  564. expect(tls.connect).toBe(guarded.tls);
  565. if (typeof originals.https === 'function') expect(https.Agent.prototype.createConnection).toBe(guarded.https);
  566. restore();
  567. restore = null;
  568. expect(http2.connect).toBe(originals.http2);
  569. expect(tls.connect).toBe(originals.tls);
  570. expect(https.Agent.prototype.createConnection).toBe(originals.https);
  571. });
  572. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.