mcp-browser-extension 0.9.35 → 0.9.38

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.
Files changed (58) hide show
  1. package/README.md +33 -15
  2. package/dist/shared/client-auth.d.ts +2 -0
  3. package/dist/shared/phone-pairing.d.ts +35 -0
  4. package/dist/shared/phone-pairing.js +10 -0
  5. package/dist/shared/policy.js +7 -0
  6. package/dist/shared/protocol.d.ts +13 -2
  7. package/dist/shared/protocol.js +13 -1
  8. package/dist/shared/site-risk.d.ts +31 -0
  9. package/dist/shared/site-risk.js +190 -0
  10. package/dist/src/bridge/client-identity.d.ts +11 -5
  11. package/dist/src/bridge/client-identity.js +7 -4
  12. package/dist/src/bridge/connection.js +1 -0
  13. package/dist/src/bridge/server.d.ts +1 -0
  14. package/dist/src/bridge/server.js +38 -19
  15. package/dist/src/bridge/workspace.d.ts +1 -0
  16. package/dist/src/bridge/workspace.js +11 -3
  17. package/dist/src/cli.js +61 -18
  18. package/dist/src/config.d.ts +2 -0
  19. package/dist/src/config.js +26 -1
  20. package/dist/src/executor/extension-executor.d.ts +1 -0
  21. package/dist/src/executor/extension-executor.js +10 -1
  22. package/dist/src/executor/types.d.ts +3 -1
  23. package/dist/src/mcp/helpers.js +18 -6
  24. package/dist/src/mcp/person-wait.js +2 -1
  25. package/dist/src/mcp/server.d.ts +2 -1
  26. package/dist/src/mcp/server.js +4 -4
  27. package/dist/src/mcp/tools.d.ts +2 -2
  28. package/dist/src/mcp/tools.js +46 -9
  29. package/dist/src/native-host.js +11 -1
  30. package/dist/src/remote/claude-chat.d.ts +21 -0
  31. package/dist/src/remote/claude-chat.js +209 -0
  32. package/dist/src/remote/codex-rpc.d.ts +19 -0
  33. package/dist/src/remote/codex-rpc.js +94 -0
  34. package/dist/src/remote/http.d.ts +5 -0
  35. package/dist/src/remote/http.js +99 -7
  36. package/dist/src/remote/key.d.ts +4 -0
  37. package/dist/src/remote/key.js +6 -2
  38. package/dist/src/remote/phone-chat.d.ts +57 -0
  39. package/dist/src/remote/phone-chat.js +366 -0
  40. package/dist/src/remote/phone-control.d.ts +6 -0
  41. package/dist/src/remote/phone-control.js +132 -0
  42. package/dist/src/remote/phone-pairing.d.ts +41 -0
  43. package/dist/src/remote/phone-pairing.js +180 -0
  44. package/dist/src/remote/relay.d.ts +37 -0
  45. package/dist/src/remote/relay.js +207 -0
  46. package/docs/CLIENT-APPROVAL.md +44 -9
  47. package/docs/PHONE-PAIRING.md +97 -0
  48. package/extension-dist/THIRD-PARTY-NOTICES.txt +35 -0
  49. package/extension-dist/activity-dashboard.css +4 -9
  50. package/extension-dist/background.js +725 -127
  51. package/extension-dist/brand.css +63 -0
  52. package/extension-dist/manifest.json +1 -1
  53. package/extension-dist/options.html +25 -22
  54. package/extension-dist/options.js +179 -42
  55. package/extension-dist/popup.html +33 -41
  56. package/extension-dist/popup.js +2529 -126
  57. package/extension-dist/site-protection.css +11 -0
  58. package/package.json +13 -2
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startPhoneControl = startPhoneControl;
4
+ exports.phoneControlReply = phoneControlReply;
5
+ /** Private loopback channel used only by the extension's native messaging helper. */
6
+ const node_crypto_1 = require("node:crypto");
7
+ const node_fs_1 = require("node:fs");
8
+ const node_http_1 = require("node:http");
9
+ const node_path_1 = require("node:path");
10
+ const phone_pairing_1 = require("../../shared/phone-pairing");
11
+ const key_1 = require("./key");
12
+ const controlPath = (dir, profile) => (0, node_path_1.join)(dir, 'phone-pairing', `control-${(0, node_crypto_1.createHash)('sha256').update(profile).digest('hex')}.json`);
13
+ async function startPhoneControl(pairing) {
14
+ const secret = (0, node_crypto_1.randomBytes)(32).toString('base64url');
15
+ const server = (0, node_http_1.createServer)((req, res) => {
16
+ res.setHeader('cache-control', 'no-store');
17
+ res.setHeader('content-type', 'application/json');
18
+ const provided = /^Bearer (\S+)$/.exec(req.headers.authorization ?? '')?.[1];
19
+ if (req.method !== 'POST' || req.url !== '/' || req.headers.origin || !(0, key_1.keyMatches)(provided, secret)) {
20
+ res.writeHead(404).end();
21
+ return;
22
+ }
23
+ let body = '';
24
+ req.setTimeout(5_000, () => req.destroy());
25
+ req.on('data', (chunk) => {
26
+ body += chunk.toString('utf8');
27
+ if (Buffer.byteLength(body) > 4096)
28
+ req.destroy();
29
+ });
30
+ req.on('end', () => {
31
+ try {
32
+ const message = JSON.parse(body);
33
+ if (!message || !phone_pairing_1.PHONE_ACTIONS.includes(message.action) ||
34
+ (['approve', 'deny', 'remove'].includes(message.action) && typeof message.id !== 'string'))
35
+ throw new Error('Invalid phone action.');
36
+ const id = typeof message.id === 'string' ? message.id : '';
37
+ if (message.action === 'create')
38
+ pairing.create();
39
+ else if (message.action === 'cancel')
40
+ pairing.cancel();
41
+ else if (message.action === 'approve')
42
+ pairing.approve(id);
43
+ else if (message.action === 'deny')
44
+ pairing.deny(id);
45
+ else if (message.action === 'remove')
46
+ pairing.remove(id);
47
+ res.end(JSON.stringify({ ok: true, state: pairing.state() }));
48
+ }
49
+ catch (err) {
50
+ const message = err instanceof Error && !/JSON|ENOENT|EACCES|ENOSPC/.test(err.message)
51
+ ? err.message : 'Could not save phone access. Try again.';
52
+ res.end(JSON.stringify({ ok: false, message }));
53
+ }
54
+ });
55
+ req.on('error', () => { if (!res.writableEnded)
56
+ res.destroy(); });
57
+ });
58
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
59
+ const address = server.address();
60
+ if (!address || typeof address === 'string')
61
+ throw new Error('Could not start phone pairing.');
62
+ const path = controlPath(pairing.dataDir, pairing.profile);
63
+ const contents = JSON.stringify({ port: address.port, token: secret, pid: process.pid });
64
+ const temporary = `${path}.${process.pid}.tmp`;
65
+ try {
66
+ (0, node_fs_1.writeFileSync)(temporary, contents, { mode: 0o600 });
67
+ (0, node_fs_1.renameSync)(temporary, path);
68
+ }
69
+ catch (err) {
70
+ server.close();
71
+ throw err;
72
+ }
73
+ return { close: async () => {
74
+ pairing.cancel();
75
+ try {
76
+ if ((0, node_fs_1.readFileSync)(path, 'utf8') === contents)
77
+ (0, node_fs_1.unlinkSync)(path);
78
+ }
79
+ catch { /* another process owns it now */ }
80
+ server.closeAllConnections();
81
+ await new Promise((resolve) => server.close(() => resolve()));
82
+ } };
83
+ }
84
+ async function phoneControlReply(dataDir, message) {
85
+ const m = message;
86
+ if (!m || typeof m.profile !== 'string' || m.profile.length > 100 || !phone_pairing_1.PHONE_ACTIONS.includes(m.action)) {
87
+ return { ok: false, message: 'Invalid phone pairing request.' };
88
+ }
89
+ try {
90
+ const config = JSON.parse((0, node_fs_1.readFileSync)(controlPath(dataDir, m.profile), 'utf8'));
91
+ if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535 ||
92
+ typeof config.token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(config.token) || !Number.isInteger(config.pid))
93
+ throw new Error('invalid');
94
+ process.kill(config.pid, 0);
95
+ return await new Promise((resolve, reject) => {
96
+ const body = JSON.stringify({ action: m.action, id: m.id });
97
+ const req = (0, node_http_1.request)({ hostname: '127.0.0.1', port: config.port, path: '/', method: 'POST',
98
+ headers: { authorization: `Bearer ${config.token}`, 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
99
+ }, (res) => {
100
+ let answer = '';
101
+ res.on('data', (chunk) => {
102
+ answer += chunk.toString('utf8');
103
+ if (Buffer.byteLength(answer) > 64 * 1024) {
104
+ res.destroy();
105
+ reject(new Error('too large'));
106
+ }
107
+ });
108
+ res.on('end', () => {
109
+ try {
110
+ if (res.statusCode !== 200)
111
+ throw new Error('unavailable');
112
+ const parsed = JSON.parse(answer);
113
+ if (typeof parsed.ok !== 'boolean')
114
+ throw new Error('invalid');
115
+ resolve(parsed);
116
+ }
117
+ catch (err) {
118
+ reject(err);
119
+ }
120
+ });
121
+ res.on('error', reject);
122
+ });
123
+ req.setTimeout(5_000, () => req.destroy(new Error('timeout')));
124
+ req.on('error', reject);
125
+ req.end(body);
126
+ });
127
+ }
128
+ catch {
129
+ return { ok: false, message: 'Phone pairing is not running for this browser. Start or update its remote connection first.' };
130
+ }
131
+ }
132
+ //# sourceMappingURL=phone-control.js.map
@@ -0,0 +1,41 @@
1
+ import { type PhoneDevice, type PhonePairingState } from '../../shared/phone-pairing';
2
+ import { type ClientIdentity } from '../bridge/client-identity';
3
+ /** Secrets are local; the public relay never receives the browser's master key. */
4
+ export declare class PhonePairing {
5
+ readonly dataDir: string;
6
+ readonly profile: string;
7
+ private readonly path;
8
+ private readonly now;
9
+ private devices;
10
+ private pending;
11
+ private invitation;
12
+ private publicUrl;
13
+ private readonly identities;
14
+ private readonly revoked;
15
+ private readonly listeners;
16
+ constructor(dataDir: string, profile: string, now?: () => number);
17
+ setPublicUrl(value?: string): void;
18
+ private expire;
19
+ state(): PhonePairingState;
20
+ create(): PhonePairingState;
21
+ cancel(): void;
22
+ claim(code: unknown, name: unknown): {
23
+ id: string;
24
+ token: string;
25
+ confirmation: string;
26
+ expiresAt: number;
27
+ };
28
+ approve(id: string): PhonePairingState;
29
+ deny(id: string): PhonePairingState;
30
+ remove(id: string): PhonePairingState;
31
+ onRemove(fn: (id: string) => void): () => void;
32
+ status(secret: unknown): {
33
+ state: 'pending' | 'paired';
34
+ confirmation: string;
35
+ expiresAt: number;
36
+ mcpUrl?: string;
37
+ } | undefined;
38
+ authenticate(secret: unknown): PhoneDevice | undefined;
39
+ identity(id: string): ClientIdentity;
40
+ private save;
41
+ }
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PhonePairing = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const client_auth_1 = require("../../shared/client-auth");
8
+ const phone_pairing_1 = require("../../shared/phone-pairing");
9
+ const client_identity_1 = require("../bridge/client-identity");
10
+ const datadir_1 = require("../bridge/datadir");
11
+ const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
12
+ const token = () => (0, node_crypto_1.randomBytes)(32).toString('base64url');
13
+ const validToken = (value) => typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
14
+ const matches = (value, expected) => validToken(value) && (0, node_crypto_1.timingSafeEqual)(Buffer.from(hash(value)), Buffer.from(expected));
15
+ /** Secrets are local; the public relay never receives the browser's master key. */
16
+ class PhonePairing {
17
+ dataDir;
18
+ profile;
19
+ path;
20
+ now;
21
+ devices = [];
22
+ pending;
23
+ invitation;
24
+ publicUrl;
25
+ identities = new Map();
26
+ revoked = new Set();
27
+ listeners = new Set();
28
+ constructor(dataDir, profile, now = Date.now) {
29
+ this.dataDir = dataDir;
30
+ this.profile = profile;
31
+ this.now = now;
32
+ const dir = (0, node_path_1.join)(dataDir, 'phone-pairing');
33
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
34
+ this.path = (0, node_path_1.join)(dir, `${hash(profile)}.json`);
35
+ if (!(0, node_fs_1.existsSync)(this.path))
36
+ return;
37
+ const saved = JSON.parse((0, node_fs_1.readFileSync)(this.path, 'utf8'));
38
+ if (!Array.isArray(saved) || saved.length > phone_pairing_1.PHONE_MAX_DEVICES)
39
+ throw new Error('Phone pairing storage is invalid.');
40
+ for (const d of saved) {
41
+ if (!d || typeof d.id !== 'string' || !/^[a-f0-9-]{36}$/.test(d.id) ||
42
+ typeof d.name !== 'string' || d.name !== (0, client_auth_1.clientName)(d.name) || d.state !== 'paired' ||
43
+ !/^[a-f0-9]{64}$/.test(d.tokenHash) || typeof d.privateKey !== 'string' ||
44
+ !Number.isSafeInteger(d.requestedAt) || !Number.isSafeInteger(d.expiresAt) ||
45
+ typeof d.confirmation !== 'string' || !/^\d{6}$/.test(d.confirmation))
46
+ throw new Error('Phone pairing storage is invalid.');
47
+ const identity = (0, client_identity_1.createClientIdentity)(() => d.name, (0, node_crypto_1.createPrivateKey)(d.privateKey));
48
+ if (identity.id !== d.clientId || identity.publicKey !== d.publicKey)
49
+ throw new Error('Phone identity storage is invalid.');
50
+ }
51
+ this.devices = saved;
52
+ }
53
+ setPublicUrl(value) {
54
+ if (value !== undefined) {
55
+ const url = new URL(value);
56
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
57
+ throw new Error('Phone pairing needs a secure public address.');
58
+ value = url.toString().replace(/\/+$/, '');
59
+ }
60
+ if (this.publicUrl !== value)
61
+ this.cancel();
62
+ this.publicUrl = value;
63
+ }
64
+ expire() {
65
+ if (this.invitation && this.invitation.expiresAt <= this.now())
66
+ this.invitation = undefined;
67
+ if (this.pending && this.pending.expiresAt <= this.now())
68
+ this.pending = undefined;
69
+ }
70
+ state() {
71
+ this.expire();
72
+ const expose = ({ tokenHash: _tokenHash, privateKey: _privateKey, ...device }) => device;
73
+ return {
74
+ online: !!this.publicUrl,
75
+ profile: this.profile,
76
+ ...(this.invitation && this.publicUrl ? { invitation: {
77
+ payload: JSON.stringify({ type: 'mbe-pairing', v: 1, url: `${this.publicUrl}/pair`, code: this.invitation.code, expiresAt: this.invitation.expiresAt }),
78
+ expiresAt: this.invitation.expiresAt,
79
+ } } : {}),
80
+ devices: [...(this.pending ? [this.pending] : []), ...this.devices.filter((d) => d.expiresAt > this.now() && !this.revoked.has(d.id))].map(expose),
81
+ };
82
+ }
83
+ create() {
84
+ if (!this.publicUrl)
85
+ throw new Error('Remote connection is offline. Try again when this computer reconnects.');
86
+ if (this.devices.filter((d) => d.expiresAt > this.now() && !this.revoked.has(d.id)).length >= phone_pairing_1.PHONE_MAX_DEVICES) {
87
+ throw new Error('Remove a paired phone before adding another.');
88
+ }
89
+ this.pending = undefined;
90
+ this.invitation = { code: token(), expiresAt: this.now() + phone_pairing_1.PHONE_INVITATION_MS };
91
+ return this.state();
92
+ }
93
+ cancel() { this.invitation = undefined; this.pending = undefined; }
94
+ claim(code, name) {
95
+ this.expire();
96
+ const invitation = this.invitation;
97
+ if (!this.publicUrl || !invitation || !matches(code, hash(invitation.code)))
98
+ throw new Error('Pairing code is invalid or expired.');
99
+ if (typeof name !== 'string' || !name.trim() || name.length > 80 || name !== (0, client_auth_1.clientName)(name))
100
+ throw new Error('Enter a valid phone name.');
101
+ const secret = token();
102
+ const { privateKey } = (0, node_crypto_1.generateKeyPairSync)('ec', { namedCurve: 'prime256v1' });
103
+ const displayName = (0, client_auth_1.clientName)(`Phone: ${name}`);
104
+ const identity = (0, client_identity_1.createClientIdentity)(() => displayName, privateKey);
105
+ const pending = {
106
+ id: (0, node_crypto_1.randomUUID)(), name: displayName, clientId: identity.id, publicKey: identity.publicKey,
107
+ tokenHash: hash(secret), privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
108
+ requestedAt: this.now(), expiresAt: invitation.expiresAt, state: 'pending',
109
+ confirmation: String((0, node_crypto_1.randomInt)(1_000_000)).padStart(6, '0'),
110
+ };
111
+ // Consume the invitation before replying. A second scanner cannot reuse it.
112
+ this.invitation = undefined;
113
+ this.pending = pending;
114
+ return { id: pending.id, token: secret, confirmation: pending.confirmation, expiresAt: pending.expiresAt };
115
+ }
116
+ approve(id) {
117
+ this.expire();
118
+ if (!this.publicUrl || !this.pending || this.pending.id !== id)
119
+ throw new Error('That phone request expired. Generate a new QR code.');
120
+ const next = [...this.devices.filter((d) => d.expiresAt > this.now() && !this.revoked.has(d.id)),
121
+ { ...this.pending, state: 'paired', expiresAt: this.now() + phone_pairing_1.PHONE_ACCESS_MS }];
122
+ this.save(next);
123
+ this.pending = undefined;
124
+ return this.state();
125
+ }
126
+ deny(id) {
127
+ if (this.pending?.id === id)
128
+ this.pending = undefined;
129
+ return this.state();
130
+ }
131
+ remove(id) {
132
+ this.revoked.add(id);
133
+ this.identities.delete(id);
134
+ for (const notify of this.listeners)
135
+ notify(id);
136
+ this.save(this.devices.filter((d) => d.id !== id));
137
+ return this.state();
138
+ }
139
+ onRemove(fn) {
140
+ this.listeners.add(fn);
141
+ return () => this.listeners.delete(fn);
142
+ }
143
+ status(secret) {
144
+ this.expire();
145
+ const d = this.pending && matches(secret, this.pending.tokenHash) ? this.pending : this.authenticate(secret);
146
+ if (!d)
147
+ return undefined;
148
+ return { state: d.state, confirmation: d.confirmation, expiresAt: d.expiresAt,
149
+ ...(d.state === 'paired' && this.publicUrl ? { mcpUrl: `${this.publicUrl}/mcp` } : {}) };
150
+ }
151
+ authenticate(secret) {
152
+ return this.devices.find((d) => !this.revoked.has(d.id) && d.expiresAt > this.now() && matches(secret, d.tokenHash));
153
+ }
154
+ identity(id) {
155
+ const d = this.devices.find((d) => d.id === id && !this.revoked.has(id) && d.expiresAt > this.now());
156
+ if (!d)
157
+ throw new Error('Phone access was removed or expired.');
158
+ const cached = this.identities.get(id);
159
+ if (cached)
160
+ return cached;
161
+ const identity = (0, client_identity_1.createClientIdentity)(() => d.name, (0, node_crypto_1.createPrivateKey)(d.privateKey));
162
+ identity.profile = this.profile;
163
+ identity.workspace = (0, datadir_1.ensureWorkspace)(this.dataDir, this.profile, `phone-${id}`);
164
+ identity.assertAccess = () => {
165
+ if (this.revoked.has(id) || !this.devices.some((x) => x.id === id && x.expiresAt > this.now()))
166
+ throw new Error('Phone access was removed or expired.');
167
+ };
168
+ this.identities.set(id, identity);
169
+ return identity;
170
+ }
171
+ save(devices) {
172
+ const temporary = `${this.path}.${(0, node_crypto_1.randomUUID)()}.tmp`;
173
+ (0, node_fs_1.writeFileSync)(temporary, JSON.stringify(devices), { mode: 0o600, flag: 'wx' });
174
+ (0, node_fs_1.chmodSync)(temporary, 0o600);
175
+ (0, node_fs_1.renameSync)(temporary, this.path);
176
+ this.devices = devices;
177
+ }
178
+ }
179
+ exports.PhonePairing = PhonePairing;
180
+ //# sourceMappingURL=phone-pairing.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * src/remote/relay.ts — a permanent public address for the local HTTP endpoint,
3
+ * through a relay server the person runs (for example on AWS).
4
+ *
5
+ * This computer dials out to the relay over a WebSocket, so no inbound port is
6
+ * opened here, and the relay hands each public request down that socket. Every
7
+ * request is replayed against the local `--http` server, so the remote key, app
8
+ * approval and site approval all still apply on this computer; the relay only
9
+ * carries bytes. The link itself is guarded by the relay token, kept in
10
+ * `<dataDir>/relay-token` (mode 0600) and configured on the relay server.
11
+ *
12
+ * Frames are JSON text; bodies and chunks are base64:
13
+ * relay -> here: hello {publicUrl}, req {id, method, path, headers, body?}, cancel {id}
14
+ * here -> relay: head {id, status, headers}, data {id, chunk}, end {id}, fail {id, message}
15
+ */
16
+ import { type IncomingHttpHeaders } from 'node:http';
17
+ export type Headers = Record<string, string | string[]>;
18
+ export interface RelayLink {
19
+ stop(): void;
20
+ }
21
+ export interface RelayOptions {
22
+ /** The relay's base URL, e.g. https://relay.example.com; the link dials `<url>/connect`. */
23
+ url: string;
24
+ token: string;
25
+ localPort: number;
26
+ log: (message: string) => void;
27
+ /** Each time the relay accepts this computer, with the address clients use. */
28
+ onReady?: (publicUrl: string) => void;
29
+ onOffline?: () => void;
30
+ }
31
+ export declare function relayTokenPath(dataDir: string): string;
32
+ export declare function resolveRelayToken(dataDir: string): string;
33
+ /** The relay's WebSocket address for a base URL given as http(s) or ws(s). */
34
+ export declare function connectUrl(base: string): string;
35
+ /** Lower-cased headers without the hop-by-hop ones. */
36
+ export declare function endToEndHeaders(headers: IncomingHttpHeaders | Headers): Headers;
37
+ export declare function connectRelay(opts: RelayOptions): RelayLink;
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ /**
3
+ * src/remote/relay.ts — a permanent public address for the local HTTP endpoint,
4
+ * through a relay server the person runs (for example on AWS).
5
+ *
6
+ * This computer dials out to the relay over a WebSocket, so no inbound port is
7
+ * opened here, and the relay hands each public request down that socket. Every
8
+ * request is replayed against the local `--http` server, so the remote key, app
9
+ * approval and site approval all still apply on this computer; the relay only
10
+ * carries bytes. The link itself is guarded by the relay token, kept in
11
+ * `<dataDir>/relay-token` (mode 0600) and configured on the relay server.
12
+ *
13
+ * Frames are JSON text; bodies and chunks are base64:
14
+ * relay -> here: hello {publicUrl}, req {id, method, path, headers, body?}, cancel {id}
15
+ * here -> relay: head {id, status, headers}, data {id, chunk}, end {id}, fail {id, message}
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.relayTokenPath = relayTokenPath;
19
+ exports.resolveRelayToken = resolveRelayToken;
20
+ exports.connectUrl = connectUrl;
21
+ exports.endToEndHeaders = endToEndHeaders;
22
+ exports.connectRelay = connectRelay;
23
+ const node_http_1 = require("node:http");
24
+ const node_path_1 = require("node:path");
25
+ const ws_1 = require("ws");
26
+ const key_1 = require("./key");
27
+ const TOKEN_FILE = 'relay-token';
28
+ const RETRY_MIN_MS = 1_000;
29
+ const RETRY_MAX_MS = 30_000;
30
+ /** Pings keep idle proxies from closing the link and notice a dead one. */
31
+ const PING_MS = 25_000;
32
+ const PONG_TIMEOUT_MS = 60_000;
33
+ /** Headers that describe one hop rather than the request; never carried across. */
34
+ const HOP_BY_HOP = new Set([
35
+ 'connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'upgrade', 'te', 'trailer',
36
+ 'host', 'content-length',
37
+ ]);
38
+ function relayTokenPath(dataDir) {
39
+ return (0, node_path_1.join)(dataDir, TOKEN_FILE);
40
+ }
41
+ function resolveRelayToken(dataDir) {
42
+ return (0, key_1.resolveSecret)(relayTokenPath(dataDir));
43
+ }
44
+ /** The relay's WebSocket address for a base URL given as http(s) or ws(s). */
45
+ function connectUrl(base) {
46
+ const url = new URL(base);
47
+ if (url.protocol === 'https:')
48
+ url.protocol = 'wss:';
49
+ else if (url.protocol === 'http:')
50
+ url.protocol = 'ws:';
51
+ else if (url.protocol !== 'wss:' && url.protocol !== 'ws:') {
52
+ throw new Error(`--relay needs an http(s) URL, got ${base}`);
53
+ }
54
+ url.pathname = `${url.pathname.replace(/\/+$/, '')}/connect`;
55
+ url.search = '';
56
+ url.hash = '';
57
+ return url.toString();
58
+ }
59
+ /** Lower-cased headers without the hop-by-hop ones. */
60
+ function endToEndHeaders(headers) {
61
+ const out = {};
62
+ for (const [name, value] of Object.entries(headers)) {
63
+ const key = name.toLowerCase();
64
+ if (value === undefined || HOP_BY_HOP.has(key))
65
+ continue;
66
+ out[key] = value;
67
+ }
68
+ return out;
69
+ }
70
+ /** Only an origin-relative path may reach the local server, never an absolute URL. */
71
+ function safePath(path) {
72
+ return typeof path === 'string' && path.startsWith('/') && !path.startsWith('//');
73
+ }
74
+ function connectRelay(opts) {
75
+ const target = connectUrl(opts.url);
76
+ const inflight = new Map();
77
+ let socket = null;
78
+ let stopped = false;
79
+ let retryMs = RETRY_MIN_MS;
80
+ let retryTimer;
81
+ // Log changes, not every retry: a long outage would otherwise fill the log.
82
+ let up = false;
83
+ let outageLogged = false;
84
+ const dropInflight = () => {
85
+ for (const req of inflight.values())
86
+ req.destroy();
87
+ inflight.clear();
88
+ };
89
+ const send = (ws, frame) => {
90
+ if (ws.readyState === ws_1.WebSocket.OPEN)
91
+ ws.send(JSON.stringify(frame));
92
+ };
93
+ const forward = (ws, frame) => {
94
+ const { id } = frame;
95
+ if (!safePath(frame.path))
96
+ return send(ws, { t: 'fail', id, message: 'bad path' });
97
+ const body = frame.body ? Buffer.from(frame.body, 'base64') : undefined;
98
+ const headers = endToEndHeaders(frame.headers ?? {});
99
+ if (body)
100
+ headers['content-length'] = String(body.length);
101
+ const req = (0, node_http_1.request)({ host: '127.0.0.1', port: opts.localPort, method: frame.method, path: frame.path, headers }, (res) => {
102
+ send(ws, { t: 'head', id, status: res.statusCode ?? 502, headers: endToEndHeaders(res.headers) });
103
+ res.on('data', (chunk) => send(ws, { t: 'data', id, chunk: chunk.toString('base64') }));
104
+ res.on('end', () => {
105
+ inflight.delete(id);
106
+ send(ws, { t: 'end', id });
107
+ });
108
+ res.on('error', () => {
109
+ inflight.delete(id);
110
+ send(ws, { t: 'fail', id, message: 'local response failed' });
111
+ });
112
+ });
113
+ req.on('error', (err) => {
114
+ if (!inflight.delete(id))
115
+ return; // cancelled: the relay already let go
116
+ send(ws, { t: 'fail', id, message: `local server unreachable: ${err.message}` });
117
+ });
118
+ inflight.set(id, req);
119
+ req.end(body);
120
+ };
121
+ const scheduleRetry = () => {
122
+ if (stopped)
123
+ return;
124
+ retryTimer = setTimeout(open, retryMs);
125
+ retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
126
+ };
127
+ function open() {
128
+ if (stopped)
129
+ return;
130
+ const ws = new ws_1.WebSocket(target, { headers: { authorization: `Bearer ${opts.token}` } });
131
+ socket = ws;
132
+ let alive = true;
133
+ let ping;
134
+ ws.on('unexpected-response', (_req, res) => {
135
+ if (!outageLogged) {
136
+ outageLogged = true;
137
+ opts.log(res.statusCode === 401 || res.statusCode === 403
138
+ ? 'the relay refused this computer: its relay token does not match the one set on the relay server.'
139
+ : `the relay answered ${res.statusCode}; retrying`);
140
+ }
141
+ ws.terminate();
142
+ });
143
+ ws.on('open', () => {
144
+ ping = setInterval(() => {
145
+ if (!alive)
146
+ return ws.terminate();
147
+ alive = false;
148
+ ws.ping();
149
+ }, PING_MS);
150
+ ping.unref();
151
+ });
152
+ ws.on('pong', () => {
153
+ alive = true;
154
+ });
155
+ ws.on('message', (data) => {
156
+ let frame;
157
+ try {
158
+ frame = JSON.parse(data.toString());
159
+ }
160
+ catch {
161
+ return;
162
+ }
163
+ if (frame.t === 'hello' && typeof frame.publicUrl === 'string') {
164
+ retryMs = RETRY_MIN_MS;
165
+ up = true;
166
+ outageLogged = false;
167
+ opts.onReady?.(frame.publicUrl);
168
+ }
169
+ else if (frame.t === 'req' && typeof frame.id === 'string') {
170
+ forward(ws, frame);
171
+ }
172
+ else if (frame.t === 'cancel' && typeof frame.id === 'string') {
173
+ const req = inflight.get(frame.id);
174
+ inflight.delete(frame.id);
175
+ req?.destroy();
176
+ }
177
+ });
178
+ ws.on('close', () => {
179
+ clearInterval(ping);
180
+ if (socket === ws)
181
+ socket = null;
182
+ dropInflight();
183
+ opts.onOffline?.();
184
+ if (up && !stopped)
185
+ opts.log('relay link lost; reconnecting');
186
+ up = false;
187
+ scheduleRetry();
188
+ });
189
+ // 'close' follows every 'error', and is where the retry is scheduled.
190
+ ws.on('error', (err) => {
191
+ if (outageLogged)
192
+ return;
193
+ outageLogged = true;
194
+ opts.log(`cannot reach the relay (${err.message}); retrying`);
195
+ });
196
+ }
197
+ open();
198
+ return {
199
+ stop: () => {
200
+ stopped = true;
201
+ clearTimeout(retryTimer);
202
+ dropInflight();
203
+ socket?.close();
204
+ },
205
+ };
206
+ }
207
+ //# sourceMappingURL=relay.js.map
@@ -25,11 +25,44 @@ profile. Expired access requires a new approval. Each initialized MCP session,
25
25
  including each remote HTTP session, receives a new key. Restarting a session
