@modelriver/cli 1.2.5 → 2.0.0

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.
@@ -0,0 +1,361 @@
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const config = require('./config');
6
+
7
+ const { CONFIG_DIR_MODE, CONFIG_FILE_MODE } = config;
8
+
9
+ const FILE_NAME = 'tool-sessions.json';
10
+ // A saved session with less than this left is not rejoined; a new one is
11
+ // opened instead, so a restarted CLI doesn't run on a session about to end.
12
+ const REUSE_MIN_REMAINING_MS = 60 * 60 * 1000;
13
+ // Every read-modify-write of the file holds <file>.lock (created with O_EXCL),
14
+ // so several CLIs writing at once don't lose each other's records. A lock is
15
+ // held for a few milliseconds. One whose CLI is gone (same machine) is taken
16
+ // over at once; one this old is taken over too (a CLI on another machine
17
+ // sharing the folder, or a process id the system has reused).
18
+ const LOCK_STALE_MS = 5 * 1000;
19
+ // Longer than LOCK_STALE_MS, so a stale lock is always taken over before a
20
+ // CLI gives up waiting.
21
+ const LOCK_TIMEOUT_MS = 6 * 1000;
22
+ const LOCK_RETRY_MIN_MS = 5;
23
+ const LOCK_RETRY_MAX_MS = 100;
24
+
25
+ function sleepSync(ms) {
26
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
27
+ }
28
+
29
+ /** Whether a process with this id is running on this machine. */
30
+ function processAlive(pid) {
31
+ if (pid === process.pid) return true;
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ } catch (error) {
36
+ return error.code === 'EPERM'; // running, as another user
37
+ }
38
+ }
39
+ // How many forwarded call ids are kept per session (oldest forgotten first).
40
+ const FORWARDED_LIMIT = 1000;
41
+
42
+ /**
43
+ * The `modelriver tools` sessions this machine opened, so a CLI that was
44
+ * stopped or restarted rejoins the session it had instead of opening a new
45
+ * one: requests that already name the session keep working.
46
+ *
47
+ * Kept in <config dir>/tool-sessions.json (default ~/.modelriver), readable
48
+ * only by you (0600, in a 0700 folder): a session token works like a
49
+ * password while it is valid. Each session is filed under a hash of the API
50
+ * URL, the API key and the --forward-to origin, so it is only reused for the
51
+ * same account and the same local server. The API key itself is not stored.
52
+ *
53
+ * Each record also lists the calls already forwarded to the local server, so
54
+ * a restarted CLI never forwards one of them a second time.
55
+ */
56
+ class ToolSessionStore {
57
+ /**
58
+ * @param {object} [options]
59
+ * @param {string} [options.dir] - folder for the file (default: the config folder)
60
+ * @param {Function} [options.now] - () => ms since epoch
61
+ * @param {number} [options.lockTimeoutMs] - how long to wait for the lock
62
+ */
63
+ constructor({ dir = config.getConfigDir(), now = Date.now, lockTimeoutMs = LOCK_TIMEOUT_MS } = {}) {
64
+ this.lockTimeoutMs = lockTimeoutMs;
65
+ this.dir = dir;
66
+ this.file = path.join(dir, FILE_NAME);
67
+ this.lockFile = `${this.file}.lock`;
68
+ this.now = now;
69
+ }
70
+
71
+ /**
72
+ * Make the folder 0700 and the file 0600 if they are looser (an older CLI,
73
+ * a copy or a restore may have left them readable by others).
74
+ */
75
+ tightenPermissions() {
76
+ for (const [target, mode] of [[this.dir, CONFIG_DIR_MODE], [this.file, CONFIG_FILE_MODE]]) {
77
+ try {
78
+ const stat = fs.statSync(target);
79
+ if ((stat.mode & 0o777) !== mode) fs.chmodSync(target, mode);
80
+ } catch (error) {
81
+ // Missing, or not ours to change: nothing to do.
82
+ }
83
+ }
84
+ }
85
+
86
+ ensureDir() {
87
+ if (!fs.existsSync(this.dir)) {
88
+ fs.mkdirSync(this.dir, { recursive: true, mode: CONFIG_DIR_MODE });
89
+ }
90
+ fs.chmodSync(this.dir, CONFIG_DIR_MODE);
91
+ }
92
+
93
+ /**
94
+ * Run fn while holding the lock file, so no other CLI reads or writes the
95
+ * session file in between. Works across processes: the lock is created
96
+ * with O_EXCL. A stale lock (see LOCK_STALE_MS) is taken over.
97
+ * @param {Function} fn
98
+ * @returns {*} fn's result
99
+ */
100
+ withLock(fn) {
101
+ this.ensureDir();
102
+ // Written in the lock: who holds it, so a crashed holder is seen at once,
103
+ // and a random part, so a CLI only ever removes its own lock.
104
+ const token = `${process.pid} ${os.hostname()} ${crypto.randomBytes(8).toString('hex')}`;
105
+ const deadline = Date.now() + this.lockTimeoutMs;
106
+ let wait = LOCK_RETRY_MIN_MS;
107
+ for (;;) {
108
+ let fd;
109
+ try {
110
+ fd = fs.openSync(this.lockFile, 'wx', CONFIG_FILE_MODE);
111
+ } catch (error) {
112
+ if (error.code !== 'EEXIST') throw error;
113
+ if (this.removeStaleLock()) continue;
114
+ if (Date.now() >= deadline) {
115
+ throw new Error(`Timed out waiting for ${this.lockFile}; another "modelriver tools" is holding it`);
116
+ }
117
+ sleepSync(wait + Math.floor(Math.random() * wait));
118
+ wait = Math.min(wait * 2, LOCK_RETRY_MAX_MS);
119
+ continue;
120
+ }
121
+
122
+ try {
123
+ try {
124
+ fs.writeSync(fd, `${token}\n`);
125
+ } finally {
126
+ fs.closeSync(fd);
127
+ }
128
+ } catch (error) {
129
+ // A full disk, say: the lock must not stay behind, held by no one.
130
+ try { fs.unlinkSync(this.lockFile); } catch (unlinkError) { /* already gone */ }
131
+ throw error;
132
+ }
133
+ try {
134
+ return fn();
135
+ } finally {
136
+ this.releaseLock(token);
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Remove the lock if it is still this CLI's. If this CLI was paused long
143
+ * enough for its lock to be taken over, the lock there now is another's.
144
+ * @param {string} token
145
+ */
146
+ releaseLock(token) {
147
+ try {
148
+ const lock = this.readLock();
149
+ if (lock && lock.token === token) fs.unlinkSync(this.lockFile);
150
+ } catch (error) {
151
+ // Gone already, or unreadable: it is taken over once stale.
152
+ }
153
+ }
154
+
155
+ /** @returns {{token: string, mtimeMs: number}|null} the lock, or null when there is none */
156
+ readLock() {
157
+ try {
158
+ const { mtimeMs } = fs.statSync(this.lockFile);
159
+ return { token: fs.readFileSync(this.lockFile, 'utf8').trim(), mtimeMs };
160
+ } catch (error) {
161
+ if (error.code === 'ENOENT') return null;
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Whether a lock was left behind: its CLI's process is gone (a lock
168
+ * written on this machine), or it is older than LOCK_STALE_MS. A lock
169
+ * just created, before its holder wrote in it, is new, so not stale.
170
+ */
171
+ isStale({ token, mtimeMs }) {
172
+ if (Date.now() - mtimeMs >= LOCK_STALE_MS) return true;
173
+ const [pid, host] = token.split(' ');
174
+ if (host === os.hostname() && /^\d+$/.test(pid || '')) return !processAlive(Number(pid));
175
+ return false;
176
+ }
177
+
178
+ /**
179
+ * Remove the lock if it is stale. One CLI at a time does this (it holds
180
+ * <lock>.takeover meanwhile) and checks again that the lock is still the
181
+ * same stale one, so a lock another CLI has just taken is never removed.
182
+ * @returns {boolean} true when the lock is gone and taking it can be tried again
183
+ */
184
+ removeStaleLock() {
185
+ const seen = this.readLock();
186
+ if (!seen) return true; // released meanwhile: try again now
187
+ if (!this.isStale(seen)) return false;
188
+
189
+ const takeover = `${this.lockFile}.takeover`;
190
+ let fd;
191
+ try {
192
+ fd = fs.openSync(takeover, 'wx', CONFIG_FILE_MODE);
193
+ } catch (error) {
194
+ if (error.code !== 'EEXIST') throw error;
195
+ // Another CLI is taking it over. One that crashed while doing so
196
+ // leaves this file: it is removed once it is old.
197
+ try {
198
+ if (Date.now() - fs.statSync(takeover).mtimeMs >= LOCK_STALE_MS) fs.unlinkSync(takeover);
199
+ } catch (statError) { /* gone meanwhile */ }
200
+ return false;
201
+ }
202
+ fs.closeSync(fd);
203
+ try {
204
+ const now = this.readLock();
205
+ if (!now) return true;
206
+ if (now.token !== seen.token || !this.isStale(now)) return false;
207
+ fs.unlinkSync(this.lockFile);
208
+ return true;
209
+ } finally {
210
+ try { fs.unlinkSync(takeover); } catch (error) { /* already gone */ }
211
+ }
212
+ }
213
+
214
+ /**
215
+ * The name a session is filed under.
216
+ * @param {object} what - {apiUrl, apiKey, origin}
217
+ * @returns {string}
218
+ */
219
+ static keyFor({ apiUrl, apiKey, origin }) {
220
+ return crypto
221
+ .createHash('sha256')
222
+ .update([apiUrl, apiKey, origin].map((part) => String(part || '')).join('\0'))
223
+ .digest('hex');
224
+ }
225
+
226
+ readAll() {
227
+ this.tightenPermissions();
228
+ try {
229
+ const data = JSON.parse(fs.readFileSync(this.file, 'utf8'));
230
+ const sessions = data && typeof data === 'object' && data.sessions;
231
+ return sessions && typeof sessions === 'object' && !Array.isArray(sessions) ? sessions : {};
232
+ } catch (error) {
233
+ // No file yet, or one that can't be read: nothing saved.
234
+ return {};
235
+ }
236
+ }
237
+
238
+ // Call only inside withLock().
239
+ writeAll(sessions) {
240
+ this.ensureDir();
241
+
242
+ // Written as a new 0600 file and moved into place, so the tokens are never
243
+ // in a file other users can read, even for a moment.
244
+ const tmpPath = `${this.file}.${process.pid}.${Date.now()}.tmp`;
245
+ try {
246
+ fs.writeFileSync(tmpPath, JSON.stringify({ version: 1, sessions }, null, 2), {
247
+ encoding: 'utf8', mode: CONFIG_FILE_MODE, flag: 'wx',
248
+ });
249
+ fs.chmodSync(tmpPath, CONFIG_FILE_MODE);
250
+ fs.renameSync(tmpPath, this.file);
251
+ } catch (error) {
252
+ try { fs.unlinkSync(tmpPath); } catch (cleanupError) { /* already gone */ }
253
+ throw error;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Milliseconds the record has left, or -Infinity when it isn't a session.
259
+ */
260
+ remainingMs(record) {
261
+ if (!record || typeof record !== 'object') return -Infinity;
262
+ if (typeof record.session_id !== 'string' || !record.session_id.startsWith('cts_')) return -Infinity;
263
+ if (typeof record.channel !== 'string' || !record.channel.startsWith('cli_tools:')) return -Infinity;
264
+ const expires = Date.parse(record.expires_at);
265
+ return Number.isFinite(expires) ? expires - this.now() : -Infinity;
266
+ }
267
+
268
+ /** Worth rejoining: at least an hour left. */
269
+ isUsable(record) {
270
+ return this.remainingMs(record) >= REUSE_MIN_REMAINING_MS;
271
+ }
272
+
273
+ /**
274
+ * The saved session for this key, if it has at least an hour left.
275
+ * @param {string} key - from keyFor()
276
+ * @returns {{session_id: string, channel: string, expires_at: string, project_id: (string|undefined), forwarded: string[]}|null}
277
+ */
278
+ load(key) {
279
+ const record = this.readAll()[key];
280
+ if (!this.isUsable(record)) return null;
281
+ return {
282
+ session_id: record.session_id,
283
+ channel: record.channel,
284
+ expires_at: record.expires_at,
285
+ project_id: record.project_id,
286
+ forwarded: Array.isArray(record.forwarded) ? record.forwarded.filter((id) => typeof id === 'string') : [],
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Save a session the CLI has joined. Expired sessions are dropped from the
292
+ * file at the same time.
293
+ * @param {string} key
294
+ * @param {object} session - {session_id, channel, expires_at, project_id}
295
+ * @param {string[]} [forwarded] - calls already handed to the local server
296
+ * (one can arrive right behind the join, before the session is saved)
297
+ */
298
+ save(key, session, forwarded = []) {
299
+ this.withLock(() => {
300
+ const sessions = this.readAll();
301
+ // Only expired ones: a session with little time left may still be in
302
+ // use by another CLI.
303
+ for (const [name, record] of Object.entries(sessions)) {
304
+ if (this.remainingMs(record) <= 0) delete sessions[name];
305
+ }
306
+ sessions[key] = {
307
+ session_id: session.session_id,
308
+ channel: session.channel,
309
+ expires_at: session.expires_at,
310
+ project_id: session.project_id,
311
+ forwarded: forwarded.filter((id) => typeof id === 'string').slice(-FORWARDED_LIMIT),
312
+ };
313
+ this.writeAll(sessions);
314
+ });
315
+ }
316
+
317
+ /**
318
+ * Record that a call was handed to the local server, before it is sent.
319
+ * @param {string} key
320
+ * @param {string} callId
321
+ * @param {string} [sessionId] - only record it if the saved session is still
322
+ * this one (another CLI may have saved a newer one under the same key)
323
+ */
324
+ addForwarded(key, callId, sessionId) {
325
+ this.withLock(() => {
326
+ const sessions = this.readAll();
327
+ const record = sessions[key];
328
+ if (!record || typeof record !== 'object') return;
329
+ if (sessionId !== undefined && record.session_id !== sessionId) return;
330
+ const forwarded = Array.isArray(record.forwarded) ? record.forwarded : [];
331
+ forwarded.push(callId);
332
+ record.forwarded = forwarded.slice(-FORWARDED_LIMIT);
333
+ this.writeAll(sessions);
334
+ });
335
+ }
336
+
337
+ /**
338
+ * Forget a session that can no longer be joined.
339
+ * @param {string} key
340
+ * @param {string} [sessionId] - only remove the record if it is still this
341
+ * session; another CLI (--new-session) may have saved a newer one under
342
+ * the same key
343
+ * @returns {boolean} whether a record was removed
344
+ */
345
+ remove(key, sessionId) {
346
+ return this.withLock(() => {
347
+ const sessions = this.readAll();
348
+ if (!(key in sessions)) return false;
349
+ if (sessionId !== undefined && (!sessions[key] || sessions[key].session_id !== sessionId)) return false;
350
+ delete sessions[key];
351
+ this.writeAll(sessions);
352
+ return true;
353
+ });
354
+ }
355
+ }
356
+
357
+ module.exports = ToolSessionStore;
358
+ module.exports.FILE_NAME = FILE_NAME;
359
+ module.exports.FORWARDED_LIMIT = FORWARDED_LIMIT;
360
+ module.exports.REUSE_MIN_REMAINING_MS = REUSE_MIN_REMAINING_MS;
361
+ module.exports.LOCK_STALE_MS = LOCK_STALE_MS;
@@ -0,0 +1,141 @@
1
+ const crypto = require('crypto');
2
+
3
+ // Reject calls whose timestamp is more than 5 minutes from now, so an old
4
+ // signed call can't be replayed.
5
+ const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
6
+ const VERSION = 'v2';
7
+
8
+ /**
9
+ * Checks the signature ModelRiver puts on each hosted tool call.
10
+ *
11
+ * This is not the webhook signature (see WebhookVerifier). A tool call signs
12
+ * the exact bytes of the request body together with the timestamp and the
13
+ * call id:
14
+ *
15
+ * x-modelriver-signature: v2=hex(HMAC-SHA256(secret, "v2.<timestamp>.<call id>.<raw body>"))
16
+ *
17
+ * While a signing secret is being rotated, the header carries one value per
18
+ * valid secret, comma-separated, newest first; a call is valid when any of
19
+ * them matches.
20
+ *
21
+ * Use the raw body as received. Parsing the JSON and encoding it again
22
+ * changes the bytes and the signature no longer matches.
23
+ */
24
+ class ToolSignature {
25
+ /**
26
+ * The hex signature for one call (without the "v2=" prefix).
27
+ * @param {string} secret - the project's tool signing secret
28
+ * @param {string|number} timestamp - x-modelriver-timestamp (Unix seconds)
29
+ * @param {string} callId - x-modelriver-tool-call-id
30
+ * @param {string|Buffer} rawBody - the request body exactly as received
31
+ * @returns {string}
32
+ */
33
+ static sign(secret, timestamp, callId, rawBody) {
34
+ const hmac = crypto.createHmac('sha256', secret);
35
+ hmac.update(`${VERSION}.${timestamp}.${callId}.`);
36
+ hmac.update(Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), 'utf8'));
37
+ return hmac.digest('hex');
38
+ }
39
+
40
+ /**
41
+ * The v2 values in an x-modelriver-signature header.
42
+ * @param {string} header - e.g. "v2=abc…" or "v2=abc…,v2=def…"
43
+ * @returns {string[]}
44
+ */
45
+ static parseHeader(header) {
46
+ if (typeof header !== 'string') return [];
47
+ return header
48
+ .split(',')
49
+ .map((part) => part.trim())
50
+ .filter((part) => part.startsWith(`${VERSION}=`))
51
+ .map((part) => part.slice(VERSION.length + 1));
52
+ }
53
+
54
+ /**
55
+ * Is the timestamp (Unix seconds) within `toleranceSeconds` of now?
56
+ * @param {string|number} timestamp
57
+ * @param {object} [options] - {now (ms), toleranceSeconds}
58
+ * @returns {boolean}
59
+ */
60
+ static isTimestampFresh(timestamp, { now = Date.now(), toleranceSeconds = DEFAULT_TOLERANCE_SECONDS } = {}) {
61
+ const text = String(timestamp ?? '').trim();
62
+ if (!/^\d+$/.test(text)) return false;
63
+ const seconds = Number(text);
64
+ if (!Number.isSafeInteger(seconds)) return false;
65
+ return Math.abs(Math.floor(now / 1000) - seconds) <= toleranceSeconds;
66
+ }
67
+
68
+ /**
69
+ * Check signature and timestamp separately.
70
+ *
71
+ * @param {object} call
72
+ * @param {string|string[]} call.secret - one secret, or several (e.g. old and new while you rotate)
73
+ * @param {string|number} call.timestamp - x-modelriver-timestamp
74
+ * @param {string} call.callId - x-modelriver-tool-call-id
75
+ * @param {string|Buffer} call.rawBody - the request body exactly as received
76
+ * @param {string} call.signature - x-modelriver-signature
77
+ * @param {object} [options] - {now (ms), toleranceSeconds}
78
+ * @returns {{valid: boolean, signatureValid: boolean, timestampValid: boolean}}
79
+ */
80
+ static check({ secret, timestamp, callId, rawBody, signature }, options = {}) {
81
+ const secrets = (Array.isArray(secret) ? secret : [secret]).filter((s) => typeof s === 'string' && s !== '');
82
+ const given = this.parseHeader(signature);
83
+ let signatureValid = false;
84
+
85
+ if (secrets.length > 0 && given.length > 0 && typeof callId === 'string' && callId !== '' && rawBody != null) {
86
+ for (const s of secrets) {
87
+ const expected = this.sign(s, String(timestamp ?? ''), callId, rawBody);
88
+ // Compare against every value, so the time taken doesn't say which matched.
89
+ for (const value of given) {
90
+ if (secureCompare(value, expected)) signatureValid = true;
91
+ }
92
+ }
93
+ }
94
+
95
+ const timestampValid = this.isTimestampFresh(timestamp, options);
96
+ return { valid: signatureValid && timestampValid, signatureValid, timestampValid };
97
+ }
98
+
99
+ /**
100
+ * Verify a tool call: a matching v2 signature and a timestamp no more than
101
+ * 5 minutes off.
102
+ * @param {object} call - see check()
103
+ * @param {object} [options] - {now (ms), toleranceSeconds}
104
+ * @returns {boolean}
105
+ */
106
+ static verify(call, options = {}) {
107
+ return this.check(call, options).valid;
108
+ }
109
+
110
+ /**
111
+ * Verify a call from its headers (any object with lower-case header names,
112
+ * such as Node's req.headers or Express's).
113
+ * @param {object} headers
114
+ * @param {string|Buffer} rawBody
115
+ * @param {string|string[]} secret
116
+ * @param {object} [options] - {now (ms), toleranceSeconds}
117
+ * @returns {boolean}
118
+ */
119
+ static verifyRequest(headers, rawBody, secret, options = {}) {
120
+ const h = headers || {};
121
+ return this.verify({
122
+ secret,
123
+ timestamp: h['x-modelriver-timestamp'],
124
+ callId: h['x-modelriver-tool-call-id'],
125
+ rawBody,
126
+ signature: h['x-modelriver-signature'],
127
+ }, options);
128
+ }
129
+ }
130
+
131
+ function secureCompare(left, right) {
132
+ if (typeof left !== 'string' || typeof right !== 'string') return false;
133
+ const a = Buffer.from(left, 'utf8');
134
+ const b = Buffer.from(right, 'utf8');
135
+ if (a.length !== b.length) return false;
136
+ return crypto.timingSafeEqual(a, b);
137
+ }
138
+
139
+ ToolSignature.DEFAULT_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
140
+
141
+ module.exports = ToolSignature;
@@ -1,5 +1,9 @@
1
1
  const crypto = require('crypto');
2
2
 
3
+ // Reject webhooks whose timestamp is more than 5 minutes from now, so an old
4
+ // signed delivery can't be replayed.
5
+ const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
6
+
3
7
  class WebhookVerifier {
4
8
  /**
5
9
  * Generate HMAC-SHA256 signature for webhook payload
@@ -17,40 +21,63 @@ class WebhookVerifier {
17
21
  }
18
22
 
19
23
  /**
20
- * Verify webhook signature
24
+ * Is the timestamp (Unix seconds) within `toleranceSeconds` of now?
25
+ * @param {string|number} timestamp
26
+ * @param {object} [options]
27
+ * @param {number} [options.now] - current time in ms (tests)
28
+ * @param {number} [options.toleranceSeconds]
29
+ * @returns {boolean}
30
+ */
31
+ static isTimestampFresh(timestamp, { now = Date.now(), toleranceSeconds = DEFAULT_TOLERANCE_SECONDS } = {}) {
32
+ const text = String(timestamp ?? '').trim();
33
+ if (!/^\d+$/.test(text)) return false;
34
+ const seconds = Number(text);
35
+ if (!Number.isSafeInteger(seconds)) return false;
36
+ return Math.abs(Math.floor(now / 1000) - seconds) <= toleranceSeconds;
37
+ }
38
+
39
+ /**
40
+ * Check signature and timestamp separately.
41
+ * @returns {{valid: boolean, signatureValid: boolean, timestampValid: boolean}}
42
+ */
43
+ static check(providedSignature, payload, secret, timestamp, options = {}) {
44
+ const expectedSignature = this.generateSignature(payload, secret, timestamp);
45
+ const signatureValid = this.secureCompare(providedSignature, expectedSignature);
46
+ const timestampValid = this.isTimestampFresh(timestamp, options);
47
+ return { valid: signatureValid && timestampValid, signatureValid, timestampValid };
48
+ }
49
+
50
+ /**
51
+ * Verify webhook signature and that the timestamp is no more than 5 minutes off.
21
52
  * @param {string} providedSignature - Signature from X-ModelRiver-Signature header
22
53
  * @param {object} payload - The payload.data object from webhook body
23
54
  * @param {string} secret - Webhook secret
24
- * @param {string|number} timestamp - Timestamp from X-ModelRiver-Timestamp header
25
- * @returns {boolean} - True if signature is valid
55
+ * @param {string|number} timestamp - Timestamp from X-ModelRiver-Timestamp header (Unix seconds)
56
+ * @param {object} [options] - {now, toleranceSeconds}
57
+ * @returns {boolean} - True if signature is valid and the timestamp is fresh
26
58
  */
27
- static verify(providedSignature, payload, secret, timestamp) {
28
- const expectedSignature = this.generateSignature(payload, secret, timestamp);
29
- return this.secureCompare(providedSignature, expectedSignature);
59
+ static verify(providedSignature, payload, secret, timestamp, options = {}) {
60
+ return this.check(providedSignature, payload, secret, timestamp, options).valid;
30
61
  }
31
62
 
32
63
  /**
33
64
  * Constant-time comparison to prevent timing attacks
34
- * Matches backend implementation
35
65
  */
36
66
  static secureCompare(left, right) {
37
67
  if (typeof left !== 'string' || typeof right !== 'string') {
38
68
  return false;
39
69
  }
40
70
 
41
- if (left.length !== right.length) {
71
+ const a = Buffer.from(left, 'utf8');
72
+ const b = Buffer.from(right, 'utf8');
73
+ if (a.length !== b.length) {
42
74
  return false;
43
75
  }
44
76
 
45
- let result = 0;
46
- for (let i = 0; i < left.length; i++) {
47
- result |= left.charCodeAt(i) ^ right.charCodeAt(i);
48
- }
49
-
50
- return result === 0;
77
+ return crypto.timingSafeEqual(a, b);
51
78
  }
52
79
  }
53
80
 
54
- module.exports = WebhookVerifier;
55
-
81
+ WebhookVerifier.DEFAULT_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
56
82
 
83
+ module.exports = WebhookVerifier;
@@ -1,4 +1,5 @@
1
1
  const WebSocket = require('ws');
2
+ const { checkWebSocketUrl } = require('../utils/url-helpers');
2
3
 
3
4
  class WebSocketClient {
4
5
  constructor(websocketUrl, token, verbose = false) {
@@ -8,6 +9,7 @@ class WebSocketClient {
8
9
  this.ws = null;
9
10
  this.channel = null;
10
11
  this.listeners = {};
12
+ this.eventListeners = new Map(); // event -> handler(payload)
11
13
  this.heartbeatInterval = null;
12
14
  this.heartbeatRef = 0;
13
15
  }
@@ -18,6 +20,13 @@ class WebSocketClient {
18
20
  */
19
21
  connect() {
20
22
  return new Promise((resolve, reject) => {
23
+ try {
24
+ // Refuse a URL that isn't wss (ws is allowed only for localhost).
25
+ checkWebSocketUrl(this.websocketUrl);
26
+ } catch (error) {
27
+ reject(error);
28
+ return;
29
+ }
21
30
  const url = `${this.websocketUrl}/websocket?token=${encodeURIComponent(this.token)}`;
22
31
 
23
32
  this.ws = new WebSocket(url);
@@ -62,6 +71,8 @@ class WebSocketClient {
62
71
  this.ws.send(heartbeat);
63
72
  }
64
73
  }, 30000); // Every 30 seconds
74
+ // The heartbeat alone must not keep the process alive.
75
+ if (this.heartbeatInterval.unref) this.heartbeatInterval.unref();
65
76
  }
66
77
 
67
78
  /**
@@ -97,6 +108,7 @@ class WebSocketClient {
97
108
  });
98
109
 
99
110
  let resolved = false;
111
+ let joinTimer = null;
100
112
 
101
113
  // Set up a temporary listener for the join response
102
114
  // This will process the response and then be removed
@@ -108,6 +120,7 @@ class WebSocketClient {
108
120
  // Look for the join response (phx_reply with our ref)
109
121
  if (msg.event === 'phx_reply' && msg.ref === joinRef && msg.topic === channelName) {
110
122
  resolved = true;
123
+ clearTimeout(joinTimer);
111
124
  // Remove this listener - handleMessage() will continue processing other messages
112
125
  this.ws.removeListener('message', handleJoinResponse);
113
126
 
@@ -130,7 +143,7 @@ class WebSocketClient {
130
143
  this.ws.send(joinMsg);
131
144
 
132
145
  // Timeout after 10 seconds
133
- setTimeout(() => {
146
+ joinTimer = setTimeout(() => {
134
147
  if (!resolved) {
135
148
  resolved = true;
136
149
  this.ws.removeListener('message', handleJoinResponse);
@@ -164,8 +177,10 @@ class WebSocketClient {
164
177
  }
165
178
  }
166
179
  } else {
167
- // In non-verbose mode, only log non-standard events
168
- if (msg.event !== 'phx_reply' && msg.event !== 'heartbeat' && msg.event !== 'response') {
180
+ // In non-verbose mode, only log non-standard events (events with
181
+ // their own handler print themselves)
182
+ if (msg.event !== 'phx_reply' && msg.event !== 'heartbeat' && msg.event !== 'response' &&
183
+ !this.eventListeners.has(msg.event)) {
169
184
  Logger.info(`received event: ${msg.event} on topic: ${msg.topic}`);
170
185
  }
171
186
  }
@@ -180,6 +195,8 @@ class WebSocketClient {
180
195
  } else if (this.verbose) {
181
196
  Logger.warning(`⚠️ Response event received but no listener registered!`);
182
197
  }
198
+ } else if (this.eventListeners.has(msg.event)) {
199
+ this.eventListeners.get(msg.event)(msg.payload || {});
183
200
  } else if (msg.event === 'phx_reply') {
184
201
  // Handle join responses
185
202
  if (this.listeners.join) {
@@ -203,6 +220,15 @@ class WebSocketClient {
203
220
  this.listeners.response = callback;
204
221
  }
205
222
 
223
+ /**
224
+ * Listen for one other server event (e.g. "tool_approval_required").
225
+ * @param {string} event
226
+ * @param {Function} callback - (payload) => void
227
+ */
228
+ onEvent(event, callback) {
229
+ this.eventListeners.set(event, callback);
230
+ }
231
+
206
232
  /**
207
233
  * Listen for close events
208
234
  * @param {Function} callback - Callback function