@weave-os/router 0.2.31 → 0.2.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,228 @@
1
+ #!/usr/bin/env node
2
+ // Local HTTPS proxy for Claude Desktop's Code tab and Cowork. Desktop forces
3
+ // ANTHROPIC_BASE_URL to Anthropic, but gives both the OS proxy (here, the PAC
4
+ // file served at /proxy.pac) and the OS certificate store. This proxy terminates
5
+ // TLS for api.anthropic.com only and sends Desktop's Messages API calls to the
6
+ // Weave Router with the router key added. Everything else, including other apps'
7
+ // api.anthropic.com traffic and every other host, passes through untouched.
8
+
9
+ "use strict";
10
+
11
+ const { execFile } = require("node:child_process");
12
+ const fs = require("node:fs");
13
+ const http = require("node:http");
14
+ const https = require("node:https");
15
+ const net = require("node:net");
16
+ const tls = require("node:tls");
17
+
18
+ const INTERCEPT_HOST = "api.anthropic.com";
19
+ const ROUTER_KEY_HEADER = "x-weave-router-key";
20
+ // Claude Code's user agent names its entrypoint: "claude-desktop" for the Code
21
+ // tab, "local-agent" for Cowork.
22
+ const DESKTOP_USER_AGENT = /[(,]\s*(claude-desktop|local-agent)(?![\w-])/;
23
+ const HOP_BY_HOP = new Set([
24
+ "connection",
25
+ "keep-alive",
26
+ "proxy-authenticate",
27
+ "proxy-authorization",
28
+ "proxy-connection",
29
+ "te",
30
+ "trailer",
31
+ "transfer-encoding",
32
+ "upgrade",
33
+ ]);
34
+
35
+ function loadConfig(file) {
36
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
37
+ for (const field of ["router_base_url", "cert_file", "key_file"]) {
38
+ if (typeof parsed[field] !== "string" || parsed[field] === "") {
39
+ throw new Error(`${file}: missing ${field}`);
40
+ }
41
+ }
42
+ return {
43
+ host: parsed.listen_host || "127.0.0.1",
44
+ port: Number(parsed.listen_port ?? 47821),
45
+ router: new URL(parsed.router_base_url),
46
+ routerKey: typeof parsed.router_key === "string" ? parsed.router_key : "",
47
+ anthropic: new URL(parsed.anthropic_origin || `https://${INTERCEPT_HOST}`),
48
+ cert: fs.readFileSync(parsed.cert_file),
49
+ key: fs.readFileSync(parsed.key_file),
50
+ };
51
+ }
52
+
53
+ function routesToRouter(req) {
54
+ const path = req.url;
55
+ const isMessages = path === "/v1/messages" || path.startsWith("/v1/messages/") || path.startsWith("/v1/messages?");
56
+ return isMessages && DESKTOP_USER_AGENT.test(req.headers["user-agent"] || "");
57
+ }
58
+
59
+ // Loopback is shared by every OS account and the proxy adds the installing
60
+ // user's router key, so it only serves that user's processes. peerUid finds
61
+ // the OS user owning the client end of a loopback connection.
62
+ function peerUid(socket, callback) {
63
+ // Match the whole 4-tuple: another user can reuse the owner's source port
64
+ // from a different loopback address such as 127.0.0.2.
65
+ if (process.platform === "linux") {
66
+ // /proc/net/tcp writes IPv4 endpoints as little-endian hex, e.g. 0100007F:B8CD.
67
+ const procEndpoint = (address, port) => {
68
+ const octets = address.replace(/^::ffff:/, "").split(".").reverse();
69
+ const ip = octets.map((octet) => Number(octet).toString(16).padStart(2, "0")).join("");
70
+ return `${ip}:${port.toString(16).padStart(4, "0")}`.toUpperCase();
71
+ };
72
+ const client = procEndpoint(socket.remoteAddress, socket.remotePort);
73
+ const proxy = procEndpoint(socket.localAddress, socket.localPort);
74
+ for (const row of fs.readFileSync("/proc/net/tcp", "utf8").split("\n").slice(1)) {
75
+ const [, local, remote, , , , , uid] = row.trim().split(/\s+/);
76
+ if (local === client && remote === proxy) return callback(Number(uid));
77
+ }
78
+ return callback(null);
79
+ }
80
+ // lsof without root lists only the caller's own processes, so another
81
+ // user's client is simply not found.
82
+ const connection = `n${socket.remoteAddress}:${socket.remotePort}->${socket.localAddress}:${socket.localPort}`;
83
+ execFile("lsof", ["-nP", "-a", `-iTCP:${socket.remotePort}`, "-sTCP:ESTABLISHED", "-Fun"], (_err, out = "") => {
84
+ let uid = null;
85
+ for (const line of out.split("\n")) {
86
+ if (line.startsWith("u")) uid = Number(line.slice(1));
87
+ if (line === connection) return callback(uid);
88
+ }
89
+ callback(null);
90
+ });
91
+ }
92
+
93
+ function pacFile(port) {
94
+ return `function FindProxyForURL(url, host) {
95
+ if (host === "${INTERCEPT_HOST}") return "PROXY 127.0.0.1:${port}";
96
+ return "DIRECT";
97
+ }
98
+ `;
99
+ }
100
+
101
+ function forward(cfg, req, res) {
102
+ const toRouter = routesToRouter(req);
103
+ const target = toRouter ? cfg.router : cfg.anthropic;
104
+ const headers = {};
105
+ for (const [name, value] of Object.entries(req.headers)) {
106
+ if (!HOP_BY_HOP.has(name) && name !== ROUTER_KEY_HEADER) headers[name] = value;
107
+ }
108
+ headers.host = target.host;
109
+ if (toRouter && cfg.routerKey) headers[ROUTER_KEY_HEADER] = cfg.routerKey;
110
+
111
+ const client = target.protocol === "http:" ? http : https;
112
+ const upstream = client.request(
113
+ {
114
+ protocol: target.protocol,
115
+ hostname: target.hostname,
116
+ port: target.port || (target.protocol === "http:" ? 80 : 443),
117
+ method: req.method,
118
+ path: target.pathname.replace(/\/+$/, "") + req.url,
119
+ headers,
120
+ },
121
+ (upstreamRes) => {
122
+ const out = {};
123
+ for (const [name, value] of Object.entries(upstreamRes.headers)) {
124
+ if (!HOP_BY_HOP.has(name)) out[name] = value;
125
+ }
126
+ res.writeHead(upstreamRes.statusCode, out);
127
+ res.flushHeaders();
128
+ // A body cut off mid-stream must reach Desktop as a broken response, not
129
+ // a connection that silently stays open.
130
+ upstreamRes.on("close", () => {
131
+ if (!upstreamRes.complete) res.destroy();
132
+ });
133
+ upstreamRes.pipe(res);
134
+ },
135
+ );
136
+ upstream.setNoDelay(true);
137
+ upstream.on("error", (err) => {
138
+ if (res.destroyed) return;
139
+ console.error(`${req.method} ${req.url} -> ${target.host}: ${err.message}`);
140
+ if (!res.headersSent) {
141
+ res.writeHead(502, { "content-type": "application/json" });
142
+ res.end(JSON.stringify({
143
+ type: "error",
144
+ error: { type: "api_error", message: `Weave Router desktop proxy could not reach ${target.host}: ${err.message}` },
145
+ }));
146
+ } else {
147
+ res.destroy(err);
148
+ }
149
+ });
150
+ // Desktop's Stop closes the response; stop the upstream generation with it.
151
+ res.on("close", () => {
152
+ if (!res.writableFinished) upstream.destroy();
153
+ });
154
+ req.pipe(upstream);
155
+ }
156
+
157
+ function start(cfg) {
158
+ const intercepted = http.createServer((req, res) => forward(cfg, req, res));
159
+ const secureContext = tls.createSecureContext({ cert: cfg.cert, key: cfg.key });
160
+
161
+ const proxy = http.createServer((req, res) => {
162
+ if (req.method === "GET" && req.url === "/proxy.pac") {
163
+ res.writeHead(200, { "content-type": "application/x-ns-proxy-autoconfig" });
164
+ res.end(pacFile(proxy.address().port));
165
+ return;
166
+ }
167
+ if (req.method === "GET" && req.url === "/health") {
168
+ res.writeHead(200, { "content-type": "text/plain" });
169
+ res.end("ok\n");
170
+ return;
171
+ }
172
+ res.writeHead(405, { "content-type": "text/plain" });
173
+ res.end("CONNECT only\n");
174
+ });
175
+
176
+ proxy.on("connect", (req, socket, head) => {
177
+ socket.on("error", () => socket.destroy());
178
+ peerUid(socket, (uid) => {
179
+ if (uid === process.getuid()) tunnel(req, socket, head);
180
+ else socket.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
181
+ });
182
+ });
183
+
184
+ function tunnel(req, socket, head) {
185
+ let target;
186
+ try {
187
+ target = new URL(`http://${req.url}`);
188
+ } catch {
189
+ socket.end("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n");
190
+ return;
191
+ }
192
+ const host = target.hostname.replace(/^\[|\]$/g, "");
193
+ if (host === INTERCEPT_HOST) {
194
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
195
+ if (head.length) socket.unshift(head);
196
+ const tlsSocket = new tls.TLSSocket(socket, { isServer: true, secureContext, ALPNProtocols: ["http/1.1"] });
197
+ tlsSocket.on("error", () => tlsSocket.destroy());
198
+ intercepted.emit("connection", tlsSocket);
199
+ return;
200
+ }
201
+ const upstream = net.connect(Number(target.port) || 443, host, () => {
202
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
203
+ if (head.length) upstream.write(head);
204
+ upstream.pipe(socket);
205
+ socket.pipe(upstream);
206
+ });
207
+ upstream.on("error", () => {
208
+ socket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
209
+ });
210
+ }
211
+
212
+ proxy.listen(cfg.port, cfg.host, () => {
213
+ const address = proxy.address();
214
+ console.log(`Weave Router desktop proxy listening on ${address.address}:${address.port}, router ${cfg.router.origin}`);
215
+ });
216
+ return proxy;
217
+ }
218
+
219
+ module.exports = { loadConfig, peerUid, routesToRouter, start };
220
+
221
+ if (require.main === module) {
222
+ const file = process.argv[2];
223
+ if (!file) {
224
+ console.error("usage: desktop-shim.js <config.json>");
225
+ process.exit(2);
226
+ }
227
+ start(loadConfig(file));
228
+ }
package/install.sh CHANGED
@@ -233,6 +233,7 @@ uninstall_cmd() {
233
233
  opencode) cmd="$cmd --opencode" ;;
234
234
  pi) cmd="$cmd --pi" ;;
