@clawchatsai/connector 0.1.49 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -6
- package/dist/auth-handler.d.ts +41 -20
- package/dist/auth-handler.js +136 -106
- package/dist/channel-binding.d.ts +57 -0
- package/dist/channel-binding.js +73 -0
- package/dist/config-store.d.ts +14 -6
- package/dist/config-store.js +58 -11
- package/dist/devices-cli.d.ts +16 -0
- package/dist/devices-cli.js +90 -0
- package/dist/index.js +76 -16
- package/dist/plugin-config.d.ts +12 -0
- package/dist/session-token.d.ts +6 -39
- package/dist/session-token.js +6 -95
- package/dist/shim.js +13 -10
- package/dist/totp.d.ts +8 -0
- package/dist/totp.js +16 -0
- package/dist/webrtc-peer.d.ts +2 -0
- package/dist/webrtc-peer.js +15 -1
- package/package.json +1 -1
- package/server/approval-client.test.js +1 -1
- package/server/controllers/title.js +3 -1
- package/server/controllers/title.test.js +8 -1
- package/server/gateway.js +21 -3
- package/server/gateway.test.js +44 -0
- package/server/history-export.js +5 -1
- package/server/history-export.test.js +63 -0
- package/server/index.js +4 -1
- package/server/peer/guest-agent.js +41 -8
- package/server/peer/guest-agent.test.js +50 -1
- package/server/peer/keys.js +12 -0
- package/server/peer/sharing.js +17 -3
- package/server/peer/sharing.test.js +42 -4
- package/server/peer/wordlist.js +3 -0
- package/server/team.js +15 -6
- package/server/team.test.js +48 -4
- package/server/util/gateway-retry.js +58 -0
- package/server/util/gateway-retry.test.js +78 -0
- package/server/util/redact.js +84 -0
- package/server/util/redact.test.js +97 -0
- package/dist/google-jwt.d.ts +0 -34
- package/dist/google-jwt.js +0 -87
package/dist/totp.d.ts
CHANGED
|
@@ -19,6 +19,14 @@ export declare function generateTotp(secretBase32: string): string;
|
|
|
19
19
|
* @returns The matched time step if valid, or -1 if invalid
|
|
20
20
|
*/
|
|
21
21
|
export declare function verifyTotp(code: string, secretBase32: string, lastUsedStep: number): number;
|
|
22
|
+
/**
|
|
23
|
+
* The codes that are valid now (T-1, T, T+1, newest first) and not yet used, with their time
|
|
24
|
+
* steps. For a login that proves knowledge of the code without sending it (device pairing).
|
|
25
|
+
*/
|
|
26
|
+
export declare function totpCandidates(secretBase32: string, lastUsedStep: number): Array<{
|
|
27
|
+
step: number;
|
|
28
|
+
code: string;
|
|
29
|
+
}>;
|
|
22
30
|
/**
|
|
23
31
|
* Generate a random 20-byte TOTP secret, returned as base32.
|
|
24
32
|
*/
|
package/dist/totp.js
CHANGED
|
@@ -63,6 +63,22 @@ export function verifyTotp(code, secretBase32, lastUsedStep) {
|
|
|
63
63
|
}
|
|
64
64
|
return -1;
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* The codes that are valid now (T-1, T, T+1, newest first) and not yet used, with their time
|
|
68
|
+
* steps. For a login that proves knowledge of the code without sending it (device pairing).
|
|
69
|
+
*/
|
|
70
|
+
export function totpCandidates(secretBase32, lastUsedStep) {
|
|
71
|
+
const secret = base32Decode(secretBase32);
|
|
72
|
+
const currentStep = Math.floor(Date.now() / 1000 / PERIOD);
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const offset of [1, 0, -1]) {
|
|
75
|
+
const step = currentStep + offset;
|
|
76
|
+
if (step <= lastUsedStep)
|
|
77
|
+
continue; // replay protection
|
|
78
|
+
out.push({ step, code: generateForStep(secret, step) });
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
66
82
|
/**
|
|
67
83
|
* Generate a random 20-byte TOTP secret, returned as base32.
|
|
68
84
|
*/
|
package/dist/webrtc-peer.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export declare class WebRTCPeerManager extends EventEmitter {
|
|
|
51
51
|
private activeChannels;
|
|
52
52
|
/** Gateway-sharing connections: never handed to the browser path, not counted as devices. */
|
|
53
53
|
private peerInfo;
|
|
54
|
+
/** Browser connections: both DTLS fingerprints as the SDPs set on this peer connection say, fixed at the first offer. */
|
|
55
|
+
private browserDtls;
|
|
54
56
|
constructor();
|
|
55
57
|
setIceServers(data: IceServers): void;
|
|
56
58
|
handleOffer(offer: IceOffer): Promise<{
|
package/dist/webrtc-peer.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { EventEmitter } from 'node:events';
|
|
11
11
|
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, } from 'node-datachannel/polyfill';
|
|
12
|
+
import { sdpFingerprint as strictSdpFingerprint } from './channel-binding.js';
|
|
12
13
|
// ---------------------------------------------------------------------------
|
|
13
14
|
// Public interfaces
|
|
14
15
|
// ---------------------------------------------------------------------------
|
|
@@ -85,6 +86,8 @@ export class WebRTCPeerManager extends EventEmitter {
|
|
|
85
86
|
activeChannels = new Map();
|
|
86
87
|
/** Gateway-sharing connections: never handed to the browser path, not counted as devices. */
|
|
87
88
|
peerInfo = new Map();
|
|
89
|
+
/** Browser connections: both DTLS fingerprints as the SDPs set on this peer connection say, fixed at the first offer. */
|
|
90
|
+
browserDtls = new Map();
|
|
88
91
|
constructor() {
|
|
89
92
|
super();
|
|
90
93
|
}
|
|
@@ -185,6 +188,14 @@ export class WebRTCPeerManager extends EventEmitter {
|
|
|
185
188
|
const info = this.peerInfo.get(connectionId);
|
|
186
189
|
if (info)
|
|
187
190
|
info.dtls.local = sdpFingerprint(pc.localDescription?.sdp || answer.sdp);
|
|
191
|
+
else {
|
|
192
|
+
// What the login signs (auth-handler.ts). Read from the descriptions the peer connection
|
|
193
|
+
// holds, which are what DTLS verifies the other side's certificate against.
|
|
194
|
+
this.browserDtls.set(connectionId, {
|
|
195
|
+
browser: strictSdpFingerprint(pc.remoteDescription?.sdp),
|
|
196
|
+
connector: strictSdpFingerprint(pc.localDescription?.sdp || answer.sdp),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
188
199
|
console.log(`[WebRTCPeerManager] Answer created for connection ${connectionId}`);
|
|
189
200
|
return {
|
|
190
201
|
connectionId,
|
|
@@ -238,6 +249,7 @@ export class WebRTCPeerManager extends EventEmitter {
|
|
|
238
249
|
catch { /* gone */ }
|
|
239
250
|
this.peerConnections.delete(connectionId);
|
|
240
251
|
this.peerInfo.delete(connectionId);
|
|
252
|
+
this.browserDtls.delete(connectionId);
|
|
241
253
|
this.pendingIceServers.delete(connectionId);
|
|
242
254
|
}
|
|
243
255
|
handleIceCandidate(connectionId, candidate) {
|
|
@@ -268,6 +280,7 @@ export class WebRTCPeerManager extends EventEmitter {
|
|
|
268
280
|
this.peerConnections.clear();
|
|
269
281
|
this.pendingIceServers.clear();
|
|
270
282
|
this.peerInfo.clear();
|
|
283
|
+
this.browserDtls.clear();
|
|
271
284
|
}
|
|
272
285
|
/** Browser connections (gateway-sharing links aren't devices). */
|
|
273
286
|
get activeCount() {
|
|
@@ -294,12 +307,13 @@ export class WebRTCPeerManager extends EventEmitter {
|
|
|
294
307
|
}
|
|
295
308
|
const info = this.peerInfo.get(connectionId);
|
|
296
309
|
this.peerInfo.delete(connectionId);
|
|
310
|
+
this.browserDtls.delete(connectionId);
|
|
297
311
|
this.emit(info ? 'peer-datachannel-closed' : 'datachannel-closed', connectionId);
|
|
298
312
|
});
|
|
299
313
|
const info = this.peerInfo.get(connectionId);
|
|
300
314
|
if (info)
|
|
301
315
|
this.emit('peer-datachannel', channel, info);
|
|
302
316
|
else
|
|
303
|
-
this.emit('datachannel', channel, connectionId);
|
|
317
|
+
this.emit('datachannel', channel, connectionId, this.browserDtls.get(connectionId));
|
|
304
318
|
}
|
|
305
319
|
}
|
package/package.json
CHANGED
|
@@ -41,7 +41,7 @@ test('no browser: no approval-client connection; main connection never declares
|
|
|
41
41
|
c.connect();
|
|
42
42
|
await wait(200);
|
|
43
43
|
assert.equal(gw.conns.length, 1);
|
|
44
|
-
assert.deepEqual(gw.conns[0].params.caps, ['tool-events']);
|
|
44
|
+
assert.deepEqual(gw.conns[0].params.caps, ['tool-events', 'chat-queue-status']);
|
|
45
45
|
assert.equal(gw.approvalConns().length, 0);
|
|
46
46
|
c.close();
|
|
47
47
|
await new Promise(r => gw.wss.close(r));
|
|
@@ -29,7 +29,9 @@ function createCompletion(llm) {
|
|
|
29
29
|
try {
|
|
30
30
|
return await llm.complete(base);
|
|
31
31
|
} catch (err) {
|
|
32
|
-
|
|
32
|
+
// Not a transport problem: isolated mode fails the same way. LLM_RUNTIME_LIFECYCLE (2026.11.5+): the plugin or
|
|
33
|
+
// model runtime is reloading; the host says to retry from a fresh plugin operation, not inside this one.
|
|
34
|
+
if (['LLM_COMPLETION_NOT_AUTHORIZED', 'LLM_RUNTIME_LIFECYCLE', 'LLM_COMPLETION_ABORTED'].includes(err?.code)) throw err;
|
|
33
35
|
return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
|
|
34
36
|
}
|
|
35
37
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import { Readable } from 'node:stream';
|
|
4
|
-
import { createTitleHandler, normalizeTitle, TITLE_PROMPT } from './title.js';
|
|
4
|
+
import { createTitleHandler, createTitler, normalizeTitle, TITLE_PROMPT } from './title.js';
|
|
5
5
|
|
|
6
6
|
function call(handler, body) {
|
|
7
7
|
const req = Readable.from([Buffer.from(JSON.stringify(body))]);
|
|
@@ -44,3 +44,10 @@ test('authorization failures are not retried; bad input is rejected', async () =
|
|
|
44
44
|
assert.equal((await call(handler, { message: ' ' })).status, 400);
|
|
45
45
|
assert.equal((await call(createTitleHandler(undefined), { message: 'x' })).status, 501);
|
|
46
46
|
});
|
|
47
|
+
|
|
48
|
+
test('a runtime reload (2026.11.5+ LLM_RUNTIME_LIFECYCLE) is not retried in isolated mode', async () => {
|
|
49
|
+
let n = 0;
|
|
50
|
+
const titler = createTitler({ complete: async () => { n++; throw Object.assign(new Error('reloading'), { code: 'LLM_RUNTIME_LIFECYCLE' }); } });
|
|
51
|
+
await assert.rejects(titler('plan the offsite'), /reloading/);
|
|
52
|
+
assert.equal(n, 1);
|
|
53
|
+
});
|
package/server/gateway.js
CHANGED
|
@@ -5,10 +5,25 @@ import { ApprovalClient } from './approval-client.js';
|
|
|
5
5
|
|
|
6
6
|
// Per-session run/transcript events; hidden sessions' ones are dropped by the lens.
|
|
7
7
|
const RUN_EVENTS = new Set(['chat', 'agent', 'session.tool', 'session.operation', 'session.observer']);
|
|
8
|
-
const SCOPES = ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'];
|
|
8
|
+
export const SCOPES = ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'];
|
|
9
9
|
// After the last browser leaves, the approval-client connection stays this long (P2P reconnects, reloads).
|
|
10
10
|
const APPROVAL_CLIENT_GRACE_MS = 10_000;
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* The Error for a failed gateway response. The error shape's machine-readable fields stay on it (gatewayCode,
|
|
14
|
+
* retryable, retryAfterMs, details; 2026.11.4+ sets them on startup refusals and persisted-but-unapplied config writes)
|
|
15
|
+
* so callers can tell "try again" from "failed". Not `code`: that name is the peer protocol's (peer/link.js).
|
|
16
|
+
*/
|
|
17
|
+
export function gatewayError(error, fallback) {
|
|
18
|
+
const err = new Error(error?.message || fallback);
|
|
19
|
+
if (!error || typeof error !== 'object') return err;
|
|
20
|
+
if (typeof error.code === 'string') err.gatewayCode = error.code;
|
|
21
|
+
if (typeof error.retryable === 'boolean') err.retryable = error.retryable;
|
|
22
|
+
if (typeof error.retryAfterMs === 'number') err.retryAfterMs = error.retryAfterMs;
|
|
23
|
+
if (error.details !== undefined) err.details = error.details;
|
|
24
|
+
return err;
|
|
25
|
+
}
|
|
26
|
+
|
|
12
27
|
export class GatewayClient {
|
|
13
28
|
constructor({ dataDir, debugLogger, gatewayWsUrl, authToken, approvalClientGraceMs = APPROVAL_CLIENT_GRACE_MS }) {
|
|
14
29
|
this.dataDir = dataDir;
|
|
@@ -85,7 +100,7 @@ export class GatewayClient {
|
|
|
85
100
|
this._rpc.delete(msg.id);
|
|
86
101
|
clearTimeout(pending.timer);
|
|
87
102
|
if (msg.ok) pending.resolve(msg.payload);
|
|
88
|
-
else pending.reject(
|
|
103
|
+
else pending.reject(gatewayError(msg.error, `${pending.method} failed`));
|
|
89
104
|
return;
|
|
90
105
|
}
|
|
91
106
|
|
|
@@ -99,7 +114,10 @@ export class GatewayClient {
|
|
|
99
114
|
if (msg.type === 'event' && this.onEvent) { try { this.onEvent(msg); } catch (e) { console.error('[gateway] event observer:', e.message); } }
|
|
100
115
|
|
|
101
116
|
if (msg.type === 'event' && msg.event === 'connect.challenge') {
|
|
102
|
-
|
|
117
|
+
// chat-queue-status (2026.11.6+; older gateways ignore unknown caps): a queued send is shown from pendingInputs,
|
|
118
|
+
// as in the Control UI. Without it the gateway sends the "queued" notice as a chat delta carrying text, which
|
|
119
|
+
// browsers would render as reply text and team chat would keep as a stopped turn's partial reply.
|
|
120
|
+
this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events', 'chat-queue-status']) }));
|
|
103
121
|
return;
|
|
104
122
|
}
|
|
105
123
|
if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.onConnected?.(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seedWithRetry(); }
|
package/server/gateway.test.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
2
5
|
import assert from 'node:assert/strict';
|
|
3
6
|
import { WebSocketServer } from 'ws';
|
|
4
7
|
import { GatewayClient } from './gateway.js';
|
|
@@ -25,3 +28,44 @@ test('close() shuts the socket and stops reconnecting (plugin reload drain)', as
|
|
|
25
28
|
assert.equal(connections, 1);
|
|
26
29
|
await new Promise(r => wss.close(r));
|
|
27
30
|
});
|
|
31
|
+
|
|
32
|
+
test('request() keeps the error fields the gateway sends (gatewayCode, retryable, retryAfterMs, details)', async () => {
|
|
33
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gw-err-'));
|
|
34
|
+
const wss = new WebSocketServer({ port: 0 });
|
|
35
|
+
wss.on('connection', ws => {
|
|
36
|
+
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: { nonce: 'n' } }));
|
|
37
|
+
ws.on('message', raw => {
|
|
38
|
+
const m = JSON.parse(raw.toString());
|
|
39
|
+
if (m.method === 'connect') return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: true, payload: { type: 'hello-ok' } }));
|
|
40
|
+
if (m.method === 'chat.send') return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: false, error: { code: 'UNAVAILABLE', message: 'chat.send unavailable during gateway startup', retryable: true, retryAfterMs: 500, details: { reason: 'startup-sidecars', method: 'chat.send' } } }));
|
|
41
|
+
if (m.method === 'config.patch') return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: false, error: { code: 'UNAVAILABLE', message: 'config.patch persisted but was not applied', details: { persistedConfig: { hash: 'h2' } } } }));
|
|
42
|
+
if (m.method === 'sessions.subscribe') return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: true, payload: {} }));
|
|
43
|
+
ws.send(JSON.stringify({ type: 'res', id: m.id, ok: false, error: { message: 'plain failure' } })); // 9.7 style: code optional
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
await new Promise(r => wss.once('listening', r));
|
|
47
|
+
const gw = new GatewayClient({ dataDir: dir, debugLogger: logger, gatewayWsUrl: `ws://127.0.0.1:${wss.address().port}`, authToken: '' });
|
|
48
|
+
gw.connect();
|
|
49
|
+
for (let i = 0; i < 50 && !gw.connected; i++) await new Promise(r => setTimeout(r, 20));
|
|
50
|
+
assert.ok(gw.connected);
|
|
51
|
+
|
|
52
|
+
const startup = await gw.request('chat.send', {}).catch(e => e);
|
|
53
|
+
assert.equal(startup.message, 'chat.send unavailable during gateway startup');
|
|
54
|
+
assert.equal(startup.gatewayCode, 'UNAVAILABLE');
|
|
55
|
+
assert.equal(startup.retryable, true);
|
|
56
|
+
assert.equal(startup.retryAfterMs, 500);
|
|
57
|
+
assert.equal(startup.details.reason, 'startup-sidecars');
|
|
58
|
+
assert.equal(startup.code, undefined); // `code` stays the peer protocol's
|
|
59
|
+
|
|
60
|
+
const persisted = await gw.request('config.patch', {}).catch(e => e);
|
|
61
|
+
assert.equal(persisted.details.persistedConfig.hash, 'h2');
|
|
62
|
+
assert.equal(persisted.retryable, undefined);
|
|
63
|
+
|
|
64
|
+
const plain = await gw.request('x', {}).catch(e => e);
|
|
65
|
+
assert.equal(plain.message, 'plain failure');
|
|
66
|
+
assert.equal(plain.gatewayCode, undefined);
|
|
67
|
+
|
|
68
|
+
gw.close();
|
|
69
|
+
await new Promise(r => wss.close(r));
|
|
70
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
71
|
+
});
|
package/server/history-export.js
CHANGED
|
@@ -13,6 +13,7 @@ import { DatabaseSync } from 'node:sqlite';
|
|
|
13
13
|
import { WebSocket } from 'ws';
|
|
14
14
|
import { loadOrCreateDeviceIdentity, buildDeviceAuth } from './bootstrap/identity.js';
|
|
15
15
|
import { parseSessionKey } from './util/helpers.js';
|
|
16
|
+
import { SCOPES } from './gateway.js';
|
|
16
17
|
|
|
17
18
|
const PLACEHOLDER_TITLES = new Set(['New chat', '']);
|
|
18
19
|
|
|
@@ -38,7 +39,10 @@ export async function withGateway({ url, token, identityPath }, fn) {
|
|
|
38
39
|
let msg; try { msg = JSON.parse(data.toString()); } catch { return; }
|
|
39
40
|
if (msg.type === 'event' && msg.event === 'connect.challenge') {
|
|
40
41
|
const identity = loadOrCreateDeviceIdentity(identityPath);
|
|
41
|
-
|
|
42
|
+
// The connector's own scopes (it's the same paired device). operator.read alone lists every session on a default
|
|
43
|
+
// gateway, but from 2026.11.5 a gateway with `gateway.roles` set shows a non-admin client none: the export would
|
|
44
|
+
// then take every chat for missing and write duplicates.
|
|
45
|
+
const scopes = SCOPES;
|
|
42
46
|
const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes, token, nonce: msg.payload?.nonce || '' });
|
|
43
47
|
ws.send(JSON.stringify({ type: 'req', id: 'connect', method: 'connect', params: { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes, device, auth: { token } } }));
|
|
44
48
|
return;
|
|
@@ -0,0 +1,63 @@
|
|
|
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 { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { WebSocketServer } from 'ws';
|
|
8
|
+
import { exportHistory } from './history-export.js';
|
|
9
|
+
|
|
10
|
+
const KEY = 'sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789';
|
|
11
|
+
|
|
12
|
+
async function fixture() {
|
|
13
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hist-export-'));
|
|
14
|
+
const dataDir = path.join(dir, 'data'), stateDir = path.join(dir, 'state');
|
|
15
|
+
fs.mkdirSync(dataDir); fs.mkdirSync(stateDir);
|
|
16
|
+
fs.writeFileSync(path.join(dataDir, 'workspaces.json'), JSON.stringify({ workspaces: { p: { name: 'proj', label: 'Proj', order: 1 } } }));
|
|
17
|
+
const db = new DatabaseSync(path.join(dataDir, 'proj.db'));
|
|
18
|
+
db.exec('CREATE TABLE threads (id TEXT PRIMARY KEY, title TEXT, session_key TEXT); CREATE TABLE messages (thread_id TEXT, role TEXT, content TEXT, timestamp INTEGER)');
|
|
19
|
+
db.prepare('INSERT INTO threads VALUES (?, ?, ?)').run('t1', 'Env check', 'agent:main:proj:chat:t1');
|
|
20
|
+
db.prepare('INSERT INTO threads VALUES (?, ?, ?)').run('t2', 'Already there', 'agent:main:proj:chat:t2');
|
|
21
|
+
const msg = db.prepare('INSERT INTO messages VALUES (?, ?, ?, ?)');
|
|
22
|
+
msg.run('t1', 'user', 'what is in the .env?', 1000);
|
|
23
|
+
msg.run('t1', 'assistant', `It has ANTHROPIC_API_KEY=${KEY} and PORT=3000. The password policy is documented.`, 2000);
|
|
24
|
+
msg.run('t2', 'user', 'hi', 1000);
|
|
25
|
+
db.close();
|
|
26
|
+
let connect = null;
|
|
27
|
+
const wss = new WebSocketServer({ port: 0 });
|
|
28
|
+
wss.on('connection', ws => {
|
|
29
|
+
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: { nonce: 'n' } }));
|
|
30
|
+
ws.on('message', raw => {
|
|
31
|
+
const m = JSON.parse(raw.toString());
|
|
32
|
+
if (m.method === 'connect') { connect = m.params; return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: true, payload: { type: 'hello-ok' } })); }
|
|
33
|
+
if (m.method === 'sessions.list') return ws.send(JSON.stringify({ type: 'res', id: m.id, ok: true, payload: { sessions: [{ key: 'agent:main:proj:chat:t2' }], hasMore: false, nextOffset: null } }));
|
|
34
|
+
ws.send(JSON.stringify({ type: 'res', id: m.id, ok: false, error: { message: 'unexpected' } }));
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
await new Promise(r => wss.once('listening', r));
|
|
38
|
+
const run = (opts = {}) => exportHistory({ dataDir, stateDir, gatewayUrl: `ws://127.0.0.1:${wss.address().port}`, token: 't', print: () => {}, ...opts });
|
|
39
|
+
const cleanup = async () => { await new Promise(r => wss.close(r)); fs.rmSync(dir, { recursive: true, force: true }); };
|
|
40
|
+
return { run, cleanup, stateDir, connectParams: () => connect };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test('export-history copies the text as it was (the user\'s own history, same machine); check mode writes nothing', async () => {
|
|
44
|
+
const f = await fixture();
|
|
45
|
+
try {
|
|
46
|
+
const checked = await f.run({ check: true });
|
|
47
|
+
assert.deepEqual([checked.exported, checked.written], [1, []]);
|
|
48
|
+
assert.equal(fs.existsSync(path.join(f.stateDir, 'agents')), false);
|
|
49
|
+
const res = await f.run();
|
|
50
|
+
assert.equal(res.exported, 1);
|
|
51
|
+
const dir = path.join(f.stateDir, 'agents', 'main', 'sessions');
|
|
52
|
+
assert.ok(fs.readFileSync(path.join(dir, fs.readdirSync(dir).find(n => n.endsWith('.jsonl'))), 'utf8').includes(KEY));
|
|
53
|
+
} finally { await f.cleanup(); }
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('export-history connects with the connector\'s own scopes, so a gateway with roles still lists every session', async () => {
|
|
57
|
+
const f = await fixture();
|
|
58
|
+
try {
|
|
59
|
+
await f.run({ check: true });
|
|
60
|
+
const p = f.connectParams();
|
|
61
|
+
assert.ok(p.scopes.includes('operator.read') && p.scopes.includes('operator.admin'));
|
|
62
|
+
} finally { await f.cleanup(); }
|
|
63
|
+
});
|
package/server/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { Database } from './bootstrap/native.js';
|
|
|
8
8
|
import { GATEWAY_WS_URL, AUTH_TOKEN, discoverWorkspaceDir } from './config.js';
|
|
9
9
|
import { DebugLogger } from './debug.js';
|
|
10
10
|
import { GatewayClient } from './gateway.js';
|
|
11
|
+
import { withGatewayRetry } from './util/gateway-retry.js';
|
|
11
12
|
import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload, handleWorkspaceCreate, handleWorkspaceMove, handleWorkspaceCopy } from './controllers/filesystem.js';
|
|
12
13
|
import { handleTranscribe } from './controllers/transcribe.js';
|
|
13
14
|
import { createGatewayMediaHandler } from './controllers/gateway-media.js';
|
|
@@ -79,7 +80,9 @@ export function createApp(config = {}) {
|
|
|
79
80
|
const extras = createExtrasStore(() => globalDbCache.get());
|
|
80
81
|
try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
|
|
81
82
|
catch (e) { console.error('[extras] style seed failed:', e.message); }
|
|
82
|
-
|
|
83
|
+
// The connector's own requests wait out a gateway that is still starting (2026.11.4+ refuses writes with a retryable
|
|
84
|
+
// UNAVAILABLE; util/gateway-retry.js). Frames a browser relays don't pass here: the frontend retries those.
|
|
85
|
+
const gwRequest = withGatewayRetry((m, p, t) => gatewayClient.request(m, p, t));
|
|
83
86
|
// Gateway sharing (server/peer/): other people's agents in team chats, and ours in theirs. The
|
|
84
87
|
// plugin host (src/index.ts) supplies the signal server link and the peer transport (config.peer).
|
|
85
88
|
const peerKey = loadOrCreatePeerKey(DATA_DIR);
|
|
@@ -55,17 +55,50 @@ export function hasGuestRestrictions(tools) {
|
|
|
55
55
|
export async function ensureGuestRestrictions(request, agentId) {
|
|
56
56
|
const cfg = await request('config.get', {});
|
|
57
57
|
if (hasGuestRestrictions(cfg?.parsed?.agents?.entries?.[agentId]?.tools)) return false;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
58
|
+
try {
|
|
59
|
+
await request('config.patch', {
|
|
60
|
+
raw: JSON.stringify({ agents: { entries: { [agentId]: { tools: GUEST_TOOLS } } } }),
|
|
61
|
+
...(cfg?.hash ? { baseHash: cfg.hash } : {}),
|
|
62
|
+
// The gateway only lets a patch shrink an array named exactly (a parent path doesn't count),
|
|
63
|
+
// e.g. dropping view_image/pdf from an older guest's alsoAllow.
|
|
64
|
+
replacePaths: ['', '.alsoAllow', '.deny'].map(p => `agents.entries.${agentId}.tools${p}`),
|
|
65
|
+
note: `ClawChats sharing: guest restrictions for ${agentId}`,
|
|
66
|
+
}, 60_000);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
if (!persistedButNotApplied(e, agentId)) throw e;
|
|
69
|
+
// 2026.11.4+: the patch was saved but the running gateway didn't apply it yet (a plugin deferred the reload, or a
|
|
70
|
+
// restart is pending). Sharing it now is fine once it applies: until then the turn check (restrictionsPending)
|
|
71
|
+
// keeps the guest from being served on the old tool policy.
|
|
72
|
+
unappliedGuests.add(agentId);
|
|
73
|
+
}
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Guests whose restrictions were saved but not yet applied by the running gateway (see ensureGuestRestrictions). */
|
|
78
|
+
export const unappliedGuests = new Set();
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Whether a guest's saved restrictions still aren't the running gateway's. Only for a guest ensureGuestRestrictions
|
|
82
|
+
* had to leave unapplied: config.get's configRevisionHash (saved) differs from appliedConfigHash (running) until the
|
|
83
|
+
* reload lands (the check the gateway's own CLI uses). Missing hashes (older gateways) count as applied.
|
|
84
|
+
*/
|
|
85
|
+
export function restrictionsPending(cfg, agentId) {
|
|
86
|
+
if (!unappliedGuests.has(agentId)) return false;
|
|
87
|
+
const saved = cfg?.configRevisionHash, applied = cfg?.appliedConfigHash;
|
|
88
|
+
if (typeof saved !== 'string' || typeof applied !== 'string' || saved === applied) { unappliedGuests.delete(agentId); return false; }
|
|
66
89
|
return true;
|
|
67
90
|
}
|
|
68
91
|
|
|
92
|
+
/**
|
|
93
|
+
* Whether a failed config.patch had saved its change anyway (2026.11.4+: UNAVAILABLE with details.persistedConfig).
|
|
94
|
+
* When the error carries the saved config (not on every path), it must show this guest's restrictions.
|
|
95
|
+
*/
|
|
96
|
+
export function persistedButNotApplied(e, agentId) {
|
|
97
|
+
const saved = e?.gatewayCode === 'UNAVAILABLE' && e.details?.persistedConfig;
|
|
98
|
+
if (!saved || typeof saved !== 'object') return false;
|
|
99
|
+
return saved.config === undefined || hasGuestRestrictions(saved.config?.agents?.entries?.[agentId]?.tools);
|
|
100
|
+
}
|
|
101
|
+
|
|
69
102
|
/** A new agent is only usable once the gateway's config reload picked it up. */
|
|
70
103
|
async function waitForAgent(request, agentId, { tries = 120, ms = 250 } = {}) {
|
|
71
104
|
for (let i = 0; i < tries; i++) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
|
-
import { createGuestAgent, GUEST_TOOLS, GUEST_TOOLS_DENY, hasGuestRestrictions } from './guest-agent.js';
|
|
3
|
+
import { createGuestAgent, ensureGuestRestrictions, restrictionsPending, unappliedGuests, GUEST_TOOLS, GUEST_TOOLS_DENY, hasGuestRestrictions } from './guest-agent.js';
|
|
4
4
|
|
|
5
5
|
function fakeGateway() {
|
|
6
6
|
const agents = [{ id: 'jarvis', identity: { name: 'Jarvis', emoji: '🤖' }, model: { primary: 'anthropic/claude-x' }, workspace: '/home/k/.openclaw/workspace' }];
|
|
@@ -102,3 +102,52 @@ test('a guest the gateway shows under the original\'s name is still found (and h
|
|
|
102
102
|
assert.equal(findGuestAgent([agents[0], agents[2]], 'capy', new Set(['capy-guest-2']))?.id, 'capy-guest-2');
|
|
103
103
|
assert.ok(isGuestAgent(agents[1], new Set(['capy-guest'])) && !isGuestAgent(agents[0], new Set(['capy-guest'])));
|
|
104
104
|
});
|
|
105
|
+
|
|
106
|
+
/** What a 2026.11.4+ gateway answers when config.patch saved the change but the running gateway didn't apply it. */
|
|
107
|
+
const persistedError = (config, extra = {}) => Object.assign(new Error('config.patch persisted but was not applied to the active Gateway (plugin-reload-deferred)'), {
|
|
108
|
+
gatewayCode: 'UNAVAILABLE', details: { persistedConfig: { hash: 'h2', ...(config ? { config } : {}) } }, ...extra,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('config.get -> config.patch round trip: baseHash from config.get, exact-path replacePaths (as the 11.6 handler requires)', async () => {
|
|
112
|
+
const calls = [];
|
|
113
|
+
await ensureGuestRestrictions(async (m, p) => {
|
|
114
|
+
calls.push([m, p]);
|
|
115
|
+
return m === 'config.get' ? { hash: 'abc', parsed: { agents: { entries: { g: { tools: { profile: 'full' } } } } } } : { ok: true };
|
|
116
|
+
}, 'g');
|
|
117
|
+
assert.equal(calls[1][1].baseHash, 'abc');
|
|
118
|
+
assert.deepEqual(calls[1][1].replacePaths, ['agents.entries.g.tools', 'agents.entries.g.tools.alsoAllow', 'agents.entries.g.tools.deny']);
|
|
119
|
+
assert.deepEqual(JSON.parse(calls[1][1].raw), { agents: { entries: { g: { tools: GUEST_TOOLS } } } });
|
|
120
|
+
// Without a hash (a gateway that doesn't send one) the patch still goes out, hash-free.
|
|
121
|
+
const noHash = [];
|
|
122
|
+
await ensureGuestRestrictions(async (m, p) => { noHash.push([m, p]); return m === 'config.get' ? { parsed: {} } : { ok: true }; }, 'g');
|
|
123
|
+
assert.equal('baseHash' in noHash[1][1], false);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('a config.patch that persisted but was not applied counts as written; the guest is not served until it applies', async () => {
|
|
127
|
+
unappliedGuests.clear();
|
|
128
|
+
const patched = async config => ensureGuestRestrictions(async m => {
|
|
129
|
+
if (m === 'config.get') return { hash: 'h1', parsed: {} };
|
|
130
|
+
throw persistedError(config);
|
|
131
|
+
}, 'g1');
|
|
132
|
+
// The saved config the error carries shows the restrictions (or isn't included): accepted.
|
|
133
|
+
assert.equal(await patched({ agents: { entries: { g1: { tools: GUEST_TOOLS } } } }), true);
|
|
134
|
+
assert.equal(await patched(undefined), true);
|
|
135
|
+
// Until the running config catches up, the turn check says "pending"; afterwards it clears.
|
|
136
|
+
assert.equal(restrictionsPending({ configRevisionHash: 'saved', appliedConfigHash: 'older' }, 'g1'), true);
|
|
137
|
+
assert.equal(restrictionsPending({ configRevisionHash: 'saved', appliedConfigHash: 'saved' }, 'g1'), false);
|
|
138
|
+
assert.equal(restrictionsPending({ configRevisionHash: 'saved', appliedConfigHash: 'older' }, 'g1'), false); // forgotten once applied
|
|
139
|
+
// A guest that never failed to apply isn't gated, and neither is a gateway without the hashes (9.7).
|
|
140
|
+
assert.equal(restrictionsPending({ configRevisionHash: 'a', appliedConfigHash: 'b' }, 'other'), false);
|
|
141
|
+
await patched(undefined);
|
|
142
|
+
assert.equal(restrictionsPending({ hash: 'x' }, 'g1'), false);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('a failed config.patch is still a failure unless it saved this guest\'s restrictions', async () => {
|
|
146
|
+
const run = error => ensureGuestRestrictions(async m => { if (m === 'config.get') return { hash: 'h', parsed: {} }; throw error; }, 'g2');
|
|
147
|
+
await assert.rejects(run(new Error('config base hash required')), /base hash/);
|
|
148
|
+
await assert.rejects(run(Object.assign(new Error('x'), { gatewayCode: 'INVALID_REQUEST', details: { persistedConfig: {} } })), /x/);
|
|
149
|
+
await assert.rejects(run(Object.assign(new Error('busy'), { gatewayCode: 'UNAVAILABLE' })), /busy/); // nothing was saved
|
|
150
|
+
// The saved config shows the agent without the restrictions: not what we wrote.
|
|
151
|
+
await assert.rejects(run(persistedError({ agents: { entries: { g2: { tools: { profile: 'full' } } } } })), /persisted/);
|
|
152
|
+
await assert.rejects(run(persistedError({ agents: { entries: {} } })), /persisted/);
|
|
153
|
+
});
|
package/server/peer/keys.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import crypto from 'node:crypto';
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
+
import { WORDS } from './wordlist.js';
|
|
8
9
|
|
|
9
10
|
/** JSON with sorted keys: what both sides sign and verify (same as the signal server's). */
|
|
10
11
|
export function canonicalJson(v) {
|
|
@@ -27,6 +28,17 @@ export function fingerprint(pubB64) {
|
|
|
27
28
|
return h.match(/.{4}/g).join('-');
|
|
28
29
|
}
|
|
29
30
|
|
|
31
|
+
/**
|
|
32
|
+
* The same key as four easy-to-compare words, e.g. `maple-orbit-tiger-lantern` (4 x 12.9 = about
|
|
33
|
+
* 52 bits). Display only: the pinned and compared value stays the key itself. The browser has the
|
|
34
|
+
* identical function (frontend/connection/device-auth.js keyWords) and the identical list.
|
|
35
|
+
* Each word is the next 32 bits of the key's SHA-256 modulo 7776 (bias below 10^-6).
|
|
36
|
+
*/
|
|
37
|
+
export function fingerprintWords(pubB64) {
|
|
38
|
+
const h = crypto.createHash('sha256').update(Buffer.from(String(pubB64 || ''), 'base64')).digest();
|
|
39
|
+
return [0, 4, 8, 12].map(i => WORDS[h.readUInt32BE(i) % WORDS.length]).join('-');
|
|
40
|
+
}
|
|
41
|
+
|
|
30
42
|
/** Load the key pair from `<dataDir>/peer-key.json`, creating it (mode 0600) on first use. */
|
|
31
43
|
export function loadOrCreatePeerKey(dataDir) {
|
|
32
44
|
const file = path.join(dataDir, 'peer-key.json');
|
package/server/peer/sharing.js
CHANGED
|
@@ -16,9 +16,12 @@
|
|
|
16
16
|
import crypto from 'node:crypto';
|
|
17
17
|
import { PeerLink } from './link.js';
|
|
18
18
|
import { canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
19
|
-
import {
|
|
19
|
+
import { redactSecrets } from '../util/redact.js';
|
|
20
|
+
import { hasGuestRestrictions, ensureGuestRestrictions, findGuestAgent, isGuestAgent, restrictionsPending } from './guest-agent.js';
|
|
20
21
|
|
|
21
22
|
const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
23
|
+
/** The gateway's "the run gave no visible reply" failure (2026.10.1+: a passed turn, see team.js PASS_TOKEN). */
|
|
24
|
+
export const EMPTY_REPLY_ERROR = /empty response|did not produce a visible reply/i;
|
|
22
25
|
const DEFAULT_DAILY_CAP = 50;
|
|
23
26
|
const MAX_CONCURRENT_TURNS = 2; // per share: the daily cap alone would allow 50 parallel 10-minute runs
|
|
24
27
|
const ACCESS_MODES = { restricted: 'read-only', trusted: 'guarded' };
|
|
@@ -194,6 +197,8 @@ export class SharingManager {
|
|
|
194
197
|
const presented = s.as === 'owner' ? s.requester?.pubKey : s.owner?.pubKey;
|
|
195
198
|
const pinned = this._gatewayKey(this._other(s).gatewayId);
|
|
196
199
|
out.keyChanged = !!(presented && pinned && presented !== pinned);
|
|
200
|
+
// What "Trust new key" would accept, as fingerprints to compare with the contact out of band.
|
|
201
|
+
if (out.keyChanged) out.keyChange = { was: fingerprint(pinned), now: fingerprint(presented) };
|
|
197
202
|
return out;
|
|
198
203
|
});
|
|
199
204
|
}
|
|
@@ -592,12 +597,18 @@ export class SharingManager {
|
|
|
592
597
|
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());
|
|
593
598
|
this._changed(); // the owner's Sharing view shows today's count
|
|
594
599
|
try {
|
|
595
|
-
|
|
600
|
+
// Everything the guest's agent says leaves this gateway (to the other person, or into a room they see). The
|
|
601
|
+
// gateway stopped masking secrets in tool output in 2026.10.10, so a credential an agent read can come out in
|
|
602
|
+
// its reply: redact it here (util/redact.js), in the streamed text, the final one and a failed turn's partial.
|
|
603
|
+
const safeEmit = emit && ((event, data) => emit(event, event === 'delta' ? redactSecrets(data) : data));
|
|
604
|
+
const r = await this._runGuestTurn(shareId, grant, agent, roomId, p, safeEmit, this._turns.get(turnKey));
|
|
605
|
+
if (typeof r?.text === 'string') r.text = redactSecrets(r.text);
|
|
596
606
|
// What this gateway's agent said for that gateway's room: its copy of the room may show it as ours (team.js).
|
|
597
607
|
if (!p.inOwnerRoom && r?.text) try { this.onGuestReply?.(grant.requesterGatewayId, roomId, shareId, agent.id, r.text); } catch { /* best effort */ }
|
|
598
608
|
return r;
|
|
599
609
|
}
|
|
600
610
|
catch (e) {
|
|
611
|
+
if (typeof e?.partial === 'string') e.partial = redactSecrets(e.partial);
|
|
601
612
|
// A reply that failed without saying anything doesn't use up the day's replies. A timeout still
|
|
602
613
|
// counts: it ran for the full turn timeout.
|
|
603
614
|
if (!e.partial && !/timed out/i.test(e.message)) {
|
|
@@ -613,7 +624,7 @@ export class SharingManager {
|
|
|
613
624
|
const cfg = await this.request('config.get', {}, 30_000);
|
|
614
625
|
// A guest version whose restrictions were edited away (e.g. in the Control UI) isn't served.
|
|
615
626
|
const isGuest = this._db().prepare('SELECT 1 FROM peer_guest_agents WHERE agent_id = ?').get(agent.id);
|
|
616
|
-
if (isGuest && !hasGuestRestrictions(cfg?.parsed?.agents?.entries?.[agent.id]?.tools)) {
|
|
627
|
+
if (isGuest && (!hasGuestRestrictions(cfg?.parsed?.agents?.entries?.[agent.id]?.tools) || restrictionsPending(cfg, agent.id))) {
|
|
617
628
|
this.log.warn?.(`[sharing] ${agent.id} lost its guest restrictions: refusing turn for ${shareId}`);
|
|
618
629
|
throw Object.assign(new Error(`${agent.name} isn't available right now`), { code: 'unavailable' });
|
|
619
630
|
}
|
|
@@ -645,6 +656,9 @@ export class SharingManager {
|
|
|
645
656
|
const r = await done;
|
|
646
657
|
if (r.state === 'final') return { state: 'final', text: r.message ? messageText(r.message) : await this._lastReply(sessionKey) };
|
|
647
658
|
if (r.state === 'aborted') return { state: 'aborted', text: r.text || '' };
|
|
659
|
+
// A host on an older connector still asks for NO_REPLY: on 2026.10.1+ that ends the run with an empty-reply
|
|
660
|
+
// error and no final. Report it as an empty reply; the host treats that as a pass.
|
|
661
|
+
if (!r.text && EMPTY_REPLY_ERROR.test(r.errorMessage || '')) return { state: 'final', text: '' };
|
|
648
662
|
throw Object.assign(new Error(r.errorMessage || 'The agent run failed'), { code: 'run_failed', partial: r.text || '' });
|
|
649
663
|
} finally {
|
|
650
664
|
const run = this._runs.get(runId);
|