@clawchatsai/connector 0.1.47 → 0.1.49
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/dist/auth-handler.d.ts +47 -29
- package/dist/auth-handler.js +306 -245
- package/dist/chunk-reassembly.d.ts +38 -0
- package/dist/chunk-reassembly.js +88 -0
- package/dist/config-store.d.ts +46 -0
- package/dist/config-store.js +154 -0
- package/dist/index.js +168 -213
- package/dist/totp.js +3 -1
- package/dist/webrtc-peer.js +11 -2
- package/package.json +3 -2
- package/server/controllers/static.js +19 -3
- package/server/controllers/static.test.js +48 -0
- package/server/controllers/title.js +12 -2
- package/server/debug.js +3 -1
- package/server/debug.test.js +23 -1
- package/server/index.js +6 -0
- package/server/peer/link.js +5 -1
- package/server/peer/link.test.js +10 -0
- package/server/peer/sharing.js +172 -34
- package/server/peer/sharing.test.js +153 -0
- package/server/team.js +116 -32
- package/server/team.test.js +131 -4
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Writable } from 'node:stream';
|
|
7
|
+
import { handleStatic, resolveStaticPath } from './static.js';
|
|
8
|
+
|
|
9
|
+
function setup() {
|
|
10
|
+
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-static-'));
|
|
11
|
+
const root = path.join(base, 'plugin');
|
|
12
|
+
fs.mkdirSync(path.join(root, 'frontend'), { recursive: true });
|
|
13
|
+
fs.writeFileSync(path.join(root, 'frontend', 'app.js'), 'ok');
|
|
14
|
+
fs.writeFileSync(path.join(base, 'secret.txt'), 'secret');
|
|
15
|
+
fs.mkdirSync(path.join(base, 'plugin-evil'));
|
|
16
|
+
fs.writeFileSync(path.join(base, 'plugin-evil', 'x.js'), 'sibling');
|
|
17
|
+
fs.symlinkSync(path.join(base, 'secret.txt'), path.join(root, 'frontend', 'link.js'));
|
|
18
|
+
fs.symlinkSync(base, path.join(root, 'frontend', 'up'));
|
|
19
|
+
return { base, root };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function get(url, root) {
|
|
23
|
+
const out = { status: 0, served: false };
|
|
24
|
+
const res = new Writable({ write(_c, _e, cb) { cb(); } });
|
|
25
|
+
res.writeHead = (s) => { out.status = s; out.served = true; };
|
|
26
|
+
out.handled = handleStatic({ url }, res, root);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
test('static files: inside the plugin dir only (.., absolute, NUL, sibling prefix, symlinks)', async () => {
|
|
31
|
+
const { base, root } = setup();
|
|
32
|
+
assert.equal(resolveStaticPath(root, 'frontend/app.js'), fs.realpathSync(path.join(root, 'frontend', 'app.js')));
|
|
33
|
+
for (const rel of ['frontend/../../secret.txt', '../secret.txt', path.join(base, 'secret.txt'), '/etc/passwd',
|
|
34
|
+
'frontend/app.js\0.png', '../plugin-evil/x.js', 'frontend/link.js', 'frontend/up/secret.txt', 'frontend/missing.js', '']) {
|
|
35
|
+
assert.equal(resolveStaticPath(root, rel), null, JSON.stringify(rel));
|
|
36
|
+
}
|
|
37
|
+
assert.equal(resolveStaticPath(root, 42), null);
|
|
38
|
+
|
|
39
|
+
assert.equal(get('/frontend/app.js', root).status, 200);
|
|
40
|
+
for (const url of ['/frontend/../../secret.txt', '/frontend/../../../../etc/passwd', '/lib/../../secret.txt',
|
|
41
|
+
'/frontend/link.js', '/frontend/up/secret.txt', '/frontend/app.js%00']) {
|
|
42
|
+
const r = get(url, root);
|
|
43
|
+
assert.equal(r.handled, false, url);
|
|
44
|
+
assert.equal(r.served, false, url);
|
|
45
|
+
}
|
|
46
|
+
await new Promise(r => setTimeout(r, 50)); // the served file's read stream
|
|
47
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
48
|
+
});
|
|
@@ -54,7 +54,17 @@ export function createTitleHandler(llm) {
|
|
|
54
54
|
if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
|
|
55
55
|
const { message } = await parseBody(req);
|
|
56
56
|
if (typeof message !== 'string' || !message.trim()) return sendError(res, 400, 'Missing message');
|
|
57
|
-
const
|
|
58
|
-
|
|
57
|
+
const source = Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join('');
|
|
58
|
+
let result;
|
|
59
|
+
try {
|
|
60
|
+
result = await complete(source);
|
|
61
|
+
} catch (err) {
|
|
62
|
+
console.warn(`[title] completion failed (source ${source.length} chars): ${err?.code || ''} ${err?.stack || err}`);
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
const title = normalizeTitle(result?.text);
|
|
66
|
+
// The reason a retitle comes back empty: which model answered, and what it actually returned.
|
|
67
|
+
if (!title) console.warn(`[title] no title from ${result?.provider}/${result?.model} (source ${source.length} chars, reply ${JSON.stringify(String(result?.text ?? '').slice(0, 200))}, keys ${Object.keys(result || {}).join(',')})`);
|
|
68
|
+
return send(res, 200, { title, model: result?.provider && result?.model ? `${result.provider}/${result.model}` : undefined });
|
|
59
69
|
};
|
|
60
70
|
}
|
package/server/debug.js
CHANGED
|
@@ -25,7 +25,9 @@ export class DebugLogger {
|
|
|
25
25
|
|
|
26
26
|
start(ts, originatingClient) {
|
|
27
27
|
if (this.active) return { error: 'already-active', sessionId: this.sessionId };
|
|
28
|
-
|
|
28
|
+
// The id names files in baseDir: only an ISO-timestamp-like token, never a path
|
|
29
|
+
const id = typeof ts === 'string' ? ts.replace(/[:.]/g, '-') : '';
|
|
30
|
+
this.sessionId = /^[A-Za-z0-9_-]{1,64}$/.test(id) ? id : new Date().toISOString().replace(/[:.]/g, '-');
|
|
29
31
|
this.originatingClient = originatingClient;
|
|
30
32
|
fs.mkdirSync(this.baseDir, { recursive: true });
|
|
31
33
|
this.wsStream = fs.createWriteStream(path.join(this.baseDir, `session-${this.sessionId}-ws.log`), { flags: 'a' });
|
package/server/debug.test.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
|
-
import
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { redactFrame, DebugLogger } from './debug.js';
|
|
4
7
|
|
|
5
8
|
test('question.resolve answers are masked in debug logs', () => {
|
|
6
9
|
const frame = JSON.stringify({ type: 'req', id: '1', method: 'question.resolve', params: { id: 'q', answers: { answers: { api_key: ['sk-live-SECRET'], other: ['a', 'b'] } }, secretStoreAllowedHosts: ['api.example.com'] } });
|
|
@@ -20,3 +23,22 @@ test('other frames pass through untouched; unparseable question.resolve frames a
|
|
|
20
23
|
const cancel = JSON.stringify({ type: 'req', method: 'question.resolve', params: { id: 'q', cancel: true } });
|
|
21
24
|
assert.equal(redactFrame(cancel), cancel);
|
|
22
25
|
});
|
|
26
|
+
|
|
27
|
+
test('debug-start: the session id can never be a path', async (t) => {
|
|
28
|
+
t.mock.method(console, 'log', () => {});
|
|
29
|
+
const data = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-debug-')) + '/data';
|
|
30
|
+
for (const ts of ['../../../../tmp/evil', '/etc/cron.d/x', 'a/b', 'a\\b', 'x\0y', '', 'z'.repeat(200), undefined, 42, { a: 1 }]) {
|
|
31
|
+
const d = new DebugLogger(data);
|
|
32
|
+
const r = d.start(ts, {});
|
|
33
|
+
assert.match(r.sessionId, /^[A-Za-z0-9_-]{1,64}$/, String(ts));
|
|
34
|
+
d.handleClientDisconnect({}); // closes nothing (other client)
|
|
35
|
+
d.saveDump({});
|
|
36
|
+
}
|
|
37
|
+
const d = new DebugLogger(data);
|
|
38
|
+
assert.equal(d.start('2026-10-28T20:48:00.000Z', {}).sessionId, '2026-10-28T20-48-00-000Z');
|
|
39
|
+
d.saveDump({});
|
|
40
|
+
await new Promise(r => setTimeout(r, 100)); // write streams open asynchronously
|
|
41
|
+
const files = fs.readdirSync(path.join(data, '..', 'debug'));
|
|
42
|
+
assert.ok(files.every(f => /^session-[A-Za-z0-9_-]+-ws\.log$/.test(f)), files.join(','));
|
|
43
|
+
fs.rmSync(path.dirname(data), { recursive: true, force: true });
|
|
44
|
+
});
|
package/server/index.js
CHANGED
|
@@ -290,6 +290,12 @@ export function createApp(config = {}) {
|
|
|
290
290
|
try { return send(res, 200, sharing.markKeyVerified(p.id)); }
|
|
291
291
|
catch (e) { return sendError(res, 400, e.message); }
|
|
292
292
|
}
|
|
293
|
+
// Their gateway key changed (shares list `keyChanged`): the owner accepts the new one after checking it with them.
|
|
294
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/trust-key'))) {
|
|
295
|
+
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
296
|
+
try { return send(res, 200, sharing.trustNewKey(p.id)); }
|
|
297
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
298
|
+
}
|
|
293
299
|
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/revoke'))) {
|
|
294
300
|
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
295
301
|
sharing.revoke(p.id);
|
package/server/peer/link.js
CHANGED
|
@@ -48,7 +48,10 @@ export class PeerLink extends EventEmitter {
|
|
|
48
48
|
this._handlers = new Map(); // method -> async (params, emit) => result
|
|
49
49
|
this._timer = setTimeout(() => this._fail('handshake timed out'), handshakeMs);
|
|
50
50
|
this._timer.unref?.();
|
|
51
|
-
dc.onMessage(data =>
|
|
51
|
+
dc.onMessage(data => {
|
|
52
|
+
// A frame must never throw into the channel's dispatch (that would take the gateway down)
|
|
53
|
+
try { this._onFrame(data); } catch (e) { this.log.warn?.(`[peer] ${this.shareId}: frame handling failed: ${e?.message}`); this._fail('bad frame'); }
|
|
54
|
+
});
|
|
52
55
|
dc.onClosed(() => this._onClosed());
|
|
53
56
|
this._send({ t: 'hello', v: 1, role, shareId, nonce: this.nonce });
|
|
54
57
|
}
|
|
@@ -63,6 +66,7 @@ export class PeerLink extends EventEmitter {
|
|
|
63
66
|
if (typeof data !== 'string' || data.length > MAX_FRAME) return this._fail('oversized frame');
|
|
64
67
|
let m;
|
|
65
68
|
try { m = JSON.parse(data); } catch { return this._fail('bad frame'); }
|
|
69
|
+
if (!m || typeof m !== 'object') return this._fail('bad frame');
|
|
66
70
|
if (!this.ready) return this._onHandshake(m);
|
|
67
71
|
if (m.t === 'req') return this._onRequest(m);
|
|
68
72
|
if (m.t === 'res') {
|
package/server/peer/link.test.js
CHANGED
|
@@ -100,3 +100,13 @@ test('a peer that never authenticates is dropped; frames before auth are refused
|
|
|
100
100
|
assert.match(await until(r2, 'failed'), /before auth/);
|
|
101
101
|
void dx;
|
|
102
102
|
});
|
|
103
|
+
|
|
104
|
+
test('malformed frames (null, numbers, arrays) fail the link instead of throwing', async () => {
|
|
105
|
+
for (const frame of ['null', '5', '"x"', '[]', '{"t":"auth"}']) {
|
|
106
|
+
const { req, own } = linkPair();
|
|
107
|
+
const failed = until(own, 'failed');
|
|
108
|
+
assert.doesNotThrow(() => own.dc.handlers.forEach(h => h(frame)));
|
|
109
|
+
assert.ok(await failed, frame);
|
|
110
|
+
req.close();
|
|
111
|
+
}
|
|
112
|
+
});
|
package/server/peer/sharing.js
CHANGED
|
@@ -22,16 +22,27 @@ const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
|
22
22
|
const DEFAULT_DAILY_CAP = 50;
|
|
23
23
|
const MAX_CONCURRENT_TURNS = 2; // per share: the daily cap alone would allow 50 parallel 10-minute runs
|
|
24
24
|
const ACCESS_MODES = { restricted: 'read-only', trusted: 'guarded' };
|
|
25
|
+
/**
|
|
26
|
+
* Requests one contact's gateway may make of this one over the sharing link: [burst, per ms] token
|
|
27
|
+
* buckets per contact and kind. Far above what a person and their agents send in a chat (a turn per
|
|
28
|
+
* agent per round, a post per message, batched room pushes); they stop a peer that floods.
|
|
29
|
+
*/
|
|
30
|
+
const PEER_RATES = { turn: [20, 60_000], 'room.post': [30, 60_000], 'room.sync': [300, 60_000], '*': [120, 60_000] };
|
|
25
31
|
/**
|
|
26
32
|
* The gateway loads any local image path or file:// URL written in a prompt (detectImageReferences),
|
|
27
33
|
* ignoring the agent's tool policy and fs.workspaceOnly, so a guest could type the path of one of the
|
|
28
34
|
* owner's screenshots and have the agent describe it. A zero-width space before each path with a file
|
|
29
35
|
* extension (and inside `file://`) stops that match; the agent still reads the text normally, and
|
|
30
36
|
* other text (`/commands`, `~`) passes through unchanged.
|
|
37
|
+
* The gateway blanks attachment markers ("[media attached: \u2026]", "[Image: source: \u2026]") before it looks
|
|
38
|
+
* for paths, so a path right after one starts a fresh word there: markers are broken too (and `]`
|
|
39
|
+
* counts as a word start), and "MEDIA:" lines never pass as the gateway's attachment syntax.
|
|
31
40
|
*/
|
|
32
|
-
export const defangLocalPaths = text => text
|
|
41
|
+
export const defangLocalPaths = text => String(text ?? '')
|
|
42
|
+
.replace(/\[(?=\s*(?:media\s+attached|image\s*:))/gi, '[\u200b')
|
|
33
43
|
.replace(/file:\/\//gi, 'file:\u200b//')
|
|
34
|
-
.replace(
|
|
44
|
+
.replace(/\bMEDIA:/gi, m => `${m.slice(0, -1)}\u200b:`)
|
|
45
|
+
.replace(/(^|[\s"'`(\]])(?=(?:\.\.?[\\/]|[~/\\]|[A-Za-z]:[\\/])[^\s"'`()[\]]*\.[A-Za-z0-9])/g, '$1\u200b');
|
|
35
46
|
const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team chat on behalf of your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
36
47
|
// The same agent in its owner's own team chat, answering another person's agent (localTurnFor).
|
|
37
48
|
const ACTING_FOR_NOTE = (name, byPerson) => `(Shared session: in your owner's team chat, you are answering ${byPerson ? name : `${name}'s agent`}, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
@@ -67,7 +78,9 @@ export class SharingManager {
|
|
|
67
78
|
this._linking = new Map(); // shareId -> Promise<PeerLink>
|
|
68
79
|
this._served = new Set(); // owner-side PeerLinks
|
|
69
80
|
this._runs = new Map(); // runId -> { resolve, timer, text } (owner-side guest runs)
|
|
70
|
-
|
|
81
|
+
// Owner-side guest turns, keyed by an id made here (never the requester's): { shareId, clientTurnId, sessionKey, runId, aborted }
|
|
82
|
+
this._turns = new Map();
|
|
83
|
+
this._buckets = new Map(); // `${gateway}|${kind}` -> { tokens, at } (PEER_RATES)
|
|
71
84
|
this._ready = false;
|
|
72
85
|
}
|
|
73
86
|
|
|
@@ -86,6 +99,18 @@ export class SharingManager {
|
|
|
86
99
|
// counts as verified on every share with it, a different key doesn't).
|
|
87
100
|
g.exec(`CREATE TABLE IF NOT EXISTS peer_key_verified (share_id TEXT PRIMARY KEY, pubkey TEXT NOT NULL, verified_at INTEGER NOT NULL)`);
|
|
88
101
|
g.exec(`CREATE TABLE IF NOT EXISTS peer_guest_agents (agent_id TEXT PRIMARY KEY, created_at INTEGER NOT NULL)`);
|
|
102
|
+
// Each contact's key, by their gateway id, pinned on first use (either direction). A share can't bring
|
|
103
|
+
// another key for that gateway; only the owner can accept a changed one (trustNewKey).
|
|
104
|
+
g.exec(`CREATE TABLE IF NOT EXISTS peer_gateway_keys (gateway_id TEXT PRIMARY KEY, pubkey TEXT NOT NULL, created_at INTEGER NOT NULL)`);
|
|
105
|
+
// Requester side: the owner gateway a share's pinned key signed for (ownerOf, also once the share has ended).
|
|
106
|
+
if (!g.prepare('PRAGMA table_info(peer_pins)').all().some(c => c.name === 'owner_gateway_id')) g.exec('ALTER TABLE peer_pins ADD COLUMN owner_gateway_id TEXT');
|
|
107
|
+
// Gateways already approved here keep the key they were approved with (newest grant first).
|
|
108
|
+
for (const r of g.prepare('SELECT grant_json FROM peer_grants WHERE revoked_at IS NULL ORDER BY created_at DESC').all()) {
|
|
109
|
+
try {
|
|
110
|
+
const gr = JSON.parse(r.grant_json);
|
|
111
|
+
if (gr.requesterGatewayId && gr.requesterPubKey) g.prepare('INSERT OR IGNORE INTO peer_gateway_keys (gateway_id, pubkey, created_at) VALUES (?, ?, ?)').run(gr.requesterGatewayId, gr.requesterPubKey, Date.now());
|
|
112
|
+
} catch { /* unreadable grant */ }
|
|
113
|
+
}
|
|
89
114
|
this._ready = true;
|
|
90
115
|
}
|
|
91
116
|
return g;
|
|
@@ -165,10 +190,43 @@ export class SharingManager {
|
|
|
165
190
|
out.theirKey = pin ? fingerprint(pin) : null;
|
|
166
191
|
out.keyVerified = !!pin && this._keyVerified(s.id, pin);
|
|
167
192
|
}
|
|
193
|
+
// The server shows a different key for them than the one pinned for their gateway: refused until the owner trusts it.
|
|
194
|
+
const presented = s.as === 'owner' ? s.requester?.pubKey : s.owner?.pubKey;
|
|
195
|
+
const pinned = this._gatewayKey(this._other(s).gatewayId);
|
|
196
|
+
out.keyChanged = !!(presented && pinned && presented !== pinned);
|
|
168
197
|
return out;
|
|
169
198
|
});
|
|
170
199
|
}
|
|
171
200
|
|
|
201
|
+
/** The key pinned for a contact's gateway, or null before first use. */
|
|
202
|
+
_gatewayKey(gatewayId) {
|
|
203
|
+
return gatewayId ? this._db().prepare('SELECT pubkey FROM peer_gateway_keys WHERE gateway_id = ?').get(gatewayId)?.pubkey || null : null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Pin a gateway's key on first use. False when another key is pinned for it. */
|
|
207
|
+
_pinGatewayKey(gatewayId, pubKey) {
|
|
208
|
+
if (!gatewayId || !pubKey) return false;
|
|
209
|
+
this._db().prepare('INSERT OR IGNORE INTO peer_gateway_keys (gateway_id, pubkey, created_at) VALUES (?, ?, ?)').run(gatewayId, pubKey, Date.now());
|
|
210
|
+
return this._gatewayKey(gatewayId) === pubKey;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The owner accepts the key the server now shows for this share's other side (they reinstalled, say),
|
|
215
|
+
* after checking it with them. Until then a changed key is refused on every share with that gateway.
|
|
216
|
+
*/
|
|
217
|
+
trustNewKey(shareId) {
|
|
218
|
+
const s = this._shares.find(x => x.id === shareId);
|
|
219
|
+
const gw = s && this._other(s).gatewayId;
|
|
220
|
+
const key = s?.as === 'owner' ? s.requester?.pubKey : s?.owner?.pubKey;
|
|
221
|
+
if (!gw || !key) throw new Error('Nothing to trust yet');
|
|
222
|
+
this._db().prepare('INSERT OR REPLACE INTO peer_gateway_keys (gateway_id, pubkey, created_at) VALUES (?, ?, ?)').run(gw, key, Date.now());
|
|
223
|
+
if (s.as === 'requester') this._db().prepare('DELETE FROM peer_pins WHERE share_id = ?').run(shareId); // its own pin follows
|
|
224
|
+
this._nameCache = null;
|
|
225
|
+
this._changed();
|
|
226
|
+
this._sharesChanged();
|
|
227
|
+
return { theirKey: fingerprint(key) };
|
|
228
|
+
}
|
|
229
|
+
|
|
172
230
|
/** The other side's key this gateway trusts for a share (owner: from the signed grant, or the request's key
|
|
173
231
|
* while pending, which approving pins; requester: the pin). Same source as list()'s "Their key". */
|
|
174
232
|
_theirKey(s) {
|
|
@@ -202,11 +260,14 @@ export class SharingManager {
|
|
|
202
260
|
_revokeLocal(shareId) {
|
|
203
261
|
this._db().prepare('UPDATE peer_grants SET revoked_at = ? WHERE share_id = ? AND revoked_at IS NULL').run(Date.now(), shareId);
|
|
204
262
|
for (const link of this._served) if (link.shareId === shareId) link.close();
|
|
205
|
-
// Runs already going stop too: "Stop sharing" must not leave a guest run working for minutes.
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
263
|
+
// Runs already going stop too: "Stop sharing" must not leave a guest run working for minutes. One still
|
|
264
|
+
// being set up is marked, so it never starts (or is aborted the moment it has started).
|
|
265
|
+
for (const t of this._turns.values()) if (t.shareId === shareId) this._abortTurn(t);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
_abortTurn(t) {
|
|
269
|
+
t.aborted = true;
|
|
270
|
+
if (t.runId) this.request('chat.abort', { sessionKey: t.sessionKey, runId: t.runId }).catch(() => {});
|
|
210
271
|
}
|
|
211
272
|
|
|
212
273
|
/** Remember an agent created here as a guest version (ClawChats → Sharing). */
|
|
@@ -265,6 +326,11 @@ export class SharingManager {
|
|
|
265
326
|
if (prev && JSON.parse(prev.grant_json).requesterPubKey !== s.requester.pubKey) {
|
|
266
327
|
throw new Error("The requester's gateway key changed since you approved them. Stop sharing and ask them to request again.");
|
|
267
328
|
}
|
|
329
|
+
// Nor can a new request bring another key for a gateway this one already knows (a server posing as them).
|
|
330
|
+
const pinned = this._gatewayKey(s.requester.gatewayId);
|
|
331
|
+
if (pinned && pinned !== s.requester.pubKey) {
|
|
332
|
+
throw new Error(`${cleanName(s.requester.name || s.requester.email, 60) || 'Their'} gateway key isn't the one you connected with before. Check "Their key" with them, then trust the new key.`);
|
|
333
|
+
}
|
|
268
334
|
// The signal server only activates a grant signed for this gateway's own id; without one it would say no, silently.
|
|
269
335
|
const ownerGatewayId = this.gatewayId();
|
|
270
336
|
if (!ownerGatewayId) throw new Error("This gateway isn't connected to the signal server yet. Try again in a moment.");
|
|
@@ -274,6 +340,7 @@ export class SharingManager {
|
|
|
274
340
|
agents: list, access, dailyCap: Math.max(1, Math.min(1000, Math.floor(Number(dailyCap) || DEFAULT_DAILY_CAP))), issuedAt: Date.now(),
|
|
275
341
|
};
|
|
276
342
|
const sig = this.key.signJson(grant);
|
|
343
|
+
this._pinGatewayKey(grant.requesterGatewayId, grant.requesterPubKey);
|
|
277
344
|
this._db().prepare('INSERT INTO peer_grants (share_id, grant_json, sig, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(share_id) DO UPDATE SET grant_json = excluded.grant_json, sig = excluded.sig, created_at = excluded.created_at, revoked_at = NULL')
|
|
278
345
|
.run(shareId, JSON.stringify(grant), sig, Date.now());
|
|
279
346
|
// An agent removed from the grant: its links pick up the new list on the next turn.
|
|
@@ -313,15 +380,36 @@ export class SharingManager {
|
|
|
313
380
|
return null;
|
|
314
381
|
}
|
|
315
382
|
const link = new PeerLink({ dc, dtls, role: 'owner', shareId, key: this.key, peerKey: g.grant.requesterPubKey, log: this.log });
|
|
383
|
+
const gw = g.grant.requesterGatewayId; // the gateway the key this link authenticates was approved for
|
|
316
384
|
this._served.add(link);
|
|
317
385
|
link.on('closed', () => this._served.delete(link));
|
|
318
|
-
link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
|
|
319
|
-
link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit)); // only localTurnFor sets these
|
|
320
|
-
link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
|
|
321
|
-
this._wireRooms(link,
|
|
386
|
+
link.handle('agents', this._limited(gw, 'agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] })));
|
|
387
|
+
link.handle('turn', this._limited(gw, 'turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit))); // only localTurnFor sets these
|
|
388
|
+
link.handle('abort', this._limited(gw, 'abort', async p => this._guestAbort(shareId, p?.turnId)));
|
|
389
|
+
this._wireRooms(link, gw);
|
|
322
390
|
return link;
|
|
323
391
|
}
|
|
324
392
|
|
|
393
|
+
/** A peer request handler, refused once that contact's gateway goes over its rate (PEER_RATES). */
|
|
394
|
+
_limited(gatewayId, method, fn) {
|
|
395
|
+
return (p, emit) => {
|
|
396
|
+
const kind = PEER_RATES[method] ? method : '*';
|
|
397
|
+
const [burst, per] = PEER_RATES[kind];
|
|
398
|
+
const now = Date.now();
|
|
399
|
+
const key = `${gatewayId}|${kind}`;
|
|
400
|
+
const b = this._buckets.get(key) || { tokens: burst, at: now };
|
|
401
|
+
b.tokens = Math.min(burst, b.tokens + ((now - b.at) * burst) / per);
|
|
402
|
+
b.at = now;
|
|
403
|
+
this._buckets.set(key, b);
|
|
404
|
+
if (b.tokens < 1) {
|
|
405
|
+
this.log.warn?.(`[sharing] ${gatewayId} is sending too many ${kind === '*' ? 'requests' : kind} requests: refused`);
|
|
406
|
+
return Promise.reject(Object.assign(new Error('Too many requests; try again in a moment'), { code: 'rate_limited' }));
|
|
407
|
+
}
|
|
408
|
+
b.tokens -= 1;
|
|
409
|
+
return fn(p, emit);
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
325
413
|
/**
|
|
326
414
|
* Team chats with people (specs/sharing-people.md) travel over whichever link the two gateways
|
|
327
415
|
* have, in either direction: the room host pushes its room to members (room.sync), members post,
|
|
@@ -330,10 +418,10 @@ export class SharingManager {
|
|
|
330
418
|
*/
|
|
331
419
|
_wireRooms(link, otherGatewayId) {
|
|
332
420
|
for (const method of ['room.sync', 'room.post', 'room.leave', 'room.fetch']) {
|
|
333
|
-
link.handle(method, async p => {
|
|
421
|
+
link.handle(method, this._limited(otherGatewayId, method, async p => {
|
|
334
422
|
if (!this.onRoom) throw Object.assign(new Error('team chats are not available'), { code: 'unavailable' });
|
|
335
423
|
return this.onRoom(method, p || {}, otherGatewayId);
|
|
336
|
-
});
|
|
424
|
+
}));
|
|
337
425
|
}
|
|
338
426
|
const ready = () => { try { this.onPeerReady?.(otherGatewayId); } catch (e) { this.log.warn?.(`[sharing] peer ready: ${e.message}`); } };
|
|
339
427
|
if (link.ready) setImmediate(ready); else link.once('ready', ready);
|
|
@@ -344,7 +432,9 @@ export class SharingManager {
|
|
|
344
432
|
/** The other person of a share, as this side sees them: { gatewayId, name, email }. */
|
|
345
433
|
_other(s) {
|
|
346
434
|
const p = s.as === 'owner' ? s.requester : s.owner;
|
|
347
|
-
|
|
435
|
+
// Their gateway as this side signed or verified it, not as the server lists it now.
|
|
436
|
+
const gatewayId = s.as === 'owner' ? this._grant(s.id)?.grant.requesterGatewayId || p?.gatewayId : this._ownerGateway(s) || p?.gatewayId;
|
|
437
|
+
return { gatewayId: gatewayId || null, name: cleanName(p?.name || p?.email, 60) || 'Someone', email: p?.email || null };
|
|
348
438
|
}
|
|
349
439
|
|
|
350
440
|
/**
|
|
@@ -417,12 +507,39 @@ export class SharingManager {
|
|
|
417
507
|
/** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
|
|
418
508
|
ownerOf(remoteAgentId) {
|
|
419
509
|
const id = SharingManager.parseRemoteId(remoteAgentId);
|
|
420
|
-
return
|
|
510
|
+
return id ? this._ownerGateway(this._shares.find(s => s.id === id.shareId && s.as === 'requester')) : null;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* The owner gateway of a share shared with this one: the id its grant was signed for by the key pinned
|
|
515
|
+
* for it (the server's word alone can't make it someone else). Remembered after the share ends.
|
|
516
|
+
*/
|
|
517
|
+
_ownerGateway(s) {
|
|
518
|
+
if (!s) return null;
|
|
519
|
+
const g = this._verifiedGrant(s);
|
|
520
|
+
if (g) return g.ownerGatewayId;
|
|
521
|
+
const pin = this._db().prepare('SELECT owner_pubkey, owner_gateway_id FROM peer_pins WHERE share_id = ?').get(s.id);
|
|
522
|
+
if (pin?.owner_gateway_id) return pin.owner_gateway_id;
|
|
523
|
+
// Pinned before the owner gateway was recorded with it: the grant still says, if the pinned key signed it.
|
|
524
|
+
const ok = pin && s.grant && s.grant.ownerGatewayId === s.owner?.gatewayId && verifySignature(pin.owner_pubkey, canonicalJson(s.grant), s.signature);
|
|
525
|
+
return ok ? s.grant.ownerGatewayId : null;
|
|
421
526
|
}
|
|
422
527
|
|
|
423
528
|
/** Whether this gateway owns (granted) that share. */
|
|
424
529
|
ownsShare(shareId) { return !!this._grant(shareId); }
|
|
425
530
|
|
|
531
|
+
/** Whether this gateway shares `agentId` with that gateway (an unrevoked grant it signed; only that share, if given). */
|
|
532
|
+
grantedTo(gatewayId, agentId, shareId = null) {
|
|
533
|
+
if (!gatewayId || !agentId) return false;
|
|
534
|
+
return this._localGrants().some(r => {
|
|
535
|
+
if (shareId && r.share_id !== shareId) return false;
|
|
536
|
+
try {
|
|
537
|
+
const g = JSON.parse(r.grant_json);
|
|
538
|
+
return g.requesterGatewayId === gatewayId && (g.agents || []).some(a => a?.id === agentId);
|
|
539
|
+
} catch { return false; }
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
|
|
426
543
|
/** This gateway's person, as the others see them (from any share). */
|
|
427
544
|
selfName() {
|
|
428
545
|
for (const s of this._shares) {
|
|
@@ -463,15 +580,23 @@ export class SharingManager {
|
|
|
463
580
|
const roomId = String(p.roomId || '').slice(0, 200);
|
|
464
581
|
if (!roomId || typeof p.message !== 'string' || !p.message.trim()) throw Object.assign(new Error('Bad turn'), { code: 'bad_request' });
|
|
465
582
|
if (this._usage(shareId) >= grant.dailyCap) throw Object.assign(new Error(`Daily limit reached (${grant.dailyCap} replies)`), { code: 'cap' });
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const
|
|
470
|
-
|
|
583
|
+
// The requester's turn id only names the turn for its Stop; the turn itself is tracked under an id made here,
|
|
584
|
+
// so reusing one can't hide a turn from the limit or from "Stop sharing".
|
|
585
|
+
const clientTurnId = typeof p.turnId === 'string' && p.turnId ? p.turnId.slice(0, 200) : null;
|
|
586
|
+
const running = [...this._turns.values()].filter(t => t.shareId === shareId);
|
|
587
|
+
if (clientTurnId && running.some(t => t.clientTurnId === clientTurnId)) throw Object.assign(new Error('That turn is already running'), { code: 'bad_request' });
|
|
588
|
+
if (running.length >= MAX_CONCURRENT_TURNS) throw Object.assign(new Error('Too many replies at once; try again shortly'), { code: 'busy' });
|
|
589
|
+
const turnKey = crypto.randomUUID();
|
|
590
|
+
this._turns.set(turnKey, { shareId, clientTurnId, sessionKey: null, runId: null, aborted: false }); // counts toward the limit from here on
|
|
471
591
|
// Counted before any await, so parallel turns can't both pass the cap.
|
|
472
592
|
this._db().prepare('INSERT INTO peer_usage (share_id, day, turns) VALUES (?, ?, 1) ON CONFLICT(share_id, day) DO UPDATE SET turns = turns + 1').run(shareId, today());
|
|
473
593
|
this._changed(); // the owner's Sharing view shows today's count
|
|
474
|
-
try {
|
|
594
|
+
try {
|
|
595
|
+
const r = await this._runGuestTurn(shareId, grant, agent, roomId, p, emit, this._turns.get(turnKey));
|
|
596
|
+
// What this gateway's agent said for that gateway's room: its copy of the room may show it as ours (team.js).
|
|
597
|
+
if (!p.inOwnerRoom && r?.text) try { this.onGuestReply?.(grant.requesterGatewayId, roomId, shareId, agent.id, r.text); } catch { /* best effort */ }
|
|
598
|
+
return r;
|
|
599
|
+
}
|
|
475
600
|
catch (e) {
|
|
476
601
|
// A reply that failed without saying anything doesn't use up the day's replies. A timeout still
|
|
477
602
|
// counts: it ran for the full turn timeout.
|
|
@@ -484,7 +609,7 @@ export class SharingManager {
|
|
|
484
609
|
finally { this._turns.delete(turnKey); }
|
|
485
610
|
}
|
|
486
611
|
|
|
487
|
-
async _runGuestTurn(shareId, grant, agent, roomId, p, emit,
|
|
612
|
+
async _runGuestTurn(shareId, grant, agent, roomId, p, emit, turn) {
|
|
488
613
|
const cfg = await this.request('config.get', {}, 30_000);
|
|
489
614
|
// A guest version whose restrictions were edited away (e.g. in the Control UI) isn't served.
|
|
490
615
|
const isGuest = this._db().prepare('SELECT 1 FROM peer_guest_agents WHERE agent_id = ?').get(agent.id);
|
|
@@ -506,14 +631,17 @@ export class SharingManager {
|
|
|
506
631
|
timer.unref?.();
|
|
507
632
|
this._runs.set(runId, { resolve, timer, text: '', emit, sessionKey });
|
|
508
633
|
});
|
|
509
|
-
|
|
634
|
+
Object.assign(turn, { sessionKey, runId });
|
|
510
635
|
try {
|
|
511
636
|
if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
|
|
637
|
+
if (turn.aborted) return { state: 'aborted', text: '' }; // stopped while setting up
|
|
512
638
|
await this.request('chat.send', {
|
|
513
639
|
sessionKey, message: defangLocalPaths(`${p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
514
640
|
timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
|
|
515
641
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
516
642
|
}, 30_000);
|
|
643
|
+
// Stopped or revoked while the send was on its way (the abort may have reached the gateway before the run).
|
|
644
|
+
if (turn.aborted || !this._grant(shareId)) this._abortTurn(turn);
|
|
517
645
|
const r = await done;
|
|
518
646
|
if (r.state === 'final') return { state: 'final', text: r.message ? messageText(r.message) : await this._lastReply(sessionKey) };
|
|
519
647
|
if (r.state === 'aborted') return { state: 'aborted', text: r.text || '' };
|
|
@@ -526,8 +654,7 @@ export class SharingManager {
|
|
|
526
654
|
}
|
|
527
655
|
|
|
528
656
|
async _guestAbort(shareId, turnId) {
|
|
529
|
-
const t
|
|
530
|
-
if (t) await this.request('chat.abort', { sessionKey: t.sessionKey, runId: t.runId }).catch(() => {});
|
|
657
|
+
for (const t of this._turns.values()) if (t.shareId === shareId && turnId && t.clientTurnId === turnId) this._abortTurn(t);
|
|
531
658
|
return { ok: true };
|
|
532
659
|
}
|
|
533
660
|
|
|
@@ -628,14 +755,24 @@ export class SharingManager {
|
|
|
628
755
|
if (s?.as !== 'requester' || s.status !== 'active' || !s.grant || !s.signature || !s.owner?.pubKey) return null;
|
|
629
756
|
if (this._db().prepare('SELECT 1 FROM peer_removed WHERE share_id = ?').get(s.id)) return null;
|
|
630
757
|
if (s.grant.requesterGatewayId !== this.gatewayId() || s.grant.shareId !== s.id || s.grant.requesterPubKey !== this.key.publicKey) return null;
|
|
758
|
+
// Signed for the gateway the server says it's from: a grant from one contact can't pass as another's.
|
|
759
|
+
if (!s.owner.gatewayId || s.grant.ownerGatewayId !== s.owner.gatewayId) return null;
|
|
631
760
|
const db = this._db();
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
|
|
761
|
+
const pinRow = db.prepare('SELECT owner_pubkey, owner_gateway_id FROM peer_pins WHERE share_id = ?').get(s.id);
|
|
762
|
+
const pin = pinRow?.owner_pubkey;
|
|
763
|
+
const gwPin = this._gatewayKey(s.owner.gatewayId);
|
|
764
|
+
if ((pin && pin !== s.owner.pubKey) || (gwPin && gwPin !== s.owner.pubKey)) {
|
|
765
|
+
const was = pin && pin !== s.owner.pubKey ? pin : gwPin;
|
|
766
|
+
if (!(this._warnedKeys ??= new Set()).has(`${s.id}|${s.owner.pubKey}`)) {
|
|
767
|
+
this._warnedKeys.add(`${s.id}|${s.owner.pubKey}`);
|
|
768
|
+
this.log.warn?.(`[sharing] owner key changed for ${s.id} (was ${fingerprint(was)}, now ${fingerprint(s.owner.pubKey)}): refusing`);
|
|
769
|
+
}
|
|
635
770
|
return null;
|
|
636
771
|
}
|
|
637
772
|
if (!verifySignature(s.owner.pubKey, canonicalJson(s.grant), s.signature)) return null;
|
|
638
|
-
if (!pin) db.prepare('INSERT OR IGNORE INTO peer_pins (share_id, owner_pubkey, created_at) VALUES (?, ?, ?)').run(s.id, s.owner.pubKey, Date.now());
|
|
773
|
+
if (!pin) db.prepare('INSERT OR IGNORE INTO peer_pins (share_id, owner_pubkey, created_at, owner_gateway_id) VALUES (?, ?, ?, ?)').run(s.id, s.owner.pubKey, Date.now(), s.owner.gatewayId);
|
|
774
|
+
else if (!pinRow.owner_gateway_id) db.prepare('UPDATE peer_pins SET owner_gateway_id = ? WHERE share_id = ?').run(s.owner.gatewayId, s.id);
|
|
775
|
+
if (!gwPin) this._pinGatewayKey(s.owner.gatewayId, s.owner.pubKey);
|
|
639
776
|
return s.grant;
|
|
640
777
|
}
|
|
641
778
|
|
|
@@ -664,14 +801,15 @@ export class SharingManager {
|
|
|
664
801
|
if (cur?.ready && !cur.closed) return cur;
|
|
665
802
|
if (this._linking.has(shareId)) return this._linking.get(shareId);
|
|
666
803
|
const s = this._shares.find(x => x.id === shareId);
|
|
667
|
-
|
|
804
|
+
const grant = this._verifiedGrant(s);
|
|
805
|
+
if (!grant) throw Object.assign(new Error('This share is not active'), { code: 'revoked' });
|
|
668
806
|
const p = (async () => {
|
|
669
807
|
const { dc, dtls } = await this.openPeer(shareId);
|
|
670
808
|
const link = new PeerLink({ dc, dtls, role: 'requester', shareId, key: this.key, peerKey: s.owner.pubKey, log: this.log });
|
|
671
809
|
await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
|
|
672
810
|
this._links.set(shareId, link);
|
|
673
811
|
link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
|
|
674
|
-
this._wireRooms(link,
|
|
812
|
+
this._wireRooms(link, grant.ownerGatewayId); // the gateway the key this link authenticated signed for
|
|
675
813
|
return link;
|
|
676
814
|
})().finally(() => this._linking.delete(shareId));
|
|
677
815
|
this._linking.set(shareId, p);
|
|
@@ -709,10 +847,10 @@ export class SharingManager {
|
|
|
709
847
|
const id = SharingManager.parseRemoteId(who);
|
|
710
848
|
const theirs = id && this._shares.find(s => s.id === id.shareId && s.as === 'requester');
|
|
711
849
|
if (!theirs) return null;
|
|
712
|
-
gw = theirs
|
|
850
|
+
gw = this._ownerGateway(theirs); email = String(theirs.owner?.email || '').toLowerCase();
|
|
713
851
|
}
|
|
714
852
|
const candidates = this._shares.filter(s => s.as === 'owner' && s.status === 'active');
|
|
715
|
-
const mine = candidates.find(s => gw && s.
|
|
853
|
+
const mine = candidates.find(s => gw && this._other(s).gatewayId === gw)
|
|
716
854
|
|| candidates.find(s => email && String(s.requester?.email || '').toLowerCase() === email);
|
|
717
855
|
const g = mine && this._grant(mine.id);
|
|
718
856
|
return g ? { shareId: mine.id, grant: g.grant } : null;
|