cctether 0.0.0-stage → 0.3.1
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.
- package/LICENSE +21 -0
- package/README.md +35 -2
- package/bin/cctether.js +7 -0
- package/package.json +42 -4
- package/src/check.js +108 -0
- package/src/cli.js +273 -0
- package/src/config.js +164 -0
- package/src/control.js +114 -0
- package/src/daemon.js +134 -0
- package/src/gateway.js +410 -0
- package/src/log.js +4 -0
- package/src/mcp.js +145 -0
- package/src/pairing.js +29 -0
- package/src/protocol.js +107 -0
- package/src/ratelimit.js +59 -0
- package/src/schema.js +56 -0
- package/src/setup.js +634 -0
- package/src/shim.js +122 -0
- package/src/system.js +294 -0
- package/src/text.js +291 -0
- package/src/tools.js +329 -0
package/src/setup.js
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
// `cctether setup` (SPEC §8.1): install, key, how the browser connects, background service,
|
|
2
|
+
// Claude Code registration, a self-check, and the connection code. Safe to run again: finished steps
|
|
3
|
+
// are reported and skipped, the key is never replaced (that's `cctether rotate`), and a service unit
|
|
4
|
+
// or Claude Code entry that setup didn't write is only replaced when the user says so.
|
|
5
|
+
|
|
6
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
7
|
+
import { homedir, userInfo } from 'node:os';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
11
|
+
import {
|
|
12
|
+
WS_PATH, paths, loadConfig, initConfig, saveConfig, serverUrl, localUrl, isValidServerUrl,
|
|
13
|
+
} from './config.js';
|
|
14
|
+
import { encodePairingCode, keyFingerprint } from './pairing.js';
|
|
15
|
+
import { adminRequest } from './control.js';
|
|
16
|
+
import { spawnDaemon } from './shim.js';
|
|
17
|
+
import { checkAddress, explainCheck } from './check.js';
|
|
18
|
+
import { createText, pickLanguage } from './text.js';
|
|
19
|
+
import * as sys from './system.js';
|
|
20
|
+
|
|
21
|
+
const MODES = ['local', 'ssh', 'https'];
|
|
22
|
+
|
|
23
|
+
/** ANSI styling, only when writing to a terminal that wants colour. */
|
|
24
|
+
export function createStyle(enabled) {
|
|
25
|
+
const wrap = (code) => (s) => (enabled ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
26
|
+
const bold = wrap('1'), dim = wrap('2'), green = wrap('32'), red = wrap('31'), yellow = wrap('33'), cyan = wrap('36');
|
|
27
|
+
return { bold, dim, green, red, yellow, cyan, ok: green('✓'), bad: red('✗'), warn: yellow('!'), dot: dim('·') };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Text shared by setup and check: prints lines with a fixed left margin. */
|
|
31
|
+
export function createPrinter(write, style) {
|
|
32
|
+
const BODY = ' ';
|
|
33
|
+
return {
|
|
34
|
+
blank: () => write(''),
|
|
35
|
+
title: (s, sub) => { write(''); write(` ${style.bold(s)}`); if (sub) write(` ${style.dim(sub)}`); },
|
|
36
|
+
step: (n, s) => { write(''); write(` ${style.cyan(String(n))} ${style.bold(s)}`); },
|
|
37
|
+
line: (s) => { for (const l of String(s).split('\n')) write(l ? BODY + l : ''); },
|
|
38
|
+
code: (s) => { for (const l of String(s).split('\n')) write(l ? BODY + ' ' + style.dim(l) : ''); },
|
|
39
|
+
raw: write,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The config folder cctether uses when nothing is set (what a service or Claude Code would get). */
|
|
44
|
+
const defaultConfigDir = () => join(homedir(), '.config', 'cctether');
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {object} c
|
|
48
|
+
* @param {string} c.dir config directory
|
|
49
|
+
* @param {string} c.version
|
|
50
|
+
* @param {string} c.cliPath bin/cctether.js of this copy
|
|
51
|
+
* @param {object} c.opts parsed flags: yes, mode, url, port, lang, install, service, mcp
|
|
52
|
+
* @param {(line: string) => void} c.write
|
|
53
|
+
* @param {(prompt: string) => Promise<string>} c.ask reads one answer (not used with --yes)
|
|
54
|
+
* @param {boolean} c.interactive stdin and stdout are a terminal
|
|
55
|
+
* @param {boolean} [c.showCode] print the connection code (only when the output is a terminal)
|
|
56
|
+
* @param {boolean} [c.color]
|
|
57
|
+
* @param {object} [c.env]
|
|
58
|
+
* @param {string} [c.platform]
|
|
59
|
+
* @param {Function} [c.runFn] sys.run replacement (tests)
|
|
60
|
+
* @param {object} [c.self] locateSelf() result (tests)
|
|
61
|
+
* @param {Function} [c.startDaemon] (P, cliPath, env) => void
|
|
62
|
+
* @returns {Promise<number>} exit code: 0 done, 1 something failed, 2 bad input
|
|
63
|
+
*/
|
|
64
|
+
export async function runSetup(c) {
|
|
65
|
+
const env = c.env ?? process.env;
|
|
66
|
+
const platform = c.platform ?? process.platform;
|
|
67
|
+
const baseRun = c.runFn ?? sys.run;
|
|
68
|
+
const runFn = (cmd, args, o = {}) => baseRun(cmd, args, { env, ...o });
|
|
69
|
+
const opts = c.opts ?? {};
|
|
70
|
+
const style = createStyle(!!c.color);
|
|
71
|
+
const t = createText(pickLanguage(opts.lang, env), style);
|
|
72
|
+
const out = createPrinter(c.write, style);
|
|
73
|
+
const startDaemon = c.startDaemon ?? spawnDaemon;
|
|
74
|
+
const P = paths(c.dir, env);
|
|
75
|
+
|
|
76
|
+
if (platform === 'win32') {
|
|
77
|
+
c.write(t('setup.windows'));
|
|
78
|
+
return 1;
|
|
79
|
+
}
|
|
80
|
+
if (!opts.yes && !c.interactive) {
|
|
81
|
+
c.write(t('setup.needTty'));
|
|
82
|
+
return 2;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Check the flags before changing anything.
|
|
86
|
+
let mode = opts.mode ?? (opts.url ? (isLocalUrl(opts.url) ? 'local' : 'https') : null);
|
|
87
|
+
let flagUrl = null;
|
|
88
|
+
if (opts.url !== undefined) {
|
|
89
|
+
if (mode === 'https') {
|
|
90
|
+
flagUrl = normalizePublicUrl(opts.url);
|
|
91
|
+
if (!flagUrl || !isValidServerUrl(flagUrl.url)) {
|
|
92
|
+
c.write(t('mode.https.invalid'));
|
|
93
|
+
return 2;
|
|
94
|
+
}
|
|
95
|
+
} else if (isLocalUrl(opts.url) && isValidServerUrl(opts.url)) flagUrl = { url: opts.url };
|
|
96
|
+
}
|
|
97
|
+
if (opts.yes && mode === 'https' && !flagUrl) {
|
|
98
|
+
const prev = safeLoadConfig(c.dir)?.publicUrl;
|
|
99
|
+
if (!prev || isLocalUrl(prev)) {
|
|
100
|
+
c.write(t('setup.needUrl'));
|
|
101
|
+
return 2;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Ask yes/no. With --yes, answer `yesAnswer` (default: the same as the default). */
|
|
106
|
+
const yn = async (question, def, yesAnswer = def) => {
|
|
107
|
+
if (opts.yes) return yesAnswer;
|
|
108
|
+
for (let tries = 0; ; tries++) {
|
|
109
|
+
if (tries >= MAX_TRIES) throw new TooManyTries();
|
|
110
|
+
const a = (await c.ask(`${BODY_PROMPT(style)}${question} ${style.dim(`[${def ? t('setup.yes') : t('setup.no')}]`)} `)).trim().toLowerCase();
|
|
111
|
+
if (!a) return def;
|
|
112
|
+
if (['y', 'yes', '是', '好', '要'].includes(a)) return true;
|
|
113
|
+
if (['n', 'no', '否', '不', '不要'].includes(a)) return false;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
try {
|
|
117
|
+
return await steps();
|
|
118
|
+
} catch (e) {
|
|
119
|
+
if (!(e instanceof TooManyTries)) throw e;
|
|
120
|
+
out.line(t('setup.tooManyTries'));
|
|
121
|
+
return 2;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function steps() {
|
|
125
|
+
let problems = false;
|
|
126
|
+
|
|
127
|
+
out.title(t('setup.title'), t('setup.tagline'));
|
|
128
|
+
|
|
129
|
+
// 1. Install ------------------------------------------------------------------------------
|
|
130
|
+
out.step(1, t('step.install'));
|
|
131
|
+
let self = c.self ?? sys.locateSelf({ cliPath: c.cliPath, env, runFn });
|
|
132
|
+
if (self.kind === 'npx') {
|
|
133
|
+
if (opts.install === false) {
|
|
134
|
+
out.line(t('install.noInstall'));
|
|
135
|
+
return 1;
|
|
136
|
+
}
|
|
137
|
+
self = await installFromNpx({ c, t, out, yn, runFn, env });
|
|
138
|
+
if (!self) return 1;
|
|
139
|
+
} else if (self.kind === 'installed') {
|
|
140
|
+
out.line(t('install.ok', { version: c.version, path: self.binPath }));
|
|
141
|
+
if (!self.onPath) out.line(t('install.notOnPath', { dir: dirname(self.binPath) }));
|
|
142
|
+
} else {
|
|
143
|
+
out.line(t('install.checkout', { path: dirname(dirname(self.cliPath)) }));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// 2. Key ----------------------------------------------------------------------------------
|
|
147
|
+
out.step(2, t('step.key'));
|
|
148
|
+
let { cfg, created } = initConfig(c.dir, { port: opts.port });
|
|
149
|
+
if (opts.port !== undefined && opts.port !== cfg.port) {
|
|
150
|
+
cfg.port = opts.port;
|
|
151
|
+
saveConfig(c.dir, cfg);
|
|
152
|
+
}
|
|
153
|
+
out.line(t(created ? 'key.created' : 'key.exists', { fp: keyFingerprint(cfg.key), path: P.config }));
|
|
154
|
+
|
|
155
|
+
// 3. How the browser connects -------------------------------------------------------------
|
|
156
|
+
out.step(3, t('step.mode'));
|
|
157
|
+
const unitPath = sys.unitFile(env);
|
|
158
|
+
const hadUnit = existsSync(unitPath);
|
|
159
|
+
let asked = false;
|
|
160
|
+
if (!mode) {
|
|
161
|
+
const current = cfg.publicUrl && !isLocalUrl(cfg.publicUrl) ? 'https' : hadUnit ? 'ssh' : 'local';
|
|
162
|
+
if (opts.yes) mode = current;
|
|
163
|
+
else {
|
|
164
|
+
asked = true;
|
|
165
|
+
MODES.forEach((m, i) => out.line(`${style.cyan(`${i + 1})`)} ${t(`mode.${m}`)}`));
|
|
166
|
+
const def = MODES.indexOf(current) + 1;
|
|
167
|
+
for (let tries = 0; ; tries++) {
|
|
168
|
+
if (tries >= MAX_TRIES) throw new TooManyTries();
|
|
169
|
+
const a = (await c.ask(`${BODY_PROMPT(style)}${t('mode.choose')} ${style.dim(`[${def}]`)}: `)).trim();
|
|
170
|
+
const n = a ? Number(a) : def;
|
|
171
|
+
if (n >= 1 && n <= 3) { mode = MODES[n - 1]; break; }
|
|
172
|
+
out.line(t('mode.invalid'));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (!asked) out.line(`${style.cyan('→')} ${t(`mode.${mode}`)}`);
|
|
177
|
+
|
|
178
|
+
let publicUrl;
|
|
179
|
+
if (mode === 'https') {
|
|
180
|
+
const previous = cfg.publicUrl && !isLocalUrl(cfg.publicUrl) ? cfg.publicUrl : null;
|
|
181
|
+
let fixed = flagUrl;
|
|
182
|
+
for (let tries = 0; !fixed; tries++) {
|
|
183
|
+
if (tries >= MAX_TRIES) throw new TooManyTries();
|
|
184
|
+
const a = opts.yes ? previous : (await c.ask(`${BODY_PROMPT(style)}${t('mode.https.ask')}${previous ? ' ' + style.dim(`[${previous}]`) : ''}: `)).trim() || previous;
|
|
185
|
+
if (!a) continue;
|
|
186
|
+
fixed = normalizePublicUrl(a);
|
|
187
|
+
if (!fixed || !isValidServerUrl(fixed.url)) {
|
|
188
|
+
out.line(t('mode.https.invalid'));
|
|
189
|
+
fixed = null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
publicUrl = fixed.url;
|
|
193
|
+
if (fixed.addedPath) out.line(t('mode.https.addedPath', { url: publicUrl }));
|
|
194
|
+
else if (fixed.path !== WS_PATH) out.line(t('mode.https.otherPath', { path: fixed.path }));
|
|
195
|
+
} else {
|
|
196
|
+
// Same computer or SSH tunnel: the local address, or a local one given by hand (another port).
|
|
197
|
+
publicUrl = flagUrl?.url ?? (cfg.publicUrl && isLocalUrl(cfg.publicUrl) ? cfg.publicUrl : null);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (cfg.publicUrl !== publicUrl) {
|
|
201
|
+
cfg.publicUrl = publicUrl;
|
|
202
|
+
saveConfig(c.dir, cfg);
|
|
203
|
+
}
|
|
204
|
+
await adminRequest(P.socket, { cmd: 'reload' }); // a running service picks up the address
|
|
205
|
+
const url = serverUrl(cfg);
|
|
206
|
+
if (mode === 'local') out.line(t('mode.local.note', { url }));
|
|
207
|
+
if (mode === 'ssh') out.line(t('mode.ssh.note', { url, port: cfg.port }));
|
|
208
|
+
if (mode === 'https') {
|
|
209
|
+
const u = new URL(publicUrl);
|
|
210
|
+
out.line(t('mode.https.proxy', { url: publicUrl, port: cfg.port }));
|
|
211
|
+
out.blank();
|
|
212
|
+
out.code(caddySnippet(u.host, u.pathname, cfg.port));
|
|
213
|
+
out.blank();
|
|
214
|
+
out.line(t('mode.https.more'));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// 4. Background service -------------------------------------------------------------------
|
|
218
|
+
out.step(4, t('step.service'));
|
|
219
|
+
let managed = false; // systemd runs our service
|
|
220
|
+
if (platform === 'darwin') out.line(t('service.mac'));
|
|
221
|
+
else if (platform !== 'linux' || !sys.systemdUserAvailable(runFn)) out.line(t('service.noSystemd'));
|
|
222
|
+
else {
|
|
223
|
+
const remote = mode !== 'local';
|
|
224
|
+
const want = opts.service === false ? false
|
|
225
|
+
: await yn(t(remote || hadUnit ? 'service.ask.remote' : 'service.ask.local'), remote || hadUnit);
|
|
226
|
+
if (!want) out.line(t('service.skipped'));
|
|
227
|
+
else {
|
|
228
|
+
const r = await installService({ c, t, out, yn, runFn, P, self, unitPath, cfg });
|
|
229
|
+
managed = r.managed;
|
|
230
|
+
if (!r.ok) problems = true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// 5. Claude Code --------------------------------------------------------------------------
|
|
235
|
+
out.step(5, t('step.claude'));
|
|
236
|
+
const cmd = sys.mcpCommand(self);
|
|
237
|
+
const customHome = c.dir !== defaultConfigDir();
|
|
238
|
+
const shown = shellJoin(cmd);
|
|
239
|
+
const addLine = `claude mcp add -s user cctether${customHome ? ` -e ${shellJoin([`CCTETHER_HOME=${c.dir}`])}` : ''} -- ${shown}`;
|
|
240
|
+
if (opts.mcp === false) out.line(t('claude.skipped', { cmd: addLine }));
|
|
241
|
+
else if (!sys.findOnPath('claude', env)) {
|
|
242
|
+
const json = JSON.stringify({ command: cmd[0], args: cmd.slice(1), ...(customHome ? { env: { CCTETHER_HOME: c.dir } } : {}) });
|
|
243
|
+
out.line(t('claude.missing', { cmd: addLine, json }));
|
|
244
|
+
} else if (!(await registerWithClaude({ t, out, yn, runFn, env, cmd, dir: c.dir, customHome, yes: !!opts.yes }))) {
|
|
245
|
+
problems = true;
|
|
246
|
+
} else {
|
|
247
|
+
// Only once Claude Code has the tools: the note tells Claude to use them.
|
|
248
|
+
await claudeMdStep({ t, out, yn, env, opts });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 6. Check --------------------------------------------------------------------------------
|
|
252
|
+
out.step(6, t('step.check'));
|
|
253
|
+
const up = await ensureRunning({ t, out, runFn, env, P, cfg, version: c.version, self, managed, startDaemon });
|
|
254
|
+
if (!up) problems = true;
|
|
255
|
+
else {
|
|
256
|
+
const results = await checkUrls({ t, out, cfg, publicUrl: mode === 'https' ? publicUrl : null });
|
|
257
|
+
if (!results.localOk) problems = true;
|
|
258
|
+
if (mode === 'https' && !results.publicOk) {
|
|
259
|
+
if (HAIRPIN_REASONS.has(results.publicReason)) out.line(style.dim(t('check.hairpin')));
|
|
260
|
+
out.line(t('check.later'));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Connection code ------------------------------------------------------------------------
|
|
265
|
+
cfg = loadConfig(c.dir) ?? cfg;
|
|
266
|
+
out.blank();
|
|
267
|
+
out.raw(` ${style.bold(t(problems ? 'final.titleProblem' : 'final.title'))}`);
|
|
268
|
+
out.line(`1. ${t('final.step1')}`);
|
|
269
|
+
if (c.showCode) {
|
|
270
|
+
out.line(`2. ${t('final.step2')}`);
|
|
271
|
+
out.blank();
|
|
272
|
+
out.raw(encodePairingCode(serverUrl(cfg), cfg.key));
|
|
273
|
+
out.blank();
|
|
274
|
+
out.line(t('final.secret'));
|
|
275
|
+
out.line(style.dim(t('final.again')));
|
|
276
|
+
} else {
|
|
277
|
+
// Not a terminal (a script, a log, another program): the code is a secret, so it isn't printed.
|
|
278
|
+
out.line(`2. ${t('final.step2.hidden')}`);
|
|
279
|
+
}
|
|
280
|
+
out.line(t('final.restart'));
|
|
281
|
+
out.blank();
|
|
282
|
+
return problems ? 1 : 0;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Questions give up after this many answers that don't make sense (e.g. input that isn't a person). */
|
|
287
|
+
const MAX_TRIES = 10;
|
|
288
|
+
class TooManyTries extends Error {}
|
|
289
|
+
|
|
290
|
+
/** Failures that can come from a server that can't reach its own public address. */
|
|
291
|
+
const HAIRPIN_REASONS = new Set(['timeout', 'refused', 'closed', 'error']);
|
|
292
|
+
|
|
293
|
+
const BODY_PROMPT = (style) => ` ${style.cyan('?')} `;
|
|
294
|
+
|
|
295
|
+
function isLocalUrl(u) {
|
|
296
|
+
try {
|
|
297
|
+
return ['127.0.0.1', 'localhost', '[::1]'].includes(new URL(u).hostname);
|
|
298
|
+
} catch {
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function safeLoadConfig(dir) {
|
|
304
|
+
try { return loadConfig(dir); } catch { return null; }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Accept "browser.example.com", "wss://browser.example.com" or a full URL. Adds /cctether when
|
|
309
|
+
* there's no path and drops a trailing slash. Returns null for anything that isn't wss/https.
|
|
310
|
+
*/
|
|
311
|
+
export function normalizePublicUrl(input) {
|
|
312
|
+
let s = String(input).trim();
|
|
313
|
+
if (!s) return null;
|
|
314
|
+
if (!/^[a-z]+:\/\//i.test(s)) s = `wss://${s}`;
|
|
315
|
+
let u;
|
|
316
|
+
try { u = new URL(s); } catch { return null; }
|
|
317
|
+
if (u.protocol === 'https:') u = new URL(`wss:${s.slice(s.indexOf('//'))}`);
|
|
318
|
+
if (u.protocol !== 'wss:') return null;
|
|
319
|
+
let addedPath = false;
|
|
320
|
+
if (u.pathname === '/' || u.pathname === '') {
|
|
321
|
+
u.pathname = WS_PATH;
|
|
322
|
+
addedPath = true;
|
|
323
|
+
} else if (u.pathname.length > 1 && u.pathname.endsWith('/')) {
|
|
324
|
+
u.pathname = u.pathname.replace(/\/+$/, '');
|
|
325
|
+
}
|
|
326
|
+
return { url: u.toString(), path: u.pathname, addedPath };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** A complete Caddy site block; a path other than /cctether is rewritten to it. */
|
|
330
|
+
export function caddySnippet(host, path, port) {
|
|
331
|
+
return [
|
|
332
|
+
`${host} {`,
|
|
333
|
+
`\t@tether path ${path}`,
|
|
334
|
+
'\thandle @tether {',
|
|
335
|
+
...(path !== WS_PATH ? [`\t\trewrite * ${WS_PATH}`] : []),
|
|
336
|
+
`\t\treverse_proxy 127.0.0.1:${port}`,
|
|
337
|
+
'\t}',
|
|
338
|
+
'\thandle {',
|
|
339
|
+
'\t\trespond 404',
|
|
340
|
+
'\t}',
|
|
341
|
+
'}',
|
|
342
|
+
].join('\n').replace(/\t/g, ' ');
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Quote for display in a POSIX shell. */
|
|
346
|
+
export function shellJoin(argv) {
|
|
347
|
+
return argv.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function installFromNpx({ c, t, out, yn, runFn, env }) {
|
|
351
|
+
// npx puts its own temporary copy first on PATH, so look in npm's global folder directly.
|
|
352
|
+
const prefix = sys.npmGlobalPrefix(runFn);
|
|
353
|
+
if (!prefix) {
|
|
354
|
+
out.line(t('install.noNpm'));
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
const binPath = join(prefix, 'bin', 'cctether');
|
|
358
|
+
const describe = () => {
|
|
359
|
+
const self = sys.locateSelf({ cliPath: binPath, env, runFn });
|
|
360
|
+
return { kind: 'installed', binPath, cliPath: self.cliPath, onPath: sys.findOnPath('cctether', env, { skipNpx: true }) === binPath };
|
|
361
|
+
};
|
|
362
|
+
const existingVersion = sys.versionAt(binPath);
|
|
363
|
+
if (existingVersion === c.version) {
|
|
364
|
+
out.line(t('install.npx.found', { version: c.version, path: binPath }));
|
|
365
|
+
const found = describe();
|
|
366
|
+
if (!found.onPath) out.line(t('install.notOnPath', { dir: dirname(binPath) }));
|
|
367
|
+
return found;
|
|
368
|
+
}
|
|
369
|
+
const ok = await yn(existingVersion
|
|
370
|
+
? t('install.npx.update', { old: existingVersion, path: binPath, version: c.version })
|
|
371
|
+
: t('install.npx.ask', { version: c.version }), true);
|
|
372
|
+
if (!ok) {
|
|
373
|
+
out.line(t('install.declined'));
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
if (!sys.npmPrefixWritable(prefix)) {
|
|
377
|
+
out.line(t('install.noWrite', { dir: prefix, version: c.version }));
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
out.line(t('install.running', { version: c.version }));
|
|
381
|
+
const r = runFn('npm', ['install', '-g', `cctether@${c.version}`], { inherit: true, timeoutMs: 5 * 60_000 });
|
|
382
|
+
if (r.status !== 0 || sys.versionAt(binPath) !== c.version) {
|
|
383
|
+
out.line(t('install.failed', { code: r.status ?? '?' }));
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
const installed = describe();
|
|
387
|
+
out.line(t('install.done', { version: c.version, path: binPath }));
|
|
388
|
+
if (!installed.onPath) out.line(t('install.notOnPath', { dir: dirname(binPath) }));
|
|
389
|
+
return installed;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Write and start the systemd user service. Returns { ok, managed }: managed means systemd now runs
|
|
394
|
+
* this cctether; ok is false when something failed (a kept unit isn't a failure).
|
|
395
|
+
*/
|
|
396
|
+
async function installService({ c, t, out, yn, runFn, P, self, unitPath, cfg }) {
|
|
397
|
+
const unitArgs = { nodePath: process.execPath, cliPath: self.cliPath, configDir: c.dir, socketPath: P.socket };
|
|
398
|
+
let content;
|
|
399
|
+
try {
|
|
400
|
+
content = sys.renderUnit(unitArgs);
|
|
401
|
+
} catch (e) {
|
|
402
|
+
out.line(t('service.failed', { detail: e.message }));
|
|
403
|
+
return { ok: false, managed: false };
|
|
404
|
+
}
|
|
405
|
+
let existing = null;
|
|
406
|
+
try { existing = readFileSync(unitPath, 'utf8'); } catch {}
|
|
407
|
+
const changed = existing !== content;
|
|
408
|
+
if (existing !== null && changed) {
|
|
409
|
+
// Replace without asking only a unit setup wrote for this same settings folder.
|
|
410
|
+
const ours = existing.startsWith(sys.UNIT_HEADER);
|
|
411
|
+
const otherDir = ours ? sys.unitConfigDir(existing) : null;
|
|
412
|
+
if (!ours || (otherDir !== null && otherDir !== c.dir)) {
|
|
413
|
+
const question = ours ? t('service.otherDir', { path: unitPath, dir: otherDir, current: c.dir }) : t('service.overwrite', { path: unitPath });
|
|
414
|
+
if (!(await yn(question, false))) {
|
|
415
|
+
out.line(t('service.kept', { path: unitPath }));
|
|
416
|
+
return { ok: true, managed: false };
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (changed) {
|
|
421
|
+
mkdirSync(dirname(unitPath), { recursive: true });
|
|
422
|
+
writeFileSync(unitPath, content);
|
|
423
|
+
}
|
|
424
|
+
runFn('systemctl', ['--user', 'daemon-reload']);
|
|
425
|
+
runFn('systemctl', ['--user', 'enable', sys.UNIT_NAME]);
|
|
426
|
+
|
|
427
|
+
const active = sys.serviceActive(runFn);
|
|
428
|
+
const st = await adminRequest(P.socket, { cmd: 'status' });
|
|
429
|
+
const needsStart = !active || changed || st?.version !== c.version || !st?.ok || st.pid !== sys.serviceMainPid(runFn);
|
|
430
|
+
if (needsStart) {
|
|
431
|
+
// If Claude Code started a copy of the service, the one systemd starts takes over from it.
|
|
432
|
+
let r = runFn('systemctl', ['--user', active ? 'restart' : 'start', sys.UNIT_NAME]);
|
|
433
|
+
let up = r.status === 0 && await waitForManaged(P, cfg, runFn);
|
|
434
|
+
if (!up && sys.serviceExitStatus(runFn) === 226) {
|
|
435
|
+
// 226/NAMESPACE: this system doesn't allow the file-system sandbox for user services.
|
|
436
|
+
writeFileSync(unitPath, sys.renderUnit({ ...unitArgs, sandbox: false }));
|
|
437
|
+
runFn('systemctl', ['--user', 'daemon-reload']);
|
|
438
|
+
runFn('systemctl', ['--user', 'reset-failed', sys.UNIT_NAME]);
|
|
439
|
+
r = runFn('systemctl', ['--user', 'restart', sys.UNIT_NAME]);
|
|
440
|
+
up = r.status === 0 && await waitForManaged(P, cfg, runFn);
|
|
441
|
+
}
|
|
442
|
+
if (!up) {
|
|
443
|
+
const detail = (r.stderr || r.error?.message || '').trim().split('\n')[0] || `systemctl --user start ${sys.UNIT_NAME}`;
|
|
444
|
+
out.line(t('service.failed', { detail }));
|
|
445
|
+
return { ok: false, managed: false };
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
out.line(t('service.ok'));
|
|
449
|
+
const user = userInfo().username;
|
|
450
|
+
if (sys.lingerEnabled(runFn, user)) out.line(t('service.linger.ok'));
|
|
451
|
+
else if (sys.tryEnableLinger(runFn) && sys.lingerEnabled(runFn, user)) out.line(t('service.linger.enabled'));
|
|
452
|
+
else out.line(t('service.linger.need', { user }));
|
|
453
|
+
return { ok: true, managed: true };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Add cctether to Claude Code. Returns false if that failed. */
|
|
457
|
+
async function registerWithClaude({ t, out, yn, runFn, env, cmd, dir, customHome, yes }) {
|
|
458
|
+
const wantEnv = customHome ? { CCTETHER_HOME: dir } : {};
|
|
459
|
+
const current = sys.claudeRegistration(env);
|
|
460
|
+
const same = (r) => r && r.command === cmd[0] && isDeepStrictEqual(r.args, cmd.slice(1))
|
|
461
|
+
&& (r.env?.CCTETHER_HOME ?? null) === (wantEnv.CCTETHER_HOME ?? null);
|
|
462
|
+
if (same(current)) {
|
|
463
|
+
out.line(t('claude.same'));
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
const addArgs = ['mcp', 'add', '-s', 'user', 'cctether', ...(customHome ? ['-e', `CCTETHER_HOME=${dir}`] : []), '--', ...cmd];
|
|
467
|
+
let r = runFn('claude', addArgs);
|
|
468
|
+
if (r.status !== 0 && /already exists/i.test(r.stdout + r.stderr)) {
|
|
469
|
+
const old = current ? shellJoin([current.command, ...current.args]) : '?';
|
|
470
|
+
// Someone set this up differently on purpose, maybe: --yes never replaces it.
|
|
471
|
+
if (yes) {
|
|
472
|
+
out.line(t('claude.keptYes', { old, new: shellJoin(cmd) }));
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
if (!(await yn(t('claude.replace', { old, new: shellJoin(cmd) }), true))) {
|
|
476
|
+
out.line(t('claude.kept'));
|
|
477
|
+
return true;
|
|
478
|
+
}
|
|
479
|
+
runFn('claude', ['mcp', 'remove', '-s', 'user', 'cctether']);
|
|
480
|
+
r = runFn('claude', addArgs);
|
|
481
|
+
}
|
|
482
|
+
if (r.status === 0) {
|
|
483
|
+
out.line(t('claude.added'));
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
486
|
+
out.line(t('claude.failed', { detail: (r.stderr || r.stdout || r.error?.message || '').trim().split('\n')[0] }));
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Optionally tell Claude, in its personal CLAUDE.md, to use cctether for browser tasks by itself. */
|
|
491
|
+
async function claudeMdStep({ t, out, yn, env, opts }) {
|
|
492
|
+
if (opts.claudeMd === false) return;
|
|
493
|
+
const path = sys.claudeMdFile(env);
|
|
494
|
+
let state;
|
|
495
|
+
try {
|
|
496
|
+
state = sys.findClaudeMdNote(sys.readClaudeMd(path)).state;
|
|
497
|
+
} catch (e) {
|
|
498
|
+
out.line(t('claude.mdFailed', { path, detail: e.message }));
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (state === 'ambiguous') {
|
|
502
|
+
out.line(t('claude.mdAmbiguous', { path }));
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
// Someone emptied the note: they don't want it. Only --claude-md fills it again.
|
|
506
|
+
if (state === 'empty' && opts.claudeMd !== true) return;
|
|
507
|
+
// The note is cctether's own: refresh it if it's there; otherwise only add it when asked to.
|
|
508
|
+
if (state === 'absent' && opts.claudeMd !== true) {
|
|
509
|
+
if (opts.yes) {
|
|
510
|
+
out.line(t('claude.mdHint'));
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
if (!(await yn(t('claude.mdAsk', { path }), true))) {
|
|
514
|
+
out.line(t('claude.mdDeclined'));
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
try {
|
|
519
|
+
const r = sys.upsertClaudeMdNote(path, t('claude.mdBody'), t('claude.mdComment'), { force: opts.claudeMd === true });
|
|
520
|
+
const key = { added: 'claude.mdAdded', updated: 'claude.mdUpdated', same: 'claude.mdSame', ambiguous: 'claude.mdAmbiguous' }[r];
|
|
521
|
+
if (key) out.line(t(key, { path }));
|
|
522
|
+
} catch (e) {
|
|
523
|
+
out.line(t('claude.mdFailed', { path, detail: e.code === 'EACCES' || e.code === 'EPERM' ? t('claude.mdReadOnly') : e.message }));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async function waitFor(pred, ms) {
|
|
528
|
+
const end = Date.now() + ms;
|
|
529
|
+
while (Date.now() < end) {
|
|
530
|
+
if (await pred()) return true;
|
|
531
|
+
await sleep(150);
|
|
532
|
+
}
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function waitForService(P, cfg, ms = 8000) {
|
|
537
|
+
return waitFor(async () => {
|
|
538
|
+
const st = await adminRequest(P.socket, { cmd: 'status' }, 1000);
|
|
539
|
+
return !!st?.ok && st.port === cfg.port;
|
|
540
|
+
}, ms);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Wait until the service answering is the one systemd runs (not a copy Claude Code started). */
|
|
544
|
+
async function waitForManaged(P, cfg, runFn, ms = 12_000) {
|
|
545
|
+
return waitFor(async () => {
|
|
546
|
+
const st = await adminRequest(P.socket, { cmd: 'status' }, 1000);
|
|
547
|
+
return !!st?.ok && st.port === cfg.port && st.pid === sys.serviceMainPid(runFn);
|
|
548
|
+
}, ms);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Make sure a service of this version runs on the configured port. Returns true when one answers. */
|
|
552
|
+
async function ensureRunning({ t, out, runFn, env, P, cfg, version, self, managed, startDaemon }) {
|
|
553
|
+
let st = await adminRequest(P.socket, { cmd: 'status' });
|
|
554
|
+
if (st?.ok && st.version === version && st.port === cfg.port) {
|
|
555
|
+
out.line(t('check.service.up', { version: st.version, pid: st.pid }));
|
|
556
|
+
return true;
|
|
557
|
+
}
|
|
558
|
+
const restarting = !!st?.ok;
|
|
559
|
+
if (restarting && managed) runFn('systemctl', ['--user', 'restart', sys.UNIT_NAME]);
|
|
560
|
+
else if (restarting && sys.serviceActive(runFn)) {
|
|
561
|
+
// A service unit setup didn't write (or wasn't allowed to replace) runs it: don't fight it.
|
|
562
|
+
out.line(t('check.service.up', { version: st.version, pid: st.pid }));
|
|
563
|
+
if (st.version !== version) out.line(t('check.service.old', { running: st.version, version, how: 'systemctl --user restart cctether' }));
|
|
564
|
+
if (st.port !== cfg.port) out.line(t('check.service.port', { running: st.port, port: cfg.port, how: 'systemctl --user restart cctether' }));
|
|
565
|
+
return true;
|
|
566
|
+
} else if (restarting) {
|
|
567
|
+
await adminRequest(P.socket, { cmd: 'stop' });
|
|
568
|
+
await waitFor(async () => !(await adminRequest(P.socket, { cmd: 'status' }, 500))?.ok, 5000);
|
|
569
|
+
startDaemon(P, self.cliPath, env);
|
|
570
|
+
} else if (!managed) startDaemon(P, self.cliPath, env);
|
|
571
|
+
const up = await waitForService(P, cfg);
|
|
572
|
+
st = up ? await adminRequest(P.socket, { cmd: 'status' }) : null;
|
|
573
|
+
if (!st?.ok) {
|
|
574
|
+
out.line(t('check.startFailed'));
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
out.line(t(restarting ? 'check.restarted' : 'check.started', { version: st.version }));
|
|
578
|
+
if (st.version !== version) out.line(t('check.service.old', { running: st.version, version, how: 'systemctl --user restart cctether' }));
|
|
579
|
+
return true;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Try the local address and, if there is one, the public address. */
|
|
583
|
+
export async function checkUrls({ t, out, cfg, publicUrl }) {
|
|
584
|
+
const extensionId = cfg.extensionIds[0];
|
|
585
|
+
const local = localUrl(cfg);
|
|
586
|
+
const results = { localOk: false, publicOk: false, publicReason: null };
|
|
587
|
+
const r1 = await checkAddress({ url: local, key: cfg.key, extensionId, timeoutMs: 5000 });
|
|
588
|
+
results.localOk = r1.ok;
|
|
589
|
+
out.line(r1.ok ? t('check.ok.local', { url: local })
|
|
590
|
+
: t('check.fail', { url: local, why: explainCheck(t, r1, { url: local, port: cfg.port, extensionId, local: true }) }));
|
|
591
|
+
if (publicUrl) {
|
|
592
|
+
const r2 = await checkAddress({ url: publicUrl, key: cfg.key, extensionId, timeoutMs: 10_000 });
|
|
593
|
+
results.publicOk = r2.ok;
|
|
594
|
+
results.publicReason = r2.ok ? null : r2.reason;
|
|
595
|
+
out.line(r2.ok ? t('check.ok.public', { url: publicUrl })
|
|
596
|
+
: t('check.fail', { url: publicUrl, why: explainCheck(t, r2, { url: publicUrl, port: cfg.port, extensionId, local: false }) }));
|
|
597
|
+
}
|
|
598
|
+
return results;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** `cctether check` on its own. Returns the exit code: 0 all good, 1 a check failed, 3 not running. */
|
|
602
|
+
export async function runCheck({ dir, version, write, color, lang, env = process.env, runFn = sys.run }) {
|
|
603
|
+
const style = createStyle(!!color);
|
|
604
|
+
const t = createText(pickLanguage(lang, env), style);
|
|
605
|
+
const out = createPrinter(write, style);
|
|
606
|
+
const P = paths(dir, env);
|
|
607
|
+
out.title(t('check.title'));
|
|
608
|
+
out.blank();
|
|
609
|
+
const cfg = loadConfig(dir);
|
|
610
|
+
if (!cfg) {
|
|
611
|
+
out.line(t('check.notSetUp'));
|
|
612
|
+
out.blank();
|
|
613
|
+
return 3;
|
|
614
|
+
}
|
|
615
|
+
const hasUnit = existsSync(sys.unitFile(env));
|
|
616
|
+
const st = await adminRequest(P.socket, { cmd: 'status' });
|
|
617
|
+
if (!st?.ok) {
|
|
618
|
+
out.line(t('check.service.down', { how: hasUnit ? 'systemctl --user start cctether' : 'cctether daemon' }));
|
|
619
|
+
out.blank();
|
|
620
|
+
return 3;
|
|
621
|
+
}
|
|
622
|
+
out.line(t('check.service.up', { version: st.version, pid: st.pid }));
|
|
623
|
+
const how = hasUnit && sys.serviceActive(runFn) ? 'systemctl --user restart cctether' : 'cctether stop';
|
|
624
|
+
if (st.version !== version) out.line(t('check.service.old', { running: st.version, version, how }));
|
|
625
|
+
if (st.port !== cfg.port) out.line(t('check.service.port', { running: st.port, port: cfg.port, how }));
|
|
626
|
+
const publicUrl = cfg.publicUrl && !isLocalUrl(cfg.publicUrl) ? cfg.publicUrl : null;
|
|
627
|
+
const r = await checkUrls({ t, out, cfg, publicUrl });
|
|
628
|
+
if (publicUrl && !r.publicOk && r.localOk && HAIRPIN_REASONS.has(r.publicReason)) out.line(style.dim(t('check.hairpin')));
|
|
629
|
+
const b = st.browser;
|
|
630
|
+
if (b?.connected) out.line(t('check.browser.connected', { browser: b.info?.browser ?? '?', extension: b.info?.extension ?? '?' }));
|
|
631
|
+
else out.line(t('check.browser.none'));
|
|
632
|
+
out.blank();
|
|
633
|
+
return r.localOk && (!publicUrl || r.publicOk) ? 0 : 1;
|
|
634
|
+
}
|