@glyphteck/veyl 0.50.0 → 0.51.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/cli.js CHANGED
@@ -236,7 +236,7 @@ function randomBytes(bytesLength = 32) {
236
236
  throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
237
237
  return cr.getRandomValues(new Uint8Array(bytesLength));
238
238
  }
239
- var isLE, swap8IfBE, swap32IfBE, hasHexBuiltin, hexes, asciis, nextTick = async () => {}, oidNist = (suffix) => ({
239
+ var isLE, swap8IfBE, swap32IfBE, hasHexBuiltin, hexes, asciis, oidNist = (suffix) => ({
240
240
  oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
241
241
  });
242
242
  var init_utils = __esm(() => {
@@ -8447,6 +8447,7 @@ async function openVaultAccountSession(vault, password, options = {}) {
8447
8447
  onSettingsUnlocked,
8448
8448
  onSeedDecrypted,
8449
8449
  onStage,
8450
+ masterSeed: suppliedMasterSeed = null,
8450
8451
  isCurrent = () => true,
8451
8452
  diag = null
8452
8453
  } = options;
@@ -8513,10 +8514,17 @@ async function openVaultAccountSession(vault, password, options = {}) {
8513
8514
  onStage?.("decrypting");
8514
8515
  const decryptStartedAt = Date.now();
8515
8516
  mark(diag, "vault.unlock.decrypt.start", { source });
8516
- try {
8517
- masterSeed = await decryptSeed2(ct, salt, iv, normalizePassword(password), kdf);
8518
- } catch (error) {
8519
- throw vaultPasswordError(error);
8517
+ if (suppliedMasterSeed) {
8518
+ if (!(suppliedMasterSeed instanceof Uint8Array) || suppliedMasterSeed.length !== 32) {
8519
+ throw new Error("vault master seed required");
8520
+ }
8521
+ masterSeed = suppliedMasterSeed.slice();
8522
+ } else {
8523
+ try {
8524
+ masterSeed = await decryptSeed2(ct, salt, iv, normalizePassword(password), kdf);
8525
+ } catch (error) {
8526
+ throw vaultPasswordError(error);
8527
+ }
8520
8528
  }
8521
8529
  mark(diag, "vault.unlock.decrypt.done", { elapsedMs: Date.now() - decryptStartedAt, source });
8522
8530
  onStage?.("seed-decrypted");
@@ -14550,6 +14558,16 @@ function createChatDelete({
14550
14558
  }
14551
14559
  return [...byId.values()];
14552
14560
  };
14561
+ const revokeTargetDeliveries = async (targets) => {
14562
+ const capabilities = targets.filter((target) => target.deliveryRegistered && target.linkId && target.peerChatPK && chatPK && notificationPrivateKey).map((target) => deriveInboundDeliveryCapability(notificationPrivateKey, {
14563
+ linkId: target.linkId,
14564
+ chatId: target.chatId,
14565
+ selfChatPK: chatPK,
14566
+ peerChatPK: target.peerChatPK
14567
+ }));
14568
+ await Promise.all(capabilities.map((capability) => cloud.delivery.revoke(capability)));
14569
+ return capabilities.length;
14570
+ };
14553
14571
  const deleteChat = async (chat, options = {}) => {
14554
14572
  const targets = getDeleteTargets(chat);
14555
14573
  if (!targets.length)
@@ -14563,13 +14581,8 @@ function createChatDelete({
14563
14581
  try {
14564
14582
  hideDeletingChats(chatIds, options);
14565
14583
  try {
14566
- const capabilities = targets.filter((target) => target.deliveryRegistered && target.linkId && target.peerChatPK && chatPK && notificationPrivateKey).map((target) => deriveInboundDeliveryCapability(notificationPrivateKey, {
14567
- linkId: target.linkId,
14568
- chatId: target.chatId,
14569
- selfChatPK: chatPK,
14570
- peerChatPK: target.peerChatPK
14571
- }));
14572
- await Promise.all(capabilities.map((capability) => cloud.delivery.revoke(capability)));
14584
+ await revokeTargetDeliveries(targets);
14585
+ await options.onDeliveryRevoked?.();
14573
14586
  await cloud.chat.delete(targets, { cleanup: options.cleanup !== false });
14574
14587
  confirmDeletedChats(chatIds);
14575
14588
  } catch (error) {
@@ -22629,16 +22642,18 @@ function createChatSession({
22629
22642
  const dropChat = (...args) => deleteActions.dropChat(...args);
22630
22643
  const dropUnavailableChat = (...args) => deleteActions.dropUnavailableChat(...args);
22631
22644
  const deleteChat = (...args) => deleteActions.deleteChat(...args);
22632
- const retirePeerChat = async (peerChatPK) => {
22645
+ const retirePeerChat = async (peerChatPK, options = {}) => {
22633
22646
  const sendOptions = sendOptionsForPeer(peerChatPK);
22634
- if (!sendOptions?.chatId)
22647
+ if (!sendOptions?.chatId) {
22648
+ await options.onDeliveryRevoked?.();
22635
22649
  return false;
22650
+ }
22636
22651
  const chat = sendOptions.ownEntry || getChatEntry(sendOptions.chatId) || {
22637
22652
  id: sendOptions.chatId,
22638
22653
  linkId: sendOptions.linkId,
22639
22654
  peerChatPK
22640
22655
  };
22641
- return deleteChat(chat, { cleanup: false });
22656
+ return deleteChat(chat, { ...options, cleanup: false });
22642
22657
  };
22643
22658
  const restoreDeletedChat = (...args) => deleteActions.restoreDeletedChat(...args);
22644
22659
  const wasChatDeletedLocally = (...args) => deleteActions.wasChatDeletedLocally(...args);
@@ -25079,11 +25094,13 @@ function getReportAttachmentMeta(msg) {
25079
25094
  mimeType: cleanText(msg?.m) || reportAttachmentMime(kind)
25080
25095
  };
25081
25096
  }
25082
- function buildReportFields({ msg, note } = {}) {
25097
+ function buildReportFields({ msg, note, chatId } = {}) {
25083
25098
  const type = cleanText(msg?.t);
25084
25099
  const content = type === "txt" ? cleanText(msg?.c) : "";
25085
25100
  const cleanedNote = cleanText(note);
25086
25101
  const report = {};
25102
+ const sourceChatId = cleanText(chatId);
25103
+ const sourceMessageId = cleanText(msg?.cid) || cleanText(msg?.actionId) || cleanText(msg?.id);
25087
25104
  if (type) {
25088
25105
  report.type = type;
25089
25106
  }
@@ -25093,6 +25110,13 @@ function buildReportFields({ msg, note } = {}) {
25093
25110
  if (cleanedNote) {
25094
25111
  report.note = cleanedNote;
25095
25112
  }
25113
+ if (type) {
25114
+ if (!sourceChatId || !sourceMessageId) {
25115
+ throw new Error("message report source required");
25116
+ }
25117
+ report.chatId = sourceChatId;
25118
+ report.messageId = sourceMessageId;
25119
+ }
25096
25120
  return report;
25097
25121
  }
25098
25122
  var init_report = () => {};
@@ -25191,7 +25215,7 @@ function openSupport({ cloud, getUid } = {}) {
25191
25215
  }
25192
25216
  await cloud.reports.submit({
25193
25217
  uid,
25194
- ...buildReportFields({ msg: message, note: options.note }),
25218
+ ...buildReportFields({ msg: message, note: options.note, chatId: options.chatId }),
25195
25219
  ...path ? { path } : {}
25196
25220
  });
25197
25221
  return { submitted: true, attachmentIncluded: !!path };
@@ -31472,6 +31496,7 @@ function openAccount(options = {}) {
31472
31496
  },
31473
31497
  onSeedDecrypted: unlockOptions.onSeedDecrypted,
31474
31498
  onStage: (stage) => setStage(stage, unlockOptions.onStage),
31499
+ masterSeed: unlockOptions.masterSeed,
31475
31500
  isCurrent,
31476
31501
  diag
31477
31502
  });
@@ -32495,6 +32520,9 @@ async function listenAccount(client, options = {}) {
32495
32520
  const processedWakeVersions = new Map;
32496
32521
  const wantedWakeVersions = new Map;
32497
32522
  let activeChatIds = new Set;
32523
+ let chatSyncRequested = false;
32524
+ let chatSyncEmit = false;
32525
+ let chatSyncTask = Promise.resolve();
32498
32526
  let ready = false;
32499
32527
  let closed = false;
32500
32528
  function clearChatActivityTimer(chatId) {
@@ -32723,6 +32751,21 @@ async function listenAccount(client, options = {}) {
32723
32751
  }
32724
32752
  await Promise.all(chats.map((chat) => attachChat(chat, emitInitial)));
32725
32753
  }
32754
+ function requestChatSync(emitInitial = ready) {
32755
+ if (!includeChats || closed)
32756
+ return chatSyncTask;
32757
+ chatSyncRequested = true;
32758
+ chatSyncEmit ||= emitInitial;
32759
+ chatSyncTask = chatSyncTask.catch(() => {}).then(async () => {
32760
+ while (chatSyncRequested && !closed) {
32761
+ const emitChanges = chatSyncEmit;
32762
+ chatSyncRequested = false;
32763
+ chatSyncEmit = false;
32764
+ await syncChats(emitChanges);
32765
+ }
32766
+ });
32767
+ return chatSyncTask;
32768
+ }
32726
32769
  function applyTransfers(emitChanges) {
32727
32770
  if (!includeTransactions)
32728
32771
  return;
@@ -32749,7 +32792,9 @@ async function listenAccount(client, options = {}) {
32749
32792
  applyTransfers(replay);
32750
32793
  };
32751
32794
  try {
32752
- await syncChats(replay);
32795
+ if (includeChats) {
32796
+ await client.runtimeChat.list({ count: 1 });
32797
+ }
32753
32798
  if (stopped(options.signal))
32754
32799
  return;
32755
32800
  if (includeTransactions) {
@@ -32760,11 +32805,14 @@ async function listenAccount(client, options = {}) {
32760
32805
  unsubscribeWallet = runtime.wallet.subscribe(syncTransactionHistory);
32761
32806
  syncTransactionHistory();
32762
32807
  }
32763
- ready = true;
32764
- emit(event("ready", { account: compact2 ? compactAccount(account) : account }));
32765
32808
  unsubscribeChatList = includeChats ? runtime.chat.subscribe(() => {
32766
- syncChats(true).catch((error) => emit(event("error", { message: error?.message || String(error) })));
32809
+ requestChatSync(true).catch((error) => emit(event("error", { message: error?.message || String(error) })));
32767
32810
  }) : () => {};
32811
+ ready = true;
32812
+ emit(event("ready", { account: compact2 ? compactAccount(account) : account }));
32813
+ requestChatSync(replay).catch((error) => emit(event("error", {
32814
+ message: error?.message || String(error)
32815
+ })));
32768
32816
  if (!stopped(options.signal)) {
32769
32817
  await new Promise((resolve) => options.signal?.addEventListener?.("abort", resolve, { once: true }));
32770
32818
  }
@@ -33272,11 +33320,12 @@ function createRuntimeProductActions({
33272
33320
  if (peer.uid === user.uid)
33273
33321
  throw new Error("cannot block self");
33274
33322
  const chatSnapshot = runtime.chat.getSnapshot();
33275
- await user.blockPeer(peer);
33276
33323
  try {
33277
- await chatSnapshot.retirePeerChat(peer.chatPK);
33324
+ await chatSnapshot.retirePeerChat(peer.chatPK, {
33325
+ onDeliveryRevoked: () => user.blockPeer(peer)
33326
+ });
33278
33327
  } catch (error) {
33279
- throw new Error(`user blocked, but chat cleanup failed: ${error?.message || error}`, { cause: error });
33328
+ throw new Error(`block failed during private route retirement: ${error?.message || error}`, { cause: error });
33280
33329
  }
33281
33330
  runtime.peers.getSnapshot().dropPeer(peer);
33282
33331
  return { blocked: true, peer: publicPeer({ ...peer, blocked: true }) };
@@ -33340,9 +33389,11 @@ function createRuntimeProductActions({
33340
33389
  throw new Error("report target uid required");
33341
33390
  let message = null;
33342
33391
  let attachmentBytes2 = null;
33392
+ let sourceChatId = "";
33343
33393
  if (options.messageId) {
33344
33394
  const target = await chat.messageForPeer(peer.chatPK, options.messageId, { count: 100 });
33345
33395
  message = target.message;
33396
+ sourceChatId = target.chat.id;
33346
33397
  const attachment = getReportAttachmentMeta(message);
33347
33398
  if (attachment) {
33348
33399
  attachmentBytes2 = await target.runtime.chat.getSnapshot().readMessageFile(peer.chatPK, message);
@@ -33351,7 +33402,8 @@ function createRuntimeProductActions({
33351
33402
  const result = await supportOwner.report(peer.uid, {
33352
33403
  message,
33353
33404
  note: options.note,
33354
- attachmentBytes: attachmentBytes2
33405
+ attachmentBytes: attachmentBytes2,
33406
+ ...message ? { chatId: sourceChatId } : {}
33355
33407
  });
33356
33408
  return { ...result, peer: publicPeer(peer) };
33357
33409
  }
@@ -41108,7 +41160,7 @@ var package_default;
41108
41160
  var init_package = __esm(() => {
41109
41161
  package_default = {
41110
41162
  name: "veyl",
41111
- version: "0.50.0",
41163
+ version: "0.51.0",
41112
41164
  private: true,
41113
41165
  license: "Apache-2.0",
41114
41166
  workspaces: {
@@ -41365,10 +41417,10 @@ class AccountRuntime {
41365
41417
  });
41366
41418
  this.runtimeMoney = createRuntimeMoneyActions({
41367
41419
  getRuntime: async () => {
41368
- await this.ensureUnlocked();
41420
+ await this.ensureWalletReady();
41369
41421
  return this.runtime;
41370
41422
  },
41371
- getSession: () => this.ensureUnlocked(),
41423
+ getSession: () => this.ensureWalletReady(),
41372
41424
  resolvePeer: (peer, resolveOptions) => this.resolvePeer(peer, resolveOptions),
41373
41425
  chat: this.runtimeChat
41374
41426
  });
@@ -41788,17 +41840,21 @@ class AccountRuntime {
41788
41840
  this.accountOwner.setNetwork(defaultNetwork);
41789
41841
  await this.ensureUserState();
41790
41842
  let opened;
41843
+ let masterSeed = null;
41791
41844
  try {
41845
+ masterSeed = await this.options.getVaultMasterSeed?.() || null;
41792
41846
  opened = await this.accountOwner.unlock(vaultSecret, {
41793
41847
  vault,
41794
- source: "sdk"
41848
+ source: "sdk",
41849
+ masterSeed
41795
41850
  });
41796
- await opened.walletReady;
41797
41851
  this.userSnapshot = this.userOwner.getSnapshot();
41798
41852
  } catch (error) {
41799
41853
  if (opened)
41800
41854
  this.accountOwner.lock();
41801
41855
  throw error;
41856
+ } finally {
41857
+ cleanBytes(masterSeed);
41802
41858
  }
41803
41859
  this.session = Object.assign(opened, {
41804
41860
  uid: profile.uid,
@@ -41810,6 +41866,23 @@ class AccountRuntime {
41810
41866
  this.startRuntimeOwners();
41811
41867
  return this.session;
41812
41868
  }
41869
+ trackWalletIdentity(session) {
41870
+ session.walletReady.then(async ({ walletPK }) => {
41871
+ if (this.session !== session || session.closed)
41872
+ return;
41873
+ const profile = this.profileData;
41874
+ if (!profile || profile.walletPK === walletPK)
41875
+ return;
41876
+ const next = await this.saveProfile({
41877
+ ...profile,
41878
+ network: session.network,
41879
+ walletPK
41880
+ });
41881
+ if (this.session === session && !session.closed) {
41882
+ session.account = this.accountSummary(next);
41883
+ }
41884
+ }).catch(() => {});
41885
+ }
41813
41886
  async createVault(options = {}) {
41814
41887
  const profile = await this.ensureAuth();
41815
41888
  if (await this.cloud.user.vault.exists(profile.uid)) {
@@ -41834,6 +41907,7 @@ class AccountRuntime {
41834
41907
  vaultCreatedAt: Date.now()
41835
41908
  });
41836
41909
  this.session.account = this.accountSummary(next);
41910
+ this.trackWalletIdentity(session);
41837
41911
  return {
41838
41912
  ...this.accountSummary(next),
41839
41913
  vaultSecret
@@ -41873,11 +41947,12 @@ class AccountRuntime {
41873
41947
  hasVault: true,
41874
41948
  vaultSecret: options.saveSecret === false ? profile.vaultSecret || null : profile.vaultSecret || vaultSecret,
41875
41949
  network: session.network,
41876
- walletPK: session.walletPK,
41950
+ walletPK: session.walletPK || profile.walletPK || null,
41877
41951
  chatPK: session.chatPK,
41878
41952
  lastUnlockedAt: Date.now()
41879
41953
  });
41880
41954
  this.session.account = this.accountSummary(next);
41955
+ this.trackWalletIdentity(session);
41881
41956
  return this.accountSummary(next);
41882
41957
  }
41883
41958
  closeVaultSession() {
@@ -41912,6 +41987,15 @@ class AccountRuntime {
41912
41987
  }
41913
41988
  return this.session;
41914
41989
  }
41990
+ async ensureWalletReady() {
41991
+ const session = await this.ensureUnlocked();
41992
+ if (!session.wallet)
41993
+ await session.walletReady;
41994
+ if (this.session !== session || session.closed || !session.wallet) {
41995
+ throw new Error("account changed during wallet boot");
41996
+ }
41997
+ return session;
41998
+ }
41915
41999
  async resolvePeer(peer, options = {}) {
41916
42000
  await this.ensureUnlocked();
41917
42001
  const value = cleanPeer(peer);
@@ -42100,6 +42184,7 @@ var API_VERSION = 3, REQUIRED_FUNCTION_PORTS;
42100
42184
  var init_client = __esm(() => {
42101
42185
  init_values();
42102
42186
  init_pack();
42187
+ init_core();
42103
42188
  init_agreement();
42104
42189
  init_network();
42105
42190
  init_username();
@@ -56656,7 +56741,7 @@ async function asyncLoop(iters, tick, cb) {
56656
56741
  const diff = Date.now() - ts;
56657
56742
  if (diff >= 0 && diff < tick)
56658
56743
  continue;
56659
- await nextTick2();
56744
+ await nextTick();
56660
56745
  ts += diff;
56661
56746
  }
56662
56747
  }
@@ -56718,7 +56803,7 @@ function randomBytes5(bytesLength = 32) {
56718
56803
  }
56719
56804
  throw new Error("crypto.getRandomValues must be defined");
56720
56805
  }
56721
- var hasHexBuiltin3, hexes2, asciis2, nextTick2 = async () => {};
56806
+ var hasHexBuiltin3, hexes2, asciis2, nextTick = async () => {};
56722
56807
  var init_utils4 = __esm(() => {
56723
56808
  init_cryptoNode();
56724
56809
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
@@ -158250,9 +158335,6 @@ function isFirestoreValue(obj) {
158250
158335
  }
158251
158336
  return false;
158252
158337
  }
158253
- function deleteField() {
158254
- return new DeleteFieldValueImpl("deleteField");
158255
- }
158256
158338
  function serverTimestamp() {
158257
158339
  return new ServerTimestampFieldValueImpl("serverTimestamp");
158258
158340
  }
@@ -176621,7 +176703,9 @@ function createFirebaseCloud({ db, auth: auth2, getAuth: getAuth2, functions: fu
176621
176703
  await callFunction("setAvatarModeration", { uid, banned: true });
176622
176704
  return true;
176623
176705
  }
176624
- await setDoc(doc(db, "moderation", uid), { banned: { [feature]: { until: null } } }, { merge: true });
176706
+ if (feature !== "chat")
176707
+ throw new Error("unsupported moderation feature");
176708
+ await callFunction("setChatModeration", { uid, banned: true });
176625
176709
  return true;
176626
176710
  }
176627
176711
  async function unbanAdminUser(uid, feature = "chat") {
@@ -176630,7 +176714,9 @@ function createFirebaseCloud({ db, auth: auth2, getAuth: getAuth2, functions: fu
176630
176714
  await callFunction("setAvatarModeration", { uid, banned: false });
176631
176715
  return true;
176632
176716
  }
176633
- await setDoc(doc(db, "moderation", uid), { banned: { [feature]: deleteField() } }, { merge: true });
176717
+ if (feature !== "chat")
176718
+ throw new Error("unsupported moderation feature");
176719
+ await callFunction("setChatModeration", { uid, banned: false });
176634
176720
  return true;
176635
176721
  }
176636
176722
  async function readAdminUserMetrics() {
@@ -176644,6 +176730,12 @@ function createFirebaseCloud({ db, auth: auth2, getAuth: getAuth2, functions: fu
176644
176730
  throw new Error("createFirebaseCloud requires storage");
176645
176731
  return getDownloadURL(ref2(targetStorage, path));
176646
176732
  }
176733
+ async function deleteAdminReportedChat(uid, reportId) {
176734
+ requireUid(uid);
176735
+ if (!reportId)
176736
+ throw new Error("report id required");
176737
+ return callFunction("deleteReportedChat", { uid, reportId });
176738
+ }
176647
176739
  return {
176648
176740
  user: {
176649
176741
  vault: {
@@ -176769,6 +176861,7 @@ function createFirebaseCloud({ db, auth: auth2, getAuth: getAuth2, functions: fu
176769
176861
  reports: {
176770
176862
  watchOffenders: watchAdminReportOffenders,
176771
176863
  watchUser: watchAdminUserReports,
176864
+ deleteChat: deleteAdminReportedChat,
176772
176865
  evidence: {
176773
176866
  path: adminReportEvidencePath
176774
176867
  }
@@ -176869,983 +176962,142 @@ var init_cloud2 = __esm(() => {
176869
176962
  init_config3();
176870
176963
  });
176871
176964
 
176872
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/_blake.js
176873
- function G1s(a, b, c, d, x) {
176874
- a = a + b + x | 0;
176875
- d = rotr(d ^ a, 16);
176876
- c = c + d | 0;
176877
- b = rotr(b ^ c, 12);
176878
- return { a, b, c, d };
176879
- }
176880
- function G2s(a, b, c, d, x) {
176881
- a = a + b + x | 0;
176882
- d = rotr(d ^ a, 8);
176883
- c = c + d | 0;
176884
- b = rotr(b ^ c, 7);
176885
- return { a, b, c, d };
176965
+ // src/runtime/kdf-worker.js
176966
+ import { availableParallelism } from "node:os";
176967
+ import { Worker } from "node:worker_threads";
176968
+ function positiveInteger(value, fallback) {
176969
+ const number = Math.floor(Number(value));
176970
+ return Number.isFinite(number) && number > 0 ? number : fallback;
176971
+ }
176972
+ function defaultVaultKdfWorkers(options2 = {}) {
176973
+ const parallelism = positiveInteger(options2.parallelism, availableParallelism());
176974
+ const memoryBudgetKib = positiveInteger(options2.memoryBudgetKib, DEFAULT_KDF_MEMORY_BUDGET_KIB);
176975
+ const perWorkerKib = positiveInteger(options2.memoryKib, KDF_MEMORY_KIB);
176976
+ return Math.max(1, Math.min(Math.ceil(parallelism / 2), Math.floor(memoryBudgetKib / perWorkerKib)));
176977
+ }
176978
+ function workerError(details = {}) {
176979
+ const error = new Error(details.message || "vault KDF failed");
176980
+ error.name = details.name || "Error";
176981
+ error.code = details.code || "";
176982
+ return error;
176886
176983
  }
176887
- var BSIGMA;
176888
- var init__blake = __esm(() => {
176889
- init_utils();
176890
- BSIGMA = /* @__PURE__ */ Uint8Array.from([
176891
- 0,
176892
- 1,
176893
- 2,
176894
- 3,
176895
- 4,
176896
- 5,
176897
- 6,
176898
- 7,
176899
- 8,
176900
- 9,
176901
- 10,
176902
- 11,
176903
- 12,
176904
- 13,
176905
- 14,
176906
- 15,
176907
- 14,
176908
- 10,
176909
- 4,
176910
- 8,
176911
- 9,
176912
- 15,
176913
- 13,
176914
- 6,
176915
- 1,
176916
- 12,
176917
- 0,
176918
- 2,
176919
- 11,
176920
- 7,
176921
- 5,
176922
- 3,
176923
- 11,
176924
- 8,
176925
- 12,
176926
- 0,
176927
- 5,
176928
- 2,
176929
- 15,
176930
- 13,
176931
- 10,
176932
- 14,
176933
- 3,
176934
- 6,
176935
- 7,
176936
- 1,
176937
- 9,
176938
- 4,
176939
- 7,
176940
- 9,
176941
- 3,
176942
- 1,
176943
- 13,
176944
- 12,
176945
- 11,
176946
- 14,
176947
- 2,
176948
- 6,
176949
- 5,
176950
- 10,
176951
- 4,
176952
- 0,
176953
- 15,
176954
- 8,
176955
- 9,
176956
- 0,
176957
- 5,
176958
- 7,
176959
- 2,
176960
- 4,
176961
- 10,
176962
- 15,
176963
- 14,
176964
- 1,
176965
- 11,
176966
- 12,
176967
- 6,
176968
- 8,
176969
- 3,
176970
- 13,
176971
- 2,
176972
- 12,
176973
- 6,
176974
- 10,
176975
- 0,
176976
- 11,
176977
- 8,
176978
- 3,
176979
- 4,
176980
- 13,
176981
- 7,
176982
- 5,
176983
- 15,
176984
- 14,
176985
- 1,
176986
- 9,
176987
- 12,
176988
- 5,
176989
- 1,
176990
- 15,
176991
- 14,
176992
- 13,
176993
- 4,
176994
- 10,
176995
- 0,
176996
- 7,
176997
- 6,
176998
- 3,
176999
- 9,
177000
- 2,
177001
- 8,
177002
- 11,
177003
- 13,
177004
- 11,
177005
- 7,
177006
- 14,
177007
- 12,
177008
- 1,
177009
- 3,
177010
- 9,
177011
- 5,
177012
- 0,
177013
- 15,
177014
- 4,
177015
- 8,
177016
- 6,
177017
- 2,
177018
- 10,
177019
- 6,
177020
- 15,
177021
- 14,
177022
- 9,
177023
- 11,
177024
- 3,
177025
- 0,
177026
- 8,
177027
- 12,
177028
- 2,
177029
- 13,
177030
- 7,
177031
- 1,
177032
- 4,
177033
- 10,
177034
- 5,
177035
- 10,
177036
- 2,
177037
- 8,
177038
- 4,
177039
- 7,
177040
- 6,
177041
- 1,
177042
- 5,
177043
- 15,
177044
- 11,
177045
- 9,
177046
- 14,
177047
- 3,
177048
- 12,
177049
- 13,
177050
- 0,
177051
- 0,
177052
- 1,
177053
- 2,
177054
- 3,
177055
- 4,
177056
- 5,
177057
- 6,
177058
- 7,
177059
- 8,
177060
- 9,
177061
- 10,
177062
- 11,
177063
- 12,
177064
- 13,
177065
- 14,
177066
- 15,
177067
- 14,
177068
- 10,
177069
- 4,
177070
- 8,
177071
- 9,
177072
- 15,
177073
- 13,
177074
- 6,
177075
- 1,
177076
- 12,
177077
- 0,
177078
- 2,
177079
- 11,
177080
- 7,
177081
- 5,
177082
- 3,
177083
- 11,
177084
- 8,
177085
- 12,
177086
- 0,
177087
- 5,
177088
- 2,
177089
- 15,
177090
- 13,
177091
- 10,
177092
- 14,
177093
- 3,
177094
- 6,
177095
- 7,
177096
- 1,
177097
- 9,
177098
- 4,
177099
- 7,
177100
- 9,
177101
- 3,
177102
- 1,
177103
- 13,
177104
- 12,
177105
- 11,
177106
- 14,
177107
- 2,
177108
- 6,
177109
- 5,
177110
- 10,
177111
- 4,
177112
- 0,
177113
- 15,
177114
- 8,
177115
- 9,
177116
- 0,
177117
- 5,
177118
- 7,
177119
- 2,
177120
- 4,
177121
- 10,
177122
- 15,
177123
- 14,
177124
- 1,
177125
- 11,
177126
- 12,
177127
- 6,
177128
- 8,
177129
- 3,
177130
- 13,
177131
- 2,
177132
- 12,
177133
- 6,
177134
- 10,
177135
- 0,
177136
- 11,
177137
- 8,
177138
- 3,
177139
- 4,
177140
- 13,
177141
- 7,
177142
- 5,
177143
- 15,
177144
- 14,
177145
- 1,
177146
- 9
177147
- ]);
177148
- });
177149
-
177150
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/blake2.js
177151
- function G1b(a, b, c, d, msg, x) {
177152
- const Xl = msg[x], Xh = msg[x + 1];
177153
- let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
177154
- let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
177155
- let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
177156
- let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
177157
- let ll = add3L(Al, Bl, Xl);
177158
- Ah = add3H(ll, Ah, Bh, Xh);
177159
- Al = ll | 0;
177160
- ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
177161
- ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
177162
- ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
177163
- ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
177164
- ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
177165
- BBUF[2 * a] = Al, BBUF[2 * a + 1] = Ah;
177166
- BBUF[2 * b] = Bl, BBUF[2 * b + 1] = Bh;
177167
- BBUF[2 * c] = Cl, BBUF[2 * c + 1] = Ch;
177168
- BBUF[2 * d] = Dl, BBUF[2 * d + 1] = Dh;
177169
- }
177170
- function G2b(a, b, c, d, msg, x) {
177171
- const Xl = msg[x], Xh = msg[x + 1];
177172
- let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
177173
- let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
177174
- let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
177175
- let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
177176
- let ll = add3L(Al, Bl, Xl);
177177
- Ah = add3H(ll, Ah, Bh, Xh);
177178
- Al = ll | 0;
177179
- ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
177180
- ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
177181
- ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
177182
- ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
177183
- ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
177184
- BBUF[2 * a] = Al, BBUF[2 * a + 1] = Ah;
177185
- BBUF[2 * b] = Bl, BBUF[2 * b + 1] = Bh;
177186
- BBUF[2 * c] = Cl, BBUF[2 * c + 1] = Ch;
177187
- BBUF[2 * d] = Dl, BBUF[2 * d + 1] = Dh;
177188
- }
177189
- function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
177190
- anumber(keyLen);
177191
- if (outputLen <= 0 || outputLen > keyLen)
177192
- throw new Error("outputLen bigger than keyLen");
177193
- const { key, salt, personalization } = opts;
177194
- if (key !== undefined && (key.length < 1 || key.length > keyLen))
177195
- throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
177196
- if (salt !== undefined)
177197
- abytes(salt, saltLen, "salt");
177198
- if (personalization !== undefined)
177199
- abytes(personalization, persLen, "personalization");
177200
- }
177201
-
177202
- class _BLAKE2 {
177203
- buffer;
177204
- buffer32;
177205
- finished = false;
177206
- destroyed = false;
177207
- length = 0;
177208
- pos = 0;
177209
- blockLen;
177210
- outputLen;
177211
- canXOF = false;
177212
- constructor(blockLen, outputLen) {
177213
- anumber(blockLen);
177214
- anumber(outputLen);
177215
- this.blockLen = blockLen;
177216
- this.outputLen = outputLen;
177217
- this.buffer = new Uint8Array(blockLen);
177218
- this.buffer32 = u32(this.buffer);
177219
- }
177220
- update(data) {
177221
- aexists(this);
177222
- abytes(data);
177223
- const { blockLen, buffer, buffer32 } = this;
177224
- const len = data.length;
177225
- const offset = data.byteOffset;
177226
- const buf = data.buffer;
177227
- for (let pos = 0;pos < len; ) {
177228
- if (this.pos === blockLen) {
177229
- swap32IfBE(buffer32);
177230
- this.compress(buffer32, 0, false);
177231
- swap32IfBE(buffer32);
177232
- this.pos = 0;
177233
- }
177234
- const take = Math.min(blockLen - this.pos, len - pos);
177235
- const dataOffset = offset + pos;
177236
- if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
177237
- const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
177238
- swap32IfBE(data32);
177239
- for (let pos32 = 0;pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
177240
- this.length += blockLen;
177241
- this.compress(data32, pos32, false);
177242
- }
177243
- swap32IfBE(data32);
176984
+ function createVaultKdfWorkerPool(options2 = {}) {
176985
+ const size = positiveInteger(options2.size, defaultVaultKdfWorkers(options2));
176986
+ const workerUrl = options2.workerUrl || new URL("./kdf-worker-thread.js", import.meta.url);
176987
+ const workers = [];
176988
+ const queue = [];
176989
+ const pending = new Map;
176990
+ let sequence = 0;
176991
+ let closed = false;
176992
+ function dispatch() {
176993
+ if (closed)
176994
+ return;
176995
+ for (const slot of workers) {
176996
+ if (slot.task || !queue.length)
177244
176997
  continue;
177245
- }
177246
- buffer.set(data.subarray(pos, pos + take), this.pos);
177247
- this.pos += take;
177248
- this.length += take;
177249
- pos += take;
177250
- }
177251
- return this;
177252
- }
177253
- digestInto(out) {
177254
- aexists(this);
177255
- aoutput(out, this);
177256
- const { pos, buffer32 } = this;
177257
- this.finished = true;
177258
- clean(this.buffer.subarray(pos));
177259
- swap32IfBE(buffer32);
177260
- this.compress(buffer32, 0, true);
177261
- swap32IfBE(buffer32);
177262
- if (out.byteOffset & 3)
177263
- throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
177264
- const state = this.get();
177265
- const out32 = u32(out);
177266
- const full = Math.floor(this.outputLen / 4);
177267
- for (let i = 0;i < full; i++)
177268
- out32[i] = swap8IfBE(state[i]);
177269
- const tail = this.outputLen % 4;
177270
- if (!tail)
176998
+ const task = queue.shift();
176999
+ slot.task = task;
177000
+ pending.set(task.id, { slot, task });
177001
+ slot.worker.ref();
177002
+ slot.worker.postMessage({
177003
+ id: task.id,
177004
+ password: task.password.buffer,
177005
+ salt: task.salt.buffer,
177006
+ params: task.params
177007
+ }, [task.password.buffer, task.salt.buffer]);
177008
+ }
177009
+ }
177010
+ function finish(slot, task, operation, value) {
177011
+ if (slot.task !== task)
177271
177012
  return;
177272
- const off = full * 4;
177273
- const word = state[full];
177274
- for (let i = 0;i < tail; i++)
177275
- out[off + i] = word >>> 8 * i;
177276
- }
177277
- digest() {
177278
- const { buffer, outputLen } = this;
177279
- this.digestInto(buffer);
177280
- const res = buffer.slice(0, outputLen);
177281
- this.destroy();
177282
- return res;
177283
- }
177284
- _cloneInto(to) {
177285
- const { buffer, length, finished, destroyed, outputLen, pos } = this;
177286
- to ||= new this.constructor({ dkLen: outputLen });
177287
- to.set(...this.get());
177288
- to.buffer.set(buffer);
177289
- to.destroyed = destroyed;
177290
- to.finished = finished;
177291
- to.length = length;
177292
- to.pos = pos;
177293
- to.outputLen = outputLen;
177294
- return to;
177295
- }
177296
- clone() {
177297
- return this._cloneInto();
177298
- }
177299
- }
177300
- function compress2(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
177301
- let j = 0;
177302
- for (let i = 0;i < rounds; i++) {
177303
- ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
177304
- ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
177305
- ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
177306
- ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
177307
- ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
177308
- ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
177309
- ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
177310
- ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
177311
- ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
177312
- ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
177313
- ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
177314
- ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
177315
- ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
177316
- ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
177317
- ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
177318
- ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
177319
- }
177320
- return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
177321
- }
177322
- var B2B_IV, BBUF, _BLAKE2b, blake2b, B2S_IV, _BLAKE2s;
177323
- var init_blake2 = __esm(() => {
177324
- init__blake();
177325
- init__md();
177326
- init__u64();
177327
- init_utils();
177328
- B2B_IV = /* @__PURE__ */ Uint32Array.from([
177329
- 4089235720,
177330
- 1779033703,
177331
- 2227873595,
177332
- 3144134277,
177333
- 4271175723,
177334
- 1013904242,
177335
- 1595750129,
177336
- 2773480762,
177337
- 2917565137,
177338
- 1359893119,
177339
- 725511199,
177340
- 2600822924,
177341
- 4215389547,
177342
- 528734635,
177343
- 327033209,
177344
- 1541459225
177345
- ]);
177346
- BBUF = /* @__PURE__ */ new Uint32Array(32);
177347
- _BLAKE2b = class _BLAKE2b extends _BLAKE2 {
177348
- v0l = B2B_IV[0] | 0;
177349
- v0h = B2B_IV[1] | 0;
177350
- v1l = B2B_IV[2] | 0;
177351
- v1h = B2B_IV[3] | 0;
177352
- v2l = B2B_IV[4] | 0;
177353
- v2h = B2B_IV[5] | 0;
177354
- v3l = B2B_IV[6] | 0;
177355
- v3h = B2B_IV[7] | 0;
177356
- v4l = B2B_IV[8] | 0;
177357
- v4h = B2B_IV[9] | 0;
177358
- v5l = B2B_IV[10] | 0;
177359
- v5h = B2B_IV[11] | 0;
177360
- v6l = B2B_IV[12] | 0;
177361
- v6h = B2B_IV[13] | 0;
177362
- v7l = B2B_IV[14] | 0;
177363
- v7h = B2B_IV[15] | 0;
177364
- constructor(opts = {}) {
177365
- const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
177366
- super(128, olen);
177367
- checkBlake2Opts(olen, opts, 64, 16, 16);
177368
- let { key, personalization, salt } = opts;
177369
- let keyLength = 0;
177370
- if (key !== undefined) {
177371
- abytes(key, undefined, "key");
177372
- keyLength = key.length;
177373
- }
177374
- this.v0l ^= this.outputLen | keyLength << 8 | 1 << 16 | 1 << 24;
177375
- if (salt !== undefined) {
177376
- abytes(salt, undefined, "salt");
177377
- const slt = u32(salt);
177378
- this.v4l ^= swap8IfBE(slt[0]);
177379
- this.v4h ^= swap8IfBE(slt[1]);
177380
- this.v5l ^= swap8IfBE(slt[2]);
177381
- this.v5h ^= swap8IfBE(slt[3]);
177382
- }
177383
- if (personalization !== undefined) {
177384
- abytes(personalization, undefined, "personalization");
177385
- const pers = u32(personalization);
177386
- this.v6l ^= swap8IfBE(pers[0]);
177387
- this.v6h ^= swap8IfBE(pers[1]);
177388
- this.v7l ^= swap8IfBE(pers[2]);
177389
- this.v7h ^= swap8IfBE(pers[3]);
177390
- }
177391
- if (key !== undefined) {
177392
- const tmp = new Uint8Array(this.blockLen);
177393
- tmp.set(key);
177394
- this.update(tmp);
177013
+ pending.delete(task.id);
177014
+ slot.task = null;
177015
+ slot.worker.unref();
177016
+ operation(value);
177017
+ dispatch();
177018
+ }
177019
+ function failSlot(slot, error) {
177020
+ if (slot.failed)
177021
+ return;
177022
+ slot.failed = true;
177023
+ const task = slot.task;
177024
+ if (task)
177025
+ finish(slot, task, task.reject, error);
177026
+ if (closed)
177027
+ return;
177028
+ const index = workers.indexOf(slot);
177029
+ if (index >= 0)
177030
+ workers.splice(index, 1);
177031
+ spawn();
177032
+ dispatch();
177033
+ }
177034
+ function spawn() {
177035
+ const worker = new Worker(workerUrl, { type: "module" });
177036
+ const slot = { worker, task: null, failed: false };
177037
+ worker.unref();
177038
+ worker.on("message", ({ id, key, error }) => {
177039
+ const active = pending.get(id);
177040
+ if (!active || active.slot !== slot)
177041
+ return;
177042
+ if (error) {
177043
+ finish(slot, active.task, active.task.reject, workerError(error));
177044
+ return;
177395
177045
  }
177396
- }
177397
- get() {
177398
- let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
177399
- return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
177400
- }
177401
- set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
177402
- this.v0l = v0l | 0;
177403
- this.v0h = v0h | 0;
177404
- this.v1l = v1l | 0;
177405
- this.v1h = v1h | 0;
177406
- this.v2l = v2l | 0;
177407
- this.v2h = v2h | 0;
177408
- this.v3l = v3l | 0;
177409
- this.v3h = v3h | 0;
177410
- this.v4l = v4l | 0;
177411
- this.v4h = v4h | 0;
177412
- this.v5l = v5l | 0;
177413
- this.v5h = v5h | 0;
177414
- this.v6l = v6l | 0;
177415
- this.v6h = v6h | 0;
177416
- this.v7l = v7l | 0;
177417
- this.v7h = v7h | 0;
177418
- }
177419
- compress(msg, offset, isLast) {
177420
- this.get().forEach((v, i) => BBUF[i] = v);
177421
- BBUF.set(B2B_IV, 16);
177422
- let { h, l } = fromBig(BigInt(this.length));
177423
- BBUF[24] = B2B_IV[8] ^ l;
177424
- BBUF[25] = B2B_IV[9] ^ h;
177425
- if (isLast) {
177426
- BBUF[28] = ~BBUF[28];
177427
- BBUF[29] = ~BBUF[29];
177428
- }
177429
- let j = 0;
177430
- const s = BSIGMA;
177431
- for (let i = 0;i < 12; i++) {
177432
- G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
177433
- G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
177434
- G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
177435
- G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
177436
- G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
177437
- G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
177438
- G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
177439
- G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
177440
- G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
177441
- G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
177442
- G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
177443
- G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
177444
- G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
177445
- G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
177446
- G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
177447
- G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
177448
- }
177449
- this.v0l ^= BBUF[0] ^ BBUF[16];
177450
- this.v0h ^= BBUF[1] ^ BBUF[17];
177451
- this.v1l ^= BBUF[2] ^ BBUF[18];
177452
- this.v1h ^= BBUF[3] ^ BBUF[19];
177453
- this.v2l ^= BBUF[4] ^ BBUF[20];
177454
- this.v2h ^= BBUF[5] ^ BBUF[21];
177455
- this.v3l ^= BBUF[6] ^ BBUF[22];
177456
- this.v3h ^= BBUF[7] ^ BBUF[23];
177457
- this.v4l ^= BBUF[8] ^ BBUF[24];
177458
- this.v4h ^= BBUF[9] ^ BBUF[25];
177459
- this.v5l ^= BBUF[10] ^ BBUF[26];
177460
- this.v5h ^= BBUF[11] ^ BBUF[27];
177461
- this.v6l ^= BBUF[12] ^ BBUF[28];
177462
- this.v6h ^= BBUF[13] ^ BBUF[29];
177463
- this.v7l ^= BBUF[14] ^ BBUF[30];
177464
- this.v7h ^= BBUF[15] ^ BBUF[31];
177465
- clean(BBUF);
177466
- }
177467
- destroy() {
177468
- this.destroyed = true;
177469
- clean(this.buffer32);
177470
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
177471
- }
177472
- };
177473
- blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));
177474
- B2S_IV = /* @__PURE__ */ SHA256_IV.slice();
177475
- _BLAKE2s = class _BLAKE2s extends _BLAKE2 {
177476
- v0 = B2S_IV[0] | 0;
177477
- v1 = B2S_IV[1] | 0;
177478
- v2 = B2S_IV[2] | 0;
177479
- v3 = B2S_IV[3] | 0;
177480
- v4 = B2S_IV[4] | 0;
177481
- v5 = B2S_IV[5] | 0;
177482
- v6 = B2S_IV[6] | 0;
177483
- v7 = B2S_IV[7] | 0;
177484
- constructor(opts = {}) {
177485
- const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
177486
- super(64, olen);
177487
- checkBlake2Opts(olen, opts, 32, 8, 8);
177488
- let { key, personalization, salt } = opts;
177489
- let keyLength = 0;
177490
- if (key !== undefined) {
177491
- abytes(key, undefined, "key");
177492
- keyLength = key.length;
177493
- }
177494
- this.v0 ^= this.outputLen | keyLength << 8 | 1 << 16 | 1 << 24;
177495
- if (salt !== undefined) {
177496
- abytes(salt, undefined, "salt");
177497
- const slt = u32(salt);
177498
- this.v4 ^= swap8IfBE(slt[0]);
177499
- this.v5 ^= swap8IfBE(slt[1]);
177500
- }
177501
- if (personalization !== undefined) {
177502
- abytes(personalization, undefined, "personalization");
177503
- const pers = u32(personalization);
177504
- this.v6 ^= swap8IfBE(pers[0]);
177505
- this.v7 ^= swap8IfBE(pers[1]);
177506
- }
177507
- if (key !== undefined) {
177508
- const tmp = new Uint8Array(this.blockLen);
177509
- tmp.set(key);
177510
- this.update(tmp);
177046
+ finish(slot, active.task, active.task.resolve, new Uint8Array(key));
177047
+ });
177048
+ worker.on("error", (error) => failSlot(slot, error));
177049
+ worker.on("exit", (code) => {
177050
+ if (closed)
177051
+ return;
177052
+ failSlot(slot, new Error(`vault KDF worker exited (${code})`));
177053
+ });
177054
+ workers.push(slot);
177055
+ }
177056
+ for (let index = 0;index < size; index += 1)
177057
+ spawn();
177058
+ return Object.freeze({
177059
+ size,
177060
+ derive(password, salt, params = {}) {
177061
+ if (closed)
177062
+ return Promise.reject(new Error("vault KDF pool closed"));
177063
+ const passwordBytes = encoder3.encode(String(password ?? ""));
177064
+ const saltBytes = new Uint8Array(salt);
177065
+ return new Promise((resolve, reject) => {
177066
+ sequence += 1;
177067
+ queue.push({
177068
+ id: sequence,
177069
+ password: passwordBytes,
177070
+ salt: saltBytes,
177071
+ params,
177072
+ resolve,
177073
+ reject
177074
+ });
177075
+ dispatch();
177076
+ });
177077
+ },
177078
+ async close() {
177079
+ if (closed)
177080
+ return;
177081
+ closed = true;
177082
+ const error = new Error("vault KDF pool closed");
177083
+ for (const task of queue.splice(0)) {
177084
+ task.password.fill(0);
177085
+ task.salt.fill(0);
177086
+ task.reject(error);
177511
177087
  }
177088
+ for (const { task } of pending.values())
177089
+ task.reject(error);
177090
+ pending.clear();
177091
+ await Promise.all(workers.map(({ worker }) => worker.terminate()));
177092
+ workers.length = 0;
177512
177093
  }
177513
- get() {
177514
- const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
177515
- return [v0, v1, v2, v3, v4, v5, v6, v7];
177516
- }
177517
- set(v0, v1, v2, v3, v4, v5, v6, v7) {
177518
- this.v0 = v0 | 0;
177519
- this.v1 = v1 | 0;
177520
- this.v2 = v2 | 0;
177521
- this.v3 = v3 | 0;
177522
- this.v4 = v4 | 0;
177523
- this.v5 = v5 | 0;
177524
- this.v6 = v6 | 0;
177525
- this.v7 = v7 | 0;
177526
- }
177527
- compress(msg, offset, isLast) {
177528
- const { h, l } = fromBig(BigInt(this.length));
177529
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress2(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
177530
- this.v0 ^= v0 ^ v8;
177531
- this.v1 ^= v1 ^ v9;
177532
- this.v2 ^= v2 ^ v10;
177533
- this.v3 ^= v3 ^ v11;
177534
- this.v4 ^= v4 ^ v12;
177535
- this.v5 ^= v5 ^ v13;
177536
- this.v6 ^= v6 ^ v14;
177537
- this.v7 ^= v7 ^ v15;
177538
- }
177539
- destroy() {
177540
- this.destroyed = true;
177541
- clean(this.buffer32);
177542
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
177543
- }
177544
- };
177545
- });
177546
-
177547
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/argon2.js
177548
- function mul3(a, b) {
177549
- const aL = a & 65535;
177550
- const aH = a >>> 16;
177551
- const bL = b & 65535;
177552
- const bH = b >>> 16;
177553
- const ll = Math.imul(aL, bL);
177554
- const hl = Math.imul(aH, bL);
177555
- const lh = Math.imul(aL, bH);
177556
- const hh = Math.imul(aH, bH);
177557
- const carry = (ll >>> 16) + (hl & 65535) + lh;
177558
- const high = hh + (hl >>> 16) + (carry >>> 16) | 0;
177559
- const low = carry << 16 | ll & 65535;
177560
- return { h: high, l: low };
177561
- }
177562
- function mul23(a, b) {
177563
- const { h, l } = mul3(a, b);
177564
- return { h: (h << 1 | l >>> 31) & 4294967295, l: l << 1 & 4294967295 };
177565
- }
177566
- function blamka(Ah, Al, Bh, Bl) {
177567
- const { h: Ch, l: Cl } = mul23(Al, Bl);
177568
- const Rll = add3L(Al, Bl, Cl);
177569
- return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 };
177570
- }
177571
- function G(a, b, c, d) {
177572
- let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1];
177573
- let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1];
177574
- let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1];
177575
- let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1];
177576
- ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
177577
- ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
177578
- ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
177579
- ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
177580
- ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
177581
- ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
177582
- ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
177583
- ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
177584
- ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
177585
- ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
177586
- ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
177587
- ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
177588
- A2_BUF[2 * a] = Al, A2_BUF[2 * a + 1] = Ah;
177589
- A2_BUF[2 * b] = Bl, A2_BUF[2 * b + 1] = Bh;
177590
- A2_BUF[2 * c] = Cl, A2_BUF[2 * c + 1] = Ch;
177591
- A2_BUF[2 * d] = Dl, A2_BUF[2 * d + 1] = Dh;
177592
- }
177593
- function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {
177594
- G(v00, v04, v08, v12);
177595
- G(v01, v05, v09, v13);
177596
- G(v02, v06, v10, v14);
177597
- G(v03, v07, v11, v15);
177598
- G(v00, v05, v10, v15);
177599
- G(v01, v06, v11, v12);
177600
- G(v02, v07, v08, v13);
177601
- G(v03, v04, v09, v14);
177602
- }
177603
- function block(x, xPos, yPos, outPos, needXor) {
177604
- for (let i = 0;i < 256; i++)
177605
- A2_BUF[i] = x[xPos + i] ^ x[yPos + i];
177606
- for (let i = 0;i < 128; i += 16) {
177607
- P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);
177608
- }
177609
- for (let i = 0;i < 16; i += 2) {
177610
- P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);
177611
- }
177612
- if (needXor)
177613
- for (let i = 0;i < 256; i++)
177614
- x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
177615
- else
177616
- for (let i = 0;i < 256; i++)
177617
- x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
177618
- clean(A2_BUF);
177619
- }
177620
- function Hp(A, dkLen) {
177621
- const A8 = u8(A);
177622
- const T = new Uint32Array(1);
177623
- const T8 = u8(T);
177624
- T[0] = swap8IfBE(dkLen);
177625
- if (dkLen <= 64)
177626
- return blake2b.create({ dkLen }).update(T8).update(A8).digest();
177627
- const out = new Uint8Array(dkLen);
177628
- let V = blake2b.create({}).update(T8).update(A8).digest();
177629
- let pos = 0;
177630
- out.set(V.subarray(0, 32));
177631
- pos += 32;
177632
- for (;dkLen - pos > 64; pos += 32) {
177633
- const Vh = blake2b.create({}).update(V);
177634
- Vh.digestInto(V);
177635
- Vh.destroy();
177636
- out.set(V.subarray(0, 32), pos);
177637
- }
177638
- out.set(blake2b(V, { dkLen: dkLen - pos }), pos);
177639
- clean(V, T);
177640
- return out;
177641
- }
177642
- function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {
177643
- let area;
177644
- if (r === 0) {
177645
- if (s === 0)
177646
- area = index - 1;
177647
- else if (sameLane)
177648
- area = s * segmentLen + index - 1;
177649
- else
177650
- area = s * segmentLen + (index == 0 ? -1 : 0);
177651
- } else if (sameLane)
177652
- area = laneLen - segmentLen + index - 1;
177653
- else
177654
- area = laneLen - segmentLen + (index == 0 ? -1 : 0);
177655
- const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
177656
- const rel = area - 1 - mul3(area, mul3(randL, randL).h).h;
177657
- return (startPos + rel) % laneLen;
177658
- }
177659
- function isU32(num2) {
177660
- return Number.isSafeInteger(num2) && num2 >= 0 && num2 < maxUint32;
177661
- }
177662
- function argon2Opts(opts) {
177663
- const merged = {
177664
- version: 19,
177665
- dkLen: 32,
177666
- maxmem: maxUint32 - 1,
177667
- asyncTick: 10
177668
- };
177669
- for (let [k, v] of Object.entries(opts))
177670
- if (v !== undefined)
177671
- merged[k] = v;
177672
- const { dkLen, p, m, t, version: version8, onProgress, asyncTick } = merged;
177673
- if (!isU32(dkLen) || dkLen < 4)
177674
- throw new Error('"dkLen" must be 4..');
177675
- if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))
177676
- throw new Error('"p" must be 1..2^24');
177677
- if (!isU32(m))
177678
- throw new Error('"m" must be 0..2^32');
177679
- if (!isU32(t) || t < 1)
177680
- throw new Error('"t" (iterations) must be 1..2^32');
177681
- if (onProgress !== undefined && typeof onProgress !== "function")
177682
- throw new Error('"progressCb" must be a function');
177683
- anumber(asyncTick, "asyncTick");
177684
- if (!isU32(m) || m < 8 * p)
177685
- throw new Error('"m" (memory) must be at least 8*p bytes');
177686
- if (version8 !== 16 && version8 !== 19)
177687
- throw new Error('"version" must be 0x10 or 0x13, got ' + version8);
177688
- return merged;
177689
- }
177690
- function argon2Init(password, salt, type, opts) {
177691
- password = kdfInputToBytes(password, "password");
177692
- salt = kdfInputToBytes(salt, "salt");
177693
- if (!isU32(password.length))
177694
- throw new Error('"password" must be less of length 1..4Gb');
177695
- if (!isU32(salt.length) || salt.length < 8)
177696
- throw new Error('"salt" must be of length 8..4Gb');
177697
- if (!Object.values(AT).includes(type))
177698
- throw new Error('"type" was invalid');
177699
- let { p, dkLen, m, t, version: version8, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);
177700
- key = abytesOrZero(key, "key");
177701
- personalization = abytesOrZero(personalization, "personalization");
177702
- const h = blake2b.create();
177703
- const BUF = new Uint32Array(1);
177704
- const BUF8 = u8(BUF);
177705
- for (let item of [p, dkLen, m, t, version8, type]) {
177706
- BUF[0] = swap8IfBE(item);
177707
- h.update(BUF8);
177708
- }
177709
- for (let i of [password, salt, key, personalization]) {
177710
- BUF[0] = swap8IfBE(i.length);
177711
- h.update(BUF8).update(i);
177712
- }
177713
- const H0 = new Uint32Array(18);
177714
- const H0_8 = u8(H0);
177715
- h.digestInto(H0_8);
177716
- const lanes = p;
177717
- const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
177718
- const laneLen = Math.floor(mP / p);
177719
- const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
177720
- const memUsed = mP * 1024;
177721
- if (!isU32(maxmem))
177722
- throw new Error('"maxmem" expected <2**32, got ' + maxmem);
177723
- if (memUsed > maxmem)
177724
- throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ", maxmem=" + maxmem);
177725
- const B = new Uint32Array(memUsed / 4);
177726
- for (let l = 0;l < p; l++) {
177727
- const i = 256 * laneLen * l;
177728
- H0[17] = swap8IfBE(l);
177729
- H0[16] = swap8IfBE(0);
177730
- B.set(swap32IfBE(u32(Hp(H0, 1024))), i);
177731
- H0[16] = swap8IfBE(1);
177732
- B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256);
177733
- }
177734
- let perBlock = () => {};
177735
- if (onProgress) {
177736
- const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p;
177737
- const callbackPer = Math.max(Math.floor(totalBlock / 1e4), 1);
177738
- let blockCnt = 0;
177739
- perBlock = () => {
177740
- blockCnt++;
177741
- if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
177742
- onProgress(blockCnt / totalBlock);
177743
- };
177744
- }
177745
- clean(BUF, H0);
177746
- return { type, mP, p, t, version: version8, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
177747
- }
177748
- function argon2Output(B, p, laneLen, dkLen) {
177749
- const B_final = new Uint32Array(256);
177750
- for (let l = 0;l < p; l++)
177751
- for (let j = 0;j < 256; j++)
177752
- B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
177753
- const res = Hp(swap32IfBE(B_final), dkLen);
177754
- clean(B, B_final);
177755
- return res;
177756
- }
177757
- function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) {
177758
- if (offset % laneLen)
177759
- prev = offset - 1;
177760
- let randL, randH;
177761
- if (dataIndependent) {
177762
- let i128 = index % 128;
177763
- if (i128 === 0) {
177764
- address[256 + 12]++;
177765
- block(address, 256, 2 * 256, 0, false);
177766
- block(address, 0, 2 * 256, 0, false);
177767
- }
177768
- randL = address[2 * i128];
177769
- randH = address[2 * i128 + 1];
177770
- } else {
177771
- const T = 256 * prev;
177772
- randL = B[T];
177773
- randH = B[T + 1];
177774
- }
177775
- const refLane = r === 0 && s === 0 ? l : randH % lanes;
177776
- const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
177777
- const refBlock = laneLen * refLane + refPos;
177778
- block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
177779
- }
177780
- async function argon2Async(type, password, salt, opts) {
177781
- const { mP, p, t, version: version8, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } = argon2Init(password, salt, type, opts);
177782
- const address = new Uint32Array(3 * 256);
177783
- address[256 + 6] = mP;
177784
- address[256 + 8] = t;
177785
- address[256 + 10] = type;
177786
- let ts = Date.now();
177787
- for (let r = 0;r < t; r++) {
177788
- const needXor = r !== 0 && version8 === 19;
177789
- address[256 + 0] = r;
177790
- for (let s = 0;s < ARGON2_SYNC_POINTS; s++) {
177791
- address[256 + 4] = s;
177792
- const dataIndependent = type == AT.Argon2i || type == AT.Argon2id && r === 0 && s < 2;
177793
- for (let l = 0;l < p; l++) {
177794
- address[256 + 2] = l;
177795
- address[256 + 12] = 0;
177796
- let startPos = 0;
177797
- if (r === 0 && s === 0) {
177798
- startPos = 2;
177799
- if (dataIndependent) {
177800
- address[256 + 12]++;
177801
- block(address, 256, 2 * 256, 0, false);
177802
- block(address, 0, 2 * 256, 0, false);
177803
- }
177804
- }
177805
- let offset = l * laneLen + s * segmentLen + startPos;
177806
- let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
177807
- for (let index = startPos;index < segmentLen; index++, offset++, prev++) {
177808
- perBlock();
177809
- processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
177810
- const diff = Date.now() - ts;
177811
- if (!(diff >= 0 && diff < asyncTick)) {
177812
- await nextTick();
177813
- ts += diff;
177814
- }
177815
- }
177816
- }
177817
- }
177818
- }
177819
- clean(address);
177820
- return argon2Output(B, p, laneLen, dkLen);
177821
- }
177822
- var AT, ARGON2_SYNC_POINTS = 4, abytesOrZero = (buf, errorTitle = "") => {
177823
- if (buf === undefined)
177824
- return Uint8Array.of();
177825
- return kdfInputToBytes(buf, errorTitle);
177826
- }, A2_BUF, maxUint32, argon2idAsync = (password, salt, opts) => argon2Async(AT.Argon2id, password, salt, opts);
177827
- var init_argon2 = __esm(() => {
177828
- init__u64();
177829
- init_blake2();
177830
- init_utils();
177831
- AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 };
177832
- A2_BUF = new Uint32Array(256);
177833
- maxUint32 = Math.pow(2, 32);
177834
- });
177835
-
177836
- // src/kdf.js
177837
- async function deriveVaultKey(password, salt, params = {}) {
177838
- return argon2idAsync(String(password ?? ""), new Uint8Array(salt), {
177839
- t: params.t,
177840
- m: params.m,
177841
- p: params.p,
177842
- dkLen: params.dkLen,
177843
- version: params.version,
177844
- asyncTick: 10
177845
177094
  });
177846
177095
  }
177847
- var init_kdf2 = __esm(() => {
177848
- init_argon2();
177096
+ var KDF_MEMORY_KIB, DEFAULT_KDF_MEMORY_BUDGET_KIB, encoder3;
177097
+ var init_kdf_worker = __esm(() => {
177098
+ KDF_MEMORY_KIB = 64 * 1024;
177099
+ DEFAULT_KDF_MEMORY_BUDGET_KIB = 512 * 1024;
177100
+ encoder3 = new TextEncoder;
177849
177101
  });
177850
177102
 
177851
177103
  // src/machine.js
@@ -178376,6 +177628,10 @@ var init_passkey2 = __esm(() => {
178376
177628
  // src/runtime/node.js
178377
177629
  import { randomBytes as randomBytes10 } from "node:crypto";
178378
177630
  import process5 from "node:process";
177631
+ function sharedVaultCrypto() {
177632
+ defaultKdfPool ||= createVaultKdfWorkerPool();
177633
+ return createVaultSeedCrypto((password, salt, params) => defaultKdfPool.derive(password, salt, params));
177634
+ }
178379
177635
  function appName(profile) {
178380
177636
  const name7 = cleanProfileName(profile, "");
178381
177637
  return name7 ? `veyl-sdk-${name7}` : "veyl-sdk";
@@ -178400,7 +177656,7 @@ function createNodePorts(options2 = {}) {
178400
177656
  store,
178401
177657
  cloudContext,
178402
177658
  ownsCloud,
178403
- vaultCrypto: options2.vaultCrypto || vaultCrypto,
177659
+ vaultCrypto: options2.vaultCrypto || sharedVaultCrypto(),
178404
177660
  walletClass: options2.walletClass || SparkWalletNodeJS,
178405
177661
  openLocalCache: options2.openLocalCache || ((cacheSeed, { uid, network }) => openLocalDataCache(cacheSeed, {
178406
177662
  homeDir: store.dir,
@@ -178423,23 +177679,22 @@ function createAccountRuntime(options2 = {}) {
178423
177679
  async function open(options2 = {}) {
178424
177680
  return createAccountRuntime(options2);
178425
177681
  }
178426
- var vaultCrypto;
177682
+ var defaultKdfPool = null;
178427
177683
  var init_node = __esm(() => {
178428
177684
  init_index_node();
178429
177685
  init_vaultseed();
178430
177686
  init_cache();
178431
177687
  init_client();
178432
177688
  init_cloud2();
178433
- init_kdf2();
177689
+ init_kdf_worker();
178434
177690
  init_machine();
178435
177691
  init_namespace2();
178436
177692
  init_passkey2();
178437
177693
  init_storage();
178438
- vaultCrypto = createVaultSeedCrypto(deriveVaultKey);
178439
177694
  });
178440
177695
 
178441
177696
  // src/fleet.js
178442
- function positiveInteger(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
177697
+ function positiveInteger2(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
178443
177698
  const number = Math.floor(Number(value));
178444
177699
  return Number.isFinite(number) && number > 0 ? Math.min(number, maximum) : fallback;
178445
177700
  }
@@ -178536,6 +177791,9 @@ function publicAccount(record) {
178536
177791
  error: record.error || null
178537
177792
  });
178538
177793
  }
177794
+ function keepsSession(current, next) {
177795
+ return current.profile === next.profile && current.accountIndex === next.accountIndex && current.username === next.username && current.network === next.network;
177796
+ }
178539
177797
 
178540
177798
  class Fleet {
178541
177799
  constructor(options2 = {}) {
@@ -178543,13 +177801,15 @@ class Fleet {
178543
177801
  this.openClient = options2.openClient || open;
178544
177802
  this.clientOptions = options2.clientOptions || {};
178545
177803
  this.eventOptions = options2.eventOptions || {};
178546
- this.bootConcurrency = positiveInteger(options2.bootConcurrency, DEFAULT_BOOT_CONCURRENCY, 32);
178547
- this.maxPendingEvents = positiveInteger(options2.maxPendingEvents, DEFAULT_EVENT_BACKLOG, 1e5);
178548
- this.startTimeoutMs = positiveInteger(options2.startTimeoutMs, DEFAULT_START_TIMEOUT_MS);
177804
+ this.bootConcurrency = positiveInteger2(options2.bootConcurrency, DEFAULT_BOOT_CONCURRENCY, 32);
177805
+ this.maxPendingEvents = positiveInteger2(options2.maxPendingEvents, DEFAULT_EVENT_BACKLOG, 1e5);
177806
+ this.startTimeoutMs = positiveInteger2(options2.startTimeoutMs, DEFAULT_START_TIMEOUT_MS);
178549
177807
  this.policies = policyList(options2.policies);
178550
177808
  this.records = new Map;
178551
177809
  this.listeners = new Set;
178552
177810
  this.startedFleetPolicies = [];
177811
+ this.policyReloading = false;
177812
+ this.reloading = null;
178553
177813
  this.state = "idle";
178554
177814
  this.starting = null;
178555
177815
  this.stopping = null;
@@ -178615,8 +177875,6 @@ class Fleet {
178615
177875
  return operation(client2, publicAccount(record));
178616
177876
  }
178617
177877
  queuePolicies(record, event2) {
178618
- if (!this.policies.length)
178619
- return;
178620
177878
  record.pendingEvents += 1;
178621
177879
  if (record.pendingEvents > this.maxPendingEvents) {
178622
177880
  record.pendingEvents -= 1;
@@ -178630,6 +177888,18 @@ class Fleet {
178630
177888
  });
178631
177889
  return;
178632
177890
  }
177891
+ if (this.policyReloading) {
177892
+ record.reloadEvents.push(event2);
177893
+ return;
177894
+ }
177895
+ if (!this.policies.length) {
177896
+ record.pendingEvents -= 1;
177897
+ return;
177898
+ }
177899
+ this.dispatchPolicies(record, event2);
177900
+ }
177901
+ dispatchPolicies(record, event2) {
177902
+ const policies = this.policies;
178633
177903
  const context = Object.freeze({
178634
177904
  account: record.profile,
178635
177905
  client: record.client,
@@ -178637,7 +177907,7 @@ class Fleet {
178637
177907
  fleet: this
178638
177908
  });
178639
177909
  record.policyTail = record.policyTail.then(async () => {
178640
- for (const policy of this.policies) {
177910
+ for (const policy of policies) {
178641
177911
  await policy.onEvent?.(context);
178642
177912
  }
178643
177913
  }).catch((error) => {
@@ -178663,6 +177933,7 @@ class Fleet {
178663
177933
  listenTask: Promise.resolve(),
178664
177934
  unsubscribeRevoked: () => {},
178665
177935
  startedPolicies: [],
177936
+ reloadEvents: [],
178666
177937
  closed: false
178667
177938
  };
178668
177939
  this.records.set(profile.profile, record);
@@ -178728,6 +177999,167 @@ class Fleet {
178728
177999
  record.status = "ready";
178729
178000
  this.emit("account-ready", { account: publicAccount(record) });
178730
178001
  }
178002
+ async stopRecordPolicies(record) {
178003
+ const errors = [];
178004
+ await record.policyTail.catch((error) => errors.push(error));
178005
+ for (const policy of [...record.startedPolicies].reverse()) {
178006
+ try {
178007
+ await policy.stop?.({
178008
+ account: record.profile,
178009
+ client: record.client,
178010
+ fleet: this
178011
+ });
178012
+ } catch (error) {
178013
+ errors.push(error);
178014
+ }
178015
+ }
178016
+ record.startedPolicies = [];
178017
+ return errors;
178018
+ }
178019
+ async startRecordPolicies(record, policies, profile = record.profile) {
178020
+ const started = [];
178021
+ try {
178022
+ for (const policy of policies) {
178023
+ await policy.start?.({
178024
+ account: profile,
178025
+ client: record.client,
178026
+ fleet: this
178027
+ });
178028
+ started.push(policy);
178029
+ }
178030
+ return started;
178031
+ } catch (error) {
178032
+ for (const policy of started.reverse()) {
178033
+ await policy.stop?.({
178034
+ account: profile,
178035
+ client: record.client,
178036
+ fleet: this
178037
+ }).catch(() => {});
178038
+ }
178039
+ throw error;
178040
+ }
178041
+ }
178042
+ flushReloadEvents() {
178043
+ for (const record of this.records.values()) {
178044
+ const events = record.reloadEvents.splice(0);
178045
+ if (record.closed || record.status === "stopped") {
178046
+ record.pendingEvents = Math.max(0, record.pendingEvents - events.length);
178047
+ continue;
178048
+ }
178049
+ for (const item of events)
178050
+ this.dispatchPolicies(record, item);
178051
+ }
178052
+ this.policyReloading = false;
178053
+ }
178054
+ async reconcile(options2 = {}) {
178055
+ if (this.reloading)
178056
+ return this.reloading;
178057
+ if (this.state !== "running") {
178058
+ throw new Error("fleet must be running to reload");
178059
+ }
178060
+ const profiles = normalizeFleetProfiles(options2.profiles);
178061
+ const policies = policyList(options2.policies);
178062
+ this.reloading = (async () => {
178063
+ this.policyReloading = true;
178064
+ this.emit("reload-start", {
178065
+ fleet: {
178066
+ state: "reloading",
178067
+ accounts: profiles
178068
+ }
178069
+ });
178070
+ const desired = new Map(profiles.filter((profile) => profile.enabled && profile.state === "ready").map((profile) => [profile.profile, profile]));
178071
+ const retained = [];
178072
+ const removed = [];
178073
+ for (const record of this.records.values()) {
178074
+ const next = desired.get(record.profile.profile);
178075
+ if (next && record.status === "ready" && keepsSession(record.profile, next)) {
178076
+ retained.push({ record, profile: next });
178077
+ desired.delete(next.profile);
178078
+ } else {
178079
+ removed.push(record);
178080
+ }
178081
+ }
178082
+ const prepared = [];
178083
+ const preparedFleetPolicies = [];
178084
+ try {
178085
+ for (const policy of policies) {
178086
+ await policy.startFleet?.({ profiles, fleet: this });
178087
+ preparedFleetPolicies.push(policy);
178088
+ }
178089
+ for (const item of retained) {
178090
+ const started = await this.startRecordPolicies(item.record, policies, item.profile);
178091
+ prepared.push({ ...item, started });
178092
+ }
178093
+ } catch (error) {
178094
+ for (const item of prepared.reverse()) {
178095
+ for (const policy of item.started.reverse()) {
178096
+ await policy.stop?.({
178097
+ account: item.profile,
178098
+ client: item.record.client,
178099
+ fleet: this
178100
+ }).catch(() => {});
178101
+ }
178102
+ }
178103
+ if (preparedFleetPolicies.length) {
178104
+ for (const policy of preparedFleetPolicies.reverse()) {
178105
+ await policy.stopFleet?.({ profiles, fleet: this }).catch(() => {});
178106
+ }
178107
+ }
178108
+ this.flushReloadEvents();
178109
+ throw error;
178110
+ }
178111
+ const errors = [];
178112
+ await Promise.all(removed.map(async (record) => {
178113
+ errors.push(...await this.closeRecord(record));
178114
+ this.records.delete(record.profile.profile);
178115
+ }));
178116
+ for (const item of retained) {
178117
+ errors.push(...await this.stopRecordPolicies(item.record));
178118
+ }
178119
+ for (const policy of [...this.startedFleetPolicies].reverse()) {
178120
+ try {
178121
+ await policy.stopFleet?.({
178122
+ profiles: this.profiles,
178123
+ fleet: this
178124
+ });
178125
+ } catch (error) {
178126
+ errors.push(error);
178127
+ }
178128
+ }
178129
+ this.profiles = profiles;
178130
+ this.policies = policies;
178131
+ this.startedFleetPolicies = [...policies];
178132
+ for (const item of prepared) {
178133
+ item.record.profile = item.profile;
178134
+ item.record.startedPolicies = item.started;
178135
+ }
178136
+ const added = [...desired.values()];
178137
+ const bootResults = await Promise.allSettled(added.map((profile) => this.boot(profile)));
178138
+ for (let index = 0;index < bootResults.length; index += 1) {
178139
+ const result = bootResults[index];
178140
+ if (result.status !== "rejected")
178141
+ continue;
178142
+ errors.push(result.reason);
178143
+ const record = this.records.get(added[index].profile);
178144
+ if (!record)
178145
+ continue;
178146
+ record.error = result.reason?.message || String(result.reason);
178147
+ errors.push(...await this.closeRecord(record));
178148
+ }
178149
+ this.flushReloadEvents();
178150
+ const status = this.status();
178151
+ this.emit("reloaded", {
178152
+ fleet: status,
178153
+ errors: errors.map((error) => error?.message || String(error))
178154
+ });
178155
+ return status;
178156
+ })().finally(() => {
178157
+ if (this.policyReloading)
178158
+ this.flushReloadEvents();
178159
+ this.reloading = null;
178160
+ });
178161
+ return this.reloading;
178162
+ }
178731
178163
  async start() {
178732
178164
  if (this.state === "running")
178733
178165
  return this.status();
@@ -178778,18 +178210,11 @@ class Fleet {
178778
178210
  };
178779
178211
  record.controller.abort();
178780
178212
  await attempt(() => record.listenTask);
178781
- await attempt(() => record.policyTail);
178782
- for (const policy of [...record.startedPolicies].reverse()) {
178783
- await attempt(() => policy.stop?.({
178784
- account: record.profile,
178785
- client: record.client,
178786
- fleet: this
178787
- }));
178788
- }
178213
+ errors.push(...await this.stopRecordPolicies(record));
178789
178214
  await attempt(() => record.unsubscribeRevoked());
178790
178215
  await attempt(() => record.client?.close());
178791
178216
  record.closed = true;
178792
- record.status = errors.length ? "error" : "stopped";
178217
+ record.status = errors.length || record.error ? "error" : "stopped";
178793
178218
  if (errors.length) {
178794
178219
  record.error = errors[0]?.message || String(errors[0]);
178795
178220
  }
@@ -179673,6 +179098,7 @@ class FleetOwner {
179673
179098
  this.homeDir = options2.homeDir || defaultHomeDir();
179674
179099
  this.openClient = options2.openClient || createAccountRuntime;
179675
179100
  this.policies = [...options2.policies || []];
179101
+ this.policyLoader = options2.policyLoader || null;
179676
179102
  this.lock = options2.lock || new FleetOwnerLock({
179677
179103
  homeDir: this.homeDir,
179678
179104
  name: this.manifest.name,
@@ -179712,13 +179138,22 @@ class FleetOwner {
179712
179138
  throw new Error(`fleet account index missing: ${profile.profile}`);
179713
179139
  }
179714
179140
  const material = deriveFleetAccount(this.seed, profile.accountIndex);
179141
+ const accountIndex = profile.accountIndex;
179715
179142
  try {
179716
179143
  return {
179717
179144
  ...await this.baseClientOptions(profile),
179718
179145
  homeDir: this.homeDir,
179719
179146
  activate: false,
179720
179147
  credential: material.credential,
179721
- vaultSecret: material.vaultSecret
179148
+ vaultSecret: material.vaultSecret,
179149
+ getVaultMasterSeed: () => {
179150
+ const derived = deriveFleetAccount(this.seed, accountIndex);
179151
+ try {
179152
+ return derived.masterSeed.slice();
179153
+ } finally {
179154
+ derived.destroy();
179155
+ }
179156
+ }
179722
179157
  };
179723
179158
  } finally {
179724
179159
  material.destroy();
@@ -179768,6 +179203,33 @@ class FleetOwner {
179768
179203
  this.policies.push(policy);
179769
179204
  return this;
179770
179205
  }
179206
+ setPolicyLoader(loader) {
179207
+ if (typeof loader !== "function") {
179208
+ throw new Error("fleet policy loader required");
179209
+ }
179210
+ this.policyLoader = loader;
179211
+ return this;
179212
+ }
179213
+ reload() {
179214
+ return this.mutate(async () => {
179215
+ const manifest = await loadFleetManifest({
179216
+ path: this.manifest.path
179217
+ });
179218
+ const policies = this.policyLoader ? await this.policyLoader() : this.policies;
179219
+ if (!Array.isArray(policies)) {
179220
+ throw new Error("fleet policy loader must return an array");
179221
+ }
179222
+ if (this.fleet) {
179223
+ await this.fleet.reconcile({
179224
+ profiles: manifest.profiles,
179225
+ policies
179226
+ });
179227
+ }
179228
+ this.manifest = manifest;
179229
+ this.policies = [...policies];
179230
+ return this.status();
179231
+ });
179232
+ }
179771
179233
  async stop() {
179772
179234
  if (!this.fleet) {
179773
179235
  await this.lock.release();