@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.
Files changed (41) hide show
  1. package/README.md +14 -6
  2. package/dist/auth-handler.d.ts +41 -20
  3. package/dist/auth-handler.js +136 -106
  4. package/dist/channel-binding.d.ts +57 -0
  5. package/dist/channel-binding.js +73 -0
  6. package/dist/config-store.d.ts +14 -6
  7. package/dist/config-store.js +58 -11
  8. package/dist/devices-cli.d.ts +16 -0
  9. package/dist/devices-cli.js +90 -0
  10. package/dist/index.js +76 -16
  11. package/dist/plugin-config.d.ts +12 -0
  12. package/dist/session-token.d.ts +6 -39
  13. package/dist/session-token.js +6 -95
  14. package/dist/shim.js +13 -10
  15. package/dist/totp.d.ts +8 -0
  16. package/dist/totp.js +16 -0
  17. package/dist/webrtc-peer.d.ts +2 -0
  18. package/dist/webrtc-peer.js +15 -1
  19. package/package.json +1 -1
  20. package/server/approval-client.test.js +1 -1
  21. package/server/controllers/title.js +3 -1
  22. package/server/controllers/title.test.js +8 -1
  23. package/server/gateway.js +21 -3
  24. package/server/gateway.test.js +44 -0
  25. package/server/history-export.js +5 -1
  26. package/server/history-export.test.js +63 -0
  27. package/server/index.js +4 -1
  28. package/server/peer/guest-agent.js +41 -8
  29. package/server/peer/guest-agent.test.js +50 -1
  30. package/server/peer/keys.js +12 -0
  31. package/server/peer/sharing.js +17 -3
  32. package/server/peer/sharing.test.js +42 -4
  33. package/server/peer/wordlist.js +3 -0
  34. package/server/team.js +15 -6
  35. package/server/team.test.js +48 -4
  36. package/server/util/gateway-retry.js +58 -0
  37. package/server/util/gateway-retry.test.js +78 -0
  38. package/server/util/redact.js +84 -0
  39. package/server/util/redact.test.js +97 -0
  40. package/dist/google-jwt.d.ts +0 -34
  41. package/dist/google-jwt.js +0 -87
@@ -6,7 +6,7 @@
6
6
  * of the file (a consumed backup code, a new TOTP secret) re-read it from disk and change only
7
7
  * that part, so nobody writes back a stale copy (e.g. undoing a `reauth`).
8
8
  */
9
- import type { PluginConfig } from './plugin-config.js';
9
+ import type { PluginConfig, PairedDevice } from './plugin-config.js';
10
10
  import type { AuthConfig } from './auth-handler.js';
11
11
  /**
12
12
  * Write a file so readers see either the old or the new content, never a partial one.
@@ -36,11 +36,19 @@ export type AuthConfigResult = {
36
36
  };
37
37
  /**
38
38
  * The browser login settings, freshly read from disk. Only a complete schemaVersion 2 config
39
- * with TOTP and a session secret allows logins; anything else refuses every browser.
39
+ * with TOTP and a session secret allows logins (the session secret is no longer used to log in; it stays so a rollback finds a valid config); anything else refuses every browser.
40
40
  */
41
- export declare function readAuthConfig(file: string, devMode?: boolean): AuthConfigResult;
41
+ export declare function readAuthConfig(file: string): AuthConfigResult;
42
+ /** The most browsers one connector pairs with. */
43
+ export declare const MAX_DEVICES = 20;
42
44
  /**
43
- * Identifies the login secrets a browser authenticated under. It changes on `reauth` (new TOTP
44
- * secret and session secret) and authenticated connections from before are then closed.
45
+ * Pair a device (or refresh the label of one that is already paired): re-reads the config, so
46
+ * nothing else in it is overwritten. 'full' = MAX_DEVICES others are already paired; 'gone' = no
47
+ * config; 'stale' = the TOTP secret is no longer the one the pairing code was checked against
48
+ * (a `reauth` ran in between).
45
49
  */
46
- export declare function authEpoch(config: AuthConfig): string;
50
+ export declare function addDevice(file: string, device: PairedDevice, totpSecret: string): 'ok' | 'full' | 'gone' | 'stale';
51
+ /** Remove the devices `match` selects; returns them. Re-reads the config first. */
52
+ export declare function removeDevices(file: string, match: (d: PairedDevice) => boolean): PairedDevice[];
53
+ /** Record that a device logged in (rewrites only that device's lastSeen). */
54
+ export declare function touchDevice(file: string, deviceId: string, at?: string): void;
@@ -9,6 +9,7 @@
9
9
  import * as crypto from 'node:crypto';
10
10
  import * as fs from 'node:fs';
11
11
  import * as path from 'node:path';
