cctether 0.0.0-stage → 0.3.0
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 +158 -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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 guchaorui
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cctether
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Let Claude Code (or any MCP client) use your real Chrome browser over your own connection — no third-party relay.
|
|
4
|
+
|
|
5
|
+
This package is the service that runs on the computer with Claude Code. It works together with the **cctether browser extension**, which connects out to it and does the work in the browser: reading pages, screenshots, clicking and typing, console and network inspection.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
On the computer that runs Claude Code (Node.js 22 or newer):
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
npx cctether@latest setup
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Setup installs cctether, makes a key, asks how your browser will reach this computer (same computer, SSH tunnel, or HTTPS with your own domain), can install a background service, adds cctether to Claude Code, checks the connection, and prints a connection code. Then install the extension and paste the code into its settings.
|
|
16
|
+
|
|
17
|
+
Full documentation, the extension, and how each connection method works: **https://github.com/guchaorui/cctether**
|
|
18
|
+
|
|
19
|
+
## Commands
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
cctether setup Set everything up, step by step
|
|
23
|
+
cctether pair Show the connection code again
|
|
24
|
+
cctether check Test that the extension's address reaches this service
|
|
25
|
+
cctether status Is the service running? Is a browser connected?
|
|
26
|
+
cctether rotate Make a new key (the old connection code stops working)
|
|
27
|
+
cctether help All commands and options
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Security
|
|
31
|
+
|
|
32
|
+
The extension and the service authenticate each other with a shared 256-bit key and encrypt every message end to end; Claude can only use tabs in the browser's cctether tab group. See [SECURITY.md](https://github.com/guchaorui/cctether/blob/main/SECURITY.md).
|
|
33
|
+
|
|
34
|
+
## License
|
|
35
|
+
|
|
36
|
+
MIT
|
package/bin/cctether.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../src/cli.js';
|
|
3
|
+
|
|
4
|
+
main(process.argv.slice(2)).then(
|
|
5
|
+
(code) => { if (typeof code === 'number') process.exitCode = code; },
|
|
6
|
+
(e) => { process.stderr.write(`cctether: ${e.stack ?? e.message}\n`); process.exitCode = 1; },
|
|
7
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cctether",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Let Claude Code use your browser over your own connection — no third-party relay.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"claude-code",
|
|
7
|
+
"claude",
|
|
8
|
+
"mcp",
|
|
9
|
+
"mcp-server",
|
|
10
|
+
"browser",
|
|
11
|
+
"chrome",
|
|
12
|
+
"chrome-extension",
|
|
13
|
+
"devtools",
|
|
14
|
+
"automation"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://github.com/guchaorui/cctether#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/guchaorui/cctether/issues"
|
|
19
|
+
},
|
|
20
|
+
"author": "guchaorui",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"bin": {
|
|
24
|
+
"cctether": "bin/cctether.js"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"bin",
|
|
28
|
+
"src"
|
|
29
|
+
],
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=22"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"test": "node --test test/*.test.js"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/guchaorui/cctether.git",
|
|
39
|
+
"directory": "server"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"ws": "8.22.1"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/check.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// `cctether check` (SPEC §8.2): connect to an address the way the extension does and see whether
|
|
2
|
+
// it leads to *this* cctether service. Only the server's half of the handshake is used: we verify
|
|
3
|
+
// its proof with our key and hang up without sending ours, so a connected browser isn't replaced
|
|
4
|
+
// and the attempt doesn't count as a failed login.
|
|
5
|
+
|
|
6
|
+
import { WebSocket } from 'ws';
|
|
7
|
+
import { PROTO, LABEL_SERVER, b64u, fromB64u, newNonce, proof, proofMatches, CLOSE } from './protocol.js';
|
|
8
|
+
|
|
9
|
+
const TLS_CODES = /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY|ERR_TLS/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {object} o
|
|
13
|
+
* @param {string} o.url ws:// or wss:// address, as in the connection code
|
|
14
|
+
* @param {Buffer} o.key this service's key
|
|
15
|
+
* @param {string} o.extensionId an allowed extension ID (sent as the Origin)
|
|
16
|
+
* @param {number} [o.timeoutMs]
|
|
17
|
+
* @returns {Promise<{ ok: true } | { ok: false, reason: string, status?: number, detail?: string }>}
|
|
18
|
+
* reason: dns | refused | timeout | tls | http | wrong_server | not_cctether | origin_rejected |
|
|
19
|
+
* rate_limited | update_server | update_extension | closed | error
|
|
20
|
+
*/
|
|
21
|
+
export function checkAddress({ url, key, extensionId, timeoutMs = 8000 }) {
|
|
22
|
+
return new Promise((resolve) => {
|
|
23
|
+
const cn = newNonce();
|
|
24
|
+
let ws;
|
|
25
|
+
let settled = false;
|
|
26
|
+
const done = (r) => {
|
|
27
|
+
if (settled) return;
|
|
28
|
+
settled = true;
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
try { ws?.terminate(); } catch {}
|
|
31
|
+
resolve(r);
|
|
32
|
+
};
|
|
33
|
+
const timer = setTimeout(() => done({ ok: false, reason: 'timeout' }), timeoutMs);
|
|
34
|
+
try {
|
|
35
|
+
ws = new WebSocket(url, {
|
|
36
|
+
origin: `chrome-extension://${extensionId}`,
|
|
37
|
+
handshakeTimeout: timeoutMs,
|
|
38
|
+
maxPayload: 64 * 1024,
|
|
39
|
+
perMessageDeflate: false,
|
|
40
|
+
followRedirects: false,
|
|
41
|
+
});
|
|
42
|
+
} catch (e) {
|
|
43
|
+
return done({ ok: false, reason: 'error', detail: e.message });
|
|
44
|
+
}
|
|
45
|
+
ws.on('unexpected-response', (_req, res) => {
|
|
46
|
+
done({ ok: false, reason: 'http', status: res.statusCode });
|
|
47
|
+
res.destroy();
|
|
48
|
+
});
|
|
49
|
+
ws.on('error', (e) => done(classifyError(e)));
|
|
50
|
+
ws.on('open', () => {
|
|
51
|
+
ws.send(JSON.stringify({ t: 'hello', proto: PROTO, cn: b64u(cn) }));
|
|
52
|
+
});
|
|
53
|
+
ws.on('message', (data, isBinary) => {
|
|
54
|
+
if (isBinary) return done({ ok: false, reason: 'not_cctether' });
|
|
55
|
+
let m;
|
|
56
|
+
try { m = JSON.parse(data.toString('utf8')); } catch { return done({ ok: false, reason: 'not_cctether' }); }
|
|
57
|
+
if (m?.t === 'error') {
|
|
58
|
+
const known = ['origin_rejected', 'rate_limited', 'update_server', 'update_extension'];
|
|
59
|
+
return done({ ok: false, reason: known.includes(m.code) ? m.code : 'not_cctether' });
|
|
60
|
+
}
|
|
61
|
+
if (m?.t !== 'challenge') return done({ ok: false, reason: 'not_cctether' });
|
|
62
|
+
if (m.proto !== PROTO) {
|
|
63
|
+
return done({ ok: false, reason: typeof m.proto === 'number' && m.proto > PROTO ? 'update_extension' : 'update_server' });
|
|
64
|
+
}
|
|
65
|
+
const sn = fromB64u(m.sn, 32);
|
|
66
|
+
const sp = fromB64u(m.sp, 32);
|
|
67
|
+
if (!sn || !sp) return done({ ok: false, reason: 'not_cctether' });
|
|
68
|
+
done(proofMatches(proof(key, LABEL_SERVER, cn, sn), sp) ? { ok: true } : { ok: false, reason: 'wrong_server' });
|
|
69
|
+
});
|
|
70
|
+
ws.on('close', (code) => {
|
|
71
|
+
if (code === CLOSE.originRejected) return done({ ok: false, reason: 'origin_rejected' });
|
|
72
|
+
done({ ok: false, reason: 'closed', detail: code ? `code ${code}` : '' });
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function classifyError(e) {
|
|
78
|
+
const code = e?.code ?? '';
|
|
79
|
+
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EAI_NONAME') return { ok: false, reason: 'dns' };
|
|
80
|
+
if (code === 'ECONNREFUSED') return { ok: false, reason: 'refused' };
|
|
81
|
+
if (code === 'ETIMEDOUT' || code === 'EHOSTUNREACH' || code === 'ENETUNREACH' || /timed out/i.test(e?.message ?? '')) {
|
|
82
|
+
return { ok: false, reason: 'timeout' };
|
|
83
|
+
}
|
|
84
|
+
if (TLS_CODES.test(code)) return { ok: false, reason: 'tls', detail: code };
|
|
85
|
+
if (code === 'ECONNRESET' || code === 'EPIPE') return { ok: false, reason: 'closed', detail: code };
|
|
86
|
+
return { ok: false, reason: 'error', detail: (e?.message ?? String(e)).slice(0, 200) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Turn a failed checkAddress() result into a sentence, with the text function from text.js. */
|
|
90
|
+
export function explainCheck(t, r, { url, port, extensionId, local }) {
|
|
91
|
+
const u = new URL(url);
|
|
92
|
+
const host = u.hostname;
|
|
93
|
+
const upstreamPort = u.port || (u.protocol === 'wss:' ? 443 : 80);
|
|
94
|
+
switch (r.reason) {
|
|
95
|
+
case 'dns': return t('check.why.dns', { host });
|
|
96
|
+
case 'refused': return t(local ? 'check.why.refusedLocal' : 'check.why.refused', { host, port: upstreamPort });
|
|
97
|
+
case 'timeout': return t('check.why.timeout', { port: upstreamPort });
|
|
98
|
+
case 'tls': return t('check.why.tls', { detail: r.detail ?? 'TLS' });
|
|
99
|
+
case 'http':
|
|
100
|
+
return t(r.status === 502 || r.status === 503 || r.status === 504 ? 'check.why.http502' : 'check.why.http', {
|
|
101
|
+
status: r.status, path: u.pathname, port,
|
|
102
|
+
});
|
|
103
|
+
case 'origin_rejected': return t('check.why.origin_rejected', { id: extensionId });
|
|
104
|
+
case 'closed': return t('check.why.closed', { detail: r.detail ? ` (${r.detail})` : '' });
|
|
105
|
+
case 'error': return t('check.why.error', { detail: r.detail ?? '' });
|
|
106
|
+
default: return t(`check.why.${r.reason}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// Command line: cctether <command> [options]
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { configDir, paths, loadConfig, saveConfig, initConfig, newKey, serverUrl, localUrl, isValidServerUrl, trustProxy, ConfigError } from './config.js';
|
|
6
|
+
import { encodePairingCode, keyFingerprint } from './pairing.js';
|
|
7
|
+
import { adminRequest } from './control.js';
|
|
8
|
+
import { createLogger } from './log.js';
|
|
9
|
+
|
|
10
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
11
|
+
const CLI_PATH = fileURLToPath(new URL('../bin/cctether.js', import.meta.url));
|
|
12
|
+
|
|
13
|
+
const HELP = `cctether ${VERSION} — let Claude Code use your browser over your own connection.
|
|
14
|
+
|
|
15
|
+
Usage: cctether <command> [options]
|
|
16
|
+
|
|
17
|
+
Commands:
|
|
18
|
+
setup Set everything up, step by step (start here)
|
|
19
|
+
init [--port N] [--url URL] Create the key and settings (done automatically on first use)
|
|
20
|
+
pair [--url URL] Show the connection code to paste into the browser extension
|
|
21
|
+
check Test that the extension's address reaches this service
|
|
22
|
+
status [--json] Is the service running? Is a browser connected?
|
|
23
|
+
rotate Make a new key; the old connection code stops working at once
|
|
24
|
+
daemon [--takeover] Run the service in the foreground. With --takeover (the systemd service
|
|
25
|
+
uses it), replace a copy that Claude Code started instead of exiting
|
|
26
|
+
stop Stop the running service
|
|
27
|
+
mcp MCP server on stdin/stdout (Claude Code runs this)
|
|
28
|
+
version Print the version
|
|
29
|
+
|
|
30
|
+
Options:
|
|
31
|
+
--url URL The address the extension should connect to, e.g. wss://browser.example.com/cctether
|
|
32
|
+
(saved for next time). Without it: ws://127.0.0.1:<port>/cctether, which works when
|
|
33
|
+
the browser is on this computer or reaches it through an SSH tunnel.
|
|
34
|
+
--port N Port of the local service (default 27182)
|
|
35
|
+
|
|
36
|
+
Setup options (to run it from a script, give --yes and how the browser connects):
|
|
37
|
+
--yes, -y Don't ask; take the defaults
|
|
38
|
+
--mode local|ssh|https Browser on this computer / through an SSH tunnel / over HTTPS
|
|
39
|
+
--no-install --no-service --no-mcp Skip installing, the background service, or adding to Claude Code
|
|
40
|
+
--claude-md, --no-claude-md Do / don't tell Claude (in ~/.claude/CLAUDE.md) to use cctether by itself
|
|
41
|
+
for every browser task (asked when run in a terminal)
|
|
42
|
+
--lang en|zh Language of setup and check (default: from LANG)
|
|
43
|
+
|
|
44
|
+
Settings live in ${'$'}CCTETHER_HOME, else ${'$'}XDG_CONFIG_HOME/cctether, else ~/.config/cctether.
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
function parseArgs(argv) {
|
|
48
|
+
const opts = {};
|
|
49
|
+
const rest = [];
|
|
50
|
+
for (let i = 0; i < argv.length; i++) {
|
|
51
|
+
const a = argv[i];
|
|
52
|
+
if (a === '--json' || a === '-h' || a === '--help' || a === '--takeover') opts[a.replace(/^-+/, '')] = true;
|
|
53
|
+
else if (a === '--yes' || a === '-y') opts.yes = true;
|
|
54
|
+
else if (a === '--no-install' || a === '--no-service' || a === '--no-mcp') opts[a.slice(5)] = false;
|
|
55
|
+
else if (a === '--claude-md' || a === '--no-claude-md') opts.claudeMd = a === '--claude-md';
|
|
56
|
+
else if (a === '--url' || a === '--port' || a === '--mode' || a === '--lang') {
|
|
57
|
+
if (i + 1 >= argv.length) throw new ConfigError(`${a} needs a value`);
|
|
58
|
+
opts[a.slice(2)] = argv[++i];
|
|
59
|
+
} else if (/^--(url|port|mode|lang)=/.test(a)) {
|
|
60
|
+
const i2 = a.indexOf('=');
|
|
61
|
+
opts[a.slice(2, i2)] = a.slice(i2 + 1);
|
|
62
|
+
} else if (a.startsWith('-')) throw new ConfigError(`Unknown option ${a}`);
|
|
63
|
+
else rest.push(a);
|
|
64
|
+
}
|
|
65
|
+
if (opts.port !== undefined) {
|
|
66
|
+
const p = Number(opts.port);
|
|
67
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) throw new ConfigError('--port must be a number from 1 to 65535');
|
|
68
|
+
opts.port = p;
|
|
69
|
+
}
|
|
70
|
+
if (opts.mode !== undefined && !['local', 'ssh', 'https'].includes(opts.mode)) {
|
|
71
|
+
throw new ConfigError('--mode must be local, ssh or https');
|
|
72
|
+
}
|
|
73
|
+
if (opts.lang !== undefined && !['en', 'zh'].includes(opts.lang)) throw new ConfigError('--lang must be en or zh');
|
|
74
|
+
// setup also accepts a bare domain for --url and fixes it up itself
|
|
75
|
+
if (opts.url !== undefined && !isValidServerUrl(opts.url) && !(rest[0] === 'setup' && opts.mode !== 'local')) {
|
|
76
|
+
throw new ConfigError('--url must start with wss:// (or ws:// for 127.0.0.1 / localhost), with no query string, e.g. wss://browser.example.com/cctether');
|
|
77
|
+
}
|
|
78
|
+
return { opts, rest };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const out = (s = '') => process.stdout.write(s + '\n');
|
|
82
|
+
const err = (s = '') => process.stderr.write(s + '\n');
|
|
83
|
+
|
|
84
|
+
async function notifyDaemon(P) {
|
|
85
|
+
const r = await adminRequest(P.socket, { cmd: 'reload' });
|
|
86
|
+
return r?.ok ? r : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function main(argv) {
|
|
90
|
+
const [major] = process.versions.node.split('.').map(Number);
|
|
91
|
+
if (major < 22) {
|
|
92
|
+
err(`cctether needs Node.js 22 or newer (this is ${process.version}).`);
|
|
93
|
+
return 1;
|
|
94
|
+
}
|
|
95
|
+
let parsed;
|
|
96
|
+
try {
|
|
97
|
+
parsed = parseArgs(argv);
|
|
98
|
+
} catch (e) {
|
|
99
|
+
err(e.message);
|
|
100
|
+
return 2;
|
|
101
|
+
}
|
|
102
|
+
const { opts, rest } = parsed;
|
|
103
|
+
const cmd = rest[0] ?? (opts.h || opts.help ? 'help' : undefined);
|
|
104
|
+
if (opts.takeover && cmd !== 'daemon') {
|
|
105
|
+
err('--takeover only goes with `cctether daemon`.');
|
|
106
|
+
return 2;
|
|
107
|
+
}
|
|
108
|
+
// Claude Code sets CLAUDECODE=1 for the commands it runs (also for `! command` lines): anything
|
|
109
|
+
// printed there ends up in the conversation, so the connection code must not be printed.
|
|
110
|
+
const insideClaude = !!process.env.CLAUDECODE;
|
|
111
|
+
const dir = configDir();
|
|
112
|
+
const P = paths(dir);
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
switch (cmd) {
|
|
116
|
+
case 'init': {
|
|
117
|
+
const { cfg, created } = initConfig(dir, { port: opts.port, publicUrl: opts.url });
|
|
118
|
+
if (!created) {
|
|
119
|
+
let changed = false;
|
|
120
|
+
if (opts.port !== undefined && opts.port !== cfg.port) { cfg.port = opts.port; changed = true; }
|
|
121
|
+
if (opts.url !== undefined && opts.url !== cfg.publicUrl) { cfg.publicUrl = opts.url; changed = true; }
|
|
122
|
+
if (changed) {
|
|
123
|
+
saveConfig(dir, cfg);
|
|
124
|
+
out(`Updated ${P.config}.`);
|
|
125
|
+
if (await notifyDaemon(P)) out('The running service picked up the change (a new port needs a restart).');
|
|
126
|
+
} else out(`Already set up: ${P.config}`);
|
|
127
|
+
} else out(`Created ${P.config} (key fingerprint ${keyFingerprint(cfg.key)}).`);
|
|
128
|
+
out('Next: run `cctether pair` and paste the code into the browser extension.');
|
|
129
|
+
return 0;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
case 'pair': {
|
|
133
|
+
if (insideClaude) {
|
|
134
|
+
err('The connection code contains the secret key, so cctether doesn’t print it inside Claude Code:');
|
|
135
|
+
err('it would end up in the conversation. Run `cctether pair` in a terminal of your own instead.');
|
|
136
|
+
return 2;
|
|
137
|
+
}
|
|
138
|
+
let { cfg } = initConfig(dir, { port: opts.port, publicUrl: opts.url });
|
|
139
|
+
if (opts.url !== undefined && opts.url !== cfg.publicUrl) {
|
|
140
|
+
cfg.publicUrl = opts.url;
|
|
141
|
+
saveConfig(dir, cfg);
|
|
142
|
+
await notifyDaemon(P);
|
|
143
|
+
}
|
|
144
|
+
const url = serverUrl(cfg);
|
|
145
|
+
err('Connection code — keep it secret: anyone who has it can control this browser connection.');
|
|
146
|
+
err('');
|
|
147
|
+
out(encodePairingCode(url, cfg.key));
|
|
148
|
+
err('');
|
|
149
|
+
err('Paste it into the cctether extension: click its toolbar icon → Settings → Connection code.');
|
|
150
|
+
err(`The extension will connect to ${url}`);
|
|
151
|
+
err(`Key fingerprint (shown in the extension after pairing): ${keyFingerprint(cfg.key)}`);
|
|
152
|
+
if (!cfg.publicUrl) {
|
|
153
|
+
err('');
|
|
154
|
+
err('This address works when Chrome runs on this computer, or reaches it through an SSH tunnel');
|
|
155
|
+
err(`(ssh -L ${cfg.port}:127.0.0.1:${cfg.port} ...). For an HTTPS address: cctether pair --url wss://your.domain/cctether`);
|
|
156
|
+
}
|
|
157
|
+
err('If the code leaks: run `cctether rotate`, then pair again.');
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
case 'status': {
|
|
162
|
+
const cfg = loadConfig(dir);
|
|
163
|
+
const st = await adminRequest(P.socket, { cmd: 'status' });
|
|
164
|
+
if (opts.json) {
|
|
165
|
+
out(JSON.stringify({ configured: !!cfg, running: !!st?.ok, ...(st?.ok ? st : {}) }, null, 2));
|
|
166
|
+
return st?.ok ? 0 : 3;
|
|
167
|
+
}
|
|
168
|
+
if (!cfg) {
|
|
169
|
+
out('Not set up yet. Run `cctether pair`.');
|
|
170
|
+
return 3;
|
|
171
|
+
}
|
|
172
|
+
out(`Settings: ${P.config}`);
|
|
173
|
+
out(`Address: ${serverUrl(cfg)}${cfg.publicUrl ? ` (local ${localUrl(cfg)})` : ''}`);
|
|
174
|
+
out(`Key: fingerprint ${keyFingerprint(cfg.key)}`);
|
|
175
|
+
out(`Proxy: ${trustProxy(cfg) ? 'behind a local reverse proxy (client addresses from X-Forwarded-For)' : 'none (client addresses from the connection)'}`);
|
|
176
|
+
if (!st?.ok) {
|
|
177
|
+
out('Service: not running (it starts automatically when Claude Code uses cctether)');
|
|
178
|
+
return 3;
|
|
179
|
+
}
|
|
180
|
+
out(`Service: running, pid ${st.pid}, version ${st.version}, since ${new Date(st.startedAt).toLocaleString()}`);
|
|
181
|
+
if (st.browser.connected) {
|
|
182
|
+
const i = st.browser.info ?? {};
|
|
183
|
+
out(`Browser: connected since ${new Date(st.browser.since).toLocaleString()} from ${st.browser.ip}`);
|
|
184
|
+
if (i.browser || i.extension) out(` ${i.browser ?? 'unknown browser'}, extension ${i.extension ?? '?'}`);
|
|
185
|
+
} else out('Browser: not connected');
|
|
186
|
+
out(`MCP clients: ${st.mcpSessions}`);
|
|
187
|
+
return 0;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
case 'rotate': {
|
|
191
|
+
const existing = loadConfig(dir);
|
|
192
|
+
const { cfg } = existing ? { cfg: existing } : initConfig(dir);
|
|
193
|
+
cfg.key = newKey();
|
|
194
|
+
saveConfig(dir, cfg);
|
|
195
|
+
const r = await notifyDaemon(P);
|
|
196
|
+
out(`New key made (fingerprint ${keyFingerprint(cfg.key)}). The old connection code no longer works${r ? '; the browser was disconnected' : ''}.`);
|
|
197
|
+
out('Run `cctether pair` and paste the new code into the extension.');
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
case 'setup': {
|
|
202
|
+
const { runSetup } = await import('./setup.js');
|
|
203
|
+
const interactive = !!(process.stdin.isTTY && process.stdout.isTTY);
|
|
204
|
+
const { createInterface } = await import('node:readline/promises');
|
|
205
|
+
// One readline per question: while it's open the terminal is in raw mode, and Ctrl-C
|
|
206
|
+
// wouldn't reach a long `npm install` or systemctl run in between.
|
|
207
|
+
const ask = async (prompt) => {
|
|
208
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
209
|
+
rl.on('SIGINT', () => { out(''); process.exit(130); });
|
|
210
|
+
try {
|
|
211
|
+
return await rl.question(prompt);
|
|
212
|
+
} finally {
|
|
213
|
+
rl.close();
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
return runSetup({
|
|
217
|
+
dir, version: VERSION, cliPath: CLI_PATH, opts, write: out, ask, interactive,
|
|
218
|
+
// The code is a secret: only show it on a terminal, not in logs or another program's output.
|
|
219
|
+
showCode: !!process.stdout.isTTY && !insideClaude,
|
|
220
|
+
color: interactive && !process.env.NO_COLOR,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
case 'check': {
|
|
225
|
+
const { runCheck } = await import('./setup.js');
|
|
226
|
+
return runCheck({ dir, version: VERSION, write: out, lang: opts.lang, color: !!process.stdout.isTTY && !process.env.NO_COLOR });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
case 'daemon': {
|
|
230
|
+
const log = createLogger();
|
|
231
|
+
const { runDaemon } = await import('./daemon.js');
|
|
232
|
+
// --takeover: only the systemd service passes it (see renderUnit). Not an environment check:
|
|
233
|
+
// INVOCATION_ID, for one, is inherited by everything a systemd service starts.
|
|
234
|
+
const r = await runDaemon({ dir, version: VERSION, log, port: opts.port, takeOver: !!opts.takeover });
|
|
235
|
+
if (r.alreadyRunning) return 0;
|
|
236
|
+
return new Promise(() => {}); // runs until a signal
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
case 'stop': {
|
|
240
|
+
const r = await adminRequest(P.socket, { cmd: 'stop' });
|
|
241
|
+
out(r?.ok ? 'Stopped.' : 'Not running.');
|
|
242
|
+
return 0;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
case 'mcp': {
|
|
246
|
+
const { runShim } = await import('./shim.js');
|
|
247
|
+
await runShim({ dir, version: VERSION, cliPath: CLI_PATH });
|
|
248
|
+
return new Promise(() => {}); // runs until stdin closes
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
case 'version':
|
|
252
|
+
case '--version':
|
|
253
|
+
out(VERSION);
|
|
254
|
+
return 0;
|
|
255
|
+
|
|
256
|
+
case 'help':
|
|
257
|
+
case undefined:
|
|
258
|
+
out(HELP);
|
|
259
|
+
return cmd ? 0 : 2;
|
|
260
|
+
|
|
261
|
+
default:
|
|
262
|
+
err(`Unknown command: ${cmd}\n`);
|
|
263
|
+
err(HELP);
|
|
264
|
+
return 2;
|
|
265
|
+
}
|
|
266
|
+
} catch (e) {
|
|
267
|
+
if (e instanceof ConfigError) {
|
|
268
|
+
err(e.message);
|
|
269
|
+
return 2;
|
|
270
|
+
}
|
|
271
|
+
throw e;
|
|
272
|
+
}
|
|
273
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Configuration directory and config.json (SPEC §4.5).
|
|
2
|
+
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync, renameSync, chmodSync, statSync, existsSync } from 'node:fs';
|
|
4
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_PORT = 27182;
|
|
9
|
+
export const WS_PATH = '/cctether';
|
|
10
|
+
/** Extension IDs accepted by default: the unpacked build (fixed by the manifest key). */
|
|
11
|
+
export const DEFAULT_EXTENSION_IDS = ['nfebjhhcnoilmfjacolkofphfekkjioh'];
|
|
12
|
+
|
|
13
|
+
export function configDir(env = process.env) {
|
|
14
|
+
if (env.CCTETHER_HOME) return env.CCTETHER_HOME;
|
|
15
|
+
if (env.XDG_CONFIG_HOME) return join(env.XDG_CONFIG_HOME, 'cctether');
|
|
16
|
+
return join(homedir(), '.config', 'cctether');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Unix socket paths are limited to 104 (macOS) / 108 (Linux) bytes. */
|
|
20
|
+
const MAX_SOCKET_PATH = 100;
|
|
21
|
+
|
|
22
|
+
function isPrivateDir(d) {
|
|
23
|
+
try {
|
|
24
|
+
const st = statSync(d);
|
|
25
|
+
return st.isDirectory() && st.uid === process.getuid?.() && (st.mode & 0o077) === 0;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The control socket lives in the config directory. If that path is too long for a Unix socket,
|
|
33
|
+
* use the per-user runtime directory instead (private by definition, but checked anyway).
|
|
34
|
+
*/
|
|
35
|
+
export function socketPath(dir, env = process.env) {
|
|
36
|
+
const p = join(dir, 'control.sock');
|
|
37
|
+
if (Buffer.byteLength(p) <= MAX_SOCKET_PATH) return p;
|
|
38
|
+
const rt = env.XDG_RUNTIME_DIR;
|
|
39
|
+
if (rt && isPrivateDir(rt)) {
|
|
40
|
+
const alt = join(rt, `cctether-${createHash('sha256').update(dir).digest('hex').slice(0, 16)}.sock`);
|
|
41
|
+
if (Buffer.byteLength(alt) <= MAX_SOCKET_PATH) return alt;
|
|
42
|
+
}
|
|
43
|
+
return p; // too long: startControl explains what to do
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const paths = (dir, env = process.env) => ({
|
|
47
|
+
dir,
|
|
48
|
+
config: join(dir, 'config.json'),
|
|
49
|
+
socket: socketPath(dir, env),
|
|
50
|
+
log: join(dir, 'daemon.log'),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
export class ConfigError extends Error {}
|
|
54
|
+
|
|
55
|
+
function ensureDir(dir) {
|
|
56
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
57
|
+
chmodSync(dir, 0o700);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function validate(raw) {
|
|
61
|
+
const cfg = {
|
|
62
|
+
key: Buffer.from(String(raw.key ?? ''), 'base64url'),
|
|
63
|
+
port: raw.port ?? DEFAULT_PORT,
|
|
64
|
+
publicUrl: raw.publicUrl ?? null,
|
|
65
|
+
extensionIds: raw.extensionIds ?? DEFAULT_EXTENSION_IDS,
|
|
66
|
+
trustProxySetting: raw.trustProxy ?? null,
|
|
67
|
+
};
|
|
68
|
+
if (cfg.trustProxySetting !== null && typeof cfg.trustProxySetting !== 'boolean') {
|
|
69
|
+
throw new ConfigError('config.json: "trustProxy" must be true, false or null.');
|
|
70
|
+
}
|
|
71
|
+
if (cfg.key.length !== 32) throw new ConfigError('config.json: "key" must be 32 bytes (base64url). Run `cctether rotate` to make a new one.');
|
|
72
|
+
if (!Number.isInteger(cfg.port) || cfg.port < 1 || cfg.port > 65535) throw new ConfigError('config.json: "port" must be 1-65535.');
|
|
73
|
+
if (cfg.publicUrl !== null && !isValidServerUrl(cfg.publicUrl)) {
|
|
74
|
+
throw new ConfigError('config.json: "publicUrl" must be a wss:// URL (or ws:// to 127.0.0.1 / localhost).');
|
|
75
|
+
}
|
|
76
|
+
if (!Array.isArray(cfg.extensionIds) || !cfg.extensionIds.every((id) => /^[a-p]{32}$/.test(id))) {
|
|
77
|
+
throw new ConfigError('config.json: "extensionIds" must be a list of 32-letter extension IDs.');
|
|
78
|
+
}
|
|
79
|
+
return cfg;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function isValidServerUrl(url) {
|
|
83
|
+
let u;
|
|
84
|
+
try { u = new URL(url); } catch { return false; }
|
|
85
|
+
if (u.username || u.password || u.hash || u.search) return false;
|
|
86
|
+
if (u.protocol === 'wss:') return true;
|
|
87
|
+
return u.protocol === 'ws:' && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Whether to take the client address from X-Forwarded-For when the peer is this computer.
|
|
92
|
+
* Default: yes when the public address is HTTPS on another host (that means a local reverse proxy
|
|
93
|
+
* such as Caddy or cloudflared is in front), otherwise no. "trustProxy" in config.json overrides.
|
|
94
|
+
*/
|
|
95
|
+
export function trustProxy(cfg) {
|
|
96
|
+
if (cfg.trustProxySetting !== null && cfg.trustProxySetting !== undefined) return cfg.trustProxySetting;
|
|
97
|
+
if (!cfg.publicUrl) return false;
|
|
98
|
+
const u = new URL(cfg.publicUrl);
|
|
99
|
+
return u.protocol === 'wss:' && !['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function localUrl(cfg) {
|
|
103
|
+
return `ws://127.0.0.1:${cfg.port}${WS_PATH}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The URL put into connection codes. */
|
|
107
|
+
export function serverUrl(cfg) {
|
|
108
|
+
return cfg.publicUrl ?? localUrl(cfg);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function loadConfig(dir) {
|
|
112
|
+
const p = paths(dir).config;
|
|
113
|
+
if (!existsSync(p)) return null;
|
|
114
|
+
const st = statSync(p);
|
|
115
|
+
if (st.mode & 0o077) chmodSync(p, 0o600); // never leave the key readable by others
|
|
116
|
+
let raw;
|
|
117
|
+
try {
|
|
118
|
+
raw = JSON.parse(readFileSync(p, 'utf8'));
|
|
119
|
+
} catch (e) {
|
|
120
|
+
throw new ConfigError(`Can't read ${p}: ${e.message}`);
|
|
121
|
+
}
|
|
122
|
+
return validate(raw);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function saveConfig(dir, cfg) {
|
|
126
|
+
ensureDir(dir);
|
|
127
|
+
const p = paths(dir).config;
|
|
128
|
+
const tmp = `${p}.${process.pid}.tmp`;
|
|
129
|
+
const data = {
|
|
130
|
+
version: 1,
|
|
131
|
+
key: cfg.key.toString('base64url'),
|
|
132
|
+
port: cfg.port,
|
|
133
|
+
publicUrl: cfg.publicUrl,
|
|
134
|
+
extensionIds: cfg.extensionIds,
|
|
135
|
+
trustProxy: cfg.trustProxySetting ?? null,
|
|
136
|
+
};
|
|
137
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
138
|
+
chmodSync(tmp, 0o600);
|
|
139
|
+
renameSync(tmp, p);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function newKey() {
|
|
143
|
+
return randomBytes(32);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Create config.json if it doesn't exist. Returns { cfg, created }. */
|
|
147
|
+
export function initConfig(dir, { port, publicUrl } = {}) {
|
|
148
|
+
const existing = loadConfig(dir);
|
|
149
|
+
if (existing) return { cfg: existing, created: false };
|
|
150
|
+
const cfg = validate({
|
|
151
|
+
key: newKey().toString('base64url'),
|
|
152
|
+
port: port ?? DEFAULT_PORT,
|
|
153
|
+
publicUrl: publicUrl ?? null,
|
|
154
|
+
extensionIds: DEFAULT_EXTENSION_IDS,
|
|
155
|
+
});
|
|
156
|
+
saveConfig(dir, cfg);
|
|
157
|
+
return { cfg, created: true };
|
|
158
|
+
}
|