sealnet 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,8 +20,8 @@ and the SDK arrives as one global.
20
20
 
21
21
  ```html
22
22
  <script
23
- src="https://seal.net/sdk/v2.0.0/seal.js"
24
- integrity="sha384-9ZeXH0khtFG26aeQTB4tALMlc3cA8Yz29khqFiYdyA2qZoSAHPkPh2NtwBna2q50"
23
+ src="https://seal.net/sdk/v2.0.1/seal.js"
24
+ integrity="sha384-vOK/HzVVeGOp2usxeOgpmNBHovi8511y63zoXuNCfbo8wkRbmoLBiPeoTAHqZ4X1"
25
25
  crossorigin="anonymous"
26
26
  ></script>
27
27
  <script>
@@ -1,4 +1,4 @@
1
- sealnet 2.0.0 — third-party notices
1
+ sealnet 2.0.1 — third-party notices
2
2
 
3
3
  The standalone browser build (dist/seal.global.js, also published at
4
4
  https://seal.net/sdk/v<version>/seal.js) bundles the software below.
package/dist/index.cjs CHANGED
@@ -37,7 +37,7 @@ __export(index_exports, {
37
37
  module.exports = __toCommonJS(index_exports);
38
38
 
39
39
  // <define:__SEAL_WASM__>
40
- var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v2.0.0/seal_crypto.wasm", integrity: "sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018" };
40
+ var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v2.0.1/seal_crypto.wasm", integrity: "sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018" };
41
41
 
42
42
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
43
43
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
@@ -2475,7 +2475,7 @@ function abortError() {
2475
2475
  return new DOMException("Upload aborted", "AbortError");
2476
2476
  }
2477
2477
  async function runCryptoPipeline(options) {
2478
- const { stream, totalBytes, key: key2, header: header2, partSize, signal, yieldToRenderer, onSegment, onPart } = options;
2478
+ const { stream, totalBytes, key: key2, header: header2, partSize, signal, yieldToRenderer, onSegment } = options;
2479
2479
  const segmentSize = SEGMENT_SIZE;
2480
2480
  const segments = Math.max(1, Math.ceil(totalBytes / segmentSize));
2481
2481
  const encryptor = new Encryptor({ key: key2, header: header2 });
@@ -2536,8 +2536,12 @@ async function runCryptoPipeline(options) {
2536
2536
  };
2537
2537
  const emitPart = async (ciphertext) => {
2538
2538
  partNumber += 1;
2539
- const md5 = yieldToRenderer ? await contentMd5Yielding(ciphertext) : contentMd5(ciphertext);
2540
- await onPart(partNumber, ciphertext, md5);
2539
+ if (options.hashParts === false) {
2540
+ await options.onPart(partNumber, ciphertext);
2541
+ } else {
2542
+ const md5 = yieldToRenderer ? await contentMd5Yielding(ciphertext) : contentMd5(ciphertext);
2543
+ await options.onPart(partNumber, ciphertext, md5);
2544
+ }
2541
2545
  if (yieldToRenderer) await yieldToMain();
2542
2546
  };
2543
2547
  const wipe = async (buf) => {
@@ -2622,11 +2626,12 @@ function blobToSegmentStream(blob, segmentSize) {
2622
2626
  }
2623
2627
  });
2624
2628
  }
2625
- function runCryptoPipelineInWorker(worker, options) {
2629
+ function runCryptoPipelineInWorker(worker, hasher, options) {
2626
2630
  const { file, key: key2, header: header2, partSize, totalBytes, signal, initialCredits, onSegment, onPart } = options;
2627
2631
  return new Promise((resolve2, reject) => {
2628
2632
  let settled = false;
2629
2633
  let workerDone = false;
2634
+ let hashing = 0;
2630
2635
  let partChain = Promise.resolve();
2631
2636
  const fail = (err) => {
2632
2637
  if (settled) return;
@@ -2634,7 +2639,7 @@ function runCryptoPipelineInWorker(worker, options) {
2634
2639
  reject(err);
2635
2640
  };
2636
2641
  const maybeFinish = () => {
2637
- if (!workerDone) return;
2642
+ if (!workerDone || hashing > 0) return;
2638
2643
  void partChain.then(() => {
2639
2644
  if (settled) return;
2640
2645
  settled = true;
@@ -2648,7 +2653,7 @@ function runCryptoPipelineInWorker(worker, options) {
2648
2653
  }
2649
2654
  signal.addEventListener("abort", () => fail(abortError()), { once: true });
2650
2655
  }
2651
- worker.onerror = (event) => {
2656
+ worker.onerror = hasher.onerror = (event) => {
2652
2657
  fail(new Error(`crypto worker crashed: ${String(event?.message ?? event)}`));
2653
2658
  };
2654
2659
  worker.onmessage = (event) => {
@@ -2658,12 +2663,11 @@ function runCryptoPipelineInWorker(worker, options) {
2658
2663
  return;
2659
2664
  }
2660
2665
  if (msg.type === "part") {
2661
- const ciphertext = new Uint8Array(msg.buffer);
2662
- partChain = partChain.then(async () => {
2663
- if (settled) return;
2664
- await onPart(msg.partNumber, ciphertext, msg.md5);
2665
- worker.postMessage({ type: "credit" });
2666
- }).catch(fail);
2666
+ hashing += 1;
2667
+ hasher.postMessage(
2668
+ { type: "md5", partNumber: msg.partNumber, buffer: msg.buffer },
2669
+ [msg.buffer]
2670
+ );
2667
2671
  return;
2668
2672
  }
2669
2673
  if (msg.type === "done") {
@@ -2671,7 +2675,19 @@ function runCryptoPipelineInWorker(worker, options) {
2671
2675
  maybeFinish();
2672
2676
  return;
2673
2677
  }
2674
- fail(new Error(msg.message));
2678
+ if (msg.type === "error") fail(new Error(msg.message));
2679
+ };
2680
+ hasher.onmessage = (event) => {
2681
+ const msg = event.data;
2682
+ if (msg.type !== "md5") return;
2683
+ hashing -= 1;
2684
+ const ciphertext = new Uint8Array(msg.buffer);
2685
+ partChain = partChain.then(async () => {
2686
+ if (settled) return;
2687
+ await onPart(msg.partNumber, ciphertext, msg.md5);
2688
+ worker.postMessage({ type: "credit" });
2689
+ }).catch(fail);
2690
+ maybeFinish();
2675
2691
  };
2676
2692
  const keyBuf = new ArrayBuffer(key2.length);
2677
2693
  new Uint8Array(keyBuf).set(key2);
@@ -3528,18 +3544,21 @@ async function multipartUploadStream(options) {
3528
3544
  onPart: onPipelinePart
3529
3545
  });
3530
3546
  const workerFactory = getCryptoWorkerFactory();
3531
- let cryptoWorker = null;
3547
+ let cryptoWorkers = null;
3532
3548
  if (sourceFile && workerFactory && typeof document !== "undefined") {
3549
+ let first = null;
3533
3550
  try {
3534
- cryptoWorker = workerFactory();
3551
+ first = workerFactory();
3552
+ cryptoWorkers = [first, workerFactory()];
3535
3553
  } catch {
3536
- cryptoWorker = null;
3554
+ first?.terminate();
3537
3555
  }
3538
3556
  }
3539
- if (cryptoWorker) {
3557
+ if (cryptoWorkers) {
3558
+ const [cryptoWorker, md5Worker] = cryptoWorkers;
3540
3559
  log3.debug("crypto pipeline: worker");
3541
3560
  try {
3542
- await runCryptoPipelineInWorker(cryptoWorker, {
3561
+ await runCryptoPipelineInWorker(cryptoWorker, md5Worker, {
3543
3562
  file: sourceFile,
3544
3563
  key: keyCopy,
3545
3564
  header: header2,
@@ -3559,6 +3578,7 @@ async function multipartUploadStream(options) {
3559
3578
  await runInlinePipeline();
3560
3579
  } finally {
3561
3580
  cryptoWorker.terminate();
3581
+ md5Worker.terminate();
3562
3582
  }
3563
3583
  } else {
3564
3584
  await runInlinePipeline();
@@ -6203,7 +6223,7 @@ async function dismissItem(api, item, opts) {
6203
6223
  }
6204
6224
 
6205
6225
  // src/index.ts
6206
- var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/2.0.0".split("/");
6226
+ var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/2.0.1".split("/");
6207
6227
  if (typeof globalThis.process?.versions?.node !== "string") {
6208
6228
  configureWasm(define_SEAL_WASM_default);
6209
6229
  }
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // <define:__SEAL_WASM__>
2
- var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v2.0.0/seal_crypto.wasm", integrity: "sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018" };
2
+ var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v2.0.1/seal_crypto.wasm", integrity: "sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018" };
3
3
 
4
4
  var __defProp = Object.defineProperty;
5
5
  var __export = (target, all) => {
@@ -2434,7 +2434,7 @@ function abortError() {
2434
2434
  return new DOMException("Upload aborted", "AbortError");
2435
2435
  }
2436
2436
  async function runCryptoPipeline(options) {
2437
- const { stream, totalBytes, key: key2, header: header2, partSize, signal, yieldToRenderer, onSegment, onPart } = options;
2437
+ const { stream, totalBytes, key: key2, header: header2, partSize, signal, yieldToRenderer, onSegment } = options;
2438
2438
  const segmentSize = SEGMENT_SIZE;
2439
2439
  const segments = Math.max(1, Math.ceil(totalBytes / segmentSize));
2440
2440
  const encryptor = new Encryptor({ key: key2, header: header2 });
@@ -2495,8 +2495,12 @@ async function runCryptoPipeline(options) {
2495
2495
  };
2496
2496
  const emitPart = async (ciphertext) => {
2497
2497
  partNumber += 1;
2498
- const md5 = yieldToRenderer ? await contentMd5Yielding(ciphertext) : contentMd5(ciphertext);
2499
- await onPart(partNumber, ciphertext, md5);
2498
+ if (options.hashParts === false) {
2499
+ await options.onPart(partNumber, ciphertext);
2500
+ } else {
2501
+ const md5 = yieldToRenderer ? await contentMd5Yielding(ciphertext) : contentMd5(ciphertext);
2502
+ await options.onPart(partNumber, ciphertext, md5);
2503
+ }
2500
2504
  if (yieldToRenderer) await yieldToMain();
2501
2505
  };
2502
2506
  const wipe = async (buf) => {
@@ -2581,11 +2585,12 @@ function blobToSegmentStream(blob, segmentSize) {
2581
2585
  }
2582
2586
  });
2583
2587
  }
2584
- function runCryptoPipelineInWorker(worker, options) {
2588
+ function runCryptoPipelineInWorker(worker, hasher, options) {
2585
2589
  const { file, key: key2, header: header2, partSize, totalBytes, signal, initialCredits, onSegment, onPart } = options;
2586
2590
  return new Promise((resolve2, reject) => {
2587
2591
  let settled = false;
2588
2592
  let workerDone = false;
2593
+ let hashing = 0;
2589
2594
  let partChain = Promise.resolve();
2590
2595
  const fail = (err) => {
2591
2596
  if (settled) return;
@@ -2593,7 +2598,7 @@ function runCryptoPipelineInWorker(worker, options) {
2593
2598
  reject(err);
2594
2599
  };
2595
2600
  const maybeFinish = () => {
2596
- if (!workerDone) return;
2601
+ if (!workerDone || hashing > 0) return;
2597
2602
  void partChain.then(() => {
2598
2603
  if (settled) return;
2599
2604
  settled = true;
@@ -2607,7 +2612,7 @@ function runCryptoPipelineInWorker(worker, options) {
2607
2612
  }
2608
2613
  signal.addEventListener("abort", () => fail(abortError()), { once: true });
2609
2614
  }
2610
- worker.onerror = (event) => {
2615
+ worker.onerror = hasher.onerror = (event) => {
2611
2616
  fail(new Error(`crypto worker crashed: ${String(event?.message ?? event)}`));
2612
2617
  };
2613
2618
  worker.onmessage = (event) => {
@@ -2617,12 +2622,11 @@ function runCryptoPipelineInWorker(worker, options) {
2617
2622
  return;
2618
2623
  }
2619
2624
  if (msg.type === "part") {
2620
- const ciphertext = new Uint8Array(msg.buffer);
2621
- partChain = partChain.then(async () => {
2622
- if (settled) return;
2623
- await onPart(msg.partNumber, ciphertext, msg.md5);
2624
- worker.postMessage({ type: "credit" });
2625
- }).catch(fail);
2625
+ hashing += 1;
2626
+ hasher.postMessage(
2627
+ { type: "md5", partNumber: msg.partNumber, buffer: msg.buffer },
2628
+ [msg.buffer]
2629
+ );
2626
2630
  return;
2627
2631
  }
2628
2632
  if (msg.type === "done") {
@@ -2630,7 +2634,19 @@ function runCryptoPipelineInWorker(worker, options) {
2630
2634
  maybeFinish();
2631
2635
  return;
2632
2636
  }
2633
- fail(new Error(msg.message));
2637
+ if (msg.type === "error") fail(new Error(msg.message));
2638
+ };
2639
+ hasher.onmessage = (event) => {
2640
+ const msg = event.data;
2641
+ if (msg.type !== "md5") return;
2642
+ hashing -= 1;
2643
+ const ciphertext = new Uint8Array(msg.buffer);
2644
+ partChain = partChain.then(async () => {
2645
+ if (settled) return;
2646
+ await onPart(msg.partNumber, ciphertext, msg.md5);
2647
+ worker.postMessage({ type: "credit" });
2648
+ }).catch(fail);
2649
+ maybeFinish();
2634
2650
  };
2635
2651
  const keyBuf = new ArrayBuffer(key2.length);
2636
2652
  new Uint8Array(keyBuf).set(key2);
@@ -3487,18 +3503,21 @@ async function multipartUploadStream(options) {
3487
3503
  onPart: onPipelinePart
3488
3504
  });
3489
3505
  const workerFactory = getCryptoWorkerFactory();
3490
- let cryptoWorker = null;
3506
+ let cryptoWorkers = null;
3491
3507
  if (sourceFile && workerFactory && typeof document !== "undefined") {
3508
+ let first = null;
3492
3509
  try {
3493
- cryptoWorker = workerFactory();
3510
+ first = workerFactory();
3511
+ cryptoWorkers = [first, workerFactory()];
3494
3512
  } catch {
3495
- cryptoWorker = null;
3513
+ first?.terminate();
3496
3514
  }
3497
3515
  }
3498
- if (cryptoWorker) {
3516
+ if (cryptoWorkers) {
3517
+ const [cryptoWorker, md5Worker] = cryptoWorkers;
3499
3518
  log3.debug("crypto pipeline: worker");
3500
3519
  try {
3501
- await runCryptoPipelineInWorker(cryptoWorker, {
3520
+ await runCryptoPipelineInWorker(cryptoWorker, md5Worker, {
3502
3521
  file: sourceFile,
3503
3522
  key: keyCopy,
3504
3523
  header: header2,
@@ -3518,6 +3537,7 @@ async function multipartUploadStream(options) {
3518
3537
  await runInlinePipeline();
3519
3538
  } finally {
3520
3539
  cryptoWorker.terminate();
3540
+ md5Worker.terminate();
3521
3541
  }
3522
3542
  } else {
3523
3543
  await runInlinePipeline();
@@ -6162,7 +6182,7 @@ async function dismissItem(api, item, opts) {
6162
6182
  }
6163
6183
 
6164
6184
  // src/index.ts
6165
- var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/2.0.0".split("/");
6185
+ var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/2.0.1".split("/");
6166
6186
  if (typeof globalThis.process?.versions?.node !== "string") {
6167
6187
  configureWasm(define_SEAL_WASM_default);
6168
6188
  }
@@ -1,5 +1,5 @@
1
- /*! sealnet v2.0.0 | Proprietary — see LICENSE | bundles MIT-licensed @noble/hashes (Copyright (c) 2022 Paul Miller (https://paulmillr.com)), fflate (Copyright (c) 2023 Arjun Barrett) | full texts: THIRD-PARTY-NOTICES.txt */
2
- "use strict";var Seal=(()=>{var Ua=Object.create;var At=Object.defineProperty;var Fa=Object.getOwnPropertyDescriptor;var $a=Object.getOwnPropertyNames;var Ha=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var Wn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var za=(e,t)=>{for(var n in t)At(e,n,{get:t[n],enumerable:!0})},zn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of $a(t))!Wa.call(e,a)&&a!==n&&At(e,a,{get:()=>t[a],enumerable:!(r=Fa(t,a))||r.enumerable});return e};var Kn=(e,t,n)=>(n=e!=null?Ua(Ha(e)):{},zn(t||!e||!e.__esModule?At(n,"default",{value:e,enumerable:!0}):n,e)),Ka=e=>zn(At({},"__esModule",{value:!0}),e);var Ai={};za(Ai,{SealClient:()=>Nn,SealError:()=>K,VERSION:()=>Si});var be={url:"https://seal.net/sdk/v2.0.0/seal_crypto.wasm",integrity:"sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018"};var Es={},ja=Object.defineProperty,Ya=(e,t)=>{for(var n in t)ja(e,n,{get:t[n],enumerable:!0})},qn={};Ya(qn,{WasmIdentity:()=>en,default:()=>ds,init:()=>Va,initSync:()=>cs,wasm_bundle_address:()=>qa,wasm_bundle_verify_for_address:()=>Xa,wasm_contract_message:()=>Za,wasm_ed25519_verify:()=>Ja,wasm_sealbox_unwrap:()=>Qa,wasm_sealbox_wrap:()=>es,wasm_unwrap_file_key:()=>ts,wasm_wrap_file_key:()=>ns});var en=class Tt{static __wrap(t){let n=Object.create(Tt.prototype);return n.__wbg_ptr=t,Gn.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Gn.unregister(this),t}free(){let t=this.__destroy_into_raw();c.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_address(s,this.__wbg_ptr);var r=m().getInt32(s+0,!0),a=m().getInt32(s+4,!0);return t=r,n=a,Fe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}bundle(){let t=c.wasmidentity_bundle(this.__wbg_ptr);return H(t)}static fromSeed32(t){try{let s=c.__wbindgen_add_to_stack_pointer(-16),o=J(t,c.__wbindgen_export3),i=v;c.wasmidentity_fromSeed32(s,o,i);var n=m().getInt32(s+0,!0),r=m().getInt32(s+4,!0),a=m().getInt32(s+8,!0);if(a)throw H(r);return Tt.__wrap(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=J(t,c.__wbindgen_export3),l=v;c.wasmidentity_fromSeed64(o,i,l,n);var r=m().getInt32(o+0,!0),a=m().getInt32(o+4,!0),s=m().getInt32(o+8,!0);if(s)throw H(a);return Tt.__wrap(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=J(n,c.__wbindgen_export3),l=v;c.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,l);var r=m().getInt32(o+0,!0),a=m().getInt32(o+4,!0),s=m().getInt32(o+8,!0);if(s)throw H(a);return H(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}legacyAddress(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_legacyAddress(s,this.__wbg_ptr);var r=m().getInt32(s+0,!0),a=m().getInt32(s+4,!0);return t=r,n=a,Fe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}open(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=J(t,c.__wbindgen_export3),d=v,p=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),f=v,u=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),_=v;c.wasmidentity_open(i,this.__wbg_ptr,l,d,p,f,u,_);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signContract(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ae(t,c.__wbindgen_export3,c.__wbindgen_export4),d=v,p=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),f=v,u=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),_=v;c.wasmidentity_signContract(i,this.__wbg_ptr,l,d,p,f,u,_);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_words(s,this.__wbg_ptr);var r=m().getInt32(s+0,!0),a=m().getInt32(s+4,!0);return t=r,n=a,Fe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=J(t,c.__wbindgen_export3),l=v,d=J(n,c.__wbindgen_export3),p=v;c.wasmidentity_workloadProof(o,this.__wbg_ptr,i,l,d,p);var r=m().getInt32(o+0,!0),a=m().getInt32(o+4,!0),s=m().getInt32(o+8,!0);if(s)throw H(a);return H(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(en.prototype[Symbol.dispose]=en.prototype.free);function Va(){c.init()}function qa(e){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=J(e,c.__wbindgen_export3),o=v;c.wasm_bundle_address(a,s,o);var t=m().getInt32(a+0,!0),n=m().getInt32(a+4,!0),r=m().getInt32(a+8,!0);if(r)throw H(n);return H(t)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function Xa(e,t){let n=J(e,c.__wbindgen_export3),r=v,a=ae(t,c.__wbindgen_export3,c.__wbindgen_export4),s=v;return c.wasm_bundle_verify_for_address(n,r,a,s)!==0}function Za(e,t,n){let r,a;try{let f=c.__wbindgen_add_to_stack_pointer(-16),u=ae(e,c.__wbindgen_export3,c.__wbindgen_export4),_=v,h=ae(t,c.__wbindgen_export3,c.__wbindgen_export4),E=v,g=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),M=v;c.wasm_contract_message(f,u,_,h,E,g,M);var s=m().getInt32(f+0,!0),o=m().getInt32(f+4,!0),i=m().getInt32(f+8,!0),l=m().getInt32(f+12,!0),d=s,p=o;if(l)throw d=0,p=0,H(i);return r=d,a=p,Fe(d,p)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function Ja(e,t,n){let r=J(e,c.__wbindgen_export3),a=v,s=J(t,c.__wbindgen_export3),o=v,i=J(n,c.__wbindgen_export3),l=v;return c.wasm_ed25519_verify(r,a,s,o,i,l)!==0}function Qa(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=J(e,c.__wbindgen_export3),d=v,p=J(t,c.__wbindgen_export3),f=v,u=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),_=v,h=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),E=v;c.wasm_sealbox_unwrap(i,l,d,p,f,u,_,h,E);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function es(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=J(e,c.__wbindgen_export3),d=v,p=J(t,c.__wbindgen_export3),f=v,u=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),_=v,h=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),E=v;c.wasm_sealbox_wrap(i,l,d,p,f,u,_,h,E);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function ts(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=J(e,c.__wbindgen_export3),d=v,p=J(t,c.__wbindgen_export3),f=v,u=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),_=v,h=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),E=v;c.wasm_unwrap_file_key(i,l,d,p,f,u,_,h,E);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function ns(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=J(e,c.__wbindgen_export3),d=v,p=J(t,c.__wbindgen_export3),f=v,u=ae(n,c.__wbindgen_export3,c.__wbindgen_export4),_=v,h=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),E=v;c.wasm_wrap_file_key(i,l,d,p,f,u,_,h,E);var a=m().getInt32(i+0,!0),s=m().getInt32(i+4,!0),o=m().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function Xn(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof $(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=$(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof $(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return $(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Fe(t,n))},__wbg_call_a41d6421b30a32c5:function(){return st(function(t,n,r){let a=$(t).call($(n),$(r));return X(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=$(t).crypto;return X(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Fe(t,n))}finally{c.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return st(function(t,n){$(t).getRandomValues($(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return $(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=$(t).msCrypto;return X(n)},__wbg_new_227d7c05414eb861:function(){let t=new Error;return X(t)},__wbg_new_2fad8ca02fd00684:function(){let t=new Object;return X(t)},__wbg_new_from_slice_5a173c243af2e823:function(t,n){let r=new Uint8Array(Jt(t,n));return X(r)},__wbg_new_with_length_9011f5da794bf5d9:function(t){let n=new Uint8Array(t>>>0);return X(n)},__wbg_node_84ea875411254db1:function(t){let n=$(t).node;return X(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=$(t).process;return X(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(Jt(t,n),$(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return st(function(t,n){$(t).randomFillSync(H(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return st(function(){let t=module.require;return X(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return st(function(t,n,r){return Reflect.set($(t),$(n),$(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=$(n).stack,a=ae(r,c.__wbindgen_export3,c.__wbindgen_export4),s=v;m().setInt32(t+4,s,!0),m().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return vt(t)?0:X(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return vt(t)?0:X(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return vt(t)?0:X(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return vt(t)?0:X(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=$(t).subarray(n>>>0,r>>>0);return X(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=$(t).versions;return X(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=Jt(t,n);return X(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Fe(t,n);return X(r)},__wbindgen_object_clone_ref:function(t){let n=$(t);return X(n)},__wbindgen_object_drop_ref:function(t){H(t)}}}}var Gn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_wasmidentity_free(e,1));function X(e){it===xe.length&&xe.push(xe.length+1);let t=it;return it=xe[t],xe[t]=e,t}function rs(e){e<1028||(xe[e]=it,it=e)}function Jt(e,t){return e=e>>>0,Ye().subarray(e/1,e/1+t)}var Ue=null;function m(){return(Ue===null||Ue.buffer.detached===!0||Ue.buffer.detached===void 0&&Ue.buffer!==c.memory.buffer)&&(Ue=new DataView(c.memory.buffer)),Ue}function Fe(e,t){return ss(e>>>0,t)}var ot=null;function Ye(){return(ot===null||ot.byteLength===0)&&(ot=new Uint8Array(c.memory.buffer)),ot}function $(e){return xe[e]}function st(e,t){try{return e.apply(this,t)}catch(n){c.__wbindgen_export(X(n))}}var xe=new Array(1024).fill(void 0);xe.push(void 0,null,!0,!1);var it=xe.length;function vt(e){return e==null}function J(e,t){let n=t(e.length*1,1)>>>0;return Ye().set(e,n/1),v=e.length,n}function ae(e,t,n){if(n===void 0){let i=lt.encode(e),l=t(i.length,1)>>>0;return Ye().subarray(l,l+i.length).set(i),v=i.length,l}let r=e.length,a=t(r,1)>>>0,s=Ye(),o=0;for(;o<r;o++){let i=e.charCodeAt(o);if(i>127)break;s[a+o]=i}if(o!==r){o!==0&&(e=e.slice(o)),a=n(a,r,r=o+e.length*3,1)>>>0;let i=Ye().subarray(a+o,a+r),l=lt.encodeInto(e,i);o+=l.written,a=n(a,r,o,1)>>>0}return v=o,a}function H(e){let t=$(e);return rs(e),t}var kt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});kt.decode();var as=2146435072,Qt=0;function ss(e,t){return Qt+=t,Qt>=as&&(kt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),kt.decode(),Qt=t),kt.decode(Ye().subarray(e,e+t))}var lt=new TextEncoder;"encodeInto"in lt||(lt.encodeInto=function(e,t){let n=lt.encode(e);return t.set(n),{read:e.length,written:n.length}});var v=0,os,is,c;function Zn(e,t){return is=e,c=e.exports,os=t,Ue=null,ot=null,c}async function ls(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(a){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",a);else throw a}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}function cs(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Xn();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Zn(n,e)}async function ds(e){if(c!==void 0)return c;if(e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0)throw new Error("SEAL crypto: the WASM source must be passed to the loader");let t=Xn();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await ls(await e,t);return Zn(n,r)}var us="seal_crypto.wasm",ke=null,xt=null,je=null;function Jn(e){if(xt||je)throw new Error("configureWasm: the WASM is already loaded or loading");ke=e}function fs(){return typeof globalThis.process?.versions?.node=="string"}async function jn(e){let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}async function hs(){if(ke&&"url"in ke)return fetch(ke.url,ke.integrity?{integrity:ke.integrity}:{});if(ke&&"path"in ke)return jn(ke.path);if(fs())return jn(new URL(us,Es.url));throw new Error("sealnet: no WASM source in this browser (a broken build — reinstall sealnet)")}async function $e(){if(xt)return xt;if(je)return je;je=(async()=>{let e=qn;return await e.default({module_or_path:await hs()}),typeof e.init=="function"&&e.init(),xt=e,e})();try{return await je}catch(e){throw je=null,e}}async function ps(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Ve(e){let t=await ps(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}var Yn=32768,Vn=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function ys(e){let t="";for(let n=0;n<e.length;n+=Yn){let r=e.subarray(n,Math.min(n+Yn,e.length));t+=String.fromCharCode.apply(null,r)}return t}function _s(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function ws(e){let t=e.substring(0,20)+(e.length>20?"...":"");if(typeof atob<"u")try{return atob(e)}catch(n){throw new Vn(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new Vn(`Invalid base64 encoding: ${n.message}`,t)}}function gs(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function bs(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function ms(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ie(e){return gs(ys(e))}function Q(e){return ms(Ie(e))}function It(e){return _s(ws(e))}function Y(e){return It(bs(e))}function Ss(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Rt(e,...t){if(!Ss(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function tn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Qn(e,t){Rt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ct(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Lt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function me(e,t){return e<<32-t|e>>>t}function As(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function nn(e){return typeof e=="string"&&(e=As(e)),Rt(e),e}var Ot=class{};function er(e){let t=r=>e().update(nn(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function vs(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let a=BigInt(32),s=BigInt(4294967295),o=Number(n>>a&s),i=Number(n&s),l=r?4:0,d=r?0:4;e.setUint32(t+l,o,r),e.setUint32(t+d,i,r)}function tr(e,t,n){return e&t^~e&n}function nr(e,t,n){return e&t^e&n^t&n}var Pt=class extends Ot{constructor(t,n,r,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=a,this.buffer=new Uint8Array(t),this.view=Lt(this.buffer)}update(t){tn(this),t=nn(t),Rt(t);let{view:n,buffer:r,blockLen:a}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(a-this.pos,s-o);if(i===a){let l=Lt(t);for(;a<=s-o;o+=a)this.process(l,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===a&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){tn(this),Qn(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,ct(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let f=o;f<a;f++)n[f]=0;vs(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Lt(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=l/4,p=this.get();if(d>p.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<d;f++)i.setUint32(4*f,p[f],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:n,buffer:r,length:a,finished:s,destroyed:o,pos:i}=this;return t.destroyed=o,t.finished=s,t.length=a,t.pos=i,a%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ts=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),De=new Uint32Array(64),rn=class extends Pt{constructor(t=32){super(64,t,8,!1),this.A=Oe[0]|0,this.B=Oe[1]|0,this.C=Oe[2]|0,this.D=Oe[3]|0,this.E=Oe[4]|0,this.F=Oe[5]|0,this.G=Oe[6]|0,this.H=Oe[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:l}=this;return[t,n,r,a,s,o,i,l]}set(t,n,r,a,s,o,i,l){this.A=t|0,this.B=n|0,this.C=r|0,this.D=a|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=l|0}process(t,n){for(let f=0;f<16;f++,n+=4)De[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let u=De[f-15],_=De[f-2],h=me(u,7)^me(u,18)^u>>>3,E=me(_,17)^me(_,19)^_>>>10;De[f]=E+De[f-7]+h+De[f-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:l,G:d,H:p}=this;for(let f=0;f<64;f++){let u=me(i,6)^me(i,11)^me(i,25),_=p+u+tr(i,l,d)+Ts[f]+De[f]|0,E=(me(r,2)^me(r,13)^me(r,22))+nr(r,a,s)|0;p=d,d=l,l=i,i=o+_|0,o=s,s=a,a=r,r=_+E|0}r=r+this.A|0,a=a+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,l=l+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(r,a,s,o,i,l,d,p)}roundClean(){ct(De)}destroy(){this.set(0,0,0,0,0,0,0,0),ct(this.buffer)}};var Bt=er(()=>new rn);var he={version:2,name:"AEON",magic_bytes:[65,69,79,52],magic_length:4,header_length:24,header_layout:[{name:"magic",offset:0,length:4},{name:"segment_size_u32_le",offset:4,length:4},{name:"file_id",offset:8,length:16}],nonce_length:12,tag_length:16,segment_overhead:28,segment_size_bytes:1048576,min_segment_size_bytes:1048576,max_segment_size_bytes:67108864,aad_layout:[{name:"header",length:24},{name:"segment_index_u64_le",length:8},{name:"last_u8",length:1}],supported_format_versions:[3,4],current_format_version:4,v3_reader:{magic_bytes:[65,69,79,78],header_length:8}},hn=new Uint8Array(he.magic_bytes),Nt=he.magic_length,Me=he.header_length,qe=he.nonce_length,pn=he.tag_length,kr=he.segment_overhead,Kt=he.segment_size_bytes,rr=he.min_segment_size_bytes,ar=he.max_segment_size_bytes,ft=he.header_layout.find(e=>e.name==="file_id"),sr=he.aad_layout.reduce((e,t)=>e+t.length,0),xr=new Uint8Array(he.v3_reader.magic_bytes),Ir=he.v3_reader.header_length;function ks(e){return qe+e+pn}function yn(e){let t=Math.max(1,Math.ceil(e/Kt));return Me+t*kr+e}function xs(){let e=new Uint8Array(Me);return e.set(hn,0),new DataView(e.buffer).setUint32(Nt,Kt,!0),e.set(crypto.getRandomValues(new Uint8Array(ft.length)),ft.offset),e}function Ut(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function Or(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(Nt,!0);if(t<rr||t>ar)throw new Error(`segment size ${t} is outside ${rr}\u2026${ar}`);return t}function Rr(e){if(e.length<Me)throw new Error(`an AEON v4 header is ${Me} bytes, got ${e.length}`);if(!Ut(e,hn))throw new Error("not an AEON v4 header");return{segmentSize:Or(e),fileId:e.slice(ft.offset,ft.offset+ft.length)}}function Is(e){if(e.length<Ir||!Ut(e,xr))throw new Error("not an AEON v3 header");return{segmentSize:Or(e)}}function Os(e){return Ut(e,hn)?"v4":Ut(e,xr)?"v3":null}function Lr(e,t,n){let r=new Uint8Array(sr);return r.set(e.subarray(0,Me),0),new DataView(r.buffer).setBigUint64(Me,BigInt(t),!0),r[sr-1]=n?1:0,r}function Rs(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function Pr(e){return crypto.subtle.importKey("raw",Rs(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Ls(e,t,n){let r=crypto.getRandomValues(new Uint8Array(qe)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:pn*8,additionalData:n},e,t),s=new Uint8Array(qe+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),qe),s}async function Ps(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,qe),tagLength:pn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(qe)))}function Bs(){return Bt.create()}async function ht(){let e=globalThis.scheduler;return typeof e?.yield=="function"?e.yield():typeof MessageChannel<"u"?new Promise(t=>{let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(null)}):new Promise(t=>setTimeout(t,0))}function Ds(){return crypto.getRandomValues(new Uint8Array(32))}var Ke={version:1,limits:{MAX_FILES_PER_SEAL:30,FREE_TIER_BYTES:1073741824,MAX_TOTAL_SIZE_BYTES:1073741824,MAX_FILE_SIZE_BYTES:10737418240,MAX_MULTIPART_FILE_SIZE_BYTES:10737418240,MAX_BLOB_SIZE:1048576,MAX_BLOB_BASE64_SIZE:1468006,MAX_MESSAGE_LENGTH:5e3,MAX_FILE_KEYS:1e4,MAX_ACTIVE_UPLOADS_PER_SEAL:10,MAX_OPENS_PER_SEAL_FREE:10,TIER_BYTES:{free:1073741824,"5gb":5368709120,"50gb":53687091200,"500gb":536870912e3},SEAL_TIERS:{"5gb":{bytes:5368709120,amount_cents:900,duration_days:90,name:"5 GB / 3 months",description:"One-time payment for 5 GB storage and 3 months TTL"},"50gb":{bytes:53687091200,amount_cents:2900,duration_days:180,name:"50 GB / 6 months",description:"One-time payment for 50 GB storage and 6 months TTL"},"500gb":{bytes:536870912e3,amount_cents:9900,duration_days:365,name:"500 GB / 12 months",description:"One-time payment for 500 GB storage and 12 months TTL"}},PRO_REGIONS:["eu-west","us-east","us-west","apac-southeast","apac-northeast"],ttl_options:["5m","30m","1h","1d","7d"],OTP_LENGTH:{min:6,max:10},USER_PASSWORD_MIN_LENGTH:8,INTAKE_TTL_DEFAULT_SECONDS:900,INTAKE_TTL_MAX_SECONDS:86400,INTAKE_WAIT_MAX_SECONDS:25,PAYMENT_WAIT_MAX_SECONDS:82800,ADDRESS_PROOF_TTL_SECONDS:300,INBOX_MAX_ITEMS:200,DRIVE_OPEN_TTL_SECONDS:300,DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES:67108864,DRIVE_PRESIGN_WINDOW_MIN_BYTES:8388608,DRIVE_PRESIGN_UNBOUND_TTL_SECONDS:30,DRIVE_WRITE_LEASE_SECONDS:7200,DRIVE_WRITE_BACK_SECONDS:5,VERSION_RETENTION_DAYS_DEFAULT:30,VERSION_KEEP_MIN:10,GRANT_WORKLOAD_MAX_TTL_DAYS:90,SENSOR_OPENS_PER_MINUTE_DEFAULT:120,SENSOR_BYTES_PER_MINUTE_DEFAULT:2147483648,SENSOR_SECRETS_PER_MINUTE_DEFAULT:20,SENSOR_NOVELTY_WINDOW_DAYS:30,SENSOR_HOLD_TTL_SECONDS:86400,SENSOR_BASELINE_MIN_HOURS:72,SENSOR_GROWTH_BYTES_PER_DAY_DEFAULT:107374182400}},Le={version:2,$comment:"Address of a bundle: who a seal is for, without a URL (SPEC-AEON-V4 \xA75). Numbers live in limits.json, error codes in error_codes.json, the bundle and the wrap in crypto.json (keybundle, sealed_box_v2).",address:{of:"SHA-256 of the identity key (Ed25519) of the bundle v2, 32 bytes",text:"base64url without padding, 43 characters",words:"fingerprint_words.json over the first three bytes of the address: the words of SHA-256(identity key), named without hashing again",inbox:"the 32 bytes of the address are the key the server finds an inbox by"},box_origin:"https://box.seal.net",seed:{env:"SEAL_SEED",text:"base64url without padding of the 32-byte seed of an agent, a device or an inbox, 43 characters",derives:"the agreement key (X25519) is the seed itself; the identity key (Ed25519) and the ML-KEM-768 key are HKDF of the seed (crypto.json hkdf.identity_key_salt, info_prefixes workload_identity and kem_mlkem768) \u2014 together the bundle v2 the address names",same_as:["sealnet-mcp state.identity.x25519_secret_b64","seal identity.v1.json x25519_secret_b64url","sealnet (npm) KeyPair.secretKey","sealnet (PyPI) keygen().secret_key"]},bundles:{put:"PUT /intake/bundles {bundle}: bundle is base64url of the packed bundle (crypto.json keybundle.packed_length). The server verifies it with the core and files it under the address it computes; no authorization \u2014 the bundle proves itself \u2014 and a limit per IP",get:"GET /intake/bundles/{address} -> {bundle}; 404 intake.bundle_not_found",accept:"a sender takes a bundle only if SHA-256 of its identity key is the address and its signature verifies; a client puts its own bundle at its first start and again whenever it is gone"},scopes:{share_link:"seal_share",owner_copy:"seal_owner"},proof:{header_address:"X-Seal-Address",header_proof:"X-Seal-Proof",challenge:"POST /intake/proof {address} -> {ts, challenge}: challenge = base64url(HMAC(server key, address(32) || ts u64 BE)), 43 characters; the server keeps no state",message:'"seal:inbox-proof:v2" || address(32) || ts u64 BE || challenge(32), signed with the identity key of the address; the core builds it (Identity::inbox_proof)',proof_text:"<ts>.<challenge>.<signature>: ts the decimal Unix second of the challenge, challenge as received, signature base64url of 64 bytes",check:"the window, the HMAC, and the signature against the bundle of the address with a small-order key refused"},items:{delivery:{id:"s.<seal_id>.<share_code>",is:"a share link addressed to this address: path /s/<seal_id>/<share_code> without a fragment; fragment = its key wrapped to the address's bundle (sealed box v2, scope share_link)"},owner:{id:"o.<seal_id>",is:"the seal's owner-blob key wrapped to the address's bundle (sealed box v2, scope owner_copy); path /s/<seal_id> opens the seal page, the only place that manages a seal"},request:{id:"r.<intake_id>",is:"a request asked of this address; path /i/<intake_id>, no fragment; carries what, kind and recipient_bundle"},listing:"GET /intake?to= lists deliveries only, as before owner copies and cards existed; `all=1` adds owner and request items (a person's inbox). Agent clients never send it: those rows are a person's."},request:{recipient_bundle:"POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it and shows the three words of its address, the answer's key is wrapped to it (scope share_link) and comes back as the request's fragment, with share_path without a fragment"},owner_copy:{web_label:"seal.net",is:"The seal names the inbox that manages it: its row carries the owner-blob key wrapped to that address's bundle, one per seal, written with the owner blob (PATCH /seal/{id}/blob with to, fragment, label) before the first byte of the files. Best effort: an address without a bundle is the same PATCH without the address part, and the seal is made anyway."},request_kinds:["secret","file","any","pair","device"],pair_what:"inbox",payloads:{name_max:80,pair:{mime:"application/vnd.seal.pairing+json",json:`{"v":2,"bundle":"<the inbox's packed bundle, base64url, 1755>","name":"<inbox name, at most name_max>"}`},device:{mime:"application/vnd.seal.device+json",json:'{"v":2,"seed":"<inbox seed, 43>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>"}]}'}},device_link:{code:"8 Crockford base32 characters from 5 random bytes",what:"base64url(HMAC-SHA256(key = the code in ASCII, message = the 32-byte address of the new device)), 43 characters: the what of the device request",link:"https://box.seal.net/#link=<address>.<code>"},bridge:{path:"/bridge",is:"A hidden iframe of box_origin on seal.net; postMessage only between the two origins. It never gives out the address or the name: it answers any script of seal.net.",hello:"box.hello {sealId?} -> {box: boolean, has: boolean}; box: this device has an inbox; has: this seal is already in Yours",owner_copy:"box.ownerCopy {sealId, ownerToken, linkKey} -> {ok: boolean}"},migrate:{until:"C1 + 7 days (C1 \xA76)",is:"Every inbox and agent changes its address once (\xA75.7). The X25519 key does not change \u2014 it is the seed \u2014 so the client moves the live rows of its old address once, under the proof of its new one: POST /intake/migrate {old_address} answers the old challenge, {old_address, old_proof} moves links, owner copies, cards and push subscriptions; the agreement key of the new address's bundle must equal the old address, and the senders of moved rows are cleared. Zero rows is a success.",old_address:"the X25519 public key of the seed, base64url without padding, 43 characters",challenge:"sealed box v1 of a 32-byte token to the old address with scope (address_proof, decimal ts): ephemeral_pub(32) || nonce(12) || ciphertext(48), base64url, 123 characters",old_proof:"<ts>.<token>: token base64url of the 32 bytes the challenge opens to",scope_address_proof:"seal_address_proof",vector:{comment:"every client that migrates must open it",secret:"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",address:"E75P6uryBMf9M1j8nAByGIHRdCeBKCJ-xnTzf3_pe20",ts:179e7,challenge:"4Oel-UMfgP_1dBhmf13yZiujhPDouCIQ6sSx1nY1qy-vyzFqDqb9jARbJ0e5A8vv4EDELDS5OPqBQMcsmDA-C_lXO95y_CVUyYtSu-1fltsy5ZihOFDp0T-C9Ro",token:"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"}},vectors:[{address:"Afdcc-OkgjU572_xdbUHZSNPO6r6Up6ctP2pfF0PHJw",bundle:"4rFhOdoKNSNI9qMxGju3FssbOjE0YN8CnitU4OD4dW4Eun0cCRx-W2Ad-PsAyD8R9LVv_v5mxs08kUEG5VurbwtRz7BXT4NoZoZytUXshnRVuBnjT3nghVcGmLLCpUi4qVzBsZOkO3e7tBbmAHsnDDF1eEPkjS0zQ6s6mkmFbHQnANoFXUnSM6ESOpPMmi11pv4QE9XYRpj2C_5JzmFXWLiYTA3pucRjUgPZkSmgp38RGRWZbcpsexeMmmJCdEolY52MoQaJesxJYRPgzlMSa9YnEICxfr8Xuwkgpxw3ucOxMolUXQKUBToGfUUxtC7BHrq2W3wEcF4LJaFytD44qdW2Ze0LSf8IlsESZWj6YbLabL25FAwmGntZKHQ7LDK7C4ZXsNVioS9yDNh1ADaqdTqGZnPlDaI2HiDCGVMzVTOQRvt6BZWKSUNrudd7t-2JxyUCWFk5szNrcUVJwsBrNdIXm_04iuvbcW-4s-kmXmX6CStgPdZSVgFgcAOQwsOwU57zjoA0pehUqiLwaHbLu0Z5poD1agnppIXItFLhVkRDExOHF7KxUD70CEJjUrHxxf0ln4H1S1t3udfFTA11SjBYXsTxq0VIMDoTnXzYenHLWXpYwDlogzagyb1UXfprRkNgbssmd9xyw_aKz2AWjAdqpeAmIwVbnlfcxA-0MixZpVtkpSyZeXhwAPf8Q0raFNESLbJSBx1GStgiNzNkf553RC0JCLXITOw6YHuyQKF8y05gFwXTjJ0hBwUgTEQVJt71miJ8N7asYFDrAVSWm7t0qA55RobkTdnBliKCCjrnKxGET5M0sPrlyC3yTUu3fHrpEDRqiN8yFZRpD9QBXtaorIM8b6XcVAWJFKjauhn5tC4RAJDEi384o_NQAg0WowA3UuJ0LFg5ELRGQuZCrP_RVIHGAR5lcOeSY9SzW-dmp-MbsfSWf_iBEkYsc_iFTwkTf3M5Thd4TSJxwJ9odRS0LqRZgrgEWcYYl5PalYYrBHqhsMiAshpzibQLTPbQh1CUMTLMIrorvqVbhdZovQmSdShIWLTmkhWJGN_seAfnQNFhufXlg2dsNSGZCdcivn_VfKUHFpm8DOHRCqWcdwcrw7K3gtPgTC2GQvSJxAH6pq5hshTKCqF6mtFiA2-FbjYwDhRskt8Mf15IkQWDCI2LNDnJLg6qPMbaMxUEyWd7N1QWmHNgtU9syAMLhVHsHlohPq8ZdygIRIw6IjbFR0EDb8jYhY1DQUc3WWLQX_AsdMwHNgeRzhlcd2fohE5BzB_Lb3V1NpmsMPe2FhmGD8b3Pb-1ZR-MtJD6tgq1YSs7JOeWjKETlN2YqCaIFCeRWUIygkpbF158x4lVqqgQQZ70kzXsJTWJZbY5mvXHbAUsWLezERn4hWWKau_Mno78GTRKZfO5ymbWl4Hku8ECskl3dL8oy5hAOGhGcGOyhDLXISTTZL3JQ2Qwy0X7AfqDIQCTnuCLa3_AhIsjMXFzB-rCq8WjUsh4YsW1ENBJjV_2G6-HWRVDpo6nIDVnZRGxATTCvnLjXcn0USEXsBI6R6aAcgqGXzabd_QyLpK2EdUnaH3xIWjGYsdRjIuUWQM3odyjH7TFOurwlQV3hU2KMmAO13XqmD5fvhxVi5-kWTnN16EDDV0EXLky4Jug0SNgHchy3ymbXVBx8TfsJcCumYk9iuui2D-cDpa7KJEGwBVN-9lvLEidQddWX_CMfbmG_wdHaC4Hapi-U2OhsH-2AwEAAAA",challenge:"wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8",comment:"generated once by shared/core (Identity::from_seed32, Identity::inbox_proof); every client must reproduce it",legacy_address:"BLp9HAkcfltgHfj7AMg_EfS1b_7-ZsbNPJFBBuVbq28",proof:"1790000000.wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8.74s5T1rE2xRNbameeTbYUHVMN-ZzFu1JBPZJNtH8eYC1vV7-h2HE_hxgo4vUB0_sHFfdYRUf0bve4_KGe32ICg",seed:"Aw4ZJC86RVBbZnF8h5KdqLO-ydTf6vUACxYhLDdCTVg",signature:"74s5T1rE2xRNbameeTbYUHVMN-ZzFu1JBPZJNtH8eYC1vV7-h2HE_hxgo4vUB0_sHFfdYRUf0bve4_KGe32ICg",ts:179e7,words:"album wren hedge"}]},Cs="X-Seal-Client",L={version:1,upload:{DEFAULT_PART_SIZE_BYTES:16777216,S3_MIN_PART_SIZE_BYTES:5242880,MAX_PART_SIZE_BYTES:268435456,MULTIPART_THRESHOLD_BYTES:8388608,FINE_PART_SIZE_BYTES:8388608,FINE_PART_MAX_FILE_BYTES:536870912,INMEMORY_BLOB_LIMIT_BYTES:104857600,MULTIPART_UPLOAD_TTL_SECONDS:86400,PRESIGN_BATCH_SIZE:100,SMALL_FILE_POOL:4,PART_POOL_MIN:2,PART_POOL_START:2,PART_POOL_MAX:5,PART_POOL_GROW_RATIO:1.15,PART_POOL_SHRINK_RATIO:.7,PART_QUEUE_LIMIT:2,HEDGE_MIN_INFLIGHT_MS:3e3,HEDGE_LAG_FACTOR:3,HEDGE_POLL_MS:1e3,LIVENESS_SILENCE_MS:3e4,RETRY_BACKOFF_MS:[1e3,3e3,7e3,15e3,3e4],RETRY_JITTER_RATIO:.2,STALL_NOTICE_MS:3e4,MAX_STALL_MS:6e5,PUT_FLOOR_BYTES_PER_SECOND:20480,PUT_MIN_DEADLINE_MS:3e4,CONTROL_TIMEOUT_MS:3e4,COMPLETE_TIMEOUT_MS:12e4,VERIFY_POLL_BACKOFF_MS:[0,2e3,3e3,5e3,8e3],VERIFY_FALLBACK_WAIT_MS:6e4,NOT_READY_MAX_RETRIES:3,PROGRESS_SPEED_WINDOW_MS:2e4}},ln;function Br(e,t){ln=`${e}/${t}`}function Dr(){return ln===void 0?{}:{[Cs]:ln}}var le=class extends Error{constructor(e,t,n,r={}){super(e),this.name="BackendError",this.code=t,this.status=n,this.body=r.body,this.detail=r.detail,this.appCode=r.appCode,this.retryAfter=r.retryAfter,this.update=r.update,this.minVersion=r.minVersion}};function Ms(e){return e===404?"not_found":e===410?"revoked":e===429?"rate_limited":e===401||e===403?"auth":e>=500&&e<600?"transient":"unknown"}async function Cr(e,t){let n=await e.text().catch(()=>""),r,a,s,o,i;if(n)try{let l=JSON.parse(n);typeof l?.detail=="string"&&(r=l.detail),typeof l?.code=="string"&&(a=l.code),typeof l?.retry_after=="number"&&(s=l.retry_after),typeof l?.update=="string"&&(o=l.update),typeof l?.min_version=="string"&&(i=l.min_version)}catch{}return new le(r??t,Ms(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function Ns(e){return{id:e.id,expiresAt:e.expires_at,revokedAt:e.revoked_at,ndaRequired:e.nda_required,otpRequired:e.otp_required,singleUse:e.single_use,maxOpens:e.max_opens??null,files:(e.files??[]).map(t=>({id:t.id,size:t.size,sha256_hex:t.sha256_hex,name_encrypted:t.name_encrypted,name_nonce:t.name_nonce,mime_encrypted:t.mime_encrypted,mime_nonce:t.mime_nonce}))}}function V(e){return encodeURIComponent(e)}var yt=class ye{constructor(t){if(this.baseUrl=t.baseUrl.replace(/\/+$/,""),typeof(t.fetch??globalThis.fetch)!="function")throw new Error("SealApi: no global fetch in this runtime \u2014 pass options.fetch or use Node >= 18");this.injectedFetch=t.fetch,this.credentials=t.credentials}fetchImpl(t,n){return(this.injectedFetch??globalThis.fetch).call(globalThis,t,n)}url(t){if(!t.startsWith("/"))throw new Error(`SealApi: path must start with '/', got: ${t}`);return`${this.baseUrl}${t}`}async request(t,n){let{what:r,...a}=n,s=await this.fetchImpl(this.url(t),{...a,headers:{...Dr(),...a.headers},credentials:a.credentials??this.credentials});if(!s.ok)throw await Cr(s,`${r} failed: ${s.status}`);return s}static ownerHeaders(t,n=!1){let r={"X-Owner-Token":t};return n&&(r["Content-Type"]="application/json"),r}async getMetadata(t,n={}){return await(await this.request(`/seal/${V(t)}`,{what:`GET /seal/${t}`,signal:n.signal})).json()}async getShareBlob(t,n,r={}){let a=`GET /seal/${t}/share/${n}`,s=await this.request(`/seal/${V(t)}/share/${V(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:lr(o,a,s.status),wrap:typeof o.fragment=="string"&&o.fragment?o.fragment:null}}async verifyOtp(t,n,r={}){let a={code:n.code};n.fileId&&(a.file_id=n.fileId),n.shareCode&&(a.share_code=n.shareCode);let s=await this.request(`/seal/${V(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=$s(s,`otp_${t}`),i=await s.json().catch(()=>({}));return{status:typeof i.status=="string"?i.status:"ok",sessionCookie:o}}async acceptNda(t,n,r={}){let a={signature:n.signature,timestamp:n.timestamp,first_name:n.firstName,last_name:n.lastName};n.company&&(a.company=n.company),n.fileId&&(a.file_id=n.fileId),n.shareCode&&(a.share_code=n.shareCode),n.ndaText&&(a.nda_text=n.ndaText);let o=await(await this.request(`/seal/${V(t)}/nda`,{what:`POST /seal/${t}/nda`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal})).json().catch(()=>({}));return{status:typeof o.status=="string"?o.status:"ok"}}downloadUrl(t,n){return this.url(`/seal/${V(t)}/download?${or(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?ye.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie);for(let s=0;;s++)try{return await this.request(`/seal/${V(t)}/download?${or(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal})}catch(o){if(!(o instanceof le&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<L.upload.NOT_READY_MAX_RETRIES))throw o;await Fs((o.retryAfter??Us)*1e3,r.signal)}}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${V(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:ye.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${V(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:lr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=ye.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return ir(a,o,s),{etag:(await this.request(`/seal/${V(t)}/blob`,{what:`PATCH /seal/${t}/blob`,method:"PATCH",headers:s,body:JSON.stringify(o),signal:a.signal})).headers.get("ETag")}}async createShareLink(t,n,r,a={}){let s=n===null?{"Content-Type":"application/json"}:ye.ownerHeaders(n,!0),o={encrypted_blob:r};a.fileIds&&(o.file_ids=a.fileIds),ir(a,o,s);let i=await this.request(`/seal/${V(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:s,body:JSON.stringify(o),signal:a.signal}),l=await i.json();if(typeof l.share_code!="string"||!l.share_code)throw new le(`POST /seal/${t}/share returned no share_code`,"unknown",i.status);return l.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${V(t)}/share/${V(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:ye.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${V(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:ye.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof le&&(o.status===404||o.status===410))return{status:"revoked",revokedAt:null};throw o}let s=await a.json().catch(()=>({}));return{status:typeof s.status=="string"?s.status:"revoked",revokedAt:typeof s.revoked_at=="string"?s.revoked_at:null}}async revokeFile(t,n,r,a={}){await this.request(`/seal/${V(t)}/files/${V(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:ye.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${V(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:ye.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${V(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:ye.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${V(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:ye.ownerHeaders(n,!0),body:JSON.stringify(r.reference?{reference:r.reference}:{}),signal:a.signal}),o=await s.json();if(typeof o.id!="string"||typeof o.secret!="string")throw new le(`POST /seal/${t}/subscriptions returned no subscription`,"unknown",s.status);return{id:o.id,secret:o.secret}}async createCheckout(t,n,r,a={}){let s=await this.request("/billing/checkout",{what:"POST /billing/checkout",method:"POST",headers:ye.ownerHeaders(n,!0),body:JSON.stringify({seal_id:t,tier:r}),signal:a.signal}),o=await s.json();if(typeof o.url!="string"||!o.url)throw new le("POST /billing/checkout returned no url","unknown",s.status);return o.url}async createIntake(t,n={}){let r={recipient_bundle:t.recipientBundle,label:t.label,what:t.what,kind:t.kind??"any"};return t.whereUrl&&(r.where_url=t.whereUrl),t.ttlSeconds!==void 0&&(r.ttl_seconds=t.ttlSeconds),t.to&&(r.to=t.to),await(await this.request("/intake",{what:"POST /intake",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal})).json()}async getIntake(t,n={}){let r=n.waitSeconds?`?wait=${n.waitSeconds}`:"";return await(await this.request(`/intake/${V(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${V(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seal_id:n.sealId,share_code:n.shareCode,fragment:n.fragment}),signal:r.signal})).json()}async putBundle(t,n={}){await this.request("/intake/bundles",{what:"PUT /intake/bundles",method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundle:Q(t)}),signal:n.signal})}async getBundle(t,n={}){try{let r=await this.request(`/intake/bundles/${V(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return Y((await r.json()).bundle)}catch(r){if(r instanceof le&&r.status===404)return null;throw r}}async requestAddressProof(t,n={}){return await(await this.request("/intake/proof",{what:"POST /intake/proof",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:t}),signal:n.signal})).json()}async listInbox(t,n={}){let r=new URLSearchParams({to:t.address});return n.waitSeconds&&r.set("wait",String(Math.min(n.waitSeconds,Ke.limits.INTAKE_WAIT_MAX_SECONDS))),n.seen&&r.set("seen",n.seen),n.all&&r.set("all","1"),await(await this.request(`/intake?${r.toString()}`,{what:"GET /intake",headers:ut(t),signal:n.signal})).json()}async dismissInboxItem(t,n,r={}){let a=new URLSearchParams({to:n.address,item:t});await this.request(`/intake?${a.toString()}`,{what:"DELETE /intake",method:"DELETE",headers:ut(n),signal:r.signal})}async migrateInbox(t,n,r={}){return await(await this.request("/intake/migrate",{what:"POST /intake/migrate",method:"POST",headers:{"Content-Type":"application/json",...ut(t)},body:JSON.stringify(n),signal:r.signal})).json()}async pushKey(t={}){return(await(await this.request("/intake/push-key",{what:"GET /intake/push-key",signal:t.signal})).json()).vapid_public}async setInboxPush(t,n,r,a={}){let s=n?"POST":"DELETE";await this.request("/intake/subscriptions",{what:`${s} /intake/subscriptions`,method:s,headers:{"Content-Type":"application/json",...ut(r)},body:JSON.stringify({to:r.address,endpoint:t}),signal:a.signal})}},Us=3;function ut(e){return{[Le.proof.header_address]:e.address,[Le.proof.header_proof]:e.proof}}function or(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function ir(e,t,n){"to"in e&&(t.to=e.to,t.fragment=e.fragment,e.label&&(t.label=e.label),e.sender&&Object.assign(n,ut(e.sender)))}function Fs(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let a=()=>{clearTimeout(s),r(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}function lr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new le(`${t} returned an empty blob`,"unknown",n);return Y(e.encrypted_blob)}function $s(e,t){let n=e.headers,r=typeof n.getSetCookie=="function"?n.getSetCookie():[],a=r.length>0?r:(()=>{let s=e.headers.get("set-cookie");return s?[s]:[]})();for(let s of a){let o=s.split(";",1)[0]?.trim()??"";if(o.startsWith(`${t}=`))return o}return null}var Hs=32,Ws=32,Ft=Ke.limits.MAX_BLOB_SIZE,zs=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function Mr(){return crypto.getRandomValues(new Uint8Array(Hs))}async function Nr(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function _n(){return crypto.getRandomValues(new Uint8Array(Ws))}async function Ur(e,t,n,r,a){let s={owner_token:e,file_keys:Object.fromEntries(t),...r?{message:r}:{},...a?{nda_file:a}:{}};return $r(s,n)}async function Fr(e,t,n,r){let a={file_keys:Object.fromEntries(e),...n?{message:n}:{},...r?{nda_file:r}:{}};return $r(a,t)}async function $r(e,t){let n=JSON.stringify(e);if(n.length>Ft)throw new Error(`Blob data size ${n.length} exceeds maximum of ${Ft}`);let r=new TextEncoder().encode(n),a=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},s,r),i=new Uint8Array(12+o.byteLength);return i.set(a,0),i.set(new Uint8Array(o),12),i}function Ks(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.file_keys!="object"||t.file_keys===null)return!1;for(let[n,r]of Object.entries(t.file_keys))if(typeof n!="string"||typeof r!="string")return!1;return!(t.message!==void 0&&typeof t.message!="string")}async function Gs(e,t){let n=await js(e,t);if(!Ks(n))throw new Error("Invalid share blob structure");return n}async function js(e,t){if(e.length>Ft)throw new Error(`Blob size ${e.length} exceeds maximum of ${Ft}`);if(e.length<28)throw new Error("Encrypted blob too short");let n=e.slice(0,12),r=e.slice(12),a=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),s;try{s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},a,r)}catch{throw new zs}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}function Ys(){try{return typeof process<"u"&&!0}catch{return!1}}var Vs=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":Ys()||console.debug(a,...r);break;case"info":console.info(a,...r);break;case"warn":console.warn(a,...r);break;case"error":console.error(a,...r);break}},Dt=Vs;function _t(e){return{debug:(t,...n)=>Dt("debug",e,t,...n),info:(t,...n)=>Dt("info",e,t,...n),warn:(t,...n)=>Dt("warn",e,t,...n),error:(t,...n)=>Dt("error",e,t,...n)}}var Yi=Ke.limits.MAX_FILE_KEYS;var Ce=64,cr=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],qs=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),Xs=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function dr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let l,d;i<16?(l=a&s|~a&o,d=i):i<32?(l=o&a|~o&s,d=5*i+1&15):i<48?(l=a^s^o,d=3*i+5&15):(l=s^(a|~o),d=7*i&15);let p=r+l+qs[i]+t[n+d]|0;r=o,o=s,s=a,a=a+(p<<cr[i]|p>>>32-cr[i])|0}e[0]=e[0]+r|0,e[1]=e[1]+a|0,e[2]=e[2]+s|0,e[3]=e[3]+o|0}var wn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array(Ce),this.pendingLength=0,this.totalBytes=0,this.scratch=new Int32Array(16)}update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let r=Math.min(Ce-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<Ce)return this;this.compressBytes(this.pending,0,Ce),this.pendingLength=0}let n=e.length-(e.length-t)%Ce;return this.compressBytes(e,t,n),n<e.length&&(this.pending.set(e.subarray(n)),this.pendingLength=e.length-n),this}digest(){let e=new Uint8Array(this.pendingLength<56?Ce:2*Ce);e.set(this.pending.subarray(0,this.pendingLength)),e[this.pendingLength]=128;let t=new DataView(e.buffer);t.setUint32(e.length-8,this.totalBytes*8>>>0,!0),t.setUint32(e.length-4,Math.floor(this.totalBytes/2**29),!0),this.compressBytes(e,0,e.length);let n=new Uint8Array(16),r=new DataView(n.buffer);for(let a=0;a<4;a++)r.setInt32(a*4,this.state[a],!0);return n}compressBytes(e,t,n){if(t>=n)return;if(Xs&&(e.byteOffset+t)%4===0){let a=new Int32Array(e.buffer,e.byteOffset+t,(n-t)/4);for(let s=0;s<a.length;s+=16)dr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=Ce){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);dr(this.state,this.scratch,0)}}};function Zs(e){return Ie(new wn().update(e).digest())}var an=4*1024*1024;async function Js(e){let t=new wn;for(let n=0;n<e.length;n+=an)t.update(e.subarray(n,Math.min(n+an,e.length))),n+an<e.length&&await ht();return Ie(t.digest())}var Hr=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Rr(e.header).segmentSize,this.header=e.header.subarray(0,Me),this.key=e.key}async init(){this.cryptoKey=await Pr(this.key)}sha256Hex(){return Ve(this.header)}async encryptSegment(e,t,n){if(!this.cryptoKey)throw new Error("Encryptor.init() was not awaited");if(!(t?n.length<=this.segmentSize&&(n.length>0||e===0):n.length===this.segmentSize))throw new Error(`segment ${e}${t?" (last)":""} cannot carry ${n.length} bytes at segment size ${this.segmentSize}`);return Ls(this.cryptoKey,n,Lr(this.header,e,t))}};async function Qs(e,t,n,r){let a=new Uint8Array(t);try{let s=new Hr({key:a,header:n});await s.init();let o=new wn().update(s.header),i=[ur(s.header)],l=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let d=0;d<l;d++){let p=Math.min((d+1)*s.segmentSize,e.size),f=new Uint8Array(await e.slice(d*s.segmentSize,p).arrayBuffer()),u=await s.encryptSegment(d,d===l-1,f);f.fill(0),o.update(u),i.push(ur(u)),r?.(p,e.size)}return{blob:new Blob(i),md5_b64:Ie(o.digest())}}finally{a.fill(0)}}function ur(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Re=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function eo(e,t){e.chunks.push(t),e.bytes+=t.length}function Ct(e,t){let n=new Uint8Array(t),r=0;for(;r<t;){let a=e.chunks[0],s=t-r;a.length<=s?(n.set(a,r),r+=a.length,e.chunks.shift()):(n.set(a.subarray(0,s),r),r+=s,e.chunks[0]=a.subarray(s))}return e.bytes-=t,n}function to(e,t){let n=Ct(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function no(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Re("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,l=0,d=null,p=async(u,_)=>{if(u.length<kr)throw new Re("integrity",`segment ${l} is ${u.length} bytes: the stream was cut`);try{return await Ps(a,u,o==="v4"?Lr(s,l,_):null)}catch(h){throw new Re("integrity",`segment ${l} does not decrypt as the ${_?"last":"next"} segment of this file: moved, cut, extended or changed`,h)}finally{l+=1}},f=async()=>{if(r.bytes<Nt)return!1;let u=Os(to(r,Nt));if(u===null)throw new Re("outdated","the file is in a format newer than this client: update it");let _=u==="v4"?Me:Ir;if(r.bytes<_)return!1;if(u==="v3"){d=Bs();for(let g of r.chunks)d.update(g)}let h=Ct(r,_),E;try{E=u==="v4"?Rr(h).segmentSize:Is(h).segmentSize}catch(g){throw new Re("integrity",g instanceof Error?g.message:String(g),g)}if(u==="v4"&&await Ve(h)!==n)throw new Re("integrity","the file header is not the one registered for this file");return s=h,o=u,i=ks(E),!0};return new TransformStream({async start(){a=await Pr(e)},async transform(u,_){if(u.length!==0&&(eo(r,u),d&&d.update(u),!(o===null&&!await f())))for(;r.bytes>i;){let h=Ct(r,i),E=await p(h,!1);h.fill(0),t.onPlaintextBytes?.(E.length),_.enqueue(E)}},async flush(u){if(o===null)throw new Re("integrity",r.bytes===0?"the ciphertext stream is empty":"the ciphertext stream was cut inside its header");if(o==="v3"){if(Array.from(d.digest(),E=>E.toString(16).padStart(2,"0")).join("")!==n)throw new Re("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let _=await p(Ct(r,r.bytes),!0);t.onPlaintextBytes?.(_.length),u.enqueue(_)}},{highWaterMark:1},{highWaterMark:1})}var Xi=_t("SwDownload");var Zi=L.upload.MULTIPART_THRESHOLD_BYTES,Ji=L.upload.MULTIPART_THRESHOLD_BYTES;var Qi=_t("FolderZip");var el=100*1024*1024,tl=4*1024*1024;var ro=_t("upload"),dt=4*1024*1024;function $t(){return new DOMException("Upload aborted","AbortError")}async function ao(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:l,onPart:d}=e,p=Kt,f=Math.max(1,Math.ceil(n/p)),u=new Hr({key:r,header:a});await u.init();let _=!0,h=0,E=0,g=[],M=0,F=b=>{if(g.length>0&&g[0].length===b)return M-=b,g.shift();let I=new Uint8Array(b),ee=0;for(;ee<b;){let z=g[0],N=b-ee;z.length<=N?(I.set(z,ee),ee+=z.length,g.shift()):(I.set(z.subarray(0,N),ee),g[0]=z.subarray(N),ee+=N)}return M-=b,I},k=[],x=0,P=async b=>{let I=new Uint8Array(b),ee=0,z=0;for(;ee<b;){let N=k[0],pe=i?dt-z:Number.MAX_SAFE_INTEGER,te=Math.min(N.length,b-ee,pe);I.set(N.subarray(0,te),ee),ee+=te,z+=te,te===N.length?k.shift():k[0]=N.subarray(te),i&&z>=dt&&ee<b&&(z=0,await ht())}return x-=b,I},B=async b=>{E+=1;let I=i?await Js(b):Zs(b);await d(E,b,I),i&&await ht()},S=async b=>{if(!i){b.fill(0);return}for(let I=0;I<b.length;I+=dt)b.fill(0,I,Math.min(I+dt,b.length)),I+dt<b.length&&await ht()},W=async()=>{for(;x>=s;)await B(await P(s))},D=async(b,I)=>{if(o?.aborted)throw $t();let ee=h;h+=1;let z=performance.now(),N=u.encryptSegment(ee,I,b);await W();let pe=await N;await S(b),ro.debug(`encrypt segment=${h} bytes=${b.length} time=${Math.round(performance.now()-z)}ms`);let te;_?(te=new Uint8Array(a.length+pe.length),te.set(a,0),te.set(pe,a.length),_=!1):te=pe,l?.(h),k.push(te),x+=te.length},fe=t.getReader();try{for(;;){if(o?.aborted)throw $t();let{done:b,value:I}=await fe.read();if(b)break;for(I&&I.length>0&&(g.push(I),M+=I.length);M>=p;)await D(F(p),h===f-1)}(M>0||h===0)&&await D(F(M),!0),await W(),x>0&&await B(await P(x))}finally{fe.releaseLock()}}function so(e,t){let n=0;return new ReadableStream({async pull(r){if(n>=e.size){r.close();return}let a=Math.min(n+t,e.size);try{let s=await e.slice(n,a).arrayBuffer();r.enqueue(new Uint8Array(s)),n=a}catch(s){r.error(s)}}})}function oo(e,t){let{file:n,key:r,header:a,partSize:s,totalBytes:o,signal:i,initialCredits:l,onSegment:d,onPart:p}=t;return new Promise((f,u)=>{let _=!1,h=!1,E=Promise.resolve(),g=x=>{_||(_=!0,u(x))},M=()=>{h&&E.then(()=>{_||(_=!0,f())})};if(i){if(i.aborted){g($t());return}i.addEventListener("abort",()=>g($t()),{once:!0})}e.onerror=x=>{g(new Error(`crypto worker crashed: ${String(x?.message??x)}`))},e.onmessage=x=>{let P=x.data;if(P.type==="segment"){d?.(P.segmentNumber);return}if(P.type==="part"){let B=new Uint8Array(P.buffer);E=E.then(async()=>{_||(await p(P.partNumber,B,P.md5),e.postMessage({type:"credit"}))}).catch(g);return}if(P.type==="done"){h=!0,M();return}g(new Error(P.message))};let F=new ArrayBuffer(r.length);new Uint8Array(F).set(r);let k=a.slice().buffer;e.postMessage({type:"start",file:n,key:F,header:k,partSize:s,totalBytes:o,credits:l},[F,k])})}var io=null;function lo(){return io}var O=class extends Error{constructor(e,t,n,r,a=!1){super(e),this.code=t,this.httpStatus=n,this.partNumber=r,this.retryable=a,this.name="UploadError"}};function We(e,t){return e instanceof O?e:e instanceof DOMException&&e.name==="AbortError"?new O("Upload aborted","ABORTED"):new O(e instanceof Error?e.message:t,"UNKNOWN")}async function Xe(e,t,n,r){let a=await Cr(e,String(e.status));return new O(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var co=_t("upload"),uo={retryBackoffMs:L.upload.RETRY_BACKOFF_MS,retryJitterRatio:L.upload.RETRY_JITTER_RATIO,stallNoticeMs:L.upload.STALL_NOTICE_MS,maxStallMs:L.upload.MAX_STALL_MS,putFloorBytesPerSecond:L.upload.PUT_FLOOR_BYTES_PER_SECOND,putMinDeadlineMs:L.upload.PUT_MIN_DEADLINE_MS,controlTimeoutMs:L.upload.CONTROL_TIMEOUT_MS,completeTimeoutMs:L.upload.COMPLETE_TIMEOUT_MS,poolStart:L.upload.PART_POOL_START,poolMax:L.upload.PART_POOL_MAX,poolMin:L.upload.PART_POOL_MIN,poolGrowRatio:L.upload.PART_POOL_GROW_RATIO,poolShrinkRatio:L.upload.PART_POOL_SHRINK_RATIO,partQueueLimit:L.upload.PART_QUEUE_LIMIT,hedgeMinInflightMs:L.upload.HEDGE_MIN_INFLIGHT_MS,hedgeLagFactor:L.upload.HEDGE_LAG_FACTOR,hedgePollMs:L.upload.HEDGE_POLL_MS,livenessSilenceMs:L.upload.LIVENESS_SILENCE_MS,verifyPollBackoffMs:L.upload.VERIFY_POLL_BACKOFF_MS,verifyFallbackWaitMs:L.upload.VERIFY_FALLBACK_WAIT_MS,speedWindowMs:L.upload.PROGRESS_SPEED_WINDOW_MS};function Wr(e){return{...uo,...e}}function cn(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}function zr(e,t){let n=globalThis.AbortSignal;if(typeof n?.timeout!="function")return e;let r=n.timeout(t);return e?typeof n.any!="function"?e:n.any([e,r]):r}async function pt(e,t,n,r){try{return await fetch(e,{...t,signal:zr(r,n)})}catch(a){throw r?.aborted?new O("Upload aborted","ABORTED"):new O(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function Kr(e){return e===408||e===429||e>=500?"retryable":"terminal"}function Gr(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":Kr(e.httpStatus)}function jr(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":Kr(e.httpStatus)}var Yr=class{constructor(e,t,n=()=>performance.now()){this.policy=e,this.onState=t,this.now=n,this.failingSince=null,this.current="running",this.noticeTimer=null,this.retriesSinceDelivery=0}get state(){return this.current}connectionLost(){this.setState("stalled")}delivered(){this.failingSince=null,this.retriesSinceDelivery=0,this.clearNotice(),this.setState("running")}exhausted(){return this.failingSince!==null&&this.now()-this.failingSince>=this.policy.maxStallMs}failed(){this.retriesSinceDelivery+=1,this.failingSince??(this.failingSince=this.now());let e=this.policy.stallNoticeMs-(this.now()-this.failingSince);e<=0?this.setState("stalled"):this.noticeTimer===null&&this.current==="running"&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=null,this.setState("stalled")},e))}dispose(){this.clearNotice()}clearNotice(){this.noticeTimer!==null&&(clearTimeout(this.noticeTimer),this.noticeTimer=null)}setState(e){e!==this.current&&(this.current=e,this.onState?.(e))}};function gn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new O("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new O("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function Ht(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,l=0;for(let d=0;;d++){if(a?.aborted)throw new O("Upload aborted","ABORTED");try{return await e({attempt:d,after:i})}catch(p){let f=We(p,`${o} failed`);if(f.code==="ABORTED")throw f;let u=s(f);if(u==="terminal")throw f;if(n.exhausted())throw new O(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${f.message}`,f.code,f.httpStatus,f.partNumber,!1);n.failed(),l=u==="refresh_url"?l+1:0;let _=u==="refresh_url"&&l===1,h=r.retryBackoffMs[Math.min(d,r.retryBackoffMs.length-1)]??0,E=1+(Math.random()*2-1)*r.retryJitterRatio,g=_?0:Math.round(h*E);co.debug(`retry ${o} attempt=${d+2} in ${g}ms after ${f.code}${f.httpStatus?" "+f.httpStatus:""} (${u})`),i=u,await gn(g,a)}}}var He=_t("upload"),fr="<Code>BadDigest</Code>",fo=2;function bn(e){let t=Dr();return e?e.type==="bearer"?{...t,Authorization:`Bearer ${e.value}`}:e.type==="ownerToken"?{...t,"X-Owner-Token":e.value}:{...t,"X-API-Key":e.value}:t}async function ho(e){return po({file:e.file,sealId:e.sealId,fileId:e.fileId,key:e.key,header:e.header,baseUrl:e.baseUrl,auth:e.auth,partSize:e.partSize,onProgress:e.onProgress,signal:e.signal,transport:e.transport,onStreamed:e.onStreamed,onConflict:e.onConflict})}async function po(e){let{file:t,partSize:n}=e;return yo({stream:so(t,Kt),totalBytes:t.size,sealId:e.sealId,fileId:e.fileId,key:e.key,header:e.header,baseUrl:e.baseUrl,auth:e.auth,partSize:n,onProgress:e.onProgress,signal:e.signal,sourceFile:t,transport:e.transport,onStreamed:e.onStreamed,onConflict:e.onConflict})}async function yo(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:l,partSize:d,contentType:p="application/octet-stream",onProgress:f,signal:u,sourceFile:_,onStreamed:h,onConflict:E}=e,g=Wr(e.transport);if(s.length!==32)throw new O("Key must be 32 bytes","ENCRYPTION_FAILED");if(d<L.upload.S3_MIN_PART_SIZE_BYTES)throw new O(`Part size must be at least ${L.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let M=new Uint8Array(s),F=bn(l),k=yn(n),x=Math.ceil(k/d),P=null,B=[],S=0,W=0,D="encrypting",fe=[],b=null,I,ee=y=>{let w=performance.now();fe.push({at:w,bytes:y});let A=Math.max(b??w,w-g.speedWindowMs);for(;fe.length>0&&fe[0].at<A;)fe.shift();let R=w-A;R>0&&(I=Math.round(fe.reduce((T,G)=>T+G.bytes,0)/R*1e3))},z=y=>{D=y;let w=k-S;f?.({phase:y,percent:y==="done"?100:Math.min(99,Math.floor(S/k*100)),deliveredBytes:S,preparedBytes:W,totalBytes:k,speedBps:I,etaMs:I&&I>0?Math.round(w/I*1e3):void 0,state:N.state,attempt:N.retriesSinceDelivery+1})},N=new Yr(g,()=>z(D)),pe=new AbortController,te=globalThis.AbortSignal?.any,Te=u&&typeof te=="function"?te([u,pe.signal]):u??pe.signal,Ze=(y,w)=>Ht(w,{clock:N,policy:g,signal:Te,classify:jr,what:y}),Je=async y=>{throw M.fill(0),new O("Upload aborted","ABORTED")},ne=y=>{if(P)try{fetch(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...F},body:JSON.stringify(y?{upload_id:P,discard_file:!0}:{upload_id:P}),keepalive:!0}).catch(()=>{})}catch{}},Z=new Map,Ae=null,de=null,ue=[],_e=new Set,we=g.poolStart,gt=g.poolMax,bt=0,Ne=null,mt=0,Et=0,Qe=null,qt=[],Un=[],et=new Set,tt=performance.now(),Fn=!1,Xt=y=>{tt=performance.now();for(let w of[...et])w.reconnect(y)};function Ia(y,w){let A=y.ciphertext.length;if(A>=d&&w>0){let G=Math.min(y.flowsAtStart??1,_e.size);if(Un.push({rate:A/w,flows:G}),A/w*1e3<g.putFloorBytesPerSecond*2&&we>g.poolMin){we-=1,gt=we,Qe=null,bt+=1,Ne=performance.now(),mt=0,Et=0;return}}if(y.round!==bt||(mt+=A,Et+=1,Et<we||Ne===null))return;let R=performance.now()-Ne;if(R<=0)return;let T=mt/R;Qe===null||T>Qe*g.poolGrowRatio?we=Math.min(gt,we+1):T<Qe*g.poolShrinkRatio&&(we=Math.max(Math.min(g.poolStart,gt),we-1)),Qe=T,bt+=1,Ne=performance.now(),mt=0,Et=0}function Oa(y,w){let A=performance.now()-w;if(A<g.hedgeMinInflightMs)return!1;let R=_e.size,T=Un.filter(C=>C.flows>=R).map(C=>C.rate);if(T.length===0)return!1;T.sort((C,j)=>C-j);let G=T[Math.floor(T.length/2)];return y.ciphertext.length/A*g.hedgeLagFactor<G}async function Ra(y,w,A,R,T,G){if(typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((j,ge)=>{let re=new XMLHttpRequest,oe=!1;Fn=!0,re.upload.onprogress=Pe=>{G.onSocketActivity(Pe.loaded,Pe.lengthComputable?Pe.total:y.length),clearTimeout(se),se=Ge()};let Ge=()=>setTimeout(()=>{oe||G.onDeadline()},cn(y.length,g)),se=Ge(),U=()=>{clearTimeout(se),T.removeEventListener("abort",ie)},ie=()=>{oe||(oe=!0,re.abort(),U(),ge(new O("Upload aborted","ABORTED",void 0,A)))};if(re.onload=()=>{if(oe)return;oe=!0;let Pe={status:re.status,etag:re.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:re.status===400&&String(re.responseText??"").includes(fr)};U(),j(Pe)},re.onerror=()=>{oe||(oe=!0,U(),ge(new O(`Failed to upload part ${A}: network error`,"NETWORK",void 0,A,!0)))},re.onabort=()=>{oe||(oe=!0,U(),ge(new O("Upload aborted","ABORTED",void 0,A)))},T.aborted){U(),ge(new O("Upload aborted","ABORTED",void 0,A));return}T.addEventListener("abort",ie,{once:!0}),re.open("PUT",R),re.setRequestHeader("Content-MD5",w),re.send(y)});let C;try{C=await fetch(R,{method:"PUT",headers:{"Content-MD5":w},body:y,signal:zr(T,cn(y.length,g))})}catch(j){throw u?.aborted||T.aborted?We(j,"Upload aborted"):new O(`Part ${A}: transport failure (${j instanceof Error?j.message:String(j)})`,"NETWORK",void 0,A,!0)}return{status:C.status,etag:C.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:C.status===400&&(await C.text().catch(()=>"")).includes(fr)}}function La(y,w){if(w.badDigest)throw new O(`Part ${y} arrived corrupted (BadDigest)`,"BAD_DIGEST",w.status,y,!0);if(w.status<200||w.status>=300)throw new O(`Failed to upload part ${y}: ${w.status}`,w.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",w.status,y,w.status!==404);if(!w.etag)throw new O(`No ETag returned for part ${y}`,"S3_ETAG_MISMATCH",void 0,y);return w.etag}async function Pa(y,w){let A=performance.now(),R=null,T=0,G=A,C=null,j=()=>{},ge={reconnect:re=>j(re,!1),hasUnsentBytes:()=>C?.unsent??!1};et.add(ge);try{let re=await new Promise((Ge,se)=>{let U=!1,ie=Be=>{U||(U=!0,Be())},Pe=()=>{let Be=new AbortController,nt=()=>Be.abort();Te?.aborted?Be.abort():Te?.addEventListener("abort",nt,{once:!0});let ve={ctl:Be,unsent:!0,ended:Promise.resolve()};C=ve,G=performance.now(),tt=G,ve.ended=Ra(y.ciphertext,y.contentMd5,y.partNumber,w,Be.signal,{onSocketActivity:(rt,at)=>{tt=performance.now(),ve.unsent=rt<at},onDeadline:()=>j("copy deadline",!1)}).then(rt=>{if(C===ve)try{let at=La(y.partNumber,rt);ie(()=>Ge(at))}catch(at){ie(()=>se(at))}},rt=>{C===ve&&ie(()=>se(We(rt,`Failed to upload part ${y.partNumber}`)))}).finally(()=>{ve.unsent=!1,Te?.removeEventListener("abort",nt)})};j=(Be,nt)=>{let ve=C;U||ve===null||u?.aborted||(C=null,T=nt?T+1:0,He.debug(`${nt?"replace":"reconnect"} part=${y.partNumber} (${Be})`),ve.ctl.abort(),ve.ended.then(()=>{U||(Te?.aborted?ie(()=>se(new O("Upload aborted","ABORTED",void 0,y.partNumber))):Pe())}))},Pe(),R=setInterval(()=>{U||u?.aborted||C===null||T>=fo||Oa(y,G)&&j(`slower than its peers after ${Math.round(performance.now()-A)}ms`,!0)},g.hedgePollMs)}),oe=performance.now();B.push({part_number:y.partNumber,etag:re}),S+=y.ciphertext.length,ee(y.ciphertext.length),Ia(y,oe-A),N.delivered(),tt=oe,He.debug(`part=${y.partNumber}/${x} put=${Math.round(oe-A)}ms size=${y.ciphertext.length}${T>0?` replaced\xD7${T}`:""}`),z("uploading")}finally{et.delete(ge),j=()=>{},R!==null&&clearInterval(R),C?.ctl.abort()}}let St=(y,w,A)=>pt(y,w,A,Te);async function Ba(){try{let y=await St(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(P??"")}`,{method:"GET",headers:F},g.controlTimeoutMs);if(!y.ok)return null;let w=await y.json();return typeof w.status=="string"?w.status:null}catch{return null}}async function $n(y){let w=performance.now(),A=await Ze("presign batch",async()=>{let T=await St(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...F},body:JSON.stringify({upload_id:P,part_numbers:y})},g.controlTimeoutMs);if(!T.ok)throw await Xe(T,"Failed to get presigned URLs",T.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:G}=await T.json();return G}),R=new Map;for(let[T,G]of Object.entries(A))R.set(Number(T),G);return He.debug(`batch presign ${y.length} urls in ${Math.round(performance.now()-w)}ms`),R}async function Da(y){let w=[];for(let R=y;R<=x&&w.length<L.upload.PRESIGN_BATCH_SIZE;R++)Z.has(R)||w.push(R);if(w.length===0)return;let A=await $n(w);for(let[R,T]of A)Z.set(R,T)}function Hn(y){Ae||(Ae=Da(y).catch(()=>{}).finally(()=>{Ae=null}))}async function Ca(y){await ht(),Ne??(Ne=performance.now()),b??(b=Ne),y.round=bt,y.flowsAtStart=_e.size;let w=Z.get(y.partNumber);!w&&Ae&&(await Ae,w=Z.get(y.partNumber)),Z.delete(y.partNumber),Hn(y.partNumber+1),await Ht(async({after:A})=>{if((!w||A==="refresh_url")&&(w=(await $n([y.partNumber])).get(y.partNumber),!w))throw new O(`No presigned URL for part ${y.partNumber}`,"NETWORK",void 0,y.partNumber,!0);await Pa(y,w)},{clock:N,policy:g,signal:Te,classify:Gr,what:`part ${y.partNumber}`})}function Zt(){for(;!de&&!u?.aborted&&_e.size<we&&ue.length>0;){let y=ue.shift(),w=Ca(y).catch(A=>{de??(de=We(A,"Part upload failed"))}).finally(()=>{_e.delete(w);let A=qt;qt=[];for(let R of A)R();Zt()});_e.add(w)}}let Ma=()=>new Promise(y=>{qt.push(y)}),Na=(()=>{let y=globalThis,w=globalThis.navigator?.connection,A=w?.type,R=()=>Xt("network is back"),T=()=>N.connectionLost(),G=()=>{let j=w?.type;j!==A&&(A=j,Xt("network changed"))};y.addEventListener?.("online",R),y.addEventListener?.("offline",T),w?.addEventListener?.("change",G);let C=setInterval(()=>{!Fn||et.size===0||performance.now()-tt<g.livenessSilenceMs||[...et].some(j=>j.hasUnsentBytes())&&(N.connectionLost(),Xt("every socket silent"))},Math.max(10,g.livenessSilenceMs/4));return()=>{clearInterval(C),y.removeEventListener?.("online",R),y.removeEventListener?.("offline",T),w?.removeEventListener?.("change",G)}})();try{let y=performance.now();if(He.debug(`starting multipart: totalBytes=${n} parts=${x} partSize=${d} pool=${g.poolStart}..${g.poolMax}`),u?.aborted)throw new O("Upload aborted","ABORTED");z("encrypting"),P=await Ze("multipart init",async()=>{let se=await St(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...F},body:JSON.stringify({seal_id:r,content_type:p,content_length:k,part_size:d,file_id:a})},g.controlTimeoutMs);if(!se.ok)throw await Xe(se,"Failed to initialize multipart upload","NETWORK");return(await se.json()).upload_id}),Hn(1),z("encrypting");let w=!1,A=()=>{w=!0,z("encrypting")},R=async(se,U,ie)=>{for(w=!0,W+=U.length,z("encrypting"),u?.aborted&&await Je(u?.aborted===!0),ue.push({partNumber:se,ciphertext:U,contentMd5:ie}),Zt();ue.length>=g.partQueueLimit;)if(await Ma(),de)throw de;if(de)throw de},T=()=>ao({stream:t,totalBytes:n,key:M,header:o,partSize:d,signal:u,yieldToRenderer:typeof document<"u",onSegment:A,onPart:R}),G=lo(),C=null;if(_&&G&&typeof document<"u")try{C=G()}catch{C=null}if(C){He.debug("crypto pipeline: worker");try{await oo(C,{file:_,key:M,header:o,partSize:d,totalBytes:n,signal:u,initialCredits:g.partQueueLimit,onSegment:A,onPart:R})}catch(se){let U=We(se,"Crypto worker failed");if(U.code==="ABORTED"||w)throw U;He.debug(`crypto worker failed before output \u2014 inline fallback (${U.message})`),await T()}finally{C.terminate()}}else await T();for(;Zt(),!(de||(u?.aborted&&await Je(!0),_e.size===0&&ue.length===0));)await Promise.race(_e);if(de)throw de;z("verifying"),u?.aborted&&await Je(u?.aborted===!0),h?.();let j=!1,ge,re=await Ze("complete",async()=>{let se=j;j=!0;let U=await St(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...F},body:JSON.stringify({upload_id:P,parts:B.map(ie=>({part_number:ie.part_number,etag:ie.etag})),...E?{on_conflict:E}:{}})},g.completeTimeoutMs);if(U.ok){let ie=await U.json().catch(()=>null);return typeof ie?.conflict_with=="string"&&(ge=ie.conflict_with),ie?.status==="verified"}if(se&&U.status===400&&await Ba()==="completed")return!1;throw await Xe(U,"Failed to complete multipart upload",U.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});N.delivered(),z("done");let oe=Math.round(performance.now()-y),Ge=n/(1024*1024)/(oe/1e3);return He.debug(`DONE totalTime=${oe}ms speed=${Ge.toFixed(2)}MB/s parts=${B.length}`),M.fill(0),{verified:re,...ge?{conflictWith:ge}:{}}}catch(y){M.fill(0);let w=We(y,"Unknown upload error");throw ne(w.code==="ABORTED"),w}finally{Na(),N.dispose(),pe.abort()}}var Wt="Encrypted file",zt="application/octet-stream";function Vr(e){return new TextEncoder().encode(`field:${e}`)}async function sn(e,t,n){let r=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.importKey("raw",t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),{name:"AES-GCM"},!1,["encrypt"]),s={name:"AES-GCM",iv:r,tagLength:128};if(n){let i=Vr(n);s.additionalData=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}let o=await crypto.subtle.encrypt(s,a,new TextEncoder().encode(e));return{ciphertext:Ie(new Uint8Array(o)),nonce:Ie(r)}}function _o(e){return e?.name==="OperationError"}async function hr(e,t,n,r){let a=It(e),s=It(t),o=async i=>{let l={name:"AES-GCM",iv:s};i&&(l.additionalData=i);let d=await crypto.subtle.decrypt(l,n,a);return new TextDecoder().decode(d)};if(!r)return o(void 0);try{return await o(Vr(r))}catch(i){if(!_o(i))throw i;return o(void 0)}}async function wo(e,t){let n=e.name||Wt,r=e.mime||zt;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await hr(e.name_encrypted,e.name_nonce,t,"name")}catch{n=Wt}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await hr(e.mime_encrypted,e.mime_nonce,t,"mime")}catch{r=zt}return{name:n,mime:r}}async function go(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function bo(e,t){try{let n=await go(t);return wo(e,n)}catch{return{name:e.name||Wt,mime:e.mime||zt}}}var Gt={multipartThresholdBytes:L.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:L.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:L.upload.INMEMORY_BLOB_LIMIT_BYTES};function mo(e,t=Gt){return e<=L.upload.FINE_PART_MAX_FILE_BYTES?L.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Eo(e,t){return e>=t.multipartThresholdBytes}function So(e){if(!(e.kind==="none"||!e.value)){if(e.kind==="ownerToken")return{type:"ownerToken",value:e.value};if(e.kind==="bearer")return{type:"bearer",value:e.value}}}function qr(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:So(e.auth)}function Ao(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var vo={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},pr=[2,12],To=[12,95],ko=[95,99];function yr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=vo[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=ko:r.deliveredBytes===0?s=pr:s=To;let o=s===pr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,l=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,l),t({phase:r.phase,percent:n,deliveredBytes:r.deliveredBytes,preparedBytes:r.preparedBytes,totalBytes:r.totalBytes,speedBps:r.speedBps,etaMs:r.etaMs,state:r.state,attempt:r.attempt})}}var mn=class{constructor(e,t){this.run=t,this.cancelled=!1,this.ctx=e.ctx,this.policy=e.policy,this.sealId=e.sealId,this.createdSeal=e.createdSeal,this.expiresAt=e.expiresAt,this.files=e.files}get pending(){return this.files.filter(e=>e.state==="pending")}get verification(){return this.files.every(e=>e.state==="verified")?"verified":"pending"}async resume(e={}){if(this.cancelled)throw new O("Upload session was cancelled","ABORTED");try{return await this.run(this,e)}catch(t){let n=We(t,"Upload failed");throw n.session=this,n}}async cancel(){this.cancelled=!0;let e=Ao(this.ctx);if(!e)return;let t=new yt({baseUrl:this.ctx.baseUrl,credentials:this.ctx.credentials??"include"});try{if(this.createdSeal){await t.revoke(this.sealId,e);return}for(let n of this.pending)await t.revokeFile(this.sealId,n.fileId,e)}catch{}}};function xo(e,t,n){let r=t.length;if(!e||e.length<r)throw new Error(`${n} returned ${e?.length??0} file record(s) for ${r} file(s) \u2014 cannot upload ciphertext`);let a=e.slice(e.length-r);return a.forEach((s,o)=>{if(!s?.id)throw new Error(`${n}: file record ${o} has no id \u2014 cannot upload ciphertext`);if(s.sha256_hex===void 0){if(r===1)return;throw new Error(`${n}: file record ${o} carries no sha256_hex \u2014 refusing to pair ${r} files by position alone`)}if(s.sha256_hex!==t[o])throw new Error(`${n}: file record ${o} has sha256=${s.sha256_hex.slice(0,16)}\u2026 but we sent ${t[o].slice(0,16)}\u2026 \u2014 response order corrupted, refusing to upload`)}),a}function Io(e){return e>=200&&e<300||e===204}async function Oo(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:l,clock:d,transport:p}=e,f=` for ${i}`,u={"Content-Type":"application/json",...s},_=t.credentials??"include",h=(k,x)=>Ht(x,{clock:d,policy:p,signal:l,classify:jr,what:k}),E=()=>h(`initiate${f}`,async()=>{let k=await pt(`${t.baseUrl}/upload/initiate`,{method:"POST",headers:u,credentials:_,body:JSON.stringify({seal_id:n,content_type:"application/octet-stream",content_length:a.blob.size,file_id:r})},p.controlTimeoutMs,l);if(k.status===409)return null;if(!k.ok)throw await Xe(k,`Upload initiate failed${f}`,"NETWORK");let x=await k.json();return x.already_verified?null:x}),g=await E();if(g===null)return!1;let M=!1;if(await Ht(async({after:k})=>{if(k==="refresh_url"){let B=await E();if(B===null){M=!0;return}g=B}let{upload_url:x}=g,P=await pt(x,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},cn(a.blob.size,p),l);if(P.status===400&&(await P.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new O(`Upload arrived corrupted (BadDigest)${f}`,"BAD_DIGEST",400,void 0,!0);if(!Io(P.status))throw new O(`Upload PUT failed${f}: ${P.status}`,"NETWORK",P.status)},{clock:d,policy:p,signal:l,classify:Gr,what:`PUT${f}`}),M)return!1;d.delivered(),o();let F=await h(`confirm${f}`,async()=>{let k=await pt(`${t.baseUrl}/upload/confirm`,{method:"POST",headers:u,credentials:_,body:JSON.stringify({seal_id:n,file_id:r,...t.onConflict?{on_conflict:t.onConflict}:{}})},p.controlTimeoutMs,l);if(!k.ok)throw await Xe(k,`Upload confirm failed${f}`,"NETWORK");let x=await k.json().catch(()=>null);return typeof x?.conflict_with=="string"&&e.onConflictWith(x.conflict_with),x?.status==="verified"});return d.delivered(),F}async function Xr(e,t,n,r,a,s){try{let o=await pt(`${e.baseUrl}/upload/status/${encodeURIComponent(t)}/${n}`,{method:"GET",headers:r,credentials:e.credentials??"include"},a.controlTimeoutMs,s);if(!o.ok)return null;let i=await o.json();return typeof i.status=="string"?i.status:null}catch(o){if(o instanceof O&&o.code==="ABORTED")throw o;return null}}var Ro=new Set(["failed","size_mismatch","verification_error"]);async function Lo(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i}=e,l=s.verifyFallbackWaitMs,d=performance.now(),p=s.verifyPollBackoffMs;for(let f=0;;f++){let u=p[Math.min(f,p.length-1)]??0;if(performance.now()-d+u>l)return"pending";u>0&&await gn(u,o);let _=await Xr(t,n,r,a,s,o);if(_==="verified")return"verified";if(_!==null&&Ro.has(_))throw new O(`The server rejected ${i} after upload (${_}). It has to be sent again.`,"VERIFICATION_REJECTED");if(_===null&&f===0)return"pending"}}async function Po(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:l}=t,{onProgress:d,signal:p}=n;if(t.state!=="pending")return;if(p?.aborted)throw new O("Upload aborted","ABORTED");let f=qr(r),u=bn(f),_=Wr(a.transport),h=async B=>{if(t.state=B?"verified":"uploaded",!B)try{await Lo({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:u,transport:_,signal:p,label:o.name})==="verified"&&(t.state="verified")}catch(S){throw S instanceof O&&S.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),S}};if(Eo(o.size,a)){if(t.streamed){let b=await Xr(r,s,t.sha256_hex,u,_,p);if(b!==null&&b!=="pending"){await h(b==="verified");return}}let B=yr("multipart",b=>d?.(b)),S=null,W=await ho({file:o,sealId:s,fileId:l,key:i,header:t.header,baseUrl:r.baseUrl,auth:f,partSize:mo(o.size,a),onProgress:b=>{S=b;let I=b.phase==="done";B({...b,phase:I?"verifying":b.phase,fraction:I?0:b.deliveredBytes/b.totalBytes,preparedFraction:b.totalBytes>0?(b.preparedBytes??0)/b.totalBytes:0,preparedBytes:b.preparedBytes})},signal:p,transport:a.transport,onStreamed:()=>{t.streamed=!0},onConflict:r.onConflict});t.streamed=void 0,t.conflictWith=W.conflictWith,await h(W.verified);let D=t.encryptedSize;B({...S??{phase:"done",percent:100,deliveredBytes:D,totalBytes:D,state:"running",attempt:1},phase:"done",fraction:1});return}let E=yr("single-put",B=>d?.(B)),g=t.encryptedSize,M={phase:"encrypting",fraction:0,delivered:!1},F=(B,S,W=M.delivered)=>{M={phase:B,fraction:S,delivered:W},E({phase:B,fraction:S,deliveredBytes:W?g:0,totalBytes:g,state:k.state,attempt:k.retriesSinceDelivery+1})},k=new Yr(_,()=>F(M.phase,M.fraction));t.prepared||(F("encrypting",0),t.prepared=await Qs(o,i,t.header,B=>F("encrypting",o.size>0?B/o.size:1)));let x=t.prepared;F("uploading",0);let P;try{P=await Oo({ctx:r,sealId:s,fileId:l,ciphertext:x,authHeaders:u,onVerifying:()=>F("verifying",0,!0),label:o.name,signal:p,clock:k,transport:_,onConflictWith:B=>{t.conflictWith=B}})}finally{k.dispose()}F("verifying",.5,!0),await h(P),t.prepared=void 0,F("done",1,!0)}function Bo(e){if(!e.roomId){if(!e.ownerTokenHash)throw new Error("ownerTokenHash is required for seal creation (SHORT LINKS)");if(e.ownerTokenHash.length!==64||!/^[a-f0-9]{64}$/i.test(e.ownerTokenHash))throw new Error("ownerTokenHash must be 64 hex characters (SHA256)")}}function Do(e,t){t.ttl&&(e.ttl=t.ttl),t.roomId&&(e.room_id=t.roomId),t.otp&&(e.otp=t.otp),t.nda&&(e.nda=!0),t.ownerEmail&&(e.owner_email=t.ownerEmail),t.singleUse&&(e.single_use=!0),t.geo&&t.geo.length>0&&(e.geo=t.geo),typeof t.maxOpens=="number"&&t.maxOpens>0&&(e.max_opens=t.maxOpens),t.tier&&(e.tier=t.tier)}async function Co(e,t,n,r,a={}){let s=await sn(e.name,t,"name"),o=await sn(e.type||"application/octet-stream",t,"mime"),i={size:n,sha256_hex:r,name_encrypted:s.ciphertext,name_nonce:s.nonce,mime_encrypted:o.ciphertext,mime_nonce:o.nonce,encryption_version:he.current_format_version};if(a.relativePath!==void 0){let l=await sn(a.relativePath,t,"path");i.path_encrypted=l.ciphertext,i.path_nonce=l.nonce}return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function Mo(e,t,n){if(n?.aborted)throw new O("Upload aborted","ABORTED");try{return await fetch(e,{...t,signal:n})}catch(r){throw n?.aborted?new O("Upload aborted","ABORTED"):r}}async function No(e,t,n){let r={files_meta:t};e.ownerTokenHash&&(r.owner_token_hash=e.ownerTokenHash),Do(r,e);let a=await Mo(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...bn(qr(e))},credentials:e.credentials??"include",body:JSON.stringify(r)},n);if(!a.ok)throw await Xe(a,"Create seal failed","UNKNOWN");return await a.json()}async function Uo(e,t){let n=xs();return{file:e,key:t,header:n,sha256_hex:await Ve(n)}}async function Fo(e,t,n,r){await e.onRegistered?.(t,n.map((a,s)=>({fileId:r[s].id,sha256_hex:a.sha256_hex,key:a.key})))}function $o(e,t){return e.map((n,r)=>({index:r,fileId:t[r].id,file:n.file,key:n.key,header:n.header,sha256_hex:n.sha256_hex,encryptedSize:yn(n.file.size),state:"pending"}))}async function Zr(e,t,n=Gt,r={}){Bo(e);let a=await Uo(t,Ds()),s=await No(e,[await Co(t,a.key,yn(t.size),a.sha256_hex)],r.signal),o=xo(s.files,[a.sha256_hex],`Create seal ${s.id}`);return await Fo(r,s.id,[a],o),new mn({ctx:e,policy:n,sealId:s.id,createdSeal:!0,expiresAt:s.expires_at,files:$o([a],o)},async(l,d)=>{let p=l.files[0];return await Po(l,p,{onProgress:f=>d.onProgress?.(f),signal:d.signal}),{sealId:l.sealId,fileId:p.fileId,encryptionKey:p.key,sha256_hex:p.sha256_hex,expiresAt:l.expiresAt,verification:l.verification}}).resume(r)}var _r=[2e3,4e3,8e3,15e3],on=Ke.limits.TIER_BYTES,rl=Object.keys(on).filter(e=>e!=="free").sort((e,t)=>on[e]-on[t]);function Jr(e){return e instanceof O&&e.httpStatus===402&&e.session?e.session:null}function Qr(e,t=Date.now()){let n=t+Ke.limits.PAYMENT_WAIT_MAX_SECONDS*1e3,r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)?Math.min(n,r):n}async function ea(e,t,n,r){for(let a=0;;a++){try{let o=await e.getOwnerSeal(t,n,{signal:r.signal});if(r.tier?o.tier===r.tier:o.tier&&o.tier!=="free")return o}catch(o){if(r.signal?.aborted||o instanceof le&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=_r[Math.min(a,_r.length-1)];if(Date.now()+s>r.deadline)return null;await gn(s,r.signal)}}var al=Ke.limits.ttl_options;var ta={version:2,name:"SEAL_SHARE_URL",description:"URL fragment scheme for SEAL share links (SPEC-AEON-V4 \xA76, law \u041B2): the fragment of any link carries one symmetric key or nothing. A link addressed to someone carries no fragment: its key, wrapped to the recipient's bundle (sealed box v2, crypto.json sealed_box_v2), lives in the share link's row on the server and comes back as `fragment` of GET /seal/{id}/share/{code}. Backends never see fragments (URL fragments are not sent over HTTP per RFC 3986 \xA73.5). Consumers: the web, the CLI, the MCP server, the SDK, sealnet and the bots. The wrap and its opening live in shared/core (targeted.rs over sealed_box.rs, Identity::open).",url_template:"https://<host>/s/<seal_id>/<share_code>[#<link_key>]",fragment_variants:{key:{format:"<link_key_urlsafe_b64_no_pad>",detection:"exactly 43 urlsafe-b64-no-pad characters, 32 bytes: the AES-256-GCM key of the share blob (seal_blob.v1.json)",field_layout:[{name:"link_key",offset:0,length:32,encoding:"urlsafe-b64-no-pad in URL"}]},none:{format:"",detection:"no fragment: an addressed link. The key, wrapped to the recipient's bundle with scope ('seal_share', seal_id from the path), is the `fragment` field of the share blob response (1575 base64url characters, first byte 0x02); only the recipient's seed opens it."},targeted_x25519_v1:{status:"read only until the removal (C1 \xA76): links made before C1 with the sealed box v1 in the fragment",format:"x25519:<packed_b64>",prefix:"x25519:",packed_binary_length_bytes:92,packed_layout:[{name:"ephemeral_public",offset:0,length:32,encoding:"raw bytes; X25519 ephemeral pubkey from sender"},{name:"nonce",offset:32,length:12,encoding:"raw bytes; AES-256-GCM nonce"},{name:"wrapped_link_key",offset:44,length:48,encoding:"raw bytes; 32 B ciphertext of the link key || 16 B GCM tag"}],implicit_fields_not_in_packed:{recipient_public:"the X25519 key of the recipient's seed (the seed itself is the X25519 secret)",scope_type:"'seal_share'",scope_id:"seal_id from the URL path /s/<seal_id>/<code>",grant_version:"1"},kdf_info_layout:'seal_crypto::hkdf::derive_wrap_key: b"WRAP" || 0x01 || len(scope_type) || scope_type || len(scope_id) || scope_id, salt crypto.json hkdf.wrap_key_salt',aad_layout:"recipient_public (32 B) || 0x01"}},version_detection_rule:"(1) no fragment \u2192 none: the wrap comes from the server; (2) starts with 'x25519:' \u2192 targeted_x25519_v1, read only until the removal; (3) exactly 43 urlsafe-b64-no-pad characters \u2192 key; (4) anything else \u2192 'update the client' (SPEC-AEON-V4 \xA77.4), never decoded as a key.",current_format_version:2,supported_format_versions:[2],implementations:{rust:"shared/core/src/targeted.rs (wrap_link_key / open_wrap; the x25519: opening until the removal); the CLI calls it as seal_crypto::targeted",ts:"shared/packages/protocol/src/identity.ts (wrapTo / openWrap) over the core's WASM; the whole link is parsed by protocol/src/url.ts::parseShareUrl",python:"sealnet calls the Rust core in its wheel (sealnet.seal_crypto); no Python implementation"},test_vectors:{description:"Frozen outputs of the read-only v1 variant, until the removal: every reader MUST recover link_key from fragment with recipient_secret (the seed) and seal_id, and MUST fail with any other seal_id.",targeted_x25519_v1:[{recipient_secret_b64url:"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",recipient_public_b64url:"E75P6uryBMf9M1j8nAByGIHRdCeBKCJ-xnTzf3_pe20",seal_id:"AbCd1234",fragment:"x25519:GkbbXddA43eoSgY1ZAAnPTCDmJIoGM3ZrY2_wctdKX2ivODHag_TCSjQql3PMu22xzsxJsYKHnIhHjXhvuJfe468pvsvvzuEZiaVzoPu2PTqlRin8xiDsopyrGQ",link_key_b64url:"q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s"}]},security_properties:{key:"Anyone with the URL can open. link_key is the entire capability \u2014 treat the URL itself as a bearer credential.",none:"The URL alone opens nothing: the key is sealed to the recipient's bundle (X25519 + ML-KEM-768) and only the seed on the recipient's device opens it. Each wrap has a fresh ephemeral key and encapsulation."}},Ho=ta.fragment_variants.targeted_x25519_v1.prefix,En=8,Sn=43,dn=4,jt=/^[A-Za-z0-9_-]+$/;function Wo(e,t){if(!jt.test(e))return!1;try{let n=e.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return atob(n).length===t}catch{return!1}}function An(e){return e.length===En&&jt.test(e)}function vn(e){return e.length===Sn&&Wo(e,32)}function na(e,t){if(!An(e))throw new Error(`Invalid sealId: must be ${En} base64url characters`);if(!vn(t))throw new Error(`Invalid linkKey: must be ${Sn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function ra(e,t,n){if(!An(e))throw new Error(`Invalid sealId: must be ${En} base64url characters`);if(t.length!==dn||!jt.test(t))throw new Error(`Invalid shareCode: must be ${dn} base64url characters`);if(!vn(n))throw new Error(`Invalid linkKey: must be ${Sn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var Mt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function zo(e){let t;try{t=new URL(e)}catch{throw new Mt("url_invalid",`not a valid URL: ${e}`)}let n;try{n=Ko(t.pathname.replace(/\/+$/,""))}catch{throw new Mt("url_invalid",`expected /s/<seal_id>[/<share_code>] path, got: ${t.pathname}`)}let r=t.hash.replace(/^#/,"").trim(),a=n.shareCode??null;if(!r)return{sealId:n.sealId,shareCode:a,fragmentVariant:"none",fragment:r};if(r.startsWith(Ho))return{sealId:n.sealId,shareCode:a,fragmentVariant:"targeted_x25519_v1",fragment:r};if(!vn(r))throw new Mt("url_invalid",`the fragment is not one 43-character key (got ${r.length} characters): a mangled link, or one from a newer client \u2014 update it`);return{sealId:n.sealId,shareCode:a,fragmentVariant:"key",fragment:r}}function Ko(e){let t=e.match(/^\/s\/([A-Za-z0-9_-]{8})(?:\/([A-Za-z0-9_-]{4}))?$/);if(!t)throw new Error("Invalid seal URL format");let n=t[1],r=t[2];if(!An(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==dn||!jt.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var Tn={version:1,default_aead:"aes_256_gcm",aes_gcm:{key_length_bytes:32,nonce_length_bytes:12,tag_length_bytes:16},sha256:{output_length_bytes:32,hex_string_length:64},owner_token_bytes:32,link_key_bytes:32,metadata_aad_prefix:"field:",keybundle:{signature_prefix:"seal:keybundle:",signed_bundle_version:2,v2_fields:["identity_ed25519_pub","agreement_x25519_pub","kem_mlkem768_pub"],packed_length:1316,address:{of:"sha256(identity_ed25519_pub), 32 bytes",text:"base64url without padding, 43 characters",words:"fingerprint_words.json over its first three bytes"}},hkdf:{wrap_key_salt:"seal:wrapkey:v1",wrap_key_salt_v2:"seal:wrapkey:v2",identity_key_salt:"seal:key-derivation:v1",file_envelope_salt:"seal:file-envelope:v1",info_prefixes:{wrap:"WRAP",agreement:"AGRE",identity:"IDEN",workload_identity:"seal:workload-identity:v1",kem_mlkem768:"seal:kem-mlkem768:v1"}},xwing:{label_hex:"5c2e2f2f5e5c"},sealed_box_v2:{version_byte:2,packed_layout:[{name:"version",offset:0,length:1},{name:"eph_pub",offset:1,length:32},{name:"kem_ct",offset:33,length:1088},{name:"nonce",offset:1121,length:12},{name:"ct",offset:1133,length:48}],packed_length:1181,packed_b64_length:1575},secret_scope_aad:"secret:{secret_id}",sign:{message_prefix:"aeon:sign:v1",message_format:"aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}"}},kn=Le.scopes.share_link,aa=Le.scopes.owner_copy,wr=Tn.sealed_box_v2.version_byte,gr=Tn.sealed_box_v2.packed_length,ze=ta.fragment_variants.targeted_x25519_v1,Go=Le.migrate.scope_address_proof,Se=32,br=32,xn=/^[A-Za-z0-9_-]+$/;function sa(){return crypto.getRandomValues(new Uint8Array(Se))}async function In(e,t=1){let n=await $e();if(e.length===Se)return n.WasmIdentity.fromSeed32(e);if(e.length===2*Se)return n.WasmIdentity.fromSeed64(e,t);throw new Error(`a seed is ${Se} or ${2*Se} bytes, got ${e.length}`)}async function Yt(e,t=1){let n=await In(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words(),legacyAddress:n.legacyAddress()}}finally{n.free()}}function oa(e){let t=e.trim().replace(/=+$/,"");if(t.length!==43)throw new Error(`an address is 43 urlsafe-base64-no-pad characters, got ${t.length}`);if(!xn.test(t))throw new Error("not valid urlsafe-base64-no-pad: contains characters outside [A-Za-z0-9_-] (standard-base64 input is rejected \u2014 copy the exact address from `seal keygen` or `sealnet-mcp pubkey`)");return t}async function ia(e,t){return(await $e()).wasm_bundle_verify_for_address(e,t)}async function On(e){return(await $e()).wasm_bundle_address(e)}async function Rn(e,t,n,r){if(e.length!==br)throw new Error(`a wrapped key is ${br} bytes, got ${e.length}`);if(r.length===0)throw new Error("the scope id must not be empty: the wrap binds to it");return Q((await $e()).wasm_sealbox_wrap(e,t,n,r))}var Ee=class extends Error{constructor(e,t,n){super(t),this.name="WrapError",this.kind=e,this.cause=n}};async function jo(e,t,n,r,a=1){if(r.length===0)throw new Ee("parse","the scope id must not be empty: the wrap binds to it");if(e.startsWith(ze.prefix))return Yo(e.slice(ze.prefix.length),t,n,r);if(!xn.test(e))throw new Ee("parse","the wrap is not urlsafe-base64-no-pad");let s=Y(e);if(s[0]!==wr)throw new Ee("parse",`the wrap is not a sealed box v${wr}: a newer client made it \u2014 update this one`);if(s.length!==gr)throw new Ee("parse",`the wrap is ${s.length} bytes, expected ${gr}`);if(t.length!==Se&&t.length!==2*Se)throw new Ee("parse",`a seed is ${Se} or ${2*Se} bytes, got ${t.length}`);let o=await In(t,a);try{return o.open(s,n,r)}catch(i){throw new Ee("aead","the wrap does not open: it is not for this seed, or its scope, id or bytes were changed",i)}finally{o.free()}}async function Yo(e,t,n,r){if(!xn.test(e))throw new Ee("parse",`the ${ze.prefix} wrap is not urlsafe-base64-no-pad`);let a=Y(e);if(a.length!==ze.packed_binary_length_bytes)throw new Ee("parse",`the ${ze.prefix} wrap is ${a.length} bytes, expected ${ze.packed_binary_length_bytes}`);if(t.length!==Se)throw new Ee("parse",`an ${ze.prefix} wrap opens with a ${Se}-byte seed`);let s=await $e();try{return s.wasm_sealbox_unwrap(a,t,n,r)}catch(o){throw new Ee("aead","the wrap does not open: it is not for this seed, or its scope, id or bytes were changed",o)}}async function Vo(e,t){let n=await In(e);try{let r=n.inboxProof(BigInt(t.ts),Y(t.challenge));return`${t.ts}.${t.challenge}.${Q(r)}`}finally{n.free()}}async function qo(e,t,n){let a=(await $e()).wasm_sealbox_unwrap(Y(t),e,Go,String(n));return`${n}.${Q(a)}`}var un={version:1,name:"FINGERPRINT_WORDS",description:"Three words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3): word i (i = 0, 1, 2) is words[byte i of SHA-256(identity public key)] \u2014 the first three bytes of the same SHA-256 that is the address, so a client names an address by its own first bytes without hashing again \u2014 24 bits in all, written in lower case with one space between them. The agent shows them in its chat, box.seal.net and seal.net/i/{id} show them on the page, so a person sees at a glance whether both sides hold the same key. One list for every language and client: 256 English nouns of 3 to 7 letters, no two sharing their first three letters, in alphabetical order.",digest:"sha256",count:3,separator:" ",words:["acorn","album","amber","anchor","apple","arrow","atlas","bamboo","banjo","basket","beach","bell","bench","berry","birch","bison","bloom","boat","bolt","bottle","brick","broom","butter","cabin","cactus","camel","candle","cargo","castle","cedar","cherry","clock","coast","comet","copper","coral","cotton","crab","crown","daisy","dawn","deer","delta","desert","diamond","dolphin","dove","dragon","drum","duck","dune","eagle","earth","echo","egg","elk","ember","emerald","engine","falcon","farm","feather","fence","fern","fig","finch","fish","flag","flute","fog","forest","fossil","fox","frog","garden","gate","gazelle","gecko","geyser","ginger","giraffe","glacier","globe","goat","gold","goose","grape","guitar","hammer","harbor","hawk","hazel","hedge","heron","hill","hippo","hive","honey","horse","igloo","iguana","iris","iron","island","ivory","jacket","jaguar","jasmine","jelly","jewel","juice","jungle","kayak","kelp","kettle","kite","kiwi","koala","ladder","lagoon","lamp","lantern","lava","leaf","lemon","leopard","lily","lime","lion","lizard","llama","lobster","lotus","lynx","magnet","mango","maple","marble","meadow","melon","meteor","mint","mirror","monkey","moon","mosaic","muffin","nail","nectar","needle","nest","oasis","ocean","olive","opal","orange","orbit","orchid","otter","owl","palm","panda","paper","parrot","peach","pebble","pelican","pencil","pepper","piano","pine","pizza","planet","plum","pony","poppy","prism","pumpkin","quartz","queen","quill","rabbit","radio","raft","raven","reed","rhino","ribbon","ridge","river","robin","rocket","rose","ruby","sail","salmon","sand","saturn","scroll","shark","shell","ship","silk","sled","sloth","snail","snow","spider","spruce","star","stone","sugar","summit","swan","table","teapot","thunder","tiger","tile","timber","toast","tomato","topaz","torch","tower","trout","truck","tulip","turtle","unicorn","valley","vanilla","vase","velvet","violin","volcano","wagon","walnut","wave","whale","wheat","whistle","willow","window","wizard","wolf","wombat","wren","yacht","yarn","yeti","yucca","zebra","zenith","zinc","zipper"],vector:{public_key_b64url:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",sha256_prefix_hex:"66687a",words:"iron ivory lava"}},Xo=un.words,Zo=/^[A-Za-z0-9_-]{43}$/;function la(e){if(!Zo.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=Y(e);return Array.from(t.subarray(0,un.count),n=>Xo[n]).join(un.separator)}var ca=Le.payloads.pair.mime,ol=Le.payloads.device.mime,da=Le.pair_what,mr=Le.payloads.name_max,Er=Tn.keybundle.packed_length,Sr=2;var Jo=/^[A-Za-z0-9_-]+$/;function ua(e){let t=Qo(e,"pairing");if(typeof t.bundle!="string"||!Jo.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:ei(Y(t.bundle)),name:ti(t.name)}}function Qo(e,t){let n;try{n=JSON.parse(new TextDecoder().decode(e))}catch{throw new Error(`${t} payload is not JSON`)}if(typeof n!="object"||n===null||n.v!==Sr)throw new Error(`${t} payload is not version ${Sr}`);return n}function ei(e){if(e.length!==Er)throw new Error(`a bundle is ${Er} bytes, got ${e.length}`);return e}function ti(e){if(typeof e!="string"||e.length===0||e.length>mr)throw new Error(`name must be 1 to ${mr} characters`);return e}var ni={version:1,name:"SECRETS",description:"How a secret travels (SPEC-AGENTS \xA74.3, \xA76.1). `mime` is the marker a sender pins on a file that is a secret (`seal send --kind secret`, the intake page, the local dialog); it rides encrypted in the file metadata, so a receiving agent saves it to disk and never reads it into a conversation (`seal_open inline` refuses it). `sources`: where well-known keys are created, service name \u2192 the host of its key page. A request's `where_url` whose host is in this list is shown as that service; any other https host is shown with the note that the address came from the agent and should be checked. Data, not code: a service is added with one line.",mime:"application/vnd.seal.secret",sources:{Anthropic:"console.anthropic.com",AWS:"console.aws.amazon.com","Brave Search":"api.search.brave.com",Cloudflare:"dash.cloudflare.com",DigitalOcean:"cloud.digitalocean.com",Discord:"discord.com",GitHub:"github.com","Google AI Studio":"aistudio.google.com","Google Cloud":"console.cloud.google.com",Groq:"console.groq.com","Hugging Face":"huggingface.co",Mistral:"console.mistral.ai",npm:"www.npmjs.com",OpenAI:"platform.openai.com",OpenRouter:"openrouter.ai",PyPI:"pypi.org",Slack:"api.slack.com",Stripe:"dashboard.stripe.com",Supabase:"supabase.com","Telegram BotFather":"t.me",Twilio:"console.twilio.com",Vercel:"vercel.com"},patterns_note:"What a key looks like, for every reader: `seal doctor --transcripts`, the scanner of the Pro web page and the `sealfs` detector (C1 \u042039). `pattern` is an expression in the subset all three run alike \u2014 JS, Python `re`, Rust `regex`: no lookaround, no backreference, no inline flag; a boundary is `\\b` inside the expression. The flags are shared: case-insensitive and multiline. A match that contains a string of the entry's `allowlist` (case-insensitive) is no finding. A finding is shown masked: its first four characters, `\u2026`, its last two. `vectors.hit` holds a finding of the entry, `vectors.clean` none; every reader passes them. The scanner page does not take a file larger than `max_file_bytes`; `seal doctor` reads agent transcripts of any size, a line at a time \u2014 skipping a long transcript would hide its leak. Data, not code: a service is added with one entry.",max_file_bytes:10485760,patterns:[{name:"openai_api_key",pattern:"\\bsk-proj-[A-Za-z0-9_-]{40,}",severity:"critical",description:"OpenAI API Key",keywords:["openai","sk-proj-"],vectors:{hit:"OPENAI_API_KEY=sk-proj-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEf",clean:"OPENAI_API_KEY=sk-proj-AbCdEfGhIj"}},{name:"anthropic_api_key",pattern:"\\bsk-ant-[A-Za-z0-9_-]{40,}",severity:"critical",description:"Anthropic API Key",keywords:["anthropic","sk-ant-"],vectors:{hit:"sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCd",clean:"sk-ant-api03-short"}},{name:"github_token",pattern:"\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{30,}",severity:"critical",description:"GitHub Token",keywords:["github","token","ghp_","github_pat_"],vectors:{hit:"token: ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"token: xghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"}},{name:"gitlab_token",pattern:"glpat-[A-Za-z0-9\\-]{20,}",severity:"critical",description:"GitLab Personal Access Token",keywords:["gitlab","token"],vectors:{hit:"glpat-AbCdEfGhIjKlMnOpQrSt",clean:"glpat-short"}},{name:"aws_access_key_id",pattern:"\\b(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}\\b",severity:"critical",description:"AWS Access Key ID",keywords:["aws","amazon","access_key","accesskey"],vectors:{hit:"AKIAIOSFODNN7EXAMPLE",clean:"AKIAIOSFODNN7EXAMPLEX"}},{name:"aws_secret_access_key",pattern:`aws[_\\-\\.]?secret[_\\-\\.]?access[_\\-\\.]?key['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9/+=]{40})['\\"]?`,severity:"critical",description:"AWS Secret Access Key",keywords:["aws","secret","access_key"],vectors:{hit:'aws_secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"',clean:'aws_secret_access_key = "short"'}},{name:"stripe_live_key",pattern:"\\b[sr]k_live_[A-Za-z0-9]{20,}",severity:"critical",description:"Stripe Live Secret Key",keywords:["stripe","live","secret"],vectors:{hit:"sk_live_AbCdEfGhIjKlMnOpQrStUvWx",clean:"sk_live_AbCd"}},{name:"stripe_test_key",pattern:"\\b[sr]k_test_[A-Za-z0-9]{20,}",severity:"medium",description:"Stripe Test Secret Key",keywords:["stripe","test"],vectors:{hit:"rk_test_AbCdEfGhIjKlMnOpQrStUvWx",clean:"rk_test_AbCd"}},{name:"stripe_publishable_live",pattern:"pk_live_[A-Za-z0-9]{24,}",severity:"low",description:"Stripe Live Publishable Key",keywords:["stripe","publishable"],vectors:{hit:"pk_live_AbCdEfGhIjKlMnOpQrStUvWx",clean:"pk_live_AbCd"}},{name:"slack_token",pattern:"\\bxox[abprs]-[A-Za-z0-9-]{20,}",severity:"critical",description:"Slack Token",keywords:["slack","token","xox"],vectors:{hit:"xoxb-1234567890-1234567890123-AbCdEfGhIjKl",clean:"xoxb-12345"}},{name:"slack_webhook",pattern:"https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+",severity:"high",description:"Slack Webhook URL",keywords:["slack","webhook","hooks.slack.com"],vectors:{hit:"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",clean:"https://hooks.slack.com/services/"}},{name:"google_api_key",pattern:"\\bAIza[0-9A-Za-z\\-_]{35}",severity:"high",description:"Google API Key",keywords:["google","api","AIza"],vectors:{hit:"AIzaSyAbCdEfGhIjKlMnOpQrStUvWxYz0123456",clean:"AIzaSyShort"}},{name:"google_oauth_client_secret",pattern:`client[_\\-]?secret['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9\\-_]{24})['\\"]?`,severity:"high",description:"Google OAuth Client Secret",keywords:["google","oauth","client_secret"],vectors:{hit:'client_secret: "AbCdEfGhIjKlMnOpQrStUvWx"',clean:'client_secret: "short"'}},{name:"private_key",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY(?:\\s+BLOCK)?-----",severity:"critical",description:"Private Key",keywords:["private","key","-----BEGIN"],vectors:{hit:"-----BEGIN OPENSSH PRIVATE KEY-----",clean:"-----BEGIN PUBLIC KEY-----"}},{name:"jwt_token",pattern:"eyJ[A-Za-z0-9_-]*\\.eyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]*",severity:"high",description:"JSON Web Token (JWT)",keywords:["jwt","token","eyJ"],vectors:{hit:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl",clean:"eyJhbGciOiJIUzI1NiJ9"}},{name:"basic_auth",pattern:"(?:basic\\s+)[A-Za-z0-9+/=]{20,}",severity:"high",description:"Basic Authentication Header",keywords:["basic","auth","authorization"],vectors:{hit:"Authorization: Basic dXNlcjpwYXNzd29yZDEyMzQ1Ng==",clean:"Basic auth is disabled"}},{name:"bearer_token",pattern:"bearer\\s+[A-Za-z0-9_\\-\\.]{20,}",severity:"high",description:"Bearer Token",keywords:["bearer","token","authorization"],vectors:{hit:"Authorization: Bearer AbCdEfGhIjKlMnOpQrStUvWx",clean:"Bearer token expired"}},{name:"postgres_uri",pattern:"postgres(?:ql)?://[^:]+:[^@]+@[^/]+/[^\\s]+",severity:"critical",description:"PostgreSQL Connection String",keywords:["postgres","postgresql","database"],vectors:{hit:"postgresql://app:hunter2secret@db.internal:5432/app",clean:"postgresql://db.internal/app"}},{name:"mysql_uri",pattern:"mysql://[^:]+:[^@]+@[^/]+/[^\\s]+",severity:"critical",description:"MySQL Connection String",keywords:["mysql","database"],vectors:{hit:"mysql://app:hunter2secret@db.internal/app",clean:"mysql://db.internal/app"}},{name:"mongodb_uri",pattern:"mongodb(?:\\+srv)?://[^:]+:[^@]+@[^\\s]+",severity:"critical",description:"MongoDB Connection String",keywords:["mongodb","mongo","database"],vectors:{hit:"mongodb+srv://app:hunter2secret@cluster0.example.net",clean:"mongodb://localhost"}},{name:"redis_uri",pattern:"redis://[^:]*:[^@]+@[^\\s]+",severity:"high",description:"Redis Connection String",keywords:["redis","cache"],vectors:{hit:"redis://:hunter2secret@cache.internal:6379",clean:"redis://cache.internal:6379"}},{name:"azure_storage_key",pattern:`(?:account[_\\-]?key|storage[_\\-]?key)['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9+/=]{88})['\\"]?`,severity:"critical",description:"Azure Storage Account Key",keywords:["azure","storage","account_key"],vectors:{hit:"AccountKey=AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKl",clean:"AccountKey=short"}},{name:"gcp_service_account",pattern:'"type"\\s*:\\s*"service_account"',severity:"critical",description:"GCP Service Account JSON",keywords:["gcp","google","service_account"],vectors:{hit:'{"type": "service_account", "project_id": "demo"}',clean:'{"type": "user"}'}},{name:"sendgrid_api_key",pattern:"SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}",severity:"high",description:"SendGrid API Key",keywords:["sendgrid","email","SG."],vectors:{hit:"SG.AbCdEfGhIjKlMnOpQrStUv.AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdE",clean:"SG.short.key"}},{name:"twilio_api_key",pattern:"SK[a-f0-9]{32}",severity:"high",description:"Twilio API Key",keywords:["twilio","sms"],vectors:{hit:"SK0123456789abcdef0123456789abcdef",clean:"SK0123456789abcdef"}},{name:"npm_token",pattern:"npm_[A-Za-z0-9]{36}",severity:"high",description:"NPM Access Token",keywords:["npm","token"],vectors:{hit:"npm_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"npm_short"}},{name:"pypi_token",pattern:"pypi-[A-Za-z0-9_-]{100,}",severity:"high",description:"PyPI API Token",keywords:["pypi","token","python"],vectors:{hit:"pypi-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWx",clean:"pypi-short"}},{name:"generic_password",pattern:`(?:password|passwd|pwd|secret)['\\"]?\\s*[:=]\\s*['\\"]([^'\\"]{8,})['\\"]`,severity:"medium",description:"Generic Password Assignment",keywords:["password","passwd","secret"],allowlist:["password123","changeme","example","placeholder","xxxxxxxx"],vectors:{hit:'password = "s3cr3t-Value!"',clean:'password = "changeme-now"'}},{name:"generic_api_key",pattern:`(?:api[_\\-]?key|apikey)['\\"]?\\s*[:=]\\s*['\\"]([A-Za-z0-9_\\-]{20,})['\\"]`,severity:"medium",description:"Generic API Key Assignment",keywords:["api_key","apikey"],vectors:{hit:'api_key = "AbCdEfGhIjKlMnOpQrStUvWx"',clean:'api_key = "short"'}},{name:"seal_link",pattern:"https://seal\\.net/(?:pro/)?s/[A-Za-z0-9_/-]{8,}#[A-Za-z0-9_-]{43}",severity:"critical",description:"SEAL link (it opens its seal)",keywords:["seal","seal.net/s/"],vectors:{hit:"https://seal.net/s/AbCd1234/Xy7Q#AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCde",clean:"https://seal.net/s/AbCd1234/Xy7Q"}}]},ri=ni.mime,q=class extends Error{constructor(e,t,n){super(t),this.name="OpenError",this.code=e,this.cause=n}},ai=32;async function Ln(e,t,n={}){let r;try{r=zo(t)}catch(h){throw h instanceof Mt?new q(h.code,h.message,h):h}if(r.shareCode===null)throw new q("url_invalid","share code missing from the URL path (/s/<seal_id>/<share_code>#<key>)");let{sealId:a,shareCode:s}=r;if(r.fragmentVariant!=="key"&&!n.seed)throw new q("targeted_fragment_invalid","this link is addressed to someone: pass their seed to open it");let o=n.seed,i=r.fragmentVariant==="targeted_x25519_v1"?r.fragment:n.wrap??null,l=r.fragmentVariant==="key"?Y(r.fragment):i!==null&&o?await Ar(i,o,a):null,d=n.signal?{signal:n.signal}:{},p;try{p=Ns(await e.getMetadata(r.sealId,d))}catch(h){throw h instanceof le&&(h.code==="not_found"||h.code==="revoked")?new q(h.code==="revoked"?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${h.code==="revoked"?"has been revoked":"was not found or has expired"}`,h):new q("metadata_failed",`reading seal ${r.sealId} failed: ${fn(h)}`,h)}if(p.revokedAt!==null)throw new q("seal_revoked",`seal ${r.sealId} has been revoked`);if(p.files.length===0)throw new q("seal_not_ready",`seal ${r.sealId} has no files available yet: the server verifies an upload before offering it. Retry in a few seconds.`);let f;try{let h=await e.getShareBlob(a,s,d);if(f=h.blob,l===null){if(h.wrap===null||!o)throw new q("url_no_fragment","the link carries no key and the server holds no wrap of it for this link");l=await Ar(h.wrap,o,a)}}catch(h){throw h instanceof q?h:h instanceof le&&(h.code==="not_found"||h.code==="revoked")?new q(h.code==="revoked"?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${h.code==="revoked"?"has been revoked":"was not found"}`,h):new q("share_blob_fetch_failed",`share blob fetch failed: ${fn(h)}`,h)}let u;try{u=(await Gs(f,l)).file_keys}catch(h){throw new q("share_blob_decrypt_failed","the share blob does not open with this link \u2014 mistyped URL, or the link was revoked and minted again",h)}let _=await Promise.all(p.files.map(h=>li(h,u)));return{sealId:a,expiresAt:p.expiresAt,singleUse:p.singleUse,maxOpens:p.maxOpens,otpRequired:p.otpRequired,ndaRequired:p.ndaRequired,files:_}}async function Ar(e,t,n){try{return await jo(e,t,kn,n)}catch(r){let a=r instanceof Ee&&r.kind==="aead";throw new q(a?"targeted_decrypt_failed":"targeted_fragment_invalid",fn(r),r)}}async function fa(e,t,n={}){for(;;){let r;try{r=await e.getIntake(t,{...n,waitSeconds:Ke.limits.INTAKE_WAIT_MAX_SECONDS})}catch(a){throw a instanceof le&&a.code==="not_found"?new q("request_expired","the request expired before anybody answered",a):a}if(r.status==="expired")throw new q("request_expired","nobody answered before the request expired");if(r.status==="fulfilled"&&r.share_path&&r.fragment)return{sharePath:r.share_path,wrap:r.fragment}}}var si=64*1024;async function ha(e,t,n,r){let a=await Ln(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||_a(s.mime)!==n||s.size>si)throw new q("share_blob_corrupt",`the answer is not one ${n} file`);let i=await e.openDownload(a.sealId,{fileId:s.id},r.signal?{signal:r.signal}:{});if(!i.body)throw new q("share_blob_corrupt","the answer came without a body");let l=Bn(i.body,s.key,s.sha256Hex).stream.getReader(),d=[];for(let u=await l.read();!u.done;u=await l.read())d.push(u.value);let p=new Uint8Array(d.reduce((u,_)=>u+_.length,0)),f=0;for(let u of d)p.set(u,f),f+=u.length;return p}var oi=3e4,vr=new Map;async function ii(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&ui(r,t.bundle)||await e.putBundle(t.bundle,n)}async function Tr(e,t,n={}){let r=await Yt(t),a=`${e.baseUrl} ${r.address}`,s=vr.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await ii(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await Vo(t,o)};return vr.set(a,{proof:i,until:Date.parse(o.expires_at)-oi}),i}async function wt(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await Tr(e,t,a))}catch(s){if(!(s instanceof le&&s.appCode==="intake.proof_required"))throw s;return r(await Tr(e,t,{...a,fresh:!0}))}}async function pa(e,t,n={}){let{legacyAddress:r}=await Yt(t);return wt(e,t,n.signal,async a=>{let s=await e.migrateInbox(a,{old_address:r},n),o=await qo(t,s.challenge,s.ts);return(await e.migrateInbox(a,{old_address:r,old_proof:o},n)).moved})}async function Pn(e,t,n={}){let r=n;return wt(e,t,n.signal,a=>e.listInbox(a,r))}async function ya(e,t,n,r={}){return wt(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function li(e,t){let n=e.sha256_hex?t[e.sha256_hex]:void 0,r={id:e.id,size:e.size,sha256Hex:e.sha256_hex};if(n===void 0)return{...r,name:Wt,mime:zt,secret:!1,key:null};let a;try{a=Y(n)}catch(i){throw new q("share_blob_corrupt",`share blob carries a non-base64url key for ${e.sha256_hex}`,i)}if(a.length!==ai)throw new q("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${a.length} bytes`);let{name:s,mime:o}=await bo(e,a);return{...r,name:s,mime:o,secret:_a(o)===ri,key:a}}function _a(e){return(e.split(";")[0]??e).trim().toLowerCase()}function Bn(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=Bt.create(),o=0,i,l=new Promise((u,_)=>{i={resolve:u,reject:_}});l.catch(()=>{});let d=new TransformStream({transform(u,_){r(u.length),_.enqueue(u)}}),p=new TransformStream({transform(u,_){s.update(u),o+=u.length,_.enqueue(u)},flush(){a.fill(0),i.resolve({sizeBytes:o,sha256:di(s.digest())})}}),f=e.pipeThrough(d).pipeThrough(no(a,{expectedSha256Hex:n})).pipeThrough(p);return{stream:fi(f,i.reject,a),done:l}}function ci(e){return e instanceof Re?new q(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function di(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ui(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function fi(e,t,n){let r=e.getReader();return new ReadableStream({async pull(a){try{let{value:s,done:o}=await r.read();o?a.close():a.enqueue(s)}catch(s){let o=ci(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function fn(e){return e instanceof Error?e.message:String(e)}var hi="_",pi=200,yi=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);function _i(){if(typeof process<"u"&&process.platform)switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";case"android":return"android";default:return"unknown"}if(typeof navigator<"u"&&navigator.userAgent){let e=navigator.userAgent.toLowerCase();if(e.includes("win"))return"windows";if(e.includes("android"))return"android";if(e.includes("iphone")||e.includes("ipad")||e.includes("ipod"))return"ios";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"}function wi(e,t){let n=e.charCodeAt(0);if(n<32||n===127)return!1;switch(t){case"windows":return!/[<>:"/\\|?*]/.test(e);case"macos":case"ios":return!/[/:]/.test(e);case"linux":case"android":return e!=="/";default:return!/[<>:"/\\|?*]/.test(e)}}function gi(e){let t=e.split(".")[0].toUpperCase();return yi.has(t)}function wa(e,t={}){let{platform:n=_i(),replacement:r=hi,maxLength:a=pi,fallback:s="file"}=t;if(!e||!e.trim())return s;let o=e.normalize("NFC");o=o.trim(),o=o.replace(/^\.+|\.+$/g,""),o=[...o].map(d=>wi(d,n)?d:r).join("");let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${l}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${l})+|${l}+$`,"g"),""),(n==="windows"||n==="unknown")&&gi(o)&&(o=`${r}${o}`),o.length>a){let d=o.lastIndexOf(".");if(d>0&&d>o.length-10){let p=o.slice(d);o=o.slice(0,a-p.length)+p}else o=o.slice(0,a)}return!o||o===r?s:o}var ga={version:1,limits:{MAX_FILES_PER_SEAL:30,FREE_TIER_BYTES:1073741824,MAX_TOTAL_SIZE_BYTES:1073741824,MAX_FILE_SIZE_BYTES:10737418240,MAX_MULTIPART_FILE_SIZE_BYTES:10737418240,MAX_BLOB_SIZE:1048576,MAX_BLOB_BASE64_SIZE:1468006,MAX_MESSAGE_LENGTH:5e3,MAX_FILE_KEYS:1e4,MAX_ACTIVE_UPLOADS_PER_SEAL:10,MAX_OPENS_PER_SEAL_FREE:10,TIER_BYTES:{free:1073741824,"5gb":5368709120,"50gb":53687091200,"500gb":536870912e3},SEAL_TIERS:{"5gb":{bytes:5368709120,amount_cents:900,duration_days:90,name:"5 GB / 3 months",description:"One-time payment for 5 GB storage and 3 months TTL"},"50gb":{bytes:53687091200,amount_cents:2900,duration_days:180,name:"50 GB / 6 months",description:"One-time payment for 50 GB storage and 6 months TTL"},"500gb":{bytes:536870912e3,amount_cents:9900,duration_days:365,name:"500 GB / 12 months",description:"One-time payment for 500 GB storage and 12 months TTL"}},PRO_REGIONS:["eu-west","us-east","us-west","apac-southeast","apac-northeast"],ttl_options:["5m","30m","1h","1d","7d"],OTP_LENGTH:{min:6,max:10},USER_PASSWORD_MIN_LENGTH:8,INTAKE_TTL_DEFAULT_SECONDS:900,INTAKE_TTL_MAX_SECONDS:86400,INTAKE_WAIT_MAX_SECONDS:25,PAYMENT_WAIT_MAX_SECONDS:82800,ADDRESS_PROOF_TTL_SECONDS:300,INBOX_MAX_ITEMS:200,DRIVE_OPEN_TTL_SECONDS:300,DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES:67108864,DRIVE_PRESIGN_WINDOW_MIN_BYTES:8388608,DRIVE_PRESIGN_UNBOUND_TTL_SECONDS:30,DRIVE_WRITE_LEASE_SECONDS:7200,DRIVE_WRITE_BACK_SECONDS:5,VERSION_RETENTION_DAYS_DEFAULT:30,VERSION_KEEP_MIN:10,GRANT_WORKLOAD_MAX_TTL_DAYS:90,SENSOR_OPENS_PER_MINUTE_DEFAULT:120,SENSOR_BYTES_PER_MINUTE_DEFAULT:2147483648,SENSOR_SECRETS_PER_MINUTE_DEFAULT:20,SENSOR_NOVELTY_WINDOW_DAYS:30,SENSOR_HOLD_TTL_SECONDS:86400,SENSOR_BASELINE_MIN_HOURS:72,SENSOR_GROWTH_BYTES_PER_DAY_DEFAULT:107374182400}};var K=class e extends Error{code;status;details;constructor(t,n,r,a=null,s){super(t,s),this.name="SealError",this.code=n,this.status=r,this.details=a,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},mi={url_invalid:"VALIDATION_ERROR",url_no_fragment:"VALIDATION_ERROR",targeted_fragment_invalid:"INVALID_KEY",targeted_decrypt_failed:"INVALID_KEY",seal_not_found:"RESOURCE_NOT_FOUND",seal_revoked:"RESOURCE_NOT_FOUND",share_link_not_found:"RESOURCE_NOT_FOUND",share_link_revoked:"RESOURCE_NOT_FOUND",request_expired:"RESOURCE_NOT_FOUND",seal_not_ready:"SERVICE_UNAVAILABLE",metadata_failed:"SERVICE_UNAVAILABLE",share_blob_fetch_failed:"SERVICE_UNAVAILABLE",share_blob_decrypt_failed:"DECRYPTION_ERROR",share_blob_corrupt:"DECRYPTION_ERROR",integrity_check_failed:"DECRYPTION_ERROR",client_outdated:"CLIENT_OUTDATED"};function ce(e,t,n=null){if(e instanceof K)return e;if(e instanceof q){let r=e.cause instanceof le?e.cause.status:400;return new K(e.message,mi[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof le){let r=e.appCode==="client.outdated"?"CLIENT_OUTDATED":e.appCode==="intake.proof_required"?"AUTH_INVALID_KEY":e.code==="not_found"||e.code==="revoked"?"RESOURCE_NOT_FOUND":e.code==="auth"?"AUTH_INSUFFICIENT_SCOPE":e.code==="rate_limited"?"RATE_LIMITED":e.code==="transient"?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR";return new K(e.detail??t,r,e.status,n,{cause:e})}return new K(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}var Ol=ga.limits.ttl_options,Vt=class{api;baseUrl;shareUrlBase;credentials;constructor(t){this.baseUrl=(t?.apiUrl||"").replace(/\/$/,""),this.shareUrlBase=(t?.shareUrl||"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.credentials=t?.credentials,this.api=new yt({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){if(t.nda&&!t.ownerEmail)throw new K("ownerEmail is required when nda=true","VALIDATION_ERROR",400);if(t.tier&&!t.onPaymentRequired)throw new K("onPaymentRequired is required with tier","VALIDATION_ERROR",400);let n=(S,W)=>{if(W!==void 0)try{return oa(W)}catch(D){throw new K(`${S}: ${D instanceof Error?D.message:String(D)}`,"VALIDATION_ERROR",400)}},r=n("to",t.to),a=n("owner",t.owner),s=t.signal?{signal:t.signal}:{},o=async S=>{let W=await this.api.getBundle(S,s);return W&&await ia(W,S)?W:null},i=null;if(r){try{i=await o(r)}catch(S){throw ce(S,"Failed to read the recipient key")}if(!i)throw new K(`to: ${r} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let l=a?await o(a).catch(()=>null):null,d=t.keyPair?Y(t.keyPair.secretKey):null,p=S=>d?wt(this.api,d,t.signal,S):S(),f=t.mimeType||t.file instanceof File&&t.file.type||"application/octet-stream",u;if(t.file instanceof File&&t.file.name===t.filename&&t.file.type===f)u=t.file;else if(t.file instanceof Blob)u=new File([t.file],t.filename,{type:f});else if(t.file instanceof Uint8Array){let S=t.file.buffer.slice(t.file.byteOffset,t.file.byteOffset+t.file.byteLength);u=new File([S],t.filename,{type:f})}else u=new File([t.file],t.filename,{type:f});let _=Mr(),h=Q(_),E=await Nr(_),g=_n(),M=Q(g),F={baseUrl:this.baseUrl,auth:{kind:"none"},ttl:t.ttl,ownerTokenHash:E,ownerToken:h,...this.credentials!==void 0?{credentials:this.credentials}:{},...t.otp!==void 0?{otp:t.otp}:{},...t.nda!==void 0?{nda:t.nda}:{},...t.nda&&t.ownerEmail!==void 0?{ownerEmail:t.ownerEmail}:{},...t.singleUse!==void 0?{singleUse:t.singleUse}:{},...t.geoAllowlist!==void 0?{geo:t.geoAllowlist}:{},...t.maxOpens!==void 0?{maxOpens:t.maxOpens}:{},...t.tier!==void 0?{tier:t.tier}:{}},k=null,x=S=>({sealId:S,ownerToken:h,ownerLinkKey:M}),P=t.message?.trim()?t.message:void 0,B=!1;try{let S=t.onProgress,W={...S?{onProgress:ne=>S({phase:ne.phase,percent:ne.percent})}:{},...t.signal?{signal:t.signal}:{},onRegistered:async(ne,Z)=>{k=ne;let Ae=new Map(Z.map(ue=>[ue.sha256_hex,Q(ue.key)])),de=Q(await Ur(h,Ae,g,P));if(a&&l){let ue=await Rn(g,l,aa,ne);B=await p(_e=>this.api.writeOwnerBlob(ne,h,de,{...s,to:a,fragment:ue,label:"sealnet",..._e?{sender:_e}:{}})).then(()=>!0,()=>!1)}try{B||await this.api.writeOwnerBlob(ne,h,de,s)}catch(ue){throw ce(ue,"Failed to store encrypted blob",x(ne))}}},D,fe;try{D=await Zr(F,u,Gt,W),fe=D.expiresAt}catch(ne){let Z=Jr(ne);if(!Z||!t.tier||!t.onPaymentRequired)throw ne;let Ae=t.signal?{signal:t.signal}:{};await t.onPaymentRequired(await this.api.createCheckout(Z.sealId,h,t.tier,Ae));let de=Qr(Z instanceof mn?Z.expiresAt:void 0),ue=await ea(this.api,Z.sealId,h,{deadline:de,...Ae});if(!ue)throw await this.api.revoke(Z.sealId,h).catch(()=>{}),new K("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,x(Z.sealId));D=await Z.resume(W),fe=ue.expires_at}if(!fe)throw new K(`Seal ${D.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,x(D.sealId));let b=new Map;b.set(D.sha256_hex,Q(D.encryptionKey));let I=_n(),ee=Q(I),z=await Fr(b,I,P),N=r&&i?await Rn(I,i,kn,D.sealId):null,pe;try{let ne=Q(z);pe=r&&N?await p(Z=>this.api.createShareLink(D.sealId,h,ne,{...s,to:r,fragment:N,label:"sealnet",...Z?{sender:Z}:{}})):await this.api.createShareLink(D.sealId,h,ne,s)}catch(ne){throw ce(ne,"Seal created but share link mint failed",x(D.sealId))}let te=ra(D.sealId,pe,ee),Te=`${this.shareUrlBase}${N?te.split("#")[0]:te}`,Ze=`${this.shareUrlBase}${na(D.sealId,M)}`,Je=Ie(D.encryptionKey);return{sealId:D.sealId,shareUrl:Te,ownerUrl:Ze,ownerToken:h,expiresAt:fe,encryptionKey:Je,fileId:D.fileId,delivered:N!==null,ownerCopy:B}}catch(S){if(S instanceof K)throw S;if(k){let W=S instanceof Error?S.message:String(S);throw new K(`Seal ${k} was created but the create flow was interrupted: ${W}`,"INTERNAL_ERROR",500,x(k),{cause:S})}throw S}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw ce(a,"Failed to revoke seal")}}};async function ba(e,t,n){let r=await import("fs/promises"),a=await import("path");await r.mkdir(t,{recursive:!0});let s=Array.from(crypto.getRandomValues(new Uint8Array(6)),d=>d.toString(16).padStart(2,"0")).join(""),o=a.join(t,`.seal-partial-${s}`),i=await r.open(o,"wx",384),l=!1;try{await e.stream.pipeTo(new WritableStream({async write(_){await i.write(_)}}));let{sizeBytes:d,sha256:p}=await e.done;await i.sync(),await i.close();let f=a.extname(n),u=n.slice(0,n.length-f.length);for(let _=0;_<1e3;_++){let h=a.join(t,_===0?n:`${u} (${_})${f}`);try{await r.link(o,h)}catch(E){if(E.code==="EEXIST")continue;throw E}return await r.unlink(o),l=!0,{path:h,sizeBytes:d,sha256:p}}throw new Error(`no free name for ${n} in ${t}`)}finally{l||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}async function ma(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await Ln(e,t,{...n.keyPair?{seed:Y(n.keyPair.secretKey)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new K("This seal asks for an NDA signature: open it in a browser","AUTH_INSUFFICIENT_SCOPE",403);let o=null;if(s.otpRequired){if(!n.password)throw new K("This seal is password-protected: pass `password`","AUTH_INVALID_KEY",401);o=(await e.verifyOtp(s.sealId,{code:n.password},a)).sessionCookie}let i=s.files.filter(f=>f.key!==null&&f.sha256Hex!==null),l=i.reduce((f,u)=>f+u.size,0),d=0;return{seal:s,covered:i,read:async f=>{let u=await e.openDownload(s.sealId,{fileId:f.id,...o?{sessionCookie:o}:{}},a);if(!u.body)throw new K(`Download of ${f.name} returned no body`,"INTERNAL_ERROR",u.status);return Bn(u.body,f.key,f.sha256Hex,_=>{d+=_,n.onProgress?.(d,l)})}}}async function Dn(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await ma(e,t,n,r);return{sealId:a.sealId,expiresAt:a.expiresAt,files:s.map(i=>({name:i.name,mime:i.mime,size:i.size,secret:i.secret,read:()=>o(i).catch(l=>Promise.reject(ce(l,"Download failed")))}))}}catch(a){throw ce(a,"Failed to open the link")}}async function Cn(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i}=await ma(e,t,r,a),l=[];for(let d of o){let p=await ba(await i(d),n,wa(d.name));l.push({name:d.name,mime:d.mime,secret:d.secret,...p})}return{sealId:s.sealId,expiresAt:s.expiresAt,files:l}}catch(s){throw ce(s,"Failed to open the link")}}async function Ea(e,t,n){try{let r=await e.createIntake({recipientBundle:n.recipientBundle,label:n.label??"sealnet",what:n.what,...n.whereUrl?{whereUrl:n.whereUrl}:{},...n.kind?{kind:n.kind}:{},...n.ttl!==void 0?{ttlSeconds:n.ttl}:{},...n.to!==void 0?{to:n.to}:{}},n.signal?{signal:n.signal}:{});return{intakeId:r.id,url:`${t}/i/${r.id}`,words:(await On(Y(n.recipientBundle))).words,expiresAt:r.expires_at}}catch(r){throw ce(r,"Failed to create the request")}}async function Mn(e,t,n){try{return await fa(e,t,n?{signal:n}:{})}catch(r){throw ce(r,"Failed to wait for the request")}}async function Sa(e,t,n){let r;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:da,kind:"pair"},n.signal?{signal:n.signal}:{})}catch(s){throw ce(s,"Failed to create the pairing request")}let a=async()=>{let{sharePath:s,wrap:o}=await Mn(e,r.id,n.signal);try{let i=await ha(e,`${t}${s}`,ca,{seed:Y(n.keyPair.secretKey),wrap:o,...n.signal?{signal:n.signal}:{}}),{bundle:l,name:d}=ua(i);return{address:(await On(l)).address,name:d}}catch(i){throw ce(i,"The answer of the inbox did not open")}};return{url:`${t}/i/${r.id}`,words:n.keyPair.words,expiresAt:r.expires_at,wait:a}}async function Aa(){let e=sa(),{address:t,bundle:n,words:r}=await Yt(e);return{secretKey:Q(e),address:t,bundle:Q(n),words:r}}async function va(e,t){let n=Y(t.keyPair.secretKey),r=Date.now()+(t.wait??0)*1e3;try{for(await pa(e,n,t.signal?{signal:t.signal}:{}).catch(()=>0);;){let a=Math.ceil((r-Date.now())/1e3),s=await Pn(e,n,{...a>0?{waitSeconds:a}:{},...t.seen!==void 0?{seen:t.seen}:{},...t.signal?{signal:t.signal}:{}});if((t.seen!==void 0?s.version!==t.seen:s.items.length>0)||Date.now()>=r)return{version:s.version,items:s.items.map(i=>({id:i.id,fromWords:i.sender===null?null:la(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw ce(a,"Failed to read the inbox")}}async function Ta(e,t,n,r){let a;try{a=(await Pn(e,Y(r.keyPair.secretKey),r.signal?{signal:r.signal}:{})).items}catch(o){throw ce(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new K(`${n.id} is not in the inbox: it was revoked, expired or removed`,"RESOURCE_NOT_FOUND",404);return{url:`${t}${s.path}`,wrap:s.fragment}}async function ka(e,t,n){try{await ya(e,Y(n.keyPair.secretKey),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw ce(r,"Failed to remove the item")}}var[Ei="",xa=""]="sdk-web/2.0.0".split("/");typeof globalThis.process?.versions?.node!="string"&&Jn(be);var Nn=class{seals;api;site;constructor(t={}){Br(Ei,xa);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new Vt({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new yt({baseUrl:n,credentials:"omit"})}async send(t){return this.seals.create(t)}async open(t,n={}){let{to:r,...a}=n,s;if(typeof t=="string")s={url:t,wrap:null};else if(a.keyPair)s=await Ta(this.api,this.site,t,{keyPair:a.keyPair,...a.signal?{signal:a.signal}:{}});else throw new K("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?Cn(this.api,s.url,r,a,s.wrap):Dn(this.api,s.url,a,s.wrap)}async inbox(t){return va(this.api,t)}async dismiss(t,n){return ka(this.api,t,n)}async request(t){return Ea(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await Mn(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?Cn(this.api,i,s,o,a):Dn(this.api,i,o,a)}async pair(t){return Sa(this.api,this.site,t)}async keygen(){return Aa()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},Si=xa;return Ka(Ai);})();
1
+ /*! sealnet v2.0.1 | Proprietary — see LICENSE | bundles MIT-licensed @noble/hashes (Copyright (c) 2022 Paul Miller (https://paulmillr.com)), fflate (Copyright (c) 2023 Arjun Barrett) | full texts: THIRD-PARTY-NOTICES.txt */
2
+ "use strict";var Seal=(()=>{var Ua=Object.create;var At=Object.defineProperty;var Fa=Object.getOwnPropertyDescriptor;var $a=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var Hn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var za=(e,t)=>{for(var n in t)At(e,n,{get:t[n],enumerable:!0})},zn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of $a(t))!Ha.call(e,a)&&a!==n&&At(e,a,{get:()=>t[a],enumerable:!(r=Fa(t,a))||r.enumerable});return e};var Kn=(e,t,n)=>(n=e!=null?Ua(Wa(e)):{},zn(t||!e||!e.__esModule?At(n,"default",{value:e,enumerable:!0}):n,e)),Ka=e=>zn(At({},"__esModule",{value:!0}),e);var Ai={};za(Ai,{SealClient:()=>Nn,SealError:()=>K,VERSION:()=>Si});var be={url:"https://seal.net/sdk/v2.0.1/seal_crypto.wasm",integrity:"sha384-bbicfS1liwHQ9WbNLPa8l66ReuwXxR8f3oUoYTqmjFhMRQez08ujjIkXQw+L5018"};var Es={},ja=Object.defineProperty,Ya=(e,t)=>{for(var n in t)ja(e,n,{get:t[n],enumerable:!0})},qn={};Ya(qn,{WasmIdentity:()=>en,default:()=>ds,init:()=>Va,initSync:()=>cs,wasm_bundle_address:()=>qa,wasm_bundle_verify_for_address:()=>Xa,wasm_contract_message:()=>Za,wasm_ed25519_verify:()=>Ja,wasm_sealbox_unwrap:()=>Qa,wasm_sealbox_wrap:()=>es,wasm_unwrap_file_key:()=>ts,wasm_wrap_file_key:()=>ns});var en=class Tt{static __wrap(t){let n=Object.create(Tt.prototype);return n.__wbg_ptr=t,Gn.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Gn.unregister(this),t}free(){let t=this.__destroy_into_raw();c.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_address(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Ue(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}bundle(){let t=c.wasmidentity_bundle(this.__wbg_ptr);return H(t)}static fromSeed32(t){try{let s=c.__wbindgen_add_to_stack_pointer(-16),o=te(t,c.__wbindgen_export3),i=T;c.wasmidentity_fromSeed32(s,o,i);var n=S().getInt32(s+0,!0),r=S().getInt32(s+4,!0),a=S().getInt32(s+8,!0);if(a)throw H(r);return Tt.__wrap(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=te(t,c.__wbindgen_export3),l=T;c.wasmidentity_fromSeed64(o,i,l,n);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw H(a);return Tt.__wrap(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=te(n,c.__wbindgen_export3),l=T;c.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,l);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw H(a);return H(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}legacyAddress(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_legacyAddress(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Ue(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}open(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=te(t,c.__wbindgen_export3),d=T,p=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),f=T,u=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),_=T;c.wasmidentity_open(i,this.__wbg_ptr,l,d,p,f,u,_);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signContract(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=oe(t,c.__wbindgen_export3,c.__wbindgen_export4),d=T,p=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),f=T,u=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),_=T;c.wasmidentity_signContract(i,this.__wbg_ptr,l,d,p,f,u,_);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_words(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Ue(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=te(t,c.__wbindgen_export3),l=T,d=te(n,c.__wbindgen_export3),p=T;c.wasmidentity_workloadProof(o,this.__wbg_ptr,i,l,d,p);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw H(a);return H(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(en.prototype[Symbol.dispose]=en.prototype.free);function Va(){c.init()}function qa(e){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=te(e,c.__wbindgen_export3),o=T;c.wasm_bundle_address(a,s,o);var t=S().getInt32(a+0,!0),n=S().getInt32(a+4,!0),r=S().getInt32(a+8,!0);if(r)throw H(n);return H(t)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function Xa(e,t){let n=te(e,c.__wbindgen_export3),r=T,a=oe(t,c.__wbindgen_export3,c.__wbindgen_export4),s=T;return c.wasm_bundle_verify_for_address(n,r,a,s)!==0}function Za(e,t,n){let r,a;try{let f=c.__wbindgen_add_to_stack_pointer(-16),u=oe(e,c.__wbindgen_export3,c.__wbindgen_export4),_=T,h=oe(t,c.__wbindgen_export3,c.__wbindgen_export4),m=T,g=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),N=T;c.wasm_contract_message(f,u,_,h,m,g,N);var s=S().getInt32(f+0,!0),o=S().getInt32(f+4,!0),i=S().getInt32(f+8,!0),l=S().getInt32(f+12,!0),d=s,p=o;if(l)throw d=0,p=0,H(i);return r=d,a=p,Ue(d,p)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function Ja(e,t,n){let r=te(e,c.__wbindgen_export3),a=T,s=te(t,c.__wbindgen_export3),o=T,i=te(n,c.__wbindgen_export3),l=T;return c.wasm_ed25519_verify(r,a,s,o,i,l)!==0}function Qa(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=te(e,c.__wbindgen_export3),d=T,p=te(t,c.__wbindgen_export3),f=T,u=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),_=T,h=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),m=T;c.wasm_sealbox_unwrap(i,l,d,p,f,u,_,h,m);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function es(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=te(e,c.__wbindgen_export3),d=T,p=te(t,c.__wbindgen_export3),f=T,u=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),_=T,h=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),m=T;c.wasm_sealbox_wrap(i,l,d,p,f,u,_,h,m);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function ts(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=te(e,c.__wbindgen_export3),d=T,p=te(t,c.__wbindgen_export3),f=T,u=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),_=T,h=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),m=T;c.wasm_unwrap_file_key(i,l,d,p,f,u,_,h,m);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function ns(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=te(e,c.__wbindgen_export3),d=T,p=te(t,c.__wbindgen_export3),f=T,u=oe(n,c.__wbindgen_export3,c.__wbindgen_export4),_=T,h=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),m=T;c.wasm_wrap_file_key(i,l,d,p,f,u,_,h,m);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw H(s);return H(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function Xn(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof W(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=W(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof W(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return W(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Ue(t,n))},__wbg_call_a41d6421b30a32c5:function(){return st(function(t,n,r){let a=W(t).call(W(n),W(r));return J(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=W(t).crypto;return J(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Ue(t,n))}finally{c.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return st(function(t,n){W(t).getRandomValues(W(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return W(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=W(t).msCrypto;return J(n)},__wbg_new_227d7c05414eb861:function(){let t=new Error;return J(t)},__wbg_new_2fad8ca02fd00684:function(){let t=new Object;return J(t)},__wbg_new_from_slice_5a173c243af2e823:function(t,n){let r=new Uint8Array(Jt(t,n));return J(r)},__wbg_new_with_length_9011f5da794bf5d9:function(t){let n=new Uint8Array(t>>>0);return J(n)},__wbg_node_84ea875411254db1:function(t){let n=W(t).node;return J(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=W(t).process;return J(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(Jt(t,n),W(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return st(function(t,n){W(t).randomFillSync(H(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return st(function(){let t=module.require;return J(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return st(function(t,n,r){return Reflect.set(W(t),W(n),W(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=W(n).stack,a=oe(r,c.__wbindgen_export3,c.__wbindgen_export4),s=T;S().setInt32(t+4,s,!0),S().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return vt(t)?0:J(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return vt(t)?0:J(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return vt(t)?0:J(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return vt(t)?0:J(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=W(t).subarray(n>>>0,r>>>0);return J(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=W(t).versions;return J(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=Jt(t,n);return J(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Ue(t,n);return J(r)},__wbindgen_object_clone_ref:function(t){let n=W(t);return J(n)},__wbindgen_object_drop_ref:function(t){H(t)}}}}var Gn=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_wasmidentity_free(e,1));function J(e){it===xe.length&&xe.push(xe.length+1);let t=it;return it=xe[t],xe[t]=e,t}function rs(e){e<1028||(xe[e]=it,it=e)}function Jt(e,t){return e=e>>>0,je().subarray(e/1,e/1+t)}var Ne=null;function S(){return(Ne===null||Ne.buffer.detached===!0||Ne.buffer.detached===void 0&&Ne.buffer!==c.memory.buffer)&&(Ne=new DataView(c.memory.buffer)),Ne}function Ue(e,t){return ss(e>>>0,t)}var ot=null;function je(){return(ot===null||ot.byteLength===0)&&(ot=new Uint8Array(c.memory.buffer)),ot}function W(e){return xe[e]}function st(e,t){try{return e.apply(this,t)}catch(n){c.__wbindgen_export(J(n))}}var xe=new Array(1024).fill(void 0);xe.push(void 0,null,!0,!1);var it=xe.length;function vt(e){return e==null}function te(e,t){let n=t(e.length*1,1)>>>0;return je().set(e,n/1),T=e.length,n}function oe(e,t,n){if(n===void 0){let i=lt.encode(e),l=t(i.length,1)>>>0;return je().subarray(l,l+i.length).set(i),T=i.length,l}let r=e.length,a=t(r,1)>>>0,s=je(),o=0;for(;o<r;o++){let i=e.charCodeAt(o);if(i>127)break;s[a+o]=i}if(o!==r){o!==0&&(e=e.slice(o)),a=n(a,r,r=o+e.length*3,1)>>>0;let i=je().subarray(a+o,a+r),l=lt.encodeInto(e,i);o+=l.written,a=n(a,r,o,1)>>>0}return T=o,a}function H(e){let t=W(e);return rs(e),t}var kt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});kt.decode();var as=2146435072,Qt=0;function ss(e,t){return Qt+=t,Qt>=as&&(kt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),kt.decode(),Qt=t),kt.decode(je().subarray(e,e+t))}var lt=new TextEncoder;"encodeInto"in lt||(lt.encodeInto=function(e,t){let n=lt.encode(e);return t.set(n),{read:e.length,written:n.length}});var T=0,os,is,c;function Zn(e,t){return is=e,c=e.exports,os=t,Ne=null,ot=null,c}async function ls(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(a){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",a);else throw a}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}function cs(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Xn();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Zn(n,e)}async function ds(e){if(c!==void 0)return c;if(e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0)throw new Error("SEAL crypto: the WASM source must be passed to the loader");let t=Xn();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await ls(await e,t);return Zn(n,r)}var us="seal_crypto.wasm",ke=null,xt=null,Ge=null;function Jn(e){if(xt||Ge)throw new Error("configureWasm: the WASM is already loaded or loading");ke=e}function fs(){return typeof globalThis.process?.versions?.node=="string"}async function jn(e){let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}async function hs(){if(ke&&"url"in ke)return fetch(ke.url,ke.integrity?{integrity:ke.integrity}:{});if(ke&&"path"in ke)return jn(ke.path);if(fs())return jn(new URL(us,Es.url));throw new Error("sealnet: no WASM source in this browser (a broken build — reinstall sealnet)")}async function Fe(){if(xt)return xt;if(Ge)return Ge;Ge=(async()=>{let e=qn;return await e.default({module_or_path:await hs()}),typeof e.init=="function"&&e.init(),xt=e,e})();try{return await Ge}catch(e){throw Ge=null,e}}async function ps(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Ye(e){let t=await ps(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}var Yn=32768,Vn=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function ys(e){let t="";for(let n=0;n<e.length;n+=Yn){let r=e.subarray(n,Math.min(n+Yn,e.length));t+=String.fromCharCode.apply(null,r)}return t}function _s(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function ws(e){let t=e.substring(0,20)+(e.length>20?"...":"");if(typeof atob<"u")try{return atob(e)}catch(n){throw new Vn(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new Vn(`Invalid base64 encoding: ${n.message}`,t)}}function gs(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function bs(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function ms(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ie(e){return gs(ys(e))}function ne(e){return ms(Ie(e))}function It(e){return _s(ws(e))}function V(e){return It(bs(e))}function Ss(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Rt(e,...t){if(!Ss(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function tn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Qn(e,t){Rt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ct(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Lt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function me(e,t){return e<<32-t|e>>>t}function As(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function nn(e){return typeof e=="string"&&(e=As(e)),Rt(e),e}var Ot=class{};function er(e){let t=r=>e().update(nn(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function vs(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let a=BigInt(32),s=BigInt(4294967295),o=Number(n>>a&s),i=Number(n&s),l=r?4:0,d=r?0:4;e.setUint32(t+l,o,r),e.setUint32(t+d,i,r)}function tr(e,t,n){return e&t^~e&n}function nr(e,t,n){return e&t^e&n^t&n}var Pt=class extends Ot{constructor(t,n,r,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=a,this.buffer=new Uint8Array(t),this.view=Lt(this.buffer)}update(t){tn(this),t=nn(t),Rt(t);let{view:n,buffer:r,blockLen:a}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(a-this.pos,s-o);if(i===a){let l=Lt(t);for(;a<=s-o;o+=a)this.process(l,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===a&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){tn(this),Qn(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,ct(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let f=o;f<a;f++)n[f]=0;vs(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Lt(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=l/4,p=this.get();if(d>p.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<d;f++)i.setUint32(4*f,p[f],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:n,buffer:r,length:a,finished:s,destroyed:o,pos:i}=this;return t.destroyed=o,t.finished=s,t.length=a,t.pos=i,a%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ts=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Be=new Uint32Array(64),rn=class extends Pt{constructor(t=32){super(64,t,8,!1),this.A=Oe[0]|0,this.B=Oe[1]|0,this.C=Oe[2]|0,this.D=Oe[3]|0,this.E=Oe[4]|0,this.F=Oe[5]|0,this.G=Oe[6]|0,this.H=Oe[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:l}=this;return[t,n,r,a,s,o,i,l]}set(t,n,r,a,s,o,i,l){this.A=t|0,this.B=n|0,this.C=r|0,this.D=a|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=l|0}process(t,n){for(let f=0;f<16;f++,n+=4)Be[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let u=Be[f-15],_=Be[f-2],h=me(u,7)^me(u,18)^u>>>3,m=me(_,17)^me(_,19)^_>>>10;Be[f]=m+Be[f-7]+h+Be[f-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:l,G:d,H:p}=this;for(let f=0;f<64;f++){let u=me(i,6)^me(i,11)^me(i,25),_=p+u+tr(i,l,d)+Ts[f]+Be[f]|0,m=(me(r,2)^me(r,13)^me(r,22))+nr(r,a,s)|0;p=d,d=l,l=i,i=o+_|0,o=s,s=a,a=r,r=_+m|0}r=r+this.A|0,a=a+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,l=l+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(r,a,s,o,i,l,d,p)}roundClean(){ct(Be)}destroy(){this.set(0,0,0,0,0,0,0,0),ct(this.buffer)}};var Bt=er(()=>new rn);var he={version:2,name:"AEON",magic_bytes:[65,69,79,52],magic_length:4,header_length:24,header_layout:[{name:"magic",offset:0,length:4},{name:"segment_size_u32_le",offset:4,length:4},{name:"file_id",offset:8,length:16}],nonce_length:12,tag_length:16,segment_overhead:28,segment_size_bytes:1048576,min_segment_size_bytes:1048576,max_segment_size_bytes:67108864,aad_layout:[{name:"header",length:24},{name:"segment_index_u64_le",length:8},{name:"last_u8",length:1}],supported_format_versions:[3,4],current_format_version:4,v3_reader:{magic_bytes:[65,69,79,78],header_length:8}},hn=new Uint8Array(he.magic_bytes),Nt=he.magic_length,Ce=he.header_length,Ve=he.nonce_length,pn=he.tag_length,kr=he.segment_overhead,Kt=he.segment_size_bytes,rr=he.min_segment_size_bytes,ar=he.max_segment_size_bytes,ft=he.header_layout.find(e=>e.name==="file_id"),sr=he.aad_layout.reduce((e,t)=>e+t.length,0),xr=new Uint8Array(he.v3_reader.magic_bytes),Ir=he.v3_reader.header_length;function ks(e){return Ve+e+pn}function yn(e){let t=Math.max(1,Math.ceil(e/Kt));return Ce+t*kr+e}function xs(){let e=new Uint8Array(Ce);return e.set(hn,0),new DataView(e.buffer).setUint32(Nt,Kt,!0),e.set(crypto.getRandomValues(new Uint8Array(ft.length)),ft.offset),e}function Ut(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function Or(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(Nt,!0);if(t<rr||t>ar)throw new Error(`segment size ${t} is outside ${rr}\u2026${ar}`);return t}function Rr(e){if(e.length<Ce)throw new Error(`an AEON v4 header is ${Ce} bytes, got ${e.length}`);if(!Ut(e,hn))throw new Error("not an AEON v4 header");return{segmentSize:Or(e),fileId:e.slice(ft.offset,ft.offset+ft.length)}}function Is(e){if(e.length<Ir||!Ut(e,xr))throw new Error("not an AEON v3 header");return{segmentSize:Or(e)}}function Os(e){return Ut(e,hn)?"v4":Ut(e,xr)?"v3":null}function Lr(e,t,n){let r=new Uint8Array(sr);return r.set(e.subarray(0,Ce),0),new DataView(r.buffer).setBigUint64(Ce,BigInt(t),!0),r[sr-1]=n?1:0,r}function Rs(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function Pr(e){return crypto.subtle.importKey("raw",Rs(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Ls(e,t,n){let r=crypto.getRandomValues(new Uint8Array(Ve)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:pn*8,additionalData:n},e,t),s=new Uint8Array(Ve+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),Ve),s}async function Ps(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,Ve),tagLength:pn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(Ve)))}function Bs(){return Bt.create()}async function ht(){let e=globalThis.scheduler;return typeof e?.yield=="function"?e.yield():typeof MessageChannel<"u"?new Promise(t=>{let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(null)}):new Promise(t=>setTimeout(t,0))}function Ds(){return crypto.getRandomValues(new Uint8Array(32))}var ze={version:1,limits:{MAX_FILES_PER_SEAL:30,FREE_TIER_BYTES:1073741824,MAX_TOTAL_SIZE_BYTES:1073741824,MAX_FILE_SIZE_BYTES:10737418240,MAX_MULTIPART_FILE_SIZE_BYTES:10737418240,MAX_BLOB_SIZE:1048576,MAX_BLOB_BASE64_SIZE:1468006,MAX_MESSAGE_LENGTH:5e3,MAX_FILE_KEYS:1e4,MAX_ACTIVE_UPLOADS_PER_SEAL:10,MAX_OPENS_PER_SEAL_FREE:10,TIER_BYTES:{free:1073741824,"5gb":5368709120,"50gb":53687091200,"500gb":536870912e3},SEAL_TIERS:{"5gb":{bytes:5368709120,amount_cents:900,duration_days:90,name:"5 GB / 3 months",description:"One-time payment for 5 GB storage and 3 months TTL"},"50gb":{bytes:53687091200,amount_cents:2900,duration_days:180,name:"50 GB / 6 months",description:"One-time payment for 50 GB storage and 6 months TTL"},"500gb":{bytes:536870912e3,amount_cents:9900,duration_days:365,name:"500 GB / 12 months",description:"One-time payment for 500 GB storage and 12 months TTL"}},PRO_REGIONS:["eu-west","us-east","us-west","apac-southeast","apac-northeast"],ttl_options:["5m","30m","1h","1d","7d"],OTP_LENGTH:{min:6,max:10},USER_PASSWORD_MIN_LENGTH:8,INTAKE_TTL_DEFAULT_SECONDS:900,INTAKE_TTL_MAX_SECONDS:86400,INTAKE_WAIT_MAX_SECONDS:25,PAYMENT_WAIT_MAX_SECONDS:82800,ADDRESS_PROOF_TTL_SECONDS:300,INBOX_MAX_ITEMS:200,DRIVE_OPEN_TTL_SECONDS:300,DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES:67108864,DRIVE_PRESIGN_WINDOW_MIN_BYTES:8388608,DRIVE_PRESIGN_UNBOUND_TTL_SECONDS:30,DRIVE_WRITE_LEASE_SECONDS:7200,DRIVE_WRITE_BACK_SECONDS:5,VERSION_RETENTION_DAYS_DEFAULT:30,VERSION_KEEP_MIN:10,GRANT_WORKLOAD_MAX_TTL_DAYS:90,SENSOR_OPENS_PER_MINUTE_DEFAULT:120,SENSOR_BYTES_PER_MINUTE_DEFAULT:2147483648,SENSOR_SECRETS_PER_MINUTE_DEFAULT:20,SENSOR_NOVELTY_WINDOW_DAYS:30,SENSOR_HOLD_TTL_SECONDS:86400,SENSOR_BASELINE_MIN_HOURS:72,SENSOR_GROWTH_BYTES_PER_DAY_DEFAULT:107374182400}},Le={version:2,$comment:"Address of a bundle: who a seal is for, without a URL (SPEC-AEON-V4 \xA75). Numbers live in limits.json, error codes in error_codes.json, the bundle and the wrap in crypto.json (keybundle, sealed_box_v2).",address:{of:"SHA-256 of the identity key (Ed25519) of the bundle v2, 32 bytes",text:"base64url without padding, 43 characters",words:"fingerprint_words.json over the first three bytes of the address: the words of SHA-256(identity key), named without hashing again",inbox:"the 32 bytes of the address are the key the server finds an inbox by"},box_origin:"https://box.seal.net",seed:{env:"SEAL_SEED",text:"base64url without padding of the 32-byte seed of an agent, a device or an inbox, 43 characters",derives:"the agreement key (X25519) is the seed itself; the identity key (Ed25519) and the ML-KEM-768 key are HKDF of the seed (crypto.json hkdf.identity_key_salt, info_prefixes workload_identity and kem_mlkem768) \u2014 together the bundle v2 the address names",same_as:["sealnet-mcp state.identity.x25519_secret_b64","seal identity.v1.json x25519_secret_b64url","sealnet (npm) KeyPair.secretKey","sealnet (PyPI) keygen().secret_key"]},bundles:{put:"PUT /intake/bundles {bundle}: bundle is base64url of the packed bundle (crypto.json keybundle.packed_length). The server verifies it with the core and files it under the address it computes; no authorization \u2014 the bundle proves itself \u2014 and a limit per IP",get:"GET /intake/bundles/{address} -> {bundle}; 404 intake.bundle_not_found",accept:"a sender takes a bundle only if SHA-256 of its identity key is the address and its signature verifies; a client puts its own bundle at its first start and again whenever it is gone"},scopes:{share_link:"seal_share",owner_copy:"seal_owner"},proof:{header_address:"X-Seal-Address",header_proof:"X-Seal-Proof",challenge:"POST /intake/proof {address} -> {ts, challenge}: challenge = base64url(HMAC(server key, address(32) || ts u64 BE)), 43 characters; the server keeps no state",message:'"seal:inbox-proof:v2" || address(32) || ts u64 BE || challenge(32), signed with the identity key of the address; the core builds it (Identity::inbox_proof)',proof_text:"<ts>.<challenge>.<signature>: ts the decimal Unix second of the challenge, challenge as received, signature base64url of 64 bytes",check:"the window, the HMAC, and the signature against the bundle of the address with a small-order key refused"},items:{delivery:{id:"s.<seal_id>.<share_code>",is:"a share link addressed to this address: path /s/<seal_id>/<share_code> without a fragment; fragment = its key wrapped to the address's bundle (sealed box v2, scope share_link)"},owner:{id:"o.<seal_id>",is:"the seal's owner-blob key wrapped to the address's bundle (sealed box v2, scope owner_copy); path /s/<seal_id> opens the seal page, the only place that manages a seal"},request:{id:"r.<intake_id>",is:"a request asked of this address; path /i/<intake_id>, no fragment; carries what, kind and recipient_bundle"},listing:"GET /intake?to= lists deliveries only, as before owner copies and cards existed; `all=1` adds owner and request items (a person's inbox). Agent clients never send it: those rows are a person's."},request:{recipient_bundle:"POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it and shows the three words of its address, the answer's key is wrapped to it (scope share_link) and comes back as the request's fragment, with share_path without a fragment"},owner_copy:{web_label:"seal.net",is:"The seal names the inbox that manages it: its row carries the owner-blob key wrapped to that address's bundle, one per seal, written with the owner blob (PATCH /seal/{id}/blob with to, fragment, label) before the first byte of the files. Best effort: an address without a bundle is the same PATCH without the address part, and the seal is made anyway."},request_kinds:["secret","file","any","pair","device"],pair_what:"inbox",payloads:{name_max:80,pair:{mime:"application/vnd.seal.pairing+json",json:`{"v":2,"bundle":"<the inbox's packed bundle, base64url, 1755>","name":"<inbox name, at most name_max>"}`},device:{mime:"application/vnd.seal.device+json",json:'{"v":2,"seed":"<inbox seed, 43>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>"}]}'}},device_link:{code:"8 Crockford base32 characters from 5 random bytes",what:"base64url(HMAC-SHA256(key = the code in ASCII, message = the 32-byte address of the new device)), 43 characters: the what of the device request",link:"https://box.seal.net/#link=<address>.<code>"},bridge:{path:"/bridge",is:"A hidden iframe of box_origin on seal.net; postMessage only between the two origins. It never gives out the address or the name: it answers any script of seal.net.",hello:"box.hello {sealId?} -> {box: boolean, has: boolean}; box: this device has an inbox; has: this seal is already in Yours",owner_copy:"box.ownerCopy {sealId, ownerToken, linkKey} -> {ok: boolean}"},migrate:{until:"C1 + 7 days (C1 \xA76)",is:"Every inbox and agent changes its address once (\xA75.7). The X25519 key does not change \u2014 it is the seed \u2014 so the client moves the live rows of its old address once, under the proof of its new one: POST /intake/migrate {old_address} answers the old challenge, {old_address, old_proof} moves links, owner copies, cards and push subscriptions; the agreement key of the new address's bundle must equal the old address, and the senders of moved rows are cleared. Zero rows is a success.",old_address:"the X25519 public key of the seed, base64url without padding, 43 characters",challenge:"sealed box v1 of a 32-byte token to the old address with scope (address_proof, decimal ts): ephemeral_pub(32) || nonce(12) || ciphertext(48), base64url, 123 characters",old_proof:"<ts>.<token>: token base64url of the 32 bytes the challenge opens to",scope_address_proof:"seal_address_proof",vector:{comment:"every client that migrates must open it",secret:"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",address:"E75P6uryBMf9M1j8nAByGIHRdCeBKCJ-xnTzf3_pe20",ts:179e7,challenge:"4Oel-UMfgP_1dBhmf13yZiujhPDouCIQ6sSx1nY1qy-vyzFqDqb9jARbJ0e5A8vv4EDELDS5OPqBQMcsmDA-C_lXO95y_CVUyYtSu-1fltsy5ZihOFDp0T-C9Ro",token:"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"}},vectors:[{address:"Afdcc-OkgjU572_xdbUHZSNPO6r6Up6ctP2pfF0PHJw",bundle:"4rFhOdoKNSNI9qMxGju3FssbOjE0YN8CnitU4OD4dW4Eun0cCRx-W2Ad-PsAyD8R9LVv_v5mxs08kUEG5VurbwtRz7BXT4NoZoZytUXshnRVuBnjT3nghVcGmLLCpUi4qVzBsZOkO3e7tBbmAHsnDDF1eEPkjS0zQ6s6mkmFbHQnANoFXUnSM6ESOpPMmi11pv4QE9XYRpj2C_5JzmFXWLiYTA3pucRjUgPZkSmgp38RGRWZbcpsexeMmmJCdEolY52MoQaJesxJYRPgzlMSa9YnEICxfr8Xuwkgpxw3ucOxMolUXQKUBToGfUUxtC7BHrq2W3wEcF4LJaFytD44qdW2Ze0LSf8IlsESZWj6YbLabL25FAwmGntZKHQ7LDK7C4ZXsNVioS9yDNh1ADaqdTqGZnPlDaI2HiDCGVMzVTOQRvt6BZWKSUNrudd7t-2JxyUCWFk5szNrcUVJwsBrNdIXm_04iuvbcW-4s-kmXmX6CStgPdZSVgFgcAOQwsOwU57zjoA0pehUqiLwaHbLu0Z5poD1agnppIXItFLhVkRDExOHF7KxUD70CEJjUrHxxf0ln4H1S1t3udfFTA11SjBYXsTxq0VIMDoTnXzYenHLWXpYwDlogzagyb1UXfprRkNgbssmd9xyw_aKz2AWjAdqpeAmIwVbnlfcxA-0MixZpVtkpSyZeXhwAPf8Q0raFNESLbJSBx1GStgiNzNkf553RC0JCLXITOw6YHuyQKF8y05gFwXTjJ0hBwUgTEQVJt71miJ8N7asYFDrAVSWm7t0qA55RobkTdnBliKCCjrnKxGET5M0sPrlyC3yTUu3fHrpEDRqiN8yFZRpD9QBXtaorIM8b6XcVAWJFKjauhn5tC4RAJDEi384o_NQAg0WowA3UuJ0LFg5ELRGQuZCrP_RVIHGAR5lcOeSY9SzW-dmp-MbsfSWf_iBEkYsc_iFTwkTf3M5Thd4TSJxwJ9odRS0LqRZgrgEWcYYl5PalYYrBHqhsMiAshpzibQLTPbQh1CUMTLMIrorvqVbhdZovQmSdShIWLTmkhWJGN_seAfnQNFhufXlg2dsNSGZCdcivn_VfKUHFpm8DOHRCqWcdwcrw7K3gtPgTC2GQvSJxAH6pq5hshTKCqF6mtFiA2-FbjYwDhRskt8Mf15IkQWDCI2LNDnJLg6qPMbaMxUEyWd7N1QWmHNgtU9syAMLhVHsHlohPq8ZdygIRIw6IjbFR0EDb8jYhY1DQUc3WWLQX_AsdMwHNgeRzhlcd2fohE5BzB_Lb3V1NpmsMPe2FhmGD8b3Pb-1ZR-MtJD6tgq1YSs7JOeWjKETlN2YqCaIFCeRWUIygkpbF158x4lVqqgQQZ70kzXsJTWJZbY5mvXHbAUsWLezERn4hWWKau_Mno78GTRKZfO5ymbWl4Hku8ECskl3dL8oy5hAOGhGcGOyhDLXISTTZL3JQ2Qwy0X7AfqDIQCTnuCLa3_AhIsjMXFzB-rCq8WjUsh4YsW1ENBJjV_2G6-HWRVDpo6nIDVnZRGxATTCvnLjXcn0USEXsBI6R6aAcgqGXzabd_QyLpK2EdUnaH3xIWjGYsdRjIuUWQM3odyjH7TFOurwlQV3hU2KMmAO13XqmD5fvhxVi5-kWTnN16EDDV0EXLky4Jug0SNgHchy3ymbXVBx8TfsJcCumYk9iuui2D-cDpa7KJEGwBVN-9lvLEidQddWX_CMfbmG_wdHaC4Hapi-U2OhsH-2AwEAAAA",challenge:"wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8",comment:"generated once by shared/core (Identity::from_seed32, Identity::inbox_proof); every client must reproduce it",legacy_address:"BLp9HAkcfltgHfj7AMg_EfS1b_7-ZsbNPJFBBuVbq28",proof:"1790000000.wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8.74s5T1rE2xRNbameeTbYUHVMN-ZzFu1JBPZJNtH8eYC1vV7-h2HE_hxgo4vUB0_sHFfdYRUf0bve4_KGe32ICg",seed:"Aw4ZJC86RVBbZnF8h5KdqLO-ydTf6vUACxYhLDdCTVg",signature:"74s5T1rE2xRNbameeTbYUHVMN-ZzFu1JBPZJNtH8eYC1vV7-h2HE_hxgo4vUB0_sHFfdYRUf0bve4_KGe32ICg",ts:179e7,words:"album wren hedge"}]},Cs="X-Seal-Client",L={version:1,upload:{DEFAULT_PART_SIZE_BYTES:16777216,S3_MIN_PART_SIZE_BYTES:5242880,MAX_PART_SIZE_BYTES:268435456,MULTIPART_THRESHOLD_BYTES:8388608,FINE_PART_SIZE_BYTES:8388608,FINE_PART_MAX_FILE_BYTES:536870912,INMEMORY_BLOB_LIMIT_BYTES:104857600,MULTIPART_UPLOAD_TTL_SECONDS:86400,PRESIGN_BATCH_SIZE:100,SMALL_FILE_POOL:4,PART_POOL_MIN:2,PART_POOL_START:2,PART_POOL_MAX:5,PART_POOL_GROW_RATIO:1.15,PART_POOL_SHRINK_RATIO:.7,PART_QUEUE_LIMIT:2,HEDGE_MIN_INFLIGHT_MS:3e3,HEDGE_LAG_FACTOR:3,HEDGE_POLL_MS:1e3,LIVENESS_SILENCE_MS:3e4,RETRY_BACKOFF_MS:[1e3,3e3,7e3,15e3,3e4],RETRY_JITTER_RATIO:.2,STALL_NOTICE_MS:3e4,MAX_STALL_MS:6e5,PUT_FLOOR_BYTES_PER_SECOND:20480,PUT_MIN_DEADLINE_MS:3e4,CONTROL_TIMEOUT_MS:3e4,COMPLETE_TIMEOUT_MS:12e4,VERIFY_POLL_BACKOFF_MS:[0,2e3,3e3,5e3,8e3],VERIFY_FALLBACK_WAIT_MS:6e4,NOT_READY_MAX_RETRIES:3,PROGRESS_SPEED_WINDOW_MS:2e4}},ln;function Br(e,t){ln=`${e}/${t}`}function Dr(){return ln===void 0?{}:{[Cs]:ln}}var ce=class extends Error{constructor(e,t,n,r={}){super(e),this.name="BackendError",this.code=t,this.status=n,this.body=r.body,this.detail=r.detail,this.appCode=r.appCode,this.retryAfter=r.retryAfter,this.update=r.update,this.minVersion=r.minVersion}};function Ms(e){return e===404?"not_found":e===410?"revoked":e===429?"rate_limited":e===401||e===403?"auth":e>=500&&e<600?"transient":"unknown"}async function Cr(e,t){let n=await e.text().catch(()=>""),r,a,s,o,i;if(n)try{let l=JSON.parse(n);typeof l?.detail=="string"&&(r=l.detail),typeof l?.code=="string"&&(a=l.code),typeof l?.retry_after=="number"&&(s=l.retry_after),typeof l?.update=="string"&&(o=l.update),typeof l?.min_version=="string"&&(i=l.min_version)}catch{}return new ce(r??t,Ms(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function Ns(e){return{id:e.id,expiresAt:e.expires_at,revokedAt:e.revoked_at,ndaRequired:e.nda_required,otpRequired:e.otp_required,singleUse:e.single_use,maxOpens:e.max_opens??null,files:(e.files??[]).map(t=>({id:t.id,size:t.size,sha256_hex:t.sha256_hex,name_encrypted:t.name_encrypted,name_nonce:t.name_nonce,mime_encrypted:t.mime_encrypted,mime_nonce:t.mime_nonce}))}}function q(e){return encodeURIComponent(e)}var yt=class ye{constructor(t){if(this.baseUrl=t.baseUrl.replace(/\/+$/,""),typeof(t.fetch??globalThis.fetch)!="function")throw new Error("SealApi: no global fetch in this runtime \u2014 pass options.fetch or use Node >= 18");this.injectedFetch=t.fetch,this.credentials=t.credentials}fetchImpl(t,n){return(this.injectedFetch??globalThis.fetch).call(globalThis,t,n)}url(t){if(!t.startsWith("/"))throw new Error(`SealApi: path must start with '/', got: ${t}`);return`${this.baseUrl}${t}`}async request(t,n){let{what:r,...a}=n,s=await this.fetchImpl(this.url(t),{...a,headers:{...Dr(),...a.headers},credentials:a.credentials??this.credentials});if(!s.ok)throw await Cr(s,`${r} failed: ${s.status}`);return s}static ownerHeaders(t,n=!1){let r={"X-Owner-Token":t};return n&&(r["Content-Type"]="application/json"),r}async getMetadata(t,n={}){return await(await this.request(`/seal/${q(t)}`,{what:`GET /seal/${t}`,signal:n.signal})).json()}async getShareBlob(t,n,r={}){let a=`GET /seal/${t}/share/${n}`,s=await this.request(`/seal/${q(t)}/share/${q(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:lr(o,a,s.status),wrap:typeof o.fragment=="string"&&o.fragment?o.fragment:null}}async verifyOtp(t,n,r={}){let a={code:n.code};n.fileId&&(a.file_id=n.fileId),n.shareCode&&(a.share_code=n.shareCode);let s=await this.request(`/seal/${q(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=$s(s,`otp_${t}`),i=await s.json().catch(()=>({}));return{status:typeof i.status=="string"?i.status:"ok",sessionCookie:o}}async acceptNda(t,n,r={}){let a={signature:n.signature,timestamp:n.timestamp,first_name:n.firstName,last_name:n.lastName};n.company&&(a.company=n.company),n.fileId&&(a.file_id=n.fileId),n.shareCode&&(a.share_code=n.shareCode),n.ndaText&&(a.nda_text=n.ndaText);let o=await(await this.request(`/seal/${q(t)}/nda`,{what:`POST /seal/${t}/nda`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal})).json().catch(()=>({}));return{status:typeof o.status=="string"?o.status:"ok"}}downloadUrl(t,n){return this.url(`/seal/${q(t)}/download?${or(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?ye.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie);for(let s=0;;s++)try{return await this.request(`/seal/${q(t)}/download?${or(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal})}catch(o){if(!(o instanceof ce&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<L.upload.NOT_READY_MAX_RETRIES))throw o;await Fs((o.retryAfter??Us)*1e3,r.signal)}}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${q(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:ye.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${q(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:lr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=ye.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return ir(a,o,s),{etag:(await this.request(`/seal/${q(t)}/blob`,{what:`PATCH /seal/${t}/blob`,method:"PATCH",headers:s,body:JSON.stringify(o),signal:a.signal})).headers.get("ETag")}}async createShareLink(t,n,r,a={}){let s=n===null?{"Content-Type":"application/json"}:ye.ownerHeaders(n,!0),o={encrypted_blob:r};a.fileIds&&(o.file_ids=a.fileIds),ir(a,o,s);let i=await this.request(`/seal/${q(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:s,body:JSON.stringify(o),signal:a.signal}),l=await i.json();if(typeof l.share_code!="string"||!l.share_code)throw new ce(`POST /seal/${t}/share returned no share_code`,"unknown",i.status);return l.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${q(t)}/share/${q(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:ye.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${q(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:ye.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof ce&&(o.status===404||o.status===410))return{status:"revoked",revokedAt:null};throw o}let s=await a.json().catch(()=>({}));return{status:typeof s.status=="string"?s.status:"revoked",revokedAt:typeof s.revoked_at=="string"?s.revoked_at:null}}async revokeFile(t,n,r,a={}){await this.request(`/seal/${q(t)}/files/${q(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:ye.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${q(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:ye.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${q(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:ye.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${q(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:ye.ownerHeaders(n,!0),body:JSON.stringify(r.reference?{reference:r.reference}:{}),signal:a.signal}),o=await s.json();if(typeof o.id!="string"||typeof o.secret!="string")throw new ce(`POST /seal/${t}/subscriptions returned no subscription`,"unknown",s.status);return{id:o.id,secret:o.secret}}async createCheckout(t,n,r,a={}){let s=await this.request("/billing/checkout",{what:"POST /billing/checkout",method:"POST",headers:ye.ownerHeaders(n,!0),body:JSON.stringify({seal_id:t,tier:r}),signal:a.signal}),o=await s.json();if(typeof o.url!="string"||!o.url)throw new ce("POST /billing/checkout returned no url","unknown",s.status);return o.url}async createIntake(t,n={}){let r={recipient_bundle:t.recipientBundle,label:t.label,what:t.what,kind:t.kind??"any"};return t.whereUrl&&(r.where_url=t.whereUrl),t.ttlSeconds!==void 0&&(r.ttl_seconds=t.ttlSeconds),t.to&&(r.to=t.to),await(await this.request("/intake",{what:"POST /intake",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n.signal})).json()}async getIntake(t,n={}){let r=n.waitSeconds?`?wait=${n.waitSeconds}`:"";return await(await this.request(`/intake/${q(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${q(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seal_id:n.sealId,share_code:n.shareCode,fragment:n.fragment}),signal:r.signal})).json()}async putBundle(t,n={}){await this.request("/intake/bundles",{what:"PUT /intake/bundles",method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundle:ne(t)}),signal:n.signal})}async getBundle(t,n={}){try{let r=await this.request(`/intake/bundles/${q(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return V((await r.json()).bundle)}catch(r){if(r instanceof ce&&r.status===404)return null;throw r}}async requestAddressProof(t,n={}){return await(await this.request("/intake/proof",{what:"POST /intake/proof",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:t}),signal:n.signal})).json()}async listInbox(t,n={}){let r=new URLSearchParams({to:t.address});return n.waitSeconds&&r.set("wait",String(Math.min(n.waitSeconds,ze.limits.INTAKE_WAIT_MAX_SECONDS))),n.seen&&r.set("seen",n.seen),n.all&&r.set("all","1"),await(await this.request(`/intake?${r.toString()}`,{what:"GET /intake",headers:ut(t),signal:n.signal})).json()}async dismissInboxItem(t,n,r={}){let a=new URLSearchParams({to:n.address,item:t});await this.request(`/intake?${a.toString()}`,{what:"DELETE /intake",method:"DELETE",headers:ut(n),signal:r.signal})}async migrateInbox(t,n,r={}){return await(await this.request("/intake/migrate",{what:"POST /intake/migrate",method:"POST",headers:{"Content-Type":"application/json",...ut(t)},body:JSON.stringify(n),signal:r.signal})).json()}async pushKey(t={}){return(await(await this.request("/intake/push-key",{what:"GET /intake/push-key",signal:t.signal})).json()).vapid_public}async setInboxPush(t,n,r,a={}){let s=n?"POST":"DELETE";await this.request("/intake/subscriptions",{what:`${s} /intake/subscriptions`,method:s,headers:{"Content-Type":"application/json",...ut(r)},body:JSON.stringify({to:r.address,endpoint:t}),signal:a.signal})}},Us=3;function ut(e){return{[Le.proof.header_address]:e.address,[Le.proof.header_proof]:e.proof}}function or(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function ir(e,t,n){"to"in e&&(t.to=e.to,t.fragment=e.fragment,e.label&&(t.label=e.label),e.sender&&Object.assign(n,ut(e.sender)))}function Fs(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let a=()=>{clearTimeout(s),r(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}function lr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new ce(`${t} returned an empty blob`,"unknown",n);return V(e.encrypted_blob)}function $s(e,t){let n=e.headers,r=typeof n.getSetCookie=="function"?n.getSetCookie():[],a=r.length>0?r:(()=>{let s=e.headers.get("set-cookie");return s?[s]:[]})();for(let s of a){let o=s.split(";",1)[0]?.trim()??"";if(o.startsWith(`${t}=`))return o}return null}var Ws=32,Hs=32,Ft=ze.limits.MAX_BLOB_SIZE,zs=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function Mr(){return crypto.getRandomValues(new Uint8Array(Ws))}async function Nr(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function _n(){return crypto.getRandomValues(new Uint8Array(Hs))}async function Ur(e,t,n,r,a){let s={owner_token:e,file_keys:Object.fromEntries(t),...r?{message:r}:{},...a?{nda_file:a}:{}};return $r(s,n)}async function Fr(e,t,n,r){let a={file_keys:Object.fromEntries(e),...n?{message:n}:{},...r?{nda_file:r}:{}};return $r(a,t)}async function $r(e,t){let n=JSON.stringify(e);if(n.length>Ft)throw new Error(`Blob data size ${n.length} exceeds maximum of ${Ft}`);let r=new TextEncoder().encode(n),a=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},s,r),i=new Uint8Array(12+o.byteLength);return i.set(a,0),i.set(new Uint8Array(o),12),i}function Ks(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.file_keys!="object"||t.file_keys===null)return!1;for(let[n,r]of Object.entries(t.file_keys))if(typeof n!="string"||typeof r!="string")return!1;return!(t.message!==void 0&&typeof t.message!="string")}async function Gs(e,t){let n=await js(e,t);if(!Ks(n))throw new Error("Invalid share blob structure");return n}async function js(e,t){if(e.length>Ft)throw new Error(`Blob size ${e.length} exceeds maximum of ${Ft}`);if(e.length<28)throw new Error("Encrypted blob too short");let n=e.slice(0,12),r=e.slice(12),a=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),s;try{s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},a,r)}catch{throw new zs}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}function Ys(){try{return typeof process<"u"&&!0}catch{return!1}}var Vs=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":Ys()||console.debug(a,...r);break;case"info":console.info(a,...r);break;case"warn":console.warn(a,...r);break;case"error":console.error(a,...r);break}},Dt=Vs;function _t(e){return{debug:(t,...n)=>Dt("debug",e,t,...n),info:(t,...n)=>Dt("info",e,t,...n),warn:(t,...n)=>Dt("warn",e,t,...n),error:(t,...n)=>Dt("error",e,t,...n)}}var Yi=ze.limits.MAX_FILE_KEYS;var De=64,cr=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],qs=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),Xs=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function dr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let l,d;i<16?(l=a&s|~a&o,d=i):i<32?(l=o&a|~o&s,d=5*i+1&15):i<48?(l=a^s^o,d=3*i+5&15):(l=s^(a|~o),d=7*i&15);let p=r+l+qs[i]+t[n+d]|0;r=o,o=s,s=a,a=a+(p<<cr[i]|p>>>32-cr[i])|0}e[0]=e[0]+r|0,e[1]=e[1]+a|0,e[2]=e[2]+s|0,e[3]=e[3]+o|0}var wn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array(De),this.pendingLength=0,this.totalBytes=0,this.scratch=new Int32Array(16)}update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let r=Math.min(De-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<De)return this;this.compressBytes(this.pending,0,De),this.pendingLength=0}let n=e.length-(e.length-t)%De;return this.compressBytes(e,t,n),n<e.length&&(this.pending.set(e.subarray(n)),this.pendingLength=e.length-n),this}digest(){let e=new Uint8Array(this.pendingLength<56?De:2*De);e.set(this.pending.subarray(0,this.pendingLength)),e[this.pendingLength]=128;let t=new DataView(e.buffer);t.setUint32(e.length-8,this.totalBytes*8>>>0,!0),t.setUint32(e.length-4,Math.floor(this.totalBytes/2**29),!0),this.compressBytes(e,0,e.length);let n=new Uint8Array(16),r=new DataView(n.buffer);for(let a=0;a<4;a++)r.setInt32(a*4,this.state[a],!0);return n}compressBytes(e,t,n){if(t>=n)return;if(Xs&&(e.byteOffset+t)%4===0){let a=new Int32Array(e.buffer,e.byteOffset+t,(n-t)/4);for(let s=0;s<a.length;s+=16)dr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=De){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);dr(this.state,this.scratch,0)}}};function Zs(e){return Ie(new wn().update(e).digest())}var an=4*1024*1024;async function Js(e){let t=new wn;for(let n=0;n<e.length;n+=an)t.update(e.subarray(n,Math.min(n+an,e.length))),n+an<e.length&&await ht();return Ie(t.digest())}var Wr=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Rr(e.header).segmentSize,this.header=e.header.subarray(0,Ce),this.key=e.key}async init(){this.cryptoKey=await Pr(this.key)}sha256Hex(){return Ye(this.header)}async encryptSegment(e,t,n){if(!this.cryptoKey)throw new Error("Encryptor.init() was not awaited");if(!(t?n.length<=this.segmentSize&&(n.length>0||e===0):n.length===this.segmentSize))throw new Error(`segment ${e}${t?" (last)":""} cannot carry ${n.length} bytes at segment size ${this.segmentSize}`);return Ls(this.cryptoKey,n,Lr(this.header,e,t))}};async function Qs(e,t,n,r){let a=new Uint8Array(t);try{let s=new Wr({key:a,header:n});await s.init();let o=new wn().update(s.header),i=[ur(s.header)],l=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let d=0;d<l;d++){let p=Math.min((d+1)*s.segmentSize,e.size),f=new Uint8Array(await e.slice(d*s.segmentSize,p).arrayBuffer()),u=await s.encryptSegment(d,d===l-1,f);f.fill(0),o.update(u),i.push(ur(u)),r?.(p,e.size)}return{blob:new Blob(i),md5_b64:Ie(o.digest())}}finally{a.fill(0)}}function ur(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Re=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function eo(e,t){e.chunks.push(t),e.bytes+=t.length}function Ct(e,t){let n=new Uint8Array(t),r=0;for(;r<t;){let a=e.chunks[0],s=t-r;a.length<=s?(n.set(a,r),r+=a.length,e.chunks.shift()):(n.set(a.subarray(0,s),r),r+=s,e.chunks[0]=a.subarray(s))}return e.bytes-=t,n}function to(e,t){let n=Ct(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function no(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Re("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,l=0,d=null,p=async(u,_)=>{if(u.length<kr)throw new Re("integrity",`segment ${l} is ${u.length} bytes: the stream was cut`);try{return await Ps(a,u,o==="v4"?Lr(s,l,_):null)}catch(h){throw new Re("integrity",`segment ${l} does not decrypt as the ${_?"last":"next"} segment of this file: moved, cut, extended or changed`,h)}finally{l+=1}},f=async()=>{if(r.bytes<Nt)return!1;let u=Os(to(r,Nt));if(u===null)throw new Re("outdated","the file is in a format newer than this client: update it");let _=u==="v4"?Ce:Ir;if(r.bytes<_)return!1;if(u==="v3"){d=Bs();for(let g of r.chunks)d.update(g)}let h=Ct(r,_),m;try{m=u==="v4"?Rr(h).segmentSize:Is(h).segmentSize}catch(g){throw new Re("integrity",g instanceof Error?g.message:String(g),g)}if(u==="v4"&&await Ye(h)!==n)throw new Re("integrity","the file header is not the one registered for this file");return s=h,o=u,i=ks(m),!0};return new TransformStream({async start(){a=await Pr(e)},async transform(u,_){if(u.length!==0&&(eo(r,u),d&&d.update(u),!(o===null&&!await f())))for(;r.bytes>i;){let h=Ct(r,i),m=await p(h,!1);h.fill(0),t.onPlaintextBytes?.(m.length),_.enqueue(m)}},async flush(u){if(o===null)throw new Re("integrity",r.bytes===0?"the ciphertext stream is empty":"the ciphertext stream was cut inside its header");if(o==="v3"){if(Array.from(d.digest(),m=>m.toString(16).padStart(2,"0")).join("")!==n)throw new Re("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let _=await p(Ct(r,r.bytes),!0);t.onPlaintextBytes?.(_.length),u.enqueue(_)}},{highWaterMark:1},{highWaterMark:1})}var Xi=_t("SwDownload");var Zi=L.upload.MULTIPART_THRESHOLD_BYTES,Ji=L.upload.MULTIPART_THRESHOLD_BYTES;var Qi=_t("FolderZip");var el=100*1024*1024,tl=4*1024*1024;var ro=_t("upload"),dt=4*1024*1024;function $t(){return new DOMException("Upload aborted","AbortError")}async function ao(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:l}=e,d=Kt,p=Math.max(1,Math.ceil(n/d)),f=new Wr({key:r,header:a});await f.init();let u=!0,_=0,h=0,m=[],g=0,N=A=>{if(m.length>0&&m[0].length===A)return g-=A,m.shift();let E=new Uint8Array(A),C=0;for(;C<A;){let ie=m[0],G=A-C;ie.length<=G?(E.set(ie,C),C+=ie.length,m.shift()):(E.set(ie.subarray(0,G),C),m[0]=ie.subarray(G),C+=G)}return g-=A,E},D=[],k=0,P=async A=>{let E=new Uint8Array(A),C=0,ie=0;for(;C<A;){let G=D[0],Z=i?dt-ie:Number.MAX_SAFE_INTEGER,Q=Math.min(G.length,A-C,Z);E.set(G.subarray(0,Q),C),C+=Q,ie+=Q,Q===G.length?D.shift():D[0]=G.subarray(Q),i&&ie>=dt&&C<A&&(ie=0,await ht())}return k-=A,E},U=async A=>{if(h+=1,e.hashParts===!1)await e.onPart(h,A);else{let E=i?await Js(A):Zs(A);await e.onPart(h,A,E)}i&&await ht()},I=async A=>{if(!i){A.fill(0);return}for(let E=0;E<A.length;E+=dt)A.fill(0,E,Math.min(E+dt,A.length)),E+dt<A.length&&await ht()},b=async()=>{for(;k>=s;)await U(await P(s))},F=async(A,E)=>{if(o?.aborted)throw $t();let C=_;_+=1;let ie=performance.now(),G=f.encryptSegment(C,E,A);await b();let Z=await G;await I(A),ro.debug(`encrypt segment=${_} bytes=${A.length} time=${Math.round(performance.now()-ie)}ms`);let Q;u?(Q=new Uint8Array(a.length+Z.length),Q.set(a,0),Q.set(Z,a.length),u=!1):Q=Z,l?.(_),D.push(Q),k+=Q.length},B=t.getReader();try{for(;;){if(o?.aborted)throw $t();let{done:A,value:E}=await B.read();if(A)break;for(E&&E.length>0&&(m.push(E),g+=E.length);g>=d;)await F(N(d),_===p-1)}(g>0||_===0)&&await F(N(g),!0),await b(),k>0&&await U(await P(k))}finally{B.releaseLock()}}function so(e,t){let n=0;return new ReadableStream({async pull(r){if(n>=e.size){r.close();return}let a=Math.min(n+t,e.size);try{let s=await e.slice(n,a).arrayBuffer();r.enqueue(new Uint8Array(s)),n=a}catch(s){r.error(s)}}})}function oo(e,t,n){let{file:r,key:a,header:s,partSize:o,totalBytes:i,signal:l,initialCredits:d,onSegment:p,onPart:f}=n;return new Promise((u,_)=>{let h=!1,m=!1,g=0,N=Promise.resolve(),D=I=>{h||(h=!0,_(I))},k=()=>{!m||g>0||N.then(()=>{h||(h=!0,u())})};if(l){if(l.aborted){D($t());return}l.addEventListener("abort",()=>D($t()),{once:!0})}e.onerror=t.onerror=I=>{D(new Error(`crypto worker crashed: ${String(I?.message??I)}`))},e.onmessage=I=>{let b=I.data;if(b.type==="segment"){p?.(b.segmentNumber);return}if(b.type==="part"){g+=1,t.postMessage({type:"md5",partNumber:b.partNumber,buffer:b.buffer},[b.buffer]);return}if(b.type==="done"){m=!0,k();return}b.type==="error"&&D(new Error(b.message))},t.onmessage=I=>{let b=I.data;if(b.type!=="md5")return;g-=1;let F=new Uint8Array(b.buffer);N=N.then(async()=>{h||(await f(b.partNumber,F,b.md5),e.postMessage({type:"credit"}))}).catch(D),k()};let P=new ArrayBuffer(a.length);new Uint8Array(P).set(a);let U=s.slice().buffer;e.postMessage({type:"start",file:r,key:P,header:U,partSize:o,totalBytes:i,credits:d},[P,U])})}var io=null;function lo(){return io}var O=class extends Error{constructor(e,t,n,r,a=!1){super(e),this.code=t,this.httpStatus=n,this.partNumber=r,this.retryable=a,this.name="UploadError"}};function We(e,t){return e instanceof O?e:e instanceof DOMException&&e.name==="AbortError"?new O("Upload aborted","ABORTED"):new O(e instanceof Error?e.message:t,"UNKNOWN")}async function qe(e,t,n,r){let a=await Cr(e,String(e.status));return new O(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var co=_t("upload"),uo={retryBackoffMs:L.upload.RETRY_BACKOFF_MS,retryJitterRatio:L.upload.RETRY_JITTER_RATIO,stallNoticeMs:L.upload.STALL_NOTICE_MS,maxStallMs:L.upload.MAX_STALL_MS,putFloorBytesPerSecond:L.upload.PUT_FLOOR_BYTES_PER_SECOND,putMinDeadlineMs:L.upload.PUT_MIN_DEADLINE_MS,controlTimeoutMs:L.upload.CONTROL_TIMEOUT_MS,completeTimeoutMs:L.upload.COMPLETE_TIMEOUT_MS,poolStart:L.upload.PART_POOL_START,poolMax:L.upload.PART_POOL_MAX,poolMin:L.upload.PART_POOL_MIN,poolGrowRatio:L.upload.PART_POOL_GROW_RATIO,poolShrinkRatio:L.upload.PART_POOL_SHRINK_RATIO,partQueueLimit:L.upload.PART_QUEUE_LIMIT,hedgeMinInflightMs:L.upload.HEDGE_MIN_INFLIGHT_MS,hedgeLagFactor:L.upload.HEDGE_LAG_FACTOR,hedgePollMs:L.upload.HEDGE_POLL_MS,livenessSilenceMs:L.upload.LIVENESS_SILENCE_MS,verifyPollBackoffMs:L.upload.VERIFY_POLL_BACKOFF_MS,verifyFallbackWaitMs:L.upload.VERIFY_FALLBACK_WAIT_MS,speedWindowMs:L.upload.PROGRESS_SPEED_WINDOW_MS};function Hr(e){return{...uo,...e}}function cn(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}function zr(e,t){let n=globalThis.AbortSignal;if(typeof n?.timeout!="function")return e;let r=n.timeout(t);return e?typeof n.any!="function"?e:n.any([e,r]):r}async function pt(e,t,n,r){try{return await fetch(e,{...t,signal:zr(r,n)})}catch(a){throw r?.aborted?new O("Upload aborted","ABORTED"):new O(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function Kr(e){return e===408||e===429||e>=500?"retryable":"terminal"}function Gr(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":Kr(e.httpStatus)}function jr(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":Kr(e.httpStatus)}var Yr=class{constructor(e,t,n=()=>performance.now()){this.policy=e,this.onState=t,this.now=n,this.failingSince=null,this.current="running",this.noticeTimer=null,this.retriesSinceDelivery=0}get state(){return this.current}connectionLost(){this.setState("stalled")}delivered(){this.failingSince=null,this.retriesSinceDelivery=0,this.clearNotice(),this.setState("running")}exhausted(){return this.failingSince!==null&&this.now()-this.failingSince>=this.policy.maxStallMs}failed(){this.retriesSinceDelivery+=1,this.failingSince??(this.failingSince=this.now());let e=this.policy.stallNoticeMs-(this.now()-this.failingSince);e<=0?this.setState("stalled"):this.noticeTimer===null&&this.current==="running"&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=null,this.setState("stalled")},e))}dispose(){this.clearNotice()}clearNotice(){this.noticeTimer!==null&&(clearTimeout(this.noticeTimer),this.noticeTimer=null)}setState(e){e!==this.current&&(this.current=e,this.onState?.(e))}};function gn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new O("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new O("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function Wt(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,l=0;for(let d=0;;d++){if(a?.aborted)throw new O("Upload aborted","ABORTED");try{return await e({attempt:d,after:i})}catch(p){let f=We(p,`${o} failed`);if(f.code==="ABORTED")throw f;let u=s(f);if(u==="terminal")throw f;if(n.exhausted())throw new O(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${f.message}`,f.code,f.httpStatus,f.partNumber,!1);n.failed(),l=u==="refresh_url"?l+1:0;let _=u==="refresh_url"&&l===1,h=r.retryBackoffMs[Math.min(d,r.retryBackoffMs.length-1)]??0,m=1+(Math.random()*2-1)*r.retryJitterRatio,g=_?0:Math.round(h*m);co.debug(`retry ${o} attempt=${d+2} in ${g}ms after ${f.code}${f.httpStatus?" "+f.httpStatus:""} (${u})`),i=u,await gn(g,a)}}}var $e=_t("upload"),fr="<Code>BadDigest</Code>",fo=2;function bn(e){let t=Dr();return e?e.type==="bearer"?{...t,Authorization:`Bearer ${e.value}`}:e.type==="ownerToken"?{...t,"X-Owner-Token":e.value}:{...t,"X-API-Key":e.value}:t}async function ho(e){return po({file:e.file,sealId:e.sealId,fileId:e.fileId,key:e.key,header:e.header,baseUrl:e.baseUrl,auth:e.auth,partSize:e.partSize,onProgress:e.onProgress,signal:e.signal,transport:e.transport,onStreamed:e.onStreamed,onConflict:e.onConflict})}async function po(e){let{file:t,partSize:n}=e;return yo({stream:so(t,Kt),totalBytes:t.size,sealId:e.sealId,fileId:e.fileId,key:e.key,header:e.header,baseUrl:e.baseUrl,auth:e.auth,partSize:n,onProgress:e.onProgress,signal:e.signal,sourceFile:t,transport:e.transport,onStreamed:e.onStreamed,onConflict:e.onConflict})}async function yo(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:l,partSize:d,contentType:p="application/octet-stream",onProgress:f,signal:u,sourceFile:_,onStreamed:h,onConflict:m}=e,g=Hr(e.transport);if(s.length!==32)throw new O("Key must be 32 bytes","ENCRYPTION_FAILED");if(d<L.upload.S3_MIN_PART_SIZE_BYTES)throw new O(`Part size must be at least ${L.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let N=new Uint8Array(s),D=bn(l),k=yn(n),P=Math.ceil(k/d),U=null,I=[],b=0,F=0,B="encrypting",A=[],E=null,C,ie=y=>{let w=performance.now();A.push({at:w,bytes:y});let v=Math.max(E??w,w-g.speedWindowMs);for(;A.length>0&&A[0].at<v;)A.shift();let R=w-v;R>0&&(C=Math.round(A.reduce((x,z)=>x+z.bytes,0)/R*1e3))},G=y=>{B=y;let w=k-b;f?.({phase:y,percent:y==="done"?100:Math.min(99,Math.floor(b/k*100)),deliveredBytes:b,preparedBytes:F,totalBytes:k,speedBps:C,etaMs:C&&C>0?Math.round(w/C*1e3):void 0,state:Z.state,attempt:Z.retriesSinceDelivery+1})},Z=new Yr(g,()=>G(B)),Q=new AbortController,Xe=globalThis.AbortSignal?.any,Te=u&&typeof Xe=="function"?Xe([u,Q.signal]):u??Q.signal,Ze=(y,w)=>Wt(w,{clock:Z,policy:g,signal:Te,classify:jr,what:y}),Je=async y=>{throw N.fill(0),new O("Upload aborted","ABORTED")},re=y=>{if(U)try{fetch(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...D},body:JSON.stringify(y?{upload_id:U,discard_file:!0}:{upload_id:U}),keepalive:!0}).catch(()=>{})}catch{}},ee=new Map,Ae=null,ue=null,fe=[],_e=new Set,we=g.poolStart,gt=g.poolMax,bt=0,Me=null,mt=0,Et=0,Qe=null,qt=[],Un=[],et=new Set,tt=performance.now(),Fn=!1,Xt=y=>{tt=performance.now();for(let w of[...et])w.reconnect(y)};function Ia(y,w){let v=y.ciphertext.length;if(v>=d&&w>0){let z=Math.min(y.flowsAtStart??1,_e.size);if(Un.push({rate:v/w,flows:z}),v/w*1e3<g.putFloorBytesPerSecond*2&&we>g.poolMin){we-=1,gt=we,Qe=null,bt+=1,Me=performance.now(),mt=0,Et=0;return}}if(y.round!==bt||(mt+=v,Et+=1,Et<we||Me===null))return;let R=performance.now()-Me;if(R<=0)return;let x=mt/R;Qe===null||x>Qe*g.poolGrowRatio?we=Math.min(gt,we+1):x<Qe*g.poolShrinkRatio&&(we=Math.max(Math.min(g.poolStart,gt),we-1)),Qe=x,bt+=1,Me=performance.now(),mt=0,Et=0}function Oa(y,w){let v=performance.now()-w;if(v<g.hedgeMinInflightMs)return!1;let R=_e.size,x=Un.filter(M=>M.flows>=R).map(M=>M.rate);if(x.length===0)return!1;x.sort((M,j)=>M-j);let z=x[Math.floor(x.length/2)];return y.ciphertext.length/v*g.hedgeLagFactor<z}async function Ra(y,w,v,R,x,z){if(typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((j,ge)=>{let ae=new XMLHttpRequest,le=!1;Fn=!0,ae.upload.onprogress=pe=>{z.onSocketActivity(pe.loaded,pe.lengthComputable?pe.total:y.length),clearTimeout(Y),Y=Ke()};let Ke=()=>setTimeout(()=>{le||z.onDeadline()},cn(y.length,g)),Y=Ke(),$=()=>{clearTimeout(Y),x.removeEventListener("abort",se)},se=()=>{le||(le=!0,ae.abort(),$(),ge(new O("Upload aborted","ABORTED",void 0,v)))};if(ae.onload=()=>{if(le)return;le=!0;let pe={status:ae.status,etag:ae.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:ae.status===400&&String(ae.responseText??"").includes(fr)};$(),j(pe)},ae.onerror=()=>{le||(le=!0,$(),ge(new O(`Failed to upload part ${v}: network error`,"NETWORK",void 0,v,!0)))},ae.onabort=()=>{le||(le=!0,$(),ge(new O("Upload aborted","ABORTED",void 0,v)))},x.aborted){$(),ge(new O("Upload aborted","ABORTED",void 0,v));return}x.addEventListener("abort",se,{once:!0}),ae.open("PUT",R),ae.setRequestHeader("Content-MD5",w),ae.send(y)});let M;try{M=await fetch(R,{method:"PUT",headers:{"Content-MD5":w},body:y,signal:zr(x,cn(y.length,g))})}catch(j){throw u?.aborted||x.aborted?We(j,"Upload aborted"):new O(`Part ${v}: transport failure (${j instanceof Error?j.message:String(j)})`,"NETWORK",void 0,v,!0)}return{status:M.status,etag:M.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:M.status===400&&(await M.text().catch(()=>"")).includes(fr)}}function La(y,w){if(w.badDigest)throw new O(`Part ${y} arrived corrupted (BadDigest)`,"BAD_DIGEST",w.status,y,!0);if(w.status<200||w.status>=300)throw new O(`Failed to upload part ${y}: ${w.status}`,w.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",w.status,y,w.status!==404);if(!w.etag)throw new O(`No ETag returned for part ${y}`,"S3_ETAG_MISMATCH",void 0,y);return w.etag}async function Pa(y,w){let v=performance.now(),R=null,x=0,z=v,M=null,j=()=>{},ge={reconnect:ae=>j(ae,!1),hasUnsentBytes:()=>M?.unsent??!1};et.add(ge);try{let ae=await new Promise((Ke,Y)=>{let $=!1,se=Pe=>{$||($=!0,Pe())},pe=()=>{let Pe=new AbortController,nt=()=>Pe.abort();Te?.aborted?Pe.abort():Te?.addEventListener("abort",nt,{once:!0});let ve={ctl:Pe,unsent:!0,ended:Promise.resolve()};M=ve,z=performance.now(),tt=z,ve.ended=Ra(y.ciphertext,y.contentMd5,y.partNumber,w,Pe.signal,{onSocketActivity:(rt,at)=>{tt=performance.now(),ve.unsent=rt<at},onDeadline:()=>j("copy deadline",!1)}).then(rt=>{if(M===ve)try{let at=La(y.partNumber,rt);se(()=>Ke(at))}catch(at){se(()=>Y(at))}},rt=>{M===ve&&se(()=>Y(We(rt,`Failed to upload part ${y.partNumber}`)))}).finally(()=>{ve.unsent=!1,Te?.removeEventListener("abort",nt)})};j=(Pe,nt)=>{let ve=M;$||ve===null||u?.aborted||(M=null,x=nt?x+1:0,$e.debug(`${nt?"replace":"reconnect"} part=${y.partNumber} (${Pe})`),ve.ctl.abort(),ve.ended.then(()=>{$||(Te?.aborted?se(()=>Y(new O("Upload aborted","ABORTED",void 0,y.partNumber))):pe())}))},pe(),R=setInterval(()=>{$||u?.aborted||M===null||x>=fo||Oa(y,z)&&j(`slower than its peers after ${Math.round(performance.now()-v)}ms`,!0)},g.hedgePollMs)}),le=performance.now();I.push({part_number:y.partNumber,etag:ae}),b+=y.ciphertext.length,ie(y.ciphertext.length),Ia(y,le-v),Z.delivered(),tt=le,$e.debug(`part=${y.partNumber}/${P} put=${Math.round(le-v)}ms size=${y.ciphertext.length}${x>0?` replaced\xD7${x}`:""}`),G("uploading")}finally{et.delete(ge),j=()=>{},R!==null&&clearInterval(R),M?.ctl.abort()}}let St=(y,w,v)=>pt(y,w,v,Te);async function Ba(){try{let y=await St(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(U??"")}`,{method:"GET",headers:D},g.controlTimeoutMs);if(!y.ok)return null;let w=await y.json();return typeof w.status=="string"?w.status:null}catch{return null}}async function $n(y){let w=performance.now(),v=await Ze("presign batch",async()=>{let x=await St(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...D},body:JSON.stringify({upload_id:U,part_numbers:y})},g.controlTimeoutMs);if(!x.ok)throw await qe(x,"Failed to get presigned URLs",x.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:z}=await x.json();return z}),R=new Map;for(let[x,z]of Object.entries(v))R.set(Number(x),z);return $e.debug(`batch presign ${y.length} urls in ${Math.round(performance.now()-w)}ms`),R}async function Da(y){let w=[];for(let R=y;R<=P&&w.length<L.upload.PRESIGN_BATCH_SIZE;R++)ee.has(R)||w.push(R);if(w.length===0)return;let v=await $n(w);for(let[R,x]of v)ee.set(R,x)}function Wn(y){Ae||(Ae=Da(y).catch(()=>{}).finally(()=>{Ae=null}))}async function Ca(y){await ht(),Me??(Me=performance.now()),E??(E=Me),y.round=bt,y.flowsAtStart=_e.size;let w=ee.get(y.partNumber);!w&&Ae&&(await Ae,w=ee.get(y.partNumber)),ee.delete(y.partNumber),Wn(y.partNumber+1),await Wt(async({after:v})=>{if((!w||v==="refresh_url")&&(w=(await $n([y.partNumber])).get(y.partNumber),!w))throw new O(`No presigned URL for part ${y.partNumber}`,"NETWORK",void 0,y.partNumber,!0);await Pa(y,w)},{clock:Z,policy:g,signal:Te,classify:Gr,what:`part ${y.partNumber}`})}function Zt(){for(;!ue&&!u?.aborted&&_e.size<we&&fe.length>0;){let y=fe.shift(),w=Ca(y).catch(v=>{ue??(ue=We(v,"Part upload failed"))}).finally(()=>{_e.delete(w);let v=qt;qt=[];for(let R of v)R();Zt()});_e.add(w)}}let Ma=()=>new Promise(y=>{qt.push(y)}),Na=(()=>{let y=globalThis,w=globalThis.navigator?.connection,v=w?.type,R=()=>Xt("network is back"),x=()=>Z.connectionLost(),z=()=>{let j=w?.type;j!==v&&(v=j,Xt("network changed"))};y.addEventListener?.("online",R),y.addEventListener?.("offline",x),w?.addEventListener?.("change",z);let M=setInterval(()=>{!Fn||et.size===0||performance.now()-tt<g.livenessSilenceMs||[...et].some(j=>j.hasUnsentBytes())&&(Z.connectionLost(),Xt("every socket silent"))},Math.max(10,g.livenessSilenceMs/4));return()=>{clearInterval(M),y.removeEventListener?.("online",R),y.removeEventListener?.("offline",x),w?.removeEventListener?.("change",z)}})();try{let y=performance.now();if($e.debug(`starting multipart: totalBytes=${n} parts=${P} partSize=${d} pool=${g.poolStart}..${g.poolMax}`),u?.aborted)throw new O("Upload aborted","ABORTED");G("encrypting"),U=await Ze("multipart init",async()=>{let Y=await St(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...D},body:JSON.stringify({seal_id:r,content_type:p,content_length:k,part_size:d,file_id:a})},g.controlTimeoutMs);if(!Y.ok)throw await qe(Y,"Failed to initialize multipart upload","NETWORK");return(await Y.json()).upload_id}),Wn(1),G("encrypting");let w=!1,v=()=>{w=!0,G("encrypting")},R=async(Y,$,se)=>{for(w=!0,F+=$.length,G("encrypting"),u?.aborted&&await Je(u?.aborted===!0),fe.push({partNumber:Y,ciphertext:$,contentMd5:se}),Zt();fe.length>=g.partQueueLimit;)if(await Ma(),ue)throw ue;if(ue)throw ue},x=()=>ao({stream:t,totalBytes:n,key:N,header:o,partSize:d,signal:u,yieldToRenderer:typeof document<"u",onSegment:v,onPart:R}),z=lo(),M=null;if(_&&z&&typeof document<"u"){let Y=null;try{Y=z(),M=[Y,z()]}catch{Y?.terminate()}}if(M){let[Y,$]=M;$e.debug("crypto pipeline: worker");try{await oo(Y,$,{file:_,key:N,header:o,partSize:d,totalBytes:n,signal:u,initialCredits:g.partQueueLimit,onSegment:v,onPart:R})}catch(se){let pe=We(se,"Crypto worker failed");if(pe.code==="ABORTED"||w)throw pe;$e.debug(`crypto worker failed before output \u2014 inline fallback (${pe.message})`),await x()}finally{Y.terminate(),$.terminate()}}else await x();for(;Zt(),!(ue||(u?.aborted&&await Je(!0),_e.size===0&&fe.length===0));)await Promise.race(_e);if(ue)throw ue;G("verifying"),u?.aborted&&await Je(u?.aborted===!0),h?.();let j=!1,ge,ae=await Ze("complete",async()=>{let Y=j;j=!0;let $=await St(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...D},body:JSON.stringify({upload_id:U,parts:I.map(se=>({part_number:se.part_number,etag:se.etag})),...m?{on_conflict:m}:{}})},g.completeTimeoutMs);if($.ok){let se=await $.json().catch(()=>null);return typeof se?.conflict_with=="string"&&(ge=se.conflict_with),se?.status==="verified"}if(Y&&$.status===400&&await Ba()==="completed")return!1;throw await qe($,"Failed to complete multipart upload",$.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});Z.delivered(),G("done");let le=Math.round(performance.now()-y),Ke=n/(1024*1024)/(le/1e3);return $e.debug(`DONE totalTime=${le}ms speed=${Ke.toFixed(2)}MB/s parts=${I.length}`),N.fill(0),{verified:ae,...ge?{conflictWith:ge}:{}}}catch(y){N.fill(0);let w=We(y,"Unknown upload error");throw re(w.code==="ABORTED"),w}finally{Na(),Z.dispose(),Q.abort()}}var Ht="Encrypted file",zt="application/octet-stream";function Vr(e){return new TextEncoder().encode(`field:${e}`)}async function sn(e,t,n){let r=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.importKey("raw",t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),{name:"AES-GCM"},!1,["encrypt"]),s={name:"AES-GCM",iv:r,tagLength:128};if(n){let i=Vr(n);s.additionalData=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}let o=await crypto.subtle.encrypt(s,a,new TextEncoder().encode(e));return{ciphertext:Ie(new Uint8Array(o)),nonce:Ie(r)}}function _o(e){return e?.name==="OperationError"}async function hr(e,t,n,r){let a=It(e),s=It(t),o=async i=>{let l={name:"AES-GCM",iv:s};i&&(l.additionalData=i);let d=await crypto.subtle.decrypt(l,n,a);return new TextDecoder().decode(d)};if(!r)return o(void 0);try{return await o(Vr(r))}catch(i){if(!_o(i))throw i;return o(void 0)}}async function wo(e,t){let n=e.name||Ht,r=e.mime||zt;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await hr(e.name_encrypted,e.name_nonce,t,"name")}catch{n=Ht}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await hr(e.mime_encrypted,e.mime_nonce,t,"mime")}catch{r=zt}return{name:n,mime:r}}async function go(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function bo(e,t){try{let n=await go(t);return wo(e,n)}catch{return{name:e.name||Ht,mime:e.mime||zt}}}var Gt={multipartThresholdBytes:L.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:L.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:L.upload.INMEMORY_BLOB_LIMIT_BYTES};function mo(e,t=Gt){return e<=L.upload.FINE_PART_MAX_FILE_BYTES?L.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Eo(e,t){return e>=t.multipartThresholdBytes}function So(e){if(!(e.kind==="none"||!e.value)){if(e.kind==="ownerToken")return{type:"ownerToken",value:e.value};if(e.kind==="bearer")return{type:"bearer",value:e.value}}}function qr(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:So(e.auth)}function Ao(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var vo={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},pr=[2,12],To=[12,95],ko=[95,99];function yr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=vo[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=ko:r.deliveredBytes===0?s=pr:s=To;let o=s===pr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,l=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,l),t({phase:r.phase,percent:n,deliveredBytes:r.deliveredBytes,preparedBytes:r.preparedBytes,totalBytes:r.totalBytes,speedBps:r.speedBps,etaMs:r.etaMs,state:r.state,attempt:r.attempt})}}var mn=class{constructor(e,t){this.run=t,this.cancelled=!1,this.ctx=e.ctx,this.policy=e.policy,this.sealId=e.sealId,this.createdSeal=e.createdSeal,this.expiresAt=e.expiresAt,this.files=e.files}get pending(){return this.files.filter(e=>e.state==="pending")}get verification(){return this.files.every(e=>e.state==="verified")?"verified":"pending"}async resume(e={}){if(this.cancelled)throw new O("Upload session was cancelled","ABORTED");try{return await this.run(this,e)}catch(t){let n=We(t,"Upload failed");throw n.session=this,n}}async cancel(){this.cancelled=!0;let e=Ao(this.ctx);if(!e)return;let t=new yt({baseUrl:this.ctx.baseUrl,credentials:this.ctx.credentials??"include"});try{if(this.createdSeal){await t.revoke(this.sealId,e);return}for(let n of this.pending)await t.revokeFile(this.sealId,n.fileId,e)}catch{}}};function xo(e,t,n){let r=t.length;if(!e||e.length<r)throw new Error(`${n} returned ${e?.length??0} file record(s) for ${r} file(s) \u2014 cannot upload ciphertext`);let a=e.slice(e.length-r);return a.forEach((s,o)=>{if(!s?.id)throw new Error(`${n}: file record ${o} has no id \u2014 cannot upload ciphertext`);if(s.sha256_hex===void 0){if(r===1)return;throw new Error(`${n}: file record ${o} carries no sha256_hex \u2014 refusing to pair ${r} files by position alone`)}if(s.sha256_hex!==t[o])throw new Error(`${n}: file record ${o} has sha256=${s.sha256_hex.slice(0,16)}\u2026 but we sent ${t[o].slice(0,16)}\u2026 \u2014 response order corrupted, refusing to upload`)}),a}function Io(e){return e>=200&&e<300||e===204}async function Oo(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:l,clock:d,transport:p}=e,f=` for ${i}`,u={"Content-Type":"application/json",...s},_=t.credentials??"include",h=(k,P)=>Wt(P,{clock:d,policy:p,signal:l,classify:jr,what:k}),m=()=>h(`initiate${f}`,async()=>{let k=await pt(`${t.baseUrl}/upload/initiate`,{method:"POST",headers:u,credentials:_,body:JSON.stringify({seal_id:n,content_type:"application/octet-stream",content_length:a.blob.size,file_id:r})},p.controlTimeoutMs,l);if(k.status===409)return null;if(!k.ok)throw await qe(k,`Upload initiate failed${f}`,"NETWORK");let P=await k.json();return P.already_verified?null:P}),g=await m();if(g===null)return!1;let N=!1;if(await Wt(async({after:k})=>{if(k==="refresh_url"){let I=await m();if(I===null){N=!0;return}g=I}let{upload_url:P}=g,U=await pt(P,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},cn(a.blob.size,p),l);if(U.status===400&&(await U.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new O(`Upload arrived corrupted (BadDigest)${f}`,"BAD_DIGEST",400,void 0,!0);if(!Io(U.status))throw new O(`Upload PUT failed${f}: ${U.status}`,"NETWORK",U.status)},{clock:d,policy:p,signal:l,classify:Gr,what:`PUT${f}`}),N)return!1;d.delivered(),o();let D=await h(`confirm${f}`,async()=>{let k=await pt(`${t.baseUrl}/upload/confirm`,{method:"POST",headers:u,credentials:_,body:JSON.stringify({seal_id:n,file_id:r,...t.onConflict?{on_conflict:t.onConflict}:{}})},p.controlTimeoutMs,l);if(!k.ok)throw await qe(k,`Upload confirm failed${f}`,"NETWORK");let P=await k.json().catch(()=>null);return typeof P?.conflict_with=="string"&&e.onConflictWith(P.conflict_with),P?.status==="verified"});return d.delivered(),D}async function Xr(e,t,n,r,a,s){try{let o=await pt(`${e.baseUrl}/upload/status/${encodeURIComponent(t)}/${n}`,{method:"GET",headers:r,credentials:e.credentials??"include"},a.controlTimeoutMs,s);if(!o.ok)return null;let i=await o.json();return typeof i.status=="string"?i.status:null}catch(o){if(o instanceof O&&o.code==="ABORTED")throw o;return null}}var Ro=new Set(["failed","size_mismatch","verification_error"]);async function Lo(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i}=e,l=s.verifyFallbackWaitMs,d=performance.now(),p=s.verifyPollBackoffMs;for(let f=0;;f++){let u=p[Math.min(f,p.length-1)]??0;if(performance.now()-d+u>l)return"pending";u>0&&await gn(u,o);let _=await Xr(t,n,r,a,s,o);if(_==="verified")return"verified";if(_!==null&&Ro.has(_))throw new O(`The server rejected ${i} after upload (${_}). It has to be sent again.`,"VERIFICATION_REJECTED");if(_===null&&f===0)return"pending"}}async function Po(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:l}=t,{onProgress:d,signal:p}=n;if(t.state!=="pending")return;if(p?.aborted)throw new O("Upload aborted","ABORTED");let f=qr(r),u=bn(f),_=Hr(a.transport),h=async I=>{if(t.state=I?"verified":"uploaded",!I)try{await Lo({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:u,transport:_,signal:p,label:o.name})==="verified"&&(t.state="verified")}catch(b){throw b instanceof O&&b.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),b}};if(Eo(o.size,a)){if(t.streamed){let E=await Xr(r,s,t.sha256_hex,u,_,p);if(E!==null&&E!=="pending"){await h(E==="verified");return}}let I=yr("multipart",E=>d?.(E)),b=null,F=await ho({file:o,sealId:s,fileId:l,key:i,header:t.header,baseUrl:r.baseUrl,auth:f,partSize:mo(o.size,a),onProgress:E=>{b=E;let C=E.phase==="done";I({...E,phase:C?"verifying":E.phase,fraction:C?0:E.deliveredBytes/E.totalBytes,preparedFraction:E.totalBytes>0?(E.preparedBytes??0)/E.totalBytes:0,preparedBytes:E.preparedBytes})},signal:p,transport:a.transport,onStreamed:()=>{t.streamed=!0},onConflict:r.onConflict});t.streamed=void 0,t.conflictWith=F.conflictWith,await h(F.verified);let B=t.encryptedSize;I({...b??{phase:"done",percent:100,deliveredBytes:B,totalBytes:B,state:"running",attempt:1},phase:"done",fraction:1});return}let m=yr("single-put",I=>d?.(I)),g=t.encryptedSize,N={phase:"encrypting",fraction:0,delivered:!1},D=(I,b,F=N.delivered)=>{N={phase:I,fraction:b,delivered:F},m({phase:I,fraction:b,deliveredBytes:F?g:0,totalBytes:g,state:k.state,attempt:k.retriesSinceDelivery+1})},k=new Yr(_,()=>D(N.phase,N.fraction));t.prepared||(D("encrypting",0),t.prepared=await Qs(o,i,t.header,I=>D("encrypting",o.size>0?I/o.size:1)));let P=t.prepared;D("uploading",0);let U;try{U=await Oo({ctx:r,sealId:s,fileId:l,ciphertext:P,authHeaders:u,onVerifying:()=>D("verifying",0,!0),label:o.name,signal:p,clock:k,transport:_,onConflictWith:I=>{t.conflictWith=I}})}finally{k.dispose()}D("verifying",.5,!0),await h(U),t.prepared=void 0,D("done",1,!0)}function Bo(e){if(!e.roomId){if(!e.ownerTokenHash)throw new Error("ownerTokenHash is required for seal creation (SHORT LINKS)");if(e.ownerTokenHash.length!==64||!/^[a-f0-9]{64}$/i.test(e.ownerTokenHash))throw new Error("ownerTokenHash must be 64 hex characters (SHA256)")}}function Do(e,t){t.ttl&&(e.ttl=t.ttl),t.roomId&&(e.room_id=t.roomId),t.otp&&(e.otp=t.otp),t.nda&&(e.nda=!0),t.ownerEmail&&(e.owner_email=t.ownerEmail),t.singleUse&&(e.single_use=!0),t.geo&&t.geo.length>0&&(e.geo=t.geo),typeof t.maxOpens=="number"&&t.maxOpens>0&&(e.max_opens=t.maxOpens),t.tier&&(e.tier=t.tier)}async function Co(e,t,n,r,a={}){let s=await sn(e.name,t,"name"),o=await sn(e.type||"application/octet-stream",t,"mime"),i={size:n,sha256_hex:r,name_encrypted:s.ciphertext,name_nonce:s.nonce,mime_encrypted:o.ciphertext,mime_nonce:o.nonce,encryption_version:he.current_format_version};if(a.relativePath!==void 0){let l=await sn(a.relativePath,t,"path");i.path_encrypted=l.ciphertext,i.path_nonce=l.nonce}return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function Mo(e,t,n){if(n?.aborted)throw new O("Upload aborted","ABORTED");try{return await fetch(e,{...t,signal:n})}catch(r){throw n?.aborted?new O("Upload aborted","ABORTED"):r}}async function No(e,t,n){let r={files_meta:t};e.ownerTokenHash&&(r.owner_token_hash=e.ownerTokenHash),Do(r,e);let a=await Mo(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...bn(qr(e))},credentials:e.credentials??"include",body:JSON.stringify(r)},n);if(!a.ok)throw await qe(a,"Create seal failed","UNKNOWN");return await a.json()}async function Uo(e,t){let n=xs();return{file:e,key:t,header:n,sha256_hex:await Ye(n)}}async function Fo(e,t,n,r){await e.onRegistered?.(t,n.map((a,s)=>({fileId:r[s].id,sha256_hex:a.sha256_hex,key:a.key})))}function $o(e,t){return e.map((n,r)=>({index:r,fileId:t[r].id,file:n.file,key:n.key,header:n.header,sha256_hex:n.sha256_hex,encryptedSize:yn(n.file.size),state:"pending"}))}async function Zr(e,t,n=Gt,r={}){Bo(e);let a=await Uo(t,Ds()),s=await No(e,[await Co(t,a.key,yn(t.size),a.sha256_hex)],r.signal),o=xo(s.files,[a.sha256_hex],`Create seal ${s.id}`);return await Fo(r,s.id,[a],o),new mn({ctx:e,policy:n,sealId:s.id,createdSeal:!0,expiresAt:s.expires_at,files:$o([a],o)},async(l,d)=>{let p=l.files[0];return await Po(l,p,{onProgress:f=>d.onProgress?.(f),signal:d.signal}),{sealId:l.sealId,fileId:p.fileId,encryptionKey:p.key,sha256_hex:p.sha256_hex,expiresAt:l.expiresAt,verification:l.verification}}).resume(r)}var _r=[2e3,4e3,8e3,15e3],on=ze.limits.TIER_BYTES,rl=Object.keys(on).filter(e=>e!=="free").sort((e,t)=>on[e]-on[t]);function Jr(e){return e instanceof O&&e.httpStatus===402&&e.session?e.session:null}function Qr(e,t=Date.now()){let n=t+ze.limits.PAYMENT_WAIT_MAX_SECONDS*1e3,r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)?Math.min(n,r):n}async function ea(e,t,n,r){for(let a=0;;a++){try{let o=await e.getOwnerSeal(t,n,{signal:r.signal});if(r.tier?o.tier===r.tier:o.tier&&o.tier!=="free")return o}catch(o){if(r.signal?.aborted||o instanceof ce&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=_r[Math.min(a,_r.length-1)];if(Date.now()+s>r.deadline)return null;await gn(s,r.signal)}}var al=ze.limits.ttl_options;var ta={version:2,name:"SEAL_SHARE_URL",description:"URL fragment scheme for SEAL share links (SPEC-AEON-V4 \xA76, law \u041B2): the fragment of any link carries one symmetric key or nothing. A link addressed to someone carries no fragment: its key, wrapped to the recipient's bundle (sealed box v2, crypto.json sealed_box_v2), lives in the share link's row on the server and comes back as `fragment` of GET /seal/{id}/share/{code}. Backends never see fragments (URL fragments are not sent over HTTP per RFC 3986 \xA73.5). Consumers: the web, the CLI, the MCP server, the SDK, sealnet and the bots. The wrap and its opening live in shared/core (targeted.rs over sealed_box.rs, Identity::open).",url_template:"https://<host>/s/<seal_id>/<share_code>[#<link_key>]",fragment_variants:{key:{format:"<link_key_urlsafe_b64_no_pad>",detection:"exactly 43 urlsafe-b64-no-pad characters, 32 bytes: the AES-256-GCM key of the share blob (seal_blob.v1.json)",field_layout:[{name:"link_key",offset:0,length:32,encoding:"urlsafe-b64-no-pad in URL"}]},none:{format:"",detection:"no fragment: an addressed link. The key, wrapped to the recipient's bundle with scope ('seal_share', seal_id from the path), is the `fragment` field of the share blob response (1575 base64url characters, first byte 0x02); only the recipient's seed opens it."},targeted_x25519_v1:{status:"read only until the removal (C1 \xA76): links made before C1 with the sealed box v1 in the fragment",format:"x25519:<packed_b64>",prefix:"x25519:",packed_binary_length_bytes:92,packed_layout:[{name:"ephemeral_public",offset:0,length:32,encoding:"raw bytes; X25519 ephemeral pubkey from sender"},{name:"nonce",offset:32,length:12,encoding:"raw bytes; AES-256-GCM nonce"},{name:"wrapped_link_key",offset:44,length:48,encoding:"raw bytes; 32 B ciphertext of the link key || 16 B GCM tag"}],implicit_fields_not_in_packed:{recipient_public:"the X25519 key of the recipient's seed (the seed itself is the X25519 secret)",scope_type:"'seal_share'",scope_id:"seal_id from the URL path /s/<seal_id>/<code>",grant_version:"1"},kdf_info_layout:'seal_crypto::hkdf::derive_wrap_key: b"WRAP" || 0x01 || len(scope_type) || scope_type || len(scope_id) || scope_id, salt crypto.json hkdf.wrap_key_salt',aad_layout:"recipient_public (32 B) || 0x01"}},version_detection_rule:"(1) no fragment \u2192 none: the wrap comes from the server; (2) starts with 'x25519:' \u2192 targeted_x25519_v1, read only until the removal; (3) exactly 43 urlsafe-b64-no-pad characters \u2192 key; (4) anything else \u2192 'update the client' (SPEC-AEON-V4 \xA77.4), never decoded as a key.",current_format_version:2,supported_format_versions:[2],implementations:{rust:"shared/core/src/targeted.rs (wrap_link_key / open_wrap; the x25519: opening until the removal); the CLI calls it as seal_crypto::targeted",ts:"shared/packages/protocol/src/identity.ts (wrapTo / openWrap) over the core's WASM; the whole link is parsed by protocol/src/url.ts::parseShareUrl",python:"sealnet calls the Rust core in its wheel (sealnet.seal_crypto); no Python implementation"},test_vectors:{description:"Frozen outputs of the read-only v1 variant, until the removal: every reader MUST recover link_key from fragment with recipient_secret (the seed) and seal_id, and MUST fail with any other seal_id.",targeted_x25519_v1:[{recipient_secret_b64url:"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",recipient_public_b64url:"E75P6uryBMf9M1j8nAByGIHRdCeBKCJ-xnTzf3_pe20",seal_id:"AbCd1234",fragment:"x25519:GkbbXddA43eoSgY1ZAAnPTCDmJIoGM3ZrY2_wctdKX2ivODHag_TCSjQql3PMu22xzsxJsYKHnIhHjXhvuJfe468pvsvvzuEZiaVzoPu2PTqlRin8xiDsopyrGQ",link_key_b64url:"q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s"}]},security_properties:{key:"Anyone with the URL can open. link_key is the entire capability \u2014 treat the URL itself as a bearer credential.",none:"The URL alone opens nothing: the key is sealed to the recipient's bundle (X25519 + ML-KEM-768) and only the seed on the recipient's device opens it. Each wrap has a fresh ephemeral key and encapsulation."}},Wo=ta.fragment_variants.targeted_x25519_v1.prefix,En=8,Sn=43,dn=4,jt=/^[A-Za-z0-9_-]+$/;function Ho(e,t){if(!jt.test(e))return!1;try{let n=e.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return atob(n).length===t}catch{return!1}}function An(e){return e.length===En&&jt.test(e)}function vn(e){return e.length===Sn&&Ho(e,32)}function na(e,t){if(!An(e))throw new Error(`Invalid sealId: must be ${En} base64url characters`);if(!vn(t))throw new Error(`Invalid linkKey: must be ${Sn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function ra(e,t,n){if(!An(e))throw new Error(`Invalid sealId: must be ${En} base64url characters`);if(t.length!==dn||!jt.test(t))throw new Error(`Invalid shareCode: must be ${dn} base64url characters`);if(!vn(n))throw new Error(`Invalid linkKey: must be ${Sn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var Mt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function zo(e){let t;try{t=new URL(e)}catch{throw new Mt("url_invalid",`not a valid URL: ${e}`)}let n;try{n=Ko(t.pathname.replace(/\/+$/,""))}catch{throw new Mt("url_invalid",`expected /s/<seal_id>[/<share_code>] path, got: ${t.pathname}`)}let r=t.hash.replace(/^#/,"").trim(),a=n.shareCode??null;if(!r)return{sealId:n.sealId,shareCode:a,fragmentVariant:"none",fragment:r};if(r.startsWith(Wo))return{sealId:n.sealId,shareCode:a,fragmentVariant:"targeted_x25519_v1",fragment:r};if(!vn(r))throw new Mt("url_invalid",`the fragment is not one 43-character key (got ${r.length} characters): a mangled link, or one from a newer client \u2014 update it`);return{sealId:n.sealId,shareCode:a,fragmentVariant:"key",fragment:r}}function Ko(e){let t=e.match(/^\/s\/([A-Za-z0-9_-]{8})(?:\/([A-Za-z0-9_-]{4}))?$/);if(!t)throw new Error("Invalid seal URL format");let n=t[1],r=t[2];if(!An(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==dn||!jt.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var Tn={version:1,default_aead:"aes_256_gcm",aes_gcm:{key_length_bytes:32,nonce_length_bytes:12,tag_length_bytes:16},sha256:{output_length_bytes:32,hex_string_length:64},owner_token_bytes:32,link_key_bytes:32,metadata_aad_prefix:"field:",keybundle:{signature_prefix:"seal:keybundle:",signed_bundle_version:2,v2_fields:["identity_ed25519_pub","agreement_x25519_pub","kem_mlkem768_pub"],packed_length:1316,address:{of:"sha256(identity_ed25519_pub), 32 bytes",text:"base64url without padding, 43 characters",words:"fingerprint_words.json over its first three bytes"}},hkdf:{wrap_key_salt:"seal:wrapkey:v1",wrap_key_salt_v2:"seal:wrapkey:v2",identity_key_salt:"seal:key-derivation:v1",file_envelope_salt:"seal:file-envelope:v1",info_prefixes:{wrap:"WRAP",agreement:"AGRE",identity:"IDEN",workload_identity:"seal:workload-identity:v1",kem_mlkem768:"seal:kem-mlkem768:v1"}},xwing:{label_hex:"5c2e2f2f5e5c"},sealed_box_v2:{version_byte:2,packed_layout:[{name:"version",offset:0,length:1},{name:"eph_pub",offset:1,length:32},{name:"kem_ct",offset:33,length:1088},{name:"nonce",offset:1121,length:12},{name:"ct",offset:1133,length:48}],packed_length:1181,packed_b64_length:1575},secret_scope_aad:"secret:{secret_id}",sign:{message_prefix:"aeon:sign:v1",message_format:"aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}"}},kn=Le.scopes.share_link,aa=Le.scopes.owner_copy,wr=Tn.sealed_box_v2.version_byte,gr=Tn.sealed_box_v2.packed_length,He=ta.fragment_variants.targeted_x25519_v1,Go=Le.migrate.scope_address_proof,Se=32,br=32,xn=/^[A-Za-z0-9_-]+$/;function sa(){return crypto.getRandomValues(new Uint8Array(Se))}async function In(e,t=1){let n=await Fe();if(e.length===Se)return n.WasmIdentity.fromSeed32(e);if(e.length===2*Se)return n.WasmIdentity.fromSeed64(e,t);throw new Error(`a seed is ${Se} or ${2*Se} bytes, got ${e.length}`)}async function Yt(e,t=1){let n=await In(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words(),legacyAddress:n.legacyAddress()}}finally{n.free()}}function oa(e){let t=e.trim().replace(/=+$/,"");if(t.length!==43)throw new Error(`an address is 43 urlsafe-base64-no-pad characters, got ${t.length}`);if(!xn.test(t))throw new Error("not valid urlsafe-base64-no-pad: contains characters outside [A-Za-z0-9_-] (standard-base64 input is rejected \u2014 copy the exact address from `seal keygen` or `sealnet-mcp pubkey`)");return t}async function ia(e,t){return(await Fe()).wasm_bundle_verify_for_address(e,t)}async function On(e){return(await Fe()).wasm_bundle_address(e)}async function Rn(e,t,n,r){if(e.length!==br)throw new Error(`a wrapped key is ${br} bytes, got ${e.length}`);if(r.length===0)throw new Error("the scope id must not be empty: the wrap binds to it");return ne((await Fe()).wasm_sealbox_wrap(e,t,n,r))}var Ee=class extends Error{constructor(e,t,n){super(t),this.name="WrapError",this.kind=e,this.cause=n}};async function jo(e,t,n,r,a=1){if(r.length===0)throw new Ee("parse","the scope id must not be empty: the wrap binds to it");if(e.startsWith(He.prefix))return Yo(e.slice(He.prefix.length),t,n,r);if(!xn.test(e))throw new Ee("parse","the wrap is not urlsafe-base64-no-pad");let s=V(e);if(s[0]!==wr)throw new Ee("parse",`the wrap is not a sealed box v${wr}: a newer client made it \u2014 update this one`);if(s.length!==gr)throw new Ee("parse",`the wrap is ${s.length} bytes, expected ${gr}`);if(t.length!==Se&&t.length!==2*Se)throw new Ee("parse",`a seed is ${Se} or ${2*Se} bytes, got ${t.length}`);let o=await In(t,a);try{return o.open(s,n,r)}catch(i){throw new Ee("aead","the wrap does not open: it is not for this seed, or its scope, id or bytes were changed",i)}finally{o.free()}}async function Yo(e,t,n,r){if(!xn.test(e))throw new Ee("parse",`the ${He.prefix} wrap is not urlsafe-base64-no-pad`);let a=V(e);if(a.length!==He.packed_binary_length_bytes)throw new Ee("parse",`the ${He.prefix} wrap is ${a.length} bytes, expected ${He.packed_binary_length_bytes}`);if(t.length!==Se)throw new Ee("parse",`an ${He.prefix} wrap opens with a ${Se}-byte seed`);let s=await Fe();try{return s.wasm_sealbox_unwrap(a,t,n,r)}catch(o){throw new Ee("aead","the wrap does not open: it is not for this seed, or its scope, id or bytes were changed",o)}}async function Vo(e,t){let n=await In(e);try{let r=n.inboxProof(BigInt(t.ts),V(t.challenge));return`${t.ts}.${t.challenge}.${ne(r)}`}finally{n.free()}}async function qo(e,t,n){let a=(await Fe()).wasm_sealbox_unwrap(V(t),e,Go,String(n));return`${n}.${ne(a)}`}var un={version:1,name:"FINGERPRINT_WORDS",description:"Three words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3): word i (i = 0, 1, 2) is words[byte i of SHA-256(identity public key)] \u2014 the first three bytes of the same SHA-256 that is the address, so a client names an address by its own first bytes without hashing again \u2014 24 bits in all, written in lower case with one space between them. The agent shows them in its chat, box.seal.net and seal.net/i/{id} show them on the page, so a person sees at a glance whether both sides hold the same key. One list for every language and client: 256 English nouns of 3 to 7 letters, no two sharing their first three letters, in alphabetical order.",digest:"sha256",count:3,separator:" ",words:["acorn","album","amber","anchor","apple","arrow","atlas","bamboo","banjo","basket","beach","bell","bench","berry","birch","bison","bloom","boat","bolt","bottle","brick","broom","butter","cabin","cactus","camel","candle","cargo","castle","cedar","cherry","clock","coast","comet","copper","coral","cotton","crab","crown","daisy","dawn","deer","delta","desert","diamond","dolphin","dove","dragon","drum","duck","dune","eagle","earth","echo","egg","elk","ember","emerald","engine","falcon","farm","feather","fence","fern","fig","finch","fish","flag","flute","fog","forest","fossil","fox","frog","garden","gate","gazelle","gecko","geyser","ginger","giraffe","glacier","globe","goat","gold","goose","grape","guitar","hammer","harbor","hawk","hazel","hedge","heron","hill","hippo","hive","honey","horse","igloo","iguana","iris","iron","island","ivory","jacket","jaguar","jasmine","jelly","jewel","juice","jungle","kayak","kelp","kettle","kite","kiwi","koala","ladder","lagoon","lamp","lantern","lava","leaf","lemon","leopard","lily","lime","lion","lizard","llama","lobster","lotus","lynx","magnet","mango","maple","marble","meadow","melon","meteor","mint","mirror","monkey","moon","mosaic","muffin","nail","nectar","needle","nest","oasis","ocean","olive","opal","orange","orbit","orchid","otter","owl","palm","panda","paper","parrot","peach","pebble","pelican","pencil","pepper","piano","pine","pizza","planet","plum","pony","poppy","prism","pumpkin","quartz","queen","quill","rabbit","radio","raft","raven","reed","rhino","ribbon","ridge","river","robin","rocket","rose","ruby","sail","salmon","sand","saturn","scroll","shark","shell","ship","silk","sled","sloth","snail","snow","spider","spruce","star","stone","sugar","summit","swan","table","teapot","thunder","tiger","tile","timber","toast","tomato","topaz","torch","tower","trout","truck","tulip","turtle","unicorn","valley","vanilla","vase","velvet","violin","volcano","wagon","walnut","wave","whale","wheat","whistle","willow","window","wizard","wolf","wombat","wren","yacht","yarn","yeti","yucca","zebra","zenith","zinc","zipper"],vector:{public_key_b64url:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",sha256_prefix_hex:"66687a",words:"iron ivory lava"}},Xo=un.words,Zo=/^[A-Za-z0-9_-]{43}$/;function la(e){if(!Zo.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=V(e);return Array.from(t.subarray(0,un.count),n=>Xo[n]).join(un.separator)}var ca=Le.payloads.pair.mime,ol=Le.payloads.device.mime,da=Le.pair_what,mr=Le.payloads.name_max,Er=Tn.keybundle.packed_length,Sr=2;var Jo=/^[A-Za-z0-9_-]+$/;function ua(e){let t=Qo(e,"pairing");if(typeof t.bundle!="string"||!Jo.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:ei(V(t.bundle)),name:ti(t.name)}}function Qo(e,t){let n;try{n=JSON.parse(new TextDecoder().decode(e))}catch{throw new Error(`${t} payload is not JSON`)}if(typeof n!="object"||n===null||n.v!==Sr)throw new Error(`${t} payload is not version ${Sr}`);return n}function ei(e){if(e.length!==Er)throw new Error(`a bundle is ${Er} bytes, got ${e.length}`);return e}function ti(e){if(typeof e!="string"||e.length===0||e.length>mr)throw new Error(`name must be 1 to ${mr} characters`);return e}var ni={version:1,name:"SECRETS",description:"How a secret travels (SPEC-AGENTS \xA74.3, \xA76.1). `mime` is the marker a sender pins on a file that is a secret (`seal send --kind secret`, the intake page, the local dialog); it rides encrypted in the file metadata, so a receiving agent saves it to disk and never reads it into a conversation (`seal_open inline` refuses it). `sources`: where well-known keys are created, service name \u2192 the host of its key page. A request's `where_url` whose host is in this list is shown as that service; any other https host is shown with the note that the address came from the agent and should be checked. Data, not code: a service is added with one line.",mime:"application/vnd.seal.secret",sources:{Anthropic:"console.anthropic.com",AWS:"console.aws.amazon.com","Brave Search":"api.search.brave.com",Cloudflare:"dash.cloudflare.com",DigitalOcean:"cloud.digitalocean.com",Discord:"discord.com",GitHub:"github.com","Google AI Studio":"aistudio.google.com","Google Cloud":"console.cloud.google.com",Groq:"console.groq.com","Hugging Face":"huggingface.co",Mistral:"console.mistral.ai",npm:"www.npmjs.com",OpenAI:"platform.openai.com",OpenRouter:"openrouter.ai",PyPI:"pypi.org",Slack:"api.slack.com",Stripe:"dashboard.stripe.com",Supabase:"supabase.com","Telegram BotFather":"t.me",Twilio:"console.twilio.com",Vercel:"vercel.com"},patterns_note:"What a key looks like, for every reader: `seal doctor --transcripts`, the scanner of the Pro web page and the `sealfs` detector (C1 \u042039). `pattern` is an expression in the subset all three run alike \u2014 JS, Python `re`, Rust `regex`: no lookaround, no backreference, no inline flag; a boundary is `\\b` inside the expression. The flags are shared: case-insensitive and multiline. A match that contains a string of the entry's `allowlist` (case-insensitive) is no finding. A finding is shown masked: its first four characters, `\u2026`, its last two. `vectors.hit` holds a finding of the entry, `vectors.clean` none; every reader passes them. The scanner page does not take a file larger than `max_file_bytes`; `seal doctor` reads agent transcripts of any size, a line at a time \u2014 skipping a long transcript would hide its leak. Data, not code: a service is added with one entry.",max_file_bytes:10485760,patterns:[{name:"openai_api_key",pattern:"\\bsk-proj-[A-Za-z0-9_-]{40,}",severity:"critical",description:"OpenAI API Key",keywords:["openai","sk-proj-"],vectors:{hit:"OPENAI_API_KEY=sk-proj-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEf",clean:"OPENAI_API_KEY=sk-proj-AbCdEfGhIj"}},{name:"anthropic_api_key",pattern:"\\bsk-ant-[A-Za-z0-9_-]{40,}",severity:"critical",description:"Anthropic API Key",keywords:["anthropic","sk-ant-"],vectors:{hit:"sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCd",clean:"sk-ant-api03-short"}},{name:"github_token",pattern:"\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{30,}",severity:"critical",description:"GitHub Token",keywords:["github","token","ghp_","github_pat_"],vectors:{hit:"token: ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"token: xghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"}},{name:"gitlab_token",pattern:"glpat-[A-Za-z0-9\\-]{20,}",severity:"critical",description:"GitLab Personal Access Token",keywords:["gitlab","token"],vectors:{hit:"glpat-AbCdEfGhIjKlMnOpQrSt",clean:"glpat-short"}},{name:"aws_access_key_id",pattern:"\\b(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}\\b",severity:"critical",description:"AWS Access Key ID",keywords:["aws","amazon","access_key","accesskey"],vectors:{hit:"AKIAIOSFODNN7EXAMPLE",clean:"AKIAIOSFODNN7EXAMPLEX"}},{name:"aws_secret_access_key",pattern:`aws[_\\-\\.]?secret[_\\-\\.]?access[_\\-\\.]?key['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9/+=]{40})['\\"]?`,severity:"critical",description:"AWS Secret Access Key",keywords:["aws","secret","access_key"],vectors:{hit:'aws_secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"',clean:'aws_secret_access_key = "short"'}},{name:"stripe_live_key",pattern:"\\b[sr]k_live_[A-Za-z0-9]{20,}",severity:"critical",description:"Stripe Live Secret Key",keywords:["stripe","live","secret"],vectors:{hit:"sk_live_AbCdEfGhIjKlMnOpQrStUvWx",clean:"sk_live_AbCd"}},{name:"stripe_test_key",pattern:"\\b[sr]k_test_[A-Za-z0-9]{20,}",severity:"medium",description:"Stripe Test Secret Key",keywords:["stripe","test"],vectors:{hit:"rk_test_AbCdEfGhIjKlMnOpQrStUvWx",clean:"rk_test_AbCd"}},{name:"stripe_publishable_live",pattern:"pk_live_[A-Za-z0-9]{24,}",severity:"low",description:"Stripe Live Publishable Key",keywords:["stripe","publishable"],vectors:{hit:"pk_live_AbCdEfGhIjKlMnOpQrStUvWx",clean:"pk_live_AbCd"}},{name:"slack_token",pattern:"\\bxox[abprs]-[A-Za-z0-9-]{20,}",severity:"critical",description:"Slack Token",keywords:["slack","token","xox"],vectors:{hit:"xoxb-1234567890-1234567890123-AbCdEfGhIjKl",clean:"xoxb-12345"}},{name:"slack_webhook",pattern:"https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+",severity:"high",description:"Slack Webhook URL",keywords:["slack","webhook","hooks.slack.com"],vectors:{hit:"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",clean:"https://hooks.slack.com/services/"}},{name:"google_api_key",pattern:"\\bAIza[0-9A-Za-z\\-_]{35}",severity:"high",description:"Google API Key",keywords:["google","api","AIza"],vectors:{hit:"AIzaSyAbCdEfGhIjKlMnOpQrStUvWxYz0123456",clean:"AIzaSyShort"}},{name:"google_oauth_client_secret",pattern:`client[_\\-]?secret['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9\\-_]{24})['\\"]?`,severity:"high",description:"Google OAuth Client Secret",keywords:["google","oauth","client_secret"],vectors:{hit:'client_secret: "AbCdEfGhIjKlMnOpQrStUvWx"',clean:'client_secret: "short"'}},{name:"private_key",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY(?:\\s+BLOCK)?-----",severity:"critical",description:"Private Key",keywords:["private","key","-----BEGIN"],vectors:{hit:"-----BEGIN OPENSSH PRIVATE KEY-----",clean:"-----BEGIN PUBLIC KEY-----"}},{name:"jwt_token",pattern:"eyJ[A-Za-z0-9_-]*\\.eyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]*",severity:"high",description:"JSON Web Token (JWT)",keywords:["jwt","token","eyJ"],vectors:{hit:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl",clean:"eyJhbGciOiJIUzI1NiJ9"}},{name:"basic_auth",pattern:"(?:basic\\s+)[A-Za-z0-9+/=]{20,}",severity:"high",description:"Basic Authentication Header",keywords:["basic","auth","authorization"],vectors:{hit:"Authorization: Basic dXNlcjpwYXNzd29yZDEyMzQ1Ng==",clean:"Basic auth is disabled"}},{name:"bearer_token",pattern:"bearer\\s+[A-Za-z0-9_\\-\\.]{20,}",severity:"high",description:"Bearer Token",keywords:["bearer","token","authorization"],vectors:{hit:"Authorization: Bearer AbCdEfGhIjKlMnOpQrStUvWx",clean:"Bearer token expired"}},{name:"postgres_uri",pattern:"postgres(?:ql)?://[^:]+:[^@]+@[^/]+/[^\\s]+",severity:"critical",description:"PostgreSQL Connection String",keywords:["postgres","postgresql","database"],vectors:{hit:"postgresql://app:hunter2secret@db.internal:5432/app",clean:"postgresql://db.internal/app"}},{name:"mysql_uri",pattern:"mysql://[^:]+:[^@]+@[^/]+/[^\\s]+",severity:"critical",description:"MySQL Connection String",keywords:["mysql","database"],vectors:{hit:"mysql://app:hunter2secret@db.internal/app",clean:"mysql://db.internal/app"}},{name:"mongodb_uri",pattern:"mongodb(?:\\+srv)?://[^:]+:[^@]+@[^\\s]+",severity:"critical",description:"MongoDB Connection String",keywords:["mongodb","mongo","database"],vectors:{hit:"mongodb+srv://app:hunter2secret@cluster0.example.net",clean:"mongodb://localhost"}},{name:"redis_uri",pattern:"redis://[^:]*:[^@]+@[^\\s]+",severity:"high",description:"Redis Connection String",keywords:["redis","cache"],vectors:{hit:"redis://:hunter2secret@cache.internal:6379",clean:"redis://cache.internal:6379"}},{name:"azure_storage_key",pattern:`(?:account[_\\-]?key|storage[_\\-]?key)['\\"]?\\s*[:=]\\s*['\\"]?([A-Za-z0-9+/=]{88})['\\"]?`,severity:"critical",description:"Azure Storage Account Key",keywords:["azure","storage","account_key"],vectors:{hit:"AccountKey=AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKl",clean:"AccountKey=short"}},{name:"gcp_service_account",pattern:'"type"\\s*:\\s*"service_account"',severity:"critical",description:"GCP Service Account JSON",keywords:["gcp","google","service_account"],vectors:{hit:'{"type": "service_account", "project_id": "demo"}',clean:'{"type": "user"}'}},{name:"sendgrid_api_key",pattern:"SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}",severity:"high",description:"SendGrid API Key",keywords:["sendgrid","email","SG."],vectors:{hit:"SG.AbCdEfGhIjKlMnOpQrStUv.AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdE",clean:"SG.short.key"}},{name:"twilio_api_key",pattern:"SK[a-f0-9]{32}",severity:"high",description:"Twilio API Key",keywords:["twilio","sms"],vectors:{hit:"SK0123456789abcdef0123456789abcdef",clean:"SK0123456789abcdef"}},{name:"npm_token",pattern:"npm_[A-Za-z0-9]{36}",severity:"high",description:"NPM Access Token",keywords:["npm","token"],vectors:{hit:"npm_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"npm_short"}},{name:"pypi_token",pattern:"pypi-[A-Za-z0-9_-]{100,}",severity:"high",description:"PyPI API Token",keywords:["pypi","token","python"],vectors:{hit:"pypi-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWx",clean:"pypi-short"}},{name:"generic_password",pattern:`(?:password|passwd|pwd|secret)['\\"]?\\s*[:=]\\s*['\\"]([^'\\"]{8,})['\\"]`,severity:"medium",description:"Generic Password Assignment",keywords:["password","passwd","secret"],allowlist:["password123","changeme","example","placeholder","xxxxxxxx"],vectors:{hit:'password = "s3cr3t-Value!"',clean:'password = "changeme-now"'}},{name:"generic_api_key",pattern:`(?:api[_\\-]?key|apikey)['\\"]?\\s*[:=]\\s*['\\"]([A-Za-z0-9_\\-]{20,})['\\"]`,severity:"medium",description:"Generic API Key Assignment",keywords:["api_key","apikey"],vectors:{hit:'api_key = "AbCdEfGhIjKlMnOpQrStUvWx"',clean:'api_key = "short"'}},{name:"seal_link",pattern:"https://seal\\.net/(?:pro/)?s/[A-Za-z0-9_/-]{8,}#[A-Za-z0-9_-]{43}",severity:"critical",description:"SEAL link (it opens its seal)",keywords:["seal","seal.net/s/"],vectors:{hit:"https://seal.net/s/AbCd1234/Xy7Q#AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCde",clean:"https://seal.net/s/AbCd1234/Xy7Q"}}]},ri=ni.mime,X=class extends Error{constructor(e,t,n){super(t),this.name="OpenError",this.code=e,this.cause=n}},ai=32;async function Ln(e,t,n={}){let r;try{r=zo(t)}catch(h){throw h instanceof Mt?new X(h.code,h.message,h):h}if(r.shareCode===null)throw new X("url_invalid","share code missing from the URL path (/s/<seal_id>/<share_code>#<key>)");let{sealId:a,shareCode:s}=r;if(r.fragmentVariant!=="key"&&!n.seed)throw new X("targeted_fragment_invalid","this link is addressed to someone: pass their seed to open it");let o=n.seed,i=r.fragmentVariant==="targeted_x25519_v1"?r.fragment:n.wrap??null,l=r.fragmentVariant==="key"?V(r.fragment):i!==null&&o?await Ar(i,o,a):null,d=n.signal?{signal:n.signal}:{},p;try{p=Ns(await e.getMetadata(r.sealId,d))}catch(h){throw h instanceof ce&&(h.code==="not_found"||h.code==="revoked")?new X(h.code==="revoked"?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${h.code==="revoked"?"has been revoked":"was not found or has expired"}`,h):new X("metadata_failed",`reading seal ${r.sealId} failed: ${fn(h)}`,h)}if(p.revokedAt!==null)throw new X("seal_revoked",`seal ${r.sealId} has been revoked`);if(p.files.length===0)throw new X("seal_not_ready",`seal ${r.sealId} has no files available yet: the server verifies an upload before offering it. Retry in a few seconds.`);let f;try{let h=await e.getShareBlob(a,s,d);if(f=h.blob,l===null){if(h.wrap===null||!o)throw new X("url_no_fragment","the link carries no key and the server holds no wrap of it for this link");l=await Ar(h.wrap,o,a)}}catch(h){throw h instanceof X?h:h instanceof ce&&(h.code==="not_found"||h.code==="revoked")?new X(h.code==="revoked"?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${h.code==="revoked"?"has been revoked":"was not found"}`,h):new X("share_blob_fetch_failed",`share blob fetch failed: ${fn(h)}`,h)}let u;try{u=(await Gs(f,l)).file_keys}catch(h){throw new X("share_blob_decrypt_failed","the share blob does not open with this link \u2014 mistyped URL, or the link was revoked and minted again",h)}let _=await Promise.all(p.files.map(h=>li(h,u)));return{sealId:a,expiresAt:p.expiresAt,singleUse:p.singleUse,maxOpens:p.maxOpens,otpRequired:p.otpRequired,ndaRequired:p.ndaRequired,files:_}}async function Ar(e,t,n){try{return await jo(e,t,kn,n)}catch(r){let a=r instanceof Ee&&r.kind==="aead";throw new X(a?"targeted_decrypt_failed":"targeted_fragment_invalid",fn(r),r)}}async function fa(e,t,n={}){for(;;){let r;try{r=await e.getIntake(t,{...n,waitSeconds:ze.limits.INTAKE_WAIT_MAX_SECONDS})}catch(a){throw a instanceof ce&&a.code==="not_found"?new X("request_expired","the request expired before anybody answered",a):a}if(r.status==="expired")throw new X("request_expired","nobody answered before the request expired");if(r.status==="fulfilled"&&r.share_path&&r.fragment)return{sharePath:r.share_path,wrap:r.fragment}}}var si=64*1024;async function ha(e,t,n,r){let a=await Ln(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||_a(s.mime)!==n||s.size>si)throw new X("share_blob_corrupt",`the answer is not one ${n} file`);let i=await e.openDownload(a.sealId,{fileId:s.id},r.signal?{signal:r.signal}:{});if(!i.body)throw new X("share_blob_corrupt","the answer came without a body");let l=Bn(i.body,s.key,s.sha256Hex).stream.getReader(),d=[];for(let u=await l.read();!u.done;u=await l.read())d.push(u.value);let p=new Uint8Array(d.reduce((u,_)=>u+_.length,0)),f=0;for(let u of d)p.set(u,f),f+=u.length;return p}var oi=3e4,vr=new Map;async function ii(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&ui(r,t.bundle)||await e.putBundle(t.bundle,n)}async function Tr(e,t,n={}){let r=await Yt(t),a=`${e.baseUrl} ${r.address}`,s=vr.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await ii(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await Vo(t,o)};return vr.set(a,{proof:i,until:Date.parse(o.expires_at)-oi}),i}async function wt(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await Tr(e,t,a))}catch(s){if(!(s instanceof ce&&s.appCode==="intake.proof_required"))throw s;return r(await Tr(e,t,{...a,fresh:!0}))}}async function pa(e,t,n={}){let{legacyAddress:r}=await Yt(t);return wt(e,t,n.signal,async a=>{let s=await e.migrateInbox(a,{old_address:r},n),o=await qo(t,s.challenge,s.ts);return(await e.migrateInbox(a,{old_address:r,old_proof:o},n)).moved})}async function Pn(e,t,n={}){let r=n;return wt(e,t,n.signal,a=>e.listInbox(a,r))}async function ya(e,t,n,r={}){return wt(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function li(e,t){let n=e.sha256_hex?t[e.sha256_hex]:void 0,r={id:e.id,size:e.size,sha256Hex:e.sha256_hex};if(n===void 0)return{...r,name:Ht,mime:zt,secret:!1,key:null};let a;try{a=V(n)}catch(i){throw new X("share_blob_corrupt",`share blob carries a non-base64url key for ${e.sha256_hex}`,i)}if(a.length!==ai)throw new X("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${a.length} bytes`);let{name:s,mime:o}=await bo(e,a);return{...r,name:s,mime:o,secret:_a(o)===ri,key:a}}function _a(e){return(e.split(";")[0]??e).trim().toLowerCase()}function Bn(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=Bt.create(),o=0,i,l=new Promise((u,_)=>{i={resolve:u,reject:_}});l.catch(()=>{});let d=new TransformStream({transform(u,_){r(u.length),_.enqueue(u)}}),p=new TransformStream({transform(u,_){s.update(u),o+=u.length,_.enqueue(u)},flush(){a.fill(0),i.resolve({sizeBytes:o,sha256:di(s.digest())})}}),f=e.pipeThrough(d).pipeThrough(no(a,{expectedSha256Hex:n})).pipeThrough(p);return{stream:fi(f,i.reject,a),done:l}}function ci(e){return e instanceof Re?new X(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function di(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ui(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function fi(e,t,n){let r=e.getReader();return new ReadableStream({async pull(a){try{let{value:s,done:o}=await r.read();o?a.close():a.enqueue(s)}catch(s){let o=ci(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function fn(e){return e instanceof Error?e.message:String(e)}var hi="_",pi=200,yi=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);function _i(){if(typeof process<"u"&&process.platform)switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";case"android":return"android";default:return"unknown"}if(typeof navigator<"u"&&navigator.userAgent){let e=navigator.userAgent.toLowerCase();if(e.includes("win"))return"windows";if(e.includes("android"))return"android";if(e.includes("iphone")||e.includes("ipad")||e.includes("ipod"))return"ios";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"}function wi(e,t){let n=e.charCodeAt(0);if(n<32||n===127)return!1;switch(t){case"windows":return!/[<>:"/\\|?*]/.test(e);case"macos":case"ios":return!/[/:]/.test(e);case"linux":case"android":return e!=="/";default:return!/[<>:"/\\|?*]/.test(e)}}function gi(e){let t=e.split(".")[0].toUpperCase();return yi.has(t)}function wa(e,t={}){let{platform:n=_i(),replacement:r=hi,maxLength:a=pi,fallback:s="file"}=t;if(!e||!e.trim())return s;let o=e.normalize("NFC");o=o.trim(),o=o.replace(/^\.+|\.+$/g,""),o=[...o].map(d=>wi(d,n)?d:r).join("");let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${l}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${l})+|${l}+$`,"g"),""),(n==="windows"||n==="unknown")&&gi(o)&&(o=`${r}${o}`),o.length>a){let d=o.lastIndexOf(".");if(d>0&&d>o.length-10){let p=o.slice(d);o=o.slice(0,a-p.length)+p}else o=o.slice(0,a)}return!o||o===r?s:o}var ga={version:1,limits:{MAX_FILES_PER_SEAL:30,FREE_TIER_BYTES:1073741824,MAX_TOTAL_SIZE_BYTES:1073741824,MAX_FILE_SIZE_BYTES:10737418240,MAX_MULTIPART_FILE_SIZE_BYTES:10737418240,MAX_BLOB_SIZE:1048576,MAX_BLOB_BASE64_SIZE:1468006,MAX_MESSAGE_LENGTH:5e3,MAX_FILE_KEYS:1e4,MAX_ACTIVE_UPLOADS_PER_SEAL:10,MAX_OPENS_PER_SEAL_FREE:10,TIER_BYTES:{free:1073741824,"5gb":5368709120,"50gb":53687091200,"500gb":536870912e3},SEAL_TIERS:{"5gb":{bytes:5368709120,amount_cents:900,duration_days:90,name:"5 GB / 3 months",description:"One-time payment for 5 GB storage and 3 months TTL"},"50gb":{bytes:53687091200,amount_cents:2900,duration_days:180,name:"50 GB / 6 months",description:"One-time payment for 50 GB storage and 6 months TTL"},"500gb":{bytes:536870912e3,amount_cents:9900,duration_days:365,name:"500 GB / 12 months",description:"One-time payment for 500 GB storage and 12 months TTL"}},PRO_REGIONS:["eu-west","us-east","us-west","apac-southeast","apac-northeast"],ttl_options:["5m","30m","1h","1d","7d"],OTP_LENGTH:{min:6,max:10},USER_PASSWORD_MIN_LENGTH:8,INTAKE_TTL_DEFAULT_SECONDS:900,INTAKE_TTL_MAX_SECONDS:86400,INTAKE_WAIT_MAX_SECONDS:25,PAYMENT_WAIT_MAX_SECONDS:82800,ADDRESS_PROOF_TTL_SECONDS:300,INBOX_MAX_ITEMS:200,DRIVE_OPEN_TTL_SECONDS:300,DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES:67108864,DRIVE_PRESIGN_WINDOW_MIN_BYTES:8388608,DRIVE_PRESIGN_UNBOUND_TTL_SECONDS:30,DRIVE_WRITE_LEASE_SECONDS:7200,DRIVE_WRITE_BACK_SECONDS:5,VERSION_RETENTION_DAYS_DEFAULT:30,VERSION_KEEP_MIN:10,GRANT_WORKLOAD_MAX_TTL_DAYS:90,SENSOR_OPENS_PER_MINUTE_DEFAULT:120,SENSOR_BYTES_PER_MINUTE_DEFAULT:2147483648,SENSOR_SECRETS_PER_MINUTE_DEFAULT:20,SENSOR_NOVELTY_WINDOW_DAYS:30,SENSOR_HOLD_TTL_SECONDS:86400,SENSOR_BASELINE_MIN_HOURS:72,SENSOR_GROWTH_BYTES_PER_DAY_DEFAULT:107374182400}};var K=class e extends Error{code;status;details;constructor(t,n,r,a=null,s){super(t,s),this.name="SealError",this.code=n,this.status=r,this.details=a,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},mi={url_invalid:"VALIDATION_ERROR",url_no_fragment:"VALIDATION_ERROR",targeted_fragment_invalid:"INVALID_KEY",targeted_decrypt_failed:"INVALID_KEY",seal_not_found:"RESOURCE_NOT_FOUND",seal_revoked:"RESOURCE_NOT_FOUND",share_link_not_found:"RESOURCE_NOT_FOUND",share_link_revoked:"RESOURCE_NOT_FOUND",request_expired:"RESOURCE_NOT_FOUND",seal_not_ready:"SERVICE_UNAVAILABLE",metadata_failed:"SERVICE_UNAVAILABLE",share_blob_fetch_failed:"SERVICE_UNAVAILABLE",share_blob_decrypt_failed:"DECRYPTION_ERROR",share_blob_corrupt:"DECRYPTION_ERROR",integrity_check_failed:"DECRYPTION_ERROR",client_outdated:"CLIENT_OUTDATED"};function de(e,t,n=null){if(e instanceof K)return e;if(e instanceof X){let r=e.cause instanceof ce?e.cause.status:400;return new K(e.message,mi[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof ce){let r=e.appCode==="client.outdated"?"CLIENT_OUTDATED":e.appCode==="intake.proof_required"?"AUTH_INVALID_KEY":e.code==="not_found"||e.code==="revoked"?"RESOURCE_NOT_FOUND":e.code==="auth"?"AUTH_INSUFFICIENT_SCOPE":e.code==="rate_limited"?"RATE_LIMITED":e.code==="transient"?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR";return new K(e.detail??t,r,e.status,n,{cause:e})}return new K(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}var Ol=ga.limits.ttl_options,Vt=class{api;baseUrl;shareUrlBase;credentials;constructor(t){this.baseUrl=(t?.apiUrl||"").replace(/\/$/,""),this.shareUrlBase=(t?.shareUrl||"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.credentials=t?.credentials,this.api=new yt({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){if(t.nda&&!t.ownerEmail)throw new K("ownerEmail is required when nda=true","VALIDATION_ERROR",400);if(t.tier&&!t.onPaymentRequired)throw new K("onPaymentRequired is required with tier","VALIDATION_ERROR",400);let n=(b,F)=>{if(F!==void 0)try{return oa(F)}catch(B){throw new K(`${b}: ${B instanceof Error?B.message:String(B)}`,"VALIDATION_ERROR",400)}},r=n("to",t.to),a=n("owner",t.owner),s=t.signal?{signal:t.signal}:{},o=async b=>{let F=await this.api.getBundle(b,s);return F&&await ia(F,b)?F:null},i=null;if(r){try{i=await o(r)}catch(b){throw de(b,"Failed to read the recipient key")}if(!i)throw new K(`to: ${r} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let l=a?await o(a).catch(()=>null):null,d=t.keyPair?V(t.keyPair.secretKey):null,p=b=>d?wt(this.api,d,t.signal,b):b(),f=t.mimeType||t.file instanceof File&&t.file.type||"application/octet-stream",u;if(t.file instanceof File&&t.file.name===t.filename&&t.file.type===f)u=t.file;else if(t.file instanceof Blob)u=new File([t.file],t.filename,{type:f});else if(t.file instanceof Uint8Array){let b=t.file.buffer.slice(t.file.byteOffset,t.file.byteOffset+t.file.byteLength);u=new File([b],t.filename,{type:f})}else u=new File([t.file],t.filename,{type:f});let _=Mr(),h=ne(_),m=await Nr(_),g=_n(),N=ne(g),D={baseUrl:this.baseUrl,auth:{kind:"none"},ttl:t.ttl,ownerTokenHash:m,ownerToken:h,...this.credentials!==void 0?{credentials:this.credentials}:{},...t.otp!==void 0?{otp:t.otp}:{},...t.nda!==void 0?{nda:t.nda}:{},...t.nda&&t.ownerEmail!==void 0?{ownerEmail:t.ownerEmail}:{},...t.singleUse!==void 0?{singleUse:t.singleUse}:{},...t.geoAllowlist!==void 0?{geo:t.geoAllowlist}:{},...t.maxOpens!==void 0?{maxOpens:t.maxOpens}:{},...t.tier!==void 0?{tier:t.tier}:{}},k=null,P=b=>({sealId:b,ownerToken:h,ownerLinkKey:N}),U=t.message?.trim()?t.message:void 0,I=!1;try{let b=t.onProgress,F={...b?{onProgress:re=>b({phase:re.phase,percent:re.percent})}:{},...t.signal?{signal:t.signal}:{},onRegistered:async(re,ee)=>{k=re;let Ae=new Map(ee.map(fe=>[fe.sha256_hex,ne(fe.key)])),ue=ne(await Ur(h,Ae,g,U));if(a&&l){let fe=await Rn(g,l,aa,re);I=await p(_e=>this.api.writeOwnerBlob(re,h,ue,{...s,to:a,fragment:fe,label:"sealnet",..._e?{sender:_e}:{}})).then(()=>!0,()=>!1)}try{I||await this.api.writeOwnerBlob(re,h,ue,s)}catch(fe){throw de(fe,"Failed to store encrypted blob",P(re))}}},B,A;try{B=await Zr(D,u,Gt,F),A=B.expiresAt}catch(re){let ee=Jr(re);if(!ee||!t.tier||!t.onPaymentRequired)throw re;let Ae=t.signal?{signal:t.signal}:{};await t.onPaymentRequired(await this.api.createCheckout(ee.sealId,h,t.tier,Ae));let ue=Qr(ee instanceof mn?ee.expiresAt:void 0),fe=await ea(this.api,ee.sealId,h,{deadline:ue,...Ae});if(!fe)throw await this.api.revoke(ee.sealId,h).catch(()=>{}),new K("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,P(ee.sealId));B=await ee.resume(F),A=fe.expires_at}if(!A)throw new K(`Seal ${B.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,P(B.sealId));let E=new Map;E.set(B.sha256_hex,ne(B.encryptionKey));let C=_n(),ie=ne(C),G=await Fr(E,C,U),Z=r&&i?await Rn(C,i,kn,B.sealId):null,Q;try{let re=ne(G);Q=r&&Z?await p(ee=>this.api.createShareLink(B.sealId,h,re,{...s,to:r,fragment:Z,label:"sealnet",...ee?{sender:ee}:{}})):await this.api.createShareLink(B.sealId,h,re,s)}catch(re){throw de(re,"Seal created but share link mint failed",P(B.sealId))}let Xe=ra(B.sealId,Q,ie),Te=`${this.shareUrlBase}${Z?Xe.split("#")[0]:Xe}`,Ze=`${this.shareUrlBase}${na(B.sealId,N)}`,Je=Ie(B.encryptionKey);return{sealId:B.sealId,shareUrl:Te,ownerUrl:Ze,ownerToken:h,expiresAt:A,encryptionKey:Je,fileId:B.fileId,delivered:Z!==null,ownerCopy:I}}catch(b){if(b instanceof K)throw b;if(k){let F=b instanceof Error?b.message:String(b);throw new K(`Seal ${k} was created but the create flow was interrupted: ${F}`,"INTERNAL_ERROR",500,P(k),{cause:b})}throw b}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw de(a,"Failed to revoke seal")}}};async function ba(e,t,n){let r=await import("fs/promises"),a=await import("path");await r.mkdir(t,{recursive:!0});let s=Array.from(crypto.getRandomValues(new Uint8Array(6)),d=>d.toString(16).padStart(2,"0")).join(""),o=a.join(t,`.seal-partial-${s}`),i=await r.open(o,"wx",384),l=!1;try{await e.stream.pipeTo(new WritableStream({async write(_){await i.write(_)}}));let{sizeBytes:d,sha256:p}=await e.done;await i.sync(),await i.close();let f=a.extname(n),u=n.slice(0,n.length-f.length);for(let _=0;_<1e3;_++){let h=a.join(t,_===0?n:`${u} (${_})${f}`);try{await r.link(o,h)}catch(m){if(m.code==="EEXIST")continue;throw m}return await r.unlink(o),l=!0,{path:h,sizeBytes:d,sha256:p}}throw new Error(`no free name for ${n} in ${t}`)}finally{l||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}async function ma(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await Ln(e,t,{...n.keyPair?{seed:V(n.keyPair.secretKey)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new K("This seal asks for an NDA signature: open it in a browser","AUTH_INSUFFICIENT_SCOPE",403);let o=null;if(s.otpRequired){if(!n.password)throw new K("This seal is password-protected: pass `password`","AUTH_INVALID_KEY",401);o=(await e.verifyOtp(s.sealId,{code:n.password},a)).sessionCookie}let i=s.files.filter(f=>f.key!==null&&f.sha256Hex!==null),l=i.reduce((f,u)=>f+u.size,0),d=0;return{seal:s,covered:i,read:async f=>{let u=await e.openDownload(s.sealId,{fileId:f.id,...o?{sessionCookie:o}:{}},a);if(!u.body)throw new K(`Download of ${f.name} returned no body`,"INTERNAL_ERROR",u.status);return Bn(u.body,f.key,f.sha256Hex,_=>{d+=_,n.onProgress?.(d,l)})}}}async function Dn(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await ma(e,t,n,r);return{sealId:a.sealId,expiresAt:a.expiresAt,files:s.map(i=>({name:i.name,mime:i.mime,size:i.size,secret:i.secret,read:()=>o(i).catch(l=>Promise.reject(de(l,"Download failed")))}))}}catch(a){throw de(a,"Failed to open the link")}}async function Cn(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i}=await ma(e,t,r,a),l=[];for(let d of o){let p=await ba(await i(d),n,wa(d.name));l.push({name:d.name,mime:d.mime,secret:d.secret,...p})}return{sealId:s.sealId,expiresAt:s.expiresAt,files:l}}catch(s){throw de(s,"Failed to open the link")}}async function Ea(e,t,n){try{let r=await e.createIntake({recipientBundle:n.recipientBundle,label:n.label??"sealnet",what:n.what,...n.whereUrl?{whereUrl:n.whereUrl}:{},...n.kind?{kind:n.kind}:{},...n.ttl!==void 0?{ttlSeconds:n.ttl}:{},...n.to!==void 0?{to:n.to}:{}},n.signal?{signal:n.signal}:{});return{intakeId:r.id,url:`${t}/i/${r.id}`,words:(await On(V(n.recipientBundle))).words,expiresAt:r.expires_at}}catch(r){throw de(r,"Failed to create the request")}}async function Mn(e,t,n){try{return await fa(e,t,n?{signal:n}:{})}catch(r){throw de(r,"Failed to wait for the request")}}async function Sa(e,t,n){let r;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:da,kind:"pair"},n.signal?{signal:n.signal}:{})}catch(s){throw de(s,"Failed to create the pairing request")}let a=async()=>{let{sharePath:s,wrap:o}=await Mn(e,r.id,n.signal);try{let i=await ha(e,`${t}${s}`,ca,{seed:V(n.keyPair.secretKey),wrap:o,...n.signal?{signal:n.signal}:{}}),{bundle:l,name:d}=ua(i);return{address:(await On(l)).address,name:d}}catch(i){throw de(i,"The answer of the inbox did not open")}};return{url:`${t}/i/${r.id}`,words:n.keyPair.words,expiresAt:r.expires_at,wait:a}}async function Aa(){let e=sa(),{address:t,bundle:n,words:r}=await Yt(e);return{secretKey:ne(e),address:t,bundle:ne(n),words:r}}async function va(e,t){let n=V(t.keyPair.secretKey),r=Date.now()+(t.wait??0)*1e3;try{for(await pa(e,n,t.signal?{signal:t.signal}:{}).catch(()=>0);;){let a=Math.ceil((r-Date.now())/1e3),s=await Pn(e,n,{...a>0?{waitSeconds:a}:{},...t.seen!==void 0?{seen:t.seen}:{},...t.signal?{signal:t.signal}:{}});if((t.seen!==void 0?s.version!==t.seen:s.items.length>0)||Date.now()>=r)return{version:s.version,items:s.items.map(i=>({id:i.id,fromWords:i.sender===null?null:la(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw de(a,"Failed to read the inbox")}}async function Ta(e,t,n,r){let a;try{a=(await Pn(e,V(r.keyPair.secretKey),r.signal?{signal:r.signal}:{})).items}catch(o){throw de(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new K(`${n.id} is not in the inbox: it was revoked, expired or removed`,"RESOURCE_NOT_FOUND",404);return{url:`${t}${s.path}`,wrap:s.fragment}}async function ka(e,t,n){try{await ya(e,V(n.keyPair.secretKey),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw de(r,"Failed to remove the item")}}var[Ei="",xa=""]="sdk-web/2.0.1".split("/");typeof globalThis.process?.versions?.node!="string"&&Jn(be);var Nn=class{seals;api;site;constructor(t={}){Br(Ei,xa);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new Vt({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new yt({baseUrl:n,credentials:"omit"})}async send(t){return this.seals.create(t)}async open(t,n={}){let{to:r,...a}=n,s;if(typeof t=="string")s={url:t,wrap:null};else if(a.keyPair)s=await Ta(this.api,this.site,t,{keyPair:a.keyPair,...a.signal?{signal:a.signal}:{}});else throw new K("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?Cn(this.api,s.url,r,a,s.wrap):Dn(this.api,s.url,a,s.wrap)}async inbox(t){return va(this.api,t)}async dismiss(t,n){return ka(this.api,t,n)}async request(t){return Ea(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await Mn(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?Cn(this.api,i,s,o,a):Dn(this.api,i,o,a)}async pair(t){return Sa(this.api,this.site,t)}async keygen(){return Aa()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},Si=xa;return Ka(Ai);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js:
@@ -1 +1 @@
1
- sha384-9ZeXH0khtFG26aeQTB4tALMlc3cA8Yz29khqFiYdyA2qZoSAHPkPh2NtwBna2q50
1
+ sha384-vOK/HzVVeGOp2usxeOgpmNBHovi8511y63zoXuNCfbo8wkRbmoLBiPeoTAHqZ4X1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sealnet",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Official SEAL SDK: send and open end-to-end encrypted files and secrets, and ask a person for one, from any website or server. The key never reaches SEAL.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",