235
235
  copilot) cmd="$cmd --copilot" ;;
236
+ claude-desktop) cmd="$cmd --claude-desktop" ;;
236
237
  esac
237
238
  [ "$scope" = "project" ] && cmd="$cmd --scope project"
238
239
  [ -n "$install_dir" ] && cmd="$cmd --dir $(printf '%q' "$install_dir")"
@@ -279,6 +280,7 @@ print_banner() {
279
280
  opencode) target_label="opencode installer" ;;
280
281
  pi) target_label="pi installer" ;;
281
282
  copilot) target_label="GitHub Copilot CLI installer" ;;
283
+ claude-desktop) target_label="Claude Desktop installer" ;;
282
284
  *) target_label="Claude Code installer" ;;
283
285
  esac
284
286
  printf '\n'
@@ -401,6 +403,7 @@ Set up
401
403
  $npx setup --claude --codex install for both (one key prompt)
402
404
  $npx --opencode | --pi install for opencode or pi
403
405
  $npx --copilot add Weave Router to Copilot CLI's /model picker
406
+ $npx --claude-desktop route Claude Desktop's Code tab (local proxy)
404
407
 
405
408
  Every day
406
409
  $npx status is each tool routed, signed in, working?
@@ -1780,6 +1783,9 @@ while [ $# -gt 0 ]; do
1780
1783
  lsp_langs="${2:-}"; shift 2
1781
1784
  [ -n "$lsp_langs" ] || { err "--lsp requires a comma-separated language list (go,typescript,python,rust)."; exit 2; }
1782
1785
  ;;
1786
+ --claude-desktop)
1787
+ target="claude-desktop"; target_explicit="true"; shift
1788
+ ;;
1783
1789
  --claude)
