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