@clawchatsai/connector 0.1.49 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -6
- package/dist/auth-handler.d.ts +41 -20
- package/dist/auth-handler.js +136 -106
- package/dist/channel-binding.d.ts +57 -0
- package/dist/channel-binding.js +73 -0
- package/dist/config-store.d.ts +14 -6
- package/dist/config-store.js +58 -11
- package/dist/devices-cli.d.ts +16 -0
- package/dist/devices-cli.js +90 -0
- package/dist/index.js +76 -16
- package/dist/plugin-config.d.ts +12 -0
- package/dist/session-token.d.ts +6 -39
- package/dist/session-token.js +6 -95
- package/dist/shim.js +13 -10
- package/dist/totp.d.ts +8 -0
- package/dist/totp.js +16 -0
- package/dist/webrtc-peer.d.ts +2 -0
- package/dist/webrtc-peer.js +15 -1
- package/package.json +1 -1
- package/server/approval-client.test.js +1 -1
- package/server/controllers/title.js +3 -1
- package/server/controllers/title.test.js +8 -1
- package/server/gateway.js +21 -3
- package/server/gateway.test.js +44 -0
- package/server/history-export.js +5 -1
- package/server/history-export.test.js +63 -0
- package/server/index.js +4 -1
- package/server/peer/guest-agent.js +41 -8
- package/server/peer/guest-agent.test.js +50 -1
- package/server/peer/keys.js +12 -0
- package/server/peer/sharing.js +17 -3
- package/server/peer/sharing.test.js +42 -4
- package/server/peer/wordlist.js +3 -0
- package/server/team.js +15 -6
- package/server/team.test.js +48 -4
- package/server/util/gateway-retry.js +58 -0
- package/server/util/gateway-retry.test.js +78 -0
- package/server/util/redact.js +84 -0
- package/server/util/redact.test.js +97 -0
- package/dist/google-jwt.d.ts +0 -34
- package/dist/google-jwt.js +0 -87
package/README.md
CHANGED
|
@@ -34,14 +34,22 @@ The signaling server only facilitates the handshake. After step 4, it is out of
|
|
|
34
34
|
Requires OpenClaw 2026.9.7 or newer on the machine that runs your gateway.
|
|
35
35
|
|
|
36
36
|
```bash
|
|
37
|
-
openclaw plugins install
|
|
37
|
+
openclaw gateway stop && openclaw plugins install npm:@clawchatsai/connector --force --accept-capabilities && openclaw gateway start
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
This stops the gateway for a moment, installs the plugin, and starts the gateway again with it loaded.
|
|
41
|
+
Stopping first avoids the install failing with a gateway ownership or lock error, which happens for
|
|
42
|
+
example when OpenClaw was updated but the running gateway is still the old version.
|
|
42
43
|
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
- `--force` confirms the npm source, which is outside ClawHub review.
|
|
45
|
+
- `--accept-capabilities` approves the capabilities the plugin declares (review them with
|
|
46
|
+
`openclaw plugins inspect connector`).
|
|
47
|
+
- Keep the `npm:` prefix: since OpenClaw 2026.11, a package name without a prefix is looked up only
|
|
48
|
+
on ClawHub, and the install fails with "Package not found on ClawHub".
|
|
49
|
+
|
|
50
|
+
If your gateway runs in a container where stopping it also stops the container, run the install
|
|
51
|
+
without the stop and start: `openclaw plugins install npm:@clawchatsai/connector --force`. A running
|
|
52
|
+
gateway loads the plugin right away.
|
|
45
53
|
|
|
46
54
|
Then connect it to your ClawChats account:
|
|
47
55
|
|
|
@@ -92,7 +100,7 @@ src/ # OpenClaw plugin wrapper (TypeScript)
|
|
|
92
100
|
|
|
93
101
|
**Session cleanup:** When a thread or workspace is deleted, the plugin removes the associated OpenClaw session files (`.jsonl`) to prevent stale context. These are files created by the gateway itself during that session.
|
|
94
102
|
|
|
95
|
-
**Auth:**
|
|
103
|
+
**Auth:** Before any data is processed, the connector proves its identity to the browser (a signature over the WebRTC connection's DTLS fingerprints, made with the connector's own key), then the browser logs in by signing the same data with its device key. A new browser pairs once with a TOTP or backup code. There is no session token. Manage paired browsers with `openclaw clawchats devices` and `openclaw clawchats devices revoke <id|label>`; compare the connector key with `openclaw clawchats show-fingerprint`. The HTTP API uses a local bearer token (set via `CLAWCHATS_AUTH_TOKEN` or `config.js`). No credentials are sent to external servers.
|
|
96
104
|
|
|
97
105
|
**No shell execution:** The plugin contains no `exec`, `spawn`, or shell calls. SQLite is handled by Node's built-in `node:sqlite` module — no native binary compilation required.
|
|
98
106
|
|
package/dist/auth-handler.d.ts
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* auth-handler.ts — DataChannel authentication gate
|
|
2
|
+
* auth-handler.ts — DataChannel authentication gate (device keys, authVersion 2)
|
|
3
3
|
*
|
|
4
4
|
* Every browser DataChannel goes through attachBrowserChannel() before anything else sees it:
|
|
5
5
|
* 1. Refuse (message + close) unless the config on disk is complete with TOTP set up
|
|
6
|
-
* 2. Send auth-required
|
|
7
|
-
*
|
|
6
|
+
* 2. Send auth-required: a random nonce, this connector's public key, and its signature over the
|
|
7
|
+
* channel (nonce, connection id, both DTLS fingerprints). The browser checks that first, so
|
|
8
|
+
* it never sends anything to a relay that terminated DTLS on its own.
|
|
9
|
+
* 3. Wait for auth-device (a paired browser signing the same channel data with its device key)
|
|
10
|
+
* or auth-pair (a new browser: its public key, proven with a TOTP/backup code that is bound
|
|
11
|
+
* to the channel and never sent), validating every field
|
|
8
12
|
* 4. Verify against the config as it is on disk at that moment
|
|
9
|
-
* 5.
|
|
13
|
+
* 5. Only then are messages handed to the request handlers
|
|
14
|
+
* There is no bearer token: nothing a browser sends can be replayed on another channel.
|
|
10
15
|
* A channel that does not log in within 60 s, fails too often or sends malformed login
|
|
11
|
-
* messages is closed.
|
|
16
|
+
* messages is closed. Failed pairings and failed device signatures count towards a lockout that
|
|
17
|
+
* survives a restart (auth-state.json).
|
|
12
18
|
*
|
|
13
|
-
* Spec:
|
|
19
|
+
* Spec: specs/device-keys-auth.md (clawchats repo)
|
|
14
20
|
*/
|
|
15
21
|
import { type AuthConfigResult } from './config-store.js';
|
|
22
|
+
import type { PairedDevice } from './plugin-config.js';
|
|
16
23
|
export interface AuthConfig {
|
|
17
24
|
userId: string;
|
|
18
25
|
totp: {
|
|
@@ -22,15 +29,9 @@ export interface AuthConfig {
|
|
|
22
29
|
period: number;
|
|
23
30
|
enabledAt: string;
|
|
24
31
|
};
|
|
25
|
-
google: {
|
|
26
|
-
clientId: string;
|
|
27
|
-
authorizedSub: string;
|
|
28
|
-
authorizedEmail: string;
|
|
29
|
-
};
|
|
30
|
-
sessionSecret: string;
|
|
31
32
|
backupCodeHashes?: string[];
|
|
32
|
-
/**
|
|
33
|
-
|
|
33
|
+
/** Paired browsers. */
|
|
34
|
+
devices: PairedDevice[];
|
|
34
35
|
}
|
|
35
36
|
/** The DataChannel surface the gate needs (webrtc-peer.ts DataChannelLike). */
|
|
36
37
|
export interface AuthChannel {
|
|
@@ -39,16 +40,34 @@ export interface AuthChannel {
|
|
|
39
40
|
onMessage(handler: (data: string) => void): void;
|
|
40
41
|
onClosed(handler: () => void): void;
|
|
41
42
|
}
|
|
43
|
+
/** DTLS fingerprints of the two certificates on this connection, from the SDPs (64 hex digits each). */
|
|
44
|
+
export interface DtlsFingerprints {
|
|
45
|
+
browser: string;
|
|
46
|
+
connector: string;
|
|
47
|
+
}
|
|
42
48
|
export interface BrowserChannelHooks {
|
|
43
49
|
/** Fresh read of the login settings from disk. Called on open and again at every verification. */
|
|
44
50
|
loadAuthConfig: () => AuthConfigResult;
|
|
45
51
|
/** Remove one backup code (by hash) from the config on disk; false if it is no longer there. */
|
|
46
52
|
consumeBackupCode: (hash: string) => boolean;
|
|
47
|
-
/**
|
|
48
|
-
|
|
53
|
+
/** This connector's identity (server/peer/keys.js): the public key (SPKI base64) and Ed25519 signing. */
|
|
54
|
+
connectorKey: {
|
|
55
|
+
publicKey: string;
|
|
56
|
+
sign: (data: string) => string;
|
|
57
|
+
};
|
|
58
|
+
/** Save a newly paired device in the config on disk, if its TOTP secret is still `totpSecret` (the one the code was checked against). */
|
|
59
|
+
addDevice: (device: PairedDevice, totpSecret: string) => 'ok' | 'full' | 'gone' | 'stale';
|
|
60
|
+
/** A paired device logged in (updates its lastSeen; failures are not the login's problem). */
|
|
61
|
+
touchDevice: (deviceId: string) => void;
|
|
62
|
+
/** The channel logged in. `paired`: this login added the device. */
|
|
63
|
+
onAuthenticated: (info: {
|
|
64
|
+
deviceId: string;
|
|
65
|
+
label: string;
|
|
66
|
+
paired: boolean;
|
|
67
|
+
}) => void;
|
|
49
68
|
/** A message on a logged-in channel. Errors (thrown or rejected) are logged, never propagated. */
|
|
50
69
|
onMessage: (msg: Record<string, unknown>) => void | Promise<void>;
|
|
51
|
-
/** A wrong
|
|
70
|
+
/** A wrong code or signature was tried (for telling already logged-in browsers). */
|
|
52
71
|
onLoginFailure?: (reason: string) => void;
|
|
53
72
|
log: {
|
|
54
73
|
info: (m: string) => void;
|
|
@@ -65,11 +84,13 @@ export declare function loadAuthState(file: string): void;
|
|
|
65
84
|
/**
|
|
66
85
|
* Put a new browser DataChannel behind the login gate. Nothing reaches hooks.onMessage
|
|
67
86
|
* before the channel has logged in.
|
|
87
|
+
* @param dtls both certificates' fingerprints as this side sees them in the SDPs; without both
|
|
88
|
+
* the channel cannot be bound and is refused.
|
|
68
89
|
*/
|
|
69
|
-
export declare function attachBrowserChannel(dc: AuthChannel, connectionId: string, hooks: BrowserChannelHooks): void;
|
|
90
|
+
export declare function attachBrowserChannel(dc: AuthChannel, connectionId: string, hooks: BrowserChannelHooks, dtls?: DtlsFingerprints): void;
|
|
70
91
|
/**
|
|
71
|
-
* The config on disk changed: close logged-in channels whose
|
|
72
|
-
* (`reauth`, `reset`, a deleted or broken config). Returns their connection ids.
|
|
92
|
+
* The config on disk changed: close logged-in channels whose device is no longer paired
|
|
93
|
+
* (`devices revoke`, `reauth`, `reset`, a deleted or broken config). Returns their connection ids.
|
|
73
94
|
*/
|
|
74
95
|
export declare function revokeStaleChannels(current: AuthConfigResult): string[];
|
|
75
96
|
/** Tests only: forget every channel and the lockout state. */
|
package/dist/auth-handler.js
CHANGED
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* auth-handler.ts — DataChannel authentication gate
|
|
2
|
+
* auth-handler.ts — DataChannel authentication gate (device keys, authVersion 2)
|
|
3
3
|
*
|
|
4
4
|
* Every browser DataChannel goes through attachBrowserChannel() before anything else sees it:
|
|
5
5
|
* 1. Refuse (message + close) unless the config on disk is complete with TOTP set up
|
|
6
|
-
* 2. Send auth-required
|
|
7
|
-
*
|
|
6
|
+
* 2. Send auth-required: a random nonce, this connector's public key, and its signature over the
|
|
7
|
+
* channel (nonce, connection id, both DTLS fingerprints). The browser checks that first, so
|
|
8
|
+
* it never sends anything to a relay that terminated DTLS on its own.
|
|
9
|
+
* 3. Wait for auth-device (a paired browser signing the same channel data with its device key)
|
|
10
|
+
* or auth-pair (a new browser: its public key, proven with a TOTP/backup code that is bound
|
|
11
|
+
* to the channel and never sent), validating every field
|
|
8
12
|
* 4. Verify against the config as it is on disk at that moment
|
|
9
|
-
* 5.
|
|
13
|
+
* 5. Only then are messages handed to the request handlers
|
|
14
|
+
* There is no bearer token: nothing a browser sends can be replayed on another channel.
|
|
10
15
|
* A channel that does not log in within 60 s, fails too often or sends malformed login
|
|
11
|
-
* messages is closed.
|
|
16
|
+
* messages is closed. Failed pairings and failed device signatures count towards a lockout that
|
|
17
|
+
* survives a restart (auth-state.json).
|
|
12
18
|
*
|
|
13
|
-
* Spec:
|
|
19
|
+
* Spec: specs/device-keys-auth.md (clawchats repo)
|
|
14
20
|
*/
|
|
15
21
|
import * as crypto from 'node:crypto';
|
|
16
22
|
import * as fs from 'node:fs';
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { authEpoch, writeFileAtomic } from './config-store.js';
|
|
23
|
+
import { totpCandidates } from './totp.js';
|
|
24
|
+
import { writeFileAtomic, MAX_DEVICES } from './config-store.js';
|
|
25
|
+
import { AUTH_VERSION, transcript, deviceIdOf, verifyEd25519, isEd25519Spki, pairProof, proofEquals, } from './channel-binding.js';
|
|
21
26
|
// ---------------------------------------------------------------------------
|
|
22
27
|
// Limits
|
|
23
28
|
// ---------------------------------------------------------------------------
|
|
@@ -27,8 +32,8 @@ export const MAX_PENDING_CHANNELS = 10;
|
|
|
27
32
|
export const AUTH_TIMEOUT_MS = 60_000; // enough time to open authenticator app and enter code
|
|
28
33
|
const MAX_FAILURES = 5; // per channel, then it is closed
|
|
29
34
|
const MAX_PREAUTH_MESSAGE_LENGTH = 16 * 1024;
|
|
30
|
-
const
|
|
31
|
-
const
|
|
35
|
+
const MAX_SIG_LENGTH = 200; // Ed25519 signatures are 88 base64 characters
|
|
36
|
+
const MAX_LABEL_LENGTH = 64;
|
|
32
37
|
const GLOBAL_MAX_FAILURES = 5;
|
|
33
38
|
const GLOBAL_LOCKOUT_BASE_MS = 60_000; // doubles per consecutive lockout
|
|
34
39
|
const GLOBAL_LOCKOUT_MAX_MS = 60 * 60_000;
|
|
@@ -37,6 +42,12 @@ const SETUP_MESSAGES = {
|
|
|
37
42
|
invalid: 'The ClawChats login settings on your gateway are incomplete or damaged. Run "openclaw clawchats reauth" on your gateway machine.',
|
|
38
43
|
missing: 'ClawChats is not set up on your gateway. Run "openclaw clawchats setup <token>" on your gateway machine.',
|
|
39
44
|
};
|
|
45
|
+
/**
|
|
46
|
+
* What a browser that still has the old login (session tokens, authVersion 1) is told. It shows
|
|
47
|
+
* a gateway's `auth-required-setup` text as is; its "reconnect" button reloads the page, which
|
|
48
|
+
* fetches the new frontend. (Other `auth-failed` reasons it does not know are silently ignored.)
|
|
49
|
+
*/
|
|
50
|
+
const OLD_FRONTEND_MESSAGE = 'This connector was updated and your browser still has the old ClawChats app. Reload the page (Ctrl+Shift+R) to get the new version, then pair this browser with a code from your authenticator app.';
|
|
40
51
|
// ---------------------------------------------------------------------------
|
|
41
52
|
// Module state
|
|
42
53
|
// ---------------------------------------------------------------------------
|
|
@@ -79,41 +90,63 @@ function saveAuthState() {
|
|
|
79
90
|
/**
|
|
80
91
|
* Put a new browser DataChannel behind the login gate. Nothing reaches hooks.onMessage
|
|
81
92
|
* before the channel has logged in.
|
|
93
|
+
* @param dtls both certificates' fingerprints as this side sees them in the SDPs; without both
|
|
94
|
+
* the channel cannot be bound and is refused.
|
|
82
95
|
*/
|
|
83
|
-
export function attachBrowserChannel(dc, connectionId, hooks) {
|
|
84
|
-
const ch = { connectionId, dc, status: 'pending',
|
|
96
|
+
export function attachBrowserChannel(dc, connectionId, hooks, dtls) {
|
|
97
|
+
const ch = { connectionId, dc, status: 'pending', binding: null, failCount: 0, chain: Promise.resolve() };
|
|
85
98
|
dc.onClosed(() => detach(ch));
|
|
86
99
|
const cfg = hooks.loadAuthConfig();
|
|
87
100
|
if (!cfg.ok) {
|
|
88
101
|
refuseSetup(ch, cfg.reason, hooks);
|
|
89
102
|
return;
|
|
90
103
|
}
|
|
104
|
+
if (!dtls?.browser || !dtls.connector) {
|
|
105
|
+
hooks.log.warn(`Browser ${connectionId} refused: could not read the DTLS fingerprints from the SDP`);
|
|
106
|
+
refuse(ch, { type: 'auth-failed', reason: 'no_channel_binding' });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
91
109
|
if (pendingCount() >= MAX_PENDING_CHANNELS) {
|
|
92
110
|
hooks.log.warn(`Browser ${connectionId} refused: ${MAX_PENDING_CHANNELS} connections are already waiting to log in`);
|
|
93
111
|
refuse(ch, { type: 'auth-failed', reason: 'rate_limited' });
|
|
94
112
|
return;
|
|
95
113
|
}
|
|
96
114
|
channels.add(ch);
|
|
97
|
-
|
|
115
|
+
const { publicKey, sign } = hooks.connectorKey;
|
|
116
|
+
ch.binding = {
|
|
117
|
+
nonce: crypto.randomBytes(32).toString('hex'),
|
|
118
|
+
connectionId,
|
|
119
|
+
browserFp: dtls.browser,
|
|
120
|
+
connectorFp: dtls.connector,
|
|
121
|
+
connectorPub: publicKey,
|
|
122
|
+
};
|
|
98
123
|
ch.timer = setTimeout(() => {
|
|
99
124
|
if (ch.status === 'pending')
|
|
100
125
|
refuse(ch, { type: 'auth-failed', reason: 'auth_timeout' });
|
|
101
126
|
}, AUTH_TIMEOUT_MS);
|
|
102
127
|
ch.timer.unref?.();
|
|
103
128
|
dc.onMessage((data) => onData(ch, data, hooks));
|
|
104
|
-
dc.send(JSON.stringify({
|
|
129
|
+
dc.send(JSON.stringify({
|
|
130
|
+
type: 'auth-required',
|
|
131
|
+
authVersion: AUTH_VERSION,
|
|
132
|
+
nonce: ch.binding.nonce,
|
|
133
|
+
connectorKey: publicKey,
|
|
134
|
+
connectorSig: sign(transcript('connector', ch.binding)),
|
|
135
|
+
}));
|
|
105
136
|
}
|
|
106
137
|
/**
|
|
107
|
-
* The config on disk changed: close logged-in channels whose
|
|
108
|
-
* (`reauth`, `reset`, a deleted or broken config). Returns their connection ids.
|
|
138
|
+
* The config on disk changed: close logged-in channels whose device is no longer paired
|
|
139
|
+
* (`devices revoke`, `reauth`, `reset`, a deleted or broken config). Returns their connection ids.
|
|
109
140
|
*/
|
|
110
141
|
export function revokeStaleChannels(current) {
|
|
111
|
-
const epoch = current.ok ? authEpoch(current.config) : null;
|
|
112
142
|
const revoked = [];
|
|
113
143
|
for (const ch of [...channels]) {
|
|
114
|
-
if (ch.status
|
|
115
|
-
|
|
116
|
-
|
|
144
|
+
if (ch.status !== 'authenticated')
|
|
145
|
+
continue;
|
|
146
|
+
const still = current.ok && current.config.devices.some(d => d.deviceId === ch.device?.deviceId && d.pubkey === ch.device?.pubkey);
|
|
147
|
+
if (!still) {
|
|
148
|
+
// device_revoked: the browser asks for a new pairing
|
|
149
|
+
refuse(ch, { type: 'auth-failed', reason: 'device_revoked' });
|
|
117
150
|
revoked.push(ch.connectionId);
|
|
118
151
|
}
|
|
119
152
|
}
|
|
@@ -180,111 +213,108 @@ async function handlePreAuth(ch, data, hooks) {
|
|
|
180
213
|
}
|
|
181
214
|
if (!isObject(msg))
|
|
182
215
|
return refuseMalformed(ch, hooks, 'not a JSON object or too large');
|
|
183
|
-
if (msg['type'] === 'auth-
|
|
184
|
-
return
|
|
185
|
-
if (msg['type'] === 'auth-
|
|
186
|
-
return
|
|
216
|
+
if (msg['type'] === 'auth-device')
|
|
217
|
+
return authDevice(ch, msg, hooks);
|
|
218
|
+
if (msg['type'] === 'auth-pair')
|
|
219
|
+
return authPair(ch, msg, hooks);
|
|
220
|
+
if (msg['type'] === 'auth-session' || msg['type'] === 'auth-full') {
|
|
221
|
+
// The old login. Never honoured, whatever it carries.
|
|
222
|
+
hooks.log.warn(`Browser ${ch.connectionId} refused: it uses the old login (session token); it needs the new ClawChats app`);
|
|
223
|
+
return refuse(ch, { type: 'auth-required-setup', message: OLD_FRONTEND_MESSAGE });
|
|
224
|
+
}
|
|
187
225
|
// Anything else before login is dropped: it never reaches a request handler.
|
|
188
226
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
227
|
+
/** A paired browser: its signature over this channel, made with the device key. */
|
|
228
|
+
function authDevice(ch, msg, hooks) {
|
|
229
|
+
const { deviceId, sig } = msg;
|
|
230
|
+
if (typeof deviceId !== 'string' || !/^[0-9a-f]{32}$/.test(deviceId) || typeof sig !== 'string' || sig.length > MAX_SIG_LENGTH) {
|
|
231
|
+
return refuseMalformed(ch, hooks, 'bad auth-device fields');
|
|
193
232
|
}
|
|
194
233
|
const cfg = hooks.loadAuthConfig();
|
|
195
234
|
if (!cfg.ok)
|
|
196
235
|
return refuseSetup(ch, cfg.reason, hooks);
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
236
|
+
const device = cfg.config.devices.find(d => d.deviceId === deviceId);
|
|
237
|
+
if (!device)
|
|
238
|
+
return failure(ch, 'unknown_device'); // revoked, or never paired: the browser offers pairing
|
|
239
|
+
if (!verifyEd25519(device.pubkey, transcript('device', ch.binding, device.pubkey), sig)) {
|
|
240
|
+
recordGlobalFailure();
|
|
241
|
+
hooks.onLoginFailure?.('invalid_signature');
|
|
242
|
+
return failure(ch, 'invalid_signature');
|
|
200
243
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
if (e.message === 'expired_session') {
|
|
204
|
-
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'expired_session' }));
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
return failure(ch, 'invalid_session');
|
|
208
|
-
}
|
|
209
|
-
succeed(ch, config, hooks, { type: 'auth-ok' });
|
|
244
|
+
hooks.touchDevice(device.deviceId);
|
|
245
|
+
succeed(ch, device, false, hooks);
|
|
210
246
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|| typeof
|
|
216
|
-
|
|
247
|
+
/** A new browser: its public key, signed, with a proof of the one-time code that is tied to this channel. */
|
|
248
|
+
function authPair(ch, msg, hooks) {
|
|
249
|
+
const { devicePub, label, kind, proof, sig } = msg;
|
|
250
|
+
if (!isEd25519Spki(devicePub)
|
|
251
|
+
|| typeof label !== 'string' || !label.trim() || label.length > MAX_LABEL_LENGTH
|
|
252
|
+
|| (kind !== 'totp' && kind !== 'backup')
|
|
253
|
+
|| typeof proof !== 'string' || !/^[0-9a-f]{64}$/.test(proof)
|
|
254
|
+
|| typeof sig !== 'string' || sig.length > MAX_SIG_LENGTH) {
|
|
255
|
+
return refuseMalformed(ch, hooks, 'bad auth-pair fields');
|
|
217
256
|
}
|
|
218
|
-
const sessionDays = typeof msg['sessionDays'] === 'number' && Number.isFinite(msg['sessionDays']) ? msg['sessionDays'] : 7;
|
|
219
257
|
// Gateway-wide lockout: refuse without checking anything, so no guess is tested
|
|
220
258
|
if (Date.now() < authState.lockedUntil) {
|
|
221
259
|
ch.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
|
|
222
260
|
return;
|
|
223
261
|
}
|
|
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);
|
|
243
|
-
}
|
|
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);
|
|
250
|
-
}
|
|
251
|
-
catch {
|
|
252
|
-
return failure(ch, 'invalid_id_token');
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
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
262
|
const cfg = hooks.loadAuthConfig();
|
|
261
263
|
if (!cfg.ok)
|
|
262
264
|
return refuseSetup(ch, cfg.reason, hooks);
|
|
263
265
|
const config = cfg.config;
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
return;
|
|
266
|
+
const deviceId = deviceIdOf(devicePub);
|
|
267
|
+
if (config.devices.length >= MAX_DEVICES && !config.devices.some(d => d.deviceId === deviceId)) {
|
|
268
|
+
return failure(ch, 'too_many_devices');
|
|
267
269
|
}
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
270
|
+
// The signature proves the sender holds the private half of devicePub and that label and key
|
|
271
|
+
// were not swapped in transit; the proof below ties the code to this channel and this key.
|
|
272
|
+
const signed = transcript('pair', ch.binding, devicePub, label);
|
|
273
|
+
if (!verifyEd25519(devicePub, signed, sig)) {
|
|
274
|
+
recordGlobalFailure();
|
|
275
|
+
hooks.onLoginFailure?.('invalid_signature');
|
|
276
|
+
return failure(ch, 'invalid_signature');
|
|
277
|
+
}
|
|
278
|
+
let step = -1;
|
|
279
|
+
let backupHash = null;
|
|
280
|
+
if (kind === 'totp') {
|
|
281
|
+
for (const cand of totpCandidates(config.totp.secret, authState.lastUsedTotpStep)) {
|
|
282
|
+
if (proofEquals(pairProof(cand.code, signed), proof)) {
|
|
283
|
+
step = cand.step;
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
272
287
|
}
|
|
273
288
|
else {
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
return failure(ch, 'invalid_totp');
|
|
289
|
+
for (const hash of config.backupCodeHashes ?? []) {
|
|
290
|
+
if (proofEquals(pairProof(hash, signed), proof)) {
|
|
291
|
+
backupHash = hash;
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
280
294
|
}
|
|
281
295
|
}
|
|
296
|
+
if (step >= 0) {
|
|
297
|
+
authState.lastUsedTotpStep = step;
|
|
298
|
+
}
|
|
299
|
+
else if (!backupHash || !hooks.consumeBackupCode(backupHash)) {
|
|
300
|
+
// A backup code is one-time: it counts only if it was still on disk and is now removed.
|
|
301
|
+
recordGlobalFailure();
|
|
302
|
+
hooks.onLoginFailure?.('invalid_code');
|
|
303
|
+
return failure(ch, 'invalid_code');
|
|
304
|
+
}
|
|
282
305
|
authState.failCount = 0;
|
|
283
306
|
authState.lockoutCount = 0;
|
|
284
307
|
saveAuthState();
|
|
285
|
-
const
|
|
286
|
-
const
|
|
287
|
-
|
|
308
|
+
const now = new Date().toISOString();
|
|
309
|
+
const device = { deviceId, pubkey: devicePub, label: label.trim(), createdAt: now, lastSeen: now };
|
|
310
|
+
const added = hooks.addDevice(device, config.totp.secret);
|
|
311
|
+
if (added === 'gone')
|
|
312
|
+
return refuseSetup(ch, 'missing', hooks);
|
|
313
|
+
if (added === 'full')
|
|
314
|
+
return failure(ch, 'too_many_devices');
|
|
315
|
+
if (added === 'stale')
|
|
316
|
+
return failure(ch, 'invalid_code'); // `reauth` ran while the code was being checked
|
|
317
|
+
succeed(ch, device, true, hooks);
|
|
288
318
|
}
|
|
289
319
|
// ---------------------------------------------------------------------------
|
|
290
320
|
// Internal helpers
|
|
@@ -299,13 +329,13 @@ function pendingCount() {
|
|
|
299
329
|
n++;
|
|
300
330
|
return n;
|
|
301
331
|
}
|
|
302
|
-
function succeed(ch,
|
|
332
|
+
function succeed(ch, device, paired, hooks) {
|
|
303
333
|
if (ch.timer)
|
|
304
334
|
clearTimeout(ch.timer);
|
|
305
335
|
ch.status = 'authenticated';
|
|
306
|
-
ch.
|
|
307
|
-
ch.dc.send(JSON.stringify(ok));
|
|
308
|
-
hooks.onAuthenticated();
|
|
336
|
+
ch.device = { deviceId: device.deviceId, pubkey: device.pubkey };
|
|
337
|
+
ch.dc.send(JSON.stringify({ type: 'auth-ok', deviceId: device.deviceId, label: device.label, paired }));
|
|
338
|
+
hooks.onAuthenticated({ deviceId: device.deviceId, label: device.label, paired });
|
|
309
339
|
}
|
|
310
340
|
/** Wrong credentials: tell the browser; too many on one channel closes it. */
|
|
311
341
|
function failure(ch, reason) {
|
|
@@ -349,7 +379,7 @@ function recordGlobalFailure() {
|
|
|
349
379
|
authState.lockedUntil = Date.now() + duration;
|
|
350
380
|
authState.lockoutCount++;
|
|
351
381
|
authState.failCount = 0;
|
|
352
|
-
console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed
|
|
382
|
+
console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed login attempts — pairing locked for ${duration / 1000}s`);
|
|
353
383
|
}
|
|
354
384
|
saveAuthState();
|
|
355
385
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* channel-binding.ts — what the connector and a browser sign to log in over a DataChannel
|
|
3
|
+
*
|
|
4
|
+
* The signaling server brokers the WebRTC connection and is not trusted. Both sides therefore
|
|
5
|
+
* sign a transcript that contains the DTLS fingerprints each of them sees in the SDP. A relay
|
|
6
|
+
* that terminates DTLS separately towards each side sees different fingerprints on each leg, so a
|
|
7
|
+
* signature made on one leg does not verify on the other.
|
|
8
|
+
*
|
|
9
|
+
* The browser has the same code (frontend/connection/device-auth.js). tests pin both to the same
|
|
10
|
+
* test vectors; change them together and bump AUTH_DOMAIN.
|
|
11
|
+
*
|
|
12
|
+
* Spec: specs/device-keys-auth.md (clawchats repo)
|
|
13
|
+
*/
|
|
14
|
+
/** Protocol version announced in auth-required. 1 (no field) = the old session-token login. */
|
|
15
|
+
export declare const AUTH_VERSION = 2;
|
|
16
|
+
/** Domain separation: a signature made for anything else never verifies here, and the reverse. */
|
|
17
|
+
export declare const AUTH_DOMAIN = "clawchats-auth-v2";
|
|
18
|
+
export type SignRole = 'connector' | 'device' | 'pair';
|
|
19
|
+
/** What both sides know about one channel. Fingerprints are 64 upper-case hex digits. */
|
|
20
|
+
export interface ChannelBinding {
|
|
21
|
+
/** Random per channel, chosen by the connector. */
|
|
22
|
+
nonce: string;
|
|
23
|
+
/** The signaling server's connection id (a label: both sides must agree on it). */
|
|
24
|
+
connectionId: string;
|
|
25
|
+
/** DTLS fingerprint of the browser's certificate: the one in the browser's offer. */
|
|
26
|
+
browserFp: string;
|
|
27
|
+
/** DTLS fingerprint of the connector's certificate: the one in the connector's answer. */
|
|
28
|
+
connectorFp: string;
|
|
29
|
+
/** The connector's Ed25519 public key (SPKI, base64). */
|
|
30
|
+
connectorPub: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The single `a=fingerprint:sha-256` of an SDP as 64 upper-case hex digits; "" unless there is
|
|
34
|
+
* exactly one distinct value (no fingerprint, or two to choose from, cannot be bound to).
|
|
35
|
+
*/
|
|
36
|
+
export declare function sdpFingerprint(sdp: string | undefined | null): string;
|
|
37
|
+
/** The exact string that gets signed. A JSON array of strings: no field can run into the next. */
|
|
38
|
+
export declare function transcript(role: SignRole, b: ChannelBinding, devicePub?: string, label?: string): string;
|
|
39
|
+
/** Id of a device key: first 16 bytes of SHA-256 over its SPKI, hex. Derived, so no one can claim another's. */
|
|
40
|
+
export declare function deviceIdOf(devicePub: string): string;
|
|
41
|
+
/** Does `sig` (base64) sign `data` under the Ed25519 key `pub` (SPKI, base64)? */
|
|
42
|
+
export declare function verifyEd25519(pub: string, data: string, sig: string): boolean;
|
|
43
|
+
/** Is this a well-formed Ed25519 SPKI public key (base64)? */
|
|
44
|
+
export declare function isEd25519Spki(pub: unknown): pub is string;
|
|
45
|
+
/** Short comparable fingerprint of a public key, same format as the sharing keys: `abcd-ef01-…` (5 groups). */
|
|
46
|
+
export declare const publicKeyFingerprint: (pub: string) => string;
|
|
47
|
+
/** The same key as four words (what pairing screens show first); see server/peer/keys.js. */
|
|
48
|
+
export declare const publicKeyWords: (pub: string) => string;
|
|
49
|
+
/**
|
|
50
|
+
* Proof that the sender knew the one-time code, tied to this channel and device key. The code
|
|
51
|
+
* itself is never sent. Key = the 6 digits (TOTP) or the stored hash of the backup code.
|
|
52
|
+
* A relay without the code cannot make one; one with the proof can still try all 10^6 codes
|
|
53
|
+
* offline, so this is a binding, not a PAKE (see the spec's residual risks).
|
|
54
|
+
*/
|
|
55
|
+
export declare function pairProof(key: string, message: string): string;
|
|
56
|
+
/** Constant-time comparison of two hex proofs. */
|
|
57
|
+
export declare function proofEquals(a: string, b: string): boolean;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* channel-binding.ts — what the connector and a browser sign to log in over a DataChannel
|
|
3
|
+
*
|
|
4
|
+
* The signaling server brokers the WebRTC connection and is not trusted. Both sides therefore
|
|
5
|
+
* sign a transcript that contains the DTLS fingerprints each of them sees in the SDP. A relay
|
|
6
|
+
* that terminates DTLS separately towards each side sees different fingerprints on each leg, so a
|
|
7
|
+
* signature made on one leg does not verify on the other.
|
|
8
|
+
*
|
|
9
|
+
* The browser has the same code (frontend/connection/device-auth.js). tests pin both to the same
|
|
10
|
+
* test vectors; change them together and bump AUTH_DOMAIN.
|
|
11
|
+
*
|
|
12
|
+
* Spec: specs/device-keys-auth.md (clawchats repo)
|
|
13
|
+
*/
|
|
14
|
+
import * as crypto from 'node:crypto';
|
|
15
|
+
// @ts-expect-error — server/ is plain JS with no .d.ts
|
|
16
|
+
import { verifySignature, fingerprint as keyFingerprint, fingerprintWords } from '../server/peer/keys.js';
|
|
17
|
+
/** Protocol version announced in auth-required. 1 (no field) = the old session-token login. */
|
|
18
|
+
export const AUTH_VERSION = 2;
|
|
19
|
+
/** Domain separation: a signature made for anything else never verifies here, and the reverse. */
|
|
20
|
+
export const AUTH_DOMAIN = 'clawchats-auth-v2';
|
|
21
|
+
/**
|
|
22
|
+
* The single `a=fingerprint:sha-256` of an SDP as 64 upper-case hex digits; "" unless there is
|
|
23
|
+
* exactly one distinct value (no fingerprint, or two to choose from, cannot be bound to).
|
|
24
|
+
*/
|
|
25
|
+
export function sdpFingerprint(sdp) {
|
|
26
|
+
const found = new Set();
|
|
27
|
+
for (const m of String(sdp || '').matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){31})[ \t]*\r?$/gm)) {
|
|
28
|
+
found.add(m[1].replace(/:/g, '').toUpperCase());
|
|
29
|
+
}
|
|
30
|
+
return found.size === 1 ? [...found][0] : '';
|
|
31
|
+
}
|
|
32
|
+
/** The exact string that gets signed. A JSON array of strings: no field can run into the next. */
|
|
33
|
+
export function transcript(role, b, devicePub = '', label = '') {
|
|
34
|
+
return JSON.stringify([AUTH_DOMAIN, role, b.nonce, b.connectionId, b.browserFp, b.connectorFp, b.connectorPub, devicePub, label]);
|
|
35
|
+
}
|
|
36
|
+
/** Id of a device key: first 16 bytes of SHA-256 over its SPKI, hex. Derived, so no one can claim another's. */
|
|
37
|
+
export function deviceIdOf(devicePub) {
|
|
38
|
+
return crypto.createHash('sha256').update(Buffer.from(devicePub, 'base64')).digest('hex').slice(0, 32);
|
|
39
|
+
}
|
|
40
|
+
/** Does `sig` (base64) sign `data` under the Ed25519 key `pub` (SPKI, base64)? */
|
|
41
|
+
export function verifyEd25519(pub, data, sig) {
|
|
42
|
+
return typeof pub === 'string' && typeof sig === 'string' && !!verifySignature(pub, data, sig);
|
|
43
|
+
}
|
|
44
|
+
/** Is this a well-formed Ed25519 SPKI public key (base64)? */
|
|
45
|
+
export function isEd25519Spki(pub) {
|
|
46
|
+
if (typeof pub !== 'string' || pub.length > 128)
|
|
47
|
+
return false;
|
|
48
|
+
try {
|
|
49
|
+
const key = crypto.createPublicKey({ key: Buffer.from(pub, 'base64'), format: 'der', type: 'spki' });
|
|
50
|
+
return key.asymmetricKeyType === 'ed25519' && Buffer.from(pub, 'base64').toString('base64') === pub;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Short comparable fingerprint of a public key, same format as the sharing keys: `abcd-ef01-…` (5 groups). */
|
|
57
|
+
export const publicKeyFingerprint = keyFingerprint;
|
|
58
|
+
/** The same key as four words (what pairing screens show first); see server/peer/keys.js. */
|
|
59
|
+
export const publicKeyWords = fingerprintWords;
|
|
60
|
+
/**
|
|
61
|
+
* Proof that the sender knew the one-time code, tied to this channel and device key. The code
|
|
62
|
+
* itself is never sent. Key = the 6 digits (TOTP) or the stored hash of the backup code.
|
|
63
|
+
* A relay without the code cannot make one; one with the proof can still try all 10^6 codes
|
|
64
|
+
* offline, so this is a binding, not a PAKE (see the spec's residual risks).
|
|
65
|
+
*/
|
|
66
|
+
export function pairProof(key, message) {
|
|
67
|
+
return crypto.createHmac('sha256', key).update(message).digest('hex');
|
|
68
|
+
}
|
|
69
|
+
/** Constant-time comparison of two hex proofs. */
|
|
70
|
+
export function proofEquals(a, b) {
|
|
71
|
+
return typeof a === 'string' && typeof b === 'string' && a.length === b.length
|
|
72
|
+
&& crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
73
|
+
}
|