1784
1790
  # No-op selector for symmetry with --codex / --opencode. Useful in
1785
1791
  # pipelines that want to skip the interactive picker without depending
@@ -2018,6 +2024,16 @@ if [ "$target" = "copilot" ] && [ "$scope" = "project" ]; then
2018
2024
  err "--copilot installs in user scope only (Copilot CLI has no project-level providers.json). Drop --scope project, or use --dir for a throwaway COPILOT_HOME."
2019
2025
  exit 2
2020
2026
  fi
2027
+ # Claude Desktop is configured through a local proxy service, not a settings
2028
+ # file, so there is nothing to toggle or scope per repo.
2029
+ if [ "$target" = "claude-desktop" ] && [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
2030
+ err "Toggle verbs (off/on/status) aren't supported for --claude-desktop. Remove HTTPS_PROXY from Claude Desktop's local environment to go direct, or run 'npx $npm_package_name --uninstall --claude-desktop'."
2031
+ exit 2
2032
+ fi
2033
+ if [ "$target" = "claude-desktop" ] && [ "$scope" = "project" ]; then
2034
+ err "--claude-desktop installs in user scope only. Drop --scope project."
2035
+ exit 2
2036
+ fi
2021
2037
 
2022
2038
  if [ -z "$base_url" ]; then
2023
2039
  base_url="$DEFAULT_BASE_URL"
@@ -2071,7 +2087,7 @@ fi
2071
2087
  # they keep the user-scope default unless the caller explicitly selects a
2072
2088
  # project scope. Non-interactive installs (CI, `curl | sh --non-interactive`)
2073
2089
  # silently use the "user" default.
2074
- if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ "$target" != "copilot" ] && [ -r /dev/tty ]; then
2090
+ if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ "$target" != "copilot" ] && [ "$target" != "claude-desktop" ] && [ -r /dev/tty ]; then
2075
2091
  # Per-target paths so the prompt text matches what actually gets written.
2076
2092
  case "$target" in
2077
2093
  codex)
@@ -2162,7 +2178,7 @@ fi
2162
2178
  # payloads with jq regardless of which client's config supplied the endpoint,
2163
2179
  # so require it there too rather than dying mid-render on `jq: command not
2164
2180
  # found`. Installing Codex itself still needs no jq.
2165
- if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] || [ "$target" = "copilot" ] \
2181
+ if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] || [ "$target" = "copilot" ] || [ "$target" = "claude-desktop" ] \
2166
2182
  || { [ "$mode" = "models" ] && [ "$target" = "codex" ]; }; then
2167
2183
  ensure_jq
2168
2184
  fi
@@ -2205,6 +2221,10 @@ case "$target" in
2205
2221
  warn "Continuing — models.json/settings.json will be written and take effect once pi is installed."
2206
2222
  fi
2207
2223
  ;;
2224
+ claude-desktop)
2225
+ require_cmd node "the proxy runs on Node.js 18+: https://nodejs.org"
2226
+ require_cmd openssl "macOS: preinstalled; Linux: install openssl from your package manager"
2227
+ ;;
2208
2228
  copilot)
2209
2229
  if ! command -v copilot >/dev/null 2>&1; then
2210
2230
  warn "'copilot' not found on PATH. Install with 'npm install -g @github/copilot', then re-run this script."
@@ -2439,6 +2459,11 @@ if [ "$target" = "claude" ]; then
2439
2459
  if [ "$statusline_install" = "true" ]; then
2440
2460
  mkdir -p "$statusline_dir"
2441
2461
  fi
