@jaw.id/cli 0.0.3 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/base-command.js +1 -2
  2. package/dist/base-command.js.map +1 -1
  3. package/dist/commands/config/set.js +19 -3
  4. package/dist/commands/config/set.js.map +1 -1
  5. package/dist/commands/config/show.js +1 -2
  6. package/dist/commands/config/show.js.map +1 -1
  7. package/dist/commands/disconnect.js +439 -36
  8. package/dist/commands/disconnect.js.map +1 -1
  9. package/dist/commands/mcp/index.js +472 -218
  10. package/dist/commands/mcp/index.js.map +1 -1
  11. package/dist/commands/rpc/call.js +429 -204
  12. package/dist/commands/rpc/call.js.map +1 -1
  13. package/dist/commands/version.js +134 -0
  14. package/dist/commands/version.js.map +1 -0
  15. package/dist/index.js +455 -203
  16. package/dist/index.js.map +1 -1
  17. package/dist/lib/bridge-singleton.js +457 -205
  18. package/dist/lib/bridge-singleton.js.map +1 -1
  19. package/dist/lib/config.js +17 -2
  20. package/dist/lib/config.js.map +1 -1
  21. package/dist/lib/crypto.js +74 -0
  22. package/dist/lib/crypto.js.map +1 -0
  23. package/dist/lib/paths.js +1 -2
  24. package/dist/lib/paths.js.map +1 -1
  25. package/dist/lib/session-store.js +1 -2
  26. package/dist/lib/session-store.js.map +1 -1
  27. package/dist/lib/validation.js +12 -1
  28. package/dist/lib/validation.js.map +1 -1
  29. package/dist/lib/ws-bridge.js +321 -59
  30. package/dist/lib/ws-bridge.js.map +1 -1
  31. package/dist/mcp/handlers/config.js +17 -2
  32. package/dist/mcp/handlers/config.js.map +1 -1
  33. package/dist/mcp/handlers/daemon.js +446 -46
  34. package/dist/mcp/handlers/daemon.js.map +1 -1
  35. package/dist/mcp/handlers/rpc.js +429 -204
  36. package/dist/mcp/handlers/rpc.js.map +1 -1
  37. package/dist/mcp/server.js +472 -218
  38. package/dist/mcp/server.js.map +1 -1
  39. package/oclif.manifest.json +70 -2
  40. package/package.json +5 -1
  41. package/dist/lib/ws-daemon.js +0 -382
  42. package/dist/lib/ws-daemon.js.map +0 -1
@@ -1,10 +1,8 @@
1
1
  import * as fs2 from 'fs';
2
+ import * as crypto from 'crypto';
2
3
  import * as path from 'path';
3
- import 'url';
4
- import { execSync } from 'child_process';
5
4
  import * as os from 'os';
6
- import 'crypto';
7
- import 'ws';
5
+ import WebSocket from 'ws';
8
6
  import { z } from 'zod';
9
7
 
10
8
  // src/mcp/handlers/daemon.ts
@@ -26,8 +24,7 @@ var PATHS = {
26
24
  root: JAW_DIR,
27
25
  config: path.join(JAW_DIR, "config.json"),
28
26
  session: path.join(JAW_DIR, "session.json"),
29
- bridge: path.join(JAW_DIR, "bridge.json"),
30
- daemonLog: path.join(JAW_DIR, "daemon.log")
27
+ relay: path.join(JAW_DIR, "relay.json")
31
28
  };
