-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.js
More file actions
517 lines (459 loc) · 16.7 KB
/
install.js
File metadata and controls
517 lines (459 loc) · 16.7 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#!/usr/bin/env node
// Claude Code Environment Installer
// Usage: curl -fsSL https://raw.githubusercontent.com/aproorg/claude-wrapper/main/install.js | node
//
// Installs a process wrapper at ~/.local/bin/claude that:
// - Shadows the real Claude Code binary
// - Fetches and caches team configuration from a central URL
// - Retrieves API keys from 1Password
// - Forwards all arguments to the real Claude Code binary
//
// Options (via environment variables):
// CLAUDE_ENV_URL Override the remote env script URL
// CLAUDE_FORCE=1 Overwrite existing wrapper without prompting
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const https = require("https");
const { execSync } = require("child_process");
// ============================================================================
// Configuration
// ============================================================================
const REMOTE_ENV_URL =
process.env.CLAUDE_ENV_URL ||
"https://raw.githubusercontent.com/aproorg/claude-wrapper/main/claude-env.sh";
// ============================================================================
// Output helpers
// ============================================================================
const color = (code, text) =>
process.stderr.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text;
const info = (msg) => console.error(` ${color(34, "[INFO]")} ${msg}`);
const ok = (msg) => console.error(` ${color(32, "[OK]")} ${msg}`);
const warn = (msg) => console.error(` ${color(33, "[WARN]")} ${msg}`);
const error = (msg) => console.error(` ${color(31, "[ERROR]")} ${msg}`);
function die(msg) {
error(msg);
process.exit(1);
}
// ============================================================================
// Platform detection
// ============================================================================
function detectPlatform() {
switch (process.platform) {
case "darwin":
return "macos";
case "linux":
try {
const version = fs.readFileSync("/proc/version", "utf8");
if (/microsoft/i.test(version)) return "wsl";
} catch {}
return "linux";
case "win32":
return "windows";
default:
return "unknown";
}
}
// ============================================================================
// Helpers
// ============================================================================
function commandExists(cmd) {
if (!/^[a-zA-Z0-9_.-]+$/.test(cmd)) return false;
try {
const check =
process.platform === "win32" ? `where ${cmd}` : `command -v ${cmd}`;
execSync(check, { stdio: "ignore" });
return true;
} catch {
return false;
}
}
function fetch(url, redirectsLeft = 5) {
return new Promise((resolve, reject) => {
if (redirectsLeft <= 0) return reject(new Error("Too many redirects"));
const get = url.startsWith("https") ? https.get : require("http").get;
get(url, { timeout: 10_000 }, (res) => {
if (
res.statusCode >= 300 &&
res.statusCode < 400 &&
res.headers.location
) {
return fetch(res.headers.location, redirectsLeft - 1).then(
resolve,
reject,
);
}
if (res.statusCode !== 200) {
return reject(new Error(`HTTP ${res.statusCode}`));
}
const chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
res.on("error", reject);
}).on("error", reject);
});
}
// ============================================================================
// Paths
// ============================================================================
function installBinDir() {
if (process.platform === "win32") {
return path.join(
process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"),
"Programs",
"claude-wrapper",
);
}
return path.join(os.homedir(), ".local", "bin");
}
function configDir() {
if (process.platform === "win32") {
return path.join(
process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"),
"claude",
);
}
return path.join(
process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"),
"claude",
);
}
function cacheDir() {
if (process.platform === "win32") {
return path.join(
process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"),
"claude",
);
}
return path.join(
process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"),
"claude",
);
}
// ============================================================================
// Shell profile detection
// ============================================================================
function detectShellProfile() {
const shell = process.env.SHELL || "";
const home = os.homedir();
if (shell.endsWith("/zsh")) {
return path.join(home, ".zshrc");
}
if (shell.endsWith("/bash")) {
const bashrc = path.join(home, ".bashrc");
if (fs.existsSync(bashrc)) return bashrc;
return path.join(home, ".bash_profile");
}
return path.join(home, ".profile");
}
function ensureOnPath(binDir) {
// Already on PATH
const dirs = (process.env.PATH || "").split(":");
if (dirs.includes(binDir)) return null;
const profile = detectShellProfile();
// Profile already references the dir
try {
const content = fs.readFileSync(profile, "utf8");
if (content.includes(binDir)) return null;
} catch {}
const line = '\nexport PATH="' + binDir + ':$PATH"\n';
fs.appendFileSync(profile, line);
return profile;
}
// ============================================================================
// Download and patch the process wrapper script
// ============================================================================
async function fetchWrapper(remoteUrl) {
const wrapperUrl = remoteUrl.replace("claude-env.sh", "claude");
const script = await fetch(wrapperUrl);
// The only dynamic value: bake the remote config URL into the default
const defaultLine =
'CLAUDE_ENV_REMOTE_URL="${CLAUDE_ENV_URL:-https://raw.githubusercontent.com/aproorg/claude-wrapper/main/claude-env.sh}"';
const patchedLine = `CLAUDE_ENV_REMOTE_URL="\${CLAUDE_ENV_URL:-${remoteUrl}}"`;
return script.replace(defaultLine, patchedLine);
}
// ============================================================================
// Interactive prompting (via /dev/tty for curl-pipe compatibility)
// ============================================================================
function prompt(question, defaultValue) {
return new Promise((resolve) => {
try {
const display = defaultValue
? `${question} [${defaultValue}]: `
: `${question}: `;
let rl;
if (process.platform === "win32") {
// Windows: no /dev/tty; use stdin directly (works for interactive runs)
rl = require("readline").createInterface({
input: process.stdin,
output: process.stderr,
});
} else {
const tty = fs.openSync("/dev/tty", "r+");
rl = require("readline").createInterface({
input: new fs.createReadStream(null, { fd: tty }),
output: new fs.createWriteStream(null, { fd: tty }),
});
}
rl.question(display, (answer) => {
rl.close();
resolve(answer.trim() || defaultValue || "");
});
} catch {
resolve(defaultValue || "");
}
});
}
// ============================================================================
// Local config (local.env) read/write
// ============================================================================
function readLocalConfig(filePath) {
const values = {};
try {
const content = fs.readFileSync(filePath, "utf8");
for (const line of content.split("\n")) {
const m = line.match(/^(LITELLM_BASE_URL|OP_ITEM)="(.*)"\s*$/);
if (m) values[m[1]] = m[2];
}
} catch {}
return values;
}
function writeLocalConfig(filePath, values) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const content = [
"# Local overrides — User-specific settings",
"# Written by install.js, sourced by claude-env.sh / claudestart.ps1",
`LITELLM_BASE_URL="${values.LITELLM_BASE_URL}"`,
`OP_ITEM="${values.OP_ITEM}"`,
"",
].join("\n");
// mode: 0o600 is Unix-only (no-op / errors on Windows)
const opts = process.platform === "win32" ? {} : { mode: 0o600 };
fs.writeFileSync(filePath, content, opts);
}
// ============================================================================
// Shared: interactive prompts for local.env
// ============================================================================
async function promptLocalConfig(cfgDir) {
const localEnvPath = path.join(cfgDir, "local.env");
const existing = readLocalConfig(localEnvPath);
const defaultUrl =
existing.LITELLM_BASE_URL || "https://litellm.ai.apro.is";
const defaultItem = existing.OP_ITEM || "op://Employee/ai.apro.is litellm";
console.error("");
info("Configure your local connection settings:");
console.error("");
let litellmUrl = "";
while (!litellmUrl) {
litellmUrl = await prompt(" LiteLLM base URL", defaultUrl);
}
let opItem = "";
while (!opItem || !opItem.startsWith("op://")) {
opItem = await prompt(" 1Password item (op://...)", defaultItem);
if (opItem && !opItem.startsWith("op://")) {
warn("Must start with op:// — try again");
opItem = "";
}
}
writeLocalConfig(localEnvPath, {
LITELLM_BASE_URL: litellmUrl,
OP_ITEM: opItem,
});
ok(`Wrote ${localEnvPath}`);
}
// ============================================================================
// Windows: install + PATH management
// ============================================================================
function ensureOnPathWindows(dir) {
try {
const currentPath = execSync(
`powershell -Command "[Environment]::GetEnvironmentVariable('Path','User')"`,
{ encoding: "utf8" },
).trim();
const normalize = (d) => d.toLowerCase().replace(/\\+$/, "");
const dirs = currentPath.split(";").map(normalize);
if (dirs.includes(normalize(dir))) {
ok(`${dir} is already on user PATH`);
return;
}
const newPath = currentPath ? `${currentPath};${dir}` : dir;
execSync(
`powershell -Command "[Environment]::SetEnvironmentVariable('Path','${newPath.replace(/'/g, "''")}','User')"`,
{ stdio: "ignore" },
);
ok(`Added ${dir} to user PATH`);
warn("Restart your terminal for PATH changes to take effect");
} catch (err) {
warn(`Could not update PATH: ${err.message}`);
warn(`Manually add ${dir} to your user PATH`);
}
}
async function installWindows(platform) {
const binDir = installBinDir();
const cfgDir = configDir();
const cchDir = cacheDir();
info(`Platform: ${platform}`);
info(`Install dir: ${binDir}`);
// Create directories
fs.mkdirSync(binDir, { recursive: true });
fs.mkdirSync(cfgDir, { recursive: true });
fs.mkdirSync(cchDir, { recursive: true });
// Download claudestart.ps1
info("Downloading claudestart.ps1...");
const ps1Url = REMOTE_ENV_URL.replace("claude-env.sh", "claudestart.ps1");
const ps1Content = await fetch(ps1Url);
const ps1Path = path.join(binDir, "claudestart.ps1");
fs.writeFileSync(ps1Path, ps1Content);
ok(`Wrote ${ps1Path}`);
// Write claudestart.cmd batch shim
const cmdPath = path.join(binDir, "claudestart.cmd");
const cmdContent =
'@powershell -ExecutionPolicy Bypass -File "%~dp0claudestart.ps1" %*\r\n';
fs.writeFileSync(cmdPath, cmdContent);
ok(`Wrote ${cmdPath}`);
// Add to user PATH
ensureOnPathWindows(binDir);
// Interactive prompts for local config
await promptLocalConfig(cfgDir);
}
// ============================================================================
// Installation (macOS / Linux / WSL)
// ============================================================================
async function install(platform) {
const binDir = installBinDir();
const cfgDir = configDir();
const cchDir = cacheDir();
const wrapperPath = path.join(binDir, "claude");
info(`Platform: ${platform}`);
info(`Wrapper: ${wrapperPath}`);
// Create directories
fs.mkdirSync(binDir, { recursive: true, mode: 0o755 });
fs.mkdirSync(cfgDir, { recursive: true, mode: 0o755 });
fs.mkdirSync(cchDir, { recursive: true, mode: 0o700 });
try {
fs.chmodSync(cchDir, 0o700);
} catch {}
// Clean up old env.sh bootstrap from previous install method (no longer used)
const oldEnvSh = path.join(cfgDir, "env.sh");
if (fs.existsSync(oldEnvSh)) {
fs.unlinkSync(oldEnvSh);
info("Removed old env.sh bootstrap (no longer needed)");
}
// Handle existing wrapper
if (fs.existsSync(wrapperPath) && process.env.CLAUDE_FORCE !== "1") {
const stat = fs.lstatSync(wrapperPath);
if (stat.isSymbolicLink()) {
const target = fs.readlinkSync(wrapperPath);
info(`Replacing symlink ${wrapperPath} → ${target}`);
fs.unlinkSync(wrapperPath);
} else {
const backup = `${wrapperPath}.backup.${Date.now()}`;
fs.copyFileSync(wrapperPath, backup);
info(`Backed up existing wrapper to ${backup}`);
}
}
// Download and write the process wrapper
info("Downloading process wrapper...");
const wrapperContent = await fetchWrapper(REMOTE_ENV_URL);
fs.writeFileSync(wrapperPath, wrapperContent, { mode: 0o755 });
ok(`Wrote ${wrapperPath}`);
// Ensure ~/.local/bin is on PATH
const modifiedProfile = ensureOnPath(binDir);
if (modifiedProfile) {
ok(`Added ${binDir} to PATH in ${modifiedProfile}`);
warn("Restart your shell or run: source " + modifiedProfile);
} else {
ok(`${binDir} is already on PATH`);
}
// Pre-fetch the remote config
info("Fetching remote configuration...");
try {
const remoteEnv = await fetch(REMOTE_ENV_URL);
const cachePath = path.join(cchDir, "env-remote.sh");
fs.writeFileSync(cachePath, remoteEnv, { mode: 0o600 });
ok("Remote configuration cached");
} catch (err) {
warn(`Could not fetch remote configuration: ${err.message}`);
warn(` URL: ${REMOTE_ENV_URL}`);
warn("The wrapper will retry on next Claude invocation");
}
// Interactive prompts for local config
await promptLocalConfig(cfgDir);
}
// ============================================================================
// Prerequisites
// ============================================================================
function checkPrerequisites(platform) {
if (platform === "windows") {
if (!commandExists("powershell")) {
die("PowerShell is required");
}
// Windows uses claudestart, not a shadow binary — skip claude check
} else {
if (!commandExists("claude")) {
die(
"Claude Code must be installed first (brew install claude-code, or npm install -g @anthropic-ai/claude-code)",
);
}
if (!commandExists("curl")) {
die("curl is required (used by the wrapper for fetching config updates)");
}
}
if (!commandExists("op")) {
warn("1Password CLI (op) not found — API key management will not work");
warn("Install: https://developer.1password.com/docs/cli/get-started/");
}
if (!commandExists("git")) {
warn("git not found — project detection will fall back to directory name");
}
}
// ============================================================================
// Main
// ============================================================================
async function main() {
console.error("");
console.error(" Claude Code Environment Installer");
console.error(" " + "─".repeat(35));
console.error("");
const platform = detectPlatform();
if (platform === "unknown") {
die(`Unsupported platform: ${process.platform}`);
}
checkPrerequisites(platform);
if (platform === "windows") {
await installWindows(platform);
} else {
await install(platform);
}
ok("Installation complete!");
if (platform === "windows") {
console.error("");
console.error(
" The claudestart command launches Claude Code with team config.",
);
console.error("");
console.error(" Commands:");
console.error(" Launch: claudestart");
console.error(" Debug: $env:CLAUDE_DEBUG = '1'; claudestart");
console.error(
" Force refresh: Remove-Item $env:LOCALAPPDATA\\claude\\env-remote.ps1",
);
console.error("");
} else {
console.error("");
console.error(
" The wrapper at ~/.local/bin/claude shadows the real binary,",
);
console.error(" injects your team config, and forwards all arguments.");
console.error("");
console.error(" Commands:");
console.error(
" Verify: which claude (should show ~/.local/bin/claude)",
);
console.error(" Debug: CLAUDE_DEBUG=1 claude");
console.error(" Force refresh: rm ~/.cache/claude/env-remote.sh");
console.error("");
}
}
main().catch((err) => die(err.message));