@vapi-network/core 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account-add.d.ts +8 -1
- package/dist/account-add.d.ts.map +1 -1
- package/dist/account-movement-lock.d.ts +10 -0
- package/dist/account-movement-lock.d.ts.map +1 -0
- package/dist/agent-link.d.ts +1 -0
- package/dist/agent-link.d.ts.map +1 -1
- package/dist/agent-link.js +21 -10
- package/dist/agent-link.js.map +1 -1
- package/dist/agent-profile.d.ts +14 -2
- package/dist/agent-profile.d.ts.map +1 -1
- package/dist/agent-run.d.ts +12 -0
- package/dist/agent-run.d.ts.map +1 -0
- package/dist/allocation.d.ts +35 -4
- package/dist/allocation.d.ts.map +1 -1
- package/dist/api-key.js.map +1 -1
- package/dist/atomic-file.d.ts +23 -0
- package/dist/atomic-file.d.ts.map +1 -0
- package/dist/audit.d.ts +4 -1
- package/dist/audit.d.ts.map +1 -1
- package/dist/backup.d.ts +153 -32
- package/dist/backup.d.ts.map +1 -1
- package/dist/backup.js +2535 -139
- package/dist/backup.js.map +3 -3
- package/dist/call-contracts-wire.d.ts +12 -12
- package/dist/ceiling.d.ts +8 -0
- package/dist/ceiling.d.ts.map +1 -1
- package/dist/cloud-backup.d.ts +8 -10
- package/dist/cloud-backup.d.ts.map +1 -1
- package/dist/cloud-backup.js +2806 -381
- package/dist/cloud-backup.js.map +3 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/distribute.d.ts +9 -1
- package/dist/distribute.d.ts.map +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5206 -1270
- package/dist/index.js.map +3 -3
- package/dist/marketplace-contracts.d.ts +14 -14
- package/dist/member-bundle.d.ts +110 -0
- package/dist/member-bundle.d.ts.map +1 -0
- package/dist/movement-open.d.ts +10 -0
- package/dist/movement-open.d.ts.map +1 -0
- package/dist/movement.d.ts +77 -7
- package/dist/movement.d.ts.map +1 -1
- package/dist/receipts.d.ts +9 -0
- package/dist/receipts.d.ts.map +1 -1
- package/dist/router-client.d.ts +9 -1
- package/dist/router-client.d.ts.map +1 -1
- package/dist/router-client.js +2073 -607
- package/dist/router-client.js.map +3 -3
- package/dist/run-budget.d.ts +17 -0
- package/dist/run-budget.d.ts.map +1 -0
- package/dist/secret-store.d.ts +6 -0
- package/dist/secret-store.d.ts.map +1 -1
- package/dist/secrets.d.ts +2 -1
- package/dist/secrets.d.ts.map +1 -1
- package/dist/secrets.js +884 -48
- package/dist/secrets.js.map +3 -3
- package/dist/support-report.d.ts +1 -1
- package/dist/swarm-capital.d.ts +147 -0
- package/dist/swarm-capital.d.ts.map +1 -0
- package/dist/swarm.d.ts +224 -0
- package/dist/swarm.d.ts.map +1 -0
- package/dist/transfer-journal.d.ts +11 -0
- package/dist/transfer-journal.d.ts.map +1 -0
- package/dist/transfer.d.ts +4 -1
- package/dist/transfer.d.ts.map +1 -1
- package/dist/vault.d.ts +11 -0
- package/dist/vault.d.ts.map +1 -1
- package/dist/wallet-store.d.ts +19 -8
- package/dist/wallet-store.d.ts.map +1 -1
- package/dist/x402-pay.d.ts +7 -0
- package/dist/x402-pay.d.ts.map +1 -1
- package/dist/x402.d.ts +3 -0
- package/dist/x402.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/cloud-backup.js
CHANGED
|
@@ -3947,7 +3947,7 @@ function weierstrass(curveDef) {
|
|
|
3947
3947
|
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
|
|
3948
3948
|
if (["recovered", "canonical"].some((k) => k in opts))
|
|
3949
3949
|
throw new Error("sign() legacy options not supported");
|
|
3950
|
-
const { hash: hash2, randomBytes:
|
|
3950
|
+
const { hash: hash2, randomBytes: randomBytes7 } = CURVE;
|
|
3951
3951
|
let { lowS, prehash, extraEntropy: ent } = opts;
|
|
3952
3952
|
if (lowS == null)
|
|
3953
3953
|
lowS = true;
|
|
@@ -3959,7 +3959,7 @@ function weierstrass(curveDef) {
|
|
|
3959
3959
|
const d = normPrivateKeyToScalar(privateKey);
|
|
3960
3960
|
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3961
3961
|
if (ent != null && ent !== false) {
|
|
3962
|
-
const e = ent === true ?
|
|
3962
|
+
const e = ent === true ? randomBytes7(Fp.BYTES) : ent;
|
|
3963
3963
|
seedArgs.push(ensureBytes("extraEntropy", e));
|
|
3964
3964
|
}
|
|
3965
3965
|
const seed = concatBytes3(...seedArgs);
|
|
@@ -4273,13 +4273,14 @@ var init_secp256k1 = __esm({
|
|
|
4273
4273
|
});
|
|
4274
4274
|
|
|
4275
4275
|
// src/cloud-backup.ts
|
|
4276
|
-
import { join as
|
|
4276
|
+
import { join as join9 } from "node:path";
|
|
4277
4277
|
|
|
4278
4278
|
// src/backup.ts
|
|
4279
4279
|
import {
|
|
4280
4280
|
createCipheriv as createCipheriv2,
|
|
4281
4281
|
createDecipheriv as createDecipheriv2,
|
|
4282
|
-
createHash,
|
|
4282
|
+
createHash as createHash2,
|
|
4283
|
+
createHmac,
|
|
4283
4284
|
createPrivateKey,
|
|
4284
4285
|
createPublicKey,
|
|
4285
4286
|
diffieHellman,
|
|
@@ -4288,8 +4289,18 @@ import {
|
|
|
4288
4289
|
scrypt as scrypt2,
|
|
4289
4290
|
timingSafeEqual
|
|
4290
4291
|
} from "node:crypto";
|
|
4291
|
-
import {
|
|
4292
|
-
|
|
4292
|
+
import {
|
|
4293
|
+
chmod as chmod2,
|
|
4294
|
+
link as link2,
|
|
4295
|
+
lstat,
|
|
4296
|
+
mkdir as mkdir8,
|
|
4297
|
+
mkdtemp,
|
|
4298
|
+
open as openFile,
|
|
4299
|
+
readFile as readFile9,
|
|
4300
|
+
readdir as readdir5,
|
|
4301
|
+
rm as rm2
|
|
4302
|
+
} from "node:fs/promises";
|
|
4303
|
+
import { dirname as dirname5, join as join8 } from "node:path";
|
|
4293
4304
|
|
|
4294
4305
|
// ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
|
|
4295
4306
|
init_getAddress();
|
|
@@ -5332,6 +5343,7 @@ function serializeSignature({ r, s, to = "hex", v, yParity }) {
|
|
|
5332
5343
|
|
|
5333
5344
|
// ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/index.js
|
|
5334
5345
|
init_getAddress();
|
|
5346
|
+
init_isAddress();
|
|
5335
5347
|
|
|
5336
5348
|
// ../../node_modules/.pnpm/@scure+bip32@1.7.0/node_modules/@scure/bip32/lib/esm/index.js
|
|
5337
5349
|
init_modular();
|
|
@@ -45490,6 +45502,263 @@ function date4(params) {
|
|
|
45490
45502
|
return _coercedDate(ZodDate, params);
|
|
45491
45503
|
}
|
|
45492
45504
|
|
|
45505
|
+
// src/agent-profile.ts
|
|
45506
|
+
import { mkdir as mkdir3, readFile as readFile3, readdir as readdir2, rename as rename3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
45507
|
+
import { join as join4 } from "node:path";
|
|
45508
|
+
|
|
45509
|
+
// src/config.ts
|
|
45510
|
+
import { constants } from "node:fs";
|
|
45511
|
+
import { copyFile, mkdir as mkdir2, readFile as readFile2, rename as rename2, stat as stat2, writeFile } from "node:fs/promises";
|
|
45512
|
+
import { homedir } from "node:os";
|
|
45513
|
+
import { dirname as dirname2, join as join3 } from "node:path";
|
|
45514
|
+
|
|
45515
|
+
// src/atomic-file.ts
|
|
45516
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
45517
|
+
import { link, mkdir, open as open2, readdir, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
45518
|
+
import { basename, dirname, join as join2 } from "node:path";
|
|
45519
|
+
var DEFAULT_LOCK_TIMEOUT_MS = 2e3;
|
|
45520
|
+
var LOCK_RETRY_MS = 20;
|
|
45521
|
+
var LOCK_STALE_AFTER_MS = 12e4;
|
|
45522
|
+
var LOCK_HEARTBEAT_MS = 3e4;
|
|
45523
|
+
var atomicFileTestHooks;
|
|
45524
|
+
var FileLockedError = class extends Error {
|
|
45525
|
+
constructor(message = "Timed out waiting for the file lock.") {
|
|
45526
|
+
super(message);
|
|
45527
|
+
this.name = "FileLockedError";
|
|
45528
|
+
}
|
|
45529
|
+
};
|
|
45530
|
+
async function writeJsonAtomic(path, value, options = {}) {
|
|
45531
|
+
const directory = dirname(path);
|
|
45532
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
45533
|
+
const temporaryPath = join2(
|
|
45534
|
+
directory,
|
|
45535
|
+
`.${basename(path)}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`
|
|
45536
|
+
);
|
|
45537
|
+
let handle;
|
|
45538
|
+
try {
|
|
45539
|
+
handle = await open2(temporaryPath, "wx", options.mode ?? 384);
|
|
45540
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}
|
|
45541
|
+
`, "utf8");
|
|
45542
|
+
await handle.sync();
|
|
45543
|
+
await handle.close();
|
|
45544
|
+
handle = void 0;
|
|
45545
|
+
await rename(temporaryPath, path);
|
|
45546
|
+
const directoryHandle = await open2(directory, "r");
|
|
45547
|
+
try {
|
|
45548
|
+
await directoryHandle.sync();
|
|
45549
|
+
} finally {
|
|
45550
|
+
await directoryHandle.close();
|
|
45551
|
+
}
|
|
45552
|
+
} catch (error61) {
|
|
45553
|
+
await handle?.close().catch(() => void 0);
|
|
45554
|
+
await unlink(temporaryPath).catch(() => void 0);
|
|
45555
|
+
throw error61;
|
|
45556
|
+
}
|
|
45557
|
+
}
|
|
45558
|
+
async function withFileLock(lockPath, fn, options = {}) {
|
|
45559
|
+
await mkdir(dirname(lockPath), { recursive: true, mode: 448 });
|
|
45560
|
+
const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS);
|
|
45561
|
+
const ownerRecord = {
|
|
45562
|
+
pid: process.pid,
|
|
45563
|
+
token: randomBytes2(16).toString("hex")
|
|
45564
|
+
};
|
|
45565
|
+
const owner = JSON.stringify(ownerRecord);
|
|
45566
|
+
const releasedOwner = JSON.stringify({ ...ownerRecord, released: true });
|
|
45567
|
+
let handle;
|
|
45568
|
+
while (handle === void 0) {
|
|
45569
|
+
await atomicFileTestHooks?.beforeLockAttempt?.(lockPath);
|
|
45570
|
+
try {
|
|
45571
|
+
const candidate = await open2(lockPath, "wx", 384);
|
|
45572
|
+
try {
|
|
45573
|
+
await candidate.writeFile(owner, "utf8");
|
|
45574
|
+
await candidate.sync();
|
|
45575
|
+
await atomicFileTestHooks?.afterLockCreate?.(lockPath);
|
|
45576
|
+
if (await lockTakeoverInProgress(lockPath)) {
|
|
45577
|
+
await candidate.close();
|
|
45578
|
+
await removeOwnedLock(lockPath, [owner]);
|
|
45579
|
+
await removeAbandonedLockTombs(lockPath);
|
|
45580
|
+
if (Date.now() >= deadline) {
|
|
45581
|
+
throw new FileLockedError(options.lockedMessage);
|
|
45582
|
+
}
|
|
45583
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
|
45584
|
+
continue;
|
|
45585
|
+
}
|
|
45586
|
+
handle = candidate;
|
|
45587
|
+
} catch (error61) {
|
|
45588
|
+
await candidate.close().catch(() => void 0);
|
|
45589
|
+
await removeOwnedLock(lockPath, [owner]).catch(() => void 0);
|
|
45590
|
+
throw error61;
|
|
45591
|
+
}
|
|
45592
|
+
} catch (error61) {
|
|
45593
|
+
if (!hasCode(error61, "EEXIST")) throw error61;
|
|
45594
|
+
await removeStaleLock(lockPath);
|
|
45595
|
+
if (Date.now() >= deadline) {
|
|
45596
|
+
throw new FileLockedError(options.lockedMessage);
|
|
45597
|
+
}
|
|
45598
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
|
45599
|
+
}
|
|
45600
|
+
}
|
|
45601
|
+
const ownedHandle = handle;
|
|
45602
|
+
const heartbeat = setInterval(() => {
|
|
45603
|
+
const time3 = /* @__PURE__ */ new Date();
|
|
45604
|
+
void ownedHandle.utimes(time3, time3).catch(() => void 0);
|
|
45605
|
+
}, LOCK_HEARTBEAT_MS);
|
|
45606
|
+
heartbeat.unref();
|
|
45607
|
+
try {
|
|
45608
|
+
return await fn();
|
|
45609
|
+
} finally {
|
|
45610
|
+
clearInterval(heartbeat);
|
|
45611
|
+
try {
|
|
45612
|
+
await markLockReleased(ownedHandle, releasedOwner);
|
|
45613
|
+
} finally {
|
|
45614
|
+
try {
|
|
45615
|
+
await ownedHandle.close();
|
|
45616
|
+
} finally {
|
|
45617
|
+
await removeOwnedLock(lockPath, [owner, releasedOwner]);
|
|
45618
|
+
}
|
|
45619
|
+
}
|
|
45620
|
+
}
|
|
45621
|
+
}
|
|
45622
|
+
async function removeStaleLock(path) {
|
|
45623
|
+
try {
|
|
45624
|
+
const owner = await readFile(path, "utf8");
|
|
45625
|
+
if (lockOwnerReleased(owner)) {
|
|
45626
|
+
await removeOwnedLock(path, [owner]);
|
|
45627
|
+
return;
|
|
45628
|
+
}
|
|
45629
|
+
const metadata = await stat(path);
|
|
45630
|
+
if (Date.now() - metadata.mtimeMs <= LOCK_STALE_AFTER_MS) return;
|
|
45631
|
+
const pid = lockOwnerPid(owner);
|
|
45632
|
+
if (pid !== void 0 && processIsAlive(pid)) return;
|
|
45633
|
+
await atomicFileTestHooks?.beforeStaleLockBreak?.(path);
|
|
45634
|
+
await removeOwnedLock(path, [owner]);
|
|
45635
|
+
} catch (error61) {
|
|
45636
|
+
if (!hasCode(error61, "ENOENT")) throw error61;
|
|
45637
|
+
}
|
|
45638
|
+
}
|
|
45639
|
+
async function removeOwnedLock(path, owners) {
|
|
45640
|
+
const tombPath = `${path}.stale.${randomBytes2(16).toString("hex")}`;
|
|
45641
|
+
try {
|
|
45642
|
+
await rename(path, tombPath);
|
|
45643
|
+
} catch (error61) {
|
|
45644
|
+
if (hasCode(error61, "ENOENT")) {
|
|
45645
|
+
await removeOwnedTombs(path, owners);
|
|
45646
|
+
const currentOwner = await readFile(path, "utf8").catch(() => void 0);
|
|
45647
|
+
if (currentOwner !== void 0 && owners.includes(currentOwner)) {
|
|
45648
|
+
await removeOwnedLock(path, owners);
|
|
45649
|
+
}
|
|
45650
|
+
return;
|
|
45651
|
+
}
|
|
45652
|
+
throw error61;
|
|
45653
|
+
}
|
|
45654
|
+
let pendingError;
|
|
45655
|
+
try {
|
|
45656
|
+
const renamedOwner = await readFile(tombPath, "utf8");
|
|
45657
|
+
if (!owners.includes(renamedOwner) && !lockOwnerReleased(renamedOwner)) {
|
|
45658
|
+
await atomicFileTestHooks?.afterMismatchedLockRename?.(path);
|
|
45659
|
+
const currentOwner = await readFile(tombPath, "utf8");
|
|
45660
|
+
if (!lockOwnerReleased(currentOwner)) await restoreRenamedLock(path, tombPath);
|
|
45661
|
+
await atomicFileTestHooks?.afterMismatchedLockRestore?.(path);
|
|
45662
|
+
}
|
|
45663
|
+
} catch (error61) {
|
|
45664
|
+
pendingError = error61;
|
|
45665
|
+
}
|
|
45666
|
+
try {
|
|
45667
|
+
await unlink(tombPath);
|
|
45668
|
+
} catch (error61) {
|
|
45669
|
+
if (!hasCode(error61, "ENOENT") && pendingError === void 0) {
|
|
45670
|
+
pendingError = error61;
|
|
45671
|
+
}
|
|
45672
|
+
}
|
|
45673
|
+
if (pendingError !== void 0) throw pendingError;
|
|
45674
|
+
}
|
|
45675
|
+
async function lockTakeoverInProgress(path) {
|
|
45676
|
+
const prefix = `${basename(path)}.stale.`;
|
|
45677
|
+
return (await readdir(dirname(path))).some((entry) => entry.startsWith(prefix));
|
|
45678
|
+
}
|
|
45679
|
+
async function removeAbandonedLockTombs(path) {
|
|
45680
|
+
const directory = dirname(path);
|
|
45681
|
+
const prefix = `${basename(path)}.stale.`;
|
|
45682
|
+
for (const entry of await readdir(directory)) {
|
|
45683
|
+
if (!entry.startsWith(prefix)) continue;
|
|
45684
|
+
const tombPath = join2(directory, entry);
|
|
45685
|
+
const [metadata, owner] = await Promise.all([
|
|
45686
|
+
stat(tombPath).catch(() => void 0),
|
|
45687
|
+
readFile(tombPath, "utf8").catch(() => void 0)
|
|
45688
|
+
]);
|
|
45689
|
+
if (metadata === void 0 || owner === void 0) continue;
|
|
45690
|
+
const pid = lockOwnerPid(owner);
|
|
45691
|
+
const abandoned = lockOwnerReleased(owner) || Date.now() - metadata.mtimeMs > LOCK_STALE_AFTER_MS && (pid === void 0 || !processIsAlive(pid));
|
|
45692
|
+
if (!abandoned) continue;
|
|
45693
|
+
await unlink(tombPath).catch((error61) => {
|
|
45694
|
+
if (!hasCode(error61, "ENOENT")) throw error61;
|
|
45695
|
+
});
|
|
45696
|
+
}
|
|
45697
|
+
}
|
|
45698
|
+
async function removeOwnedTombs(path, owners) {
|
|
45699
|
+
const directory = dirname(path);
|
|
45700
|
+
const prefix = `${basename(path)}.stale.`;
|
|
45701
|
+
for (const entry of await readdir(directory)) {
|
|
45702
|
+
if (!entry.startsWith(prefix)) continue;
|
|
45703
|
+
const tombPath = join2(directory, entry);
|
|
45704
|
+
const owner = await readFile(tombPath, "utf8").catch(() => void 0);
|
|
45705
|
+
if (owner === void 0 || !owners.includes(owner)) continue;
|
|
45706
|
+
await unlink(tombPath).catch((error61) => {
|
|
45707
|
+
if (!hasCode(error61, "ENOENT")) throw error61;
|
|
45708
|
+
});
|
|
45709
|
+
}
|
|
45710
|
+
}
|
|
45711
|
+
async function restoreRenamedLock(path, tombPath) {
|
|
45712
|
+
while (true) {
|
|
45713
|
+
try {
|
|
45714
|
+
await link(tombPath, path);
|
|
45715
|
+
return;
|
|
45716
|
+
} catch (error61) {
|
|
45717
|
+
if (hasCode(error61, "ENOENT")) return;
|
|
45718
|
+
if (!hasCode(error61, "EEXIST")) throw error61;
|
|
45719
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
|
45720
|
+
}
|
|
45721
|
+
}
|
|
45722
|
+
}
|
|
45723
|
+
async function markLockReleased(handle, owner) {
|
|
45724
|
+
const contents = Buffer.from(owner, "utf8");
|
|
45725
|
+
await handle.write(contents, 0, contents.length, 0);
|
|
45726
|
+
await handle.truncate(contents.length);
|
|
45727
|
+
await handle.sync();
|
|
45728
|
+
}
|
|
45729
|
+
function lockOwnerPid(owner) {
|
|
45730
|
+
try {
|
|
45731
|
+
const value = JSON.parse(owner);
|
|
45732
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
45733
|
+
const pid = Reflect.get(value, "pid");
|
|
45734
|
+
return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
45735
|
+
} catch {
|
|
45736
|
+
return void 0;
|
|
45737
|
+
}
|
|
45738
|
+
}
|
|
45739
|
+
function lockOwnerReleased(owner) {
|
|
45740
|
+
try {
|
|
45741
|
+
const value = JSON.parse(owner);
|
|
45742
|
+
return typeof value === "object" && value !== null && Reflect.get(value, "released") === true;
|
|
45743
|
+
} catch {
|
|
45744
|
+
return false;
|
|
45745
|
+
}
|
|
45746
|
+
}
|
|
45747
|
+
function processIsAlive(pid) {
|
|
45748
|
+
if (atomicFileTestHooks?.isProcessAlive !== void 0) {
|
|
45749
|
+
return atomicFileTestHooks.isProcessAlive(pid);
|
|
45750
|
+
}
|
|
45751
|
+
try {
|
|
45752
|
+
process.kill(pid, 0);
|
|
45753
|
+
return true;
|
|
45754
|
+
} catch (error61) {
|
|
45755
|
+
return hasCode(error61, "EPERM");
|
|
45756
|
+
}
|
|
45757
|
+
}
|
|
45758
|
+
function hasCode(error61, code) {
|
|
45759
|
+
return error61 instanceof Error && "code" in error61 && error61.code === code;
|
|
45760
|
+
}
|
|
45761
|
+
|
|
45493
45762
|
// src/x402-networks.ts
|
|
45494
45763
|
var BASE_MAINNET_CAIP2 = "eip155:8453";
|
|
45495
45764
|
var ARC_MAINNET_CAIP2 = "eip155:5042";
|
|
@@ -45793,6 +46062,14 @@ function parseEip155ChainId(network) {
|
|
|
45793
46062
|
function isSolanaNetwork(network) {
|
|
45794
46063
|
return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
|
|
45795
46064
|
}
|
|
46065
|
+
function explorerTransactionUrl(network, hash2) {
|
|
46066
|
+
try {
|
|
46067
|
+
const explorerUrl = getNetworkDefinition(network).explorerUrl;
|
|
46068
|
+
return explorerUrl ? `${explorerUrl}/tx/${hash2}` : void 0;
|
|
46069
|
+
} catch {
|
|
46070
|
+
return void 0;
|
|
46071
|
+
}
|
|
46072
|
+
}
|
|
45796
46073
|
function isSupportedPaymentNetwork(network) {
|
|
45797
46074
|
if (isSolanaNetwork(network)) return true;
|
|
45798
46075
|
try {
|
|
@@ -45802,15 +46079,37 @@ function isSupportedPaymentNetwork(network) {
|
|
|
45802
46079
|
return false;
|
|
45803
46080
|
}
|
|
45804
46081
|
}
|
|
46082
|
+
function getNetworkDefinition(network) {
|
|
46083
|
+
const known = NETWORKS[network];
|
|
46084
|
+
if (known) {
|
|
46085
|
+
return known;
|
|
46086
|
+
}
|
|
46087
|
+
const chainId = parseEip155ChainId(network);
|
|
46088
|
+
return {
|
|
46089
|
+
family: "evm",
|
|
46090
|
+
chainId,
|
|
46091
|
+
name: network,
|
|
46092
|
+
usdc: getAddress("0x0000000000000000000000000000000000000000"),
|
|
46093
|
+
gasToken: "ETH",
|
|
46094
|
+
rpcEnv: ""
|
|
46095
|
+
};
|
|
46096
|
+
}
|
|
45805
46097
|
|
|
45806
46098
|
// src/config.ts
|
|
45807
46099
|
var DEFAULT_REGISTRY_URL = "https://api.vapinetwork.ai";
|
|
45808
46100
|
var DEFAULT_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/services`;
|
|
45809
46101
|
var DEFAULT_MARKETPLACE_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/discovery`;
|
|
46102
|
+
var DEFAULT_REGISTRY_FALLBACKS = [
|
|
46103
|
+
{
|
|
46104
|
+
discoveryUrl: DEFAULT_DISCOVERY_URL,
|
|
46105
|
+
marketplaceDiscoveryUrl: DEFAULT_MARKETPLACE_DISCOVERY_URL
|
|
46106
|
+
}
|
|
46107
|
+
];
|
|
45810
46108
|
var DEFAULT_SPEND_CAPS = {
|
|
45811
46109
|
perCallAtomic: "100000",
|
|
45812
46110
|
perDayAtomic: "1000000"
|
|
45813
46111
|
};
|
|
46112
|
+
var DEFAULT_CEILING_ATOMIC = 5000000n;
|
|
45814
46113
|
var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
|
|
45815
46114
|
var spendCapsSchema = external_exports.object({
|
|
45816
46115
|
perCallAtomic: atomicString,
|
|
@@ -45873,9 +46172,339 @@ var configSchema = external_exports.object({
|
|
|
45873
46172
|
}
|
|
45874
46173
|
}
|
|
45875
46174
|
});
|
|
46175
|
+
function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join3(homedir(), ".vapi")) {
|
|
46176
|
+
return {
|
|
46177
|
+
directory,
|
|
46178
|
+
agentsDir: join3(directory, "agents"),
|
|
46179
|
+
config: join3(directory, "config.json"),
|
|
46180
|
+
keystore: join3(directory, "keystore.json"),
|
|
46181
|
+
receipts: join3(directory, "receipts.jsonl"),
|
|
46182
|
+
searches: join3(directory, "searches.jsonl"),
|
|
46183
|
+
ledger: join3(directory, "spend-ledger.json")
|
|
46184
|
+
};
|
|
46185
|
+
}
|
|
46186
|
+
async function migrateLegacyVapiHome(options = {}) {
|
|
46187
|
+
const target = getVapiPaths(options.targetDirectory);
|
|
46188
|
+
const legacyDirectory = options.legacyDirectory ?? join3(homedir(), ".vapi", "agent-cash");
|
|
46189
|
+
if (legacyDirectory === target.directory || !await pathExists(legacyDirectory)) return [];
|
|
46190
|
+
await mkdir2(target.directory, { recursive: true, mode: 448 });
|
|
46191
|
+
const copied = [];
|
|
46192
|
+
for (const filename of [
|
|
46193
|
+
"config.json",
|
|
46194
|
+
"keystore.json",
|
|
46195
|
+
"receipts.jsonl",
|
|
46196
|
+
"searches.jsonl",
|
|
46197
|
+
"spend-ledger.json"
|
|
46198
|
+
]) {
|
|
46199
|
+
const source = join3(legacyDirectory, filename);
|
|
46200
|
+
const destination = join3(target.directory, filename);
|
|
46201
|
+
try {
|
|
46202
|
+
const copy = async () => await copyFile(source, destination, constants.COPYFILE_EXCL);
|
|
46203
|
+
if (filename === "receipts.jsonl") {
|
|
46204
|
+
await withFileLock(`${destination}.lock`, copy, {
|
|
46205
|
+
lockedMessage: "The receipt journal is busy. Wait for the other vapi command to finish, then retry."
|
|
46206
|
+
});
|
|
46207
|
+
} else {
|
|
46208
|
+
await copy();
|
|
46209
|
+
}
|
|
46210
|
+
copied.push(destination);
|
|
46211
|
+
} catch (error61) {
|
|
46212
|
+
if (isMissingFile(error61) || isAlreadyExists(error61)) continue;
|
|
46213
|
+
throw error61;
|
|
46214
|
+
}
|
|
46215
|
+
}
|
|
46216
|
+
if (copied.length > 0) {
|
|
46217
|
+
const message = `Migrated legacy vAPI wallet files from ${legacyDirectory} to ${target.directory}; originals were kept.`;
|
|
46218
|
+
(options.notice ?? ((value) => process.stderr.write(`${value}
|
|
46219
|
+
`)))(message);
|
|
46220
|
+
}
|
|
46221
|
+
return copied;
|
|
46222
|
+
}
|
|
46223
|
+
var LEGACY_REGISTRY_HOSTS = /* @__PURE__ */ new Map([
|
|
46224
|
+
["console.vapinetwork.ai", "api.vapinetwork.ai"],
|
|
46225
|
+
["console-staging.vapinetwork.ai", "api-staging.vapinetwork.ai"]
|
|
46226
|
+
]);
|
|
46227
|
+
var LEGACY_REGISTRY_PATHS = /* @__PURE__ */ new Map([
|
|
46228
|
+
["/api/network/services", "/api/call/services"],
|
|
46229
|
+
["/api/marketplace/discovery", "/api/call/discovery"]
|
|
46230
|
+
]);
|
|
46231
|
+
var REGISTRY_DOMAIN = "vapinetwork.ai";
|
|
46232
|
+
function rewriteLegacyRegistryUrl(value) {
|
|
46233
|
+
let url2;
|
|
46234
|
+
try {
|
|
46235
|
+
url2 = new URL(value);
|
|
46236
|
+
} catch {
|
|
46237
|
+
return value;
|
|
46238
|
+
}
|
|
46239
|
+
let rewritten = false;
|
|
46240
|
+
const host = LEGACY_REGISTRY_HOSTS.get(url2.hostname.toLowerCase());
|
|
46241
|
+
if (host) {
|
|
46242
|
+
url2.hostname = host;
|
|
46243
|
+
rewritten = true;
|
|
46244
|
+
}
|
|
46245
|
+
const hostname3 = url2.hostname.toLowerCase();
|
|
46246
|
+
if (hostname3 === REGISTRY_DOMAIN || hostname3.endsWith(`.${REGISTRY_DOMAIN}`)) {
|
|
46247
|
+
const path = LEGACY_REGISTRY_PATHS.get(url2.pathname.replace(/\/+$/, ""));
|
|
46248
|
+
if (path) {
|
|
46249
|
+
url2.pathname = path;
|
|
46250
|
+
rewritten = true;
|
|
46251
|
+
}
|
|
46252
|
+
}
|
|
46253
|
+
return rewritten ? url2.href : value;
|
|
46254
|
+
}
|
|
46255
|
+
function rewriteLegacyRegistryUrls(config2) {
|
|
46256
|
+
const changes = [];
|
|
46257
|
+
const rewrite = (field, from) => {
|
|
46258
|
+
const to = rewriteLegacyRegistryUrl(from);
|
|
46259
|
+
if (to !== from) changes.push({ field, from, to });
|
|
46260
|
+
return to;
|
|
46261
|
+
};
|
|
46262
|
+
const next = {
|
|
46263
|
+
...config2,
|
|
46264
|
+
discoveryUrl: rewrite("discoveryUrl", config2.discoveryUrl),
|
|
46265
|
+
marketplaceDiscoveryUrl: rewrite("marketplaceDiscoveryUrl", config2.marketplaceDiscoveryUrl),
|
|
46266
|
+
...config2.registryFallbacks ? {
|
|
46267
|
+
registryFallbacks: config2.registryFallbacks.map((fallback, index) => ({
|
|
46268
|
+
discoveryUrl: rewrite(
|
|
46269
|
+
`registryFallbacks[${index}].discoveryUrl`,
|
|
46270
|
+
fallback.discoveryUrl
|
|
46271
|
+
),
|
|
46272
|
+
marketplaceDiscoveryUrl: rewrite(
|
|
46273
|
+
`registryFallbacks[${index}].marketplaceDiscoveryUrl`,
|
|
46274
|
+
fallback.marketplaceDiscoveryUrl
|
|
46275
|
+
)
|
|
46276
|
+
}))
|
|
46277
|
+
} : {}
|
|
46278
|
+
};
|
|
46279
|
+
return changes.length === 0 ? { config: config2, changes } : { config: next, changes };
|
|
46280
|
+
}
|
|
46281
|
+
function formatLegacyRegistryRewrites(changes) {
|
|
46282
|
+
return [
|
|
46283
|
+
"Rewrote retired vAPI registry URLs in the local config:",
|
|
46284
|
+
...changes.map((change) => ` ${change.field}: ${change.from} -> ${change.to}`)
|
|
46285
|
+
].join("\n");
|
|
46286
|
+
}
|
|
46287
|
+
function getDefaultConfig(source = process.env, options = {}) {
|
|
46288
|
+
const registry2 = registryEndpoints(source.VAPI_REGISTRY_URL?.trim() || DEFAULT_REGISTRY_URL);
|
|
46289
|
+
const requested = new Set(options.networks ?? ["base"]);
|
|
46290
|
+
const networks = {};
|
|
46291
|
+
if (requested.has("base") || requested.has(BASE_MAINNET_CAIP2)) {
|
|
46292
|
+
networks[BASE_MAINNET_CAIP2] = {
|
|
46293
|
+
rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS[BASE_MAINNET_CAIP2].publicRpcUrl,
|
|
46294
|
+
usdc: NETWORKS[BASE_MAINNET_CAIP2].usdc
|
|
46295
|
+
};
|
|
46296
|
+
}
|
|
46297
|
+
const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
|
|
46298
|
+
if (arcMainnetRpcUrl || requested.has("arc") || requested.has(ARC_MAINNET_CAIP2)) {
|
|
46299
|
+
networks[ARC_MAINNET_CAIP2] = {
|
|
46300
|
+
rpcUrl: arcMainnetRpcUrl || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl,
|
|
46301
|
+
usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc
|
|
46302
|
+
};
|
|
46303
|
+
}
|
|
46304
|
+
const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
|
|
46305
|
+
if (arcTestnetRpcUrl || requested.has("arc-testnet") || requested.has(ARC_TESTNET_CAIP2)) {
|
|
46306
|
+
if (!arcTestnetRpcUrl) {
|
|
46307
|
+
throw new Error(
|
|
46308
|
+
"Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL before enabling Arc testnet."
|
|
46309
|
+
);
|
|
46310
|
+
}
|
|
46311
|
+
networks[ARC_TESTNET_CAIP2] = {
|
|
46312
|
+
rpcUrl: arcTestnetRpcUrl,
|
|
46313
|
+
usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc
|
|
46314
|
+
};
|
|
46315
|
+
}
|
|
46316
|
+
const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
|
|
46317
|
+
if (solanaRpcUrl || requested.has("solana") || requested.has(SOLANA_MAINNET_CAIP2)) {
|
|
46318
|
+
networks[SOLANA_MAINNET_CAIP2] = {
|
|
46319
|
+
rpcUrl: solanaRpcUrl || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
|
|
46320
|
+
usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
|
|
46321
|
+
};
|
|
46322
|
+
}
|
|
46323
|
+
return {
|
|
46324
|
+
discoveryUrl: source.VAPI_DISCOVERY_URL?.trim() || registry2.discoveryUrl,
|
|
46325
|
+
marketplaceDiscoveryUrl: source.VAPI_MARKETPLACE_DISCOVERY_URL?.trim() || registry2.marketplaceDiscoveryUrl,
|
|
46326
|
+
registryFallbacks: DEFAULT_REGISTRY_FALLBACKS.map((fallback) => ({ ...fallback })),
|
|
46327
|
+
allowPrivateNetwork: false,
|
|
46328
|
+
networks,
|
|
46329
|
+
spendCaps: { ...DEFAULT_SPEND_CAPS }
|
|
46330
|
+
};
|
|
46331
|
+
}
|
|
46332
|
+
async function loadConfig(path = getVapiPaths().config, source = process.env, options = {}) {
|
|
46333
|
+
if (!process.env.VAPI_HOME?.trim() && path === getVapiPaths(join3(homedir(), ".vapi")).config) {
|
|
46334
|
+
await migrateLegacyVapiHome({ targetDirectory: join3(homedir(), ".vapi") });
|
|
46335
|
+
}
|
|
46336
|
+
let raw;
|
|
46337
|
+
try {
|
|
46338
|
+
raw = await readFile2(path, "utf8");
|
|
46339
|
+
} catch (error61) {
|
|
46340
|
+
if (isMissingFile(error61)) return getDefaultConfig(source);
|
|
46341
|
+
throw error61;
|
|
46342
|
+
}
|
|
46343
|
+
const parsed = configSchema.parse(JSON.parse(raw));
|
|
46344
|
+
parsed.registryFallbacks ??= DEFAULT_REGISTRY_FALLBACKS.map((fallback) => ({ ...fallback }));
|
|
46345
|
+
const migrated = rewriteLegacyRegistryUrls(parsed);
|
|
46346
|
+
const config2 = migrated.config;
|
|
46347
|
+
if (migrated.changes.length > 0 && options.notice) {
|
|
46348
|
+
options.notice(
|
|
46349
|
+
`${formatLegacyRegistryRewrites(migrated.changes)}
|
|
46350
|
+
Run vapi init to write the new URLs to ${path}.`
|
|
46351
|
+
);
|
|
46352
|
+
}
|
|
46353
|
+
const baseRpcUrl = source.BASE_RPC_URL?.trim();
|
|
46354
|
+
const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
|
|
46355
|
+
const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
|
|
46356
|
+
const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
|
|
46357
|
+
const discoveryUrl = source.VAPI_DISCOVERY_URL?.trim();
|
|
46358
|
+
const marketplaceDiscoveryUrl = source.VAPI_MARKETPLACE_DISCOVERY_URL?.trim();
|
|
46359
|
+
const registryUrl = source.VAPI_REGISTRY_URL?.trim();
|
|
46360
|
+
if (config2.networks[BASE_MAINNET_CAIP2] && baseRpcUrl) {
|
|
46361
|
+
config2.networks[BASE_MAINNET_CAIP2].rpcUrl = baseRpcUrl;
|
|
46362
|
+
}
|
|
46363
|
+
if (arcMainnetRpcUrl) {
|
|
46364
|
+
const existing = config2.networks[ARC_MAINNET_CAIP2];
|
|
46365
|
+
config2.networks[ARC_MAINNET_CAIP2] = {
|
|
46366
|
+
...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
|
|
46367
|
+
rpcUrl: arcMainnetRpcUrl
|
|
46368
|
+
};
|
|
46369
|
+
}
|
|
46370
|
+
if (arcTestnetRpcUrl) {
|
|
46371
|
+
const existing = config2.networks[ARC_TESTNET_CAIP2];
|
|
46372
|
+
config2.networks[ARC_TESTNET_CAIP2] = {
|
|
46373
|
+
...existing ?? { usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc },
|
|
46374
|
+
rpcUrl: arcTestnetRpcUrl
|
|
46375
|
+
};
|
|
46376
|
+
}
|
|
46377
|
+
if (solanaRpcUrl) {
|
|
46378
|
+
config2.networks[SOLANA_MAINNET_CAIP2] = {
|
|
46379
|
+
rpcUrl: solanaRpcUrl,
|
|
46380
|
+
usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS[SOLANA_MAINNET_CAIP2].usdc
|
|
46381
|
+
};
|
|
46382
|
+
}
|
|
46383
|
+
if (registryUrl) {
|
|
46384
|
+
const registry2 = registryEndpoints(registryUrl);
|
|
46385
|
+
config2.discoveryUrl = registry2.discoveryUrl;
|
|
46386
|
+
config2.marketplaceDiscoveryUrl = registry2.marketplaceDiscoveryUrl;
|
|
46387
|
+
}
|
|
46388
|
+
if (discoveryUrl) config2.discoveryUrl = discoveryUrl;
|
|
46389
|
+
if (marketplaceDiscoveryUrl) config2.marketplaceDiscoveryUrl = marketplaceDiscoveryUrl;
|
|
46390
|
+
for (const [network, configured] of Object.entries(config2.networks)) {
|
|
46391
|
+
configured.rpcUrl = configured.rpcUrl.trim();
|
|
46392
|
+
configured.usdc = configured.usdc.trim();
|
|
46393
|
+
if (isSolanaNetwork(network) && configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
|
|
46394
|
+
throw new Error(`Network ${network} must use canonical Solana mainnet USDC.`);
|
|
46395
|
+
}
|
|
46396
|
+
if (!configured.rpcUrl) delete config2.networks[network];
|
|
46397
|
+
}
|
|
46398
|
+
return config2;
|
|
46399
|
+
}
|
|
46400
|
+
function registryEndpoints(baseUrl) {
|
|
46401
|
+
const base = new URL(baseUrl);
|
|
46402
|
+
base.search = "";
|
|
46403
|
+
base.hash = "";
|
|
46404
|
+
const prefix = base.pathname === "/" ? "" : base.pathname.replace(/\/+$/, "");
|
|
46405
|
+
const discovery = new URL(base);
|
|
46406
|
+
discovery.pathname = `${prefix}/api/call/services`;
|
|
46407
|
+
const marketplace = new URL(base);
|
|
46408
|
+
marketplace.pathname = `${prefix}/api/call/discovery`;
|
|
46409
|
+
return { discoveryUrl: discovery.href, marketplaceDiscoveryUrl: marketplace.href };
|
|
46410
|
+
}
|
|
46411
|
+
async function pathExists(path) {
|
|
46412
|
+
try {
|
|
46413
|
+
await stat2(path);
|
|
46414
|
+
return true;
|
|
46415
|
+
} catch (error61) {
|
|
46416
|
+
if (isMissingFile(error61)) return false;
|
|
46417
|
+
throw error61;
|
|
46418
|
+
}
|
|
46419
|
+
}
|
|
46420
|
+
function isMissingFile(error61) {
|
|
46421
|
+
return error61 instanceof Error && "code" in error61 && error61.code === "ENOENT";
|
|
46422
|
+
}
|
|
46423
|
+
function isAlreadyExists(error61) {
|
|
46424
|
+
return error61 instanceof Error && "code" in error61 && error61.code === "EEXIST";
|
|
46425
|
+
}
|
|
46426
|
+
|
|
46427
|
+
// src/wallet-name.ts
|
|
46428
|
+
var DEFAULT_WALLET_NAME = "main";
|
|
46429
|
+
var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
46430
|
+
var walletNameSchema = external_exports.string().regex(
|
|
46431
|
+
WALLET_NAME_PATTERN,
|
|
46432
|
+
"A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
|
|
46433
|
+
);
|
|
46434
|
+
|
|
46435
|
+
// src/agent-profile.ts
|
|
46436
|
+
var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
|
|
46437
|
+
var AGENT_GRANTS = ["read", "delegate", "allocate"];
|
|
46438
|
+
var agentProfileShape = {
|
|
46439
|
+
version: external_exports.literal(1),
|
|
46440
|
+
name: walletNameSchema,
|
|
46441
|
+
wallet: external_exports.string(),
|
|
46442
|
+
model: external_exports.string().min(1),
|
|
46443
|
+
instructions: external_exports.string().max(2e4),
|
|
46444
|
+
verifiedOnly: external_exports.boolean().default(true),
|
|
46445
|
+
approveAboveUsd: external_exports.number().min(0).default(0.5),
|
|
46446
|
+
maxSteps: external_exports.number().int().min(1).max(50).default(12),
|
|
46447
|
+
paused: external_exports.boolean().default(false),
|
|
46448
|
+
grants: external_exports.array(external_exports.enum(AGENT_GRANTS)).default([]),
|
|
46449
|
+
createdAt: external_exports.string()
|
|
46450
|
+
};
|
|
46451
|
+
function createAgentProfileSchema(toolNames) {
|
|
46452
|
+
if (toolNames.length === 0) {
|
|
46453
|
+
throw new Error("Agent profiles require at least one registered tool.");
|
|
46454
|
+
}
|
|
46455
|
+
const tools = [...toolNames];
|
|
46456
|
+
return external_exports.object({ ...agentProfileShape, tools: external_exports.array(external_exports.enum(tools)).default(tools) });
|
|
46457
|
+
}
|
|
46458
|
+
var agentProfileSchema = createAgentProfileSchema(DEFAULT_AGENT_TOOLS);
|
|
46459
|
+
async function listAgentProfiles(home, options = {}) {
|
|
46460
|
+
const directory = getVapiPaths(home).agentsDir;
|
|
46461
|
+
let files;
|
|
46462
|
+
try {
|
|
46463
|
+
files = await readdir2(directory);
|
|
46464
|
+
} catch (error61) {
|
|
46465
|
+
if (isMissingFile(error61)) return [];
|
|
46466
|
+
throw error61;
|
|
46467
|
+
}
|
|
46468
|
+
const warn = options.warn ?? ((message) => console.warn(message));
|
|
46469
|
+
const profiles = [];
|
|
46470
|
+
for (const file2 of files) {
|
|
46471
|
+
if (!file2.endsWith(".json")) continue;
|
|
46472
|
+
try {
|
|
46473
|
+
profiles.push(
|
|
46474
|
+
(options.schema ?? agentProfileSchema).parse(
|
|
46475
|
+
JSON.parse(await readFile3(join4(directory, file2), "utf8"))
|
|
46476
|
+
)
|
|
46477
|
+
);
|
|
46478
|
+
} catch {
|
|
46479
|
+
options.onInvalid?.(file2);
|
|
46480
|
+
warn(`Skipping invalid agent profile ${file2}.`);
|
|
46481
|
+
}
|
|
46482
|
+
}
|
|
46483
|
+
profiles.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
46484
|
+
return profiles;
|
|
46485
|
+
}
|
|
46486
|
+
|
|
46487
|
+
// src/device.ts
|
|
46488
|
+
import { hostname as operatingSystemHostname } from "node:os";
|
|
46489
|
+
var DEVICE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
46490
|
+
function normalizedDeviceName(value) {
|
|
46491
|
+
return value.toLowerCase().replace(/[^a-z0-9-]/gu, "-").replace(/-+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 32).replace(/-+$/gu, "");
|
|
46492
|
+
}
|
|
46493
|
+
function slugifyDeviceName(value) {
|
|
46494
|
+
return normalizedDeviceName(value) || "device";
|
|
46495
|
+
}
|
|
46496
|
+
function deviceName(args = {}) {
|
|
46497
|
+
const environmentValue = args.env === void 0 ? process.env.VAPI_DEVICE : args.env.VAPI_DEVICE;
|
|
46498
|
+
for (const value of [environmentValue?.trim(), args.config?.device]) {
|
|
46499
|
+
if (value === void 0 || value.length === 0) continue;
|
|
46500
|
+
const normalized = normalizedDeviceName(value);
|
|
46501
|
+
if (normalized.length > 0) return normalized;
|
|
46502
|
+
}
|
|
46503
|
+
return slugifyDeviceName(args.hostname ?? operatingSystemHostname());
|
|
46504
|
+
}
|
|
45876
46505
|
|
|
45877
46506
|
// src/keystore.ts
|
|
45878
|
-
import { createCipheriv, createDecipheriv, randomBytes as
|
|
46507
|
+
import { createCipheriv, createDecipheriv, randomBytes as randomBytes3, scrypt } from "node:crypto";
|
|
45879
46508
|
var SCRYPT_N = 2 ** 15;
|
|
45880
46509
|
var SCRYPT_R = 8;
|
|
45881
46510
|
var SCRYPT_P = 1;
|
|
@@ -45950,7 +46579,7 @@ function encryptWithKey(key, plaintext) {
|
|
|
45950
46579
|
if (key.byteLength !== KEY_LENGTH) {
|
|
45951
46580
|
throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
|
|
45952
46581
|
}
|
|
45953
|
-
const nonce =
|
|
46582
|
+
const nonce = randomBytes3(12);
|
|
45954
46583
|
const cipher = createCipheriv("aes-256-gcm", key, nonce, {
|
|
45955
46584
|
authTagLength: AUTH_TAG_LENGTH
|
|
45956
46585
|
});
|
|
@@ -46038,20 +46667,517 @@ function deriveEvmPrivateKey(seed, path = EVM_DERIVATION_PATH) {
|
|
|
46038
46667
|
return `0x${Buffer.from(privateKey).toString("hex")}`;
|
|
46039
46668
|
}
|
|
46040
46669
|
|
|
46041
|
-
// src/
|
|
46042
|
-
|
|
46043
|
-
|
|
46044
|
-
|
|
46045
|
-
|
|
46046
|
-
|
|
46670
|
+
// src/movement.ts
|
|
46671
|
+
import { randomBytes as randomBytes6 } from "node:crypto";
|
|
46672
|
+
import { chmod, mkdir as mkdir7, open as open6, readFile as readFile7, readdir as readdir3, rename as rename5, unlink as unlink6 } from "node:fs/promises";
|
|
46673
|
+
import { join as join6 } from "node:path";
|
|
46674
|
+
|
|
46675
|
+
// src/account-movement-lock.ts
|
|
46676
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
46677
|
+
import { mkdir as mkdir4, open as open3, readFile as readFile4, stat as stat3, unlink as unlink3 } from "node:fs/promises";
|
|
46678
|
+
import { join as join5 } from "node:path";
|
|
46679
|
+
var AccountMovementLockedError = class extends Error {
|
|
46680
|
+
constructor(account) {
|
|
46681
|
+
super(`Another capital movement is already running for account ${account}.`);
|
|
46682
|
+
this.account = account;
|
|
46683
|
+
this.name = "AccountMovementLockedError";
|
|
46684
|
+
}
|
|
46685
|
+
account;
|
|
46686
|
+
code = "account_movement_locked";
|
|
46687
|
+
};
|
|
46688
|
+
async function withAccountMovementLock(home, account, timeoutMs, operation, signal) {
|
|
46689
|
+
const directory = join5(home, "movements");
|
|
46690
|
+
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
46691
|
+
const path = join5(directory, `.${account}.lock`);
|
|
46692
|
+
const deadline = Date.now() + (timeoutMs ?? 2e3);
|
|
46693
|
+
const owner = JSON.stringify({ pid: process.pid, token: randomBytes4(16).toString("hex") });
|
|
46694
|
+
let handle;
|
|
46695
|
+
while (handle === void 0) {
|
|
46696
|
+
signal?.throwIfAborted();
|
|
46697
|
+
try {
|
|
46698
|
+
handle = await open3(path, "wx", 384);
|
|
46699
|
+
await handle.writeFile(owner, "utf8");
|
|
46700
|
+
await handle.sync();
|
|
46701
|
+
} catch (error61) {
|
|
46702
|
+
if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
|
|
46703
|
+
await removeStaleLock2(path);
|
|
46704
|
+
if (Date.now() >= deadline) throw new AccountMovementLockedError(account);
|
|
46705
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
46706
|
+
}
|
|
46707
|
+
}
|
|
46708
|
+
const ownedHandle = handle;
|
|
46709
|
+
const heartbeat = setInterval(() => {
|
|
46710
|
+
const time3 = /* @__PURE__ */ new Date();
|
|
46711
|
+
void ownedHandle.utimes(time3, time3).catch(() => void 0);
|
|
46712
|
+
}, 3e4);
|
|
46713
|
+
heartbeat.unref();
|
|
46714
|
+
try {
|
|
46715
|
+
return await operation();
|
|
46716
|
+
} finally {
|
|
46717
|
+
clearInterval(heartbeat);
|
|
46718
|
+
await ownedHandle.close();
|
|
46719
|
+
await unlinkOwnedLock(path, owner);
|
|
46720
|
+
}
|
|
46721
|
+
}
|
|
46722
|
+
async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
|
|
46723
|
+
return await acquireAccountMovementLocks(
|
|
46724
|
+
home,
|
|
46725
|
+
[...new Set(accounts)].sort(),
|
|
46726
|
+
timeoutMs,
|
|
46727
|
+
operation
|
|
46728
|
+
);
|
|
46729
|
+
}
|
|
46730
|
+
async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
|
|
46731
|
+
const [account, ...remaining] = accounts;
|
|
46732
|
+
if (account === void 0) return await operation();
|
|
46733
|
+
return await withAccountMovementLock(
|
|
46734
|
+
home,
|
|
46735
|
+
account,
|
|
46736
|
+
timeoutMs,
|
|
46737
|
+
async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
|
|
46738
|
+
);
|
|
46739
|
+
}
|
|
46740
|
+
async function removeStaleLock2(path) {
|
|
46741
|
+
try {
|
|
46742
|
+
const metadata = await stat3(path);
|
|
46743
|
+
if (Date.now() - metadata.mtimeMs <= 12e4) return;
|
|
46744
|
+
const owner = await readFile4(path, "utf8").catch(() => "");
|
|
46745
|
+
const pid = lockOwnerPid2(owner);
|
|
46746
|
+
if (pid !== void 0 && processIsAlive2(pid)) return;
|
|
46747
|
+
await unlinkOwnedLock(path, owner);
|
|
46748
|
+
} catch (error61) {
|
|
46749
|
+
if (!isMissingFile(error61)) throw error61;
|
|
46750
|
+
}
|
|
46751
|
+
}
|
|
46752
|
+
async function unlinkOwnedLock(path, owner) {
|
|
46753
|
+
try {
|
|
46754
|
+
if (await readFile4(path, "utf8") === owner) await unlink3(path);
|
|
46755
|
+
} catch (error61) {
|
|
46756
|
+
if (!isMissingFile(error61)) throw error61;
|
|
46757
|
+
}
|
|
46758
|
+
}
|
|
46759
|
+
function lockOwnerPid2(owner) {
|
|
46760
|
+
try {
|
|
46761
|
+
const value = JSON.parse(owner);
|
|
46762
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
46763
|
+
const pid = Reflect.get(value, "pid");
|
|
46764
|
+
return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
46765
|
+
} catch {
|
|
46766
|
+
return void 0;
|
|
46767
|
+
}
|
|
46768
|
+
}
|
|
46769
|
+
function processIsAlive2(pid) {
|
|
46770
|
+
try {
|
|
46771
|
+
process.kill(pid, 0);
|
|
46772
|
+
return true;
|
|
46773
|
+
} catch (error61) {
|
|
46774
|
+
return error61 instanceof Error && "code" in error61 && error61.code === "EPERM";
|
|
46775
|
+
}
|
|
46776
|
+
}
|
|
46777
|
+
|
|
46778
|
+
// src/agent-run.ts
|
|
46779
|
+
var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
|
|
46780
|
+
var runRefSchema = external_exports.strictObject({
|
|
46781
|
+
id: external_exports.string().regex(RUN_ID_PATTERN),
|
|
46782
|
+
swarm: external_exports.string().optional(),
|
|
46783
|
+
member: external_exports.string().optional(),
|
|
46784
|
+
parentRunId: external_exports.string().optional()
|
|
46785
|
+
});
|
|
46786
|
+
|
|
46787
|
+
// src/receipts.ts
|
|
46788
|
+
var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
|
|
46789
|
+
async function withReceiptJournalLock(path, operation) {
|
|
46790
|
+
return await withFileLock(`${path}.lock`, operation, {
|
|
46791
|
+
lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
|
|
46792
|
+
});
|
|
46793
|
+
}
|
|
46794
|
+
var durationSchema = external_exports.number().nonnegative().finite();
|
|
46795
|
+
var receiptSchema = external_exports.strictObject({
|
|
46796
|
+
id: external_exports.string().min(1),
|
|
46797
|
+
timestamp: external_exports.iso.datetime(),
|
|
46798
|
+
run: runRefSchema.optional(),
|
|
46799
|
+
kind: external_exports.literal("transfer").optional(),
|
|
46800
|
+
wallet: walletNameSchema.optional(),
|
|
46801
|
+
resourceUrl: external_exports.url(),
|
|
46802
|
+
method: external_exports.string().min(1).optional(),
|
|
46803
|
+
source: external_exports.string().min(1).optional(),
|
|
46804
|
+
provenance: external_exports.array(
|
|
46805
|
+
external_exports.strictObject({
|
|
46806
|
+
source: external_exports.string().min(1),
|
|
46807
|
+
sourceUrl: external_exports.string().optional(),
|
|
46808
|
+
ref: external_exports.string().optional()
|
|
46809
|
+
})
|
|
46810
|
+
).optional(),
|
|
46811
|
+
quote: external_exports.strictObject({
|
|
46812
|
+
network: external_exports.string(),
|
|
46813
|
+
asset: external_exports.string().optional(),
|
|
46814
|
+
amountAtomic: external_exports.string().regex(/^\d+$/),
|
|
46815
|
+
payTo: external_exports.string().optional()
|
|
46816
|
+
}).optional(),
|
|
46817
|
+
payer: external_exports.string().optional(),
|
|
46818
|
+
paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
|
|
46819
|
+
authorization: external_exports.strictObject({
|
|
46820
|
+
from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
46821
|
+
nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
|
|
46822
|
+
validBefore: external_exports.string().regex(/^\d+$/)
|
|
46823
|
+
}).optional(),
|
|
46824
|
+
transfer: external_exports.strictObject({
|
|
46825
|
+
to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
46826
|
+
toName: external_exports.string().min(1),
|
|
46827
|
+
toKind: external_exports.enum(["owner", "account"]),
|
|
46828
|
+
amountAtomic: external_exports.string().regex(/^\d+$/),
|
|
46829
|
+
network: external_exports.string().min(1),
|
|
46830
|
+
nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
|
|
46831
|
+
status: external_exports.enum(["sent", "unknown", "failed"]),
|
|
46832
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
|
|
46833
|
+
replayed: external_exports.boolean(),
|
|
46834
|
+
reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
|
46835
|
+
request: external_exports.strictObject({
|
|
46836
|
+
authorization: external_exports.strictObject({
|
|
46837
|
+
from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
46838
|
+
to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
46839
|
+
value: external_exports.string().regex(/^\d+$/),
|
|
46840
|
+
validAfter: external_exports.string().regex(/^\d+$/),
|
|
46841
|
+
validBefore: external_exports.string().regex(/^\d+$/),
|
|
46842
|
+
nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
|
|
46843
|
+
}),
|
|
46844
|
+
signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
|
|
46845
|
+
}).optional()
|
|
46846
|
+
}).optional(),
|
|
46847
|
+
settlement: external_exports.strictObject({
|
|
46848
|
+
outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
|
|
46849
|
+
transaction: external_exports.string().optional(),
|
|
46850
|
+
explorerUrl: external_exports.url().optional(),
|
|
46851
|
+
evidence: external_exports.unknown().optional()
|
|
46852
|
+
}).optional(),
|
|
46853
|
+
latencyMs: external_exports.number().nonnegative().finite().optional(),
|
|
46854
|
+
status: external_exports.number().int().min(100).max(599).optional(),
|
|
46855
|
+
error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
|
|
46856
|
+
phases: external_exports.strictObject({
|
|
46857
|
+
discoverMs: durationSchema.optional(),
|
|
46858
|
+
quoteMs: durationSchema.optional(),
|
|
46859
|
+
signMs: durationSchema.optional(),
|
|
46860
|
+
requestMs: durationSchema.optional(),
|
|
46861
|
+
settleMs: durationSchema.optional()
|
|
46862
|
+
}).optional(),
|
|
46863
|
+
listing: external_exports.strictObject({
|
|
46864
|
+
name: external_exports.string().min(1).optional(),
|
|
46865
|
+
providerHost: external_exports.string().min(1).optional(),
|
|
46866
|
+
source: external_exports.string().min(1)
|
|
46867
|
+
}).optional(),
|
|
46868
|
+
retry: external_exports.number().int().nonnegative().optional(),
|
|
46869
|
+
policy: external_exports.strictObject({
|
|
46870
|
+
maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
|
|
46871
|
+
capsApplied: external_exports.boolean()
|
|
46872
|
+
}).optional(),
|
|
46873
|
+
client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
|
|
46874
|
+
outcome: external_exports.enum([
|
|
46875
|
+
"paid",
|
|
46876
|
+
"signed_in",
|
|
46877
|
+
"declined_policy",
|
|
46878
|
+
"failed_request",
|
|
46879
|
+
"settlement_rejected",
|
|
46880
|
+
"settlement_unknown"
|
|
46881
|
+
]).optional()
|
|
46882
|
+
});
|
|
46883
|
+
function parseReceipt(value) {
|
|
46884
|
+
const receipt = receiptSchema.parse(value);
|
|
46885
|
+
const transaction = receipt.settlement?.transaction;
|
|
46886
|
+
const network = receipt.quote?.network;
|
|
46887
|
+
const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
|
|
46888
|
+
if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
|
|
46889
|
+
return receipt;
|
|
46890
|
+
}
|
|
46891
|
+
return {
|
|
46892
|
+
...receipt,
|
|
46893
|
+
settlement: {
|
|
46894
|
+
outcome: receipt.settlement.outcome,
|
|
46895
|
+
...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
|
|
46896
|
+
explorerUrl,
|
|
46897
|
+
...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
|
|
46898
|
+
}
|
|
46899
|
+
};
|
|
46900
|
+
}
|
|
46901
|
+
function receiptWallet(receipt) {
|
|
46902
|
+
return receipt.wallet ?? DEFAULT_WALLET_NAME;
|
|
46903
|
+
}
|
|
46904
|
+
|
|
46905
|
+
// src/agent-link.ts
|
|
46906
|
+
import { createHash } from "node:crypto";
|
|
46907
|
+
import { mkdir as mkdir5, open as open4, stat as stat4, unlink as unlink4 } from "node:fs/promises";
|
|
46908
|
+
import { dirname as dirname3 } from "node:path";
|
|
46909
|
+
var AGENT_LINK_REVOKED_MESSAGE = "This agent's link was revoked or has expired. Run vapi login to link it again.";
|
|
46910
|
+
var REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE = "The Railway run's short-lived vAPI access token expired. Start a new Railway run from the owner machine.";
|
|
46911
|
+
var AgentLinkError = class extends Error {
|
|
46912
|
+
constructor(code, message) {
|
|
46913
|
+
super(message);
|
|
46914
|
+
this.code = code;
|
|
46915
|
+
this.name = "AgentLinkError";
|
|
46916
|
+
}
|
|
46917
|
+
code;
|
|
46918
|
+
};
|
|
46919
|
+
var DEFAULT_AGENT_SCOPES = ["mcp:call", "router.use"];
|
|
46920
|
+
var ALLOWED_AGENT_SCOPES = /* @__PURE__ */ new Set([...DEFAULT_AGENT_SCOPES, "call.publish"]);
|
|
46921
|
+
var publicFetch = createPublicFetch({ allowPrivateNetwork: false });
|
|
46922
|
+
var agentSecretAccounts = (wallet) => ({
|
|
46923
|
+
tokens: `vapi.agent.${wallet}.tokens`,
|
|
46924
|
+
routerStake: `vapi.agent.${wallet}.router.stake`,
|
|
46925
|
+
routerBalance: `vapi.agent.${wallet}.router.balance`
|
|
46926
|
+
});
|
|
46927
|
+
async function agentFetch(args, url2, init) {
|
|
46928
|
+
const fetchImpl = args.fetchImpl ?? publicFetch;
|
|
46929
|
+
const accessToken = await resolveAgentAccessToken(args, {});
|
|
46930
|
+
const response = await safeAgentFetch(fetchImpl, url2, withBearer(init, accessToken));
|
|
46931
|
+
if (response.status !== 401) return response;
|
|
46932
|
+
const refreshedToken = await resolveAgentAccessToken(args, { rejectedAccessToken: accessToken });
|
|
46933
|
+
const refreshedResponse = await safeAgentFetch(fetchImpl, url2, withBearer(init, refreshedToken));
|
|
46934
|
+
if (refreshedResponse.status === 401) {
|
|
46935
|
+
throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
|
|
46936
|
+
}
|
|
46937
|
+
return refreshedResponse;
|
|
46938
|
+
}
|
|
46939
|
+
async function resolveAgentAccessToken(args, options) {
|
|
46940
|
+
await args.wallets.reload();
|
|
46941
|
+
const link3 = args.wallets.entry(args.wallet)?.link;
|
|
46942
|
+
if (link3 === void 0 || !args.secrets.available) throw notLinkedError();
|
|
46943
|
+
const accounts = agentSecretAccounts(args.wallet);
|
|
46944
|
+
const tokens = parseTokens(await safeGetSecret(args.secrets, accounts.tokens));
|
|
46945
|
+
if (tokens === void 0) throw notLinkedError();
|
|
46946
|
+
const now = args.now ?? Date.now;
|
|
46947
|
+
if (options.rejectedAccessToken === void 0 && tokens.expiresAt - 6e4 > now()) {
|
|
46948
|
+
return tokens.accessToken;
|
|
46949
|
+
}
|
|
46950
|
+
return await withAgentCredentialLock(args.wallets, link3.clientId, async () => {
|
|
46951
|
+
await args.wallets.reload();
|
|
46952
|
+
const currentLink = args.wallets.entry(args.wallet)?.link;
|
|
46953
|
+
if (currentLink === void 0) throw notLinkedError();
|
|
46954
|
+
const currentAccounts = agentSecretAccounts(args.wallet);
|
|
46955
|
+
const current = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
|
|
46956
|
+
if (current === void 0) throw notLinkedError();
|
|
46957
|
+
if (options.rejectedAccessToken !== void 0 && current.accessToken !== options.rejectedAccessToken) {
|
|
46958
|
+
return current.accessToken;
|
|
46959
|
+
}
|
|
46960
|
+
if (options.rejectedAccessToken === void 0 && current.expiresAt - 6e4 > now()) {
|
|
46961
|
+
return current.accessToken;
|
|
46962
|
+
}
|
|
46963
|
+
if (current.refreshToken === void 0) {
|
|
46964
|
+
throw new AgentLinkError("not_linked", REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE);
|
|
46965
|
+
}
|
|
46966
|
+
const response = await safeFetch(
|
|
46967
|
+
args.fetchImpl ?? publicFetch,
|
|
46968
|
+
apiEndpoint(currentLink.apiBase, "/oauth/token"),
|
|
46969
|
+
{
|
|
46970
|
+
method: "POST",
|
|
46971
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
46972
|
+
body: new URLSearchParams({
|
|
46973
|
+
grant_type: "refresh_token",
|
|
46974
|
+
refresh_token: current.refreshToken,
|
|
46975
|
+
client_id: currentLink.clientId
|
|
46976
|
+
})
|
|
46977
|
+
}
|
|
46978
|
+
);
|
|
46979
|
+
const payload = await responseRecord(response);
|
|
46980
|
+
if (!response.ok) {
|
|
46981
|
+
if (response.status === 400 && stringField(payload, "error") === "invalid_grant") {
|
|
46982
|
+
throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
|
|
46983
|
+
}
|
|
46984
|
+
throw httpError("The vAPI agent token refresh failed.");
|
|
46985
|
+
}
|
|
46986
|
+
const refreshed = {
|
|
46987
|
+
accessToken: requiredString(payload, "access_token"),
|
|
46988
|
+
refreshToken: stringField(payload, "refresh_token") ?? current.refreshToken,
|
|
46989
|
+
expiresAt: now() + requiredNumber(payload, "expires_in") * 1e3,
|
|
46990
|
+
scopes: stringField(payload, "scope") === void 0 ? [...current.scopes] : splitScopes(requiredString(payload, "scope"))
|
|
46991
|
+
};
|
|
46992
|
+
await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
|
|
46993
|
+
return refreshed.accessToken;
|
|
46994
|
+
});
|
|
46995
|
+
}
|
|
46996
|
+
async function withAgentCredentialLock(wallets, clientId, operation) {
|
|
46997
|
+
const digest = createHash("sha256").update(clientId).digest("hex").slice(0, 24);
|
|
46998
|
+
const lockPath = `${wallets.registryPath}.${digest}.agent-link.lock`;
|
|
46999
|
+
await mkdir5(dirname3(lockPath), { recursive: true, mode: 448 });
|
|
47000
|
+
const deadline = Date.now() + 3e4;
|
|
47001
|
+
let handle;
|
|
47002
|
+
while (!handle) {
|
|
47003
|
+
try {
|
|
47004
|
+
handle = await open4(lockPath, "wx", 384);
|
|
47005
|
+
} catch (error61) {
|
|
47006
|
+
if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
|
|
47007
|
+
await removeStaleCredentialLock(lockPath);
|
|
47008
|
+
if (Date.now() >= deadline) {
|
|
47009
|
+
throw httpError("Timed out waiting to update the agent credentials.");
|
|
47010
|
+
}
|
|
47011
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
47012
|
+
}
|
|
47013
|
+
}
|
|
47014
|
+
try {
|
|
47015
|
+
return await operation();
|
|
47016
|
+
} finally {
|
|
47017
|
+
await handle.close();
|
|
47018
|
+
await unlink4(lockPath).catch(() => void 0);
|
|
47019
|
+
}
|
|
47020
|
+
}
|
|
47021
|
+
async function removeStaleCredentialLock(path) {
|
|
47022
|
+
try {
|
|
47023
|
+
const metadata = await stat4(path);
|
|
47024
|
+
if (Date.now() - metadata.mtimeMs > 5 * 6e4) await unlink4(path);
|
|
47025
|
+
} catch {
|
|
47026
|
+
}
|
|
47027
|
+
}
|
|
47028
|
+
async function safeGetSecret(secrets, account) {
|
|
47029
|
+
try {
|
|
47030
|
+
return await secrets.get(account);
|
|
47031
|
+
} catch {
|
|
47032
|
+
throw httpError("The agent tokens could not be read from the OS secret store.");
|
|
47033
|
+
}
|
|
47034
|
+
}
|
|
47035
|
+
async function safeSetSecret(secrets, account, value) {
|
|
47036
|
+
try {
|
|
47037
|
+
await secrets.set(account, value);
|
|
47038
|
+
} catch {
|
|
47039
|
+
throw httpError("The agent credentials could not be stored in the OS secret store.");
|
|
47040
|
+
}
|
|
47041
|
+
}
|
|
47042
|
+
function parseTokens(value) {
|
|
47043
|
+
if (value === void 0) return void 0;
|
|
47044
|
+
let parsed;
|
|
47045
|
+
try {
|
|
47046
|
+
parsed = JSON.parse(value);
|
|
47047
|
+
} catch {
|
|
47048
|
+
return void 0;
|
|
47049
|
+
}
|
|
47050
|
+
if (!isRecord(parsed)) return void 0;
|
|
47051
|
+
const accessToken = stringField(parsed, "accessToken");
|
|
47052
|
+
const refreshToken = stringField(parsed, "refreshToken");
|
|
47053
|
+
const refreshable = parsed.refreshable;
|
|
47054
|
+
const expiresAt = numberField(parsed, "expiresAt");
|
|
47055
|
+
const scopes = parsed.scopes;
|
|
47056
|
+
if (accessToken === void 0 || expiresAt === void 0 || !Array.isArray(scopes) || scopes.some((scope) => typeof scope !== "string") || (refreshToken === void 0 ? refreshable !== false : refreshable === false)) {
|
|
47057
|
+
return void 0;
|
|
47058
|
+
}
|
|
47059
|
+
return {
|
|
47060
|
+
accessToken,
|
|
47061
|
+
...refreshToken === void 0 ? {} : { refreshToken },
|
|
47062
|
+
expiresAt,
|
|
47063
|
+
scopes
|
|
47064
|
+
};
|
|
47065
|
+
}
|
|
47066
|
+
function withBearer(init, accessToken) {
|
|
47067
|
+
const headers = new Headers(init?.headers);
|
|
47068
|
+
headers.set("authorization", `Bearer ${accessToken}`);
|
|
47069
|
+
return { ...init, headers };
|
|
47070
|
+
}
|
|
47071
|
+
async function safeFetch(fetchImpl, input2, init) {
|
|
47072
|
+
try {
|
|
47073
|
+
return await fetchImpl(input2, init);
|
|
47074
|
+
} catch {
|
|
47075
|
+
throw httpError("The vAPI agent link request failed.");
|
|
47076
|
+
}
|
|
47077
|
+
}
|
|
47078
|
+
async function safeAgentFetch(fetchImpl, input2, init) {
|
|
47079
|
+
try {
|
|
47080
|
+
return await fetchImpl(input2, init);
|
|
47081
|
+
} catch {
|
|
47082
|
+
throw httpError("The vAPI agent request failed.");
|
|
47083
|
+
}
|
|
47084
|
+
}
|
|
47085
|
+
function notLinkedError() {
|
|
47086
|
+
return new AgentLinkError("not_linked", "Run vapi login first.");
|
|
47087
|
+
}
|
|
47088
|
+
function httpError(message) {
|
|
47089
|
+
return new AgentLinkError("http", message);
|
|
47090
|
+
}
|
|
47091
|
+
function apiEndpoint(apiBase, path) {
|
|
47092
|
+
return new URL(path, new URL(apiBase).origin).toString();
|
|
47093
|
+
}
|
|
47094
|
+
async function responseRecord(response) {
|
|
47095
|
+
let payload;
|
|
47096
|
+
try {
|
|
47097
|
+
payload = await response.json();
|
|
47098
|
+
} catch {
|
|
47099
|
+
throw httpError("The vAPI agent link response was invalid.");
|
|
47100
|
+
}
|
|
47101
|
+
if (!isRecord(payload)) throw httpError("The vAPI agent link response was invalid.");
|
|
47102
|
+
return payload;
|
|
47103
|
+
}
|
|
47104
|
+
function isRecord(value) {
|
|
47105
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
47106
|
+
}
|
|
47107
|
+
function stringField(record2, key) {
|
|
47108
|
+
const value = record2[key];
|
|
47109
|
+
return typeof value === "string" ? value : void 0;
|
|
47110
|
+
}
|
|
47111
|
+
function numberField(record2, key) {
|
|
47112
|
+
const value = record2[key];
|
|
47113
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
47114
|
+
}
|
|
47115
|
+
function requiredString(record2, key) {
|
|
47116
|
+
const value = stringField(record2, key);
|
|
47117
|
+
if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
|
|
47118
|
+
return value;
|
|
47119
|
+
}
|
|
47120
|
+
function requiredNumber(record2, key) {
|
|
47121
|
+
const value = numberField(record2, key);
|
|
47122
|
+
if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
|
|
47123
|
+
return value;
|
|
47124
|
+
}
|
|
47125
|
+
function splitScopes(scope) {
|
|
47126
|
+
return scope.split(/\s+/u).filter(Boolean);
|
|
47127
|
+
}
|
|
47128
|
+
|
|
47129
|
+
// src/movement-open.ts
|
|
47130
|
+
function isOpenMovementLeg(leg, journalEvidence) {
|
|
47131
|
+
if (leg.status === "sent" || leg.status === "cancelled") return false;
|
|
47132
|
+
if (leg.restored === true) return true;
|
|
47133
|
+
if (leg.status === "planned" || leg.status === "unknown") return true;
|
|
47134
|
+
if (leg.status !== "failed") return false;
|
|
47135
|
+
if (leg.retryable === true) return true;
|
|
47136
|
+
return journalEvidence === "signed";
|
|
47137
|
+
}
|
|
47138
|
+
|
|
47139
|
+
// src/transfer-journal.ts
|
|
47140
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
47141
|
+
async function readTransferJournal(home, from, nonce) {
|
|
47142
|
+
let raw;
|
|
47143
|
+
try {
|
|
47144
|
+
raw = await readFile5(getVapiPaths(home).receipts, "utf8");
|
|
47145
|
+
} catch (error61) {
|
|
47146
|
+
if (isMissingFile(error61)) return { signed: false };
|
|
47147
|
+
throw error61;
|
|
47148
|
+
}
|
|
47149
|
+
let latest;
|
|
47150
|
+
let request;
|
|
47151
|
+
for (const [index, line] of raw.split("\n").entries()) {
|
|
47152
|
+
if (!line.trim()) continue;
|
|
47153
|
+
let receipt;
|
|
47154
|
+
try {
|
|
47155
|
+
receipt = parseReceipt(JSON.parse(line));
|
|
47156
|
+
} catch (error61) {
|
|
47157
|
+
throw new Error(`Invalid receipt on JSONL line ${index + 1}.`, { cause: error61 });
|
|
47158
|
+
}
|
|
47159
|
+
if (receiptWallet(receipt) !== from || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
|
|
47160
|
+
continue;
|
|
47161
|
+
}
|
|
47162
|
+
latest = receipt;
|
|
47163
|
+
if (receipt.transfer.request !== void 0) request = receipt;
|
|
47164
|
+
}
|
|
47165
|
+
return {
|
|
47166
|
+
signed: latest !== void 0,
|
|
47167
|
+
...latest === void 0 ? {} : { latest },
|
|
47168
|
+
...request === void 0 ? {} : { request },
|
|
47169
|
+
...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
|
|
47170
|
+
...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
|
|
47171
|
+
};
|
|
47172
|
+
}
|
|
46047
47173
|
|
|
46048
47174
|
// src/vault-key.ts
|
|
46049
47175
|
import { randomBytes as cryptoRandomBytes } from "node:crypto";
|
|
46050
47176
|
|
|
46051
47177
|
// src/vault.ts
|
|
46052
|
-
import { randomBytes as
|
|
46053
|
-
import { mkdir, open as
|
|
46054
|
-
import { dirname } from "node:path";
|
|
47178
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
47179
|
+
import { mkdir as mkdir6, open as open5, readFile as readFile6, rename as rename4, rm, stat as stat5, unlink as unlink5, writeFile as writeFile3 } from "node:fs/promises";
|
|
47180
|
+
import { dirname as dirname4 } from "node:path";
|
|
46055
47181
|
var VaultError = class extends Error {
|
|
46056
47182
|
code;
|
|
46057
47183
|
constructor(code, message, options) {
|
|
@@ -46596,9 +47722,9 @@ async function readVaultFile(path, key) {
|
|
|
46596
47722
|
async function readVaultFileUnlocked(path) {
|
|
46597
47723
|
let raw;
|
|
46598
47724
|
try {
|
|
46599
|
-
raw = await
|
|
47725
|
+
raw = await readFile6(path, "utf8");
|
|
46600
47726
|
} catch (error61) {
|
|
46601
|
-
if (
|
|
47727
|
+
if (isMissingFile2(error61)) {
|
|
46602
47728
|
throw new VaultError("not_found", "No vault file was found at the requested path.", {
|
|
46603
47729
|
cause: error61
|
|
46604
47730
|
});
|
|
@@ -46609,9 +47735,9 @@ async function readVaultFileUnlocked(path) {
|
|
|
46609
47735
|
}
|
|
46610
47736
|
async function refuseExistingVault(path) {
|
|
46611
47737
|
try {
|
|
46612
|
-
await
|
|
47738
|
+
await stat5(path);
|
|
46613
47739
|
} catch (error61) {
|
|
46614
|
-
if (
|
|
47740
|
+
if (isMissingFile2(error61)) return;
|
|
46615
47741
|
throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
|
|
46616
47742
|
cause: error61
|
|
46617
47743
|
});
|
|
@@ -46619,29 +47745,29 @@ async function refuseExistingVault(path) {
|
|
|
46619
47745
|
throw new VaultError("corrupt", "A vault already exists at the requested path.");
|
|
46620
47746
|
}
|
|
46621
47747
|
async function writeVaultFile(path, file2) {
|
|
46622
|
-
await
|
|
46623
|
-
const temporaryPath = `${path}.${process.pid}.${
|
|
47748
|
+
await mkdir6(dirname4(path), { recursive: true, mode: 448 });
|
|
47749
|
+
const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
|
|
46624
47750
|
try {
|
|
46625
|
-
await
|
|
47751
|
+
await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
|
|
46626
47752
|
`, {
|
|
46627
47753
|
encoding: "utf8",
|
|
46628
47754
|
mode: 384,
|
|
46629
47755
|
flag: "wx"
|
|
46630
47756
|
});
|
|
46631
|
-
await
|
|
47757
|
+
await rename4(temporaryPath, path);
|
|
46632
47758
|
} catch (error61) {
|
|
46633
47759
|
await rm(temporaryPath, { force: true }).catch(() => void 0);
|
|
46634
47760
|
throw error61;
|
|
46635
47761
|
}
|
|
46636
47762
|
}
|
|
46637
47763
|
async function withVaultLock(path, operation) {
|
|
46638
|
-
await
|
|
47764
|
+
await mkdir6(dirname4(path), { recursive: true, mode: 448 });
|
|
46639
47765
|
const lockPath = `${path}.lock`;
|
|
46640
47766
|
const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
|
|
46641
47767
|
let handle;
|
|
46642
47768
|
while (!handle) {
|
|
46643
47769
|
try {
|
|
46644
|
-
handle = await
|
|
47770
|
+
handle = await open5(lockPath, "wx", 384);
|
|
46645
47771
|
} catch (error61) {
|
|
46646
47772
|
if (!isExistingFile(error61)) throw error61;
|
|
46647
47773
|
await removeStaleVaultLock(lockPath);
|
|
@@ -46655,18 +47781,18 @@ async function withVaultLock(path, operation) {
|
|
|
46655
47781
|
return await operation();
|
|
46656
47782
|
} finally {
|
|
46657
47783
|
await handle.close();
|
|
46658
|
-
await
|
|
47784
|
+
await unlink5(lockPath).catch(() => void 0);
|
|
46659
47785
|
}
|
|
46660
47786
|
}
|
|
46661
47787
|
async function removeStaleVaultLock(path) {
|
|
46662
47788
|
try {
|
|
46663
|
-
const metadata = await
|
|
46664
|
-
if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await
|
|
47789
|
+
const metadata = await stat5(path);
|
|
47790
|
+
if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink5(path);
|
|
46665
47791
|
} catch (error61) {
|
|
46666
|
-
if (!
|
|
47792
|
+
if (!isMissingFile2(error61)) throw error61;
|
|
46667
47793
|
}
|
|
46668
47794
|
}
|
|
46669
|
-
function
|
|
47795
|
+
function isMissingFile2(error61) {
|
|
46670
47796
|
return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
|
|
46671
47797
|
}
|
|
46672
47798
|
function isExistingFile(error61) {
|
|
@@ -46810,8 +47936,8 @@ function passwordRequiredError() {
|
|
|
46810
47936
|
"A vault password is needed. Pass it or set VAPI_VAULT_PASSWORD."
|
|
46811
47937
|
);
|
|
46812
47938
|
}
|
|
46813
|
-
function randomKeyBytes(
|
|
46814
|
-
const key = Buffer.from((
|
|
47939
|
+
function randomKeyBytes(randomBytes7) {
|
|
47940
|
+
const key = Buffer.from((randomBytes7 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
|
|
46815
47941
|
if (key.byteLength !== DEVICE_KEY_LENGTH) {
|
|
46816
47942
|
key.fill(0);
|
|
46817
47943
|
throw new VaultError("corrupt", "A generated device vault key has the wrong length.");
|
|
@@ -46879,6 +48005,7 @@ var routerRefillSchema = external_exports.object({
|
|
|
46879
48005
|
});
|
|
46880
48006
|
var ceilingSweepPendingSchema = external_exports.strictObject({
|
|
46881
48007
|
owner: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
48008
|
+
target: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).optional(),
|
|
46882
48009
|
amountAtomic: external_exports.string().regex(/^\d+$/),
|
|
46883
48010
|
nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
|
|
46884
48011
|
createdAt: external_exports.iso.datetime(),
|
|
@@ -46902,6 +48029,426 @@ var walletRegistrySchema = external_exports.object({
|
|
|
46902
48029
|
wallets: external_exports.record(walletNameSchema, walletEntrySchema)
|
|
46903
48030
|
});
|
|
46904
48031
|
|
|
48032
|
+
// src/movement.ts
|
|
48033
|
+
var movementIdSchema = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/);
|
|
48034
|
+
var nonceSchema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/);
|
|
48035
|
+
var amountSchema = external_exports.string().regex(/^\d+\.\d{2}$/);
|
|
48036
|
+
var movementReasonSchema = external_exports.enum([
|
|
48037
|
+
"distribute",
|
|
48038
|
+
"allocate",
|
|
48039
|
+
"rebalance",
|
|
48040
|
+
"delegate",
|
|
48041
|
+
"sweep",
|
|
48042
|
+
"send"
|
|
48043
|
+
]);
|
|
48044
|
+
var movementPurposeSchema = external_exports.enum(["send", "sweep"]);
|
|
48045
|
+
var movementAddressSchema = external_exports.string().refine((value) => isAddress(value, { strict: false }));
|
|
48046
|
+
var movementLegSchema = external_exports.strictObject({
|
|
48047
|
+
from: walletNameSchema,
|
|
48048
|
+
to: external_exports.string().trim().min(1),
|
|
48049
|
+
fromAddress: movementAddressSchema.optional(),
|
|
48050
|
+
toAddress: movementAddressSchema.optional(),
|
|
48051
|
+
amountUsd: amountSchema,
|
|
48052
|
+
purpose: movementPurposeSchema,
|
|
48053
|
+
nonce: nonceSchema,
|
|
48054
|
+
status: external_exports.enum(["planned", "sent", "failed", "unknown", "cancelled"]),
|
|
48055
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).optional(),
|
|
48056
|
+
reason: external_exports.string().min(1).optional(),
|
|
48057
|
+
retryable: external_exports.boolean().optional(),
|
|
48058
|
+
restored: external_exports.literal(true).optional(),
|
|
48059
|
+
addressBindingSource: external_exports.enum(["journal", "terminal-review"]).optional()
|
|
48060
|
+
});
|
|
48061
|
+
var movementSchema = external_exports.strictObject({
|
|
48062
|
+
v: external_exports.literal(2),
|
|
48063
|
+
id: movementIdSchema,
|
|
48064
|
+
reason: movementReasonSchema,
|
|
48065
|
+
from: walletNameSchema,
|
|
48066
|
+
// The only account a `sweep` leg may name besides the owner. Sweeps skip the
|
|
48067
|
+
// spend caps, so the parent comes from the plan, never from a leg's `to`.
|
|
48068
|
+
treasury: walletNameSchema.optional(),
|
|
48069
|
+
network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
|
|
48070
|
+
createdAt: external_exports.iso.datetime(),
|
|
48071
|
+
legs: external_exports.array(movementLegSchema).min(1)
|
|
48072
|
+
});
|
|
48073
|
+
var legacyMovementSchema = external_exports.strictObject({
|
|
48074
|
+
v: external_exports.literal(1),
|
|
48075
|
+
id: movementIdSchema,
|
|
48076
|
+
reason: external_exports.literal("distribute"),
|
|
48077
|
+
from: walletNameSchema,
|
|
48078
|
+
network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
|
|
48079
|
+
createdAt: external_exports.iso.datetime(),
|
|
48080
|
+
legs: external_exports.array(
|
|
48081
|
+
external_exports.strictObject({
|
|
48082
|
+
to: external_exports.string().trim().min(1),
|
|
48083
|
+
amountUsd: amountSchema,
|
|
48084
|
+
nonce: nonceSchema,
|
|
48085
|
+
status: external_exports.enum(["planned", "sent", "failed", "unknown"]),
|
|
48086
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).optional(),
|
|
48087
|
+
reason: external_exports.string().min(1).optional(),
|
|
48088
|
+
retryable: external_exports.boolean().optional()
|
|
48089
|
+
})
|
|
48090
|
+
).min(1)
|
|
48091
|
+
});
|
|
48092
|
+
var MovementError = class extends Error {
|
|
48093
|
+
constructor(code, message, movementId) {
|
|
48094
|
+
super(message);
|
|
48095
|
+
this.code = code;
|
|
48096
|
+
this.movementId = movementId;
|
|
48097
|
+
this.name = "MovementError";
|
|
48098
|
+
}
|
|
48099
|
+
code;
|
|
48100
|
+
movementId;
|
|
48101
|
+
};
|
|
48102
|
+
async function listUnfinishedMovementSnapshots(options) {
|
|
48103
|
+
const directory = movementsDirectory(options.home);
|
|
48104
|
+
let names;
|
|
48105
|
+
try {
|
|
48106
|
+
names = await readdir3(directory);
|
|
48107
|
+
} catch (error61) {
|
|
48108
|
+
if (isMissingFile(error61)) return [];
|
|
48109
|
+
throw error61;
|
|
48110
|
+
}
|
|
48111
|
+
const snapshots = [];
|
|
48112
|
+
for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
|
|
48113
|
+
const movement = parseMovement(JSON.parse(await readFile7(join6(directory, name), "utf8")));
|
|
48114
|
+
if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
|
|
48115
|
+
continue;
|
|
48116
|
+
}
|
|
48117
|
+
const pendingLegs = movement.legs.filter((leg) => leg.status === "planned").length;
|
|
48118
|
+
const unknownLegs = movement.legs.filter((leg) => leg.status === "unknown").length;
|
|
48119
|
+
const evidence = await movementOpenEvidence(options.home, movement, options.from);
|
|
48120
|
+
if (!evidence.open) continue;
|
|
48121
|
+
snapshots.push({
|
|
48122
|
+
movement,
|
|
48123
|
+
summary: {
|
|
48124
|
+
id: movement.id,
|
|
48125
|
+
from: movement.from,
|
|
48126
|
+
network: movement.network,
|
|
48127
|
+
createdAt: movement.createdAt,
|
|
48128
|
+
pendingLegs,
|
|
48129
|
+
unknownLegs
|
|
48130
|
+
},
|
|
48131
|
+
signedFailedLegKeys: evidence.signedFailedLegKeys
|
|
48132
|
+
});
|
|
48133
|
+
}
|
|
48134
|
+
return snapshots.sort(
|
|
48135
|
+
(left, right) => left.summary.createdAt.localeCompare(right.summary.createdAt) || left.summary.id.localeCompare(right.summary.id)
|
|
48136
|
+
);
|
|
48137
|
+
}
|
|
48138
|
+
async function movementOpenEvidence(home, movement, from) {
|
|
48139
|
+
let open7 = false;
|
|
48140
|
+
const signedFailedLegKeys = [];
|
|
48141
|
+
for (const leg of movement.legs) {
|
|
48142
|
+
if (from !== void 0 && leg.from !== from) continue;
|
|
48143
|
+
if (isOpenMovementLeg(leg, "unsigned")) open7 = true;
|
|
48144
|
+
if (leg.status !== "failed") continue;
|
|
48145
|
+
const journal = await readTransferJournal(home, leg.from, leg.nonce);
|
|
48146
|
+
if (journal.signed) signedFailedLegKeys.push(movementTransferKey(leg.from, leg.nonce));
|
|
48147
|
+
if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open7 = true;
|
|
48148
|
+
}
|
|
48149
|
+
return { open: open7, signedFailedLegKeys };
|
|
48150
|
+
}
|
|
48151
|
+
async function readMovement(home, id) {
|
|
48152
|
+
const safeId = parseMovementId(id);
|
|
48153
|
+
try {
|
|
48154
|
+
return parseMovement(
|
|
48155
|
+
JSON.parse(await readFile7(join6(movementsDirectory(home), `${safeId}.json`), "utf8"))
|
|
48156
|
+
);
|
|
48157
|
+
} catch (error61) {
|
|
48158
|
+
if (isMissingFile(error61)) {
|
|
48159
|
+
throw new MovementError(
|
|
48160
|
+
"movement_not_found",
|
|
48161
|
+
`No movement named ${safeId} was found.`,
|
|
48162
|
+
safeId
|
|
48163
|
+
);
|
|
48164
|
+
}
|
|
48165
|
+
throw error61;
|
|
48166
|
+
}
|
|
48167
|
+
}
|
|
48168
|
+
function movementTransferKey(from, nonce) {
|
|
48169
|
+
return `${from}\0${nonce.toLowerCase()}`;
|
|
48170
|
+
}
|
|
48171
|
+
async function reconcileSignedLegs(home, id, signedKeys) {
|
|
48172
|
+
const initial = await readMovement(home, id);
|
|
48173
|
+
return await withMovementLocks(home, movementSenders(initial), void 0, async () => {
|
|
48174
|
+
const movement = await readMovement(home, id);
|
|
48175
|
+
const reconciled = movementWithSignedLegsUnknown(movement, signedKeys);
|
|
48176
|
+
if (reconciled !== movement) await writeMovement(home, reconciled);
|
|
48177
|
+
return reconciled;
|
|
48178
|
+
});
|
|
48179
|
+
}
|
|
48180
|
+
async function markOpenLegsRestored(home, id) {
|
|
48181
|
+
let initial;
|
|
48182
|
+
try {
|
|
48183
|
+
initial = await readMovement(home, id);
|
|
48184
|
+
} catch (error61) {
|
|
48185
|
+
if (error61 instanceof MovementError && error61.code === "movement_not_found" || error61 instanceof SyntaxError || error61 instanceof external_exports.ZodError) {
|
|
48186
|
+
return void 0;
|
|
48187
|
+
}
|
|
48188
|
+
throw error61;
|
|
48189
|
+
}
|
|
48190
|
+
return await withMovementLocks(home, movementSenders(initial), void 0, async () => {
|
|
48191
|
+
const movement = await readMovement(home, id);
|
|
48192
|
+
let changed = false;
|
|
48193
|
+
const legs = movement.legs.map((leg) => {
|
|
48194
|
+
if (leg.status === "sent" || leg.status === "cancelled" || leg.restored === true) return leg;
|
|
48195
|
+
changed = true;
|
|
48196
|
+
return { ...leg, restored: true };
|
|
48197
|
+
});
|
|
48198
|
+
if (!changed) return movement;
|
|
48199
|
+
const restored = movementSchema.parse({ ...movement, legs });
|
|
48200
|
+
await writeMovement(home, restored);
|
|
48201
|
+
return restored;
|
|
48202
|
+
});
|
|
48203
|
+
}
|
|
48204
|
+
function unknownLeg(leg) {
|
|
48205
|
+
return {
|
|
48206
|
+
from: leg.from,
|
|
48207
|
+
to: leg.to,
|
|
48208
|
+
...legAddressBinding(leg),
|
|
48209
|
+
amountUsd: leg.amountUsd,
|
|
48210
|
+
purpose: leg.purpose,
|
|
48211
|
+
nonce: leg.nonce,
|
|
48212
|
+
status: "unknown",
|
|
48213
|
+
...restoredMarker(leg)
|
|
48214
|
+
};
|
|
48215
|
+
}
|
|
48216
|
+
function restoredMarker(leg) {
|
|
48217
|
+
return leg.restored === true ? { restored: true } : {};
|
|
48218
|
+
}
|
|
48219
|
+
function legAddressBinding(leg) {
|
|
48220
|
+
return {
|
|
48221
|
+
...leg.fromAddress === void 0 ? {} : { fromAddress: leg.fromAddress },
|
|
48222
|
+
...leg.toAddress === void 0 ? {} : { toAddress: leg.toAddress },
|
|
48223
|
+
...leg.addressBindingSource === void 0 ? {} : { addressBindingSource: leg.addressBindingSource }
|
|
48224
|
+
};
|
|
48225
|
+
}
|
|
48226
|
+
function isExpiredRestoredReview(leg) {
|
|
48227
|
+
return leg.restored === true && leg.reason === "restored_nonce_expired";
|
|
48228
|
+
}
|
|
48229
|
+
function movementWithSignedLegsUnknown(movement, signedKeys) {
|
|
48230
|
+
let changed = false;
|
|
48231
|
+
const legs = movement.legs.map((leg) => {
|
|
48232
|
+
if (isExpiredRestoredReview(leg)) return leg;
|
|
48233
|
+
if (leg.status === "sent" || leg.status === "cancelled" || !signedKeys.has(movementTransferKey(leg.from, leg.nonce)) || leg.status === "unknown" && leg.txHash === void 0 && leg.reason === void 0 && leg.retryable === void 0) {
|
|
48234
|
+
return leg;
|
|
48235
|
+
}
|
|
48236
|
+
changed = true;
|
|
48237
|
+
return unknownLeg(leg);
|
|
48238
|
+
});
|
|
48239
|
+
return changed ? movementSchema.parse({ ...movement, legs }) : movement;
|
|
48240
|
+
}
|
|
48241
|
+
function parseMovement(value) {
|
|
48242
|
+
const current = movementSchema.safeParse(value);
|
|
48243
|
+
if (current.success) return current.data;
|
|
48244
|
+
const legacy = legacyMovementSchema.parse(value);
|
|
48245
|
+
return movementSchema.parse({
|
|
48246
|
+
...legacy,
|
|
48247
|
+
v: 2,
|
|
48248
|
+
legs: legacy.legs.map((leg) => ({
|
|
48249
|
+
...leg,
|
|
48250
|
+
from: legacy.from,
|
|
48251
|
+
purpose: "send"
|
|
48252
|
+
}))
|
|
48253
|
+
});
|
|
48254
|
+
}
|
|
48255
|
+
function movementSenders(movement) {
|
|
48256
|
+
return sortedUniqueSenders(movement.legs.map((leg) => leg.from));
|
|
48257
|
+
}
|
|
48258
|
+
function sortedUniqueSenders(senders) {
|
|
48259
|
+
return [...new Set(senders)].sort();
|
|
48260
|
+
}
|
|
48261
|
+
function parseMovementId(value) {
|
|
48262
|
+
const parsed = movementIdSchema.safeParse(value);
|
|
48263
|
+
if (!parsed.success) throw new MovementError("invalid_movement", "The movement id is invalid.");
|
|
48264
|
+
return parsed.data;
|
|
48265
|
+
}
|
|
48266
|
+
function movementsDirectory(home) {
|
|
48267
|
+
return join6(home, "movements");
|
|
48268
|
+
}
|
|
48269
|
+
async function writeMovement(home, movement) {
|
|
48270
|
+
const parsed = movementSchema.parse(movement);
|
|
48271
|
+
const directory = movementsDirectory(home);
|
|
48272
|
+
await mkdir7(directory, { recursive: true, mode: 448 });
|
|
48273
|
+
await chmod(directory, 448);
|
|
48274
|
+
const path = join6(directory, `${parsed.id}.json`);
|
|
48275
|
+
const temporary = join6(
|
|
48276
|
+
directory,
|
|
48277
|
+
`.${parsed.id}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`
|
|
48278
|
+
);
|
|
48279
|
+
let handle;
|
|
48280
|
+
try {
|
|
48281
|
+
handle = await open6(temporary, "wx", 384);
|
|
48282
|
+
await handle.writeFile(serializeMovement(parsed), "utf8");
|
|
48283
|
+
await handle.sync();
|
|
48284
|
+
await handle.close();
|
|
48285
|
+
handle = void 0;
|
|
48286
|
+
await rename5(temporary, path);
|
|
48287
|
+
const directoryHandle = await open6(directory, "r");
|
|
48288
|
+
try {
|
|
48289
|
+
await directoryHandle.sync();
|
|
48290
|
+
} finally {
|
|
48291
|
+
await directoryHandle.close();
|
|
48292
|
+
}
|
|
48293
|
+
} catch (error61) {
|
|
48294
|
+
await handle?.close().catch(() => void 0);
|
|
48295
|
+
await unlink6(temporary).catch(() => void 0);
|
|
48296
|
+
throw error61;
|
|
48297
|
+
}
|
|
48298
|
+
}
|
|
48299
|
+
function serializeMovement(movement) {
|
|
48300
|
+
return `${JSON.stringify(movementSchema.parse(movement), null, 2)}
|
|
48301
|
+
`;
|
|
48302
|
+
}
|
|
48303
|
+
async function withMovementLock(home, from, timeoutMs, operation) {
|
|
48304
|
+
try {
|
|
48305
|
+
return await withAccountMovementLocks(home, [from], timeoutMs, operation);
|
|
48306
|
+
} catch (error61) {
|
|
48307
|
+
if (error61 instanceof AccountMovementLockedError) {
|
|
48308
|
+
throw new MovementError(
|
|
48309
|
+
"movement_locked",
|
|
48310
|
+
`Another movement is already running for account ${from}.`
|
|
48311
|
+
);
|
|
48312
|
+
}
|
|
48313
|
+
throw error61;
|
|
48314
|
+
}
|
|
48315
|
+
}
|
|
48316
|
+
async function withMovementLocks(home, senders, timeoutMs, operation) {
|
|
48317
|
+
const [sender, ...remaining] = senders;
|
|
48318
|
+
if (sender === void 0) return await operation();
|
|
48319
|
+
return await withMovementLock(
|
|
48320
|
+
home,
|
|
48321
|
+
sender,
|
|
48322
|
+
timeoutMs,
|
|
48323
|
+
async () => withMovementLocks(home, remaining, timeoutMs, operation)
|
|
48324
|
+
);
|
|
48325
|
+
}
|
|
48326
|
+
|
|
48327
|
+
// src/swarm.ts
|
|
48328
|
+
import { readdir as readdir4, readFile as readFile8, stat as stat6, unlink as unlink7 } from "node:fs/promises";
|
|
48329
|
+
import { join as join7 } from "node:path";
|
|
48330
|
+
var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
|
|
48331
|
+
var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
|
|
48332
|
+
var atomicSchema = external_exports.string().regex(/^\d+$/);
|
|
48333
|
+
var addressSchema2 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/);
|
|
48334
|
+
var capsSchema = external_exports.strictObject({ perCallAtomic: atomicSchema, perDayAtomic: atomicSchema });
|
|
48335
|
+
var movementIdSchema2 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
|
|
48336
|
+
var amountUsdSchema = external_exports.string().regex(/^\d+\.\d{2}$/u);
|
|
48337
|
+
var setupFundingStatusSchema = external_exports.enum(["planned", "sent", "incomplete"]);
|
|
48338
|
+
var blockedFundingLegSchema = external_exports.strictObject({
|
|
48339
|
+
to: external_exports.string().trim().min(1),
|
|
48340
|
+
amountUsd: amountUsdSchema,
|
|
48341
|
+
reason: external_exports.string().trim().min(1)
|
|
48342
|
+
});
|
|
48343
|
+
var setupFundingSchema = external_exports.strictObject({
|
|
48344
|
+
amountUsd: amountUsdSchema,
|
|
48345
|
+
from: walletNameSchema,
|
|
48346
|
+
movementId: movementIdSchema2.optional(),
|
|
48347
|
+
status: setupFundingStatusSchema,
|
|
48348
|
+
policy: external_exports.strictObject({
|
|
48349
|
+
strategy: external_exports.enum(["targets", "even", "weights"]),
|
|
48350
|
+
movementId: movementIdSchema2.optional(),
|
|
48351
|
+
status: setupFundingStatusSchema,
|
|
48352
|
+
blocked: external_exports.array(blockedFundingLegSchema).optional()
|
|
48353
|
+
}).optional()
|
|
48354
|
+
});
|
|
48355
|
+
var accountSteps = {
|
|
48356
|
+
creating: external_exports.boolean().default(false),
|
|
48357
|
+
created: external_exports.boolean(),
|
|
48358
|
+
capped: external_exports.boolean(),
|
|
48359
|
+
linked: external_exports.boolean()
|
|
48360
|
+
};
|
|
48361
|
+
var treasurySchema = external_exports.strictObject({
|
|
48362
|
+
account: walletNameSchema,
|
|
48363
|
+
// A planned account has no address until its vault derivation succeeds.
|
|
48364
|
+
address: addressSchema2.optional(),
|
|
48365
|
+
steps: external_exports.strictObject(accountSteps)
|
|
48366
|
+
}).refine(
|
|
48367
|
+
(value) => !value.steps.created || value.address !== void 0,
|
|
48368
|
+
"Created accounts require an address."
|
|
48369
|
+
);
|
|
48370
|
+
var memberSchema = external_exports.strictObject({
|
|
48371
|
+
account: walletNameSchema,
|
|
48372
|
+
address: addressSchema2.optional(),
|
|
48373
|
+
role: external_exports.string().regex(SWARM_ROLE_PATTERN),
|
|
48374
|
+
weight: external_exports.number().int().positive(),
|
|
48375
|
+
targetAtomic: atomicSchema,
|
|
48376
|
+
ceilingAtomic: atomicSchema.nullable(),
|
|
48377
|
+
steps: external_exports.strictObject({ ...accountSteps, profiled: external_exports.boolean() })
|
|
48378
|
+
}).refine(
|
|
48379
|
+
(value) => !value.steps.created || value.address !== void 0,
|
|
48380
|
+
"Created accounts require an address."
|
|
48381
|
+
);
|
|
48382
|
+
var swarmFileSchema = external_exports.strictObject({
|
|
48383
|
+
v: external_exports.literal(1),
|
|
48384
|
+
name: external_exports.string().regex(SWARM_NAME_PATTERN),
|
|
48385
|
+
device: external_exports.string().regex(DEVICE_NAME_PATTERN),
|
|
48386
|
+
network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
|
|
48387
|
+
createdAt: external_exports.iso.datetime(),
|
|
48388
|
+
treasury: treasurySchema,
|
|
48389
|
+
members: external_exports.array(memberSchema),
|
|
48390
|
+
setupFunding: setupFundingSchema.optional(),
|
|
48391
|
+
policy: external_exports.strictObject({
|
|
48392
|
+
strategy: external_exports.enum(["targets", "even", "weights"]),
|
|
48393
|
+
treasuryCaps: capsSchema
|
|
48394
|
+
})
|
|
48395
|
+
}).refine(
|
|
48396
|
+
(value) => (/* @__PURE__ */ new Set([value.treasury.account, ...value.members.map((member) => member.account)])).size === value.members.length + 1,
|
|
48397
|
+
"Swarm accounts must be unique."
|
|
48398
|
+
);
|
|
48399
|
+
var SwarmError = class extends Error {
|
|
48400
|
+
constructor(code, message) {
|
|
48401
|
+
super(message);
|
|
48402
|
+
this.code = code;
|
|
48403
|
+
this.name = "SwarmError";
|
|
48404
|
+
}
|
|
48405
|
+
code;
|
|
48406
|
+
};
|
|
48407
|
+
function swarmsDirectory(home) {
|
|
48408
|
+
return join7(home, "swarms");
|
|
48409
|
+
}
|
|
48410
|
+
function swarmFilePath(home, name) {
|
|
48411
|
+
assertName(name);
|
|
48412
|
+
return join7(swarmsDirectory(home), `${name}.json`);
|
|
48413
|
+
}
|
|
48414
|
+
async function readSwarm(home, name) {
|
|
48415
|
+
const path = swarmFilePath(home, name);
|
|
48416
|
+
try {
|
|
48417
|
+
const swarm = parseSwarm(JSON.parse(await readFile8(path, "utf8")));
|
|
48418
|
+
if (swarm.name !== name)
|
|
48419
|
+
throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
|
|
48420
|
+
return swarm;
|
|
48421
|
+
} catch (error61) {
|
|
48422
|
+
if (isMissingFile(error61)) throw new SwarmError("swarm_not_found", `No swarm named ${name}.`);
|
|
48423
|
+
if (error61 instanceof SwarmError) throw error61;
|
|
48424
|
+
throw new SwarmError("invalid_swarm", `Invalid swarm file for ${name}.`);
|
|
48425
|
+
}
|
|
48426
|
+
}
|
|
48427
|
+
async function listSwarms(home) {
|
|
48428
|
+
let files;
|
|
48429
|
+
try {
|
|
48430
|
+
files = await readdir4(swarmsDirectory(home));
|
|
48431
|
+
} catch (error61) {
|
|
48432
|
+
if (isMissingFile(error61)) return [];
|
|
48433
|
+
throw error61;
|
|
48434
|
+
}
|
|
48435
|
+
return await Promise.all(
|
|
48436
|
+
files.filter((file2) => file2.endsWith(".json")).sort().map((file2) => readSwarm(home, file2.slice(0, -5)))
|
|
48437
|
+
);
|
|
48438
|
+
}
|
|
48439
|
+
function parseSwarm(value) {
|
|
48440
|
+
const result = swarmFileSchema.safeParse(value);
|
|
48441
|
+
if (!result.success) throw new SwarmError("invalid_swarm", "Invalid swarm state.");
|
|
48442
|
+
return result.data;
|
|
48443
|
+
}
|
|
48444
|
+
function assertName(name) {
|
|
48445
|
+
if (!SWARM_NAME_PATTERN.test(name))
|
|
48446
|
+
throw new SwarmError(
|
|
48447
|
+
"invalid_swarm",
|
|
48448
|
+
"A swarm name must be 1 to 16 lowercase letters, digits or dashes, starting with a letter."
|
|
48449
|
+
);
|
|
48450
|
+
}
|
|
48451
|
+
|
|
46905
48452
|
// src/backup.ts
|
|
46906
48453
|
var ERROR_MESSAGES = {
|
|
46907
48454
|
backup_too_large: "Backup envelope exceeds 65,536 bytes.",
|
|
@@ -46910,6 +48457,7 @@ var ERROR_MESSAGES = {
|
|
|
46910
48457
|
unsupported_signature: "Unsupported signature.",
|
|
46911
48458
|
weak_password: "Password must contain at least 12 characters.",
|
|
46912
48459
|
backup_invalid_input: "Invalid backup input.",
|
|
48460
|
+
backup_snapshot_busy: "Backup files changed while they were being captured. Retry the backup; no backup was created or uploaded.",
|
|
46913
48461
|
relay_open_failed: "Unable to open relay payload.",
|
|
46914
48462
|
relay_invalid_key: "Invalid relay key.",
|
|
46915
48463
|
vault_exists: "A vault already exists."
|
|
@@ -46931,6 +48479,15 @@ var SCRYPT_N2 = 131072;
|
|
|
46931
48479
|
var SCRYPT_R2 = 8;
|
|
46932
48480
|
var SCRYPT_P2 = 1;
|
|
46933
48481
|
var SCRYPT_MAXMEM = 256 * 1024 * 1024;
|
|
48482
|
+
var RESTORE_MARKER_FILE = ".backup-restore.json";
|
|
48483
|
+
var restoreDigestSchema = external_exports.string().regex(/^[0-9a-f]{64}$/u);
|
|
48484
|
+
var restoreMarkerSchema = external_exports.strictObject({
|
|
48485
|
+
v: external_exports.literal(1),
|
|
48486
|
+
fingerprint: restoreDigestSchema,
|
|
48487
|
+
vaultSha256: restoreDigestSchema,
|
|
48488
|
+
registrySha256: restoreDigestSchema,
|
|
48489
|
+
mac: restoreDigestSchema
|
|
48490
|
+
});
|
|
46934
48491
|
var SECP256K1_ORDER = BigInt(
|
|
46935
48492
|
"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
|
|
46936
48493
|
);
|
|
@@ -46950,7 +48507,7 @@ var X25519_PRIVATE_DER_PREFIX = Buffer.from("302e020100300506032b656e04220420",
|
|
|
46950
48507
|
var X25519_PUBLIC_DER_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
|
|
46951
48508
|
var CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
46952
48509
|
var isoUtcMillisecondsSchema = external_exports.string().refine(isIsoUtcMilliseconds);
|
|
46953
|
-
var
|
|
48510
|
+
var addressSchema3 = external_exports.custom(
|
|
46954
48511
|
(value) => typeof value === "string" && ADDRESS_PATTERN2.test(value)
|
|
46955
48512
|
);
|
|
46956
48513
|
var privateKeySchema = external_exports.custom(
|
|
@@ -46959,7 +48516,7 @@ var privateKeySchema = external_exports.custom(
|
|
|
46959
48516
|
var safeNonnegativeIntegerSchema = external_exports.number().int().nonnegative().refine(Number.isSafeInteger);
|
|
46960
48517
|
var accountFields2 = {
|
|
46961
48518
|
name: walletNameSchema,
|
|
46962
|
-
address:
|
|
48519
|
+
address: addressSchema3,
|
|
46963
48520
|
createdAt: isoUtcMillisecondsSchema
|
|
46964
48521
|
};
|
|
46965
48522
|
var backupAccountSchema = external_exports.discriminatedUnion("kind", [
|
|
@@ -46983,26 +48540,189 @@ var backupRegistryAccountSchema = external_exports.object({
|
|
|
46983
48540
|
label: external_exports.string().optional(),
|
|
46984
48541
|
spendCaps: spendCapsSchema.strict()
|
|
46985
48542
|
}).strict();
|
|
46986
|
-
var
|
|
48543
|
+
var backupRegistryV1Schema = external_exports.object({
|
|
46987
48544
|
default: walletNameSchema.optional(),
|
|
46988
48545
|
accounts: external_exports.array(backupRegistryAccountSchema),
|
|
46989
48546
|
networks: external_exports.array(external_exports.string().regex(CAIP2_PATTERN))
|
|
46990
48547
|
}).strict();
|
|
46991
|
-
var
|
|
48548
|
+
var routerRefillSchema2 = external_exports.strictObject({
|
|
48549
|
+
belowUsd: external_exports.number().finite().min(0),
|
|
48550
|
+
tierUsd: external_exports.union([external_exports.literal(1), external_exports.literal(5), external_exports.literal(20), external_exports.literal(50)])
|
|
48551
|
+
});
|
|
48552
|
+
var backupRegistryAccountV2Schema = external_exports.strictObject({
|
|
48553
|
+
name: walletNameSchema,
|
|
48554
|
+
label: external_exports.string().optional(),
|
|
48555
|
+
spendCaps: spendCapsSchema.strict(),
|
|
48556
|
+
ceilingAtomic: external_exports.string().regex(/^\d+$/u).nullable().optional(),
|
|
48557
|
+
routerRefill: routerRefillSchema2.optional()
|
|
48558
|
+
});
|
|
48559
|
+
var backupRegistryV2Schema = external_exports.strictObject({
|
|
48560
|
+
default: walletNameSchema.optional(),
|
|
48561
|
+
accounts: external_exports.array(backupRegistryAccountV2Schema),
|
|
48562
|
+
networks: external_exports.array(external_exports.string().regex(CAIP2_PATTERN))
|
|
48563
|
+
});
|
|
48564
|
+
var backupAgentProfileSchema = external_exports.strictObject({
|
|
48565
|
+
version: external_exports.literal(1),
|
|
48566
|
+
name: walletNameSchema,
|
|
48567
|
+
wallet: external_exports.string(),
|
|
48568
|
+
model: external_exports.string().min(1),
|
|
48569
|
+
instructions: external_exports.string().max(2e4),
|
|
48570
|
+
verifiedOnly: external_exports.boolean(),
|
|
48571
|
+
approveAboveUsd: external_exports.number().min(0),
|
|
48572
|
+
maxSteps: external_exports.number().int().min(1).max(50),
|
|
48573
|
+
paused: external_exports.boolean(),
|
|
48574
|
+
createdAt: external_exports.string(),
|
|
48575
|
+
tools: external_exports.array(external_exports.string().min(1)),
|
|
48576
|
+
grants: external_exports.array(external_exports.enum(["read", "delegate", "allocate"])).min(1).optional()
|
|
48577
|
+
});
|
|
48578
|
+
var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
|
|
48579
|
+
var movementNonceSchema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u);
|
|
48580
|
+
var movementAmountSchema = external_exports.string().regex(/^\d+\.\d{2}$/u);
|
|
48581
|
+
var movementStatusSchema = external_exports.enum(["planned", "sent", "failed", "unknown"]);
|
|
48582
|
+
var movementV2StatusSchema = external_exports.enum(["planned", "sent", "failed", "unknown", "cancelled"]);
|
|
48583
|
+
var movementOptionalFields = {
|
|
48584
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u).optional(),
|
|
48585
|
+
reason: external_exports.string().min(1).optional(),
|
|
48586
|
+
retryable: external_exports.boolean().optional()
|
|
48587
|
+
};
|
|
48588
|
+
var backupMovementV1Schema = external_exports.strictObject({
|
|
48589
|
+
v: external_exports.literal(1),
|
|
48590
|
+
id: movementIdSchema3,
|
|
48591
|
+
reason: external_exports.literal("distribute"),
|
|
48592
|
+
from: walletNameSchema,
|
|
48593
|
+
network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
|
|
48594
|
+
createdAt: external_exports.iso.datetime(),
|
|
48595
|
+
legs: external_exports.array(
|
|
48596
|
+
external_exports.strictObject({
|
|
48597
|
+
to: external_exports.string().trim().min(1),
|
|
48598
|
+
amountUsd: movementAmountSchema,
|
|
48599
|
+
nonce: movementNonceSchema,
|
|
48600
|
+
status: movementStatusSchema,
|
|
48601
|
+
...movementOptionalFields
|
|
48602
|
+
})
|
|
48603
|
+
).min(1)
|
|
48604
|
+
});
|
|
48605
|
+
var backupMovementV2Schema = external_exports.strictObject({
|
|
48606
|
+
v: external_exports.literal(2),
|
|
48607
|
+
id: movementIdSchema3,
|
|
48608
|
+
reason: external_exports.enum(["distribute", "allocate", "rebalance", "delegate", "sweep", "send"]),
|
|
48609
|
+
from: walletNameSchema,
|
|
48610
|
+
treasury: walletNameSchema.optional(),
|
|
48611
|
+
network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
|
|
48612
|
+
createdAt: external_exports.iso.datetime(),
|
|
48613
|
+
legs: external_exports.array(
|
|
48614
|
+
external_exports.strictObject({
|
|
48615
|
+
from: walletNameSchema,
|
|
48616
|
+
to: external_exports.string().trim().min(1),
|
|
48617
|
+
amountUsd: movementAmountSchema,
|
|
48618
|
+
purpose: external_exports.enum(["send", "sweep"]),
|
|
48619
|
+
nonce: movementNonceSchema,
|
|
48620
|
+
status: movementV2StatusSchema,
|
|
48621
|
+
...movementOptionalFields
|
|
48622
|
+
})
|
|
48623
|
+
).min(1)
|
|
48624
|
+
});
|
|
48625
|
+
var backupMovementSchema = external_exports.discriminatedUnion("v", [
|
|
48626
|
+
backupMovementV1Schema,
|
|
48627
|
+
backupMovementV2Schema
|
|
48628
|
+
]);
|
|
48629
|
+
var backupTransferRequestSchema = external_exports.strictObject({
|
|
48630
|
+
authorization: external_exports.strictObject({
|
|
48631
|
+
from: addressSchema3,
|
|
48632
|
+
to: addressSchema3,
|
|
48633
|
+
value: external_exports.string().regex(/^\d+$/u),
|
|
48634
|
+
validAfter: external_exports.string().regex(/^\d+$/u),
|
|
48635
|
+
validBefore: external_exports.string().regex(/^\d+$/u),
|
|
48636
|
+
nonce: movementNonceSchema
|
|
48637
|
+
}),
|
|
48638
|
+
signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u)
|
|
48639
|
+
});
|
|
48640
|
+
var backupTransferSchema = external_exports.strictObject({
|
|
48641
|
+
to: addressSchema3,
|
|
48642
|
+
toName: external_exports.string().min(1),
|
|
48643
|
+
toKind: external_exports.enum(["owner", "account"]),
|
|
48644
|
+
amountAtomic: external_exports.string().regex(/^\d+$/u),
|
|
48645
|
+
network: external_exports.string().min(1),
|
|
48646
|
+
nonce: movementNonceSchema,
|
|
48647
|
+
status: external_exports.enum(["sent", "unknown", "failed"]),
|
|
48648
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u).nullable(),
|
|
48649
|
+
replayed: external_exports.boolean(),
|
|
48650
|
+
reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u).optional(),
|
|
48651
|
+
request: backupTransferRequestSchema.optional()
|
|
48652
|
+
});
|
|
48653
|
+
var backupTransferReceiptSchema = external_exports.strictObject({
|
|
48654
|
+
id: external_exports.string().min(1),
|
|
48655
|
+
timestamp: external_exports.iso.datetime(),
|
|
48656
|
+
kind: external_exports.literal("transfer"),
|
|
48657
|
+
wallet: walletNameSchema,
|
|
48658
|
+
resourceUrl: external_exports.url(),
|
|
48659
|
+
quote: external_exports.strictObject({
|
|
48660
|
+
network: external_exports.string().min(1),
|
|
48661
|
+
asset: external_exports.string().min(1),
|
|
48662
|
+
amountAtomic: external_exports.string().regex(/^\d+$/u)
|
|
48663
|
+
}),
|
|
48664
|
+
transfer: backupTransferSchema,
|
|
48665
|
+
error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional()
|
|
48666
|
+
}).superRefine((receipt, context) => {
|
|
48667
|
+
try {
|
|
48668
|
+
parseReceipt(receipt);
|
|
48669
|
+
} catch {
|
|
48670
|
+
context.addIssue({ code: "custom", message: "Invalid transfer receipt." });
|
|
48671
|
+
}
|
|
48672
|
+
});
|
|
48673
|
+
var backupSourceV1Schema = external_exports.object({
|
|
46992
48674
|
phrase: external_exports.string().min(1),
|
|
46993
48675
|
nextDerivedIndex: safeNonnegativeIntegerSchema,
|
|
46994
48676
|
accounts: external_exports.array(backupAccountSchema),
|
|
46995
|
-
registry:
|
|
48677
|
+
registry: backupRegistryV1Schema,
|
|
46996
48678
|
protected: external_exports.boolean()
|
|
46997
48679
|
}).strict().superRefine(validateBackupSourceRelationships);
|
|
46998
|
-
var
|
|
48680
|
+
var backupSourceV2Schema = external_exports.strictObject({
|
|
48681
|
+
phrase: external_exports.string().min(1),
|
|
48682
|
+
nextDerivedIndex: safeNonnegativeIntegerSchema,
|
|
48683
|
+
accounts: external_exports.array(backupAccountSchema),
|
|
48684
|
+
registry: backupRegistryV2Schema,
|
|
48685
|
+
protected: external_exports.boolean(),
|
|
48686
|
+
agents: external_exports.array(backupAgentProfileSchema),
|
|
48687
|
+
swarms: external_exports.array(swarmFileSchema),
|
|
48688
|
+
movements: external_exports.array(backupMovementSchema),
|
|
48689
|
+
transferReceipts: external_exports.array(backupTransferReceiptSchema),
|
|
48690
|
+
skipped: external_exports.array(
|
|
48691
|
+
external_exports.strictObject({
|
|
48692
|
+
kind: external_exports.literal("agent"),
|
|
48693
|
+
name: external_exports.string().min(1),
|
|
48694
|
+
reason: external_exports.literal("invalid_profile")
|
|
48695
|
+
})
|
|
48696
|
+
).optional()
|
|
48697
|
+
}).superRefine((source, context) => {
|
|
48698
|
+
validateBackupSourceRelationships(source, context);
|
|
48699
|
+
validateBackupV2Uniqueness(source, context);
|
|
48700
|
+
});
|
|
48701
|
+
var backupSourceSchema = external_exports.union([backupSourceV1Schema, backupSourceV2Schema]);
|
|
48702
|
+
var backupPlaintextV1Schema = external_exports.strictObject({
|
|
46999
48703
|
v: external_exports.literal(1),
|
|
47000
48704
|
phrase: external_exports.string().min(1),
|
|
47001
48705
|
nextDerivedIndex: safeNonnegativeIntegerSchema,
|
|
47002
48706
|
accounts: external_exports.array(backupAccountSchema),
|
|
47003
|
-
registry:
|
|
48707
|
+
registry: backupRegistryV1Schema,
|
|
47004
48708
|
protected: external_exports.boolean()
|
|
47005
|
-
})
|
|
48709
|
+
});
|
|
48710
|
+
var backupPlaintextV2Schema = external_exports.strictObject({
|
|
48711
|
+
v: external_exports.literal(2),
|
|
48712
|
+
phrase: external_exports.string().min(1),
|
|
48713
|
+
nextDerivedIndex: safeNonnegativeIntegerSchema,
|
|
48714
|
+
accounts: external_exports.array(backupAccountSchema),
|
|
48715
|
+
registry: backupRegistryV2Schema,
|
|
48716
|
+
protected: external_exports.boolean(),
|
|
48717
|
+
agents: external_exports.array(backupAgentProfileSchema).optional(),
|
|
48718
|
+
swarms: external_exports.array(swarmFileSchema).optional(),
|
|
48719
|
+
movements: external_exports.array(backupMovementSchema).optional(),
|
|
48720
|
+
transferReceipts: external_exports.array(backupTransferReceiptSchema).optional()
|
|
48721
|
+
});
|
|
48722
|
+
var backupPlaintextSchema = external_exports.discriminatedUnion("v", [backupPlaintextV1Schema, backupPlaintextV2Schema]).superRefine((plaintext, context) => {
|
|
48723
|
+
validateBackupSourceRelationships(plaintext, context);
|
|
48724
|
+
if (plaintext.v === 2) validateBackupV2Uniqueness(plaintext, context);
|
|
48725
|
+
});
|
|
47006
48726
|
async function createBackup(options) {
|
|
47007
48727
|
const parsed = backupSourceSchema.safeParse(options.vault);
|
|
47008
48728
|
if (!parsed.success) throw new BackupError("backup_invalid_input");
|
|
@@ -47010,8 +48730,8 @@ async function createBackup(options) {
|
|
|
47010
48730
|
assertDevice(options.device);
|
|
47011
48731
|
assertOwnerKey(options.ownerKey);
|
|
47012
48732
|
const createdAt = readCreatedAt(options.now ?? (() => /* @__PURE__ */ new Date()));
|
|
47013
|
-
const
|
|
47014
|
-
const nonce = readRandomBytes(
|
|
48733
|
+
const randomBytes7 = options.randomBytes ?? cryptoRandomBytes2;
|
|
48734
|
+
const nonce = readRandomBytes(randomBytes7, 12);
|
|
47015
48735
|
const salt = encodeBase64Url(options.ownerKey.salt);
|
|
47016
48736
|
const kdf = options.ownerKey.kdf === "hkdf-sha256" ? { name: "hkdf-sha256", salt } : { name: "scrypt", salt, N: SCRYPT_N2, r: SCRYPT_R2, p: SCRYPT_P2 };
|
|
47017
48737
|
const cipher = { name: CIPHER_NAME, nonce: encodeBase64Url(nonce) };
|
|
@@ -47024,30 +48744,54 @@ async function createBackup(options) {
|
|
|
47024
48744
|
kdf,
|
|
47025
48745
|
cipher
|
|
47026
48746
|
};
|
|
47027
|
-
const plaintextValue = buildPlaintext(parsed.data);
|
|
47028
|
-
const plaintext = Buffer.from(JSON.stringify(plaintextValue), "utf8");
|
|
47029
48747
|
const key = Buffer.from(options.ownerKey.key);
|
|
47030
|
-
let encrypted;
|
|
47031
48748
|
try {
|
|
47032
|
-
|
|
47033
|
-
const
|
|
47034
|
-
|
|
47035
|
-
|
|
47036
|
-
|
|
47037
|
-
|
|
47038
|
-
|
|
47039
|
-
|
|
47040
|
-
|
|
47041
|
-
|
|
47042
|
-
|
|
47043
|
-
|
|
47044
|
-
|
|
47045
|
-
|
|
48749
|
+
const candidates = backupCandidates(parsed.data);
|
|
48750
|
+
for (const candidate of candidates) {
|
|
48751
|
+
const plaintext = Buffer.from(JSON.stringify(candidate.plaintext), "utf8");
|
|
48752
|
+
let encrypted;
|
|
48753
|
+
try {
|
|
48754
|
+
encrypted = encryptAesGcm(
|
|
48755
|
+
key,
|
|
48756
|
+
nonce,
|
|
48757
|
+
plaintext,
|
|
48758
|
+
Buffer.from(buildBackupAad(header), "utf8")
|
|
48759
|
+
);
|
|
48760
|
+
const envelope = JSON.stringify({
|
|
48761
|
+
format: header.format,
|
|
48762
|
+
v: header.v,
|
|
48763
|
+
owner: header.owner,
|
|
48764
|
+
device: header.device,
|
|
48765
|
+
createdAt: header.createdAt,
|
|
48766
|
+
kdf: header.kdf,
|
|
48767
|
+
cipher: header.cipher,
|
|
48768
|
+
ciphertext: encodeBase64Url(encrypted)
|
|
48769
|
+
});
|
|
48770
|
+
const bytes = Buffer.byteLength(envelope, "utf8");
|
|
48771
|
+
const relayPayload = buildRelayRestorePayload({
|
|
48772
|
+
owner,
|
|
48773
|
+
device: "d".repeat(32),
|
|
48774
|
+
kdf,
|
|
48775
|
+
key: Buffer.alloc(32),
|
|
48776
|
+
vault: candidate.plaintext
|
|
48777
|
+
});
|
|
48778
|
+
const relayBytes = Buffer.byteLength(relayPayload, "utf8");
|
|
48779
|
+
if (bytes <= MAX_BACKUP_BYTES && relayBytes <= RELAY_PLAINTEXT_LIMIT) {
|
|
48780
|
+
return {
|
|
48781
|
+
envelope,
|
|
48782
|
+
bytes,
|
|
48783
|
+
...candidate.omitted.length === 0 ? {} : { omitted: candidate.omitted }
|
|
48784
|
+
};
|
|
48785
|
+
}
|
|
48786
|
+
} finally {
|
|
48787
|
+
plaintext.fill(0);
|
|
48788
|
+
encrypted?.fill(0);
|
|
48789
|
+
}
|
|
48790
|
+
}
|
|
48791
|
+
throw new BackupError("backup_too_large");
|
|
47046
48792
|
} finally {
|
|
47047
|
-
plaintext.fill(0);
|
|
47048
48793
|
key.fill(0);
|
|
47049
48794
|
nonce.fill(0);
|
|
47050
|
-
encrypted?.fill(0);
|
|
47051
48795
|
}
|
|
47052
48796
|
}
|
|
47053
48797
|
function createRelayKeyPair(options = {}) {
|
|
@@ -47070,7 +48814,7 @@ function createRelayKeyPair(options = {}) {
|
|
|
47070
48814
|
}
|
|
47071
48815
|
function relayCode(publicKey) {
|
|
47072
48816
|
assertRelayKey(publicKey);
|
|
47073
|
-
const digest =
|
|
48817
|
+
const digest = createHash2("sha256").update(publicKey).digest();
|
|
47074
48818
|
try {
|
|
47075
48819
|
let bits = BigInt(`0x${digest.subarray(0, 8).toString("hex")}`) >> 4n;
|
|
47076
48820
|
const characters = Array.from({ length: 12 }, () => "0");
|
|
@@ -47134,69 +48878,173 @@ function openSealed(options) {
|
|
|
47134
48878
|
plaintext?.fill(0);
|
|
47135
48879
|
}
|
|
47136
48880
|
}
|
|
48881
|
+
function buildRelayRestorePayload(options) {
|
|
48882
|
+
try {
|
|
48883
|
+
const owner = normalizedOwner(options.owner);
|
|
48884
|
+
assertDevice(options.device);
|
|
48885
|
+
assertBytes(options.key, 32);
|
|
48886
|
+
if (!isRecord2(options.kdf)) throw new Error();
|
|
48887
|
+
const kdf = parseKdf(options.kdf);
|
|
48888
|
+
const parsed = backupPlaintextSchema.safeParse(options.vault);
|
|
48889
|
+
if (!parsed.success) throw new Error();
|
|
48890
|
+
const vault = parsed.data.v === 1 ? buildPlaintextV1(parsed.data) : buildPlaintextV2(parsed.data);
|
|
48891
|
+
return JSON.stringify({
|
|
48892
|
+
format: "vapi-vault-relay-payload",
|
|
48893
|
+
v: 1,
|
|
48894
|
+
purpose: "restore",
|
|
48895
|
+
owner,
|
|
48896
|
+
device: options.device,
|
|
48897
|
+
kdf,
|
|
48898
|
+
key: encodeBase64Url(options.key),
|
|
48899
|
+
vault
|
|
48900
|
+
});
|
|
48901
|
+
} catch {
|
|
48902
|
+
throw new BackupError("backup_invalid_input");
|
|
48903
|
+
}
|
|
48904
|
+
}
|
|
47137
48905
|
async function exportBackupSource(options) {
|
|
47138
48906
|
try {
|
|
47139
48907
|
assertBytes(options.vaultKey, 32);
|
|
47140
|
-
if (!
|
|
48908
|
+
if (!isRecord2(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
|
|
47141
48909
|
throw new BackupError("backup_invalid_input");
|
|
47142
48910
|
}
|
|
47143
48911
|
const networks = normalizeNetworks(options.networks ?? []);
|
|
47144
|
-
|
|
47145
|
-
|
|
47146
|
-
|
|
47147
|
-
|
|
47148
|
-
|
|
47149
|
-
readVaultFileUnlocked(path)
|
|
47150
|
-
]);
|
|
47151
|
-
const accounts2 = [];
|
|
47152
|
-
for (const account of vault.accounts()) {
|
|
47153
|
-
if (account.kind === "derived") {
|
|
47154
|
-
accounts2.push({ ...account });
|
|
47155
|
-
} else {
|
|
47156
|
-
const privateKey = await exportVaultAccountKey({
|
|
47157
|
-
path,
|
|
47158
|
-
key: options.vaultKey,
|
|
47159
|
-
name: account.name
|
|
47160
|
-
});
|
|
47161
|
-
accounts2.push({ ...account, privateKey });
|
|
47162
|
-
}
|
|
48912
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
48913
|
+
try {
|
|
48914
|
+
return await exportBackupSourceAttempt(options, networks);
|
|
48915
|
+
} catch (error61) {
|
|
48916
|
+
if (!(error61 instanceof BackupSnapshotChangedError)) throw error61;
|
|
47163
48917
|
}
|
|
47164
|
-
return { phrase: phrase2, file: file3, accounts: accounts2 };
|
|
47165
|
-
});
|
|
47166
|
-
const snapshot = await options.store.reload();
|
|
47167
|
-
const names = new Set(accounts.map((account) => account.name));
|
|
47168
|
-
const source = {
|
|
47169
|
-
phrase,
|
|
47170
|
-
nextDerivedIndex: file2.nextDerivedIndex ?? accounts.reduce(
|
|
47171
|
-
(next, account) => account.kind === "derived" ? Math.max(next, account.index + 1) : next,
|
|
47172
|
-
0
|
|
47173
|
-
),
|
|
47174
|
-
accounts,
|
|
47175
|
-
registry: {
|
|
47176
|
-
...snapshot.default !== void 0 && names.has(snapshot.default) ? { default: snapshot.default } : {},
|
|
47177
|
-
accounts: accounts.map((account) => {
|
|
47178
|
-
const entry = snapshot.wallets[account.name];
|
|
47179
|
-
return {
|
|
47180
|
-
name: account.name,
|
|
47181
|
-
...entry?.label === void 0 ? {} : { label: entry.label },
|
|
47182
|
-
spendCaps: {
|
|
47183
|
-
perCallAtomic: entry?.spendCaps.perCallAtomic ?? DEFAULT_SPEND_CAPS.perCallAtomic,
|
|
47184
|
-
perDayAtomic: entry?.spendCaps.perDayAtomic ?? DEFAULT_SPEND_CAPS.perDayAtomic
|
|
47185
|
-
}
|
|
47186
|
-
};
|
|
47187
|
-
}),
|
|
47188
|
-
networks
|
|
47189
|
-
},
|
|
47190
|
-
protected: file2.protected
|
|
47191
|
-
};
|
|
47192
|
-
if (!backupSourceSchema.safeParse(source).success) {
|
|
47193
|
-
throw new BackupError("backup_invalid_input");
|
|
47194
48918
|
}
|
|
47195
|
-
|
|
47196
|
-
} catch {
|
|
48919
|
+
throw new BackupError("backup_snapshot_busy");
|
|
48920
|
+
} catch (error61) {
|
|
48921
|
+
if (error61 instanceof BackupError && error61.code === "backup_snapshot_busy") throw error61;
|
|
47197
48922
|
throw new BackupError("backup_invalid_input");
|
|
47198
48923
|
}
|
|
47199
48924
|
}
|
|
48925
|
+
var BackupSnapshotChangedError = class extends Error {
|
|
48926
|
+
};
|
|
48927
|
+
async function exportBackupSourceAttempt(options, networks) {
|
|
48928
|
+
const path = join8(options.store.home, "vault.json");
|
|
48929
|
+
const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
|
|
48930
|
+
const [phrase2, vault, file3] = await Promise.all([
|
|
48931
|
+
exportVaultPhrase({ path, key: options.vaultKey }),
|
|
48932
|
+
openVault({ path, key: options.vaultKey }),
|
|
48933
|
+
readVaultFileUnlocked(path)
|
|
48934
|
+
]);
|
|
48935
|
+
const accounts2 = [];
|
|
48936
|
+
for (const account of vault.accounts()) {
|
|
48937
|
+
if (account.kind === "derived") {
|
|
48938
|
+
accounts2.push({ ...account });
|
|
48939
|
+
} else {
|
|
48940
|
+
const privateKey = await exportVaultAccountKey({
|
|
48941
|
+
path,
|
|
48942
|
+
key: options.vaultKey,
|
|
48943
|
+
name: account.name
|
|
48944
|
+
});
|
|
48945
|
+
accounts2.push({ ...account, privateKey });
|
|
48946
|
+
}
|
|
48947
|
+
}
|
|
48948
|
+
return { phrase: phrase2, file: file3, accounts: accounts2 };
|
|
48949
|
+
});
|
|
48950
|
+
const snapshot = await options.store.reload();
|
|
48951
|
+
const names = new Set(accounts.map((account) => account.name));
|
|
48952
|
+
const home = options.store.home;
|
|
48953
|
+
const skipped = [];
|
|
48954
|
+
const [agents, swarms, movementSnapshots] = await Promise.all([
|
|
48955
|
+
listAgentProfiles(home, {
|
|
48956
|
+
schema: options.agentProfileSchema ?? agentProfileSchema,
|
|
48957
|
+
warn: () => void 0,
|
|
48958
|
+
onInvalid: (profileFile) => {
|
|
48959
|
+
skipped.push({
|
|
48960
|
+
kind: "agent",
|
|
48961
|
+
name: profileFile.endsWith(".json") ? profileFile.slice(0, -5) : profileFile,
|
|
48962
|
+
reason: "invalid_profile"
|
|
48963
|
+
});
|
|
48964
|
+
}
|
|
48965
|
+
}),
|
|
48966
|
+
listSwarms(home),
|
|
48967
|
+
listUnfinishedMovementSnapshots({ home })
|
|
48968
|
+
]);
|
|
48969
|
+
const localMovements = await Promise.all(
|
|
48970
|
+
movementSnapshots.map(async ({ summary }) => await readMovement(home, summary.id))
|
|
48971
|
+
);
|
|
48972
|
+
localMovements.sort(compareMovements);
|
|
48973
|
+
const expectedSignedFailedLegs = movementSnapshots.flatMap(
|
|
48974
|
+
({ signedFailedLegKeys }) => signedFailedLegKeys
|
|
48975
|
+
);
|
|
48976
|
+
const receipts = await readReceiptJournal(getVapiPaths(home).receipts);
|
|
48977
|
+
const receiptLegs = new Set(
|
|
48978
|
+
receipts.flatMap(
|
|
48979
|
+
(receipt) => receipt.kind === "transfer" && receipt.transfer !== void 0 ? [movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce)] : []
|
|
48980
|
+
)
|
|
48981
|
+
);
|
|
48982
|
+
const requiredReceiptLegs = /* @__PURE__ */ new Set([
|
|
48983
|
+
...expectedSignedFailedLegs,
|
|
48984
|
+
...localMovements.flatMap(
|
|
48985
|
+
(movement) => movement.legs.filter((leg) => leg.status === "unknown").map((leg) => movementTransferKey(leg.from, leg.nonce))
|
|
48986
|
+
)
|
|
48987
|
+
]);
|
|
48988
|
+
const verifiedFile = await readVaultFileUnlocked(path);
|
|
48989
|
+
const verifiedSnapshot = await options.store.reload();
|
|
48990
|
+
if ([...requiredReceiptLegs].some((leg) => !receiptLegs.has(leg)) || JSON.stringify(file2) !== JSON.stringify(verifiedFile) || JSON.stringify(snapshot) !== JSON.stringify(verifiedSnapshot)) {
|
|
48991
|
+
throw new BackupSnapshotChangedError();
|
|
48992
|
+
}
|
|
48993
|
+
const movements = localMovements.map(toBackupMovement);
|
|
48994
|
+
const includedLegs = new Set(
|
|
48995
|
+
localMovements.flatMap(
|
|
48996
|
+
(movement) => movement.legs.map((leg) => movementTransferKey(leg.from, leg.nonce))
|
|
48997
|
+
)
|
|
48998
|
+
);
|
|
48999
|
+
const transferReceipts = receipts.filter(
|
|
49000
|
+
(receipt) => receipt.kind === "transfer" && receipt.transfer !== void 0 && includedLegs.has(movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce))
|
|
49001
|
+
).map(toBackupTransferReceipt);
|
|
49002
|
+
const source = {
|
|
49003
|
+
phrase,
|
|
49004
|
+
nextDerivedIndex: file2.nextDerivedIndex ?? accounts.reduce(
|
|
49005
|
+
(next, account) => account.kind === "derived" ? Math.max(next, account.index + 1) : next,
|
|
49006
|
+
0
|
|
49007
|
+
),
|
|
49008
|
+
accounts,
|
|
49009
|
+
registry: {
|
|
49010
|
+
...snapshot.default !== void 0 && names.has(snapshot.default) ? { default: snapshot.default } : {},
|
|
49011
|
+
accounts: accounts.map((account) => {
|
|
49012
|
+
const entry = snapshot.wallets[account.name];
|
|
49013
|
+
const ceilingAtomic = entry?.ceilingAtomic === null ? null : entry?.ceilingAtomic ?? DEFAULT_CEILING_ATOMIC.toString();
|
|
49014
|
+
return {
|
|
49015
|
+
name: account.name,
|
|
49016
|
+
...entry?.label === void 0 ? {} : { label: entry.label },
|
|
49017
|
+
spendCaps: {
|
|
49018
|
+
perCallAtomic: entry?.spendCaps.perCallAtomic ?? DEFAULT_SPEND_CAPS.perCallAtomic,
|
|
49019
|
+
perDayAtomic: entry?.spendCaps.perDayAtomic ?? DEFAULT_SPEND_CAPS.perDayAtomic
|
|
49020
|
+
},
|
|
49021
|
+
...ceilingAtomic === DEFAULT_CEILING_ATOMIC.toString() ? {} : { ceilingAtomic },
|
|
49022
|
+
...entry?.routerRefill === void 0 ? {} : {
|
|
49023
|
+
routerRefill: {
|
|
49024
|
+
belowUsd: entry.routerRefill.belowUsd,
|
|
49025
|
+
tierUsd: entry.routerRefill.tierUsd
|
|
49026
|
+
}
|
|
49027
|
+
}
|
|
49028
|
+
};
|
|
49029
|
+
}),
|
|
49030
|
+
networks
|
|
49031
|
+
},
|
|
49032
|
+
protected: file2.protected,
|
|
49033
|
+
agents: agents.map(
|
|
49034
|
+
({ grants, ...profile }) => backupAgentProfileSchema.parse(
|
|
49035
|
+
grants === void 0 || grants.length === 0 ? profile : { ...profile, grants }
|
|
49036
|
+
)
|
|
49037
|
+
).sort(compareNamedValues),
|
|
49038
|
+
swarms: [...swarms].sort(compareNamedValues),
|
|
49039
|
+
movements,
|
|
49040
|
+
transferReceipts,
|
|
49041
|
+
...skipped.length === 0 ? {} : { skipped: skipped.sort(compareNamedValues) }
|
|
49042
|
+
};
|
|
49043
|
+
if (!backupSourceSchema.safeParse(source).success) {
|
|
49044
|
+
throw new BackupError("backup_invalid_input");
|
|
49045
|
+
}
|
|
49046
|
+
return source;
|
|
49047
|
+
}
|
|
47200
49048
|
function parseBackupPlaintext(value) {
|
|
47201
49049
|
return validateRestorePlaintext(value);
|
|
47202
49050
|
}
|
|
@@ -47205,20 +49053,24 @@ async function restoreBackupPlaintext(options) {
|
|
|
47205
49053
|
if (typeof options.home !== "string" || options.home.length === 0) {
|
|
47206
49054
|
throw new BackupError("backup_invalid_input");
|
|
47207
49055
|
}
|
|
49056
|
+
if (options.device !== void 0 && !DEVICE_NAME_PATTERN.test(options.device)) {
|
|
49057
|
+
throw new BackupError("backup_invalid_input");
|
|
49058
|
+
}
|
|
47208
49059
|
try {
|
|
47209
49060
|
assertBytes(options.vaultKey, 32);
|
|
47210
49061
|
} catch {
|
|
47211
49062
|
throw new BackupError("backup_invalid_input");
|
|
47212
49063
|
}
|
|
47213
|
-
const vaultPath =
|
|
47214
|
-
const registryPath =
|
|
49064
|
+
const vaultPath = join8(options.home, "vault.json");
|
|
49065
|
+
const registryPath = join8(options.home, "wallets.json");
|
|
47215
49066
|
let stagingHome;
|
|
47216
49067
|
let beforePublishError;
|
|
49068
|
+
let afterPublishError;
|
|
47217
49069
|
try {
|
|
47218
|
-
await
|
|
47219
|
-
stagingHome = await mkdtemp(
|
|
47220
|
-
const stagedVaultPath =
|
|
47221
|
-
const stagedRegistryPath =
|
|
49070
|
+
await mkdir8(options.home, { recursive: true, mode: 448 });
|
|
49071
|
+
stagingHome = await mkdtemp(join8(options.home, ".backup-restore-"));
|
|
49072
|
+
const stagedVaultPath = join8(stagingHome, "vault.json");
|
|
49073
|
+
const stagedRegistryPath = join8(stagingHome, "wallets.json");
|
|
47222
49074
|
await createVault({
|
|
47223
49075
|
path: stagedVaultPath,
|
|
47224
49076
|
key: options.vaultKey,
|
|
@@ -47264,16 +49116,59 @@ async function restoreBackupPlaintext(options) {
|
|
|
47264
49116
|
} finally {
|
|
47265
49117
|
await handle.close();
|
|
47266
49118
|
}
|
|
49119
|
+
const stagedV2 = plaintext.v === 2 ? await stageV2Restore({
|
|
49120
|
+
plaintext,
|
|
49121
|
+
stagingHome,
|
|
49122
|
+
home: options.home,
|
|
49123
|
+
...options.device === void 0 ? {} : { device: options.device }
|
|
49124
|
+
}) : void 0;
|
|
47267
49125
|
const accounts = (await openVault({ path: stagedVaultPath, key: options.vaultKey })).accounts();
|
|
47268
|
-
const
|
|
49126
|
+
const baseResult = {
|
|
47269
49127
|
accounts,
|
|
47270
49128
|
...plaintext.registry.default === void 0 ? {} : { default: plaintext.registry.default },
|
|
47271
49129
|
protected: plaintext.protected,
|
|
47272
49130
|
networks: [...plaintext.registry.networks]
|
|
47273
49131
|
};
|
|
49132
|
+
const markerPath = join8(options.home, RESTORE_MARKER_FILE);
|
|
49133
|
+
const fingerprint = restoreFingerprint(
|
|
49134
|
+
plaintext,
|
|
49135
|
+
stagedV2?.restoreDevice ?? options.device,
|
|
49136
|
+
options.vaultKey
|
|
49137
|
+
);
|
|
47274
49138
|
await withVaultLock(vaultPath, async () => {
|
|
47275
|
-
|
|
47276
|
-
|
|
49139
|
+
const existingVault = await pathExists2(vaultPath);
|
|
49140
|
+
const existingRegistry = await pathExists2(registryPath);
|
|
49141
|
+
let marker;
|
|
49142
|
+
if (existingVault || existingRegistry) {
|
|
49143
|
+
if (!existingVault) throw new BackupError("vault_exists");
|
|
49144
|
+
marker = await readRestoreMarker(markerPath, fingerprint, options.vaultKey);
|
|
49145
|
+
if (await sha256File(vaultPath) !== marker.vaultSha256) {
|
|
49146
|
+
throw new BackupError("vault_exists");
|
|
49147
|
+
}
|
|
49148
|
+
if (existingRegistry) {
|
|
49149
|
+
if (await sha256File(registryPath) !== marker.registrySha256) {
|
|
49150
|
+
throw new BackupError("vault_exists");
|
|
49151
|
+
}
|
|
49152
|
+
} else if (await sha256File(stagedRegistryPath) !== marker.registrySha256) {
|
|
49153
|
+
throw new BackupError("vault_exists");
|
|
49154
|
+
}
|
|
49155
|
+
} else {
|
|
49156
|
+
marker = await createRestoreMarker(
|
|
49157
|
+
stagedVaultPath,
|
|
49158
|
+
stagedRegistryPath,
|
|
49159
|
+
fingerprint,
|
|
49160
|
+
options.vaultKey
|
|
49161
|
+
);
|
|
49162
|
+
await writeJsonAtomic(markerPath, marker, { mode: 384 });
|
|
49163
|
+
await notifyRestorePublish(options.afterPublish, { kind: "marker" }, (error61) => {
|
|
49164
|
+
afterPublishError = error61;
|
|
49165
|
+
});
|
|
49166
|
+
}
|
|
49167
|
+
if (stagedV2 !== void 0) {
|
|
49168
|
+
await publishV2RestoreSafety(stagedV2, options.home);
|
|
49169
|
+
await notifyRestorePublish(options.afterPublish, { kind: "safety" }, (error61) => {
|
|
49170
|
+
afterPublishError = error61;
|
|
49171
|
+
});
|
|
47277
49172
|
}
|
|
47278
49173
|
try {
|
|
47279
49174
|
await options.beforePublish?.({ vault: stagedVaultPath, registry: stagedRegistryPath });
|
|
@@ -47281,21 +49176,66 @@ async function restoreBackupPlaintext(options) {
|
|
|
47281
49176
|
beforePublishError = error61;
|
|
47282
49177
|
throw error61;
|
|
47283
49178
|
}
|
|
49179
|
+
if (!existingVault && !existingRegistry) {
|
|
49180
|
+
const refreshedMarker = await createRestoreMarker(
|
|
49181
|
+
stagedVaultPath,
|
|
49182
|
+
stagedRegistryPath,
|
|
49183
|
+
fingerprint,
|
|
49184
|
+
options.vaultKey
|
|
49185
|
+
);
|
|
49186
|
+
if (refreshedMarker.vaultSha256 !== marker.vaultSha256 || refreshedMarker.registrySha256 !== marker.registrySha256) {
|
|
49187
|
+
marker = refreshedMarker;
|
|
49188
|
+
await writeJsonAtomic(markerPath, marker, { mode: 384 });
|
|
49189
|
+
}
|
|
49190
|
+
}
|
|
47284
49191
|
let publishedVault = false;
|
|
47285
|
-
|
|
47286
|
-
|
|
47287
|
-
|
|
47288
|
-
|
|
47289
|
-
|
|
47290
|
-
|
|
47291
|
-
|
|
49192
|
+
if (!existingVault) {
|
|
49193
|
+
try {
|
|
49194
|
+
await link2(stagedVaultPath, vaultPath);
|
|
49195
|
+
publishedVault = true;
|
|
49196
|
+
} catch (error61) {
|
|
49197
|
+
await rm2(markerPath, { force: true }).catch(() => void 0);
|
|
49198
|
+
throw error61;
|
|
49199
|
+
}
|
|
49200
|
+
await notifyRestorePublish(options.afterPublish, { kind: "vault" }, (error61) => {
|
|
49201
|
+
afterPublishError = error61;
|
|
49202
|
+
});
|
|
49203
|
+
}
|
|
49204
|
+
if (!existingRegistry) {
|
|
49205
|
+
try {
|
|
49206
|
+
await link2(stagedRegistryPath, registryPath);
|
|
49207
|
+
} catch (error61) {
|
|
49208
|
+
if (publishedVault) await rm2(vaultPath, { force: true }).catch(() => void 0);
|
|
49209
|
+
await rm2(markerPath, { force: true }).catch(() => void 0);
|
|
49210
|
+
throw error61;
|
|
49211
|
+
}
|
|
49212
|
+
await notifyRestorePublish(options.afterPublish, { kind: "registry" }, (error61) => {
|
|
49213
|
+
afterPublishError = error61;
|
|
49214
|
+
});
|
|
49215
|
+
}
|
|
49216
|
+
if (stagedV2 !== void 0) {
|
|
49217
|
+
await publishV2Restore(stagedV2, options.home, async (step) => {
|
|
49218
|
+
await notifyRestorePublish(options.afterPublish, step, (error61) => {
|
|
49219
|
+
afterPublishError = error61;
|
|
49220
|
+
});
|
|
49221
|
+
});
|
|
47292
49222
|
}
|
|
49223
|
+
await rm2(markerPath, { force: true });
|
|
47293
49224
|
});
|
|
47294
|
-
return
|
|
49225
|
+
if (stagedV2 === void 0) return baseResult;
|
|
49226
|
+
return {
|
|
49227
|
+
...baseResult,
|
|
49228
|
+
agents: stagedV2.restoredAgents,
|
|
49229
|
+
swarms: stagedV2.restoredSwarms,
|
|
49230
|
+
movements: stagedV2.restoredMovements,
|
|
49231
|
+
skipped: stagedV2.skipped,
|
|
49232
|
+
conflicts: stagedV2.conflicts
|
|
49233
|
+
};
|
|
47295
49234
|
} catch (error61) {
|
|
47296
49235
|
if (error61 === beforePublishError) throw error61;
|
|
49236
|
+
if (error61 === afterPublishError) throw error61;
|
|
47297
49237
|
if (error61 instanceof BackupError && error61.code === "vault_exists") throw error61;
|
|
47298
|
-
if (isExistingFile2(error61) || await
|
|
49238
|
+
if (isExistingFile2(error61) || await pathExists2(vaultPath).catch(() => false) || await pathExists2(registryPath).catch(() => false)) {
|
|
47299
49239
|
throw new BackupError("vault_exists");
|
|
47300
49240
|
}
|
|
47301
49241
|
throw new BackupError("backup_invalid_input");
|
|
@@ -47305,9 +49245,400 @@ async function restoreBackupPlaintext(options) {
|
|
|
47305
49245
|
}
|
|
47306
49246
|
}
|
|
47307
49247
|
}
|
|
49248
|
+
async function stageV2Restore(options) {
|
|
49249
|
+
const skipped = [];
|
|
49250
|
+
const conflicts = [];
|
|
49251
|
+
const accounts = new Map(options.plaintext.accounts.map((account) => [account.name, account]));
|
|
49252
|
+
const validAgents = (options.plaintext.agents ?? []).filter((profile) => {
|
|
49253
|
+
if (accounts.has(profile.wallet)) return true;
|
|
49254
|
+
skipped.push({ kind: "agent", name: profile.name, reason: "missing_account" });
|
|
49255
|
+
return false;
|
|
49256
|
+
});
|
|
49257
|
+
const validSwarms = (options.plaintext.swarms ?? []).filter((swarm) => {
|
|
49258
|
+
const treasury = accounts.get(swarm.treasury.account);
|
|
49259
|
+
if (treasury === void 0) {
|
|
49260
|
+
if (swarm.treasury.steps.created || swarm.treasury.steps.creating) {
|
|
49261
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "missing_account" });
|
|
49262
|
+
return false;
|
|
49263
|
+
}
|
|
49264
|
+
} else if (swarm.treasury.address !== void 0 && swarm.treasury.address.toLowerCase() !== treasury.address.toLowerCase()) {
|
|
49265
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "address_mismatch" });
|
|
49266
|
+
return false;
|
|
49267
|
+
}
|
|
49268
|
+
for (const member of swarm.members) {
|
|
49269
|
+
const account = accounts.get(member.account);
|
|
49270
|
+
if (account === void 0) {
|
|
49271
|
+
if (member.steps.created || member.steps.creating) {
|
|
49272
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "missing_account" });
|
|
49273
|
+
return false;
|
|
49274
|
+
}
|
|
49275
|
+
continue;
|
|
49276
|
+
}
|
|
49277
|
+
if (member.address !== void 0 && member.address.toLowerCase() !== account.address.toLowerCase()) {
|
|
49278
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "address_mismatch" });
|
|
49279
|
+
return false;
|
|
49280
|
+
}
|
|
49281
|
+
}
|
|
49282
|
+
return true;
|
|
49283
|
+
});
|
|
49284
|
+
const allMovementLegs = /* @__PURE__ */ new Set();
|
|
49285
|
+
const backupMovementIds = [];
|
|
49286
|
+
const validMovements = [];
|
|
49287
|
+
for (const backupMovement of options.plaintext.movements ?? []) {
|
|
49288
|
+
const movement = currentMovement(backupMovement);
|
|
49289
|
+
backupMovementIds.push(movement.id);
|
|
49290
|
+
const legKeys = movement.legs.map((leg) => movementTransferKey(leg.from, leg.nonce));
|
|
49291
|
+
for (const key of legKeys) allMovementLegs.add(key);
|
|
49292
|
+
const senders = /* @__PURE__ */ new Set([
|
|
49293
|
+
movement.from,
|
|
49294
|
+
...movement.treasury === void 0 ? [] : [movement.treasury],
|
|
49295
|
+
...movement.legs.map((leg) => leg.from)
|
|
49296
|
+
]);
|
|
49297
|
+
if ([...senders].some((sender) => !accounts.has(sender))) {
|
|
49298
|
+
skipped.push({ kind: "movement", name: movement.id, reason: "missing_account" });
|
|
49299
|
+
continue;
|
|
49300
|
+
}
|
|
49301
|
+
validMovements.push(movement);
|
|
49302
|
+
}
|
|
49303
|
+
const validReceipts = [];
|
|
49304
|
+
for (const receipt of options.plaintext.transferReceipts ?? []) {
|
|
49305
|
+
const key = movementTransferKey(receipt.wallet, receipt.transfer.nonce);
|
|
49306
|
+
if (!accounts.has(receipt.wallet)) {
|
|
49307
|
+
skipped.push({ kind: "receipt", name: receipt.id, reason: "missing_account" });
|
|
49308
|
+
} else if (!allMovementLegs.has(key)) {
|
|
49309
|
+
skipped.push({ kind: "receipt", name: receipt.id, reason: "missing_movement" });
|
|
49310
|
+
} else {
|
|
49311
|
+
validReceipts.push({
|
|
49312
|
+
name: receipt.id,
|
|
49313
|
+
line: JSON.stringify(parseReceipt(receipt)),
|
|
49314
|
+
legKey: key
|
|
49315
|
+
});
|
|
49316
|
+
}
|
|
49317
|
+
}
|
|
49318
|
+
let receiptsPath;
|
|
49319
|
+
let stagedReceipts = validReceipts;
|
|
49320
|
+
if (validReceipts.length > 0) {
|
|
49321
|
+
receiptsPath = getVapiPaths(options.stagingHome).receipts;
|
|
49322
|
+
const staged = await stageRestoreBytes(
|
|
49323
|
+
receiptsPath,
|
|
49324
|
+
`${validReceipts.map((receipt) => receipt.line).join("\n")}
|
|
49325
|
+
`
|
|
49326
|
+
);
|
|
49327
|
+
if (!staged) {
|
|
49328
|
+
for (const receipt of validReceipts) {
|
|
49329
|
+
skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
|
|
49330
|
+
}
|
|
49331
|
+
stagedReceipts = [];
|
|
49332
|
+
receiptsPath = void 0;
|
|
49333
|
+
}
|
|
49334
|
+
}
|
|
49335
|
+
const assumedReceiptKeys = new Set(validReceipts.map((receipt) => receipt.legKey));
|
|
49336
|
+
try {
|
|
49337
|
+
const existingJournal = await readRestoreReceiptJournal(getVapiPaths(options.home).receipts);
|
|
49338
|
+
for (const key of existingJournal.signedKeys) assumedReceiptKeys.add(key);
|
|
49339
|
+
} catch {
|
|
49340
|
+
}
|
|
49341
|
+
const agents = [];
|
|
49342
|
+
for (const profile of validAgents) {
|
|
49343
|
+
const stagedPath = join8(options.stagingHome, "agents", `${profile.name}.json`);
|
|
49344
|
+
if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
|
|
49345
|
+
agents.push({
|
|
49346
|
+
kind: "agent",
|
|
49347
|
+
name: profile.name,
|
|
49348
|
+
stagedPath,
|
|
49349
|
+
targetPath: join8(options.home, "agents", `${profile.name}.json`)
|
|
49350
|
+
});
|
|
49351
|
+
} else {
|
|
49352
|
+
skipped.push({ kind: "agent", name: profile.name, reason: "write_failed" });
|
|
49353
|
+
}
|
|
49354
|
+
}
|
|
49355
|
+
let restoreDevice = options.device;
|
|
49356
|
+
if (validSwarms.length > 0 && restoreDevice === void 0) {
|
|
49357
|
+
try {
|
|
49358
|
+
restoreDevice = deviceName({ config: await loadConfig(getVapiPaths(options.home).config) });
|
|
49359
|
+
} catch {
|
|
49360
|
+
for (const swarm of validSwarms) {
|
|
49361
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
|
|
49362
|
+
}
|
|
49363
|
+
}
|
|
49364
|
+
}
|
|
49365
|
+
const swarms = [];
|
|
49366
|
+
if (restoreDevice !== void 0) {
|
|
49367
|
+
for (const value of validSwarms) {
|
|
49368
|
+
const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
|
|
49369
|
+
const stagedPath = join8(options.stagingHome, "swarms", `${swarm.name}.json`);
|
|
49370
|
+
if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
|
|
49371
|
+
swarms.push({
|
|
49372
|
+
kind: "swarm",
|
|
49373
|
+
name: swarm.name,
|
|
49374
|
+
stagedPath,
|
|
49375
|
+
targetPath: join8(options.home, "swarms", `${swarm.name}.json`)
|
|
49376
|
+
});
|
|
49377
|
+
} else {
|
|
49378
|
+
skipped.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
|
|
49379
|
+
}
|
|
49380
|
+
}
|
|
49381
|
+
}
|
|
49382
|
+
const movements = [];
|
|
49383
|
+
for (const movement of validMovements) {
|
|
49384
|
+
const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
|
|
49385
|
+
const stagedPath = join8(options.stagingHome, "movements", `${restored.id}.json`);
|
|
49386
|
+
if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
|
|
49387
|
+
movements.push({
|
|
49388
|
+
kind: "movement",
|
|
49389
|
+
name: restored.id,
|
|
49390
|
+
stagedPath,
|
|
49391
|
+
targetPath: join8(options.home, "movements", `${restored.id}.json`),
|
|
49392
|
+
movement: restored
|
|
49393
|
+
});
|
|
49394
|
+
} else {
|
|
49395
|
+
skipped.push({ kind: "movement", name: restored.id, reason: "write_failed" });
|
|
49396
|
+
}
|
|
49397
|
+
}
|
|
49398
|
+
return {
|
|
49399
|
+
agents,
|
|
49400
|
+
swarms,
|
|
49401
|
+
movements,
|
|
49402
|
+
backupMovementIds,
|
|
49403
|
+
receipts: stagedReceipts,
|
|
49404
|
+
signedReceiptKeys: assumedReceiptKeys,
|
|
49405
|
+
...receiptsPath === void 0 ? {} : { receiptsPath },
|
|
49406
|
+
restoredAgents: [],
|
|
49407
|
+
restoredSwarms: [],
|
|
49408
|
+
restoredMovements: [],
|
|
49409
|
+
skipped,
|
|
49410
|
+
conflicts,
|
|
49411
|
+
...restoreDevice === void 0 ? {} : { restoreDevice }
|
|
49412
|
+
};
|
|
49413
|
+
}
|
|
49414
|
+
async function publishV2Restore(staged, home, afterPublish) {
|
|
49415
|
+
for (const file2 of staged.agents) {
|
|
49416
|
+
const outcome = await publishRestoreFile(file2, staged);
|
|
49417
|
+
if (outcome === "restored") staged.restoredAgents.push(file2.name);
|
|
49418
|
+
if (outcome === "restored") await afterPublish?.({ kind: "agent", name: file2.name });
|
|
49419
|
+
}
|
|
49420
|
+
for (const file2 of staged.swarms) {
|
|
49421
|
+
const outcome = await publishRestoreFile(file2, staged);
|
|
49422
|
+
if (outcome === "restored") staged.restoredSwarms.push(file2.name);
|
|
49423
|
+
if (outcome === "restored") await afterPublish?.({ kind: "swarm", name: file2.name });
|
|
49424
|
+
}
|
|
49425
|
+
const restoredMovementIds = [];
|
|
49426
|
+
for (const file2 of staged.movements) {
|
|
49427
|
+
const outcome = await publishRestoreFile(file2, staged);
|
|
49428
|
+
if (outcome === "restored") restoredMovementIds.push(file2.movement.id);
|
|
49429
|
+
if (outcome === "restored") await afterPublish?.({ kind: "movement", name: file2.name });
|
|
49430
|
+
}
|
|
49431
|
+
await reconcilePublishedMovements(staged, home);
|
|
49432
|
+
for (const id of restoredMovementIds) {
|
|
49433
|
+
try {
|
|
49434
|
+
staged.restoredMovements.push(movementSummary(await readMovement(home, id)));
|
|
49435
|
+
} catch {
|
|
49436
|
+
staged.skipped.push({ kind: "movement", name: id, reason: "write_failed" });
|
|
49437
|
+
}
|
|
49438
|
+
}
|
|
49439
|
+
}
|
|
49440
|
+
async function publishV2RestoreSafety(staged, home) {
|
|
49441
|
+
for (const id of staged.backupMovementIds) {
|
|
49442
|
+
await markOpenLegsRestored(home, id);
|
|
49443
|
+
}
|
|
49444
|
+
await publishRestoreReceipts(staged, getVapiPaths(home).receipts);
|
|
49445
|
+
await reconcilePublishedMovements(staged, home, true);
|
|
49446
|
+
}
|
|
49447
|
+
async function publishRestoreFile(file2, staged) {
|
|
49448
|
+
try {
|
|
49449
|
+
const directory = dirname5(file2.targetPath);
|
|
49450
|
+
await mkdir8(directory, { recursive: true, mode: 448 });
|
|
49451
|
+
await chmod2(directory, 448);
|
|
49452
|
+
try {
|
|
49453
|
+
await link2(file2.stagedPath, file2.targetPath);
|
|
49454
|
+
await chmod2(file2.targetPath, 384);
|
|
49455
|
+
return "restored";
|
|
49456
|
+
} catch (error61) {
|
|
49457
|
+
if (!isExistingFile2(error61)) throw error61;
|
|
49458
|
+
}
|
|
49459
|
+
let identical = false;
|
|
49460
|
+
try {
|
|
49461
|
+
const [source, target] = await Promise.all([
|
|
49462
|
+
readFile9(file2.stagedPath),
|
|
49463
|
+
readFile9(file2.targetPath)
|
|
49464
|
+
]);
|
|
49465
|
+
identical = source.equals(target);
|
|
49466
|
+
} catch {
|
|
49467
|
+
}
|
|
49468
|
+
if (identical) {
|
|
49469
|
+
await chmod2(file2.targetPath, 384);
|
|
49470
|
+
return "restored";
|
|
49471
|
+
}
|
|
49472
|
+
staged.conflicts.push({
|
|
49473
|
+
kind: file2.kind,
|
|
49474
|
+
name: file2.name,
|
|
49475
|
+
path: file2.targetPath
|
|
49476
|
+
});
|
|
49477
|
+
return "conflict";
|
|
49478
|
+
} catch {
|
|
49479
|
+
staged.skipped.push({ kind: file2.kind, name: file2.name, reason: "write_failed" });
|
|
49480
|
+
return "failed";
|
|
49481
|
+
}
|
|
49482
|
+
}
|
|
49483
|
+
async function publishRestoreReceipts(staged, targetPath) {
|
|
49484
|
+
return await withReceiptJournalLock(
|
|
49485
|
+
targetPath,
|
|
49486
|
+
async () => publishRestoreReceiptsLocked(staged, targetPath)
|
|
49487
|
+
);
|
|
49488
|
+
}
|
|
49489
|
+
async function publishRestoreReceiptsLocked(staged, targetPath) {
|
|
49490
|
+
const restored = /* @__PURE__ */ new Set();
|
|
49491
|
+
if (staged.receipts.length === 0 || staged.receiptsPath === void 0) return restored;
|
|
49492
|
+
let existing = "";
|
|
49493
|
+
let existingLines = /* @__PURE__ */ new Set();
|
|
49494
|
+
try {
|
|
49495
|
+
await readFile9(staged.receiptsPath, "utf8");
|
|
49496
|
+
await mkdir8(dirname5(targetPath), { recursive: true, mode: 448 });
|
|
49497
|
+
try {
|
|
49498
|
+
const journal = await readRestoreReceiptJournal(targetPath);
|
|
49499
|
+
existing = journal.raw;
|
|
49500
|
+
existingLines = journal.lines;
|
|
49501
|
+
await chmod2(targetPath, 384);
|
|
49502
|
+
} catch (error61) {
|
|
49503
|
+
if (!isMissingFile3(error61)) throw error61;
|
|
49504
|
+
}
|
|
49505
|
+
} catch {
|
|
49506
|
+
for (const receipt of staged.receipts) {
|
|
49507
|
+
staged.skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
|
|
49508
|
+
}
|
|
49509
|
+
return restored;
|
|
49510
|
+
}
|
|
49511
|
+
let needsLeadingNewline = existing.length > 0 && !existing.endsWith("\n");
|
|
49512
|
+
for (const receipt of staged.receipts) {
|
|
49513
|
+
if (existingLines.has(receipt.line)) {
|
|
49514
|
+
restored.add(receipt.legKey);
|
|
49515
|
+
continue;
|
|
49516
|
+
}
|
|
49517
|
+
let handle;
|
|
49518
|
+
try {
|
|
49519
|
+
handle = await openFile(targetPath, "a", 384);
|
|
49520
|
+
await handle.chmod(384);
|
|
49521
|
+
await handle.writeFile(`${needsLeadingNewline ? "\n" : ""}${receipt.line}
|
|
49522
|
+
`, "utf8");
|
|
49523
|
+
await handle.close();
|
|
49524
|
+
handle = void 0;
|
|
49525
|
+
needsLeadingNewline = false;
|
|
49526
|
+
existingLines.add(receipt.line);
|
|
49527
|
+
restored.add(receipt.legKey);
|
|
49528
|
+
} catch {
|
|
49529
|
+
await handle?.close().catch(() => void 0);
|
|
49530
|
+
staged.skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
|
|
49531
|
+
}
|
|
49532
|
+
}
|
|
49533
|
+
return restored;
|
|
49534
|
+
}
|
|
49535
|
+
async function reconcilePublishedMovements(staged, home, requireDurableSafety = false) {
|
|
49536
|
+
const signedKeys = new Set(staged.signedReceiptKeys);
|
|
49537
|
+
const journaledKeys = /* @__PURE__ */ new Set();
|
|
49538
|
+
try {
|
|
49539
|
+
const journal = await readRestoreReceiptJournal(getVapiPaths(home).receipts);
|
|
49540
|
+
for (const key of journal.signedKeys) {
|
|
49541
|
+
signedKeys.add(key);
|
|
49542
|
+
journaledKeys.add(key);
|
|
49543
|
+
}
|
|
49544
|
+
} catch {
|
|
49545
|
+
}
|
|
49546
|
+
if (signedKeys.size === 0) return;
|
|
49547
|
+
const unjournaledKeys = new Set([...signedKeys].filter((key) => !journaledKeys.has(key)));
|
|
49548
|
+
let files;
|
|
49549
|
+
try {
|
|
49550
|
+
files = await readdir5(join8(home, "movements"));
|
|
49551
|
+
} catch (error61) {
|
|
49552
|
+
if (isMissingFile3(error61)) return;
|
|
49553
|
+
if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
|
|
49554
|
+
return;
|
|
49555
|
+
}
|
|
49556
|
+
for (const file2 of files) {
|
|
49557
|
+
if (!file2.endsWith(".json")) continue;
|
|
49558
|
+
const id = file2.slice(0, -5);
|
|
49559
|
+
let movement;
|
|
49560
|
+
try {
|
|
49561
|
+
movement = await readMovement(home, id);
|
|
49562
|
+
} catch (error61) {
|
|
49563
|
+
if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
|
|
49564
|
+
continue;
|
|
49565
|
+
}
|
|
49566
|
+
if (!movement.legs.some(
|
|
49567
|
+
(leg) => leg.status !== "sent" && leg.status !== "cancelled" && signedKeys.has(movementTransferKey(leg.from, leg.nonce))
|
|
49568
|
+
)) {
|
|
49569
|
+
continue;
|
|
49570
|
+
}
|
|
49571
|
+
try {
|
|
49572
|
+
await reconcileSignedLegs(home, id, signedKeys);
|
|
49573
|
+
} catch (error61) {
|
|
49574
|
+
staged.skipped.push({ kind: "movement", name: id, reason: "write_failed" });
|
|
49575
|
+
if (requireDurableSafety && movement.legs.some(
|
|
49576
|
+
(leg) => leg.status !== "sent" && leg.status !== "cancelled" && unjournaledKeys.has(movementTransferKey(leg.from, leg.nonce))
|
|
49577
|
+
)) {
|
|
49578
|
+
throw error61;
|
|
49579
|
+
}
|
|
49580
|
+
}
|
|
49581
|
+
}
|
|
49582
|
+
}
|
|
49583
|
+
async function stageRestoreBytes(path, bytes) {
|
|
49584
|
+
let handle;
|
|
49585
|
+
try {
|
|
49586
|
+
await mkdir8(dirname5(path), { recursive: true, mode: 448 });
|
|
49587
|
+
handle = await openFile(path, "wx", 384);
|
|
49588
|
+
await handle.writeFile(bytes, "utf8");
|
|
49589
|
+
await handle.close();
|
|
49590
|
+
return true;
|
|
49591
|
+
} catch {
|
|
49592
|
+
await handle?.close().catch(() => void 0);
|
|
49593
|
+
return false;
|
|
49594
|
+
}
|
|
49595
|
+
}
|
|
49596
|
+
function currentMovement(movement) {
|
|
49597
|
+
if (movement.v === 2) return movement;
|
|
49598
|
+
return {
|
|
49599
|
+
...movement,
|
|
49600
|
+
v: 2,
|
|
49601
|
+
legs: movement.legs.map((leg) => ({
|
|
49602
|
+
...leg,
|
|
49603
|
+
from: movement.from,
|
|
49604
|
+
purpose: "send"
|
|
49605
|
+
}))
|
|
49606
|
+
};
|
|
49607
|
+
}
|
|
49608
|
+
function reconcileRestoredMovement(movement, receiptKeys) {
|
|
49609
|
+
return {
|
|
49610
|
+
...movement,
|
|
49611
|
+
legs: movement.legs.map((leg) => {
|
|
49612
|
+
if (leg.status === "cancelled") return leg;
|
|
49613
|
+
return leg.status !== "sent" && receiptKeys.has(movementTransferKey(leg.from, leg.nonce)) ? {
|
|
49614
|
+
from: leg.from,
|
|
49615
|
+
to: leg.to,
|
|
49616
|
+
amountUsd: leg.amountUsd,
|
|
49617
|
+
purpose: leg.purpose,
|
|
49618
|
+
nonce: leg.nonce,
|
|
49619
|
+
status: "unknown",
|
|
49620
|
+
restored: true
|
|
49621
|
+
} : { ...leg, restored: true };
|
|
49622
|
+
})
|
|
49623
|
+
};
|
|
49624
|
+
}
|
|
49625
|
+
function movementSummary(movement) {
|
|
49626
|
+
return {
|
|
49627
|
+
id: movement.id,
|
|
49628
|
+
from: movement.from,
|
|
49629
|
+
network: movement.network,
|
|
49630
|
+
createdAt: movement.createdAt,
|
|
49631
|
+
pendingLegs: movement.legs.filter((leg) => leg.status === "planned").length,
|
|
49632
|
+
unknownLegs: movement.legs.filter((leg) => leg.status === "unknown").length
|
|
49633
|
+
};
|
|
49634
|
+
}
|
|
49635
|
+
function prettyJson(value) {
|
|
49636
|
+
return `${JSON.stringify(value, null, 2)}
|
|
49637
|
+
`;
|
|
49638
|
+
}
|
|
47308
49639
|
function parseSealed(sealed) {
|
|
47309
49640
|
const value = JSON.parse(sealed);
|
|
47310
|
-
if (!
|
|
49641
|
+
if (!isRecord2(value) || !hasExactKeys(value, RELAY_KEYS) || value.format !== RELAY_FORMAT || value.v !== RELAY_VERSION || typeof value.epk !== "string" || typeof value.nonce !== "string" || typeof value.ciphertext !== "string" || decodeBase64Url(value.epk)?.byteLength !== 32 || decodeBase64Url(value.nonce)?.byteLength !== 12 || (decodeBase64Url(value.ciphertext)?.byteLength ?? 0) < 16) {
|
|
47311
49642
|
throw new Error();
|
|
47312
49643
|
}
|
|
47313
49644
|
return { epk: value.epk, nonce: value.nonce, ciphertext: value.ciphertext };
|
|
@@ -47317,9 +49648,9 @@ function assertRelayKey(value) {
|
|
|
47317
49648
|
throw new BackupError("relay_invalid_key");
|
|
47318
49649
|
}
|
|
47319
49650
|
}
|
|
47320
|
-
function readRelayRandomBytes(
|
|
49651
|
+
function readRelayRandomBytes(randomBytes7, length) {
|
|
47321
49652
|
try {
|
|
47322
|
-
const value =
|
|
49653
|
+
const value = randomBytes7(length);
|
|
47323
49654
|
if (!(value instanceof Uint8Array) || value.byteLength !== length) throw new Error();
|
|
47324
49655
|
return Buffer.from(value);
|
|
47325
49656
|
} catch {
|
|
@@ -47375,7 +49706,7 @@ function validateRestorePlaintext(value) {
|
|
|
47375
49706
|
try {
|
|
47376
49707
|
const parsed = backupPlaintextSchema.safeParse(value);
|
|
47377
49708
|
if (!parsed.success) throw new Error();
|
|
47378
|
-
const plaintext =
|
|
49709
|
+
const plaintext = parsed.data.v === 1 ? buildPlaintextV1(parsed.data) : buildPlaintextV2(parsed.data);
|
|
47379
49710
|
const phrase = validateRecoveryPhrase(plaintext.phrase);
|
|
47380
49711
|
let seed;
|
|
47381
49712
|
try {
|
|
@@ -47398,12 +49729,22 @@ function buildRestoredRegistry(plaintext) {
|
|
|
47398
49729
|
for (let index = 0; index < plaintext.accounts.length; index += 1) {
|
|
47399
49730
|
const account = plaintext.accounts[index];
|
|
47400
49731
|
const metadata = plaintext.registry.accounts[index];
|
|
49732
|
+
const metadataV2 = plaintext.v === 2 ? plaintext.registry.accounts[index] : void 0;
|
|
47401
49733
|
wallets[account.name] = {
|
|
47402
49734
|
createdAt: account.createdAt,
|
|
47403
49735
|
...metadata.label === void 0 ? {} : { label: metadata.label },
|
|
47404
49736
|
spendCaps: {
|
|
47405
49737
|
perCallAtomic: metadata.spendCaps.perCallAtomic,
|
|
47406
49738
|
perDayAtomic: metadata.spendCaps.perDayAtomic
|
|
49739
|
+
},
|
|
49740
|
+
...metadataV2 === void 0 ? {} : {
|
|
49741
|
+
ceilingAtomic: metadataV2.ceilingAtomic === void 0 ? DEFAULT_CEILING_ATOMIC.toString() : metadataV2.ceilingAtomic,
|
|
49742
|
+
...metadataV2.routerRefill === void 0 ? {} : {
|
|
49743
|
+
routerRefill: {
|
|
49744
|
+
belowUsd: metadataV2.routerRefill.belowUsd,
|
|
49745
|
+
tierUsd: metadataV2.routerRefill.tierUsd
|
|
49746
|
+
}
|
|
49747
|
+
}
|
|
47407
49748
|
}
|
|
47408
49749
|
};
|
|
47409
49750
|
}
|
|
@@ -47413,7 +49754,48 @@ function buildRestoredRegistry(plaintext) {
|
|
|
47413
49754
|
wallets
|
|
47414
49755
|
});
|
|
47415
49756
|
}
|
|
47416
|
-
|
|
49757
|
+
function restoreFingerprint(plaintext, device, vaultKey) {
|
|
49758
|
+
return createHmac("sha256", vaultKey).update("vapi-backup-restore/v1\n", "utf8").update(JSON.stringify({ device: device ?? null, plaintext }), "utf8").digest("hex");
|
|
49759
|
+
}
|
|
49760
|
+
async function createRestoreMarker(vaultPath, registryPath, fingerprint, vaultKey) {
|
|
49761
|
+
const marker = {
|
|
49762
|
+
v: 1,
|
|
49763
|
+
fingerprint,
|
|
49764
|
+
vaultSha256: await sha256File(vaultPath),
|
|
49765
|
+
registrySha256: await sha256File(registryPath)
|
|
49766
|
+
};
|
|
49767
|
+
return { ...marker, mac: restoreMarkerMac(marker, vaultKey) };
|
|
49768
|
+
}
|
|
49769
|
+
async function readRestoreMarker(path, fingerprint, vaultKey) {
|
|
49770
|
+
try {
|
|
49771
|
+
const marker = restoreMarkerSchema.parse(JSON.parse(await readFile9(path, "utf8")));
|
|
49772
|
+
const expectedMac = restoreMarkerMac(marker, vaultKey);
|
|
49773
|
+
if (marker.fingerprint !== fingerprint || !timingSafeEqual(Buffer.from(marker.mac, "hex"), Buffer.from(expectedMac, "hex"))) {
|
|
49774
|
+
throw new Error();
|
|
49775
|
+
}
|
|
49776
|
+
return marker;
|
|
49777
|
+
} catch {
|
|
49778
|
+
throw new BackupError("vault_exists");
|
|
49779
|
+
}
|
|
49780
|
+
}
|
|
49781
|
+
function restoreMarkerMac(marker, vaultKey) {
|
|
49782
|
+
return createHmac("sha256", vaultKey).update(
|
|
49783
|
+
`vapi-backup-restore-marker/v1|${marker.fingerprint}|${marker.vaultSha256}|${marker.registrySha256}`,
|
|
49784
|
+
"utf8"
|
|
49785
|
+
).digest("hex");
|
|
49786
|
+
}
|
|
49787
|
+
async function sha256File(path) {
|
|
49788
|
+
return createHash2("sha256").update(await readFile9(path)).digest("hex");
|
|
49789
|
+
}
|
|
49790
|
+
async function notifyRestorePublish(hook, step, rememberError) {
|
|
49791
|
+
try {
|
|
49792
|
+
await hook?.(step);
|
|
49793
|
+
} catch (error61) {
|
|
49794
|
+
rememberError(error61);
|
|
49795
|
+
throw error61;
|
|
49796
|
+
}
|
|
49797
|
+
}
|
|
49798
|
+
async function pathExists2(path) {
|
|
47417
49799
|
try {
|
|
47418
49800
|
await lstat(path);
|
|
47419
49801
|
return true;
|
|
@@ -47429,7 +49811,7 @@ function isExistingFile2(error61) {
|
|
|
47429
49811
|
return isErrorCode(error61, "EEXIST");
|
|
47430
49812
|
}
|
|
47431
49813
|
function isErrorCode(error61, code) {
|
|
47432
|
-
return
|
|
49814
|
+
return isRecord2(error61) && Reflect.get(error61, "code") === code;
|
|
47433
49815
|
}
|
|
47434
49816
|
function validateBackupSourceRelationships(source, context) {
|
|
47435
49817
|
const names = /* @__PURE__ */ new Set();
|
|
@@ -47463,7 +49845,23 @@ function validateBackupSourceRelationships(source, context) {
|
|
|
47463
49845
|
}
|
|
47464
49846
|
}
|
|
47465
49847
|
}
|
|
47466
|
-
function
|
|
49848
|
+
function validateBackupV2Uniqueness(source, context) {
|
|
49849
|
+
validateUniqueValues(source.agents, (agent) => agent.name, "agent name", context);
|
|
49850
|
+
validateUniqueValues(source.swarms, (swarm) => swarm.name, "swarm name", context);
|
|
49851
|
+
validateUniqueValues(source.movements, (movement) => movement.id, "movement id", context);
|
|
49852
|
+
}
|
|
49853
|
+
function validateUniqueValues(values, key, label, context) {
|
|
49854
|
+
if (values === void 0) return;
|
|
49855
|
+
const seen = /* @__PURE__ */ new Set();
|
|
49856
|
+
for (const value of values) {
|
|
49857
|
+
const current = key(value);
|
|
49858
|
+
if (seen.has(current)) {
|
|
49859
|
+
context.addIssue({ code: "custom", message: `Duplicate ${label}.` });
|
|
49860
|
+
}
|
|
49861
|
+
seen.add(current);
|
|
49862
|
+
}
|
|
49863
|
+
}
|
|
49864
|
+
function buildPlaintextV1(source) {
|
|
47467
49865
|
const accounts = source.accounts.map(
|
|
47468
49866
|
(account) => account.kind === "derived" ? {
|
|
47469
49867
|
name: account.name,
|
|
@@ -47501,7 +49899,245 @@ function buildPlaintext(source) {
|
|
|
47501
49899
|
protected: source.protected
|
|
47502
49900
|
};
|
|
47503
49901
|
}
|
|
49902
|
+
function buildPlaintextV2(source, included = { agents: true, swarms: true, movements: true }) {
|
|
49903
|
+
const accounts = buildPlaintextV1({
|
|
49904
|
+
phrase: source.phrase,
|
|
49905
|
+
nextDerivedIndex: source.nextDerivedIndex,
|
|
49906
|
+
accounts: source.accounts,
|
|
49907
|
+
registry: {
|
|
49908
|
+
...source.registry.default === void 0 ? {} : { default: source.registry.default },
|
|
49909
|
+
accounts: source.registry.accounts,
|
|
49910
|
+
networks: source.registry.networks
|
|
49911
|
+
},
|
|
49912
|
+
protected: source.protected
|
|
49913
|
+
}).accounts;
|
|
49914
|
+
const registry2 = {
|
|
49915
|
+
...source.registry.default === void 0 ? {} : { default: source.registry.default },
|
|
49916
|
+
accounts: source.registry.accounts.map((account) => ({
|
|
49917
|
+
name: account.name,
|
|
49918
|
+
...account.label === void 0 ? {} : { label: account.label },
|
|
49919
|
+
spendCaps: {
|
|
49920
|
+
perCallAtomic: account.spendCaps.perCallAtomic,
|
|
49921
|
+
perDayAtomic: account.spendCaps.perDayAtomic
|
|
49922
|
+
},
|
|
49923
|
+
...account.ceilingAtomic === void 0 || account.ceilingAtomic === DEFAULT_CEILING_ATOMIC.toString() ? {} : { ceilingAtomic: account.ceilingAtomic },
|
|
49924
|
+
...account.routerRefill === void 0 ? {} : {
|
|
49925
|
+
routerRefill: {
|
|
49926
|
+
belowUsd: account.routerRefill.belowUsd,
|
|
49927
|
+
tierUsd: account.routerRefill.tierUsd
|
|
49928
|
+
}
|
|
49929
|
+
}
|
|
49930
|
+
})),
|
|
49931
|
+
networks: [...source.registry.networks]
|
|
49932
|
+
};
|
|
49933
|
+
const agents = source.agents;
|
|
49934
|
+
const swarms = source.swarms;
|
|
49935
|
+
const movements = source.movements;
|
|
49936
|
+
const transferReceipts = source.transferReceipts;
|
|
49937
|
+
return {
|
|
49938
|
+
v: 2,
|
|
49939
|
+
phrase: source.phrase,
|
|
49940
|
+
nextDerivedIndex: source.nextDerivedIndex,
|
|
49941
|
+
accounts,
|
|
49942
|
+
registry: registry2,
|
|
49943
|
+
protected: source.protected,
|
|
49944
|
+
...included.agents !== false && agents !== void 0 && agents.length > 0 ? { agents: [...agents].sort(compareNamedValues).map(copyAgentProfile) } : {},
|
|
49945
|
+
...included.swarms !== false && swarms !== void 0 && swarms.length > 0 ? { swarms: [...swarms].sort(compareNamedValues).map(copySwarm) } : {},
|
|
49946
|
+
...included.movements !== false && movements !== void 0 && movements.length > 0 ? { movements: [...movements].sort(compareMovements).map(copyMovement) } : {},
|
|
49947
|
+
...included.movements !== false && transferReceipts !== void 0 && transferReceipts.length > 0 ? { transferReceipts: transferReceipts.map(copyTransferReceipt) } : {}
|
|
49948
|
+
};
|
|
49949
|
+
}
|
|
49950
|
+
function backupCandidates(source) {
|
|
49951
|
+
if (!isBackupSourceV2(source)) {
|
|
49952
|
+
return [{ plaintext: buildPlaintextV1(source), omitted: [] }];
|
|
49953
|
+
}
|
|
49954
|
+
const candidates = [];
|
|
49955
|
+
const included = { agents: true, swarms: true, movements: true };
|
|
49956
|
+
const omitted = [];
|
|
49957
|
+
const addCandidate = () => {
|
|
49958
|
+
candidates.push({
|
|
49959
|
+
plaintext: hasV2OnlyData(source, included) ? buildPlaintextV2(source, included) : buildPlaintextV1(source),
|
|
49960
|
+
omitted: [...omitted]
|
|
49961
|
+
});
|
|
49962
|
+
};
|
|
49963
|
+
addCandidate();
|
|
49964
|
+
if (source.agents.length > 0) {
|
|
49965
|
+
included.agents = false;
|
|
49966
|
+
omitted.push("agents");
|
|
49967
|
+
addCandidate();
|
|
49968
|
+
}
|
|
49969
|
+
if (source.swarms.length > 0) {
|
|
49970
|
+
included.swarms = false;
|
|
49971
|
+
omitted.push("swarms");
|
|
49972
|
+
addCandidate();
|
|
49973
|
+
}
|
|
49974
|
+
if (source.movements.length > 0 || source.transferReceipts.length > 0) {
|
|
49975
|
+
included.movements = false;
|
|
49976
|
+
omitted.push("movements");
|
|
49977
|
+
addCandidate();
|
|
49978
|
+
}
|
|
49979
|
+
return candidates;
|
|
49980
|
+
}
|
|
49981
|
+
function hasV2OnlyData(source, included) {
|
|
49982
|
+
return source.registry.accounts.some(
|
|
49983
|
+
(account) => account.ceilingAtomic !== void 0 && account.ceilingAtomic !== DEFAULT_CEILING_ATOMIC.toString() || account.routerRefill !== void 0
|
|
49984
|
+
) || included.agents !== false && source.agents.length > 0 || included.swarms !== false && source.swarms.length > 0 || included.movements !== false && (source.movements.length > 0 || source.transferReceipts.length > 0);
|
|
49985
|
+
}
|
|
49986
|
+
function isBackupSourceV2(source) {
|
|
49987
|
+
return "agents" in source;
|
|
49988
|
+
}
|
|
49989
|
+
function copyAgentProfile(profile) {
|
|
49990
|
+
return {
|
|
49991
|
+
version: profile.version,
|
|
49992
|
+
name: profile.name,
|
|
49993
|
+
wallet: profile.wallet,
|
|
49994
|
+
model: profile.model,
|
|
49995
|
+
instructions: profile.instructions,
|
|
49996
|
+
verifiedOnly: profile.verifiedOnly,
|
|
49997
|
+
approveAboveUsd: profile.approveAboveUsd,
|
|
49998
|
+
maxSteps: profile.maxSteps,
|
|
49999
|
+
paused: profile.paused,
|
|
50000
|
+
createdAt: profile.createdAt,
|
|
50001
|
+
tools: [...profile.tools],
|
|
50002
|
+
...profile.grants === void 0 ? {} : { grants: [...profile.grants] }
|
|
50003
|
+
};
|
|
50004
|
+
}
|
|
50005
|
+
function copySwarm(swarm) {
|
|
50006
|
+
return swarmFileSchema.parse(swarm);
|
|
50007
|
+
}
|
|
50008
|
+
function copyMovement(movement) {
|
|
50009
|
+
return toBackupMovement(movement);
|
|
50010
|
+
}
|
|
50011
|
+
function toBackupMovement(movement) {
|
|
50012
|
+
if (movement.v === 1) return backupMovementSchema.parse(movement);
|
|
50013
|
+
return backupMovementSchema.parse({
|
|
50014
|
+
...movement,
|
|
50015
|
+
legs: movement.legs.map(
|
|
50016
|
+
({
|
|
50017
|
+
restored: _restored,
|
|
50018
|
+
fromAddress: _fromAddress,
|
|
50019
|
+
toAddress: _toAddress,
|
|
50020
|
+
addressBindingSource: _addressBindingSource,
|
|
50021
|
+
...leg
|
|
50022
|
+
}) => leg
|
|
50023
|
+
)
|
|
50024
|
+
});
|
|
50025
|
+
}
|
|
50026
|
+
function toBackupTransferReceipt(receipt) {
|
|
50027
|
+
if (receipt.quote?.asset === void 0) throw new BackupError("backup_invalid_input");
|
|
50028
|
+
return copyTransferReceipt({
|
|
50029
|
+
id: receipt.id,
|
|
50030
|
+
timestamp: receipt.timestamp,
|
|
50031
|
+
kind: "transfer",
|
|
50032
|
+
wallet: receiptWallet(receipt),
|
|
50033
|
+
resourceUrl: receipt.resourceUrl,
|
|
50034
|
+
quote: {
|
|
50035
|
+
network: receipt.quote.network,
|
|
50036
|
+
asset: receipt.quote.asset,
|
|
50037
|
+
amountAtomic: receipt.quote.amountAtomic
|
|
50038
|
+
},
|
|
50039
|
+
transfer: receipt.transfer,
|
|
50040
|
+
...receipt.error === void 0 ? {} : { error: receipt.error }
|
|
50041
|
+
});
|
|
50042
|
+
}
|
|
50043
|
+
function copyTransferReceipt(receipt) {
|
|
50044
|
+
const transfer = receipt.transfer;
|
|
50045
|
+
const request = transfer.request;
|
|
50046
|
+
return backupTransferReceiptSchema.parse({
|
|
50047
|
+
id: receipt.id,
|
|
50048
|
+
timestamp: receipt.timestamp,
|
|
50049
|
+
kind: "transfer",
|
|
50050
|
+
wallet: receipt.wallet,
|
|
50051
|
+
resourceUrl: receipt.resourceUrl,
|
|
50052
|
+
quote: {
|
|
50053
|
+
network: receipt.quote.network,
|
|
50054
|
+
asset: receipt.quote.asset,
|
|
50055
|
+
amountAtomic: receipt.quote.amountAtomic
|
|
50056
|
+
},
|
|
50057
|
+
transfer: {
|
|
50058
|
+
to: transfer.to,
|
|
50059
|
+
toName: transfer.toName,
|
|
50060
|
+
toKind: transfer.toKind,
|
|
50061
|
+
amountAtomic: transfer.amountAtomic,
|
|
50062
|
+
network: transfer.network,
|
|
50063
|
+
nonce: transfer.nonce,
|
|
50064
|
+
status: transfer.status,
|
|
50065
|
+
txHash: transfer.txHash,
|
|
50066
|
+
replayed: transfer.replayed,
|
|
50067
|
+
...transfer.reservedOn === void 0 ? {} : { reservedOn: transfer.reservedOn },
|
|
50068
|
+
...request === void 0 ? {} : {
|
|
50069
|
+
request: {
|
|
50070
|
+
authorization: {
|
|
50071
|
+
from: request.authorization.from,
|
|
50072
|
+
to: request.authorization.to,
|
|
50073
|
+
value: request.authorization.value,
|
|
50074
|
+
validAfter: request.authorization.validAfter,
|
|
50075
|
+
validBefore: request.authorization.validBefore,
|
|
50076
|
+
nonce: request.authorization.nonce
|
|
50077
|
+
},
|
|
50078
|
+
signature: request.signature
|
|
50079
|
+
}
|
|
50080
|
+
}
|
|
50081
|
+
},
|
|
50082
|
+
...receipt.error === void 0 ? {} : { error: { code: receipt.error.code, message: receipt.error.message } }
|
|
50083
|
+
});
|
|
50084
|
+
}
|
|
50085
|
+
async function readReceiptJournal(path) {
|
|
50086
|
+
let raw;
|
|
50087
|
+
try {
|
|
50088
|
+
raw = await readFile9(path, "utf8");
|
|
50089
|
+
} catch (error61) {
|
|
50090
|
+
if (isMissingFile3(error61)) return [];
|
|
50091
|
+
throw error61;
|
|
50092
|
+
}
|
|
50093
|
+
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => parseReceipt(JSON.parse(line)));
|
|
50094
|
+
}
|
|
50095
|
+
async function readRestoreReceiptJournal(path) {
|
|
50096
|
+
let raw;
|
|
50097
|
+
try {
|
|
50098
|
+
raw = await readFile9(path, "utf8");
|
|
50099
|
+
} catch (error61) {
|
|
50100
|
+
if (isMissingFile3(error61)) return { raw: "", lines: /* @__PURE__ */ new Set(), signedKeys: /* @__PURE__ */ new Set() };
|
|
50101
|
+
throw error61;
|
|
50102
|
+
}
|
|
50103
|
+
const lines = new Set(raw.split("\n"));
|
|
50104
|
+
const signedKeys = /* @__PURE__ */ new Set();
|
|
50105
|
+
for (const line of lines) {
|
|
50106
|
+
if (line.trim().length === 0) continue;
|
|
50107
|
+
try {
|
|
50108
|
+
const receipt = parseReceipt(JSON.parse(line));
|
|
50109
|
+
if (receipt.transfer !== void 0) {
|
|
50110
|
+
signedKeys.add(movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce));
|
|
50111
|
+
}
|
|
50112
|
+
} catch {
|
|
50113
|
+
}
|
|
50114
|
+
}
|
|
50115
|
+
return { raw, lines, signedKeys };
|
|
50116
|
+
}
|
|
50117
|
+
function compareNamedValues(left, right) {
|
|
50118
|
+
return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
|
|
50119
|
+
}
|
|
50120
|
+
function compareMovements(left, right) {
|
|
50121
|
+
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
|
50122
|
+
}
|
|
47504
50123
|
var RELAY_KEYS = ["format", "v", "epk", "nonce", "ciphertext"];
|
|
50124
|
+
var HKDF_KEYS = ["name", "salt"];
|
|
50125
|
+
var SCRYPT_KEYS = ["name", "salt", "N", "r", "p"];
|
|
50126
|
+
function parseKdf(value) {
|
|
50127
|
+
if (value.name === "hkdf-sha256" && hasExactKeys(value, HKDF_KEYS)) {
|
|
50128
|
+
if (typeof value.salt !== "string" || decodeBase64Url(value.salt)?.byteLength !== 32) {
|
|
50129
|
+
throw new BackupError("backup_unsupported");
|
|
50130
|
+
}
|
|
50131
|
+
return { name: "hkdf-sha256", salt: value.salt };
|
|
50132
|
+
}
|
|
50133
|
+
if (value.name === "scrypt" && hasExactKeys(value, SCRYPT_KEYS)) {
|
|
50134
|
+
if (typeof value.salt !== "string" || decodeBase64Url(value.salt)?.byteLength !== 32 || value.N !== SCRYPT_N2 || value.r !== SCRYPT_R2 || value.p !== SCRYPT_P2) {
|
|
50135
|
+
throw new BackupError("backup_unsupported");
|
|
50136
|
+
}
|
|
50137
|
+
return { name: "scrypt", salt: value.salt, N: SCRYPT_N2, r: SCRYPT_R2, p: SCRYPT_P2 };
|
|
50138
|
+
}
|
|
50139
|
+
throw new BackupError("backup_unsupported");
|
|
50140
|
+
}
|
|
47505
50141
|
function buildBackupAad(header) {
|
|
47506
50142
|
const parameters = header.kdf.name === "scrypt" ? [String(header.kdf.N), String(header.kdf.r), String(header.kdf.p)] : ["", "", ""];
|
|
47507
50143
|
return [
|
|
@@ -47572,14 +50208,14 @@ function assertBytes(value, length) {
|
|
|
47572
50208
|
}
|
|
47573
50209
|
}
|
|
47574
50210
|
function assertOwnerKey(ownerKey) {
|
|
47575
|
-
if (!
|
|
50211
|
+
if (!isRecord2(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
|
|
47576
50212
|
throw new BackupError("backup_invalid_input");
|
|
47577
50213
|
}
|
|
47578
50214
|
assertBytes(ownerKey.key, 32);
|
|
47579
50215
|
assertBytes(ownerKey.salt, 32);
|
|
47580
50216
|
}
|
|
47581
|
-
function readRandomBytes(
|
|
47582
|
-
const value =
|
|
50217
|
+
function readRandomBytes(randomBytes7, length) {
|
|
50218
|
+
const value = randomBytes7(length);
|
|
47583
50219
|
if (!(value instanceof Uint8Array) || value.byteLength !== length) {
|
|
47584
50220
|
throw new BackupError("backup_invalid_input");
|
|
47585
50221
|
}
|
|
@@ -47602,7 +50238,7 @@ function isIsoUtcMilliseconds(value) {
|
|
|
47602
50238
|
return false;
|
|
47603
50239
|
}
|
|
47604
50240
|
}
|
|
47605
|
-
function
|
|
50241
|
+
function isRecord2(value) {
|
|
47606
50242
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
47607
50243
|
}
|
|
47608
50244
|
function hasExactKeys(value, expected) {
|
|
@@ -47610,225 +50246,6 @@ function hasExactKeys(value, expected) {
|
|
|
47610
50246
|
return keys.length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
47611
50247
|
}
|
|
47612
50248
|
|
|
47613
|
-
// src/agent-link.ts
|
|
47614
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
47615
|
-
import { mkdir as mkdir3, open as open3, stat as stat2, unlink as unlink2 } from "node:fs/promises";
|
|
47616
|
-
import { dirname as dirname2 } from "node:path";
|
|
47617
|
-
|
|
47618
|
-
// src/device.ts
|
|
47619
|
-
var DEVICE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
47620
|
-
|
|
47621
|
-
// src/agent-link.ts
|
|
47622
|
-
var AGENT_LINK_REVOKED_MESSAGE = "This agent's link was revoked or has expired. Run vapi login to link it again.";
|
|
47623
|
-
var AgentLinkError = class extends Error {
|
|
47624
|
-
constructor(code, message) {
|
|
47625
|
-
super(message);
|
|
47626
|
-
this.code = code;
|
|
47627
|
-
this.name = "AgentLinkError";
|
|
47628
|
-
}
|
|
47629
|
-
code;
|
|
47630
|
-
};
|
|
47631
|
-
var DEFAULT_AGENT_SCOPES = ["mcp:call", "router.use"];
|
|
47632
|
-
var ALLOWED_AGENT_SCOPES = /* @__PURE__ */ new Set([...DEFAULT_AGENT_SCOPES, "call.publish"]);
|
|
47633
|
-
var publicFetch = createPublicFetch({ allowPrivateNetwork: false });
|
|
47634
|
-
var agentSecretAccounts = (wallet) => ({
|
|
47635
|
-
tokens: `vapi.agent.${wallet}.tokens`,
|
|
47636
|
-
routerStake: `vapi.agent.${wallet}.router.stake`,
|
|
47637
|
-
routerBalance: `vapi.agent.${wallet}.router.balance`
|
|
47638
|
-
});
|
|
47639
|
-
async function agentFetch(args, url2, init) {
|
|
47640
|
-
const fetchImpl = args.fetchImpl ?? publicFetch;
|
|
47641
|
-
const accessToken = await resolveAgentAccessToken(args, {});
|
|
47642
|
-
const response = await safeAgentFetch(fetchImpl, url2, withBearer(init, accessToken));
|
|
47643
|
-
if (response.status !== 401) return response;
|
|
47644
|
-
const refreshedToken = await resolveAgentAccessToken(args, { rejectedAccessToken: accessToken });
|
|
47645
|
-
const refreshedResponse = await safeAgentFetch(fetchImpl, url2, withBearer(init, refreshedToken));
|
|
47646
|
-
if (refreshedResponse.status === 401) {
|
|
47647
|
-
throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
|
|
47648
|
-
}
|
|
47649
|
-
return refreshedResponse;
|
|
47650
|
-
}
|
|
47651
|
-
async function resolveAgentAccessToken(args, options) {
|
|
47652
|
-
await args.wallets.reload();
|
|
47653
|
-
const link2 = args.wallets.entry(args.wallet)?.link;
|
|
47654
|
-
if (link2 === void 0 || !args.secrets.available) throw notLinkedError();
|
|
47655
|
-
const accounts = agentSecretAccounts(args.wallet);
|
|
47656
|
-
const tokens = parseTokens(await safeGetSecret(args.secrets, accounts.tokens));
|
|
47657
|
-
if (tokens === void 0) throw notLinkedError();
|
|
47658
|
-
const now = args.now ?? Date.now;
|
|
47659
|
-
if (options.rejectedAccessToken === void 0 && tokens.expiresAt - 6e4 > now()) {
|
|
47660
|
-
return tokens.accessToken;
|
|
47661
|
-
}
|
|
47662
|
-
return await withAgentCredentialLock(args.wallets, link2.clientId, async () => {
|
|
47663
|
-
await args.wallets.reload();
|
|
47664
|
-
const currentLink = args.wallets.entry(args.wallet)?.link;
|
|
47665
|
-
if (currentLink === void 0) throw notLinkedError();
|
|
47666
|
-
const currentAccounts = agentSecretAccounts(args.wallet);
|
|
47667
|
-
const current = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
|
|
47668
|
-
if (current === void 0) throw notLinkedError();
|
|
47669
|
-
if (options.rejectedAccessToken !== void 0 && current.accessToken !== options.rejectedAccessToken) {
|
|
47670
|
-
return current.accessToken;
|
|
47671
|
-
}
|
|
47672
|
-
if (options.rejectedAccessToken === void 0 && current.expiresAt - 6e4 > now()) {
|
|
47673
|
-
return current.accessToken;
|
|
47674
|
-
}
|
|
47675
|
-
const response = await safeFetch(
|
|
47676
|
-
args.fetchImpl ?? publicFetch,
|
|
47677
|
-
apiEndpoint(currentLink.apiBase, "/oauth/token"),
|
|
47678
|
-
{
|
|
47679
|
-
method: "POST",
|
|
47680
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
47681
|
-
body: new URLSearchParams({
|
|
47682
|
-
grant_type: "refresh_token",
|
|
47683
|
-
refresh_token: current.refreshToken,
|
|
47684
|
-
client_id: currentLink.clientId
|
|
47685
|
-
})
|
|
47686
|
-
}
|
|
47687
|
-
);
|
|
47688
|
-
const payload = await responseRecord(response);
|
|
47689
|
-
if (!response.ok) {
|
|
47690
|
-
if (response.status === 400 && stringField(payload, "error") === "invalid_grant") {
|
|
47691
|
-
throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
|
|
47692
|
-
}
|
|
47693
|
-
throw httpError("The vAPI agent token refresh failed.");
|
|
47694
|
-
}
|
|
47695
|
-
const refreshed = {
|
|
47696
|
-
accessToken: requiredString(payload, "access_token"),
|
|
47697
|
-
refreshToken: stringField(payload, "refresh_token") ?? current.refreshToken,
|
|
47698
|
-
expiresAt: now() + requiredNumber(payload, "expires_in") * 1e3,
|
|
47699
|
-
scopes: stringField(payload, "scope") === void 0 ? [...current.scopes] : splitScopes(requiredString(payload, "scope"))
|
|
47700
|
-
};
|
|
47701
|
-
await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
|
|
47702
|
-
return refreshed.accessToken;
|
|
47703
|
-
});
|
|
47704
|
-
}
|
|
47705
|
-
async function withAgentCredentialLock(wallets, clientId, operation) {
|
|
47706
|
-
const digest = createHash2("sha256").update(clientId).digest("hex").slice(0, 24);
|
|
47707
|
-
const lockPath = `${wallets.registryPath}.${digest}.agent-link.lock`;
|
|
47708
|
-
await mkdir3(dirname2(lockPath), { recursive: true, mode: 448 });
|
|
47709
|
-
const deadline = Date.now() + 3e4;
|
|
47710
|
-
let handle;
|
|
47711
|
-
while (!handle) {
|
|
47712
|
-
try {
|
|
47713
|
-
handle = await open3(lockPath, "wx", 384);
|
|
47714
|
-
} catch (error61) {
|
|
47715
|
-
if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
|
|
47716
|
-
await removeStaleCredentialLock(lockPath);
|
|
47717
|
-
if (Date.now() >= deadline) {
|
|
47718
|
-
throw httpError("Timed out waiting to update the agent credentials.");
|
|
47719
|
-
}
|
|
47720
|
-
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
47721
|
-
}
|
|
47722
|
-
}
|
|
47723
|
-
try {
|
|
47724
|
-
return await operation();
|
|
47725
|
-
} finally {
|
|
47726
|
-
await handle.close();
|
|
47727
|
-
await unlink2(lockPath).catch(() => void 0);
|
|
47728
|
-
}
|
|
47729
|
-
}
|
|
47730
|
-
async function removeStaleCredentialLock(path) {
|
|
47731
|
-
try {
|
|
47732
|
-
const metadata = await stat2(path);
|
|
47733
|
-
if (Date.now() - metadata.mtimeMs > 5 * 6e4) await unlink2(path);
|
|
47734
|
-
} catch {
|
|
47735
|
-
}
|
|
47736
|
-
}
|
|
47737
|
-
async function safeGetSecret(secrets, account) {
|
|
47738
|
-
try {
|
|
47739
|
-
return await secrets.get(account);
|
|
47740
|
-
} catch {
|
|
47741
|
-
throw httpError("The agent tokens could not be read from the OS secret store.");
|
|
47742
|
-
}
|
|
47743
|
-
}
|
|
47744
|
-
async function safeSetSecret(secrets, account, value) {
|
|
47745
|
-
try {
|
|
47746
|
-
await secrets.set(account, value);
|
|
47747
|
-
} catch {
|
|
47748
|
-
throw httpError("The agent credentials could not be stored in the OS secret store.");
|
|
47749
|
-
}
|
|
47750
|
-
}
|
|
47751
|
-
function parseTokens(value) {
|
|
47752
|
-
if (value === void 0) return void 0;
|
|
47753
|
-
let parsed;
|
|
47754
|
-
try {
|
|
47755
|
-
parsed = JSON.parse(value);
|
|
47756
|
-
} catch {
|
|
47757
|
-
return void 0;
|
|
47758
|
-
}
|
|
47759
|
-
if (!isRecord2(parsed)) return void 0;
|
|
47760
|
-
const accessToken = stringField(parsed, "accessToken");
|
|
47761
|
-
const refreshToken = stringField(parsed, "refreshToken");
|
|
47762
|
-
const expiresAt = numberField(parsed, "expiresAt");
|
|
47763
|
-
const scopes = parsed.scopes;
|
|
47764
|
-
if (accessToken === void 0 || refreshToken === void 0 || expiresAt === void 0 || !Array.isArray(scopes) || scopes.some((scope) => typeof scope !== "string")) {
|
|
47765
|
-
return void 0;
|
|
47766
|
-
}
|
|
47767
|
-
return { accessToken, refreshToken, expiresAt, scopes };
|
|
47768
|
-
}
|
|
47769
|
-
function withBearer(init, accessToken) {
|
|
47770
|
-
const headers = new Headers(init?.headers);
|
|
47771
|
-
headers.set("authorization", `Bearer ${accessToken}`);
|
|
47772
|
-
return { ...init, headers };
|
|
47773
|
-
}
|
|
47774
|
-
async function safeFetch(fetchImpl, input2, init) {
|
|
47775
|
-
try {
|
|
47776
|
-
return await fetchImpl(input2, init);
|
|
47777
|
-
} catch {
|
|
47778
|
-
throw httpError("The vAPI agent link request failed.");
|
|
47779
|
-
}
|
|
47780
|
-
}
|
|
47781
|
-
async function safeAgentFetch(fetchImpl, input2, init) {
|
|
47782
|
-
try {
|
|
47783
|
-
return await fetchImpl(input2, init);
|
|
47784
|
-
} catch {
|
|
47785
|
-
throw httpError("The vAPI agent request failed.");
|
|
47786
|
-
}
|
|
47787
|
-
}
|
|
47788
|
-
function notLinkedError() {
|
|
47789
|
-
return new AgentLinkError("not_linked", "Run vapi login first.");
|
|
47790
|
-
}
|
|
47791
|
-
function httpError(message) {
|
|
47792
|
-
return new AgentLinkError("http", message);
|
|
47793
|
-
}
|
|
47794
|
-
function apiEndpoint(apiBase, path) {
|
|
47795
|
-
return new URL(path, new URL(apiBase).origin).toString();
|
|
47796
|
-
}
|
|
47797
|
-
async function responseRecord(response) {
|
|
47798
|
-
let payload;
|
|
47799
|
-
try {
|
|
47800
|
-
payload = await response.json();
|
|
47801
|
-
} catch {
|
|
47802
|
-
throw httpError("The vAPI agent link response was invalid.");
|
|
47803
|
-
}
|
|
47804
|
-
if (!isRecord2(payload)) throw httpError("The vAPI agent link response was invalid.");
|
|
47805
|
-
return payload;
|
|
47806
|
-
}
|
|
47807
|
-
function isRecord2(value) {
|
|
47808
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
47809
|
-
}
|
|
47810
|
-
function stringField(record2, key) {
|
|
47811
|
-
const value = record2[key];
|
|
47812
|
-
return typeof value === "string" ? value : void 0;
|
|
47813
|
-
}
|
|
47814
|
-
function numberField(record2, key) {
|
|
47815
|
-
const value = record2[key];
|
|
47816
|
-
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
47817
|
-
}
|
|
47818
|
-
function requiredString(record2, key) {
|
|
47819
|
-
const value = stringField(record2, key);
|
|
47820
|
-
if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
|
|
47821
|
-
return value;
|
|
47822
|
-
}
|
|
47823
|
-
function requiredNumber(record2, key) {
|
|
47824
|
-
const value = numberField(record2, key);
|
|
47825
|
-
if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
|
|
47826
|
-
return value;
|
|
47827
|
-
}
|
|
47828
|
-
function splitScopes(scope) {
|
|
47829
|
-
return scope.split(/\s+/u).filter(Boolean);
|
|
47830
|
-
}
|
|
47831
|
-
|
|
47832
50249
|
// src/cloud-backup.ts
|
|
47833
50250
|
var ERROR_MESSAGES2 = {
|
|
47834
50251
|
relay_create_failed: "The backup approval request could not be started. Try again.",
|
|
@@ -47854,8 +50271,8 @@ var RELAY_PAYLOAD_FORMAT = "vapi-vault-relay-payload";
|
|
|
47854
50271
|
var OWNER_PATTERN = /^0x[0-9a-f]{40}$/u;
|
|
47855
50272
|
var BASE64URL_PATTERN2 = /^[A-Za-z0-9_-]*$/u;
|
|
47856
50273
|
var ISO_UTC_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
|
|
47857
|
-
var
|
|
47858
|
-
var
|
|
50274
|
+
var HKDF_KEYS2 = ["name", "salt"];
|
|
50275
|
+
var SCRYPT_KEYS2 = ["name", "salt", "N", "r", "p"];
|
|
47859
50276
|
var ENROLL_PAYLOAD_KEYS = ["format", "v", "purpose", "owner", "device", "kdf", "key"];
|
|
47860
50277
|
var RESTORE_PAYLOAD_KEYS = [...ENROLL_PAYLOAD_KEYS, "vault"];
|
|
47861
50278
|
var STORED_KEY_KEYS = ["owner", "device", "kdf", "key"];
|
|
@@ -48037,7 +50454,7 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48037
50454
|
try {
|
|
48038
50455
|
let vaultFile;
|
|
48039
50456
|
try {
|
|
48040
|
-
vaultFile = await readVaultFileUnlocked(
|
|
50457
|
+
vaultFile = await readVaultFileUnlocked(join9(options.store.home, "vault.json"));
|
|
48041
50458
|
} catch (error61) {
|
|
48042
50459
|
if (error61 instanceof VaultError && error61.code === "not_found") {
|
|
48043
50460
|
return { status: "skipped", reason: "no_vault" };
|
|
@@ -48046,7 +50463,7 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48046
50463
|
}
|
|
48047
50464
|
try {
|
|
48048
50465
|
vaultKey = vaultFile.protected ? await unlockProtectedVault({
|
|
48049
|
-
path:
|
|
50466
|
+
path: join9(options.store.home, "vault.json"),
|
|
48050
50467
|
secrets: options.secrets,
|
|
48051
50468
|
env: options.env,
|
|
48052
50469
|
...options.now === void 0 ? {} : { now: options.now }
|
|
@@ -48057,7 +50474,8 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48057
50474
|
const source = await exportBackupSource({
|
|
48058
50475
|
store: options.store,
|
|
48059
50476
|
vaultKey,
|
|
48060
|
-
...options.networks === void 0 ? {} : { networks: options.networks }
|
|
50477
|
+
...options.networks === void 0 ? {} : { networks: options.networks },
|
|
50478
|
+
...options.agentProfileSchema === void 0 ? {} : { agentProfileSchema: options.agentProfileSchema }
|
|
48061
50479
|
});
|
|
48062
50480
|
salt = decodeBase64Url2(stored.kdf.salt);
|
|
48063
50481
|
if (salt?.byteLength !== 32) return { status: "skipped", reason: "rejected" };
|
|
@@ -48080,8 +50498,8 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48080
50498
|
`wallet:${selected.name}`,
|
|
48081
50499
|
async () => {
|
|
48082
50500
|
await options.store.reload();
|
|
48083
|
-
const
|
|
48084
|
-
if (!linkMatches(
|
|
50501
|
+
const link3 = options.store.entry(selected.name)?.link;
|
|
50502
|
+
if (!linkMatches(link3, stored.owner, options.apiBase)) {
|
|
48085
50503
|
throw new AgentLinkError("not_linked", "Run vapi login first.");
|
|
48086
50504
|
}
|
|
48087
50505
|
return await agentFetch(
|
|
@@ -48092,7 +50510,7 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48092
50510
|
...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
|
|
48093
50511
|
...now === void 0 ? {} : { now: () => now().getTime() }
|
|
48094
50512
|
},
|
|
48095
|
-
apiEndpoint2(
|
|
50513
|
+
apiEndpoint2(link3.apiBase, "/api/agents/self/backup"),
|
|
48096
50514
|
{
|
|
48097
50515
|
method: "PUT",
|
|
48098
50516
|
headers: { "content-type": "application/json" },
|
|
@@ -48122,13 +50540,18 @@ async function uploadBackupLocked(options, signal) {
|
|
|
48122
50540
|
status: "uploaded",
|
|
48123
50541
|
account: selected.name,
|
|
48124
50542
|
bytes: created.bytes,
|
|
48125
|
-
uploadedAt
|
|
50543
|
+
uploadedAt,
|
|
50544
|
+
...created.omitted === void 0 ? {} : { omitted: created.omitted },
|
|
50545
|
+
...source.skipped === void 0 ? {} : { skipped: source.skipped }
|
|
48126
50546
|
};
|
|
48127
50547
|
} catch (error61) {
|
|
48128
50548
|
if (signal.aborted) return { status: "skipped", reason: "timeout" };
|
|
48129
50549
|
if (error61 instanceof AgentLinkError && error61.code === "not_linked") {
|
|
48130
50550
|
return { status: "skipped", reason: "not_linked" };
|
|
48131
50551
|
}
|
|
50552
|
+
if (error61 instanceof BackupError && error61.code === "backup_snapshot_busy") {
|
|
50553
|
+
return { status: "skipped", reason: "snapshot_busy" };
|
|
50554
|
+
}
|
|
48132
50555
|
return { status: "skipped", reason: "rejected" };
|
|
48133
50556
|
} finally {
|
|
48134
50557
|
vaultKey?.fill(0);
|
|
@@ -48146,6 +50569,7 @@ async function restoreFromOwner(options) {
|
|
|
48146
50569
|
plaintext: options.payload.vault,
|
|
48147
50570
|
home: options.home,
|
|
48148
50571
|
vaultKey: options.vaultKey,
|
|
50572
|
+
device: options.payload.device,
|
|
48149
50573
|
...options.now === void 0 ? {} : { now: options.now },
|
|
48150
50574
|
beforePublish: async ({ vault }) => {
|
|
48151
50575
|
if (options.payload.vault?.protected === true) {
|
|
@@ -48216,7 +50640,7 @@ function parseRelayPayload(value) {
|
|
|
48216
50640
|
if (!hasExactKeys2(value, expectedKeys) || value.format !== RELAY_PAYLOAD_FORMAT || value.v !== 1 || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord3(value.kdf) || typeof value.key !== "string") {
|
|
48217
50641
|
throw new CloudBackupError("payload_invalid");
|
|
48218
50642
|
}
|
|
48219
|
-
const kdf =
|
|
50643
|
+
const kdf = parseKdf2(value.kdf);
|
|
48220
50644
|
const key = decodeBase64Url2(value.key);
|
|
48221
50645
|
if (kdf === void 0 || key?.byteLength !== 32) {
|
|
48222
50646
|
key?.fill(0);
|
|
@@ -48246,7 +50670,7 @@ function parseStoredBackupKey(value) {
|
|
|
48246
50670
|
if (!isRecord3(value) || !hasExactKeys2(value, STORED_KEY_KEYS) || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord3(value.kdf) || typeof value.key !== "string") {
|
|
48247
50671
|
return void 0;
|
|
48248
50672
|
}
|
|
48249
|
-
const kdf =
|
|
50673
|
+
const kdf = parseKdf2(value.kdf);
|
|
48250
50674
|
const key = decodeBase64Url2(value.key);
|
|
48251
50675
|
if (kdf === void 0 || key?.byteLength !== 32) {
|
|
48252
50676
|
key?.fill(0);
|
|
@@ -48256,11 +50680,11 @@ function parseStoredBackupKey(value) {
|
|
|
48256
50680
|
key.fill(0);
|
|
48257
50681
|
return { owner: value.owner, device: value.device, kdf, key: copiedKey };
|
|
48258
50682
|
}
|
|
48259
|
-
function
|
|
48260
|
-
if (value.name === "hkdf-sha256" && hasExactKeys2(value,
|
|
50683
|
+
function parseKdf2(value) {
|
|
50684
|
+
if (value.name === "hkdf-sha256" && hasExactKeys2(value, HKDF_KEYS2) && typeof value.salt === "string" && isBase64UrlBytes(value.salt, 32)) {
|
|
48261
50685
|
return { name: "hkdf-sha256", salt: value.salt };
|
|
48262
50686
|
}
|
|
48263
|
-
if (value.name === "scrypt" && hasExactKeys2(value,
|
|
50687
|
+
if (value.name === "scrypt" && hasExactKeys2(value, SCRYPT_KEYS2) && typeof value.salt === "string" && isBase64UrlBytes(value.salt, 32) && value.N === 131072 && value.r === 8 && value.p === 1) {
|
|
48264
50688
|
return { name: "scrypt", salt: value.salt, N: 131072, r: 8, p: 1 };
|
|
48265
50689
|
}
|
|
48266
50690
|
return void 0;
|
|
@@ -48295,11 +50719,11 @@ async function selectLinkedAccount(options, owner) {
|
|
|
48295
50719
|
}
|
|
48296
50720
|
return void 0;
|
|
48297
50721
|
}
|
|
48298
|
-
function linkMatches(
|
|
48299
|
-
if (
|
|
50722
|
+
function linkMatches(link3, owner, apiBase) {
|
|
50723
|
+
if (link3 === void 0 || link3.owner.toLowerCase() !== owner.toLowerCase()) return false;
|
|
48300
50724
|
if (apiBase === void 0) return true;
|
|
48301
50725
|
try {
|
|
48302
|
-
return new URL(
|
|
50726
|
+
return new URL(link3.apiBase).origin === new URL(apiBase).origin;
|
|
48303
50727
|
} catch {
|
|
48304
50728
|
return false;
|
|
48305
50729
|
}
|
|
@@ -48391,6 +50815,7 @@ export {
|
|
|
48391
50815
|
awaitRelay,
|
|
48392
50816
|
backupKeyAccount,
|
|
48393
50817
|
backupStateAccount,
|
|
50818
|
+
buildRelayRestorePayload,
|
|
48394
50819
|
forgetBackupKey,
|
|
48395
50820
|
readBackupKey,
|
|
48396
50821
|
readCloudBackupState,
|