2462
+ elif [ "$target" = "claude-desktop" ]; then
2463
+ desktop_shim_dir="$settings_base/.weave-router/desktop-shim"
2464
+ desktop_shim_config="$desktop_shim_dir/config.json"
2465
+ mkdir -p "$desktop_shim_dir"
2466
+ chmod 700 "$desktop_shim_dir"
2442
2467
  elif [ "$target" = "codex" ]; then
2443
2468
  # Codex CLI reads config from ~/.codex/config.toml by default. For project
2444
2469
  # scope we write to <repo>/.codex/config.toml; the user invokes Codex with
@@ -2743,6 +2768,7 @@ read_installed_key() {
2743
2768
  opencode) read_opencode_key "$opencode_config_file" ;;
2744
2769
  pi) read_pi_key ;;
2745
2770
  copilot) read_copilot_key ;;
2771
+ claude-desktop) json_get "$desktop_shim_config" '.router_key' ;;
2746
2772
  esac
2747
2773
  }
2748
2774
 
@@ -2823,6 +2849,10 @@ resolve_installed_endpoint() {
2823
2849
  resolve_installed_base_url
2824
2850
  return 0
2825
2851
  ;;
2852
+ claude-desktop)
2853
+ json_get "$desktop_shim_config" '.router_base_url'
2854
+ return 0
2855
+ ;;
2826
2856
  codex)
2827
2857
  # Read base_url from the [model_providers.weave] table wherever it sits,
2828
2858
  # not only from between the managed markers. Codex drops our comment
@@ -4954,6 +4984,10 @@ rewrite_installed_key() {
4954
4984
  chmod 600 "$pi_key_file"
4955
4985
  ;;
4956
4986
  copilot) write_copilot_providers "$copilot_providers_file" "$base_url" "$key" "$user_email" "$user_name" ;;
4987
+ claude-desktop)
4988
+ write_desktop_shim_config "$key"
4989
+ start_desktop_shim_service
4990
+ ;;
4957
4991
  esac
4958
4992
  }
4959
4993
 
@@ -6199,6 +6233,288 @@ if [ "$target" = "codex" ]; then
6199
6233
  exit 0
6200
6234
  fi
6201
6235
 