26
26
  requires approval again. Several sessions with the same name are separate keys.
27
27
 
28
- App approval does not approve websites. Each website must also be on the allowed
29
- sites list. A blocked request gives one line of instructions to click Allow next
30
- to that website in the Chrome popup. All-site access is no longer supported:
31
- remove `--unsafe-all-domains` from older configurations. Catch-all policy entries
32
- grant no access, including when sent by an older server.
28
+ App approval does not supply Chrome website permission. **Suspicious-site checks**
29
+ are selected by default. A person clicks **Allow website access** in the popup or
30
+ Settings and accepts Chrome's optional HTTP/HTTPS permission once. Ordinary sites
31
+ then work automatically; only local warnings need Allow. Before that grant, the
32
+ extension asks for setup without queueing ordinary websites. **Use per-site
33
+ approval** or **Turn off** explicitly selects the named-site mode; that choice is
34
+ remembered. Old inherited broad permissions are still removed during migration.
35
+ Server flags cannot supply the Chrome grant or override the browser preference, and
36
+ `--no-site-grants` disables it. The retired `--unsafe-all-domains` flag and
37
+ catch-all allowlist entries remain unsupported.
38
+
39
+ The local rules check selected brand impersonation patterns, lookalike addresses,
40
+ unencrypted password pages and destinations, explicit GET password forms, and
41
+ password pages claiming a recognised brand outside its configured domains. A
42
+ password field or an internationalised domain alone is not a warning. The brand
43
+ list is limited, and these rules can miss scams or flag legitimate sites. This
44
+ is not antivirus, a reputation database, or protection against prompt injection.
45
+ Form checks run after loading, before app reads or actions; page scripts can run
46
+ while loading. Form checks cover visible password inputs in the targeted document;
47
+ closed shadow roots, canvas interfaces and arbitrary script-driven submissions
48
+ are not inspected. New page states are checked on subsequent commands and between
49
+ batched form fields; this does not make page changes and actions atomic.
50
+
51
+ Warnings and approvals stay in the Chrome profile. Approval covers the displayed
52
+ reason IDs at an exact origin (scheme, hostname and port); changed reasons need
53
+ review again. A stale Allow click cannot approve a newly changed warning. Removing
54
+ an exception makes the next matching check wait again. Blocked websites remain
55
+ blocked until restored. Turning automatic access off removes its broad Chrome
56
+ grant and returns to named-site access. Revoking that Chrome grant requires setup
57
+ again. Automatic checks never auto-approve an app or a Chrome permission dialog.
58
+
59
+ The server negotiates signed `site_check` support per paired browser, including
60
+ through peers. It checks tool capabilities before asking that browser for a site
61
+ decision, and the worker checks the actual page again before execution. Old
62
+ extensions retain the original server allowlist gate. Observer hooks in automatic
63
+ mode are installed on demand after checking the page, never across every site at
64
+ document start. Late navigation warnings withhold results without automatically
65
+ replaying an action that already started.
33
66
 
