sealnet 3.1.0 → 3.1.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/v3.1.0/seal.js"
24
- integrity="sha384-cwrpNTtrwmKvOqEIX3B0BacbxDFEx2X6MfoDvNFtjLemefebcp8HZ/YyIHAw5/9h"
23
+ src="https://seal.net/sdk/v3.1.1/seal.js"
24
+ integrity="sha384-4pS2jav0xvLH34aYt9AP/qDFunAYLF/U3j/CxEAn1L0LBBq3rPDaFRFcPxfaFYz3"
25
25
  crossorigin="anonymous"
26
26
  ></script>
27
27
  <script>
@@ -71,7 +71,7 @@ const result = await seal.send({
71
71
  ttl: '1d',
72
72
  otp: 'secret42', // recipient must enter this password
73
73
  nda: true, // recipient must sign an NDA first
74
- ownerEmail: 'me@corp.com', // required when nda: true
74
+ ownerEmail: 'me@corp.com', // a letter each time it is opened; required when nda: true
75
75
  singleUse: true, // first download destroys the file
76
76
  maxOpens: 3, // or: cap total downloads
77
77
  geoAllowlist: ['DE', 'CH'], // or: restrict by country
@@ -1,4 +1,4 @@
1
- sealnet 3.1.0 — third-party notices
1
+ sealnet 3.1.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/v3.1.0/seal_crypto.wasm", integrity: "sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O" };
40
+ var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v3.1.1/seal_crypto.wasm", integrity: "sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O" };
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();
@@ -6583,7 +6583,7 @@ function createOptions(rules, keys, tier) {
6583
6583
  ...tier ? { tier } : {},
6584
6584
  ...rules.otp ? { otp: rules.otp } : {},
6585
6585
  nda: rules.nda ?? false,
6586
- ...rules.nda && rules.ownerEmail ? { ownerEmail: rules.ownerEmail } : {},
6586
+ ...rules.ownerEmail ? { ownerEmail: rules.ownerEmail } : {},
6587
6587
  singleUse: rules.singleUse ?? false,
6588
6588
  ...!rules.singleUse && rules.maxOpens ? { maxOpens: rules.maxOpens } : {},
6589
6589
  ...rules.geo && rules.geo.length > 0 ? { geo: rules.geo } : {},
@@ -7477,7 +7477,7 @@ async function dismissItem(api, item, opts) {
7477
7477
  }
7478
7478
 
7479
7479
  // src/index.ts
7480
- var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/3.1.0".split("/");
7480
+ var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/3.1.1".split("/");
7481
7481
  if (typeof globalThis.process?.versions?.node !== "string") {
7482
7482
  configureWasm(define_SEAL_WASM_default);
7483
7483
  }
package/dist/index.d.cts CHANGED
@@ -78,7 +78,7 @@ interface CreateAnonymousSealOptions {
78
78
  otp?: string | undefined;
79
79
  /** Require NDA signature before download */
80
80
  nda?: boolean;
81
- /** Owner email (required if nda=true) */
81
+ /** Your email: a letter each time the seal is opened, with when and from which country. Required with `nda`: the signed agreement comes here too. */
82
82
  ownerEmail?: string;
83
83
  /**
84
84
  * The document the recipient signs for (with `nda`, instead of `message`): sent last, marked as the NDA's. The
package/dist/index.d.ts CHANGED
@@ -78,7 +78,7 @@ interface CreateAnonymousSealOptions {
78
78
  otp?: string | undefined;
79
79
  /** Require NDA signature before download */
80
80
  nda?: boolean;
81
- /** Owner email (required if nda=true) */
81
+ /** Your email: a letter each time the seal is opened, with when and from which country. Required with `nda`: the signed agreement comes here too. */
82
82
  ownerEmail?: string;
83
83
  /**
84
84
  * The document the recipient signs for (with `nda`, instead of `message`): sent last, marked as the NDA's. The
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/v3.1.0/seal_crypto.wasm", integrity: "sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O" };
2
+ var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v3.1.1/seal_crypto.wasm", integrity: "sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O" };
3
3
 
4
4
  var __defProp = Object.defineProperty;
5
5
  var __export = (target, all) => {
@@ -6542,7 +6542,7 @@ function createOptions(rules, keys, tier) {
6542
6542
  ...tier ? { tier } : {},
6543
6543
  ...rules.otp ? { otp: rules.otp } : {},
6544
6544
  nda: rules.nda ?? false,
6545
- ...rules.nda && rules.ownerEmail ? { ownerEmail: rules.ownerEmail } : {},
6545
+ ...rules.ownerEmail ? { ownerEmail: rules.ownerEmail } : {},
6546
6546
  singleUse: rules.singleUse ?? false,
6547
6547
  ...!rules.singleUse && rules.maxOpens ? { maxOpens: rules.maxOpens } : {},
6548
6548
  ...rules.geo && rules.geo.length > 0 ? { geo: rules.geo } : {},
@@ -7436,7 +7436,7 @@ async function dismissItem(api, item, opts) {
7436
7436
  }
7437
7437
 
7438
7438
  // src/index.ts
7439
- var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/3.1.0".split("/");
7439
+ var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/3.1.1".split("/");
7440
7440
  if (typeof globalThis.process?.versions?.node !== "string") {
7441
7441
  configureWasm(define_SEAL_WASM_default);
7442
7442
  }
@@ -1,6 +1,6 @@
1
- /*! sealnet v3.1.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 Ts=Object.create;var Pt=Object.defineProperty;var Is=Object.getOwnPropertyDescriptor;var Os=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var cr=(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 Ls=(e,t)=>{for(var n in t)Pt(e,n,{get:t[n],enumerable:!0})},dr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Os(t))!Ps.call(e,a)&&a!==n&&Pt(e,a,{get:()=>t[a],enumerable:!(r=Is(t,a))||r.enumerable});return e};var ur=(e,t,n)=>(n=e!=null?Ts(Rs(e)):{},dr(t||!e||!e.__esModule?Pt(n,"default",{value:e,enumerable:!0}):n,e)),Ds=e=>dr(Pt({},"__esModule",{value:!0}),e);var Gl={};Ls(Gl,{SealClient:()=>rr,SealError:()=>z,VERSION:()=>zl});var me={url:"https://seal.net/sdk/v3.1.0/seal_crypto.wasm",integrity:"sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O"};var fo={},Cs=Object.defineProperty,Ms=(e,t)=>{for(var n in t)Cs(e,n,{get:t[n],enumerable:!0})},gr={};Ms(gr,{ContractTermsBuilder:()=>pn,WasmIdentity:()=>_n,default:()=>to,init:()=>Bs,initSync:()=>eo,wasm_approval_message:()=>Us,wasm_bundle_address:()=>Fs,wasm_bundle_verify_for_address:()=>$s,wasm_contract_message:()=>Ws,wasm_contract_message_v2:()=>Hs,wasm_ed25519_verify:()=>Ks,wasm_sealbox_wrap:()=>zs,wasm_summary_message:()=>Gs,wasm_unwrap_file_key:()=>js,wasm_wrap_file_key:()=>Ys});var pn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,hr.unregister(this),e}free(){let e=this.__destroy_into_raw();l.__wbg_contracttermsbuilder_free(e,0)}digest(){let e,t;try{let a=this.__destroy_into_raw(),s=l.__wbindgen_add_to_stack_pointer(-16);l.contracttermsbuilder_digest(s,a);var n=b().getInt32(s+0,!0),r=b().getInt32(s+4,!0);return e=n,t=r,Re(n,r)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(e,t,1)}}field(e,t,n,r,a,s,o,i,c,d){try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(i,l.__wbindgen_export3,l.__wbindgen_export4),y=A,T=k(c,l.__wbindgen_export3,l.__wbindgen_export4),x=A;l.contracttermsbuilder_field(h,this.__wbg_ptr,p,g,S,_,n,r,a,s,o,E,y,T,x,d);var f=b().getInt32(h+0,!0),u=b().getInt32(h+4,!0);if(u)throw N(f)}finally{l.__wbindgen_add_to_stack_pointer(16)}}filled(e,t){try{let a=l.__wbindgen_add_to_stack_pointer(-16),s=k(e,l.__wbindgen_export3,l.__wbindgen_export4),o=A,i=k(t,l.__wbindgen_export3,l.__wbindgen_export4),c=A;l.contracttermsbuilder_filled(a,this.__wbg_ptr,s,o,i,c);var n=b().getInt32(a+0,!0),r=b().getInt32(a+4,!0);if(r)throw N(n)}finally{l.__wbindgen_add_to_stack_pointer(16)}}constructor(e){var t=dt(e)?0:k(e,l.__wbindgen_export3,l.__wbindgen_export4),n=A;let r=l.contracttermsbuilder_new(t,n);return this.__wbg_ptr=r,hr.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(pn.prototype[Symbol.dispose]=pn.prototype.free);var _n=class Lt{static __wrap(t){let n=Object.create(Lt.prototype);return n.__wbg_ptr=t,fr.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,fr.unregister(this),t}free(){let t=this.__destroy_into_raw();l.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.wasmidentity_address(s,this.__wbg_ptr);var r=b().getInt32(s+0,!0),a=b().getInt32(s+4,!0);return t=r,n=a,Re(r,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(t,n,1)}}bundle(){let t=l.wasmidentity_bundle(this.__wbg_ptr);return N(t)}static fromSeed32(t){try{let s=l.__wbindgen_add_to_stack_pointer(-16),o=le(t,l.__wbindgen_export3),i=A;l.wasmidentity_fromSeed32(s,o,i);var n=b().getInt32(s+0,!0),r=b().getInt32(s+4,!0),a=b().getInt32(s+8,!0);if(a)throw N(r);return Lt.__wrap(n)}finally{l.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A;l.wasmidentity_fromSeed64(o,i,c,n);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return Lt.__wrap(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(n,l.__wbindgen_export3),c=A;l.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,c);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}open(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(t,l.__wbindgen_export3),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_open(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signApproval(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=k(t,l.__wbindgen_export3,l.__wbindgen_export4),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_signApproval(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signContract(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=k(t,l.__wbindgen_export3,l.__wbindgen_export4),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_signContract(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signContractV2(t,n,r,a){try{let c=l.__wbindgen_add_to_stack_pointer(-16),d=k(t,l.__wbindgen_export3,l.__wbindgen_export4),f=A,u=k(n,l.__wbindgen_export3,l.__wbindgen_export4),h=A,p=k(r,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(a,l.__wbindgen_export3,l.__wbindgen_export4),_=A;l.wasmidentity_signContractV2(c,this.__wbg_ptr,d,f,u,h,p,g,S,_);var s=b().getInt32(c+0,!0),o=b().getInt32(c+4,!0),i=b().getInt32(c+8,!0);if(i)throw N(o);return N(s)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signSummary(t,n,r,a){try{let c=l.__wbindgen_add_to_stack_pointer(-16),d=k(t,l.__wbindgen_export3,l.__wbindgen_export4),f=A,u=k(n,l.__wbindgen_export3,l.__wbindgen_export4),h=A,p=k(r,l.__wbindgen_export3,l.__wbindgen_export4),g=A;l.wasmidentity_signSummary(c,this.__wbg_ptr,d,f,u,h,p,g,a);var s=b().getInt32(c+0,!0),o=b().getInt32(c+4,!0),i=b().getInt32(c+8,!0);if(i)throw N(o);return N(s)}finally{l.__wbindgen_add_to_stack_pointer(16)}}userProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A,d=le(n,l.__wbindgen_export3),f=A;l.wasmidentity_userProof(o,this.__wbg_ptr,i,c,d,f);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.wasmidentity_words(s,this.__wbg_ptr);var r=b().getInt32(s+0,!0),a=b().getInt32(s+4,!0);return t=r,n=a,Re(r,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A,d=le(n,l.__wbindgen_export3),f=A;l.wasmidentity_workloadProof(o,this.__wbg_ptr,i,c,d,f);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(_n.prototype[Symbol.dispose]=_n.prototype.free);function Bs(){l.init()}function Us(e,t,n){let r,a;try{let u=l.__wbindgen_add_to_stack_pointer(-16),h=k(e,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(t,l.__wbindgen_export3,l.__wbindgen_export4),S=A,_=k(n,l.__wbindgen_export3,l.__wbindgen_export4),E=A;l.wasm_approval_message(u,h,p,g,S,_,E);var s=b().getInt32(u+0,!0),o=b().getInt32(u+4,!0),i=b().getInt32(u+8,!0),c=b().getInt32(u+12,!0),d=s,f=o;if(c)throw d=0,f=0,N(i);return r=d,a=f,Re(d,f)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(r,a,1)}}function Fs(e){try{let a=l.__wbindgen_add_to_stack_pointer(-16),s=le(e,l.__wbindgen_export3),o=A;l.wasm_bundle_address(a,s,o);var t=b().getInt32(a+0,!0),n=b().getInt32(a+4,!0),r=b().getInt32(a+8,!0);if(r)throw N(n);return N(t)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function $s(e,t){let n=le(e,l.__wbindgen_export3),r=A,a=k(t,l.__wbindgen_export3,l.__wbindgen_export4),s=A;return l.wasm_bundle_verify_for_address(n,r,a,s)!==0}function Ws(e,t,n){let r,a;try{let u=l.__wbindgen_add_to_stack_pointer(-16),h=k(e,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(t,l.__wbindgen_export3,l.__wbindgen_export4),S=A,_=k(n,l.__wbindgen_export3,l.__wbindgen_export4),E=A;l.wasm_contract_message(u,h,p,g,S,_,E);var s=b().getInt32(u+0,!0),o=b().getInt32(u+4,!0),i=b().getInt32(u+8,!0),c=b().getInt32(u+12,!0),d=s,f=o;if(c)throw d=0,f=0,N(i);return r=d,a=f,Re(d,f)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(r,a,1)}}function Hs(e,t,n,r){let a,s;try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(n,l.__wbindgen_export3,l.__wbindgen_export4),y=A,T=k(r,l.__wbindgen_export3,l.__wbindgen_export4),x=A;l.wasm_contract_message_v2(h,p,g,S,_,E,y,T,x);var o=b().getInt32(h+0,!0),i=b().getInt32(h+4,!0),c=b().getInt32(h+8,!0),d=b().getInt32(h+12,!0),f=o,u=i;if(d)throw f=0,u=0,N(c);return a=f,s=u,Re(f,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(a,s,1)}}function Ks(e,t,n){let r=le(e,l.__wbindgen_export3),a=A,s=le(t,l.__wbindgen_export3),o=A,i=le(n,l.__wbindgen_export3),c=A;return l.wasm_ed25519_verify(r,a,s,o,i,c)!==0}function zs(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_sealbox_wrap(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function Gs(e,t,n,r){let a,s;try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(n,l.__wbindgen_export3,l.__wbindgen_export4),y=A;l.wasm_summary_message(h,p,g,S,_,E,y,r);var o=b().getInt32(h+0,!0),i=b().getInt32(h+4,!0),c=b().getInt32(h+8,!0),d=b().getInt32(h+12,!0),f=o,u=i;if(d)throw f=0,u=0,N(c);return a=f,s=u,Re(f,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(a,s,1)}}function js(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_unwrap_file_key(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function Ys(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_wrap_file_key(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function wr(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof K(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=K(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof K(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return K(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Re(t,n))},__wbg_call_a41d6421b30a32c5:function(){return lt(function(t,n,r){let a=K(t).call(K(n),K(r));return re(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=K(t).crypto;return re(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Re(t,n))}finally{l.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return lt(function(t,n){K(t).getRandomValues(K(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return K(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=K(t).msCrypto;return re(n)},__wbg_new_227d7c05414eb861:function(){let t=new Error;return re(t)},__wbg_new_2fad8ca02fd00684:function(){let t=new Object;return re(t)},__wbg_new_from_slice_5a173c243af2e823:function(t,n){let r=new Uint8Array(hn(t,n));return re(r)},__wbg_new_with_length_9011f5da794bf5d9:function(t){let n=new Uint8Array(t>>>0);return re(n)},__wbg_node_84ea875411254db1:function(t){let n=K(t).node;return re(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=K(t).process;return re(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(hn(t,n),K(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return lt(function(t,n){K(t).randomFillSync(N(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return lt(function(){let t=module.require;return re(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return lt(function(t,n,r){return Reflect.set(K(t),K(n),K(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=K(n).stack,a=k(r,l.__wbindgen_export3,l.__wbindgen_export4),s=A;b().setInt32(t+4,s,!0),b().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return dt(t)?0:re(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return dt(t)?0:re(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return dt(t)?0:re(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return dt(t)?0:re(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=K(t).subarray(n>>>0,r>>>0);return re(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=K(t).versions;return re(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=hn(t,n);return re(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Re(t,n);return re(r)},__wbindgen_object_clone_ref:function(t){let n=K(t);return re(n)},__wbindgen_object_drop_ref:function(t){N(t)}}}}var hr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbg_contracttermsbuilder_free(e,1)),fr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbg_wasmidentity_free(e,1));function re(e){ut===De.length&&De.push(De.length+1);let t=ut;return ut=De[t],De[t]=e,t}function Vs(e){e<1028||(De[e]=ut,ut=e)}function hn(e,t){return e=e>>>0,qe().subarray(e/1,e/1+t)}var Ge=null;function b(){return(Ge===null||Ge.buffer.detached===!0||Ge.buffer.detached===void 0&&Ge.buffer!==l.memory.buffer)&&(Ge=new DataView(l.memory.buffer)),Ge}function Re(e,t){return qs(e>>>0,t)}var ct=null;function qe(){return(ct===null||ct.byteLength===0)&&(ct=new Uint8Array(l.memory.buffer)),ct}function K(e){return De[e]}function lt(e,t){try{return e.apply(this,t)}catch(n){l.__wbindgen_export(re(n))}}var De=new Array(1024).fill(void 0);De.push(void 0,null,!0,!1);var ut=De.length;function dt(e){return e==null}function le(e,t){let n=t(e.length*1,1)>>>0;return qe().set(e,n/1),A=e.length,n}function k(e,t,n){if(n===void 0){let i=ht.encode(e),c=t(i.length,1)>>>0;return qe().subarray(c,c+i.length).set(i),A=i.length,c}let r=e.length,a=t(r,1)>>>0,s=qe(),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=qe().subarray(a+o,a+r),c=ht.encodeInto(e,i);o+=c.written,a=n(a,r,o,1)>>>0}return A=o,a}function N(e){let t=K(e);return Vs(e),t}var Dt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Dt.decode();var Xs=2146435072,fn=0;function qs(e,t){return fn+=t,fn>=Xs&&(Dt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Dt.decode(),fn=t),Dt.decode(qe().subarray(e,e+t))}var ht=new TextEncoder;"encodeInto"in ht||(ht.encodeInto=function(e,t){let n=ht.encode(e);return t.set(n),{read:e.length,written:n.length}});var A=0,Zs,Js,l;function br(e,t){return Js=e,l=e.exports,Zs=t,Ge=null,ct=null,l}async function Qs(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 eo(e){if(l!==void 0)return l;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=wr();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return br(n,e)}async function to(e){if(l!==void 0)return l;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=wr();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Qs(await e,t);return br(n,r)}var no="seal_crypto.wasm",xe=null,Nt=null,Xe=null;function mr(e){if(Nt||Xe)throw new Error("configureWasm: the WASM is already loaded or loading");xe=e}function Er(){return globalThis.navigator?.userAgent==="Cloudflare-Workers"}function ro(){return typeof globalThis.process?.versions?.node=="string"&&!Er()}async function pr(e){let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}async function ao(){if(xe&&"module"in xe)return xe.module;if(xe&&"url"in xe)return fetch(xe.url,xe.integrity?{integrity:xe.integrity}:{});if(xe&&"path"in xe)return pr(xe.path);if(ro())return pr(new URL(no,fo.url));throw new Error(Er()?"seal crypto core: a Worker compiles no WASM from bytes \u2014 call configureWasm({ module }) with the imported .wasm":"sealnet: no WASM source in this browser (a broken build — reinstall sealnet)")}async function ft(){if(Nt)return Nt;if(Xe)return Xe;Xe=(async()=>{let e=gr;return await e.default({module_or_path:await ao()}),typeof e.init=="function"&&e.init(),Nt=e,e})();try{return await Xe}catch(e){throw Xe=null,e}}var _r=32768,yr=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function so(e){let t="";for(let n=0;n<e.length;n+=_r){let r=e.subarray(n,Math.min(n+_r,e.length));t+=String.fromCharCode.apply(null,r)}return t}function oo(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function io(e){let t=`${e.length} characters`;if(typeof atob<"u")try{return atob(e)}catch(n){throw new yr(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new yr(`Invalid base64 encoding: ${n.message}`,t)}}function lo(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function co(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function uo(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ne(e){return lo(so(e))}function ae(e){return uo(Ne(e))}function Ct(e){return oo(io(e))}function ue(e){return Ct(co(e))}async function ho(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 Ze(e){let t=await ho(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function po(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Bt(e,...t){if(!po(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 yn(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 Sr(e,t){Bt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function pt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ut(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ie(e,t){return e<<32-t|e>>>t}function _o(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function gn(e){return typeof e=="string"&&(e=_o(e)),Bt(e),e}var Mt=class{};function Ar(e){let t=r=>e().update(gn(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function yo(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),c=r?4:0,d=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+d,i,r)}function vr(e,t,n){return e&t^~e&n}function xr(e,t,n){return e&t^e&n^t&n}var Ft=class extends Mt{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=Ut(this.buffer)}update(t){yn(this),t=gn(t),Bt(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 c=Ut(t);for(;a<=s-o;o+=a)this.process(c,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){yn(this),Sr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,pt(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let u=o;u<a;u++)n[u]=0;yo(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Ut(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,f=this.get();if(d>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<d;u++)i.setUint32(4*u,f[u],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()}},Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var go=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]),Ue=new Uint32Array(64),wn=class extends Ft{constructor(t=32){super(64,t,8,!1),this.A=Ce[0]|0,this.B=Ce[1]|0,this.C=Ce[2]|0,this.D=Ce[3]|0,this.E=Ce[4]|0,this.F=Ce[5]|0,this.G=Ce[6]|0,this.H=Ce[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:c}=this;return[t,n,r,a,s,o,i,c]}set(t,n,r,a,s,o,i,c){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=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)Ue[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){let h=Ue[u-15],p=Ue[u-2],g=Ie(h,7)^Ie(h,18)^h>>>3,S=Ie(p,17)^Ie(p,19)^p>>>10;Ue[u]=S+Ue[u-7]+g+Ue[u-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let h=Ie(i,6)^Ie(i,11)^Ie(i,25),p=f+h+vr(i,c,d)+go[u]+Ue[u]|0,S=(Ie(r,2)^Ie(r,13)^Ie(r,22))+xr(r,a,s)|0;f=d,d=c,c=i,i=o+p|0,o=s,s=a,a=r,r=p+S|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,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(r,a,s,o,i,c,d,f)}roundClean(){pt(Ue)}destroy(){this.set(0,0,0,0,0,0,0,0),pt(this.buffer)}};var $t=Ar(()=>new wn);var Se={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}},On=new Uint8Array(Se.magic_bytes),Gt=Se.magic_length,$e=Se.header_length,Je=Se.nonce_length,Rn=Se.tag_length,ea=Se.segment_overhead,ta=Se.segment_size_bytes,kr=Se.min_segment_size_bytes,Tr=Se.max_segment_size_bytes,gt=Se.header_layout.find(e=>e.name==="file_id"),Ir=Se.aad_layout.reduce((e,t)=>e+t.length,0),na=new Uint8Array(Se.v3_reader.magic_bytes),ra=Se.v3_reader.header_length;function wo(e){return Je+e+Rn}function Pn(e){let t=Math.max(1,Math.ceil(e/ta));return $e+t*ea+e}function bo(){let e=new Uint8Array($e);return e.set(On,0),new DataView(e.buffer).setUint32(Gt,ta,!0),e.set(crypto.getRandomValues(new Uint8Array(gt.length)),gt.offset),e}function jt(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function aa(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(Gt,!0);if(t<kr||t>Tr)throw new Error(`segment size ${t} is outside ${kr}\u2026${Tr}`);return t}function Ln(e){if(e.length<$e)throw new Error(`an AEON v4 header is ${$e} bytes, got ${e.length}`);if(!jt(e,On))throw new Error("not an AEON v4 header");return{segmentSize:aa(e),fileId:e.slice(gt.offset,gt.offset+gt.length)}}function mo(e){if(e.length<ra||!jt(e,na))throw new Error("not an AEON v3 header");return{segmentSize:aa(e)}}function Eo(e){return jt(e,On)?"v4":jt(e,na)?"v3":null}function sa(e,t,n){let r=new Uint8Array(Ir);return r.set(e.subarray(0,$e),0),new DataView(r.buffer).setBigUint64($e,BigInt(t),!0),r[Ir-1]=n?1:0,r}function So(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function oa(e){let t=So(e);try{return crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{new Uint8Array(t).fill(0)}}async function Ao(e,t,n){let r=crypto.getRandomValues(new Uint8Array(Je)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:Rn*8,additionalData:n},e,t),s=new Uint8Array(Je+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),Je),s}async function vo(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,Je),tagLength:Rn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(Je)))}function xo(){return $t.create()}async function wt(){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 ko(){return crypto.getRandomValues(new Uint8Array(32))}var ye={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,MAX_GEO_COUNTRIES:50,SEAL_VISIT_SECONDS:21600,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","eu-central","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,LEASE_DEFAULT_DAYS:7,LEASE_MAX_DAYS:90,LEASE_STATUS_BATCH_MAX:500,LEASE_POLL_SECONDS:600,LEASE_KEEP_DAYS:30,APPROVE_WAIT_SECONDS:120,APPROVE_BODY_SHOWN_BYTES:2048,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}},et={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 eight bytes"}},hkdf:{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",share_proof:"seal:share-proof:v1",kem_mlkem768:"seal:kem-mlkem768:v1"}},share_link:{proof_of:"the proof of a share link's key (AUDIT K237): HKDF-SHA256(ikm = the link's 32-byte key, salt = hkdf.identity_key_salt, info = hkdf.info_prefixes.share_proof, 32 bytes), base64url; its maker gives the server proof_hash = SHA-256 hex of those bytes, an opener sends the proof in proof_header",proof_header:"X-Share-Proof",proof_vector:{link_key:"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",proof:"xYwpyfG6o6iW43T5O7W9Av5bVZJc5MpUhcmPa6SxQy8",proof_hash:"75d668b6b3295aad0b8e3f83eb9d03181a9c81f92836105077023bf3bea0aa4a"}},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}",scope_metadata_aad:{is:"What a sealed text of a scope's metadata is bound to: the AAD of its AES-256-GCM (SEAL Pro, AUDIT K140, SPEC-NAMES-BOUND). A room's name and description are bound to the room. A text under the organization's key and the name of a seal's folder are bound to their own object: its id stands in the AAD, so two of them cannot be swapped unnoticed. The binding before that named the kind and the organization (the seal) only; a row says which one its text has by `encryption_version`. Since the old binding's end (SPEC-NAMES-BOUND \u04213) a text of before is read only of the kinds in `org_object.before_read` \u2014 a contract's data and a member's drawing lie under their signatures and are never sealed again (\u041D5) \u2014; any other, and a seal's folder's name, opens bound alone.",room:"room:{room_id}:{field}",org_object:{bound:"{kind}:{org_id}:{object_id}:{field}",before:"{kind}:{org_id}:{field}",kinds:["secret","sign-policy","sign-template","sign-template-body","sign-template-meta","sign-folder","sign-request-meta","sign-field-value"],before_read:["sign-request-meta","sign-field-value"],field:"name",object:"the row the text belongs to: the secret, the policy, the template (its name, text and terms alike), the contract folder, the sign request, the signature field of a drawing"},folder:{bound:"seal:{seal_id}:{folder_id}:name",before:"seal:{seal_id}:name",before_read:!1},versions:{before:3,bound:5,note:"4 is a file's format version (seal_files) and names no metadata"},vectors:{key_hex:"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",nonce_b64:"ZGVmZ2hpamtsbW5v",org_object:{kind:"secret",org_id:"0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e",object_id:"7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d",other_object_id:"11111111-2222-4333-8444-555555555555",text:"prod-db",bound_aad:"secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d:name",bound_b64:"OGmxAlSNNC/EcAW6hlU6eU73XrC7Vaw=",before_aad:"secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:name",before_b64:"OGmxAlSNNBiKlnxW4fkbPMjFoZGJJDY="},org_object_signed:{kind:"sign-request-meta",org_id:"0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e",object_id:"5c2e8f71-3a94-4d0b-b6e1-0f7a9c2d4e85",text:"NDA Acme 2026",before_aad:"sign-request-meta:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:name",before_b64:"Bl+fRjiKO/seUG/a7Ln0rJ0phFB+8MGpdfuM+fI="},folder:{seal_id:"AbCd1234",folder_id:"c0ffee00-1234-4abc-8def-0123456789ab",other_folder_id:"11111111-2222-4333-8444-555555555555",text:"\u0414\u043E\u0433\u043E\u0432\u043E\u0440\u044B 2026",bound_aad:"seal:AbCd1234:c0ffee00-1234-4abc-8def-0123456789ab:name",bound_b64:"mI8O2KlahiDu0I9WC+W7dmLwNji94CvUmMxJnLVFN5EChD6uMg==",before_aad:"seal:AbCd1234:name",before_b64:"mI8O2KlahiDu0I9WC+W7dmLwNji9ni0vIvgReyNDk0uY98XR7Q=="}}},sign:{message_prefix:"aeon:sign:v1",message_format:"aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}",message_prefix_v2:"aeon:sign:v2",message_format_v2:"aeon:sign:v2|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}|terms:{terms_hex}",terms_label:"aeon:terms:v1",terms_of:"what the signer was shown (AUDIT K204): SHA-256 hex of the lines the core builds (shared/core/src/contract_terms.rs) \u2014 for a member of the organization or its agent from the metadata ciphertext and the whole field layout, for an outside signer from their own fields alone and no metadata \u2014 and the signer's own filled fields",terms_vector:{org_id:"0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70",request_id:"7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e",doc_hash:"cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33",meta:"bWV0YS1jaXBoZXJ0ZXh0",fields:[{id:"b2f1c3d4-0000-4000-8000-000000000002",type:"signature",page:2,x:.615,y:.8125,w:.3,h:.075,assignee_type:"email",assignee:"ann|example@example.com",required:!0},{id:"a1e0b2c3-0000-4000-8000-000000000001",type:"signature",page:1,x:.1,y:.7,w:.3,h:.075,assignee_type:"user",assignee:"5c9e7a3b-1d2f-4a6b-8c0d-2e4f6a8b0c1d",required:!0}],filled:[{field_id:"a1e0b2c3-0000-4000-8000-000000000001",sha256:"bde5c9647a96e96c78ea116eaa7a653b2347cd83855d223b30984f235151f813"}],terms:"a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30",message:"aeon:sign:v2|org:0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70|req:7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e|doc_hash:cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33|terms:a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30"}},sign_doc_hash_of:"sha256(plaintext) of the exact seal_files row in doc_ref",recovery_phrase:{seed:`BIP39: PBKDF2-HMAC-SHA512 of the phrase after trim, lower case and NFKD, salt "mnemonic", 2048 iterations, 64 bytes; the web's recoveryPhrase.ts phraseToMasterSeed and the core's hkdf::master_seed_from_phrase (\u04145 \xA73.2)`,vector:{phrase:"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",typed:` Abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon ART
3
- `,seed_hex:"408b285c123836004f4b8842c89324c1f01382450c0d439af345ba7fc49acf705489c6fc77dbd4e3dc1dd8cc6bc9f043db8ada1e243c4a0eafb290d399480840"}},device_link:{record:"a person's seed64, base64url, sealed by the browser to the one-time bundle of sealfs login: sealReply(seed64, bundle, scope, code) of the protocol's identity module \u2014 box (sealed_box_v2) \u2016 nonce(12) \u2016 AES-256-GCM of the record under the box's key; the daemon opens it with its one-time identity (\u04145 \xA73.2 \u043F. 2, D119)",scope:"device",vector:{daemon_seed64_hex:"01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3ba",code:"K7M2Q9XA",seed64_hex:"030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bc",record:"AlbSFUYf2V9yux_9DyViIEw_gXJcdITRt0kFjJC9XAJTOCRSKh3_hDCGxBSS5idHldzc_qQOtd43_GYaZQm9_VH90eY2JDP_A2T4I8W_qPPfS4MlLGtBp0kkShY_PnspF6bELAbft3XNkEuwQpfynXH2OFFvAPwJFKceua18YAywNbq84plsv8n3C5lRmeITyeFwKlxDW3-6q-2NHlAgkSrScie1B63CQu3D0U3SRWcOHMvwnl9Topwe1J2iu4EpOUlJRZQsgfBR4LhyywAWam0R3VHa_pXjCtN4Of-JRyO3Jub-6MgDXpoGsQuD9V1XszngRZkwz0R_4xqSlabtA-GMiCJyhff7HBp3t0XHeaS04cNdtATfwce_FUL3IL-z0YAQh-JSzKz_VeVq8iFSZcbHnx2Eab3ND4YuwvJxfJJ8jGquahnhndiI6qxZtK7OmQsy8ZBQ_p4Gi8v1ziN74OMdQG9UtqR9igeJohiMos5tHpveIXQ9luWiQ9gk22p53yGzP8hH_mv508tb4KsveNjssXS0hVmLl4c7fqQbrBjKvNauuEbzNd1gimV4I_f-N0FN2c7Pe7sTZevR5dnIGrAF_31cxFTOWVjZdKsyEWUiwSHrG2dQBccO2AB6TurTsqr4hBP64c3WkUW1vJVXKEOCKxBIwMa7XyyLw4La5tZue0Ls2cHzfy2Kd5jKCo3UIQrjvNWOvXFDRlkTx10UMFpZNvmnITHVh6rHkr5_tGFVMwqU2arRmwQBWCBYsDhN1NVJ8cEwEb0lNHfuotqf54IZUP25JwqpqSkSadjHdVHZdJ50MQUiNiumm0e-kbLDfWHds9dkGhwVgqha3s-svngKweowybgYAnRIDYeHHkSN-9Bm2jNmidilQhTiY6eLmnxg81sdESUNrjk1nhNJdiTaDAeX-CL5DJxPVirKFWYgrBpvJ7ocpxg9Idqsdm8fIzZi-MAQyq_I1y2RcsUqZEwFFeHqwPZdUce1PxVBjFn27cfKzyifotbTBumodLXMRnrrhfQ2i6cHAt9utI2X_WJuGxDRfYICuKdQHt3NPswIwLxSxgNUvpani5DzhYA5FnC-zfh_LWXyJnyfJx1Yr-07_ICpIP85fwzO7FAVZxpdpsL8wk19HhW63LAOVcQxANLcIue7hp1vU6QU1Co0H4yGJgmehDEBYWFJCpaDk8_srkw42Y9eZn6SNoIekuz-BNgjnnB0WB2mh-k3vux92C-_2o8GsSeENNvOOTRwLOLAB4PCi-Uf__oonrLR0kBdE2gbrVjb6sttEx8Df_S7YuTCytpw13ABaXCcJRsPfR6os2KuM1Rv53CH5SZ2NpKgdFlBmva9gIsMSJxAh08UtLGNhKrli3uUW1KER7Ng92RDDV-HHUqNyOhkPPD4KteeZHX0m9h8POVCjXr0TNHSisQK_CPFMMOhUc2DmEHDOZO9piI5uMAznMdzrR-qFbhPNN9ugUUSIdDnVS9Mc2INiUIKjnLWB37_wYTSpXRCS5bSfohMPyNu0dTuAJuHLNfK1hA9XOGhvZLFW9rgXN8bYdAmUL0TrJJ4DYBWrpzXuzaiXEf2peRi0z6LYiXWyjvmIaQfvttTgWSymbREbJmanBDfTUPR5XPFQHZ-n_876ODCoJAXnqOkSSWEHKf885bOre3IkJIS_2jH9_MJzG0Fsmnvj8VYHECIrZlRFdsqzMQ9MIIIIWg0bfHvAn5R06o"}}},Ee={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 eight 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 64-byte seed of an agent, a device or an inbox, 86 characters",derives:"all three keys of the bundle v2 the address names are HKDF-SHA256 of the seed under crypto.json hkdf.identity_key_salt, each under its own info: hkdf.info_prefixes identity (Ed25519), agreement (X25519) and kem_mlkem768 (d \u2016 z of ML-KEM-768), followed by key_version as four bytes, little-endian \u2014 the core's Identity::from_seed. No public key of the bundle is the seed",key_version:1,same_as:["sealnet-mcp state.identity.seed_b64","seal identity.v1.json seed_b64url","sealnet (npm) KeyPair.secretKey","sealnet (PyPI) keygen().secret_key"],root:"SPEC-SEED-ROOT: the one kind of seed. A seed of 32 bytes (43 characters) is a key of the kind before: a holder that keeps its seed itself reads it as its previous key (below) until that expires, and nothing makes it or takes it as a seed \u2014 SEAL_SEED, an inbox key file, a device transfer and an SDK key of that length are refused in words that say how to make a new one.",vector:{comment:"the seed of the vector `sealed-box-v2-person` of xwing_test_vectors.json (seed64_hex; its bundle, address and words are there) signs the challenge of ts into this proof \u2014 Identity::from_seed, Identity::inbox_proof; Ed25519 is deterministic, every client reproduces it",of:"sealed-box-v2-person",ts:179e7,challenge:"wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8",proof:"1790000000.wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8.1VKxaNHrNu5Is9gYxMur7mAABL8Pn0Lcz6vpw5JDmUI65epcxGCMUOGcJK-lneqALDx0EHlBHbhmUIHWPCCDCQ"},previous:"the seed a holder had before it replaced its key, 32 or 64 bytes, kept beside the current one where the holder keeps its seed itself (an inbox, a device's identity file, the MCP server's state): it opens what the server still holds at the old address and is erased when the last of that has expired \u2014 seven days from the replacement (limits.json ttl_options, the longest free seal), longer while the inbox shows a live row at the old address"},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 eight 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","guard"],pair_what:"inbox",guard:{kind:"guard",is:"a pair request whose requester is this machine's guard (SPEC agent egress \xA73.1): the same answer as `pair` (the pairing file), and the inbox marks the agent as a guard. A request for a secret whose recipient_bundle is a guard's is shown by the inbox as sealed to that guard; one whose bundle is no known guard's is answered only after the person types its eight words (\xA76.1, T2\u0430).",gateway:"SPEC agent egress \xA77.2, level \u0412: `seal guard expose --listen <address:port> [--as <host:port>]` makes a guard the owner's gateway \u2014 `POST https://<host:port>/v1/forward` over mTLS, both certificates made from the guards' Ed25519 identity keys and checked against the published bundles of their addresses (the client names its address in `x-seal-address`, the server is the `gateway.guard` of the binding). `seal guard lend <key> --to <address>` lends a key as use: the borrower's guard receives a handle under a binding with `gateway: {at, guard}` (owner_blob_payload.v1.json bindings) and sends the request with `x-seal-method` and `x-seal-url` (the host's URL) to the gateway, which puts the value in and answers with the host's answer. The gateway not reachable: 502 `{error: seal_guard.gateway, reason: gateway_offline}`.",bind:"POST /intake may carry `bind`: what the agent proposes the key be bound to \u2014 {hosts: [<host>], place?: <place>, class?: outbound|inprocess} (secrets.json guard_note). `bind` is sent only when the recipient_bundle is a guard's, hosts proposed or not: its presence is what lets the page bind the key and lend it under a lease; without it the page says the value goes to the agent as it is. The page shows the proposal as the binding when no entry of secrets.json knows the key's form; the person confirms, narrows or removes it. At most 16 hosts of 253 characters, each a name of two labels or more (`*.` with two labels under it, three under secrets.json wildcard_public_second_level); the server checks the shape and keeps it as given."},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, 86>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>","kind":"guard"?}]}',kind:"`guard` for an agent that is a machine's guard (request kind `guard`): it stays a guard on every device of the inbox and through a rename; a reader drops a kind it does not know (SPEC-APP r5 \u041425)"},approve:{mime:"application/vnd.seal.approve+json",json:'{"v":2,"ask":"<16 random bytes, base64url>","secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","guard":"<eight words of the guard>","host":"api.stripe.com","method":"POST","path":"/v1/refunds?expand=charge","at":"<ISO 8601>","until":"<ISO 8601>","body_bytes":24,"body":"charge=ch_1&amount=50000"?,"body_sha256":"<SHA-256 hex of the whole body>"?,"body_more":true?}',body:"What the call carries (AUDIT K152): `path` is the path with its query; `body_bytes` the bytes of the body the guard read; `body` its first `limits.json::APPROVE_BODY_SHOWN_BYTES` bytes when they are text, cut where a character ends, absent for an empty or a binary body; `body_sha256` the digest of the whole body, absent for an empty one and for one that streams on past what the guard reads whole, which `body_more` says. An agent's request holds surrogates, never a value. A reader takes a question without these fields (a guard before them) and shows what it has.",is:"A guard's question to a key's owner (SPEC agent egress \xA77.3, \u04214): a call the binding marks `approve: owner` waits for this answer. Sent as a seal addressed to the owner (30 minutes, one open), its share blob marked `payload: approve`; the inbox shows it as a card with Allow and Deny and pushes. Unanswered within `limits.json::APPROVE_WAIT_SECONDS` the call is refused (403 `approve`)."},approve_answer:{mime:"application/vnd.seal.approve-answer+json",json:`{"v":2,"ask":"<the ask>","decision":"allow"|"deny","at":"<ISO 8601>","signature":"<Ed25519 by the inbox's identity key over the core's approval message, base64url, 86>"}`,is:"The owner's answer (\xA77.3): a seal from the inbox to the guard's address (30 minutes, one open), blob `payload: approve_answer`; the guard checks the signature against the owner's bundle (the `owner` of the binding). `allow` is for the one call the question was about (AUDIT K152): the same call again is another question."},summary:{mime:"application/vnd.seal.summary+json",json:`{"v":2,"secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","day":"<YYYY-MM-DD, UTC>","counts":[{"method":"GET","path":"/v1/charges/*","status":200,"n":40}],"approved":2,"refused":1,"root":"<SHA-256 hex, the chain's last link>","n":43,"signature":"<Ed25519 by the guard's identity key over the core's summary message, base64url, 86>"}`,is:"A guard's daily summary of one lent key to its owner (\xA77.4, \u04213): once a day by UTC and on a revoke, a seal addressed to the owner (7 days, one open), blob `payload: summary`. The inbox checks the signature against the guard's bundle (the item's sender), keeps the summary in its own storage (the carrier expires) and shows the journal under the lease. Attested by the guard that wrote the receipts: honest of an honest guard."},blob_payload:"A seal a machine makes for another machine or for an inbox carries the kind of its file in the share blob's `payload` (`approve`, `approve_answer`, `summary`, `delivery`), under the link key: the inbox reads the blob of every delivery and downloads only the files of these kinds; the server sees one more addressed seal. Readers tolerate a blob without the field.",delivery:{mime:"application/vnd.seal.delivery+json",json:`{"v":2,"name":"<the binding's name, STRIPE_KEY>","level":"A"|"B"|"0","at":"<ISO 8601>"}`,is:"The receipt of a lent key's arrival (SPEC agent egress \xA76.2, T17): whoever opens a secret whose binding names an `owner` sends this file, as a seal addressed to that owner (7d, one open), the moment the secret is opened. `A` or `B`: the opener's guard holds the key and the agent got a surrogate \u2014 the level is the one that guard names in its `status` (SPEC-APP r4 \u042038: `A` its key in a file of the user, `B` in the protected keychain of the SEAL app); `0`: the opener holds the value itself, the second level. The level travels inside the ciphertext; the server sees one more addressed seal. No receipt when the binding has no owner, or the owner is the opener itself."}},device_link:{code:"16 Crockford base32 characters from 10 random bytes (80 bits): the server sees the what beside the device's address, so the code must not be searchable from them (SPEC-r4 \u041A-4, AUDIT wpkg03.3)",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 for the asking: it answers any script of seal.net. The address goes back only with a lease the inbox kept (box.lease), to be sealed into the key's binding as its owner.",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}",lease:"box.lease {lease: {id, token, name, hosts, words, expires_at}} -> {ok: boolean, address?: string}; ok: the lease and its revoke token are in Sent; address: the inbox's address, the owner of the lent key (SPEC agent egress \xA77.3\u20137.5: the guard asks it for its word and sends it the daily summary)"},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",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 kite tulip peach llama echo"}]},To="X-Seal-Client",C={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,VISIT_HEADER:"X-Seal-Visit",PROGRESS_SPEED_WINDOW_MS:2e4}},ia;function tt(e,t){return(ia??globalThis.fetch).call(globalThis,e,t)}function Io(){return ia!==void 0}var pc=2*1024*1024,Oo=(ye.limits.INTAKE_WAIT_MAX_SECONDS+15)*1e3,_c=Ee.proof.header_address,yc=Ee.proof.header_proof;function Ro(){try{return typeof process<"u"&&!0}catch{return!1}}var Po=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":Ro()||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}},Wt=Po;function Et(e){return{debug:(t,...n)=>Wt("debug",e,t,...n),info:(t,...n)=>Wt("info",e,t,...n),warn:(t,...n)=>Wt("warn",e,t,...n),error:(t,...n)=>Wt("error",e,t,...n)}}var P=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 Lo(e,t){return Object.defineProperty(e,"session",{value:t,enumerable:!1,configurable:!0,writable:!0}),e}function Ve(e,t){return e instanceof P?e:e instanceof DOMException&&e.name==="AbortError"?new P("Upload aborted","ABORTED"):new P(e instanceof Error?e.message:t,"UNKNOWN")}async function Qe(e,t,n,r){let a=await Ht(e,String(e.status));return new P(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var Do=Et("upload"),No={now:()=>performance.now(),after:(e,t)=>{let n=setTimeout(t,e);return()=>clearTimeout(n)},every:(e,t)=>{let n=setInterval(t,e);return()=>clearInterval(n)}},Co={retryBackoffMs:C.upload.RETRY_BACKOFF_MS,retryJitterRatio:C.upload.RETRY_JITTER_RATIO,stallNoticeMs:C.upload.STALL_NOTICE_MS,maxStallMs:C.upload.MAX_STALL_MS,putFloorBytesPerSecond:C.upload.PUT_FLOOR_BYTES_PER_SECOND,putMinDeadlineMs:C.upload.PUT_MIN_DEADLINE_MS,controlTimeoutMs:C.upload.CONTROL_TIMEOUT_MS,completeTimeoutMs:C.upload.COMPLETE_TIMEOUT_MS,poolStart:C.upload.PART_POOL_START,poolMax:C.upload.PART_POOL_MAX,poolMin:C.upload.PART_POOL_MIN,poolGrowRatio:C.upload.PART_POOL_GROW_RATIO,poolShrinkRatio:C.upload.PART_POOL_SHRINK_RATIO,partQueueLimit:C.upload.PART_QUEUE_LIMIT,hedgeMinInflightMs:C.upload.HEDGE_MIN_INFLIGHT_MS,hedgeLagFactor:C.upload.HEDGE_LAG_FACTOR,hedgePollMs:C.upload.HEDGE_POLL_MS,livenessSilenceMs:C.upload.LIVENESS_SILENCE_MS,verifyPollBackoffMs:C.upload.VERIFY_POLL_BACKOFF_MS,verifyFallbackWaitMs:C.upload.VERIFY_FALLBACK_WAIT_MS,speedWindowMs:C.upload.PROGRESS_SPEED_WINDOW_MS,clock:No};function Dn(e){return{...Co,...e}}function Sn(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}var la=()=>globalThis.AbortSignal;function Nn(e){let t=la()?.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController,r=e.find(a=>a.aborted);if(r)return n.abort(r.reason),n.signal;for(let a of e)a.addEventListener("abort",()=>n.abort(a.reason),{once:!0,signal:n.signal});return n.signal}function Mo(e){let t=la()?.timeout;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;return setTimeout(()=>n.abort(new DOMException("The operation timed out.","TimeoutError")),e),n.signal}function ca(e,t){let n=Mo(t);return e?Nn([e,n]):n}async function bt(e,t,n,r){try{return await tt(e,{...t,signal:ca(r,n)})}catch(a){throw r?.aborted?new P("Upload aborted","ABORTED"):new P(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function da(e){return e===408||e===429||e>=500?"retryable":"terminal"}function ua(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":da(e.httpStatus)}function ha(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":da(e.httpStatus)}var fa=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 Cn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new P("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new P("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function Yt(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,c=0;for(let d=0;;d++){if(a?.aborted)throw new P("Upload aborted","ABORTED");try{return await e({attempt:d,after:i})}catch(f){let u=Ve(f,`${o} failed`);if(u.code==="ABORTED")throw u;let h=s(u);if(h==="terminal")throw u;if(n.exhausted())throw new P(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${u.message}`,u.code,u.httpStatus,u.partNumber,!1);n.failed(),c=h==="refresh_url"?c+1:0;let p=h==="refresh_url"&&c===1,g=r.retryBackoffMs[Math.min(d,r.retryBackoffMs.length-1)]??0,S=1+(Math.random()*2-1)*r.retryJitterRatio,_=p?0:Math.round(g*S);Do.debug(`retry ${o} attempt=${d+2} in ${_}ms after ${u.code}${u.httpStatus?" "+u.httpStatus:""} (${h})`),i=h,await Cn(_,a)}}}var An;function pa(e,t){An=`${e}/${t}`}var Bo=()=>{};function vn(){return{...An===void 0?{}:{[To]:An},...Bo()}}var te=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 Uo(e){return e===404?"not_found":e===410?"revoked":e===451?"blocked":e===429?"rate_limited":e===401||e===403?"auth":e>=500&&e<600?"transient":"unknown"}async function Ht(e,t){let n=await e.text().catch(()=>""),r,a,s,o,i;if(n)try{let c=JSON.parse(n);typeof c?.detail=="string"&&(r=c.detail),typeof c?.code=="string"&&(a=c.code),typeof c?.retry_after=="number"&&(s=c.retry_after),typeof c?.update=="string"&&(o=c.update),typeof c?.min_version=="string"&&(i=c.min_version)}catch{}return new te(r??t,Uo(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function Fo(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}))}}var $o=C.upload.VISIT_HEADER;function _a(){return ae(crypto.getRandomValues(new Uint8Array(16)))}function $(e){return encodeURIComponent(e)}var Wo=et.share_link.proof_header,ya=new Map;async function ga(e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits"]),r=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:t.encode(et.hkdf.identity_key_salt),info:t.encode(et.hkdf.info_prefixes.share_proof)},n,256),a=new Uint8Array(r),s=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return{proof:ae(a),hash:Array.from(s,o=>o.toString(16).padStart(2,"0")).join("")}}async function Or(e,t){ya.set(e,(await ga(t)).proof)}function Rr(e){let t=/^\/seal\/([^/?]+)/.exec(e)?.[1],n=t?ya.get(decodeURIComponent(t)):void 0;return n?{[Wo]:n}:{}}var St=class Ae{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,this.answerTimeoutMs=t.answerTimeoutMs??Oo}fetchImpl(t,n){return this.injectedFetch?this.injectedFetch.call(globalThis,t,n):tt(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=new AbortController,o=setTimeout(()=>s.abort(new DOMException(`${r}: no answer in time`,"TimeoutError")),this.answerTimeoutMs),i;try{i=await this.fetchImpl(this.url(t),{...a,headers:{...vn(),...Rr(t),...a.headers},credentials:a.credentials??this.credentials,signal:a.signal?Nn([a.signal,s.signal]):s.signal})}finally{clearTimeout(o)}if(!i.ok)throw await Ht(i,`${r} failed: ${i.status}`);return i}static ownerHeaders(t,n=!1){let r={"X-Owner-Token":t};return n&&(r["Content-Type"]="application/json"),r}async getMetadata(t,n={}){let r=n.shareCode?`?share_code=${$(n.shareCode)}`:"";return await(await this.request(`/seal/${$(t)}${r}`,{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/${$(t)}/share/${$(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:Dr(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/${$(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=zo(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/${$(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/${$(t)}/download?${Pr(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?Ae.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie),n.visit&&(a[$o]=n.visit);for(let s=0;;s++)try{return await this.request(`/seal/${$(t)}/download?${Pr(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal})}catch(o){if(!(o instanceof te&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<C.upload.NOT_READY_MAX_RETRIES))throw o;await Ko((o.retryAfter??Ho)*1e3,r.signal)}}async downloadCiphertext(t,n,r={}){let a=await this.openDownload(t,n,r);if(a.headers.get("X-Download-Mode")!=="presigned")return a;let{url:s}=await a.json();if(typeof s!="string"||!s)throw new te(`GET /seal/${t}/download answered no storage URL`,"transient",502);let o=await this.fetchImpl(s,{signal:r.signal});if(!o.ok)throw await Ht(o,`storage download failed: ${o.status}`);return o}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${$(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${$(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:Dr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=Ae.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return Lr(a,o,s),{etag:(await this.request(`/seal/${$(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,s={}){let o=n===null?{"Content-Type":"application/json"}:Ae.ownerHeaders(n,!0),i={encrypted_blob:r,proof_hash:(await ga(a)).hash};s.fileIds&&(i.file_ids=s.fileIds),Lr(s,i,o);let c=await this.request(`/seal/${$(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal}),d=await c.json();if(typeof d.share_code!="string"||!d.share_code)throw new te(`POST /seal/${t}/share returned no share_code`,"unknown",c.status);return d.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${$(t)}/share/${$(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:Ae.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${$(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:Ae.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof te&&(o.status===404&&o.appCode==="seal.not_found"||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/${$(t)}/files/${$(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:Ae.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${$(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${$(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:Ae.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${$(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:Ae.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 te(`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:Ae.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 te("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),t.bind&&(r.bind=t.bind),t.answerToInbox&&(r.answer_to_inbox=!0),await(await this.request("/intake",{what:"POST /intake",method:"POST",headers:{"Content-Type":"application/json",...t.answerToInbox?yt(t.answerToInbox):{}},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/${$(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${$(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json",...Rr(`/seal/${$(n.sealId)}`)},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:ae(t)}),signal:n.signal})}async getBundle(t,n={}){try{let r=await this.request(`/intake/bundles/${$(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return ue((await r.json()).bundle)}catch(r){if(r instanceof te&&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,ye.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:yt(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:yt(n),signal:r.signal})}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",...yt(r)},body:JSON.stringify({to:r.address,endpoint:t}),signal:a.signal})}async createLease(t,n,r={}){return await(await this.request("/lease",{what:"POST /lease",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({owner_token_hash:t,expires_at:n}),signal:r.signal})).json()}async revokeLease(t,n,r={}){return await(await this.request(`/lease/${$(t)}/revoke`,{what:`POST /lease/${t}/revoke`,method:"POST",headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async leaseStatus(t,n={}){let r={"Content-Type":"application/json"};n.etag&&(r["If-None-Match"]=n.etag);let a=await this.fetchImpl(this.url("/lease/status"),{method:"POST",headers:{...vn(),...r},body:JSON.stringify({ids:t}),credentials:this.credentials,signal:n.signal});if(a.status===304)return null;if(!a.ok)throw await Ht(a,`POST /lease/status failed: ${a.status}`);return{statuses:await a.json(),etag:a.headers.get("ETag")}}},Ho=3;function yt(e){return{[Ee.proof.header_address]:e.address,[Ee.proof.header_proof]:e.proof}}function Pr(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function Lr(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,yt(e.sender)))}function Ko(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 Dr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new te(`${t} returned an empty blob`,"unknown",n);return ue(e.encrypted_blob)}function zo(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 Go=32,jo=32,Vt=ye.limits.MAX_BLOB_SIZE,Nr=ye.limits.MAX_FILE_KEYS;function wa(e){if(e>Nr)throw new Error(`Too many file keys: ${e} exceeds maximum of ${Nr}`)}var Yo=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function ba(){return crypto.getRandomValues(new Uint8Array(Go))}async function ma(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 Mn(){return crypto.getRandomValues(new Uint8Array(jo))}async function Ea(e,t,n,r,a,s,o){wa(t.size);let i={owner_token:e,file_keys:Object.fromEntries(t),...r?{message:r}:{},...a?{nda_file:a}:{},...s&&Object.keys(s).length>0?{bindings:s}:{},...o?{payload:o}:{}};return Aa(i,n)}async function Sa(e,t,n,r,a,s,o){wa(e.size);let i={file_keys:Object.fromEntries(e),...n?{message:n}:{},...r?{nda_file:r}:{},...a?{reply_to:ae(a)}:{},...s&&Object.keys(s).length>0?{bindings:s}:{},...o?{payload:o}:{}};return Aa(i,t)}async function Aa(e,t){let n=new TextEncoder().encode(JSON.stringify(e)),r=12+n.length+16;if(r>Vt)throw new Error(`Blob size ${r} exceeds maximum of ${Vt}`);let 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,n),i=new Uint8Array(12+o.byteLength);return i.set(a,0),i.set(new Uint8Array(o),12),i}function Vo(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha256_hex=="string"&&typeof t.name=="string"}function Xo(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.v===1&&typeof t.name=="string"&&(t.class==="outbound"||t.class==="inprocess")&&Array.isArray(t.hosts)&&t.hosts.every(n=>typeof n=="string")}function qo(e){return typeof e.bindings!="object"||e.bindings===null?{}:Object.fromEntries(Object.entries(e.bindings).filter(([,t])=>Xo(t)))}function Zo(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"||t.reply_to!==void 0&&typeof t.reply_to!="string"||t.payload!==void 0&&typeof t.payload!="string")}async function Jo(e,t){let n=await Qo(e,t);if(!Zo(n))throw new Error("Invalid share blob structure");return n}async function Qo(e,t){if(e.length>Vt)throw new Error(`Blob size ${e.length} exceeds maximum of ${Vt}`);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 Yo}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}var bc=ye.limits.MAX_FILE_KEYS;var Fe=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],ei=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),ti=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function Mr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let c,d;i<16?(c=a&s|~a&o,d=i):i<32?(c=o&a|~o&s,d=5*i+1&15):i<48?(c=a^s^o,d=3*i+5&15):(c=s^(a|~o),d=7*i&15);let f=r+c+ei[i]+t[n+d]|0;r=o,o=s,s=a,a=a+(f<<Cr[i]|f>>>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 Bn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array(Fe),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(Fe-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<Fe)return this;this.compressBytes(this.pending,0,Fe),this.pendingLength=0}let n=e.length-(e.length-t)%Fe;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?Fe:2*Fe);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(ti&&(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)Mr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=Fe){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);Mr(this.state,this.scratch,0)}}};function ni(e){return Ne(new Bn().update(e).digest())}var bn=4*1024*1024;async function ri(e){let t=new Bn;for(let n=0;n<e.length;n+=bn)t.update(e.subarray(n,Math.min(n+bn,e.length))),n+bn<e.length&&await wt();return Ne(t.digest())}var va=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Ln(e.header).segmentSize,this.header=e.header.subarray(0,$e),this.key=e.key}async init(){this.cryptoKey=await oa(this.key)}sha256Hex(){return Ze(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 Ao(this.cryptoKey,n,sa(this.header,e,t))}};async function ai(e,t,n,r){let a=new Uint8Array(t);try{let s=new va({key:a,header:n});await s.init();let o=new Bn().update(s.header),i=[Br(s.header)],c=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let d=0;d<c;d++){let f=Math.min((d+1)*s.segmentSize,e.size),u=new Uint8Array(await e.slice(d*s.segmentSize,f).arrayBuffer()),h=await s.encryptSegment(d,d===c-1,u);u.fill(0),o.update(h),i.push(Br(h)),r?.(f,e.size)}return{blob:new Blob(i),md5_b64:Ne(o.digest())}}finally{a.fill(0)}}function Br(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Me=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function si(e,t){e.chunks.push(t),e.bytes+=t.length}function Kt(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 oi(e,t){let n=Kt(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function ii(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Me("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,c=0,d=null,f=async(h,p)=>{if(h.length<ea)throw new Me("integrity",`segment ${c} is ${h.length} bytes: the stream was cut`);try{return await vo(a,h,o==="v4"?sa(s,c,p):null)}catch(g){throw new Me("integrity",`segment ${c} does not decrypt as the ${p?"last":"next"} segment of this file: moved, cut, extended or changed`,g)}finally{c+=1}},u=async()=>{if(r.bytes<Gt)return!1;let h=Eo(oi(r,Gt));if(h===null)throw new Me("outdated","the file is in a format newer than this client: update it");let p=h==="v4"?$e:ra;if(r.bytes<p)return!1;if(h==="v3"){d=xo();for(let _ of r.chunks)d.update(_)}let g=Kt(r,p),S;try{S=h==="v4"?Ln(g).segmentSize:mo(g).segmentSize}catch(_){throw new Me("integrity",_ instanceof Error?_.message:String(_),_)}if(h==="v4"&&await Ze(g)!==n)throw new Me("integrity","the file header is not the one registered for this file");return s=g,o=h,i=wo(S),!0};return new TransformStream({async start(){a=await oa(e)},async transform(h,p){if(h.length!==0&&(si(r,h),d&&d.update(h),!(o===null&&!await u())))for(;r.bytes>i;){let g=Kt(r,i),S=await f(g,!1);g.fill(0),t.onPlaintextBytes?.(S.length),p.enqueue(S)}},async flush(h){if(o===null)throw new Me("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(),S=>S.toString(16).padStart(2,"0")).join("")!==n)throw new Me("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let p=await f(Kt(r,r.bytes),!0);t.onPlaintextBytes?.(p.length),h.enqueue(p)}},{highWaterMark:1},{highWaterMark:1})}var Sc=Et("SwDownload");var Ac=10*6e4;var xa={version:1,default:"application/octet-stream",extensions:{json:"application/json",txt:"text/plain",log:"text/plain",md:"text/plain",csv:"text/csv",html:"text/html",htm:"text/html",xml:"application/xml",pdf:"application/pdf",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}},li="_",ci=200,di=new TextEncoder;function xn(e){return di.encode(e).length}function Ur(e,t){let n="",r=0;for(let a of e){if(r+=xn(a),r>t)break;n+=a}return n}var ui=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 hi(){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 fi(e,t){let n=e.charCodeAt(0);if(n<32||n===127||/[\u202A-\u202E\u2066-\u2069\u200E\u200F\u061C]/.test(e))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 pi(e){let t=e.split(".")[0].toUpperCase();return ui.has(t)}function Un(e,t={}){let{platform:n=hi(),replacement:r=li,maxLength:a=ci,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=>fi(d,n)?d:r).join("");let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${c}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${c})+|${c}+$`,"g"),""),(n==="windows"||n==="unknown")&&pi(o)&&(o=`${r}${o}`),xn(o)>a){let d=o.lastIndexOf(".");if(d>0&&d>o.length-10){let f=o.slice(d);o=Ur(o.slice(0,d),a-xn(f))+f}else o=Ur(o,a)}return!o||o===r?s:o}var _i=new Map(Object.entries(xa.extensions));function yi(e){let t=e.lastIndexOf("."),n=t>=0&&t<e.length-1?e.slice(t+1).toLowerCase():"";return _i.get(n)??xa.default}var vc=C.upload.MULTIPART_THRESHOLD_BYTES,xc=C.upload.MULTIPART_THRESHOLD_BYTES;var kc=new TextEncoder;var Tc=Et("FolderZip");var Ic=100*1024*1024,Oc=4*1024*1024;var gi=new WeakMap;function ka(e){return gi.get(e)??(e.webkitRelativePath||void 0)}var Xt="Encrypted file",qt="application/octet-stream";function Ta(e){return new TextEncoder().encode(`field:${e}`)}async function Fr(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=Ta(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:Ne(new Uint8Array(o)),nonce:Ne(r)}}async function $r(e,t,n,r){let a=Ct(e),s=Ct(t);return(async i=>{let c={name:"AES-GCM",iv:s};i&&(c.additionalData=i);let d=await crypto.subtle.decrypt(c,n,a);return new TextDecoder().decode(d)})(r?Ta(r):void 0)}async function wi(e,t){let n=Xt,r=qt;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await $r(e.name_encrypted,e.name_nonce,t,"name")}catch{n=Xt}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await $r(e.mime_encrypted,e.mime_nonce,t,"mime")}catch{r=qt}return{name:n,mime:r}}async function bi(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function mi(e,t){try{let n=await bi(t);return wi(e,n)}catch{return{name:Xt,mime:qt}}}var Ei=Et("upload"),_t=4*1024*1024;function Zt(){return new DOMException("Upload aborted","AbortError")}async function Si(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:c}=e,d=new va({key:r,header:a});await d.init();let f=d.segmentSize,u=Math.max(1,Math.ceil(n/f)),h=0,p=v=>new P(`The file changed while it was being sent: ${v} ${h} of ${n} bytes`,"FILE_CHANGED"),g=!0,S=0,_=0,E=[],y=0,T=v=>{if(E.length>0&&E[0].length===v)return y-=v,E.shift();let D=new Uint8Array(v),se=0;for(;se<v;){let G=E[0],j=v-se;G.length<=j?(D.set(G,se),se+=G.length,E.shift()):(D.set(G.subarray(0,j),se),E[0]=G.subarray(j),se+=j)}return y-=v,D},x=[],M=0,B=async v=>{let D=new Uint8Array(v),se=0,G=0;for(;se<v;){let j=x[0],we=i?_t-G:Number.MAX_SAFE_INTEGER,Y=Math.min(j.length,v-se,we);D.set(j.subarray(0,Y),se),se+=Y,G+=Y,Y===j.length?x.shift():x[0]=j.subarray(Y),i&&G>=_t&&se<v&&(G=0,await wt())}return M-=v,D},R=async v=>{if(_+=1,e.hashParts===!1)await e.onPart(_,v);else{let D=i?await ri(v):ni(v);await e.onPart(_,v,D)}i&&await wt()},Z=async v=>{if(!i){v.fill(0);return}for(let D=0;D<v.length;D+=_t)v.fill(0,D,Math.min(D+_t,v.length)),D+_t<v.length&&await wt()},ge=async()=>{for(;M>=s;)await R(await B(s))},O=async(v,D)=>{if(o?.aborted)throw Zt();let se=S;S+=1;let G=performance.now(),j=d.encryptSegment(se,D,v);await ge();let we=await j;await Z(v),Ei.debug(`encrypt segment=${S} bytes=${v.length} time=${Math.round(performance.now()-G)}ms`);let Y;g?(Y=new Uint8Array(a.length+we.length),Y.set(a,0),Y.set(we,a.length),g=!1):Y=we,c?.(S),x.push(Y),M+=Y.length},F=t.getReader();try{for(;;){if(o?.aborted)throw Zt();let{done:v,value:D}=await F.read();if(v)break;if(D&&D.length>0){if(h+=D.length,h>n)throw p("it gave more than");E.push(D),y+=D.length}for(;y>=f;)await O(T(f),S===u-1)}if(h<n)throw p("it ended at");(y>0||S===0)&&await O(T(y),!0),await ge(),M>0&&await R(await B(M))}finally{F.releaseLock()}}function Ai(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 vi(e,t,n){let{file:r,key:a,header:s,partSize:o,totalBytes:i,signal:c,initialCredits:d,onSegment:f,onPart:u}=n;return new Promise((h,p)=>{let g=!1,S=!1,_=0,E=Promise.resolve(),y=B=>{g||(g=!0,p(B))},T=()=>{!S||_>0||E.then(()=>{g||(g=!0,h())})};if(c){if(c.aborted){y(Zt());return}c.addEventListener("abort",()=>y(Zt()),{once:!0})}e.onerror=t.onerror=B=>{y(new Error(`crypto worker crashed: ${String(B?.message??B)}`))},e.onmessage=B=>{let R=B.data;if(R.type==="segment"){f?.(R.segmentNumber);return}if(R.type==="part"){_+=1,t.postMessage({type:"md5",partNumber:R.partNumber,buffer:R.buffer},[R.buffer]);return}if(R.type==="done"){S=!0,T();return}R.type==="error"&&y(new Error(R.message))},t.onmessage=B=>{let R=B.data;if(R.type!=="md5")return;_-=1;let Z=new Uint8Array(R.buffer);E=E.then(async()=>{g||(await u(R.partNumber,Z,R.md5),e.postMessage({type:"credit"}))}).catch(y),T()};let x=new ArrayBuffer(a.length);new Uint8Array(x).set(a);let M=s.slice().buffer;e.postMessage({type:"start",file:r,key:x,header:M,partSize:o,totalBytes:i,credits:d},[x,M])})}var xi=null;function ki(){return xi}var je=Et("upload");function Ti(e){return e.now-e.lastLookAt>2*e.every?!1:e.now-e.lastActivityAt>=e.silenceMs}var Wr="<Code>BadDigest</Code>",Ii=2;function en(e){let t=vn();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 Oi(e){return Ri({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 Ri(e){let{file:t,partSize:n}=e;return Pi({stream:Ai(t,Ln(e.header).segmentSize),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 Pi(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:c,partSize:d,contentType:f="application/octet-stream",onProgress:u,signal:h,sourceFile:p,onStreamed:g,onConflict:S}=e,_=Dn(e.transport),E=_.clock;if(s.length!==32)throw new P("Key must be 32 bytes","ENCRYPTION_FAILED");if(d<C.upload.S3_MIN_PART_SIZE_BYTES)throw new P(`Part size must be at least ${C.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let y=new Uint8Array(s),T=en(c),x=Pn(n),M=Math.ceil(x/d),B=null,R=[],Z=0,ge=0,O="encrypting",F=[],v=null,D,se=w=>{let m=E.now();F.push({at:m,bytes:w});let I=Math.max(v??m,m-_.speedWindowMs);for(;F.length>0&&F[0].at<I;)F.shift();let U=m-I;U>0&&(D=Math.round(F.reduce((L,ee)=>L+ee.bytes,0)/U*1e3))},G=w=>{O=w;let m=x-Z;u?.({phase:w,percent:w==="done"?100:Math.min(99,Math.floor(Z/x*100)),deliveredBytes:Z,preparedBytes:ge,totalBytes:x,speedBps:D,etaMs:D&&D>0?Math.round(m/D*1e3):void 0,state:j.state,attempt:j.retriesSinceDelivery+1})},j=new fa(_,()=>G(O),E.now),we=new AbortController,Y=h?Nn([h,we.signal]):we.signal,nt=(w,m)=>Yt(m,{clock:j,policy:_,signal:Y,classify:ha,what:w}),Q=async w=>{throw y.fill(0),new P("Upload aborted","ABORTED")},ve=w=>{if(B)try{tt(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify(w?{upload_id:B,discard_file:!0}:{upload_id:B}),keepalive:!0}).catch(()=>{})}catch{}},ce=!1,be=new Map,oe=null,J=null,Ke=[],ke=new Set,Te=_.poolStart,kt=_.poolMax,Tt=0,ze=null,It=0,Ot=0,rt=null,cn=[],ar=[],at=new Set,st=E.now(),sr=!1,dn=w=>{st=E.now();for(let m of[...at])m.reconnect(w)};function gs(w,m){let I=w.ciphertext.length;if(I>=d&&m>0){let ee=Math.min(w.flowsAtStart??1,ke.size);if(ar.push({rate:I/m,flows:ee}),I/m*1e3<_.putFloorBytesPerSecond*2&&Te>_.poolMin){Te-=1,kt=Te,rt=null,Tt+=1,ze=E.now(),It=0,Ot=0;return}}if(w.round!==Tt||(It+=I,Ot+=1,Ot<Te||ze===null))return;let U=E.now()-ze;if(U<=0)return;let L=It/U;rt===null||L>rt*_.poolGrowRatio?Te=Math.min(kt,Te+1):L<rt*_.poolShrinkRatio&&(Te=Math.max(Math.min(_.poolStart,kt),Te-1)),rt=L,Tt+=1,ze=E.now(),It=0,Ot=0}function ws(w,m){let I=E.now()-m;if(I<_.hedgeMinInflightMs)return!1;let U=ke.size,L=ar.filter(V=>V.flows>=U).map(V=>V.rate);if(L.length===0)return!1;L.sort((V,H)=>V-H);let ee=L[Math.floor(L.length/2)];return w.ciphertext.length/I*_.hedgeLagFactor<ee}async function bs(w,m,I,U,L,ee){if(!Io()&&typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((H,he)=>{let X=new XMLHttpRequest,de=!1;sr=!0,X.upload.onprogress=_e=>{ee.onSocketActivity(_e.loaded,_e.lengthComputable?_e.total:w.length),ne(),ne=Oe()};let Oe=()=>E.after(Sn(w.length,_),()=>{de||ee.onDeadline()}),ne=Oe(),q=()=>{ne(),L.removeEventListener("abort",ie)},ie=()=>{de||(de=!0,X.abort(),q(),he(new P("Upload aborted","ABORTED",void 0,I)))};if(X.onload=()=>{if(de)return;de=!0;let _e={status:X.status,etag:X.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:X.status===400&&String(X.responseText??"").includes(Wr)};q(),H(_e)},X.onerror=()=>{de||(de=!0,q(),he(new P(`Failed to upload part ${I}: network error`,"NETWORK",void 0,I,!0)))},X.onabort=()=>{de||(de=!0,q(),he(new P("Upload aborted","ABORTED",void 0,I)))},L.aborted){q(),he(new P("Upload aborted","ABORTED",void 0,I));return}L.addEventListener("abort",ie,{once:!0}),X.open("PUT",U),X.setRequestHeader("Content-MD5",m),X.send(w)});let V;try{V=await tt(U,{method:"PUT",headers:{"Content-MD5":m},body:w,signal:ca(L,Sn(w.length,_))})}catch(H){throw h?.aborted||L.aborted?Ve(H,"Upload aborted"):new P(`Part ${I}: transport failure (${H instanceof Error?H.message:String(H)})`,"NETWORK",void 0,I,!0)}return{status:V.status,etag:V.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:V.status===400&&(await V.text().catch(()=>"")).includes(Wr)}}function ms(w,m){if(m.badDigest)throw new P(`Part ${w} arrived corrupted (BadDigest)`,"BAD_DIGEST",m.status,w,!0);if(m.status<200||m.status>=300)throw new P(`Failed to upload part ${w}: ${m.status}`,m.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",m.status,w,m.status!==404);if(!m.etag)throw new P(`No ETag returned for part ${w}`,"S3_ETAG_MISMATCH",void 0,w);return m.etag}async function Es(w,m){let I=E.now(),U=()=>{},L=0,ee=0,V=I,H=null,he=()=>{},X={reconnect:de=>he(de,!1),hasUnsentBytes:()=>H?.unsent??!1};at.add(X);try{let de=await new Promise((ne,q)=>{let ie=!1,_e=Be=>{ie||(ie=!0,Be())},lr=()=>{let Be=new AbortController,ot=()=>Be.abort();Y?.aborted?Be.abort():Y?.addEventListener("abort",ot,{once:!0});let Pe={ctl:Be,unsent:!0,ended:Promise.resolve()};H=Pe,V=E.now(),st=V,Pe.ended=bs(w.ciphertext,w.contentMd5,w.partNumber,m,Be.signal,{onSocketActivity:(Le,it)=>{st=E.now(),Pe.unsent=Le<it},onDeadline:()=>{if(++ee<2)return he("copy deadline",!1,!1);H===Pe&&_e(()=>q(new P(`Part ${w.partNumber}: no answer from storage after a reconnect`,"NETWORK",void 0,w.partNumber,!0)))}}).then(Le=>{if(H===Pe)try{let it=ms(w.partNumber,Le);_e(()=>ne(it))}catch(it){_e(()=>q(it))}},Le=>{H===Pe&&_e(()=>q(Ve(Le,`Failed to upload part ${w.partNumber}`)))}).finally(()=>{Pe.unsent=!1,Y?.removeEventListener("abort",ot)})};he=(Be,ot,Pe=!0)=>{let Le=H;ie||Le===null||h?.aborted||(H=null,L=ot?L+1:Pe?0:L,je.debug(`${ot?"replace":"reconnect"} part=${w.partNumber} (${Be})`),Le.ctl.abort(),Le.ended.then(()=>{ie||(Y?.aborted?_e(()=>q(new P("Upload aborted","ABORTED",void 0,w.partNumber))):lr())}))},lr(),U=E.every(_.hedgePollMs,()=>{ie||h?.aborted||H===null||L>=Ii||ws(w,V)&&he(`slower than its peers after ${Math.round(E.now()-I)}ms`,!0)})}),Oe=E.now();R.push({part_number:w.partNumber,etag:de}),Z+=w.ciphertext.length,se(w.ciphertext.length),gs(w,Oe-I),j.delivered(),st=Oe,je.debug(`part=${w.partNumber}/${M} put=${Math.round(Oe-I)}ms size=${w.ciphertext.length}${L>0?` replaced\xD7${L}`:""}`),G("uploading")}finally{at.delete(X),he=()=>{},U(),H?.ctl.abort()}}let Rt=(w,m,I)=>bt(w,m,I,Y);async function Ss(){try{let w=await Rt(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(B??"")}`,{method:"GET",headers:T},_.controlTimeoutMs);if(!w.ok)return null;let m=await w.json();return typeof m.status=="string"?m.status:null}catch{return null}}async function or(w){let m=performance.now(),I=await nt("presign batch",async()=>{let L=await Rt(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({upload_id:B,part_numbers:w})},_.controlTimeoutMs);if(!L.ok)throw await Qe(L,"Failed to get presigned URLs",L.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:ee}=await L.json();return ee}),U=new Map;for(let[L,ee]of Object.entries(I))U.set(Number(L),ee);return je.debug(`batch presign ${w.length} urls in ${Math.round(performance.now()-m)}ms`),U}async function As(w){let m=[];for(let U=w;U<=M&&m.length<C.upload.PRESIGN_BATCH_SIZE;U++)be.has(U)||m.push(U);if(m.length===0)return;let I=await or(m);for(let[U,L]of I)be.set(U,L)}function ir(w){oe||(oe=As(w).catch(()=>{}).finally(()=>{oe=null}))}async function vs(w){await wt(),ze??(ze=E.now()),v??(v=ze),w.round=Tt,w.flowsAtStart=ke.size;let m=be.get(w.partNumber);!m&&oe&&(await oe,m=be.get(w.partNumber)),be.delete(w.partNumber),ir(w.partNumber+1),await Yt(async({after:I})=>{if((!m||I==="refresh_url")&&(m=(await or([w.partNumber])).get(w.partNumber),!m))throw new P(`No presigned URL for part ${w.partNumber}`,"NETWORK",void 0,w.partNumber,!0);await Es(w,m)},{clock:j,policy:_,signal:Y,classify:ua,what:`part ${w.partNumber}`})}function un(){for(;!J&&!h?.aborted&&ke.size<Te&&Ke.length>0;){let w=Ke.shift(),m=vs(w).catch(I=>{J??(J=Ve(I,"Part upload failed"))}).finally(()=>{ke.delete(m);let I=cn;cn=[];for(let U of I)U();un()});ke.add(m)}}let xs=()=>new Promise(w=>{cn.push(w)}),ks=(()=>{let w=globalThis,m=globalThis.navigator?.connection,I=m?.type,U=()=>dn("network is back"),L=()=>j.connectionLost(),ee=()=>{let X=m?.type;X!==I&&(I=X,dn("network changed"))};w.addEventListener?.("online",U),w.addEventListener?.("offline",L),m?.addEventListener?.("change",ee);let V=Math.max(10,_.livenessSilenceMs/4),H=E.now(),he=E.every(V,()=>{let X=E.now(),de=Ti({now:X,lastLookAt:H,every:V,lastActivityAt:st,silenceMs:_.livenessSilenceMs});H=X,!(!sr||at.size===0||!de)&&[...at].some(Oe=>Oe.hasUnsentBytes())&&(j.connectionLost(),dn("every socket silent"))});return()=>{he(),w.removeEventListener?.("online",U),w.removeEventListener?.("offline",L),m?.removeEventListener?.("change",ee)}})();try{let w=performance.now();if(je.debug(`starting multipart: totalBytes=${n} parts=${M} partSize=${d} pool=${_.poolStart}..${_.poolMax}`),h?.aborted)throw new P("Upload aborted","ABORTED");G("encrypting"),B=await nt("multipart init",async()=>{let ne=await Rt(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({seal_id:r,content_type:f,content_length:x,part_size:d,file_id:a})},_.controlTimeoutMs);if(!ne.ok)throw await Qe(ne,"Failed to initialize multipart upload","NETWORK");return(await ne.json()).upload_id}),ir(1),G("encrypting");let m=!1,I=()=>{m=!0,G("encrypting")},U=async(ne,q,ie)=>{for(m=!0,ge+=q.length,G("encrypting"),h?.aborted&&await Q(h?.aborted===!0),Ke.push({partNumber:ne,ciphertext:q,contentMd5:ie}),un();Ke.length>=_.partQueueLimit;)if(await xs(),J)throw J;if(J)throw J},L=()=>Si({stream:t,totalBytes:n,key:y,header:o,partSize:d,signal:h,yieldToRenderer:typeof document<"u",onSegment:I,onPart:U}),ee=ki(),V=null;if(p&&ee&&typeof document<"u"){let ne=null;try{ne=ee(),V=[ne,ee()]}catch{ne?.terminate()}}if(V){let[ne,q]=V;je.debug("crypto pipeline: worker");try{await vi(ne,q,{file:p,key:y,header:o,partSize:d,totalBytes:n,signal:h,initialCredits:_.partQueueLimit,onSegment:I,onPart:U})}catch(ie){let _e=Ve(ie,"Crypto worker failed");if(_e.code==="ABORTED"||m)throw _e;je.debug(`crypto worker failed before output \u2014 inline fallback (${_e.message})`),await L()}finally{ne.terminate(),q.terminate()}}else await L();for(;un(),!(J||(h?.aborted&&await Q(!0),ke.size===0&&Ke.length===0));)await Promise.race(ke);if(J)throw J;G("verifying"),h?.aborted&&await Q(h?.aborted===!0),ce=!0,g?.();let H=!1,he,X=await nt("complete",async()=>{let ne=H;H=!0;let q=await Rt(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({upload_id:B,parts:R.map(ie=>({part_number:ie.part_number,etag:ie.etag})),...S?{on_conflict:S}:{}})},_.completeTimeoutMs);if(q.ok){let ie=await q.json().catch(()=>null);return typeof ie?.conflict_with=="string"&&(he=ie.conflict_with),ie?.status==="verified"}if(ne&&q.status===400&&await Ss()==="completed")return!1;throw await Qe(q,"Failed to complete multipart upload",q.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});j.delivered(),G("done");let de=Math.round(performance.now()-w),Oe=n/(1024*1024)/(de/1e3);return je.debug(`DONE totalTime=${de}ms speed=${Oe.toFixed(2)}MB/s parts=${R.length}`),y.fill(0),{verified:X,...he?{conflictWith:he}:{}}}catch(w){y.fill(0);let m=Ve(w,"Unknown upload error");throw ce&&m.code!=="ABORTED"&&(m.httpStatus===void 0||m.httpStatus>=500)||ve(m.code==="ABORTED"),m}finally{ks(),j.dispose(),we.abort()}}var We={multipartThresholdBytes:C.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:C.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:C.upload.INMEMORY_BLOB_LIMIT_BYTES};function Li(e,t=We){return e<=C.upload.FINE_PART_MAX_FILE_BYTES?C.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Ia(e,t){return e>=t.multipartThresholdBytes}function Di(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 Fn(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:Di(e.auth)}function Ni(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var Ci={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},Hr=[2,12],Mi=[12,95],Bi=[95,99];function Kr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=Ci[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=Bi:r.deliveredBytes===0?s=Hr:s=Mi;let o=s===Hr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,c=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,c),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 $n=class{constructor(e,t){this.run=t,this.cancelled=!1,this.running=null,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 P("Upload session was cancelled","ABORTED");return this.running??(this.running=this.run(this,e).catch(t=>{throw Lo(Ve(t,"Upload failed"),this)}).finally(()=>{this.running=null})),this.running}async cancel(){this.cancelled=!0;let e=Ni(this.ctx);if(!e){let n=this.ctx.revokeFilePath;if(!n||this.createdSeal)return;for(let r of this.pending){let a=n.replace("{sealId}",encodeURIComponent(this.sealId)).replace("{fileId}",encodeURIComponent(r.fileId));await tt(`${this.ctx.baseUrl}${a}`,{method:"DELETE",headers:en(Fn(this.ctx)),credentials:this.ctx.credentials??"include"}).catch(()=>{})}return}let t=new St({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 Ui(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)throw new Error(`${n}: file record ${o} carries no sha256_hex \u2014 refusing to pair it by position`);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 Fi(e){return e>=200&&e<300||e===204}async function $i(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:c,clock:d,transport:f}=e,u=` for ${i}`,h={"Content-Type":"application/json",...s},p=t.credentials??"include",g=(T,x)=>Yt(x,{clock:d,policy:f,signal:c,classify:ha,what:T}),S=()=>g(`initiate${u}`,async()=>{let T=await bt(`${t.baseUrl}/upload/initiate`,{method:"POST",headers:h,credentials:p,body:JSON.stringify({seal_id:n,content_type:"application/octet-stream",content_length:a.blob.size,file_id:r})},f.controlTimeoutMs,c);if(T.status===409)return null;if(!T.ok)throw await Qe(T,`Upload initiate failed${u}`,"NETWORK");let x=await T.json();return x.already_verified?null:x}),_=await S();if(_===null)return!1;let E=!1;if(await Yt(async({after:T})=>{if(T==="refresh_url"){let B=await S();if(B===null){E=!0;return}_=B}let{upload_url:x}=_,M=await bt(x,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},Sn(a.blob.size,f),c);if(M.status===400&&(await M.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new P(`Upload arrived corrupted (BadDigest)${u}`,"BAD_DIGEST",400,void 0,!0);if(!Fi(M.status))throw new P(`Upload PUT failed${u}: ${M.status}`,"NETWORK",M.status)},{clock:d,policy:f,signal:c,classify:ua,what:`PUT${u}`}),E)return!1;d.delivered(),o();let y=await g(`confirm${u}`,async()=>{let T=await bt(`${t.baseUrl}/upload/confirm`,{method:"POST",headers:h,credentials:p,body:JSON.stringify({seal_id:n,file_id:r,...t.onConflict?{on_conflict:t.onConflict}:{}})},f.controlTimeoutMs,c);if(T.status===409)return!1;if(!T.ok)throw await Qe(T,`Upload confirm failed${u}`,"NETWORK");let x=await T.json().catch(()=>null);return typeof x?.conflict_with=="string"&&e.onConflictWith(x.conflict_with),x?.status==="verified"});return d.delivered(),y}async function Oa(e,t,n,r,a,s){try{let o=await bt(`${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 P&&o.code==="ABORTED")throw o;return null}}var Wi=new Set(["failed","size_mismatch","verification_error"]),Hi=new Set(["verified","pending_verification"]);async function Ki(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i}=e,c=s.verifyFallbackWaitMs,d=performance.now(),f=s.verifyPollBackoffMs;for(let u=0;;u++){let h=f[Math.min(u,f.length-1)]??0;if(performance.now()-d+h>c)return"pending";h>0&&await Cn(h,o);let p=await Oa(t,n,r,a,s,o);if(p==="verified")return"verified";if(p!==null&&Wi.has(p))throw new P(`The server rejected ${i} after upload (${p}). It has to be sent again.`,"VERIFICATION_REJECTED");if(p===null&&u===0)return"pending"}}async function zi(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:c}=t,{onProgress:d,signal:f}=n;if(t.state!=="pending")return;if(f?.aborted)throw new P("Upload aborted","ABORTED");let u=Fn(r),h=en(u),p=Dn(a.transport),g=async R=>{if(t.state=R?"verified":"uploaded",!R)try{await Ki({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:h,transport:p,signal:f,label:o.name})==="verified"&&(t.state="verified")}catch(Z){throw Z instanceof P&&Z.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),Z}};if(Ia(o.size,a)){if(t.streamed){let v=await Oa(r,s,t.sha256_hex,h,p,f);if(v!==null&&Hi.has(v)){await g(v==="verified");return}}let R=Kr("multipart",v=>d?.(v)),Z=null,ge=await Oi({file:o,sealId:s,fileId:c,key:i,header:t.header,baseUrl:r.baseUrl,auth:u,partSize:Li(o.size,a),onProgress:v=>{Z=v;let D=v.phase==="done";R({...v,phase:D?"verifying":v.phase,fraction:D?0:v.deliveredBytes/v.totalBytes,preparedFraction:v.totalBytes>0?(v.preparedBytes??0)/v.totalBytes:0,preparedBytes:v.preparedBytes})},signal:f,transport:a.transport,onStreamed:()=>{t.streamed=!0},onConflict:r.onConflict});t.streamed=void 0,t.conflictWith=ge.conflictWith,await g(ge.verified);let O=t.encryptedSize;R({...Z??{phase:"done",percent:100,deliveredBytes:O,totalBytes:O,state:"running",attempt:1},phase:"done",fraction:1});return}let S=Kr("single-put",R=>d?.(R)),_=t.encryptedSize,E={phase:"encrypting",fraction:0,delivered:!1},y=null,T=(R,Z,ge=E.delivered)=>{E={phase:R,fraction:Z,delivered:ge},S({phase:R,fraction:Z,deliveredBytes:ge?_:0,totalBytes:_,state:y?.state??"running",attempt:(y?.retriesSinceDelivery??0)+1})};t.prepared||(T("encrypting",0),t.prepared=await ai(o,i,t.header,R=>T("encrypting",o.size>0?R/o.size:1)));let x=t.prepared,M=new fa(p,()=>T(E.phase,E.fraction));y=M,T("uploading",0);let B;try{B=await $i({ctx:r,sealId:s,fileId:c,ciphertext:x,authHeaders:h,onVerifying:()=>T("verifying",0,!0),label:o.name,signal:f,clock:M,transport:p,onConflictWith:R=>{t.conflictWith=R}})}finally{M.dispose()}T("verifying",.5,!0),await g(B),t.prepared=void 0,T("done",1,!0)}async function Gi(e,t={}){let{signal:n,onFileProgress:r}=t,a=h=>Ia(h.file.size,e.policy),s=e.pending,o=s.filter(h=>!a(h)),i=s.filter(a),c=new AbortController,d=()=>c.abort();n?.aborted?c.abort():n?.addEventListener("abort",d,{once:!0});let f=null,u=async h=>{try{await zi(e,h,{signal:c.signal,onProgress:p=>r?.(h,p)})}catch(p){f===null&&(f=p,c.abort())}};try{let h=0,p=async()=>{for(;f===null&&!c.signal.aborted&&h<o.length;)await u(o[h++])};await Promise.all(Array.from({length:Math.min(C.upload.SMALL_FILE_POOL,o.length)},p));for(let g of i){if(f!==null||c.signal.aborted)break;await u(g)}}finally{n?.removeEventListener("abort",d)}if(f!==null)throw f;if(n?.aborted)throw new P("Upload aborted","ABORTED")}function ji(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 Yi(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 Vi(e,t,n,r,a={}){let s=await Fr(a.relativePath??e.name,t,"name"),o=await Fr(e.type||yi(e.name),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:Se.current_format_version};return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function Xi(e,t,n,r,a){if(n?.aborted)throw new P("Upload aborted","ABORTED");let s=tt(e,t);return new Promise((o,i)=>{let c=!1,d=p=>{c||(c=!0,h(),i(p),s.then(async g=>g.ok?r(await g.json()):void 0).catch(()=>{}))},f=()=>d(new P("Upload aborted","ABORTED")),u=setTimeout(()=>d(new P(`The registration got no answer in ${Math.round(a/1e3)} s`,"NETWORK",void 0,void 0,!0)),a),h=()=>{clearTimeout(u),n?.removeEventListener("abort",f)};n?.addEventListener("abort",f,{once:!0}),s.then(p=>{c||(c=!0,h(),o(p))},p=>{c||(c=!0,h(),i(p))})})}function qi(e){return Dn(e.transport).completeTimeoutMs}async function Zi(e,t,n,r){try{return Ui(e,t,n)}catch(a){throw await r((e??[]).filter(s=>s.sha256_hex!==void 0&&t.includes(s.sha256_hex))).catch(()=>{}),a}}async function Ji(e,t){if(t?.aborted)throw await e.cancel(),new P("Upload aborted","ABORTED")}async function Qi(e,t,n,r,a){let s={files_meta:t};e.ownerTokenHash&&(s.owner_token_hash=e.ownerTokenHash),Yi(s,e);let o=await Xi(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...en(Fn(e))},credentials:e.credentials??"include",body:JSON.stringify(s)},n,r,a);if(!o.ok)throw await Qe(o,"Create seal failed","UNKNOWN");return await o.json()}async function el(e,t){let n=bo();return{file:e,key:t,header:n,sha256_hex:await Ze(n)}}async function tl(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 nl(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:Pn(n.file.size),state:"pending"}))}function Ra(e){let t=new Map;for(let n of e)t.set(n.sha256_hex,n.key);return t}function rl(e){let t=e.reduce((a,s)=>a+s.file.size,0),n=new Map;for(let a of e)n.set(a.index,a.state==="pending"?0:100);let r=0;return{note(a,s){n.set(a.index,s.phase==="done"?100:Math.max(n.get(a.index)??0,s.percent));let o=e.every(d=>n.get(d.index)===100),i=e.reduce((d,f)=>d+f.file.size*(n.get(f.index)??0),0),c=t>0?Math.floor(i/t):100;return r=Math.max(r,o?100:Math.min(99,c)),{percent:r,finished:o}}}}async function al(e,t){let{onProgress:n,signal:r}=t,a=e.files,s=rl(a);await Gi(e,{signal:r,onFileProgress:(o,i)=>{n?.({fileIndex:o.index,totalFiles:a.length,fileName:o.file.name,fileProgress:i,overallPercent:s.note(o,i).percent})}})}async function Pa(e,t,n,r,a){if(t.length===0)throw new Error("At least one file is required");ji(e);let s=await Promise.all(t.map(({file:u})=>el(u,ko()))),o=await Promise.all(s.map((u,h)=>Vi(u.file,u.key,Pn(u.file.size),u.sha256_hex,{relativePath:t[h].relativePath}))),i=(u,h)=>new $n({ctx:e,policy:n,sealId:u.id,createdSeal:!0,expiresAt:u.expires_at,files:h},async(p,g)=>(await al(p,g),a(p))),c=await Qi(e,o,r.signal,u=>i(u,[]).cancel(),qi(n)),d=await Zi(c.files,s.map(u=>u.sha256_hex),`Create seal ${c.id}`,()=>i(c,[]).cancel()),f=i(c,nl(s,d));return await Ji(f,r.signal),await tl(r,c.id,s,d),f.resume(r)}async function La(e,t,n=We,r={}){return Pa(e,t.map(a=>({file:a})),n,r,a=>({sealId:a.sealId,files:a.files.map(s=>({fileId:s.fileId,sha256_hex:s.sha256_hex,encryptedSize:s.encryptedSize})),encryptionKeys:Ra(a.files),expiresAt:a.expiresAt,verification:a.verification}))}async function Da(e,t,n,r=We,a={},s){if(s&&s.length!==t.length)throw new Error(`uploadFolderAsFiles: ${t.length} file(s) but ${s.length} path(s)`);let o=t.map((i,c)=>({file:i,relativePath:s?.[c]||i.webkitRelativePath||`${n}/${i.name}`}));return Pa(e,o,r,a,i=>({sealId:i.sealId,files:i.files.map(c=>({fileId:c.fileId,sha256_hex:c.sha256_hex,encryptedSize:c.encryptedSize,relativePath:o[c.index].relativePath})),encryptionKeys:Ra(i.files),folderName:n,expiresAt:i.expiresAt,verification:i.verification}))}var zr=[2e3,4e3,8e3,15e3],mn=ye.limits.TIER_BYTES,Pc=Object.keys(mn).filter(e=>e!=="free").sort((e,t)=>mn[e]-mn[t]);function Na(e){return e instanceof P&&e.httpStatus===402&&e.session?e.session:null}function Ca(e,t=Date.now()){let n=t+ye.limits.PAYMENT_WAIT_MAX_SECONDS*1e3,r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)?Math.min(n,r):n}async function Ma(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 te&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=zr[Math.min(a,zr.length-1)];if(Date.now()+s>r.deadline)return null;await Cn(s,r.signal)}}var tn=ye.limits.ttl_options;function Ba(e){let t=e.trim();if(t==="")return;let n=/^\d+$/.test(t)?Number(t):Number.NaN;return n>=1&&n<=ye.limits.MAX_OPENS_PER_SEAL_FREE?n:null}var sl=new Set(["AC","CP","CQ","DG","EA","EU","EZ","IC","QO","TA","UN","XA","XB","ZZ"]),En;function Ua(e){En??(En=new Intl.DisplayNames(["en"],{type:"region",fallback:"none"}));let t=[],n=[];for(let r of e.split(/[\s,;]+/)){if(r==="")continue;let a=r.toUpperCase(),s=/^[A-Z]{2}$/.test(a)?Intl.getCanonicalLocales(`und-${a}`)[0]?.split("-")[1]:void 0;!s||sl.has(s)||!En.of(s)?n.push(r):t.includes(s)||t.push(s)}return{codes:t,bad:n}}var Wn=8,Hn=43,kn=4,nn=/^[A-Za-z0-9_-]+$/;function ol(e,t){if(!nn.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 Kn(e){return e.length===Wn&&nn.test(e)}function zn(e){return e.length===Hn&&ol(e,32)}function Fa(e,t){if(!Kn(e))throw new Error(`Invalid sealId: must be ${Wn} base64url characters`);if(!zn(t))throw new Error(`Invalid linkKey: must be ${Hn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function $a(e,t,n){if(!Kn(e))throw new Error(`Invalid sealId: must be ${Wn} base64url characters`);if(t.length!==kn||!nn.test(t))throw new Error(`Invalid shareCode: must be ${kn} base64url characters`);if(!zn(n))throw new Error(`Invalid linkKey: must be ${Hn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var zt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function il(e){let t;try{t=new URL(e)}catch{throw new zt("url_invalid",`not a valid URL (${e.length} characters)`)}let n;try{n=ll(t.pathname.replace(/\/+$/,""))}catch{throw new zt("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(!zn(r))throw new zt("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 ll(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(!Kn(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==kn||!nn.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var Gn=Ee.scopes.share_link,Wa=Ee.scopes.owner_copy;var Gr=et.sealed_box_v2.version_byte,jr=et.sealed_box_v2.packed_length,mt=64,Jt=32,Yr=32;var Ha=/^[A-Za-z0-9_-]+$/;function Ka(){return crypto.getRandomValues(new Uint8Array(mt))}async function jn(e,t=1){let n=await ft();if(e.length===mt)return n.WasmIdentity.fromSeed64(e,t);if(e.length===Jt)return n.WasmIdentity.fromSeed32(e);throw new Error(`a seed is ${mt} bytes, or the ${Jt} of a key made before, got ${e.length}`)}async function Yn(e,t=1){let n=await jn(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words()}}finally{n.free()}}function za(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(!Ha.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 Ga(e,t){return(await ft()).wasm_bundle_verify_for_address(e,t)}async function Vn(e){return(await ft()).wasm_bundle_address(e)}async function rn(e,t,n,r){if(e.length!==Yr)throw new Error(`a wrapped key is ${Yr} bytes, got ${e.length}`);if(r.length===0)throw new Error("the scope id must not be empty: the wrap binds to it");return ae((await ft()).wasm_sealbox_wrap(e,t,n,r))}var Ye=class extends Error{constructor(e,t,n){super(t),this.name="WrapError",this.kind=e,this.cause=n}};async function cl(e,t,n,r,a=1){if(r.length===0)throw new Ye("parse","the scope id must not be empty: the wrap binds to it");if(!Ha.test(e))throw new Ye("parse","the wrap is not urlsafe-base64-no-pad");let s=ue(e);if(s[0]!==Gr)throw new Ye("parse",`the wrap is not a sealed box v${Gr}: a newer client made it \u2014 update this one`);if(s.length!==jr)throw new Ye("parse",`the wrap is ${s.length} bytes, expected ${jr}`);if(t.length!==mt&&t.length!==Jt)throw new Ye("parse",`a seed is ${mt} bytes, or the ${Jt} of a key made before, got ${t.length}`);let o=await jn(t,a);try{return o.open(s,n,r)}catch(i){throw new Ye("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 dl(e,t){let n=await jn(e);try{let r=n.inboxProof(BigInt(t.ts),ue(t.challenge));return`${t.ts}.${t.challenge}.${ae(r)}`}finally{n.free()}}var Tn={version:2,name:"FINGERPRINT_WORDS",description:"Eight words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3; eight since AUDIT K251, owner 11.11: eight words, 24 bits, were ground in 207 s on one Mac): word i (i = 0 \u2026 7) is words[byte i of SHA-256(identity public key)] \u2014 the first eight 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 64 bits in all, written in lower case with one space between them; the first three are the three of before. 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:8,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:"66687aadf862bd77",words:"iron ivory lava plum yacht horse river lagoon"}},ul=Tn.words,hl=/^[A-Za-z0-9_-]{43}$/;function ja(e){if(!hl.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=ue(e);return Array.from(t.subarray(0,Tn.count),n=>ul[n]).join(Tn.separator)}var Ya=Ee.payloads.pair.mime,Dc=Ee.payloads.device.mime,Nc=Ee.payloads.delivery.mime,Cc=Ee.payloads.approve.mime,Mc=Ee.payloads.approve_answer.mime,Bc=Ee.payloads.summary.mime,Va=Ee.pair_what,Vr=Ee.payloads.name_max,Uc=ye.limits.APPROVE_BODY_SHOWN_BYTES;var Xr=et.keybundle.packed_length,qr=2;var fl=/^[A-Za-z0-9_-]+$/;function Xa(e){let t=pl(e,"pairing");if(typeof t.bundle!="string"||!fl.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:_l(ue(t.bundle)),name:yl(t.name)}}function pl(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!==qr)throw new Error(`${t} payload is not version ${qr}`);return n}function _l(e){if(e.length!==Xr)throw new Error(`a bundle is ${Xr} bytes, got ${e.length}`);return e}function yl(e){if(typeof e!="string"||e.length===0||e.length>Vr)throw new Error(`name must be 1 to ${Vr} characters`);return e}var gl={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 match of an entry with `checksum` is a finding only when it passes that sum: `luhn` \u2014 the Luhn sum of its digits is 0 modulo 10; `iban` \u2014 its characters but spaces, upper-cased, the first four moved to the end, each letter read as a number (A = 10 \u2026 Z = 35), are 1 modulo 97. 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,wildcard_public_second_level:["ac","co","com","edu","gov","go","ne","net","or","org","mil","int","gob","ltd","plc","me","nom"],shared_host_suffixes:["s3.amazonaws.com","cloudfront.net","azurewebsites.net","appspot.com","firebaseapp.com","web.app","github.io","githubusercontent.com","gitlab.io","herokuapp.com","pages.dev","workers.dev","vercel.app","netlify.app","onrender.com","fly.dev","blogspot.com","ngrok.io","ngrok-free.app","glitch.me","surge.sh"],shared_host_note:"Names under which each customer has a name of its own (the private part of the public suffix list): a host there is one service with the label before it, as `x.co.uk` is \u2014 AUDIT K162: by its last two labels every github.io page was one service.",wildcard_note:"A proposed `*.<name>` binds a key unless <name> is a public suffix: one label (`*.com`), or two where the second is a two-letter country top level and the first is one of wildcard_public_second_level (`*.co.uk` would be a root for every .co.uk host; `*.me.com` is a name of its own); a bare name needs two labels (SPEC agent egress \xA74.2, review of phase 1).",guard_note:"What the guard does with a key of an entry (SPEC agent egress \xA74.1, read by `seal-client-core::guard`). `hosts`: where the key is a way in, the default binding a person confirms or narrows; `*.` is one label. `place`: where the guard puts the value \u2014 `bearer` (Authorization: Bearer), `header:<name>`, `query:<param>`, `basic_user`, `basic_pass`, `userinfo`, `url` (the secret is the request address itself, a webhook). `class`: `outbound` \u2014 a key a program enters a service with, the proxy puts it in; `inprocess` \u2014 a key a program works with itself (a webhook signing secret, a database password of a driver that uses no proxy, a private key, an assignment the pattern matches with its name): the program gets the value, by the person's word on the page. `surrogate`: the form of the stand-in the agent sees \u2014 `keep_prefix` (kept as it is), `alphabet` (`base62`, `base64url`, `hex`, `digits`, `base32`, `classes` \u2014 each character keeps its class and punctuation stays), `length` (a number, else the value's), `checksum` (`github_crc32`: the last six characters are the CRC32 of the body, base62), `parts` (`password`: of a connection URI only the password changes). An entry without `surrogate` is treated by classes. `provision_commands`: commands that write a key as data into a service's own store; a surrogate in their arguments or stdin is refused unless the binding's `provision` names the host (\xA75.4, \xA76.4). Data, not code: a service is added with one entry.",provision_commands:[{command:"wrangler secret put",host:"api.cloudflare.com"},{command:"gh secret set",host:"api.github.com"},{command:"vercel env add",host:"api.vercel.com"},{command:"fly secrets set",host:"api.machines.dev"},{command:"kubectl create secret",host:null},{command:"aws secretsmanager put-secret-value",host:"*.amazonaws.com"},{command:"heroku config:set",host:"api.heroku.com"},{command:"doppler secrets set",host:"api.doppler.com"}],patterns:[{name:"openai_api_key",pattern:"\\bsk-proj-[A-Za-z0-9_-]{40,}",severity:"critical",description:"OpenAI API Key",keywords:["openai","sk-proj-"],hosts:["api.openai.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^sk-proj-",alphabet:"base64url"},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-"],hosts:["api.anthropic.com"],place:"header:x-api-key",class:"outbound",surrogate:{keep_prefix:"^sk-ant-(?:api[0-9]{2}-)?",alphabet:"base64url"},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_"],hosts:["api.github.com","github.com","uploads.github.com","codeload.github.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^(?:gh[pousr]|github_pat)_",alphabet:"classes",checksum:"github_crc32"},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"],hosts:["gitlab.com"],place:"header:PRIVATE-TOKEN",class:"outbound",surrogate:{keep_prefix:"^glpat-",alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:"^(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)",alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]?`,alphabet:"classes"},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"],hosts:["api.stripe.com","files.stripe.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^[sr]k_live_",alphabet:"base62"},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"],hosts:["api.stripe.com","files.stripe.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^[sr]k_test_",alphabet:"base62"},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:"stripe_webhook_secret",pattern:"\\bwhsec_[A-Za-z0-9]{32,}",severity:"critical",description:"Stripe Webhook Signing Secret",keywords:["stripe","webhook","whsec_"],class:"inprocess",surrogate:{keep_prefix:"^whsec_",alphabet:"base62"},vectors:{hit:"STRIPE_WEBHOOK_SECRET=whsec_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"STRIPE_WEBHOOK_SECRET=whsec_short"}},{name:"slack_token",pattern:"\\bxox[abprs]-[A-Za-z0-9-]{20,}",severity:"critical",description:"Slack Token",keywords:["slack","token","xox"],hosts:["slack.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^xox[abprs]-",alphabet:"classes"},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"],hosts:["hooks.slack.com"],place:"url",class:"outbound",surrogate:{keep_prefix:"^https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B",alphabet:"classes"},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"],hosts:["*.googleapis.com"],place:"query:key",class:"outbound",surrogate:{keep_prefix:"^AIza",alphabet:"base64url"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]?`,alphabet:"classes"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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."],hosts:["api.sendgrid.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^SG\\.",alphabet:"classes"},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"],hosts:["api.twilio.com"],place:"basic_user",class:"outbound",surrogate:{keep_prefix:"^SK",alphabet:"hex"},vectors:{hit:"SK0123456789abcdef0123456789abcdef",clean:"SK0123456789abcdef"}},{name:"npm_token",pattern:"npm_[A-Za-z0-9]{36}",severity:"high",description:"NPM Access Token",keywords:["npm","token"],hosts:["registry.npmjs.org"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^npm_",alphabet:"base62"},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"],hosts:["upload.pypi.org"],place:"basic_pass",class:"outbound",surrogate:{keep_prefix:"^pypi-",alphabet:"base64url"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]`,alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]`,alphabet:"classes"},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"}},{name:"payment_card",pattern:"\\b(?:\\d[ -]?){12,18}\\d\\b",checksum:"luhn",severity:"high",description:"Payment Card Number",keywords:["card","visa","mastercard"],vectors:{hit:"card: 4111 1111 1111 1111",clean:"card: 4111 1111 1111 1112"}},{name:"iban",pattern:"\\b[A-Z]{2}\\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\\b",checksum:"iban",severity:"high",description:"IBAN",keywords:["iban","bank","account"],vectors:{hit:"IBAN DE89 3704 0044 0532 0130 00, please",clean:"IBAN DE89 3704 0044 0532 0130 01, please"}},{name:"passport_number",pattern:"\\bpassport(?:\\s*(?:no|number|#))?\\.?\\s*[:=#]?\\s*[A-Z]{0,2}[0-9]{6,9}\\b",severity:"high",description:"Passport Number",keywords:["passport"],vectors:{hit:"Passport No: X1234567",clean:"Passport photos: 2 copies"}}]},an=gl.mime,W=class extends Error{constructor(e,t,n){super(t),this.name="OpenError",this.code=e,this.cause=n}},wl=32;async function Xn(e,t,n={}){let r;try{r=il(t)}catch(y){throw y instanceof zt?new W(y.code,y.message,y):y}if(r.shareCode===null)throw new W("url_invalid","share code missing from the URL path (/s/<seal_id>/<share_code>#<key>)");let{sealId:a,shareCode:s}=r,o=n.seed,i=n.wrap??null,c=r.fragmentVariant==="key"?ue(r.fragment):i!==null&&o?await Zr(i,o,a):null;c!==null&&await Or(a,c);let d=n.signal?{signal:n.signal}:{},f;try{f=await e.getMetadata(r.sealId,{...d,shareCode:s})}catch(y){throw y instanceof te&&(y.code==="not_found"||y.code==="revoked")?new W(y.code==="revoked"?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${y.code==="revoked"?"has been revoked":"was not found or has expired"}`,y):new W("metadata_failed",`reading seal ${r.sealId} failed: ${In(y)}`,y)}let u=Fo(f);if(u.revokedAt!==null)throw new W("seal_revoked",`seal ${r.sealId} has been revoked`);if(u.files.length===0)throw new W("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 h;try{let y=await e.getShareBlob(a,s,d);if(h=y.blob,c===null){if(y.wrap===null)throw new W("url_no_fragment","the link carries no key after #: copy it whole");if(!o)throw new W("targeted_fragment_invalid","this link is addressed to someone: pass their seed to open it");c=await Zr(y.wrap,o,a),await Or(a,c)}}catch(y){throw y instanceof W?y:y instanceof te&&(y.code==="not_found"||y.code==="revoked")?new W(y.code==="revoked"?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${y.code==="revoked"?"has been revoked":"was not found"}`,y):new W("share_blob_fetch_failed",`share blob fetch failed: ${In(y)}`,y)}let p,g,S,_;try{let y=await Jo(h,c);p=y.file_keys,g=qo(y),S=y.message?.trim()?y.message:null,_=Vo(y.nda_file)?y.nda_file:null}catch(y){throw new W("share_blob_decrypt_failed","the share blob does not open with this link \u2014 mistyped URL, or the link was revoked and minted again",y)}let E=await Promise.all(u.files.map(y=>vl(y,p,g)));return{sealId:a,shareCode:s,expiresAt:u.expiresAt,singleUse:u.singleUse,maxOpens:u.maxOpens,otpRequired:u.otpRequired,ndaRequired:u.ndaRequired,otpPassed:f.otp_session_valid===!0,ndaPassed:f.nda_session_valid===!0,spent:f.spent===!0,countries:f.geo_allowlist?.length?f.geo_allowlist:null,message:S,ndaFile:_,linkKey:c,files:E}}async function Zr(e,t,n){try{return await cl(e,t,Gn,n)}catch(r){let a=r instanceof Ye&&r.kind==="aead";throw new W(a?"targeted_decrypt_failed":"targeted_fragment_invalid",In(r),r)}}async function qa(e,t,n={}){for(;;){n.signal?.throwIfAborted();let r=Date.now(),a;try{a=await e.getIntake(t,{...n,waitSeconds:ye.limits.INTAKE_WAIT_MAX_SECONDS})}catch(o){throw o instanceof te&&o.code==="not_found"?new W("request_expired","the request expired before anybody answered",o):o}if(a.status==="expired")throw new W("request_expired","nobody answered before the request expired");if(a.status==="fulfilled"){if(a.share_path&&a.fragment)return{sharePath:a.share_path,wrap:a.fragment};throw new W("share_blob_corrupt","the request was answered without its link")}if(a.status!=="pending")throw new W("client_outdated",`the request is ${String(a.status)}, a state this client does not know`);let s=bl-(Date.now()-r);s>0&&await ml(s,n.signal)}}var bl=2e3;function ml(e,t){return new Promise((n,r)=>{let a=()=>{clearTimeout(s),r(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}var Jr=64*1024;async function Za(e,t,n,r){let a=await Xn(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||Qa(s.mime)!==n||s.size>Jr)throw new W("share_blob_corrupt",`the answer is not one ${n} file`);return El(e,{sealId:a.sealId,shareCode:null},s,{maxBytes:Jr,...r.signal?{signal:r.signal}:{}})}async function El(e,t,n,r){if(!n.key||!n.sha256Hex||n.size>r.maxBytes)throw new W("share_blob_corrupt",`file ${n.id} is not one of at most ${r.maxBytes} bytes this link opens`);let a=await e.downloadCiphertext(t.sealId,{fileId:n.id,...t.shareCode?{shareCode:t.shareCode}:{},...r.sessionCookie?{sessionCookie:r.sessionCookie}:{},...r.visit?{visit:r.visit}:{}},r.signal?{signal:r.signal}:{});if(!a.body)throw new W("share_blob_corrupt",`file ${n.id} came without a body`);let s=Zn(a.body,n.key,n.sha256Hex).stream.getReader(),o=[];for(let d=await s.read();!d.done;d=await s.read())o.push(d.value);let i=new Uint8Array(o.reduce((d,f)=>d+f.length,0)),c=0;for(let d of o)i.set(d,c),c+=d.length;return i}var Sl=3e4,Qr=new Map;async function Al(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&Tl(r,t.bundle)||await e.putBundle(t.bundle,n)}async function Qt(e,t,n={}){let r=await Yn(t),a=`${e.baseUrl} ${r.address}`,s=Qr.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await Al(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await dl(t,o)};return Qr.set(a,{proof:i,until:Date.parse(o.expires_at)-Sl}),i}async function sn(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await Qt(e,t,a))}catch(s){if(!(s instanceof te&&s.appCode==="intake.proof_required"))throw s;return r(await Qt(e,t,{...a,fresh:!0}))}}async function qn(e,t,n={}){let r=n;return sn(e,t,n.signal,a=>e.listInbox(a,r))}async function Ja(e,t,n,r={}){return sn(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function vl(e,t,n){let r=e.sha256_hex?t[e.sha256_hex]:void 0,a={id:e.id,size:e.size,sha256Hex:e.sha256_hex};if(r===void 0)return{...a,name:Xt,mime:qt,secret:!1,key:null,binding:null};let s;try{s=ue(r)}catch(f){throw new W("share_blob_corrupt",`share blob carries a non-base64url key for ${e.sha256_hex}`,f)}if(s.length!==wl)throw new W("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${s.length} bytes`);let{name:o,mime:i}=await mi(e,s),c=Qa(i)===an,d=c&&e.sha256_hex?n[e.sha256_hex]??null:null;return{...a,name:o,mime:i,secret:c,key:s,binding:d}}function Qa(e){return(e.split(";")[0]??e).trim().toLowerCase()}function Zn(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=$t.create(),o=0,i,c=new Promise((h,p)=>{i={resolve:h,reject:p}});c.catch(()=>{});let d=new TransformStream({transform(h,p){r(h.length),p.enqueue(h)}}),f=new TransformStream({transform(h,p){s.update(h),o+=h.length,p.enqueue(h)},flush(){a.fill(0),i.resolve({sizeBytes:o,sha256:kl(s.digest())})}}),u=e.pipeThrough(d).pipeThrough(ii(a,{expectedSha256Hex:n})).pipeThrough(f);return{stream:Il(u,i.reject,a),done:c}}function xl(e){return e instanceof Me?new W(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function kl(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Tl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Il(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=xl(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function In(e){return e instanceof Error?e.message:String(e)}var $c=ye.limits.LEASE_DEFAULT_DAYS,Wc=ye.limits.LEASE_MAX_DAYS,Hc=ye.limits.LEASE_POLL_SECONDS,Kc=ye.limits.LEASE_STATUS_BATCH_MAX;async function ts(){let e=ba(),t=Mn();return{ownerTokenB64:ae(e),ownerTokenHash:await ma(e),linkKey:t,linkKeyB64:ae(t)}}var ns=tn[tn.length-1]??tn[0],Jn={ttl:"1h",singleUse:!0};function rs(e,t,n){return{ttl:n&&e.ttl!=="1d"&&e.ttl!=="7d"?"1d":e.ttl,...n?{tier:n}:{},...e.otp?{otp:e.otp}:{},nda:e.nda??!1,...e.nda&&e.ownerEmail?{ownerEmail:e.ownerEmail}:{},singleUse:e.singleUse??!1,...!e.singleUse&&e.maxOpens?{maxOpens:e.maxOpens}:{},...e.geo&&e.geo.length>0?{geo:e.geo}:{},ownerTokenHash:t.ownerTokenHash,ownerToken:t.ownerTokenB64}}var ad={...We,transport:{maxStallMs:1/0}};function as(e,t){let{ttl:n,tier:r,otp:a,nda:s,ownerEmail:o,singleUse:i,maxOpens:c,geo:d,ownerTokenHash:f,ownerToken:u}=t;return{baseUrl:e,auth:{kind:"none"},ttl:n,...r?{tier:r}:{},...a?{otp:a}:{},...s!==void 0?{nda:s}:{},...o?{ownerEmail:o}:{},...i!==void 0?{singleUse:i}:{},...c?{maxOpens:c}:{},...d&&d.length>0?{geo:[...d]}:{},ownerTokenHash:f,ownerToken:u}}var At=class extends Error{};async function ss(e){let{keys:t,ndaFileName:n,api:r}=e,a=e.message?.trim()?e.message:void 0,s=await e.upload(async(p,g)=>{e.registered?.(p);let{fileKeys:S,ndaFile:_}=es(g,n),E=ae(await Ea(t.ownerTokenB64,S,t.linkKey,a,_));await Ol(r,p,t.ownerTokenB64,E),await e.ownerBlobStored?.(p)});e.uploaded?.(s);let o=s.fileResults.map(p=>{let g=s.encryptionKeys.get(p.sha256_hex);if(!g)throw new Error(`the upload returned no key for the file ${p.fileId}`);return{sha256_hex:p.sha256_hex,key:g}}),{fileKeys:i,ndaFile:c}=es(o,n),d=Mn(),f={blobB64:ae(await Sa(i,d,a,c)),linkKeyB64:ae(d)};e.minting?.(f);let{to:u}=e;if(u){let p=await rn(d,u.bundle,Gn,s.sealId),g=u.label?.slice(0,80),S=x=>r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,d,{to:u.address,fragment:p,...g?{label:g}:{},...x?{sender:x}:{}}),_=async x=>await u.sender?.(x).catch(()=>null)??null,E=x=>x instanceof te&&x.appCode==="intake.proof_required",y=await _(!1),T=await S(y).catch(async x=>{if(!y||!E(x))throw x;let M=await _(!0);return M?S(M).catch(B=>{if(E(B))return S(null);throw B}):S(null)});return{sealId:s.sealId,verification:s.verification,shareCode:T,share:f}}let h=await r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,d).catch(()=>null);return{sealId:s.sealId,verification:s.verification,shareCode:h,share:f}}async function Ol(e,t,n,r){let a=null;for(let s=0;s<2;s++)try{await e.writeOwnerBlob(t,n,r);return}catch(o){a=o}throw new At(a instanceof Error?a.message:String(a),{cause:a})}function es(e,t){let n=e[e.length-1];return{fileKeys:new Map(e.map(r=>[r.sha256_hex,ae(r.key)])),ndaFile:t&&n?{sha256_hex:n.sha256_hex,name:t}:void 0}}var os={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,MAX_GEO_COUNTRIES:50,SEAL_VISIT_SECONDS:21600,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","eu-central","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,LEASE_DEFAULT_DAYS:7,LEASE_MAX_DAYS:90,LEASE_STATUS_BATCH_MAX:500,LEASE_POLL_SECONDS:600,LEASE_KEEP_DAYS:30,APPROVE_WAIT_SECONDS:120,APPROVE_BODY_SHOWN_BYTES:2048,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 Qn=["byte","kilobyte","megabyte","gigabyte","terabyte"],Pl=["B","KB","MB","GB","TB"];function is(e,t){let r=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),Qn.length-1):0,a=parseFloat((e/Math.pow(1024,r)).toFixed(2));return a>=1024&&r<Qn.length-1&&(r+=1,a=parseFloat((e/Math.pow(1024,r)).toFixed(2))),t?new Intl.NumberFormat(t,{style:"unit",unit:Qn[r],unitDisplay:r===0?"long":"short",maximumFractionDigits:2}).format(a):`${a} ${Pl[r]}`}var Ll=1e3,Dl=60*Ll,Nl=60*Dl,ld=24*Nl;var z=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&&Ml(a),Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},Cl=["ownerToken","ownerLinkKey"];function Ml(e){let t={...e};for(let n of Cl){if(!(n in t))continue;let r=t[n];delete t[n],Object.defineProperty(t,n,{value:r,enumerable:!1,writable:!1,configurable:!1})}return t}var Bl={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 fe(e,t,n=null){if(e instanceof z)return e;if(e instanceof W){let r=e.cause instanceof te?e.cause.status:400;return new z(e.message,Bl[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof te){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 z(e.detail??t,r,e.status,n,{cause:e})}return new z(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}function on(e){return e.split("/").filter(t=>t!==""&&t!=="."&&t!=="..")}var He=os.limits,Ad=He.ttl_options,Ul="Secret",Fl="Confidentiality Agreement",ln=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 St({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){t.nda&&!t.ownerEmail&&pe("ownerEmail is required when nda=true"),t.tier&&!t.onPaymentRequired&&pe("onPaymentRequired is required with tier");let{files:n,relativePaths:r,ndaDocument:a,secretAlone:s}=Wl(t),o=t.message?.trim()?t.message:void 0;o&&o.length>He.MAX_MESSAGE_LENGTH&&pe(`message: ${o.length} characters, at most ${He.MAX_MESSAGE_LENGTH}`),o&&a&&pe("message and ndaFile: the NDA is its text or its document, give one of them");let i=o??(a?`NDA document attached: ${a.name} (${is(a.size)})`:t.nda?Fl:void 0),c=$l(t,s);"to"in t&&!t.to&&pe("to: empty: an address holds a value");let d=(O,F)=>{if(F!==void 0)try{return za(F)}catch(v){throw new z(`${O}: ${v instanceof Error?v.message:String(v)}`,"VALIDATION_ERROR",400)}},f=d("to",t.to),u=d("owner",t.owner),h=t.signal?{signal:t.signal}:{},p=async O=>{let F=await this.api.getBundle(O,h);return F&&await Ga(F,O)?F:null},g=null;if(f){try{g=await p(f)}catch(O){throw fe(O,"Failed to read the recipient key")}if(!g)throw new z(`to: ${f} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let S=u?await p(u).catch(()=>null):null,_=t.keyPair?ue(t.keyPair.secretKey):null,E=O=>_?sn(this.api,_,t.signal,O):O(),y=await ts(),T={...as(this.baseUrl,rs(c,y,t.tier)),...this.credentials!==void 0?{credentials:this.credentials}:{}},x=null,M=O=>({sealId:O,ownerToken:y.ownerTokenB64,ownerLinkKey:y.linkKeyB64}),B=!1,R=!1,Z=null,ge=t.onProgress;try{let O=await ss({keys:y,ndaFileName:a?.name??null,message:i,api:{writeOwnerBlob:async(Q,ve,ce)=>{if(u&&S&&!R){let be=await rn(y.linkKey,S,Wa,Q),oe=await E(J=>this.api.writeOwnerBlob(Q,ve,ce,{...h,to:u,fragment:be,label:"sealnet",...J?{sender:J}:{}})).catch(()=>null);if(oe)return B=!0,oe;R=!0}return this.api.writeOwnerBlob(Q,ve,ce,h)},createShareLink:(Q,ve,ce,be,oe={})=>this.api.createShareLink(Q,ve,ce,be,{...oe,...h})},registered:Q=>{x=Q},upload:async Q=>{let ve={onRegistered:Q,...ge?{onProgress:oe=>ge({phase:oe.fileProgress.phase,percent:oe.overallPercent,fileIndex:oe.fileIndex,totalFiles:oe.totalFiles,fileName:oe.fileName})}:{},...h},ce,be;try{ce=r?await Da(T,n,"",We,ve,r):await La(T,n,We,ve),be=ce.expiresAt}catch(oe){let J=Na(oe);if(!J||!t.tier||!t.onPaymentRequired)throw oe;await t.onPaymentRequired(await this.api.createCheckout(J.sealId,y.ownerTokenB64,t.tier,h));let Ke=Ca(J instanceof $n?J.expiresAt:void 0),ke=await Ma(this.api,J.sealId,y.ownerTokenB64,{deadline:Ke,...h});if(!ke)throw await this.api.revoke(J.sealId,y.ownerTokenB64).catch(()=>{}),new z("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,M(J.sealId));ce=await J.resume(ve),be=ke.expires_at}if(!be)throw new z(`Seal ${ce.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,M(ce.sealId));return Z={result:ce,expiresAt:be},{sealId:ce.sealId,encryptionKeys:ce.encryptionKeys,fileResults:ce.files,verification:ce.verification}},...f&&g?{to:{address:f,bundle:g,label:"sealnet",..._?{sender:Q=>Qt(this.api,_,{...h,fresh:Q})}:{}}}:{}}),{result:F,expiresAt:v}=Z,D=O.shareCode;if(D===null)try{D=await this.api.createShareLink(O.sealId,y.ownerTokenB64,O.share.blobB64,ue(O.share.linkKeyB64),h)}catch(Q){throw fe(Q,"Seal created but share link mint failed",M(O.sealId))}let se=$a(O.sealId,D,O.share.linkKeyB64),G=`${this.shareUrlBase}${f?se.split("#")[0]:se}`,j=`${this.shareUrlBase}${Fa(O.sealId,y.linkKeyB64)}`,[we]=F.files,Y=we&&F.encryptionKeys.get(we.sha256_hex);if(!we||!Y)throw new z(`Seal ${O.sealId}: the upload returned no key for its first file`,"INTERNAL_ERROR",500,M(O.sealId));let nt=r??n.map(Q=>Q.name);return{sealId:O.sealId,shareUrl:G,ownerUrl:j,ownerToken:y.ownerTokenB64,expiresAt:v,encryptionKey:Ne(Y),fileId:we.fileId,files:F.files.map((Q,ve)=>({fileId:Q.fileId,name:nt[ve]})),delivered:f!==void 0,ownerCopy:B}}catch(O){if(O instanceof z||!x)throw O;let F=O instanceof At?O.cause:O;if(F instanceof te)throw fe(F,`Seal ${x} was created but its send did not finish`,M(x));let v=F instanceof Error?F.message:String(F);throw new z(`Seal ${x} was created but the create flow was interrupted: ${v}`,"INTERNAL_ERROR",500,M(x),{cause:O})}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw fe(a,"Failed to revoke seal")}}};function $l(e,t){"otp"in e&&!e.otp&&pe("otp: empty: a password holds a value");let n=e.maxOpens===void 0?void 0:Ba(String(e.maxOpens));n===null&&pe(`maxOpens: ${e.maxOpens}: a whole number from 1 to ${He.MAX_OPENS_PER_SEAL_FREE}`);let r=Ua((e.geoAllowlist??[]).join(" "));return r.bad.length>0&&pe(`geoAllowlist: ${r.bad.join(", ")}: two-letter country codes such as DE, CH, US`),r.codes.length>He.MAX_GEO_COUNTRIES&&pe(`geoAllowlist: ${r.codes.length} countries, at most ${He.MAX_GEO_COUNTRIES}`),{ttl:e.ttl??(t?Jn.ttl:ns),otp:e.otp,nda:e.nda,ownerEmail:e.ownerEmail,singleUse:e.singleUse??(t&&n===void 0?Jn.singleUse:void 0),maxOpens:n,geo:r.codes}}function Wl(e){let t=(a,s,o)=>o||(s instanceof File?s.name:"")||pe(`${a}: bytes need a filename`),n=[];if("secret"in e){(e.secret===void 0||e.secret.length===0)&&pe("secret: empty: a secret holds a value");let a=typeof e.secret=="string"?new Blob([e.secret]):e.secret;n.push({file:vt(a,Ul,an),secret:!0})}e.file!==void 0&&n.push({file:vt(e.file,t("file",e.file,e.filename),e.mimeType),secret:!1});for(let[a,s]of(e.files??[]).entries()){let o=vt(s.file,t(`files[${a}]`,s.file,s.filename),s.secret?an:s.mimeType);s.secret&&o.size===0&&pe(`files[${a}]: an empty secret`),n.push({file:o,secret:s.secret===!0})}for(let[a,s]of(e.folder??[]).entries()){let o=on(s instanceof File?ka(s)??s.name:s.path),i=o.at(-1);i||pe(`folder[${a}]: a file with no path`);let c=o.join("/");n.push(s instanceof File?{file:s,path:c,secret:!1}:{file:vt(s.file,i,s.mimeType),path:c,secret:!1})}let r=null;if(e.ndaFile!==void 0){e.nda||pe("ndaFile goes with nda: true");let{file:a,filename:s,mimeType:o}=e.ndaFile;r=vt(a,t("ndaFile",a,s),o),n.push({file:r,secret:!1})}return n.length===0&&pe("Nothing to seal: give file, files, folder or secret"),n.length>He.MAX_FILES_PER_SEAL&&pe(`A seal holds at most ${He.MAX_FILES_PER_SEAL} files: ${n.length} given`),{files:n.map(a=>a.file),relativePaths:n.some(a=>a.path!==void 0)?n.map(a=>a.path??a.file.name):void 0,ndaDocument:r,secretAlone:n.length===1&&n[0].secret}}function pe(e){throw new z(e,"VALIDATION_ERROR",400)}function vt(e,t,n){let r=n||e instanceof File&&e.type||"application/octet-stream";if(e instanceof File&&e.name===t&&e.type===r)return e;if(e instanceof Blob)return new File([e],t,{type:r});let a=e instanceof Uint8Array?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e;return new File([a],t,{type:r})}async function ls(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),c=!1;try{await e.stream.pipeTo(new WritableStream({async write(p){await i.write(p)}}));let{sizeBytes:d,sha256:f}=await e.done;await i.sync(),await i.close();let u=a.extname(n),h=n.slice(0,n.length-u.length);for(let p=0;p<1e3;p++){let g=a.join(t,p===0?n:`${h} (${p})${u}`);try{await r.link(o,g)}catch(S){let _=S.code;if(_==="EEXIST")continue;if(_!=="EPERM"&&_!=="ENOTSUP"&&_!=="EOPNOTSUPP"&&_!=="ENOSYS")throw S;if(await r.access(g).then(()=>!0,()=>!1))continue;return await r.rename(o,g),c=!0,{path:g,sizeBytes:d,sha256:f}}return c=!0,await r.unlink(o).catch(()=>{}),{path:g,sizeBytes:d,sha256:f}}throw new Error(`no free name for ${n} in ${t}`)}finally{c||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}var Hl=/^[A-Za-z0-9_-]{86}$/;function xt(e){if(Hl.test(e.secretKey))return ue(e.secretKey);let t=e.secretKey.length===43?"This key is of the kind before: make a new one with keygen() and give its address to whoever sends to you. What was sent to the old address does not open.":"secretKey is not a SEAL key: expected the 86 base64url characters keygen() gives";throw new z(t,"INVALID_KEY",400)}async function cs(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await Xn(e,t,{...n.keyPair?{seed:xt(n.keyPair)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new z("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 z("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(_=>_.key!==null&&_.sha256Hex!==null),c=i.reduce((_,E)=>_+E.size,0),d=0,f=_a(),u=!1,h=Promise.resolve(),p=_=>e.downloadCiphertext(s.sealId,{fileId:_.id,visit:f,...o?{sessionCookie:o}:{}},a),g=_=>{if(u)return p(_);let E=h.then(async()=>{let y=await p(_);return u=!0,y});return h=E.catch(()=>{}),E};return{seal:s,covered:i,read:async _=>{let E=await g(_);if(!E.body)throw new z(`Download of ${_.name} returned no body`,"INTERNAL_ERROR",E.status);return Zn(E.body,_.key,_.sha256Hex,y=>{d+=y,n.onProgress?.(d,c)})}}}async function er(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await cs(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(c=>Promise.reject(fe(c,"Download failed")))}))}}catch(a){throw fe(a,"Failed to open the link")}}async function tr(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i}=await cs(e,t,r,a),c=[];for(let d of o){let f=on(d.name).map(g=>Un(g)),u=f.pop()??Un(d.name),h=f.length>0?[n||".",...f].join("/"):n,p=await ls(await i(d),h,u);c.push({name:d.name,mime:d.mime,secret:d.secret,...p})}return{sealId:s.sealId,expiresAt:s.expiresAt,files:c}}catch(s){throw fe(s,"Failed to open the link")}}async function ds(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 Vn(ue(n.recipientBundle))).words,expiresAt:r.expires_at}}catch(r){throw fe(r,"Failed to create the request")}}async function nr(e,t,n){try{return await qa(e,t,n?{signal:n}:{})}catch(r){throw fe(r,"Failed to wait for the request")}}async function us(e,t,n){let r;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:Va,kind:"pair"},n.signal?{signal:n.signal}:{})}catch(s){throw fe(s,"Failed to create the pairing request")}let a=async()=>{let{sharePath:s,wrap:o}=await nr(e,r.id,n.signal);try{let i=await Za(e,`${t}${s}`,Ya,{seed:xt(n.keyPair),wrap:o,...n.signal?{signal:n.signal}:{}}),{bundle:c,name:d}=Xa(i);return{address:(await Vn(c)).address,name:d}}catch(i){throw fe(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 hs(){let e=Ka(),{address:t,bundle:n,words:r}=await Yn(e);return{secretKey:ae(e),address:t,bundle:ae(n),words:r}}async function fs(e,t){let n=xt(t.keyPair),r=Date.now()+(t.wait??0)*1e3;try{for(;;){let a=Math.ceil((r-Date.now())/1e3),s=await qn(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:ja(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw fe(a,"Failed to read the inbox")}}async function ps(e,t,n,r){let a;try{a=(await qn(e,xt(r.keyPair),r.signal?{signal:r.signal}:{})).items}catch(o){throw fe(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new z(`${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 _s(e,t,n){try{await Ja(e,xt(n.keyPair),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw fe(r,"Failed to remove the item")}}var[Kl="",ys=""]="sdk-web/3.1.0".split("/");typeof globalThis.process?.versions?.node!="string"&&mr(me);var rr=class{seals;api;site;constructor(t={}){pa(Kl,ys);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new ln({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new St({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 ps(this.api,this.site,t,{keyPair:a.keyPair,...a.signal?{signal:a.signal}:{}});else throw new z("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?tr(this.api,s.url,r,a,s.wrap):er(this.api,s.url,a,s.wrap)}async inbox(t){return fs(this.api,t)}async dismiss(t,n){return _s(this.api,t,n)}async request(t){return ds(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await nr(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?tr(this.api,i,s,o,a):er(this.api,i,o,a)}async pair(t){return us(this.api,this.site,t)}async keygen(){return hs()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},zl=ys;return Ds(Gl);})();
1
+ /*! sealnet v3.1.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 Ts=Object.create;var Pt=Object.defineProperty;var Is=Object.getOwnPropertyDescriptor;var Os=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var cr=(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 Ls=(e,t)=>{for(var n in t)Pt(e,n,{get:t[n],enumerable:!0})},dr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Os(t))!Ps.call(e,a)&&a!==n&&Pt(e,a,{get:()=>t[a],enumerable:!(r=Is(t,a))||r.enumerable});return e};var ur=(e,t,n)=>(n=e!=null?Ts(Rs(e)):{},dr(t||!e||!e.__esModule?Pt(n,"default",{value:e,enumerable:!0}):n,e)),Ds=e=>dr(Pt({},"__esModule",{value:!0}),e);var Gl={};Ls(Gl,{SealClient:()=>rr,SealError:()=>z,VERSION:()=>zl});var me={url:"https://seal.net/sdk/v3.1.1/seal_crypto.wasm",integrity:"sha384-cxLyz7pU4Ov7nYYJ5cqyhupM04QkkuB7UI3Fvl8FkXp8uWcm8PvGYSYu0PFl4J0O"};var fo={},Cs=Object.defineProperty,Ms=(e,t)=>{for(var n in t)Cs(e,n,{get:t[n],enumerable:!0})},gr={};Ms(gr,{ContractTermsBuilder:()=>pn,WasmIdentity:()=>_n,default:()=>to,init:()=>Bs,initSync:()=>eo,wasm_approval_message:()=>Us,wasm_bundle_address:()=>Fs,wasm_bundle_verify_for_address:()=>$s,wasm_contract_message:()=>Ws,wasm_contract_message_v2:()=>Hs,wasm_ed25519_verify:()=>Ks,wasm_sealbox_wrap:()=>zs,wasm_summary_message:()=>Gs,wasm_unwrap_file_key:()=>js,wasm_wrap_file_key:()=>Ys});var pn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,hr.unregister(this),e}free(){let e=this.__destroy_into_raw();l.__wbg_contracttermsbuilder_free(e,0)}digest(){let e,t;try{let a=this.__destroy_into_raw(),s=l.__wbindgen_add_to_stack_pointer(-16);l.contracttermsbuilder_digest(s,a);var n=b().getInt32(s+0,!0),r=b().getInt32(s+4,!0);return e=n,t=r,Re(n,r)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(e,t,1)}}field(e,t,n,r,a,s,o,i,c,d){try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(i,l.__wbindgen_export3,l.__wbindgen_export4),y=A,T=k(c,l.__wbindgen_export3,l.__wbindgen_export4),x=A;l.contracttermsbuilder_field(h,this.__wbg_ptr,p,g,S,_,n,r,a,s,o,E,y,T,x,d);var f=b().getInt32(h+0,!0),u=b().getInt32(h+4,!0);if(u)throw N(f)}finally{l.__wbindgen_add_to_stack_pointer(16)}}filled(e,t){try{let a=l.__wbindgen_add_to_stack_pointer(-16),s=k(e,l.__wbindgen_export3,l.__wbindgen_export4),o=A,i=k(t,l.__wbindgen_export3,l.__wbindgen_export4),c=A;l.contracttermsbuilder_filled(a,this.__wbg_ptr,s,o,i,c);var n=b().getInt32(a+0,!0),r=b().getInt32(a+4,!0);if(r)throw N(n)}finally{l.__wbindgen_add_to_stack_pointer(16)}}constructor(e){var t=dt(e)?0:k(e,l.__wbindgen_export3,l.__wbindgen_export4),n=A;let r=l.contracttermsbuilder_new(t,n);return this.__wbg_ptr=r,hr.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(pn.prototype[Symbol.dispose]=pn.prototype.free);var _n=class Lt{static __wrap(t){let n=Object.create(Lt.prototype);return n.__wbg_ptr=t,fr.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,fr.unregister(this),t}free(){let t=this.__destroy_into_raw();l.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.wasmidentity_address(s,this.__wbg_ptr);var r=b().getInt32(s+0,!0),a=b().getInt32(s+4,!0);return t=r,n=a,Re(r,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(t,n,1)}}bundle(){let t=l.wasmidentity_bundle(this.__wbg_ptr);return N(t)}static fromSeed32(t){try{let s=l.__wbindgen_add_to_stack_pointer(-16),o=le(t,l.__wbindgen_export3),i=A;l.wasmidentity_fromSeed32(s,o,i);var n=b().getInt32(s+0,!0),r=b().getInt32(s+4,!0),a=b().getInt32(s+8,!0);if(a)throw N(r);return Lt.__wrap(n)}finally{l.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A;l.wasmidentity_fromSeed64(o,i,c,n);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return Lt.__wrap(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(n,l.__wbindgen_export3),c=A;l.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,c);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}open(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(t,l.__wbindgen_export3),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_open(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signApproval(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=k(t,l.__wbindgen_export3,l.__wbindgen_export4),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_signApproval(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signContract(t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=k(t,l.__wbindgen_export3,l.__wbindgen_export4),d=A,f=k(n,l.__wbindgen_export3,l.__wbindgen_export4),u=A,h=k(r,l.__wbindgen_export3,l.__wbindgen_export4),p=A;l.wasmidentity_signContract(i,this.__wbg_ptr,c,d,f,u,h,p);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signContractV2(t,n,r,a){try{let c=l.__wbindgen_add_to_stack_pointer(-16),d=k(t,l.__wbindgen_export3,l.__wbindgen_export4),f=A,u=k(n,l.__wbindgen_export3,l.__wbindgen_export4),h=A,p=k(r,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(a,l.__wbindgen_export3,l.__wbindgen_export4),_=A;l.wasmidentity_signContractV2(c,this.__wbg_ptr,d,f,u,h,p,g,S,_);var s=b().getInt32(c+0,!0),o=b().getInt32(c+4,!0),i=b().getInt32(c+8,!0);if(i)throw N(o);return N(s)}finally{l.__wbindgen_add_to_stack_pointer(16)}}signSummary(t,n,r,a){try{let c=l.__wbindgen_add_to_stack_pointer(-16),d=k(t,l.__wbindgen_export3,l.__wbindgen_export4),f=A,u=k(n,l.__wbindgen_export3,l.__wbindgen_export4),h=A,p=k(r,l.__wbindgen_export3,l.__wbindgen_export4),g=A;l.wasmidentity_signSummary(c,this.__wbg_ptr,d,f,u,h,p,g,a);var s=b().getInt32(c+0,!0),o=b().getInt32(c+4,!0),i=b().getInt32(c+8,!0);if(i)throw N(o);return N(s)}finally{l.__wbindgen_add_to_stack_pointer(16)}}userProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A,d=le(n,l.__wbindgen_export3),f=A;l.wasmidentity_userProof(o,this.__wbg_ptr,i,c,d,f);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=l.__wbindgen_add_to_stack_pointer(-16);l.wasmidentity_words(s,this.__wbg_ptr);var r=b().getInt32(s+0,!0),a=b().getInt32(s+4,!0);return t=r,n=a,Re(r,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=l.__wbindgen_add_to_stack_pointer(-16),i=le(t,l.__wbindgen_export3),c=A,d=le(n,l.__wbindgen_export3),f=A;l.wasmidentity_workloadProof(o,this.__wbg_ptr,i,c,d,f);var r=b().getInt32(o+0,!0),a=b().getInt32(o+4,!0),s=b().getInt32(o+8,!0);if(s)throw N(a);return N(r)}finally{l.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(_n.prototype[Symbol.dispose]=_n.prototype.free);function Bs(){l.init()}function Us(e,t,n){let r,a;try{let u=l.__wbindgen_add_to_stack_pointer(-16),h=k(e,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(t,l.__wbindgen_export3,l.__wbindgen_export4),S=A,_=k(n,l.__wbindgen_export3,l.__wbindgen_export4),E=A;l.wasm_approval_message(u,h,p,g,S,_,E);var s=b().getInt32(u+0,!0),o=b().getInt32(u+4,!0),i=b().getInt32(u+8,!0),c=b().getInt32(u+12,!0),d=s,f=o;if(c)throw d=0,f=0,N(i);return r=d,a=f,Re(d,f)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(r,a,1)}}function Fs(e){try{let a=l.__wbindgen_add_to_stack_pointer(-16),s=le(e,l.__wbindgen_export3),o=A;l.wasm_bundle_address(a,s,o);var t=b().getInt32(a+0,!0),n=b().getInt32(a+4,!0),r=b().getInt32(a+8,!0);if(r)throw N(n);return N(t)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function $s(e,t){let n=le(e,l.__wbindgen_export3),r=A,a=k(t,l.__wbindgen_export3,l.__wbindgen_export4),s=A;return l.wasm_bundle_verify_for_address(n,r,a,s)!==0}function Ws(e,t,n){let r,a;try{let u=l.__wbindgen_add_to_stack_pointer(-16),h=k(e,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(t,l.__wbindgen_export3,l.__wbindgen_export4),S=A,_=k(n,l.__wbindgen_export3,l.__wbindgen_export4),E=A;l.wasm_contract_message(u,h,p,g,S,_,E);var s=b().getInt32(u+0,!0),o=b().getInt32(u+4,!0),i=b().getInt32(u+8,!0),c=b().getInt32(u+12,!0),d=s,f=o;if(c)throw d=0,f=0,N(i);return r=d,a=f,Re(d,f)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(r,a,1)}}function Hs(e,t,n,r){let a,s;try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(n,l.__wbindgen_export3,l.__wbindgen_export4),y=A,T=k(r,l.__wbindgen_export3,l.__wbindgen_export4),x=A;l.wasm_contract_message_v2(h,p,g,S,_,E,y,T,x);var o=b().getInt32(h+0,!0),i=b().getInt32(h+4,!0),c=b().getInt32(h+8,!0),d=b().getInt32(h+12,!0),f=o,u=i;if(d)throw f=0,u=0,N(c);return a=f,s=u,Re(f,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(a,s,1)}}function Ks(e,t,n){let r=le(e,l.__wbindgen_export3),a=A,s=le(t,l.__wbindgen_export3),o=A,i=le(n,l.__wbindgen_export3),c=A;return l.wasm_ed25519_verify(r,a,s,o,i,c)!==0}function zs(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_sealbox_wrap(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function Gs(e,t,n,r){let a,s;try{let h=l.__wbindgen_add_to_stack_pointer(-16),p=k(e,l.__wbindgen_export3,l.__wbindgen_export4),g=A,S=k(t,l.__wbindgen_export3,l.__wbindgen_export4),_=A,E=k(n,l.__wbindgen_export3,l.__wbindgen_export4),y=A;l.wasm_summary_message(h,p,g,S,_,E,y,r);var o=b().getInt32(h+0,!0),i=b().getInt32(h+4,!0),c=b().getInt32(h+8,!0),d=b().getInt32(h+12,!0),f=o,u=i;if(d)throw f=0,u=0,N(c);return a=f,s=u,Re(f,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_export2(a,s,1)}}function js(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_unwrap_file_key(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function Ys(e,t,n,r){try{let i=l.__wbindgen_add_to_stack_pointer(-16),c=le(e,l.__wbindgen_export3),d=A,f=le(t,l.__wbindgen_export3),u=A,h=k(n,l.__wbindgen_export3,l.__wbindgen_export4),p=A,g=k(r,l.__wbindgen_export3,l.__wbindgen_export4),S=A;l.wasm_wrap_file_key(i,c,d,f,u,h,p,g,S);var a=b().getInt32(i+0,!0),s=b().getInt32(i+4,!0),o=b().getInt32(i+8,!0);if(o)throw N(s);return N(a)}finally{l.__wbindgen_add_to_stack_pointer(16)}}function wr(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof K(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=K(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof K(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return K(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Re(t,n))},__wbg_call_a41d6421b30a32c5:function(){return lt(function(t,n,r){let a=K(t).call(K(n),K(r));return re(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=K(t).crypto;return re(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Re(t,n))}finally{l.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return lt(function(t,n){K(t).getRandomValues(K(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return K(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=K(t).msCrypto;return re(n)},__wbg_new_227d7c05414eb861:function(){let t=new Error;return re(t)},__wbg_new_2fad8ca02fd00684:function(){let t=new Object;return re(t)},__wbg_new_from_slice_5a173c243af2e823:function(t,n){let r=new Uint8Array(hn(t,n));return re(r)},__wbg_new_with_length_9011f5da794bf5d9:function(t){let n=new Uint8Array(t>>>0);return re(n)},__wbg_node_84ea875411254db1:function(t){let n=K(t).node;return re(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=K(t).process;return re(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(hn(t,n),K(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return lt(function(t,n){K(t).randomFillSync(N(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return lt(function(){let t=module.require;return re(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return lt(function(t,n,r){return Reflect.set(K(t),K(n),K(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=K(n).stack,a=k(r,l.__wbindgen_export3,l.__wbindgen_export4),s=A;b().setInt32(t+4,s,!0),b().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return dt(t)?0:re(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return dt(t)?0:re(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return dt(t)?0:re(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return dt(t)?0:re(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=K(t).subarray(n>>>0,r>>>0);return re(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=K(t).versions;return re(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=hn(t,n);return re(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Re(t,n);return re(r)},__wbindgen_object_clone_ref:function(t){let n=K(t);return re(n)},__wbindgen_object_drop_ref:function(t){N(t)}}}}var hr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbg_contracttermsbuilder_free(e,1)),fr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>l.__wbg_wasmidentity_free(e,1));function re(e){ut===De.length&&De.push(De.length+1);let t=ut;return ut=De[t],De[t]=e,t}function Vs(e){e<1028||(De[e]=ut,ut=e)}function hn(e,t){return e=e>>>0,qe().subarray(e/1,e/1+t)}var Ge=null;function b(){return(Ge===null||Ge.buffer.detached===!0||Ge.buffer.detached===void 0&&Ge.buffer!==l.memory.buffer)&&(Ge=new DataView(l.memory.buffer)),Ge}function Re(e,t){return qs(e>>>0,t)}var ct=null;function qe(){return(ct===null||ct.byteLength===0)&&(ct=new Uint8Array(l.memory.buffer)),ct}function K(e){return De[e]}function lt(e,t){try{return e.apply(this,t)}catch(n){l.__wbindgen_export(re(n))}}var De=new Array(1024).fill(void 0);De.push(void 0,null,!0,!1);var ut=De.length;function dt(e){return e==null}function le(e,t){let n=t(e.length*1,1)>>>0;return qe().set(e,n/1),A=e.length,n}function k(e,t,n){if(n===void 0){let i=ht.encode(e),c=t(i.length,1)>>>0;return qe().subarray(c,c+i.length).set(i),A=i.length,c}let r=e.length,a=t(r,1)>>>0,s=qe(),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=qe().subarray(a+o,a+r),c=ht.encodeInto(e,i);o+=c.written,a=n(a,r,o,1)>>>0}return A=o,a}function N(e){let t=K(e);return Vs(e),t}var Dt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Dt.decode();var Xs=2146435072,fn=0;function qs(e,t){return fn+=t,fn>=Xs&&(Dt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Dt.decode(),fn=t),Dt.decode(qe().subarray(e,e+t))}var ht=new TextEncoder;"encodeInto"in ht||(ht.encodeInto=function(e,t){let n=ht.encode(e);return t.set(n),{read:e.length,written:n.length}});var A=0,Zs,Js,l;function br(e,t){return Js=e,l=e.exports,Zs=t,Ge=null,ct=null,l}async function Qs(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 eo(e){if(l!==void 0)return l;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=wr();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return br(n,e)}async function to(e){if(l!==void 0)return l;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=wr();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Qs(await e,t);return br(n,r)}var no="seal_crypto.wasm",xe=null,Nt=null,Xe=null;function mr(e){if(Nt||Xe)throw new Error("configureWasm: the WASM is already loaded or loading");xe=e}function Er(){return globalThis.navigator?.userAgent==="Cloudflare-Workers"}function ro(){return typeof globalThis.process?.versions?.node=="string"&&!Er()}async function pr(e){let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}async function ao(){if(xe&&"module"in xe)return xe.module;if(xe&&"url"in xe)return fetch(xe.url,xe.integrity?{integrity:xe.integrity}:{});if(xe&&"path"in xe)return pr(xe.path);if(ro())return pr(new URL(no,fo.url));throw new Error(Er()?"seal crypto core: a Worker compiles no WASM from bytes \u2014 call configureWasm({ module }) with the imported .wasm":"sealnet: no WASM source in this browser (a broken build — reinstall sealnet)")}async function ft(){if(Nt)return Nt;if(Xe)return Xe;Xe=(async()=>{let e=gr;return await e.default({module_or_path:await ao()}),typeof e.init=="function"&&e.init(),Nt=e,e})();try{return await Xe}catch(e){throw Xe=null,e}}var _r=32768,yr=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function so(e){let t="";for(let n=0;n<e.length;n+=_r){let r=e.subarray(n,Math.min(n+_r,e.length));t+=String.fromCharCode.apply(null,r)}return t}function oo(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function io(e){let t=`${e.length} characters`;if(typeof atob<"u")try{return atob(e)}catch(n){throw new yr(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new yr(`Invalid base64 encoding: ${n.message}`,t)}}function lo(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function co(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function uo(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ne(e){return lo(so(e))}function ae(e){return uo(Ne(e))}function Ct(e){return oo(io(e))}function ue(e){return Ct(co(e))}async function ho(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 Ze(e){let t=await ho(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function po(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Bt(e,...t){if(!po(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 yn(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 Sr(e,t){Bt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function pt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ut(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ie(e,t){return e<<32-t|e>>>t}function _o(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function gn(e){return typeof e=="string"&&(e=_o(e)),Bt(e),e}var Mt=class{};function Ar(e){let t=r=>e().update(gn(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function yo(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),c=r?4:0,d=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+d,i,r)}function vr(e,t,n){return e&t^~e&n}function xr(e,t,n){return e&t^e&n^t&n}var Ft=class extends Mt{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=Ut(this.buffer)}update(t){yn(this),t=gn(t),Bt(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 c=Ut(t);for(;a<=s-o;o+=a)this.process(c,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){yn(this),Sr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,pt(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let u=o;u<a;u++)n[u]=0;yo(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Ut(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,f=this.get();if(d>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<d;u++)i.setUint32(4*u,f[u],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()}},Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var go=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]),Ue=new Uint32Array(64),wn=class extends Ft{constructor(t=32){super(64,t,8,!1),this.A=Ce[0]|0,this.B=Ce[1]|0,this.C=Ce[2]|0,this.D=Ce[3]|0,this.E=Ce[4]|0,this.F=Ce[5]|0,this.G=Ce[6]|0,this.H=Ce[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:c}=this;return[t,n,r,a,s,o,i,c]}set(t,n,r,a,s,o,i,c){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=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)Ue[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){let h=Ue[u-15],p=Ue[u-2],g=Ie(h,7)^Ie(h,18)^h>>>3,S=Ie(p,17)^Ie(p,19)^p>>>10;Ue[u]=S+Ue[u-7]+g+Ue[u-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let h=Ie(i,6)^Ie(i,11)^Ie(i,25),p=f+h+vr(i,c,d)+go[u]+Ue[u]|0,S=(Ie(r,2)^Ie(r,13)^Ie(r,22))+xr(r,a,s)|0;f=d,d=c,c=i,i=o+p|0,o=s,s=a,a=r,r=p+S|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,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(r,a,s,o,i,c,d,f)}roundClean(){pt(Ue)}destroy(){this.set(0,0,0,0,0,0,0,0),pt(this.buffer)}};var $t=Ar(()=>new wn);var Se={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}},On=new Uint8Array(Se.magic_bytes),Gt=Se.magic_length,$e=Se.header_length,Je=Se.nonce_length,Rn=Se.tag_length,ea=Se.segment_overhead,ta=Se.segment_size_bytes,kr=Se.min_segment_size_bytes,Tr=Se.max_segment_size_bytes,gt=Se.header_layout.find(e=>e.name==="file_id"),Ir=Se.aad_layout.reduce((e,t)=>e+t.length,0),na=new Uint8Array(Se.v3_reader.magic_bytes),ra=Se.v3_reader.header_length;function wo(e){return Je+e+Rn}function Pn(e){let t=Math.max(1,Math.ceil(e/ta));return $e+t*ea+e}function bo(){let e=new Uint8Array($e);return e.set(On,0),new DataView(e.buffer).setUint32(Gt,ta,!0),e.set(crypto.getRandomValues(new Uint8Array(gt.length)),gt.offset),e}function jt(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function aa(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(Gt,!0);if(t<kr||t>Tr)throw new Error(`segment size ${t} is outside ${kr}\u2026${Tr}`);return t}function Ln(e){if(e.length<$e)throw new Error(`an AEON v4 header is ${$e} bytes, got ${e.length}`);if(!jt(e,On))throw new Error("not an AEON v4 header");return{segmentSize:aa(e),fileId:e.slice(gt.offset,gt.offset+gt.length)}}function mo(e){if(e.length<ra||!jt(e,na))throw new Error("not an AEON v3 header");return{segmentSize:aa(e)}}function Eo(e){return jt(e,On)?"v4":jt(e,na)?"v3":null}function sa(e,t,n){let r=new Uint8Array(Ir);return r.set(e.subarray(0,$e),0),new DataView(r.buffer).setBigUint64($e,BigInt(t),!0),r[Ir-1]=n?1:0,r}function So(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function oa(e){let t=So(e);try{return crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{new Uint8Array(t).fill(0)}}async function Ao(e,t,n){let r=crypto.getRandomValues(new Uint8Array(Je)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:Rn*8,additionalData:n},e,t),s=new Uint8Array(Je+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),Je),s}async function vo(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,Je),tagLength:Rn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(Je)))}function xo(){return $t.create()}async function wt(){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 ko(){return crypto.getRandomValues(new Uint8Array(32))}var ye={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,MAX_GEO_COUNTRIES:50,SEAL_VISIT_SECONDS:21600,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","eu-central","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,LEASE_DEFAULT_DAYS:7,LEASE_MAX_DAYS:90,LEASE_STATUS_BATCH_MAX:500,LEASE_POLL_SECONDS:600,LEASE_KEEP_DAYS:30,APPROVE_WAIT_SECONDS:120,APPROVE_BODY_SHOWN_BYTES:2048,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}},et={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 eight bytes"}},hkdf:{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",share_proof:"seal:share-proof:v1",kem_mlkem768:"seal:kem-mlkem768:v1"}},share_link:{proof_of:"the proof of a share link's key (AUDIT K237): HKDF-SHA256(ikm = the link's 32-byte key, salt = hkdf.identity_key_salt, info = hkdf.info_prefixes.share_proof, 32 bytes), base64url; its maker gives the server proof_hash = SHA-256 hex of those bytes, an opener sends the proof in proof_header",proof_header:"X-Share-Proof",proof_vector:{link_key:"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",proof:"xYwpyfG6o6iW43T5O7W9Av5bVZJc5MpUhcmPa6SxQy8",proof_hash:"75d668b6b3295aad0b8e3f83eb9d03181a9c81f92836105077023bf3bea0aa4a"}},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}",scope_metadata_aad:{is:"What a sealed text of a scope's metadata is bound to: the AAD of its AES-256-GCM (SEAL Pro, AUDIT K140, SPEC-NAMES-BOUND). A room's name and description are bound to the room. A text under the organization's key and the name of a seal's folder are bound to their own object: its id stands in the AAD, so two of them cannot be swapped unnoticed. The binding before that named the kind and the organization (the seal) only; a row says which one its text has by `encryption_version`. Since the old binding's end (SPEC-NAMES-BOUND \u04213) a text of before is read only of the kinds in `org_object.before_read` \u2014 a contract's data and a member's drawing lie under their signatures and are never sealed again (\u041D5) \u2014; any other, and a seal's folder's name, opens bound alone.",room:"room:{room_id}:{field}",org_object:{bound:"{kind}:{org_id}:{object_id}:{field}",before:"{kind}:{org_id}:{field}",kinds:["secret","sign-policy","sign-template","sign-template-body","sign-template-meta","sign-folder","sign-request-meta","sign-field-value"],before_read:["sign-request-meta","sign-field-value"],field:"name",object:"the row the text belongs to: the secret, the policy, the template (its name, text and terms alike), the contract folder, the sign request, the signature field of a drawing"},folder:{bound:"seal:{seal_id}:{folder_id}:name",before:"seal:{seal_id}:name",before_read:!1},versions:{before:3,bound:5,note:"4 is a file's format version (seal_files) and names no metadata"},vectors:{key_hex:"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",nonce_b64:"ZGVmZ2hpamtsbW5v",org_object:{kind:"secret",org_id:"0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e",object_id:"7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d",other_object_id:"11111111-2222-4333-8444-555555555555",text:"prod-db",bound_aad:"secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d:name",bound_b64:"OGmxAlSNNC/EcAW6hlU6eU73XrC7Vaw=",before_aad:"secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:name",before_b64:"OGmxAlSNNBiKlnxW4fkbPMjFoZGJJDY="},org_object_signed:{kind:"sign-request-meta",org_id:"0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e",object_id:"5c2e8f71-3a94-4d0b-b6e1-0f7a9c2d4e85",text:"NDA Acme 2026",before_aad:"sign-request-meta:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:name",before_b64:"Bl+fRjiKO/seUG/a7Ln0rJ0phFB+8MGpdfuM+fI="},folder:{seal_id:"AbCd1234",folder_id:"c0ffee00-1234-4abc-8def-0123456789ab",other_folder_id:"11111111-2222-4333-8444-555555555555",text:"\u0414\u043E\u0433\u043E\u0432\u043E\u0440\u044B 2026",bound_aad:"seal:AbCd1234:c0ffee00-1234-4abc-8def-0123456789ab:name",bound_b64:"mI8O2KlahiDu0I9WC+W7dmLwNji94CvUmMxJnLVFN5EChD6uMg==",before_aad:"seal:AbCd1234:name",before_b64:"mI8O2KlahiDu0I9WC+W7dmLwNji9ni0vIvgReyNDk0uY98XR7Q=="}}},sign:{message_prefix:"aeon:sign:v1",message_format:"aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}",message_prefix_v2:"aeon:sign:v2",message_format_v2:"aeon:sign:v2|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}|terms:{terms_hex}",terms_label:"aeon:terms:v1",terms_of:"what the signer was shown (AUDIT K204): SHA-256 hex of the lines the core builds (shared/core/src/contract_terms.rs) \u2014 for a member of the organization or its agent from the metadata ciphertext and the whole field layout, for an outside signer from their own fields alone and no metadata \u2014 and the signer's own filled fields",terms_vector:{org_id:"0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70",request_id:"7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e",doc_hash:"cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33",meta:"bWV0YS1jaXBoZXJ0ZXh0",fields:[{id:"b2f1c3d4-0000-4000-8000-000000000002",type:"signature",page:2,x:.615,y:.8125,w:.3,h:.075,assignee_type:"email",assignee:"ann|example@example.com",required:!0},{id:"a1e0b2c3-0000-4000-8000-000000000001",type:"signature",page:1,x:.1,y:.7,w:.3,h:.075,assignee_type:"user",assignee:"5c9e7a3b-1d2f-4a6b-8c0d-2e4f6a8b0c1d",required:!0}],filled:[{field_id:"a1e0b2c3-0000-4000-8000-000000000001",sha256:"bde5c9647a96e96c78ea116eaa7a653b2347cd83855d223b30984f235151f813"}],terms:"a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30",message:"aeon:sign:v2|org:0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70|req:7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e|doc_hash:cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33|terms:a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30"}},sign_doc_hash_of:"sha256(plaintext) of the exact seal_files row in doc_ref",recovery_phrase:{seed:`BIP39: PBKDF2-HMAC-SHA512 of the phrase after trim, lower case and NFKD, salt "mnemonic", 2048 iterations, 64 bytes; the web's recoveryPhrase.ts phraseToMasterSeed and the core's hkdf::master_seed_from_phrase (\u04145 \xA73.2)`,vector:{phrase:"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",typed:` Abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon ART
3
+ `,seed_hex:"408b285c123836004f4b8842c89324c1f01382450c0d439af345ba7fc49acf705489c6fc77dbd4e3dc1dd8cc6bc9f043db8ada1e243c4a0eafb290d399480840"}},device_link:{record:"a person's seed64, base64url, sealed by the browser to the one-time bundle of sealfs login: sealReply(seed64, bundle, scope, code) of the protocol's identity module \u2014 box (sealed_box_v2) \u2016 nonce(12) \u2016 AES-256-GCM of the record under the box's key; the daemon opens it with its one-time identity (\u04145 \xA73.2 \u043F. 2, D119)",scope:"device",vector:{daemon_seed64_hex:"01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3ba",code:"K7M2Q9XA",seed64_hex:"030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bc",record:"AlbSFUYf2V9yux_9DyViIEw_gXJcdITRt0kFjJC9XAJTOCRSKh3_hDCGxBSS5idHldzc_qQOtd43_GYaZQm9_VH90eY2JDP_A2T4I8W_qPPfS4MlLGtBp0kkShY_PnspF6bELAbft3XNkEuwQpfynXH2OFFvAPwJFKceua18YAywNbq84plsv8n3C5lRmeITyeFwKlxDW3-6q-2NHlAgkSrScie1B63CQu3D0U3SRWcOHMvwnl9Topwe1J2iu4EpOUlJRZQsgfBR4LhyywAWam0R3VHa_pXjCtN4Of-JRyO3Jub-6MgDXpoGsQuD9V1XszngRZkwz0R_4xqSlabtA-GMiCJyhff7HBp3t0XHeaS04cNdtATfwce_FUL3IL-z0YAQh-JSzKz_VeVq8iFSZcbHnx2Eab3ND4YuwvJxfJJ8jGquahnhndiI6qxZtK7OmQsy8ZBQ_p4Gi8v1ziN74OMdQG9UtqR9igeJohiMos5tHpveIXQ9luWiQ9gk22p53yGzP8hH_mv508tb4KsveNjssXS0hVmLl4c7fqQbrBjKvNauuEbzNd1gimV4I_f-N0FN2c7Pe7sTZevR5dnIGrAF_31cxFTOWVjZdKsyEWUiwSHrG2dQBccO2AB6TurTsqr4hBP64c3WkUW1vJVXKEOCKxBIwMa7XyyLw4La5tZue0Ls2cHzfy2Kd5jKCo3UIQrjvNWOvXFDRlkTx10UMFpZNvmnITHVh6rHkr5_tGFVMwqU2arRmwQBWCBYsDhN1NVJ8cEwEb0lNHfuotqf54IZUP25JwqpqSkSadjHdVHZdJ50MQUiNiumm0e-kbLDfWHds9dkGhwVgqha3s-svngKweowybgYAnRIDYeHHkSN-9Bm2jNmidilQhTiY6eLmnxg81sdESUNrjk1nhNJdiTaDAeX-CL5DJxPVirKFWYgrBpvJ7ocpxg9Idqsdm8fIzZi-MAQyq_I1y2RcsUqZEwFFeHqwPZdUce1PxVBjFn27cfKzyifotbTBumodLXMRnrrhfQ2i6cHAt9utI2X_WJuGxDRfYICuKdQHt3NPswIwLxSxgNUvpani5DzhYA5FnC-zfh_LWXyJnyfJx1Yr-07_ICpIP85fwzO7FAVZxpdpsL8wk19HhW63LAOVcQxANLcIue7hp1vU6QU1Co0H4yGJgmehDEBYWFJCpaDk8_srkw42Y9eZn6SNoIekuz-BNgjnnB0WB2mh-k3vux92C-_2o8GsSeENNvOOTRwLOLAB4PCi-Uf__oonrLR0kBdE2gbrVjb6sttEx8Df_S7YuTCytpw13ABaXCcJRsPfR6os2KuM1Rv53CH5SZ2NpKgdFlBmva9gIsMSJxAh08UtLGNhKrli3uUW1KER7Ng92RDDV-HHUqNyOhkPPD4KteeZHX0m9h8POVCjXr0TNHSisQK_CPFMMOhUc2DmEHDOZO9piI5uMAznMdzrR-qFbhPNN9ugUUSIdDnVS9Mc2INiUIKjnLWB37_wYTSpXRCS5bSfohMPyNu0dTuAJuHLNfK1hA9XOGhvZLFW9rgXN8bYdAmUL0TrJJ4DYBWrpzXuzaiXEf2peRi0z6LYiXWyjvmIaQfvttTgWSymbREbJmanBDfTUPR5XPFQHZ-n_876ODCoJAXnqOkSSWEHKf885bOre3IkJIS_2jH9_MJzG0Fsmnvj8VYHECIrZlRFdsqzMQ9MIIIIWg0bfHvAn5R06o"}}},Ee={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 eight 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 64-byte seed of an agent, a device or an inbox, 86 characters",derives:"all three keys of the bundle v2 the address names are HKDF-SHA256 of the seed under crypto.json hkdf.identity_key_salt, each under its own info: hkdf.info_prefixes identity (Ed25519), agreement (X25519) and kem_mlkem768 (d \u2016 z of ML-KEM-768), followed by key_version as four bytes, little-endian \u2014 the core's Identity::from_seed. No public key of the bundle is the seed",key_version:1,same_as:["sealnet-mcp state.identity.seed_b64","seal identity.v1.json seed_b64url","sealnet (npm) KeyPair.secretKey","sealnet (PyPI) keygen().secret_key"],root:"SPEC-SEED-ROOT: the one kind of seed. A seed of 32 bytes (43 characters) is a key of the kind before: a holder that keeps its seed itself reads it as its previous key (below) until that expires, and nothing makes it or takes it as a seed \u2014 SEAL_SEED, an inbox key file, a device transfer and an SDK key of that length are refused in words that say how to make a new one.",vector:{comment:"the seed of the vector `sealed-box-v2-person` of xwing_test_vectors.json (seed64_hex; its bundle, address and words are there) signs the challenge of ts into this proof \u2014 Identity::from_seed, Identity::inbox_proof; Ed25519 is deterministic, every client reproduces it",of:"sealed-box-v2-person",ts:179e7,challenge:"wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8",proof:"1790000000.wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8.1VKxaNHrNu5Is9gYxMur7mAABL8Pn0Lcz6vpw5JDmUI65epcxGCMUOGcJK-lneqALDx0EHlBHbhmUIHWPCCDCQ"},previous:"the seed a holder had before it replaced its key, 32 or 64 bytes, kept beside the current one where the holder keeps its seed itself (an inbox, a device's identity file, the MCP server's state): it opens what the server still holds at the old address and is erased when the last of that has expired \u2014 seven days from the replacement (limits.json ttl_options, the longest free seal), longer while the inbox shows a live row at the old address"},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 eight 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","guard"],pair_what:"inbox",guard:{kind:"guard",is:"a pair request whose requester is this machine's guard (SPEC agent egress \xA73.1): the same answer as `pair` (the pairing file), and the inbox marks the agent as a guard. A request for a secret whose recipient_bundle is a guard's is shown by the inbox as sealed to that guard; one whose bundle is no known guard's is answered only after the person types its eight words (\xA76.1, T2\u0430).",gateway:"SPEC agent egress \xA77.2, level \u0412: `seal guard expose --listen <address:port> [--as <host:port>]` makes a guard the owner's gateway \u2014 `POST https://<host:port>/v1/forward` over mTLS, both certificates made from the guards' Ed25519 identity keys and checked against the published bundles of their addresses (the client names its address in `x-seal-address`, the server is the `gateway.guard` of the binding). `seal guard lend <key> --to <address>` lends a key as use: the borrower's guard receives a handle under a binding with `gateway: {at, guard}` (owner_blob_payload.v1.json bindings) and sends the request with `x-seal-method` and `x-seal-url` (the host's URL) to the gateway, which puts the value in and answers with the host's answer. The gateway not reachable: 502 `{error: seal_guard.gateway, reason: gateway_offline}`.",bind:"POST /intake may carry `bind`: what the agent proposes the key be bound to \u2014 {hosts: [<host>], place?: <place>, class?: outbound|inprocess} (secrets.json guard_note). `bind` is sent only when the recipient_bundle is a guard's, hosts proposed or not: its presence is what lets the page bind the key and lend it under a lease; without it the page says the value goes to the agent as it is. The page shows the proposal as the binding when no entry of secrets.json knows the key's form; the person confirms, narrows or removes it. At most 16 hosts of 253 characters, each a name of two labels or more (`*.` with two labels under it, three under secrets.json wildcard_public_second_level); the server checks the shape and keeps it as given."},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, 86>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>","kind":"guard"?}]}',kind:"`guard` for an agent that is a machine's guard (request kind `guard`): it stays a guard on every device of the inbox and through a rename; a reader drops a kind it does not know (SPEC-APP r5 \u041425)"},approve:{mime:"application/vnd.seal.approve+json",json:'{"v":2,"ask":"<16 random bytes, base64url>","secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","guard":"<eight words of the guard>","host":"api.stripe.com","method":"POST","path":"/v1/refunds?expand=charge","at":"<ISO 8601>","until":"<ISO 8601>","body_bytes":24,"body":"charge=ch_1&amount=50000"?,"body_sha256":"<SHA-256 hex of the whole body>"?,"body_more":true?}',body:"What the call carries (AUDIT K152): `path` is the path with its query; `body_bytes` the bytes of the body the guard read; `body` its first `limits.json::APPROVE_BODY_SHOWN_BYTES` bytes when they are text, cut where a character ends, absent for an empty or a binary body; `body_sha256` the digest of the whole body, absent for an empty one and for one that streams on past what the guard reads whole, which `body_more` says. An agent's request holds surrogates, never a value. A reader takes a question without these fields (a guard before them) and shows what it has.",is:"A guard's question to a key's owner (SPEC agent egress \xA77.3, \u04214): a call the binding marks `approve: owner` waits for this answer. Sent as a seal addressed to the owner (30 minutes, one open), its share blob marked `payload: approve`; the inbox shows it as a card with Allow and Deny and pushes. Unanswered within `limits.json::APPROVE_WAIT_SECONDS` the call is refused (403 `approve`)."},approve_answer:{mime:"application/vnd.seal.approve-answer+json",json:`{"v":2,"ask":"<the ask>","decision":"allow"|"deny","at":"<ISO 8601>","signature":"<Ed25519 by the inbox's identity key over the core's approval message, base64url, 86>"}`,is:"The owner's answer (\xA77.3): a seal from the inbox to the guard's address (30 minutes, one open), blob `payload: approve_answer`; the guard checks the signature against the owner's bundle (the `owner` of the binding). `allow` is for the one call the question was about (AUDIT K152): the same call again is another question."},summary:{mime:"application/vnd.seal.summary+json",json:`{"v":2,"secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","day":"<YYYY-MM-DD, UTC>","counts":[{"method":"GET","path":"/v1/charges/*","status":200,"n":40}],"approved":2,"refused":1,"root":"<SHA-256 hex, the chain's last link>","n":43,"signature":"<Ed25519 by the guard's identity key over the core's summary message, base64url, 86>"}`,is:"A guard's daily summary of one lent key to its owner (\xA77.4, \u04213): once a day by UTC and on a revoke, a seal addressed to the owner (7 days, one open), blob `payload: summary`. The inbox checks the signature against the guard's bundle (the item's sender), keeps the summary in its own storage (the carrier expires) and shows the journal under the lease. Attested by the guard that wrote the receipts: honest of an honest guard."},blob_payload:"A seal a machine makes for another machine or for an inbox carries the kind of its file in the share blob's `payload` (`approve`, `approve_answer`, `summary`, `delivery`), under the link key: the inbox reads the blob of every delivery and downloads only the files of these kinds; the server sees one more addressed seal. Readers tolerate a blob without the field.",delivery:{mime:"application/vnd.seal.delivery+json",json:`{"v":2,"name":"<the binding's name, STRIPE_KEY>","level":"A"|"B"|"0","at":"<ISO 8601>"}`,is:"The receipt of a lent key's arrival (SPEC agent egress \xA76.2, T17): whoever opens a secret whose binding names an `owner` sends this file, as a seal addressed to that owner (7d, one open), the moment the secret is opened. `A` or `B`: the opener's guard holds the key and the agent got a surrogate \u2014 the level is the one that guard names in its `status` (SPEC-APP r4 \u042038: `A` its key in a file of the user, `B` in the protected keychain of the SEAL app); `0`: the opener holds the value itself, the second level. The level travels inside the ciphertext; the server sees one more addressed seal. No receipt when the binding has no owner, or the owner is the opener itself."}},device_link:{code:"16 Crockford base32 characters from 10 random bytes (80 bits): the server sees the what beside the device's address, so the code must not be searchable from them (SPEC-r4 \u041A-4, AUDIT wpkg03.3)",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 for the asking: it answers any script of seal.net. The address goes back only with a lease the inbox kept (box.lease), to be sealed into the key's binding as its owner.",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}",lease:"box.lease {lease: {id, token, name, hosts, words, expires_at}} -> {ok: boolean, address?: string}; ok: the lease and its revoke token are in Sent; address: the inbox's address, the owner of the lent key (SPEC agent egress \xA77.3\u20137.5: the guard asks it for its word and sends it the daily summary)"},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",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 kite tulip peach llama echo"}]},To="X-Seal-Client",C={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,VISIT_HEADER:"X-Seal-Visit",PROGRESS_SPEED_WINDOW_MS:2e4}},ia;function tt(e,t){return(ia??globalThis.fetch).call(globalThis,e,t)}function Io(){return ia!==void 0}var pc=2*1024*1024,Oo=(ye.limits.INTAKE_WAIT_MAX_SECONDS+15)*1e3,_c=Ee.proof.header_address,yc=Ee.proof.header_proof;function Ro(){try{return typeof process<"u"&&!0}catch{return!1}}var Po=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":Ro()||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}},Wt=Po;function Et(e){return{debug:(t,...n)=>Wt("debug",e,t,...n),info:(t,...n)=>Wt("info",e,t,...n),warn:(t,...n)=>Wt("warn",e,t,...n),error:(t,...n)=>Wt("error",e,t,...n)}}var P=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 Lo(e,t){return Object.defineProperty(e,"session",{value:t,enumerable:!1,configurable:!0,writable:!0}),e}function Ve(e,t){return e instanceof P?e:e instanceof DOMException&&e.name==="AbortError"?new P("Upload aborted","ABORTED"):new P(e instanceof Error?e.message:t,"UNKNOWN")}async function Qe(e,t,n,r){let a=await Ht(e,String(e.status));return new P(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var Do=Et("upload"),No={now:()=>performance.now(),after:(e,t)=>{let n=setTimeout(t,e);return()=>clearTimeout(n)},every:(e,t)=>{let n=setInterval(t,e);return()=>clearInterval(n)}},Co={retryBackoffMs:C.upload.RETRY_BACKOFF_MS,retryJitterRatio:C.upload.RETRY_JITTER_RATIO,stallNoticeMs:C.upload.STALL_NOTICE_MS,maxStallMs:C.upload.MAX_STALL_MS,putFloorBytesPerSecond:C.upload.PUT_FLOOR_BYTES_PER_SECOND,putMinDeadlineMs:C.upload.PUT_MIN_DEADLINE_MS,controlTimeoutMs:C.upload.CONTROL_TIMEOUT_MS,completeTimeoutMs:C.upload.COMPLETE_TIMEOUT_MS,poolStart:C.upload.PART_POOL_START,poolMax:C.upload.PART_POOL_MAX,poolMin:C.upload.PART_POOL_MIN,poolGrowRatio:C.upload.PART_POOL_GROW_RATIO,poolShrinkRatio:C.upload.PART_POOL_SHRINK_RATIO,partQueueLimit:C.upload.PART_QUEUE_LIMIT,hedgeMinInflightMs:C.upload.HEDGE_MIN_INFLIGHT_MS,hedgeLagFactor:C.upload.HEDGE_LAG_FACTOR,hedgePollMs:C.upload.HEDGE_POLL_MS,livenessSilenceMs:C.upload.LIVENESS_SILENCE_MS,verifyPollBackoffMs:C.upload.VERIFY_POLL_BACKOFF_MS,verifyFallbackWaitMs:C.upload.VERIFY_FALLBACK_WAIT_MS,speedWindowMs:C.upload.PROGRESS_SPEED_WINDOW_MS,clock:No};function Dn(e){return{...Co,...e}}function Sn(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}var la=()=>globalThis.AbortSignal;function Nn(e){let t=la()?.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController,r=e.find(a=>a.aborted);if(r)return n.abort(r.reason),n.signal;for(let a of e)a.addEventListener("abort",()=>n.abort(a.reason),{once:!0,signal:n.signal});return n.signal}function Mo(e){let t=la()?.timeout;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;return setTimeout(()=>n.abort(new DOMException("The operation timed out.","TimeoutError")),e),n.signal}function ca(e,t){let n=Mo(t);return e?Nn([e,n]):n}async function bt(e,t,n,r){try{return await tt(e,{...t,signal:ca(r,n)})}catch(a){throw r?.aborted?new P("Upload aborted","ABORTED"):new P(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function da(e){return e===408||e===429||e>=500?"retryable":"terminal"}function ua(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":da(e.httpStatus)}function ha(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":da(e.httpStatus)}var fa=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 Cn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new P("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new P("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function Yt(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,c=0;for(let d=0;;d++){if(a?.aborted)throw new P("Upload aborted","ABORTED");try{return await e({attempt:d,after:i})}catch(f){let u=Ve(f,`${o} failed`);if(u.code==="ABORTED")throw u;let h=s(u);if(h==="terminal")throw u;if(n.exhausted())throw new P(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${u.message}`,u.code,u.httpStatus,u.partNumber,!1);n.failed(),c=h==="refresh_url"?c+1:0;let p=h==="refresh_url"&&c===1,g=r.retryBackoffMs[Math.min(d,r.retryBackoffMs.length-1)]??0,S=1+(Math.random()*2-1)*r.retryJitterRatio,_=p?0:Math.round(g*S);Do.debug(`retry ${o} attempt=${d+2} in ${_}ms after ${u.code}${u.httpStatus?" "+u.httpStatus:""} (${h})`),i=h,await Cn(_,a)}}}var An;function pa(e,t){An=`${e}/${t}`}var Bo=()=>{};function vn(){return{...An===void 0?{}:{[To]:An},...Bo()}}var te=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 Uo(e){return e===404?"not_found":e===410?"revoked":e===451?"blocked":e===429?"rate_limited":e===401||e===403?"auth":e>=500&&e<600?"transient":"unknown"}async function Ht(e,t){let n=await e.text().catch(()=>""),r,a,s,o,i;if(n)try{let c=JSON.parse(n);typeof c?.detail=="string"&&(r=c.detail),typeof c?.code=="string"&&(a=c.code),typeof c?.retry_after=="number"&&(s=c.retry_after),typeof c?.update=="string"&&(o=c.update),typeof c?.min_version=="string"&&(i=c.min_version)}catch{}return new te(r??t,Uo(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function Fo(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}))}}var $o=C.upload.VISIT_HEADER;function _a(){return ae(crypto.getRandomValues(new Uint8Array(16)))}function $(e){return encodeURIComponent(e)}var Wo=et.share_link.proof_header,ya=new Map;async function ga(e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits"]),r=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:t.encode(et.hkdf.identity_key_salt),info:t.encode(et.hkdf.info_prefixes.share_proof)},n,256),a=new Uint8Array(r),s=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return{proof:ae(a),hash:Array.from(s,o=>o.toString(16).padStart(2,"0")).join("")}}async function Or(e,t){ya.set(e,(await ga(t)).proof)}function Rr(e){let t=/^\/seal\/([^/?]+)/.exec(e)?.[1],n=t?ya.get(decodeURIComponent(t)):void 0;return n?{[Wo]:n}:{}}var St=class Ae{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,this.answerTimeoutMs=t.answerTimeoutMs??Oo}fetchImpl(t,n){return this.injectedFetch?this.injectedFetch.call(globalThis,t,n):tt(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=new AbortController,o=setTimeout(()=>s.abort(new DOMException(`${r}: no answer in time`,"TimeoutError")),this.answerTimeoutMs),i;try{i=await this.fetchImpl(this.url(t),{...a,headers:{...vn(),...Rr(t),...a.headers},credentials:a.credentials??this.credentials,signal:a.signal?Nn([a.signal,s.signal]):s.signal})}finally{clearTimeout(o)}if(!i.ok)throw await Ht(i,`${r} failed: ${i.status}`);return i}static ownerHeaders(t,n=!1){let r={"X-Owner-Token":t};return n&&(r["Content-Type"]="application/json"),r}async getMetadata(t,n={}){let r=n.shareCode?`?share_code=${$(n.shareCode)}`:"";return await(await this.request(`/seal/${$(t)}${r}`,{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/${$(t)}/share/${$(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:Dr(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/${$(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=zo(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/${$(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/${$(t)}/download?${Pr(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?Ae.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie),n.visit&&(a[$o]=n.visit);for(let s=0;;s++)try{return await this.request(`/seal/${$(t)}/download?${Pr(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal})}catch(o){if(!(o instanceof te&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<C.upload.NOT_READY_MAX_RETRIES))throw o;await Ko((o.retryAfter??Ho)*1e3,r.signal)}}async downloadCiphertext(t,n,r={}){let a=await this.openDownload(t,n,r);if(a.headers.get("X-Download-Mode")!=="presigned")return a;let{url:s}=await a.json();if(typeof s!="string"||!s)throw new te(`GET /seal/${t}/download answered no storage URL`,"transient",502);let o=await this.fetchImpl(s,{signal:r.signal});if(!o.ok)throw await Ht(o,`storage download failed: ${o.status}`);return o}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${$(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${$(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:Dr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=Ae.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return Lr(a,o,s),{etag:(await this.request(`/seal/${$(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,s={}){let o=n===null?{"Content-Type":"application/json"}:Ae.ownerHeaders(n,!0),i={encrypted_blob:r,proof_hash:(await ga(a)).hash};s.fileIds&&(i.file_ids=s.fileIds),Lr(s,i,o);let c=await this.request(`/seal/${$(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal}),d=await c.json();if(typeof d.share_code!="string"||!d.share_code)throw new te(`POST /seal/${t}/share returned no share_code`,"unknown",c.status);return d.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${$(t)}/share/${$(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:Ae.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${$(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:Ae.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof te&&(o.status===404&&o.appCode==="seal.not_found"||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/${$(t)}/files/${$(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:Ae.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${$(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${$(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:Ae.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${$(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:Ae.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 te(`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:Ae.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 te("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),t.bind&&(r.bind=t.bind),t.answerToInbox&&(r.answer_to_inbox=!0),await(await this.request("/intake",{what:"POST /intake",method:"POST",headers:{"Content-Type":"application/json",...t.answerToInbox?yt(t.answerToInbox):{}},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/${$(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${$(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json",...Rr(`/seal/${$(n.sealId)}`)},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:ae(t)}),signal:n.signal})}async getBundle(t,n={}){try{let r=await this.request(`/intake/bundles/${$(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return ue((await r.json()).bundle)}catch(r){if(r instanceof te&&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,ye.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:yt(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:yt(n),signal:r.signal})}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",...yt(r)},body:JSON.stringify({to:r.address,endpoint:t}),signal:a.signal})}async createLease(t,n,r={}){return await(await this.request("/lease",{what:"POST /lease",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({owner_token_hash:t,expires_at:n}),signal:r.signal})).json()}async revokeLease(t,n,r={}){return await(await this.request(`/lease/${$(t)}/revoke`,{what:`POST /lease/${t}/revoke`,method:"POST",headers:Ae.ownerHeaders(n),signal:r.signal})).json()}async leaseStatus(t,n={}){let r={"Content-Type":"application/json"};n.etag&&(r["If-None-Match"]=n.etag);let a=await this.fetchImpl(this.url("/lease/status"),{method:"POST",headers:{...vn(),...r},body:JSON.stringify({ids:t}),credentials:this.credentials,signal:n.signal});if(a.status===304)return null;if(!a.ok)throw await Ht(a,`POST /lease/status failed: ${a.status}`);return{statuses:await a.json(),etag:a.headers.get("ETag")}}},Ho=3;function yt(e){return{[Ee.proof.header_address]:e.address,[Ee.proof.header_proof]:e.proof}}function Pr(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function Lr(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,yt(e.sender)))}function Ko(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 Dr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new te(`${t} returned an empty blob`,"unknown",n);return ue(e.encrypted_blob)}function zo(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 Go=32,jo=32,Vt=ye.limits.MAX_BLOB_SIZE,Nr=ye.limits.MAX_FILE_KEYS;function wa(e){if(e>Nr)throw new Error(`Too many file keys: ${e} exceeds maximum of ${Nr}`)}var Yo=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function ba(){return crypto.getRandomValues(new Uint8Array(Go))}async function ma(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 Mn(){return crypto.getRandomValues(new Uint8Array(jo))}async function Ea(e,t,n,r,a,s,o){wa(t.size);let i={owner_token:e,file_keys:Object.fromEntries(t),...r?{message:r}:{},...a?{nda_file:a}:{},...s&&Object.keys(s).length>0?{bindings:s}:{},...o?{payload:o}:{}};return Aa(i,n)}async function Sa(e,t,n,r,a,s,o){wa(e.size);let i={file_keys:Object.fromEntries(e),...n?{message:n}:{},...r?{nda_file:r}:{},...a?{reply_to:ae(a)}:{},...s&&Object.keys(s).length>0?{bindings:s}:{},...o?{payload:o}:{}};return Aa(i,t)}async function Aa(e,t){let n=new TextEncoder().encode(JSON.stringify(e)),r=12+n.length+16;if(r>Vt)throw new Error(`Blob size ${r} exceeds maximum of ${Vt}`);let 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,n),i=new Uint8Array(12+o.byteLength);return i.set(a,0),i.set(new Uint8Array(o),12),i}function Vo(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha256_hex=="string"&&typeof t.name=="string"}function Xo(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.v===1&&typeof t.name=="string"&&(t.class==="outbound"||t.class==="inprocess")&&Array.isArray(t.hosts)&&t.hosts.every(n=>typeof n=="string")}function qo(e){return typeof e.bindings!="object"||e.bindings===null?{}:Object.fromEntries(Object.entries(e.bindings).filter(([,t])=>Xo(t)))}function Zo(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"||t.reply_to!==void 0&&typeof t.reply_to!="string"||t.payload!==void 0&&typeof t.payload!="string")}async function Jo(e,t){let n=await Qo(e,t);if(!Zo(n))throw new Error("Invalid share blob structure");return n}async function Qo(e,t){if(e.length>Vt)throw new Error(`Blob size ${e.length} exceeds maximum of ${Vt}`);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 Yo}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}var bc=ye.limits.MAX_FILE_KEYS;var Fe=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],ei=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),ti=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function Mr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let c,d;i<16?(c=a&s|~a&o,d=i):i<32?(c=o&a|~o&s,d=5*i+1&15):i<48?(c=a^s^o,d=3*i+5&15):(c=s^(a|~o),d=7*i&15);let f=r+c+ei[i]+t[n+d]|0;r=o,o=s,s=a,a=a+(f<<Cr[i]|f>>>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 Bn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array(Fe),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(Fe-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<Fe)return this;this.compressBytes(this.pending,0,Fe),this.pendingLength=0}let n=e.length-(e.length-t)%Fe;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?Fe:2*Fe);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(ti&&(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)Mr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=Fe){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);Mr(this.state,this.scratch,0)}}};function ni(e){return Ne(new Bn().update(e).digest())}var bn=4*1024*1024;async function ri(e){let t=new Bn;for(let n=0;n<e.length;n+=bn)t.update(e.subarray(n,Math.min(n+bn,e.length))),n+bn<e.length&&await wt();return Ne(t.digest())}var va=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Ln(e.header).segmentSize,this.header=e.header.subarray(0,$e),this.key=e.key}async init(){this.cryptoKey=await oa(this.key)}sha256Hex(){return Ze(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 Ao(this.cryptoKey,n,sa(this.header,e,t))}};async function ai(e,t,n,r){let a=new Uint8Array(t);try{let s=new va({key:a,header:n});await s.init();let o=new Bn().update(s.header),i=[Br(s.header)],c=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let d=0;d<c;d++){let f=Math.min((d+1)*s.segmentSize,e.size),u=new Uint8Array(await e.slice(d*s.segmentSize,f).arrayBuffer()),h=await s.encryptSegment(d,d===c-1,u);u.fill(0),o.update(h),i.push(Br(h)),r?.(f,e.size)}return{blob:new Blob(i),md5_b64:Ne(o.digest())}}finally{a.fill(0)}}function Br(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Me=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function si(e,t){e.chunks.push(t),e.bytes+=t.length}function Kt(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 oi(e,t){let n=Kt(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function ii(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Me("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,c=0,d=null,f=async(h,p)=>{if(h.length<ea)throw new Me("integrity",`segment ${c} is ${h.length} bytes: the stream was cut`);try{return await vo(a,h,o==="v4"?sa(s,c,p):null)}catch(g){throw new Me("integrity",`segment ${c} does not decrypt as the ${p?"last":"next"} segment of this file: moved, cut, extended or changed`,g)}finally{c+=1}},u=async()=>{if(r.bytes<Gt)return!1;let h=Eo(oi(r,Gt));if(h===null)throw new Me("outdated","the file is in a format newer than this client: update it");let p=h==="v4"?$e:ra;if(r.bytes<p)return!1;if(h==="v3"){d=xo();for(let _ of r.chunks)d.update(_)}let g=Kt(r,p),S;try{S=h==="v4"?Ln(g).segmentSize:mo(g).segmentSize}catch(_){throw new Me("integrity",_ instanceof Error?_.message:String(_),_)}if(h==="v4"&&await Ze(g)!==n)throw new Me("integrity","the file header is not the one registered for this file");return s=g,o=h,i=wo(S),!0};return new TransformStream({async start(){a=await oa(e)},async transform(h,p){if(h.length!==0&&(si(r,h),d&&d.update(h),!(o===null&&!await u())))for(;r.bytes>i;){let g=Kt(r,i),S=await f(g,!1);g.fill(0),t.onPlaintextBytes?.(S.length),p.enqueue(S)}},async flush(h){if(o===null)throw new Me("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(),S=>S.toString(16).padStart(2,"0")).join("")!==n)throw new Me("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let p=await f(Kt(r,r.bytes),!0);t.onPlaintextBytes?.(p.length),h.enqueue(p)}},{highWaterMark:1},{highWaterMark:1})}var Sc=Et("SwDownload");var Ac=10*6e4;var xa={version:1,default:"application/octet-stream",extensions:{json:"application/json",txt:"text/plain",log:"text/plain",md:"text/plain",csv:"text/csv",html:"text/html",htm:"text/html",xml:"application/xml",pdf:"application/pdf",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}},li="_",ci=200,di=new TextEncoder;function xn(e){return di.encode(e).length}function Ur(e,t){let n="",r=0;for(let a of e){if(r+=xn(a),r>t)break;n+=a}return n}var ui=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 hi(){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 fi(e,t){let n=e.charCodeAt(0);if(n<32||n===127||/[\u202A-\u202E\u2066-\u2069\u200E\u200F\u061C]/.test(e))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 pi(e){let t=e.split(".")[0].toUpperCase();return ui.has(t)}function Un(e,t={}){let{platform:n=hi(),replacement:r=li,maxLength:a=ci,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=>fi(d,n)?d:r).join("");let c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${c}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${c})+|${c}+$`,"g"),""),(n==="windows"||n==="unknown")&&pi(o)&&(o=`${r}${o}`),xn(o)>a){let d=o.lastIndexOf(".");if(d>0&&d>o.length-10){let f=o.slice(d);o=Ur(o.slice(0,d),a-xn(f))+f}else o=Ur(o,a)}return!o||o===r?s:o}var _i=new Map(Object.entries(xa.extensions));function yi(e){let t=e.lastIndexOf("."),n=t>=0&&t<e.length-1?e.slice(t+1).toLowerCase():"";return _i.get(n)??xa.default}var vc=C.upload.MULTIPART_THRESHOLD_BYTES,xc=C.upload.MULTIPART_THRESHOLD_BYTES;var kc=new TextEncoder;var Tc=Et("FolderZip");var Ic=100*1024*1024,Oc=4*1024*1024;var gi=new WeakMap;function ka(e){return gi.get(e)??(e.webkitRelativePath||void 0)}var Xt="Encrypted file",qt="application/octet-stream";function Ta(e){return new TextEncoder().encode(`field:${e}`)}async function Fr(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=Ta(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:Ne(new Uint8Array(o)),nonce:Ne(r)}}async function $r(e,t,n,r){let a=Ct(e),s=Ct(t);return(async i=>{let c={name:"AES-GCM",iv:s};i&&(c.additionalData=i);let d=await crypto.subtle.decrypt(c,n,a);return new TextDecoder().decode(d)})(r?Ta(r):void 0)}async function wi(e,t){let n=Xt,r=qt;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await $r(e.name_encrypted,e.name_nonce,t,"name")}catch{n=Xt}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await $r(e.mime_encrypted,e.mime_nonce,t,"mime")}catch{r=qt}return{name:n,mime:r}}async function bi(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function mi(e,t){try{let n=await bi(t);return wi(e,n)}catch{return{name:Xt,mime:qt}}}var Ei=Et("upload"),_t=4*1024*1024;function Zt(){return new DOMException("Upload aborted","AbortError")}async function Si(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:c}=e,d=new va({key:r,header:a});await d.init();let f=d.segmentSize,u=Math.max(1,Math.ceil(n/f)),h=0,p=v=>new P(`The file changed while it was being sent: ${v} ${h} of ${n} bytes`,"FILE_CHANGED"),g=!0,S=0,_=0,E=[],y=0,T=v=>{if(E.length>0&&E[0].length===v)return y-=v,E.shift();let D=new Uint8Array(v),se=0;for(;se<v;){let G=E[0],j=v-se;G.length<=j?(D.set(G,se),se+=G.length,E.shift()):(D.set(G.subarray(0,j),se),E[0]=G.subarray(j),se+=j)}return y-=v,D},x=[],M=0,B=async v=>{let D=new Uint8Array(v),se=0,G=0;for(;se<v;){let j=x[0],we=i?_t-G:Number.MAX_SAFE_INTEGER,Y=Math.min(j.length,v-se,we);D.set(j.subarray(0,Y),se),se+=Y,G+=Y,Y===j.length?x.shift():x[0]=j.subarray(Y),i&&G>=_t&&se<v&&(G=0,await wt())}return M-=v,D},R=async v=>{if(_+=1,e.hashParts===!1)await e.onPart(_,v);else{let D=i?await ri(v):ni(v);await e.onPart(_,v,D)}i&&await wt()},Z=async v=>{if(!i){v.fill(0);return}for(let D=0;D<v.length;D+=_t)v.fill(0,D,Math.min(D+_t,v.length)),D+_t<v.length&&await wt()},ge=async()=>{for(;M>=s;)await R(await B(s))},O=async(v,D)=>{if(o?.aborted)throw Zt();let se=S;S+=1;let G=performance.now(),j=d.encryptSegment(se,D,v);await ge();let we=await j;await Z(v),Ei.debug(`encrypt segment=${S} bytes=${v.length} time=${Math.round(performance.now()-G)}ms`);let Y;g?(Y=new Uint8Array(a.length+we.length),Y.set(a,0),Y.set(we,a.length),g=!1):Y=we,c?.(S),x.push(Y),M+=Y.length},F=t.getReader();try{for(;;){if(o?.aborted)throw Zt();let{done:v,value:D}=await F.read();if(v)break;if(D&&D.length>0){if(h+=D.length,h>n)throw p("it gave more than");E.push(D),y+=D.length}for(;y>=f;)await O(T(f),S===u-1)}if(h<n)throw p("it ended at");(y>0||S===0)&&await O(T(y),!0),await ge(),M>0&&await R(await B(M))}finally{F.releaseLock()}}function Ai(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 vi(e,t,n){let{file:r,key:a,header:s,partSize:o,totalBytes:i,signal:c,initialCredits:d,onSegment:f,onPart:u}=n;return new Promise((h,p)=>{let g=!1,S=!1,_=0,E=Promise.resolve(),y=B=>{g||(g=!0,p(B))},T=()=>{!S||_>0||E.then(()=>{g||(g=!0,h())})};if(c){if(c.aborted){y(Zt());return}c.addEventListener("abort",()=>y(Zt()),{once:!0})}e.onerror=t.onerror=B=>{y(new Error(`crypto worker crashed: ${String(B?.message??B)}`))},e.onmessage=B=>{let R=B.data;if(R.type==="segment"){f?.(R.segmentNumber);return}if(R.type==="part"){_+=1,t.postMessage({type:"md5",partNumber:R.partNumber,buffer:R.buffer},[R.buffer]);return}if(R.type==="done"){S=!0,T();return}R.type==="error"&&y(new Error(R.message))},t.onmessage=B=>{let R=B.data;if(R.type!=="md5")return;_-=1;let Z=new Uint8Array(R.buffer);E=E.then(async()=>{g||(await u(R.partNumber,Z,R.md5),e.postMessage({type:"credit"}))}).catch(y),T()};let x=new ArrayBuffer(a.length);new Uint8Array(x).set(a);let M=s.slice().buffer;e.postMessage({type:"start",file:r,key:x,header:M,partSize:o,totalBytes:i,credits:d},[x,M])})}var xi=null;function ki(){return xi}var je=Et("upload");function Ti(e){return e.now-e.lastLookAt>2*e.every?!1:e.now-e.lastActivityAt>=e.silenceMs}var Wr="<Code>BadDigest</Code>",Ii=2;function en(e){let t=vn();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 Oi(e){return Ri({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 Ri(e){let{file:t,partSize:n}=e;return Pi({stream:Ai(t,Ln(e.header).segmentSize),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 Pi(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:c,partSize:d,contentType:f="application/octet-stream",onProgress:u,signal:h,sourceFile:p,onStreamed:g,onConflict:S}=e,_=Dn(e.transport),E=_.clock;if(s.length!==32)throw new P("Key must be 32 bytes","ENCRYPTION_FAILED");if(d<C.upload.S3_MIN_PART_SIZE_BYTES)throw new P(`Part size must be at least ${C.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let y=new Uint8Array(s),T=en(c),x=Pn(n),M=Math.ceil(x/d),B=null,R=[],Z=0,ge=0,O="encrypting",F=[],v=null,D,se=w=>{let m=E.now();F.push({at:m,bytes:w});let I=Math.max(v??m,m-_.speedWindowMs);for(;F.length>0&&F[0].at<I;)F.shift();let U=m-I;U>0&&(D=Math.round(F.reduce((L,ee)=>L+ee.bytes,0)/U*1e3))},G=w=>{O=w;let m=x-Z;u?.({phase:w,percent:w==="done"?100:Math.min(99,Math.floor(Z/x*100)),deliveredBytes:Z,preparedBytes:ge,totalBytes:x,speedBps:D,etaMs:D&&D>0?Math.round(m/D*1e3):void 0,state:j.state,attempt:j.retriesSinceDelivery+1})},j=new fa(_,()=>G(O),E.now),we=new AbortController,Y=h?Nn([h,we.signal]):we.signal,nt=(w,m)=>Yt(m,{clock:j,policy:_,signal:Y,classify:ha,what:w}),Q=async w=>{throw y.fill(0),new P("Upload aborted","ABORTED")},ve=w=>{if(B)try{tt(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify(w?{upload_id:B,discard_file:!0}:{upload_id:B}),keepalive:!0}).catch(()=>{})}catch{}},ce=!1,be=new Map,oe=null,J=null,Ke=[],ke=new Set,Te=_.poolStart,kt=_.poolMax,Tt=0,ze=null,It=0,Ot=0,rt=null,cn=[],ar=[],at=new Set,st=E.now(),sr=!1,dn=w=>{st=E.now();for(let m of[...at])m.reconnect(w)};function gs(w,m){let I=w.ciphertext.length;if(I>=d&&m>0){let ee=Math.min(w.flowsAtStart??1,ke.size);if(ar.push({rate:I/m,flows:ee}),I/m*1e3<_.putFloorBytesPerSecond*2&&Te>_.poolMin){Te-=1,kt=Te,rt=null,Tt+=1,ze=E.now(),It=0,Ot=0;return}}if(w.round!==Tt||(It+=I,Ot+=1,Ot<Te||ze===null))return;let U=E.now()-ze;if(U<=0)return;let L=It/U;rt===null||L>rt*_.poolGrowRatio?Te=Math.min(kt,Te+1):L<rt*_.poolShrinkRatio&&(Te=Math.max(Math.min(_.poolStart,kt),Te-1)),rt=L,Tt+=1,ze=E.now(),It=0,Ot=0}function ws(w,m){let I=E.now()-m;if(I<_.hedgeMinInflightMs)return!1;let U=ke.size,L=ar.filter(V=>V.flows>=U).map(V=>V.rate);if(L.length===0)return!1;L.sort((V,H)=>V-H);let ee=L[Math.floor(L.length/2)];return w.ciphertext.length/I*_.hedgeLagFactor<ee}async function bs(w,m,I,U,L,ee){if(!Io()&&typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((H,he)=>{let X=new XMLHttpRequest,de=!1;sr=!0,X.upload.onprogress=_e=>{ee.onSocketActivity(_e.loaded,_e.lengthComputable?_e.total:w.length),ne(),ne=Oe()};let Oe=()=>E.after(Sn(w.length,_),()=>{de||ee.onDeadline()}),ne=Oe(),q=()=>{ne(),L.removeEventListener("abort",ie)},ie=()=>{de||(de=!0,X.abort(),q(),he(new P("Upload aborted","ABORTED",void 0,I)))};if(X.onload=()=>{if(de)return;de=!0;let _e={status:X.status,etag:X.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:X.status===400&&String(X.responseText??"").includes(Wr)};q(),H(_e)},X.onerror=()=>{de||(de=!0,q(),he(new P(`Failed to upload part ${I}: network error`,"NETWORK",void 0,I,!0)))},X.onabort=()=>{de||(de=!0,q(),he(new P("Upload aborted","ABORTED",void 0,I)))},L.aborted){q(),he(new P("Upload aborted","ABORTED",void 0,I));return}L.addEventListener("abort",ie,{once:!0}),X.open("PUT",U),X.setRequestHeader("Content-MD5",m),X.send(w)});let V;try{V=await tt(U,{method:"PUT",headers:{"Content-MD5":m},body:w,signal:ca(L,Sn(w.length,_))})}catch(H){throw h?.aborted||L.aborted?Ve(H,"Upload aborted"):new P(`Part ${I}: transport failure (${H instanceof Error?H.message:String(H)})`,"NETWORK",void 0,I,!0)}return{status:V.status,etag:V.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:V.status===400&&(await V.text().catch(()=>"")).includes(Wr)}}function ms(w,m){if(m.badDigest)throw new P(`Part ${w} arrived corrupted (BadDigest)`,"BAD_DIGEST",m.status,w,!0);if(m.status<200||m.status>=300)throw new P(`Failed to upload part ${w}: ${m.status}`,m.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",m.status,w,m.status!==404);if(!m.etag)throw new P(`No ETag returned for part ${w}`,"S3_ETAG_MISMATCH",void 0,w);return m.etag}async function Es(w,m){let I=E.now(),U=()=>{},L=0,ee=0,V=I,H=null,he=()=>{},X={reconnect:de=>he(de,!1),hasUnsentBytes:()=>H?.unsent??!1};at.add(X);try{let de=await new Promise((ne,q)=>{let ie=!1,_e=Be=>{ie||(ie=!0,Be())},lr=()=>{let Be=new AbortController,ot=()=>Be.abort();Y?.aborted?Be.abort():Y?.addEventListener("abort",ot,{once:!0});let Pe={ctl:Be,unsent:!0,ended:Promise.resolve()};H=Pe,V=E.now(),st=V,Pe.ended=bs(w.ciphertext,w.contentMd5,w.partNumber,m,Be.signal,{onSocketActivity:(Le,it)=>{st=E.now(),Pe.unsent=Le<it},onDeadline:()=>{if(++ee<2)return he("copy deadline",!1,!1);H===Pe&&_e(()=>q(new P(`Part ${w.partNumber}: no answer from storage after a reconnect`,"NETWORK",void 0,w.partNumber,!0)))}}).then(Le=>{if(H===Pe)try{let it=ms(w.partNumber,Le);_e(()=>ne(it))}catch(it){_e(()=>q(it))}},Le=>{H===Pe&&_e(()=>q(Ve(Le,`Failed to upload part ${w.partNumber}`)))}).finally(()=>{Pe.unsent=!1,Y?.removeEventListener("abort",ot)})};he=(Be,ot,Pe=!0)=>{let Le=H;ie||Le===null||h?.aborted||(H=null,L=ot?L+1:Pe?0:L,je.debug(`${ot?"replace":"reconnect"} part=${w.partNumber} (${Be})`),Le.ctl.abort(),Le.ended.then(()=>{ie||(Y?.aborted?_e(()=>q(new P("Upload aborted","ABORTED",void 0,w.partNumber))):lr())}))},lr(),U=E.every(_.hedgePollMs,()=>{ie||h?.aborted||H===null||L>=Ii||ws(w,V)&&he(`slower than its peers after ${Math.round(E.now()-I)}ms`,!0)})}),Oe=E.now();R.push({part_number:w.partNumber,etag:de}),Z+=w.ciphertext.length,se(w.ciphertext.length),gs(w,Oe-I),j.delivered(),st=Oe,je.debug(`part=${w.partNumber}/${M} put=${Math.round(Oe-I)}ms size=${w.ciphertext.length}${L>0?` replaced\xD7${L}`:""}`),G("uploading")}finally{at.delete(X),he=()=>{},U(),H?.ctl.abort()}}let Rt=(w,m,I)=>bt(w,m,I,Y);async function Ss(){try{let w=await Rt(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(B??"")}`,{method:"GET",headers:T},_.controlTimeoutMs);if(!w.ok)return null;let m=await w.json();return typeof m.status=="string"?m.status:null}catch{return null}}async function or(w){let m=performance.now(),I=await nt("presign batch",async()=>{let L=await Rt(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({upload_id:B,part_numbers:w})},_.controlTimeoutMs);if(!L.ok)throw await Qe(L,"Failed to get presigned URLs",L.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:ee}=await L.json();return ee}),U=new Map;for(let[L,ee]of Object.entries(I))U.set(Number(L),ee);return je.debug(`batch presign ${w.length} urls in ${Math.round(performance.now()-m)}ms`),U}async function As(w){let m=[];for(let U=w;U<=M&&m.length<C.upload.PRESIGN_BATCH_SIZE;U++)be.has(U)||m.push(U);if(m.length===0)return;let I=await or(m);for(let[U,L]of I)be.set(U,L)}function ir(w){oe||(oe=As(w).catch(()=>{}).finally(()=>{oe=null}))}async function vs(w){await wt(),ze??(ze=E.now()),v??(v=ze),w.round=Tt,w.flowsAtStart=ke.size;let m=be.get(w.partNumber);!m&&oe&&(await oe,m=be.get(w.partNumber)),be.delete(w.partNumber),ir(w.partNumber+1),await Yt(async({after:I})=>{if((!m||I==="refresh_url")&&(m=(await or([w.partNumber])).get(w.partNumber),!m))throw new P(`No presigned URL for part ${w.partNumber}`,"NETWORK",void 0,w.partNumber,!0);await Es(w,m)},{clock:j,policy:_,signal:Y,classify:ua,what:`part ${w.partNumber}`})}function un(){for(;!J&&!h?.aborted&&ke.size<Te&&Ke.length>0;){let w=Ke.shift(),m=vs(w).catch(I=>{J??(J=Ve(I,"Part upload failed"))}).finally(()=>{ke.delete(m);let I=cn;cn=[];for(let U of I)U();un()});ke.add(m)}}let xs=()=>new Promise(w=>{cn.push(w)}),ks=(()=>{let w=globalThis,m=globalThis.navigator?.connection,I=m?.type,U=()=>dn("network is back"),L=()=>j.connectionLost(),ee=()=>{let X=m?.type;X!==I&&(I=X,dn("network changed"))};w.addEventListener?.("online",U),w.addEventListener?.("offline",L),m?.addEventListener?.("change",ee);let V=Math.max(10,_.livenessSilenceMs/4),H=E.now(),he=E.every(V,()=>{let X=E.now(),de=Ti({now:X,lastLookAt:H,every:V,lastActivityAt:st,silenceMs:_.livenessSilenceMs});H=X,!(!sr||at.size===0||!de)&&[...at].some(Oe=>Oe.hasUnsentBytes())&&(j.connectionLost(),dn("every socket silent"))});return()=>{he(),w.removeEventListener?.("online",U),w.removeEventListener?.("offline",L),m?.removeEventListener?.("change",ee)}})();try{let w=performance.now();if(je.debug(`starting multipart: totalBytes=${n} parts=${M} partSize=${d} pool=${_.poolStart}..${_.poolMax}`),h?.aborted)throw new P("Upload aborted","ABORTED");G("encrypting"),B=await nt("multipart init",async()=>{let ne=await Rt(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({seal_id:r,content_type:f,content_length:x,part_size:d,file_id:a})},_.controlTimeoutMs);if(!ne.ok)throw await Qe(ne,"Failed to initialize multipart upload","NETWORK");return(await ne.json()).upload_id}),ir(1),G("encrypting");let m=!1,I=()=>{m=!0,G("encrypting")},U=async(ne,q,ie)=>{for(m=!0,ge+=q.length,G("encrypting"),h?.aborted&&await Q(h?.aborted===!0),Ke.push({partNumber:ne,ciphertext:q,contentMd5:ie}),un();Ke.length>=_.partQueueLimit;)if(await xs(),J)throw J;if(J)throw J},L=()=>Si({stream:t,totalBytes:n,key:y,header:o,partSize:d,signal:h,yieldToRenderer:typeof document<"u",onSegment:I,onPart:U}),ee=ki(),V=null;if(p&&ee&&typeof document<"u"){let ne=null;try{ne=ee(),V=[ne,ee()]}catch{ne?.terminate()}}if(V){let[ne,q]=V;je.debug("crypto pipeline: worker");try{await vi(ne,q,{file:p,key:y,header:o,partSize:d,totalBytes:n,signal:h,initialCredits:_.partQueueLimit,onSegment:I,onPart:U})}catch(ie){let _e=Ve(ie,"Crypto worker failed");if(_e.code==="ABORTED"||m)throw _e;je.debug(`crypto worker failed before output \u2014 inline fallback (${_e.message})`),await L()}finally{ne.terminate(),q.terminate()}}else await L();for(;un(),!(J||(h?.aborted&&await Q(!0),ke.size===0&&Ke.length===0));)await Promise.race(ke);if(J)throw J;G("verifying"),h?.aborted&&await Q(h?.aborted===!0),ce=!0,g?.();let H=!1,he,X=await nt("complete",async()=>{let ne=H;H=!0;let q=await Rt(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...T},body:JSON.stringify({upload_id:B,parts:R.map(ie=>({part_number:ie.part_number,etag:ie.etag})),...S?{on_conflict:S}:{}})},_.completeTimeoutMs);if(q.ok){let ie=await q.json().catch(()=>null);return typeof ie?.conflict_with=="string"&&(he=ie.conflict_with),ie?.status==="verified"}if(ne&&q.status===400&&await Ss()==="completed")return!1;throw await Qe(q,"Failed to complete multipart upload",q.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});j.delivered(),G("done");let de=Math.round(performance.now()-w),Oe=n/(1024*1024)/(de/1e3);return je.debug(`DONE totalTime=${de}ms speed=${Oe.toFixed(2)}MB/s parts=${R.length}`),y.fill(0),{verified:X,...he?{conflictWith:he}:{}}}catch(w){y.fill(0);let m=Ve(w,"Unknown upload error");throw ce&&m.code!=="ABORTED"&&(m.httpStatus===void 0||m.httpStatus>=500)||ve(m.code==="ABORTED"),m}finally{ks(),j.dispose(),we.abort()}}var We={multipartThresholdBytes:C.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:C.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:C.upload.INMEMORY_BLOB_LIMIT_BYTES};function Li(e,t=We){return e<=C.upload.FINE_PART_MAX_FILE_BYTES?C.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Ia(e,t){return e>=t.multipartThresholdBytes}function Di(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 Fn(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:Di(e.auth)}function Ni(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var Ci={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},Hr=[2,12],Mi=[12,95],Bi=[95,99];function Kr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=Ci[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=Bi:r.deliveredBytes===0?s=Hr:s=Mi;let o=s===Hr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,c=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,c),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 $n=class{constructor(e,t){this.run=t,this.cancelled=!1,this.running=null,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 P("Upload session was cancelled","ABORTED");return this.running??(this.running=this.run(this,e).catch(t=>{throw Lo(Ve(t,"Upload failed"),this)}).finally(()=>{this.running=null})),this.running}async cancel(){this.cancelled=!0;let e=Ni(this.ctx);if(!e){let n=this.ctx.revokeFilePath;if(!n||this.createdSeal)return;for(let r of this.pending){let a=n.replace("{sealId}",encodeURIComponent(this.sealId)).replace("{fileId}",encodeURIComponent(r.fileId));await tt(`${this.ctx.baseUrl}${a}`,{method:"DELETE",headers:en(Fn(this.ctx)),credentials:this.ctx.credentials??"include"}).catch(()=>{})}return}let t=new St({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 Ui(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)throw new Error(`${n}: file record ${o} carries no sha256_hex \u2014 refusing to pair it by position`);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 Fi(e){return e>=200&&e<300||e===204}async function $i(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:c,clock:d,transport:f}=e,u=` for ${i}`,h={"Content-Type":"application/json",...s},p=t.credentials??"include",g=(T,x)=>Yt(x,{clock:d,policy:f,signal:c,classify:ha,what:T}),S=()=>g(`initiate${u}`,async()=>{let T=await bt(`${t.baseUrl}/upload/initiate`,{method:"POST",headers:h,credentials:p,body:JSON.stringify({seal_id:n,content_type:"application/octet-stream",content_length:a.blob.size,file_id:r})},f.controlTimeoutMs,c);if(T.status===409)return null;if(!T.ok)throw await Qe(T,`Upload initiate failed${u}`,"NETWORK");let x=await T.json();return x.already_verified?null:x}),_=await S();if(_===null)return!1;let E=!1;if(await Yt(async({after:T})=>{if(T==="refresh_url"){let B=await S();if(B===null){E=!0;return}_=B}let{upload_url:x}=_,M=await bt(x,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},Sn(a.blob.size,f),c);if(M.status===400&&(await M.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new P(`Upload arrived corrupted (BadDigest)${u}`,"BAD_DIGEST",400,void 0,!0);if(!Fi(M.status))throw new P(`Upload PUT failed${u}: ${M.status}`,"NETWORK",M.status)},{clock:d,policy:f,signal:c,classify:ua,what:`PUT${u}`}),E)return!1;d.delivered(),o();let y=await g(`confirm${u}`,async()=>{let T=await bt(`${t.baseUrl}/upload/confirm`,{method:"POST",headers:h,credentials:p,body:JSON.stringify({seal_id:n,file_id:r,...t.onConflict?{on_conflict:t.onConflict}:{}})},f.controlTimeoutMs,c);if(T.status===409)return!1;if(!T.ok)throw await Qe(T,`Upload confirm failed${u}`,"NETWORK");let x=await T.json().catch(()=>null);return typeof x?.conflict_with=="string"&&e.onConflictWith(x.conflict_with),x?.status==="verified"});return d.delivered(),y}async function Oa(e,t,n,r,a,s){try{let o=await bt(`${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 P&&o.code==="ABORTED")throw o;return null}}var Wi=new Set(["failed","size_mismatch","verification_error"]),Hi=new Set(["verified","pending_verification"]);async function Ki(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i}=e,c=s.verifyFallbackWaitMs,d=performance.now(),f=s.verifyPollBackoffMs;for(let u=0;;u++){let h=f[Math.min(u,f.length-1)]??0;if(performance.now()-d+h>c)return"pending";h>0&&await Cn(h,o);let p=await Oa(t,n,r,a,s,o);if(p==="verified")return"verified";if(p!==null&&Wi.has(p))throw new P(`The server rejected ${i} after upload (${p}). It has to be sent again.`,"VERIFICATION_REJECTED");if(p===null&&u===0)return"pending"}}async function zi(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:c}=t,{onProgress:d,signal:f}=n;if(t.state!=="pending")return;if(f?.aborted)throw new P("Upload aborted","ABORTED");let u=Fn(r),h=en(u),p=Dn(a.transport),g=async R=>{if(t.state=R?"verified":"uploaded",!R)try{await Ki({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:h,transport:p,signal:f,label:o.name})==="verified"&&(t.state="verified")}catch(Z){throw Z instanceof P&&Z.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),Z}};if(Ia(o.size,a)){if(t.streamed){let v=await Oa(r,s,t.sha256_hex,h,p,f);if(v!==null&&Hi.has(v)){await g(v==="verified");return}}let R=Kr("multipart",v=>d?.(v)),Z=null,ge=await Oi({file:o,sealId:s,fileId:c,key:i,header:t.header,baseUrl:r.baseUrl,auth:u,partSize:Li(o.size,a),onProgress:v=>{Z=v;let D=v.phase==="done";R({...v,phase:D?"verifying":v.phase,fraction:D?0:v.deliveredBytes/v.totalBytes,preparedFraction:v.totalBytes>0?(v.preparedBytes??0)/v.totalBytes:0,preparedBytes:v.preparedBytes})},signal:f,transport:a.transport,onStreamed:()=>{t.streamed=!0},onConflict:r.onConflict});t.streamed=void 0,t.conflictWith=ge.conflictWith,await g(ge.verified);let O=t.encryptedSize;R({...Z??{phase:"done",percent:100,deliveredBytes:O,totalBytes:O,state:"running",attempt:1},phase:"done",fraction:1});return}let S=Kr("single-put",R=>d?.(R)),_=t.encryptedSize,E={phase:"encrypting",fraction:0,delivered:!1},y=null,T=(R,Z,ge=E.delivered)=>{E={phase:R,fraction:Z,delivered:ge},S({phase:R,fraction:Z,deliveredBytes:ge?_:0,totalBytes:_,state:y?.state??"running",attempt:(y?.retriesSinceDelivery??0)+1})};t.prepared||(T("encrypting",0),t.prepared=await ai(o,i,t.header,R=>T("encrypting",o.size>0?R/o.size:1)));let x=t.prepared,M=new fa(p,()=>T(E.phase,E.fraction));y=M,T("uploading",0);let B;try{B=await $i({ctx:r,sealId:s,fileId:c,ciphertext:x,authHeaders:h,onVerifying:()=>T("verifying",0,!0),label:o.name,signal:f,clock:M,transport:p,onConflictWith:R=>{t.conflictWith=R}})}finally{M.dispose()}T("verifying",.5,!0),await g(B),t.prepared=void 0,T("done",1,!0)}async function Gi(e,t={}){let{signal:n,onFileProgress:r}=t,a=h=>Ia(h.file.size,e.policy),s=e.pending,o=s.filter(h=>!a(h)),i=s.filter(a),c=new AbortController,d=()=>c.abort();n?.aborted?c.abort():n?.addEventListener("abort",d,{once:!0});let f=null,u=async h=>{try{await zi(e,h,{signal:c.signal,onProgress:p=>r?.(h,p)})}catch(p){f===null&&(f=p,c.abort())}};try{let h=0,p=async()=>{for(;f===null&&!c.signal.aborted&&h<o.length;)await u(o[h++])};await Promise.all(Array.from({length:Math.min(C.upload.SMALL_FILE_POOL,o.length)},p));for(let g of i){if(f!==null||c.signal.aborted)break;await u(g)}}finally{n?.removeEventListener("abort",d)}if(f!==null)throw f;if(n?.aborted)throw new P("Upload aborted","ABORTED")}function ji(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 Yi(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 Vi(e,t,n,r,a={}){let s=await Fr(a.relativePath??e.name,t,"name"),o=await Fr(e.type||yi(e.name),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:Se.current_format_version};return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function Xi(e,t,n,r,a){if(n?.aborted)throw new P("Upload aborted","ABORTED");let s=tt(e,t);return new Promise((o,i)=>{let c=!1,d=p=>{c||(c=!0,h(),i(p),s.then(async g=>g.ok?r(await g.json()):void 0).catch(()=>{}))},f=()=>d(new P("Upload aborted","ABORTED")),u=setTimeout(()=>d(new P(`The registration got no answer in ${Math.round(a/1e3)} s`,"NETWORK",void 0,void 0,!0)),a),h=()=>{clearTimeout(u),n?.removeEventListener("abort",f)};n?.addEventListener("abort",f,{once:!0}),s.then(p=>{c||(c=!0,h(),o(p))},p=>{c||(c=!0,h(),i(p))})})}function qi(e){return Dn(e.transport).completeTimeoutMs}async function Zi(e,t,n,r){try{return Ui(e,t,n)}catch(a){throw await r((e??[]).filter(s=>s.sha256_hex!==void 0&&t.includes(s.sha256_hex))).catch(()=>{}),a}}async function Ji(e,t){if(t?.aborted)throw await e.cancel(),new P("Upload aborted","ABORTED")}async function Qi(e,t,n,r,a){let s={files_meta:t};e.ownerTokenHash&&(s.owner_token_hash=e.ownerTokenHash),Yi(s,e);let o=await Xi(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...en(Fn(e))},credentials:e.credentials??"include",body:JSON.stringify(s)},n,r,a);if(!o.ok)throw await Qe(o,"Create seal failed","UNKNOWN");return await o.json()}async function el(e,t){let n=bo();return{file:e,key:t,header:n,sha256_hex:await Ze(n)}}async function tl(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 nl(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:Pn(n.file.size),state:"pending"}))}function Ra(e){let t=new Map;for(let n of e)t.set(n.sha256_hex,n.key);return t}function rl(e){let t=e.reduce((a,s)=>a+s.file.size,0),n=new Map;for(let a of e)n.set(a.index,a.state==="pending"?0:100);let r=0;return{note(a,s){n.set(a.index,s.phase==="done"?100:Math.max(n.get(a.index)??0,s.percent));let o=e.every(d=>n.get(d.index)===100),i=e.reduce((d,f)=>d+f.file.size*(n.get(f.index)??0),0),c=t>0?Math.floor(i/t):100;return r=Math.max(r,o?100:Math.min(99,c)),{percent:r,finished:o}}}}async function al(e,t){let{onProgress:n,signal:r}=t,a=e.files,s=rl(a);await Gi(e,{signal:r,onFileProgress:(o,i)=>{n?.({fileIndex:o.index,totalFiles:a.length,fileName:o.file.name,fileProgress:i,overallPercent:s.note(o,i).percent})}})}async function Pa(e,t,n,r,a){if(t.length===0)throw new Error("At least one file is required");ji(e);let s=await Promise.all(t.map(({file:u})=>el(u,ko()))),o=await Promise.all(s.map((u,h)=>Vi(u.file,u.key,Pn(u.file.size),u.sha256_hex,{relativePath:t[h].relativePath}))),i=(u,h)=>new $n({ctx:e,policy:n,sealId:u.id,createdSeal:!0,expiresAt:u.expires_at,files:h},async(p,g)=>(await al(p,g),a(p))),c=await Qi(e,o,r.signal,u=>i(u,[]).cancel(),qi(n)),d=await Zi(c.files,s.map(u=>u.sha256_hex),`Create seal ${c.id}`,()=>i(c,[]).cancel()),f=i(c,nl(s,d));return await Ji(f,r.signal),await tl(r,c.id,s,d),f.resume(r)}async function La(e,t,n=We,r={}){return Pa(e,t.map(a=>({file:a})),n,r,a=>({sealId:a.sealId,files:a.files.map(s=>({fileId:s.fileId,sha256_hex:s.sha256_hex,encryptedSize:s.encryptedSize})),encryptionKeys:Ra(a.files),expiresAt:a.expiresAt,verification:a.verification}))}async function Da(e,t,n,r=We,a={},s){if(s&&s.length!==t.length)throw new Error(`uploadFolderAsFiles: ${t.length} file(s) but ${s.length} path(s)`);let o=t.map((i,c)=>({file:i,relativePath:s?.[c]||i.webkitRelativePath||`${n}/${i.name}`}));return Pa(e,o,r,a,i=>({sealId:i.sealId,files:i.files.map(c=>({fileId:c.fileId,sha256_hex:c.sha256_hex,encryptedSize:c.encryptedSize,relativePath:o[c.index].relativePath})),encryptionKeys:Ra(i.files),folderName:n,expiresAt:i.expiresAt,verification:i.verification}))}var zr=[2e3,4e3,8e3,15e3],mn=ye.limits.TIER_BYTES,Pc=Object.keys(mn).filter(e=>e!=="free").sort((e,t)=>mn[e]-mn[t]);function Na(e){return e instanceof P&&e.httpStatus===402&&e.session?e.session:null}function Ca(e,t=Date.now()){let n=t+ye.limits.PAYMENT_WAIT_MAX_SECONDS*1e3,r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)?Math.min(n,r):n}async function Ma(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 te&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=zr[Math.min(a,zr.length-1)];if(Date.now()+s>r.deadline)return null;await Cn(s,r.signal)}}var tn=ye.limits.ttl_options;function Ba(e){let t=e.trim();if(t==="")return;let n=/^\d+$/.test(t)?Number(t):Number.NaN;return n>=1&&n<=ye.limits.MAX_OPENS_PER_SEAL_FREE?n:null}var sl=new Set(["AC","CP","CQ","DG","EA","EU","EZ","IC","QO","TA","UN","XA","XB","ZZ"]),En;function Ua(e){En??(En=new Intl.DisplayNames(["en"],{type:"region",fallback:"none"}));let t=[],n=[];for(let r of e.split(/[\s,;]+/)){if(r==="")continue;let a=r.toUpperCase(),s=/^[A-Z]{2}$/.test(a)?Intl.getCanonicalLocales(`und-${a}`)[0]?.split("-")[1]:void 0;!s||sl.has(s)||!En.of(s)?n.push(r):t.includes(s)||t.push(s)}return{codes:t,bad:n}}var Wn=8,Hn=43,kn=4,nn=/^[A-Za-z0-9_-]+$/;function ol(e,t){if(!nn.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 Kn(e){return e.length===Wn&&nn.test(e)}function zn(e){return e.length===Hn&&ol(e,32)}function Fa(e,t){if(!Kn(e))throw new Error(`Invalid sealId: must be ${Wn} base64url characters`);if(!zn(t))throw new Error(`Invalid linkKey: must be ${Hn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function $a(e,t,n){if(!Kn(e))throw new Error(`Invalid sealId: must be ${Wn} base64url characters`);if(t.length!==kn||!nn.test(t))throw new Error(`Invalid shareCode: must be ${kn} base64url characters`);if(!zn(n))throw new Error(`Invalid linkKey: must be ${Hn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var zt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function il(e){let t;try{t=new URL(e)}catch{throw new zt("url_invalid",`not a valid URL (${e.length} characters)`)}let n;try{n=ll(t.pathname.replace(/\/+$/,""))}catch{throw new zt("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(!zn(r))throw new zt("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 ll(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(!Kn(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==kn||!nn.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var Gn=Ee.scopes.share_link,Wa=Ee.scopes.owner_copy;var Gr=et.sealed_box_v2.version_byte,jr=et.sealed_box_v2.packed_length,mt=64,Jt=32,Yr=32;var Ha=/^[A-Za-z0-9_-]+$/;function Ka(){return crypto.getRandomValues(new Uint8Array(mt))}async function jn(e,t=1){let n=await ft();if(e.length===mt)return n.WasmIdentity.fromSeed64(e,t);if(e.length===Jt)return n.WasmIdentity.fromSeed32(e);throw new Error(`a seed is ${mt} bytes, or the ${Jt} of a key made before, got ${e.length}`)}async function Yn(e,t=1){let n=await jn(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words()}}finally{n.free()}}function za(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(!Ha.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 Ga(e,t){return(await ft()).wasm_bundle_verify_for_address(e,t)}async function Vn(e){return(await ft()).wasm_bundle_address(e)}async function rn(e,t,n,r){if(e.length!==Yr)throw new Error(`a wrapped key is ${Yr} bytes, got ${e.length}`);if(r.length===0)throw new Error("the scope id must not be empty: the wrap binds to it");return ae((await ft()).wasm_sealbox_wrap(e,t,n,r))}var Ye=class extends Error{constructor(e,t,n){super(t),this.name="WrapError",this.kind=e,this.cause=n}};async function cl(e,t,n,r,a=1){if(r.length===0)throw new Ye("parse","the scope id must not be empty: the wrap binds to it");if(!Ha.test(e))throw new Ye("parse","the wrap is not urlsafe-base64-no-pad");let s=ue(e);if(s[0]!==Gr)throw new Ye("parse",`the wrap is not a sealed box v${Gr}: a newer client made it \u2014 update this one`);if(s.length!==jr)throw new Ye("parse",`the wrap is ${s.length} bytes, expected ${jr}`);if(t.length!==mt&&t.length!==Jt)throw new Ye("parse",`a seed is ${mt} bytes, or the ${Jt} of a key made before, got ${t.length}`);let o=await jn(t,a);try{return o.open(s,n,r)}catch(i){throw new Ye("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 dl(e,t){let n=await jn(e);try{let r=n.inboxProof(BigInt(t.ts),ue(t.challenge));return`${t.ts}.${t.challenge}.${ae(r)}`}finally{n.free()}}var Tn={version:2,name:"FINGERPRINT_WORDS",description:"Eight words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3; eight since AUDIT K251, owner 11.11: eight words, 24 bits, were ground in 207 s on one Mac): word i (i = 0 \u2026 7) is words[byte i of SHA-256(identity public key)] \u2014 the first eight 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 64 bits in all, written in lower case with one space between them; the first three are the three of before. 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:8,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:"66687aadf862bd77",words:"iron ivory lava plum yacht horse river lagoon"}},ul=Tn.words,hl=/^[A-Za-z0-9_-]{43}$/;function ja(e){if(!hl.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=ue(e);return Array.from(t.subarray(0,Tn.count),n=>ul[n]).join(Tn.separator)}var Ya=Ee.payloads.pair.mime,Dc=Ee.payloads.device.mime,Nc=Ee.payloads.delivery.mime,Cc=Ee.payloads.approve.mime,Mc=Ee.payloads.approve_answer.mime,Bc=Ee.payloads.summary.mime,Va=Ee.pair_what,Vr=Ee.payloads.name_max,Uc=ye.limits.APPROVE_BODY_SHOWN_BYTES;var Xr=et.keybundle.packed_length,qr=2;var fl=/^[A-Za-z0-9_-]+$/;function Xa(e){let t=pl(e,"pairing");if(typeof t.bundle!="string"||!fl.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:_l(ue(t.bundle)),name:yl(t.name)}}function pl(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!==qr)throw new Error(`${t} payload is not version ${qr}`);return n}function _l(e){if(e.length!==Xr)throw new Error(`a bundle is ${Xr} bytes, got ${e.length}`);return e}function yl(e){if(typeof e!="string"||e.length===0||e.length>Vr)throw new Error(`name must be 1 to ${Vr} characters`);return e}var gl={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 match of an entry with `checksum` is a finding only when it passes that sum: `luhn` \u2014 the Luhn sum of its digits is 0 modulo 10; `iban` \u2014 its characters but spaces, upper-cased, the first four moved to the end, each letter read as a number (A = 10 \u2026 Z = 35), are 1 modulo 97. 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,wildcard_public_second_level:["ac","co","com","edu","gov","go","ne","net","or","org","mil","int","gob","ltd","plc","me","nom"],shared_host_suffixes:["s3.amazonaws.com","cloudfront.net","azurewebsites.net","appspot.com","firebaseapp.com","web.app","github.io","githubusercontent.com","gitlab.io","herokuapp.com","pages.dev","workers.dev","vercel.app","netlify.app","onrender.com","fly.dev","blogspot.com","ngrok.io","ngrok-free.app","glitch.me","surge.sh"],shared_host_note:"Names under which each customer has a name of its own (the private part of the public suffix list): a host there is one service with the label before it, as `x.co.uk` is \u2014 AUDIT K162: by its last two labels every github.io page was one service.",wildcard_note:"A proposed `*.<name>` binds a key unless <name> is a public suffix: one label (`*.com`), or two where the second is a two-letter country top level and the first is one of wildcard_public_second_level (`*.co.uk` would be a root for every .co.uk host; `*.me.com` is a name of its own); a bare name needs two labels (SPEC agent egress \xA74.2, review of phase 1).",guard_note:"What the guard does with a key of an entry (SPEC agent egress \xA74.1, read by `seal-client-core::guard`). `hosts`: where the key is a way in, the default binding a person confirms or narrows; `*.` is one label. `place`: where the guard puts the value \u2014 `bearer` (Authorization: Bearer), `header:<name>`, `query:<param>`, `basic_user`, `basic_pass`, `userinfo`, `url` (the secret is the request address itself, a webhook). `class`: `outbound` \u2014 a key a program enters a service with, the proxy puts it in; `inprocess` \u2014 a key a program works with itself (a webhook signing secret, a database password of a driver that uses no proxy, a private key, an assignment the pattern matches with its name): the program gets the value, by the person's word on the page. `surrogate`: the form of the stand-in the agent sees \u2014 `keep_prefix` (kept as it is), `alphabet` (`base62`, `base64url`, `hex`, `digits`, `base32`, `classes` \u2014 each character keeps its class and punctuation stays), `length` (a number, else the value's), `checksum` (`github_crc32`: the last six characters are the CRC32 of the body, base62), `parts` (`password`: of a connection URI only the password changes). An entry without `surrogate` is treated by classes. `provision_commands`: commands that write a key as data into a service's own store; a surrogate in their arguments or stdin is refused unless the binding's `provision` names the host (\xA75.4, \xA76.4). Data, not code: a service is added with one entry.",provision_commands:[{command:"wrangler secret put",host:"api.cloudflare.com"},{command:"gh secret set",host:"api.github.com"},{command:"vercel env add",host:"api.vercel.com"},{command:"fly secrets set",host:"api.machines.dev"},{command:"kubectl create secret",host:null},{command:"aws secretsmanager put-secret-value",host:"*.amazonaws.com"},{command:"heroku config:set",host:"api.heroku.com"},{command:"doppler secrets set",host:"api.doppler.com"}],patterns:[{name:"openai_api_key",pattern:"\\bsk-proj-[A-Za-z0-9_-]{40,}",severity:"critical",description:"OpenAI API Key",keywords:["openai","sk-proj-"],hosts:["api.openai.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^sk-proj-",alphabet:"base64url"},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-"],hosts:["api.anthropic.com"],place:"header:x-api-key",class:"outbound",surrogate:{keep_prefix:"^sk-ant-(?:api[0-9]{2}-)?",alphabet:"base64url"},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_"],hosts:["api.github.com","github.com","uploads.github.com","codeload.github.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^(?:gh[pousr]|github_pat)_",alphabet:"classes",checksum:"github_crc32"},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"],hosts:["gitlab.com"],place:"header:PRIVATE-TOKEN",class:"outbound",surrogate:{keep_prefix:"^glpat-",alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:"^(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)",alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]?`,alphabet:"classes"},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"],hosts:["api.stripe.com","files.stripe.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^[sr]k_live_",alphabet:"base62"},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"],hosts:["api.stripe.com","files.stripe.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^[sr]k_test_",alphabet:"base62"},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:"stripe_webhook_secret",pattern:"\\bwhsec_[A-Za-z0-9]{32,}",severity:"critical",description:"Stripe Webhook Signing Secret",keywords:["stripe","webhook","whsec_"],class:"inprocess",surrogate:{keep_prefix:"^whsec_",alphabet:"base62"},vectors:{hit:"STRIPE_WEBHOOK_SECRET=whsec_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789",clean:"STRIPE_WEBHOOK_SECRET=whsec_short"}},{name:"slack_token",pattern:"\\bxox[abprs]-[A-Za-z0-9-]{20,}",severity:"critical",description:"Slack Token",keywords:["slack","token","xox"],hosts:["slack.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^xox[abprs]-",alphabet:"classes"},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"],hosts:["hooks.slack.com"],place:"url",class:"outbound",surrogate:{keep_prefix:"^https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B",alphabet:"classes"},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"],hosts:["*.googleapis.com"],place:"query:key",class:"outbound",surrogate:{keep_prefix:"^AIza",alphabet:"base64url"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]?`,alphabet:"classes"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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"],class:"inprocess",surrogate:{parts:"password"},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."],hosts:["api.sendgrid.com"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^SG\\.",alphabet:"classes"},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"],hosts:["api.twilio.com"],place:"basic_user",class:"outbound",surrogate:{keep_prefix:"^SK",alphabet:"hex"},vectors:{hit:"SK0123456789abcdef0123456789abcdef",clean:"SK0123456789abcdef"}},{name:"npm_token",pattern:"npm_[A-Za-z0-9]{36}",severity:"high",description:"NPM Access Token",keywords:["npm","token"],hosts:["registry.npmjs.org"],place:"bearer",class:"outbound",surrogate:{keep_prefix:"^npm_",alphabet:"base62"},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"],hosts:["upload.pypi.org"],place:"basic_pass",class:"outbound",surrogate:{keep_prefix:"^pypi-",alphabet:"base64url"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]`,alphabet:"classes"},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"],class:"inprocess",surrogate:{keep_prefix:`^.*[:=]\\s*['\\"]`,alphabet:"classes"},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"}},{name:"payment_card",pattern:"\\b(?:\\d[ -]?){12,18}\\d\\b",checksum:"luhn",severity:"high",description:"Payment Card Number",keywords:["card","visa","mastercard"],vectors:{hit:"card: 4111 1111 1111 1111",clean:"card: 4111 1111 1111 1112"}},{name:"iban",pattern:"\\b[A-Z]{2}\\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\\b",checksum:"iban",severity:"high",description:"IBAN",keywords:["iban","bank","account"],vectors:{hit:"IBAN DE89 3704 0044 0532 0130 00, please",clean:"IBAN DE89 3704 0044 0532 0130 01, please"}},{name:"passport_number",pattern:"\\bpassport(?:\\s*(?:no|number|#))?\\.?\\s*[:=#]?\\s*[A-Z]{0,2}[0-9]{6,9}\\b",severity:"high",description:"Passport Number",keywords:["passport"],vectors:{hit:"Passport No: X1234567",clean:"Passport photos: 2 copies"}}]},an=gl.mime,W=class extends Error{constructor(e,t,n){super(t),this.name="OpenError",this.code=e,this.cause=n}},wl=32;async function Xn(e,t,n={}){let r;try{r=il(t)}catch(y){throw y instanceof zt?new W(y.code,y.message,y):y}if(r.shareCode===null)throw new W("url_invalid","share code missing from the URL path (/s/<seal_id>/<share_code>#<key>)");let{sealId:a,shareCode:s}=r,o=n.seed,i=n.wrap??null,c=r.fragmentVariant==="key"?ue(r.fragment):i!==null&&o?await Zr(i,o,a):null;c!==null&&await Or(a,c);let d=n.signal?{signal:n.signal}:{},f;try{f=await e.getMetadata(r.sealId,{...d,shareCode:s})}catch(y){throw y instanceof te&&(y.code==="not_found"||y.code==="revoked")?new W(y.code==="revoked"?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${y.code==="revoked"?"has been revoked":"was not found or has expired"}`,y):new W("metadata_failed",`reading seal ${r.sealId} failed: ${In(y)}`,y)}let u=Fo(f);if(u.revokedAt!==null)throw new W("seal_revoked",`seal ${r.sealId} has been revoked`);if(u.files.length===0)throw new W("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 h;try{let y=await e.getShareBlob(a,s,d);if(h=y.blob,c===null){if(y.wrap===null)throw new W("url_no_fragment","the link carries no key after #: copy it whole");if(!o)throw new W("targeted_fragment_invalid","this link is addressed to someone: pass their seed to open it");c=await Zr(y.wrap,o,a),await Or(a,c)}}catch(y){throw y instanceof W?y:y instanceof te&&(y.code==="not_found"||y.code==="revoked")?new W(y.code==="revoked"?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${y.code==="revoked"?"has been revoked":"was not found"}`,y):new W("share_blob_fetch_failed",`share blob fetch failed: ${In(y)}`,y)}let p,g,S,_;try{let y=await Jo(h,c);p=y.file_keys,g=qo(y),S=y.message?.trim()?y.message:null,_=Vo(y.nda_file)?y.nda_file:null}catch(y){throw new W("share_blob_decrypt_failed","the share blob does not open with this link \u2014 mistyped URL, or the link was revoked and minted again",y)}let E=await Promise.all(u.files.map(y=>vl(y,p,g)));return{sealId:a,shareCode:s,expiresAt:u.expiresAt,singleUse:u.singleUse,maxOpens:u.maxOpens,otpRequired:u.otpRequired,ndaRequired:u.ndaRequired,otpPassed:f.otp_session_valid===!0,ndaPassed:f.nda_session_valid===!0,spent:f.spent===!0,countries:f.geo_allowlist?.length?f.geo_allowlist:null,message:S,ndaFile:_,linkKey:c,files:E}}async function Zr(e,t,n){try{return await cl(e,t,Gn,n)}catch(r){let a=r instanceof Ye&&r.kind==="aead";throw new W(a?"targeted_decrypt_failed":"targeted_fragment_invalid",In(r),r)}}async function qa(e,t,n={}){for(;;){n.signal?.throwIfAborted();let r=Date.now(),a;try{a=await e.getIntake(t,{...n,waitSeconds:ye.limits.INTAKE_WAIT_MAX_SECONDS})}catch(o){throw o instanceof te&&o.code==="not_found"?new W("request_expired","the request expired before anybody answered",o):o}if(a.status==="expired")throw new W("request_expired","nobody answered before the request expired");if(a.status==="fulfilled"){if(a.share_path&&a.fragment)return{sharePath:a.share_path,wrap:a.fragment};throw new W("share_blob_corrupt","the request was answered without its link")}if(a.status!=="pending")throw new W("client_outdated",`the request is ${String(a.status)}, a state this client does not know`);let s=bl-(Date.now()-r);s>0&&await ml(s,n.signal)}}var bl=2e3;function ml(e,t){return new Promise((n,r)=>{let a=()=>{clearTimeout(s),r(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}var Jr=64*1024;async function Za(e,t,n,r){let a=await Xn(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||Qa(s.mime)!==n||s.size>Jr)throw new W("share_blob_corrupt",`the answer is not one ${n} file`);return El(e,{sealId:a.sealId,shareCode:null},s,{maxBytes:Jr,...r.signal?{signal:r.signal}:{}})}async function El(e,t,n,r){if(!n.key||!n.sha256Hex||n.size>r.maxBytes)throw new W("share_blob_corrupt",`file ${n.id} is not one of at most ${r.maxBytes} bytes this link opens`);let a=await e.downloadCiphertext(t.sealId,{fileId:n.id,...t.shareCode?{shareCode:t.shareCode}:{},...r.sessionCookie?{sessionCookie:r.sessionCookie}:{},...r.visit?{visit:r.visit}:{}},r.signal?{signal:r.signal}:{});if(!a.body)throw new W("share_blob_corrupt",`file ${n.id} came without a body`);let s=Zn(a.body,n.key,n.sha256Hex).stream.getReader(),o=[];for(let d=await s.read();!d.done;d=await s.read())o.push(d.value);let i=new Uint8Array(o.reduce((d,f)=>d+f.length,0)),c=0;for(let d of o)i.set(d,c),c+=d.length;return i}var Sl=3e4,Qr=new Map;async function Al(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&Tl(r,t.bundle)||await e.putBundle(t.bundle,n)}async function Qt(e,t,n={}){let r=await Yn(t),a=`${e.baseUrl} ${r.address}`,s=Qr.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await Al(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await dl(t,o)};return Qr.set(a,{proof:i,until:Date.parse(o.expires_at)-Sl}),i}async function sn(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await Qt(e,t,a))}catch(s){if(!(s instanceof te&&s.appCode==="intake.proof_required"))throw s;return r(await Qt(e,t,{...a,fresh:!0}))}}async function qn(e,t,n={}){let r=n;return sn(e,t,n.signal,a=>e.listInbox(a,r))}async function Ja(e,t,n,r={}){return sn(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function vl(e,t,n){let r=e.sha256_hex?t[e.sha256_hex]:void 0,a={id:e.id,size:e.size,sha256Hex:e.sha256_hex};if(r===void 0)return{...a,name:Xt,mime:qt,secret:!1,key:null,binding:null};let s;try{s=ue(r)}catch(f){throw new W("share_blob_corrupt",`share blob carries a non-base64url key for ${e.sha256_hex}`,f)}if(s.length!==wl)throw new W("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${s.length} bytes`);let{name:o,mime:i}=await mi(e,s),c=Qa(i)===an,d=c&&e.sha256_hex?n[e.sha256_hex]??null:null;return{...a,name:o,mime:i,secret:c,key:s,binding:d}}function Qa(e){return(e.split(";")[0]??e).trim().toLowerCase()}function Zn(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=$t.create(),o=0,i,c=new Promise((h,p)=>{i={resolve:h,reject:p}});c.catch(()=>{});let d=new TransformStream({transform(h,p){r(h.length),p.enqueue(h)}}),f=new TransformStream({transform(h,p){s.update(h),o+=h.length,p.enqueue(h)},flush(){a.fill(0),i.resolve({sizeBytes:o,sha256:kl(s.digest())})}}),u=e.pipeThrough(d).pipeThrough(ii(a,{expectedSha256Hex:n})).pipeThrough(f);return{stream:Il(u,i.reject,a),done:c}}function xl(e){return e instanceof Me?new W(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function kl(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Tl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Il(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=xl(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function In(e){return e instanceof Error?e.message:String(e)}var $c=ye.limits.LEASE_DEFAULT_DAYS,Wc=ye.limits.LEASE_MAX_DAYS,Hc=ye.limits.LEASE_POLL_SECONDS,Kc=ye.limits.LEASE_STATUS_BATCH_MAX;async function ts(){let e=ba(),t=Mn();return{ownerTokenB64:ae(e),ownerTokenHash:await ma(e),linkKey:t,linkKeyB64:ae(t)}}var ns=tn[tn.length-1]??tn[0],Jn={ttl:"1h",singleUse:!0};function rs(e,t,n){return{ttl:n&&e.ttl!=="1d"&&e.ttl!=="7d"?"1d":e.ttl,...n?{tier:n}:{},...e.otp?{otp:e.otp}:{},nda:e.nda??!1,...e.ownerEmail?{ownerEmail:e.ownerEmail}:{},singleUse:e.singleUse??!1,...!e.singleUse&&e.maxOpens?{maxOpens:e.maxOpens}:{},...e.geo&&e.geo.length>0?{geo:e.geo}:{},ownerTokenHash:t.ownerTokenHash,ownerToken:t.ownerTokenB64}}var ad={...We,transport:{maxStallMs:1/0}};function as(e,t){let{ttl:n,tier:r,otp:a,nda:s,ownerEmail:o,singleUse:i,maxOpens:c,geo:d,ownerTokenHash:f,ownerToken:u}=t;return{baseUrl:e,auth:{kind:"none"},ttl:n,...r?{tier:r}:{},...a?{otp:a}:{},...s!==void 0?{nda:s}:{},...o?{ownerEmail:o}:{},...i!==void 0?{singleUse:i}:{},...c?{maxOpens:c}:{},...d&&d.length>0?{geo:[...d]}:{},ownerTokenHash:f,ownerToken:u}}var At=class extends Error{};async function ss(e){let{keys:t,ndaFileName:n,api:r}=e,a=e.message?.trim()?e.message:void 0,s=await e.upload(async(p,g)=>{e.registered?.(p);let{fileKeys:S,ndaFile:_}=es(g,n),E=ae(await Ea(t.ownerTokenB64,S,t.linkKey,a,_));await Ol(r,p,t.ownerTokenB64,E),await e.ownerBlobStored?.(p)});e.uploaded?.(s);let o=s.fileResults.map(p=>{let g=s.encryptionKeys.get(p.sha256_hex);if(!g)throw new Error(`the upload returned no key for the file ${p.fileId}`);return{sha256_hex:p.sha256_hex,key:g}}),{fileKeys:i,ndaFile:c}=es(o,n),d=Mn(),f={blobB64:ae(await Sa(i,d,a,c)),linkKeyB64:ae(d)};e.minting?.(f);let{to:u}=e;if(u){let p=await rn(d,u.bundle,Gn,s.sealId),g=u.label?.slice(0,80),S=x=>r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,d,{to:u.address,fragment:p,...g?{label:g}:{},...x?{sender:x}:{}}),_=async x=>await u.sender?.(x).catch(()=>null)??null,E=x=>x instanceof te&&x.appCode==="intake.proof_required",y=await _(!1),T=await S(y).catch(async x=>{if(!y||!E(x))throw x;let M=await _(!0);return M?S(M).catch(B=>{if(E(B))return S(null);throw B}):S(null)});return{sealId:s.sealId,verification:s.verification,shareCode:T,share:f}}let h=await r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,d).catch(()=>null);return{sealId:s.sealId,verification:s.verification,shareCode:h,share:f}}async function Ol(e,t,n,r){let a=null;for(let s=0;s<2;s++)try{await e.writeOwnerBlob(t,n,r);return}catch(o){a=o}throw new At(a instanceof Error?a.message:String(a),{cause:a})}function es(e,t){let n=e[e.length-1];return{fileKeys:new Map(e.map(r=>[r.sha256_hex,ae(r.key)])),ndaFile:t&&n?{sha256_hex:n.sha256_hex,name:t}:void 0}}var os={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,MAX_GEO_COUNTRIES:50,SEAL_VISIT_SECONDS:21600,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","eu-central","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,LEASE_DEFAULT_DAYS:7,LEASE_MAX_DAYS:90,LEASE_STATUS_BATCH_MAX:500,LEASE_POLL_SECONDS:600,LEASE_KEEP_DAYS:30,APPROVE_WAIT_SECONDS:120,APPROVE_BODY_SHOWN_BYTES:2048,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 Qn=["byte","kilobyte","megabyte","gigabyte","terabyte"],Pl=["B","KB","MB","GB","TB"];function is(e,t){let r=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),Qn.length-1):0,a=parseFloat((e/Math.pow(1024,r)).toFixed(2));return a>=1024&&r<Qn.length-1&&(r+=1,a=parseFloat((e/Math.pow(1024,r)).toFixed(2))),t?new Intl.NumberFormat(t,{style:"unit",unit:Qn[r],unitDisplay:r===0?"long":"short",maximumFractionDigits:2}).format(a):`${a} ${Pl[r]}`}var Ll=1e3,Dl=60*Ll,Nl=60*Dl,ld=24*Nl;var z=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&&Ml(a),Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},Cl=["ownerToken","ownerLinkKey"];function Ml(e){let t={...e};for(let n of Cl){if(!(n in t))continue;let r=t[n];delete t[n],Object.defineProperty(t,n,{value:r,enumerable:!1,writable:!1,configurable:!1})}return t}var Bl={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 fe(e,t,n=null){if(e instanceof z)return e;if(e instanceof W){let r=e.cause instanceof te?e.cause.status:400;return new z(e.message,Bl[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof te){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 z(e.detail??t,r,e.status,n,{cause:e})}return new z(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}function on(e){return e.split("/").filter(t=>t!==""&&t!=="."&&t!=="..")}var He=os.limits,Ad=He.ttl_options,Ul="Secret",Fl="Confidentiality Agreement",ln=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 St({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){t.nda&&!t.ownerEmail&&pe("ownerEmail is required when nda=true"),t.tier&&!t.onPaymentRequired&&pe("onPaymentRequired is required with tier");let{files:n,relativePaths:r,ndaDocument:a,secretAlone:s}=Wl(t),o=t.message?.trim()?t.message:void 0;o&&o.length>He.MAX_MESSAGE_LENGTH&&pe(`message: ${o.length} characters, at most ${He.MAX_MESSAGE_LENGTH}`),o&&a&&pe("message and ndaFile: the NDA is its text or its document, give one of them");let i=o??(a?`NDA document attached: ${a.name} (${is(a.size)})`:t.nda?Fl:void 0),c=$l(t,s);"to"in t&&!t.to&&pe("to: empty: an address holds a value");let d=(O,F)=>{if(F!==void 0)try{return za(F)}catch(v){throw new z(`${O}: ${v instanceof Error?v.message:String(v)}`,"VALIDATION_ERROR",400)}},f=d("to",t.to),u=d("owner",t.owner),h=t.signal?{signal:t.signal}:{},p=async O=>{let F=await this.api.getBundle(O,h);return F&&await Ga(F,O)?F:null},g=null;if(f){try{g=await p(f)}catch(O){throw fe(O,"Failed to read the recipient key")}if(!g)throw new z(`to: ${f} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let S=u?await p(u).catch(()=>null):null,_=t.keyPair?ue(t.keyPair.secretKey):null,E=O=>_?sn(this.api,_,t.signal,O):O(),y=await ts(),T={...as(this.baseUrl,rs(c,y,t.tier)),...this.credentials!==void 0?{credentials:this.credentials}:{}},x=null,M=O=>({sealId:O,ownerToken:y.ownerTokenB64,ownerLinkKey:y.linkKeyB64}),B=!1,R=!1,Z=null,ge=t.onProgress;try{let O=await ss({keys:y,ndaFileName:a?.name??null,message:i,api:{writeOwnerBlob:async(Q,ve,ce)=>{if(u&&S&&!R){let be=await rn(y.linkKey,S,Wa,Q),oe=await E(J=>this.api.writeOwnerBlob(Q,ve,ce,{...h,to:u,fragment:be,label:"sealnet",...J?{sender:J}:{}})).catch(()=>null);if(oe)return B=!0,oe;R=!0}return this.api.writeOwnerBlob(Q,ve,ce,h)},createShareLink:(Q,ve,ce,be,oe={})=>this.api.createShareLink(Q,ve,ce,be,{...oe,...h})},registered:Q=>{x=Q},upload:async Q=>{let ve={onRegistered:Q,...ge?{onProgress:oe=>ge({phase:oe.fileProgress.phase,percent:oe.overallPercent,fileIndex:oe.fileIndex,totalFiles:oe.totalFiles,fileName:oe.fileName})}:{},...h},ce,be;try{ce=r?await Da(T,n,"",We,ve,r):await La(T,n,We,ve),be=ce.expiresAt}catch(oe){let J=Na(oe);if(!J||!t.tier||!t.onPaymentRequired)throw oe;await t.onPaymentRequired(await this.api.createCheckout(J.sealId,y.ownerTokenB64,t.tier,h));let Ke=Ca(J instanceof $n?J.expiresAt:void 0),ke=await Ma(this.api,J.sealId,y.ownerTokenB64,{deadline:Ke,...h});if(!ke)throw await this.api.revoke(J.sealId,y.ownerTokenB64).catch(()=>{}),new z("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,M(J.sealId));ce=await J.resume(ve),be=ke.expires_at}if(!be)throw new z(`Seal ${ce.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,M(ce.sealId));return Z={result:ce,expiresAt:be},{sealId:ce.sealId,encryptionKeys:ce.encryptionKeys,fileResults:ce.files,verification:ce.verification}},...f&&g?{to:{address:f,bundle:g,label:"sealnet",..._?{sender:Q=>Qt(this.api,_,{...h,fresh:Q})}:{}}}:{}}),{result:F,expiresAt:v}=Z,D=O.shareCode;if(D===null)try{D=await this.api.createShareLink(O.sealId,y.ownerTokenB64,O.share.blobB64,ue(O.share.linkKeyB64),h)}catch(Q){throw fe(Q,"Seal created but share link mint failed",M(O.sealId))}let se=$a(O.sealId,D,O.share.linkKeyB64),G=`${this.shareUrlBase}${f?se.split("#")[0]:se}`,j=`${this.shareUrlBase}${Fa(O.sealId,y.linkKeyB64)}`,[we]=F.files,Y=we&&F.encryptionKeys.get(we.sha256_hex);if(!we||!Y)throw new z(`Seal ${O.sealId}: the upload returned no key for its first file`,"INTERNAL_ERROR",500,M(O.sealId));let nt=r??n.map(Q=>Q.name);return{sealId:O.sealId,shareUrl:G,ownerUrl:j,ownerToken:y.ownerTokenB64,expiresAt:v,encryptionKey:Ne(Y),fileId:we.fileId,files:F.files.map((Q,ve)=>({fileId:Q.fileId,name:nt[ve]})),delivered:f!==void 0,ownerCopy:B}}catch(O){if(O instanceof z||!x)throw O;let F=O instanceof At?O.cause:O;if(F instanceof te)throw fe(F,`Seal ${x} was created but its send did not finish`,M(x));let v=F instanceof Error?F.message:String(F);throw new z(`Seal ${x} was created but the create flow was interrupted: ${v}`,"INTERNAL_ERROR",500,M(x),{cause:O})}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw fe(a,"Failed to revoke seal")}}};function $l(e,t){"otp"in e&&!e.otp&&pe("otp: empty: a password holds a value");let n=e.maxOpens===void 0?void 0:Ba(String(e.maxOpens));n===null&&pe(`maxOpens: ${e.maxOpens}: a whole number from 1 to ${He.MAX_OPENS_PER_SEAL_FREE}`);let r=Ua((e.geoAllowlist??[]).join(" "));return r.bad.length>0&&pe(`geoAllowlist: ${r.bad.join(", ")}: two-letter country codes such as DE, CH, US`),r.codes.length>He.MAX_GEO_COUNTRIES&&pe(`geoAllowlist: ${r.codes.length} countries, at most ${He.MAX_GEO_COUNTRIES}`),{ttl:e.ttl??(t?Jn.ttl:ns),otp:e.otp,nda:e.nda,ownerEmail:e.ownerEmail,singleUse:e.singleUse??(t&&n===void 0?Jn.singleUse:void 0),maxOpens:n,geo:r.codes}}function Wl(e){let t=(a,s,o)=>o||(s instanceof File?s.name:"")||pe(`${a}: bytes need a filename`),n=[];if("secret"in e){(e.secret===void 0||e.secret.length===0)&&pe("secret: empty: a secret holds a value");let a=typeof e.secret=="string"?new Blob([e.secret]):e.secret;n.push({file:vt(a,Ul,an),secret:!0})}e.file!==void 0&&n.push({file:vt(e.file,t("file",e.file,e.filename),e.mimeType),secret:!1});for(let[a,s]of(e.files??[]).entries()){let o=vt(s.file,t(`files[${a}]`,s.file,s.filename),s.secret?an:s.mimeType);s.secret&&o.size===0&&pe(`files[${a}]: an empty secret`),n.push({file:o,secret:s.secret===!0})}for(let[a,s]of(e.folder??[]).entries()){let o=on(s instanceof File?ka(s)??s.name:s.path),i=o.at(-1);i||pe(`folder[${a}]: a file with no path`);let c=o.join("/");n.push(s instanceof File?{file:s,path:c,secret:!1}:{file:vt(s.file,i,s.mimeType),path:c,secret:!1})}let r=null;if(e.ndaFile!==void 0){e.nda||pe("ndaFile goes with nda: true");let{file:a,filename:s,mimeType:o}=e.ndaFile;r=vt(a,t("ndaFile",a,s),o),n.push({file:r,secret:!1})}return n.length===0&&pe("Nothing to seal: give file, files, folder or secret"),n.length>He.MAX_FILES_PER_SEAL&&pe(`A seal holds at most ${He.MAX_FILES_PER_SEAL} files: ${n.length} given`),{files:n.map(a=>a.file),relativePaths:n.some(a=>a.path!==void 0)?n.map(a=>a.path??a.file.name):void 0,ndaDocument:r,secretAlone:n.length===1&&n[0].secret}}function pe(e){throw new z(e,"VALIDATION_ERROR",400)}function vt(e,t,n){let r=n||e instanceof File&&e.type||"application/octet-stream";if(e instanceof File&&e.name===t&&e.type===r)return e;if(e instanceof Blob)return new File([e],t,{type:r});let a=e instanceof Uint8Array?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e;return new File([a],t,{type:r})}async function ls(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),c=!1;try{await e.stream.pipeTo(new WritableStream({async write(p){await i.write(p)}}));let{sizeBytes:d,sha256:f}=await e.done;await i.sync(),await i.close();let u=a.extname(n),h=n.slice(0,n.length-u.length);for(let p=0;p<1e3;p++){let g=a.join(t,p===0?n:`${h} (${p})${u}`);try{await r.link(o,g)}catch(S){let _=S.code;if(_==="EEXIST")continue;if(_!=="EPERM"&&_!=="ENOTSUP"&&_!=="EOPNOTSUPP"&&_!=="ENOSYS")throw S;if(await r.access(g).then(()=>!0,()=>!1))continue;return await r.rename(o,g),c=!0,{path:g,sizeBytes:d,sha256:f}}return c=!0,await r.unlink(o).catch(()=>{}),{path:g,sizeBytes:d,sha256:f}}throw new Error(`no free name for ${n} in ${t}`)}finally{c||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}var Hl=/^[A-Za-z0-9_-]{86}$/;function xt(e){if(Hl.test(e.secretKey))return ue(e.secretKey);let t=e.secretKey.length===43?"This key is of the kind before: make a new one with keygen() and give its address to whoever sends to you. What was sent to the old address does not open.":"secretKey is not a SEAL key: expected the 86 base64url characters keygen() gives";throw new z(t,"INVALID_KEY",400)}async function cs(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await Xn(e,t,{...n.keyPair?{seed:xt(n.keyPair)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new z("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 z("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(_=>_.key!==null&&_.sha256Hex!==null),c=i.reduce((_,E)=>_+E.size,0),d=0,f=_a(),u=!1,h=Promise.resolve(),p=_=>e.downloadCiphertext(s.sealId,{fileId:_.id,visit:f,...o?{sessionCookie:o}:{}},a),g=_=>{if(u)return p(_);let E=h.then(async()=>{let y=await p(_);return u=!0,y});return h=E.catch(()=>{}),E};return{seal:s,covered:i,read:async _=>{let E=await g(_);if(!E.body)throw new z(`Download of ${_.name} returned no body`,"INTERNAL_ERROR",E.status);return Zn(E.body,_.key,_.sha256Hex,y=>{d+=y,n.onProgress?.(d,c)})}}}async function er(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await cs(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(c=>Promise.reject(fe(c,"Download failed")))}))}}catch(a){throw fe(a,"Failed to open the link")}}async function tr(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i}=await cs(e,t,r,a),c=[];for(let d of o){let f=on(d.name).map(g=>Un(g)),u=f.pop()??Un(d.name),h=f.length>0?[n||".",...f].join("/"):n,p=await ls(await i(d),h,u);c.push({name:d.name,mime:d.mime,secret:d.secret,...p})}return{sealId:s.sealId,expiresAt:s.expiresAt,files:c}}catch(s){throw fe(s,"Failed to open the link")}}async function ds(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 Vn(ue(n.recipientBundle))).words,expiresAt:r.expires_at}}catch(r){throw fe(r,"Failed to create the request")}}async function nr(e,t,n){try{return await qa(e,t,n?{signal:n}:{})}catch(r){throw fe(r,"Failed to wait for the request")}}async function us(e,t,n){let r;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:Va,kind:"pair"},n.signal?{signal:n.signal}:{})}catch(s){throw fe(s,"Failed to create the pairing request")}let a=async()=>{let{sharePath:s,wrap:o}=await nr(e,r.id,n.signal);try{let i=await Za(e,`${t}${s}`,Ya,{seed:xt(n.keyPair),wrap:o,...n.signal?{signal:n.signal}:{}}),{bundle:c,name:d}=Xa(i);return{address:(await Vn(c)).address,name:d}}catch(i){throw fe(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 hs(){let e=Ka(),{address:t,bundle:n,words:r}=await Yn(e);return{secretKey:ae(e),address:t,bundle:ae(n),words:r}}async function fs(e,t){let n=xt(t.keyPair),r=Date.now()+(t.wait??0)*1e3;try{for(;;){let a=Math.ceil((r-Date.now())/1e3),s=await qn(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:ja(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw fe(a,"Failed to read the inbox")}}async function ps(e,t,n,r){let a;try{a=(await qn(e,xt(r.keyPair),r.signal?{signal:r.signal}:{})).items}catch(o){throw fe(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new z(`${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 _s(e,t,n){try{await Ja(e,xt(n.keyPair),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw fe(r,"Failed to remove the item")}}var[Kl="",ys=""]="sdk-web/3.1.1".split("/");typeof globalThis.process?.versions?.node!="string"&&mr(me);var rr=class{seals;api;site;constructor(t={}){pa(Kl,ys);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new ln({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new St({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 ps(this.api,this.site,t,{keyPair:a.keyPair,...a.signal?{signal:a.signal}:{}});else throw new z("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?tr(this.api,s.url,r,a,s.wrap):er(this.api,s.url,a,s.wrap)}async inbox(t){return fs(this.api,t)}async dismiss(t,n){return _s(this.api,t,n)}async request(t){return ds(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await nr(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?tr(this.api,i,s,o,a):er(this.api,i,o,a)}async pair(t){return us(this.api,this.site,t)}async keygen(){return hs()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},zl=ys;return Ds(Gl);})();
4
4
  /*! Bundled license information:
5
5
 
6
6
  @noble/hashes/esm/utils.js:
@@ -1 +1 @@
1
- sha384-cwrpNTtrwmKvOqEIX3B0BacbxDFEx2X6MfoDvNFtjLemefebcp8HZ/YyIHAw5/9h
1
+ sha384-4pS2jav0xvLH34aYt9AP/qDFunAYLF/U3j/CxEAn1L0LBBq3rPDaFRFcPxfaFYz3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sealnet",
3
- "version": "3.1.0",
3
+ "version": "3.1.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",