12
+ import { deviceIdOf, isEd25519Spki } from './channel-binding.js';
12
13
  /**
13
14
  * Write a file so readers see either the old or the new content, never a partial one.
14
15
  * `beforeRename` returning false abandons the write (returns false).
@@ -113,9 +114,9 @@ export function removeBackupCode(file, hash) {
113
114
  const isStr = (v) => typeof v === 'string' && v.length > 0;
114
115
  /**
115
116
  * The browser login settings, freshly read from disk. Only a complete schemaVersion 2 config
116
- * with TOTP and a session secret allows logins; anything else refuses every browser.
117
+ * with TOTP and a session secret allows logins (the session secret is no longer used to log in; it stays so a rollback finds a valid config); anything else refuses every browser.
117
118
  */
118
- export function readAuthConfig(file, devMode = false) {
119
+ export function readAuthConfig(file) {
119
120
  const cfg = readConfig(file);
120
121
  if (!cfg)
121
122
  return { ok: false, reason: fs.existsSync(file) ? 'invalid' : 'missing' };
@@ -129,7 +130,8 @@ export function readAuthConfig(file, devMode = false) {
129
130
  || !isStr(cfg.sessionSecret) || !/^[0-9a-f]{64}$/i.test(cfg.sessionSecret)
130
131
  || (cfg.backupCodeHashes !== undefined && (!Array.isArray(cfg.backupCodeHashes) || !cfg.backupCodeHashes.every(isStr)))
131
132
  || (g !== undefined && (!g || typeof g !== 'object' || typeof g.clientId !== 'string'
132
- || typeof g.authorizedSub !== 'string' || typeof g.authorizedEmail !== 'string'))) {
133
+ || typeof g.authorizedSub !== 'string' || typeof g.authorizedEmail !== 'string'))
134
+ || (cfg.devices !== undefined && !Array.isArray(cfg.devices))) {
133
135
  return { ok: false, reason: 'invalid' };
134
136
  }
135
137
  return {
@@ -137,18 +139,63 @@ export function readAuthConfig(file, devMode = false) {
137
139
  config: {
138
140
  userId: cfg.userId,
139
141
  totp: t,
140
- // No Google identity bound (dev installs): placeholder, Google check skipped
141
- google: g ?? { clientId: 'dev-placeholder', authorizedSub: 'dev-placeholder', authorizedEmail: 'dev@localhost' },
142
- sessionSecret: cfg.sessionSecret,
143
142
  backupCodeHashes: cfg.backupCodeHashes,
144
- devMode,
143
+ // A malformed entry is a device that cannot log in, not a reason to refuse everyone
144
+ devices: (cfg.devices ?? []).filter(isDevice),
145
145
  },
146
146
  };
147
147
  }
148
+ const isDevice = (d) => {
149
+ const x = d;
150
+ return !!x && typeof x === 'object' && isStr(x.deviceId) && isEd25519Spki(x.pubkey) && x.deviceId === deviceIdOf(x.pubkey)
151
+ && typeof x.label === 'string' && typeof x.createdAt === 'string' && typeof x.lastSeen === 'string';
152
+ };
153
+ /** The most browsers one connector pairs with. */
154
+ export const MAX_DEVICES = 20;
148
155
  /**
149
- * Identifies the login secrets a browser authenticated under. It changes on `reauth` (new TOTP
150
- * secret and session secret) and authenticated connections from before are then closed.
156
+ * Pair a device (or refresh the label of one that is already paired): re-reads the config, so
157
+ * nothing else in it is overwritten. 'full' = MAX_DEVICES others are already paired; 'gone' = no
158
+ * config; 'stale' = the TOTP secret is no longer the one the pairing code was checked against
159
+ * (a `reauth` ran in between).
151
160
  */