32
29
  function loadConfig() {
33
30
  if (!fs2.existsSync(PATHS.config)) {
@@ -49,53 +46,459 @@ function redactConfig(config) {
49
46
  };
50
47
  }
51
48
 
52
- // src/lib/bridge-singleton.ts
53
- path.join(PATHS.root, "daemon.lock");
54
- function isDaemonProcess(pid) {
55
- if (!Number.isInteger(pid) || pid <= 0 || pid > 4194304) return false;
56
- try {
57
- process.kill(pid, 0);
58
- } catch {
59
- return false;
49
+ // src/lib/crypto.ts
50
+ var subtle = globalThis.crypto.subtle;
51
+ async function deriveSharedSecret(privateKey, peerPublicKey) {
52
+ return subtle.deriveKey(
53
+ { name: "ECDH", public: peerPublicKey },
54
+ privateKey,
55
+ { name: "AES-GCM", length: 256 },
56
+ false,
57
+ ["encrypt", "decrypt"]
58
+ );
59
+ }
60
+ async function encryptMessage(sharedSecret, payload) {
61
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
62
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
63
+ const cipherBuf = await subtle.encrypt(
64
+ { name: "AES-GCM", iv },
65
+ sharedSecret,
66
+ plaintext
67
+ );
68
+ return {
69
+ iv: bufferToBase64(iv),
70
+ ciphertext: bufferToBase64(new Uint8Array(cipherBuf))
71
+ };
72
+ }
73
+ async function decryptMessage(sharedSecret, envelope) {
74
+ const iv = Buffer.from(envelope.iv, "base64");
75
+ const ciphertext = Buffer.from(envelope.ciphertext, "base64");
76
+ const plainBuf = await subtle.decrypt(
77
+ { name: "AES-GCM", iv },
78
+ sharedSecret,
79
+ ciphertext
80
+ );
81
+ return JSON.parse(new TextDecoder().decode(plainBuf));
82
+ }
83
+ async function importKeyFromHex(type, hex) {
84
+ const format = type === "private" ? "pkcs8" : "spki";
85
+ return subtle.importKey(
86
+ format,
87
+ Buffer.from(hexToBytes(hex)),
88
+ { name: "ECDH", namedCurve: "P-256" },
89
+ true,
90
+ type === "private" ? ["deriveKey"] : []
91
+ );
92
+ }
93
+ function hexToBytes(hex) {
94
+ if (hex.length % 2 !== 0) throw new Error("Invalid hex: odd length");
95
+ const bytes = new Uint8Array(hex.length / 2);
96
+ for (let i = 0; i < hex.length; i += 2) {
97
+ bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
98
+ }
99
+ return bytes;
100
+ }
101
+ function bufferToBase64(buf) {
102
+ return Buffer.from(buf).toString("base64");
103
+ }
104
+
105
+ // src/lib/ws-bridge.ts
106
+ var DEFAULT_TIMEOUT_MS = 12e4;
107
+ var MAX_MESSAGE_BYTES = 5 * 1024 * 1024;
108
+ var BROWSER_REOPEN_COOLDOWN_MS = 5e3;
109
+ var MAX_RECONNECT_ATTEMPTS = 3;
110
+ var RECONNECT_BASE_DELAY_MS = 1e3;
111
+ var WSBridge = class {
112
+ relayUrl;
113
+ session;
114
+ timeout;
115
+ config;
116
+ privateKeyHex;
117
+ publicKeyHex;
118
+ peerPublicKeyHex;
119
+ sharedSecret = null;
120
+ ws = null;
121
+ disposed = false;
122
+ // Auto-reopen browser state
123
+ onBrowserNeeded;
124
+ onPeerKeyChanged;
125
+ lastBrowserOpenTime = 0;
126
+ // Reconnection state
127
+ reconnectAttempts = 0;
128
+ /** Updated after key exchange — caller should persist this. */
129
+ get peerPublicKey() {
130
+ return this.peerPublicKeyHex;
131
+ }
132
+ constructor(options) {
133
+ this.relayUrl = options.relayUrl;
134
+ this.session = options.session;
135
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
136
+ this.config = options.config;
137
+ this.privateKeyHex = options.privateKeyHex;
138
+ this.publicKeyHex = options.publicKeyHex;
139
+ this.peerPublicKeyHex = options.peerPublicKeyHex;
140
+ }
141
+ /**
142
+ * Connect to the relay and wait for the browser to be ready.
143
+ *
144
+ * @param onBrowserNeeded — called when the relay reports no browser connected.
145
+ * @param onPeerKeyChanged — called when a key_exchange updates the peer key.
146
+ */
147
+ async connect(onBrowserNeeded, onPeerKeyChanged) {
148
+ this.onBrowserNeeded = onBrowserNeeded;
149
+ this.onPeerKeyChanged = onPeerKeyChanged;
150
+ if (this.peerPublicKeyHex) {
151
+ await this.deriveSecret();
152
+ }
153
+ return this.connectInternal(onBrowserNeeded, onPeerKeyChanged);
154
+ }
155
+ async connectInternal(onBrowserNeeded, onPeerKeyChanged) {
156
+ return new Promise((resolve, reject) => {
157
+ const url = `${this.relayUrl}?session=${encodeURIComponent(this.session)}&role=cli`;
158
+ const ws = new WebSocket(url);
159
+ let browserOpened = false;
160
+ let resolved = false;
161
+ let expectingKeyExchange = !this.peerPublicKeyHex;
162
+ const timer = setTimeout(() => {
163
+ ws.close();
164
+ reject(
165
+ new Error(
166
+ "Browser did not connect in time.\nRun `jaw disconnect` then try again."
167
+ )
168
+ );
169
+ }, 3e4);
170
+ const sendEncryptedInit = async () => {
171
+ if (!this.sharedSecret) return;
172
+ const envelope = await encryptMessage(this.sharedSecret, {
173
+ type: "init",
174
+ apiKey: this.config.apiKey,
175
+ chainId: this.config.chainId,
176
+ ens: this.config.ens,
177
+ paymasterUrl: this.config.paymasterUrl
178
+ });
179
+ this.sendRaw(ws, JSON.stringify({ type: "encrypted", ...envelope }));
180
+ };
181
+ const waitForReady = () => {
182
+ const readyTimer = setTimeout(() => {
183
+ ws.close();
184
+ reject(new Error("Browser SDK did not become ready in time."));
185
+ }, 15e3);
186
+ const onMsg = async (data) => {
187
+ const msg = safeParse(data);
188
+ if (!msg) return;
189
+ if (msg.type === "encrypted" && this.sharedSecret) {
190
+ try {
191
+ const inner = await decryptMessage(
192
+ this.sharedSecret,
193
+ msg
194
+ );
195
+ if (inner.type === "ready") {
196
+ clearTimeout(readyTimer);
197
+ ws.off("message", onMsg);
198
+ this.reconnectAttempts = 0;
199
+ resolve();
200
+ }
201
+ } catch {
202
+ }
203
+ }
204
+ };
205
+ ws.on("message", onMsg);
206
+ };
207
+ const onBrowserReady = async () => {
208
+ if (resolved) return;
209
+ resolved = true;
210
+ clearTimeout(timer);
211
+ waitForReady();
212
+ await sendEncryptedInit();
213
+ };
214
+ ws.on("open", () => {
215
+ this.ws = ws;
216
+ });
217
+ ws.on("message", async (data) => {
218
+ const msg = safeParse(data);
219
+ if (!msg) return;
220
+ if (msg.type === "status") {
221
+ if (msg.browserConnected) {
222
+ if (this.sharedSecret) {
223
+ await onBrowserReady();
224
+ } else {
225
+ expectingKeyExchange = true;
226
+ }
227
+ } else if (!browserOpened && onBrowserNeeded) {
228
+ browserOpened = true;
229
+ expectingKeyExchange = true;
230
+ onBrowserNeeded().catch(() => {
231
+ });
232
+ }
233
+ } else if (msg.type === "browser_connected") {
234
+ expectingKeyExchange = true;
235
+ } else if (msg.type === "browser_disconnected") {
236
+ this.handleBrowserDisconnect();
237
+ } else if (msg.type === "key_exchange" && expectingKeyExchange) {
238
+ expectingKeyExchange = false;
239
+ const peerKey = msg.publicKey;
240
+ this.peerPublicKeyHex = peerKey;
241
+ await this.deriveSecret();
242
+ onPeerKeyChanged?.(peerKey);
243
+ await onBrowserReady();
244
+ }
245
+ });
246
+ ws.on("error", (err) => {
247
+ clearTimeout(timer);
248
+ reject(err);
249
+ });
250
+ ws.on("close", () => {
251
+ clearTimeout(timer);
252
+ if (!this.disposed) {
253
+ this.handleRelayDisconnect();
254
+ }
255
+ });
256
+ });
257
+ }
258
+ /**
259
+ * Send an encrypted RPC request through the relay to the browser SDK.
260
+ */
261
+ async request(method, params) {
262
+ const ws = this.ws;
263
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
264
+ throw new Error("Not connected to relay");
265
+ }
266
+ if (!this.sharedSecret) {
267
+ throw new Error("No shared secret \u2014 key exchange not completed");
268
+ }
269
+ const id = crypto.randomUUID();
270
+ const envelope = await encryptMessage(this.sharedSecret, {
271
+ type: "rpc_request",
272
+ id,
273
+ method,
274
+ params
275
+ });
276
+ const serialized = JSON.stringify({ type: "encrypted", ...envelope });
277
+ assertMessageSize(serialized, method);
278
+ return new Promise((resolve, reject) => {
279
+ const timer = setTimeout(() => {
280
+ reject(
281
+ new Error(
282
+ `Request timed out after ${this.timeout / 1e3}s. Did you complete the action in the browser?`
283
+ )
284
+ );
285
+ this.close();
286
+ }, this.timeout);
287
+ const onMessage = async (data) => {
288
+ const msg = safeParse(data);
289
+ if (!msg || msg.type !== "encrypted" || !this.sharedSecret) return;
290
+ try {
291
+ const inner = await decryptMessage(
292
+ this.sharedSecret,
293
+ msg
294
+ );
295
+ if (inner.type === "rpc_response" && inner.id === id) {
296
+ clearTimeout(timer);
297
+ ws.off("message", onMessage);
298
+ if (inner.success) {
299
+ resolve(inner.data);
300
+ } else {
301
+ const err = inner.error;
302
+ reject(
303
+ new Error(
304
+ err ? `[${err.code}] ${err.message}` : "Request failed"
305
+ )
306
+ );
307
+ }
308
+ }
309
+ } catch {
310
+ }
311
+ };
312
+ ws.on("message", onMessage);
313
+ this.sendRaw(ws, serialized);
314
+ });
315
+ }
316
+ isOpen() {
317
+ return this.ws?.readyState === WebSocket.OPEN;
318
+ }
319
+ async shutdown() {
320
+ this.disposed = true;
321
+ if (this.ws?.readyState === WebSocket.OPEN && this.sharedSecret) {
322
+ try {
323
+ const envelope = await encryptMessage(this.sharedSecret, {
324
+ type: "shutdown"
325
+ });
326
+ this.sendRaw(
327
+ this.ws,
328
+ JSON.stringify({ type: "encrypted", ...envelope })
329
+ );
330
+ } catch {
331
+ }
332
+ }
333
+ this.close();
60
334
  }
335
+ /**
336
+ * Connect to relay and send shutdown directly — no init/ready handshake.
337
+ * Used by `jaw disconnect` when we just need to tell the browser to close.
338
+ */
339
+ async connectAndShutdown() {
340
+ if (!this.peerPublicKeyHex) {
341
+ return;
342
+ }
343
+ this.disposed = true;
344
+ await this.deriveSecret();
345
+ return new Promise((resolve) => {
346
+ const url = `${this.relayUrl}?session=${encodeURIComponent(this.session)}&role=cli`;
347
+ const ws = new WebSocket(url);
348
+ const timer = setTimeout(() => {
349
+ try {
350
+ ws.close();
351
+ } catch {
352
+ }
353
+ resolve();
354
+ }, 3e3);
355
+ ws.on("open", async () => {
356
+ this.ws = ws;
357
+ try {
358
+ await this.shutdown();
359
+ } catch {
360
+ }
361
+ clearTimeout(timer);
362
+ resolve();
363
+ });
364
+ ws.on("error", () => {
365
+ clearTimeout(timer);
366
+ resolve();
367
+ });
368
+ });
369
+ }
370
+ close() {
371
+ this.disposed = true;
372
+ if (this.ws) {
373
+ try {
374
+ this.ws.close();
375
+ } catch {
376
+ }
377
+ this.ws = null;
378
+ }
379
+ }
380
+ /**
381
+ * Auto-reopen browser when browser_disconnected is received from relay.
382
+ * Respects a cooldown to prevent rapid re-opening.
383
+ */
384
+ handleBrowserDisconnect() {
385
+ if (this.disposed || !this.onBrowserNeeded) return;
386
+ const now = Date.now();
387
+ if (now - this.lastBrowserOpenTime < BROWSER_REOPEN_COOLDOWN_MS) {
388
+ return;
389
+ }
390
+ this.lastBrowserOpenTime = now;
391
+ this.sharedSecret = null;
392
+ this.peerPublicKeyHex = null;
393
+ this.onBrowserNeeded().catch(() => {
394
+ });
395
+ }
396
+ /**
397
+ * Attempt to reconnect to the relay with exponential backoff
398
+ * when the WebSocket connection drops unexpectedly.
399
+ */
400
+ handleRelayDisconnect() {
401
+ if (this.disposed) return;
402
+ if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) return;
403
+ const delay = RECONNECT_BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts);
404
+ this.reconnectAttempts++;
405
+ setTimeout(() => {
406
+ if (this.disposed) return;
407
+ this.connectInternal(this.onBrowserNeeded, this.onPeerKeyChanged).catch(
408
+ () => {
409
+ }
410
+ );
411
+ }, delay);
412
+ }
413
+ /** Send a raw string over the WebSocket, enforcing message size limits. */
414
+ sendRaw(ws, data) {
415
+ ws.send(data);
416
+ }
417
+ async deriveSecret() {
418
+ if (!this.peerPublicKeyHex) return;
419
+ const privateKey = await importKeyFromHex("private", this.privateKeyHex);
420
+ const peerPublicKey = await importKeyFromHex(
421
+ "public",
422
+ this.peerPublicKeyHex
423
+ );
424
+ this.sharedSecret = await deriveSharedSecret(privateKey, peerPublicKey);
425
+ }
426
+ };
427
+ function assertMessageSize(serialized, method) {
428
+ const byteLength = Buffer.byteLength(serialized, "utf-8");
429
+ if (byteLength > MAX_MESSAGE_BYTES) {
430
+ const sizeMB = (byteLength / (1024 * 1024)).toFixed(2);
431
+ throw new Error(
432
+ `Message for ${method} is too large (${sizeMB} MB, limit ${MAX_MESSAGE_BYTES / (1024 * 1024)} MB). Try reducing the number of calls in your batch.`
433
+ );
434
+ }
435
+ }
436
+ function safeParse(data) {
61
437
  try {
62
- const cmd = execSync(`ps -p ${String(pid)} -o command=`, {
63
- encoding: "utf-8",
64
- timeout: 3e3
65
- }).trim();
66
- return cmd.includes("ws-daemon");
438
+ return JSON.parse(data.toString());
67
439
  } catch {
68
- return false;
440
+ return null;
69
441
  }
70
442
  }