6236
+ # ---------- Claude Desktop install path (dispatch + exit before the Claude-only writes) ----------
6237
+ #
6238
+ # Claude Desktop sets ANTHROPIC_BASE_URL to Anthropic for its Code tab and
6239
+ # Cowork sessions, so the settings.json route the CLI uses never reaches them.
6240
+ # Both do take the OS proxy and the OS certificate store. So this path:
6241
+ # 1. runs desktop-shim.js as a login service on 127.0.0.1,
6242
+ # 2. trusts a certificate that can only vouch for api.anthropic.com,
6243
+ # 3. points the OS auto-proxy at the shim's PAC file, which sends only
6244
+ # api.anthropic.com to the shim.
6245
+ # The shim sends Desktop's Messages API calls to the router and passes the rest
6246
+ # to Anthropic, so the user's Claude sign-in and subscription are untouched.
6247
+
6248
+ desktop_shim_service_name="weave-router-desktop-shim"
6249
+ desktop_shim_launchd_label="ai.workweave.router-desktop-shim"
6250
+
6251
+ desktop_shim_proxy_url() {
6252
+ printf 'http://127.0.0.1:%s' "$desktop_shim_port"
6253
+ }
6254
+
6255
+ desktop_shim_source() {
6256
+ local candidate
6257
+ [ -n "$script_dir" ] || return 1
6258
+ for candidate in "$script_dir/desktop-shim.js" "$script_dir/../desktop-shim.js"; do
6259
+ if [ -f "$candidate" ]; then
6260
+ printf '%s' "$candidate"
6261
+ return 0
6262
+ fi
6263
+ done
6264
+ return 1
6265
+ }
6266
+
6267
+ # write_desktop_shim_certs makes a CA that may only sign api.anthropic.com,
6268
+ # signs one leaf with it, then deletes the CA key so nothing else can ever be
6269
+ # minted from the CA that Claude Code is told to trust. Re-runs keep a still
6270
+ # valid pair, because Desktop's saved NODE_EXTRA_CA_CERTS points at ca.pem.
6271
+ write_desktop_shim_certs() {
6272
+ local dir="$desktop_shim_dir" tmp
6273
+ # An organization can hand every machine the same IT-made pair instead, and
6274
+ # trust that CA through its device management.
6275
+ if [ -n "${WEAVE_DESKTOP_CERT_DIR:-}" ]; then
6276
+ cp "$WEAVE_DESKTOP_CERT_DIR/ca.pem" "$WEAVE_DESKTOP_CERT_DIR/leaf.pem" "$dir/"
6277
+ (umask 077 && cp "$WEAVE_DESKTOP_CERT_DIR/leaf-key.pem" "$dir/leaf-key.pem")
6278
+ return 0
6279
+ fi
6280
+ if [ -f "$dir/ca.pem" ] && [ -f "$dir/leaf.pem" ] && [ -f "$dir/leaf-key.pem" ] \
6281
+ && openssl verify -CAfile "$dir/ca.pem" "$dir/leaf.pem" >/dev/null 2>&1 \
6282
+ && openssl x509 -checkend 2592000 -noout -in "$dir/leaf.pem" >/dev/null 2>&1; then
6283
+ return 0
6284
+ fi
6285
+ tmp="$(mktemp -d)"
6286
+ cat >"$tmp/ca.cnf" <<'CNF'
6287
+ [req]
6288
+ distinguished_name = dn
6289
+ prompt = no
6290
+ x509_extensions = v3_ca
6291
+ [dn]
6292
+ CN = Weave Router Claude Desktop proxy
6293
+ [v3_ca]
6294
+ basicConstraints = critical,CA:TRUE,pathlen:0
6295
+ keyUsage = critical,keyCertSign,cRLSign
6296
+ nameConstraints = critical,permitted;DNS:api.anthropic.com
6297
+ subjectKeyIdentifier = hash
6298
+ CNF
6299
+ cat >"$tmp/leaf.ext" <<'EXT'
6300
+ basicConstraints = critical,CA:FALSE
6301
+ keyUsage = critical,digitalSignature,keyEncipherment
6302
+ extendedKeyUsage = serverAuth
6303
+ subjectAltName = DNS:api.anthropic.com
6304
+ authorityKeyIdentifier = keyid
6305
+ EXT
6306
+ if ! {
6307
+ openssl req -x509 -newkey rsa:2048 -nodes -days 825 -config "$tmp/ca.cnf" \
6308
+ -keyout "$tmp/ca-key.pem" -out "$tmp/ca.pem" \
6309
+ && openssl req -newkey rsa:2048 -nodes -subj "/CN=api.anthropic.com" \
6310
+ -keyout "$tmp/leaf-key.pem" -out "$tmp/leaf.csr" \
6311
+ && openssl x509 -req -days 825 -in "$tmp/leaf.csr" -CA "$tmp/ca.pem" -CAkey "$tmp/ca-key.pem" \
6312
+ -set_serial "0x$(openssl rand -hex 16)" -extfile "$tmp/leaf.ext" -out "$tmp/leaf.pem"
6313
+ } >/dev/null 2>&1; then
6314
+ rm -rf "$tmp"
6315
+ err "openssl could not create the Claude Desktop proxy certificate."
6316
+ exit 1
6317
+ fi
6318
+ (umask 077 && cp "$tmp/leaf-key.pem" "$dir/leaf-key.pem")
6319
+ cp "$tmp/leaf.pem" "$dir/leaf.pem"
6320
+ cp "$tmp/ca.pem" "$dir/ca.pem"
6321
+ rm -rf "$tmp"
6322
+ ok "Created a local certificate for api.anthropic.com in $dir"
6323
+ }
6324
+
6325
+ write_desktop_shim_config() {
6326
+ local key="$1" tmp
6327
+ tmp="$(mktemp "$desktop_shim_dir/config.json.XXXXXX")"
6328
+ chmod 600 "$tmp"
6329
+ jq -n \
6330
+ --arg base "$base_url" \
6331
+ --arg key "$key" \
6332
+ --argjson port "$desktop_shim_port" \
6333
+ --arg cert "$desktop_shim_dir/leaf.pem" \
6334
+ --arg cert_key "$desktop_shim_dir/leaf-key.pem" \
6335
+ '{listen_host: "127.0.0.1", listen_port: $port, router_base_url: $base, router_key: $key, cert_file: $cert, key_file: $cert_key}' >"$tmp"
6336
+ mv "$tmp" "$desktop_shim_config"
6337
+ }
6338
+
6339
+ xml_escape() {
6340
+ printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
6341
+ }
6342
+
6343
+ start_desktop_shim_service() {
6344
+ local node_bin shim="$desktop_shim_dir/desktop-shim.js"
6345
+ node_bin="$(command -v node)"
6346
+ case "$(uname -s)" in
6347
+ Darwin)
6348
+ local plist="$HOME/Library/LaunchAgents/$desktop_shim_launchd_label.plist" uid
6349
+ local xml_node xml_shim xml_config xml_log
6350
+ uid="$(id -u)"
6351
+ xml_node="$(xml_escape "$node_bin")"
6352
+ xml_shim="$(xml_escape "$shim")"
6353
+ xml_config="$(xml_escape "$desktop_shim_config")"
6354
+ xml_log="$(xml_escape "$desktop_shim_dir/proxy.log")"
6355
+ mkdir -p "$(dirname "$plist")"
6356
+ cat >"$plist" <<PLIST
6357
+ <?xml version="1.0" encoding="UTF-8"?>
6358
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
6359
+ <plist version="1.0">
6360
+ <dict>
6361
+ <key>Label</key>
6362
+ <string>$desktop_shim_launchd_label</string>
6363
+ <key>ProgramArguments</key>
6364
+ <array>
6365
+ <string>$xml_node</string>
6366
+ <string>$xml_shim</string>
6367
+ <string>$xml_config</string>
6368
+ </array>
6369
+ <key>RunAtLoad</key>
6370
+ <true/>
6371
+ <key>KeepAlive</key>
6372
+ <true/>
6373
+ <key>StandardOutPath</key>
6374
+ <string>$xml_log</string>
6375
+ <key>StandardErrorPath</key>
6376
+ <string>$xml_log</string>
6377
+ </dict>
6378
+ </plist>
6379
+ PLIST
6380
+ launchctl bootout "gui/$uid/$desktop_shim_launchd_label" >/dev/null 2>&1 || true
6381
+ if ! launchctl bootstrap "gui/$uid" "$plist"; then
6382
+ err "launchctl could not start the Claude Desktop proxy from $plist."
6383
+ exit 1
6384
+ fi
6385
+ ok "Claude Desktop proxy runs at login (launchd $desktop_shim_launchd_label)"
6386
+ ;;
6387
+ Linux)
6388
+ local unit_dir="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" unit
6389
+ unit="$unit_dir/$desktop_shim_service_name.service"
6390
+ mkdir -p "$unit_dir"
6391
+ cat >"$unit" <<UNIT
6392
+ [Unit]
6393
+ Description=Weave Router proxy for Claude Desktop
6394
+
6395
+ [Service]
6396
+ ExecStart="$node_bin" "$shim" "$desktop_shim_config"
6397
+ Restart=always
6398
+ RestartSec=2
6399
+
6400
+ [Install]
6401
+ WantedBy=default.target
6402
+ UNIT
6403
+ if systemctl --user daemon-reload >/dev/null 2>&1 \
6404
+ && systemctl --user enable "$desktop_shim_service_name.service" >/dev/null 2>&1 \
6405
+ && systemctl --user restart "$desktop_shim_service_name.service" >/dev/null 2>&1; then
6406
+ ok "Claude Desktop proxy runs at login (systemd --user $desktop_shim_service_name)"
6407
+ else
6408
+ warn "systemctl --user could not start $unit. Start the proxy yourself: \"$node_bin\" \"$shim\" \"$desktop_shim_config\""
6409
+ fi
6410
+ ;;
6411
+ *)
6412
+ err "--claude-desktop supports macOS and Linux."
6413
+ exit 1
6414
+ ;;
6415
+ esac
6416
+ }
6417
+
6418
+ wait_for_desktop_shim() {
6419
+ local _
6420
+ for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
6421
+ curl -fsS --noproxy '*' --max-time 1 "$(desktop_shim_proxy_url)/health" >/dev/null 2>&1 && return 0
6422
+ sleep 0.25
6423
+ done
6424
+ return 1
6425
+ }
6426
+
6427
+ desktop_shim_ca_store="/usr/local/share/ca-certificates/weave-router-claude-desktop.crt"
6428
+
6429
+ trust_desktop_shim_ca() {
6430
+ case "$(uname -s)" in
6431
+ Darwin)
6432
+ if security verify-cert -c "$desktop_shim_dir/leaf.pem" -p ssl -s api.anthropic.com >/dev/null 2>&1; then
6433
+ return 0
6434
+ fi
6435
+ if [ "$non_interactive" = "true" ]; then
6436
+ warn "macOS shows a password dialog to trust the api.anthropic.com certificate, even with --non-interactive; the install waits for it. Push the CA with device management first to skip it (see install/README.md)."
6437
+ else
6438
+ info "macOS will ask for your password to trust the api.anthropic.com certificate."
6439
+ fi
6440
+ if ! security add-trusted-cert -r trustRoot -k "$HOME/Library/Keychains/login.keychain-db" "$desktop_shim_dir/ca.pem"; then
6441
+ err "Could not trust $desktop_shim_dir/ca.pem in your login keychain."
6442
+ exit 1
6443
+ fi
6444
+ ;;
6445
+ Linux)
6446
+ cmp -s "$desktop_shim_dir/ca.pem" "$desktop_shim_ca_store" && return 0
6447
+ info "sudo is needed to add the api.anthropic.com certificate to the system trust store."
6448
+ if ! { sudo install -m 644 "$desktop_shim_dir/ca.pem" "$desktop_shim_ca_store" && sudo update-ca-certificates >/dev/null; }; then
6449
+ err "Could not add $desktop_shim_dir/ca.pem to the system trust store."
6450
+ exit 1
6451
+ fi
6452
+ ;;
6453
+ esac
6454
+ ok "Trusted the proxy's api.anthropic.com certificate"
6455
+ }
6456
+
6457
+ # set_desktop_system_proxy leaves an auto-proxy someone else set alone: the PAC
6458
+ # rule to add to it is printed instead.
6459
+ set_desktop_system_proxy() {
6460
+ local pac rule service current
6461
+ pac="http://127.0.0.1:$desktop_shim_port/proxy.pac"
6462
+ rule="if (host === \"api.anthropic.com\") return \"PROXY 127.0.0.1:$desktop_shim_port\";"
6463
+ case "$(uname -s)" in
6464
+ Darwin)
6465
+ while IFS= read -r service; do
6466
+ current="$(networksetup -getautoproxyurl "$service" | sed -n 's/^URL: //p')"
6467
+ [ "$current" = "$pac" ] && continue
6468
+ if [ -n "$current" ] && [ "$current" != "(null)" ]; then
6469
+ warn "$service already uses the auto-proxy $current. Add this rule to it: $rule"
6470
+ continue
6471
+ fi
6472
+ sudo networksetup -setautoproxyurl "$service" "$pac"
6473
+ done < <(networksetup -listallnetworkservices | tail -n +2 | grep -v '^\*')
6474
+ ;;
6475
+ Linux)
6476
+ current="$(gsettings get org.gnome.system.proxy autoconfig-url)"
6477
+ if [ "$(gsettings get org.gnome.system.proxy mode)" != "'none'" ] && [ "$current" != "'$pac'" ]; then
6478
+ warn "A system proxy is already set. Add this rule to its PAC file: $rule"
6479
+ return 0
6480
+ fi
6481
+ gsettings set org.gnome.system.proxy autoconfig-url "$pac"
6482
+ gsettings set org.gnome.system.proxy mode 'auto'
6483
+ ;;
6484
+ esac
6485
+ ok "System auto-proxy sends api.anthropic.com to $(desktop_shim_proxy_url)"
6486
+ }
6487
+
6488
+ if [ "$target" = "claude-desktop" ]; then
6489
+ desktop_shim_port="${WEAVE_DESKTOP_SHIM_PORT:-$(json_get "$desktop_shim_config" '.listen_port')}"
6490
+ desktop_shim_port="${desktop_shim_port:-47821}"
6491
+ if ! desktop_shim_src="$(desktop_shim_source)"; then
6492
+ err "desktop-shim.js is missing next to the installer. Install with 'npx $npm_package_name --claude-desktop'."
6493
+ exit 1
6494
+ fi
6495
+ cp "$desktop_shim_src" "$desktop_shim_dir/desktop-shim.js"
6496
+ write_desktop_shim_certs
6497
+ write_desktop_shim_config "$api_key"
6498
+ ok "Proxy config written to $desktop_shim_config"
6499
+ start_desktop_shim_service
6500
+ if wait_for_desktop_shim; then
6501
+ ok "Claude Desktop proxy is listening on $(desktop_shim_proxy_url)"
6502
+ else
6503
+ warn "The Claude Desktop proxy isn't answering on $(desktop_shim_proxy_url) yet. Check $desktop_shim_dir/proxy.log (macOS) or 'journalctl --user -u $desktop_shim_service_name' (Linux)."
6504
+ fi
6505
+ trust_desktop_shim_ca
6506
+ set_desktop_system_proxy
6507
+
6508
+ verify_install
6509
+
6510
+ announce_done "Claude Desktop"
6511
+ if [ "$mode" = "install" ] && [ "$quiet" != "true" ]; then
6512
+ printf "\n%sNext:%s quit and reopen Claude Desktop. New Code sessions, and Cowork tasks that run on this computer, go through Weave Router; Cowork tasks running in Anthropic's cloud do not. You stay signed in to Claude.\n" "$C_BOLD" "$C_RESET"
6513
+ fi
6514
+ [ "$mode" = "update" ] || print_uninstall_hint
6515
+ exit 0
6516
+ fi
6517
+
6202
6518
  # ---------- copilot install path (dispatch + exit before the Claude-only writes) ----------