152
- export function authEpoch(config) {
153
- return crypto.createHash('sha256').update(`${config.sessionSecret}\n${config.totp.secret}`).digest('hex').slice(0, 32);
161
+ export function addDevice(file, device, totpSecret) {
162
+ let result = 'ok';
163
+ const saved = updateConfig(file, (cfg) => {
164
+ if (cfg.totp?.secret !== totpSecret) {
165
+ result = 'stale';
166
+ return false;
167
+ }
168
+ const all = Array.isArray(cfg.devices) ? cfg.devices : [];
169
+ const before = all.find(d => d.deviceId === device.deviceId);
170
+ const list = all.filter(d => d.deviceId !== device.deviceId);
171
+ if (list.length >= MAX_DEVICES) {
172
+ result = 'full';
173
+ return false;
174
+ }
175
+ result = 'ok';
176
+ list.push(before ? { ...device, createdAt: before.createdAt } : device);
177
+ cfg.devices = list;
178
+ });
179
+ return saved ? result : 'gone';
180
+ }
181
+ /** Remove the devices `match` selects; returns them. Re-reads the config first. */
182
+ export function removeDevices(file, match) {
183
+ let removed = [];
184
+ updateConfig(file, (cfg) => {
185
+ const list = Array.isArray(cfg.devices) ? cfg.devices : [];
186
+ removed = list.filter(match);
187
+ if (!removed.length)
188
+ return false;
189
+ cfg.devices = list.filter(d => !match(d));
190
+ });
191
+ return removed;
192
+ }
193
+ /** Record that a device logged in (rewrites only that device's lastSeen). */
194
+ export function touchDevice(file, deviceId, at = new Date().toISOString()) {
195
+ updateConfig(file, (cfg) => {
196
+ const d = (Array.isArray(cfg.devices) ? cfg.devices : []).find(x => x.deviceId === deviceId);
197
+ if (!d)
198
+ return false;
199
+ d.lastSeen = at;
200
+ });
154
201
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * devices-cli.ts — `openclaw clawchats devices [revoke <id|label>]` and `show-fingerprint`
3
+ *
4
+ * Plain functions over the config file and an output function, so tests can run them. The
5
+ * running service sees a revoked device in config.json within a second and closes its channels
6
+ * (auth-handler.ts revokeStaleChannels).
7
+ */
8
+ import type { PairedDevice } from './plugin-config.js';
9
+ type Out = (line: string) => void;
10
+ /** Devices that `query` names: a full device id, an id prefix of 6+ characters, or a label (case-insensitive). */
11
+ export declare function matchDevices(devices: PairedDevice[], query: string): PairedDevice[];
12
+ export declare function listDevices(configFile: string, out: Out): boolean;
13
+ /** Unpair the device `query` names. False (nothing changed) when it names none, or more than one. */
14
+ export declare function revokeDevice(configFile: string, query: string, out: Out): boolean;
15
+ export declare function showFingerprint(publicKey: string | null, out: Out): boolean;
16
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * devices-cli.ts — `openclaw clawchats devices [revoke <id|label>]` and `show-fingerprint`
3
+ *
4
+ * Plain functions over the config file and an output function, so tests can run them. The
5
+ * running service sees a revoked device in config.json within a second and closes its channels
6
+ * (auth-handler.ts revokeStaleChannels).
7
+ */
8
+ import { readConfig, removeDevices } from './config-store.js';
9
+ import { publicKeyFingerprint, publicKeyWords } from './channel-binding.js';
10
+ const short = (id) => id.slice(0, 8);
11
+ const day = (iso) => iso.replace('T', ' ').slice(0, 16);
12
+ /** Devices that `query` names: a full device id, an id prefix of 6+ characters, or a label (case-insensitive). */
13
+ export function matchDevices(devices, query) {
14
+ const q = query.trim();
15
+ if (!q)
16
+ return [];
17
+ const exactId = devices.filter(d => d.deviceId === q);
18
+ if (exactId.length)
19
+ return exactId;
20
+ if (q.length >= 6) {
21
+ const byPrefix = devices.filter(d => d.deviceId.startsWith(q.toLowerCase()));
22
+ if (byPrefix.length)
23
+ return byPrefix;
24
+ }
25
+ return devices.filter(d => d.label.toLowerCase() === q.toLowerCase());
26
+ }
27
+ export function listDevices(configFile, out) {
28
+ const cfg = readConfig(configFile);
29
+ if (!cfg) {
30
+ out('ClawChats is not configured. Run: openclaw clawchats setup <token>');
31
+ return false;
32
+ }
33
+ const devices = Array.isArray(cfg.devices) ? cfg.devices : [];
34
+ if (!devices.length) {
35
+ out('No browsers are paired. Open ClawChats in a browser and enter a code from your authenticator app to pair it.');
36
+ return true;
37
+ }
38
+ out(`Paired browsers (${devices.length}):`);
39
+ out('');
40
+ for (const d of devices) {
41
+ out(` ${short(d.deviceId)} ${d.label}`);
42
+ out(` paired ${day(d.createdAt)}, last login ${day(d.lastSeen)}`);
43
+ }
44
+ out('');
45
+ out('Remove one with: openclaw clawchats devices revoke <id|label>');
46
+ return true;
47
+ }
48
+ /** Unpair the device `query` names. False (nothing changed) when it names none, or more than one. */
49
+ export function revokeDevice(configFile, query, out) {
50
+ const cfg = readConfig(configFile);
51
+ if (!cfg) {
52
+ out('ClawChats is not configured. Run: openclaw clawchats setup <token>');
53
+ return false;
54
+ }
55
+ const devices = Array.isArray(cfg.devices) ? cfg.devices : [];
56
+ const hits = matchDevices(devices, query);
57
+ if (!hits.length) {
58
+ out(`No paired browser matches "${query}". List them with: openclaw clawchats devices`);
59
+ return false;
60
+ }
61
+ if (hits.length > 1) {
62
+ out(`"${query}" matches ${hits.length} browsers. Use the id instead:`);
63
+ for (const d of hits)
64
+ out(` ${short(d.deviceId)} ${d.label}`);
65
+ return false;
66
+ }
67
+ const ids = new Set(hits.map(d => d.deviceId));
68
+ const removed = removeDevices(configFile, d => ids.has(d.deviceId));
69
+ if (!removed.length) {
70
+ out('That browser was already removed.');
71
+ return false;
72
+ }
73
+ out(`Revoked "${removed[0].label}" (${short(removed[0].deviceId)}). It is signed out now and must pair again with a code.`);
74
+ return true;
75
+ }
76
+ export function showFingerprint(publicKey, out) {
77
+ if (!publicKey) {
78
+ out('This connector has no key yet. It is created when the gateway starts the ClawChats service for the first time.');
79
+ return false;
80
+ }
81
+ out('Your gateway\'s key, as four words:');
82
+ out('');
83
+ out(` ${publicKeyWords(publicKey)}`);
84
+ out('');
85
+ out(`(the same key as digits: ${publicKeyFingerprint(publicKey)})`);
86
+ out('');
87
+ out('ClawChats shows the same words when you pair a browser (and in Settings). If they differ,');
88
+ out('do not pair: something between your browser and this machine is answering instead of it.');
89
+ return true;
90
+ }
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Spec: specs/multitenant-p2p.md sections 6.1-6.2
11
11
  */
12
+ import * as crypto from 'node:crypto';
12
13
  import * as fs from 'node:fs';
13
14
  import * as http from 'node:http';
14
15
  import * as os from 'node:os';
@@ -17,7 +18,8 @@ import { createRequire } from 'node:module';
17
18
  import { SignalingClient } from './signaling-client.js';
18
19
  import { dispatchRpc } from './shim.js';
19
20
  import { attachBrowserChannel, revokeStaleChannels, loadAuthState } from './auth-handler.js';
20
- import { readConfig, writeConfig, updateConfig, readAuthConfig, removeBackupCode, writeFileAtomic } from './config-store.js';
21
+ import { readConfig, writeConfig, updateConfig, readAuthConfig, removeBackupCode, writeFileAtomic, addDevice, touchDevice } from './config-store.js';
22
+ import { listDevices, revokeDevice, showFingerprint } from './devices-cli.js';
21
23
  import { ChunkReassembler } from './chunk-reassembly.js';
22
24
  import { generateTotpSecret, verifyTotp, generateBackupCodes, buildOtpauthUri } from './totp.js';
23
25
  import { generateSessionSecret } from './session-token.js';
@@ -216,7 +218,7 @@ async function ensureNativeModules(ctx) {
216
218
  const ndcRoot = resolvePackageRoot(require, 'node-datachannel');
217
219
  if (!ndcRoot) {
218
220
  throw new Error(`the WebRTC library (node-datachannel) is missing from this install. ` +
219
- `Reinstall the plugin: openclaw plugins install @clawchatsai/connector --force`);
221
+ `Reinstall the plugin: openclaw plugins install npm:@clawchatsai/connector --force`);
220
222
  }
221
223
  const targetPath = path.join(ndcRoot, 'build', 'Release', 'node_datachannel.node');
222
224
  // Already built — nothing to do.
@@ -424,9 +426,9 @@ async function runClawChats(ctx, api) {
424
426
  webrtcPeer = new WebRTCPeerManager();
425
427
  loadAuthState(AUTH_STATE_FILE);
426
428
  watchConfigForRevocation(ctx);
427
- webrtcPeer.on('datachannel', (dc, connectionId) => {
429
+ webrtcPeer.on('datachannel', (dc, connectionId, dtls) => {
428
430
  ctx.logger.info(`Browser connected via DataChannel: ${connectionId}`);
429
- setupDataChannelHandler(dc, connectionId, ctx);
431
+ setupDataChannelHandler(dc, connectionId, ctx, dtls);
430
432
  signaling?.reportConnectionCount(webrtcPeer?.activeCount ?? 0);
431
433
  });
432
434
  // A Desktop view's tunnel to the gateway's desktop stream: only on an authenticated browser
@@ -603,7 +605,7 @@ function teardownRuntime() {
603
605
  // Track which ClawChats thread sessions have received the capability note (once per session).
604
606
  // DataChannel message handler (spec section 6.4)
605
607
  // ---------------------------------------------------------------------------
606
- function setupDataChannelHandler(dc, connectionId, ctx) {
608
+ function setupDataChannelHandler(dc, connectionId, ctx, dtls) {
607
609
  dc.onClosed(() => {
608
610
  connectedClients.delete(connectionId);
609
611
  rpcReqChunks.dropConnection(connectionId);
@@ -611,19 +613,41 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
611
613
  app?.debugLogger.handleClientDisconnect(dc);
612
614
  });
613
615
  // Login gate (auth-handler.ts): refuses and closes the channel unless config.json is complete
614
- // with TOTP set up, and hands messages on only after the browser logged in.
616
+ // with TOTP set up, and hands messages on only after the browser logged in with a paired
617
+ // device key (or paired with a code). The connector proves itself first, with the key it uses
618
+ // for gateway sharing.
619
+ if (!app?.peerKey) { // the key is created with the app; without it nobody can be told who we are
620
+ ctx.logger.error(`Browser ${connectionId} refused: no connector key`);
621
+ dc.close();
622
+ return;
623
+ }
615
624
  attachBrowserChannel(dc, connectionId, {
616
- loadAuthConfig: () => readAuthConfig(CONFIG_FILE, process.env.CLAWCHATS_DEV === 'true'),
625
+ loadAuthConfig: () => readAuthConfig(CONFIG_FILE),
626
+ connectorKey: app.peerKey,
627
+ addDevice: (device, totpSecret) => addDevice(CONFIG_FILE, device, totpSecret),
628
+ touchDevice: (deviceId) => {
629
+ try {
630
+ touchDevice(CONFIG_FILE, deviceId);
631
+ }
632
+ catch (e) {
633
+ ctx.logger.warn(`Could not save last-seen for device ${deviceId}: ${e.message}`);
634
+ }
635
+ },
617
636
  consumeBackupCode: (hash) => {
618
637
  const consumed = removeBackupCode(CONFIG_FILE, hash);
619
638
  if (consumed)
620
639
  ctx.logger.warn(`Browser ${connectionId} logged in with a backup code`);
621
640
  return consumed;
622
641
  },
623
- onAuthenticated: () => {
642
+ onAuthenticated: ({ deviceId, label, paired }) => {
624
643
  // Auth succeeded — add to broadcast clients and inform gateway
644
+ if (paired) {
645
+ // Tell the browsers that are already in: a device they did not pair would show up here
646
+ ctx.logger.warn(`New device paired: "${label}" (${deviceId}) on ${connectionId}`);
647
+ broadcastToClients({ type: 'device-paired', deviceId, label, at: new Date().toISOString() });
648
+ }
625
649
  connectedClients.set(connectionId, dc);
626
- ctx.logger.info(`Browser authenticated: ${connectionId}`);
650
+ ctx.logger.info(`Browser authenticated: ${connectionId} (${label})`);
627
651
  },
628
652
  onMessage: (msg) => processAuthenticatedMessage(dc, connectionId, msg, ctx),
629
653
  onLoginFailure: (reason) => {
@@ -631,10 +655,10 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
631
655
  broadcastToClients({ type: 'auth-attempt-failed', reason, at: new Date().toISOString() });
632
656
  },
633
657
  log: ctx.logger,
634
- });
658
+ }, dtls);
635
659
  }
636
660
  /**
637
- * Browsers that logged in under secrets the config no longer has (`reauth`, `reset`, a deleted
661
+ * Browsers whose device the config no longer has (`devices revoke`, `reauth`, `reset`, a deleted
638
662
  * config) are signed out. Polls the file's stat, so atomic renames and deletion are both seen.
639
663
  */
640
664
  let configWatcher = null;
@@ -644,10 +668,10 @@ function watchConfigForRevocation(ctx) {
644
668
  configWatcher = () => {
645
669
  for (const id of revokeStaleChannels(readAuthConfig(CONFIG_FILE))) {
646
670
  connectedClients.delete(id);
647
- ctx.logger.warn(`Browser ${id} signed out: ClawChats login settings changed (reauth/reset)`);
671
+ ctx.logger.warn(`Browser ${id} signed out: its device was revoked or the ClawChats login settings changed (devices revoke/reauth/reset)`);
648
672
  }
649
673
  };
650
- fs.watchFile(CONFIG_FILE, { interval: 2000, persistent: false }, configWatcher);
674
+ fs.watchFile(CONFIG_FILE, { interval: 1000, persistent: false }, configWatcher);
651
675
  }
652
676
  /**
653
677
  * Process a message on an authenticated DataChannel.
@@ -1061,6 +1085,7 @@ async function enrollTotp(config) {
1061
1085
  enabledAt: new Date().toISOString(),
1062
1086
  };
1063
1087
  c.sessionSecret = sessionSecret;
1088
+ c.devices = []; // new secrets: every browser pairs again
1064
1089
  c.backupCodeHashes = hashes;
1065
1090
  c.schemaVersion = 2;
1066
1091
  delete c.totpPending;
@@ -1133,6 +1158,34 @@ async function handleShowTotp() {
1133
1158
  console.log(' 3. When prompted for a TOTP secret, paste the value above');
1134
1159
  console.log('');
1135
1160
  }
1161
+ /** `openclaw clawchats devices [revoke <id|label>]` */
1162
+ async function handleDevices(action, target) {
1163
+ const out = (line) => console.log(line);
1164
+ if (action === undefined) {
1165
+ listDevices(CONFIG_FILE, out);
1166
+ return;
1167
+ }
1168
+ if (action !== 'revoke' || !target) {
1169
+ console.error('Usage: openclaw clawchats devices (list paired browsers)');
1170
+ console.error(' openclaw clawchats devices revoke <id|label>');
1171
+ process.exitCode = 1;
1172
+ return;
1173
+ }
1174
+ if (!revokeDevice(CONFIG_FILE, target, out))
1175
+ process.exitCode = 1;
1176
+ }
1177
+ /** `openclaw clawchats show-fingerprint`: read from peer-key.json, never creating it. */
1178
+ async function handleShowFingerprint() {
1179
+ let publicKey = null;
1180
+ try {
1181
+ const saved = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, 'data', 'peer-key.json'), 'utf8'));
1182
+ publicKey = crypto.createPublicKey(crypto.createPrivateKey({ key: Buffer.from(saved.privateKey, 'base64'), format: 'der', type: 'pkcs8' }))
1183
+ .export({ format: 'der', type: 'spki' }).toString('base64');
1184
+ }
1185
+ catch { /* no key yet */ }
1186
+ if (!showFingerprint(publicKey, (line) => console.log(line)))
1187
+ process.exitCode = 1;
1188
+ }
1136
1189
  // ---------------------------------------------------------------------------
1137
1190
  // Agent-driven TOTP setup (setup-totp + verify-totp)
1138
1191
  // ---------------------------------------------------------------------------
@@ -1212,6 +1265,7 @@ async function handleVerifyTotp(code) {
1212
1265
  enabledAt: new Date().toISOString(),
1213
1266
  };
1214
1267
  c.sessionSecret = sessionSecret;
1268
+ c.devices = []; // new secrets: every browser pairs again
1215
1269
  c.backupCodeHashes = hashes;
1216
1270
  c.schemaVersion = 2;
1217
1271
  delete c.totpPending;
@@ -1246,12 +1300,12 @@ async function handleReauth() {
1246
1300
  }
1247
1301
  console.log('🔐 Re-initializing ClawChats authentication...');
1248
1302
  console.log('');
1249
- console.log(' ⚠️ This will invalidate all existing sessions.');
1250
- console.log(' All connected browsers will need to re-authenticate.');
1303
+ console.log(' ⚠️ This will unpair every browser.');
1304
+ console.log(' All connected browsers will need to pair again with a code.');
1251
1305
  console.log('');
1252
1306
  const success = await enrollTotp(config);
1253
1307
  if (success) {
1254
- console.log(' All previous sessions have been invalidated.');
1308
+ console.log(' All paired browsers have been removed.');
1255
1309
  console.log(' Restart the gateway for changes to take effect: systemctl --user restart openclaw-gateway');
1256
1310
  }
1257
1311
  }
@@ -1465,6 +1519,12 @@ const plugin = {
1465
1519
  cmd.command('show-totp')
1466
1520
  .description('Show your TOTP secret (use when adding ClawChats to a second gateway)')
1467
1521
  .action(() => handleShowTotp());
1522
+ cmd.command('devices [action] [target]')
1523
+ .description('List the browsers paired with this gateway; "devices revoke <id|label>" signs one out and unpairs it')
1524
+ .action((action, target) => handleDevices(action === undefined ? undefined : String(action), target === undefined ? undefined : String(target)));
1525
+ cmd.command('show-fingerprint')
1526
+ .description("Show this connector's key fingerprint, to compare with the one ClawChats shows when you pair a browser")
1527
+ .action(() => handleShowFingerprint());
1468
1528
  cmd.command('reset')
1469
1529
  .description('Disconnect and remove all ClawChats data')
1470
1530
  .action(() => handleReset());
@@ -1,3 +1,13 @@
1
+ /** A browser that may log in by signing a challenge with its device key. */
2
+ export interface PairedDevice {
3
+ /** First 16 bytes of SHA-256 over the public key, hex (channel-binding.ts deviceIdOf). */
4
+ deviceId: string;
5
+ /** Ed25519 public key, SPKI, base64. */
6
+ pubkey: string;
7
+ label: string;
8
+ createdAt: string;
9
+ lastSeen: string;
10
+ }
1
11
  /** Persisted ClawChats plugin config (~/.ocplatform/clawchats/config.json). */
2
12
  export interface PluginConfig {
3
13
  userId: string;
@@ -22,6 +32,8 @@ export interface PluginConfig {
22
32
  };
23
33
  sessionSecret?: string;
24
34
  backupCodeHashes?: string[];
35
+ /** Browsers paired with this connector (src/auth-handler.ts). `reauth` and `reset` clear them. */
36
+ devices?: PairedDevice[];
25
37
  totpPending?: {
26
38
  secret: string;
27
39
  generatedAt: string;
@@ -1,43 +1,10 @@
1
1
  /**
2
- * session-token.ts — Plugin-local session JWT management
2
+ * session-token.ts — the config's session secret
3
3
  *
4
- * Issues and verifies HS256 JWTs that let returning users skip TOTP.
5
- * Signing key is stored in config.json — regenerating it invalidates
6
- * all previously issued tokens.
7
- *
8
- * Spec: datachannel-auth-totp.md §6
9
- */
10
- interface SessionPayload {
11
- sub: string;
12
- googleSub: string;
13
- iat: number;
14
- exp: number;
15
- jti: string;
16
- }
17
- /**
18
- * Issue a session token.
19
- *
20
- * @param userId The ClawChats user ID
21
- * @param googleSub The Google account sub
22
- * @param sessionDays Duration in days (1-30, clamped)
23
- * @param secret The 256-bit hex signing key from config
24
- * @returns The signed JWT string
25
- */
26
- export declare function issueSessionToken(userId: string, googleSub: string, sessionDays: number, secret: string): string;
27
- /**
28
- * Verify a session token.
29
- *
30
- * @param token The JWT string from the browser
31
- * @param secret The 256-bit hex signing key from config
32
- * @param userId Expected userId
33
- * @param googleSub Expected Google sub
34
- * @returns The decoded payload if valid
35
- * @throws Error with descriptive message on failure
36
- */
37
- export declare function verifySessionToken(token: string, secret: string, userId: string, googleSub: string): SessionPayload;
38
- /**
39
- * Generate a new 256-bit session secret (hex-encoded).
40
- * Call this during initial setup and on `reauth` to invalidate all sessions.
4
+ * Browsers no longer log in with session tokens (src/auth-handler.ts: device keys), so nothing
5
+ * issues or verifies them. `sessionSecret` stays in config.json, regenerated by setup and
6
+ * `reauth`, because readAuthConfig() still requires it: an older connector rolled back onto the
7
+ * same config would otherwise find it invalid.
41
8
  */
9
+ /** Generate a new 256-bit session secret (hex-encoded). */
42
10
  export declare function generateSessionSecret(): string;
43
- export {};
@@ -1,102 +1,13 @@
1
1
  /**
2
- * session-token.ts — Plugin-local session JWT management
2
+ * session-token.ts — the config's session secret
3
3
  *
4
- * Issues and verifies HS256 JWTs that let returning users skip TOTP.
5
- * Signing key is stored in config.json — regenerating it invalidates
6
- * all previously issued tokens.
7
- *
8
- * Spec: datachannel-auth-totp.md §6
4
+ * Browsers no longer log in with session tokens (src/auth-handler.ts: device keys), so nothing
5
+ * issues or verifies them. `sessionSecret` stays in config.json, regenerated by setup and
6
+ * `reauth`, because readAuthConfig() still requires it: an older connector rolled back onto the
7
+ * same config would otherwise find it invalid.
9
8
  */
10
9
  import * as crypto from 'node:crypto';
11
- // ---------------------------------------------------------------------------
12
- // HS256 JWT implementation (minimal, no dependencies)
13
- // ---------------------------------------------------------------------------
14
- function base64urlEncode(data) {
15
- const buf = typeof data === 'string' ? Buffer.from(data) : data;
16
- return buf.toString('base64url');
17
- }
18
- function base64urlDecode(str) {
19
- return Buffer.from(str, 'base64url');
20
- }
21
- /**
22
- * Issue a session token.
23
- *
24
- * @param userId The ClawChats user ID
25
- * @param googleSub The Google account sub
26
- * @param sessionDays Duration in days (1-30, clamped)
27
- * @param secret The 256-bit hex signing key from config
28
- * @returns The signed JWT string
29
- */
30
- export function issueSessionToken(userId, googleSub, sessionDays, secret) {
31
- const days = Math.min(Math.max(Math.round(sessionDays), 1), 30);
32
- const now = Math.floor(Date.now() / 1000);
33
- const header = { alg: 'HS256', typ: 'JWT' };
34
- const payload = {
35
- sub: userId,
36
- googleSub,
37
- iat: now,
38
- exp: now + days * 86400,
39
- jti: crypto.randomUUID(),
40
- };
41
- const headerB64 = base64urlEncode(JSON.stringify(header));
42
- const payloadB64 = base64urlEncode(JSON.stringify(payload));
43
- const signingInput = `${headerB64}.${payloadB64}`;
44
- const hmac = crypto.createHmac('sha256', Buffer.from(secret, 'hex'));
45
- hmac.update(signingInput);
46
- const signature = hmac.digest().toString('base64url');
47
- return `${signingInput}.${signature}`;
48
- }
49
- /**
50
- * Verify a session token.
51
- *
52
- * @param token The JWT string from the browser
53
- * @param secret The 256-bit hex signing key from config
54
- * @param userId Expected userId
55
- * @param googleSub Expected Google sub
56
- * @returns The decoded payload if valid
57
- * @throws Error with descriptive message on failure
58
- */
59
- export function verifySessionToken(token, secret, userId, googleSub) {
60
- const parts = token.split('.');
61
- if (parts.length !== 3)
62
- throw new Error('malformed_token');
63
- const [headerB64, payloadB64, signatureB64] = parts;
64
- // Verify signature
65
- const signingInput = `${headerB64}.${payloadB64}`;
66
- const hmac = crypto.createHmac('sha256', Buffer.from(secret, 'hex'));
67
- hmac.update(signingInput);
68
- const expectedSig = hmac.digest();
69
- const actualSig = base64urlDecode(signatureB64);
70
- if (expectedSig.length !== actualSig.length ||
71
- !crypto.timingSafeEqual(expectedSig, actualSig)) {
72
- throw new Error('invalid_signature');
73
- }
74
- // Decode payload
75
- let payload;
76
- try {
77
- payload = JSON.parse(base64urlDecode(payloadB64).toString('utf8'));
78
- }
79
- catch {
80
- throw new Error('malformed_payload');
81
- }
82
- // Check expiry
83
- const now = Math.floor(Date.now() / 1000);
84
- if (payload.exp <= now)
85
- throw new Error('expired_session');
86
- // Check not issued in the future (clock skew tolerance: 60s)
87
- if (payload.iat > now + 60)
88
- throw new Error('invalid_iat');
89
- // Check identity
90
- if (payload.sub !== userId)
91
- throw new Error('invalid_user');
92
- if (payload.googleSub !== googleSub)
93
- throw new Error('invalid_google_sub');
94
- return payload;
95
- }
96
- /**
97
- * Generate a new 256-bit session secret (hex-encoded).
98
- * Call this during initial setup and on `reauth` to invalidate all sessions.
99
- */
10
+ /** Generate a new 256-bit session secret (hex-encoded). */
100
11
  export function generateSessionSecret() {
101
12
  return crypto.randomBytes(32).toString('hex');
102
13
  }
package/dist/shim.js CHANGED
@@ -45,20 +45,23 @@ class FakeReq extends Readable {
45
45
  this.push(parsed['data']);
46
46
  }
47
47
  else if (parsed && parsed['_multipart']) {
48
- // Multipart form data: { _multipart: true, fields: { key: string | { filename, contentType, data } } }
48
+ // Multipart form data: { _multipart: true, fields: { key: Entry | Entry[] } } where
49
+ // Entry = string | { filename, contentType, data }. An array is a repeated key (many files).
49
50
  const boundary = '----ClawChatsBoundary' + Date.now();
50
51
  this.headers['content-type'] = `multipart/form-data; boundary=${boundary}`;
51
52
  const fields = parsed['fields'] || {};
52
53
  const parts = [];
53
- for (const [key, value] of Object.entries(fields)) {
54
- if (value && typeof value === 'object' && value['filename']) {
55
- const f = value;
56
- parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${key}"; filename="${f.filename}"\r\nContent-Type: ${f.contentType}\r\n\r\n`));
57
- parts.push(Buffer.from(f.data, 'base64'));
58
- parts.push(Buffer.from('\r\n'));
59
- }
60
- else {
61
- parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${String(value)}\r\n`));
54
+ for (const [key, raw] of Object.entries(fields)) {
55
+ for (const value of Array.isArray(raw) ? raw : [raw]) {
56
+ if (value && typeof value === 'object' && value['filename']) {
57
+ const f = value;
58
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${key}"; filename="${f.filename}"\r\nContent-Type: ${f.contentType}\r\n\r\n`));
59
+ parts.push(Buffer.from(f.data, 'base64'));
60
+ parts.push(Buffer.from('\r\n'));
61
+ }
62
+ else {
63
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${String(value)}\r\n`));
64
+ }
62
65
  }
63
66
  }
64
67
  parts.push(Buffer.from(`--${boundary}--\r\n`));