34
67
  Allowing a website permits approved apps to read and take actions there, subject
35
68
  to configured tool permissions. This includes sending messages, deleting
@@ -125,10 +158,12 @@ Transport pairing may succeed while browser access remains blocked.
125
158
 
126
159
  This is session authorization for the extension, not isolation between approved
127
160
  apps. Approved apps still share permitted tabs and the existing browser policy.
128
- Website content access additionally requires a named Chrome host permission.
129
- The popup's Allow action requests Chrome permission before adding the server
130
- grant, and Remove revokes the host permission. Server flags, saved app approval
131
- and YOLO mode cannot supply the Chrome grant. Cookies and downloads also require
161
+ Website content access additionally requires Chrome host permission: the explicit
162
+ HTTP/HTTPS grant for automatic access, or individually named sites. In named-site
163
+ mode, Allow requests Chrome permission before adding the server grant, and Remove
164
+ revokes the host permission. In automatic mode, Block keeps a site inaccessible
165
+ without removing the shared broad grant. Server flags, saved app approval and
166
+ YOLO mode cannot supply the Chrome grant. Cookies and downloads also require
132
167
  their optional API permission. Debugger and proxy remain required permissions
133
168
  because Chrome does not support them as optional; debugger access is checked
134
169
  against website permission by the extension, rather than isolated by Chrome.