6203
6519
 
6204
6520
  if [ "$target" = "copilot" ]; then
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weave-os/router",
3
- "version": "0.2.31",
3
+ "version": "0.2.32",
4
4
  "description": "One-command installer that points Claude Code, Codex, opencode, or pi at the Weave Router. For pi it also ships the routing extension, loaded via pi.extensions.",
5
5
  "bin": {
6
6
  "weave-router": "bin.js",
@@ -19,6 +19,7 @@
19
19
  "windows.js",
20
20
  "install.sh",
21
21
  "uninstall.sh",
22
+ "desktop-shim.js",
22
23
  "cc-statusline.sh",
23
24
  "codex-status.sh",
24
25
  "codex-toggle.sh",
package/uninstall.sh CHANGED
@@ -263,6 +263,9 @@ while [ $# -gt 0 ]; do
263
263
  --copilot)
264
264
  target="copilot"; target_explicit="true"; shift
265
265
  ;;
266
+ --claude-desktop)
267
+ target="claude-desktop"; target_explicit="true"; shift
268
+ ;;
266
269
  --claude)
267
270
  # No-op selector for symmetry with --codex / --opencode and install.sh's
268
271
  # --claude. Lets `./install.sh --uninstall --claude` (which forwards
@@ -299,6 +302,7 @@ client_label() {
299
302
  claude) printf 'Claude Code' ;;
