@clawchatsai/connector 0.1.48 → 0.1.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-handler.d.ts +47 -29
- package/dist/auth-handler.js +306 -245
- package/dist/chunk-reassembly.d.ts +38 -0
- package/dist/chunk-reassembly.js +88 -0
- package/dist/config-store.d.ts +46 -0
- package/dist/config-store.js +154 -0
- package/dist/index.js +168 -213
- package/dist/totp.js +3 -1
- package/dist/webrtc-peer.js +11 -2
- package/package.json +3 -2
- package/server/controllers/static.js +19 -3
- package/server/controllers/static.test.js +48 -0
- package/server/debug.js +3 -1
- package/server/debug.test.js +23 -1
- package/server/index.js +6 -0
- package/server/peer/link.js +5 -1
- package/server/peer/link.test.js +10 -0
- package/server/peer/sharing.js +172 -34
- package/server/peer/sharing.test.js +153 -0
- package/server/team.js +116 -32
- package/server/team.test.js +131 -4
package/dist/index.js
CHANGED
|
@@ -16,7 +16,9 @@ import * as path from 'node:path';
|
|
|
16
16
|
import { createRequire } from 'node:module';
|
|
17
17
|
import { SignalingClient } from './signaling-client.js';
|
|
18
18
|
import { dispatchRpc } from './shim.js';
|
|
19
|
-
import {
|
|
19
|
+
import { attachBrowserChannel, revokeStaleChannels, loadAuthState } from './auth-handler.js';
|
|
20
|
+
import { readConfig, writeConfig, updateConfig, readAuthConfig, removeBackupCode, writeFileAtomic } from './config-store.js';
|
|
21
|
+
import { ChunkReassembler } from './chunk-reassembly.js';
|
|
20
22
|
import { generateTotpSecret, verifyTotp, generateBackupCodes, buildOtpauthUri } from './totp.js';
|
|
21
23
|
import { generateSessionSecret } from './session-token.js';
|
|
22
24
|
import { fileURLToPath } from 'node:url';
|
|
@@ -80,10 +82,9 @@ let GATEWAY_WS_URL = resolveGatewayWsUrl();
|
|
|
80
82
|
/** Open Desktop tunnels per browser connection (server/desktop-tunnel.js); a viewer uses one or two. */
|
|
81
83
|
const desktopTunnels = new Map();
|
|
82
84
|
const MAX_TUNNELS_PER_CONNECTION = 8;
|
|
83
|
-
/** Reassembly
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
const gatewayMsgChunkBuffers = new Map();
|
|
85
|
+
/** Reassembly of chunked RPC requests (large uploads) and gateway-msg (e.g. image attachments) from browsers. */
|
|
86
|
+
const rpcReqChunks = new ChunkReassembler();
|
|
87
|
+
const gatewayMsgChunks = new ChunkReassembler();
|
|
87
88
|
let app = null;
|
|
88
89
|
let signaling = null;
|
|
89
90
|
let webrtcPeer = null;
|
|
@@ -135,22 +136,16 @@ function gatewayConfigPath() {
|
|
|
135
136
|
const CONFIG_DIR = path.join(stateRoot(), 'clawchats');
|
|
136
137
|
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
137
138
|
const RUNTIME_FILE = path.join(CONFIG_DIR, 'runtime.json');
|
|
139
|
+
/** Browser login failures and lockout (auth-handler.ts), kept across restarts. */
|
|
140
|
+
const AUTH_STATE_FILE = path.join(CONFIG_DIR, 'auth-state.json');
|
|
141
|
+
/** setup-totp's QR as an image, for agent-driven setups; deleted by verify-totp. */
|
|
142
|
+
const TOTP_QR_IMAGE = path.join(CONFIG_DIR, 'totp-qr.gif');
|
|
143
|
+
// All writes are atomic; a change to part of the config is a read-modify-write (config-store.ts).
|
|
138
144
|
function loadConfig() {
|
|
139
|
-
|
|
140
|
-
const raw = fs.readFileSync(CONFIG_FILE, 'utf8');
|
|
141
|
-
const cfg = JSON.parse(raw);
|
|
142
|
-
if (!cfg.userId || !cfg.apiKey || !cfg.serverUrl) {
|
|
143
|
-
return null;
|
|
144
|
-
}
|
|
145
|
-
return cfg;
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
return null;
|
|
149
|
-
}
|
|
145
|
+
return readConfig(CONFIG_FILE);
|
|
150
146
|
}
|
|
151
147
|
function saveConfig(config) {
|
|
152
|
-
|
|
153
|
-
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
148
|
+
writeConfig(CONFIG_FILE, config);
|
|
154
149
|
}
|
|
155
150
|
// ---------------------------------------------------------------------------
|
|
156
151
|
// Service lifecycle
|
|
@@ -290,12 +285,11 @@ function startHealthEndpoint(ctx) {
|
|
|
290
285
|
});
|
|
291
286
|
healthServer.listen(0, '127.0.0.1', () => {
|
|
292
287
|
const addr = healthServer.address();
|
|
293
|
-
|
|
294
|
-
fs.writeFileSync(RUNTIME_FILE, JSON.stringify({
|
|
288
|
+
writeFileAtomic(RUNTIME_FILE, JSON.stringify({
|
|
295
289
|
pid: process.pid,
|
|
296
290
|
healthPort: addr.port,
|
|
297
291
|
startedAt: new Date().toISOString(),
|
|
298
|
-
}, null, 2)
|
|
292
|
+
}, null, 2));
|
|
299
293
|
ctx.logger.info(`Health endpoint on 127.0.0.1:${addr.port}`);
|
|
300
294
|
});
|
|
301
295
|
}
|
|
@@ -400,12 +394,15 @@ async function runClawChats(ctx, api) {
|
|
|
400
394
|
// Installed before the setup flow saved the gateway id: log in by userId, then keep the id the server answers with,
|
|
401
395
|
// so the next login uses it and grants carry it. Nothing for the user to do.
|
|
402
396
|
signaling.on('gateway-id', (id) => {
|
|
403
|
-
|
|
404
|
-
|
|
397
|
+
let saved = false;
|
|
398
|
+
updateConfig(CONFIG_FILE, (cfg) => {
|
|
399
|
+
if (cfg.gatewayId)
|
|
400
|
+
return false;
|
|
405
401
|
cfg.gatewayId = id;
|
|
406
|
-
|
|
402
|
+
saved = true;
|
|
403
|
+
});
|
|
404
|
+
if (saved)
|
|
407
405
|
ctx.logger.info(`[clawchats] saved gateway id ${id} (this install had none; it logged in by user id)`);
|
|
408
|
-
}
|
|
409
406
|
});
|
|
410
407
|
signaling.on('connected', () => {
|
|
411
408
|
ctx.logger.info('Connected to signaling server');
|
|
@@ -425,6 +422,8 @@ async function runClawChats(ctx, api) {
|
|
|
425
422
|
return;
|
|
426
423
|
}
|
|
427
424
|
webrtcPeer = new WebRTCPeerManager();
|
|
425
|
+
loadAuthState(AUTH_STATE_FILE);
|
|
426
|
+
watchConfigForRevocation(ctx);
|
|
428
427
|
webrtcPeer.on('datachannel', (dc, connectionId) => {
|
|
429
428
|
ctx.logger.info(`Browser connected via DataChannel: ${connectionId}`);
|
|
430
429
|
setupDataChannelHandler(dc, connectionId, ctx);
|
|
@@ -565,6 +564,10 @@ function teardownRuntime() {
|
|
|
565
564
|
fs.unlinkSync(RUNTIME_FILE);
|
|
566
565
|
}
|
|
567
566
|
catch { /* already gone */ }
|
|
567
|
+
if (configWatcher) {
|
|
568
|
+
fs.unwatchFile(CONFIG_FILE, configWatcher);
|
|
569
|
+
configWatcher = null;
|
|
570
|
+
}
|
|
568
571
|
// 1. Notify connected browsers and close DataChannels
|
|
569
572
|
for (const [id, client] of connectedClients) {
|
|
570
573
|
try {
|
|
@@ -601,97 +604,50 @@ function teardownRuntime() {
|
|
|
601
604
|
// DataChannel message handler (spec section 6.4)
|
|
602
605
|
// ---------------------------------------------------------------------------
|
|
603
606
|
function setupDataChannelHandler(dc, connectionId, ctx) {
|
|
604
|
-
// Build auth config from plugin config
|
|
605
|
-
const config = loadConfig();
|
|
606
|
-
const isDevMode = process.env.CLAWCHATS_DEV === 'true';
|
|
607
|
-
const hasGoogle = !!config?.google;
|
|
608
|
-
const authEnabled = config?.schemaVersion === 2 && config?.totp && config?.sessionSecret;
|
|
609
|
-
if (authEnabled) {
|
|
610
|
-
// In dev mode without Google identity, use placeholder
|
|
611
|
-
const google = config.google ?? {
|
|
612
|
-
clientId: 'dev-placeholder',
|
|
613
|
-
authorizedSub: 'dev-placeholder',
|
|
614
|
-
authorizedEmail: 'dev@localhost',
|
|
615
|
-
};
|
|
616
|
-
// Auth-gated: don't add to broadcast clients until authenticated
|
|
617
|
-
const authConfig = {
|
|
618
|
-
userId: config.userId,
|
|
619
|
-
totp: config.totp,
|
|
620
|
-
google,
|
|
621
|
-
sessionSecret: config.sessionSecret,
|
|
622
|
-
backupCodeHashes: config.backupCodeHashes,
|
|
623
|
-
devMode: isDevMode,
|
|
624
|
-
};
|
|
625
|
-
const authStarted = initAuth(dc, connectionId);
|
|
626
|
-
if (!authStarted)
|
|
627
|
-
return; // rate-limited, DC will be closed
|
|
628
|
-
dc.onMessage(async (data) => {
|
|
629
|
-
let msg;
|
|
630
|
-
try {
|
|
631
|
-
msg = JSON.parse(data);
|
|
632
|
-
}
|
|
633
|
-
catch {
|
|
634
|
-
dc.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
|
|
635
|
-
return;
|
|
636
|
-
}
|
|
637
|
-
// Check auth state
|
|
638
|
-
const authResult = await handleAuthMessage(dc, connectionId, msg, authConfig);
|
|
639
|
-
switch (authResult) {
|
|
640
|
-
case 'authenticated':
|
|
641
|
-
// Auth succeeded — add to broadcast clients and inform gateway
|
|
642
|
-
connectedClients.set(connectionId, dc);
|
|
643
|
-
ctx.logger.info(`Browser authenticated: ${connectionId}`);
|
|
644
|
-
// Persist backup code changes if any were consumed
|
|
645
|
-
if (authConfig.backupCodeHashes && config.backupCodeHashes) {
|
|
646
|
-
config.backupCodeHashes = authConfig.backupCodeHashes;
|
|
647
|
-
saveConfig(config);
|
|
648
|
-
}
|
|
649
|
-
return;
|
|
650
|
-
case 'pending':
|
|
651
|
-
// Still waiting for valid auth
|
|
652
|
-
return;
|
|
653
|
-
case 'blocked':
|
|
654
|
-
// Pre-auth non-auth message — drop silently
|
|
655
|
-
return;
|
|
656
|
-
case 'pass':
|
|
657
|
-
// Completed auth on this connection — process message normally.
|
|
658
|
-
// A connection whose auth timed out or was rate-limited gets
|
|
659
|
-
// 'blocked', never 'pass'; the client reconnects (Fix 4).
|
|
660
|
-
break;
|
|
661
|
-
}
|
|
662
|
-
// Authenticated message processing
|
|
663
|
-
processAuthenticatedMessage(dc, connectionId, msg, ctx);
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
|
-
else {
|
|
667
|
-
// No auth configured (schemaVersion 1 or missing TOTP)
|
|
668
|
-
if (config && config.schemaVersion !== undefined && config.schemaVersion < 2) {
|
|
669
|
-
ctx.logger.warn('TOTP not configured — DataChannel access blocked. Run: openclaw clawchats reauth');
|
|
670
|
-
dc.send(JSON.stringify({
|
|
671
|
-
type: 'auth-required-setup',
|
|
672
|
-
message: 'Two-factor authentication is required. Run "openclaw clawchats reauth" on your gateway machine to set it up.',
|
|
673
|
-
}));
|
|
674
|
-
return; // Don't process any messages
|
|
675
|
-
}
|
|
676
|
-
// Legacy path: no config at all (shouldn't happen in normal flow)
|
|
677
|
-
connectedClients.set(connectionId, dc);
|
|
678
|
-
dc.onMessage(async (data) => {
|
|
679
|
-
let msg;
|
|
680
|
-
try {
|
|
681
|
-
msg = JSON.parse(data);
|
|
682
|
-
}
|
|
683
|
-
catch {
|
|
684
|
-
dc.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
687
|
-
processAuthenticatedMessage(dc, connectionId, msg, ctx);
|
|
688
|
-
});
|
|
689
|
-
}
|
|
690
607
|
dc.onClosed(() => {
|
|
691
608
|
connectedClients.delete(connectionId);
|
|
692
|
-
|
|
609
|
+
rpcReqChunks.dropConnection(connectionId);
|
|
610
|
+
gatewayMsgChunks.dropConnection(connectionId);
|
|
693
611
|
app?.debugLogger.handleClientDisconnect(dc);
|
|
694
612
|
});
|
|
613
|
+
// 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.
|
|
615
|
+
attachBrowserChannel(dc, connectionId, {
|
|
616
|
+
loadAuthConfig: () => readAuthConfig(CONFIG_FILE, process.env.CLAWCHATS_DEV === 'true'),
|
|
617
|
+
consumeBackupCode: (hash) => {
|
|
618
|
+
const consumed = removeBackupCode(CONFIG_FILE, hash);
|
|
619
|
+
if (consumed)
|
|
620
|
+
ctx.logger.warn(`Browser ${connectionId} logged in with a backup code`);
|
|
621
|
+
return consumed;
|
|
622
|
+
},
|
|
623
|
+
onAuthenticated: () => {
|
|
624
|
+
// Auth succeeded — add to broadcast clients and inform gateway
|
|
625
|
+
connectedClients.set(connectionId, dc);
|
|
626
|
+
ctx.logger.info(`Browser authenticated: ${connectionId}`);
|
|
627
|
+
},
|
|
628
|
+
onMessage: (msg) => processAuthenticatedMessage(dc, connectionId, msg, ctx),
|
|
629
|
+
onLoginFailure: (reason) => {
|
|
630
|
+
ctx.logger.warn(`Failed ClawChats login attempt on ${connectionId} (${reason})`);
|
|
631
|
+
broadcastToClients({ type: 'auth-attempt-failed', reason, at: new Date().toISOString() });
|
|
632
|
+
},
|
|
633
|
+
log: ctx.logger,
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Browsers that logged in under secrets the config no longer has (`reauth`, `reset`, a deleted
|
|
638
|
+
* config) are signed out. Polls the file's stat, so atomic renames and deletion are both seen.
|
|
639
|
+
*/
|
|
640
|
+
let configWatcher = null;
|
|
641
|
+
function watchConfigForRevocation(ctx) {
|
|
642
|
+
if (configWatcher)
|
|
643
|
+
fs.unwatchFile(CONFIG_FILE, configWatcher);
|
|
644
|
+
configWatcher = () => {
|
|
645
|
+
for (const id of revokeStaleChannels(readAuthConfig(CONFIG_FILE))) {
|
|
646
|
+
connectedClients.delete(id);
|
|
647
|
+
ctx.logger.warn(`Browser ${id} signed out: ClawChats login settings changed (reauth/reset)`);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
fs.watchFile(CONFIG_FILE, { interval: 2000, persistent: false }, configWatcher);
|
|
695
651
|
}
|
|
696
652
|
/**
|
|
697
653
|
* Process a message on an authenticated DataChannel.
|
|
@@ -699,43 +655,27 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
|
|
|
699
655
|
function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
|
|
700
656
|
switch (msg['type']) {
|
|
701
657
|
case 'rpc':
|
|
702
|
-
handleRpcMessage(dc, msg, ctx);
|
|
703
|
-
break;
|
|
658
|
+
return handleRpcMessage(dc, msg, ctx);
|
|
704
659
|
case 'rpc-chunk-req': {
|
|
705
|
-
const
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
dc.send(JSON.stringify({ type: 'error', message: 'malformed rpc-chunk-req' }));
|
|
660
|
+
const r = rpcReqChunks.add(connectionId, msg);
|
|
661
|
+
if (!r)
|
|
662
|
+
break;
|
|
663
|
+
if ('error' in r) {
|
|
664
|
+
dc.send(JSON.stringify({ type: 'error', message: `malformed rpc-chunk-req: ${r.error}` }));
|
|
711
665
|
break;
|
|
712
666
|
}
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
received: 0,
|
|
717
|
-
total,
|
|
718
|
-
createdAt: Date.now(),
|
|
719
|
-
});
|
|
720
|
-
setTimeout(() => rpcReqChunkBuffers.delete(chunkId), 30_000);
|
|
667
|
+
let reassembled;
|
|
668
|
+
try {
|
|
669
|
+
reassembled = JSON.parse(r.done);
|
|
721
670
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
rpcBuf.chunks[index] = chunkData;
|
|
725
|
-
rpcBuf.received++;
|
|
671
|
+
catch {
|
|
672
|
+
reassembled = null;
|
|
726
673
|
}
|
|
727
|
-
if (
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
try {
|
|
731
|
-
const reassembled = JSON.parse(fullMsg);
|
|
732
|
-
handleRpcMessage(dc, reassembled, ctx);
|
|
733
|
-
}
|
|
734
|
-
catch (e) {
|
|
735
|
-
dc.send(JSON.stringify({ type: 'rpc-res', id: chunkId, status: 400, body: { error: 'Failed to reassemble chunked RPC' } }));
|
|
736
|
-
}
|
|
674
|
+
if (!reassembled || typeof reassembled !== 'object') {
|
|
675
|
+
dc.send(JSON.stringify({ type: 'rpc-res', id: msg['id'], status: 400, body: { error: 'Failed to reassemble chunked RPC' } }));
|
|
676
|
+
break;
|
|
737
677
|
}
|
|
738
|
-
|
|
678
|
+
return handleRpcMessage(dc, reassembled, ctx);
|
|
739
679
|
}
|
|
740
680
|
case 'gateway-msg':
|
|
741
681
|
if (app?.gatewayClient && typeof msg['payload'] === 'string') {
|
|
@@ -744,35 +684,14 @@ function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
|
|
|
744
684
|
}
|
|
745
685
|
break;
|
|
746
686
|
case 'gateway-msg-chunk': {
|
|
747
|
-
const
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
dc.send(JSON.stringify({ type: 'error', message: 'malformed gateway-msg-chunk' }));
|
|
687
|
+
const r = gatewayMsgChunks.add(connectionId, msg);
|
|
688
|
+
if (!r)
|
|
689
|
+
break;
|
|
690
|
+
if ('error' in r) {
|
|
691
|
+
dc.send(JSON.stringify({ type: 'error', message: `malformed gateway-msg-chunk: ${r.error}` }));
|
|
753
692
|
break;
|
|
754
693
|
}
|
|
755
|
-
|
|
756
|
-
gatewayMsgChunkBuffers.set(chunkId, {
|
|
757
|
-
chunks: new Array(total),
|
|
758
|
-
received: 0,
|
|
759
|
-
total,
|
|
760
|
-
createdAt: Date.now(),
|
|
761
|
-
});
|
|
762
|
-
setTimeout(() => gatewayMsgChunkBuffers.delete(chunkId), 30_000);
|
|
763
|
-
}
|
|
764
|
-
const buf = gatewayMsgChunkBuffers.get(chunkId);
|
|
765
|
-
if (!buf.chunks[index]) {
|
|
766
|
-
buf.chunks[index] = chunkData;
|
|
767
|
-
buf.received++;
|
|
768
|
-
}
|
|
769
|
-
if (buf.received === buf.total) {
|
|
770
|
-
gatewayMsgChunkBuffers.delete(chunkId);
|
|
771
|
-
const fullPayload = buf.chunks.join('');
|
|
772
|
-
if (app?.gatewayClient) {
|
|
773
|
-
app.gatewayClient.forwardFromBrowser(fullPayload);
|
|
774
|
-
}
|
|
775
|
-
}
|
|
694
|
+
app?.gatewayClient?.forwardFromBrowser(r.done);
|
|
776
695
|
break;
|
|
777
696
|
}
|
|
778
697
|
case 'ping':
|
|
@@ -1099,13 +1018,11 @@ async function enrollTotp(config) {
|
|
|
1099
1018
|
// Generate a brand new TOTP secret
|
|
1100
1019
|
totpSecret = generateTotpSecret();
|
|
1101
1020
|
const email = config.google?.authorizedEmail || config.userId;
|
|
1102
|
-
void buildOtpauthUri(totpSecret, email); // keep import used
|
|
1103
1021
|
const formatted = totpSecret.match(/.{1,4}/g)?.join(' ') || totpSecret;
|
|
1104
1022
|
console.log('');
|
|
1105
1023
|
console.log(' 🔐 Setting up two-factor authentication');
|
|
1106
1024
|
console.log('');
|
|
1107
|
-
|
|
1108
|
-
console.log(` ${config.serverUrl.replace('wss://', 'https://').replace(/\/ws\/?$/, '')}/totp-setup#${totpSecret}`);
|
|
1025
|
+
await printTotpQr(totpSecret, email);
|
|
1109
1026
|
console.log('');
|
|
1110
1027
|
console.log(` Or enter this code manually: ${formatted}`);
|
|
1111
1028
|
console.log('');
|
|
@@ -1130,9 +1047,27 @@ async function enrollTotp(config) {
|
|
|
1130
1047
|
rl.close();
|
|
1131
1048
|
return false;
|
|
1132
1049
|
}
|
|
1133
|
-
|
|
1134
|
-
// Generate backup codes
|
|
1050
|
+
// Generate backup codes and a new session secret (invalidates every session token)
|
|
1135
1051
|
const { codes, hashes } = generateBackupCodes();
|
|
1052
|
+
const sessionSecret = generateSessionSecret();
|
|
1053
|
+
// Update only the 2FA fields of the config as it is on disk now (the prompts above can take
|
|
1054
|
+
// minutes; the running service may have changed it meanwhile)
|
|
1055
|
+
const saved = updateConfig(CONFIG_FILE, (c) => {
|
|
1056
|
+
c.totp = {
|
|
1057
|
+
secret: totpSecret,
|
|
1058
|
+
algorithm: 'SHA1',
|
|
1059
|
+
digits: 6,
|
|
1060
|
+
period: 30,
|
|
1061
|
+
enabledAt: new Date().toISOString(),
|
|
1062
|
+
};
|
|
1063
|
+
c.sessionSecret = sessionSecret;
|
|
1064
|
+
c.backupCodeHashes = hashes;
|
|
1065
|
+
c.schemaVersion = 2;
|
|
1066
|
+
delete c.totpPending;
|
|
1067
|
+
});
|
|
1068
|
+
if (!saved)
|
|
1069
|
+
throw new Error('the ClawChats config is gone (was it reset?). Run setup again.');
|
|
1070
|
+
console.log(' ✅ Two-factor authentication enabled!');
|
|
1136
1071
|
console.log('');
|
|
1137
1072
|
console.log(' 🔑 Backup codes (save these somewhere safe — one-time use):');
|
|
1138
1073
|
for (const code of codes) {
|
|
@@ -1140,20 +1075,6 @@ async function enrollTotp(config) {
|
|
|
1140
1075
|
}
|
|
1141
1076
|
console.log('');
|
|
1142
1077
|
console.log(' ⚠️ These codes will NOT be shown again.');
|
|
1143
|
-
// Generate session secret
|
|
1144
|
-
const sessionSecret = generateSessionSecret();
|
|
1145
|
-
// Update config
|
|
1146
|
-
config.totp = {
|
|
1147
|
-
secret: totpSecret,
|
|
1148
|
-
algorithm: 'SHA1',
|
|
1149
|
-
digits: 6,
|
|
1150
|
-
period: 30,
|
|
1151
|
-
enabledAt: new Date().toISOString(),
|
|
1152
|
-
};
|
|
1153
|
-
config.sessionSecret = sessionSecret;
|
|
1154
|
-
config.backupCodeHashes = hashes;
|
|
1155
|
-
config.schemaVersion = 2;
|
|
1156
|
-
saveConfig(config);
|
|
1157
1078
|
console.log('');
|
|
1158
1079
|
rl.close();
|
|
1159
1080
|
return true;
|
|
@@ -1164,6 +1085,33 @@ async function enrollTotp(config) {
|
|
|
1164
1085
|
return false;
|
|
1165
1086
|
}
|
|
1166
1087
|
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Draw the authenticator QR code (otpauth URI) here, in the terminal: the TOTP secret never
|
|
1090
|
+
* goes to another server. `imageFile` also saves it as a GIF (owner-only).
|
|
1091
|
+
*/
|
|
1092
|
+
async function printTotpQr(secret, email, imageFile) {
|
|
1093
|
+
const uri = buildOtpauthUri(secret, email);
|
|
1094
|
+
let qr;
|
|
1095
|
+
try {
|
|
1096
|
+
// Loaded only here (CLI): the service never needs it
|
|
1097
|
+
const { default: qrcode } = await import('qrcode-generator');
|
|
1098
|
+
qr = qrcode(0, 'M');
|
|
1099
|
+
qr.addData(uri);
|
|
1100
|
+
qr.make();
|
|
1101
|
+
}
|
|
1102
|
+
catch (e) {
|
|
1103
|
+
console.log(` (Could not draw the QR code: ${e.message}.) Add this to your authenticator app:`);
|
|
1104
|
+
console.log(` ${uri}`);
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
console.log(' Scan this QR code with your authenticator app:');
|
|
1108
|
+
console.log('');
|
|
1109
|
+
console.log(qr.createASCII(1, 4).split('\n').map(line => ` ${line}`).join('\n'));
|
|
1110
|
+
if (imageFile) {
|
|
1111
|
+
writeFileAtomic(imageFile, Buffer.from(qr.createDataURL(6, 4).split(',')[1], 'base64'));
|
|
1112
|
+
console.log(` The same QR code as an image: ${imageFile}`);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1167
1115
|
async function handleShowTotp() {
|
|
1168
1116
|
const config = loadConfig();
|
|
1169
1117
|
if (!config) {
|
|
@@ -1211,22 +1159,19 @@ async function handleSetupTotp() {
|
|
|
1211
1159
|
else {
|
|
1212
1160
|
// Expired — generate a fresh one
|
|
1213
1161
|
totpSecret = process.env.CLAWCHATS_DEV_TOTP_SECRET || generateTotpSecret();
|
|
1214
|
-
|
|
1215
|
-
saveConfig(config);
|
|
1162
|
+
updateConfig(CONFIG_FILE, (c) => { c.totpPending = { secret: totpSecret, generatedAt: new Date().toISOString() }; });
|
|
1216
1163
|
}
|
|
1217
1164
|
}
|
|
1218
1165
|
else {
|
|
1219
1166
|
totpSecret = process.env.CLAWCHATS_DEV_TOTP_SECRET || generateTotpSecret();
|
|
1220
|
-
|
|
1221
|
-
saveConfig(config);
|
|
1167
|
+
updateConfig(CONFIG_FILE, (c) => { c.totpPending = { secret: totpSecret, generatedAt: new Date().toISOString() }; });
|
|
1222
1168
|
}
|
|
1223
1169
|
const formatted = totpSecret.match(/.{1,4}/g)?.join(' ') || totpSecret;
|
|
1224
|
-
const setupUrl = `${config.serverUrl.replace('wss://', 'https://').replace(/\/ws\/?$/, '')}/totp-setup#${totpSecret}`;
|
|
1225
1170
|
console.log('');
|
|
1226
1171
|
console.log(' 🔐 ClawChats Two-Factor Authentication Setup');
|
|
1227
1172
|
console.log('');
|
|
1228
|
-
|
|
1229
|
-
|
|
1173
|
+
// Agent-driven: the agent can't show a terminal drawing reliably, so the QR is also saved as an image
|
|
1174
|
+
await printTotpQr(totpSecret, config.google?.authorizedEmail || config.userId, TOTP_QR_IMAGE);
|
|
1230
1175
|
console.log('');
|
|
1231
1176
|
console.log(` Or enter manually: ${formatted}`);
|
|
1232
1177
|
console.log('');
|
|
@@ -1254,8 +1199,31 @@ async function handleVerifyTotp(code) {
|
|
|
1254
1199
|
console.error(' Run: openclaw clawchats verify-totp <new-code>');
|
|
1255
1200
|
process.exit(1);
|
|
1256
1201
|
}
|
|
1257
|
-
// Generate backup codes
|
|
1202
|
+
// Generate backup codes and session secret; finalize the config as it is on disk now
|
|
1258
1203
|
const { codes, hashes } = generateBackupCodes();
|
|
1204
|
+
const sessionSecret = generateSessionSecret();
|
|
1205
|
+
const secret = config.totpPending.secret;
|
|
1206
|
+
const saved = updateConfig(CONFIG_FILE, (c) => {
|
|
1207
|
+
c.totp = {
|
|
1208
|
+
secret,
|
|
1209
|
+
algorithm: 'SHA1',
|
|
1210
|
+
digits: 6,
|
|
1211
|
+
period: 30,
|
|
1212
|
+
enabledAt: new Date().toISOString(),
|
|
1213
|
+
};
|
|
1214
|
+
c.sessionSecret = sessionSecret;
|
|
1215
|
+
c.backupCodeHashes = hashes;
|
|
1216
|
+
c.schemaVersion = 2;
|
|
1217
|
+
delete c.totpPending;
|
|
1218
|
+
});
|
|
1219
|
+
if (!saved) {
|
|
1220
|
+
console.error(' The ClawChats config is gone (was it reset?). Run setup again.');
|
|
1221
|
+
process.exit(1);
|
|
1222
|
+
}
|
|
1223
|
+
try {
|
|
1224
|
+
fs.unlinkSync(TOTP_QR_IMAGE);
|
|
1225
|
+
}
|
|
1226
|
+
catch { /* never written or already deleted */ }
|
|
1259
1227
|
console.log('');
|
|
1260
1228
|
console.log(' 🔑 Backup codes (save these somewhere safe — one-time use):');
|
|
1261
1229
|
for (const backupCode of codes) {
|
|
@@ -1263,20 +1231,6 @@ async function handleVerifyTotp(code) {
|
|
|
1263
1231
|
}
|
|
1264
1232
|
console.log('');
|
|
1265
1233
|
console.log(' ⚠️ These codes will NOT be shown again.');
|
|
1266
|
-
// Generate session secret and finalize config
|
|
1267
|
-
const sessionSecret = generateSessionSecret();
|
|
1268
|
-
config.totp = {
|
|
1269
|
-
secret: config.totpPending.secret,
|
|
1270
|
-
algorithm: 'SHA1',
|
|
1271
|
-
digits: 6,
|
|
1272
|
-
period: 30,
|
|
1273
|
-
enabledAt: new Date().toISOString(),
|
|
1274
|
-
};
|
|
1275
|
-
config.sessionSecret = sessionSecret;
|
|
1276
|
-
config.backupCodeHashes = hashes;
|
|
1277
|
-
config.schemaVersion = 2;
|
|
1278
|
-
delete config.totpPending;
|
|
1279
|
-
saveConfig(config);
|
|
1280
1234
|
console.log('');
|
|
1281
1235
|
console.log(' ✅ Two-factor authentication enabled!');
|
|
1282
1236
|
console.log('');
|
|
@@ -1408,6 +1362,8 @@ async function handleStatus() {
|
|
|
1408
1362
|
}
|
|
1409
1363
|
async function handleReset() {
|
|
1410
1364
|
try {
|
|
1365
|
+
// Config first: a running service then refuses (and signs out) every browser at once
|
|
1366
|
+
fs.rmSync(CONFIG_FILE, { force: true });
|
|
1411
1367
|
fs.rmSync(CONFIG_DIR, { recursive: true, force: true });
|
|
1412
1368
|
console.log('ClawChats data removed. Plugin disconnected.');
|
|
1413
1369
|
}
|
|
@@ -1462,8 +1418,7 @@ async function handleImport(sourcePath) {
|
|
|
1462
1418
|
const parentConfigPath = path.join(path.dirname(resolvedSource), 'config.json');
|
|
1463
1419
|
if (fs.existsSync(parentConfigPath)) {
|
|
1464
1420
|
try {
|
|
1465
|
-
fs.
|
|
1466
|
-
fs.copyFileSync(parentConfigPath, CONFIG_FILE);
|
|
1421
|
+
writeFileAtomic(CONFIG_FILE, fs.readFileSync(parentConfigPath));
|
|
1467
1422
|
console.log(' ✓ config.json (plugin credentials migrated)');
|
|
1468
1423
|
}
|
|
1469
1424
|
catch (e) {
|
package/dist/totp.js
CHANGED
|
@@ -47,7 +47,7 @@ export function generateTotp(secretBase32) {
|
|
|
47
47
|
* @returns The matched time step if valid, or -1 if invalid
|
|
48
48
|
*/
|
|
49
49
|
export function verifyTotp(code, secretBase32, lastUsedStep) {
|
|
50
|
-
if (!/^\d{6}$/.test(code))
|
|
50
|
+
if (typeof code !== 'string' || !/^\d{6}$/.test(code))
|
|
51
51
|
return -1;
|
|
52
52
|
const secret = base32Decode(secretBase32);
|
|
53
53
|
const currentStep = Math.floor(Date.now() / 1000 / PERIOD);
|
|
@@ -111,6 +111,8 @@ export function generateBackupCodes() {
|
|
|
111
111
|
* Verify a backup code against stored hashes. Returns the index consumed, or -1.
|
|
112
112
|
*/
|
|
113
113
|
export function verifyBackupCode(code, hashes) {
|
|
114
|
+
if (typeof code !== 'string' || !Array.isArray(hashes))
|
|
115
|
+
return -1;
|
|
114
116
|
const normalized = code.toUpperCase().replace(/\s/g, '');
|
|
115
117
|
const hash = crypto.createHash('sha256').update(normalized).digest('hex');
|
|
116
118
|
const index = hashes.indexOf(hash);
|
package/dist/webrtc-peer.js
CHANGED
|
@@ -35,8 +35,17 @@ function wrapDataChannel(dc) {
|
|
|
35
35
|
: Buffer.isBuffer(event.data)
|
|
36
36
|
? event.data.toString('utf8')
|
|
37
37
|
: String(event.data);
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
// Safety net: a handler error must not escape into the native event dispatch (gateway process)
|
|
39
|
+
for (const h of messageHandlers) {
|
|
40
|
+
try {
|
|
41
|
+
const r = h(str);
|
|
42
|
+
if (r instanceof Promise)
|
|
43
|
+
r.catch((err) => console.error('[WebRTCPeerManager] DataChannel message handler failed:', err));
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
console.error('[WebRTCPeerManager] DataChannel message handler failed:', err);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
40
49
|
};
|
|
41
50
|
dc.onclose = () => {
|
|
42
51
|
for (const h of closedHandlers)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clawchatsai/connector",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.49",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -20,12 +20,13 @@
|
|
|
20
20
|
"scripts": {
|
|
21
21
|
"build": "tsc",
|
|
22
22
|
"dev": "tsc --watch",
|
|
23
|
-
"test": "node --test 'server/**/*.test.js'",
|
|
23
|
+
"test": "tsc && node --test 'server/**/*.test.js' 'test/**/*.test.js'",
|
|
24
24
|
"prepublishOnly": "npm run build"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"jose": "^5.10.0",
|
|
28
28
|
"node-datachannel": "^0.32.1",
|
|
29
|
+
"qrcode-generator": "^2.0.4",
|
|
29
30
|
"ws": "^8.0.0"
|
|
30
31
|
},
|
|
31
32
|
"openclaw": {
|
|
@@ -23,6 +23,21 @@ const STATIC_MAP = {
|
|
|
23
23
|
'/favicon.ico': 'favicon.ico',
|
|
24
24
|
};
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* The real path of `rel` inside rootDir, or null if it is missing or would escape rootDir
|
|
28
|
+
* (`..`, an absolute path, a NUL byte, or a symlink pointing outside).
|
|
29
|
+
*/
|
|
30
|
+
export function resolveStaticPath(rootDir, rel) {
|
|
31
|
+
if (typeof rel !== 'string' || rel.includes('\0')) return null;
|
|
32
|
+
try {
|
|
33
|
+
const root = fs.realpathSync(path.resolve(rootDir));
|
|
34
|
+
const real = fs.realpathSync(path.resolve(root, rel));
|
|
35
|
+
return real.startsWith(root + path.sep) ? real : null;
|
|
36
|
+
} catch {
|
|
37
|
+
return null; // missing
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
26
41
|
/**
|
|
27
42
|
* Serve static files from pluginDir.
|
|
28
43
|
* Returns true if the request was handled, false if it should fall through.
|
|
@@ -41,11 +56,12 @@ export function handleStatic(req, res, pluginDir) {
|
|
|
41
56
|
|
|
42
57
|
if (!isAllowed) return false;
|
|
43
58
|
|
|
44
|
-
const staticPath =
|
|
45
|
-
if (!
|
|
59
|
+
const staticPath = resolveStaticPath(pluginDir, fileName || urlPath.slice(1));
|
|
60
|
+
if (!staticPath) return false;
|
|
61
|
+
const stat = fs.statSync(staticPath);
|
|
62
|
+
if (!stat.isFile()) return false;
|
|
46
63
|
|
|
47
64
|
const ext = path.extname(staticPath).toLowerCase();
|
|
48
|
-
const stat = fs.statSync(staticPath);
|
|
49
65
|
res.writeHead(200, {
|
|
50
66
|
'Content-Type': MIME[ext] || 'application/octet-stream',
|
|
51
67
|
'Content-Length': stat.size,
|