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/control.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// The control entrance (D9): a Unix socket in the config directory (mode 700), so only this user
|
|
2
|
+
// can reach it. Each connection starts with one preamble line:
|
|
3
|
+
// {"cctether":1,"mode":"mcp"} then MCP JSON-RPC lines both ways
|
|
4
|
+
// {"cctether":1,"mode":"admin","cmd":"..."} one JSON reply line, then close
|
|
5
|
+
|
|
6
|
+
import { createServer, createConnection } from 'node:net';
|
|
7
|
+
import { existsSync, unlinkSync, chmodSync } from 'node:fs';
|
|
8
|
+
|
|
9
|
+
const PREAMBLE_MAX = 4096;
|
|
10
|
+
const PREAMBLE_TIMEOUT_MS = 5000;
|
|
11
|
+
|
|
12
|
+
export class AlreadyRunningError extends Error {}
|
|
13
|
+
|
|
14
|
+
/** Try to connect; resolves the socket or null. */
|
|
15
|
+
export function connectSocket(path, timeoutMs = 1000) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
const s = createConnection(path);
|
|
18
|
+
const t = setTimeout(() => { s.destroy(); resolve(null); }, timeoutMs);
|
|
19
|
+
s.once('connect', () => { clearTimeout(t); resolve(s); });
|
|
20
|
+
s.once('error', () => { clearTimeout(t); resolve(null); });
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Send an admin command. Resolves the reply object, or null if the daemon isn't reachable. */
|
|
25
|
+
export async function adminRequest(path, req, timeoutMs = 3000) {
|
|
26
|
+
const s = await connectSocket(path, timeoutMs);
|
|
27
|
+
if (!s) return null;
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
let buf = '';
|
|
30
|
+
const t = setTimeout(() => { s.destroy(); resolve(null); }, timeoutMs);
|
|
31
|
+
s.setEncoding('utf8');
|
|
32
|
+
s.on('data', (d) => {
|
|
33
|
+
buf += d;
|
|
34
|
+
const i = buf.indexOf('\n');
|
|
35
|
+
if (i >= 0) {
|
|
36
|
+
clearTimeout(t);
|
|
37
|
+
s.end();
|
|
38
|
+
try { resolve(JSON.parse(buf.slice(0, i))); } catch { resolve(null); }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
s.on('error', () => { clearTimeout(t); resolve(null); });
|
|
42
|
+
s.on('close', () => { clearTimeout(t); resolve(null); });
|
|
43
|
+
s.write(JSON.stringify({ cctether: 1, mode: 'admin', ...req }) + '\n');
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {object} o
|
|
49
|
+
* @param {string} o.socketPath
|
|
50
|
+
* @param {(socket: import('node:net').Socket, rest: string) => void} o.onMcp
|
|
51
|
+
* @param {(req: object) => Promise<object>} o.onAdmin
|
|
52
|
+
*/
|
|
53
|
+
export async function startControl({ socketPath, onMcp, onAdmin, log = () => {} }) {
|
|
54
|
+
if (existsSync(socketPath)) {
|
|
55
|
+
const s = await connectSocket(socketPath, 1000);
|
|
56
|
+
if (s) {
|
|
57
|
+
s.destroy();
|
|
58
|
+
throw new AlreadyRunningError('Another cctether service is already running.');
|
|
59
|
+
}
|
|
60
|
+
unlinkSync(socketPath); // stale socket from a crashed run
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const sockets = new Set();
|
|
64
|
+
const server = createServer((socket) => {
|
|
65
|
+
sockets.add(socket);
|
|
66
|
+
socket.on('close', () => sockets.delete(socket));
|
|
67
|
+
socket.setEncoding('utf8');
|
|
68
|
+
let buf = '';
|
|
69
|
+
const timer = setTimeout(() => socket.destroy(), PREAMBLE_TIMEOUT_MS);
|
|
70
|
+
const onData = (d) => {
|
|
71
|
+
buf += d;
|
|
72
|
+
const i = buf.indexOf('\n');
|
|
73
|
+
if (i < 0) {
|
|
74
|
+
if (buf.length > PREAMBLE_MAX) socket.destroy();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
socket.off('data', onData);
|
|
79
|
+
let pre;
|
|
80
|
+
try { pre = JSON.parse(buf.slice(0, i)); } catch { pre = null; }
|
|
81
|
+
const rest = buf.slice(i + 1);
|
|
82
|
+
if (pre?.cctether !== 1) return socket.destroy();
|
|
83
|
+
if (pre.mode === 'mcp') return onMcp(socket, rest);
|
|
84
|
+
if (pre.mode === 'admin') {
|
|
85
|
+
Promise.resolve(onAdmin(pre))
|
|
86
|
+
.catch((e) => ({ ok: false, error: e.message }))
|
|
87
|
+
.then((reply) => socket.end(JSON.stringify(reply) + '\n'));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
socket.destroy();
|
|
91
|
+
};
|
|
92
|
+
socket.on('data', onData);
|
|
93
|
+
socket.on('error', () => {});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
await new Promise((resolve, reject) => {
|
|
97
|
+
server.once('error', (e) => {
|
|
98
|
+
if (e.code === 'EINVAL' || e.code === 'ENAMETOOLONG') {
|
|
99
|
+
reject(new Error(`Can't create the control socket ${socketPath}: the path is too long. Set CCTETHER_HOME to a shorter folder, e.g. ~/.cctether.`));
|
|
100
|
+
} else reject(e);
|
|
101
|
+
});
|
|
102
|
+
server.listen(socketPath, () => { server.removeAllListeners('error'); resolve(); });
|
|
103
|
+
});
|
|
104
|
+
chmodSync(socketPath, 0o600);
|
|
105
|
+
log(`control socket ready`);
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
close: () => new Promise((r) => {
|
|
109
|
+
server.close(() => r());
|
|
110
|
+
for (const s of sockets) s.destroy();
|
|
111
|
+
try { unlinkSync(socketPath); } catch {}
|
|
112
|
+
}),
|
|
113
|
+
};
|
|
114
|
+
}
|
package/src/daemon.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// The resident service: extension entrance + control entrance (SPEC §4.1).
|
|
2
|
+
|
|
3
|
+
import { loadConfig, initConfig, paths, trustProxy, WS_PATH } from './config.js';
|
|
4
|
+
import { keyFingerprint } from './pairing.js';
|
|
5
|
+
import { Gateway } from './gateway.js';
|
|
6
|
+
import { startControl, adminRequest, AlreadyRunningError } from './control.js';
|
|
7
|
+
import { createMcpSession, lineSplitter } from './mcp.js';
|
|
8
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {object} o
|
|
12
|
+
* @param {boolean} [o.takeOver] the systemd service (`daemon --takeover`): if a copy started by Claude Code (`cctether mcp`)
|
|
13
|
+
* holds the port, stop it and take its place instead of exiting. Otherwise systemd would restart
|
|
14
|
+
* this service every few seconds until it gave up, and the stray copy would stay in charge.
|
|
15
|
+
*/
|
|
16
|
+
export async function runDaemon({ dir, version, log, port: portOverride, exitOnSignal = true, takeOver = false }) {
|
|
17
|
+
const P = paths(dir);
|
|
18
|
+
let { cfg, created } = initConfig(dir);
|
|
19
|
+
if (created) log(`created ${P.config} with a new key`);
|
|
20
|
+
const port = portOverride ?? cfg.port;
|
|
21
|
+
|
|
22
|
+
const gateway = new Gateway({ key: cfg.key, extensionIds: cfg.extensionIds, path: WS_PATH, version, log, trustProxy: trustProxy(cfg) });
|
|
23
|
+
let boundPort;
|
|
24
|
+
try {
|
|
25
|
+
boundPort = takeOver ? await listenTakingOver(gateway, port, P, log) : await gateway.listen(port);
|
|
26
|
+
} catch (e) {
|
|
27
|
+
if (e.code !== 'EADDRINUSE') throw e;
|
|
28
|
+
// Either another cctether service holds the port (fine) or some other program does.
|
|
29
|
+
for (let i = 0; i < 20; i++) {
|
|
30
|
+
const st = await adminRequest(P.socket, { cmd: 'status' }, 1000);
|
|
31
|
+
if (st?.ok) {
|
|
32
|
+
log(`already running (pid ${st.pid})`);
|
|
33
|
+
return { alreadyRunning: true };
|
|
34
|
+
}
|
|
35
|
+
await sleep(100);
|
|
36
|
+
}
|
|
37
|
+
throw new Error(`Port ${port} on 127.0.0.1 is used by another program. Set a different "port" in ${P.config}, then run \`cctether pair\` again and paste the new code into the extension.`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const startedAt = Date.now();
|
|
41
|
+
let sessions = 0;
|
|
42
|
+
let control;
|
|
43
|
+
try {
|
|
44
|
+
control = await startControl({
|
|
45
|
+
socketPath: P.socket,
|
|
46
|
+
log,
|
|
47
|
+
onMcp(socket, rest) {
|
|
48
|
+
sessions++;
|
|
49
|
+
const write = (line) => { if (!socket.destroyed) socket.write(line + '\n'); };
|
|
50
|
+
const session = createMcpSession({ write, browser: gateway, version, log });
|
|
51
|
+
const feed = lineSplitter((line) => {
|
|
52
|
+
session.handleLine(line).catch((e) => log(`mcp error: ${e.message}`));
|
|
53
|
+
}, { onOverflow: () => socket.destroy() });
|
|
54
|
+
socket.on('data', feed);
|
|
55
|
+
socket.on('close', () => { sessions--; });
|
|
56
|
+
if (rest) feed(rest);
|
|
57
|
+
},
|
|
58
|
+
async onAdmin(req) {
|
|
59
|
+
switch (req.cmd) {
|
|
60
|
+
case 'status':
|
|
61
|
+
return {
|
|
62
|
+
ok: true, pid: process.pid, version, port: boundPort, path: WS_PATH,
|
|
63
|
+
publicUrl: cfg.publicUrl, trustProxy: gateway.trustProxy, fingerprint: keyFingerprint(cfg.key), startedAt,
|
|
64
|
+
browser: gateway.status(), mcpSessions: sessions,
|
|
65
|
+
};
|
|
66
|
+
case 'reload':
|
|
67
|
+
return reload();
|
|
68
|
+
case 'stop':
|
|
69
|
+
setImmediate(() => shutdown('stop command'));
|
|
70
|
+
return { ok: true };
|
|
71
|
+
default:
|
|
72
|
+
return { ok: false, error: 'unknown command' };
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
} catch (e) {
|
|
77
|
+
await gateway.close();
|
|
78
|
+
if (e instanceof AlreadyRunningError) {
|
|
79
|
+
log(e.message);
|
|
80
|
+
return { alreadyRunning: true };
|
|
81
|
+
}
|
|
82
|
+
throw e;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function reload() {
|
|
86
|
+
const next = loadConfig(dir);
|
|
87
|
+
if (!next) return { ok: false, error: 'config.json is missing' };
|
|
88
|
+
const keyChanged = Buffer.compare(next.key, cfg.key) !== 0;
|
|
89
|
+
gateway.setExtensionIds(next.extensionIds);
|
|
90
|
+
gateway.trustProxy = trustProxy(next);
|
|
91
|
+
gateway.setKey(next.key);
|
|
92
|
+
const portChanged = next.port !== cfg.port;
|
|
93
|
+
cfg = next;
|
|
94
|
+
log(`config reloaded${keyChanged ? ' (new key)' : ''}${portChanged ? ' (port change needs a restart)' : ''}`);
|
|
95
|
+
return { ok: true, keyChanged, portChanged };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let stopping = false;
|
|
99
|
+
async function shutdown(why) {
|
|
100
|
+
if (stopping) return;
|
|
101
|
+
stopping = true;
|
|
102
|
+
log(`stopping (${why})`);
|
|
103
|
+
await control.close();
|
|
104
|
+
await gateway.close();
|
|
105
|
+
if (exitOnSignal) process.exit(0);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (exitOnSignal) {
|
|
109
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
110
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
111
|
+
process.on('SIGHUP', () => { try { reload(); } catch (e) { log(`reload failed: ${e.message}`); } });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
log(`cctether ${version} listening on 127.0.0.1:${boundPort}${WS_PATH} (key ${keyFingerprint(cfg.key)})`);
|
|
115
|
+
return { port: boundPort, gateway, shutdown };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Listen on the port; while another cctether service holds it, ask that one to stop (up to ~10 s). */
|
|
119
|
+
async function listenTakingOver(gateway, port, P, log) {
|
|
120
|
+
const deadline = Date.now() + 10_000;
|
|
121
|
+
for (;;) {
|
|
122
|
+
try {
|
|
123
|
+
return await gateway.listen(port);
|
|
124
|
+
} catch (e) {
|
|
125
|
+
if (e.code !== 'EADDRINUSE' || Date.now() > deadline) throw e;
|
|
126
|
+
}
|
|
127
|
+
const st = await adminRequest(P.socket, { cmd: 'status' }, 1000);
|
|
128
|
+
if (st?.ok && st.pid !== process.pid) {
|
|
129
|
+
log(`taking over from the service started outside systemd (pid ${st.pid})`);
|
|
130
|
+
await adminRequest(P.socket, { cmd: 'stop' }, 1000);
|
|
131
|
+
}
|
|
132
|
+
await sleep(150);
|
|
133
|
+
}
|
|
134
|
+
}
|
package/src/gateway.js
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// The extension entrance (SPEC §4.4, D7–D9): a WebSocket server on 127.0.0.1 that only accepts
|
|
2
|
+
// the cctether extension, authenticates it with a mutual challenge–response, and then exchanges
|
|
3
|
+
// encrypted messages. At most one browser is connected; a newly authenticated one replaces the old.
|
|
4
|
+
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { WebSocketServer } from 'ws';
|
|
7
|
+
import { EventEmitter } from 'node:events';
|
|
8
|
+
import {
|
|
9
|
+
PROTO, LABEL_SERVER, LABEL_CLIENT, CLOSE, HANDSHAKE_TIMEOUT_MS, IDLE_TIMEOUT_MS,
|
|
10
|
+
MAX_FROM_EXTENSION, MAX_TO_EXTENSION, b64u, fromB64u, newNonce, proof, proofMatches,
|
|
11
|
+
deriveSessionKeys, SessionCipher,
|
|
12
|
+
} from './protocol.js';
|
|
13
|
+
import { FailureLimiter, clientIp } from './ratelimit.js';
|
|
14
|
+
|
|
15
|
+
/** Max size of one WebSocket frame in either direction. Bigger messages arrive as fragments. */
|
|
16
|
+
export const MAX_FRAME = 1024 * 1024;
|
|
17
|
+
const MAX_HANDSHAKE_MESSAGE = 2048;
|
|
18
|
+
const MAX_PENDING_HANDSHAKES = 16;
|
|
19
|
+
|
|
20
|
+
export class GatewayError extends Error {
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.code = code;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Gateway extends EventEmitter {
|
|
28
|
+
#key;
|
|
29
|
+
#origins;
|
|
30
|
+
#path;
|
|
31
|
+
#version;
|
|
32
|
+
#log;
|
|
33
|
+
#limiter;
|
|
34
|
+
#http;
|
|
35
|
+
#wss;
|
|
36
|
+
#pendingHandshakes = 0;
|
|
37
|
+
/** @type {BrowserConnection|null} */
|
|
38
|
+
#browser = null;
|
|
39
|
+
#handshakeTimeoutMs;
|
|
40
|
+
#idleTimeoutMs;
|
|
41
|
+
|
|
42
|
+
constructor({
|
|
43
|
+
key, extensionIds, path = '/cctether', version, log = () => {}, limiter = new FailureLimiter(),
|
|
44
|
+
handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS, idleTimeoutMs = IDLE_TIMEOUT_MS, trustProxy = false,
|
|
45
|
+
}) {
|
|
46
|
+
super();
|
|
47
|
+
this.trustProxy = trustProxy;
|
|
48
|
+
this.#handshakeTimeoutMs = handshakeTimeoutMs;
|
|
49
|
+
this.#idleTimeoutMs = idleTimeoutMs;
|
|
50
|
+
this.#key = key;
|
|
51
|
+
this.#origins = new Set(extensionIds.map((id) => `chrome-extension://${id}`));
|
|
52
|
+
this.#path = path;
|
|
53
|
+
this.#version = version;
|
|
54
|
+
this.#log = log;
|
|
55
|
+
this.#limiter = limiter;
|
|
56
|
+
this.#wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME, perMessageDeflate: false });
|
|
57
|
+
this.#http = createServer((req, res) => {
|
|
58
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
59
|
+
res.end('Not found\n');
|
|
60
|
+
});
|
|
61
|
+
this.#http.on('upgrade', (req, socket, head) => this.#onUpgrade(req, socket, head));
|
|
62
|
+
this.#http.on('clientError', (_err, socket) => socket.destroy());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
listen(port, host = '127.0.0.1') {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const onError = (e) => reject(e);
|
|
68
|
+
this.#http.once('error', onError);
|
|
69
|
+
this.#http.listen(port, host, () => {
|
|
70
|
+
this.#http.off('error', onError);
|
|
71
|
+
resolve(this.#http.address().port);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
setKey(key) {
|
|
77
|
+
if (Buffer.compare(key, this.#key) === 0) return;
|
|
78
|
+
this.#key = key;
|
|
79
|
+
if (this.#browser) {
|
|
80
|
+
this.#log('key changed: disconnecting the browser');
|
|
81
|
+
this.#browser.close(CLOSE.keyChanged, 'key_changed');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
setExtensionIds(ids) {
|
|
86
|
+
this.#origins = new Set(ids.map((id) => `chrome-extension://${id}`));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get browser() {
|
|
90
|
+
return this.#browser;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
status() {
|
|
94
|
+
const b = this.#browser;
|
|
95
|
+
return b ? { connected: true, since: b.since, ip: b.ip, info: b.info } : { connected: false };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run a tool in the browser.
|
|
100
|
+
* @returns {Promise<{ ok: true, data: any } | { ok: false, error: { code: string, message: string } }>}
|
|
101
|
+
*/
|
|
102
|
+
call(tool, args, timeoutMs) {
|
|
103
|
+
if (!this.#browser) {
|
|
104
|
+
return Promise.reject(new GatewayError('no_browser', 'No browser is connected.'));
|
|
105
|
+
}
|
|
106
|
+
return this.#browser.call(tool, args, timeoutMs);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async close() {
|
|
110
|
+
if (this.#browser) this.#browser.close(CLOSE.shutdown, 'shutdown');
|
|
111
|
+
for (const ws of this.#wss.clients) ws.terminate();
|
|
112
|
+
const closed = new Promise((r) => this.#http.close(() => r()));
|
|
113
|
+
this.#http.closeAllConnections();
|
|
114
|
+
await closed;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- connection setup ------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
#onUpgrade(req, socket, head) {
|
|
120
|
+
const ip = clientIp(req, { trustProxy: this.trustProxy });
|
|
121
|
+
const reject = (status, text) => {
|
|
122
|
+
socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
123
|
+
};
|
|
124
|
+
socket.on('error', () => {});
|
|
125
|
+
let pathname;
|
|
126
|
+
try {
|
|
127
|
+
pathname = new URL(req.url, 'http://localhost').pathname;
|
|
128
|
+
} catch {
|
|
129
|
+
return reject(400, 'Bad Request');
|
|
130
|
+
}
|
|
131
|
+
if (pathname !== this.#path) return reject(404, 'Not Found');
|
|
132
|
+
if (this.#pendingHandshakes >= MAX_PENDING_HANDSHAKES) return reject(503, 'Service Unavailable');
|
|
133
|
+
|
|
134
|
+
// Refusals below are sent as a WebSocket message: a browser can't read an HTTP status code
|
|
135
|
+
// from a failed WebSocket, and the extension wants to show the user what's wrong.
|
|
136
|
+
let refusal = null;
|
|
137
|
+
const origin = req.headers.origin;
|
|
138
|
+
if (!origin || !this.#origins.has(origin)) {
|
|
139
|
+
refusal = 'origin_rejected';
|
|
140
|
+
this.#log(`refused ${ip}: origin ${JSON.stringify(origin ?? null).slice(0, 80)} is not an allowed extension`);
|
|
141
|
+
} else if (this.#limiter.isBlocked(ip)) {
|
|
142
|
+
refusal = 'rate_limited';
|
|
143
|
+
this.#log(`refused ${ip}: too many failed attempts`);
|
|
144
|
+
}
|
|
145
|
+
this.#wss.handleUpgrade(req, socket, head, (ws) => {
|
|
146
|
+
if (refusal) {
|
|
147
|
+
ws.send(JSON.stringify({ t: 'error', code: refusal }));
|
|
148
|
+
ws.close(refusal === 'origin_rejected' ? CLOSE.originRejected : CLOSE.authFailed);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
this.#handshake(ws, ip);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#handshake(ws, ip) {
|
|
156
|
+
this.#pendingHandshakes++;
|
|
157
|
+
let done = false;
|
|
158
|
+
const key = this.#key;
|
|
159
|
+
let state = 'hello';
|
|
160
|
+
let cn;
|
|
161
|
+
let sn;
|
|
162
|
+
|
|
163
|
+
const finish = () => {
|
|
164
|
+
if (done) return;
|
|
165
|
+
done = true;
|
|
166
|
+
this.#pendingHandshakes--;
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
ws.off('message', onMessage);
|
|
169
|
+
};
|
|
170
|
+
const fail = (why, { count = true, code = CLOSE.protocolError, error } = {}) => {
|
|
171
|
+
if (done) return;
|
|
172
|
+
finish();
|
|
173
|
+
if (count) this.#limiter.fail(ip);
|
|
174
|
+
this.#log(`handshake failed from ${ip}: ${why}`);
|
|
175
|
+
if (error) ws.send(JSON.stringify(error));
|
|
176
|
+
ws.close(code);
|
|
177
|
+
};
|
|
178
|
+
const timer = setTimeout(() => fail('timeout', { code: CLOSE.timeout }), this.#handshakeTimeoutMs);
|
|
179
|
+
|
|
180
|
+
const onMessage = (data, isBinary) => {
|
|
181
|
+
if (isBinary || data.length > MAX_HANDSHAKE_MESSAGE) return fail('unexpected frame');
|
|
182
|
+
let m;
|
|
183
|
+
try {
|
|
184
|
+
m = JSON.parse(data.toString('utf8'));
|
|
185
|
+
} catch {
|
|
186
|
+
return fail('bad json');
|
|
187
|
+
}
|
|
188
|
+
if (!m || typeof m !== 'object') return fail('bad message');
|
|
189
|
+
|
|
190
|
+
if (state === 'hello') {
|
|
191
|
+
if (m.t !== 'hello') return fail('expected hello');
|
|
192
|
+
if (m.proto !== PROTO) {
|
|
193
|
+
const code = typeof m.proto === 'number' && m.proto > PROTO ? 'update_server' : 'update_extension';
|
|
194
|
+
return fail(`protocol ${JSON.stringify(m.proto)} vs ${PROTO}`, {
|
|
195
|
+
count: false, code: CLOSE.versionMismatch, error: { t: 'error', code, proto: PROTO },
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
cn = fromB64u(m.cn, 32);
|
|
199
|
+
if (!cn) return fail('bad nonce');
|
|
200
|
+
sn = newNonce();
|
|
201
|
+
ws.send(JSON.stringify({ t: 'challenge', proto: PROTO, sn: b64u(sn), sp: b64u(proof(key, LABEL_SERVER, cn, sn)) }));
|
|
202
|
+
state = 'auth';
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// state === 'auth'
|
|
207
|
+
if (m.t !== 'auth') return fail('expected auth');
|
|
208
|
+
const cp = fromB64u(m.cp, 32);
|
|
209
|
+
if (!cp || !proofMatches(proof(key, LABEL_CLIENT, cn, sn), cp)) {
|
|
210
|
+
return fail('wrong key', { code: CLOSE.authFailed, error: { t: 'error', code: 'auth_rejected' } });
|
|
211
|
+
}
|
|
212
|
+
if (key !== this.#key) {
|
|
213
|
+
// The key was rotated during the handshake.
|
|
214
|
+
return fail('key changed during handshake', { count: false, code: CLOSE.keyChanged });
|
|
215
|
+
}
|
|
216
|
+
finish();
|
|
217
|
+
const { c2s, s2c } = deriveSessionKeys(key, cn, sn);
|
|
218
|
+
this.#adopt(new BrowserConnection(ws, new SessionCipher(s2c, c2s), ip, this.#version, this.#log, this.#idleTimeoutMs));
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
ws.on('message', onMessage);
|
|
222
|
+
// A client that hangs up after reading our challenge is usually the extension refusing a
|
|
223
|
+
// server whose proof didn't match its key — not an attack, so it is not counted.
|
|
224
|
+
ws.on('close', () => finish());
|
|
225
|
+
ws.on('error', () => {});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
#adopt(conn) {
|
|
229
|
+
const old = this.#browser;
|
|
230
|
+
this.#browser = conn;
|
|
231
|
+
if (old) {
|
|
232
|
+
this.#log(`browser from ${old.ip} replaced by a new connection from ${conn.ip}`);
|
|
233
|
+
old.close(CLOSE.replaced, 'replaced');
|
|
234
|
+
}
|
|
235
|
+
this.#log(`browser connected from ${conn.ip}`);
|
|
236
|
+
conn.on('info', () => this.emit('browser', this.status()));
|
|
237
|
+
conn.once('closed', (why) => {
|
|
238
|
+
if (this.#browser === conn) {
|
|
239
|
+
this.#browser = null;
|
|
240
|
+
this.#log(`browser disconnected (${why})`);
|
|
241
|
+
this.emit('browser', this.status());
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
conn.start();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** An authenticated browser connection. */
|
|
249
|
+
export class BrowserConnection extends EventEmitter {
|
|
250
|
+
#ws;
|
|
251
|
+
#cipher;
|
|
252
|
+
#nextId = 1;
|
|
253
|
+
#pending = new Map(); // id → { resolve, reject, timer }
|
|
254
|
+
#idleTimer = null;
|
|
255
|
+
#fragments = null; // string[] while a fragmented message is arriving
|
|
256
|
+
#fragmentsSize = 0;
|
|
257
|
+
#closed = false;
|
|
258
|
+
|
|
259
|
+
#idleTimeoutMs;
|
|
260
|
+
|
|
261
|
+
constructor(ws, cipher, ip, version, log, idleTimeoutMs = IDLE_TIMEOUT_MS) {
|
|
262
|
+
super();
|
|
263
|
+
this.#idleTimeoutMs = idleTimeoutMs;
|
|
264
|
+
this.#ws = ws;
|
|
265
|
+
this.#cipher = cipher;
|
|
266
|
+
this.ip = ip;
|
|
267
|
+
this.since = Date.now();
|
|
268
|
+
this.info = null;
|
|
269
|
+
this.version = version;
|
|
270
|
+
this.log = log;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
start() {
|
|
274
|
+
this.#ws.on('message', (data, isBinary) => this.#onFrame(data, isBinary));
|
|
275
|
+
this.#ws.on('close', (code) => this.#onClosed(`code ${code}`));
|
|
276
|
+
this.#ws.on('error', () => {});
|
|
277
|
+
this.#touch();
|
|
278
|
+
this.#send({ t: 'welcome', server: this.version });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
call(tool, args, timeoutMs) {
|
|
282
|
+
const id = this.#nextId++;
|
|
283
|
+
return new Promise((resolve, reject) => {
|
|
284
|
+
if (this.#closed) return reject(new GatewayError('disconnected', 'The browser disconnected.'));
|
|
285
|
+
const timer = setTimeout(() => {
|
|
286
|
+
this.#pending.delete(id);
|
|
287
|
+
reject(new GatewayError('timeout', `The browser did not answer within ${Math.round(timeoutMs / 1000)} s.`));
|
|
288
|
+
}, timeoutMs);
|
|
289
|
+
this.#pending.set(id, { resolve, reject, timer });
|
|
290
|
+
try {
|
|
291
|
+
this.#send({ t: 'call', id, tool, args });
|
|
292
|
+
} catch (e) {
|
|
293
|
+
clearTimeout(timer);
|
|
294
|
+
this.#pending.delete(id);
|
|
295
|
+
reject(new GatewayError('too_large', e.message));
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Close, telling the extension why first. */
|
|
301
|
+
close(code, reason) {
|
|
302
|
+
if (this.#closed) return;
|
|
303
|
+
try {
|
|
304
|
+
if (reason) this.#send({ t: 'bye', reason });
|
|
305
|
+
} catch {}
|
|
306
|
+
this.#ws.close(code);
|
|
307
|
+
this.#onClosed(reason ?? `code ${code}`);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
#send(obj) {
|
|
311
|
+
const frame = this.#cipher.seal(obj);
|
|
312
|
+
if (frame.length > MAX_TO_EXTENSION) throw new Error('Message to the browser is too large.');
|
|
313
|
+
this.#ws.send(frame);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
#touch() {
|
|
317
|
+
clearTimeout(this.#idleTimer);
|
|
318
|
+
this.#idleTimer = setTimeout(() => {
|
|
319
|
+
this.log('browser connection idle for too long');
|
|
320
|
+
this.close(CLOSE.timeout, null);
|
|
321
|
+
}, this.#idleTimeoutMs);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#protocolError(why) {
|
|
325
|
+
this.log(`protocol error from browser: ${why}`);
|
|
326
|
+
this.close(CLOSE.protocolError, null);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#onFrame(data, isBinary) {
|
|
330
|
+
if (this.#closed) return;
|
|
331
|
+
if (!isBinary) return this.#protocolError('text frame after handshake');
|
|
332
|
+
let msg;
|
|
333
|
+
try {
|
|
334
|
+
msg = this.#cipher.open(data);
|
|
335
|
+
} catch {
|
|
336
|
+
return this.#protocolError('could not decrypt');
|
|
337
|
+
}
|
|
338
|
+
this.#touch();
|
|
339
|
+
|
|
340
|
+
if (msg.t === 'frag') {
|
|
341
|
+
// A big message split into pieces: { t: 'frag', s: <slice of the JSON text>, end?: true }
|
|
342
|
+
if (typeof msg.s !== 'string') return this.#protocolError('bad fragment');
|
|
343
|
+
this.#fragments ??= [];
|
|
344
|
+
this.#fragments.push(msg.s);
|
|
345
|
+
this.#fragmentsSize += msg.s.length;
|
|
346
|
+
if (this.#fragmentsSize > MAX_FROM_EXTENSION) return this.#protocolError('message too large');
|
|
347
|
+
if (!msg.end) return;
|
|
348
|
+
const text = this.#fragments.join('');
|
|
349
|
+
this.#fragments = null;
|
|
350
|
+
this.#fragmentsSize = 0;
|
|
351
|
+
try {
|
|
352
|
+
msg = JSON.parse(text);
|
|
353
|
+
} catch {
|
|
354
|
+
return this.#protocolError('bad fragmented message');
|
|
355
|
+
}
|
|
356
|
+
if (!msg || typeof msg !== 'object' || msg.t === 'frag') return this.#protocolError('bad fragmented message');
|
|
357
|
+
} else if (this.#fragments) {
|
|
358
|
+
return this.#protocolError('interleaved fragments');
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
switch (msg.t) {
|
|
362
|
+
case 'ping':
|
|
363
|
+
this.#send({ t: 'pong' });
|
|
364
|
+
break;
|
|
365
|
+
case 'info':
|
|
366
|
+
this.info = sanitizeInfo(msg);
|
|
367
|
+
this.log(`browser: ${this.info.browser ?? '?'}, extension ${this.info.extension ?? '?'}`);
|
|
368
|
+
this.emit('info', this.info);
|
|
369
|
+
break;
|
|
370
|
+
case 'result': {
|
|
371
|
+
const p = this.#pending.get(msg.id);
|
|
372
|
+
if (!p) break; // timed out already
|
|
373
|
+
this.#pending.delete(msg.id);
|
|
374
|
+
clearTimeout(p.timer);
|
|
375
|
+
if (msg.ok === true) p.resolve({ ok: true, data: msg.data });
|
|
376
|
+
else {
|
|
377
|
+
const e = msg.error ?? {};
|
|
378
|
+
p.resolve({
|
|
379
|
+
ok: false,
|
|
380
|
+
error: {
|
|
381
|
+
code: typeof e.code === 'string' ? e.code.slice(0, 40) : 'internal',
|
|
382
|
+
message: typeof e.message === 'string' ? e.message.slice(0, 4000) : 'The browser reported an error.',
|
|
383
|
+
},
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
388
|
+
default:
|
|
389
|
+
// Unknown message types are ignored so newer extensions can add optional messages.
|
|
390
|
+
break;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
#onClosed(why) {
|
|
395
|
+
if (this.#closed) return;
|
|
396
|
+
this.#closed = true;
|
|
397
|
+
clearTimeout(this.#idleTimer);
|
|
398
|
+
for (const p of this.#pending.values()) {
|
|
399
|
+
clearTimeout(p.timer);
|
|
400
|
+
p.reject(new GatewayError('disconnected', 'The browser disconnected before answering.'));
|
|
401
|
+
}
|
|
402
|
+
this.#pending.clear();
|
|
403
|
+
this.emit('closed', why);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function sanitizeInfo(m) {
|
|
408
|
+
const str = (v, n = 120) => (typeof v === 'string' ? v.slice(0, n) : null);
|
|
409
|
+
return { extension: str(m.extension, 20), browser: str(m.browser), platform: str(m.platform, 40) };
|
|
410
|
+
}
|
package/src/log.js
ADDED