300
303
  codex) printf 'Codex' ;;
301
304
  copilot) printf 'Copilot CLI' ;;
305
+ claude-desktop) printf 'Claude Desktop' ;;
302
306
  *) printf '%s' "$1" ;;
303
307
  esac
304
308
  }
@@ -318,7 +322,7 @@ if [ "$target_explicit" = "false" ] && [ -z "${WEAVE_UNINSTALL_ALL_CHILD:-}" ] \
318
322
  fi
319
323
  removed=""
320
324
  failed=""
321
- for client in claude codex opencode pi copilot; do
325
+ for client in claude codex opencode pi copilot claude-desktop; do
322
326
  child_status=0
323
327
  WEAVE_UNINSTALL_ALL_CHILD=1 bash "$uninstall_self" "${uninstall_args[@]+"${uninstall_args[@]}"}" "--$client" || child_status=$?
324
328
  case "$child_status" in
@@ -330,7 +334,7 @@ if [ "$target_explicit" = "false" ] && [ -z "${WEAVE_UNINSTALL_ALL_CHILD:-}" ] \
330
334
  [ -z "$uninstall_self_tmp" ] || rm -f "$uninstall_self_tmp"
331
335
  printf '\n'
332
336
  if [ -z "$removed" ] && [ -z "$failed" ]; then
333
- info "Weave Router isn't configured for Claude Code, Codex, opencode, pi or Copilot CLI here (scope=$scope); nothing to remove."
337
+ info "Weave Router isn't configured for Claude Code, Codex, opencode, pi, Copilot CLI or Claude Desktop here (scope=$scope); nothing to remove."
334
338
  fi
335
339
  [ -z "$removed" ] || ok "Removed Weave Router from: $removed."
336
340
  if [ -n "$failed" ]; then
