@clawchatsai/connector 0.1.29 → 0.1.31
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/index.js +83 -1
- package/dist/signaling-client.d.ts +5 -0
- package/dist/signaling-client.js +29 -0
- package/dist/webrtc-peer.d.ts +33 -0
- package/dist/webrtc-peer.js +94 -3
- package/package.json +1 -1
- package/server/gateway.js +1 -1
- package/server/index.js +45 -3
- package/server/peer/guest-agent.js +144 -0
- package/server/peer/guest-agent.test.js +81 -0
- package/server/peer/keys.js +49 -0
- package/server/peer/link.js +152 -0
- package/server/peer/link.test.js +102 -0
- package/server/peer/sharing.js +473 -0
- package/server/peer/sharing.test.js +382 -0
- package/server/team.js +88 -14
- package/server/team.test.js +110 -2
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Guest version of an agent, for sharing (clawchats specs/gateway-sharing.md → Safety).
|
|
2
|
+
//
|
|
3
|
+
// The gateway can't restrict most tools per session (permission modes only cover file tools and
|
|
4
|
+
// exec), so the real boundary is the agent's own config. A guest version has the original's model
|
|
5
|
+
// and personality (SOUL.md, IDENTITY.md) but not its private memory (MEMORY.md, USER.md), its own
|
|
6
|
+
// fresh workspace, and an allowlist of tools: files and exec, which the session's permission mode
|
|
7
|
+
// then limits (read-only, or guarded = the owner approves). Everything that reaches beyond its own
|
|
8
|
+
// folder (other sessions, messaging, scheduling, browsing, devices, plugins and MCP, secrets,
|
|
9
|
+
// gateway config) is denied on top, so it stays out even if the profile list grows. `view_image`
|
|
10
|
+
// and `pdf` are denied too: unlike the managed file tools they ignore the session's permission mode,
|
|
11
|
+
// so a guest could use them to read any local path (openclaw.json, MEMORY.md…) or reach an internal
|
|
12
|
+
// URL (SSRF). `fs.workspaceOnly` pins the managed file tools to the guest's own folder on top of the
|
|
13
|
+
// permission mode. Created only when the owner asks for it (ClawChats → Sharing).
|
|
14
|
+
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
/** The guest's tool policy (gateway `agents.entries.<id>.tools`; tool groups per docs/gateway/config-tools/tool-policy.md). */
|
|
18
|
+
export const GUEST_TOOLS = Object.freeze({
|
|
19
|
+
profile: 'minimal',
|
|
20
|
+
alsoAllow: ['group:fs', 'group:runtime'],
|
|
21
|
+
deny: [
|
|
22
|
+
'group:sessions', 'group:automation', 'group:ui', 'group:nodes', 'group:messaging', 'group:plugins',
|
|
23
|
+
'group:agents', 'group:memory', 'group:web',
|
|
24
|
+
'gateway', 'openclaw', 'cron', 'automations', 'plugins', 'secrets', 'personal_instructions', 'session_status',
|
|
25
|
+
'sessions', 'sessions_spawn', 'sessions_send', 'sessions_history', 'sessions_list', 'sessions_search', 'subagents',
|
|
26
|
+
'conversations_list', 'conversations_send', 'conversations_turn', 'message', 'nodes', 'computer', 'browser', 'canvas',
|
|
27
|
+
'terminal', 'portal', 'skill_workshop', 'agents_list', 'image_generate', 'music_generate', 'video_generate', 'tts',
|
|
28
|
+
'view_image', 'pdf',
|
|
29
|
+
'discord', 'slack', 'telegram', 'whatsapp',
|
|
30
|
+
],
|
|
31
|
+
fs: Object.freeze({ workspaceOnly: true }),
|
|
32
|
+
});
|
|
33
|
+
export const GUEST_TOOLS_DENY = GUEST_TOOLS.deny;
|
|
34
|
+
const PERSONALITY_FILES = ['SOUL.md', 'IDENTITY.md'];
|
|
35
|
+
export const guestName = name => `${name} (guest)`;
|
|
36
|
+
|
|
37
|
+
const agentName = a => a?.identity?.name || a?.name || a?.id;
|
|
38
|
+
const wait = ms => new Promise(r => setTimeout(r, ms));
|
|
39
|
+
|
|
40
|
+
/** Whether an agent's configured tools are (at least) as narrow as the guest policy. */
|
|
41
|
+
export function hasGuestRestrictions(tools) {
|
|
42
|
+
if (!tools || tools.profile !== GUEST_TOOLS.profile || tools.allow) return false;
|
|
43
|
+
if (!tools.fs || tools.fs.workspaceOnly !== true) return false; // file tools pinned to the guest's folder
|
|
44
|
+
const also = Array.isArray(tools.alsoAllow) ? tools.alsoAllow : [];
|
|
45
|
+
const deny = Array.isArray(tools.deny) ? tools.deny : [];
|
|
46
|
+
// `also` a subset of the allowlist: a guest whose alsoAllow still lists view_image/pdf (made before
|
|
47
|
+
// they were removed) fails here and is re-patched on reuse; `_runGuestTurn` won't serve it meanwhile.
|
|
48
|
+
return also.every(t => GUEST_TOOLS.alsoAllow.includes(t)) && GUEST_TOOLS.deny.every(t => deny.includes(t));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Make sure the guest's tool policy is in the gateway config (idempotent; writes only when missing).
|
|
53
|
+
* Runs before anything else touches a guest agent: a guest without it must never be shared.
|
|
54
|
+
*/
|
|
55
|
+
export async function ensureGuestRestrictions(request, agentId) {
|
|
56
|
+
const cfg = await request('config.get', {});
|
|
57
|
+
if (hasGuestRestrictions(cfg?.parsed?.agents?.entries?.[agentId]?.tools)) return false;
|
|
58
|
+
await request('config.patch', {
|
|
59
|
+
raw: JSON.stringify({ agents: { entries: { [agentId]: { tools: GUEST_TOOLS } } } }),
|
|
60
|
+
...(cfg?.hash ? { baseHash: cfg.hash } : {}),
|
|
61
|
+
// The gateway only lets a patch shrink an array named exactly (a parent path doesn't count),
|
|
62
|
+
// e.g. dropping view_image/pdf from an older guest's alsoAllow.
|
|
63
|
+
replacePaths: ['', '.alsoAllow', '.deny'].map(p => `agents.entries.${agentId}.tools${p}`),
|
|
64
|
+
note: `ClawChats sharing: guest restrictions for ${agentId}`,
|
|
65
|
+
}, 60_000);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A new agent is only usable once the gateway's config reload picked it up. */
|
|
70
|
+
async function waitForAgent(request, agentId, { tries = 40, ms = 250 } = {}) {
|
|
71
|
+
for (let i = 0; i < tries; i++) {
|
|
72
|
+
if (((await request('agents.list', {}))?.agents || []).some(a => a.id === agentId)) return true;
|
|
73
|
+
await wait(ms);
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The guest version of `agentId` if it already exists (by name). */
|
|
79
|
+
export function findGuestAgent(agents, agentId) {
|
|
80
|
+
const src = agents.find(a => a.id === agentId);
|
|
81
|
+
return src ? agents.find(a => agentName(a) === guestName(agentName(src))) || null : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Create (or reuse) the guest version of an agent. Returns { agentId, name, created }.
|
|
86
|
+
* @param {(m: string, p: object, t?: number) => Promise<any>} request gateway RPC (operator.admin)
|
|
87
|
+
*/
|
|
88
|
+
export async function createGuestAgent(request, agentId) {
|
|
89
|
+
const agents = (await request('agents.list', {}))?.agents || [];
|
|
90
|
+
const src = agents.find(a => a.id === agentId);
|
|
91
|
+
if (!src) throw new Error(`unknown agent: ${agentId}`);
|
|
92
|
+
if (/\(guest\)$/.test(agentName(src))) {
|
|
93
|
+
await ensureGuestRestrictions(request, src.id); // repairs a guest agent left without them
|
|
94
|
+
return { agentId: src.id, name: agentName(src), created: false };
|
|
95
|
+
}
|
|
96
|
+
const existing = findGuestAgent(agents, agentId);
|
|
97
|
+
if (existing) {
|
|
98
|
+
// Repair a guest half-made by an earlier run: restore its restrictions, then the personality a
|
|
99
|
+
// crash between create and copy would have skipped (only missing files; never clobber edits).
|
|
100
|
+
await ensureGuestRestrictions(request, existing.id);
|
|
101
|
+
await copyPersonality(request, src.id, existing.id, { onlyMissing: true });
|
|
102
|
+
return { agentId: existing.id, name: agentName(existing), created: false };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const name = guestName(agentName(src));
|
|
106
|
+
const model = typeof src.model === 'string' ? src.model : src.model?.primary;
|
|
107
|
+
// Its own folder next to the original's workspace, not inside it (the default nests it in the
|
|
108
|
+
// agents' workspace, where the owner's main agent would see it as part of its own files).
|
|
109
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'guest';
|
|
110
|
+
const workspace = typeof src.workspace === 'string' && src.workspace.startsWith('/')
|
|
111
|
+
? path.join(path.dirname(src.workspace.replace(/\/+$/, '')), `workspace-${slug}`) : undefined;
|
|
112
|
+
const created = await request('agents.create', {
|
|
113
|
+
name, ...(workspace ? { workspace } : {}), ...(model ? { model } : {}), ...(src.identity?.emoji ? { emoji: src.identity.emoji } : {}),
|
|
114
|
+
}, 60_000);
|
|
115
|
+
const id = created.agentId;
|
|
116
|
+
|
|
117
|
+
// Restrictions first: if anything after this fails, the agent is still safe to exist.
|
|
118
|
+
await ensureGuestRestrictions(request, id);
|
|
119
|
+
if (!(await waitForAgent(request, id))) throw new Error(`The gateway didn't load ${name} yet; try again`);
|
|
120
|
+
|
|
121
|
+
await copyPersonality(request, src.id, id);
|
|
122
|
+
return { agentId: id, name, created: true };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Copy the original's personality (SOUL.md, IDENTITY.md) to the guest; never MEMORY.md / USER.md.
|
|
127
|
+
* Best effort — a guest without it still works. With `onlyMissing`, leaves files the guest already
|
|
128
|
+
* has (an owner may have edited the guest's copy), so repair fills gaps without clobbering.
|
|
129
|
+
*/
|
|
130
|
+
async function copyPersonality(request, srcId, destId, { onlyMissing = false } = {}) {
|
|
131
|
+
for (const file of PERSONALITY_FILES) {
|
|
132
|
+
if (onlyMissing) {
|
|
133
|
+
const have = await request('agents.files.get', { agentId: destId, name: file }).catch(() => null);
|
|
134
|
+
if (have?.file && !have.file.missing && typeof have.file.content === 'string' && have.file.content.trim()) continue;
|
|
135
|
+
}
|
|
136
|
+
const got = await request('agents.files.get', { agentId: srcId, name: file }).catch(() => null);
|
|
137
|
+
const content = got?.file && !got.file.missing ? got.file.content : null;
|
|
138
|
+
if (typeof content !== 'string' || !content.trim()) continue;
|
|
139
|
+
for (let i = 0; i < 5; i++) {
|
|
140
|
+
try { await request('agents.files.set', { agentId: destId, name: file, content }); break; }
|
|
141
|
+
catch (e) { if (i === 4 || !/not found/i.test(e.message)) break; await wait(400); }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { createGuestAgent, GUEST_TOOLS, GUEST_TOOLS_DENY, hasGuestRestrictions } from './guest-agent.js';
|
|
4
|
+
|
|
5
|
+
function fakeGateway() {
|
|
6
|
+
const agents = [{ id: 'jarvis', identity: { name: 'Jarvis', emoji: '🤖' }, model: { primary: 'anthropic/claude-x' }, workspace: '/home/k/.openclaw/workspace' }];
|
|
7
|
+
const files = { jarvis: { 'SOUL.md': 'be kind', 'IDENTITY.md': 'I am Jarvis', 'MEMORY.md': 'owner secrets', 'USER.md': 'owner profile' } };
|
|
8
|
+
const calls = [];
|
|
9
|
+
const config = {};
|
|
10
|
+
const request = async (method, params) => {
|
|
11
|
+
calls.push({ method, params });
|
|
12
|
+
switch (method) {
|
|
13
|
+
case 'agents.list': return { agents };
|
|
14
|
+
// Like the real gateway: the new agent only appears after the config reload (a few calls later).
|
|
15
|
+
case 'agents.create': { const id = 'jarvis-guest'; setTimeout(() => agents.push({ id, identity: { name: params.name } }), 30); files[id] = {}; return { ok: true, agentId: id, name: params.name, workspace: '/w/jarvis-guest' }; }
|
|
16
|
+
case 'agents.files.get': { const c = files[params.agentId]?.[params.name]; return { file: { name: params.name, missing: c == null, content: c } }; }
|
|
17
|
+
case 'agents.files.set': if (!agents.some(a => a.id === params.agentId)) throw new Error(`agent "${params.agentId}" not found`); files[params.agentId][params.name] = params.content; return { ok: true };
|
|
18
|
+
case 'config.get': return { hash: 'h1', parsed: { agents: { entries: Object.fromEntries(Object.entries(config).map(([k, v]) => [k, v])) } } };
|
|
19
|
+
case 'config.patch': { const p = JSON.parse(params.raw).agents.entries; for (const [k, v] of Object.entries(p)) config[k] = v; return { ok: true }; }
|
|
20
|
+
default: throw new Error(method);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
return { request, calls, files, agents, config };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
test('guest agent: same model + personality, no private memory, deny list applied; reused next time', async () => {
|
|
27
|
+
const g = fakeGateway();
|
|
28
|
+
const r = await createGuestAgent(g.request, 'jarvis');
|
|
29
|
+
assert.deepEqual(r, { agentId: 'jarvis-guest', name: 'Jarvis (guest)', created: true });
|
|
30
|
+
const create = g.calls.find(c => c.method === 'agents.create').params;
|
|
31
|
+
assert.deepEqual(create, { name: 'Jarvis (guest)', workspace: '/home/k/.openclaw/workspace-jarvis-guest', model: 'anthropic/claude-x', emoji: '🤖' });
|
|
32
|
+
assert.equal(create.workspace, '/home/k/.openclaw/workspace-jarvis-guest'); // its own folder, next to (not inside) the original's
|
|
33
|
+
assert.deepEqual(g.files['jarvis-guest'], { 'SOUL.md': 'be kind', 'IDENTITY.md': 'I am Jarvis' });
|
|
34
|
+
const patch = g.calls.find(c => c.method === 'config.patch').params;
|
|
35
|
+
assert.deepEqual(JSON.parse(patch.raw), { agents: { entries: { 'jarvis-guest': { tools: GUEST_TOOLS } } } });
|
|
36
|
+
assert.equal(patch.baseHash, 'h1');
|
|
37
|
+
// Allowlist (minimal profile) plus every group that reaches beyond its own folder denied on top.
|
|
38
|
+
assert.equal(GUEST_TOOLS.profile, 'minimal');
|
|
39
|
+
// File tools pinned to the guest's own folder; nothing extra allowed beyond files + exec.
|
|
40
|
+
assert.equal(GUEST_TOOLS.fs.workspaceOnly, true);
|
|
41
|
+
assert.deepEqual(GUEST_TOOLS.alsoAllow, ['group:fs', 'group:runtime']);
|
|
42
|
+
for (const t of ['group:sessions', 'group:messaging', 'group:automation', 'group:ui', 'group:nodes', 'group:plugins', 'group:agents',
|
|
43
|
+
'sessions_search', 'conversations_send', 'secrets', 'computer', 'message', 'cron', 'browser', 'gateway',
|
|
44
|
+
'view_image', 'pdf']) assert.ok(GUEST_TOOLS_DENY.includes(t), t); // view_image/pdf ignore permission mode: denied
|
|
45
|
+
|
|
46
|
+
const again = await createGuestAgent(g.request, 'jarvis');
|
|
47
|
+
assert.deepEqual(again, { agentId: 'jarvis-guest', name: 'Jarvis (guest)', created: false });
|
|
48
|
+
assert.equal(g.calls.filter(c => c.method === 'agents.create').length, 1);
|
|
49
|
+
// Asking for the guest of a guest returns it as is.
|
|
50
|
+
assert.equal((await createGuestAgent(g.request, 'jarvis-guest')).created, false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('restrictions go on before anything else; a guest left without them is repaired on reuse', async () => {
|
|
54
|
+
const g = fakeGateway();
|
|
55
|
+
await createGuestAgent(g.request, 'jarvis');
|
|
56
|
+
const order = g.calls.map(c => c.method).filter(m => ['agents.create', 'config.patch', 'agents.files.set'].includes(m));
|
|
57
|
+
assert.deepEqual(order.slice(0, 2), ['agents.create', 'config.patch']); // deny list before personality
|
|
58
|
+
// Simulate a half-made guest (deny list lost), then reuse: it gets its restrictions back.
|
|
59
|
+
delete g.config['jarvis-guest'];
|
|
60
|
+
await createGuestAgent(g.request, 'jarvis');
|
|
61
|
+
assert.deepEqual(g.config['jarvis-guest'].tools, GUEST_TOOLS);
|
|
62
|
+
// Already restricted: no needless config write.
|
|
63
|
+
const patches = g.calls.filter(c => c.method === 'config.patch').length;
|
|
64
|
+
await createGuestAgent(g.request, 'jarvis');
|
|
65
|
+
assert.equal(g.calls.filter(c => c.method === 'config.patch').length, patches);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('hasGuestRestrictions: only a policy at least as narrow as the guest one passes', () => {
|
|
69
|
+
assert.equal(hasGuestRestrictions(GUEST_TOOLS), true);
|
|
70
|
+
assert.equal(hasGuestRestrictions({ deny: GUEST_TOOLS_DENY }), false); // old deny-only policy
|
|
71
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, profile: 'full' }), false);
|
|
72
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, alsoAllow: [...GUEST_TOOLS.alsoAllow, 'message'] }), false);
|
|
73
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, deny: GUEST_TOOLS_DENY.slice(1) }), false);
|
|
74
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, allow: ['*'] }), false);
|
|
75
|
+
assert.equal(hasGuestRestrictions(undefined), false);
|
|
76
|
+
// File tools must be workspace-pinned.
|
|
77
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, fs: undefined }), false);
|
|
78
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, fs: { workspaceOnly: false } }), false);
|
|
79
|
+
// A guest made before view_image/pdf were removed (still in alsoAllow) no longer passes.
|
|
80
|
+
assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, alsoAllow: ['group:fs', 'group:runtime', 'view_image', 'pdf'] }), false);
|
|
81
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Peer identity of this connector for gateway sharing (specs/gateway-sharing.md in clawchats):
|
|
2
|
+
// an Ed25519 key pair whose private half never leaves this machine. The public key goes to the
|
|
3
|
+
// signal server with gateway-auth; the other side pins it when a share is approved.
|
|
4
|
+
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
/** JSON with sorted keys: what both sides sign and verify (same as the signal server's). */
|
|
10
|
+
export function canonicalJson(v) {
|
|
11
|
+
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;
|
|
12
|
+
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonicalJson(v[k])}`).join(',')}}`;
|
|
13
|
+
return JSON.stringify(v);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function verifySignature(pubB64, data, sigB64) {
|
|
17
|
+
try {
|
|
18
|
+
const key = crypto.createPublicKey({ key: Buffer.from(String(pubB64), 'base64'), format: 'der', type: 'spki' });
|
|
19
|
+
if (key.asymmetricKeyType !== 'ed25519' || typeof sigB64 !== 'string') return false;
|
|
20
|
+
return crypto.verify(null, Buffer.from(data), key, Buffer.from(sigB64, 'base64'));
|
|
21
|
+
} catch { return false; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Short, comparable fingerprint of a public key (same format as the signal server shows). */
|
|
25
|
+
export function fingerprint(pubB64) {
|
|
26
|
+
const h = crypto.createHash('sha256').update(Buffer.from(String(pubB64 || ''), 'base64')).digest('hex').slice(0, 20);
|
|
27
|
+
return h.match(/.{4}/g).join('-');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Load the key pair from `<dataDir>/peer-key.json`, creating it (mode 0600) on first use. */
|
|
31
|
+
export function loadOrCreatePeerKey(dataDir) {
|
|
32
|
+
const file = path.join(dataDir, 'peer-key.json');
|
|
33
|
+
let privateKey;
|
|
34
|
+
try {
|
|
35
|
+
const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
36
|
+
privateKey = crypto.createPrivateKey({ key: Buffer.from(saved.privateKey, 'base64'), format: 'der', type: 'pkcs8' });
|
|
37
|
+
} catch {
|
|
38
|
+
privateKey = crypto.generateKeyPairSync('ed25519').privateKey;
|
|
39
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
40
|
+
fs.writeFileSync(file, JSON.stringify({ privateKey: privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64') }), { mode: 0o600 });
|
|
41
|
+
}
|
|
42
|
+
const publicKey = crypto.createPublicKey(privateKey).export({ format: 'der', type: 'spki' }).toString('base64');
|
|
43
|
+
return {
|
|
44
|
+
publicKey,
|
|
45
|
+
fingerprint: fingerprint(publicKey),
|
|
46
|
+
sign: data => crypto.sign(null, Buffer.from(data), privateKey).toString('base64'),
|
|
47
|
+
signJson: obj => crypto.sign(null, Buffer.from(canonicalJson(obj)), privateKey).toString('base64'),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// PeerLink: an authenticated request/response channel between two connectors over a WebRTC
|
|
2
|
+
// DataChannel (gateway sharing). No TOTP: each side proves it holds the key pinned for this share
|
|
3
|
+
// by signing both handshake nonces and both DTLS fingerprints as it sees them. A relay that swapped
|
|
4
|
+
// the SDP fingerprints (to sit in the middle of DTLS) makes the two views disagree, so the
|
|
5
|
+
// signatures don't verify and the link never opens.
|
|
6
|
+
//
|
|
7
|
+
// Wire format (JSON strings):
|
|
8
|
+
// { t: 'hello', v: 1, role, shareId, nonce }
|
|
9
|
+
// { t: 'auth', sig }
|
|
10
|
+
// { t: 'req', id, method, params } → { t: 'res', id, ok, result | error }
|
|
11
|
+
// { t: 'ev', id, event, data } (progress for a request, e.g. streamed text)
|
|
12
|
+
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import { EventEmitter } from 'node:events';
|
|
15
|
+
import { canonicalJson, verifySignature } from './keys.js';
|
|
16
|
+
|
|
17
|
+
const HANDSHAKE_MS = 15_000;
|
|
18
|
+
const MAX_FRAME = 256 * 1024;
|
|
19
|
+
|
|
20
|
+
/** sha-256 DTLS fingerprint from an SDP ("" when absent). */
|
|
21
|
+
export function sdpFingerprint(sdp) {
|
|
22
|
+
const m = /^a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)\s*$/m.exec(String(sdp || ''));
|
|
23
|
+
return m ? m[1].toUpperCase() : '';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class PeerLink extends EventEmitter {
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} o
|
|
29
|
+
* @param {{ send(s: string): void, close(): void, onMessage(h): void, onClosed(h): void }} o.dc
|
|
30
|
+
* @param {'requester'|'owner'} o.role this side
|
|
31
|
+
* @param {string} o.shareId
|
|
32
|
+
* @param {{ signJson(obj): string }} o.key this connector's key
|
|
33
|
+
* @param {string} o.peerKey the other side's pinned public key (base64 SPKI)
|
|
34
|
+
* @param {{ local: string, remote: string }} o.dtls DTLS fingerprints as this side sees them
|
|
35
|
+
*/
|
|
36
|
+
constructor({ dc, role, shareId, key, peerKey, dtls = { local: '', remote: '' }, handshakeMs = HANDSHAKE_MS, log = console }) {
|
|
37
|
+
super();
|
|
38
|
+
Object.assign(this, { dc, role, shareId, key, peerKey, dtls, log });
|
|
39
|
+
this.peerRole = role === 'owner' ? 'requester' : 'owner';
|
|
40
|
+
this.nonce = crypto.randomBytes(24).toString('base64');
|
|
41
|
+
this.peerNonce = null;
|
|
42
|
+
this.sentAuth = false;
|
|
43
|
+
this.verified = false;
|
|
44
|
+
this.ready = false;
|
|
45
|
+
this.closed = false;
|
|
46
|
+
this._seq = 0;
|
|
47
|
+
this._pending = new Map(); // id -> { resolve, reject, onEvent }
|
|
48
|
+
this._handlers = new Map(); // method -> async (params, emit) => result
|
|
49
|
+
this._timer = setTimeout(() => this._fail('handshake timed out'), handshakeMs);
|
|
50
|
+
this._timer.unref?.();
|
|
51
|
+
dc.onMessage(data => this._onFrame(data));
|
|
52
|
+
dc.onClosed(() => this._onClosed());
|
|
53
|
+
this._send({ t: 'hello', v: 1, role, shareId, nonce: this.nonce });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What `signer` signs: both nonces and both fingerprints, from the signer's point of view. */
|
|
57
|
+
_statement(signer, signerNonce, otherNonce, signerFp, otherFp) {
|
|
58
|
+
return canonicalJson({ purpose: 'clawchats-peer-v1', shareId: this.shareId, signer, signerNonce, otherNonce, signerFp, otherFp });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
_onFrame(data) {
|
|
62
|
+
if (this.closed) return;
|
|
63
|
+
if (typeof data !== 'string' || data.length > MAX_FRAME) return this._fail('oversized frame');
|
|
64
|
+
let m;
|
|
65
|
+
try { m = JSON.parse(data); } catch { return this._fail('bad frame'); }
|
|
66
|
+
if (!this.ready) return this._onHandshake(m);
|
|
67
|
+
if (m.t === 'req') return this._onRequest(m);
|
|
68
|
+
if (m.t === 'res') {
|
|
69
|
+
const p = this._pending.get(m.id);
|
|
70
|
+
if (!p) return;
|
|
71
|
+
this._pending.delete(m.id);
|
|
72
|
+
return m.ok ? p.resolve(m.result) : p.reject(Object.assign(new Error(m.error?.message || 'peer error'), { code: m.error?.code }));
|
|
73
|
+
}
|
|
74
|
+
if (m.t === 'ev') this._pending.get(m.id)?.onEvent?.(m.event, m.data);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
_onHandshake(m) {
|
|
78
|
+
if (m.t === 'hello') {
|
|
79
|
+
if (m.v !== 1 || m.role !== this.peerRole || m.shareId !== this.shareId || typeof m.nonce !== 'string' || this.peerNonce) return this._fail('bad hello');
|
|
80
|
+
this.peerNonce = m.nonce;
|
|
81
|
+
this.sentAuth = true;
|
|
82
|
+
this._send({ t: 'auth', sig: this.key.signJson(JSON.parse(this._statement(this.role, this.nonce, this.peerNonce, this.dtls.local, this.dtls.remote))) });
|
|
83
|
+
} else if (m.t === 'auth') {
|
|
84
|
+
if (!this.peerNonce) return this._fail('auth before hello');
|
|
85
|
+
const statement = this._statement(this.peerRole, this.peerNonce, this.nonce, this.dtls.remote, this.dtls.local);
|
|
86
|
+
if (!verifySignature(this.peerKey, statement, m.sig)) return this._fail('peer signature did not verify');
|
|
87
|
+
this.verified = true;
|
|
88
|
+
} else {
|
|
89
|
+
return this._fail('unexpected frame before auth');
|
|
90
|
+
}
|
|
91
|
+
if (this.verified && this.sentAuth && !this.ready) {
|
|
92
|
+
this.ready = true;
|
|
93
|
+
clearTimeout(this._timer);
|
|
94
|
+
this.emit('ready');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async _onRequest(m) {
|
|
99
|
+
const h = this._handlers.get(m.method);
|
|
100
|
+
const reply = r => this._send({ t: 'res', id: m.id, ...r });
|
|
101
|
+
if (!h) return reply({ ok: false, error: { code: 'unknown_method', message: `unknown method ${m.method}` } });
|
|
102
|
+
try {
|
|
103
|
+
const result = await h(m.params || {}, (event, data) => this._send({ t: 'ev', id: m.id, event, data }));
|
|
104
|
+
reply({ ok: true, result: result ?? null });
|
|
105
|
+
} catch (e) {
|
|
106
|
+
reply({ ok: false, error: { code: e.code || 'error', message: e.message || 'failed' } });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Serve a method for the other side (owner: the narrow peer API). */
|
|
111
|
+
handle(method, fn) { this._handlers.set(method, fn); return this; }
|
|
112
|
+
|
|
113
|
+
/** Call a method on the other side; `onEvent(event, data)` gets its progress events. */
|
|
114
|
+
request(method, params = {}, { onEvent, timeoutMs = 30 * 60_000 } = {}) {
|
|
115
|
+
if (!this.ready || this.closed) return Promise.reject(new Error('peer link not ready'));
|
|
116
|
+
const id = `r${++this._seq}`;
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
const timer = setTimeout(() => { this._pending.delete(id); reject(new Error(`${method} timed out`)); }, timeoutMs);
|
|
119
|
+
timer.unref?.();
|
|
120
|
+
this._pending.set(id, {
|
|
121
|
+
resolve: v => { clearTimeout(timer); resolve(v); },
|
|
122
|
+
reject: e => { clearTimeout(timer); reject(e); },
|
|
123
|
+
onEvent,
|
|
124
|
+
});
|
|
125
|
+
this._send({ t: 'req', id, method, params });
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
_send(obj) { if (!this.closed) this.dc.send(JSON.stringify(obj)); }
|
|
130
|
+
|
|
131
|
+
_fail(reason) {
|
|
132
|
+
if (this.closed) return;
|
|
133
|
+
this.log.warn?.(`[peer] ${this.shareId}: ${reason}`);
|
|
134
|
+
this.emit('failed', reason);
|
|
135
|
+
this.close();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
close() {
|
|
139
|
+
if (this.closed) return;
|
|
140
|
+
try { this.dc.close(); } catch { /* gone */ }
|
|
141
|
+
this._onClosed();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
_onClosed() {
|
|
145
|
+
if (this.closed) return;
|
|
146
|
+
this.closed = true;
|
|
147
|
+
clearTimeout(this._timer);
|
|
148
|
+
for (const [, p] of this._pending) p.reject(new Error('peer link closed'));
|
|
149
|
+
this._pending.clear();
|
|
150
|
+
this.emit('closed');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { PeerLink, sdpFingerprint } from './link.js';
|
|
8
|
+
import { loadOrCreatePeerKey, canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
9
|
+
|
|
10
|
+
const quiet = { warn() {} };
|
|
11
|
+
|
|
12
|
+
/** Two connected fake DataChannels (async delivery, like the real one). */
|
|
13
|
+
function pair() {
|
|
14
|
+
const mk = () => ({ handlers: [], closed: [], other: null, open: true,
|
|
15
|
+
send(s) { if (this.open && this.other.open) setImmediate(() => this.other.handlers.forEach(h => h(s))); },
|
|
16
|
+
close() { if (!this.open) return; this.open = false; this.closed.forEach(h => h()); this.other.close(); },
|
|
17
|
+
onMessage(h) { this.handlers.push(h); }, onClosed(h) { this.closed.push(h); } });
|
|
18
|
+
const a = mk(), b = mk(); a.other = b; b.other = a;
|
|
19
|
+
return [a, b];
|
|
20
|
+
}
|
|
21
|
+
const keyIn = () => loadOrCreatePeerKey(fs.mkdtempSync(path.join(os.tmpdir(), 'pk-')));
|
|
22
|
+
const until = (emitter, ev) => new Promise(r => emitter.once(ev, r));
|
|
23
|
+
|
|
24
|
+
test('keys: created once with 0600, reloaded, signatures verify', () => {
|
|
25
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-'));
|
|
26
|
+
const k1 = loadOrCreatePeerKey(dir), k2 = loadOrCreatePeerKey(dir);
|
|
27
|
+
assert.equal(k1.publicKey, k2.publicKey);
|
|
28
|
+
assert.equal(fs.statSync(path.join(dir, 'peer-key.json')).mode & 0o777, 0o600);
|
|
29
|
+
const sig = k1.signJson({ b: 1, a: [2, { z: 1, y: 2 }] });
|
|
30
|
+
assert.ok(verifySignature(k1.publicKey, canonicalJson({ a: [2, { y: 2, z: 1 }], b: 1 }), sig));
|
|
31
|
+
assert.ok(!verifySignature(keyIn().publicKey, canonicalJson({ a: [2, { y: 2, z: 1 }], b: 1 }), sig));
|
|
32
|
+
assert.match(fingerprint(k1.publicKey), /^[0-9a-f]{4}(-[0-9a-f]{4}){4}$/);
|
|
33
|
+
assert.equal(sdpFingerprint('v=0\r\na=fingerprint:sha-256 ab:CD:01\r\n'), 'AB:CD:01');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
function linkPair({ ownerSeesKey, requesterSeesKey, dtlsA = { local: 'FA', remote: 'FB' }, dtlsB = { local: 'FB', remote: 'FA' } } = {}) {
|
|
37
|
+
const kr = keyIn(), ko = keyIn();
|
|
38
|
+
const [dr, downer] = pair();
|
|
39
|
+
const req = new PeerLink({ dc: dr, role: 'requester', shareId: 'sh1', key: kr, peerKey: requesterSeesKey ?? ko.publicKey, dtls: dtlsA, log: quiet, handshakeMs: 2000 });
|
|
40
|
+
const own = new PeerLink({ dc: downer, role: 'owner', shareId: 'sh1', key: ko, peerKey: ownerSeesKey ?? kr.publicKey, dtls: dtlsB, log: quiet, handshakeMs: 2000 });
|
|
41
|
+
return { req, own, kr, ko };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
test('handshake: both sides ready; requests, progress events and errors flow', async () => {
|
|
45
|
+
const { req, own } = linkPair();
|
|
46
|
+
own.handle('turn', async (p, emit) => { emit('delta', 'hel'); emit('delta', 'hello'); return { text: `${p.msg}!` }; });
|
|
47
|
+
own.handle('boom', async () => { throw Object.assign(new Error('nope'), { code: 'cap' }); });
|
|
48
|
+
await Promise.all([until(req, 'ready'), until(own, 'ready')]);
|
|
49
|
+
const events = [];
|
|
50
|
+
assert.deepEqual(await req.request('turn', { msg: 'hi' }, { onEvent: (e, d) => events.push([e, d]) }), { text: 'hi!' });
|
|
51
|
+
assert.deepEqual(events, [['delta', 'hel'], ['delta', 'hello']]);
|
|
52
|
+
await assert.rejects(req.request('boom'), e => e.code === 'cap' && /nope/.test(e.message));
|
|
53
|
+
await assert.rejects(req.request('missing'), e => e.code === 'unknown_method');
|
|
54
|
+
// owner can't call requester methods it doesn't serve, and requests fail once closed
|
|
55
|
+
req.close();
|
|
56
|
+
await assert.rejects(req.request('turn', {}), /not ready/);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/** First failure reason from either side, and whether both ended closed and never both ready. */
|
|
60
|
+
function outcome(req, own) {
|
|
61
|
+
const reasons = [];
|
|
62
|
+
req.on('failed', r => reasons.push(`requester: ${r}`));
|
|
63
|
+
own.on('failed', r => reasons.push(`owner: ${r}`));
|
|
64
|
+
return Promise.all([until(req, 'closed'), until(own, 'closed')]).then(() => ({ reasons, bothReady: req.ready && own.ready }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
test('handshake fails with the wrong pinned key (impersonation)', async () => {
|
|
68
|
+
const { req, own } = linkPair({ ownerSeesKey: keyIn().publicKey });
|
|
69
|
+
const r = await outcome(req, own);
|
|
70
|
+
assert.deepEqual(r.reasons, ['owner: peer signature did not verify']);
|
|
71
|
+
assert.equal(own.ready, false); // the owner never served anything
|
|
72
|
+
assert.equal(r.bothReady, false);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('handshake fails when a relay swapped the DTLS fingerprints (man in the middle)', async () => {
|
|
76
|
+
// Each side sees a different fingerprint for the other (the relay's), so signed views disagree.
|
|
77
|
+
const { req, own } = linkPair({ dtlsA: { local: 'FA', remote: 'MITM1' }, dtlsB: { local: 'FB', remote: 'MITM2' } });
|
|
78
|
+
const r = await outcome(req, own);
|
|
79
|
+
assert.ok(r.reasons.length >= 1 && r.reasons.every(x => /signature did not verify/.test(x)));
|
|
80
|
+
assert.equal(own.ready, false);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('a requester that turns ready first still gets nothing from an owner that rejected it', async () => {
|
|
84
|
+
const { req, own } = linkPair({ ownerSeesKey: keyIn().publicKey });
|
|
85
|
+
let served = false;
|
|
86
|
+
own.handle('turn', async () => { served = true; return {}; });
|
|
87
|
+
await until(req, 'ready').catch(() => {});
|
|
88
|
+
await assert.rejects(req.request('turn', {}));
|
|
89
|
+
assert.equal(served, false);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('a peer that never authenticates is dropped; frames before auth are refused', async () => {
|
|
93
|
+
const kr = keyIn();
|
|
94
|
+
const [dr, dx] = pair();
|
|
95
|
+
const req = new PeerLink({ dc: dr, role: 'requester', shareId: 'sh1', key: kr, peerKey: keyIn().publicKey, log: quiet, handshakeMs: 100 });
|
|
96
|
+
assert.match(await until(req, 'failed'), /timed out/);
|
|
97
|
+
const [d1, d2] = pair();
|
|
98
|
+
const r2 = new PeerLink({ dc: d1, role: 'requester', shareId: 'sh1', key: kr, peerKey: keyIn().publicKey, log: quiet });
|
|
99
|
+
d2.send(JSON.stringify({ t: 'req', id: 'x', method: 'turn', params: {} }));
|
|
100
|
+
assert.match(await until(r2, 'failed'), /before auth/);
|
|
101
|
+
void dx;
|
|
102
|
+
});
|