-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
193 lines (169 loc) · 7.32 KB
/
cli.ts
File metadata and controls
193 lines (169 loc) · 7.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env bun
import { startProxy } from "./src/proxy/server";
const AMBER = "\x1b[33m";
const DIM = "\x1b[2m";
const RED = "\x1b[31m";
const YLW = "\x1b[33m";
const RESET = "\x1b[0m";
async function buildClientBundle(): Promise<void> {
const outDir = import.meta.dir + "/public";
const outFile = outDir + "/devproxy-client.js";
try {
const result = await Bun.build({
entrypoints: [import.meta.dir + "/client/index.ts"],
outdir: outDir,
naming: { entry: "devproxy-client.js", chunk: "[name]-[hash].js" },
target: "browser",
minify: false,
});
if (!result.success) {
process.stderr.write(` ${RED}Client bundle failed:${RESET}\n`);
for (const log of result.logs) {
const loc = log.position ? ` (${log.position.file}:${log.position.line})` : "";
process.stderr.write(` ${log.level}: ${log.message}${loc}\n`);
}
} else {
process.stdout.write(` ${DIM}Client bundle → ${outFile}${RESET}\n`);
}
} catch (err: any) {
process.stderr.write(` ${RED}Bundle failed:${RESET} ${err?.message ?? err}\n`);
if (err?.errors?.length) {
for (const e of err.errors) process.stderr.write(` ${e.text ?? e.message}\n`);
}
}
}
function isLocalHost(hostname: string): boolean {
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "0.0.0.0") return true;
if (/^127\.\d+\.\d+\.\d+$/.test(hostname)) return true;
if (hostname.endsWith(".local")) return true;
return false;
}
async function runProxy(remainingArgs: string[]): Promise<void> {
let targetArg: string | undefined;
let proxyPort = 4000;
let appDir: string | undefined;
let expose = false;
let allowHttps = false;
let noConsole = true; // console capture is opt-in via --console
let captureBodies = false;
let spawnCmd: string | undefined;
for (let i = 0; i < remainingArgs.length; i++) {
if (remainingArgs[i] === "--target" && i + 1 < remainingArgs.length) {
targetArg = remainingArgs[++i];
} else if (remainingArgs[i] === "--port" && i + 1 < remainingArgs.length) {
proxyPort = parseInt(remainingArgs[++i], 10) || 4000;
} else if (remainingArgs[i] === "--app-dir" && i + 1 < remainingArgs.length) {
appDir = remainingArgs[++i];
} else if (remainingArgs[i] === "--expose") {
expose = true;
} else if (remainingArgs[i] === "--allow-https") {
allowHttps = true;
} else if (remainingArgs[i] === "--console") {
noConsole = false;
} else if (remainingArgs[i] === "--bodies") {
captureBodies = true;
} else if (remainingArgs[i] === "--no-console") {
noConsole = true; // kept for backwards compat, now a no-op (it's the default)
} else if (remainingArgs[i] === "--spawn" && i + 1 < remainingArgs.length) {
spawnCmd = remainingArgs[++i];
} else if (!remainingArgs[i].startsWith("-")) {
targetArg = remainingArgs[i];
}
}
const target = targetArg ?? "localhost:3001";
// Safety checks
if (/^https:\/\//i.test(target)) {
if (!allowHttps) {
process.stderr.write(`\n ${RED}Error:${RESET} target "${target}" uses HTTPS, which suggests a remote/production server.\n`);
process.stderr.write(` Pass ${AMBER}--allow-https${RESET} to override (e.g. a local HTTPS dev server).\n\n`);
process.exit(1);
}
}
const targetHostname = target.replace(/^https?:\/\//, "").split(":")[0].split("/")[0];
if (!isLocalHost(targetHostname)) {
process.stderr.write(`\n ${RED}Error:${RESET} target hostname "${targetHostname}" is not local.\n`);
process.stderr.write(` zeta-1 only proxies local dev servers.\n\n`);
process.exit(1);
}
const wsToken = crypto.randomUUID();
if (expose) {
process.stderr.write(`\n ${YLW}Warning:${RESET} --expose binds the proxy to 0.0.0.0. Do not use on untrusted networks.\n`);
}
// Write .mcp.json so Claude Code picks up the session token automatically.
// Uses absolute paths so the file works regardless of where `claude` is invoked from.
{
const mcpJsonPath = process.cwd() + "/.mcp.json";
const mcpServerPath = import.meta.dir + "/src/mcp/server.ts";
const wsUrl = `ws://localhost:${proxyPort}/__devproxy/ws`;
let existing: any = {};
try { existing = JSON.parse(await Bun.file(mcpJsonPath).text()); } catch { /* new file */ }
const prevArgs: string[] = existing?.mcpServers?.zeta1?.args ?? ["run", mcpServerPath];
// Strip stale --ws and --token entries, then append fresh ones
const stripped = prevArgs.filter((a: string, i: number, arr: string[]) => {
if (a === "--ws" || a === "--token") return false;
if (arr[i - 1] === "--ws" || arr[i - 1] === "--token") return false;
return true;
});
stripped.push("--ws", wsUrl, "--token", wsToken);
const mcpJson = {
...existing,
mcpServers: {
...(existing.mcpServers ?? {}),
zeta1: { type: "stdio", command: "bun", args: stripped },
},
};
await Bun.write(mcpJsonPath, JSON.stringify(mcpJson, null, 2) + "\n");
process.stdout.write(` ${DIM}.mcp.json updated with session token${RESET}\n`);
}
// Spawn dev server if requested
if (spawnCmd) {
process.stdout.write(`\n ${DIM}Spawning: ${spawnCmd}${RESET}\n`);
const child = Bun.spawn(["sh", "-c", spawnCmd], {
cwd: process.cwd(),
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
});
process.on("exit", () => child.kill());
process.on("SIGINT", () => { child.kill(); process.exit(0); });
process.on("SIGTERM", () => { child.kill(); process.exit(0); });
}
// Build client bundle
process.stdout.write(`\n ${DIM}Building devproxy client bundle...${RESET}\n`);
await buildClientBundle();
// Wire up app dir for edit handler
{
const { setAppDir, setCaptureBody } = await import("./src/proxy/control");
const resolvedAppDir = appDir
? (appDir.startsWith("/") ? appDir : process.cwd() + "/" + appDir)
: process.cwd();
setAppDir(resolvedAppDir);
setCaptureBody(captureBodies);
}
// Start proxy server
await startProxy({ targetHost: target, proxyPort, expose, noConsole, wsToken });
process.stdout.write(`
${"\x1b[1m"}zeta-1 proxy${RESET}
${DIM}──────────────────────────────────────${RESET}
${DIM}Target${RESET} ${"\x1b[36m"}http://${target}${RESET}
${DIM}Proxy${RESET} ${"\x1b[36m"}http://localhost:${proxyPort}${RESET} ${DIM}← open this in browser${expose ? ` (bound to 0.0.0.0)` : ""}${RESET}
${DIM}WS${RESET} ${"\x1b[36m"}ws://localhost:${proxyPort}/__devproxy/ws${RESET} ${DIM}← MCP connects here${RESET}${wsToken ? `\n ${YLW}WS token${RESET} ${wsToken} ${DIM}← required for connections from other machines${RESET}` : ""}
${DIM}Press Ctrl+C to stop.${RESET}
`);
// Keep running
await new Promise<never>(() => {});
}
// --- Main ---
async function main() {
const argv = process.argv.slice(2);
if (argv[0] === "proxy" || argv.length === 0 || !argv[0].startsWith("-") && argv[0] !== "proxy") {
// "proxy" sub-command or bare target argument
const args = argv[0] === "proxy" ? argv.slice(1) : argv;
await runProxy(args);
return;
}
process.stderr.write(`\n ${RED}Unknown command.${RESET}\n`);
process.stderr.write(` Usage: bun run cli.ts proxy [target] [--port 4000]\n\n`);
process.exit(1);
}
main();