@clawchatsai/connector 0.1.47 → 0.1.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-handler.d.ts +47 -29
- package/dist/auth-handler.js +306 -245
- package/dist/chunk-reassembly.d.ts +38 -0
- package/dist/chunk-reassembly.js +88 -0
- package/dist/config-store.d.ts +46 -0
- package/dist/config-store.js +154 -0
- package/dist/index.js +168 -213
- package/dist/totp.js +3 -1
- package/dist/webrtc-peer.js +11 -2
- package/package.json +3 -2
- package/server/controllers/static.js +19 -3
- package/server/controllers/static.test.js +48 -0
- package/server/controllers/title.js +12 -2
- package/server/debug.js +3 -1
- package/server/debug.test.js +23 -1
- package/server/index.js +6 -0
- package/server/peer/link.js +5 -1
- package/server/peer/link.test.js +10 -0
- package/server/peer/sharing.js +172 -34
- package/server/peer/sharing.test.js +153 -0
- package/server/team.js +116 -32
- package/server/team.test.js +131 -4
package/dist/auth-handler.js
CHANGED
|
@@ -1,294 +1,355 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* auth-handler.ts — DataChannel authentication
|
|
2
|
+
* auth-handler.ts — DataChannel authentication gate
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* 1.
|
|
6
|
-
* 2.
|
|
7
|
-
* 3.
|
|
8
|
-
* 4.
|
|
9
|
-
* 5.
|
|
4
|
+
* Every browser DataChannel goes through attachBrowserChannel() before anything else sees it:
|
|
5
|
+
* 1. Refuse (message + close) unless the config on disk is complete with TOTP set up
|
|
6
|
+
* 2. Send auth-required with nonce
|
|
7
|
+
* 3. Wait for auth-session (cached JWT) or auth-full (Google + TOTP), validating every field
|
|
8
|
+
* 4. Verify against the config as it is on disk at that moment
|
|
9
|
+
* 5. Issue session token on success; only then are messages handed to the request handlers
|
|
10
|
+
* A channel that does not log in within 60 s, fails too often or sends malformed login
|
|
11
|
+
* messages is closed. Login failures and lockouts survive a restart (auth-state.json).
|
|
10
12
|
*
|
|
11
13
|
* Spec: datachannel-auth-totp.md §4
|
|
12
14
|
*/
|
|
13
15
|
import * as crypto from 'node:crypto';
|
|
16
|
+
import * as fs from 'node:fs';
|
|
14
17
|
import { verifyTotp, verifyBackupCode } from './totp.js';
|
|
15
18
|
import { verifyGoogleIdToken, clearJWKSCache } from './google-jwt.js';
|
|
16
19
|
import { issueSessionToken, verifySessionToken } from './session-token.js';
|
|
20
|
+
import { authEpoch, writeFileAtomic } from './config-store.js';
|
|
17
21
|
// ---------------------------------------------------------------------------
|
|
18
|
-
//
|
|
22
|
+
// Limits
|
|
19
23
|
// ---------------------------------------------------------------------------
|
|
20
|
-
/**
|
|
21
|
-
const
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
/** Rate limiting: connectionIds blocked after too many failures */
|
|
29
|
-
const blockedConnections = new Map(); // connectionId → unblock timestamp
|
|
30
|
-
/** TOTP replay prevention */
|
|
31
|
-
let lastUsedTotpStep = 0;
|
|
32
|
-
/**
|
|
33
|
-
* Gateway-wide auth-full lockout. Per-connection limits alone reset on every
|
|
34
|
-
* reconnect, so failures are also counted across all connections.
|
|
35
|
-
*/
|
|
36
|
-
let globalFailCount = 0;
|
|
37
|
-
let globalLockoutCount = 0;
|
|
38
|
-
let globalLockedUntil = 0;
|
|
39
|
-
/** Max nonces to prevent memory leaks from connection storms */
|
|
40
|
-
const MAX_PENDING_NONCES = 10;
|
|
41
|
-
const AUTH_TIMEOUT_MS = 60_000; // 60s — enough time to open authenticator app and enter code
|
|
42
|
-
const MAX_FAILURES = 5;
|
|
43
|
-
const BLOCK_DURATION_MS = 60_000;
|
|
24
|
+
/** Channels waiting to log in, gateway-wide. Further ones are refused until some finish. */
|
|
25
|
+
export const MAX_PENDING_CHANNELS = 10;
|
|
26
|
+
/** A channel that has not logged in by then is closed. */
|
|
27
|
+
export const AUTH_TIMEOUT_MS = 60_000; // enough time to open authenticator app and enter code
|
|
28
|
+
const MAX_FAILURES = 5; // per channel, then it is closed
|
|
29
|
+
const MAX_PREAUTH_MESSAGE_LENGTH = 16 * 1024;
|
|
30
|
+
const MAX_TOKEN_LENGTH = 8 * 1024; // Google ID tokens and session JWTs are ~1-2 KB
|
|
31
|
+
const MAX_CODE_LENGTH = 64;
|
|
44
32
|
const GLOBAL_MAX_FAILURES = 5;
|
|
45
33
|
const GLOBAL_LOCKOUT_BASE_MS = 60_000; // doubles per consecutive lockout
|
|
46
34
|
const GLOBAL_LOCKOUT_MAX_MS = 60 * 60_000;
|
|
35
|
+
const SETUP_MESSAGES = {
|
|
36
|
+
'needs-2fa': 'Two-factor authentication is required. Run "openclaw clawchats reauth" on your gateway machine to set it up.',
|
|
37
|
+
invalid: 'The ClawChats login settings on your gateway are incomplete or damaged. Run "openclaw clawchats reauth" on your gateway machine.',
|
|
38
|
+
missing: 'ClawChats is not set up on your gateway. Run "openclaw clawchats setup <token>" on your gateway machine.',
|
|
39
|
+
};
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// Module state
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
const channels = new Set();
|
|
44
|
+
const freshState = () => ({ failCount: 0, lockoutCount: 0, lockedUntil: 0, lastUsedTotpStep: 0 });
|
|
45
|
+
let authState = freshState();
|
|
46
|
+
let authStateFile = null;
|
|
47
|
+
/** Load the persisted lockout state (call once at service start). Unreadable = fresh state. */
|
|
48
|
+
export function loadAuthState(file) {
|
|
49
|
+
authStateFile = file;
|
|
50
|
+
authState = freshState();
|
|
51
|
+
let raw;
|
|
52
|
+
try {
|
|
53
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (!raw || typeof raw !== 'object')
|
|
59
|
+
return;
|
|
60
|
+
for (const k of Object.keys(authState)) {
|
|
61
|
+
const v = raw[k];
|
|
62
|
+
if (typeof v === 'number' && Number.isFinite(v) && v >= 0)
|
|
63
|
+
authState[k] = v;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function saveAuthState() {
|
|
67
|
+
if (!authStateFile)
|
|
68
|
+
return;
|
|
69
|
+
try {
|
|
70
|
+
writeFileAtomic(authStateFile, JSON.stringify(authState));
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
console.error(`[Auth] could not save login lockout state: ${e.message}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
47
76
|
// ---------------------------------------------------------------------------
|
|
48
77
|
// Public API
|
|
49
78
|
// ---------------------------------------------------------------------------
|
|
50
79
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* @returns true if auth was initiated, false if connection is blocked
|
|
80
|
+
* Put a new browser DataChannel behind the login gate. Nothing reaches hooks.onMessage
|
|
81
|
+
* before the channel has logged in.
|
|
55
82
|
*/
|
|
56
|
-
export function
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}));
|
|
64
|
-
return false;
|
|
83
|
+
export function attachBrowserChannel(dc, connectionId, hooks) {
|
|
84
|
+
const ch = { connectionId, dc, status: 'pending', nonce: '', failCount: 0, chain: Promise.resolve() };
|
|
85
|
+
dc.onClosed(() => detach(ch));
|
|
86
|
+
const cfg = hooks.loadAuthConfig();
|
|
87
|
+
if (!cfg.ok) {
|
|
88
|
+
refuseSetup(ch, cfg.reason, hooks);
|
|
89
|
+
return;
|
|
65
90
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
let oldestKey = null;
|
|
71
|
-
let oldestTime = Infinity;
|
|
72
|
-
for (const [key, session] of authSessions) {
|
|
73
|
-
if (session.createdAt < oldestTime) {
|
|
74
|
-
oldestTime = session.createdAt;
|
|
75
|
-
oldestKey = key;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
if (oldestKey) {
|
|
79
|
-
const old = authSessions.get(oldestKey);
|
|
80
|
-
clearTimeout(old.timeoutHandle);
|
|
81
|
-
authSessions.delete(oldestKey);
|
|
82
|
-
// Tell the evicted client so it reconnects instead of hanging
|
|
83
|
-
old.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'auth_timeout' }));
|
|
84
|
-
}
|
|
91
|
+
if (pendingCount() >= MAX_PENDING_CHANNELS) {
|
|
92
|
+
hooks.log.warn(`Browser ${connectionId} refused: ${MAX_PENDING_CHANNELS} connections are already waiting to log in`);
|
|
93
|
+
refuse(ch, { type: 'auth-failed', reason: 'rate_limited' });
|
|
94
|
+
return;
|
|
85
95
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
type: 'auth-failed',
|
|
92
|
-
reason: 'auth_timeout',
|
|
93
|
-
}));
|
|
94
|
-
authSessions.delete(connectionId);
|
|
95
|
-
}
|
|
96
|
+
channels.add(ch);
|
|
97
|
+
ch.nonce = crypto.randomBytes(32).toString('hex');
|
|
98
|
+
ch.timer = setTimeout(() => {
|
|
99
|
+
if (ch.status === 'pending')
|
|
100
|
+
refuse(ch, { type: 'auth-failed', reason: 'auth_timeout' });
|
|
96
101
|
}, AUTH_TIMEOUT_MS);
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
connectionId,
|
|
101
|
-
failCount: 0,
|
|
102
|
-
createdAt: Date.now(),
|
|
103
|
-
timeoutHandle,
|
|
104
|
-
dc,
|
|
105
|
-
});
|
|
106
|
-
dc.send(JSON.stringify({
|
|
107
|
-
type: 'auth-required',
|
|
108
|
-
nonce,
|
|
109
|
-
}));
|
|
110
|
-
return true;
|
|
102
|
+
ch.timer.unref?.();
|
|
103
|
+
dc.onMessage((data) => onData(ch, data, hooks));
|
|
104
|
+
dc.send(JSON.stringify({ type: 'auth-required', nonce: ch.nonce }));
|
|
111
105
|
}
|
|
112
106
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
* @returns 'authenticated' if the message was an auth message and auth succeeded,
|
|
116
|
-
* 'pending' if auth is still in progress,
|
|
117
|
-
* 'pass' if the connection is already authenticated (message should be processed normally),
|
|
118
|
-
* 'blocked' if the message was dropped (pre-auth non-auth message)
|
|
107
|
+
* The config on disk changed: close logged-in channels whose login secrets are gone
|
|
108
|
+
* (`reauth`, `reset`, a deleted or broken config). Returns their connection ids.
|
|
119
109
|
*/
|
|
120
|
-
export
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
110
|
+
export function revokeStaleChannels(current) {
|
|
111
|
+
const epoch = current.ok ? authEpoch(current.config) : null;
|
|
112
|
+
const revoked = [];
|
|
113
|
+
for (const ch of [...channels]) {
|
|
114
|
+
if (ch.status === 'authenticated' && ch.epoch !== epoch) {
|
|
115
|
+
// invalid_session: the browser forgets its session token and asks for a new login
|
|
116
|
+
refuse(ch, { type: 'auth-failed', reason: 'invalid_session' });
|
|
117
|
+
revoked.push(ch.connectionId);
|
|
118
|
+
}
|
|
129
119
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
120
|
+
return revoked;
|
|
121
|
+
}
|
|
122
|
+
/** Tests only: forget every channel and the lockout state. */
|
|
123
|
+
export function _resetAuthForTests() {
|
|
124
|
+
for (const ch of channels)
|
|
125
|
+
if (ch.timer)
|
|
126
|
+
clearTimeout(ch.timer);
|
|
127
|
+
channels.clear();
|
|
128
|
+
authState = freshState();
|
|
129
|
+
authStateFile = null;
|
|
130
|
+
}
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// Message handling
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
function onData(ch, data, hooks) {
|
|
135
|
+
if (ch.status === 'closed')
|
|
136
|
+
return;
|
|
137
|
+
if (ch.status === 'authenticated') {
|
|
138
|
+
void handleAuthenticated(ch, data, hooks);
|
|
139
|
+
return;
|
|
134
140
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
+
ch.chain = ch.chain
|
|
142
|
+
.then(() => handlePreAuth(ch, data, hooks))
|
|
143
|
+
.catch((e) => {
|
|
144
|
+
hooks.log.error(`Login handling failed for ${ch.connectionId}: ${e?.stack || e}`);
|
|
145
|
+
refuse(ch, { type: 'auth-failed', reason: 'internal_error' });
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
async function handleAuthenticated(ch, data, hooks) {
|
|
149
|
+
try {
|
|
150
|
+
let msg;
|
|
141
151
|
try {
|
|
142
|
-
|
|
143
|
-
return authSuccess(dc, connectionId);
|
|
152
|
+
msg = JSON.parse(data);
|
|
144
153
|
}
|
|
145
|
-
catch
|
|
146
|
-
|
|
147
|
-
// On expired session, don't count as failure — just prompt for full auth
|
|
148
|
-
if (reason === 'expired_session') {
|
|
149
|
-
dc.send(JSON.stringify({ type: 'auth-failed', reason: 'expired_session' }));
|
|
150
|
-
return 'pending';
|
|
151
|
-
}
|
|
152
|
-
return sendFailure(dc, connectionId, 'invalid_session');
|
|
154
|
+
catch {
|
|
155
|
+
msg = undefined;
|
|
153
156
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const idToken = msg['idToken'];
|
|
158
|
-
const totp = msg['totp'];
|
|
159
|
-
const sessionDays = msg['sessionDays'] || 7;
|
|
160
|
-
const msgNonce = msg['nonce'];
|
|
161
|
-
// Gateway-wide lockout: refuse without checking anything, so no guess is tested
|
|
162
|
-
if (Date.now() < globalLockedUntil) {
|
|
163
|
-
dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
|
|
164
|
-
return 'pending';
|
|
157
|
+
if (!isObject(msg)) {
|
|
158
|
+
ch.dc.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
|
|
159
|
+
return;
|
|
165
160
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
161
|
+
await hooks.onMessage(msg);
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
hooks.log.error(`Message handling failed on ${ch.connectionId}: ${e?.stack || e}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function handlePreAuth(ch, data, hooks) {
|
|
168
|
+
if (ch.status === 'authenticated')
|
|
169
|
+
return handleAuthenticated(ch, data, hooks); // queued behind the login
|
|
170
|
+
if (ch.status !== 'pending')
|
|
171
|
+
return;
|
|
172
|
+
let msg;
|
|
173
|
+
if (typeof data === 'string' && data.length <= MAX_PREAUTH_MESSAGE_LENGTH) {
|
|
174
|
+
try {
|
|
175
|
+
msg = JSON.parse(data);
|
|
169
176
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
// connector-side factor and the gateway-wide lockout above protects it.
|
|
173
|
-
const skipGoogle = !config.google.clientId || config.google.clientId === 'dev-placeholder'
|
|
174
|
-
|| idToken === 'signaling-verified'
|
|
175
|
-
|| (config.devMode && idToken === 'dev-mode-no-google');
|
|
176
|
-
if (skipGoogle) {
|
|
177
|
-
console.log('[Auth] Skipping Google ID token verification (TOTP-only auth)');
|
|
177
|
+
catch {
|
|
178
|
+
msg = undefined;
|
|
178
179
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
180
|
+
}
|
|
181
|
+
if (!isObject(msg))
|
|
182
|
+
return refuseMalformed(ch, hooks, 'not a JSON object or too large');
|
|
183
|
+
if (msg['type'] === 'auth-session')
|
|
184
|
+
return authSession(ch, msg, hooks);
|
|
185
|
+
if (msg['type'] === 'auth-full')
|
|
186
|
+
return authFull(ch, msg, hooks);
|
|
187
|
+
// Anything else before login is dropped: it never reaches a request handler.
|
|
188
|
+
}
|
|
189
|
+
async function authSession(ch, msg, hooks) {
|
|
190
|
+
const token = msg['sessionToken'];
|
|
191
|
+
if (typeof token !== 'string' || !token || token.length > MAX_TOKEN_LENGTH) {
|
|
192
|
+
return refuseMalformed(ch, hooks, 'bad sessionToken');
|
|
193
|
+
}
|
|
194
|
+
const cfg = hooks.loadAuthConfig();
|
|
195
|
+
if (!cfg.ok)
|
|
196
|
+
return refuseSetup(ch, cfg.reason, hooks);
|
|
197
|
+
const config = cfg.config;
|
|
198
|
+
try {
|
|
199
|
+
verifySessionToken(token, config.sessionSecret, config.userId, config.google.authorizedSub);
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
// On expired session, don't count as failure — just prompt for full auth
|
|
203
|
+
if (e.message === 'expired_session') {
|
|
204
|
+
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'expired_session' }));
|
|
205
|
+
return;
|
|
202
206
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
+
return failure(ch, 'invalid_session');
|
|
208
|
+
}
|
|
209
|
+
succeed(ch, config, hooks, { type: 'auth-ok' });
|
|
210
|
+
}
|
|
211
|
+
async function authFull(ch, msg, hooks) {
|
|
212
|
+
const { idToken, totp, nonce } = msg;
|
|
213
|
+
if (typeof idToken !== 'string' || idToken.length > MAX_TOKEN_LENGTH
|
|
214
|
+
|| typeof totp !== 'string' || totp.length > MAX_CODE_LENGTH
|
|
215
|
+
|| typeof nonce !== 'string') {
|
|
216
|
+
return refuseMalformed(ch, hooks, 'bad auth-full fields');
|
|
217
|
+
}
|
|
218
|
+
const sessionDays = typeof msg['sessionDays'] === 'number' && Number.isFinite(msg['sessionDays']) ? msg['sessionDays'] : 7;
|
|
219
|
+
// Gateway-wide lockout: refuse without checking anything, so no guess is tested
|
|
220
|
+
if (Date.now() < authState.lockedUntil) {
|
|
221
|
+
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (nonce !== ch.nonce)
|
|
225
|
+
return failure(ch, 'nonce_mismatch');
|
|
226
|
+
const before = hooks.loadAuthConfig();
|
|
227
|
+
if (!before.ok)
|
|
228
|
+
return refuseSetup(ch, before.reason, hooks);
|
|
229
|
+
const google = before.config.google;
|
|
230
|
+
// Google ID token check. The frontend sends 'signaling-verified' on purpose
|
|
231
|
+
// (bd29058): login.clawchats.ai already did Google sign-in, so TOTP is the
|
|
232
|
+
// connector-side factor and the gateway-wide lockout above protects it.
|
|
233
|
+
const skipGoogle = !google.clientId || google.clientId === 'dev-placeholder'
|
|
234
|
+
|| idToken === 'signaling-verified'
|
|
235
|
+
|| (before.config.devMode && idToken === 'dev-mode-no-google');
|
|
236
|
+
if (skipGoogle) {
|
|
237
|
+
console.log('[Auth] Skipping Google ID token verification (TOTP-only auth)');
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
const opts = { clientId: google.clientId, authorizedSub: google.authorizedSub, authorizedEmail: google.authorizedEmail };
|
|
241
|
+
try {
|
|
242
|
+
await verifyGoogleIdToken(idToken, opts);
|
|
207
243
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
// Consume the backup code
|
|
215
|
-
config.backupCodeHashes.splice(backupIndex, 1);
|
|
216
|
-
// Caller should persist the updated config
|
|
244
|
+
catch (e) {
|
|
245
|
+
console.error(`[Auth] Google ID token verification failed: ${e.message}`);
|
|
246
|
+
// Retry with fresh JWKS on first failure (key rotation)
|
|
247
|
+
clearJWKSCache();
|
|
248
|
+
try {
|
|
249
|
+
await verifyGoogleIdToken(idToken, opts);
|
|
217
250
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
return sendFailure(dc, connectionId, 'invalid_totp');
|
|
251
|
+
catch {
|
|
252
|
+
return failure(ch, 'invalid_id_token');
|
|
221
253
|
}
|
|
222
254
|
}
|
|
223
|
-
globalFailCount = 0;
|
|
224
|
-
globalLockoutCount = 0;
|
|
225
|
-
// Issue session token
|
|
226
|
-
const sessionToken = issueSessionToken(config.userId, config.google.authorizedSub, sessionDays, config.sessionSecret);
|
|
227
|
-
const expiresAt = new Date(Date.now() + Math.min(Math.max(sessionDays, 1), 30) * 86400 * 1000).toISOString();
|
|
228
|
-
clearTimeout(session.timeoutHandle);
|
|
229
|
-
authSessions.delete(connectionId);
|
|
230
|
-
authenticatedConnections.add(connectionId);
|
|
231
|
-
dc.send(JSON.stringify({
|
|
232
|
-
type: 'auth-ok',
|
|
233
|
-
sessionToken,
|
|
234
|
-
expiresAt,
|
|
235
|
-
}));
|
|
236
|
-
return 'authenticated';
|
|
237
255
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
256
|
+
if (ch.status !== 'pending')
|
|
257
|
+
return; // closed or timed out while Google was checked
|
|
258
|
+
// Verify against the config on disk now, not the one read before the wait above:
|
|
259
|
+
// a `reauth` in between must not let the old secrets through.
|
|
260
|
+
const cfg = hooks.loadAuthConfig();
|
|
261
|
+
if (!cfg.ok)
|
|
262
|
+
return refuseSetup(ch, cfg.reason, hooks);
|
|
263
|
+
const config = cfg.config;
|
|
264
|
+
if (Date.now() < authState.lockedUntil) { // another channel triggered the lockout meanwhile
|
|
265
|
+
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
|
|
266
|
+
return;
|
|
248
267
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
268
|
+
// Verify TOTP or backup code
|
|
269
|
+
const totpStep = verifyTotp(totp, config.totp.secret, authState.lastUsedTotpStep);
|
|
270
|
+
if (totpStep >= 0) {
|
|
271
|
+
authState.lastUsedTotpStep = totpStep;
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
const backupIndex = config.backupCodeHashes ? verifyBackupCode(totp, config.backupCodeHashes) : -1;
|
|
275
|
+
// A backup code is one-time: it counts only if it was still on disk and is now removed.
|
|
276
|
+
if (backupIndex < 0 || !hooks.consumeBackupCode(config.backupCodeHashes[backupIndex])) {
|
|
277
|
+
recordGlobalFailure();
|
|
278
|
+
hooks.onLoginFailure?.('invalid_totp');
|
|
279
|
+
return failure(ch, 'invalid_totp');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
authState.failCount = 0;
|
|
283
|
+
authState.lockoutCount = 0;
|
|
284
|
+
saveAuthState();
|
|
285
|
+
const sessionToken = issueSessionToken(config.userId, config.google.authorizedSub, sessionDays, config.sessionSecret);
|
|
286
|
+
const expiresAt = new Date(Date.now() + Math.min(Math.max(sessionDays, 1), 30) * 86400 * 1000).toISOString();
|
|
287
|
+
succeed(ch, config, hooks, { type: 'auth-ok', sessionToken, expiresAt });
|
|
256
288
|
}
|
|
257
289
|
// ---------------------------------------------------------------------------
|
|
258
290
|
// Internal helpers
|
|
259
291
|
// ---------------------------------------------------------------------------
|
|
260
|
-
function
|
|
261
|
-
|
|
262
|
-
if (session) {
|
|
263
|
-
clearTimeout(session.timeoutHandle);
|
|
264
|
-
authSessions.delete(connectionId);
|
|
265
|
-
}
|
|
266
|
-
authenticatedConnections.add(connectionId);
|
|
267
|
-
dc.send(JSON.stringify({ type: 'auth-ok' }));
|
|
268
|
-
return 'authenticated';
|
|
292
|
+
function isObject(v) {
|
|
293
|
+
return !!v && typeof v === 'object' && !Array.isArray(v);
|
|
269
294
|
}
|
|
270
|
-
function
|
|
271
|
-
|
|
272
|
-
|
|
295
|
+
function pendingCount() {
|
|
296
|
+
let n = 0;
|
|
297
|
+
for (const ch of channels)
|
|
298
|
+
if (ch.status === 'pending')
|
|
299
|
+
n++;
|
|
300
|
+
return n;
|
|
301
|
+
}
|
|
302
|
+
function succeed(ch, config, hooks, ok) {
|
|
303
|
+
if (ch.timer)
|
|
304
|
+
clearTimeout(ch.timer);
|
|
305
|
+
ch.status = 'authenticated';
|
|
306
|
+
ch.epoch = authEpoch(config);
|
|
307
|
+
ch.dc.send(JSON.stringify(ok));
|
|
308
|
+
hooks.onAuthenticated();
|
|
309
|
+
}
|
|
310
|
+
/** Wrong credentials: tell the browser; too many on one channel closes it. */
|
|
311
|
+
function failure(ch, reason) {
|
|
312
|
+
ch.failCount++;
|
|
313
|
+
if (ch.failCount >= MAX_FAILURES)
|
|
314
|
+
return refuse(ch, { type: 'auth-failed', reason: 'rate_limited' });
|
|
315
|
+
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason }));
|
|
316
|
+
}
|
|
317
|
+
function refuseSetup(ch, reason, hooks) {
|
|
318
|
+
hooks.log.warn(`Browser ${ch.connectionId} refused: ${reason === 'needs-2fa' ? 'TOTP not set up' : `ClawChats config ${reason}`}. Run: openclaw clawchats reauth`);
|
|
319
|
+
refuse(ch, { type: 'auth-required-setup', message: SETUP_MESSAGES[reason] });
|
|
320
|
+
}
|
|
321
|
+
function refuseMalformed(ch, hooks, why) {
|
|
322
|
+
hooks.log.warn(`Browser ${ch.connectionId} closed: malformed login message (${why})`);
|
|
323
|
+
refuse(ch, { type: 'auth-failed', reason: 'invalid_request' });
|
|
324
|
+
}
|
|
325
|
+
/** Send a last message and close the channel. No further message on it is handled. */
|
|
326
|
+
function refuse(ch, last) {
|
|
327
|
+
if (ch.status === 'closed')
|
|
273
328
|
return;
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
329
|
+
detach(ch);
|
|
330
|
+
try {
|
|
331
|
+
ch.dc.send(JSON.stringify(last));
|
|
332
|
+
}
|
|
333
|
+
catch { /* already gone */ }
|
|
334
|
+
try {
|
|
335
|
+
ch.dc.close();
|
|
336
|
+
}
|
|
337
|
+
catch { /* already gone */ }
|
|
279
338
|
}
|
|
280
|
-
function
|
|
281
|
-
|
|
282
|
-
if (
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
339
|
+
function detach(ch) {
|
|
340
|
+
ch.status = 'closed';
|
|
341
|
+
if (ch.timer)
|
|
342
|
+
clearTimeout(ch.timer);
|
|
343
|
+
channels.delete(ch);
|
|
344
|
+
}
|
|
345
|
+
function recordGlobalFailure() {
|
|
346
|
+
authState.failCount++;
|
|
347
|
+
if (authState.failCount >= GLOBAL_MAX_FAILURES) {
|
|
348
|
+
const duration = Math.min(GLOBAL_LOCKOUT_BASE_MS * 2 ** authState.lockoutCount, GLOBAL_LOCKOUT_MAX_MS);
|
|
349
|
+
authState.lockedUntil = Date.now() + duration;
|
|
350
|
+
authState.lockoutCount++;
|
|
351
|
+
authState.failCount = 0;
|
|
352
|
+
console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed TOTP attempts — full auth locked for ${duration / 1000}s`);
|
|
291
353
|
}
|
|
292
|
-
|
|
293
|
-
return 'pending';
|
|
354
|
+
saveAuthState();
|
|
294
355
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chunk-reassembly.ts — reassembly of chunked browser messages (rpc-chunk-req, gateway-msg-chunk)
|
|
3
|
+
*
|
|
4
|
+
* The browser splits messages over the DataChannel size limit into chunks
|
|
5
|
+
* { id, index, total, data }. Every field is checked and memory is bounded: per message,
|
|
6
|
+
* across all messages, and in time (a message not complete within 30 s is dropped).
|
|
7
|
+
*/
|
|
8
|
+
/** One chunk's data: at most one DataChannel message. */
|
|
9
|
+
export declare const MAX_CHUNK_DATA_LENGTH: number;
|
|
10
|
+
/** One reassembled message (string length; uploads arrive base64-encoded). */
|
|
11
|
+
export declare const MAX_MESSAGE_LENGTH: number;
|
|
12
|
+
/** All messages being reassembled at once. */
|
|
13
|
+
export declare const MAX_BUFFERED_LENGTH: number;
|
|
14
|
+
export declare const MAX_CHUNKS = 4096;
|
|
15
|
+
export type ChunkResult = {
|
|
16
|
+
done: string;
|
|
17
|
+
} | {
|
|
18
|
+
error: string;
|
|
19
|
+
} | null;
|
|
20
|
+
export declare class ChunkReassembler {
|
|
21
|
+
private readonly limits;
|
|
22
|
+
private readonly bufs;
|
|
23
|
+
private buffered;
|
|
24
|
+
constructor(limits?: {
|
|
25
|
+
message: number;
|
|
26
|
+
buffered: number;
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Add one chunk from a connection. Returns the whole message once every chunk is in,
|
|
30
|
+
* an error for an invalid chunk (that message is dropped), or null while waiting.
|
|
31
|
+
*/
|
|
32
|
+
add(connectionId: string, msg: Record<string, unknown>): ChunkResult;
|
|
33
|
+
/** Forget a closed connection's partial messages. */
|
|
34
|
+
dropConnection(connectionId: string): void;
|
|
35
|
+
/** Characters held in partial messages (tests). */
|
|
36
|
+
get bufferedLength(): number;
|
|
37
|
+
private drop;
|
|
38
|
+
}
|