@@ -345,6 +349,77 @@ if [ -z "${WEAVE_UNINSTALL_ALL_CHILD:-}" ] && { [ "$target" = "claude" ] || [ "$
345
349
  exit 1
346
350
  fi
347
351
 
352
+ # Claude Desktop runs through a local proxy service (see install.sh); remove the
353
+ # service, its certificate and the stored router key.
354
+ if [ "$target" = "claude-desktop" ]; then
355
+ if [ "$scope" = "project" ]; then
356
+ [ -z "${WEAVE_UNINSTALL_ALL_CHILD:-}" ] || exit 3
357
+ err "--claude-desktop installs in user scope only; drop --scope project."
358
+ exit 2
359
+ fi
360
+ desktop_shim_dir="${install_dir:-$HOME}/.weave-router/desktop-shim"
361
+ desktop_shim_config="$desktop_shim_dir/config.json"
362
+ desktop_shim_plist="$HOME/Library/LaunchAgents/ai.workweave.router-desktop-shim.plist"
363
+ desktop_shim_unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/weave-router-desktop-shim.service"
364
+ skip_if_not_installed "$desktop_shim_config" 'router_base_url'
365
+ # The service files live under $HOME whatever --dir says; only remove the ones
366
+ # that run this install's config.
367
+ desktop_shim_config_xml="$(printf '%s' "$desktop_shim_config" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')"
368
+ if [ -f "$desktop_shim_plist" ] && grep -Fq "<string>$desktop_shim_config_xml</string>" "$desktop_shim_plist"; then
369
+ launchctl bootout "gui/$(id -u)/ai.workweave.router-desktop-shim" >/dev/null 2>&1 || true
370
+ rm -f "$desktop_shim_plist"
371
+ ok "Removed $desktop_shim_plist"
372
+ fi
373
+ if [ -f "$desktop_shim_unit" ] && grep -Fq "\"$desktop_shim_config\"" "$desktop_shim_unit"; then
374
+ systemctl --user disable --now weave-router-desktop-shim.service >/dev/null 2>&1 || true
375
+ rm -f "$desktop_shim_unit"
376
+ systemctl --user daemon-reload >/dev/null 2>&1 || true
377
+ ok "Removed $desktop_shim_unit"
378
+ fi
379
+ # Undo the trusted certificate and the auto-proxy, but only where they are this install's.
380
+ desktop_shim_pac="http://127.0.0.1:$(jq -r '.listen_port // 47821' "$desktop_shim_config" 2>/dev/null || echo 47821)/proxy.pac"
381
+ case "$(uname -s)" in
382
+ Darwin)
383
+ if [ -f "$desktop_shim_dir/ca.pem" ] \
384
+ && security find-certificate -c "Weave Router Claude Desktop proxy" "$HOME/Library/Keychains/login.keychain-db" >/dev/null 2>&1; then
385
+ if ! security remove-trusted-cert "$desktop_shim_dir/ca.pem" \
386
+ || ! security delete-certificate -Z "$(openssl x509 -noout -fingerprint -sha1 -in "$desktop_shim_dir/ca.pem" | sed 's/.*=//; s/://g')" \
387
+ "$HOME/Library/Keychains/login.keychain-db" >/dev/null; then
388
+ desktop_shim_ca_left="true"
389
+ fi
390
+ fi
391
+ while IFS= read -r service; do
392
+ if [ "$(networksetup -getautoproxyurl "$service" | sed -n 's/^URL: //p')" = "$desktop_shim_pac" ]; then
393
+ sudo networksetup -setautoproxystate "$service" off
394
+ fi
395
+ done < <(networksetup -listallnetworkservices | tail -n +2 | grep -v '^\*')
396
+ ;;
397
+ Linux)
398
+ desktop_shim_ca_store="/usr/local/share/ca-certificates/weave-router-claude-desktop.crt"
399
+ if [ -f "$desktop_shim_ca_store" ] && cmp -s "$desktop_shim_dir/ca.pem" "$desktop_shim_ca_store"; then
400
+ if ! { sudo rm -f "$desktop_shim_ca_store" && sudo update-ca-certificates --fresh >/dev/null; }; then
401
+ desktop_shim_ca_left="true"
402
+ fi
403
+ fi
404
+ if [ "$(gsettings get org.gnome.system.proxy autoconfig-url 2>/dev/null)" = "'$desktop_shim_pac'" ]; then
405
+ gsettings set org.gnome.system.proxy mode 'none'
406
+ gsettings reset org.gnome.system.proxy autoconfig-url
407
+ fi
408
+ ;;
409
+ esac
410
+ # Keep ca.pem and the config while the OS still trusts the CA, so a rerun can remove it.
411
+ if [ "${desktop_shim_ca_left:-}" = "true" ]; then
412
+ warn "Could not remove the proxy certificate from the OS trust store (a cancelled password prompt?). Rerun: npx @weave-os/router --uninstall --claude-desktop"
413
+ elif [ -d "$desktop_shim_dir" ]; then
414
+ refuse_if_symlink "$desktop_shim_dir"
415
+ rm -rf "$desktop_shim_dir"
416
+ rmdir "$(dirname "$desktop_shim_dir")" 2>/dev/null || true
417
+ ok "Removed $desktop_shim_dir"
418
+ fi
419
+ info "Quit and reopen Claude Desktop so new sessions go direct to Anthropic."
420
+ exit 0
421
+ fi
422
+
348
423
  # ---------- lifecycle report ----------
349
424
  #
350
425
  # report_uninstall_event tells this install's router that the uninstall is