cctether 0.5.0 → 0.6.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cctether",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Let Claude Code use your browser over your own connection — no third-party relay.",
5
5
  "keywords": [
6
6
  "claude-code",
package/src/daemon.js CHANGED
@@ -5,6 +5,7 @@ import { keyFingerprint } from './pairing.js';
5
5
  import { Gateway } from './gateway.js';
6
6
  import { startControl, adminRequest, AlreadyRunningError } from './control.js';
7
7
  import { createMcpSession, lineSplitter } from './mcp.js';
8
+ import { scriptsDir, ensureScriptsDir } from './evalfile.js';
8
9
  import { setTimeout as sleep } from 'node:timers/promises';
9
10
 
10
11
  /**
@@ -38,6 +39,8 @@ export async function runDaemon({ dir, version, log, port: portOverride, exitOnS
38
39
  }
39
40
 
40
41
  const startedAt = Date.now();
42
+ const scripts = scriptsDir(P.dir);
43
+ ensureScriptsDir(scripts);
41
44
  let sessions = 0;
42
45
  let control;
43
46
  try {
@@ -47,7 +50,8 @@ export async function runDaemon({ dir, version, log, port: portOverride, exitOnS
47
50
  onMcp(socket, rest) {
48
51
  sessions++;
49
52
  const write = (line) => { if (!socket.destroyed) socket.write(line + '\n'); };
50
- const session = createMcpSession({ write, browser: gateway, version, log });
53
+ ensureScriptsDir(scripts); // again here: it may have been deleted meanwhile
54
+ const session = createMcpSession({ write, browser: gateway, version, log, scriptsDir: scripts });
51
55
  const feed = lineSplitter((line) => {
52
56
  session.handleLine(line).catch((e) => log(`mcp error: ${e.message}`));
53
57
  }, { onOverflow: () => socket.destroy() });
@@ -0,0 +1,140 @@
1
+ // evaluate's `file` argument (SPEC §5.2): the service reads a .js file from cctether's own
2
+ // scripts directory and sends its text as `expression`. Only that directory: it holds just the
3
+ // scripts Claude wrote there for the browser, so `file` can't be used to push other files on this
4
+ // computer (keys, configs, files Claude Code's own permissions keep it from reading) into a page.
5
+
6
+ import { mkdirSync, chmodSync, lstatSync, constants } from 'node:fs';
7
+ import { open, realpath, lstat } from 'node:fs/promises';
8
+ import { homedir } from 'node:os';
9
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
10
+
11
+ export const FILE_MAX_BYTES = 200 * 1024;
12
+ export const FILE_MAX_CHARS = 200_000; // the same limit as `expression`
13
+
14
+ export class EvalFileError extends Error {}
15
+
16
+ const fail = (m) => { throw new EvalFileError(m); };
17
+
18
+ export const scriptsDir = (configDir) => join(configDir, 'scripts');
19
+
20
+ /**
21
+ * Create the scripts directory (private to the user) if it isn't there. One that is there is
22
+ * left as it is, whatever it is: making a directory others could write to private now would
23
+ * make the scripts they put there earlier look trusted. Reading checks it.
24
+ */
25
+ export function ensureScriptsDir(dir) {
26
+ try {
27
+ lstatSync(dir);
28
+ return;
29
+ } catch { /* not there */ }
30
+ try {
31
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
32
+ chmodSync(dir, 0o700); // whatever the umask
33
+ } catch { /* reported when a file is read from it */ }
34
+ }
35
+
36
+ /** Is dir itself (not a link to one) a directory of this user that nobody else can use? */
37
+ async function privateDir(dir) {
38
+ try {
39
+ const st = await lstat(dir);
40
+ return st.isDirectory() && (process.getuid ? st.uid === process.getuid() : true) && (st.mode & 0o077) === 0;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /** The path below root as segments, or null if p is not inside root (or is root). */
47
+ function below(root, p) {
48
+ const rel = relative(root, p);
49
+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
50
+ return rel.split(sep);
51
+ }
52
+
53
+ /**
54
+ * Read the script `file` names: a name (or path) in the scripts directory `dir`. Returns
55
+ * { path, text }. Throws EvalFileError with a message for Claude, never with file contents.
56
+ */
57
+ export async function readEvalFile(file, dir) {
58
+ if (typeof file !== 'string' || !file.trim()) fail('`file` is empty.');
59
+ if (file.includes('\0')) fail('`file` contains a NUL character.');
60
+ let p = file;
61
+ if (p === '~' || p.startsWith('~/')) p = join(homedir(), p.slice(1));
62
+ p = resolve(dir, p);
63
+ if (!p.endsWith('.js')) fail(`${JSON.stringify(file)} is not a .js file: \`file\` takes a JavaScript file (a browser script, run like \`expression\`).`);
64
+ const ok = await privateDir(dir);
65
+ if (ok === null) fail(`The scripts directory ${dir} does not exist. Write the script there first (the directory may need to be created).`);
66
+ // A link would make "the scripts directory" whatever it points to (a project, a home).
67
+ if (!ok) fail(`The scripts directory ${dir} is not a private directory of this user (it is a link, or others can use it), so \`file\` is off. Make it a plain directory with mode 700, or pass the script as \`expression\`.`);
68
+ let root;
69
+ try {
70
+ root = await realpath(dir);
71
+ } catch {
72
+ fail(`The scripts directory ${dir} does not exist. Write the script there first (the directory may need to be created).`);
73
+ }
74
+ let real;
75
+ try {
76
+ real = await realpath(p);
77
+ } catch (e) {
78
+ fail(e.code === 'ENOENT' ? `There is no file ${p}. Write the script into ${dir} first.` : `Can't open ${p} (${e.code || 'error'}).`);
79
+ }
80
+ const segs = below(root, real);
81
+ if (!segs) fail(`${p} is not in cctether's scripts directory, ${dir}: \`file\` reads only from there. Put the script there.`);
82
+ if (!real.endsWith('.js')) fail(`${p} links to a file that is not a .js file.`);
83
+ if (segs.some((x) => x.startsWith('.'))) fail(`${p} is hidden (a name starting with "."), which \`file\` doesn't read.`);
84
+ let fh;
85
+ try {
86
+ // O_NOFOLLOW: the file can't have been swapped for a link after the checks; O_NONBLOCK: a
87
+ // FIFO put there doesn't block the open (fstat then refuses it).
88
+ fh = await open(real, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
89
+ } catch (e) {
90
+ fail(`Can't open ${p} (${e.code || 'error'}).`);
91
+ }
92
+ let bytes;
93
+ try {
94
+ const st = await fh.stat();
95
+ if (!st.isFile()) fail(`${p} is not a regular file.`);
96
+ if (st.size > FILE_MAX_BYTES) fail(`${p} is ${Math.round(st.size / 1024)} KB; \`file\` takes at most ${FILE_MAX_BYTES / 1024} KB.`);
97
+ // At most one byte more than the limit, from the opened file (it may grow meanwhile).
98
+ const buf = Buffer.alloc(FILE_MAX_BYTES + 1);
99
+ let n = 0;
100
+ while (n < buf.length) {
101
+ const { bytesRead } = await fh.read(buf, n, buf.length - n, n);
102
+ if (!bytesRead) break;
103
+ n += bytesRead;
104
+ }
105
+ if (n > FILE_MAX_BYTES) fail(`${p} is larger than ${FILE_MAX_BYTES / 1024} KB, the most \`file\` takes.`);
106
+ bytes = buf.subarray(0, n);
107
+ } finally {
108
+ await fh.close().catch(() => {});
109
+ }
110
+ let text;
111
+ try {
112
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); // drops a BOM
113
+ } catch {
114
+ fail(`${p} is not UTF-8 text.`);
115
+ }
116
+ if (!text.trim()) fail(`${p} is empty.`);
117
+ if (text.length > FILE_MAX_CHARS) fail(`${p} has ${text.length} characters; \`file\` takes at most ${FILE_MAX_CHARS}.`);
118
+ return { path: real, text };
119
+ }
120
+
121
+ /**
122
+ * evaluate's arguments with `file` replaced by `expression`, or { error } (a message for Claude).
123
+ * Arguments without `file` come back as they are.
124
+ */
125
+ export async function expandEvalFile(args, dir) {
126
+ if (!args || !('file' in args)) {
127
+ if (!args || args.expression == null) return { error: 'Pass `expression` (the JavaScript to run) or `file`.' };
128
+ return { args };
129
+ }
130
+ const { file, ...rest } = args;
131
+ if ('expression' in rest) return { error: 'Pass either `expression` or `file`, not both.' };
132
+ if (!dir) return { error: '`file` is not available here (no scripts directory). Pass the script as `expression`.' };
133
+ try {
134
+ const { text } = await readEvalFile(file, dir);
135
+ return { args: { ...rest, expression: text } };
136
+ } catch (e) {
137
+ if (e instanceof EvalFileError) return { error: e.message };
138
+ throw e;
139
+ }
140
+ }
package/src/gateway.js CHANGED
@@ -99,10 +99,14 @@ export class Gateway extends EventEmitter {
99
99
  * Run a tool in the browser.
100
100
  * @returns {Promise<{ ok: true, data: any } | { ok: false, error: { code: string, message: string } }>}
101
101
  */
102
- call(tool, args, timeoutMs) {
102
+ call(tool, args, timeoutMs, { connection } = {}) {
103
103
  if (!this.#browser) {
104
104
  return Promise.reject(new GatewayError('no_browser', 'No browser is connected.'));
105
105
  }
106
+ // A call prepared for one connection (evaluate's file was read meanwhile) goes to it only.
107
+ if (connection !== undefined && connection !== this.#browser) {
108
+ return Promise.reject(new GatewayError('disconnected', 'The browser connection changed while cctether was preparing the call, so nothing was run.'));
109
+ }
106
110
  return this.#browser.call(tool, args, timeoutMs);
107
111
  }
108
112
 
@@ -308,9 +312,9 @@ export class BrowserConnection extends EventEmitter {
308
312
  }
309
313
 
310
314
  #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);
315
+ // Checked before sealing (SessionCipher.seal): a frame sealed but not sent would leave the
316
+ // extension expecting a counter value we've moved past.
317
+ this.#ws.send(this.#cipher.seal(obj, MAX_TO_EXTENSION));
314
318
  }
315
319
 
316
320
  #touch() {
package/src/mcp.js CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { TOOLS, mcpToolList, toolTimeoutMs } from './tools.js';
5
5
  import { validate } from './schema.js';
6
+ import { expandEvalFile } from './evalfile.js';
6
7
 
7
8
  export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
8
9
  const MAX_TEXT = 2_000_000;
@@ -27,8 +28,9 @@ const NOT_CONNECTED = [
27
28
  * @param {string} opts.version
28
29
  * @param {(msg: string) => void} [opts.log]
29
30
  * @param {string} [opts.unavailable] if set, every tool call fails with this message (used by the shim's fallback)
31
+ * @param {string} [opts.scriptsDir] where evaluate's `file` is read from (SPEC §5.2); none: no `file`
30
32
  */
31
- export function createMcpSession({ write, browser, version, log = () => {}, unavailable = null }) {
33
+ export function createMcpSession({ write, browser, version, log = () => {}, unavailable = null, scriptsDir = null }) {
32
34
  const reply = (id, result) => write(JSON.stringify({ jsonrpc: '2.0', id, result }));
33
35
  const replyError = (id, code, message) => write(JSON.stringify({ jsonrpc: '2.0', id: id ?? null, error: { code, message } }));
34
36
 
@@ -60,10 +62,20 @@ export function createMcpSession({ write, browser, version, log = () => {}, unav
60
62
  const name = params?.name;
61
63
  const tool = TOOLS.find((t) => t.name === name);
62
64
  if (!tool) return { error: { code: -32602, message: `Unknown tool: ${String(name).slice(0, 100)}` } };
63
- const args = params.arguments ?? {};
65
+ let args = params.arguments ?? {};
64
66
  const invalid = validate(tool.inputSchema, args);
65
67
  if (invalid) return { result: errorResult(`Invalid arguments: ${invalid}.`) };
66
68
  if (unavailable) return { result: errorResult(unavailable) };
69
+ let pinned; // for `file`: the browser connection when the call came, the only one it may go to
70
+ if (name === 'evaluate') {
71
+ // The service reads `file` and sends the script as `expression` (SPEC §5.2).
72
+ if ('file' in args) pinned = browser?.browser ?? null;
73
+ const ex = await expandEvalFile(args, scriptsDir);
74
+ if (ex.error) return { result: errorResult(ex.error) };
75
+ args = ex.args;
76
+ const bad = validate(tool.inputSchema, args);
77
+ if (bad) return { result: errorResult(`Invalid arguments: ${bad}.`) };
78
+ }
67
79
  // Calls an older extension accepts but answers differently, without an error (SPEC §5.2).
68
80
  const needs = minExtensionFor(name, args);
69
81
  const ext = browser?.status?.()?.info?.extension;
@@ -72,7 +84,7 @@ export function createMcpSession({ write, browser, version, log = () => {}, unav
72
84
  + `Ask the user to update the extension. Until then: ${needs.instead}`) };
73
85
  }
74
86
  try {
75
- const r = await browser.call(name, args, toolTimeoutMs(name, args));
87
+ const r = await browser.call(name, args, toolTimeoutMs(name, args), pinned !== undefined ? { connection: pinned } : undefined);
76
88
  if (!r.ok && isUnknownToolAnswer(r.error)) return { result: errorResult(outdatedExtension(name)) };
77
89
  if (!r.ok && r.error?.code === 'bad_args') return { result: errorResult(withVersionNote(r.error.message)) };
78
90
  if (!r.ok) return { result: errorResult(r.error.message) };
@@ -81,6 +93,7 @@ export function createMcpSession({ write, browser, version, log = () => {}, unav
81
93
  if (e.code === 'no_browser') return { result: errorResult(NOT_CONNECTED) };
82
94
  if (e.code === 'timeout') return { result: errorResult(`${e.message} The page may be busy or frozen; try again, or check the tab.`) };
83
95
  if (e.code === 'disconnected') return { result: errorResult(`${e.message} It may reconnect in a few seconds; try again.`) };
96
+ if (e.code === 'too_large') return { result: errorResult(`${e.message} Nothing was sent; the connection is fine. Send less (e.g. a shorter script).`) };
84
97
  log(`tool ${name} failed: ${e.message}`);
85
98
  return { result: errorResult(`cctether error: ${e.message}`) };
86
99
  }
@@ -107,7 +120,7 @@ export function createMcpSession({ write, browser, version, log = () => {}, unav
107
120
  case 'ping':
108
121
  return isRequest && reply(id, {});
109
122
  case 'tools/list':
110
- return reply(id, { tools: mcpToolList() });
123
+ return reply(id, { tools: mcpToolList(scriptsDir) });
111
124
  case 'tools/call': {
112
125
  const r = await callTool(params);
113
126
  return r.error ? replyError(id, r.error.code, r.error.message) : reply(id, r.result);
package/src/protocol.js CHANGED
@@ -75,6 +75,13 @@ function ivFor(counter) {
75
75
  return iv;
76
76
  }
77
77
 
78
+ export class TooLargeError extends Error {
79
+ constructor(bytes) {
80
+ super(`The message for the browser is too large (${Math.ceil(bytes / 1024)} KB encoded; at most ${MAX_TO_EXTENSION / 1024} KB).`);
81
+ this.bytes = bytes;
82
+ }
83
+ }
84
+
78
85
  /** Encrypts outgoing and decrypts incoming frames for one direction pair. */
79
86
  export class SessionCipher {
80
87
  #sendKey;
@@ -87,9 +94,13 @@ export class SessionCipher {
87
94
  this.#recvKey = recvKey;
88
95
  }
89
96
 
90
- /** @returns {Buffer} ciphertext || 16-byte tag */
91
- seal(obj) {
97
+ /**
98
+ * @returns {Buffer} ciphertext || 16-byte tag. Throws TooLargeError, without using up a counter
99
+ * value, if that would be longer than maxBytes: a counter value skipped would break the stream.
100
+ */
101
+ seal(obj, maxBytes = Infinity) {
92
102
  const plain = Buffer.from(JSON.stringify(obj), 'utf8');
103
+ if (plain.length + 16 > maxBytes) throw new TooLargeError(plain.length + 16);
93
104
  const c = createCipheriv('aes-256-gcm', this.#sendKey, ivFor(this.#sendCounter++));
94
105
  return Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);
95
106
  }
package/src/tools.js CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  const tab = { type: 'integer', description: 'Tab id from list_tabs. Default: the current tab.' };
6
6
  const ref = { type: 'integer', minimum: 1, description: 'Element number from read_page (interactive mode) or find. Invalid after navigation.' };
7
- const selector = { type: 'string', minLength: 1, maxLength: 2000, description: 'CSS selector (the first visible match, else the first match).' };
7
+ const selector = { type: 'string', minLength: 1, maxLength: 2000, description: 'CSS selector (the first visible match, else the first match; in same-origin iframes if the page itself has no match).' };
8
8
  const selectorFirst = { type: 'string', minLength: 1, maxLength: 2000, description: 'CSS selector (the first match, visible or not).' };
9
9
  const x = { type: 'number', description: 'Viewport x in CSS pixels, or with screenshot: x on that image.' };
10
10
  const y = { type: 'number', description: 'Viewport y in CSS pixels, or with screenshot: y on that image.' };
@@ -12,6 +12,10 @@ const text = { type: 'string', minLength: 1, maxLength: 1000, description: 'Visi
12
12
  const shot = { type: 'integer', minimum: 1, description: 'A screenshot number: x, y are then a point on that image.' };
13
13
  const timeout = (def, max) => ({ type: 'integer', minimum: 100, maximum: max, description: `Milliseconds, default ${def}.` });
14
14
 
15
+ /** evaluate's `file`; mcpToolList puts the scripts directory's path where SCRIPTS_DIR is. */
16
+ export const SCRIPTS_DIR = '<scripts directory>';
17
+ const FILE_DESC = `Instead of expression: the name of a .js file in cctether's scripts directory, ${SCRIPTS_DIR}. Write a long script there once, then pass its name (edit it there and pass the name again); it runs like expression (a browser script: no import/export). Globals it defines stay in the page until it reloads.`;
18
+
15
19
  const READ = { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
16
20
  const ACT = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
17
21
  const DANGER = { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
@@ -73,7 +77,7 @@ export const TOOLS = [
73
77
  {
74
78
  name: 'read_page',
75
79
  title: 'Read page',
76
- description: 'Read the page. mode "text" (default): visible text. "interactive": numbered list of links, buttons, inputs etc. — pass a number as `ref` to click/type/hover/select_option/scroll/screenshot. "html": HTML of `selector` (default body). Long output is split: pass the returned offset to continue.',
80
+ description: 'Read the page, including same-origin iframes. mode "text" (default): visible text. "interactive": numbered list of links, buttons, inputs etc. — pass a number as `ref` to click/type/hover/select_option/scroll/screenshot. "html": HTML of `selector` (default body). Long output is split: pass the returned offset to continue.',
77
81
  inputSchema: {
78
82
  type: 'object',
79
83
  properties: {
@@ -90,7 +94,7 @@ export const TOOLS = [
90
94
  {
91
95
  name: 'find',
92
96
  title: 'Find elements',
93
- description: 'Find elements by CSS selector and/or visible text. Returns count, and for each: ref number, tag, text, key attributes, position, visibility.',
97
+ description: 'Find elements by CSS selector and/or visible text, also inside same-origin iframes. Returns count, and for each: ref number, tag, text, key attributes, position, visibility.',
94
98
  inputSchema: {
95
99
  type: 'object',
96
100
  properties: {
@@ -262,18 +266,20 @@ export const TOOLS = [
262
266
  {
263
267
  name: 'evaluate',
264
268
  title: 'Run JavaScript',
265
- description: 'Run JavaScript in the page and return the result as JSON. Works like the DevTools console: the value of the last expression is returned (a Promise is awaited), top-level await is allowed. world "page" (default) shares globals with the page; "isolated" sees only the DOM.',
269
+ description: 'Run JavaScript in the page and return the result as JSON. Works like the DevTools console: the value of the last expression is returned (a Promise is awaited), top-level await is allowed. world "page" (default) shares globals with the page; "isolated" sees only the DOM. Pass `expression` or `file`.',
266
270
  inputSchema: {
267
271
  type: 'object',
268
272
  properties: {
269
273
  expression: { type: 'string', minLength: 1, maxLength: 200000 },
274
+ file: { type: 'string', minLength: 1, maxLength: 1000, description: FILE_DESC },
270
275
  world: { type: 'string', enum: ['page', 'isolated'] },
271
276
  timeout_ms: timeout(10000, 120000),
272
277
  tab,
273
278
  },
274
- required: ['expression'],
275
279
  additionalProperties: false,
276
280
  },
281
+ // Read by the service (mcp.js), which sends `expression` to the extension instead.
282
+ serverOnly: ['file'],
277
283
  annotations: DANGER,
278
284
  timeoutMs: (a) => (a.timeout_ms ?? 10000) + 5000,
279
285
  },
@@ -358,9 +364,17 @@ export function toolTimeoutMs(name, args) {
358
364
  return t?.timeoutMs ? t.timeoutMs(args) : DEFAULT_TIMEOUT_MS;
359
365
  }
360
366
 
361
- /** Tool list as sent in MCP tools/list. */
362
- export function mcpToolList() {
363
- return TOOLS.map(({ name, title, description, inputSchema, annotations }) => ({
364
- name, title, description, inputSchema, annotations: { title, ...annotations },
365
- }));
367
+ /** Tool list as sent in MCP tools/list; `scriptsDir`: the path to put in evaluate's `file`. */
368
+ export function mcpToolList(scriptsDir = null) {
369
+ return TOOLS.map(({ name, title, description, inputSchema, annotations }) => {
370
+ let schema = inputSchema;
371
+ if (inputSchema.properties.file) {
372
+ const { file, ...props } = inputSchema.properties;
373
+ // Without a scripts directory (the shim's fallback answers), there is no `file`.
374
+ schema = scriptsDir
375
+ ? { ...inputSchema, properties: { ...inputSchema.properties, file: { ...file, description: file.description.replace(SCRIPTS_DIR, scriptsDir) } } }
376
+ : { ...inputSchema, properties: props };
377
+ }
378
+ return { name, title, description, inputSchema: schema, annotations: { title, ...annotations } };
379
+ });
366
380
  }