@useagentpay/sdk 0.1.1 → 0.1.2

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/index.cjs CHANGED
@@ -111,6 +111,139 @@ var init_errors = __esm({
111
111
  }
112
112
  });
113
113
 
114
+ // src/utils/paths.ts
115
+ function getHomePath() {
116
+ if (process.env.AGENTPAY_HOME) return process.env.AGENTPAY_HOME;
117
+ const local = (0, import_node_path.join)(process.cwd(), "agentpay");
118
+ if ((0, import_node_fs.existsSync)(local)) return local;
119
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), ".agentpay");
120
+ }
121
+ function getCredentialsPath() {
122
+ return (0, import_node_path.join)(getHomePath(), "credentials.enc");
123
+ }
124
+ function getKeysPath() {
125
+ return (0, import_node_path.join)(getHomePath(), "keys");
126
+ }
127
+ function getPublicKeyPath() {
128
+ return (0, import_node_path.join)(getKeysPath(), "public.pem");
129
+ }
130
+ function getPrivateKeyPath() {
131
+ return (0, import_node_path.join)(getKeysPath(), "private.pem");
132
+ }
133
+ function getWalletPath() {
134
+ return (0, import_node_path.join)(getHomePath(), "wallet.json");
135
+ }
136
+ function getTransactionsPath() {
137
+ return (0, import_node_path.join)(getHomePath(), "transactions.json");
138
+ }
139
+ function getAuditPath() {
140
+ return (0, import_node_path.join)(getHomePath(), "audit.log");
141
+ }
142
+ var import_node_os, import_node_path, import_node_fs;
143
+ var init_paths = __esm({
144
+ "src/utils/paths.ts"() {
145
+ "use strict";
146
+ init_cjs_shims();
147
+ import_node_os = require("os");
148
+ import_node_path = require("path");
149
+ import_node_fs = require("fs");
150
+ }
151
+ });
152
+
153
+ // src/auth/keypair.ts
154
+ function generateKeyPair(passphrase) {
155
+ const { publicKey, privateKey } = (0, import_node_crypto3.generateKeyPairSync)("ed25519", {
156
+ publicKeyEncoding: { type: "spki", format: "pem" },
157
+ privateKeyEncoding: {
158
+ type: "pkcs8",
159
+ format: "pem",
160
+ cipher: "aes-256-cbc",
161
+ passphrase
162
+ }
163
+ });
164
+ return { publicKey, privateKey };
165
+ }
166
+ function saveKeyPair(keys, publicPath, privatePath) {
167
+ const pubPath = publicPath ?? getPublicKeyPath();
168
+ const privPath = privatePath ?? getPrivateKeyPath();
169
+ (0, import_node_fs3.mkdirSync)((0, import_node_path3.dirname)(pubPath), { recursive: true });
170
+ (0, import_node_fs3.writeFileSync)(pubPath, keys.publicKey, { mode: 420 });
171
+ (0, import_node_fs3.writeFileSync)(privPath, keys.privateKey, { mode: 384 });
172
+ }
173
+ function loadPublicKey(path) {
174
+ return (0, import_node_fs3.readFileSync)(path ?? getPublicKeyPath(), "utf8");
175
+ }
176
+ function loadPrivateKey(path) {
177
+ return (0, import_node_fs3.readFileSync)(path ?? getPrivateKeyPath(), "utf8");
178
+ }
179
+ var import_node_crypto3, import_node_fs3, import_node_path3;
180
+ var init_keypair = __esm({
181
+ "src/auth/keypair.ts"() {
182
+ "use strict";
183
+ init_cjs_shims();
184
+ import_node_crypto3 = require("crypto");
185
+ import_node_fs3 = require("fs");
186
+ import_node_path3 = require("path");
187
+ init_paths();
188
+ }
189
+ });
190
+
191
+ // src/auth/mandate.ts
192
+ function hashTransactionDetails(details) {
193
+ const canonical = JSON.stringify({
194
+ txId: details.txId,
195
+ merchant: details.merchant,
196
+ amount: details.amount,
197
+ description: details.description,
198
+ timestamp: details.timestamp
199
+ });
200
+ return (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("hex");
201
+ }
202
+ function createMandate(txDetails, privateKeyPem, passphrase) {
203
+ const txHash = hashTransactionDetails(txDetails);
204
+ const data = Buffer.from(txHash);
205
+ const privateKey = (0, import_node_crypto4.createPrivateKey)({
206
+ key: privateKeyPem,
207
+ format: "pem",
208
+ type: "pkcs8",
209
+ passphrase
210
+ });
211
+ const signature = (0, import_node_crypto4.sign)(null, data, privateKey);
212
+ const publicKey = (0, import_node_crypto4.createPublicKey)(privateKey);
213
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
214
+ return {
215
+ txId: txDetails.txId,
216
+ txHash,
217
+ signature: signature.toString("base64"),
218
+ publicKey: publicKeyPem,
219
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
220
+ };
221
+ }
222
+ function verifyMandate(mandate, txDetails) {
223
+ try {
224
+ const txHash = hashTransactionDetails(txDetails);
225
+ if (txHash !== mandate.txHash) return false;
226
+ const data = Buffer.from(txHash);
227
+ const signature = Buffer.from(mandate.signature, "base64");
228
+ const publicKey = (0, import_node_crypto4.createPublicKey)({
229
+ key: mandate.publicKey,
230
+ format: "pem",
231
+ type: "spki"
232
+ });
233
+ return (0, import_node_crypto4.verify)(null, data, publicKey, signature);
234
+ } catch {
235
+ return false;
236
+ }
237
+ }
238
+ var import_node_crypto4;
239
+ var init_mandate = __esm({
240
+ "src/auth/mandate.ts"() {
241
+ "use strict";
242
+ init_cjs_shims();
243
+ import_node_crypto4 = require("crypto");
244
+ }
245
+ });
246
+
114
247
  // src/transactions/poller.ts
115
248
  var poller_exports = {};
116
249
  __export(poller_exports, {
@@ -137,6 +270,828 @@ var init_poller = __esm({
137
270
  }
138
271
  });
139
272
 
273
+ // src/server/approval-html.ts
274
+ function esc(s) {
275
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
276
+ }
277
+ function formatCurrency2(n) {
278
+ return "$" + n.toFixed(2);
279
+ }
280
+ function getApprovalHtml(token, tx) {
281
+ const lines = [];
282
+ lines.push(`<div class="detail"><span class="detail-label">Merchant</span><span class="detail-value">${esc(tx.merchant)}</span></div>`);
283
+ lines.push(`<div class="detail"><span class="detail-label">Amount</span><span class="detail-value">${formatCurrency2(tx.amount)}</span></div>`);
284
+ lines.push(`<div class="detail"><span class="detail-label">Description</span><span class="detail-value">${esc(tx.description)}</span></div>`);
285
+ if (tx.url) {
286
+ lines.push(`<div class="detail"><span class="detail-label">URL</span><span class="detail-value"><a href="${esc(tx.url)}" target="_blank" rel="noopener" style="color:#111;">${esc(tx.url)}</a></span></div>`);
287
+ }
288
+ lines.push(`<div class="detail"><span class="detail-label">Transaction</span><span class="detail-value" style="font-family:monospace;font-size:12px;">${esc(tx.id)}</span></div>`);
289
+ const contextHtml = `<div class="card context-card">${lines.join("")}</div>`;
290
+ return `<!DOCTYPE html>
291
+ <html lang="en">
292
+ <head>
293
+ <meta charset="utf-8">
294
+ <meta name="viewport" content="width=device-width, initial-scale=1">
295
+ <title>AgentPay \u2014 Approve Purchase</title>
296
+ <style>
297
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
298
+ body {
299
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
300
+ background: #f5f5f5;
301
+ color: #111;
302
+ min-height: 100vh;
303
+ display: flex;
304
+ justify-content: center;
305
+ padding: 40px 16px;
306
+ }
307
+ .container { width: 100%; max-width: 420px; }
308
+ h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
309
+ .subtitle { color: #666; font-size: 14px; margin-bottom: 24px; }
310
+ .card {
311
+ background: #fff;
312
+ border-radius: 8px;
313
+ padding: 24px;
314
+ margin-bottom: 16px;
315
+ border: 1px solid #e0e0e0;
316
+ }
317
+ .context-card { padding: 16px 20px; }
318
+ .detail {
319
+ display: flex;
320
+ justify-content: space-between;
321
+ align-items: center;
322
+ padding: 8px 0;
323
+ border-bottom: 1px solid #f0f0f0;
324
+ }
325
+ .detail:last-child { border-bottom: none; }
326
+ .detail-label { font-size: 13px; color: #666; }
327
+ .detail-value { font-size: 14px; font-weight: 600; }
328
+ label { display: block; font-size: 13px; font-weight: 500; color: #333; margin-bottom: 6px; }
329
+ input[type="password"], textarea {
330
+ width: 100%;
331
+ padding: 12px 14px;
332
+ border: 1px solid #d0d0d0;
333
+ border-radius: 8px;
334
+ font-size: 15px;
335
+ font-family: inherit;
336
+ outline: none;
337
+ transition: border-color 0.15s;
338
+ }
339
+ input[type="password"]:focus, textarea:focus { border-color: #111; }
340
+ textarea { resize: vertical; min-height: 60px; margin-top: 8px; }
341
+ .btn-row { display: flex; gap: 12px; margin-top: 16px; }
342
+ .btn-approve, .btn-deny {
343
+ flex: 1;
344
+ padding: 12px;
345
+ border: none;
346
+ border-radius: 8px;
347
+ font-size: 14px;
348
+ font-weight: 600;
349
+ cursor: pointer;
350
+ transition: opacity 0.15s;
351
+ }
352
+ .btn-approve { background: #111; color: #fff; }
353
+ .btn-approve:hover { opacity: 0.85; }
354
+ .btn-approve:disabled { opacity: 0.5; cursor: not-allowed; }
355
+ .btn-deny { background: #fff; color: #c62828; border: 2px solid #c62828; }
356
+ .btn-deny:hover { opacity: 0.85; }
357
+ .btn-deny:disabled { opacity: 0.5; cursor: not-allowed; }
358
+ .error { color: #c62828; font-size: 13px; margin-top: 10px; }
359
+ .success-screen {
360
+ text-align: center;
361
+ padding: 40px 0;
362
+ }
363
+ .checkmark { font-size: 48px; margin-bottom: 16px; }
364
+ .success-msg { font-size: 16px; font-weight: 600; margin-bottom: 8px; }
365
+ .success-hint { font-size: 13px; color: #666; }
366
+ .hidden { display: none; }
367
+ .reason-section { margin-top: 12px; }
368
+ </style>
369
+ </head>
370
+ <body>
371
+ <div class="container">
372
+ <div id="form-view">
373
+ <h1>AgentPay</h1>
374
+ <p class="subtitle">Approve Purchase</p>
375
+ ${contextHtml}
376
+ <div class="card">
377
+ <label for="passphrase">Passphrase</label>
378
+ <input type="password" id="passphrase" placeholder="Enter your passphrase" autofocus>
379
+ <div id="reason-section" class="reason-section hidden">
380
+ <label for="reason">Reason (optional)</label>
381
+ <textarea id="reason" placeholder="Why are you denying this purchase?"></textarea>
382
+ </div>
383
+ <div id="error" class="error hidden"></div>
384
+ <div class="btn-row">
385
+ <button class="btn-approve" id="btn-approve">Approve</button>
386
+ <button class="btn-deny" id="btn-deny">Deny</button>
387
+ </div>
388
+ </div>
389
+ </div>
390
+ <div id="success-view" class="hidden">
391
+ <h1>AgentPay</h1>
392
+ <p class="subtitle" id="success-subtitle"></p>
393
+ <div class="card">
394
+ <div class="success-screen">
395
+ <div class="checkmark" id="success-icon"></div>
396
+ <div class="success-msg" id="success-msg"></div>
397
+ <div class="success-hint">This tab will close automatically.</div>
398
+ </div>
399
+ </div>
400
+ </div>
401
+ </div>
402
+ <script>
403
+ (function() {
404
+ var token = ${JSON.stringify(token)};
405
+ var form = document.getElementById('form-view');
406
+ var successView = document.getElementById('success-view');
407
+ var input = document.getElementById('passphrase');
408
+ var btnApprove = document.getElementById('btn-approve');
409
+ var btnDeny = document.getElementById('btn-deny');
410
+ var errDiv = document.getElementById('error');
411
+ var reasonSection = document.getElementById('reason-section');
412
+ var reasonInput = document.getElementById('reason');
413
+ var successSubtitle = document.getElementById('success-subtitle');
414
+ var successIcon = document.getElementById('success-icon');
415
+ var successMsg = document.getElementById('success-msg');
416
+ var denyMode = false;
417
+
418
+ function showError(msg) {
419
+ errDiv.textContent = msg;
420
+ errDiv.classList.remove('hidden');
421
+ }
422
+
423
+ function clearError() {
424
+ errDiv.classList.add('hidden');
425
+ }
426
+
427
+ function disableButtons() {
428
+ btnApprove.disabled = true;
429
+ btnDeny.disabled = true;
430
+ }
431
+
432
+ function enableButtons() {
433
+ btnApprove.disabled = false;
434
+ btnDeny.disabled = false;
435
+ }
436
+
437
+ function showSuccess(approved) {
438
+ form.classList.add('hidden');
439
+ successView.classList.remove('hidden');
440
+ if (approved) {
441
+ successSubtitle.textContent = 'Purchase Approved';
442
+ successIcon.innerHTML = '&#10003;';
443
+ successIcon.style.color = '#2e7d32';
444
+ successMsg.textContent = 'Transaction approved and signed.';
445
+ } else {
446
+ successSubtitle.textContent = 'Purchase Denied';
447
+ successIcon.innerHTML = '&#10007;';
448
+ successIcon.style.color = '#c62828';
449
+ successMsg.textContent = 'Transaction has been denied.';
450
+ }
451
+ setTimeout(function() { window.close(); }, 3000);
452
+ }
453
+
454
+ function doApprove() {
455
+ var passphrase = input.value;
456
+ if (!passphrase) {
457
+ showError('Passphrase is required to approve.');
458
+ return;
459
+ }
460
+ clearError();
461
+ disableButtons();
462
+ btnApprove.textContent = 'Approving...';
463
+
464
+ fetch('/api/approve', {
465
+ method: 'POST',
466
+ headers: { 'Content-Type': 'application/json' },
467
+ body: JSON.stringify({ token: token, passphrase: passphrase })
468
+ })
469
+ .then(function(res) { return res.json(); })
470
+ .then(function(data) {
471
+ if (data.error) {
472
+ showError(data.error);
473
+ enableButtons();
474
+ btnApprove.textContent = 'Approve';
475
+ } else {
476
+ showSuccess(true);
477
+ }
478
+ })
479
+ .catch(function() {
480
+ showError('Failed to submit. Is the CLI still running?');
481
+ enableButtons();
482
+ btnApprove.textContent = 'Approve';
483
+ });
484
+ }
485
+
486
+ function doReject() {
487
+ if (!denyMode) {
488
+ denyMode = true;
489
+ reasonSection.classList.remove('hidden');
490
+ btnDeny.textContent = 'Confirm Deny';
491
+ reasonInput.focus();
492
+ return;
493
+ }
494
+ clearError();
495
+ disableButtons();
496
+ btnDeny.textContent = 'Denying...';
497
+
498
+ fetch('/api/reject', {
499
+ method: 'POST',
500
+ headers: { 'Content-Type': 'application/json' },
501
+ body: JSON.stringify({ token: token, reason: reasonInput.value || undefined })
502
+ })
503
+ .then(function(res) { return res.json(); })
504
+ .then(function(data) {
505
+ if (data.error) {
506
+ showError(data.error);
507
+ enableButtons();
508
+ btnDeny.textContent = 'Confirm Deny';
509
+ } else {
510
+ showSuccess(false);
511
+ }
512
+ })
513
+ .catch(function() {
514
+ showError('Failed to submit. Is the CLI still running?');
515
+ enableButtons();
516
+ btnDeny.textContent = 'Confirm Deny';
517
+ });
518
+ }
519
+
520
+ btnApprove.addEventListener('click', doApprove);
521
+ btnDeny.addEventListener('click', doReject);
522
+ input.addEventListener('keydown', function(e) {
523
+ if (e.key === 'Enter') doApprove();
524
+ });
525
+ })();
526
+ </script>
527
+ </body>
528
+ </html>`;
529
+ }
530
+ var init_approval_html = __esm({
531
+ "src/server/approval-html.ts"() {
532
+ "use strict";
533
+ init_cjs_shims();
534
+ }
535
+ });
536
+
537
+ // src/utils/open-browser.ts
538
+ function openBrowser(url) {
539
+ const plat = (0, import_node_os2.platform)();
540
+ let cmd;
541
+ if (plat === "darwin") cmd = `open "${url}"`;
542
+ else if (plat === "win32") cmd = `start "" "${url}"`;
543
+ else cmd = `xdg-open "${url}"`;
544
+ (0, import_node_child_process.exec)(cmd, (err) => {
545
+ if (err) {
546
+ console.log(`Open ${url} in your browser.`);
547
+ }
548
+ });
549
+ }
550
+ var import_node_child_process, import_node_os2;
551
+ var init_open_browser = __esm({
552
+ "src/utils/open-browser.ts"() {
553
+ "use strict";
554
+ init_cjs_shims();
555
+ import_node_child_process = require("child_process");
556
+ import_node_os2 = require("os");
557
+ }
558
+ });
559
+
560
+ // src/server/approval-server.ts
561
+ var approval_server_exports = {};
562
+ __export(approval_server_exports, {
563
+ createApprovalServer: () => createApprovalServer,
564
+ requestBrowserApproval: () => requestBrowserApproval
565
+ });
566
+ function parseBody(req) {
567
+ return new Promise((resolve, reject) => {
568
+ const chunks = [];
569
+ let size = 0;
570
+ req.on("data", (chunk) => {
571
+ size += chunk.length;
572
+ if (size > MAX_BODY) {
573
+ req.destroy();
574
+ reject(new Error("Request body too large"));
575
+ return;
576
+ }
577
+ chunks.push(chunk);
578
+ });
579
+ req.on("end", () => {
580
+ try {
581
+ const text = Buffer.concat(chunks).toString("utf8");
582
+ resolve(text ? JSON.parse(text) : {});
583
+ } catch {
584
+ reject(new Error("Invalid JSON"));
585
+ }
586
+ });
587
+ req.on("error", reject);
588
+ });
589
+ }
590
+ function sendJson(res, status, body) {
591
+ const json = JSON.stringify(body);
592
+ res.writeHead(status, {
593
+ "Content-Type": "application/json",
594
+ "Content-Length": Buffer.byteLength(json)
595
+ });
596
+ res.end(json);
597
+ }
598
+ function sendHtml(res, html) {
599
+ res.writeHead(200, {
600
+ "Content-Type": "text/html; charset=utf-8",
601
+ "Content-Length": Buffer.byteLength(html)
602
+ });
603
+ res.end(html);
604
+ }
605
+ function createApprovalServer(tx, tm, audit, options) {
606
+ const nonce = (0, import_node_crypto5.randomBytes)(32).toString("hex");
607
+ let settled = false;
608
+ let tokenUsed = false;
609
+ let resolvePromise;
610
+ let rejectPromise;
611
+ let timer;
612
+ let serverInstance;
613
+ const promise = new Promise((resolve, reject) => {
614
+ resolvePromise = resolve;
615
+ rejectPromise = reject;
616
+ });
617
+ function cleanup() {
618
+ clearTimeout(timer);
619
+ serverInstance.close();
620
+ }
621
+ serverInstance = (0, import_node_http.createServer)(async (req, res) => {
622
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
623
+ const method = req.method ?? "GET";
624
+ try {
625
+ if (method === "GET" && url.pathname === `/approve/${tx.id}`) {
626
+ const token = url.searchParams.get("token");
627
+ if (token !== nonce || tokenUsed) {
628
+ sendHtml(res, "<h1>Invalid or expired link.</h1>");
629
+ return;
630
+ }
631
+ sendHtml(res, getApprovalHtml(nonce, tx));
632
+ return;
633
+ }
634
+ if (method === "POST" && url.pathname === "/api/approve") {
635
+ const body = await parseBody(req);
636
+ if (body.token !== nonce || tokenUsed) {
637
+ sendJson(res, 403, { error: "Invalid or expired token." });
638
+ return;
639
+ }
640
+ const passphrase = body.passphrase;
641
+ if (typeof passphrase !== "string" || !passphrase) {
642
+ sendJson(res, 400, { error: "Passphrase is required." });
643
+ return;
644
+ }
645
+ const currentTx = tm.get(tx.id);
646
+ if (!currentTx || currentTx.status !== "pending") {
647
+ sendJson(res, 400, { error: "Transaction is no longer pending." });
648
+ return;
649
+ }
650
+ try {
651
+ const keyPath = options?.home ? (0, import_node_path7.join)(options.home, "keys", "private.pem") : void 0;
652
+ const privateKeyPem = loadPrivateKey(keyPath);
653
+ const txDetails = {
654
+ txId: tx.id,
655
+ merchant: tx.merchant,
656
+ amount: tx.amount,
657
+ description: tx.description,
658
+ timestamp: tx.createdAt
659
+ };
660
+ const mandate = createMandate(txDetails, privateKeyPem, passphrase);
661
+ tm.approve(tx.id, mandate);
662
+ audit.log("APPROVE", { txId: tx.id, source: "browser-approval", mandateSigned: true });
663
+ } catch (err) {
664
+ const msg = err instanceof Error ? err.message : "Signing failed";
665
+ sendJson(res, 400, { error: msg });
666
+ return;
667
+ }
668
+ tokenUsed = true;
669
+ sendJson(res, 200, { ok: true });
670
+ if (!settled) {
671
+ settled = true;
672
+ cleanup();
673
+ resolvePromise({ action: "approved", passphrase });
674
+ }
675
+ return;
676
+ }
677
+ if (method === "POST" && url.pathname === "/api/reject") {
678
+ const body = await parseBody(req);
679
+ if (body.token !== nonce || tokenUsed) {
680
+ sendJson(res, 403, { error: "Invalid or expired token." });
681
+ return;
682
+ }
683
+ const currentTx = tm.get(tx.id);
684
+ if (!currentTx || currentTx.status !== "pending") {
685
+ sendJson(res, 400, { error: "Transaction is no longer pending." });
686
+ return;
687
+ }
688
+ const reason = typeof body.reason === "string" ? body.reason : void 0;
689
+ tm.reject(tx.id, reason);
690
+ audit.log("REJECT", { txId: tx.id, source: "browser-approval", reason });
691
+ tokenUsed = true;
692
+ sendJson(res, 200, { ok: true });
693
+ if (!settled) {
694
+ settled = true;
695
+ cleanup();
696
+ resolvePromise({ action: "rejected", reason });
697
+ }
698
+ return;
699
+ }
700
+ sendJson(res, 404, { error: "Not found" });
701
+ } catch (err) {
702
+ const message = err instanceof Error ? err.message : "Internal error";
703
+ sendJson(res, 500, { error: message });
704
+ }
705
+ });
706
+ timer = setTimeout(() => {
707
+ if (!settled) {
708
+ settled = true;
709
+ cleanup();
710
+ rejectPromise(new TimeoutError("Approval timed out after 5 minutes."));
711
+ }
712
+ }, TIMEOUT_MS);
713
+ serverInstance.on("error", (err) => {
714
+ if (!settled) {
715
+ settled = true;
716
+ cleanup();
717
+ rejectPromise(err);
718
+ }
719
+ });
720
+ let portValue = 0;
721
+ const handle = {
722
+ server: serverInstance,
723
+ token: nonce,
724
+ get port() {
725
+ return portValue;
726
+ },
727
+ promise
728
+ };
729
+ serverInstance.listen(0, "127.0.0.1", () => {
730
+ const addr = serverInstance.address();
731
+ if (!addr || typeof addr === "string") {
732
+ if (!settled) {
733
+ settled = true;
734
+ cleanup();
735
+ rejectPromise(new Error("Failed to bind server"));
736
+ }
737
+ return;
738
+ }
739
+ portValue = addr.port;
740
+ const pageUrl = `http://127.0.0.1:${addr.port}/approve/${tx.id}?token=${nonce}`;
741
+ if (options?.openBrowser !== false) {
742
+ console.log("Opening approval page in browser...");
743
+ openBrowser(pageUrl);
744
+ }
745
+ });
746
+ return handle;
747
+ }
748
+ function requestBrowserApproval(tx, tm, audit, home) {
749
+ const handle = createApprovalServer(tx, tm, audit, { openBrowser: true, home });
750
+ return handle.promise;
751
+ }
752
+ var import_node_http, import_node_crypto5, import_node_path7, TIMEOUT_MS, MAX_BODY;
753
+ var init_approval_server = __esm({
754
+ "src/server/approval-server.ts"() {
755
+ "use strict";
756
+ init_cjs_shims();
757
+ import_node_http = require("http");
758
+ import_node_crypto5 = require("crypto");
759
+ import_node_path7 = require("path");
760
+ init_approval_html();
761
+ init_open_browser();
762
+ init_keypair();
763
+ init_mandate();
764
+ init_errors();
765
+ TIMEOUT_MS = 5 * 60 * 1e3;
766
+ MAX_BODY = 4096;
767
+ }
768
+ });
769
+
770
+ // src/server/passphrase-html.ts
771
+ function esc2(s) {
772
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
773
+ }
774
+ function formatCurrency3(n) {
775
+ return "$" + n.toFixed(2);
776
+ }
777
+ function getPassphraseHtml(token, context) {
778
+ const actionLabel = context?.action === "approve" ? "Approve Transaction" : "Approve Purchase";
779
+ const buttonLabel = context?.action === "approve" ? "Unlock &amp; Approve" : "Unlock &amp; Approve";
780
+ let contextHtml = "";
781
+ if (context) {
782
+ const lines = [];
783
+ if (context.merchant) lines.push(`<div class="detail"><span class="detail-label">Merchant</span><span class="detail-value">${esc2(context.merchant)}</span></div>`);
784
+ if (context.amount !== void 0) lines.push(`<div class="detail"><span class="detail-label">Amount</span><span class="detail-value">${formatCurrency3(context.amount)}</span></div>`);
785
+ if (context.description) lines.push(`<div class="detail"><span class="detail-label">Description</span><span class="detail-value">${esc2(context.description)}</span></div>`);
786
+ if (context.txId) lines.push(`<div class="detail"><span class="detail-label">Transaction</span><span class="detail-value" style="font-family:monospace;font-size:12px;">${esc2(context.txId)}</span></div>`);
787
+ if (lines.length > 0) {
788
+ contextHtml = `<div class="card context-card">${lines.join("")}</div>`;
789
+ }
790
+ }
791
+ return `<!DOCTYPE html>
792
+ <html lang="en">
793
+ <head>
794
+ <meta charset="utf-8">
795
+ <meta name="viewport" content="width=device-width, initial-scale=1">
796
+ <title>AgentPay \u2014 Passphrase Required</title>
797
+ <style>
798
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
799
+ body {
800
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
801
+ background: #f5f5f5;
802
+ color: #111;
803
+ min-height: 100vh;
804
+ display: flex;
805
+ justify-content: center;
806
+ padding: 40px 16px;
807
+ }
808
+ .container { width: 100%; max-width: 420px; }
809
+ h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
810
+ .subtitle { color: #666; font-size: 14px; margin-bottom: 24px; }
811
+ .card {
812
+ background: #fff;
813
+ border-radius: 8px;
814
+ padding: 24px;
815
+ margin-bottom: 16px;
816
+ border: 1px solid #e0e0e0;
817
+ }
818
+ .context-card { padding: 16px 20px; }
819
+ .detail {
820
+ display: flex;
821
+ justify-content: space-between;
822
+ align-items: center;
823
+ padding: 8px 0;
824
+ border-bottom: 1px solid #f0f0f0;
825
+ }
826
+ .detail:last-child { border-bottom: none; }
827
+ .detail-label { font-size: 13px; color: #666; }
828
+ .detail-value { font-size: 14px; font-weight: 600; }
829
+ label { display: block; font-size: 13px; font-weight: 500; color: #333; margin-bottom: 6px; }
830
+ input[type="password"] {
831
+ width: 100%;
832
+ padding: 12px 14px;
833
+ border: 1px solid #d0d0d0;
834
+ border-radius: 8px;
835
+ font-size: 15px;
836
+ outline: none;
837
+ transition: border-color 0.15s;
838
+ }
839
+ input[type="password"]:focus { border-color: #111; }
840
+ button {
841
+ width: 100%;
842
+ padding: 12px;
843
+ border: none;
844
+ border-radius: 8px;
845
+ font-size: 14px;
846
+ font-weight: 600;
847
+ cursor: pointer;
848
+ transition: opacity 0.15s;
849
+ margin-top: 16px;
850
+ background: #111;
851
+ color: #fff;
852
+ }
853
+ button:hover { opacity: 0.85; }
854
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
855
+ .error { color: #c62828; font-size: 13px; margin-top: 10px; }
856
+ .success-screen {
857
+ text-align: center;
858
+ padding: 40px 0;
859
+ }
860
+ .checkmark {
861
+ font-size: 48px;
862
+ margin-bottom: 16px;
863
+ }
864
+ .success-msg {
865
+ font-size: 16px;
866
+ font-weight: 600;
867
+ margin-bottom: 8px;
868
+ }
869
+ .success-hint {
870
+ font-size: 13px;
871
+ color: #666;
872
+ }
873
+ .hidden { display: none; }
874
+ </style>
875
+ </head>
876
+ <body>
877
+ <div class="container">
878
+ <div id="form-view">
879
+ <h1>AgentPay</h1>
880
+ <p class="subtitle">${esc2(actionLabel)}</p>
881
+ ${contextHtml}
882
+ <div class="card">
883
+ <label for="passphrase">Passphrase</label>
884
+ <input type="password" id="passphrase" placeholder="Enter your passphrase" autofocus>
885
+ <div id="error" class="error hidden"></div>
886
+ <button id="submit">${buttonLabel}</button>
887
+ </div>
888
+ </div>
889
+ <div id="success-view" class="hidden">
890
+ <h1>AgentPay</h1>
891
+ <p class="subtitle">${esc2(actionLabel)}</p>
892
+ <div class="card">
893
+ <div class="success-screen">
894
+ <div class="checkmark">&#10003;</div>
895
+ <div class="success-msg">Passphrase received</div>
896
+ <div class="success-hint">You can close this tab.</div>
897
+ </div>
898
+ </div>
899
+ </div>
900
+ </div>
901
+ <script>
902
+ (function() {
903
+ var token = ${JSON.stringify(token)};
904
+ var form = document.getElementById('form-view');
905
+ var success = document.getElementById('success-view');
906
+ var input = document.getElementById('passphrase');
907
+ var btn = document.getElementById('submit');
908
+ var errDiv = document.getElementById('error');
909
+
910
+ function submit() {
911
+ var passphrase = input.value;
912
+ if (!passphrase) {
913
+ errDiv.textContent = 'Passphrase is required.';
914
+ errDiv.classList.remove('hidden');
915
+ return;
916
+ }
917
+ btn.disabled = true;
918
+ btn.textContent = 'Submitting...';
919
+ errDiv.classList.add('hidden');
920
+
921
+ fetch('/passphrase', {
922
+ method: 'POST',
923
+ headers: { 'Content-Type': 'application/json' },
924
+ body: JSON.stringify({ token: token, passphrase: passphrase })
925
+ })
926
+ .then(function(res) { return res.json(); })
927
+ .then(function(data) {
928
+ if (data.error) {
929
+ errDiv.textContent = data.error;
930
+ errDiv.classList.remove('hidden');
931
+ btn.disabled = false;
932
+ btn.textContent = '${buttonLabel}';
933
+ } else {
934
+ form.classList.add('hidden');
935
+ success.classList.remove('hidden');
936
+ }
937
+ })
938
+ .catch(function() {
939
+ errDiv.textContent = 'Failed to submit. Is the CLI still running?';
940
+ errDiv.classList.remove('hidden');
941
+ btn.disabled = false;
942
+ btn.textContent = '${buttonLabel}';
943
+ });
944
+ }
945
+
946
+ btn.addEventListener('click', submit);
947
+ input.addEventListener('keydown', function(e) {
948
+ if (e.key === 'Enter') submit();
949
+ });
950
+ })();
951
+ </script>
952
+ </body>
953
+ </html>`;
954
+ }
955
+ var init_passphrase_html = __esm({
956
+ "src/server/passphrase-html.ts"() {
957
+ "use strict";
958
+ init_cjs_shims();
959
+ }
960
+ });
961
+
962
+ // src/server/passphrase-server.ts
963
+ var passphrase_server_exports = {};
964
+ __export(passphrase_server_exports, {
965
+ collectPassphrase: () => collectPassphrase
966
+ });
967
+ function parseBody4(req) {
968
+ return new Promise((resolve, reject) => {
969
+ const chunks = [];
970
+ let size = 0;
971
+ req.on("data", (chunk) => {
972
+ size += chunk.length;
973
+ if (size > MAX_BODY4) {
974
+ req.destroy();
975
+ reject(new Error("Request body too large"));
976
+ return;
977
+ }
978
+ chunks.push(chunk);
979
+ });
980
+ req.on("end", () => {
981
+ try {
982
+ const text = Buffer.concat(chunks).toString("utf8");
983
+ resolve(text ? JSON.parse(text) : {});
984
+ } catch {
985
+ reject(new Error("Invalid JSON"));
986
+ }
987
+ });
988
+ req.on("error", reject);
989
+ });
990
+ }
991
+ function sendJson4(res, status, body) {
992
+ const json = JSON.stringify(body);
993
+ res.writeHead(status, {
994
+ "Content-Type": "application/json",
995
+ "Content-Length": Buffer.byteLength(json)
996
+ });
997
+ res.end(json);
998
+ }
999
+ function sendHtml4(res, html) {
1000
+ res.writeHead(200, {
1001
+ "Content-Type": "text/html; charset=utf-8",
1002
+ "Content-Length": Buffer.byteLength(html)
1003
+ });
1004
+ res.end(html);
1005
+ }
1006
+ function collectPassphrase(context) {
1007
+ return new Promise((resolve, reject) => {
1008
+ const nonce = (0, import_node_crypto7.randomBytes)(32).toString("hex");
1009
+ let settled = false;
1010
+ const server = (0, import_node_http4.createServer)(async (req, res) => {
1011
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1012
+ const method = req.method ?? "GET";
1013
+ try {
1014
+ if (method === "GET" && url.pathname === "/passphrase") {
1015
+ const token = url.searchParams.get("token");
1016
+ if (token !== nonce) {
1017
+ sendHtml4(res, "<h1>Invalid or expired link.</h1>");
1018
+ return;
1019
+ }
1020
+ sendHtml4(res, getPassphraseHtml(nonce, context));
1021
+ } else if (method === "POST" && url.pathname === "/passphrase") {
1022
+ const body = await parseBody4(req);
1023
+ if (body.token !== nonce) {
1024
+ sendJson4(res, 403, { error: "Invalid token." });
1025
+ return;
1026
+ }
1027
+ const passphrase = body.passphrase;
1028
+ if (typeof passphrase !== "string" || !passphrase) {
1029
+ sendJson4(res, 400, { error: "Passphrase is required." });
1030
+ return;
1031
+ }
1032
+ sendJson4(res, 200, { ok: true });
1033
+ if (!settled) {
1034
+ settled = true;
1035
+ cleanup();
1036
+ resolve(passphrase);
1037
+ }
1038
+ } else {
1039
+ sendJson4(res, 404, { error: "Not found" });
1040
+ }
1041
+ } catch (err) {
1042
+ const message = err instanceof Error ? err.message : "Internal error";
1043
+ sendJson4(res, 500, { error: message });
1044
+ }
1045
+ });
1046
+ const timer = setTimeout(() => {
1047
+ if (!settled) {
1048
+ settled = true;
1049
+ cleanup();
1050
+ reject(new TimeoutError("Passphrase entry timed out after 5 minutes."));
1051
+ }
1052
+ }, TIMEOUT_MS3);
1053
+ function cleanup() {
1054
+ clearTimeout(timer);
1055
+ server.close();
1056
+ }
1057
+ server.on("error", (err) => {
1058
+ if (!settled) {
1059
+ settled = true;
1060
+ cleanup();
1061
+ reject(err);
1062
+ }
1063
+ });
1064
+ server.listen(0, "127.0.0.1", () => {
1065
+ const addr = server.address();
1066
+ if (!addr || typeof addr === "string") {
1067
+ if (!settled) {
1068
+ settled = true;
1069
+ cleanup();
1070
+ reject(new Error("Failed to bind server"));
1071
+ }
1072
+ return;
1073
+ }
1074
+ const url = `http://127.0.0.1:${addr.port}/passphrase?token=${nonce}`;
1075
+ console.log("Waiting for passphrase entry in browser...");
1076
+ openBrowser(url);
1077
+ });
1078
+ });
1079
+ }
1080
+ var import_node_http4, import_node_crypto7, TIMEOUT_MS3, MAX_BODY4;
1081
+ var init_passphrase_server = __esm({
1082
+ "src/server/passphrase-server.ts"() {
1083
+ "use strict";
1084
+ init_cjs_shims();
1085
+ import_node_http4 = require("http");
1086
+ import_node_crypto7 = require("crypto");
1087
+ init_passphrase_html();
1088
+ init_open_browser();
1089
+ init_errors();
1090
+ TIMEOUT_MS3 = 5 * 60 * 1e3;
1091
+ MAX_BODY4 = 4096;
1092
+ }
1093
+ });
1094
+
140
1095
  // src/index.ts
141
1096
  var src_exports = {};
142
1097
  __export(src_exports, {
@@ -176,8 +1131,16 @@ __export(src_exports, {
176
1131
  loadPrivateKey: () => loadPrivateKey,
177
1132
  loadPublicKey: () => loadPublicKey,
178
1133
  loadVault: () => loadVault,
1134
+ openBrowser: () => openBrowser,
1135
+ promptConfirm: () => promptConfirm,
1136
+ promptInput: () => promptInput,
1137
+ promptPassphrase: () => promptPassphrase,
1138
+ promptPassphraseSafe: () => promptPassphraseSafe,
1139
+ requestBrowserApproval: () => requestBrowserApproval,
1140
+ requestBrowserSetup: () => requestBrowserSetup,
179
1141
  saveKeyPair: () => saveKeyPair,
180
1142
  saveVault: () => saveVault,
1143
+ startDashboardServer: () => startServer,
181
1144
  verifyMandate: () => verifyMandate,
182
1145
  waitForApproval: () => waitForApproval
183
1146
  });
@@ -236,41 +1199,16 @@ function formatStatus(data) {
236
1199
  return lines.join("\n");
237
1200
  }
238
1201
 
239
- // src/utils/paths.ts
240
- init_cjs_shims();
241
- var import_node_os = require("os");
242
- var import_node_path = require("path");
243
- function getHomePath() {
244
- return process.env.AGENTPAY_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".agentpay");
245
- }
246
- function getCredentialsPath() {
247
- return (0, import_node_path.join)(getHomePath(), "credentials.enc");
248
- }
249
- function getKeysPath() {
250
- return (0, import_node_path.join)(getHomePath(), "keys");
251
- }
252
- function getPublicKeyPath() {
253
- return (0, import_node_path.join)(getKeysPath(), "public.pem");
254
- }
255
- function getPrivateKeyPath() {
256
- return (0, import_node_path.join)(getKeysPath(), "private.pem");
257
- }
258
- function getWalletPath() {
259
- return (0, import_node_path.join)(getHomePath(), "wallet.json");
260
- }
261
- function getTransactionsPath() {
262
- return (0, import_node_path.join)(getHomePath(), "transactions.json");
263
- }
264
- function getAuditPath() {
265
- return (0, import_node_path.join)(getHomePath(), "audit.log");
266
- }
1202
+ // src/index.ts
1203
+ init_paths();
267
1204
 
268
1205
  // src/vault/vault.ts
269
1206
  init_cjs_shims();
270
1207
  var import_node_crypto2 = require("crypto");
271
- var import_node_fs = require("fs");
1208
+ var import_node_fs2 = require("fs");
272
1209
  var import_node_path2 = require("path");
273
1210
  init_errors();
1211
+ init_paths();
274
1212
  var ALGORITHM = "aes-256-gcm";
275
1213
  var PBKDF2_ITERATIONS = 1e5;
276
1214
  var PBKDF2_DIGEST = "sha512";
@@ -312,105 +1250,29 @@ function decrypt(vault, passphrase) {
312
1250
  }
313
1251
  function saveVault(vault, path) {
314
1252
  const filePath = path ?? getCredentialsPath();
315
- (0, import_node_fs.mkdirSync)((0, import_node_path2.dirname)(filePath), { recursive: true });
316
- (0, import_node_fs.writeFileSync)(filePath, JSON.stringify(vault, null, 2), { mode: 384 });
317
- }
318
- function loadVault(path) {
319
- const filePath = path ?? getCredentialsPath();
320
- try {
321
- const data = (0, import_node_fs.readFileSync)(filePath, "utf8");
322
- return JSON.parse(data);
323
- } catch {
324
- throw new NotSetupError();
325
- }
326
- }
327
-
328
- // src/auth/keypair.ts
329
- init_cjs_shims();
330
- var import_node_crypto3 = require("crypto");
331
- var import_node_fs2 = require("fs");
332
- var import_node_path3 = require("path");
333
- function generateKeyPair(passphrase) {
334
- const { publicKey, privateKey } = (0, import_node_crypto3.generateKeyPairSync)("ed25519", {
335
- publicKeyEncoding: { type: "spki", format: "pem" },
336
- privateKeyEncoding: {
337
- type: "pkcs8",
338
- format: "pem",
339
- cipher: "aes-256-cbc",
340
- passphrase
341
- }
342
- });
343
- return { publicKey, privateKey };
344
- }
345
- function saveKeyPair(keys, publicPath, privatePath) {
346
- const pubPath = publicPath ?? getPublicKeyPath();
347
- const privPath = privatePath ?? getPrivateKeyPath();
348
- (0, import_node_fs2.mkdirSync)((0, import_node_path3.dirname)(pubPath), { recursive: true });
349
- (0, import_node_fs2.writeFileSync)(pubPath, keys.publicKey, { mode: 420 });
350
- (0, import_node_fs2.writeFileSync)(privPath, keys.privateKey, { mode: 384 });
351
- }
352
- function loadPublicKey(path) {
353
- return (0, import_node_fs2.readFileSync)(path ?? getPublicKeyPath(), "utf8");
354
- }
355
- function loadPrivateKey(path) {
356
- return (0, import_node_fs2.readFileSync)(path ?? getPrivateKeyPath(), "utf8");
357
- }
358
-
359
- // src/auth/mandate.ts
360
- init_cjs_shims();
361
- var import_node_crypto4 = require("crypto");
362
- function hashTransactionDetails(details) {
363
- const canonical = JSON.stringify({
364
- txId: details.txId,
365
- merchant: details.merchant,
366
- amount: details.amount,
367
- description: details.description,
368
- timestamp: details.timestamp
369
- });
370
- return (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("hex");
371
- }
372
- function createMandate(txDetails, privateKeyPem, passphrase) {
373
- const txHash = hashTransactionDetails(txDetails);
374
- const data = Buffer.from(txHash);
375
- const privateKey = (0, import_node_crypto4.createPrivateKey)({
376
- key: privateKeyPem,
377
- format: "pem",
378
- type: "pkcs8",
379
- passphrase
380
- });
381
- const signature = (0, import_node_crypto4.sign)(null, data, privateKey);
382
- const publicKey = (0, import_node_crypto4.createPublicKey)(privateKey);
383
- const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
384
- return {
385
- txId: txDetails.txId,
386
- txHash,
387
- signature: signature.toString("base64"),
388
- publicKey: publicKeyPem,
389
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
390
- };
1253
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(filePath), { recursive: true });
1254
+ (0, import_node_fs2.writeFileSync)(filePath, JSON.stringify(vault, null, 2), { mode: 384 });
391
1255
  }
392
- function verifyMandate(mandate, txDetails) {
1256
+ function loadVault(path) {
1257
+ const filePath = path ?? getCredentialsPath();
393
1258
  try {
394
- const txHash = hashTransactionDetails(txDetails);
395
- if (txHash !== mandate.txHash) return false;
396
- const data = Buffer.from(txHash);
397
- const signature = Buffer.from(mandate.signature, "base64");
398
- const publicKey = (0, import_node_crypto4.createPublicKey)({
399
- key: mandate.publicKey,
400
- format: "pem",
401
- type: "spki"
402
- });
403
- return (0, import_node_crypto4.verify)(null, data, publicKey, signature);
1259
+ const data = (0, import_node_fs2.readFileSync)(filePath, "utf8");
1260
+ return JSON.parse(data);
404
1261
  } catch {
405
- return false;
1262
+ throw new NotSetupError();
406
1263
  }
407
1264
  }
408
1265
 
1266
+ // src/index.ts
1267
+ init_keypair();
1268
+ init_mandate();
1269
+
409
1270
  // src/budget/budget.ts
410
1271
  init_cjs_shims();
411
- var import_node_fs3 = require("fs");
1272
+ var import_node_fs4 = require("fs");
412
1273
  var import_node_path4 = require("path");
413
1274
  init_errors();
1275
+ init_paths();
414
1276
  var BudgetManager = class {
415
1277
  walletPath;
416
1278
  constructor(walletPath) {
@@ -418,15 +1280,15 @@ var BudgetManager = class {
418
1280
  }
419
1281
  getWallet() {
420
1282
  try {
421
- const data = (0, import_node_fs3.readFileSync)(this.walletPath, "utf8");
1283
+ const data = (0, import_node_fs4.readFileSync)(this.walletPath, "utf8");
422
1284
  return JSON.parse(data);
423
1285
  } catch {
424
1286
  throw new NotSetupError();
425
1287
  }
426
1288
  }
427
1289
  saveWallet(wallet) {
428
- (0, import_node_fs3.mkdirSync)((0, import_node_path4.dirname)(this.walletPath), { recursive: true });
429
- (0, import_node_fs3.writeFileSync)(this.walletPath, JSON.stringify(wallet, null, 2), { mode: 384 });
1290
+ (0, import_node_fs4.mkdirSync)((0, import_node_path4.dirname)(this.walletPath), { recursive: true });
1291
+ (0, import_node_fs4.writeFileSync)(this.walletPath, JSON.stringify(wallet, null, 2), { mode: 384 });
430
1292
  }
431
1293
  setBudget(amount) {
432
1294
  let wallet;
@@ -486,8 +1348,9 @@ var BudgetManager = class {
486
1348
 
487
1349
  // src/transactions/manager.ts
488
1350
  init_cjs_shims();
489
- var import_node_fs4 = require("fs");
1351
+ var import_node_fs5 = require("fs");
490
1352
  var import_node_path5 = require("path");
1353
+ init_paths();
491
1354
  var TransactionManager = class {
492
1355
  txPath;
493
1356
  constructor(txPath) {
@@ -495,15 +1358,15 @@ var TransactionManager = class {
495
1358
  }
496
1359
  loadAll() {
497
1360
  try {
498
- const data = (0, import_node_fs4.readFileSync)(this.txPath, "utf8");
1361
+ const data = (0, import_node_fs5.readFileSync)(this.txPath, "utf8");
499
1362
  return JSON.parse(data);
500
1363
  } catch {
501
1364
  return [];
502
1365
  }
503
1366
  }
504
1367
  saveAll(transactions) {
505
- (0, import_node_fs4.mkdirSync)((0, import_node_path5.dirname)(this.txPath), { recursive: true });
506
- (0, import_node_fs4.writeFileSync)(this.txPath, JSON.stringify(transactions, null, 2), { mode: 384 });
1368
+ (0, import_node_fs5.mkdirSync)((0, import_node_path5.dirname)(this.txPath), { recursive: true });
1369
+ (0, import_node_fs5.writeFileSync)(this.txPath, JSON.stringify(transactions, null, 2), { mode: 384 });
507
1370
  }
508
1371
  propose(options) {
509
1372
  const transactions = this.loadAll();
@@ -583,8 +1446,9 @@ init_poller();
583
1446
 
584
1447
  // src/audit/logger.ts
585
1448
  init_cjs_shims();
586
- var import_node_fs5 = require("fs");
1449
+ var import_node_fs6 = require("fs");
587
1450
  var import_node_path6 = require("path");
1451
+ init_paths();
588
1452
  var AuditLogger = class {
589
1453
  logPath;
590
1454
  constructor(logPath) {
@@ -595,12 +1459,12 @@ var AuditLogger = class {
595
1459
  const detailsStr = JSON.stringify(details);
596
1460
  const entry = `${timestamp} ${action} ${detailsStr}
597
1461
  `;
598
- (0, import_node_fs5.mkdirSync)((0, import_node_path6.dirname)(this.logPath), { recursive: true });
599
- (0, import_node_fs5.appendFileSync)(this.logPath, entry, { mode: 384 });
1462
+ (0, import_node_fs6.mkdirSync)((0, import_node_path6.dirname)(this.logPath), { recursive: true });
1463
+ (0, import_node_fs6.appendFileSync)(this.logPath, entry, { mode: 384 });
600
1464
  }
601
1465
  getLog() {
602
1466
  try {
603
- const data = (0, import_node_fs5.readFileSync)(this.logPath, "utf8");
1467
+ const data = (0, import_node_fs6.readFileSync)(this.logPath, "utf8");
604
1468
  return data.trim().split("\n").filter(Boolean);
605
1469
  } catch {
606
1470
  return [];
@@ -610,7 +1474,6 @@ var AuditLogger = class {
610
1474
 
611
1475
  // src/executor/executor.ts
612
1476
  init_cjs_shims();
613
- var import_stagehand = require("@browserbasehq/stagehand");
614
1477
  init_errors();
615
1478
 
616
1479
  // src/executor/placeholder.ts
@@ -674,29 +1537,33 @@ function credentialsToSwapMap(creds) {
674
1537
  };
675
1538
  }
676
1539
 
1540
+ // src/executor/providers/local-provider.ts
1541
+ init_cjs_shims();
1542
+ var import_stagehand = require("@browserbasehq/stagehand");
1543
+ var LocalBrowserProvider = class {
1544
+ createStagehand(modelApiKey) {
1545
+ return new import_stagehand.Stagehand({
1546
+ env: "LOCAL",
1547
+ model: modelApiKey ? { modelName: "claude-3-7-sonnet-latest", apiKey: modelApiKey } : void 0
1548
+ });
1549
+ }
1550
+ async close() {
1551
+ }
1552
+ };
1553
+
677
1554
  // src/executor/executor.ts
678
1555
  var PurchaseExecutor = class {
679
- config;
1556
+ provider;
1557
+ modelApiKey;
680
1558
  stagehand = null;
1559
+ proxyUrl;
1560
+ originalBaseUrl;
681
1561
  constructor(config) {
682
- this.config = {
683
- browserbaseApiKey: config?.browserbaseApiKey ?? process.env.BROWSERBASE_API_KEY,
684
- browserbaseProjectId: config?.browserbaseProjectId ?? process.env.BROWSERBASE_PROJECT_ID,
685
- modelApiKey: config?.modelApiKey ?? process.env.ANTHROPIC_API_KEY
686
- };
1562
+ this.provider = config?.provider ?? new LocalBrowserProvider();
1563
+ this.modelApiKey = config?.modelApiKey ?? process.env.ANTHROPIC_API_KEY;
687
1564
  }
688
1565
  createStagehand() {
689
- return new import_stagehand.Stagehand({
690
- env: "BROWSERBASE",
691
- apiKey: this.config.browserbaseApiKey,
692
- projectId: this.config.browserbaseProjectId,
693
- model: this.config.modelApiKey ? { modelName: "claude-3-7-sonnet-latest", apiKey: this.config.modelApiKey } : void 0,
694
- browserbaseSessionCreateParams: {
695
- browserSettings: {
696
- recordSession: false
697
- }
698
- }
699
- });
1566
+ return this.provider.createStagehand(this.modelApiKey);
700
1567
  }
701
1568
  /**
702
1569
  * Phase 1: Open browser, navigate to URL, extract price and product info.
@@ -856,13 +1723,1292 @@ var PurchaseExecutor = class {
856
1723
  this.stagehand = null;
857
1724
  }
858
1725
  } catch {
1726
+ } finally {
1727
+ await this.provider.close();
1728
+ }
1729
+ }
1730
+ };
1731
+
1732
+ // src/index.ts
1733
+ init_approval_server();
1734
+
1735
+ // src/server/setup-server.ts
1736
+ init_cjs_shims();
1737
+ var import_node_http2 = require("http");
1738
+ var import_node_crypto6 = require("crypto");
1739
+ var import_node_fs7 = require("fs");
1740
+ var import_node_path8 = require("path");
1741
+
1742
+ // src/server/setup-html.ts
1743
+ init_cjs_shims();
1744
+ function getSetupHtml(token) {
1745
+ return `<!DOCTYPE html>
1746
+ <html lang="en">
1747
+ <head>
1748
+ <meta charset="utf-8">
1749
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1750
+ <title>AgentPay \u2014 Setup</title>
1751
+ <style>
1752
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
1753
+ body {
1754
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1755
+ background: #f5f5f5;
1756
+ color: #111;
1757
+ min-height: 100vh;
1758
+ display: flex;
1759
+ justify-content: center;
1760
+ padding: 40px 16px;
1761
+ }
1762
+ .container { width: 100%; max-width: 480px; }
1763
+ h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
1764
+ .subtitle { color: #666; font-size: 14px; margin-bottom: 24px; }
1765
+ .card {
1766
+ background: #fff;
1767
+ border-radius: 8px;
1768
+ padding: 24px;
1769
+ margin-bottom: 16px;
1770
+ border: 1px solid #e0e0e0;
1771
+ }
1772
+ .card-title {
1773
+ font-size: 15px;
1774
+ font-weight: 600;
1775
+ margin-bottom: 16px;
1776
+ padding-bottom: 8px;
1777
+ border-bottom: 1px solid #f0f0f0;
1778
+ }
1779
+ label { display: block; font-size: 13px; font-weight: 500; color: #333; margin-bottom: 6px; }
1780
+ input[type="text"], input[type="password"], input[type="email"], input[type="tel"], input[type="number"] {
1781
+ width: 100%;
1782
+ padding: 12px 14px;
1783
+ border: 1px solid #d0d0d0;
1784
+ border-radius: 8px;
1785
+ font-size: 15px;
1786
+ font-family: inherit;
1787
+ outline: none;
1788
+ transition: border-color 0.15s;
1789
+ }
1790
+ input:focus { border-color: #111; }
1791
+ .field { margin-bottom: 14px; }
1792
+ .field:last-child { margin-bottom: 0; }
1793
+ .row { display: flex; gap: 12px; }
1794
+ .row > .field { flex: 1; }
1795
+ .checkbox-row {
1796
+ display: flex;
1797
+ align-items: center;
1798
+ gap: 8px;
1799
+ margin-bottom: 14px;
1800
+ }
1801
+ .checkbox-row input[type="checkbox"] {
1802
+ width: 16px;
1803
+ height: 16px;
1804
+ cursor: pointer;
1805
+ }
1806
+ .checkbox-row label {
1807
+ margin-bottom: 0;
1808
+ cursor: pointer;
1809
+ font-size: 14px;
1810
+ }
1811
+ .btn-submit {
1812
+ width: 100%;
1813
+ padding: 14px;
1814
+ border: none;
1815
+ border-radius: 8px;
1816
+ font-size: 15px;
1817
+ font-weight: 600;
1818
+ cursor: pointer;
1819
+ background: #111;
1820
+ color: #fff;
1821
+ transition: opacity 0.15s;
1822
+ }
1823
+ .btn-submit:hover { opacity: 0.85; }
1824
+ .btn-submit:disabled { opacity: 0.5; cursor: not-allowed; }
1825
+ .error { color: #c62828; font-size: 13px; margin-top: 10px; }
1826
+ .success-screen {
1827
+ text-align: center;
1828
+ padding: 40px 0;
1829
+ }
1830
+ .checkmark { font-size: 48px; margin-bottom: 16px; color: #2e7d32; }
1831
+ .success-msg { font-size: 16px; font-weight: 600; margin-bottom: 8px; }
1832
+ .success-hint { font-size: 13px; color: #666; }
1833
+ .hidden { display: none; }
1834
+ .hint { font-size: 12px; color: #999; margin-top: 4px; }
1835
+ </style>
1836
+ </head>
1837
+ <body>
1838
+ <div class="container">
1839
+ <div id="form-view">
1840
+ <h1>AgentPay</h1>
1841
+ <p class="subtitle">Initial Setup</p>
1842
+
1843
+ <div class="card">
1844
+ <div class="card-title">Passphrase</div>
1845
+ <div class="field">
1846
+ <label for="passphrase">Choose a passphrase</label>
1847
+ <input type="password" id="passphrase" placeholder="Enter passphrase" autofocus>
1848
+ </div>
1849
+ <div class="field">
1850
+ <label for="passphrase-confirm">Confirm passphrase</label>
1851
+ <input type="password" id="passphrase-confirm" placeholder="Re-enter passphrase">
1852
+ </div>
1853
+ </div>
1854
+
1855
+ <div class="card">
1856
+ <div class="card-title">Budget</div>
1857
+ <div class="row">
1858
+ <div class="field">
1859
+ <label for="budget">Total budget ($)</label>
1860
+ <input type="number" id="budget" placeholder="0" min="0" step="0.01">
1861
+ </div>
1862
+ <div class="field">
1863
+ <label for="limit-per-tx">Per-transaction limit ($)</label>
1864
+ <input type="number" id="limit-per-tx" placeholder="0" min="0" step="0.01">
1865
+ </div>
1866
+ </div>
1867
+ <div class="hint">Leave at 0 to set later via <code>agentpay budget</code>.</div>
1868
+ </div>
1869
+
1870
+ <div class="card">
1871
+ <div class="card-title">Card</div>
1872
+ <div class="field">
1873
+ <label for="card-number">Card number</label>
1874
+ <input type="text" id="card-number" placeholder="4111 1111 1111 1111" autocomplete="cc-number">
1875
+ </div>
1876
+ <div class="row">
1877
+ <div class="field">
1878
+ <label for="card-expiry">Expiry (MM/YY)</label>
1879
+ <input type="text" id="card-expiry" placeholder="MM/YY" autocomplete="cc-exp" maxlength="5">
1880
+ </div>
1881
+ <div class="field">
1882
+ <label for="card-cvv">CVV</label>
1883
+ <input type="text" id="card-cvv" placeholder="123" autocomplete="cc-csc" maxlength="4">
1884
+ </div>
1885
+ </div>
1886
+ </div>
1887
+
1888
+ <div class="card">
1889
+ <div class="card-title">Personal</div>
1890
+ <div class="field">
1891
+ <label for="name">Full name</label>
1892
+ <input type="text" id="name" placeholder="Jane Doe" autocomplete="name">
1893
+ </div>
1894
+ <div class="row">
1895
+ <div class="field">
1896
+ <label for="email">Email</label>
1897
+ <input type="email" id="email" placeholder="jane@example.com" autocomplete="email">
1898
+ </div>
1899
+ <div class="field">
1900
+ <label for="phone">Phone</label>
1901
+ <input type="tel" id="phone" placeholder="+1 555-0100" autocomplete="tel">
1902
+ </div>
1903
+ </div>
1904
+ </div>
1905
+
1906
+ <div class="card">
1907
+ <div class="card-title">Billing Address</div>
1908
+ <div class="field">
1909
+ <label for="billing-street">Street</label>
1910
+ <input type="text" id="billing-street" autocomplete="billing street-address">
1911
+ </div>
1912
+ <div class="row">
1913
+ <div class="field">
1914
+ <label for="billing-city">City</label>
1915
+ <input type="text" id="billing-city" autocomplete="billing address-level2">
1916
+ </div>
1917
+ <div class="field">
1918
+ <label for="billing-state">State</label>
1919
+ <input type="text" id="billing-state" autocomplete="billing address-level1">
1920
+ </div>
1921
+ </div>
1922
+ <div class="row">
1923
+ <div class="field">
1924
+ <label for="billing-zip">ZIP</label>
1925
+ <input type="text" id="billing-zip" autocomplete="billing postal-code">
1926
+ </div>
1927
+ <div class="field">
1928
+ <label for="billing-country">Country</label>
1929
+ <input type="text" id="billing-country" placeholder="US" autocomplete="billing country">
1930
+ </div>
1931
+ </div>
1932
+ </div>
1933
+
1934
+ <div class="card">
1935
+ <div class="card-title">Shipping Address</div>
1936
+ <div class="checkbox-row">
1937
+ <input type="checkbox" id="same-as-billing" checked>
1938
+ <label for="same-as-billing">Same as billing</label>
1939
+ </div>
1940
+ <div id="shipping-fields" class="hidden">
1941
+ <div class="field">
1942
+ <label for="shipping-street">Street</label>
1943
+ <input type="text" id="shipping-street" autocomplete="shipping street-address">
1944
+ </div>
1945
+ <div class="row">
1946
+ <div class="field">
1947
+ <label for="shipping-city">City</label>
1948
+ <input type="text" id="shipping-city" autocomplete="shipping address-level2">
1949
+ </div>
1950
+ <div class="field">
1951
+ <label for="shipping-state">State</label>
1952
+ <input type="text" id="shipping-state" autocomplete="shipping address-level1">
1953
+ </div>
1954
+ </div>
1955
+ <div class="row">
1956
+ <div class="field">
1957
+ <label for="shipping-zip">ZIP</label>
1958
+ <input type="text" id="shipping-zip" autocomplete="shipping postal-code">
1959
+ </div>
1960
+ <div class="field">
1961
+ <label for="shipping-country">Country</label>
1962
+ <input type="text" id="shipping-country" placeholder="US" autocomplete="shipping country">
1963
+ </div>
1964
+ </div>
1965
+ </div>
1966
+ </div>
1967
+
1968
+ <div id="error" class="error hidden"></div>
1969
+ <button class="btn-submit" id="btn-submit">Complete Setup</button>
1970
+ </div>
1971
+
1972
+ <div id="success-view" class="hidden">
1973
+ <h1>AgentPay</h1>
1974
+ <p class="subtitle">Setup Complete</p>
1975
+ <div class="card">
1976
+ <div class="success-screen">
1977
+ <div class="checkmark">&#10003;</div>
1978
+ <div class="success-msg">Your wallet is ready.</div>
1979
+ <div class="success-hint">You can close this tab and return to the terminal.</div>
1980
+ </div>
1981
+ </div>
1982
+ </div>
1983
+ </div>
1984
+ <script>
1985
+ (function() {
1986
+ var token = ${JSON.stringify(token)};
1987
+ var formView = document.getElementById('form-view');
1988
+ var successView = document.getElementById('success-view');
1989
+ var btnSubmit = document.getElementById('btn-submit');
1990
+ var errDiv = document.getElementById('error');
1991
+ var sameAsBilling = document.getElementById('same-as-billing');
1992
+ var shippingFields = document.getElementById('shipping-fields');
1993
+
1994
+ sameAsBilling.addEventListener('change', function() {
1995
+ shippingFields.classList.toggle('hidden', sameAsBilling.checked);
1996
+ });
1997
+
1998
+ function val(id) { return document.getElementById(id).value.trim(); }
1999
+
2000
+ function showError(msg) {
2001
+ errDiv.textContent = msg;
2002
+ errDiv.classList.remove('hidden');
2003
+ }
2004
+
2005
+ function clearError() {
2006
+ errDiv.classList.add('hidden');
2007
+ }
2008
+
2009
+ btnSubmit.addEventListener('click', function() {
2010
+ clearError();
2011
+
2012
+ var passphrase = val('passphrase');
2013
+ var passphraseConfirm = val('passphrase-confirm');
2014
+
2015
+ if (!passphrase) { showError('Passphrase is required.'); return; }
2016
+ if (passphrase !== passphraseConfirm) { showError('Passphrases do not match.'); return; }
2017
+
2018
+ var cardNumber = val('card-number');
2019
+ var cardExpiry = val('card-expiry');
2020
+ var cardCvv = val('card-cvv');
2021
+ if (!cardNumber || !cardExpiry || !cardCvv) { showError('Card number, expiry, and CVV are required.'); return; }
2022
+
2023
+ var name = val('name');
2024
+ var email = val('email');
2025
+ var phone = val('phone');
2026
+ if (!name || !email || !phone) { showError('Name, email, and phone are required.'); return; }
2027
+
2028
+ var billingStreet = val('billing-street');
2029
+ var billingCity = val('billing-city');
2030
+ var billingState = val('billing-state');
2031
+ var billingZip = val('billing-zip');
2032
+ var billingCountry = val('billing-country');
2033
+ if (!billingStreet || !billingCity || !billingState || !billingZip || !billingCountry) {
2034
+ showError('All billing address fields are required.'); return;
2035
+ }
2036
+
2037
+ var shippingStreet, shippingCity, shippingState, shippingZip, shippingCountry;
2038
+ if (sameAsBilling.checked) {
2039
+ shippingStreet = billingStreet;
2040
+ shippingCity = billingCity;
2041
+ shippingState = billingState;
2042
+ shippingZip = billingZip;
2043
+ shippingCountry = billingCountry;
2044
+ } else {
2045
+ shippingStreet = val('shipping-street');
2046
+ shippingCity = val('shipping-city');
2047
+ shippingState = val('shipping-state');
2048
+ shippingZip = val('shipping-zip');
2049
+ shippingCountry = val('shipping-country');
2050
+ if (!shippingStreet || !shippingCity || !shippingState || !shippingZip || !shippingCountry) {
2051
+ showError('All shipping address fields are required.'); return;
2052
+ }
2053
+ }
2054
+
2055
+ var budget = parseFloat(document.getElementById('budget').value) || 0;
2056
+ var limitPerTx = parseFloat(document.getElementById('limit-per-tx').value) || 0;
2057
+
2058
+ btnSubmit.disabled = true;
2059
+ btnSubmit.textContent = 'Setting up...';
2060
+
2061
+ fetch('/api/setup', {
2062
+ method: 'POST',
2063
+ headers: { 'Content-Type': 'application/json' },
2064
+ body: JSON.stringify({
2065
+ token: token,
2066
+ passphrase: passphrase,
2067
+ budget: budget,
2068
+ limitPerTx: limitPerTx,
2069
+ card: { number: cardNumber, expiry: cardExpiry, cvv: cardCvv },
2070
+ name: name,
2071
+ email: email,
2072
+ phone: phone,
2073
+ billingAddress: { street: billingStreet, city: billingCity, state: billingState, zip: billingZip, country: billingCountry },
2074
+ shippingAddress: { street: shippingStreet, city: shippingCity, state: shippingState, zip: shippingZip, country: shippingCountry }
2075
+ })
2076
+ })
2077
+ .then(function(res) { return res.json(); })
2078
+ .then(function(data) {
2079
+ if (data.error) {
2080
+ showError(data.error);
2081
+ btnSubmit.disabled = false;
2082
+ btnSubmit.textContent = 'Complete Setup';
2083
+ } else {
2084
+ formView.classList.add('hidden');
2085
+ successView.classList.remove('hidden');
2086
+ setTimeout(function() { window.close(); }, 3000);
2087
+ }
2088
+ })
2089
+ .catch(function() {
2090
+ showError('Failed to submit. Is the CLI still running?');
2091
+ btnSubmit.disabled = false;
2092
+ btnSubmit.textContent = 'Complete Setup';
2093
+ });
2094
+ });
2095
+ })();
2096
+ </script>
2097
+ </body>
2098
+ </html>`;
2099
+ }
2100
+
2101
+ // src/server/setup-server.ts
2102
+ init_open_browser();
2103
+ init_keypair();
2104
+ init_paths();
2105
+ init_errors();
2106
+ var TIMEOUT_MS2 = 10 * 60 * 1e3;
2107
+ var MAX_BODY2 = 8192;
2108
+ function parseBody2(req) {
2109
+ return new Promise((resolve, reject) => {
2110
+ const chunks = [];
2111
+ let size = 0;
2112
+ req.on("data", (chunk) => {
2113
+ size += chunk.length;
2114
+ if (size > MAX_BODY2) {
2115
+ req.destroy();
2116
+ reject(new Error("Request body too large"));
2117
+ return;
2118
+ }
2119
+ chunks.push(chunk);
2120
+ });
2121
+ req.on("end", () => {
2122
+ try {
2123
+ const text = Buffer.concat(chunks).toString("utf8");
2124
+ resolve(text ? JSON.parse(text) : {});
2125
+ } catch {
2126
+ reject(new Error("Invalid JSON"));
2127
+ }
2128
+ });
2129
+ req.on("error", reject);
2130
+ });
2131
+ }
2132
+ function sendJson2(res, status, body) {
2133
+ const json = JSON.stringify(body);
2134
+ res.writeHead(status, {
2135
+ "Content-Type": "application/json",
2136
+ "Content-Length": Buffer.byteLength(json)
2137
+ });
2138
+ res.end(json);
2139
+ }
2140
+ function sendHtml2(res, html) {
2141
+ res.writeHead(200, {
2142
+ "Content-Type": "text/html; charset=utf-8",
2143
+ "Content-Length": Buffer.byteLength(html)
2144
+ });
2145
+ res.end(html);
2146
+ }
2147
+ function isNonEmptyString(val) {
2148
+ return typeof val === "string" && val.length > 0;
2149
+ }
2150
+ function isAddress(val) {
2151
+ if (!val || typeof val !== "object") return false;
2152
+ const a = val;
2153
+ return isNonEmptyString(a.street) && isNonEmptyString(a.city) && isNonEmptyString(a.state) && isNonEmptyString(a.zip) && isNonEmptyString(a.country);
2154
+ }
2155
+ function isCard(val) {
2156
+ if (!val || typeof val !== "object") return false;
2157
+ const c = val;
2158
+ return isNonEmptyString(c.number) && isNonEmptyString(c.expiry) && isNonEmptyString(c.cvv);
2159
+ }
2160
+ function createSetupServer(options) {
2161
+ const nonce = (0, import_node_crypto6.randomBytes)(32).toString("hex");
2162
+ let settled = false;
2163
+ let tokenUsed = false;
2164
+ let resolvePromise;
2165
+ let rejectPromise;
2166
+ let timer;
2167
+ let serverInstance;
2168
+ const promise = new Promise((resolve, reject) => {
2169
+ resolvePromise = resolve;
2170
+ rejectPromise = reject;
2171
+ });
2172
+ function cleanup() {
2173
+ clearTimeout(timer);
2174
+ serverInstance.close();
2175
+ }
2176
+ const home = options?.home ?? getHomePath();
2177
+ serverInstance = (0, import_node_http2.createServer)(async (req, res) => {
2178
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
2179
+ const method = req.method ?? "GET";
2180
+ try {
2181
+ if (method === "GET" && url.pathname === "/setup") {
2182
+ const token = url.searchParams.get("token");
2183
+ if (token !== nonce || tokenUsed) {
2184
+ sendHtml2(res, "<h1>Invalid or expired link.</h1>");
2185
+ return;
2186
+ }
2187
+ sendHtml2(res, getSetupHtml(nonce));
2188
+ return;
2189
+ }
2190
+ if (method === "POST" && url.pathname === "/api/setup") {
2191
+ const body = await parseBody2(req);
2192
+ if (body.token !== nonce || tokenUsed) {
2193
+ sendJson2(res, 403, { error: "Invalid or expired token." });
2194
+ return;
2195
+ }
2196
+ const passphrase = body.passphrase;
2197
+ if (!isNonEmptyString(passphrase)) {
2198
+ sendJson2(res, 400, { error: "Passphrase is required." });
2199
+ return;
2200
+ }
2201
+ if (!isCard(body.card)) {
2202
+ sendJson2(res, 400, { error: "Card number, expiry, and CVV are required." });
2203
+ return;
2204
+ }
2205
+ if (!isNonEmptyString(body.name) || !isNonEmptyString(body.email) || !isNonEmptyString(body.phone)) {
2206
+ sendJson2(res, 400, { error: "Name, email, and phone are required." });
2207
+ return;
2208
+ }
2209
+ if (!isAddress(body.billingAddress)) {
2210
+ sendJson2(res, 400, { error: "Complete billing address is required." });
2211
+ return;
2212
+ }
2213
+ if (!isAddress(body.shippingAddress)) {
2214
+ sendJson2(res, 400, { error: "Complete shipping address is required." });
2215
+ return;
2216
+ }
2217
+ try {
2218
+ (0, import_node_fs7.mkdirSync)(home, { recursive: true });
2219
+ const credentials = {
2220
+ card: { number: body.card.number, expiry: body.card.expiry, cvv: body.card.cvv },
2221
+ name: body.name,
2222
+ billingAddress: {
2223
+ street: body.billingAddress.street,
2224
+ city: body.billingAddress.city,
2225
+ state: body.billingAddress.state,
2226
+ zip: body.billingAddress.zip,
2227
+ country: body.billingAddress.country
2228
+ },
2229
+ shippingAddress: {
2230
+ street: body.shippingAddress.street,
2231
+ city: body.shippingAddress.city,
2232
+ state: body.shippingAddress.state,
2233
+ zip: body.shippingAddress.zip,
2234
+ country: body.shippingAddress.country
2235
+ },
2236
+ email: body.email,
2237
+ phone: body.phone
2238
+ };
2239
+ const credPath = (0, import_node_path8.join)(home, "credentials.enc");
2240
+ const vault = encrypt(credentials, passphrase);
2241
+ saveVault(vault, credPath);
2242
+ const keysDir = (0, import_node_path8.join)(home, "keys");
2243
+ (0, import_node_fs7.mkdirSync)(keysDir, { recursive: true });
2244
+ const keys = generateKeyPair(passphrase);
2245
+ saveKeyPair(keys, (0, import_node_path8.join)(keysDir, "public.pem"), (0, import_node_path8.join)(keysDir, "private.pem"));
2246
+ const budget = typeof body.budget === "number" ? body.budget : 0;
2247
+ const limitPerTx = typeof body.limitPerTx === "number" ? body.limitPerTx : 0;
2248
+ const bm = new BudgetManager((0, import_node_path8.join)(home, "wallet.json"));
2249
+ bm.initWallet(budget, limitPerTx);
2250
+ const audit = new AuditLogger((0, import_node_path8.join)(home, "audit.log"));
2251
+ audit.log("SETUP", { message: "credentials encrypted, keypair generated, wallet initialized", source: "browser-setup" });
2252
+ } catch (err) {
2253
+ const msg = err instanceof Error ? err.message : "Setup failed";
2254
+ sendJson2(res, 500, { error: msg });
2255
+ return;
2256
+ }
2257
+ tokenUsed = true;
2258
+ sendJson2(res, 200, { ok: true });
2259
+ if (!settled) {
2260
+ settled = true;
2261
+ cleanup();
2262
+ resolvePromise({ completed: true });
2263
+ }
2264
+ return;
2265
+ }
2266
+ sendJson2(res, 404, { error: "Not found" });
2267
+ } catch (err) {
2268
+ const message = err instanceof Error ? err.message : "Internal error";
2269
+ sendJson2(res, 500, { error: message });
2270
+ }
2271
+ });
2272
+ timer = setTimeout(() => {
2273
+ if (!settled) {
2274
+ settled = true;
2275
+ cleanup();
2276
+ rejectPromise(new TimeoutError("Setup timed out after 10 minutes."));
2277
+ }
2278
+ }, TIMEOUT_MS2);
2279
+ serverInstance.on("error", (err) => {
2280
+ if (!settled) {
2281
+ settled = true;
2282
+ cleanup();
2283
+ rejectPromise(err);
2284
+ }
2285
+ });
2286
+ let portValue = 0;
2287
+ const handle = {
2288
+ server: serverInstance,
2289
+ token: nonce,
2290
+ get port() {
2291
+ return portValue;
2292
+ },
2293
+ promise
2294
+ };
2295
+ serverInstance.listen(0, "127.0.0.1", () => {
2296
+ const addr = serverInstance.address();
2297
+ if (!addr || typeof addr === "string") {
2298
+ if (!settled) {
2299
+ settled = true;
2300
+ cleanup();
2301
+ rejectPromise(new Error("Failed to bind server"));
2302
+ }
2303
+ return;
859
2304
  }
2305
+ portValue = addr.port;
2306
+ const pageUrl = `http://127.0.0.1:${addr.port}/setup?token=${nonce}`;
2307
+ if (options?.openBrowser !== false) {
2308
+ console.log("Opening setup form in browser...");
2309
+ openBrowser(pageUrl);
2310
+ }
2311
+ });
2312
+ return handle;
2313
+ }
2314
+ function requestBrowserSetup(home) {
2315
+ const handle = createSetupServer({ openBrowser: true, home });
2316
+ return handle.promise;
2317
+ }
2318
+
2319
+ // src/server/index.ts
2320
+ init_cjs_shims();
2321
+ var import_node_http3 = require("http");
2322
+
2323
+ // src/server/html.ts
2324
+ init_cjs_shims();
2325
+ function getDashboardHtml() {
2326
+ return `<!DOCTYPE html>
2327
+ <html lang="en">
2328
+ <head>
2329
+ <meta charset="utf-8">
2330
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2331
+ <title>AgentPay Dashboard</title>
2332
+ <style>
2333
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
2334
+ body {
2335
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
2336
+ background: #f5f5f5;
2337
+ color: #111;
2338
+ min-height: 100vh;
2339
+ display: flex;
2340
+ justify-content: center;
2341
+ padding: 40px 16px;
2342
+ }
2343
+ .container { width: 100%; max-width: 480px; }
2344
+ h1 { font-size: 24px; font-weight: 700; margin-bottom: 8px; }
2345
+ h2 { font-size: 18px; font-weight: 600; margin-bottom: 12px; }
2346
+ .subtitle { color: #666; font-size: 14px; margin-bottom: 32px; }
2347
+ .card {
2348
+ background: #fff;
2349
+ border-radius: 8px;
2350
+ padding: 24px;
2351
+ margin-bottom: 16px;
2352
+ border: 1px solid #e0e0e0;
2353
+ }
2354
+ label { display: block; font-size: 13px; font-weight: 500; color: #333; margin-bottom: 4px; }
2355
+ input, select {
2356
+ width: 100%;
2357
+ padding: 10px 12px;
2358
+ border: 1px solid #d0d0d0;
2359
+ border-radius: 8px;
2360
+ font-size: 14px;
2361
+ margin-bottom: 16px;
2362
+ outline: none;
2363
+ transition: border-color 0.15s;
2364
+ }
2365
+ input:focus { border-color: #111; }
2366
+ .row { display: flex; gap: 12px; }
2367
+ .row > div { flex: 1; }
2368
+ button {
2369
+ width: 100%;
2370
+ padding: 12px;
2371
+ border: none;
2372
+ border-radius: 8px;
2373
+ font-size: 14px;
2374
+ font-weight: 600;
2375
+ cursor: pointer;
2376
+ transition: opacity 0.15s;
2377
+ }
2378
+ button:hover { opacity: 0.85; }
2379
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
2380
+ .btn-primary { background: #111; color: #fff; }
2381
+ .btn-secondary { background: #e0e0e0; color: #111; }
2382
+
2383
+ /* Progress bar for wizard */
2384
+ .progress { display: flex; gap: 6px; margin-bottom: 24px; }
2385
+ .progress .step {
2386
+ flex: 1; height: 4px; border-radius: 2px; background: #e0e0e0;
2387
+ transition: background 0.3s;
2388
+ }
2389
+ .progress .step.active { background: #111; }
2390
+
2391
+ /* Balance display */
2392
+ .balance-display {
2393
+ text-align: center;
2394
+ padding: 32px 0;
2395
+ }
2396
+ .balance-amount {
2397
+ font-size: 48px;
2398
+ font-weight: 700;
2399
+ letter-spacing: -1px;
860
2400
  }
2401
+ .balance-label { font-size: 13px; color: #666; margin-top: 4px; }
2402
+
2403
+ /* Budget bar */
2404
+ .budget-bar-container { margin: 16px 0; }
2405
+ .budget-bar {
2406
+ height: 8px;
2407
+ background: #e0e0e0;
2408
+ border-radius: 4px;
2409
+ overflow: hidden;
2410
+ }
2411
+ .budget-bar-fill {
2412
+ height: 100%;
2413
+ background: #111;
2414
+ border-radius: 4px;
2415
+ transition: width 0.3s;
2416
+ }
2417
+ .budget-bar-labels {
2418
+ display: flex;
2419
+ justify-content: space-between;
2420
+ font-size: 12px;
2421
+ color: #666;
2422
+ margin-top: 4px;
2423
+ }
2424
+
2425
+ /* Stats grid */
2426
+ .stats { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px; }
2427
+ .stat { text-align: center; padding: 12px; background: #f9f9f9; border-radius: 8px; }
2428
+ .stat-value { font-size: 18px; font-weight: 700; }
2429
+ .stat-label { font-size: 11px; color: #666; margin-top: 2px; }
2430
+
2431
+ /* Add funds inline */
2432
+ .add-funds-row { display: flex; gap: 8px; }
2433
+ .add-funds-row input { margin-bottom: 0; flex: 1; }
2434
+ .add-funds-row button { width: auto; padding: 10px 20px; }
2435
+
2436
+ /* Transactions */
2437
+ .tx-list { margin-top: 12px; }
2438
+ .tx-item {
2439
+ display: flex;
2440
+ justify-content: space-between;
2441
+ align-items: center;
2442
+ padding: 10px 0;
2443
+ border-bottom: 1px solid #f0f0f0;
2444
+ font-size: 13px;
2445
+ }
2446
+ .tx-item:last-child { border-bottom: none; }
2447
+ .tx-merchant { font-weight: 500; }
2448
+ .tx-amount { font-weight: 600; }
2449
+ .tx-status {
2450
+ font-size: 11px;
2451
+ padding: 2px 6px;
2452
+ border-radius: 4px;
2453
+ font-weight: 500;
2454
+ }
2455
+ .tx-status.completed { background: #e6f4ea; color: #1e7e34; }
2456
+ .tx-status.pending { background: #fff8e1; color: #f57f17; }
2457
+ .tx-status.failed { background: #fde8e8; color: #c62828; }
2458
+ .tx-status.rejected { background: #fde8e8; color: #c62828; }
2459
+ .tx-status.approved { background: #e3f2fd; color: #1565c0; }
2460
+ .tx-status.executing { background: #e3f2fd; color: #1565c0; }
2461
+
2462
+ .error { color: #c62828; font-size: 13px; margin-top: 8px; }
2463
+ .success { color: #1e7e34; font-size: 13px; margin-top: 8px; }
2464
+ .hidden { display: none; }
2465
+
2466
+ /* Checkbox row for same-as-billing */
2467
+ .checkbox-row {
2468
+ display: flex;
2469
+ align-items: center;
2470
+ gap: 8px;
2471
+ margin-bottom: 16px;
2472
+ }
2473
+ .checkbox-row input { width: auto; margin: 0; }
2474
+ .checkbox-row label { margin: 0; }
2475
+ </style>
2476
+ </head>
2477
+ <body>
2478
+ <div class="container" id="app">
2479
+ <div id="loading">Loading...</div>
2480
+ </div>
2481
+
2482
+ <script>
2483
+ const App = {
2484
+ state: { isSetup: false, wallet: null, recentTransactions: [], wizardStep: 1 },
2485
+
2486
+ async init() {
2487
+ try {
2488
+ const res = await fetch('/api/status');
2489
+ const data = await res.json();
2490
+ this.state.isSetup = data.isSetup;
2491
+ this.state.wallet = data.wallet;
2492
+ this.state.recentTransactions = data.recentTransactions || [];
2493
+ } catch (e) {
2494
+ console.error('Failed to load status', e);
2495
+ }
2496
+ this.render();
2497
+ },
2498
+
2499
+ render() {
2500
+ const app = document.getElementById('app');
2501
+ if (this.state.isSetup && this.state.wallet) {
2502
+ app.innerHTML = this.renderDashboard();
2503
+ this.bindDashboard();
2504
+ } else if (this.state.isSetup) {
2505
+ app.innerHTML = '<div class="card"><h2>Setup detected</h2><p>Wallet data could not be loaded. Try running <code>agentpay budget --set 100</code> from the CLI.</p></div>';
2506
+ } else {
2507
+ app.innerHTML = this.renderWizard();
2508
+ this.bindWizard();
2509
+ }
2510
+ },
2511
+
2512
+ fmt(n) {
2513
+ return '$' + Number(n).toFixed(2);
2514
+ },
2515
+
2516
+ renderDashboard() {
2517
+ const w = this.state.wallet;
2518
+ const pct = w.budget > 0 ? Math.min(100, (w.spent / w.budget) * 100) : 0;
2519
+ const txHtml = this.state.recentTransactions.length === 0
2520
+ ? '<p style="color:#666;font-size:13px;">No transactions yet.</p>'
2521
+ : this.state.recentTransactions.map(tx => \`
2522
+ <div class="tx-item">
2523
+ <div>
2524
+ <div class="tx-merchant">\${this.esc(tx.merchant)}</div>
2525
+ <div style="color:#999;font-size:11px;">\${new Date(tx.createdAt).toLocaleDateString()}</div>
2526
+ </div>
2527
+ <div style="text-align:right">
2528
+ <div class="tx-amount">\${this.fmt(tx.amount)}</div>
2529
+ <span class="tx-status \${tx.status}">\${tx.status}</span>
2530
+ </div>
2531
+ </div>\`).join('');
2532
+
2533
+ return \`
2534
+ <h1>AgentPay</h1>
2535
+ <p class="subtitle">Wallet Dashboard</p>
2536
+
2537
+ <div class="card">
2538
+ <div class="balance-display">
2539
+ <div class="balance-amount">\${this.fmt(w.balance)}</div>
2540
+ <div class="balance-label">Available Balance</div>
2541
+ </div>
2542
+ <div class="budget-bar-container">
2543
+ <div class="budget-bar"><div class="budget-bar-fill" style="width:\${pct.toFixed(1)}%"></div></div>
2544
+ <div class="budget-bar-labels">
2545
+ <span>\${this.fmt(w.spent)} spent</span>
2546
+ <span>\${this.fmt(w.budget)} budget</span>
2547
+ </div>
2548
+ </div>
2549
+ </div>
2550
+
2551
+ <div class="card">
2552
+ <div class="stats">
2553
+ <div class="stat"><div class="stat-value">\${this.fmt(w.budget)}</div><div class="stat-label">Total Budget</div></div>
2554
+ <div class="stat"><div class="stat-value">\${this.fmt(w.spent)}</div><div class="stat-label">Total Spent</div></div>
2555
+ <div class="stat"><div class="stat-value">\${this.fmt(w.balance)}</div><div class="stat-label">Remaining</div></div>
2556
+ <div class="stat"><div class="stat-value">\${w.limitPerTx > 0 ? this.fmt(w.limitPerTx) : 'None'}</div><div class="stat-label">Per-Tx Limit</div></div>
2557
+ </div>
2558
+ </div>
2559
+
2560
+ <div class="card">
2561
+ <h2>Add Funds</h2>
2562
+ <div class="add-funds-row">
2563
+ <input type="number" id="fundAmount" placeholder="Amount" min="0.01" step="0.01">
2564
+ <button class="btn-primary" id="fundBtn">Add</button>
2565
+ </div>
2566
+ <div id="fundMsg"></div>
2567
+ </div>
2568
+
2569
+ <div class="card">
2570
+ <h2>Recent Transactions</h2>
2571
+ <div class="tx-list">\${txHtml}</div>
2572
+ </div>
2573
+ \`;
2574
+ },
2575
+
2576
+ bindDashboard() {
2577
+ const btn = document.getElementById('fundBtn');
2578
+ const input = document.getElementById('fundAmount');
2579
+ const msg = document.getElementById('fundMsg');
2580
+
2581
+ btn.addEventListener('click', async () => {
2582
+ const amount = parseFloat(input.value);
2583
+ if (!amount || amount <= 0) {
2584
+ msg.innerHTML = '<p class="error">Enter a valid amount.</p>';
2585
+ return;
2586
+ }
2587
+ btn.disabled = true;
2588
+ btn.textContent = '...';
2589
+ try {
2590
+ const res = await fetch('/api/fund', {
2591
+ method: 'POST',
2592
+ headers: { 'Content-Type': 'application/json' },
2593
+ body: JSON.stringify({ amount }),
2594
+ });
2595
+ const data = await res.json();
2596
+ if (data.error) {
2597
+ msg.innerHTML = '<p class="error">' + this.esc(data.error) + '</p>';
2598
+ } else {
2599
+ this.state.wallet = data.wallet;
2600
+ input.value = '';
2601
+ this.render();
2602
+ }
2603
+ } catch (e) {
2604
+ msg.innerHTML = '<p class="error">Request failed.</p>';
2605
+ }
2606
+ btn.disabled = false;
2607
+ btn.textContent = 'Add';
2608
+ });
2609
+ },
2610
+
2611
+ renderWizard() {
2612
+ const step = this.state.wizardStep;
2613
+ const steps = [1, 2, 3, 4];
2614
+ const progressHtml = '<div class="progress">' + steps.map(s =>
2615
+ '<div class="step' + (s <= step ? ' active' : '') + '"></div>'
2616
+ ).join('') + '</div>';
2617
+
2618
+ const titles = ['Create Passphrase', 'Card Information', 'Personal Details', 'Budget & Limits'];
2619
+
2620
+ let fields = '';
2621
+ if (step === 1) {
2622
+ fields = \`
2623
+ <label for="w_pass">Passphrase</label>
2624
+ <input type="password" id="w_pass" placeholder="Choose a strong passphrase">
2625
+ <label for="w_pass2">Confirm Passphrase</label>
2626
+ <input type="password" id="w_pass2" placeholder="Confirm your passphrase">
2627
+ \`;
2628
+ } else if (step === 2) {
2629
+ fields = \`
2630
+ <label for="w_cardNum">Card Number</label>
2631
+ <input type="text" id="w_cardNum" placeholder="4242 4242 4242 4242">
2632
+ <div class="row">
2633
+ <div><label for="w_expiry">Expiry</label><input type="text" id="w_expiry" placeholder="MM/YY"></div>
2634
+ <div><label for="w_cvv">CVV</label><input type="text" id="w_cvv" placeholder="123"></div>
2635
+ </div>
2636
+ \`;
2637
+ } else if (step === 3) {
2638
+ fields = \`
2639
+ <label for="w_name">Full Name</label>
2640
+ <input type="text" id="w_name" placeholder="Jane Doe">
2641
+ <div class="row">
2642
+ <div><label for="w_email">Email</label><input type="email" id="w_email" placeholder="jane@example.com"></div>
2643
+ <div><label for="w_phone">Phone</label><input type="tel" id="w_phone" placeholder="+1 555 0123"></div>
2644
+ </div>
2645
+ <label for="w_street">Street Address</label>
2646
+ <input type="text" id="w_street" placeholder="123 Main St">
2647
+ <div class="row">
2648
+ <div><label for="w_city">City</label><input type="text" id="w_city" placeholder="San Francisco"></div>
2649
+ <div><label for="w_state">State</label><input type="text" id="w_state" placeholder="CA"></div>
2650
+ </div>
2651
+ <div class="row">
2652
+ <div><label for="w_zip">ZIP</label><input type="text" id="w_zip" placeholder="94102"></div>
2653
+ <div><label for="w_country">Country</label><input type="text" id="w_country" placeholder="US" value="US"></div>
2654
+ </div>
2655
+ \`;
2656
+ } else if (step === 4) {
2657
+ fields = \`
2658
+ <label for="w_budget">Initial Budget ($)</label>
2659
+ <input type="number" id="w_budget" placeholder="200" min="0" step="0.01">
2660
+ <label for="w_limit">Per-Transaction Limit ($)</label>
2661
+ <input type="number" id="w_limit" placeholder="50 (0 = no limit)" min="0" step="0.01">
2662
+ \`;
2663
+ }
2664
+
2665
+ return \`
2666
+ <h1>AgentPay</h1>
2667
+ <p class="subtitle">Step \${step} of 4 \u2014 \${titles[step - 1]}</p>
2668
+ \${progressHtml}
2669
+ <div class="card">
2670
+ \${fields}
2671
+ <div id="wizardError"></div>
2672
+ <div style="display:flex;gap:8px;margin-top:8px;">
2673
+ \${step > 1 ? '<button class="btn-secondary" id="wizBack">Back</button>' : ''}
2674
+ <button class="btn-primary" id="wizNext">\${step === 4 ? 'Complete Setup' : 'Continue'}</button>
2675
+ </div>
2676
+ </div>
2677
+ \`;
2678
+ },
2679
+
2680
+ // Wizard form data persisted across steps
2681
+ wizardData: {},
2682
+
2683
+ bindWizard() {
2684
+ const step = this.state.wizardStep;
2685
+ const errDiv = document.getElementById('wizardError');
2686
+ const nextBtn = document.getElementById('wizNext');
2687
+ const backBtn = document.getElementById('wizBack');
2688
+
2689
+ // Restore saved data into fields
2690
+ this.restoreWizardFields(step);
2691
+
2692
+ if (backBtn) {
2693
+ backBtn.addEventListener('click', () => {
2694
+ this.saveWizardFields(step);
2695
+ this.state.wizardStep--;
2696
+ this.render();
2697
+ });
2698
+ }
2699
+
2700
+ nextBtn.addEventListener('click', async () => {
2701
+ errDiv.innerHTML = '';
2702
+
2703
+ if (step === 1) {
2704
+ const pass = document.getElementById('w_pass').value;
2705
+ const pass2 = document.getElementById('w_pass2').value;
2706
+ if (!pass) { errDiv.innerHTML = '<p class="error">Passphrase is required.</p>'; return; }
2707
+ if (pass !== pass2) { errDiv.innerHTML = '<p class="error">Passphrases do not match.</p>'; return; }
2708
+ this.wizardData.passphrase = pass;
2709
+ this.state.wizardStep = 2;
2710
+ this.render();
2711
+ } else if (step === 2) {
2712
+ this.saveWizardFields(step);
2713
+ const d = this.wizardData;
2714
+ if (!d.cardNumber) { errDiv.innerHTML = '<p class="error">Card number is required.</p>'; return; }
2715
+ if (!d.expiry) { errDiv.innerHTML = '<p class="error">Expiry is required.</p>'; return; }
2716
+ if (!d.cvv) { errDiv.innerHTML = '<p class="error">CVV is required.</p>'; return; }
2717
+ this.state.wizardStep = 3;
2718
+ this.render();
2719
+ } else if (step === 3) {
2720
+ this.saveWizardFields(step);
2721
+ const d = this.wizardData;
2722
+ if (!d.name) { errDiv.innerHTML = '<p class="error">Full name is required.</p>'; return; }
2723
+ this.state.wizardStep = 4;
2724
+ this.render();
2725
+ } else if (step === 4) {
2726
+ this.saveWizardFields(step);
2727
+ const d = this.wizardData;
2728
+
2729
+ nextBtn.disabled = true;
2730
+ nextBtn.textContent = 'Setting up...';
2731
+
2732
+ try {
2733
+ const res = await fetch('/api/setup', {
2734
+ method: 'POST',
2735
+ headers: { 'Content-Type': 'application/json' },
2736
+ body: JSON.stringify({
2737
+ passphrase: d.passphrase,
2738
+ credentials: {
2739
+ card: { number: d.cardNumber, expiry: d.expiry, cvv: d.cvv },
2740
+ name: d.name,
2741
+ billingAddress: { street: d.street || '', city: d.city || '', state: d.state || '', zip: d.zip || '', country: d.country || 'US' },
2742
+ shippingAddress: { street: d.street || '', city: d.city || '', state: d.state || '', zip: d.zip || '', country: d.country || 'US' },
2743
+ email: d.email || '',
2744
+ phone: d.phone || '',
2745
+ },
2746
+ budget: parseFloat(d.budget) || 0,
2747
+ limitPerTx: parseFloat(d.limit) || 0,
2748
+ }),
2749
+ });
2750
+ const result = await res.json();
2751
+ if (result.error) {
2752
+ errDiv.innerHTML = '<p class="error">' + this.esc(result.error) + '</p>';
2753
+ nextBtn.disabled = false;
2754
+ nextBtn.textContent = 'Complete Setup';
2755
+ } else {
2756
+ this.state.isSetup = true;
2757
+ this.state.wallet = result.wallet;
2758
+ this.state.recentTransactions = [];
2759
+ this.wizardData = {};
2760
+ this.render();
2761
+ }
2762
+ } catch (e) {
2763
+ errDiv.innerHTML = '<p class="error">Setup request failed.</p>';
2764
+ nextBtn.disabled = false;
2765
+ nextBtn.textContent = 'Complete Setup';
2766
+ }
2767
+ }
2768
+ });
2769
+ },
2770
+
2771
+ saveWizardFields(step) {
2772
+ const val = (id) => { const el = document.getElementById(id); return el ? el.value : ''; };
2773
+ if (step === 2) {
2774
+ this.wizardData.cardNumber = val('w_cardNum');
2775
+ this.wizardData.expiry = val('w_expiry');
2776
+ this.wizardData.cvv = val('w_cvv');
2777
+ } else if (step === 3) {
2778
+ this.wizardData.name = val('w_name');
2779
+ this.wizardData.email = val('w_email');
2780
+ this.wizardData.phone = val('w_phone');
2781
+ this.wizardData.street = val('w_street');
2782
+ this.wizardData.city = val('w_city');
2783
+ this.wizardData.state = val('w_state');
2784
+ this.wizardData.zip = val('w_zip');
2785
+ this.wizardData.country = val('w_country');
2786
+ } else if (step === 4) {
2787
+ this.wizardData.budget = val('w_budget');
2788
+ this.wizardData.limit = val('w_limit');
2789
+ }
2790
+ },
2791
+
2792
+ restoreWizardFields(step) {
2793
+ const set = (id, val) => { const el = document.getElementById(id); if (el && val) el.value = val; };
2794
+ if (step === 2) {
2795
+ set('w_cardNum', this.wizardData.cardNumber);
2796
+ set('w_expiry', this.wizardData.expiry);
2797
+ set('w_cvv', this.wizardData.cvv);
2798
+ } else if (step === 3) {
2799
+ set('w_name', this.wizardData.name);
2800
+ set('w_email', this.wizardData.email);
2801
+ set('w_phone', this.wizardData.phone);
2802
+ set('w_street', this.wizardData.street);
2803
+ set('w_city', this.wizardData.city);
2804
+ set('w_state', this.wizardData.state);
2805
+ set('w_zip', this.wizardData.zip);
2806
+ set('w_country', this.wizardData.country);
2807
+ } else if (step === 4) {
2808
+ set('w_budget', this.wizardData.budget);
2809
+ set('w_limit', this.wizardData.limit);
2810
+ }
2811
+ },
2812
+
2813
+ esc(s) {
2814
+ const d = document.createElement('div');
2815
+ d.textContent = s;
2816
+ return d.innerHTML;
2817
+ },
861
2818
  };
862
2819
 
2820
+ App.init();
2821
+ </script>
2822
+ </body>
2823
+ </html>`;
2824
+ }
2825
+
2826
+ // src/server/routes.ts
2827
+ init_cjs_shims();
2828
+ var import_node_fs8 = require("fs");
2829
+ init_keypair();
2830
+ init_paths();
2831
+ function handleGetStatus() {
2832
+ const isSetup = (0, import_node_fs8.existsSync)(getCredentialsPath());
2833
+ if (!isSetup) {
2834
+ return { status: 200, body: { isSetup: false } };
2835
+ }
2836
+ try {
2837
+ const bm = new BudgetManager();
2838
+ const wallet = bm.getBalance();
2839
+ const tm = new TransactionManager();
2840
+ const recent = tm.list().slice(-10).reverse();
2841
+ return {
2842
+ status: 200,
2843
+ body: { isSetup: true, wallet, recentTransactions: recent }
2844
+ };
2845
+ } catch {
2846
+ return { status: 200, body: { isSetup: true, wallet: null, recentTransactions: [] } };
2847
+ }
2848
+ }
2849
+ function handlePostSetup(body) {
2850
+ if (!body.passphrase || !body.credentials) {
2851
+ return { status: 400, body: { error: "Missing passphrase or credentials" } };
2852
+ }
2853
+ try {
2854
+ const home = getHomePath();
2855
+ (0, import_node_fs8.mkdirSync)(home, { recursive: true });
2856
+ const vault = encrypt(body.credentials, body.passphrase);
2857
+ saveVault(vault, getCredentialsPath());
2858
+ const keys = generateKeyPair(body.passphrase);
2859
+ (0, import_node_fs8.mkdirSync)(getKeysPath(), { recursive: true });
2860
+ saveKeyPair(keys);
2861
+ const bm = new BudgetManager();
2862
+ bm.initWallet(body.budget || 0, body.limitPerTx || 0);
2863
+ const audit = new AuditLogger();
2864
+ audit.log("SETUP", { source: "dashboard", message: "credentials encrypted, keypair generated, wallet initialized" });
2865
+ const wallet = bm.getBalance();
2866
+ return { status: 200, body: { success: true, wallet } };
2867
+ } catch (err) {
2868
+ const message = err instanceof Error ? err.message : "Setup failed";
2869
+ return { status: 500, body: { error: message } };
2870
+ }
2871
+ }
2872
+ function handlePostFund(body) {
2873
+ if (!body.amount || body.amount <= 0) {
2874
+ return { status: 400, body: { error: "Amount must be positive" } };
2875
+ }
2876
+ try {
2877
+ const bm = new BudgetManager();
2878
+ const wallet = bm.addFunds(body.amount);
2879
+ const audit = new AuditLogger();
2880
+ audit.log("ADD_FUNDS", { source: "dashboard", amount: body.amount });
2881
+ return { status: 200, body: { success: true, wallet } };
2882
+ } catch (err) {
2883
+ const message = err instanceof Error ? err.message : "Failed to add funds";
2884
+ return { status: 500, body: { error: message } };
2885
+ }
2886
+ }
2887
+
2888
+ // src/server/index.ts
2889
+ var MAX_BODY3 = 1048576;
2890
+ function parseBody3(req) {
2891
+ return new Promise((resolve, reject) => {
2892
+ const chunks = [];
2893
+ let size = 0;
2894
+ req.on("data", (chunk) => {
2895
+ size += chunk.length;
2896
+ if (size > MAX_BODY3) {
2897
+ req.destroy();
2898
+ reject(new Error("Request body too large"));
2899
+ return;
2900
+ }
2901
+ chunks.push(chunk);
2902
+ });
2903
+ req.on("end", () => {
2904
+ try {
2905
+ const text = Buffer.concat(chunks).toString("utf8");
2906
+ resolve(text ? JSON.parse(text) : {});
2907
+ } catch {
2908
+ reject(new Error("Invalid JSON"));
2909
+ }
2910
+ });
2911
+ req.on("error", reject);
2912
+ });
2913
+ }
2914
+ function sendJson3(res, status, body) {
2915
+ const json = JSON.stringify(body);
2916
+ res.writeHead(status, {
2917
+ "Content-Type": "application/json",
2918
+ "Content-Length": Buffer.byteLength(json)
2919
+ });
2920
+ res.end(json);
2921
+ }
2922
+ function sendHtml3(res, html) {
2923
+ res.writeHead(200, {
2924
+ "Content-Type": "text/html; charset=utf-8",
2925
+ "Content-Length": Buffer.byteLength(html)
2926
+ });
2927
+ res.end(html);
2928
+ }
2929
+ function startServer(port) {
2930
+ return new Promise((resolve, reject) => {
2931
+ const server = (0, import_node_http3.createServer)(async (req, res) => {
2932
+ const url = req.url ?? "/";
2933
+ const method = req.method ?? "GET";
2934
+ try {
2935
+ if (method === "GET" && url === "/api/status") {
2936
+ const result = handleGetStatus();
2937
+ sendJson3(res, result.status, result.body);
2938
+ } else if (method === "POST" && url === "/api/setup") {
2939
+ const body = await parseBody3(req);
2940
+ const result = handlePostSetup(body);
2941
+ sendJson3(res, result.status, result.body);
2942
+ } else if (method === "POST" && url === "/api/fund") {
2943
+ const body = await parseBody3(req);
2944
+ const result = handlePostFund(body);
2945
+ sendJson3(res, result.status, result.body);
2946
+ } else if (method === "GET" && (url === "/" || url === "/index.html")) {
2947
+ sendHtml3(res, getDashboardHtml());
2948
+ } else {
2949
+ sendJson3(res, 404, { error: "Not found" });
2950
+ }
2951
+ } catch (err) {
2952
+ const message = err instanceof Error ? err.message : "Internal error";
2953
+ sendJson3(res, 500, { error: message });
2954
+ }
2955
+ });
2956
+ server.on("error", (err) => {
2957
+ if (err.code === "EADDRINUSE") {
2958
+ reject(new Error(`Port ${port} is already in use. Try a different port with --port <number>.`));
2959
+ } else {
2960
+ reject(err);
2961
+ }
2962
+ });
2963
+ server.listen(port, "127.0.0.1", () => {
2964
+ resolve(server);
2965
+ });
2966
+ });
2967
+ }
2968
+
2969
+ // src/index.ts
2970
+ init_open_browser();
2971
+
2972
+ // src/utils/prompt.ts
2973
+ init_cjs_shims();
2974
+ var import_node_readline = require("readline");
2975
+ function createRl() {
2976
+ return (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stdout });
2977
+ }
2978
+ function promptInput(question) {
2979
+ return new Promise((resolve) => {
2980
+ const rl = createRl();
2981
+ rl.question(question, (answer) => {
2982
+ rl.close();
2983
+ resolve(answer.trim());
2984
+ });
2985
+ });
2986
+ }
2987
+ async function promptPassphrase(prompt = "Passphrase: ") {
2988
+ return promptInput(prompt);
2989
+ }
2990
+ function promptConfirm(question) {
2991
+ return new Promise((resolve) => {
2992
+ const rl = createRl();
2993
+ rl.question(`${question} (y/N): `, (answer) => {
2994
+ rl.close();
2995
+ resolve(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
2996
+ });
2997
+ });
2998
+ }
2999
+ async function promptPassphraseSafe(context) {
3000
+ if (process.stdin.isTTY) {
3001
+ return promptPassphrase("Enter passphrase: ");
3002
+ }
3003
+ const { collectPassphrase: collectPassphrase2 } = await Promise.resolve().then(() => (init_passphrase_server(), passphrase_server_exports));
3004
+ return collectPassphrase2(context);
3005
+ }
3006
+
863
3007
  // src/agentpay.ts
864
3008
  init_cjs_shims();
865
- var import_node_path7 = require("path");
3009
+ var import_node_path9 = require("path");
3010
+ init_mandate();
3011
+ init_paths();
866
3012
  init_errors();
867
3013
  var AgentPay = class {
868
3014
  home;
@@ -874,9 +3020,9 @@ var AgentPay = class {
874
3020
  constructor(options) {
875
3021
  this.home = options?.home ?? getHomePath();
876
3022
  this.passphrase = options?.passphrase;
877
- this.budgetManager = new BudgetManager((0, import_node_path7.join)(this.home, "wallet.json"));
878
- this.txManager = new TransactionManager((0, import_node_path7.join)(this.home, "transactions.json"));
879
- this.auditLogger = new AuditLogger((0, import_node_path7.join)(this.home, "audit.log"));
3023
+ this.budgetManager = new BudgetManager((0, import_node_path9.join)(this.home, "wallet.json"));
3024
+ this.txManager = new TransactionManager((0, import_node_path9.join)(this.home, "transactions.json"));
3025
+ this.auditLogger = new AuditLogger((0, import_node_path9.join)(this.home, "audit.log"));
880
3026
  this.executor = new PurchaseExecutor(options?.executor);
881
3027
  }
882
3028
  get wallet() {
@@ -887,16 +3033,6 @@ var AgentPay = class {
887
3033
  getLimits: () => {
888
3034
  const w = bm.getBalance();
889
3035
  return { budget: w.budget, limitPerTx: w.limitPerTx, remaining: w.balance };
890
- },
891
- generateFundingQR: async (options) => {
892
- const QRCode = await import("qrcode");
893
- const params = new URLSearchParams();
894
- if (options?.suggestedBudget) params.set("budget", String(options.suggestedBudget));
895
- if (options?.message) params.set("msg", options.message);
896
- const baseUrl = process.env.AGENTPAY_WEB_URL ?? "http://localhost:3000";
897
- const url = `${baseUrl}/setup${params.toString() ? `?${params.toString()}` : ""}`;
898
- const qrDataUrl = await QRCode.toDataURL(url);
899
- return { url, qrDataUrl };
900
3036
  }
901
3037
  };
902
3038
  }
@@ -913,6 +3049,18 @@ var AgentPay = class {
913
3049
  const { waitForApproval: waitForApproval2 } = await Promise.resolve().then(() => (init_poller(), poller_exports));
914
3050
  return waitForApproval2(txId, this.txManager, options);
915
3051
  },
3052
+ requestApproval: async (txId) => {
3053
+ const tx = this.txManager.get(txId);
3054
+ if (!tx) throw new Error(`Transaction ${txId} not found.`);
3055
+ if (tx.status !== "pending") throw new Error(`Transaction ${txId} is not pending.`);
3056
+ const { existsSync: existsSync3 } = await import("fs");
3057
+ const keyPath = (0, import_node_path9.join)(this.home, "keys", "private.pem");
3058
+ if (!existsSync3(keyPath)) {
3059
+ throw new Error('Private key not found. Run "agentpay setup" first.');
3060
+ }
3061
+ const { requestBrowserApproval: requestBrowserApproval2 } = await Promise.resolve().then(() => (init_approval_server(), approval_server_exports));
3062
+ return requestBrowserApproval2(tx, this.txManager, this.auditLogger, this.home);
3063
+ },
916
3064
  execute: async (txId) => {
917
3065
  const tx = this.txManager.get(txId);
918
3066
  if (!tx) throw new Error(`Transaction ${txId} not found.`);
@@ -942,7 +3090,7 @@ var AgentPay = class {
942
3090
  if (!this.passphrase) {
943
3091
  throw new Error("Passphrase required for execution. Pass it to AgentPay constructor.");
944
3092
  }
945
- const vaultPath = (0, import_node_path7.join)(this.home, "credentials.enc");
3093
+ const vaultPath = (0, import_node_path9.join)(this.home, "credentials.enc");
946
3094
  const vault = loadVault(vaultPath);
947
3095
  const credentials = decrypt(vault, this.passphrase);
948
3096
  const result = await this.executor.execute(tx, credentials);
@@ -999,7 +3147,7 @@ var AgentPay = class {
999
3147
  };
1000
3148
 
1001
3149
  // src/index.ts
1002
- var VERSION = "0.1.0";
3150
+ var VERSION = true ? "0.1.2" : "0.0.0";
1003
3151
  // Annotate the CommonJS export names for ESM import in node:
1004
3152
  0 && (module.exports = {
1005
3153
  AgentPay,
@@ -1038,8 +3186,16 @@ var VERSION = "0.1.0";
1038
3186
  loadPrivateKey,
1039
3187
  loadPublicKey,
1040
3188
  loadVault,
3189
+ openBrowser,
3190
+ promptConfirm,
3191
+ promptInput,
3192
+ promptPassphrase,
3193
+ promptPassphraseSafe,
3194
+ requestBrowserApproval,
3195
+ requestBrowserSetup,
1041
3196
  saveKeyPair,
1042
3197
  saveVault,
3198
+ startDashboardServer,
1043
3199
  verifyMandate,
1044
3200
  waitForApproval
1045
3201
  });