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