@jaw.id/cli 0.0.8 → 0.1.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.
- package/dist/base-command.js +26 -2
- package/dist/base-command.js.map +1 -1
- package/dist/commands/config/set.js +19 -7
- package/dist/commands/config/set.js.map +1 -1
- package/dist/commands/config/show.js +26 -2
- package/dist/commands/config/show.js.map +1 -1
- package/dist/commands/config/write.js +288 -0
- package/dist/commands/config/write.js.map +1 -0
- package/dist/commands/disconnect.js +29 -5
- package/dist/commands/disconnect.js.map +1 -1
- package/dist/commands/mcp/index.js +34 -17
- package/dist/commands/mcp/index.js.map +1 -1
- package/dist/commands/rpc/call.js +205 -37
- package/dist/commands/rpc/call.js.map +1 -1
- package/dist/commands/session/revoke.js +727 -0
- package/dist/commands/session/revoke.js.map +1 -0
- package/dist/commands/session/setup.js +960 -0
- package/dist/commands/session/setup.js.map +1 -0
- package/dist/commands/session/status.js +206 -0
- package/dist/commands/session/status.js.map +1 -0
- package/dist/commands/version.js +26 -2
- package/dist/commands/version.js.map +1 -1
- package/dist/index.js +28 -13
- package/dist/index.js.map +1 -1
- package/dist/lib/bridge-singleton.js +35 -13
- package/dist/lib/bridge-singleton.js.map +1 -1
- package/dist/lib/config.js +15 -7
- package/dist/lib/config.js.map +1 -1
- package/dist/lib/keystore.js +64 -0
- package/dist/lib/keystore.js.map +1 -0
- package/dist/lib/output.js +1 -12
- package/dist/lib/output.js.map +1 -1
- package/dist/lib/paths.js +3 -1
- package/dist/lib/paths.js.map +1 -1
- package/dist/lib/session-bridge.js +168 -0
- package/dist/lib/session-bridge.js.map +1 -0
- package/dist/lib/session-config.js +52 -0
- package/dist/lib/session-config.js.map +1 -0
- package/dist/lib/validation.js +62 -27
- package/dist/lib/validation.js.map +1 -1
- package/dist/lib/ws-bridge.js +4 -3
- package/dist/lib/ws-bridge.js.map +1 -1
- package/dist/mcp/handlers/config.js +16 -4
- package/dist/mcp/handlers/config.js.map +1 -1
- package/dist/mcp/handlers/daemon.js +29 -5
- package/dist/mcp/handlers/daemon.js.map +1 -1
- package/dist/mcp/handlers/rpc.js +49 -25
- package/dist/mcp/handlers/rpc.js.map +1 -1
- package/dist/mcp/server.js +34 -17
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/tools.js +1 -1
- package/dist/mcp/tools.js.map +1 -1
- package/oclif.manifest.json +304 -4
- package/package.json +18 -1
- package/dist/lib/session-store.js +0 -80
- package/dist/lib/session-store.js.map +0 -1
|
@@ -0,0 +1,727 @@
|
|
|
1
|
+
import { Command, Flags } from '@oclif/core';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import * as os from 'os';
|
|
5
|
+
import * as crypto from 'crypto';
|
|
6
|
+
import WebSocket from 'ws';
|
|
7
|
+
|
|
8
|
+
// src/base-command.ts
|
|
9
|
+
var JAW_DIR = path.join(os.homedir(), ".jaw");
|
|
10
|
+
var PATHS = {
|
|
11
|
+
root: JAW_DIR,
|
|
12
|
+
config: path.join(JAW_DIR, "config.json"),
|
|
13
|
+
session: path.join(JAW_DIR, "session.json"),
|
|
14
|
+
relay: path.join(JAW_DIR, "relay.json"),
|
|
15
|
+
keystore: path.join(JAW_DIR, "keystore.json"),
|
|
16
|
+
sessionConfig: path.join(JAW_DIR, "session-config.json")
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// src/lib/validation.ts
|
|
20
|
+
function isValidKeysUrl(url) {
|
|
21
|
+
try {
|
|
22
|
+
const parsed = new URL(url);
|
|
23
|
+
const isTrustedHost = parsed.hostname.endsWith(".jaw.id") || parsed.hostname === "jaw.id" || parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
|
|
24
|
+
const isSecure = parsed.protocol === "https:" || parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
|
|
25
|
+
return isTrustedHost && isSecure;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function isValidRelayUrl(url) {
|
|
31
|
+
try {
|
|
32
|
+
const parsed = new URL(url);
|
|
33
|
+
const isTrustedHost = parsed.hostname.endsWith(".jaw.id") || parsed.hostname === "jaw.id" || parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
|
|
34
|
+
const isSecure = parsed.protocol === "wss:" || parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
|
|
35
|
+
const isWebSocket = parsed.protocol === "wss:" || parsed.protocol === "ws:";
|
|
36
|
+
return isTrustedHost && isSecure && isWebSocket;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/lib/config.ts
|
|
43
|
+
function ensureDir(dir) {
|
|
44
|
+
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
45
|
+
fs.chmodSync(dir, 448);
|
|
46
|
+
}
|
|
47
|
+
function migrateConfig(config) {
|
|
48
|
+
if (config.paymasterUrl && !config.paymasters) {
|
|
49
|
+
const chainId = config.defaultChain ?? 1;
|
|
50
|
+
config.paymasters = { [chainId]: { url: config.paymasterUrl } };
|
|
51
|
+
delete config.paymasterUrl;
|
|
52
|
+
saveConfig(config);
|
|
53
|
+
}
|
|
54
|
+
return config;
|
|
55
|
+
}
|
|
56
|
+
function loadConfig() {
|
|
57
|
+
if (!fs.existsSync(PATHS.config)) {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
const raw = fs.readFileSync(PATHS.config, "utf-8");
|
|
61
|
+
try {
|
|
62
|
+
const config = JSON.parse(raw);
|
|
63
|
+
return migrateConfig(config);
|
|
64
|
+
} catch {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`Config file at ${PATHS.config} is not valid JSON. Run \`jaw config set apiKey=<key>\` to reset it.`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function saveConfig(config) {
|
|
71
|
+
ensureDir(PATHS.root);
|
|
72
|
+
fs.writeFileSync(PATHS.config, JSON.stringify(config, null, 2) + "\n", {
|
|
73
|
+
encoding: "utf-8",
|
|
74
|
+
mode: 384
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/lib/output.ts
|
|
79
|
+
function formatOutput(data, format) {
|
|
80
|
+
if (format === "json") {
|
|
81
|
+
return JSON.stringify(data, replaceBigInt, 2);
|
|
82
|
+
}
|
|
83
|
+
return formatHuman(data);
|
|
84
|
+
}
|
|
85
|
+
function replaceBigInt(_key, value) {
|
|
86
|
+
if (typeof value === "bigint") {
|
|
87
|
+
return value.toString();
|
|
88
|
+
}
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
function formatHuman(data, indent = 0) {
|
|
92
|
+
if (data === null || data === void 0) {
|
|
93
|
+
return "null";
|
|
94
|
+
}
|
|
95
|
+
if (typeof data === "string" || typeof data === "number" || typeof data === "boolean" || typeof data === "bigint") {
|
|
96
|
+
return String(data);
|
|
97
|
+
}
|
|
98
|
+
if (Array.isArray(data)) {
|
|
99
|
+
if (data.length === 0) return "(empty)";
|
|
100
|
+
return data.map((item, i) => `${i + 1}. ${formatHuman(item, indent + 2)}`).join("\n");
|
|
101
|
+
}
|
|
102
|
+
if (typeof data === "object") {
|
|
103
|
+
const entries = Object.entries(data);
|
|
104
|
+
if (entries.length === 0) return "(empty)";
|
|
105
|
+
const pad = " ".repeat(indent);
|
|
106
|
+
const maxKeyLen = Math.max(...entries.map(([k]) => k.length));
|
|
107
|
+
return entries.map(([key, val]) => {
|
|
108
|
+
const paddedKey = key.padEnd(maxKeyLen);
|
|
109
|
+
const valStr = typeof val === "object" && val !== null ? "\n" + formatHuman(val, indent + 2) : String(val);
|
|
110
|
+
return `${pad}${paddedKey} ${valStr}`;
|
|
111
|
+
}).join("\n");
|
|
112
|
+
}
|
|
113
|
+
return String(data);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/base-command.ts
|
|
117
|
+
var BaseCommand = class extends Command {
|
|
118
|
+
static baseFlags = {
|
|
119
|
+
output: Flags.string({
|
|
120
|
+
char: "o",
|
|
121
|
+
description: "Output format",
|
|
122
|
+
options: ["json", "human"],
|
|
123
|
+
default: "human",
|
|
124
|
+
env: "JAW_OUTPUT"
|
|
125
|
+
}),
|
|
126
|
+
chain: Flags.integer({
|
|
127
|
+
char: "c",
|
|
128
|
+
description: "Chain ID",
|
|
129
|
+
env: "JAW_CHAIN_ID"
|
|
130
|
+
}),
|
|
131
|
+
"api-key": Flags.string({
|
|
132
|
+
description: "JAW API key",
|
|
133
|
+
env: "JAW_API_KEY"
|
|
134
|
+
}),
|
|
135
|
+
yes: Flags.boolean({
|
|
136
|
+
char: "y",
|
|
137
|
+
description: "Skip confirmations (for AI agents)",
|
|
138
|
+
default: false
|
|
139
|
+
}),
|
|
140
|
+
quiet: Flags.boolean({
|
|
141
|
+
char: "q",
|
|
142
|
+
description: "Suppress non-essential output",
|
|
143
|
+
default: false
|
|
144
|
+
})
|
|
145
|
+
};
|
|
146
|
+
resolveApiKey(flags) {
|
|
147
|
+
const apiKey = flags["api-key"] ?? loadConfig().apiKey;
|
|
148
|
+
if (!apiKey) {
|
|
149
|
+
this.error("API key required. Set via --api-key, JAW_API_KEY env, or `jaw config set apiKey <key>`");
|
|
150
|
+
}
|
|
151
|
+
return apiKey;
|
|
152
|
+
}
|
|
153
|
+
resolveChainId(flags) {
|
|
154
|
+
const chainId = flags.chain ?? loadConfig().defaultChain;
|
|
155
|
+
if (!chainId) {
|
|
156
|
+
this.error("Chain ID required. Set via --chain, JAW_CHAIN_ID env, or `jaw config set defaultChain <id>`");
|
|
157
|
+
}
|
|
158
|
+
return chainId;
|
|
159
|
+
}
|
|
160
|
+
outputResult(data, format) {
|
|
161
|
+
const output = formatOutput(data, format);
|
|
162
|
+
this.log(output);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// src/lib/crypto.ts
|
|
167
|
+
var subtle = globalThis.crypto.subtle;
|
|
168
|
+
async function generateKeyPair() {
|
|
169
|
+
return subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveKey"]);
|
|
170
|
+
}
|
|
171
|
+
async function deriveSharedSecret(privateKey, peerPublicKey) {
|
|
172
|
+
return subtle.deriveKey(
|
|
173
|
+
{ name: "ECDH", public: peerPublicKey },
|
|
174
|
+
privateKey,
|
|
175
|
+
{ name: "AES-GCM", length: 256 },
|
|
176
|
+
false,
|
|
177
|
+
["encrypt", "decrypt"]
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
async function encryptMessage(sharedSecret, payload) {
|
|
181
|
+
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
182
|
+
const plaintext = new TextEncoder().encode(JSON.stringify(payload));
|
|
183
|
+
const cipherBuf = await subtle.encrypt({ name: "AES-GCM", iv }, sharedSecret, plaintext);
|
|
184
|
+
return {
|
|
185
|
+
iv: bufferToBase64(iv),
|
|
186
|
+
ciphertext: bufferToBase64(new Uint8Array(cipherBuf))
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
async function decryptMessage(sharedSecret, envelope) {
|
|
190
|
+
const iv = Buffer.from(envelope.iv, "base64");
|
|
191
|
+
const ciphertext = Buffer.from(envelope.ciphertext, "base64");
|
|
192
|
+
const plainBuf = await subtle.decrypt({ name: "AES-GCM", iv }, sharedSecret, ciphertext);
|
|
193
|
+
return JSON.parse(new TextDecoder().decode(plainBuf));
|
|
194
|
+
}
|
|
195
|
+
async function exportKeyToHex(type, key) {
|
|
196
|
+
const format = type === "private" ? "pkcs8" : "spki";
|
|
197
|
+
const buf = await subtle.exportKey(format, key);
|
|
198
|
+
return bytesToHex(new Uint8Array(buf));
|
|
199
|
+
}
|
|
200
|
+
async function importKeyFromHex(type, hex) {
|
|
201
|
+
const format = type === "private" ? "pkcs8" : "spki";
|
|
202
|
+
return subtle.importKey(
|
|
203
|
+
format,
|
|
204
|
+
Buffer.from(hexToBytes(hex)),
|
|
205
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
206
|
+
true,
|
|
207
|
+
type === "private" ? ["deriveKey"] : []
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
function bytesToHex(bytes) {
|
|
211
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
212
|
+
}
|
|
213
|
+
function hexToBytes(hex) {
|
|
214
|
+
if (hex.length % 2 !== 0) throw new Error("Invalid hex: odd length");
|
|
215
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
216
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
217
|
+
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
|
|
218
|
+
}
|
|
219
|
+
return bytes;
|
|
220
|
+
}
|
|
221
|
+
function bufferToBase64(buf) {
|
|
222
|
+
return Buffer.from(buf).toString("base64");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/lib/ws-bridge.ts
|
|
226
|
+
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
227
|
+
var MAX_MESSAGE_BYTES = 5 * 1024 * 1024;
|
|
228
|
+
var BROWSER_REOPEN_COOLDOWN_MS = 5e3;
|
|
229
|
+
var MAX_RECONNECT_ATTEMPTS = 3;
|
|
230
|
+
var RECONNECT_BASE_DELAY_MS = 1e3;
|
|
231
|
+
var WSBridge = class {
|
|
232
|
+
relayUrl;
|
|
233
|
+
session;
|
|
234
|
+
timeout;
|
|
235
|
+
config;
|
|
236
|
+
privateKeyHex;
|
|
237
|
+
publicKeyHex;
|
|
238
|
+
peerPublicKeyHex;
|
|
239
|
+
sharedSecret = null;
|
|
240
|
+
ws = null;
|
|
241
|
+
disposed = false;
|
|
242
|
+
// Auto-reopen browser state
|
|
243
|
+
onBrowserNeeded;
|
|
244
|
+
onPeerKeyChanged;
|
|
245
|
+
lastBrowserOpenTime = 0;
|
|
246
|
+
// Reconnection state
|
|
247
|
+
reconnectAttempts = 0;
|
|
248
|
+
/** Updated after key exchange — caller should persist this. */
|
|
249
|
+
get peerPublicKey() {
|
|
250
|
+
return this.peerPublicKeyHex;
|
|
251
|
+
}
|
|
252
|
+
constructor(options) {
|
|
253
|
+
this.relayUrl = options.relayUrl;
|
|
254
|
+
this.session = options.session;
|
|
255
|
+
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
256
|
+
this.config = options.config;
|
|
257
|
+
this.privateKeyHex = options.privateKeyHex;
|
|
258
|
+
this.publicKeyHex = options.publicKeyHex;
|
|
259
|
+
this.peerPublicKeyHex = options.peerPublicKeyHex;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Connect to the relay and wait for the browser to be ready.
|
|
263
|
+
*
|
|
264
|
+
* @param onBrowserNeeded — called when the relay reports no browser connected.
|
|
265
|
+
* @param onPeerKeyChanged — called when a key_exchange updates the peer key.
|
|
266
|
+
*/
|
|
267
|
+
async connect(onBrowserNeeded, onPeerKeyChanged) {
|
|
268
|
+
this.onBrowserNeeded = onBrowserNeeded;
|
|
269
|
+
this.onPeerKeyChanged = onPeerKeyChanged;
|
|
270
|
+
if (this.peerPublicKeyHex) {
|
|
271
|
+
await this.deriveSecret();
|
|
272
|
+
}
|
|
273
|
+
return this.connectInternal(onBrowserNeeded, onPeerKeyChanged);
|
|
274
|
+
}
|
|
275
|
+
async connectInternal(onBrowserNeeded, onPeerKeyChanged) {
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const url = `${this.relayUrl}?session=${encodeURIComponent(this.session)}&role=cli`;
|
|
278
|
+
const ws = new WebSocket(url);
|
|
279
|
+
let browserOpened = false;
|
|
280
|
+
let resolved = false;
|
|
281
|
+
let expectingKeyExchange = !this.peerPublicKeyHex;
|
|
282
|
+
const timer = setTimeout(() => {
|
|
283
|
+
ws.close();
|
|
284
|
+
reject(new Error("Browser did not connect in time.\nRun `jaw disconnect` then try again."));
|
|
285
|
+
}, 3e4);
|
|
286
|
+
const sendEncryptedInit = async () => {
|
|
287
|
+
if (!this.sharedSecret) return;
|
|
288
|
+
const envelope = await encryptMessage(this.sharedSecret, {
|
|
289
|
+
type: "init",
|
|
290
|
+
apiKey: this.config.apiKey,
|
|
291
|
+
chainId: this.config.chainId,
|
|
292
|
+
ens: this.config.ens,
|
|
293
|
+
paymasterUrl: this.config.paymasterUrl
|
|
294
|
+
});
|
|
295
|
+
this.sendRaw(ws, JSON.stringify({ type: "encrypted", ...envelope }));
|
|
296
|
+
};
|
|
297
|
+
const waitForReady = () => {
|
|
298
|
+
const readyTimer = setTimeout(() => {
|
|
299
|
+
ws.close();
|
|
300
|
+
reject(new Error("Browser SDK did not become ready in time."));
|
|
301
|
+
}, 15e3);
|
|
302
|
+
const onMsg = async (data) => {
|
|
303
|
+
const msg = safeParse(data);
|
|
304
|
+
if (!msg) return;
|
|
305
|
+
if (msg.type === "encrypted" && this.sharedSecret) {
|
|
306
|
+
try {
|
|
307
|
+
const inner = await decryptMessage(this.sharedSecret, msg);
|
|
308
|
+
if (inner.type === "ready") {
|
|
309
|
+
clearTimeout(readyTimer);
|
|
310
|
+
ws.off("message", onMsg);
|
|
311
|
+
this.reconnectAttempts = 0;
|
|
312
|
+
resolve();
|
|
313
|
+
}
|
|
314
|
+
} catch {
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
ws.on("message", onMsg);
|
|
319
|
+
};
|
|
320
|
+
const onBrowserReady = async () => {
|
|
321
|
+
if (resolved) return;
|
|
322
|
+
resolved = true;
|
|
323
|
+
clearTimeout(timer);
|
|
324
|
+
waitForReady();
|
|
325
|
+
await sendEncryptedInit();
|
|
326
|
+
};
|
|
327
|
+
ws.on("open", () => {
|
|
328
|
+
this.ws = ws;
|
|
329
|
+
});
|
|
330
|
+
ws.on("message", async (data) => {
|
|
331
|
+
const msg = safeParse(data);
|
|
332
|
+
if (!msg) return;
|
|
333
|
+
if (msg.type === "status") {
|
|
334
|
+
if (msg.browserConnected) {
|
|
335
|
+
if (this.sharedSecret) {
|
|
336
|
+
await onBrowserReady();
|
|
337
|
+
} else {
|
|
338
|
+
expectingKeyExchange = true;
|
|
339
|
+
}
|
|
340
|
+
} else if (!browserOpened && onBrowserNeeded) {
|
|
341
|
+
browserOpened = true;
|
|
342
|
+
expectingKeyExchange = true;
|
|
343
|
+
onBrowserNeeded().catch(() => {
|
|
344
|
+
});
|
|
345
|
+
} else if (!onBrowserNeeded) {
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
ws.close();
|
|
348
|
+
reject(new Error("Browser not connected \u2014 relay session is stale."));
|
|
349
|
+
}
|
|
350
|
+
} else if (msg.type === "browser_connected") {
|
|
351
|
+
expectingKeyExchange = true;
|
|
352
|
+
} else if (msg.type === "browser_disconnected") {
|
|
353
|
+
this.handleBrowserDisconnect();
|
|
354
|
+
} else if (msg.type === "key_exchange" && expectingKeyExchange) {
|
|
355
|
+
expectingKeyExchange = false;
|
|
356
|
+
const peerKey = msg.publicKey;
|
|
357
|
+
this.peerPublicKeyHex = peerKey;
|
|
358
|
+
await this.deriveSecret();
|
|
359
|
+
onPeerKeyChanged?.(peerKey);
|
|
360
|
+
await onBrowserReady();
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
ws.on("error", (err) => {
|
|
364
|
+
clearTimeout(timer);
|
|
365
|
+
reject(err);
|
|
366
|
+
});
|
|
367
|
+
ws.on("close", () => {
|
|
368
|
+
clearTimeout(timer);
|
|
369
|
+
if (!this.disposed) {
|
|
370
|
+
this.handleRelayDisconnect();
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Send an encrypted RPC request through the relay to the browser SDK.
|
|
377
|
+
*/
|
|
378
|
+
async request(method, params) {
|
|
379
|
+
const ws = this.ws;
|
|
380
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
381
|
+
throw new Error("Not connected to relay");
|
|
382
|
+
}
|
|
383
|
+
if (!this.sharedSecret) {
|
|
384
|
+
throw new Error("No shared secret \u2014 key exchange not completed");
|
|
385
|
+
}
|
|
386
|
+
const id = crypto.randomUUID();
|
|
387
|
+
const envelope = await encryptMessage(this.sharedSecret, {
|
|
388
|
+
type: "rpc_request",
|
|
389
|
+
id,
|
|
390
|
+
method,
|
|
391
|
+
params
|
|
392
|
+
});
|
|
393
|
+
const serialized = JSON.stringify({ type: "encrypted", ...envelope });
|
|
394
|
+
assertMessageSize(serialized, method);
|
|
395
|
+
return new Promise((resolve, reject) => {
|
|
396
|
+
const timer = setTimeout(() => {
|
|
397
|
+
reject(
|
|
398
|
+
new Error(`Request timed out after ${this.timeout / 1e3}s. Did you complete the action in the browser?`)
|
|
399
|
+
);
|
|
400
|
+
this.close();
|
|
401
|
+
}, this.timeout);
|
|
402
|
+
const onMessage = async (data) => {
|
|
403
|
+
const msg = safeParse(data);
|
|
404
|
+
if (!msg || msg.type !== "encrypted" || !this.sharedSecret) return;
|
|
405
|
+
try {
|
|
406
|
+
const inner = await decryptMessage(this.sharedSecret, msg);
|
|
407
|
+
if (inner.type === "rpc_response" && inner.id === id) {
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
ws.off("message", onMessage);
|
|
410
|
+
if (inner.success) {
|
|
411
|
+
resolve(inner.data);
|
|
412
|
+
} else {
|
|
413
|
+
const err = inner.error;
|
|
414
|
+
reject(new Error(err ? `[${err.code}] ${err.message}` : "Request failed"));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
ws.on("message", onMessage);
|
|
421
|
+
this.sendRaw(ws, serialized);
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
async shutdown() {
|
|
425
|
+
this.disposed = true;
|
|
426
|
+
if (this.ws?.readyState === WebSocket.OPEN && this.sharedSecret) {
|
|
427
|
+
try {
|
|
428
|
+
const envelope = await encryptMessage(this.sharedSecret, {
|
|
429
|
+
type: "shutdown"
|
|
430
|
+
});
|
|
431
|
+
this.sendRaw(this.ws, JSON.stringify({ type: "encrypted", ...envelope }));
|
|
432
|
+
} catch {
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
this.close();
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Connect to relay and send shutdown directly — no init/ready handshake.
|
|
439
|
+
* Used by `jaw disconnect` when we just need to tell the browser to close.
|
|
440
|
+
*/
|
|
441
|
+
async connectAndShutdown() {
|
|
442
|
+
if (!this.peerPublicKeyHex) {
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
this.disposed = true;
|
|
446
|
+
await this.deriveSecret();
|
|
447
|
+
return new Promise((resolve) => {
|
|
448
|
+
const url = `${this.relayUrl}?session=${encodeURIComponent(this.session)}&role=cli`;
|
|
449
|
+
const ws = new WebSocket(url);
|
|
450
|
+
const timer = setTimeout(() => {
|
|
451
|
+
try {
|
|
452
|
+
ws.close();
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
resolve();
|
|
456
|
+
}, 3e3);
|
|
457
|
+
ws.on("open", async () => {
|
|
458
|
+
this.ws = ws;
|
|
459
|
+
try {
|
|
460
|
+
await this.shutdown();
|
|
461
|
+
} catch {
|
|
462
|
+
}
|
|
463
|
+
clearTimeout(timer);
|
|
464
|
+
resolve();
|
|
465
|
+
});
|
|
466
|
+
ws.on("error", () => {
|
|
467
|
+
clearTimeout(timer);
|
|
468
|
+
resolve();
|
|
469
|
+
});
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
close() {
|
|
473
|
+
this.disposed = true;
|
|
474
|
+
if (this.ws) {
|
|
475
|
+
try {
|
|
476
|
+
this.ws.close();
|
|
477
|
+
} catch {
|
|
478
|
+
}
|
|
479
|
+
this.ws = null;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Auto-reopen browser when browser_disconnected is received from relay.
|
|
484
|
+
* Respects a cooldown to prevent rapid re-opening.
|
|
485
|
+
*/
|
|
486
|
+
handleBrowserDisconnect() {
|
|
487
|
+
if (this.disposed || !this.onBrowserNeeded) return;
|
|
488
|
+
const now = Date.now();
|
|
489
|
+
if (now - this.lastBrowserOpenTime < BROWSER_REOPEN_COOLDOWN_MS) {
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
this.lastBrowserOpenTime = now;
|
|
493
|
+
this.sharedSecret = null;
|
|
494
|
+
this.peerPublicKeyHex = null;
|
|
495
|
+
this.onBrowserNeeded().catch(() => {
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Attempt to reconnect to the relay with exponential backoff
|
|
500
|
+
* when the WebSocket connection drops unexpectedly.
|
|
501
|
+
*/
|
|
502
|
+
handleRelayDisconnect() {
|
|
503
|
+
if (this.disposed) return;
|
|
504
|
+
if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) return;
|
|
505
|
+
const delay = RECONNECT_BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts);
|
|
506
|
+
this.reconnectAttempts++;
|
|
507
|
+
setTimeout(() => {
|
|
508
|
+
if (this.disposed) return;
|
|
509
|
+
this.connectInternal(this.onBrowserNeeded, this.onPeerKeyChanged).catch(() => {
|
|
510
|
+
});
|
|
511
|
+
}, delay);
|
|
512
|
+
}
|
|
513
|
+
/** Send a raw string over the WebSocket, enforcing message size limits. */
|
|
514
|
+
sendRaw(ws, data) {
|
|
515
|
+
ws.send(data);
|
|
516
|
+
}
|
|
517
|
+
async deriveSecret() {
|
|
518
|
+
if (!this.peerPublicKeyHex) return;
|
|
519
|
+
const privateKey = await importKeyFromHex("private", this.privateKeyHex);
|
|
520
|
+
const peerPublicKey = await importKeyFromHex("public", this.peerPublicKeyHex);
|
|
521
|
+
this.sharedSecret = await deriveSharedSecret(privateKey, peerPublicKey);
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
function assertMessageSize(serialized, method) {
|
|
525
|
+
const byteLength = Buffer.byteLength(serialized, "utf-8");
|
|
526
|
+
if (byteLength > MAX_MESSAGE_BYTES) {
|
|
527
|
+
const sizeMB = (byteLength / (1024 * 1024)).toFixed(2);
|
|
528
|
+
throw new Error(
|
|
529
|
+
`Message for ${method} is too large (${sizeMB} MB, limit ${MAX_MESSAGE_BYTES / (1024 * 1024)} MB). Try reducing the number of calls in your batch.`
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function safeParse(data) {
|
|
534
|
+
try {
|
|
535
|
+
return JSON.parse(data.toString());
|
|
536
|
+
} catch {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// src/lib/bridge-singleton.ts
|
|
542
|
+
var DEFAULT_KEYS_URL = "https://keys.jaw.id";
|
|
543
|
+
var DEFAULT_RELAY_URL = "wss://relay.jaw.id";
|
|
544
|
+
function loadRelaySession() {
|
|
545
|
+
try {
|
|
546
|
+
if (!fs.existsSync(PATHS.relay)) return null;
|
|
547
|
+
const raw = fs.readFileSync(PATHS.relay, "utf-8");
|
|
548
|
+
const parsed = JSON.parse(raw);
|
|
549
|
+
if (!parsed.session || !parsed.relayUrl || !parsed.privateKey || !parsed.publicKey) {
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
return parsed;
|
|
553
|
+
} catch {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function saveRelaySession(info) {
|
|
558
|
+
ensureDir(PATHS.root);
|
|
559
|
+
fs.writeFileSync(PATHS.relay, JSON.stringify(info, null, 2) + "\n", {
|
|
560
|
+
encoding: "utf-8",
|
|
561
|
+
mode: 384
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
function deleteRelaySession() {
|
|
565
|
+
try {
|
|
566
|
+
if (fs.existsSync(PATHS.relay)) fs.unlinkSync(PATHS.relay);
|
|
567
|
+
} catch {
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
async function getBridge(options) {
|
|
571
|
+
const config = loadConfig();
|
|
572
|
+
const keysUrl = options.keysUrl ?? config.keysUrl ?? DEFAULT_KEYS_URL;
|
|
573
|
+
const relayUrl = options.relayUrl ?? config.relayUrl ?? DEFAULT_RELAY_URL;
|
|
574
|
+
const chainId = options.chainId ?? config.defaultChain ?? 1;
|
|
575
|
+
if (!isValidKeysUrl(keysUrl)) {
|
|
576
|
+
throw new Error(`Untrusted keysUrl: ${keysUrl}. Must be a *.jaw.id domain (HTTPS) or localhost.`);
|
|
577
|
+
}
|
|
578
|
+
if (!isValidRelayUrl(relayUrl)) {
|
|
579
|
+
throw new Error(`Untrusted relayUrl: ${relayUrl}. Must be wss://*.jaw.id or ws://localhost.`);
|
|
580
|
+
}
|
|
581
|
+
let relaySession = loadRelaySession();
|
|
582
|
+
if (relaySession && relaySession.relayUrl === relayUrl && relaySession.peerPublicKey) {
|
|
583
|
+
try {
|
|
584
|
+
return await connectBridge(relaySession, options, chainId, keysUrl, relayUrl, false);
|
|
585
|
+
} catch {
|
|
586
|
+
deleteRelaySession();
|
|
587
|
+
relaySession = null;
|
|
588
|
+
}
|
|
589
|
+
} else if (relaySession) {
|
|
590
|
+
deleteRelaySession();
|
|
591
|
+
}
|
|
592
|
+
const session = await createNewSession(relayUrl);
|
|
593
|
+
saveRelaySession(session);
|
|
594
|
+
return await connectBridge(session, options, chainId, keysUrl, relayUrl, true);
|
|
595
|
+
}
|
|
596
|
+
async function createNewSession(relayUrl) {
|
|
597
|
+
const kp = await generateKeyPair();
|
|
598
|
+
const privateKey = await exportKeyToHex("private", kp.privateKey);
|
|
599
|
+
const publicKey = await exportKeyToHex("public", kp.publicKey);
|
|
600
|
+
return {
|
|
601
|
+
session: crypto.randomUUID(),
|
|
602
|
+
relayUrl,
|
|
603
|
+
privateKey,
|
|
604
|
+
publicKey,
|
|
605
|
+
peerPublicKey: null,
|
|
606
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
async function connectBridge(relaySession, options, chainId, keysUrl, relayUrl, openBrowser) {
|
|
610
|
+
const config = loadConfig();
|
|
611
|
+
const bridge = new WSBridge({
|
|
612
|
+
relayUrl,
|
|
613
|
+
session: relaySession.session,
|
|
614
|
+
timeout: options.timeout,
|
|
615
|
+
config: {
|
|
616
|
+
apiKey: options.apiKey,
|
|
617
|
+
chainId,
|
|
618
|
+
ens: options.ens ?? config.ens,
|
|
619
|
+
paymasterUrl: options.paymasterUrl ?? config.paymasters?.[chainId]?.url
|
|
620
|
+
},
|
|
621
|
+
privateKeyHex: relaySession.privateKey,
|
|
622
|
+
publicKeyHex: relaySession.publicKey,
|
|
623
|
+
peerPublicKeyHex: relaySession.peerPublicKey
|
|
624
|
+
});
|
|
625
|
+
await bridge.connect(
|
|
626
|
+
// onBrowserNeeded — only open a browser for new sessions
|
|
627
|
+
openBrowser ? async () => {
|
|
628
|
+
const bridgeUrl = buildBridgeUrl(keysUrl, relaySession.session, relayUrl, relaySession.publicKey);
|
|
629
|
+
const { default: open } = await import('open');
|
|
630
|
+
await open(bridgeUrl);
|
|
631
|
+
} : void 0,
|
|
632
|
+
// onPeerKeyChanged
|
|
633
|
+
(newPeerKey) => {
|
|
634
|
+
relaySession.peerPublicKey = newPeerKey;
|
|
635
|
+
saveRelaySession(relaySession);
|
|
636
|
+
}
|
|
637
|
+
);
|
|
638
|
+
return bridge;
|
|
639
|
+
}
|
|
640
|
+
function buildBridgeUrl(keysUrl, session, relayUrl, cliPublicKeyHex) {
|
|
641
|
+
const url = new URL("/cli-bridge", keysUrl);
|
|
642
|
+
url.searchParams.set("session", session);
|
|
643
|
+
url.searchParams.set("relay", relayUrl);
|
|
644
|
+
url.hash = `pk=${cliPublicKeyHex}`;
|
|
645
|
+
return url.toString();
|
|
646
|
+
}
|
|
647
|
+
function deleteKeystore() {
|
|
648
|
+
if (fs.existsSync(PATHS.keystore)) {
|
|
649
|
+
fs.unlinkSync(PATHS.keystore);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
function keystoreExists() {
|
|
653
|
+
return fs.existsSync(PATHS.keystore);
|
|
654
|
+
}
|
|
655
|
+
function loadSessionConfig() {
|
|
656
|
+
if (!fs.existsSync(PATHS.sessionConfig)) {
|
|
657
|
+
throw new Error("No session configured. Run `jaw session setup` first.");
|
|
658
|
+
}
|
|
659
|
+
const raw = fs.readFileSync(PATHS.sessionConfig, "utf-8");
|
|
660
|
+
try {
|
|
661
|
+
return JSON.parse(raw);
|
|
662
|
+
} catch {
|
|
663
|
+
throw new Error(`Session config at ${PATHS.sessionConfig} is corrupted. Run \`jaw session setup\` to recreate it.`);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function deleteSessionConfig() {
|
|
667
|
+
if (fs.existsSync(PATHS.sessionConfig)) {
|
|
668
|
+
fs.unlinkSync(PATHS.sessionConfig);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// src/commands/session/revoke.ts
|
|
673
|
+
var SessionRevoke = class _SessionRevoke extends BaseCommand {
|
|
674
|
+
static description = "Revoke on-chain permission and delete local session key.";
|
|
675
|
+
static flags = {
|
|
676
|
+
...BaseCommand.baseFlags
|
|
677
|
+
};
|
|
678
|
+
async run() {
|
|
679
|
+
const { flags } = await this.parse(_SessionRevoke);
|
|
680
|
+
const format = flags.output;
|
|
681
|
+
if (!keystoreExists()) {
|
|
682
|
+
this.log("No session to revoke.");
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
const sessionConfig = loadSessionConfig();
|
|
686
|
+
const isExpired = sessionConfig.expiry <= Date.now() / 1e3;
|
|
687
|
+
if (isExpired) {
|
|
688
|
+
deleteKeystore();
|
|
689
|
+
deleteSessionConfig();
|
|
690
|
+
if (format === "json") {
|
|
691
|
+
this.outputResult({ revoked: true, skippedOnChain: true }, format);
|
|
692
|
+
} else {
|
|
693
|
+
this.log("Session already expired. Cleaned up local files.");
|
|
694
|
+
}
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const config = loadConfig();
|
|
698
|
+
const apiKey = this.resolveApiKey(flags);
|
|
699
|
+
const pm = config.paymasters?.[sessionConfig.chainId];
|
|
700
|
+
if (!flags.quiet) {
|
|
701
|
+
this.log("Opening browser to revoke permission...");
|
|
702
|
+
}
|
|
703
|
+
const bridge = await getBridge({
|
|
704
|
+
keysUrl: config.keysUrl,
|
|
705
|
+
apiKey,
|
|
706
|
+
chainId: sessionConfig.chainId,
|
|
707
|
+
ens: config.ens,
|
|
708
|
+
paymasterUrl: pm?.url
|
|
709
|
+
});
|
|
710
|
+
try {
|
|
711
|
+
await bridge.request("wallet_revokePermissions", [{ id: sessionConfig.permissionId }]);
|
|
712
|
+
} finally {
|
|
713
|
+
bridge.close();
|
|
714
|
+
}
|
|
715
|
+
deleteKeystore();
|
|
716
|
+
deleteSessionConfig();
|
|
717
|
+
if (format === "json") {
|
|
718
|
+
this.outputResult({ revoked: true, skippedOnChain: false }, format);
|
|
719
|
+
} else {
|
|
720
|
+
this.log("Session revoked. On-chain permission removed and local keys deleted.");
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
export { SessionRevoke as default };
|
|
726
|
+
//# sourceMappingURL=revoke.js.map
|
|
727
|
+
//# sourceMappingURL=revoke.js.map
|