71
- function loadBridgeInfo() {
443
+
444
+ // src/lib/bridge-singleton.ts
445
+ function loadRelaySession() {
72
446
  try {
73
- if (!fs2.existsSync(PATHS.bridge)) return null;
74
- const raw = fs2.readFileSync(PATHS.bridge, "utf-8");
75
- const info = JSON.parse(raw);
76
- if (!isDaemonProcess(info.pid)) {
77
- try {
78
- fs2.unlinkSync(PATHS.bridge);
79
- } catch {
80
- }
447
+ if (!fs2.existsSync(PATHS.relay)) return null;
448
+ const raw = fs2.readFileSync(PATHS.relay, "utf-8");
449
+ const parsed = JSON.parse(raw);
450
+ if (!parsed.session || !parsed.relayUrl || !parsed.privateKey || !parsed.publicKey) {
81
451
  return null;
82
452
  }
83
- return info;
453
+ return parsed;
84
454
  } catch {
85
455
  return null;
86
456
  }
87
457
  }
458
+ function deleteRelaySession() {
459
+ try {
460
+ if (fs2.existsSync(PATHS.relay)) fs2.unlinkSync(PATHS.relay);
461
+ } catch {
462
+ }
463
+ }
88
464
  async function shutdownDaemon() {
89
- const info = loadBridgeInfo();
90
- if (!info) return;
465
+ const session = loadRelaySession();
466
+ if (!session) return;
91
467
  try {
92
- process.kill(info.pid, "SIGTERM");
468
+ const bridge = new WSBridge({
469
+ relayUrl: session.relayUrl,
470
+ session: session.session,
471
+ timeout: 5e3,
472
+ config: { apiKey: "", chainId: 1 },
473
+ privateKeyHex: session.privateKey,
474
+ publicKeyHex: session.publicKey,
475
+ peerPublicKeyHex: session.peerPublicKey
476
+ });
477
+ await bridge.connectAndShutdown();
93
478
  } catch {
94
479
  }
480
+ deleteRelaySession();
481
+ const legacyBridge = PATHS.root + "/bridge.json";
482
+ const legacyLog = PATHS.root + "/daemon.log";
483
+ const legacyLock = PATHS.root + "/daemon.lock";
95
484
  try {
96
- if (fs2.existsSync(PATHS.bridge)) fs2.unlinkSync(PATHS.bridge);
485
+ if (fs2.existsSync(legacyBridge)) {
486
+ const info = JSON.parse(fs2.readFileSync(legacyBridge, "utf-8"));
487
+ if (info.pid && Number.isInteger(info.pid) && info.pid > 0) {
488
+ try {
489
+ process.kill(info.pid, "SIGTERM");
490
+ } catch {
491
+ }
492
+ }
493
+ }
97
494
  } catch {
98
495
  }
496
+ for (const f of [legacyBridge, legacyLog, legacyLock]) {
497
+ try {
498
+ if (fs2.existsSync(f)) fs2.unlinkSync(f);
499
+ } catch {
500
+ }
501
+ }
99
502
  }
100
503
  ({
101
504
  method: z.string().describe(
@@ -125,25 +528,22 @@ function isBridgeCached() {
125
528
  function registerDaemonTools(server) {
126
529
  server.tool(
127
530
  "jaw_status",
128
- "Check the current status of the JAW.id bridge \u2014 whether the daemon is running, the bridge connection is active, and what configuration is in use.",
531
+ "Check the current status of the JAW.id relay bridge \u2014 whether a relay session exists, the bridge connection is active, and what configuration is in use.",
129
532
  {},
130
533
  async () => {
131
534
  try {
132
- let daemonRunning = false;
133
- let daemonPid = null;
535
+ let relaySession = false;
134
536
  try {
135
- if (fs2.existsSync(PATHS.bridge)) {
136
- const info = JSON.parse(fs2.readFileSync(PATHS.bridge, "utf-8"));
137
- daemonPid = info.pid;
138
- process.kill(info.pid, 0);
139
- daemonRunning = true;
537
+ if (fs2.existsSync(PATHS.relay)) {
538
+ JSON.parse(fs2.readFileSync(PATHS.relay, "utf-8"));
539
+ relaySession = true;
140
540
  }
141
541
  } catch {
142
- daemonRunning = false;
542
+ relaySession = false;
143
543
  }
144
544
  const config = redactConfig(loadConfig());
145
545
  const status = {
146
- daemon: daemonRunning ? { running: true, pid: daemonPid } : { running: false },
546
+ relay: relaySession ? { session: true } : { session: false },
147
547
  bridgeConnection: isBridgeCached() ? "connected" : "disconnected",
148
548
  config
149
549
  };
@@ -159,7 +559,7 @@ function registerDaemonTools(server) {
159
559
  );
160
560
  server.tool(
161
561
  "jaw_disconnect",
162
- "Stop the background bridge daemon and close the browser session. Call this when you are done making wallet requests to clean up resources.",
562
+ "Close the relay session and browser tab. Call this when you are done making wallet requests to clean up resources.",
163
563
  {},
164
564
  async () => {
165
565
  try {
@@ -169,7 +569,7 @@ function registerDaemonTools(server) {
169
569
  content: [
170
570
  {
171
571
  type: "text",
172
- text: "Bridge daemon stopped and browser session closed."
572
+ text: "Relay session closed and browser tab dismissed."
173
573
  }
174
574
  ]
175
575
  };