sealnet 3.2.1 → 3.2.4
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 +2 -2
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/index.cjs +100 -30
- package/dist/index.js +100 -30
- package/dist/seal.global.js +3 -3
- package/dist/seal.global.js.sha384 +1 -1
- package/dist/seal_crypto.wasm +0 -0
- package/dist/seal_crypto.wasm.sha384 +1 -1
- package/package.json +1 -1
package/dist/seal.global.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/*! sealnet v3.2.
|
|
2
|
-
"use strict";var Seal=(()=>{var $s=Object.create;var Lt=Object.defineProperty;var Ks=Object.getOwnPropertyDescriptor;var Hs=Object.getOwnPropertyNames;var zs=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var _r=(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 js=(e,t)=>{for(var n in t)Lt(e,n,{get:t[n],enumerable:!0})},wr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Hs(t))!Gs.call(e,a)&&a!==n&&Lt(e,a,{get:()=>t[a],enumerable:!(r=Ks(t,a))||r.enumerable});return e};var yr=(e,t,n)=>(n=e!=null?$s(zs(e)):{},wr(t||!e||!e.__esModule?Lt(n,"default",{value:e,enumerable:!0}):n,e)),Ys=e=>wr(Lt({},"__esModule",{value:!0}),e);var gc={};js(gc,{SealClient:()=>cr,SealError:()=>$,VERSION:()=>yc,configureWasm:()=>bn});var Se={url:"https://seal.net/sdk/v3.2.1/seal_crypto.wasm",integrity:"sha384-shTJxj/f3gaTmjkHcR/wAxbvWNYCj4V/CY2RYpaWzTc02d58QB2ii6Lm1UMdh0T7"};var ko={},Xs=Object.defineProperty,qs=(e,t)=>{for(var n in t)Xs(e,n,{get:t[n],enumerable:!0})},Ar={};qs(Ar,{ContractTermsBuilder:()=>yn,WasmIdentity:()=>gn,default:()=>wo,init:()=>Zs,initSync:()=>_o,wasm_approval_message:()=>Js,wasm_bundle_address:()=>Qs,wasm_bundle_verify_for_address:()=>eo,wasm_contract_message:()=>to,wasm_contract_message_v2:()=>no,wasm_ed25519_verify:()=>ro,wasm_sealbox_wrap_to:()=>ao,wasm_summary_message:()=>so,wasm_unwrap_file_key:()=>oo,wasm_wrap_file_key:()=>io});var yn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,gr.unregister(this),e}free(){let e=this.__destroy_into_raw();c.__wbg_contracttermsbuilder_free(e,0)}digest(){let e,t;try{let a=this.__destroy_into_raw(),s=c.__wbindgen_add_to_stack_pointer(-16);c.contracttermsbuilder_digest(s,a);var n=S().getInt32(s+0,!0),r=S().getInt32(s+4,!0);return e=n,t=r,Pe(n,r)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(e,t,1)}}field(e,t,n,r,a,s,o,i,l,u){try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=P(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=P(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=P(i,c.__wbindgen_export3,c.__wbindgen_export4),T=A,k=P(l,c.__wbindgen_export3,c.__wbindgen_export4),y=A;c.contracttermsbuilder_field(h,this.__wbg_ptr,p,_,g,w,n,r,a,s,o,m,T,k,y,u);var f=S().getInt32(h+0,!0),d=S().getInt32(h+4,!0);if(d)throw B(f)}finally{c.__wbindgen_add_to_stack_pointer(16)}}filled(e,t){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=P(e,c.__wbindgen_export3,c.__wbindgen_export4),o=A,i=P(t,c.__wbindgen_export3,c.__wbindgen_export4),l=A;c.contracttermsbuilder_filled(a,this.__wbg_ptr,s,o,i,l);var n=S().getInt32(a+0,!0),r=S().getInt32(a+4,!0);if(r)throw B(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}constructor(e){var t=ut(e)?0:P(e,c.__wbindgen_export3,c.__wbindgen_export4),n=A;let r=c.contracttermsbuilder_new(t,n);return this.__wbg_ptr=r,gr.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(yn.prototype[Symbol.dispose]=yn.prototype.free);var gn=class Ct{static __wrap(t){let n=Object.create(Ct.prototype);return n.__wbg_ptr=t,br.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,br.unregister(this),t}free(){let t=this.__destroy_into_raw();c.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_address(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Pe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}bundle(){let t=c.wasmidentity_bundle(this.__wbg_ptr);return B(t)}static fromSeed32(t){try{let s=c.__wbindgen_add_to_stack_pointer(-16),o=ce(t,c.__wbindgen_export3),i=A;c.wasmidentity_fromSeed32(s,o,i);var n=S().getInt32(s+0,!0),r=S().getInt32(s+4,!0),a=S().getInt32(s+8,!0);if(a)throw B(r);return Ct.__wrap(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A;c.wasmidentity_fromSeed64(o,i,l,n);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw B(a);return Ct.__wrap(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(n,c.__wbindgen_export3),l=A;c.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,l);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw B(a);return B(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}open(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(t,c.__wbindgen_export3),u=A,f=P(n,c.__wbindgen_export3,c.__wbindgen_export4),d=A,h=P(r,c.__wbindgen_export3,c.__wbindgen_export4),p=A;c.wasmidentity_open(i,this.__wbg_ptr,l,u,f,d,h,p);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw B(s);return B(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signApproval(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=P(t,c.__wbindgen_export3,c.__wbindgen_export4),u=A,f=P(n,c.__wbindgen_export3,c.__wbindgen_export4),d=A,h=P(r,c.__wbindgen_export3,c.__wbindgen_export4),p=A;c.wasmidentity_signApproval(i,this.__wbg_ptr,l,u,f,d,h,p);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw B(s);return B(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signContractV2(t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=P(t,c.__wbindgen_export3,c.__wbindgen_export4),f=A,d=P(n,c.__wbindgen_export3,c.__wbindgen_export4),h=A,p=P(r,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=P(a,c.__wbindgen_export3,c.__wbindgen_export4),w=A;c.wasmidentity_signContractV2(l,this.__wbg_ptr,u,f,d,h,p,_,g,w);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw B(o);return B(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signSummary(t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=P(t,c.__wbindgen_export3,c.__wbindgen_export4),f=A,d=P(n,c.__wbindgen_export3,c.__wbindgen_export4),h=A,p=P(r,c.__wbindgen_export3,c.__wbindgen_export4),_=A;c.wasmidentity_signSummary(l,this.__wbg_ptr,u,f,d,h,p,_,a);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw B(o);return B(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}userProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A,u=ce(n,c.__wbindgen_export3),f=A;c.wasmidentity_userProof(o,this.__wbg_ptr,i,l,u,f);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw B(a);return B(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_words(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Pe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A,u=ce(n,c.__wbindgen_export3),f=A;c.wasmidentity_workloadProof(o,this.__wbg_ptr,i,l,u,f);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw B(a);return B(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(gn.prototype[Symbol.dispose]=gn.prototype.free);function Zs(){c.init()}function Js(e,t,n){let r,a;try{let d=c.__wbindgen_add_to_stack_pointer(-16),h=P(e,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=P(t,c.__wbindgen_export3,c.__wbindgen_export4),g=A,w=P(n,c.__wbindgen_export3,c.__wbindgen_export4),m=A;c.wasm_approval_message(d,h,p,_,g,w,m);var s=S().getInt32(d+0,!0),o=S().getInt32(d+4,!0),i=S().getInt32(d+8,!0),l=S().getInt32(d+12,!0),u=s,f=o;if(l)throw u=0,f=0,B(i);return r=u,a=f,Pe(u,f)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function Qs(e){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=ce(e,c.__wbindgen_export3),o=A;c.wasm_bundle_address(a,s,o);var t=S().getInt32(a+0,!0),n=S().getInt32(a+4,!0),r=S().getInt32(a+8,!0);if(r)throw B(n);return B(t)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function eo(e,t){let n=ce(e,c.__wbindgen_export3),r=A,a=P(t,c.__wbindgen_export3,c.__wbindgen_export4),s=A;return c.wasm_bundle_verify_for_address(n,r,a,s)!==0}function to(e,t,n){let r,a;try{let d=c.__wbindgen_add_to_stack_pointer(-16),h=P(e,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=P(t,c.__wbindgen_export3,c.__wbindgen_export4),g=A,w=P(n,c.__wbindgen_export3,c.__wbindgen_export4),m=A;c.wasm_contract_message(d,h,p,_,g,w,m);var s=S().getInt32(d+0,!0),o=S().getInt32(d+4,!0),i=S().getInt32(d+8,!0),l=S().getInt32(d+12,!0),u=s,f=o;if(l)throw u=0,f=0,B(i);return r=u,a=f,Pe(u,f)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function no(e,t,n,r){let a,s;try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=P(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=P(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=P(n,c.__wbindgen_export3,c.__wbindgen_export4),T=A,k=P(r,c.__wbindgen_export3,c.__wbindgen_export4),y=A;c.wasm_contract_message_v2(h,p,_,g,w,m,T,k,y);var o=S().getInt32(h+0,!0),i=S().getInt32(h+4,!0),l=S().getInt32(h+8,!0),u=S().getInt32(h+12,!0),f=o,d=i;if(u)throw f=0,d=0,B(l);return a=f,s=d,Pe(f,d)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(a,s,1)}}function ro(e,t,n){let r=ce(e,c.__wbindgen_export3),a=A,s=ce(t,c.__wbindgen_export3),o=A,i=ce(n,c.__wbindgen_export3),l=A;return c.wasm_ed25519_verify(r,a,s,o,i,l)!==0}function ao(e,t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=ce(e,c.__wbindgen_export3),f=A,d=ce(t,c.__wbindgen_export3),h=A,p=P(n,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=P(r,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=P(a,c.__wbindgen_export3,c.__wbindgen_export4),T=A;c.wasm_sealbox_wrap_to(l,u,f,d,h,p,_,g,w,m,T);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw B(o);return B(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function so(e,t,n,r){let a,s;try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=P(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=P(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=P(n,c.__wbindgen_export3,c.__wbindgen_export4),T=A;c.wasm_summary_message(h,p,_,g,w,m,T,r);var o=S().getInt32(h+0,!0),i=S().getInt32(h+4,!0),l=S().getInt32(h+8,!0),u=S().getInt32(h+12,!0),f=o,d=i;if(u)throw f=0,d=0,B(l);return a=f,s=d,Pe(f,d)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(a,s,1)}}function oo(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(e,c.__wbindgen_export3),u=A,f=ce(t,c.__wbindgen_export3),d=A,h=P(n,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=P(r,c.__wbindgen_export3,c.__wbindgen_export4),g=A;c.wasm_unwrap_file_key(i,l,u,f,d,h,p,_,g);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw B(s);return B(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function io(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(e,c.__wbindgen_export3),u=A,f=ce(t,c.__wbindgen_export3),d=A,h=P(n,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=P(r,c.__wbindgen_export3,c.__wbindgen_export4),g=A;c.wasm_wrap_file_key(i,l,u,f,d,h,p,_,g);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw B(s);return B(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function vr(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof j(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=j(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof j(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return j(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Pe(t,n))},__wbg_call_a41d6421b30a32c5:function(){return ct(function(t,n,r){let a=j(t).call(j(n),j(r));return re(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=j(t).crypto;return re(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Pe(t,n))}finally{c.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return ct(function(t,n){j(t).getRandomValues(j(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return j(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=j(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(_n(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=j(t).node;return re(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=j(t).process;return re(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(_n(t,n),j(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return ct(function(t,n){j(t).randomFillSync(B(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return ct(function(){let t=module.require;return re(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return ct(function(t,n,r){return Reflect.set(j(t),j(n),j(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=j(n).stack,a=P(r,c.__wbindgen_export3,c.__wbindgen_export4),s=A;S().setInt32(t+4,s,!0),S().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return ut(t)?0:re(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return ut(t)?0:re(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return ut(t)?0:re(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return ut(t)?0:re(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=j(t).subarray(n>>>0,r>>>0);return re(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=j(t).versions;return re(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=_n(t,n);return re(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Pe(t,n);return re(r)},__wbindgen_object_clone_ref:function(t){let n=j(t);return re(n)},__wbindgen_object_drop_ref:function(t){B(t)}}}}var gr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_contracttermsbuilder_free(e,1)),br=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_wasmidentity_free(e,1));function re(e){ht===Ne.length&&Ne.push(Ne.length+1);let t=ht;return ht=Ne[t],Ne[t]=e,t}function lo(e){e<1028||(Ne[e]=ht,ht=e)}function _n(e,t){return e=e>>>0,qe().subarray(e/1,e/1+t)}var Ge=null;function S(){return(Ge===null||Ge.buffer.detached===!0||Ge.buffer.detached===void 0&&Ge.buffer!==c.memory.buffer)&&(Ge=new DataView(c.memory.buffer)),Ge}function Pe(e,t){return uo(e>>>0,t)}var dt=null;function qe(){return(dt===null||dt.byteLength===0)&&(dt=new Uint8Array(c.memory.buffer)),dt}function j(e){return Ne[e]}function ct(e,t){try{return e.apply(this,t)}catch(n){c.__wbindgen_export(re(n))}}var Ne=new Array(1024).fill(void 0);Ne.push(void 0,null,!0,!1);var ht=Ne.length;function ut(e){return e==null}function ce(e,t){let n=t(e.length*1,1)>>>0;return qe().set(e,n/1),A=e.length,n}function P(e,t,n){if(n===void 0){let i=ft.encode(e),l=t(i.length,1)>>>0;return qe().subarray(l,l+i.length).set(i),A=i.length,l}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),l=ft.encodeInto(e,i);o+=l.written,a=n(a,r,o,1)>>>0}return A=o,a}function B(e){let t=j(e);return lo(e),t}var Nt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Nt.decode();var co=2146435072,wn=0;function uo(e,t){return wn+=t,wn>=co&&(Nt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Nt.decode(),wn=t),Nt.decode(qe().subarray(e,e+t))}var ft=new TextEncoder;"encodeInto"in ft||(ft.encodeInto=function(e,t){let n=ft.encode(e);return t.set(n),{read:e.length,written:n.length}});var A=0,ho,fo,c;function Tr(e,t){return fo=e,c=e.exports,ho=t,Ge=null,dt=null,c}async function po(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 _o(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=vr();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Tr(n,e)}async function wo(e){if(c!==void 0)return c;if(e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0)throw new Error("SEAL crypto: the WASM source must be passed to the loader");let t=vr();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await po(await e,t);return Tr(n,r)}var yo="seal_crypto.wasm",Ie=null,Dt=null,Xe=null;function bn(e){if(Dt||Xe)throw new Error("configureWasm: the WASM is already loaded or loading");Ie=e}function xr(){return globalThis.navigator?.userAgent==="Cloudflare-Workers"}function go(){return typeof globalThis.process?.versions?.node=="string"&&!xr()}async function mr(e){{let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}throw new Error("seal crypto core: this build reads no files (it is not for Node)")}async function bo(){if(Ie&&"module"in Ie)return Ie.module;if(Ie&&"url"in Ie)return fetch(Ie.url,Ie.integrity?{integrity:Ie.integrity}:{});if(Ie&&"path"in Ie)return mr(Ie.path);if(go())return mr(new URL(yo,ko.url));throw new Error(xr()?"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 pt(){if(Dt)return Dt;if(Xe)return Xe;Xe=(async()=>{let e=Ar;return await e.default({module_or_path:await bo()}),typeof e.init=="function"&&e.init(),Dt=e,e})();try{return await Xe}catch(e){throw Xe=null,e}}var Er=32768,Sr=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function mo(e){let t="";for(let n=0;n<e.length;n+=Er){let r=e.subarray(n,Math.min(n+Er,e.length));t+=String.fromCharCode.apply(null,r)}return t}function Eo(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function So(e){let t=`${e.length} characters`;if(typeof atob<"u")try{return atob(e)}catch(n){throw new Sr(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new Sr(`Invalid base64 encoding: ${n.message}`,t)}}function Ao(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function vo(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function To(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function De(e){return Ao(mo(e))}function ae(e){return To(De(e))}function Mt(e){return Eo(So(e))}function ue(e){return Mt(vo(e))}async function xo(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 xo(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function Io(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ut(e,...t){if(!Io(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 mn(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 kr(e,t){Ut(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function _t(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ft(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Oe(e,t){return e<<32-t|e>>>t}function Oo(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function En(e){return typeof e=="string"&&(e=Oo(e)),Ut(e),e}var Bt=class{};function Ir(e){let t=r=>e().update(En(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ro(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let a=BigInt(32),s=BigInt(4294967295),o=Number(n>>a&s),i=Number(n&s),l=r?4:0,u=r?0:4;e.setUint32(t+l,o,r),e.setUint32(t+u,i,r)}function Or(e,t,n){return e&t^~e&n}function Rr(e,t,n){return e&t^e&n^t&n}var Wt=class extends Bt{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=Ft(this.buffer)}update(t){mn(this),t=En(t),Ut(t);let{view:n,buffer:r,blockLen:a}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(a-this.pos,s-o);if(i===a){let l=Ft(t);for(;a<=s-o;o+=a)this.process(l,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===a&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){mn(this),kr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,_t(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let d=o;d<a;d++)n[d]=0;Ro(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Ft(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)i.setUint32(4*d,f[d],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()}},Me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Po=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]),We=new Uint32Array(64),Sn=class extends Wt{constructor(t=32){super(64,t,8,!1),this.A=Me[0]|0,this.B=Me[1]|0,this.C=Me[2]|0,this.D=Me[3]|0,this.E=Me[4]|0,this.F=Me[5]|0,this.G=Me[6]|0,this.H=Me[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:l}=this;return[t,n,r,a,s,o,i,l]}set(t,n,r,a,s,o,i,l){this.A=t|0,this.B=n|0,this.C=r|0,this.D=a|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=l|0}process(t,n){for(let d=0;d<16;d++,n+=4)We[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){let h=We[d-15],p=We[d-2],_=Oe(h,7)^Oe(h,18)^h>>>3,g=Oe(p,17)^Oe(p,19)^p>>>10;We[d]=g+We[d-7]+_+We[d-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:l,G:u,H:f}=this;for(let d=0;d<64;d++){let h=Oe(i,6)^Oe(i,11)^Oe(i,25),p=f+h+Or(i,l,u)+Po[d]+We[d]|0,g=(Oe(r,2)^Oe(r,13)^Oe(r,22))+Rr(r,a,s)|0;f=u,u=l,l=i,i=o+p|0,o=s,s=a,a=r,r=p+g|0}r=r+this.A|0,a=a+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,l=l+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,a,s,o,i,l,u,f)}roundClean(){_t(We)}destroy(){this.set(0,0,0,0,0,0,0,0),_t(this.buffer)}};var $t=Ir(()=>new Sn);var ve={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}},Cn=new Uint8Array(ve.magic_bytes),jt=ve.magic_length,Ke=ve.header_length,Qe=ve.nonce_length,Nn=ve.tag_length,ca=ve.segment_overhead,da=ve.segment_size_bytes,Pr=ve.min_segment_size_bytes,Lr=ve.max_segment_size_bytes,yt=ve.header_layout.find(e=>e.name==="file_id"),Cr=ve.aad_layout.reduce((e,t)=>e+t.length,0),ua=new Uint8Array(ve.v3_reader.magic_bytes),ha=ve.v3_reader.header_length;function Lo(e){return Qe+e+Nn}function Dn(e){let t=Math.max(1,Math.ceil(e/da));return Ke+t*ca+e}function Co(){let e=new Uint8Array(Ke);return e.set(Cn,0),new DataView(e.buffer).setUint32(jt,da,!0),e.set(crypto.getRandomValues(new Uint8Array(yt.length)),yt.offset),e}function Yt(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function fa(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(jt,!0);if(t<Pr||t>Lr)throw new Error(`segment size ${t} is outside ${Pr}\u2026${Lr}`);return t}function Mn(e){if(e.length<Ke)throw new Error(`an AEON v4 header is ${Ke} bytes, got ${e.length}`);if(!Yt(e,Cn))throw new Error("not an AEON v4 header");return{segmentSize:fa(e),fileId:e.slice(yt.offset,yt.offset+yt.length)}}function No(e){if(e.length<ha||!Yt(e,ua))throw new Error("not an AEON v3 header");return{segmentSize:fa(e)}}function Do(e){return Yt(e,Cn)?"v4":Yt(e,ua)?"v3":null}function pa(e,t,n){let r=new Uint8Array(Cr);return r.set(e.subarray(0,Ke),0),new DataView(r.buffer).setBigUint64(Ke,BigInt(t),!0),r[Cr-1]=n?1:0,r}function Mo(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function _a(e){let t=Mo(e);try{return crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{new Uint8Array(t).fill(0)}}async function Bo(e,t,n){let r=crypto.getRandomValues(new Uint8Array(Qe)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:Nn*8,additionalData:n},e,t),s=new Uint8Array(Qe+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),Qe),s}async function Uo(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,Qe),tagLength:Nn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(Qe)))}function Fo(){return $t.create()}async function gt(){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 Wo(){return crypto.getRandomValues(new Uint8Array(32))}var ge={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},OTP_DIGITS:{alphabet:"0123456789",min_length: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}},wa={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"}}]},tt={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",code_unknown:"pair.code_unknown",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"}}},Ae={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. Only this inbox answers it: POST /intake/{id}/fulfil of a card carries this address's proof (X-Seal-Address, X-Seal-Proof), made on the inbox's side alone, and is refused intake.proof_required without it; GET /intake/{id} says so with asked_of_inbox, never naming the address"},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:{link:"<site>/i/<intake_id>#<the requester's address, 43 characters>: whoever asks writes its own address into the fragment, which never reaches the server; the page that answers takes the recipient_bundle the server hands it only as a bundle of that address (bundles.accept) and refuses any other, a fragment cut short too. A link without a fragment is of a client made before it named the requester: its page shows the bundle's words for the person to compare. An inbox that opens a request of its list writes into the fragment the address whose words the row showed. A request without `to` is answered by whoever holds its link; a card (`to`) only by the inbox it was asked of, on that inbox's own page, and seal.net sends a card's link there.",recipient_bundle:"POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it (against the address of its link, request.link) 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":"<the guard's address, 43>","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"}]},$o="X-Seal-Client",D={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,REFUSAL_WAIT_DEFAULT_MS:2e3,REFUSAL_WAIT_MAX_MS:1e4,VISIT_HEADER:"X-Seal-Visit",PROGRESS_SPEED_WINDOW_MS:2e4}},ya;function nt(e,t){return(ya??globalThis.fetch).call(globalThis,e,t)}function Ko(){return ya!==void 0}var $c=2*1024*1024,Ho=(ge.limits.INTAKE_WAIT_MAX_SECONDS+15)*1e3,Kc=Ae.proof.header_address,Hc=Ae.proof.header_proof,{RETRY_BACKOFF_MS:Nr,RETRY_JITTER_RATIO:zo,MAX_STALL_MS:Dr}=D.upload,Go=1e3,An=3e4;function ga(e){return e>=500||e===408||e===429}async function jo(e,t,n,r=fetch){let a={signal:n};t>0&&(a.headers={Range:`bytes=${t}-`});let s=await r(e,a);if(t>0&&s.ok&&s.status!==206){let o=new Error(`Storage ignored the resume range: ${s.status}`);throw o.terminal=!0,o}if(!s.ok){let o=new Error(`Fetch failed: ${s.status}`);o.terminal=!ga(s.status);let i=t===0?await s.json().catch(()=>{}):void 0;throw i&&typeof i=="object"&&Object.assign(o,{swCode:"API",status:s.status,body:i}),o}return s}function Yo(e,t,n,r={}){if(!e.body)throw new Error("storage answered no body");let a=e.url||t,s=parseInt(e.headers.get("Content-Length")||"0",10),o={since:null,attempt:0},i=r.fetch??fetch,l=r.ended??(()=>{}),u=e.body.getReader(),f=0;return new ReadableStream({async pull(h){try{await d(h)}catch(p){throw l(),p}},cancel(){l(),n.abort()}});async function d(h){let p=0,_=Date.now();for(;;){if(Date.now()-_>An)throw new Error(`Read timeout: stream stalled for ${An}ms`);let g;try{if(g=await Zo(u,An),g.done&&f<s)throw new Error(`storage closed the body at ${f} of ${s}`)}catch(w){if(n.signal.aborted)throw w;let m=r.waiting??(()=>{}),T=await xn(a,f,n.signal,o,w,m,i);if(!T.body)throw new Error("storage answered no body");u=T.body.getReader(),_=Date.now();continue}if(g.done){h.close(),l();return}if(g.value.length===0){if(++p>=Go)throw new Error("Too many empty reads: stream may be corrupted");continue}o.since=null,o.attempt=0,f+=g.value.length,r.onBytes?.(g.value.length),h.enqueue(g.value);return}}}async function Vo(e,t,n){let r=new AbortController,a=()=>r.abort(t?.reason),s=()=>t?.removeEventListener("abort",a);t?.aborted?a():t?.addEventListener("abort",a,{once:!0});try{let o=await Xo(e,r.signal,n);if(!o.ok)return s(),o;let i=Yo(o,e,r,{fetch:n,ended:s});return new Response(i,{status:o.status,statusText:o.statusText,headers:o.headers})}catch(o){throw s(),o}}async function Xo(e,t,n){let r={since:null,attempt:0},a;try{a=await n(e,{signal:t})}catch(s){if(t.aborted)throw s;return xn(e,0,t,r,s,()=>{},n)}return a.ok||!ga(a.status)?a:(await a.body?.cancel().catch(()=>{}),xn(e,0,t,r,new Error(`storage answered ${a.status}`),()=>{},n))}async function xn(e,t,n,r,a,s,o){let i=a;for(r.since===null&&(r.since=Date.now());;){if(n.aborted)throw i;if(Date.now()-r.since>=Dr){let f=new Error(`Download stalled for ${Dr/1e3} s: ${i.message}`);throw f.swCode="NETWORK",f}let l=Nr[Math.min(r.attempt,Nr.length-1)]??0,u=1+(Math.random()*2-1)*zo;if(s(),await qo(l*u,n),n.aborted)throw n.reason??i;r.attempt++;try{return await jo(e,t,n,o)}catch(f){let d=f;if(d.terminal)throw d.swCode="NETWORK",d;i=d}}}function qo(e,t){return new Promise(n=>{let r=()=>{clearTimeout(a),t.removeEventListener("abort",r),n()},a=setTimeout(r,e);t.addEventListener("abort",r,{once:!0})})}function Zo(e,t){return new Promise((n,r)=>{let a=setTimeout(()=>{e.cancel().catch(()=>{}),r(new Error(`storage sent nothing for ${t} ms`))},t);e.read().then(s=>{clearTimeout(a),n(s)},s=>{clearTimeout(a),r(s)})})}function Jo(){try{return typeof process<"u"&&!0}catch{return!1}}var Qo=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":Jo()||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}},Kt=Qo;function St(e){return{debug:(t,...n)=>Kt("debug",e,t,...n),info:(t,...n)=>Kt("info",e,t,...n),warn:(t,...n)=>Kt("warn",e,t,...n),error:(t,...n)=>Kt("error",e,t,...n)}}var x=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 ei(e,t){return Object.defineProperty(e,"session",{value:t,enumerable:!1,configurable:!0,writable:!0}),e}function Ve(e,t){return e instanceof x?e:e instanceof DOMException&&e.name==="AbortError"?new x("Upload aborted","ABORTED"):new x(e instanceof Error?e.message:t,"UNKNOWN")}async function et(e,t,n,r){let a=await Ht(e,String(e.status));return new x(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var ti=St("upload"),ni={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)}},Bn={retryBackoffMs:D.upload.RETRY_BACKOFF_MS,retryJitterRatio:D.upload.RETRY_JITTER_RATIO,stallNoticeMs:D.upload.STALL_NOTICE_MS,maxStallMs:D.upload.MAX_STALL_MS,putFloorBytesPerSecond:D.upload.PUT_FLOOR_BYTES_PER_SECOND,putMinDeadlineMs:D.upload.PUT_MIN_DEADLINE_MS,controlTimeoutMs:D.upload.CONTROL_TIMEOUT_MS,completeTimeoutMs:D.upload.COMPLETE_TIMEOUT_MS,poolStart:D.upload.PART_POOL_START,poolMax:D.upload.PART_POOL_MAX,poolMin:D.upload.PART_POOL_MIN,poolGrowRatio:D.upload.PART_POOL_GROW_RATIO,poolShrinkRatio:D.upload.PART_POOL_SHRINK_RATIO,partQueueLimit:D.upload.PART_QUEUE_LIMIT,hedgeMinInflightMs:D.upload.HEDGE_MIN_INFLIGHT_MS,hedgeLagFactor:D.upload.HEDGE_LAG_FACTOR,hedgePollMs:D.upload.HEDGE_POLL_MS,livenessSilenceMs:D.upload.LIVENESS_SILENCE_MS,verifyPollBackoffMs:D.upload.VERIFY_POLL_BACKOFF_MS,verifyFallbackWaitMs:D.upload.VERIFY_FALLBACK_WAIT_MS,speedWindowMs:D.upload.PROGRESS_SPEED_WINDOW_MS,clock:ni};function Un(e){return{...Bn,...e}}function kn(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}var ba=()=>globalThis.AbortSignal;function Fn(e){let t=ba()?.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 ri(e){let t=ba()?.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 ma(e,t){let n=ri(t);return e?Fn([e,n]):n}async function bt(e,t,n,r){try{return await nt(e,{...t,signal:ma(r,n)})}catch(a){throw r?.aborted?new x("Upload aborted","ABORTED"):new x(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function Ea(e){return e===408||e===429||e>=500?"retryable":"terminal"}function Sa(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":Ea(e.httpStatus)}function Aa(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":Ea(e.httpStatus)}var Wn=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 $n(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new x("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new x("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function mt(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,l=0;for(let u=0;;u++){if(a?.aborted)throw new x("Upload aborted","ABORTED");try{return await e({attempt:u,after:i})}catch(f){let d=Ve(f,`${o} failed`);if(d.code==="ABORTED")throw d;let h=s(d);if(h==="terminal")throw d;if(n.exhausted())throw new x(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${d.message}`,d.code,d.httpStatus,d.partNumber,!1);n.failed(),l=h==="refresh_url"?l+1:0;let p=h==="refresh_url"&&l===1,_=r.retryBackoffMs[Math.min(u,r.retryBackoffMs.length-1)]??0,g=1+(Math.random()*2-1)*r.retryJitterRatio,w=p?0:Math.round(_*g);ti.debug(`retry ${o} attempt=${u+2} in ${w}ms after ${d.code}${d.httpStatus?" "+d.httpStatus:""} (${h})`),i=h,await $n(w,a)}}}var In;function va(e,t){In=`${e}/${t}`}var ai=()=>{};function On(){return{...In===void 0?{}:{[$o]:In},...ai()}}var F=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 si(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 l=JSON.parse(n);typeof l?.detail=="string"&&(r=l.detail),typeof l?.code=="string"&&(a=l.code),typeof l?.retry_after=="number"&&(s=l.retry_after),typeof l?.update=="string"&&(o=l.update),typeof l?.min_version=="string"&&(i=l.min_version)}catch{}return new F(r??t,si(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function oi(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 ii=D.upload.VISIT_HEADER;function li(){return ae(crypto.getRandomValues(new Uint8Array(16)))}var Ta=class{constructor(){this.id=li(),this.open=!1,this.queue=Promise.resolve()}ask(e){if(this.open)return e(this.id);let t=this.queue.then(async()=>{let n=await e(this.id);return this.open=!0,n});return this.queue=t.catch(()=>{}),t}};function H(e){return encodeURIComponent(e)}var ci=typeof process<"u"&&typeof process.versions?.node=="string",di=tt.share_link.proof_header;async function Mr(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(tt.hkdf.identity_key_salt),info:t.encode(tt.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("")}}var At=class ke{constructor(t){if(this.proofs=new Map,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??Ho}async holdShareProof(t,n){this.proofs.set(t,(await Mr(n)).proof)}shareProofHeader(t){let n=/^\/seal\/([^/?]+)/.exec(t)?.[1],r=n?this.proofs.get(decodeURIComponent(n)):void 0;return r?{[di]:r}:{}}fetchImpl(t,n){return this.injectedFetch?this.injectedFetch.call(globalThis,t,n):nt(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:{...On(),...this.shareProofHeader(t),...a.headers},credentials:a.credentials??this.credentials,signal:a.signal?Fn([a.signal,s.signal]):s.signal})}finally{clearTimeout(o)}if(a.redirect==="manual"&&i.status>=300&&i.status<400&&i.headers.has("location"))return i;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=${H(n.shareCode)}`:"";return await(await this.request(`/seal/${H(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/${H(t)}/share/${H(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:Fr(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/${H(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=fi(s,n.fileId?`otp_${t}_${n.fileId}`:`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/${H(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/${H(t)}/download?${Br(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?ke.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie),n.visit&&(a[ii]=n.visit);for(let s=0;;s++)try{let o=await this.request(`/seal/${H(t)}/download?${Br(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal,...ci?{redirect:"manual"}:{}}),i=o.status>=300&&o.status<400?o.headers.get("location"):null;return i===null?o:await this.stored(i,r.signal)}catch(o){if(!(o instanceof F&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<D.upload.NOT_READY_MAX_RETRIES))throw o;await hi((o.retryAfter??ui)*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 F(`GET /seal/${t}/download answered no storage URL`,"transient",502);return this.stored(s,r.signal)}async stored(t,n){let r=await Vo(t,n,(a,s)=>this.fetchImpl(a,s));if(!r.ok)throw await Ht(r,`storage download failed: ${r.status}`);return r}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${H(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:ke.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${H(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:Fr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=ke.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return Ur(a,o,s),{etag:(await this.request(`/seal/${H(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"}:ke.ownerHeaders(n,!0),i={encrypted_blob:r,proof_hash:(await Mr(a)).hash};s.fileIds&&(i.file_ids=s.fileIds),Ur(s,i,o);let l=await this.request(`/seal/${H(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal}),u=await l.json();if(typeof u.share_code!="string"||!u.share_code)throw new F(`POST /seal/${t}/share returned no share_code`,"unknown",l.status);return u.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${H(t)}/share/${H(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:ke.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${H(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:ke.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof F&&(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/${H(t)}/files/${H(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:ke.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${H(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:ke.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${H(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:ke.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${H(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:ke.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 F(`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:ke.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 F("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?Je(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/${H(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${H(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json",...this.shareProofHeader(`/seal/${H(n.sealId)}`),...r.inbox?Je(r.inbox):{}},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/${H(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return ue((await r.json()).bundle)}catch(r){if(r instanceof F&&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,ge.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:Je(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:Je(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",...Je(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/${H(t)}/revoke`,{what:`POST /lease/${t}/revoke`,method:"POST",headers:ke.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:{...On(),...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")}}},ui=3;function Je(e){return{[Ae.proof.header_address]:e.address,[Ae.proof.header_proof]:e.proof}}function Br(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function Ur(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,Je(e.sender)))}function hi(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 Fr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new F(`${t} returned an empty blob`,"unknown",n);return ue(e.encrypted_blob)}function fi(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 pi=32,_i=32,Vt=ge.limits.MAX_BLOB_SIZE,Wr=ge.limits.MAX_FILE_KEYS;function xa(e){if(e>Wr)throw new Error(`Too many file keys: ${e} exceeds maximum of ${Wr}`)}var wi=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function ka(){return crypto.getRandomValues(new Uint8Array(pi))}async function Ia(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 Kn(){return crypto.getRandomValues(new Uint8Array(_i))}var zc=wa.wildcard_public_second_level;async function Oa(e,t,n,r,a,s,o){xa(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 Pa(i,n)}async function Ra(e,t,n,r,a,s,o){xa(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 Pa(i,t)}async function Pa(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 yi(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha256_hex=="string"&&typeof t.name=="string"}function gi(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 bi(e){return typeof e.bindings!="object"||e.bindings===null?{}:Object.fromEntries(Object.entries(e.bindings).filter(([,t])=>gi(t)))}function mi(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 Ei(e,t){let n=await Si(e,t);if(!mi(n))throw new Error("Invalid share blob structure");return n}async function Si(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 wi}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}var Yc=ge.limits.MAX_FILE_KEYS;var $e=64,$r=[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],Ai=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),vi=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function Kr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let l,u;i<16?(l=a&s|~a&o,u=i):i<32?(l=o&a|~o&s,u=5*i+1&15):i<48?(l=a^s^o,u=3*i+5&15):(l=s^(a|~o),u=7*i&15);let f=r+l+Ai[i]+t[n+u]|0;r=o,o=s,s=a,a=a+(f<<$r[i]|f>>>32-$r[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 Hn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array($e),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($e-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<$e)return this;this.compressBytes(this.pending,0,$e),this.pendingLength=0}let n=e.length-(e.length-t)%$e;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?$e:2*$e);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(vi&&(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)Kr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=$e){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);Kr(this.state,this.scratch,0)}}};function Ti(e){return De(new Hn().update(e).digest())}var vn=4*1024*1024;async function xi(e){let t=new Hn;for(let n=0;n<e.length;n+=vn)t.update(e.subarray(n,Math.min(n+vn,e.length))),n+vn<e.length&&await gt();return De(t.digest())}var La=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Mn(e.header).segmentSize,this.header=e.header.subarray(0,Ke),this.key=e.key}async init(){this.cryptoKey=await _a(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 Bo(this.cryptoKey,n,pa(this.header,e,t))}};async function ki(e,t,n,r){let a=new Uint8Array(t);try{let s=new La({key:a,header:n});await s.init();let o=new Hn().update(s.header),i=[Hr(s.header)],l=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let u=0;u<l;u++){let f=Math.min((u+1)*s.segmentSize,e.size),d=new Uint8Array(await e.slice(u*s.segmentSize,f).arrayBuffer()),h=await s.encryptSegment(u,u===l-1,d);d.fill(0),o.update(h),i.push(Hr(h)),r?.(f,e.size)}return{blob:new Blob(i),md5_b64:De(o.digest())}}finally{a.fill(0)}}function Hr(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Be=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function Ii(e,t){e.chunks.push(t),e.bytes+=t.length}function zt(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=zt(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function Ri(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Be("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,l=0,u=null,f=async(h,p)=>{if(h.length<ca)throw new Be("integrity",`segment ${l} is ${h.length} bytes: the stream was cut`);try{return await Uo(a,h,o==="v4"?pa(s,l,p):null)}catch(_){throw new Be("integrity",`segment ${l} does not decrypt as the ${p?"last":"next"} segment of this file: moved, cut, extended or changed`,_)}finally{l+=1}},d=async()=>{if(r.bytes<jt)return!1;let h=Do(Oi(r,jt));if(h===null)throw new Be("outdated","the file is in a format newer than this client: update it");let p=h==="v4"?Ke:ha;if(r.bytes<p)return!1;if(h==="v3"){u=Fo();for(let w of r.chunks)u.update(w)}let _=zt(r,p),g;try{g=h==="v4"?Mn(_).segmentSize:No(_).segmentSize}catch(w){throw new Be("integrity",w instanceof Error?w.message:String(w),w)}if(h==="v4"&&await Ze(_)!==n)throw new Be("integrity","the file header is not the one registered for this file");return s=_,o=h,i=Lo(g),!0};return new TransformStream({async start(){a=await _a(e)},async transform(h,p){if(h.length!==0&&(Ii(r,h),u&&u.update(h),!(o===null&&!await d())))for(;r.bytes>i;){let _=zt(r,i),g=await f(_,!1);_.fill(0),t.onPlaintextBytes?.(g.length),p.enqueue(g)}},async flush(h){if(o===null)throw new Be("integrity",r.bytes===0?"the ciphertext stream is empty":"the ciphertext stream was cut inside its header");if(o==="v3"){if(Array.from(u.digest(),g=>g.toString(16).padStart(2,"0")).join("")!==n)throw new Be("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let p=await f(zt(r,r.bytes),!0);t.onPlaintextBytes?.(p.length),h.enqueue(p)}},{highWaterMark:1},{highWaterMark:1})}var qc=St("SwDownload");var Zc=10*6e4;var Ca={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"}},Pi="_",Li=200,Ci=new TextEncoder;function Rn(e){return Ci.encode(e).length}function zr(e,t){let n="",r=0;for(let a of e){if(r+=Rn(a),r>t)break;n+=a}return n}var Ni=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 Di(){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 Mi(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 Bi(e){let t=e.split(".")[0].toUpperCase();return Ni.has(t)}function Xt(e,t={}){let{platform:n=Di(),replacement:r=Pi,maxLength:a=Li,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(u=>Mi(u,n)?u:r).join("");let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${l}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${l})+|${l}+$`,"g"),""),(n==="windows"||n==="unknown")&&Bi(o)&&(o=`${r}${o}`),Rn(o)>a){let u=o.lastIndexOf(".");if(u>0&&u>o.length-10){let f=o.slice(u);o=zr(o.slice(0,u),a-Rn(f))+f}else o=zr(o,a)}return!o||o===r?s:o}function Na(e,t={}){let n=e.split(/[\\/]/).filter(r=>r!==""&&r!=="."&&r!=="..");return n.length===0?[Xt("",t)]:n.map(r=>Xt(r,t))}var Ui=new Map(Object.entries(Ca.extensions));function Fi(e){let t=e.lastIndexOf("."),n=t>=0&&t<e.length-1?e.slice(t+1).toLowerCase():"";return Ui.get(n)??Ca.default}var Jc=D.upload.INMEMORY_BLOB_LIMIT_BYTES;var Qc=new TextEncoder;var ed=St("FolderZip");var td=D.upload.INMEMORY_BLOB_LIMIT_BYTES,nd=4*1024*1024;var Wi=new WeakMap;function Da(e){return Wi.get(e)??(e.webkitRelativePath||void 0)}var qt="Encrypted file",Zt="application/octet-stream";function Ma(e){return new TextEncoder().encode(`field:${e}`)}async function Gr(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=Ma(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:De(new Uint8Array(o)),nonce:De(r)}}async function jr(e,t,n,r){let a=Mt(e),s=Mt(t);return(async i=>{let l={name:"AES-GCM",iv:s};i&&(l.additionalData=i);let u=await crypto.subtle.decrypt(l,n,a);return new TextDecoder().decode(u)})(r?Ma(r):void 0)}async function $i(e,t){let n=qt,r=Zt;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await jr(e.name_encrypted,e.name_nonce,t,"name")}catch{n=qt}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await jr(e.mime_encrypted,e.mime_nonce,t,"mime")}catch{r=Zt}return{name:n,mime:r}}async function Ki(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function Hi(e,t){try{let n=await Ki(t);return $i(e,n)}catch{return{name:qt,mime:Zt}}}var zi=St("upload"),wt=4*1024*1024;function Jt(){return new DOMException("Upload aborted","AbortError")}async function Gi(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:l}=e,u=new La({key:r,header:a});await u.init();let f=u.segmentSize,d=Math.max(1,Math.ceil(n/f)),h=0,p=v=>new x(`The file changed while it was being sent: ${v} ${h} of ${n} bytes`,"FILE_CHANGED"),_=!0,g=0,w=0,m=[],T=0,k=v=>{if(m.length>0&&m[0].length===v)return T-=v,m.shift();let M=new Uint8Array(v),se=0;for(;se<v;){let Y=m[0],V=v-se;Y.length<=V?(M.set(Y,se),se+=Y.length,m.shift()):(M.set(Y.subarray(0,V),se),m[0]=Y.subarray(V),se+=V)}return T-=v,M},y=[],L=0,R=async v=>{let M=new Uint8Array(v),se=0,Y=0;for(;se<v;){let V=y[0],me=i?wt-Y:Number.MAX_SAFE_INTEGER,X=Math.min(V.length,v-se,me);M.set(V.subarray(0,X),se),se+=X,Y+=X,X===V.length?y.shift():y[0]=V.subarray(X),i&&Y>=wt&&se<v&&(Y=0,await gt())}return L-=v,M},C=async v=>{if(w+=1,e.hashParts===!1)await e.onPart(w,v);else{let M=i?await xi(v):Ti(v);await e.onPart(w,v,M)}i&&await gt()},Q=async v=>{if(!i){v.fill(0);return}for(let M=0;M<v.length;M+=wt)v.fill(0,M,Math.min(M+wt,v.length)),M+wt<v.length&&await gt()},pe=async()=>{for(;L>=s;)await C(await R(s))},I=async(v,M)=>{if(o?.aborted)throw Jt();let se=g;g+=1;let Y=performance.now(),V=u.encryptSegment(se,M,v);await pe();let me=await V;await Q(v),zi.debug(`encrypt segment=${g} bytes=${v.length} time=${Math.round(performance.now()-Y)}ms`);let X;_?(X=new Uint8Array(a.length+me.length),X.set(a,0),X.set(me,a.length),_=!1):X=me,l?.(g),y.push(X),L+=X.length},K=t.getReader();try{for(;;){if(o?.aborted)throw Jt();let{done:v,value:M}=await K.read();if(v)break;if(M&&M.length>0){if(h+=M.length,h>n)throw p("it gave more than");m.push(M),T+=M.length}for(;T>=f;)await I(k(f),g===d-1)}if(h<n)throw p("it ended at");(T>0||g===0)&&await I(k(T),!0),await pe(),L>0&&await C(await R(L))}finally{K.releaseLock()}}function ji(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 Yi(e,t,n){let{file:r,key:a,header:s,partSize:o,totalBytes:i,signal:l,initialCredits:u,onSegment:f,onPart:d}=n;return new Promise((h,p)=>{let _=!1,g=!1,w=0,m=Promise.resolve(),T=R=>{_||(_=!0,p(R))},k=()=>{!g||w>0||m.then(()=>{_||(_=!0,h())})};if(l){if(l.aborted){T(Jt());return}l.addEventListener("abort",()=>T(Jt()),{once:!0})}e.onerror=t.onerror=R=>{T(new Error(`crypto worker crashed: ${String(R?.message??R)}`))},e.onmessage=R=>{let C=R.data;if(C.type==="segment"){f?.(C.segmentNumber);return}if(C.type==="part"){w+=1,t.postMessage({type:"md5",partNumber:C.partNumber,buffer:C.buffer},[C.buffer]);return}if(C.type==="done"){g=!0,k();return}C.type==="error"&&T(new Error(C.message))},t.onmessage=R=>{let C=R.data;if(C.type!=="md5")return;w-=1;let Q=new Uint8Array(C.buffer);m=m.then(async()=>{_||(await d(C.partNumber,Q,C.md5),e.postMessage({type:"credit"}))}).catch(T),k()};let y=new ArrayBuffer(a.length);new Uint8Array(y).set(a);let L=s.slice().buffer;e.postMessage({type:"start",file:r,key:y,header:L,partSize:o,totalBytes:i,credits:u},[y,L])})}var Vi=null;function Xi(){return Vi}var je=St("upload");function qi(e){return e.now-e.lastLookAt>2*e.every?!1:e.now-e.lastActivityAt>=e.silenceMs}var Yr="<Code>BadDigest</Code>",Zi=2;function nn(e){let t=On();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 Ji(e){return Qi({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 Qi(e){let{file:t,partSize:n}=e;return el({stream:ji(t,Mn(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 el(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:l,partSize:u,contentType:f="application/octet-stream",onProgress:d,signal:h,sourceFile:p,onStreamed:_,onConflict:g}=e,w=Un(e.transport),m=w.clock;if(s.length!==32)throw new x("Key must be 32 bytes","ENCRYPTION_FAILED");if(u<D.upload.S3_MIN_PART_SIZE_BYTES)throw new x(`Part size must be at least ${D.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let T=new Uint8Array(s),k=nn(l),y=Dn(n),L=Math.ceil(y/u),R=null,C=[],Q=0,pe=0,I="encrypting",K=[],v=null,M,se=b=>{let E=m.now();K.push({at:E,bytes:b});let O=Math.max(v??E,E-w.speedWindowMs);for(;K.length>0&&K[0].at<O;)K.shift();let U=E-O;U>0&&(M=Math.round(K.reduce((N,te)=>N+te.bytes,0)/U*1e3))},Y=b=>{I=b;let E=y-Q;d?.({phase:b,percent:b==="done"?100:Math.min(99,Math.floor(Q/y*100)),deliveredBytes:Q,preparedBytes:pe,totalBytes:y,speedBps:M,etaMs:M&&M>0?Math.round(E/M*1e3):void 0,state:V.state,attempt:V.retriesSinceDelivery+1})},V=new Wn(w,()=>Y(I),m.now),me=new AbortController,X=h?Fn([h,me.signal]):me.signal,rt=(b,E)=>mt(E,{clock:V,policy:w,signal:X,classify:Aa,what:b}),ee=async b=>{throw T.fill(0),new x("Upload aborted","ABORTED")},Te=b=>{if(R)try{nt(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...k},body:JSON.stringify(b?{upload_id:R,discard_file:!0}:{upload_id:R}),keepalive:!0}).catch(()=>{})}catch{}},oe=!1,Ee=new Map,ie=null,z=null,_e=[],xe=new Set,we=w.poolStart,kt=w.poolMax,It=0,ze=null,Ot=0,Rt=0,at=null,hn=[],dr=[],st=new Set,ot=m.now(),ur=!1,fn=b=>{ot=m.now();for(let E of[...st])E.reconnect(b)};function Ps(b,E){let O=b.ciphertext.length;if(O>=u&&E>0){let te=Math.min(b.flowsAtStart??1,xe.size);if(dr.push({rate:O/E,flows:te}),O/E*1e3<w.putFloorBytesPerSecond*2&&we>w.poolMin){we-=1,kt=we,at=null,It+=1,ze=m.now(),Ot=0,Rt=0;return}}if(b.round!==It||(Ot+=O,Rt+=1,Rt<we||ze===null))return;let U=m.now()-ze;if(U<=0)return;let N=Ot/U;at===null||N>at*w.poolGrowRatio?we=Math.min(kt,we+1):N<at*w.poolShrinkRatio&&(we=Math.max(Math.min(w.poolStart,kt),we-1)),at=N,It+=1,ze=m.now(),Ot=0,Rt=0}function Ls(b,E){let O=m.now()-E;if(O<w.hedgeMinInflightMs)return!1;let U=xe.size,N=dr.filter(q=>q.flows>=U).map(q=>q.rate);if(N.length===0)return!1;N.sort((q,G)=>q-G);let te=N[Math.floor(N.length/2)];return b.ciphertext.length/O*w.hedgeLagFactor<te}async function Cs(b,E,O,U,N,te){if(!Ko()&&typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((G,ye)=>{let Z=new XMLHttpRequest,de=!1;ur=!0,Z.upload.onprogress=be=>{te.onSocketActivity(be.loaded,be.lengthComputable?be.total:b.length),ne(),ne=Re()};let Re=()=>m.after(kn(b.length,w),()=>{de||te.onDeadline()}),ne=Re(),J=()=>{ne(),N.removeEventListener("abort",le)},le=()=>{de||(de=!0,Z.abort(),J(),ye(new x("Upload aborted","ABORTED",void 0,O)))};if(Z.onload=()=>{if(de)return;de=!0;let be={status:Z.status,etag:Z.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:Z.status===400&&String(Z.responseText??"").includes(Yr)};J(),G(be)},Z.onerror=()=>{de||(de=!0,J(),ye(new x(`Failed to upload part ${O}: network error`,"NETWORK",void 0,O,!0)))},Z.onabort=()=>{de||(de=!0,J(),ye(new x("Upload aborted","ABORTED",void 0,O)))},N.aborted){J(),ye(new x("Upload aborted","ABORTED",void 0,O));return}N.addEventListener("abort",le,{once:!0}),Z.open("PUT",U),Z.setRequestHeader("Content-MD5",E),Z.send(b)});let q;try{q=await nt(U,{method:"PUT",headers:{"Content-MD5":E},body:b,signal:ma(N,kn(b.length,w))})}catch(G){throw h?.aborted||N.aborted?Ve(G,"Upload aborted"):new x(`Part ${O}: transport failure (${G instanceof Error?G.message:String(G)})`,"NETWORK",void 0,O,!0)}return{status:q.status,etag:q.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:q.status===400&&(await q.text().catch(()=>"")).includes(Yr)}}function Ns(b,E){if(E.badDigest)throw new x(`Part ${b} arrived corrupted (BadDigest)`,"BAD_DIGEST",E.status,b,!0);if(E.status<200||E.status>=300)throw new x(`Failed to upload part ${b}: ${E.status}`,E.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",E.status,b,E.status!==404);if(!E.etag)throw new x(`No ETag returned for part ${b}`,"S3_ETAG_MISMATCH",void 0,b);return E.etag}async function Ds(b,E){let O=m.now(),U=()=>{},N=0,te=0,q=O,G=null,ye=()=>{},Z={reconnect:de=>ye(de,!1),hasUnsentBytes:()=>G?.unsent??!1};st.add(Z);try{let de=await new Promise((ne,J)=>{let le=!1,be=Fe=>{le||(le=!0,Fe())},pr=()=>{let Fe=new AbortController,it=()=>Fe.abort();X?.aborted?Fe.abort():X?.addEventListener("abort",it,{once:!0});let Le={ctl:Fe,unsent:!0,ended:Promise.resolve()};G=Le,q=m.now(),ot=q,Le.ended=Cs(b.ciphertext,b.contentMd5,b.partNumber,E,Fe.signal,{onSocketActivity:(Ce,lt)=>{ot=m.now(),Le.unsent=Ce<lt},onDeadline:()=>{if(++te<2)return ye("copy deadline",!1,!1);G===Le&&be(()=>J(new x(`Part ${b.partNumber}: no answer from storage after a reconnect`,"NETWORK",void 0,b.partNumber,!0)))}}).then(Ce=>{if(G===Le)try{let lt=Ns(b.partNumber,Ce);be(()=>ne(lt))}catch(lt){be(()=>J(lt))}},Ce=>{G===Le&&be(()=>J(Ve(Ce,`Failed to upload part ${b.partNumber}`)))}).finally(()=>{Le.unsent=!1,X?.removeEventListener("abort",it)})};ye=(Fe,it,Le=!0)=>{let Ce=G;le||Ce===null||h?.aborted||(G=null,N=it?N+1:Le?0:N,je.debug(`${it?"replace":"reconnect"} part=${b.partNumber} (${Fe})`),Ce.ctl.abort(),Ce.ended.then(()=>{le||(X?.aborted?be(()=>J(new x("Upload aborted","ABORTED",void 0,b.partNumber))):pr())}))},pr(),U=m.every(w.hedgePollMs,()=>{le||h?.aborted||G===null||N>=Zi||Ls(b,q)&&ye(`slower than its peers after ${Math.round(m.now()-O)}ms`,!0)})}),Re=m.now();C.push({part_number:b.partNumber,etag:de}),Q+=b.ciphertext.length,se(b.ciphertext.length),Ps(b,Re-O),V.delivered(),ot=Re,je.debug(`part=${b.partNumber}/${L} put=${Math.round(Re-O)}ms size=${b.ciphertext.length}${N>0?` replaced\xD7${N}`:""}`),Y("uploading")}finally{st.delete(Z),ye=()=>{},U(),G?.ctl.abort()}}let Pt=(b,E,O)=>bt(b,E,O,X);async function Ms(){try{let b=await Pt(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(R??"")}`,{method:"GET",headers:k},w.controlTimeoutMs);if(!b.ok)return null;let E=await b.json();return typeof E.status=="string"?E.status:null}catch{return null}}async function hr(b){let E=performance.now(),O=await rt("presign batch",async()=>{let N=await Pt(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...k},body:JSON.stringify({upload_id:R,part_numbers:b})},w.controlTimeoutMs);if(!N.ok)throw await et(N,"Failed to get presigned URLs",N.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:te}=await N.json();return te}),U=new Map;for(let[N,te]of Object.entries(O))U.set(Number(N),te);return je.debug(`batch presign ${b.length} urls in ${Math.round(performance.now()-E)}ms`),U}async function Bs(b){let E=[];for(let U=b;U<=L&&E.length<D.upload.PRESIGN_BATCH_SIZE;U++)Ee.has(U)||E.push(U);if(E.length===0)return;let O=await hr(E);for(let[U,N]of O)Ee.set(U,N)}function fr(b){ie||(ie=Bs(b).catch(()=>{}).finally(()=>{ie=null}))}async function Us(b){await gt(),ze??(ze=m.now()),v??(v=ze),b.round=It,b.flowsAtStart=xe.size;let E=Ee.get(b.partNumber);!E&&ie&&(await ie,E=Ee.get(b.partNumber)),Ee.delete(b.partNumber),fr(b.partNumber+1),await mt(async({after:O})=>{if((!E||O==="refresh_url")&&(E=(await hr([b.partNumber])).get(b.partNumber),!E))throw new x(`No presigned URL for part ${b.partNumber}`,"NETWORK",void 0,b.partNumber,!0);await Ds(b,E)},{clock:V,policy:w,signal:X,classify:Sa,what:`part ${b.partNumber}`})}function pn(){for(;!z&&!h?.aborted&&xe.size<we&&_e.length>0;){let b=_e.shift(),E=Us(b).catch(O=>{z??(z=Ve(O,"Part upload failed"))}).finally(()=>{xe.delete(E);let O=hn;hn=[];for(let U of O)U();pn()});xe.add(E)}}let Fs=()=>new Promise(b=>{hn.push(b)}),Ws=(()=>{let b=globalThis,E=globalThis.navigator?.connection,O=E?.type,U=()=>fn("network is back"),N=()=>V.connectionLost(),te=()=>{let Z=E?.type;Z!==O&&(O=Z,fn("network changed"))};b.addEventListener?.("online",U),b.addEventListener?.("offline",N),E?.addEventListener?.("change",te);let q=Math.max(10,w.livenessSilenceMs/4),G=m.now(),ye=m.every(q,()=>{let Z=m.now(),de=qi({now:Z,lastLookAt:G,every:q,lastActivityAt:ot,silenceMs:w.livenessSilenceMs});G=Z,!(!ur||st.size===0||!de)&&[...st].some(Re=>Re.hasUnsentBytes())&&(V.connectionLost(),fn("every socket silent"))});return()=>{ye(),b.removeEventListener?.("online",U),b.removeEventListener?.("offline",N),E?.removeEventListener?.("change",te)}})();try{let b=performance.now();if(je.debug(`starting multipart: totalBytes=${n} parts=${L} partSize=${u} pool=${w.poolStart}..${w.poolMax}`),h?.aborted)throw new x("Upload aborted","ABORTED");Y("encrypting"),R=await rt("multipart init",async()=>{let ne=await Pt(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...k},body:JSON.stringify({seal_id:r,content_type:f,content_length:y,part_size:u,file_id:a})},w.controlTimeoutMs);if(!ne.ok)throw await et(ne,"Failed to initialize multipart upload","NETWORK");return(await ne.json()).upload_id}),fr(1),Y("encrypting");let E=!1,O=()=>{E=!0,Y("encrypting")},U=async(ne,J,le)=>{for(E=!0,pe+=J.length,Y("encrypting"),h?.aborted&&await ee(h?.aborted===!0),_e.push({partNumber:ne,ciphertext:J,contentMd5:le}),pn();_e.length>=w.partQueueLimit;)if(await Fs(),z)throw z;if(z)throw z},N=()=>Gi({stream:t,totalBytes:n,key:T,header:o,partSize:u,signal:h,yieldToRenderer:typeof document<"u",onSegment:O,onPart:U}),te=Xi(),q=null;if(p&&te&&typeof document<"u"){let ne=null;try{ne=te(),q=[ne,te()]}catch{ne?.terminate()}}if(q){let[ne,J]=q;je.debug("crypto pipeline: worker");try{await Yi(ne,J,{file:p,key:T,header:o,partSize:u,totalBytes:n,signal:h,initialCredits:w.partQueueLimit,onSegment:O,onPart:U})}catch(le){let be=Ve(le,"Crypto worker failed");if(be.code==="ABORTED"||E)throw be;je.debug(`crypto worker failed before output \u2014 inline fallback (${be.message})`),await N()}finally{ne.terminate(),J.terminate()}}else await N();for(;pn(),!(z||(h?.aborted&&await ee(!0),xe.size===0&&_e.length===0));)await Promise.race(xe);if(z)throw z;Y("verifying"),h?.aborted&&await ee(h?.aborted===!0),oe=!0,_?.();let G=!1,ye,Z=await rt("complete",async()=>{let ne=G;G=!0;let J=await Pt(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...k},body:JSON.stringify({upload_id:R,parts:C.map(le=>({part_number:le.part_number,etag:le.etag})),...g?{on_conflict:g}:{}})},w.completeTimeoutMs);if(J.ok){let le=await J.json().catch(()=>null);return typeof le?.conflict_with=="string"&&(ye=le.conflict_with),le?.status==="verified"}if(ne&&J.status===400&&await Ms()==="completed")return!1;throw await et(J,"Failed to complete multipart upload",J.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});V.delivered(),Y("done");let de=Math.round(performance.now()-b),Re=n/(1024*1024)/(de/1e3);return je.debug(`DONE totalTime=${de}ms speed=${Re.toFixed(2)}MB/s parts=${C.length}`),T.fill(0),{verified:Z,...ye?{conflictWith:ye}:{}}}catch(b){T.fill(0);let E=Ve(b,"Unknown upload error");throw oe&&E.code!=="ABORTED"&&(E.httpStatus===void 0||E.httpStatus>=500)||Te(E.code==="ABORTED"),E}finally{Ws(),V.dispose(),me.abort()}}var He={multipartThresholdBytes:D.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:D.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:D.upload.INMEMORY_BLOB_LIMIT_BYTES};function tl(e,t=He){return e<=D.upload.FINE_PART_MAX_FILE_BYTES?D.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Ba(e,t){return e>=t.multipartThresholdBytes}function nl(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 zn(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:nl(e.auth)}function rl(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var al={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},Vr=[2,12],sl=[12,95],ol=[95,99];function Xr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=al[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=ol:r.deliveredBytes===0?s=Vr:s=sl;let o=s===Vr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,l=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,l),t({phase:r.phase,percent:n,deliveredBytes:r.deliveredBytes,preparedBytes:r.preparedBytes,totalBytes:r.totalBytes,speedBps:r.speedBps,etaMs:r.etaMs,state:r.state,attempt:r.attempt})}}var Gn=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 x("Upload session was cancelled","ABORTED");return this.running??(this.running=this.run(this,e).catch(t=>{throw ei(Ve(t,"Upload failed"),this)}).finally(()=>{this.running=null})),this.running}async cancel(){this.cancelled=!0;let e=rl(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 nt(`${this.ctx.baseUrl}${a}`,{method:"DELETE",headers:nn(zn(this.ctx)),credentials:this.ctx.credentials??"include"}).catch(()=>{})}return}let t=new At({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 il(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 ll(e){return e>=200&&e<300||e===204}async function cl(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:l,clock:u,transport:f}=e,d=` for ${i}`,h={"Content-Type":"application/json",...s},p=t.credentials??"include",_=(k,y)=>mt(y,{clock:u,policy:f,signal:l,classify:Aa,what:k}),g=()=>_(`initiate${d}`,async()=>{let k=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,l);if(k.status===409)return null;if(!k.ok)throw await et(k,`Upload initiate failed${d}`,"NETWORK");let y=await k.json();return y.already_verified?null:y}),w=await g();if(w===null)return!1;let m=!1;if(await mt(async({after:k})=>{if(k==="refresh_url"){let R=await g();if(R===null){m=!0;return}w=R}let{upload_url:y}=w,L=await bt(y,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},kn(a.blob.size,f),l);if(L.status===400&&(await L.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new x(`Upload arrived corrupted (BadDigest)${d}`,"BAD_DIGEST",400,void 0,!0);if(!ll(L.status))throw new x(`Upload PUT failed${d}: ${L.status}`,"NETWORK",L.status)},{clock:u,policy:f,signal:l,classify:Sa,what:`PUT${d}`}),m)return!1;u.delivered(),o();let T=await _(`confirm${d}`,async()=>{let k=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,l);if(k.status===409)return!1;if(!k.ok)throw await et(k,`Upload confirm failed${d}`,"NETWORK");let y=await k.json().catch(()=>null);return typeof y?.conflict_with=="string"&&e.onConflictWith(y.conflict_with),y?.status==="verified"});return u.delivered(),T}async function Ua(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"?null:{status:i.status,conflictWith:typeof i.conflict_with=="string"?i.conflict_with:null}}catch(o){if(o instanceof x&&o.code==="ABORTED")throw o;return null}}var dl=new Set(["failed","size_mismatch","verification_error"]),ul=new Set(["verified","pending_verification"]);async function hl(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i,onConflictWith:l}=e,u=s.verifyFallbackWaitMs,f=performance.now(),d=s.verifyPollBackoffMs;for(let h=0;;h++){let p=d[Math.min(h,d.length-1)]??0;if(performance.now()-f+p>u)return"pending";p>0&&await $n(p,o);let _=await Ua(t,n,r,a,s,o),g=_?.status??null;if(g==="verified")return _?.conflictWith&&l(_.conflictWith),"verified";if(g!==null&&dl.has(g))throw new x(`The server rejected ${i} after upload (${g}). It has to be sent again.`,"VERIFICATION_REJECTED");if(g===null&&h===0)return"pending"}}async function fl(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:l}=t,{onProgress:u,signal:f}=n;if(t.state!=="pending")return;if(f?.aborted)throw new x("Upload aborted","ABORTED");let d=zn(r),h=nn(d),p=Un(a.transport),_=async C=>{if(t.state=C?"verified":"uploaded",!C)try{await hl({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:h,transport:p,signal:f,label:o.name,onConflictWith:pe=>{t.conflictWith??(t.conflictWith=pe)}})==="verified"&&(t.state="verified")}catch(Q){throw Q instanceof x&&Q.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),Q}};if(Ba(o.size,a)){if(t.streamed){let v=await Ua(r,s,t.sha256_hex,h,p,f);if(v!==null&&ul.has(v.status)){v.conflictWith&&(t.conflictWith??(t.conflictWith=v.conflictWith)),await _(v.status==="verified");return}}let C=Xr("multipart",v=>u?.(v)),Q=null,pe=await Ji({file:o,sealId:s,fileId:l,key:i,header:t.header,baseUrl:r.baseUrl,auth:d,partSize:tl(o.size,a),onProgress:v=>{Q=v;let M=v.phase==="done";C({...v,phase:M?"verifying":v.phase,fraction:M?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=pe.conflictWith,await _(pe.verified);let I=t.encryptedSize;C({...Q??{phase:"done",percent:100,deliveredBytes:I,totalBytes:I,state:"running",attempt:1},phase:"done",fraction:1});return}let g=Xr("single-put",C=>u?.(C)),w=t.encryptedSize,m={phase:"encrypting",fraction:0,delivered:!1},T=null,k=(C,Q,pe=m.delivered)=>{m={phase:C,fraction:Q,delivered:pe},g({phase:C,fraction:Q,deliveredBytes:pe?w:0,totalBytes:w,state:T?.state??"running",attempt:(T?.retriesSinceDelivery??0)+1})};t.prepared||(k("encrypting",0),t.prepared=await ki(o,i,t.header,C=>k("encrypting",o.size>0?C/o.size:1)));let y=t.prepared,L=new Wn(p,()=>k(m.phase,m.fraction));T=L,k("uploading",0);let R;try{R=await cl({ctx:r,sealId:s,fileId:l,ciphertext:y,authHeaders:h,onVerifying:()=>k("verifying",0,!0),label:o.name,signal:f,clock:L,transport:p,onConflictWith:C=>{t.conflictWith=C}})}finally{L.dispose()}k("verifying",.5,!0),await _(R),t.prepared=void 0,k("done",1,!0)}async function pl(e,t={}){let{signal:n,onFileProgress:r}=t,a=h=>Ba(h.file.size,e.policy),s=e.pending,o=s.filter(h=>!a(h)),i=s.filter(a),l=new AbortController,u=()=>l.abort();n?.aborted?l.abort():n?.addEventListener("abort",u,{once:!0});let f=null,d=async h=>{try{await fl(e,h,{signal:l.signal,onProgress:p=>r?.(h,p)})}catch(p){f===null&&(f=p,l.abort())}};try{let h=0,p=async()=>{for(;f===null&&!l.signal.aborted&&h<o.length;)await d(o[h++])};await Promise.all(Array.from({length:Math.min(D.upload.SMALL_FILE_POOL,o.length)},p));for(let _ of i){if(f!==null||l.signal.aborted)break;await d(_)}}finally{n?.removeEventListener("abort",u)}if(f!==null)throw f;if(n?.aborted)throw new x("Upload aborted","ABORTED")}function _l(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 wl(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 yl(e,t,n,r,a={}){let s=await Gr(a.relativePath??e.name,t,"name"),o=await Gr(e.type||Fi(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:ve.current_format_version};return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function gl(e,t,n,r,a){if(n?.aborted)throw new x("Upload aborted","ABORTED");let s=nt(e,t);return new Promise((o,i)=>{let l=!1,u=p=>{l||(l=!0,h(),i(p),s.then(async _=>_.ok?r(await _.json()):void 0).catch(()=>{}))},f=()=>u(new x("Upload aborted","ABORTED")),d=setTimeout(()=>u(new x(`The registration got no answer in ${Math.round(a/1e3)} s`,"NETWORK",void 0,void 0,!0)),a),h=()=>{clearTimeout(d),n?.removeEventListener("abort",f)};n?.addEventListener("abort",f,{once:!0}),s.then(p=>{l||(l=!0,h(),o(p))},p=>{l||(l=!0,h(),i(p))})})}function bl(e){return Un(e.transport).completeTimeoutMs}async function ml(e,t,n,r){try{return il(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 El(e,t){if(t?.aborted)throw await e.cancel(),new x("Upload aborted","ABORTED")}async function Sl(e,t,n,r,a){let s={files_meta:t};e.ownerTokenHash&&(s.owner_token_hash=e.ownerTokenHash),wl(s,e);let o=await gl(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...nn(zn(e))},credentials:e.credentials??"include",body:JSON.stringify(s)},n,r,a);if(!o.ok)throw await et(o,"Create seal failed","UNKNOWN");return await o.json()}async function Al(e,t){let n=Co();return{file:e,key:t,header:n,sha256_hex:await Ze(n)}}async function vl(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 Tl(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:Dn(n.file.size),state:"pending"}))}function Fa(e){let t=new Map;for(let n of e)t.set(n.sha256_hex,n.key);return t}function xl(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(u=>n.get(u.index)===100),i=e.reduce((u,f)=>u+f.file.size*(n.get(f.index)??0),0),l=t>0?Math.floor(i/t):100;return r=Math.max(r,o?100:Math.min(99,l)),{percent:r,finished:o}}}}async function kl(e,t){let{onProgress:n,signal:r}=t,a=e.files,s=xl(a);await pl(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 Wa(e,t,n,r,a){if(t.length===0)throw new Error("At least one file is required");_l(e);let s=await Promise.all(t.map(({file:d})=>Al(d,Wo()))),o=await Promise.all(s.map((d,h)=>yl(d.file,d.key,Dn(d.file.size),d.sha256_hex,{relativePath:t[h].relativePath}))),i=(d,h)=>new Gn({ctx:e,policy:n,sealId:d.id,createdSeal:!0,expiresAt:d.expires_at,files:h},async(p,_)=>(await kl(p,_),a(p))),l=await Sl(e,o,r.signal,d=>i(d,[]).cancel(),bl(n)),u=await ml(l.files,s.map(d=>d.sha256_hex),`Create seal ${l.id}`,()=>i(l,[]).cancel()),f=i(l,Tl(s,u));return await El(f,r.signal),await vl(r,l.id,s,u),f.resume(r)}async function $a(e,t,n=He,r={}){return Wa(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:Fa(a.files),expiresAt:a.expiresAt,verification:a.verification}))}async function Ka(e,t,n,r=He,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,l)=>({file:i,relativePath:s?.[l]||i.webkitRelativePath||`${n}/${i.name}`}));return Wa(e,o,r,a,i=>({sealId:i.sealId,files:i.files.map(l=>({fileId:l.fileId,sha256_hex:l.sha256_hex,encryptedSize:l.encryptedSize,relativePath:o[l.index].relativePath})),encryptionKeys:Fa(i.files),folderName:n,expiresAt:i.expiresAt,verification:i.verification}))}var qr=[2e3,4e3,8e3,15e3],Tn=ge.limits.TIER_BYTES,ad=Object.keys(Tn).filter(e=>e!=="free").sort((e,t)=>Tn[e]-Tn[t]);function Ha(e){return e instanceof x&&e.httpStatus===402&&e.session?e.session:null}function za(e,t=Date.now()){let n=t+ge.limits.PAYMENT_WAIT_MAX_SECONDS*1e3,r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)?Math.min(n,r):n}async function Ga(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 F&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=qr[Math.min(a,qr.length-1)];if(Date.now()+s>r.deadline)return null;await $n(s,r.signal)}}var rn=ge.limits.ttl_options;var ja={version:1,name:"COUNTRIES",description:"The countries a seal may name to open from (`geo`): the two-letter codes the country database writes for a reader's network (DB-IP Lite, backend_core/geo.py: ISO 3166-1 and XK), and the old names of a country written as its code of today (`written_as`: UK is GB). The server compares a reader's country with a seal's list exactly, so it writes the list this one way when the seal is made (`SealCreate.geo`) and refuses a code that is not here; the TS clients read a typed list by the same data (the protocol package's `countryCodes`). Not here, on purpose: groupings and pseudo-regions a network is never in (EU, UN, ZZ, XA, XB, QO, EZ) and the places ISO reserves for a part of a country whose network is that country's (AC, CP, CQ, DG, EA, IC, TA). Data, no code: a new country is one entry.",codes:["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"],written_as:{AN:"CW",BU:"MM",CS:"RS",CT:"KI",DD:"DE",DY:"BJ",FQ:"AQ",FX:"FR",HV:"BF",JT:"UM",MI:"UM",NH:"VU",NQ:"AQ",NT:"SA",PC:"FM",PU:"UM",PZ:"PA",RH:"ZW",SU:"RU",TP:"TL",UK:"GB",VD:"VN",WK:"UM",YD:"YE",YU:"RS",ZR:"CD"}};function Ya(e){let t=e.trim();if(t==="")return;let n=/^\d+$/.test(t)?Number(t):Number.NaN;return n>=1&&n<=ge.limits.MAX_OPENS_PER_SEAL_FREE?n:null}var Zr=ge.limits.OTP_DIGITS;function Va(e){return e.length>0&&e.length<Zr.min_length&&Array.from(e).every(t=>Zr.alphabet.includes(t))}var Il=new Set(ja.codes),Ol=new Map(Object.entries(ja.written_as));function Xa(e){let t=[],n=[];for(let r of e.split(/[\s,;]+/)){if(r==="")continue;let a=r.toUpperCase(),s=Ol.get(a)??a;Il.has(s)?t.includes(s)||t.push(s):n.push(r)}return{codes:t,bad:n}}var jn=8,Yn=43,Pn=4,an=/^[A-Za-z0-9_-]+$/;function Rl(e,t){if(!an.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 Vn(e){return e.length===jn&&an.test(e)}function Xn(e){return e.length===Yn&&Rl(e,32)}function qa(e,t){if(!Vn(e))throw new Error(`Invalid sealId: must be ${jn} base64url characters`);if(!Xn(t))throw new Error(`Invalid linkKey: must be ${Yn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function Za(e,t,n){if(!Vn(e))throw new Error(`Invalid sealId: must be ${jn} base64url characters`);if(t.length!==Pn||!an.test(t))throw new Error(`Invalid shareCode: must be ${Pn} base64url characters`);if(!Xn(n))throw new Error(`Invalid linkKey: must be ${Yn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var Gt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function Pl(e){let t;try{t=new URL(e)}catch{throw new Gt("url_invalid",`not a valid URL (${e.length} characters)`)}let n;try{n=Ll(t.pathname.replace(/\/+$/,""))}catch{throw new Gt("url_invalid",`expected /s/<seal_id>[/<share_code>] path (got a path of ${t.pathname.length} characters)`)}let r=t.hash.replace(/^#/,"").trim(),a=n.shareCode??null;if(!r)return{sealId:n.sealId,shareCode:a,fragmentVariant:"none",fragment:r};if(!Xn(r))throw new Gt("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(!Vn(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==Pn||!an.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var qn=Ae.scopes.share_link,Ja=Ae.scopes.owner_copy;var Jr=tt.sealed_box_v2.version_byte,Qr=tt.sealed_box_v2.packed_length,Et=64,Qt=32,ea=32;var Qa=/^[A-Za-z0-9_-]+$/;function es(){return crypto.getRandomValues(new Uint8Array(Et))}async function Zn(e,t=1){let n=await pt();if(e.length===Et)return n.WasmIdentity.fromSeed64(e,t);if(e.length===Qt)return n.WasmIdentity.fromSeed32(e);throw new Error(`a seed is ${Et} bytes, or the ${Qt} of a key made before, got ${e.length}`)}async function Jn(e,t=1){let n=await Zn(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words()}}finally{n.free()}}function ts(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(!Qa.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 ns(e,t){return(await pt()).wasm_bundle_verify_for_address(e,t)}async function sn(e){let{address:t,words:n}=(await pt()).wasm_bundle_address(e);return{bundle:e,address:t,words:n}}function Qn(e,t,n){return`${e}/i/${t}#${n}`}async function on(e,t,n,r){if(e.length!==ea)throw new Error(`a wrapped key is ${ea} 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 pt()).wasm_sealbox_wrap_to(e,t.bundle,t.address,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(!Qa.test(e))throw new Ye("parse","the wrap is not urlsafe-base64-no-pad");let s=ue(e);if(s[0]!==Jr)throw new Ye("parse",`the wrap is not a sealed box v${Jr}: a newer client made it \u2014 update this one`);if(s.length!==Qr)throw new Ye("parse",`the wrap is ${s.length} bytes, expected ${Qr}`);if(t.length!==Et&&t.length!==Qt)throw new Ye("parse",`a seed is ${Et} bytes, or the ${Qt} of a key made before, got ${t.length}`);let o=await Zn(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 Nl(e,t){let n=await Zn(e);try{let r=n.inboxProof(BigInt(t.ts),ue(t.challenge));return`${t.ts}.${t.challenge}.${ae(r)}`}finally{n.free()}}var Ln={version:2,name:"FINGERPRINT_WORDS",description:"Eight words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3): 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 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"}},Dl=Ln.words,Ml=/^[A-Za-z0-9_-]{43}$/;function rs(e){if(!Ml.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=ue(e);return Array.from(t.subarray(0,Ln.count),n=>Dl[n]).join(Ln.separator)}var as=Ae.payloads.pair.mime,od=Ae.payloads.device.mime,id=Ae.payloads.delivery.mime,ld=Ae.payloads.approve.mime,cd=Ae.payloads.approve_answer.mime,dd=Ae.payloads.summary.mime,ss=Ae.pair_what,ta=Ae.payloads.name_max,ud=ge.limits.APPROVE_BODY_SHOWN_BYTES;var na=tt.keybundle.packed_length,ra=2;var Bl=/^[A-Za-z0-9_-]+$/;function os(e){let t=Ul(e,"pairing");if(typeof t.bundle!="string"||!Bl.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:Fl(ue(t.bundle)),name:Wl(t.name)}}function Ul(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!==ra)throw new Error(`${t} payload is not version ${ra}`);return n}function Fl(e){if(e.length!==na)throw new Error(`a bundle is ${na} bytes, got ${e.length}`);return e}function Wl(e){if(typeof e!="string"||e.length===0||e.length>ta)throw new Error(`name must be 1 to ${ta} characters`);return e}var $l=["seal.revoked","seal.expired","seal.not_found","seal.blocked","geo.restricted","client.outdated"],ln=wa.mime,aa=e=>e.appCode==="seal.expired";function sa(e){return!(e instanceof F)||e.appCode!=="client.outdated"?null:new W("client_outdated",[e.detail??"the server no longer serves this client",e.update].filter(Boolean).join(": "),e)}var W=class extends Error{constructor(e,t,n,r){super(t),this.name="OpenError",this.code=e,this.cause=n,r&&(this.countries=r)}},Kl=new Set($l);function er(e){return e instanceof F?e.status===451||e.status===426||e.appCode!==void 0&&Kl.has(e.appCode)?"seal":e.status===429||e.status>=500?"transient":"file":"file"}function is(e){let{REFUSAL_WAIT_DEFAULT_MS:t,REFUSAL_WAIT_MAX_MS:n}=D.upload,r=e instanceof F?e.retryAfter:void 0;return r===void 0?t:Math.min(r*1e3,n)}var Hl=32;async function tr(e,t,n={}){let r;try{r=Pl(t)}catch(y){throw y instanceof Gt?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??(r.fragmentVariant!=="key"&&o?await zl(e,o,a,s,n.signal):null),l=r.fragmentVariant==="key"?ue(r.fragment):i!==null&&o?await oa(i,o,a):null;l!==null&&await e.holdShareProof(a,l);let u=n.signal?{signal:n.signal}:{},f;try{f=await e.getMetadata(r.sealId,{...u,shareCode:s})}catch(y){let L=sa(y);if(L)throw L;if(y instanceof F&&(y.code==="not_found"||y.code==="revoked")){let R=y.code==="revoked"&&!aa(y);throw new W(R?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${R?"has been revoked":"was not found or has expired"}`,y)}throw new W("metadata_failed",`reading seal ${r.sealId} failed: ${tn(y)}`,y)}let d=oi(f);if(d.revokedAt!==null)throw new W("seal_revoked",`seal ${r.sealId} has been revoked`);if(f.spent===!0)throw new W("seal_spent",`seal ${r.sealId}: every open it allows is taken, nothing of it opens any more`);if(f.gone===!0)throw new W("seal_revoked",`seal ${r.sealId}: nothing in it is left to open; ask its sender to send it again`);let h=new Set(f.files.filter(y=>!y.revoked_at).map(y=>y.id)),p=d.files.filter(y=>h.has(y.id));if(p.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 _;try{let y=await e.getShareBlob(a,s,u);if(_=y.blob,l===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");l=await oa(y.wrap,o,a),await e.holdShareProof(a,l)}}catch(y){if(y instanceof W)throw y;let L=sa(y);if(L)throw L;if(y instanceof F&&y.appCode==="geo.restricted"){let R=f.geo_allowlist??[];throw new W("geo_restricted",`seal ${a} opens only from networks in ${R.join(", ")||"its sender's countries"}, and the server does not place this one there`,y,R)}if(y instanceof F&&(y.code==="not_found"||y.code==="revoked")){let R=y.code==="revoked"&&!aa(y);throw new W(R?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${R?"has been revoked":"was not found or has expired"}`,y)}throw new W("share_blob_fetch_failed",`share blob fetch failed: ${tn(y)}`,y)}let g,w,m,T;try{let y=await Ei(_,l);g=y.file_keys,w=bi(y),m=y.message?.trim()?y.message:null,T=yi(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 k=await Promise.all(p.map(y=>ql(y,g,w)));return{sealId:a,shareCode:s,expiresAt:d.expiresAt,singleUse:d.singleUse,maxOpens:d.maxOpens,otpRequired:d.otpRequired,ndaRequired:d.ndaRequired,otpPassed:f.otp_session_valid===!0,ndaPassed:f.nda_session_valid===!0,countries:f.geo_allowlist?.length?f.geo_allowlist:null,message:m,ndaFile:T,linkKey:l,files:k}}async function zl(e,t,n,r,a){try{return(await dn(e,t,a?{signal:a}:{})).items.find(o=>o.path===`/s/${n}/${r}`)?.fragment??null}catch(s){if(a?.aborted)throw s;return null}}async function oa(e,t,n){try{return await Cl(e,t,qn,n)}catch(r){let a=r instanceof Ye&&r.kind==="aead";throw new W(a?"targeted_decrypt_failed":"targeted_fragment_invalid",tn(r),r)}}async function ls(e,t,n={}){let r=new Wn(Bn);try{for(;;){n.signal?.throwIfAborted();let a=Date.now(),s;try{s=await Gl(e,t,n,r)}catch(i){throw i instanceof F&&i.code==="not_found"?new W("request_expired","the request expired before anybody answered",i):i}if(s.status==="expired")throw new W("request_expired","nobody answered before the request expired");if(s.status==="fulfilled"){if(s.share_path&&s.fragment)return{sharePath:s.share_path,wrap:s.fragment};throw new W("share_blob_corrupt","the request was answered without its link")}if(s.status!=="pending")throw new W("client_outdated",`the request is ${String(s.status)}, a state this client does not know`);let o=jl-(Date.now()-a);o>0&&await nr(o,n.signal)}}finally{r.dispose()}}async function Gl(e,t,n,r){let a;try{let s=await mt(async()=>{try{return await e.getIntake(t,{...n,waitSeconds:ge.limits.INTAKE_WAIT_MAX_SECONDS})}catch(o){a=o;let i=o instanceof F?o.status===408||o.status===429||o.status>=500:!n.signal?.aborted;throw new x(tn(o),i?"NETWORK":"UNKNOWN")}},{clock:r,policy:Bn,signal:n.signal,classify:o=>o.code==="NETWORK"?"retryable":"terminal",what:`GET /intake/${t}`});return r.delivered(),s}catch(s){throw n.signal?.throwIfAborted(),a??s}}var jl=2e3;function nr(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 ia=64*1024;async function cs(e,t,n,r){let a=await tr(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||us(s.mime)!==n||s.size>ia)throw new W("share_blob_corrupt",`the answer is not one ${n} file`);return Yl(e,{sealId:a.sealId,shareCode:null},s,{maxBytes:ia,...r.signal?{signal:r.signal}:{}})}async function Yl(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=rr(a.body,n.key,n.sha256Hex).stream.getReader(),o=[];for(let u=await s.read();!u.done;u=await s.read())o.push(u.value);let i=new Uint8Array(o.reduce((u,f)=>u+f.length,0)),l=0;for(let u of o)i.set(u,l),l+=u.length;return i}var Vl=3e4,la=new Map;async function Xl(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&Ql(r,t.bundle)||await e.putBundle(t.bundle,n)}async function en(e,t,n={}){let r=await Jn(t),a=`${e.baseUrl} ${r.address}`,s=la.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await Xl(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await Nl(t,o)};return la.set(a,{proof:i,until:Date.parse(o.expires_at)-Vl}),i}async function cn(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await en(e,t,a))}catch(s){if(!(s instanceof F&&s.appCode==="intake.proof_required"))throw s;return r(await en(e,t,{...a,fresh:!0}))}}async function dn(e,t,n={}){let r=n;return cn(e,t,n.signal,a=>e.listInbox(a,r))}async function ds(e,t,n,r={}){return cn(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function ql(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:qt,mime:Zt,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!==Hl)throw new W("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${s.length} bytes`);let{name:o,mime:i}=await Hi(e,s),l=us(i)===ln,u=l&&e.sha256_hex?n[e.sha256_hex]??null:null;return{...a,name:o,mime:i,secret:l,key:s,binding:u}}function us(e){return(e.split(";")[0]??e).trim().toLowerCase()}function rr(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=$t.create(),o=0,i,l=new Promise((h,p)=>{i={resolve:h,reject:p}});l.catch(()=>{});let u=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:Jl(s.digest())})}}),d=e.pipeThrough(u).pipeThrough(Ri(a,{expectedSha256Hex:n})).pipeThrough(f);return{stream:ec(d,i.reject,a),done:l}}function Zl(e){return e instanceof Be?new W(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function Jl(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Ql(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function ec(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=Zl(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function tn(e){return e instanceof Error?e.message:String(e)}var fd=ge.limits.LEASE_DEFAULT_DAYS,pd=ge.limits.LEASE_MAX_DAYS,_d=ge.limits.LEASE_POLL_SECONDS,wd=ge.limits.LEASE_STATUS_BATCH_MAX;async function fs(){let e=ka(),t=Kn();return{ownerTokenB64:ae(e),ownerTokenHash:await Ia(e),linkKey:t,linkKeyB64:ae(t)}}var ps=rn[rn.length-1]??rn[0],ar={ttl:"1h",singleUse:!0};function _s(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 Ld={...He,transport:{maxStallMs:1/0}};function ws(e,t){let{ttl:n,tier:r,otp:a,nda:s,ownerEmail:o,singleUse:i,maxOpens:l,geo:u,ownerTokenHash:f,ownerToken:d}=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}:{},...l?{maxOpens:l}:{},...u&&u.length>0?{geo:[...u]}:{},ownerTokenHash:f,ownerToken:d}}var vt=class extends Error{};async function ys(e){let{keys:t,ndaFileName:n,api:r}=e,a=e.message?.trim()?e.message:void 0,s=await e.upload(async(p,_)=>{e.registered?.(p);let{fileKeys:g,ndaFile:w}=hs(_,n),m=ae(await Oa(t.ownerTokenB64,g,t.linkKey,a,w));await tc(r,p,t.ownerTokenB64,m),await e.ownerBlobStored?.(p)});e.uploaded?.(s);let o=s.fileResults.map(p=>{let _=s.encryptionKeys.get(p.sha256_hex);if(!_)throw new Error(`the upload returned no key for the file ${p.fileId}`);return{sha256_hex:p.sha256_hex,key:_}}),{fileKeys:i,ndaFile:l}=hs(o,n),u=Kn(),f={blobB64:ae(await Ra(i,u,a,l)),linkKeyB64:ae(u)};e.minting?.(f);let{to:d}=e;if(d){let p=await on(u,d,qn,s.sealId),_=d.label?.slice(0,80),g=y=>r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,u,{to:d.address,fragment:p,..._?{label:_}:{},...y?{sender:y}:{}}),w=async y=>await d.sender?.(y).catch(()=>null)??null,m=y=>y instanceof F&&y.appCode==="intake.proof_required",T=await w(!1),k=await g(T).catch(async y=>{if(!T||!m(y))throw y;let L=await w(!0);return L?g(L).catch(R=>{if(m(R))return g(null);throw R}):g(null)});return{sealId:s.sealId,verification:s.verification,shareCode:k,share:f}}let h=await r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,u).catch(()=>null);return{sealId:s.sealId,verification:s.verification,shareCode:h,share:f}}async function tc(e,t,n,r){let a=o=>o instanceof F&&o.appCode==="blob.precondition_required",s=null;for(let o=0;o<2;o++)try{await e.writeOwnerBlob(t,n,r);return}catch(i){if(o>0&&a(i)&&!a(s))return;s=i}throw new vt(s instanceof Error?s.message:String(s),{cause:s})}function hs(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 gs={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},OTP_DIGITS:{alphabet:"0123456789",min_length: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 sr=["byte","kilobyte","megabyte","gigabyte","terabyte"],rc=["B","KB","MB","GB","TB"];function bs(e,t){let r=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),sr.length-1):0,a=parseFloat((e/Math.pow(1024,r)).toFixed(2));return a>=1024&&r<sr.length-1&&(r+=1,a=parseFloat((e/Math.pow(1024,r)).toFixed(2))),t?new Intl.NumberFormat(t,{style:"unit",unit:sr[r],unitDisplay:r===0?"long":"short",maximumFractionDigits:2}).format(a):`${a} ${rc[r]}`}var ac=1e3,sc=60*ac,oc=60*sc,Md=24*oc;var $=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&&lc(a),Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},ic=["ownerToken","ownerLinkKey"];function lc(e){let t={...e};for(let n of ic){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 cc={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",seal_spent:"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",geo_restricted:"AUTH_INSUFFICIENT_SCOPE"};function ms(e){if(e===400||e===413||e===422)return"VALIDATION_ERROR";if(e===402)return"PAYMENT_REQUIRED";if(e===426)return"CLIENT_OUTDATED";if(e===429)return"RATE_LIMITED";if(e===404||e===410||e===451)return"RESOURCE_NOT_FOUND";if(e===401||e===403)return"AUTH_INSUFFICIENT_SCOPE";if(e>=500&&e<600)return"SERVICE_UNAVAILABLE"}function he(e,t,n=null){if(e instanceof $)return e;if(e instanceof W){let r=e.cause instanceof F?e.cause.status:400;return new $(e.message,cc[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof F){let r=e.appCode==="client.outdated"?"CLIENT_OUTDATED":e.appCode==="intake.proof_required"?"AUTH_INVALID_KEY":e.code==="not_found"||e.code==="revoked"||e.code==="blocked"?"RESOURCE_NOT_FOUND":e.code==="auth"?"AUTH_INSUFFICIENT_SCOPE":e.code==="rate_limited"?"RATE_LIMITED":e.code==="transient"?"SERVICE_UNAVAILABLE":ms(e.status)??"INTERNAL_ERROR";return new $(e.detail??t,r,e.status,n,{cause:e})}if(e instanceof x){let r=e.httpStatus===void 0?void 0:ms(e.httpStatus),a=e.code==="CLIENT_OUTDATED"?"CLIENT_OUTDATED":e.code==="QUOTA_EXCEEDED"?"STORAGE_QUOTA_EXCEEDED":r??(e.code==="NETWORK"?"NETWORK_ERROR":"INTERNAL_ERROR");return new $(e.message,a,e.httpStatus??500,n,{cause:e})}return e instanceof Error&&e.swCode==="NETWORK"?new $(e.message,"NETWORK_ERROR",500,n,{cause:e}):new $(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}function Es(e){return e.split("/").filter(t=>t!==""&&t!=="."&&t!=="..")}var Ue=gs.limits;function dc(e){return e instanceof x&&e.code==="ABORTED"||e instanceof DOMException&&e.name==="AbortError"}var Zd=Ue.ttl_options,uc="Secret",hc="Confidentiality Agreement",un=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 At({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){t.nda&&!t.ownerEmail&&fe("ownerEmail is required when nda=true"),t.tier&&!t.onPaymentRequired&&fe("onPaymentRequired is required with tier");let{files:n,relativePaths:r,ndaDocument:a,secretAlone:s}=pc(t),o=t.message?.trim()?t.message:void 0;o&&o.length>Ue.MAX_MESSAGE_LENGTH&&fe(`message: ${o.length} characters, at most ${Ue.MAX_MESSAGE_LENGTH}`),o&&a&&fe("message and ndaFile: the NDA is its text or its document, give one of them");let i=o??(a?`NDA document attached: ${a.name} (${bs(a.size)})`:t.nda?hc:void 0),l=fc(t,s);"to"in t&&!t.to&&fe("to: empty: an address holds a value");let u=(I,K)=>{if(K!==void 0)try{return ts(K)}catch(v){throw new $(`${I}: ${v instanceof Error?v.message:String(v)}`,"VALIDATION_ERROR",400)}},f=u("to",t.to),d=u("owner",t.owner),h=t.signal?{signal:t.signal}:{},p=async I=>{let K=await this.api.getBundle(I,h);return K&&await ns(K,I)?K:null},_=null;if(f){try{_=await p(f)}catch(I){throw he(I,"Failed to read the recipient key")}if(!_)throw new $(`to: ${f} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let g=d?await p(d).catch(()=>null):null,w=t.keyPair?ue(t.keyPair.secretKey):null,m=I=>w?cn(this.api,w,t.signal,I):I(),T=await fs(),k={...ws(this.baseUrl,_s(l,T,t.tier)),...this.credentials!==void 0?{credentials:this.credentials}:{}},y=null,L=I=>({sealId:I,ownerToken:T.ownerTokenB64,ownerLinkKey:T.linkKeyB64}),R=!1,C=!1,Q=null,pe=t.onProgress;try{let I=await ys({keys:T,ndaFileName:a?.name??null,message:i,api:{writeOwnerBlob:async(ee,Te,oe)=>{if(d&&g&&!C){let Ee=await on(T.linkKey,{bundle:g,address:d},Ja,ee),ie=!1,z=await m(_e=>this.api.writeOwnerBlob(ee,Te,oe,{...h,to:d,fragment:Ee,label:"sealnet",..._e?{sender:_e}:{}})).catch(_e=>(ie=!(_e instanceof F),null));return z?(R=!0,z):(C=!0,this.api.writeOwnerBlob(ee,Te,oe,h).catch(_e=>{if(!ie||!(_e instanceof F)||_e.appCode!=="blob.precondition_required")throw _e;return R=!0,{etag:null}}))}return this.api.writeOwnerBlob(ee,Te,oe,h)},createShareLink:(ee,Te,oe,Ee,ie={})=>this.api.createShareLink(ee,Te,oe,Ee,{...ie,...h})},registered:ee=>{y=ee},upload:async ee=>{let Te={onRegistered:ee,...pe?{onProgress:ie=>pe({phase:ie.fileProgress.phase,percent:ie.overallPercent,fileIndex:ie.fileIndex,totalFiles:ie.totalFiles,fileName:ie.fileName})}:{},...h},oe,Ee;try{oe=r?await Ka(k,n,"",He,Te,r):await $a(k,n,He,Te),Ee=oe.expiresAt}catch(ie){let z=Ha(ie);if(!z||!t.tier||!t.onPaymentRequired)throw ie;await t.onPaymentRequired(await this.api.createCheckout(z.sealId,T.ownerTokenB64,t.tier,h));let _e=za(z instanceof Gn?z.expiresAt:void 0),xe=await Ga(this.api,z.sealId,T.ownerTokenB64,{deadline:_e,...h});if(!xe){let we=await this.api.getOwnerSeal(z.sealId,T.ownerTokenB64,h).catch(()=>{});if(!we)throw new $("The seal may be paid and was kept, not revoked","PAYMENT_REQUIRED",402,L(z.sealId));we.tier&&we.tier!=="free"&&(xe=we)}if(!xe)throw await this.api.revoke(z.sealId,T.ownerTokenB64).catch(()=>{}),new $("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,L(z.sealId));oe=await z.resume(Te),Ee=xe.expires_at}if(!Ee)throw new $(`Seal ${oe.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,L(oe.sealId));return Q={result:oe,expiresAt:Ee},{sealId:oe.sealId,encryptionKeys:oe.encryptionKeys,fileResults:oe.files,verification:oe.verification}},...f&&_?{to:{address:f,bundle:_,label:"sealnet",...w?{sender:ee=>en(this.api,w,{...h,fresh:ee})}:{}}}:{}}),{result:K,expiresAt:v}=Q,M=I.shareCode;if(M===null)try{M=await this.api.createShareLink(I.sealId,T.ownerTokenB64,I.share.blobB64,ue(I.share.linkKeyB64),h)}catch(ee){throw he(ee,"Seal created but share link mint failed",L(I.sealId))}let se=Za(I.sealId,M,I.share.linkKeyB64),Y=`${this.shareUrlBase}${f?se.split("#")[0]:se}`,V=`${this.shareUrlBase}${qa(I.sealId,T.linkKeyB64)}`,[me]=K.files,X=me&&K.encryptionKeys.get(me.sha256_hex);if(!me||!X)throw new $(`Seal ${I.sealId}: the upload returned no key for its first file`,"INTERNAL_ERROR",500,L(I.sealId));let rt=r??n.map(ee=>ee.name);return{sealId:I.sealId,shareUrl:Y,ownerUrl:V,ownerToken:T.ownerTokenB64,expiresAt:v,encryptionKey:De(X),fileId:me.fileId,files:K.files.map((ee,Te)=>({fileId:ee.fileId,name:rt[Te]})),delivered:f!==void 0,ownerCopy:R}}catch(I){if(I instanceof $)throw I;if(!y)throw!dc(I)&&(I instanceof F||I instanceof x)?he(I,"The seal was not created"):I;let K=I instanceof vt?I.cause:I;if(K instanceof F||K instanceof x)throw he(K,`Seal ${y} was created but its send did not finish`,L(y));let v=K instanceof Error?K.message:String(K);throw new $(`Seal ${y} was created but the create flow was interrupted: ${v}`,"INTERNAL_ERROR",500,L(y),{cause:I})}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw he(a,"Failed to revoke seal")}}};function fc(e,t){if("otp"in e&&!e.otp&&fe("otp: empty: a password holds a value"),e.otp&&Va(e.otp)){let a=Ue.OTP_DIGITS.min_length;fe(`otp: a password of digits only needs ${a} digits: give ${a} digits, or add a letter`)}let n=e.maxOpens===void 0?void 0:Ya(String(e.maxOpens));n===null&&fe(`maxOpens: ${e.maxOpens}: a whole number from 1 to ${Ue.MAX_OPENS_PER_SEAL_FREE}`);let r=Xa((e.geoAllowlist??[]).join(" "));return r.bad.length>0&&fe(`geoAllowlist: ${r.bad.join(", ")}: two-letter country codes such as DE, CH, US`),r.codes.length>Ue.MAX_GEO_COUNTRIES&&fe(`geoAllowlist: ${r.codes.length} countries, at most ${Ue.MAX_GEO_COUNTRIES}`),{ttl:e.ttl??(t?ar.ttl:ps),otp:e.otp,nda:e.nda,ownerEmail:e.ownerEmail,singleUse:e.singleUse??(t&&n===void 0?ar.singleUse:void 0),maxOpens:n,geo:r.codes}}function pc(e){let t=(a,s,o)=>o||(s instanceof File?s.name:"")||fe(`${a}: bytes need a filename`),n=[];if("secret"in e){(e.secret===void 0||e.secret.length===0)&&fe("secret: empty: a secret holds a value");let a=typeof e.secret=="string"?new Blob([e.secret]):e.secret;n.push({file:Tt(a,uc,ln),secret:!0})}e.file!==void 0&&n.push({file:Tt(e.file,t("file",e.file,e.filename),e.mimeType),secret:!1});for(let[a,s]of(e.files??[]).entries()){let o=Tt(s.file,t(`files[${a}]`,s.file,s.filename),s.secret?ln:s.mimeType);s.secret&&o.size===0&&fe(`files[${a}]: an empty secret`),n.push({file:o,secret:s.secret===!0})}for(let[a,s]of(e.folder??[]).entries()){let o=Es(s instanceof File?Da(s)??s.name:s.path),i=o.at(-1);i||fe(`folder[${a}]: a file with no path`);let l=o.join("/");n.push(s instanceof File?{file:s,path:l,secret:!1}:{file:Tt(s.file,i,s.mimeType),path:l,secret:!1})}let r=null;if(e.ndaFile!==void 0){e.nda||fe("ndaFile goes with nda: true");let{file:a,filename:s,mimeType:o}=e.ndaFile;r=Tt(a,t("ndaFile",a,s),o),n.push({file:r,secret:!1})}return n.length===0&&fe("Nothing to seal: give file, files, folder or secret"),n.length>Ue.MAX_FILES_PER_SEAL&&fe(`A seal holds at most ${Ue.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 fe(e){throw new $(e,"VALIDATION_ERROR",400)}function Tt(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 Ss(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)),u=>u.toString(16).padStart(2,"0")).join(""),o=a.join(t,`.seal-partial-${s}`),i=await r.open(o,"wx",384),l=!1;try{await e.stream.pipeTo(new WritableStream({async write(p){await i.write(p)}}));let{sizeBytes:u,sha256:f}=await e.done;await i.sync(),await i.close();let d=a.extname(n),h=n.slice(0,n.length-d.length);for(let p=0;p<1e3;p++){let _=a.join(t,p===0?n:`${h} (${p})${d}`);try{await r.link(o,_)}catch(g){let w=g.code;if(w==="EEXIST")continue;if(w!=="EPERM"&&w!=="ENOTSUP"&&w!=="EOPNOTSUPP"&&w!=="ENOSYS")throw g;if(await r.access(_).then(()=>!0,()=>!1))continue;return await r.rename(o,_),l=!0,{path:_,sizeBytes:u,sha256:f}}return l=!0,await r.unlink(o).catch(()=>{}),{path:_,sizeBytes:u,sha256:f}}throw new Error(`no free name for ${n} in ${t}`)}finally{l||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}var _c=/^[A-Za-z0-9_-]{86}$/;function xt(e){if(_c.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 $(t,"INVALID_KEY",400)}async function As(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await tr(e,t,{...n.keyPair?{seed:xt(n.keyPair)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new $("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 $("This seal is password-protected: pass `password`","AUTH_INVALID_KEY",401);o=(await e.verifyOtp(s.sealId,{code:n.password,shareCode:s.shareCode},a)).sessionCookie}let i=s.files.filter(d=>d.key!==null&&d.sha256Hex!==null),l={done:0,total:i.reduce((d,h)=>d+h.size,0),told(){n.onProgress?.(this.done,this.total)}},u=new Ta;return{seal:s,covered:i,read:async d=>{let h=await u.ask(p=>e.downloadCiphertext(s.sealId,{fileId:d.id,shareCode:s.shareCode,visit:p,...o?{sessionCookie:o}:{}},a));if(!h.body)throw new $(`Download of ${d.name} returned no body`,"INTERNAL_ERROR",h.status);return rr(h.body,d.key,d.sha256Hex,p=>{l.done+=p,l.told()})},progress:l}}async function or(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await As(e,t,n,r);return{sealId:a.sealId,expiresAt:a.expiresAt,message:a.message??null,files:s.map(i=>({name:i.name,mime:i.mime,size:i.size,secret:i.secret,read:()=>o(i).catch(l=>Promise.reject(he(l,"Download failed")))}))}}catch(a){throw he(a,"Failed to open the link")}}async function ir(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i,progress:l}=await As(e,t,r,a),u=async _=>{let g=Na(_.name),w=g.pop()??Xt(_.name),m=g.length>0?[n||".",...g].join("/"):n,T=await Ss(await i(_),m,w);return{name:_.name,mime:_.mime,secret:_.secret,...T}},f=[],d=[],h=null;for(let _ of o){r.signal?.throwIfAborted();let g=l.done;if(h){let w=h.details?.reason,m=new $(`${_.name} was not asked: ${h.message}`,h.code,h.status,w===void 0?null:{reason:w},{cause:h});d.push({name:_.name,error:m})}else try{f.push(await u(_).catch(async w=>{if(r.signal?.aborted||er(w)!=="transient")throw w;return l.done=g,await nr(is(w),r.signal),u(_)}));continue}catch(w){if(r.signal?.aborted)throw w;let m=he(w,`Download of ${_.name} failed`);er(w)!=="file"&&(h=m),d.push({name:_.name,error:m})}l.done=g+_.size,l.told()}if(f.length===0&&d.length>0)throw h??d[0].error;let p={sealId:s.sealId,expiresAt:s.expiresAt,message:s.message??null,files:f};return d.length>0?{...p,refused:d}:p}catch(s){throw he(s,"Failed to open the link")}}async function vs(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}:{}),{address:a,words:s}=await sn(ue(n.recipientBundle));return{intakeId:r.id,url:Qn(t,r.id,a),words:s,expiresAt:r.expires_at}}catch(r){throw he(r,"Failed to create the request")}}async function lr(e,t,n){try{return await ls(e,t,n?{signal:n}:{})}catch(r){throw he(r,"Failed to wait for the request")}}async function Ts(e,t,n){let r,a;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:ss,kind:"pair"},n.signal?{signal:n.signal}:{}),a=Qn(t,r.id,(await sn(ue(n.keyPair.bundle))).address)}catch(o){throw he(o,"Failed to create the pairing request")}let s=async()=>{let{sharePath:o,wrap:i}=await lr(e,r.id,n.signal);try{let l=await cs(e,`${t}${o}`,as,{seed:xt(n.keyPair),wrap:i,...n.signal?{signal:n.signal}:{}}),{bundle:u,name:f}=os(l),{address:d,words:h}=await sn(u);return{address:d,name:f,words:h}}catch(l){throw he(l,"The answer of the inbox did not open")}};return{url:a,words:n.keyPair.words,expiresAt:r.expires_at,wait:s}}async function xs(){let e=es(),{address:t,bundle:n,words:r}=await Jn(e);return{secretKey:ae(e),address:t,bundle:ae(n),words:r}}async function ks(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 dn(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:rs(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw he(a,"Failed to read the inbox")}}async function Is(e,t,n,r){let a;try{a=(await dn(e,xt(r.keyPair),r.signal?{signal:r.signal}:{})).items}catch(o){throw he(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new $(`${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 Os(e,t,n){try{await ds(e,xt(n.keyPair),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw he(r,"Failed to remove the item")}}var[wc="",Rs=""]="sdk-web/3.2.1".split("/");typeof globalThis.process?.versions?.node!="string"&&bn(Se);var cr=class{seals;api;site;constructor(t={}){va(wc,Rs);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new un({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new At({baseUrl:n,credentials:"same-origin"})}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 Is(this.api,this.site,t,{keyPair:a.keyPair,...a.signal?{signal:a.signal}:{}});else throw new $("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?ir(this.api,s.url,r,a,s.wrap):or(this.api,s.url,a,s.wrap)}async inbox(t){return ks(this.api,t)}async dismiss(t,n){return Os(this.api,t,n)}async request(t){return vs(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await lr(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?ir(this.api,i,s,o,a):or(this.api,i,o,a)}async pair(t){return Ts(this.api,this.site,t)}async keygen(){return xs()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},yc=Rs;return Ys(gc);})();
|
|
1
|
+
/*! sealnet v3.2.4 | 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 zs=Object.create;var Ct=Object.defineProperty;var Gs=Object.getOwnPropertyDescriptor;var js=Object.getOwnPropertyNames;var Ys=Object.getPrototypeOf,Vs=Object.prototype.hasOwnProperty;var Nt=(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 Xs=(e,t)=>{for(var n in t)Ct(e,n,{get:t[n],enumerable:!0})},yr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of js(t))!Vs.call(e,a)&&a!==n&&Ct(e,a,{get:()=>t[a],enumerable:!(r=Gs(t,a))||r.enumerable});return e};var Dt=(e,t,n)=>(n=e!=null?zs(Ys(e)):{},yr(t||!e||!e.__esModule?Ct(n,"default",{value:e,enumerable:!0}):n,e)),qs=e=>yr(Ct({},"__esModule",{value:!0}),e);var Ac={};Xs(Ac,{SealClient:()=>ur,SealError:()=>$,VERSION:()=>Sc,configureWasm:()=>Sn});var Se={url:"https://seal.net/sdk/v3.2.4/seal_crypto.wasm",integrity:"sha384-J9NTJFphVX/NdC0pcwJmhENoDqXMqj6caYtMhwzS4t9Bs+uIfpd4FuY2gX/Q4LFZ"};var Ro={},Js=Object.defineProperty,Qs=(e,t)=>{for(var n in t)Js(e,n,{get:t[n],enumerable:!0})},Ar={};Qs(Ar,{ContractTermsBuilder:()=>mn,WasmIdentity:()=>En,default:()=>bo,init:()=>eo,initSync:()=>go,wasm_approval_message:()=>to,wasm_bundle_address:()=>no,wasm_bundle_verify_for_address:()=>ro,wasm_contract_message:()=>ao,wasm_contract_message_v2:()=>so,wasm_ed25519_verify:()=>oo,wasm_sealbox_wrap_to:()=>io,wasm_summary_message:()=>lo,wasm_unwrap_file_key:()=>co,wasm_wrap_file_key:()=>uo});var mn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,gr.unregister(this),e}free(){let e=this.__destroy_into_raw();c.__wbg_contracttermsbuilder_free(e,0)}digest(){let e,t;try{let a=this.__destroy_into_raw(),s=c.__wbindgen_add_to_stack_pointer(-16);c.contracttermsbuilder_digest(s,a);var n=S().getInt32(s+0,!0),r=S().getInt32(s+4,!0);return e=n,t=r,Pe(n,r)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(e,t,1)}}field(e,t,n,r,a,s,o,i,l,u){try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=R(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=R(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=R(i,c.__wbindgen_export3,c.__wbindgen_export4),y=A,x=R(l,c.__wbindgen_export3,c.__wbindgen_export4),T=A;c.contracttermsbuilder_field(h,this.__wbg_ptr,p,_,g,w,n,r,a,s,o,m,y,x,T,u);var f=S().getInt32(h+0,!0),d=S().getInt32(h+4,!0);if(d)throw M(f)}finally{c.__wbindgen_add_to_stack_pointer(16)}}filled(e,t){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=R(e,c.__wbindgen_export3,c.__wbindgen_export4),o=A,i=R(t,c.__wbindgen_export3,c.__wbindgen_export4),l=A;c.contracttermsbuilder_filled(a,this.__wbg_ptr,s,o,i,l);var n=S().getInt32(a+0,!0),r=S().getInt32(a+4,!0);if(r)throw M(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}constructor(e){var t=ut(e)?0:R(e,c.__wbindgen_export3,c.__wbindgen_export4),n=A;let r=c.contracttermsbuilder_new(t,n);return this.__wbg_ptr=r,gr.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(mn.prototype[Symbol.dispose]=mn.prototype.free);var En=class Mt{static __wrap(t){let n=Object.create(Mt.prototype);return n.__wbg_ptr=t,br.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,br.unregister(this),t}free(){let t=this.__destroy_into_raw();c.__wbg_wasmidentity_free(t,0)}address(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_address(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Pe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}bundle(){let t=c.wasmidentity_bundle(this.__wbg_ptr);return M(t)}static fromSeed32(t){try{let s=c.__wbindgen_add_to_stack_pointer(-16),o=ce(t,c.__wbindgen_export3),i=A;c.wasmidentity_fromSeed32(s,o,i);var n=S().getInt32(s+0,!0),r=S().getInt32(s+4,!0),a=S().getInt32(s+8,!0);if(a)throw M(r);return Mt.__wrap(n)}finally{c.__wbindgen_add_to_stack_pointer(16)}}static fromSeed64(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A;c.wasmidentity_fromSeed64(o,i,l,n);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw M(a);return Mt.__wrap(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}inboxProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(n,c.__wbindgen_export3),l=A;c.wasmidentity_inboxProof(o,this.__wbg_ptr,t,i,l);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw M(a);return M(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}open(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(t,c.__wbindgen_export3),u=A,f=R(n,c.__wbindgen_export3,c.__wbindgen_export4),d=A,h=R(r,c.__wbindgen_export3,c.__wbindgen_export4),p=A;c.wasmidentity_open(i,this.__wbg_ptr,l,u,f,d,h,p);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw M(s);return M(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signApproval(t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=R(t,c.__wbindgen_export3,c.__wbindgen_export4),u=A,f=R(n,c.__wbindgen_export3,c.__wbindgen_export4),d=A,h=R(r,c.__wbindgen_export3,c.__wbindgen_export4),p=A;c.wasmidentity_signApproval(i,this.__wbg_ptr,l,u,f,d,h,p);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw M(s);return M(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signContractV2(t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=R(t,c.__wbindgen_export3,c.__wbindgen_export4),f=A,d=R(n,c.__wbindgen_export3,c.__wbindgen_export4),h=A,p=R(r,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=R(a,c.__wbindgen_export3,c.__wbindgen_export4),w=A;c.wasmidentity_signContractV2(l,this.__wbg_ptr,u,f,d,h,p,_,g,w);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw M(o);return M(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}signSummary(t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=R(t,c.__wbindgen_export3,c.__wbindgen_export4),f=A,d=R(n,c.__wbindgen_export3,c.__wbindgen_export4),h=A,p=R(r,c.__wbindgen_export3,c.__wbindgen_export4),_=A;c.wasmidentity_signSummary(l,this.__wbg_ptr,u,f,d,h,p,_,a);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw M(o);return M(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}userProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A,u=ce(n,c.__wbindgen_export3),f=A;c.wasmidentity_userProof(o,this.__wbg_ptr,i,l,u,f);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw M(a);return M(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}words(){let t,n;try{let s=c.__wbindgen_add_to_stack_pointer(-16);c.wasmidentity_words(s,this.__wbg_ptr);var r=S().getInt32(s+0,!0),a=S().getInt32(s+4,!0);return t=r,n=a,Pe(r,a)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(t,n,1)}}workloadProof(t,n){try{let o=c.__wbindgen_add_to_stack_pointer(-16),i=ce(t,c.__wbindgen_export3),l=A,u=ce(n,c.__wbindgen_export3),f=A;c.wasmidentity_workloadProof(o,this.__wbg_ptr,i,l,u,f);var r=S().getInt32(o+0,!0),a=S().getInt32(o+4,!0),s=S().getInt32(o+8,!0);if(s)throw M(a);return M(r)}finally{c.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(En.prototype[Symbol.dispose]=En.prototype.free);function eo(){c.init()}function to(e,t,n){let r,a;try{let d=c.__wbindgen_add_to_stack_pointer(-16),h=R(e,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=R(t,c.__wbindgen_export3,c.__wbindgen_export4),g=A,w=R(n,c.__wbindgen_export3,c.__wbindgen_export4),m=A;c.wasm_approval_message(d,h,p,_,g,w,m);var s=S().getInt32(d+0,!0),o=S().getInt32(d+4,!0),i=S().getInt32(d+8,!0),l=S().getInt32(d+12,!0),u=s,f=o;if(l)throw u=0,f=0,M(i);return r=u,a=f,Pe(u,f)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function no(e){try{let a=c.__wbindgen_add_to_stack_pointer(-16),s=ce(e,c.__wbindgen_export3),o=A;c.wasm_bundle_address(a,s,o);var t=S().getInt32(a+0,!0),n=S().getInt32(a+4,!0),r=S().getInt32(a+8,!0);if(r)throw M(n);return M(t)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function ro(e,t){let n=ce(e,c.__wbindgen_export3),r=A,a=R(t,c.__wbindgen_export3,c.__wbindgen_export4),s=A;return c.wasm_bundle_verify_for_address(n,r,a,s)!==0}function ao(e,t,n){let r,a;try{let d=c.__wbindgen_add_to_stack_pointer(-16),h=R(e,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=R(t,c.__wbindgen_export3,c.__wbindgen_export4),g=A,w=R(n,c.__wbindgen_export3,c.__wbindgen_export4),m=A;c.wasm_contract_message(d,h,p,_,g,w,m);var s=S().getInt32(d+0,!0),o=S().getInt32(d+4,!0),i=S().getInt32(d+8,!0),l=S().getInt32(d+12,!0),u=s,f=o;if(l)throw u=0,f=0,M(i);return r=u,a=f,Pe(u,f)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(r,a,1)}}function so(e,t,n,r){let a,s;try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=R(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=R(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=R(n,c.__wbindgen_export3,c.__wbindgen_export4),y=A,x=R(r,c.__wbindgen_export3,c.__wbindgen_export4),T=A;c.wasm_contract_message_v2(h,p,_,g,w,m,y,x,T);var o=S().getInt32(h+0,!0),i=S().getInt32(h+4,!0),l=S().getInt32(h+8,!0),u=S().getInt32(h+12,!0),f=o,d=i;if(u)throw f=0,d=0,M(l);return a=f,s=d,Pe(f,d)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(a,s,1)}}function oo(e,t,n){let r=ce(e,c.__wbindgen_export3),a=A,s=ce(t,c.__wbindgen_export3),o=A,i=ce(n,c.__wbindgen_export3),l=A;return c.wasm_ed25519_verify(r,a,s,o,i,l)!==0}function io(e,t,n,r,a){try{let l=c.__wbindgen_add_to_stack_pointer(-16),u=ce(e,c.__wbindgen_export3),f=A,d=ce(t,c.__wbindgen_export3),h=A,p=R(n,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=R(r,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=R(a,c.__wbindgen_export3,c.__wbindgen_export4),y=A;c.wasm_sealbox_wrap_to(l,u,f,d,h,p,_,g,w,m,y);var s=S().getInt32(l+0,!0),o=S().getInt32(l+4,!0),i=S().getInt32(l+8,!0);if(i)throw M(o);return M(s)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function lo(e,t,n,r){let a,s;try{let h=c.__wbindgen_add_to_stack_pointer(-16),p=R(e,c.__wbindgen_export3,c.__wbindgen_export4),_=A,g=R(t,c.__wbindgen_export3,c.__wbindgen_export4),w=A,m=R(n,c.__wbindgen_export3,c.__wbindgen_export4),y=A;c.wasm_summary_message(h,p,_,g,w,m,y,r);var o=S().getInt32(h+0,!0),i=S().getInt32(h+4,!0),l=S().getInt32(h+8,!0),u=S().getInt32(h+12,!0),f=o,d=i;if(u)throw f=0,d=0,M(l);return a=f,s=d,Pe(f,d)}finally{c.__wbindgen_add_to_stack_pointer(16),c.__wbindgen_export2(a,s,1)}}function co(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(e,c.__wbindgen_export3),u=A,f=ce(t,c.__wbindgen_export3),d=A,h=R(n,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=R(r,c.__wbindgen_export3,c.__wbindgen_export4),g=A;c.wasm_unwrap_file_key(i,l,u,f,d,h,p,_,g);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw M(s);return M(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function uo(e,t,n,r){try{let i=c.__wbindgen_add_to_stack_pointer(-16),l=ce(e,c.__wbindgen_export3),u=A,f=ce(t,c.__wbindgen_export3),d=A,h=R(n,c.__wbindgen_export3,c.__wbindgen_export4),p=A,_=R(r,c.__wbindgen_export3,c.__wbindgen_export4),g=A;c.wasm_wrap_file_key(i,l,u,f,d,h,p,_,g);var a=S().getInt32(i+0,!0),s=S().getInt32(i+4,!0),o=S().getInt32(i+8,!0);if(o)throw M(s);return M(a)}finally{c.__wbindgen_add_to_stack_pointer(16)}}function vr(){return{__proto__:null,"./seal_crypto_bg.js":{__proto__:null,__wbg___wbindgen_is_function_2f0fd7ceb86e64c5:function(t){return typeof j(t)=="function"},__wbg___wbindgen_is_object_5b22ff2418063a9c:function(t){let n=j(t);return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_eddc07a3efad52e6:function(t){return typeof j(t)=="string"},__wbg___wbindgen_is_undefined_244a92c34d3b6ec0:function(t){return j(t)===void 0},__wbg___wbindgen_throw_9c75d47bf9e7731e:function(t,n){throw new Error(Pe(t,n))},__wbg_call_a41d6421b30a32c5:function(){return ct(function(t,n,r){let a=j(t).call(j(n),j(r));return re(a)},arguments)},__wbg_crypto_38df2bab126b63dc:function(t){let n=j(t).crypto;return re(n)},__wbg_error_a6fa202b58aa1cd3:function(t,n){let r,a;try{r=t,a=n,console.error(Pe(t,n))}finally{c.__wbindgen_export2(r,a,1)}},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return ct(function(t,n){j(t).getRandomValues(j(n))},arguments)},__wbg_length_ba3c032602efe310:function(t){return j(t).length},__wbg_msCrypto_bd5a034af96bcba6:function(t){let n=j(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(gn(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=j(t).node;return re(n)},__wbg_process_44c7a14e11e9f69e:function(t){let n=j(t).process;return re(n)},__wbg_prototypesetcall_fd4050e806e1d519:function(t,n,r){Uint8Array.prototype.set.call(gn(t,n),j(r))},__wbg_randomFillSync_6c25eac9869eb53c:function(){return ct(function(t,n){j(t).randomFillSync(M(n))},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return ct(function(){let t=module.require;return re(t)},arguments)},__wbg_set_5337f8ac82364a3f:function(){return ct(function(t,n,r){return Reflect.set(j(t),j(n),j(r))},arguments)},__wbg_stack_3b0d974bbf31e44f:function(t,n){let r=j(n).stack,a=R(r,c.__wbindgen_export3,c.__wbindgen_export4),s=A;S().setInt32(t+4,s,!0),S().setInt32(t+0,a,!0)},__wbg_static_accessor_GLOBAL_THIS_1c7f1bd6c6941fdb:function(){let t=typeof globalThis>"u"?null:globalThis;return ut(t)?0:re(t)},__wbg_static_accessor_GLOBAL_e039bc914f83e74e:function(){let t=typeof global>"u"?null:global;return ut(t)?0:re(t)},__wbg_static_accessor_SELF_8bf8c48c28420ad5:function(){let t=typeof self>"u"?null:self;return ut(t)?0:re(t)},__wbg_static_accessor_WINDOW_6aeee9b51652ee0f:function(){let t=typeof window>"u"?null:window;return ut(t)?0:re(t)},__wbg_subarray_fbe3cef290e1fa43:function(t,n,r){let a=j(t).subarray(n>>>0,r>>>0);return re(a)},__wbg_versions_276b2795b1c6a219:function(t){let n=j(t).versions;return re(n)},__wbindgen_cast_0000000000000001:function(t,n){let r=gn(t,n);return re(r)},__wbindgen_cast_0000000000000002:function(t,n){let r=Pe(t,n);return re(r)},__wbindgen_object_clone_ref:function(t){let n=j(t);return re(n)},__wbindgen_object_drop_ref:function(t){M(t)}}}}var gr=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_contracttermsbuilder_free(e,1)),br=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>c.__wbg_wasmidentity_free(e,1));function re(e){ht===Ne.length&&Ne.push(Ne.length+1);let t=ht;return ht=Ne[t],Ne[t]=e,t}function ho(e){e<1028||(Ne[e]=ht,ht=e)}function gn(e,t){return e=e>>>0,qe().subarray(e/1,e/1+t)}var Ge=null;function S(){return(Ge===null||Ge.buffer.detached===!0||Ge.buffer.detached===void 0&&Ge.buffer!==c.memory.buffer)&&(Ge=new DataView(c.memory.buffer)),Ge}function Pe(e,t){return po(e>>>0,t)}var dt=null;function qe(){return(dt===null||dt.byteLength===0)&&(dt=new Uint8Array(c.memory.buffer)),dt}function j(e){return Ne[e]}function ct(e,t){try{return e.apply(this,t)}catch(n){c.__wbindgen_export(re(n))}}var Ne=new Array(1024).fill(void 0);Ne.push(void 0,null,!0,!1);var ht=Ne.length;function ut(e){return e==null}function ce(e,t){let n=t(e.length*1,1)>>>0;return qe().set(e,n/1),A=e.length,n}function R(e,t,n){if(n===void 0){let i=ft.encode(e),l=t(i.length,1)>>>0;return qe().subarray(l,l+i.length).set(i),A=i.length,l}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),l=ft.encodeInto(e,i);o+=l.written,a=n(a,r,o,1)>>>0}return A=o,a}function M(e){let t=j(e);return ho(e),t}var Bt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Bt.decode();var fo=2146435072,bn=0;function po(e,t){return bn+=t,bn>=fo&&(Bt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Bt.decode(),bn=t),Bt.decode(qe().subarray(e,e+t))}var ft=new TextEncoder;"encodeInto"in ft||(ft.encodeInto=function(e,t){let n=ft.encode(e);return t.set(n),{read:e.length,written:n.length}});var A=0,_o,wo,c;function Tr(e,t){return wo=e,c=e.exports,_o=t,Ge=null,dt=null,c}async function yo(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 go(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=vr();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Tr(n,e)}async function bo(e){if(c!==void 0)return c;if(e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0)throw new Error("SEAL crypto: the WASM source must be passed to the loader");let t=vr();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await yo(await e,t);return Tr(n,r)}var mo="seal_crypto.wasm",Ie=null,Ut=null,Xe=null;function Sn(e){if(Ut||Xe)throw new Error("configureWasm: the WASM is already loaded or loading");Ie=e}function xr(){return globalThis.navigator?.userAgent==="Cloudflare-Workers"}function Eo(){return typeof globalThis.process?.versions?.node=="string"&&!xr()}async function mr(e){{let t="node:fs/promises",{readFile:n}=await import(t);return n(e)}throw new Error("seal crypto core: this build reads no files (it is not for Node)")}async function So(){if(Ie&&"module"in Ie)return Ie.module;if(Ie&&"url"in Ie)return fetch(Ie.url,Ie.integrity?{integrity:Ie.integrity}:{});if(Ie&&"path"in Ie)return mr(Ie.path);if(Eo())return mr(new URL(mo,Ro.url));throw new Error(xr()?"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 pt(){if(Ut)return Ut;if(Xe)return Xe;Xe=(async()=>{let e=Ar;return await e.default({module_or_path:await So()}),typeof e.init=="function"&&e.init(),Ut=e,e})();try{return await Xe}catch(e){throw Xe=null,e}}var Er=32768,Sr=class extends Error{constructor(e,t){super(e),this.input=t,this.name="Base64DecodeError"}};function Ao(e){let t="";for(let n=0;n<e.length;n+=Er){let r=e.subarray(n,Math.min(n+Er,e.length));t+=String.fromCharCode.apply(null,r)}return t}function vo(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function To(e){let t=`${e.length} characters`;if(typeof atob<"u")try{return atob(e)}catch(n){throw new Sr(`Invalid base64 encoding: ${n.message}`,t)}try{return Buffer.from(e,"base64").toString("binary")}catch(n){throw new Sr(`Invalid base64 encoding: ${n.message}`,t)}}function xo(e){return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function ko(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+="=".repeat(n),t}function Io(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function De(e){return xo(Ao(e))}function ae(e){return Io(De(e))}function Ft(e){return vo(To(e))}function ue(e){return Ft(ko(e))}async function Oo(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 Oo(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 $t(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 An(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 kr(e,t){$t(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function _t(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Kt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Oe(e,t){return e<<32-t|e>>>t}function Lo(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function vn(e){return typeof e=="string"&&(e=Lo(e)),$t(e),e}var Wt=class{};function Ir(e){let t=r=>e().update(vn(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Co(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let a=BigInt(32),s=BigInt(4294967295),o=Number(n>>a&s),i=Number(n&s),l=r?4:0,u=r?0:4;e.setUint32(t+l,o,r),e.setUint32(t+u,i,r)}function Or(e,t,n){return e&t^~e&n}function Rr(e,t,n){return e&t^e&n^t&n}var Ht=class extends Wt{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=Kt(this.buffer)}update(t){An(this),t=vn(t),$t(t);let{view:n,buffer:r,blockLen:a}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(a-this.pos,s-o);if(i===a){let l=Kt(t);for(;a<=s-o;o+=a)this.process(l,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===a&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){An(this),kr(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:a,isLE:s}=this,{pos:o}=this;n[o++]=128,_t(this.buffer.subarray(o)),this.padOffset>a-o&&(this.process(r,0),o=0);for(let d=o;d<a;d++)n[d]=0;Co(r,a-8,BigInt(this.length*8),s),this.process(r,0);let i=Kt(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)i.setUint32(4*d,f[d],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()}},Me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var No=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]),We=new Uint32Array(64),Tn=class extends Ht{constructor(t=32){super(64,t,8,!1),this.A=Me[0]|0,this.B=Me[1]|0,this.C=Me[2]|0,this.D=Me[3]|0,this.E=Me[4]|0,this.F=Me[5]|0,this.G=Me[6]|0,this.H=Me[7]|0}get(){let{A:t,B:n,C:r,D:a,E:s,F:o,G:i,H:l}=this;return[t,n,r,a,s,o,i,l]}set(t,n,r,a,s,o,i,l){this.A=t|0,this.B=n|0,this.C=r|0,this.D=a|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=l|0}process(t,n){for(let d=0;d<16;d++,n+=4)We[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){let h=We[d-15],p=We[d-2],_=Oe(h,7)^Oe(h,18)^h>>>3,g=Oe(p,17)^Oe(p,19)^p>>>10;We[d]=g+We[d-7]+_+We[d-16]|0}let{A:r,B:a,C:s,D:o,E:i,F:l,G:u,H:f}=this;for(let d=0;d<64;d++){let h=Oe(i,6)^Oe(i,11)^Oe(i,25),p=f+h+Or(i,l,u)+No[d]+We[d]|0,g=(Oe(r,2)^Oe(r,13)^Oe(r,22))+Rr(r,a,s)|0;f=u,u=l,l=i,i=o+p|0,o=s,s=a,a=r,r=p+g|0}r=r+this.A|0,a=a+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,l=l+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,a,s,o,i,l,u,f)}roundClean(){_t(We)}destroy(){this.set(0,0,0,0,0,0,0,0),_t(this.buffer)}};var zt=Ir(()=>new Tn);var ve={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}},Dn=new Uint8Array(ve.magic_bytes),Xt=ve.magic_length,Ke=ve.header_length,Qe=ve.nonce_length,Mn=ve.tag_length,ca=ve.segment_overhead,da=ve.segment_size_bytes,Pr=ve.min_segment_size_bytes,Lr=ve.max_segment_size_bytes,yt=ve.header_layout.find(e=>e.name==="file_id"),Cr=ve.aad_layout.reduce((e,t)=>e+t.length,0),ua=new Uint8Array(ve.v3_reader.magic_bytes),ha=ve.v3_reader.header_length;function Do(e){return Qe+e+Mn}function Bn(e){let t=Math.max(1,Math.ceil(e/da));return Ke+t*ca+e}function Mo(){let e=new Uint8Array(Ke);return e.set(Dn,0),new DataView(e.buffer).setUint32(Xt,da,!0),e.set(crypto.getRandomValues(new Uint8Array(yt.length)),yt.offset),e}function qt(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function fa(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(Xt,!0);if(t<Pr||t>Lr)throw new Error(`segment size ${t} is outside ${Pr}\u2026${Lr}`);return t}function Un(e){if(e.length<Ke)throw new Error(`an AEON v4 header is ${Ke} bytes, got ${e.length}`);if(!qt(e,Dn))throw new Error("not an AEON v4 header");return{segmentSize:fa(e),fileId:e.slice(yt.offset,yt.offset+yt.length)}}function Bo(e){if(e.length<ha||!qt(e,ua))throw new Error("not an AEON v3 header");return{segmentSize:fa(e)}}function Uo(e){return qt(e,Dn)?"v4":qt(e,ua)?"v3":null}function pa(e,t,n){let r=new Uint8Array(Cr);return r.set(e.subarray(0,Ke),0),new DataView(r.buffer).setBigUint64(Ke,BigInt(t),!0),r[Cr-1]=n?1:0,r}function Fo(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function _a(e){let t=Fo(e);try{return crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{new Uint8Array(t).fill(0)}}async function Wo(e,t,n){let r=crypto.getRandomValues(new Uint8Array(Qe)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:Mn*8,additionalData:n},e,t),s=new Uint8Array(Qe+a.byteLength);return s.set(r,0),s.set(new Uint8Array(a),Qe),s}async function $o(e,t,n){let r={name:"AES-GCM",iv:t.subarray(0,Qe),tagLength:Mn*8};return n&&(r.additionalData=n),new Uint8Array(await crypto.subtle.decrypt(r,e,t.subarray(Qe)))}function Ko(){return zt.create()}async function gt(){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 Ho(){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},OTP_DIGITS:{alphabet:"0123456789",min_length: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,CLIENT_EVENT_STRING_MAX_CHARS:512,CLIENT_EVENT_MAX_BYTES:4096,CLIENT_EVENT_ID_MAX_CHARS:64,CLIENT_EVENT_COUNT_MAX:1e6}},wa={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). In the headers the value goes into `Authorization` (any scheme), the place's own `header:<name>`, and `headers`: the headers the service takes the key in beside its place (Google's SDKs send an API key as `x-goog-api-key`); a stand-in in any other header refuses the request (`off_place`). `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",headers:["x-goog-api-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"}}]},tt={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",code_unknown:"pair.code_unknown",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"}}},Ae={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. Only this inbox answers it: POST /intake/{id}/fulfil of a card carries this address's proof (X-Seal-Address, X-Seal-Proof), made on the inbox's side alone, and is refused intake.proof_required without it; GET /intake/{id} says so with asked_of_inbox, never naming the address"},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:{link:"<site>/i/<intake_id>#<the requester's address, 43 characters>: whoever asks writes its own address into the fragment, which never reaches the server; the page that answers takes the recipient_bundle the server hands it only as a bundle of that address (bundles.accept) and refuses any other, a fragment cut short too. A link without a fragment is of a client made before it named the requester: its page shows the bundle's words for the person to compare. An inbox that opens a request of its list writes into the fragment the address whose words the row showed. A request without `to` is answered by whoever holds its link; a card (`to`) only by the inbox it was asked of, on that inbox's own page, and seal.net sends a card's link there.",recipient_bundle:"POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it (against the address of its link, request.link) 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":"<the guard's address, 43>","from":"<the borrower's address, 43>"?,"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.",from:"Whose call it is, when the key is lent as use (\xA77.2, \xA77.3: the owner sees who asks): the address the key is lent to, whose guard dialled the owner's gateway. Absent in a question of a call of the owner's own programs, and from a guard before the field.",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"}]},zo="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,REFUSAL_WAIT_DEFAULT_MS:2e3,REFUSAL_WAIT_MAX_MS:1e4,VISIT_HEADER:"X-Seal-Visit",PROGRESS_SPEED_WINDOW_MS:2e4}},ya;function nt(e,t){return(ya??globalThis.fetch).call(globalThis,e,t)}function Go(){return ya!==void 0}var jc=2*1024*1024,jo=(ye.limits.INTAKE_WAIT_MAX_SECONDS+15)*1e3,Yc=Ae.proof.header_address,Vc=Ae.proof.header_proof,{RETRY_BACKOFF_MS:Nr,RETRY_JITTER_RATIO:Yo,MAX_STALL_MS:Dr}=C.upload,Vo=1e3,bt=3e4;function ga(e){return e>=500||e===408||e===429}async function ba(e,t,n,r){let a=new AbortController,s=()=>{a.abort(n.reason)};n.aborted?s():n.addEventListener("abort",s,{once:!0});let o=setTimeout(()=>{a.abort(new Error(`storage did not answer in ${bt} ms`))},bt);try{return await r(e,{...t,signal:a.signal})}catch(i){throw n.removeEventListener("abort",s),i}finally{clearTimeout(o)}}async function Xo(e,t,n,r=fetch){let a=await ba(e,t>0?{headers:{Range:`bytes=${t}-`}}:{},n,r);if(t>0&&a.ok&&a.status!==206){let s=new Error(`Storage ignored the resume range: ${a.status}`);throw s.terminal=!0,s}if(!a.ok){let s=new Error(`Fetch failed: ${a.status}`);s.terminal=!ga(a.status);let o=t===0?await a.json().catch(()=>{}):void 0;throw o&&typeof o=="object"&&Object.assign(s,{swCode:"API",status:a.status,body:o}),s}return a}function qo(e,t,n,r={}){if(!e.body)throw new Error("storage answered no body");let a=e.url||t,s=parseInt(e.headers.get("Content-Length")||"0",10),o={since:null,attempt:0},i=r.fetch??fetch,l=r.ended??(()=>{}),u=e.body.getReader(),f=0;return new ReadableStream({async pull(h){try{await d(h)}catch(p){throw l(),p}},cancel(){l(),n.abort()}});async function d(h){let p=0,_=Date.now();for(;;){if(Date.now()-_>bt)throw new Error(`Read timeout: stream stalled for ${bt}ms`);let g;try{if(g=await ei(u,bt),g.done&&f<s)throw new Error(`storage closed the body at ${f} of ${s}`)}catch(w){if(n.signal.aborted)throw w;let m=r.waiting??(()=>{}),y=await In(a,f,n.signal,o,w,m,i);if(!y.body)throw new Error("storage answered no body");u=y.body.getReader(),_=Date.now();continue}if(g.done){h.close(),l();return}if(g.value.length===0){if(++p>=Vo)throw new Error("Too many empty reads: stream may be corrupted");continue}o.since=null,o.attempt=0,f+=g.value.length,r.onBytes?.(g.value.length),h.enqueue(g.value);return}}}async function Zo(e,t,n){let r=new AbortController,a=()=>r.abort(t?.reason),s=()=>t?.removeEventListener("abort",a);t?.aborted?a():t?.addEventListener("abort",a,{once:!0});try{let o=await Jo(e,r.signal,n);if(!o.ok)return s(),o;let i=qo(o,e,r,{fetch:n,ended:s});return new Response(i,{status:o.status,statusText:o.statusText,headers:o.headers})}catch(o){throw s(),o}}async function Jo(e,t,n){let r={since:null,attempt:0},a;try{a=await ba(e,{},t,n)}catch(s){if(t.aborted)throw s;return In(e,0,t,r,s,()=>{},n)}return a.ok||!ga(a.status)?a:(await a.body?.cancel().catch(()=>{}),In(e,0,t,r,new Error(`storage answered ${a.status}`),()=>{},n))}async function In(e,t,n,r,a,s,o){let i=a;for(r.since===null&&(r.since=Date.now());;){if(n.aborted)throw i;if(Date.now()-r.since>=Dr){let f=new Error(`Download stalled for ${Dr/1e3} s: ${i.message}`);throw f.swCode="NETWORK",f.stalled=!0,f}let l=Nr[Math.min(r.attempt,Nr.length-1)]??0,u=1+(Math.random()*2-1)*Yo;if(s(),await Qo(l*u,n),n.aborted)throw n.reason??i;r.attempt++;try{return await Xo(e,t,n,o)}catch(f){let d=f;if(d.terminal)throw d.swCode="NETWORK",d;i=d}}}function Qo(e,t){return new Promise(n=>{let r=()=>{clearTimeout(a),t.removeEventListener("abort",r),n()},a=setTimeout(r,e);t.addEventListener("abort",r,{once:!0})})}function ei(e,t){return new Promise((n,r)=>{let a=setTimeout(()=>{e.cancel().catch(()=>{}),r(new Error(`storage sent nothing for ${t} ms`))},t);e.read().then(s=>{clearTimeout(a),n(s)},s=>{clearTimeout(a),r(s)})})}function ti(){try{return typeof process<"u"&&!0}catch{return!1}}var ni=(e,t,n,...r)=>{let a=`[${t}] ${n}`;switch(e){case"debug":ti()||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}},Gt=ni;function At(e){return{debug:(t,...n)=>Gt("debug",e,t,...n),info:(t,...n)=>Gt("info",e,t,...n),warn:(t,...n)=>Gt("warn",e,t,...n),error:(t,...n)=>Gt("error",e,t,...n)}}var k=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 ri(e,t){return Object.defineProperty(e,"session",{value:t,enumerable:!1,configurable:!0,writable:!0}),e}function Ve(e,t){return e instanceof k?e:e instanceof DOMException&&e.name==="AbortError"?new k("Upload aborted","ABORTED"):new k(e instanceof Error?e.message:t,"UNKNOWN")}async function et(e,t,n,r){let a=await jt(e,String(e.status));return new k(`${t}: ${a.message}`,e.status===426?"CLIENT_OUTDATED":n,e.status,r)}var ai=At("upload"),si={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)}},Fn={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:si};function Wn(e){return{...Fn,...e}}function On(e,t){return Math.max(t.putMinDeadlineMs,Math.ceil(e/t.putFloorBytesPerSecond*1e3))}var ma=()=>globalThis.AbortSignal;function $n(e){let t=ma()?.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 oi(e){let t=ma()?.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 Ea(e,t){let n=oi(t);return e?$n([e,n]):n}async function mt(e,t,n,r){try{return await nt(e,{...t,signal:Ea(r,n)})}catch(a){throw r?.aborted?new k("Upload aborted","ABORTED"):new k(`Request failed: ${a instanceof Error?a.message:String(a)}`,"NETWORK",void 0,void 0,!0)}}function Sa(e){return e===408||e===429||e>=500?"retryable":"terminal"}function Aa(e){return e.code==="ABORTED"?"terminal":e.code==="BAD_DIGEST"||e.httpStatus===void 0?"retryable":e.httpStatus===403?"refresh_url":Sa(e.httpStatus)}function va(e){return e.code==="ABORTED"?"terminal":e.httpStatus===void 0?"retryable":Sa(e.httpStatus)}var Kn=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 Hn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new k("Upload aborted","ABORTED"));return}let a=()=>{clearTimeout(s),r(new k("Upload aborted","ABORTED"))},s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);t?.addEventListener("abort",a,{once:!0})})}async function Et(e,t){let{clock:n,policy:r,signal:a,classify:s,what:o}=t,i,l=0;for(let u=0;;u++){if(a?.aborted)throw new k("Upload aborted","ABORTED");try{return await e({attempt:u,after:i})}catch(f){let d=Ve(f,`${o} failed`);if(d.code==="ABORTED")throw d;let h=s(d);if(h==="terminal")throw d;if(n.exhausted())throw new k(`${o}: no progress for ${Math.round(r.maxStallMs/1e3)} s \u2014 ${d.message}`,d.code,d.httpStatus,d.partNumber,!1);n.failed(),l=h==="refresh_url"?l+1:0;let p=h==="refresh_url"&&l===1,_=r.retryBackoffMs[Math.min(u,r.retryBackoffMs.length-1)]??0,g=1+(Math.random()*2-1)*r.retryJitterRatio,w=p?0:Math.round(_*g);ai.debug(`retry ${o} attempt=${u+2} in ${w}ms after ${d.code}${d.httpStatus?" "+d.httpStatus:""} (${h})`),i=h,await Hn(w,a)}}}var Rn;function Ta(e,t){Rn=`${e}/${t}`}var ii=()=>{};function Pn(){return{...Rn===void 0?{}:{[zo]:Rn},...ii()}}var F=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 li(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 jt(e,t){let n=await e.text().catch(()=>""),r,a,s,o,i;if(n)try{let l=JSON.parse(n);typeof l?.detail=="string"&&(r=l.detail),typeof l?.code=="string"&&(a=l.code),typeof l?.retry_after=="number"&&(s=l.retry_after),typeof l?.update=="string"&&(o=l.update),typeof l?.min_version=="string"&&(i=l.min_version)}catch{}return new F(r??t,li(e.status),e.status,{body:n||void 0,detail:r,appCode:a,retryAfter:s,update:o,minVersion:i})}function ci(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 di=C.upload.VISIT_HEADER;function ui(){return ae(crypto.getRandomValues(new Uint8Array(16)))}var xa=class{constructor(){this.id=ui(),this.open=!1,this.queue=Promise.resolve()}ask(e){if(this.open)return e(this.id);let t=this.queue.then(async()=>{let n=await e(this.id);return this.open=!0,n});return this.queue=t.catch(()=>{}),t}};function H(e){return encodeURIComponent(e)}var hi=typeof process<"u"&&typeof process.versions?.node=="string"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers",fi=tt.share_link.proof_header;async function Mr(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(tt.hkdf.identity_key_salt),info:t.encode(tt.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("")}}var vt=class ke{constructor(t){if(this.proofs=new Map,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??jo}async holdShareProof(t,n){this.proofs.set(t,(await Mr(n)).proof)}shareProofHeader(t){let n=/^\/seal\/([^/?]+)/.exec(t)?.[1],r=n?this.proofs.get(decodeURIComponent(n)):void 0;return r?{[fi]:r}:{}}fetchImpl(t,n){return this.injectedFetch?this.injectedFetch.call(globalThis,t,n):nt(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:{...Pn(),...this.shareProofHeader(t),...a.headers},credentials:a.credentials??this.credentials,signal:a.signal?$n([a.signal,s.signal]):s.signal})}finally{clearTimeout(o)}if(a.redirect==="manual"&&i.status>=300&&i.status<400&&i.headers.has("location"))return i;if(!i.ok)throw await jt(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=${H(n.shareCode)}`:"";return await(await this.request(`/seal/${H(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/${H(t)}/share/${H(n)}`,{what:a,signal:r.signal}),o=await s.json();return{blob:Fr(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/${H(t)}/otp`,{what:`POST /seal/${t}/otp`,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:r.signal}),o=wi(s,n.fileId?`otp_${t}_${n.fileId}`:`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/${H(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/${H(t)}/download?${Br(n)}`)}async openDownload(t,n,r={}){let a=n.ownerToken?ke.ownerHeaders(n.ownerToken):{};n.sessionCookie&&(a.Cookie=n.sessionCookie),n.visit&&(a[di]=n.visit);for(let s=0;;s++)try{let o=await this.request(`/seal/${H(t)}/download?${Br(n)}`,{what:`GET /seal/${t}/download?file_id=${n.fileId}`,headers:a,signal:r.signal,...hi?{redirect:"manual"}:{}}),i=o.status>=300&&o.status<400?o.headers.get("location"):null;return i===null?o:await this.stored(i,r.signal)}catch(o){if(!(o instanceof F&&o.appCode==="file.not_ready"&&r.retryNotReady!==!1&&s<C.upload.NOT_READY_MAX_RETRIES))throw o;await _i((o.retryAfter??pi)*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 F(`GET /seal/${t}/download answered no storage URL`,"transient",502);return this.stored(s,r.signal)}async stored(t,n){let r=await Zo(t,n,(a,s)=>this.fetchImpl(a,s));if(!r.ok)throw await jt(r,`storage download failed: ${r.status}`);return r}async getOwnerSeal(t,n,r={}){return await(await this.request(`/seal/${H(t)}/owner`,{what:`GET /seal/${t}/owner`,headers:ke.ownerHeaders(n),signal:r.signal})).json()}async readOwnerBlob(t,n={}){let r=await this.request(`/seal/${H(t)}/blob`,{what:`GET /seal/${t}/blob`,signal:n.signal}),a=r.headers.get("ETag");return{blob:Fr(await r.json(),`GET /seal/${t}/blob`,r.status),etag:a}}async writeOwnerBlob(t,n,r,a={}){let s=ke.ownerHeaders(n,!0);a.ifMatch&&(s["If-Match"]=a.ifMatch);let o={encrypted_blob:r};return Ur(a,o,s),{etag:(await this.request(`/seal/${H(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"}:ke.ownerHeaders(n,!0),i={encrypted_blob:r,proof_hash:(await Mr(a)).hash};s.fileIds&&(i.file_ids=s.fileIds),Ur(s,i,o);let l=await this.request(`/seal/${H(t)}/share`,{what:`POST /seal/${t}/share`,method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal}),u=await l.json();if(typeof u.share_code!="string"||!u.share_code)throw new F(`POST /seal/${t}/share returned no share_code`,"unknown",l.status);return u.share_code}async revokeShareLink(t,n,r,a={}){await this.request(`/seal/${H(t)}/share/${H(n)}/revoke`,{what:`POST /seal/${t}/share/${n}/revoke`,method:"POST",headers:r===null?{}:ke.ownerHeaders(r),signal:a.signal})}async revoke(t,n,r={}){let a;try{a=await this.request(`/seal/${H(t)}/revoke`,{what:`POST /seal/${t}/revoke`,method:"POST",headers:ke.ownerHeaders(n),signal:r.signal})}catch(o){if(o instanceof F&&(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/${H(t)}/files/${H(n)}/revoke`,{what:`POST /seal/${t}/files/${n}/revoke`,method:"POST",headers:ke.ownerHeaders(r),signal:a.signal})}async getAudit(t,n,r={}){return await(await this.request(`/seal/${H(t)}/audit`,{what:`GET /seal/${t}/audit`,headers:ke.ownerHeaders(n),signal:r.signal})).json()}async openAuditDownload(t,n,r={}){return this.request(`/seal/${H(t)}/audit/download`,{what:`GET /seal/${t}/audit/download`,headers:ke.ownerHeaders(n),signal:r.signal})}async createSubscription(t,n,r={},a={}){let s=await this.request(`/seal/${H(t)}/subscriptions`,{what:`POST /seal/${t}/subscriptions`,method:"POST",headers:ke.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 F(`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:ke.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 F("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?Je(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/${H(t)}${r}`,{what:`GET /intake/${t}`,signal:n.signal})).json()}async fulfilIntake(t,n,r={}){return await(await this.request(`/intake/${H(t)}/fulfil`,{what:`POST /intake/${t}/fulfil`,method:"POST",headers:{"Content-Type":"application/json",...this.shareProofHeader(`/seal/${H(n.sealId)}`),...r.inbox?Je(r.inbox):{}},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/${H(t)}`,{what:`GET /intake/bundles/${t}`,signal:n.signal});return ue((await r.json()).bundle)}catch(r){if(r instanceof F&&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:Je(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:Je(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",...Je(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/${H(t)}/revoke`,{what:`POST /lease/${t}/revoke`,method:"POST",headers:ke.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:{...Pn(),...r},body:JSON.stringify({ids:t}),credentials:this.credentials,signal:n.signal});if(a.status===304)return null;if(!a.ok)throw await jt(a,`POST /lease/status failed: ${a.status}`);return{statuses:await a.json(),etag:a.headers.get("ETag")}}},pi=3;function Je(e){return{[Ae.proof.header_address]:e.address,[Ae.proof.header_proof]:e.proof}}function Br(e){let t=new URLSearchParams({file_id:e.fileId});return e.shareCode&&t.set("share_code",e.shareCode),t.toString()}function Ur(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,Je(e.sender)))}function _i(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 Fr(e,t,n){if(typeof e.encrypted_blob!="string"||e.encrypted_blob.length===0)throw new F(`${t} returned an empty blob`,"unknown",n);return ue(e.encrypted_blob)}function wi(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 yi=32,gi=32,Zt=ye.limits.MAX_BLOB_SIZE,Wr=ye.limits.MAX_FILE_KEYS;function ka(e){if(e>Wr)throw new Error(`Too many file keys: ${e} exceeds maximum of ${Wr}`)}var bi=class extends Error{constructor(){super("Invalid encryption key"),this.name="BlobDecryptionError"}};function Ia(){return crypto.getRandomValues(new Uint8Array(yi))}async function Oa(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 zn(){return crypto.getRandomValues(new Uint8Array(gi))}var Xc=wa.wildcard_public_second_level;async function Ra(e,t,n,r,a,s,o){ka(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 La(i,n)}async function Pa(e,t,n,r,a,s,o){ka(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 La(i,t)}async function La(e,t){let n=new TextEncoder().encode(JSON.stringify(e)),r=12+n.length+16;if(r>Zt)throw new Error(`Blob size ${r} exceeds maximum of ${Zt}`);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 mi(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha256_hex=="string"&&typeof t.name=="string"}function Ei(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 Si(e){return typeof e.bindings!="object"||e.bindings===null?{}:Object.fromEntries(Object.entries(e.bindings).filter(([,t])=>Ei(t)))}function Ai(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 vi(e,t){let n=await Ti(e,t);if(!Ai(n))throw new Error("Invalid share blob structure");return n}async function Ti(e,t){if(e.length>Zt)throw new Error(`Blob size ${e.length} exceeds maximum of ${Zt}`);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 bi}try{return JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("Invalid JSON in decrypted blob")}}var Jc=ye.limits.MAX_FILE_KEYS;var $e=64,$r=[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],xi=new Int32Array(64).map((e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)|0),ki=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function Kr(e,t,n){let r=e[0],a=e[1],s=e[2],o=e[3];for(let i=0;i<64;i++){let l,u;i<16?(l=a&s|~a&o,u=i):i<32?(l=o&a|~o&s,u=5*i+1&15):i<48?(l=a^s^o,u=3*i+5&15):(l=s^(a|~o),u=7*i&15);let f=r+l+xi[i]+t[n+u]|0;r=o,o=s,s=a,a=a+(f<<$r[i]|f>>>32-$r[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 Gn=class{constructor(){this.state=new Int32Array([1732584193,-271733879,-1732584194,271733878]),this.pending=new Uint8Array($e),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($e-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,r),this.pendingLength),this.pendingLength+=r,t=r,this.pendingLength<$e)return this;this.compressBytes(this.pending,0,$e),this.pendingLength=0}let n=e.length-(e.length-t)%$e;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?$e:2*$e);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(ki&&(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)Kr(this.state,a,s);return}let r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=t;a<n;a+=$e){for(let s=0;s<16;s++)this.scratch[s]=r.getInt32(a+s*4,!0);Kr(this.state,this.scratch,0)}}};function Ii(e){return De(new Gn().update(e).digest())}var xn=4*1024*1024;async function Oi(e){let t=new Gn;for(let n=0;n<e.length;n+=xn)t.update(e.subarray(n,Math.min(n+xn,e.length))),n+xn<e.length&&await gt();return De(t.digest())}var Ca=class{constructor(e){if(this.cryptoKey=null,e.key.length!==32)throw new Error("Key must be 32 bytes (AES-256)");this.segmentSize=Un(e.header).segmentSize,this.header=e.header.subarray(0,Ke),this.key=e.key}async init(){this.cryptoKey=await _a(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 Wo(this.cryptoKey,n,pa(this.header,e,t))}};async function Ri(e,t,n,r){let a=new Uint8Array(t);try{let s=new Ca({key:a,header:n});await s.init();let o=new Gn().update(s.header),i=[Hr(s.header)],l=Math.max(1,Math.ceil(e.size/s.segmentSize));for(let u=0;u<l;u++){let f=Math.min((u+1)*s.segmentSize,e.size),d=new Uint8Array(await e.slice(u*s.segmentSize,f).arrayBuffer()),h=await s.encryptSegment(u,u===l-1,d);d.fill(0),o.update(h),i.push(Hr(h)),r?.(f,e.size)}return{blob:new Blob(i),md5_b64:De(o.digest())}}finally{a.fill(0)}}function Hr(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var Be=class extends Error{constructor(e,t,n){super(t),this.name="DecryptError",this.kind=e,this.cause=n}};function Pi(e,t){e.chunks.push(t),e.bytes+=t.length}function Yt(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 Li(e,t){let n=Yt(e,t);return e.chunks.unshift(n),e.bytes+=t,n}function Ci(e,t){let n=t.expectedSha256Hex.trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Be("integrity","the expected sha256_hex is not 64 hex characters");let r={chunks:[],bytes:0},a,s=null,o=null,i=0,l=0,u=null,f=async(h,p)=>{if(h.length<ca)throw new Be("integrity",`segment ${l} is ${h.length} bytes: the stream was cut`);try{return await $o(a,h,o==="v4"?pa(s,l,p):null)}catch(_){throw new Be("integrity",`segment ${l} does not decrypt as the ${p?"last":"next"} segment of this file: moved, cut, extended or changed`,_)}finally{l+=1}},d=async()=>{if(r.bytes<Xt)return!1;let h=Uo(Li(r,Xt));if(h===null)throw new Be("outdated","the file is in a format newer than this client: update it");let p=h==="v4"?Ke:ha;if(r.bytes<p)return!1;if(h==="v3"){u=Ko();for(let w of r.chunks)u.update(w)}let _=Yt(r,p),g;try{g=h==="v4"?Un(_).segmentSize:Bo(_).segmentSize}catch(w){throw new Be("integrity",w instanceof Error?w.message:String(w),w)}if(h==="v4"&&await Ze(_)!==n)throw new Be("integrity","the file header is not the one registered for this file");return s=_,o=h,i=Do(g),!0};return new TransformStream({async start(){a=await _a(e)},async transform(h,p){if(h.length!==0&&(Pi(r,h),u&&u.update(h),!(o===null&&!await d())))for(;r.bytes>i;){let _=Yt(r,i),g=await f(_,!1);_.fill(0),t.onPlaintextBytes?.(g.length),p.enqueue(g)}},async flush(h){if(o===null)throw new Be("integrity",r.bytes===0?"the ciphertext stream is empty":"the ciphertext stream was cut inside its header");if(o==="v3"){if(Array.from(u.digest(),g=>g.toString(16).padStart(2,"0")).join("")!==n)throw new Be("integrity","the ciphertext is not the one registered for this file");if(r.bytes===0)return}let p=await f(Yt(r,r.bytes),!0);t.onPlaintextBytes?.(p.length),h.enqueue(p)}},{highWaterMark:1},{highWaterMark:1})}var td=At("SwDownload");var nd=10*6e4;var Na={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"}},Ni="_",Di=200,Mi=new TextEncoder;function Ln(e){return Mi.encode(e).length}function zr(e,t){let n="",r=0;for(let a of e){if(r+=Ln(a),r>t)break;n+=a}return n}var Bi=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 Ui(){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 Wi(e){let t=e.split(".")[0].toUpperCase();return Bi.has(t)}function Jt(e,t={}){let{platform:n=Ui(),replacement:r=Ni,maxLength:a=Di,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(u=>Fi(u,n)?u:r).join("");let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(o=o.replace(new RegExp(`${l}+`,"g"),r),o=o.replace(new RegExp(`^(?:\\.|${l})+|${l}+$`,"g"),""),(n==="windows"||n==="unknown")&&Wi(o)&&(o=`${r}${o}`),Ln(o)>a){let u=o.lastIndexOf(".");if(u>0&&u>o.length-10){let f=o.slice(u);o=zr(o.slice(0,u),a-Ln(f))+f}else o=zr(o,a)}return!o||o===r?s:o}function Da(e,t={}){let n=e.split(/[\\/]/).filter(r=>r!==""&&r!=="."&&r!=="..");return n.length===0?[Jt("",t)]:n.map(r=>Jt(r,t))}var $i=new Map(Object.entries(Na.extensions));function Ki(e){let t=e.lastIndexOf("."),n=t>=0&&t<e.length-1?e.slice(t+1).toLowerCase():"";return $i.get(n)??Na.default}var rd=C.upload.INMEMORY_BLOB_LIMIT_BYTES;var ad=new TextEncoder;var sd=At("FolderZip");var od=C.upload.INMEMORY_BLOB_LIMIT_BYTES,id=4*1024*1024;var Hi=new WeakMap;function Ma(e){return Hi.get(e)??(e.webkitRelativePath||void 0)}var Qt="Encrypted file",en="application/octet-stream";function Ba(e){return new TextEncoder().encode(`field:${e}`)}async function Gr(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=Ba(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:De(new Uint8Array(o)),nonce:De(r)}}async function jr(e,t,n,r){let a=Ft(e),s=Ft(t);return(async i=>{let l={name:"AES-GCM",iv:s};i&&(l.additionalData=i);let u=await crypto.subtle.decrypt(l,n,a);return new TextDecoder().decode(u)})(r?Ba(r):void 0)}async function zi(e,t){let n=Qt,r=en,a=!1;if(e.name_encrypted&&e.name_nonce&&e.name_nonce.length>0)try{n=await jr(e.name_encrypted,e.name_nonce,t,"name")}catch{n=Qt}if(e.mime_encrypted&&e.mime_nonce&&e.mime_nonce.length>0)try{r=await jr(e.mime_encrypted,e.mime_nonce,t,"mime"),a=!0}catch{r=en}return{name:n,mime:r,mimeRead:a}}async function Gi(e){return crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!1,["decrypt"])}async function ji(e,t){try{let n=await Gi(t);return zi(e,n)}catch{return{name:Qt,mime:en,mimeRead:!1}}}var Yi=At("upload"),wt=4*1024*1024;function tn(){return new DOMException("Upload aborted","AbortError")}async function Vi(e){let{stream:t,totalBytes:n,key:r,header:a,partSize:s,signal:o,yieldToRenderer:i,onSegment:l}=e,u=new Ca({key:r,header:a});await u.init();let f=u.segmentSize,d=Math.max(1,Math.ceil(n/f)),h=0,p=v=>new k(`The file changed while it was being sent: ${v} ${h} of ${n} bytes`,"FILE_CHANGED"),_=!0,g=0,w=0,m=[],y=0,x=v=>{if(m.length>0&&m[0].length===v)return y-=v,m.shift();let N=new Uint8Array(v),se=0;for(;se<v;){let Y=m[0],V=v-se;Y.length<=V?(N.set(Y,se),se+=Y.length,m.shift()):(N.set(Y.subarray(0,V),se),m[0]=Y.subarray(V),se+=V)}return y-=v,N},T=[],D=0,B=async v=>{let N=new Uint8Array(v),se=0,Y=0;for(;se<v;){let V=T[0],me=i?wt-Y:Number.MAX_SAFE_INTEGER,X=Math.min(V.length,v-se,me);N.set(V.subarray(0,X),se),se+=X,Y+=X,X===V.length?T.shift():T[0]=V.subarray(X),i&&Y>=wt&&se<v&&(Y=0,await gt())}return D-=v,N},P=async v=>{if(w+=1,e.hashParts===!1)await e.onPart(w,v);else{let N=i?await Oi(v):Ii(v);await e.onPart(w,v,N)}i&&await gt()},Q=async v=>{if(!i){v.fill(0);return}for(let N=0;N<v.length;N+=wt)v.fill(0,N,Math.min(N+wt,v.length)),N+wt<v.length&&await gt()},pe=async()=>{for(;D>=s;)await P(await B(s))},I=async(v,N)=>{if(o?.aborted)throw tn();let se=g;g+=1;let Y=performance.now(),V=u.encryptSegment(se,N,v);await pe();let me=await V;await Q(v),Yi.debug(`encrypt segment=${g} bytes=${v.length} time=${Math.round(performance.now()-Y)}ms`);let X;_?(X=new Uint8Array(a.length+me.length),X.set(a,0),X.set(me,a.length),_=!1):X=me,l?.(g),T.push(X),D+=X.length},K=t.getReader();try{for(;;){if(o?.aborted)throw tn();let{done:v,value:N}=await K.read();if(v)break;if(N&&N.length>0){if(h+=N.length,h>n)throw p("it gave more than");m.push(N),y+=N.length}for(;y>=f;)await I(x(f),g===d-1)}if(h<n)throw p("it ended at");(y>0||g===0)&&await I(x(y),!0),await pe(),D>0&&await P(await B(D))}finally{K.releaseLock()}}function Xi(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 qi(e,t,n){let{file:r,key:a,header:s,partSize:o,totalBytes:i,signal:l,initialCredits:u,onSegment:f,onPart:d}=n;return new Promise((h,p)=>{let _=!1,g=!1,w=0,m=Promise.resolve(),y=B=>{_||(_=!0,p(B))},x=()=>{!g||w>0||m.then(()=>{_||(_=!0,h())})};if(l){if(l.aborted){y(tn());return}l.addEventListener("abort",()=>y(tn()),{once:!0})}e.onerror=t.onerror=B=>{y(new Error(`crypto worker crashed: ${String(B?.message??B)}`))},e.onmessage=B=>{let P=B.data;if(P.type==="segment"){f?.(P.segmentNumber);return}if(P.type==="part"){w+=1,t.postMessage({type:"md5",partNumber:P.partNumber,buffer:P.buffer},[P.buffer]);return}if(P.type==="done"){g=!0,x();return}P.type==="error"&&y(new Error(P.message))},t.onmessage=B=>{let P=B.data;if(P.type!=="md5")return;w-=1;let Q=new Uint8Array(P.buffer);m=m.then(async()=>{_||(await d(P.partNumber,Q,P.md5),e.postMessage({type:"credit"}))}).catch(y),x()};let T=new ArrayBuffer(a.length);new Uint8Array(T).set(a);let D=s.slice().buffer;e.postMessage({type:"start",file:r,key:T,header:D,partSize:o,totalBytes:i,credits:u},[T,D])})}var Zi=null;function Ji(){return Zi}var je=At("upload");function Qi(e){return e.now-e.lastLookAt>2*e.every?!1:e.now-e.lastActivityAt>=e.silenceMs}var Yr="<Code>BadDigest</Code>",el=2;function sn(e){let t=Pn();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 tl(e){return nl({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 nl(e){let{file:t,partSize:n}=e;return rl({stream:Xi(t,Un(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 rl(e){let{stream:t,totalBytes:n,sealId:r,fileId:a,key:s,header:o,baseUrl:i,auth:l,partSize:u,contentType:f="application/octet-stream",onProgress:d,signal:h,sourceFile:p,onStreamed:_,onConflict:g}=e,w=Wn(e.transport),m=w.clock;if(s.length!==32)throw new k("Key must be 32 bytes","ENCRYPTION_FAILED");if(u<C.upload.S3_MIN_PART_SIZE_BYTES)throw new k(`Part size must be at least ${C.upload.S3_MIN_PART_SIZE_BYTES} bytes (S3 spec)`,"INVALID_STATUS");let y=new Uint8Array(s),x=sn(l),T=Bn(n),D=Math.ceil(T/u),B=null,P=[],Q=0,pe=0,I="encrypting",K=[],v=null,N,se=b=>{let E=m.now();K.push({at:E,bytes:b});let O=Math.max(v??E,E-w.speedWindowMs);for(;K.length>0&&K[0].at<O;)K.shift();let U=E-O;U>0&&(N=Math.round(K.reduce((L,te)=>L+te.bytes,0)/U*1e3))},Y=b=>{I=b;let E=T-Q;d?.({phase:b,percent:b==="done"?100:Math.min(99,Math.floor(Q/T*100)),deliveredBytes:Q,preparedBytes:pe,totalBytes:T,speedBps:N,etaMs:N&&N>0?Math.round(E/N*1e3):void 0,state:V.state,attempt:V.retriesSinceDelivery+1})},V=new Kn(w,()=>Y(I),m.now),me=new AbortController,X=h?$n([h,me.signal]):me.signal,rt=(b,E)=>Et(E,{clock:V,policy:w,signal:X,classify:va,what:b}),ee=async b=>{throw y.fill(0),new k("Upload aborted","ABORTED")},Te=b=>{if(B)try{nt(`${i}/upload/multipart/abort`,{method:"POST",headers:{"Content-Type":"application/json",...x},body:JSON.stringify(b?{upload_id:B,discard_file:!0}:{upload_id:B}),keepalive:!0}).catch(()=>{})}catch{}},oe=!1,Ee=new Map,ie=null,z=null,_e=[],xe=new Set,ge=w.poolStart,It=w.poolMax,Ot=0,ze=null,Rt=0,Pt=0,at=null,_n=[],hr=[],st=new Set,ot=m.now(),fr=!1,wn=b=>{ot=m.now();for(let E of[...st])E.reconnect(b)};function Ns(b,E){let O=b.ciphertext.length;if(O>=u&&E>0){let te=Math.min(b.flowsAtStart??1,xe.size);if(hr.push({rate:O/E,flows:te}),O/E*1e3<w.putFloorBytesPerSecond*2&&ge>w.poolMin){ge-=1,It=ge,at=null,Ot+=1,ze=m.now(),Rt=0,Pt=0;return}}if(b.round!==Ot||(Rt+=O,Pt+=1,Pt<ge||ze===null))return;let U=m.now()-ze;if(U<=0)return;let L=Rt/U;at===null||L>at*w.poolGrowRatio?ge=Math.min(It,ge+1):L<at*w.poolShrinkRatio&&(ge=Math.max(Math.min(w.poolStart,It),ge-1)),at=L,Ot+=1,ze=m.now(),Rt=0,Pt=0}function Ds(b,E){let O=m.now()-E;if(O<w.hedgeMinInflightMs)return!1;let U=xe.size,L=hr.filter(q=>q.flows>=U).map(q=>q.rate);if(L.length===0)return!1;L.sort((q,G)=>q-G);let te=L[Math.floor(L.length/2)];return b.ciphertext.length/O*w.hedgeLagFactor<te}async function Ms(b,E,O,U,L,te){if(!Go()&&typeof XMLHttpRequest<"u"&&typeof document<"u")return await new Promise((G,we)=>{let Z=new XMLHttpRequest,de=!1;fr=!0,Z.upload.onprogress=be=>{te.onSocketActivity(be.loaded,be.lengthComputable?be.total:b.length),ne(),ne=Re()};let Re=()=>m.after(On(b.length,w),()=>{de||te.onDeadline()}),ne=Re(),J=()=>{ne(),L.removeEventListener("abort",le)},le=()=>{de||(de=!0,Z.abort(),J(),we(new k("Upload aborted","ABORTED",void 0,O)))};if(Z.onload=()=>{if(de)return;de=!0;let be={status:Z.status,etag:Z.getResponseHeader("ETag")?.replace(/"/g,"")??null,badDigest:Z.status===400&&String(Z.responseText??"").includes(Yr)};J(),G(be)},Z.onerror=()=>{de||(de=!0,J(),we(new k(`Failed to upload part ${O}: network error`,"NETWORK",void 0,O,!0)))},Z.onabort=()=>{de||(de=!0,J(),we(new k("Upload aborted","ABORTED",void 0,O)))},L.aborted){J(),we(new k("Upload aborted","ABORTED",void 0,O));return}L.addEventListener("abort",le,{once:!0}),Z.open("PUT",U),Z.setRequestHeader("Content-MD5",E),Z.send(b)});let q;try{q=await nt(U,{method:"PUT",headers:{"Content-MD5":E},body:b,signal:Ea(L,On(b.length,w))})}catch(G){throw h?.aborted||L.aborted?Ve(G,"Upload aborted"):new k(`Part ${O}: transport failure (${G instanceof Error?G.message:String(G)})`,"NETWORK",void 0,O,!0)}return{status:q.status,etag:q.headers.get("ETag")?.replace(/"/g,"")??null,badDigest:q.status===400&&(await q.text().catch(()=>"")).includes(Yr)}}function Bs(b,E){if(E.badDigest)throw new k(`Part ${b} arrived corrupted (BadDigest)`,"BAD_DIGEST",E.status,b,!0);if(E.status<200||E.status>=300)throw new k(`Failed to upload part ${b}: ${E.status}`,E.status===404?"EXPIRED_UPLOAD_ID":"NETWORK",E.status,b,E.status!==404);if(!E.etag)throw new k(`No ETag returned for part ${b}`,"S3_ETAG_MISMATCH",void 0,b);return E.etag}async function Us(b,E){let O=m.now(),U=()=>{},L=0,te=0,q=O,G=null,we=()=>{},Z={reconnect:de=>we(de,!1),hasUnsentBytes:()=>G?.unsent??!1};st.add(Z);try{let de=await new Promise((ne,J)=>{let le=!1,be=Fe=>{le||(le=!0,Fe())},wr=()=>{let Fe=new AbortController,it=()=>Fe.abort();X?.aborted?Fe.abort():X?.addEventListener("abort",it,{once:!0});let Le={ctl:Fe,unsent:!0,ended:Promise.resolve()};G=Le,q=m.now(),ot=q,Le.ended=Ms(b.ciphertext,b.contentMd5,b.partNumber,E,Fe.signal,{onSocketActivity:(Ce,lt)=>{ot=m.now(),Le.unsent=Ce<lt},onDeadline:()=>{if(++te<2)return we("copy deadline",!1,!1);G===Le&&be(()=>J(new k(`Part ${b.partNumber}: no answer from storage after a reconnect`,"NETWORK",void 0,b.partNumber,!0)))}}).then(Ce=>{if(G===Le)try{let lt=Bs(b.partNumber,Ce);be(()=>ne(lt))}catch(lt){be(()=>J(lt))}},Ce=>{G===Le&&be(()=>J(Ve(Ce,`Failed to upload part ${b.partNumber}`)))}).finally(()=>{Le.unsent=!1,X?.removeEventListener("abort",it)})};we=(Fe,it,Le=!0)=>{let Ce=G;le||Ce===null||h?.aborted||(G=null,L=it?L+1:Le?0:L,je.debug(`${it?"replace":"reconnect"} part=${b.partNumber} (${Fe})`),Ce.ctl.abort(),Ce.ended.then(()=>{le||(X?.aborted?be(()=>J(new k("Upload aborted","ABORTED",void 0,b.partNumber))):wr())}))},wr(),U=m.every(w.hedgePollMs,()=>{le||h?.aborted||G===null||L>=el||Ds(b,q)&&we(`slower than its peers after ${Math.round(m.now()-O)}ms`,!0)})}),Re=m.now();P.push({part_number:b.partNumber,etag:de}),Q+=b.ciphertext.length,se(b.ciphertext.length),Ns(b,Re-O),V.delivered(),ot=Re,je.debug(`part=${b.partNumber}/${D} put=${Math.round(Re-O)}ms size=${b.ciphertext.length}${L>0?` replaced\xD7${L}`:""}`),Y("uploading")}finally{st.delete(Z),we=()=>{},U(),G?.ctl.abort()}}let Lt=(b,E,O)=>mt(b,E,O,X);async function Fs(){try{let b=await Lt(`${i}/upload/multipart/status?upload_id=${encodeURIComponent(B??"")}`,{method:"GET",headers:x},w.controlTimeoutMs);if(!b.ok)return null;let E=await b.json();return typeof E.status=="string"?E.status:null}catch{return null}}async function pr(b){let E=performance.now(),O=await rt("presign batch",async()=>{let L=await Lt(`${i}/upload/multipart/parts`,{method:"POST",headers:{"Content-Type":"application/json",...x},body:JSON.stringify({upload_id:B,part_numbers:b})},w.controlTimeoutMs);if(!L.ok)throw await et(L,"Failed to get presigned URLs",L.status===404?"EXPIRED_UPLOAD_ID":"NETWORK");let{urls:te}=await L.json();return te}),U=new Map;for(let[L,te]of Object.entries(O))U.set(Number(L),te);return je.debug(`batch presign ${b.length} urls in ${Math.round(performance.now()-E)}ms`),U}async function Ws(b){let E=[];for(let U=b;U<=D&&E.length<C.upload.PRESIGN_BATCH_SIZE;U++)Ee.has(U)||E.push(U);if(E.length===0)return;let O=await pr(E);for(let[U,L]of O)Ee.set(U,L)}function _r(b){ie||(ie=Ws(b).catch(()=>{}).finally(()=>{ie=null}))}async function $s(b){await gt(),ze??(ze=m.now()),v??(v=ze),b.round=Ot,b.flowsAtStart=xe.size;let E=Ee.get(b.partNumber);!E&&ie&&(await ie,E=Ee.get(b.partNumber)),Ee.delete(b.partNumber),_r(b.partNumber+1),await Et(async({after:O})=>{if((!E||O==="refresh_url")&&(E=(await pr([b.partNumber])).get(b.partNumber),!E))throw new k(`No presigned URL for part ${b.partNumber}`,"NETWORK",void 0,b.partNumber,!0);await Us(b,E)},{clock:V,policy:w,signal:X,classify:Aa,what:`part ${b.partNumber}`})}function yn(){for(;!z&&!h?.aborted&&xe.size<ge&&_e.length>0;){let b=_e.shift(),E=$s(b).catch(O=>{z??(z=Ve(O,"Part upload failed"))}).finally(()=>{xe.delete(E);let O=_n;_n=[];for(let U of O)U();yn()});xe.add(E)}}let Ks=()=>new Promise(b=>{_n.push(b)}),Hs=(()=>{let b=globalThis,E=globalThis.navigator?.connection,O=E?.type,U=()=>wn("network is back"),L=()=>V.connectionLost(),te=()=>{let Z=E?.type;Z!==O&&(O=Z,wn("network changed"))};b.addEventListener?.("online",U),b.addEventListener?.("offline",L),E?.addEventListener?.("change",te);let q=Math.max(10,w.livenessSilenceMs/4),G=m.now(),we=m.every(q,()=>{let Z=m.now(),de=Qi({now:Z,lastLookAt:G,every:q,lastActivityAt:ot,silenceMs:w.livenessSilenceMs});G=Z,!(!fr||st.size===0||!de)&&[...st].some(Re=>Re.hasUnsentBytes())&&(V.connectionLost(),wn("every socket silent"))});return()=>{we(),b.removeEventListener?.("online",U),b.removeEventListener?.("offline",L),E?.removeEventListener?.("change",te)}})();try{let b=performance.now();if(je.debug(`starting multipart: totalBytes=${n} parts=${D} partSize=${u} pool=${w.poolStart}..${w.poolMax}`),h?.aborted)throw new k("Upload aborted","ABORTED");Y("encrypting"),B=await rt("multipart init",async()=>{let ne=await Lt(`${i}/upload/multipart/init`,{method:"POST",headers:{"Content-Type":"application/json",...x},body:JSON.stringify({seal_id:r,content_type:f,content_length:T,part_size:u,file_id:a})},w.controlTimeoutMs);if(!ne.ok)throw await et(ne,"Failed to initialize multipart upload","NETWORK");return(await ne.json()).upload_id}),_r(1),Y("encrypting");let E=!1,O=()=>{E=!0,Y("encrypting")},U=async(ne,J,le)=>{for(E=!0,pe+=J.length,Y("encrypting"),h?.aborted&&await ee(h?.aborted===!0),_e.push({partNumber:ne,ciphertext:J,contentMd5:le}),yn();_e.length>=w.partQueueLimit;)if(await Ks(),z)throw z;if(z)throw z},L=()=>Vi({stream:t,totalBytes:n,key:y,header:o,partSize:u,signal:h,yieldToRenderer:typeof document<"u",onSegment:O,onPart:U}),te=Ji(),q=null;if(p&&te&&typeof document<"u"){let ne=null;try{ne=te(),q=[ne,te()]}catch{ne?.terminate()}}if(q){let[ne,J]=q;je.debug("crypto pipeline: worker");try{await qi(ne,J,{file:p,key:y,header:o,partSize:u,totalBytes:n,signal:h,initialCredits:w.partQueueLimit,onSegment:O,onPart:U})}catch(le){let be=Ve(le,"Crypto worker failed");if(be.code==="ABORTED"||E)throw be;je.debug(`crypto worker failed before output \u2014 inline fallback (${be.message})`),await L()}finally{ne.terminate(),J.terminate()}}else await L();for(;yn(),!(z||(h?.aborted&&await ee(!0),xe.size===0&&_e.length===0));)await Promise.race(xe);if(z)throw z;Y("verifying"),h?.aborted&&await ee(h?.aborted===!0),oe=!0,_?.();let G=!1,we,Z=await rt("complete",async()=>{let ne=G;G=!0;let J=await Lt(`${i}/upload/multipart/complete`,{method:"POST",headers:{"Content-Type":"application/json",...x},body:JSON.stringify({upload_id:B,parts:P.map(le=>({part_number:le.part_number,etag:le.etag})),...g?{on_conflict:g}:{}})},w.completeTimeoutMs);if(J.ok){let le=await J.json().catch(()=>null);return typeof le?.conflict_with=="string"&&(we=le.conflict_with),le?.status==="verified"}if(ne&&J.status===400&&await Fs()==="completed")return!1;throw await et(J,"Failed to complete multipart upload",J.status===404?"EXPIRED_UPLOAD_ID":"INVALID_STATUS")});V.delivered(),Y("done");let de=Math.round(performance.now()-b),Re=n/(1024*1024)/(de/1e3);return je.debug(`DONE totalTime=${de}ms speed=${Re.toFixed(2)}MB/s parts=${P.length}`),y.fill(0),{verified:Z,...we?{conflictWith:we}:{}}}catch(b){y.fill(0);let E=Ve(b,"Unknown upload error");throw oe&&E.code!=="ABORTED"&&(E.httpStatus===void 0||E.httpStatus>=500)||Te(E.code==="ABORTED"),E}finally{Hs(),V.dispose(),me.abort()}}var He={multipartThresholdBytes:C.upload.MULTIPART_THRESHOLD_BYTES,partSizeBytes:C.upload.DEFAULT_PART_SIZE_BYTES,zipSmallLimitBytes:C.upload.INMEMORY_BLOB_LIMIT_BYTES};function al(e,t=He){return e<=C.upload.FINE_PART_MAX_FILE_BYTES?C.upload.FINE_PART_SIZE_BYTES:t.partSizeBytes}function Ua(e,t){return e>=t.multipartThresholdBytes}function sl(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 jn(e){return e.ownerToken?{type:"ownerToken",value:e.ownerToken}:sl(e.auth)}function ol(e){return e.ownerToken?e.ownerToken:e.auth.kind==="ownerToken"?e.auth.value:void 0}var il={encrypting:[0,30],uploading:[30,95],verifying:[95,99],done:[100,100]},Vr=[2,12],ll=[12,95],cl=[95,99];function Xr(e,t){let n=0;return r=>{let a=Math.min(1,Math.max(0,r.fraction)),s;e==="single-put"?s=il[r.phase]:r.phase==="done"?s=[100,100]:r.phase==="verifying"?s=cl:r.deliveredBytes===0?s=Vr:s=ll;let o=s===Vr?Math.min(1,Math.max(0,r.preparedFraction??0)):a,i=s[0]+(s[1]-s[0])*o,l=r.phase==="done"?100:Math.min(99,Math.round(i));n=Math.max(n,l),t({phase:r.phase,percent:n,deliveredBytes:r.deliveredBytes,preparedBytes:r.preparedBytes,totalBytes:r.totalBytes,speedBps:r.speedBps,etaMs:r.etaMs,state:r.state,attempt:r.attempt})}}var Yn=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 k("Upload session was cancelled","ABORTED");return this.running??(this.running=this.run(this,e).catch(t=>{throw ri(Ve(t,"Upload failed"),this)}).finally(()=>{this.running=null})),this.running}async cancel(){this.cancelled=!0;let e=ol(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 nt(`${this.ctx.baseUrl}${a}`,{method:"DELETE",headers:sn(jn(this.ctx)),credentials:this.ctx.credentials??"include"}).catch(()=>{})}return}let t=new vt({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 dl(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 ul(e){return e>=200&&e<300||e===204}async function hl(e){let{ctx:t,sealId:n,fileId:r,ciphertext:a,authHeaders:s,onVerifying:o,label:i,signal:l,clock:u,transport:f}=e,d=` for ${i}`,h={"Content-Type":"application/json",...s},p=t.credentials??"include",_=(x,T)=>Et(T,{clock:u,policy:f,signal:l,classify:va,what:x}),g=()=>_(`initiate${d}`,async()=>{let x=await mt(`${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,l);if(x.status===409)return null;if(!x.ok)throw await et(x,`Upload initiate failed${d}`,"NETWORK");let T=await x.json();return T.already_verified?null:T}),w=await g();if(w===null)return!1;let m=!1;if(await Et(async({after:x})=>{if(x==="refresh_url"){let B=await g();if(B===null){m=!0;return}w=B}let{upload_url:T}=w,D=await mt(T,{method:"PUT",body:a.blob,headers:{"Content-Type":"application/octet-stream","Content-MD5":a.md5_b64}},On(a.blob.size,f),l);if(D.status===400&&(await D.clone().text().catch(()=>"")).includes("<Code>BadDigest</Code>"))throw new k(`Upload arrived corrupted (BadDigest)${d}`,"BAD_DIGEST",400,void 0,!0);if(!ul(D.status))throw new k(`Upload PUT failed${d}: ${D.status}`,"NETWORK",D.status)},{clock:u,policy:f,signal:l,classify:Aa,what:`PUT${d}`}),m)return!1;u.delivered(),o();let y=await _(`confirm${d}`,async()=>{let x=await mt(`${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,l);if(x.status===409)return!1;if(!x.ok)throw await et(x,`Upload confirm failed${d}`,"NETWORK");let T=await x.json().catch(()=>null);return typeof T?.conflict_with=="string"&&e.onConflictWith(T.conflict_with),T?.status==="verified"});return u.delivered(),y}async function Fa(e,t,n,r,a,s){try{let o=await mt(`${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"?null:{status:i.status,conflictWith:typeof i.conflict_with=="string"?i.conflict_with:null}}catch(o){if(o instanceof k&&o.code==="ABORTED")throw o;return null}}var fl=new Set(["failed","size_mismatch","verification_error"]),pl=new Set(["verified","pending_verification"]);async function _l(e){let{ctx:t,sealId:n,digest:r,authHeaders:a,transport:s,signal:o,label:i,onConflictWith:l}=e,u=s.verifyFallbackWaitMs,f=performance.now(),d=s.verifyPollBackoffMs;for(let h=0;;h++){let p=d[Math.min(h,d.length-1)]??0;if(performance.now()-f+p>u)return"pending";p>0&&await Hn(p,o);let _=await Fa(t,n,r,a,s,o),g=_?.status??null;if(g==="verified")return _?.conflictWith&&l(_.conflictWith),"verified";if(g!==null&&fl.has(g))throw new k(`The server rejected ${i} after upload (${g}). It has to be sent again.`,"VERIFICATION_REJECTED");if(g===null&&h===0)return"pending"}}async function wl(e,t,n={}){let{ctx:r,policy:a,sealId:s}=e,{file:o,key:i,fileId:l}=t,{onProgress:u,signal:f}=n;if(t.state!=="pending")return;if(f?.aborted)throw new k("Upload aborted","ABORTED");let d=jn(r),h=sn(d),p=Wn(a.transport),_=async P=>{if(t.state=P?"verified":"uploaded",!P)try{await _l({ctx:r,sealId:s,digest:t.sha256_hex,authHeaders:h,transport:p,signal:f,label:o.name,onConflictWith:pe=>{t.conflictWith??(t.conflictWith=pe)}})==="verified"&&(t.state="verified")}catch(Q){throw Q instanceof k&&Q.code==="VERIFICATION_REJECTED"&&(t.state="pending",t.prepared=void 0,t.streamed=void 0),Q}};if(Ua(o.size,a)){if(t.streamed){let v=await Fa(r,s,t.sha256_hex,h,p,f);if(v!==null&&pl.has(v.status)){v.conflictWith&&(t.conflictWith??(t.conflictWith=v.conflictWith)),await _(v.status==="verified");return}}let P=Xr("multipart",v=>u?.(v)),Q=null,pe=await tl({file:o,sealId:s,fileId:l,key:i,header:t.header,baseUrl:r.baseUrl,auth:d,partSize:al(o.size,a),onProgress:v=>{Q=v;let N=v.phase==="done";P({...v,phase:N?"verifying":v.phase,fraction:N?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=pe.conflictWith,await _(pe.verified);let I=t.encryptedSize;P({...Q??{phase:"done",percent:100,deliveredBytes:I,totalBytes:I,state:"running",attempt:1},phase:"done",fraction:1});return}let g=Xr("single-put",P=>u?.(P)),w=t.encryptedSize,m={phase:"encrypting",fraction:0,delivered:!1},y=null,x=(P,Q,pe=m.delivered)=>{m={phase:P,fraction:Q,delivered:pe},g({phase:P,fraction:Q,deliveredBytes:pe?w:0,totalBytes:w,state:y?.state??"running",attempt:(y?.retriesSinceDelivery??0)+1})};t.prepared||(x("encrypting",0),t.prepared=await Ri(o,i,t.header,P=>x("encrypting",o.size>0?P/o.size:1)));let T=t.prepared,D=new Kn(p,()=>x(m.phase,m.fraction));y=D,x("uploading",0);let B;try{B=await hl({ctx:r,sealId:s,fileId:l,ciphertext:T,authHeaders:h,onVerifying:()=>x("verifying",0,!0),label:o.name,signal:f,clock:D,transport:p,onConflictWith:P=>{t.conflictWith=P}})}finally{D.dispose()}x("verifying",.5,!0),await _(B),t.prepared=void 0,x("done",1,!0)}async function yl(e,t={}){let{signal:n,onFileProgress:r}=t,a=h=>Ua(h.file.size,e.policy),s=e.pending,o=s.filter(h=>!a(h)),i=s.filter(a),l=new AbortController,u=()=>l.abort();n?.aborted?l.abort():n?.addEventListener("abort",u,{once:!0});let f=null,d=async h=>{try{await wl(e,h,{signal:l.signal,onProgress:p=>r?.(h,p)})}catch(p){f===null&&(f=p,l.abort())}};try{let h=0,p=async()=>{for(;f===null&&!l.signal.aborted&&h<o.length;)await d(o[h++])};await Promise.all(Array.from({length:Math.min(C.upload.SMALL_FILE_POOL,o.length)},p));for(let _ of i){if(f!==null||l.signal.aborted)break;await d(_)}}finally{n?.removeEventListener("abort",u)}if(f!==null)throw f;if(n?.aborted)throw new k("Upload aborted","ABORTED")}function gl(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 bl(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 ml(e,t,n,r,a={}){let s=await Gr(a.relativePath??e.name,t,"name"),o=await Gr(e.type||Ki(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:ve.current_format_version};return a.parentFolderId&&(i.parent_folder_id=a.parentFolderId),a.supersedes&&(i.supersedes=a.supersedes,i.layout="whole"),i}async function El(e,t,n,r,a){if(n?.aborted)throw new k("Upload aborted","ABORTED");let s=nt(e,t);return new Promise((o,i)=>{let l=!1,u=p=>{l||(l=!0,h(),i(p),s.then(async _=>_.ok?r(await _.json()):void 0).catch(()=>{}))},f=()=>u(new k("Upload aborted","ABORTED")),d=setTimeout(()=>u(new k(`The registration got no answer in ${Math.round(a/1e3)} s`,"NETWORK",void 0,void 0,!0)),a),h=()=>{clearTimeout(d),n?.removeEventListener("abort",f)};n?.addEventListener("abort",f,{once:!0}),s.then(p=>{l||(l=!0,h(),o(p))},p=>{l||(l=!0,h(),i(p))})})}function Sl(e){return Wn(e.transport).completeTimeoutMs}async function Al(e,t,n,r){try{return dl(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 vl(e,t){if(t?.aborted)throw await e.cancel(),new k("Upload aborted","ABORTED")}async function Tl(e,t,n,r,a){let s={files_meta:t};e.ownerTokenHash&&(s.owner_token_hash=e.ownerTokenHash),bl(s,e);let o=await El(`${e.baseUrl}/seal`,{method:"POST",headers:{"Content-Type":"application/json",...sn(jn(e))},credentials:e.credentials??"include",body:JSON.stringify(s)},n,r,a);if(!o.ok)throw await et(o,"Create seal failed","UNKNOWN");return await o.json()}async function xl(e,t){let n=Mo();return{file:e,key:t,header:n,sha256_hex:await Ze(n)}}async function kl(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 Il(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:Bn(n.file.size),state:"pending"}))}function Wa(e){let t=new Map;for(let n of e)t.set(n.sha256_hex,n.key);return t}function Ol(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(u=>n.get(u.index)===100),i=e.reduce((u,f)=>u+f.file.size*(n.get(f.index)??0),0),l=t>0?Math.floor(i/t):100;return r=Math.max(r,o?100:Math.min(99,l)),{percent:r,finished:o}}}}async function Rl(e,t){let{onProgress:n,signal:r}=t,a=e.files,s=Ol(a);await yl(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 $a(e,t,n,r,a){if(t.length===0)throw new Error("At least one file is required");gl(e);let s=await Promise.all(t.map(({file:d})=>xl(d,Ho()))),o=await Promise.all(s.map((d,h)=>ml(d.file,d.key,Bn(d.file.size),d.sha256_hex,{relativePath:t[h].relativePath}))),i=(d,h)=>new Yn({ctx:e,policy:n,sealId:d.id,createdSeal:!0,expiresAt:d.expires_at,files:h},async(p,_)=>(await Rl(p,_),a(p))),l=await Tl(e,o,r.signal,d=>i(d,[]).cancel(),Sl(n)),u=await Al(l.files,s.map(d=>d.sha256_hex),`Create seal ${l.id}`,()=>i(l,[]).cancel()),f=i(l,Il(s,u));return await vl(f,r.signal),await kl(r,l.id,s,u),f.resume(r)}async function Ka(e,t,n=He,r={}){return $a(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:Wa(a.files),expiresAt:a.expiresAt,verification:a.verification}))}async function Ha(e,t,n,r=He,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,l)=>({file:i,relativePath:s?.[l]||i.webkitRelativePath||`${n}/${i.name}`}));return $a(e,o,r,a,i=>({sealId:i.sealId,files:i.files.map(l=>({fileId:l.fileId,sha256_hex:l.sha256_hex,encryptedSize:l.encryptedSize,relativePath:o[l.index].relativePath})),encryptionKeys:Wa(i.files),folderName:n,expiresAt:i.expiresAt,verification:i.verification}))}var qr=[2e3,4e3,8e3,15e3],kn=ye.limits.TIER_BYTES,cd=Object.keys(kn).filter(e=>e!=="free").sort((e,t)=>kn[e]-kn[t]);function za(e){return e instanceof k&&e.httpStatus===402&&e.session?e.session:null}function Ga(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 ja(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 F&&o.code!=="transient"&&o.code!=="rate_limited")throw o}let s=qr[Math.min(a,qr.length-1)];if(Date.now()+s>r.deadline)return null;await Hn(s,r.signal)}}async function Ya(e,t,n,r={}){let a;try{a=await e.getOwnerSeal(t,n,r)}catch{return"unanswered"}return a.tier&&a.tier!=="free"?a:"unpaid"}var on=ye.limits.ttl_options;var Va={version:1,name:"COUNTRIES",description:"The countries a seal may name to open from (`geo`): the two-letter codes the country database writes for a reader's network (DB-IP Lite, backend_core/geo.py: ISO 3166-1 and XK), and the old names of a country written as its code of today (`written_as`: UK is GB). The server compares a reader's country with a seal's list exactly, so it writes the list this one way when the seal is made (`SealCreate.geo`) and refuses a code that is not here; the TS clients read a typed list by the same data (the protocol package's `countryCodes`). Not here, on purpose: groupings and pseudo-regions a network is never in (EU, UN, ZZ, XA, XB, QO, EZ) and the places ISO reserves for a part of a country whose network is that country's (AC, CP, CQ, DG, EA, IC, TA). Data, no code: a new country is one entry.",codes:["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"],written_as:{AN:"CW",BU:"MM",CS:"RS",CT:"KI",DD:"DE",DY:"BJ",FQ:"AQ",FX:"FR",HV:"BF",JT:"UM",MI:"UM",NH:"VU",NQ:"AQ",NT:"SA",PC:"FM",PU:"UM",PZ:"PA",RH:"ZW",SU:"RU",TP:"TL",UK:"GB",VD:"VN",WK:"UM",YD:"YE",YU:"RS",ZR:"CD"}};function Xa(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 Zr=ye.limits.OTP_DIGITS;function qa(e){return e.length>0&&e.length<Zr.min_length&&Array.from(e).every(t=>Zr.alphabet.includes(t))}var Pl=new Set(Va.codes),Ll=new Map(Object.entries(Va.written_as));function Za(e){let t=[],n=[];for(let r of e.split(/[\s,;]+/)){if(r==="")continue;let a=r.toUpperCase(),s=Ll.get(a)??a;Pl.has(s)?t.includes(s)||t.push(s):n.push(r)}return{codes:t,bad:n}}var Vn=8,Xn=43,Cn=4,ln=/^[A-Za-z0-9_-]+$/;function Cl(e,t){if(!ln.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 qn(e){return e.length===Vn&&ln.test(e)}function Zn(e){return e.length===Xn&&Cl(e,32)}function Ja(e,t){if(!qn(e))throw new Error(`Invalid sealId: must be ${Vn} base64url characters`);if(!Zn(t))throw new Error(`Invalid linkKey: must be ${Xn} base64url characters (32 bytes)`);return`/s/${e}#${t}`}function Qa(e,t,n){if(!qn(e))throw new Error(`Invalid sealId: must be ${Vn} base64url characters`);if(t.length!==Cn||!ln.test(t))throw new Error(`Invalid shareCode: must be ${Cn} base64url characters`);if(!Zn(n))throw new Error(`Invalid linkKey: must be ${Xn} base64url characters (32 bytes)`);return`/s/${e}/${t}#${n}`}var Vt=class extends Error{constructor(e,t){super(t),this.name="ShareUrlError",this.code=e}};function Nl(e){let t;try{t=new URL(e)}catch{throw new Vt("url_invalid",`not a valid URL (${e.length} characters)`)}let n;try{n=Dl(t.pathname.replace(/\/+$/,""))}catch{throw new Vt("url_invalid",`expected [/<lang>]/s/<seal_id>[/<share_code>] path (got a path of ${t.pathname.length} characters)`)}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 Vt("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 Dl(e){let t=e.match(/^(?:\/[a-z]{2})?\/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(!qn(n))throw new Error("Invalid sealId in URL");if(r&&(r.length!==Cn||!ln.test(r)))throw new Error("Invalid shareCode in URL");return{sealId:n,shareCode:r}}var Jn=Ae.scopes.share_link,es=Ae.scopes.owner_copy;var Jr=tt.sealed_box_v2.version_byte,Qr=tt.sealed_box_v2.packed_length,St=64,nn=32,ea=32;var ts=/^[A-Za-z0-9_-]+$/;function ns(){return crypto.getRandomValues(new Uint8Array(St))}async function Qn(e,t=1){let n=await pt();if(e.length===St)return n.WasmIdentity.fromSeed64(e,t);if(e.length===nn)return n.WasmIdentity.fromSeed32(e);throw new Error(`a seed is ${St} bytes, or the ${nn} of a key made before, got ${e.length}`)}async function er(e,t=1){let n=await Qn(e,t);try{return{bundle:n.bundle(),address:n.address(),words:n.words()}}finally{n.free()}}function rs(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(!ts.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 as(e,t){return(await pt()).wasm_bundle_verify_for_address(e,t)}async function cn(e){let{address:t,words:n}=(await pt()).wasm_bundle_address(e);return{bundle:e,address:t,words:n}}function tr(e,t,n){return`${e}/i/${t}#${n}`}async function dn(e,t,n,r){if(e.length!==ea)throw new Error(`a wrapped key is ${ea} 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 pt()).wasm_sealbox_wrap_to(e,t.bundle,t.address,n,r))}var Ye=class extends Error{constructor(e,t,n){super(t),this.name="WrapError",this.kind=e,this.cause=n}};async function Ml(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(!ts.test(e))throw new Ye("parse","the wrap is not urlsafe-base64-no-pad");let s=ue(e);if(s[0]!==Jr)throw new Ye("parse",`the wrap is not a sealed box v${Jr}: a newer client made it \u2014 update this one`);if(s.length!==Qr)throw new Ye("parse",`the wrap is ${s.length} bytes, expected ${Qr}`);if(t.length!==St&&t.length!==nn)throw new Ye("parse",`a seed is ${St} bytes, or the ${nn} of a key made before, got ${t.length}`);let o=await Qn(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 Bl(e,t){let n=await Qn(e);try{let r=n.inboxProof(BigInt(t.ts),ue(t.challenge));return`${t.ts}.${t.challenge}.${ae(r)}`}finally{n.free()}}var Nn={version:2,name:"FINGERPRINT_WORDS",description:"Eight words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3): 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 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=Nn.words,Fl=/^[A-Za-z0-9_-]{43}$/;function ss(e){if(!Fl.test(e))throw new Error(`an address is 43 base64url characters, got ${e.length}`);let t=ue(e);return Array.from(t.subarray(0,Nn.count),n=>Ul[n]).join(Nn.separator)}var os=Ae.payloads.pair.mime,ud=Ae.payloads.device.mime,hd=Ae.payloads.delivery.mime,fd=Ae.payloads.approve.mime,pd=Ae.payloads.approve_answer.mime,_d=Ae.payloads.summary.mime,is=Ae.pair_what,ta=Ae.payloads.name_max,wd=ye.limits.APPROVE_BODY_SHOWN_BYTES;var na=tt.keybundle.packed_length,ra=2;var Wl=/^[A-Za-z0-9_-]+$/;function ls(e){let t=$l(e,"pairing");if(typeof t.bundle!="string"||!Wl.test(t.bundle))throw new Error("pairing bundle is not base64url");return{bundle:Kl(ue(t.bundle)),name:Hl(t.name)}}function $l(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!==ra)throw new Error(`${t} payload is not version ${ra}`);return n}function Kl(e){if(e.length!==na)throw new Error(`a bundle is ${na} bytes, got ${e.length}`);return e}function Hl(e){if(typeof e!="string"||e.length===0||e.length>ta)throw new Error(`name must be 1 to ${ta} characters`);return e}var zl=["seal.revoked","seal.expired","seal.not_found","seal.blocked","geo.restricted","client.outdated"],Gl={"file.revoked":"taken","file.verification_failed":"rejected","single_use.exhausted":"spent","seal.revoked":"gone","seal.expired":"gone","seal.not_found":"gone","seal.blocked":"gone"},un=wa.mime,aa=e=>e.appCode==="seal.expired";function sa(e){return!(e instanceof F)||e.appCode!=="client.outdated"?null:new W("client_outdated",[e.detail??"the server no longer serves this client",e.update].filter(Boolean).join(": "),e)}var W=class extends Error{constructor(e,t,n,r){super(t),this.name="OpenError",this.code=e,this.cause=n,r&&(this.countries=r)}},jl=new Set(zl),Yl=new Set(["taken","rejected","spent","gone"]),gd=Object.fromEntries(Object.entries(Gl).filter(e=>Yl.has(e[1])));function nr(e){return e?.stalled===!0?"seal":e instanceof F?e.status===451||e.status===426||e.appCode!==void 0&&jl.has(e.appCode)?"seal":e.status===429||e.status>=500?"transient":"file":"file"}function cs(e){let{REFUSAL_WAIT_DEFAULT_MS:t,REFUSAL_WAIT_MAX_MS:n}=C.upload,r=e instanceof F?e.retryAfter:void 0;return r===void 0?t:Math.min(r*1e3,n)}var Vl=32;async function rr(e,t,n={}){let r;try{r=Nl(t)}catch(y){throw y instanceof Vt?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??(r.fragmentVariant!=="key"&&o?await Xl(e,o,a,s,n.signal):null),l=r.fragmentVariant==="key"?ue(r.fragment):i!==null&&o?await oa(i,o,a):null;l!==null&&await e.holdShareProof(a,l);let u=n.signal?{signal:n.signal}:{},f;try{f=await e.getMetadata(r.sealId,{...u,shareCode:s})}catch(y){let x=sa(y);if(x)throw x;if(y instanceof F&&(y.code==="not_found"||y.code==="revoked")){let T=y.code==="revoked"&&!aa(y);throw new W(T?"seal_revoked":"seal_not_found",`seal ${r.sealId} ${T?"has been revoked":"was not found or has expired"}`,y)}throw new W("metadata_failed",`reading seal ${r.sealId} failed: ${an(y)}`,y)}let d=ci(f);if(d.revokedAt!==null)throw new W("seal_revoked",`seal ${r.sealId} has been revoked`);if(f.spent===!0)throw new W("seal_spent",`seal ${r.sealId}: every open it allows is taken, nothing of it opens any more`);if(f.gone===!0)throw new W("seal_revoked",`seal ${r.sealId}: nothing in it is left to open; ask its sender to send it again`);if(d.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,u);if(h=y.blob,l===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");l=await oa(y.wrap,o,a),await e.holdShareProof(a,l)}}catch(y){if(y instanceof W)throw y;let x=sa(y);if(x)throw x;if(y instanceof F&&y.appCode==="geo.restricted"){let T=f.geo_allowlist??[];throw new W("geo_restricted",`seal ${a} opens only from networks in ${T.join(", ")||"its sender's countries"}, and the server does not place this one there`,y,T)}if(y instanceof F&&(y.code==="not_found"||y.code==="revoked")){let T=y.code==="revoked"&&!aa(y);throw new W(T?"share_link_revoked":"share_link_not_found",`share link ${a}/${s} ${T?"has been revoked":"was not found or has expired"}`,y)}throw new W("share_blob_fetch_failed",`share blob fetch failed: ${an(y)}`,y)}let p,_,g,w;try{let y=await vi(h,l);p=y.file_keys,_=Si(y),g=y.message?.trim()?y.message:null,w=mi(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 m=await Promise.all(d.files.map(y=>tc(y,p,_)));return{sealId:a,shareCode:s,expiresAt:d.expiresAt,singleUse:d.singleUse,maxOpens:d.maxOpens,otpRequired:d.otpRequired,ndaRequired:d.ndaRequired,otpPassed:f.otp_session_valid===!0,ndaPassed:f.nda_session_valid===!0,countries:f.geo_allowlist?.length?f.geo_allowlist:null,message:g,ndaFile:w,linkKey:l,files:m}}async function Xl(e,t,n,r,a){try{return(await fn(e,t,a?{signal:a}:{})).items.find(o=>o.path===`/s/${n}/${r}`)?.fragment??null}catch(s){if(a?.aborted)throw s;return null}}async function oa(e,t,n){try{return await Ml(e,t,Jn,n)}catch(r){let a=r instanceof Ye&&r.kind==="aead";throw new W(a?"targeted_decrypt_failed":"targeted_fragment_invalid",an(r),r)}}async function ds(e,t,n={}){let r=new Kn(Fn);try{for(;;){n.signal?.throwIfAborted();let a=Date.now(),s;try{s=await ql(e,t,n,r)}catch(i){throw i instanceof F&&i.code==="not_found"?new W("request_expired","the request expired before anybody answered",i):i}if(s.status==="expired")throw new W("request_expired","nobody answered before the request expired");if(s.status==="fulfilled"){if(s.share_path&&s.fragment)return{sharePath:s.share_path,wrap:s.fragment};throw new W("share_blob_corrupt","the request was answered without its link")}if(s.status!=="pending")throw new W("client_outdated",`the request is ${String(s.status)}, a state this client does not know`);let o=Zl-(Date.now()-a);o>0&&await ar(o,n.signal)}}finally{r.dispose()}}async function ql(e,t,n,r){let a;try{let s=await Et(async()=>{try{return await e.getIntake(t,{...n,waitSeconds:ye.limits.INTAKE_WAIT_MAX_SECONDS})}catch(o){a=o;let i=o instanceof F?o.status===408||o.status===429||o.status>=500:!n.signal?.aborted;throw new k(an(o),i?"NETWORK":"UNKNOWN")}},{clock:r,policy:Fn,signal:n.signal,classify:o=>o.code==="NETWORK"?"retryable":"terminal",what:`GET /intake/${t}`});return r.delivered(),s}catch(s){throw n.signal?.throwIfAborted(),a??s}}var Zl=2e3;function ar(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 ia=64*1024;async function us(e,t,n,r){let a=await rr(e,t,r),[s,...o]=a.files;if(!s?.key||!s.sha256Hex||o.length>0||fs(s.mime)!==n||s.size>ia)throw new W("share_blob_corrupt",`the answer is not one ${n} file`);return Jl(e,{sealId:a.sealId,shareCode:null},s,{maxBytes:ia,...r.signal?{signal:r.signal}:{}})}async function Jl(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=sr(a.body,n.key,n.sha256Hex).stream.getReader(),o=[];for(let u=await s.read();!u.done;u=await s.read())o.push(u.value);let i=new Uint8Array(o.reduce((u,f)=>u+f.length,0)),l=0;for(let u of o)i.set(u,l),l+=u.length;return i}var Ql=3e4,la=new Map;async function ec(e,t,n){let r=await e.getBundle(t.address,n);r!==null&&ac(r,t.bundle)||await e.putBundle(t.bundle,n)}async function rn(e,t,n={}){let r=await er(t),a=`${e.baseUrl} ${r.address}`,s=la.get(a);if(!n.fresh&&s&&s.until>Date.now())return s.proof;await ec(e,r,n);let o=await e.requestAddressProof(r.address,n),i={address:r.address,proof:await Bl(t,o)};return la.set(a,{proof:i,until:Date.parse(o.expires_at)-Ql}),i}async function hn(e,t,n,r){let a=n?{signal:n}:{};try{return await r(await rn(e,t,a))}catch(s){if(!(s instanceof F&&s.appCode==="intake.proof_required"))throw s;return r(await rn(e,t,{...a,fresh:!0}))}}async function fn(e,t,n={}){let r=n;return hn(e,t,n.signal,a=>e.listInbox(a,r))}async function hs(e,t,n,r={}){return hn(e,t,r.signal,a=>e.dismissInboxItem(n,a,r))}async function tc(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:Qt,mime:en,secret:!1,key:null,binding:null};let s;try{s=ue(r)}catch(d){throw new W("share_blob_corrupt",`share blob carries a non-base64url key for ${e.sha256_hex}`,d)}if(s.length!==Vl)throw new W("share_blob_corrupt",`share blob key for ${e.sha256_hex} is ${s.length} bytes`);let{name:o,mime:i,mimeRead:l}=await ji(e,s),u=!l||fs(i)===un,f=u&&e.sha256_hex?n[e.sha256_hex]??null:null;return{...a,name:o,mime:i,secret:u,key:s,binding:f}}function fs(e){return(e.split(";")[0]??e).trim().toLowerCase()}function sr(e,t,n,r=()=>{}){let a=new Uint8Array(t),s=zt.create(),o=0,i,l=new Promise((h,p)=>{i={resolve:h,reject:p}});l.catch(()=>{});let u=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:rc(s.digest())})}}),d=e.pipeThrough(u).pipeThrough(Ci(a,{expectedSha256Hex:n})).pipeThrough(f);return{stream:sc(d,i.reject,a),done:l}}function nc(e){return e instanceof Be?new W(e.kind==="outdated"?"client_outdated":"integrity_check_failed",e.message,e):e}function rc(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ac(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function sc(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=nc(s);n.fill(0),t(o),a.error(o)}},cancel(a){return n.fill(0),t(a),r.cancel(a)}})}function an(e){return e instanceof Error?e.message:String(e)}var bd=ye.limits.LEASE_DEFAULT_DAYS,md=ye.limits.LEASE_MAX_DAYS,Ed=ye.limits.LEASE_POLL_SECONDS,Sd=ye.limits.LEASE_STATUS_BATCH_MAX;async function _s(){let e=Ia(),t=zn();return{ownerTokenB64:ae(e),ownerTokenHash:await Oa(e),linkKey:t,linkKeyB64:ae(t)}}var ws=on[on.length-1]??on[0],or={ttl:"1h",singleUse:!0};function ys(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 Ud={...He,transport:{maxStallMs:1/0}};function gs(e,t){let{ttl:n,tier:r,otp:a,nda:s,ownerEmail:o,singleUse:i,maxOpens:l,geo:u,ownerTokenHash:f,ownerToken:d}=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}:{},...l?{maxOpens:l}:{},...u&&u.length>0?{geo:[...u]}:{},ownerTokenHash:f,ownerToken:d}}var Tt=class extends Error{};async function bs(e){let{keys:t,ndaFileName:n,api:r}=e,a=e.message?.trim()?e.message:void 0,s=await e.upload(async(p,_)=>{e.registered?.(p);let{fileKeys:g,ndaFile:w}=ps(_,n),m=ae(await Ra(t.ownerTokenB64,g,t.linkKey,a,w));await oc(r,p,t.ownerTokenB64,m),await e.ownerBlobStored?.(p)});e.uploaded?.(s);let o=s.fileResults.map(p=>{let _=s.encryptionKeys.get(p.sha256_hex);if(!_)throw new Error(`the upload returned no key for the file ${p.fileId}`);return{sha256_hex:p.sha256_hex,key:_}}),{fileKeys:i,ndaFile:l}=ps(o,n),u=zn(),f={blobB64:ae(await Pa(i,u,a,l)),linkKeyB64:ae(u)};e.minting?.(f);let{to:d}=e;if(d){let p=await dn(u,d,Jn,s.sealId),_=d.label?.slice(0,80),g=T=>r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,u,{to:d.address,fragment:p,..._?{label:_}:{},...T?{sender:T}:{}}),w=async T=>await d.sender?.(T).catch(()=>null)??null,m=T=>T instanceof F&&T.appCode==="intake.proof_required",y=await w(!1),x=await g(y).catch(async T=>{if(!y||!m(T))throw T;let D=await w(!0);return D?g(D).catch(B=>{if(m(B))return g(null);throw B}):g(null)});return{sealId:s.sealId,verification:s.verification,shareCode:x,share:f}}let h=await r.createShareLink(s.sealId,t.ownerTokenB64,f.blobB64,u).catch(()=>null);return{sealId:s.sealId,verification:s.verification,shareCode:h,share:f}}async function oc(e,t,n,r){let a=o=>o instanceof F&&o.appCode==="blob.precondition_required",s=null;for(let o=0;o<2;o++)try{await e.writeOwnerBlob(t,n,r);return}catch(i){if(o>0&&a(i)&&!a(s))return;s=i}throw new Tt(s instanceof Error?s.message:String(s),{cause:s})}function ps(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 ms={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},OTP_DIGITS:{alphabet:"0123456789",min_length: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,CLIENT_EVENT_STRING_MAX_CHARS:512,CLIENT_EVENT_MAX_BYTES:4096,CLIENT_EVENT_ID_MAX_CHARS:64,CLIENT_EVENT_COUNT_MAX:1e6}};var ir=["byte","kilobyte","megabyte","gigabyte","terabyte"],lc=["B","KB","MB","GB","TB"];function Es(e,t){let r=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),ir.length-1):0,a=parseFloat((e/Math.pow(1024,r)).toFixed(2));return a>=1024&&r<ir.length-1&&(r+=1,a=parseFloat((e/Math.pow(1024,r)).toFixed(2))),t?new Intl.NumberFormat(t,{style:"unit",unit:ir[r],unitDisplay:r===0?"long":"short",maximumFractionDigits:2}).format(a):`${a} ${lc[r]}`}var cc=1e3,dc=60*cc,uc=60*dc,Kd=24*uc;var $=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&&fc(a),Error.captureStackTrace&&Error.captureStackTrace(this,e)}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}},hc=["ownerToken","ownerLinkKey"];function fc(e){let t={...e};for(let n of hc){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 pc={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",seal_spent:"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",geo_restricted:"AUTH_INSUFFICIENT_SCOPE"};function Ss(e){if(e===400||e===413||e===422)return"VALIDATION_ERROR";if(e===402)return"PAYMENT_REQUIRED";if(e===426)return"CLIENT_OUTDATED";if(e===429)return"RATE_LIMITED";if(e===404||e===410||e===451)return"RESOURCE_NOT_FOUND";if(e===401||e===403)return"AUTH_INSUFFICIENT_SCOPE";if(e>=500&&e<600)return"SERVICE_UNAVAILABLE"}function he(e,t,n=null){if(e instanceof $)return e;if(e instanceof W){let r=e.cause instanceof F?e.cause.status:400;return new $(e.message,pc[e.code],r,{...n,reason:e.code},{cause:e})}if(e instanceof F){let r=e.appCode==="client.outdated"?"CLIENT_OUTDATED":e.appCode==="intake.proof_required"?"AUTH_INVALID_KEY":e.code==="not_found"||e.code==="revoked"||e.code==="blocked"?"RESOURCE_NOT_FOUND":e.code==="auth"?"AUTH_INSUFFICIENT_SCOPE":e.code==="rate_limited"?"RATE_LIMITED":e.code==="transient"?"SERVICE_UNAVAILABLE":Ss(e.status)??"INTERNAL_ERROR";return new $(e.detail??t,r,e.status,n,{cause:e})}if(e instanceof k){let r=e.httpStatus===void 0?void 0:Ss(e.httpStatus),a=e.code==="CLIENT_OUTDATED"?"CLIENT_OUTDATED":e.code==="QUOTA_EXCEEDED"?"STORAGE_QUOTA_EXCEEDED":r??(e.code==="NETWORK"?"NETWORK_ERROR":"INTERNAL_ERROR");return new $(e.message,a,e.httpStatus??500,n,{cause:e})}return e instanceof Error&&e.swCode==="NETWORK"?new $(e.message,"NETWORK_ERROR",500,n,{cause:e}):new $(e instanceof Error?e.message:t,"INTERNAL_ERROR",500,n,{cause:e})}function As(e){return e.split("/").filter(t=>t!==""&&t!=="."&&t!=="..")}var Ue=ms.limits;function _c(e){return e instanceof k&&e.code==="ABORTED"||e instanceof DOMException&&e.name==="AbortError"}var ru=Ue.ttl_options,wc="Secret",yc="Confidentiality Agreement",pn=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 vt({baseUrl:this.baseUrl,...this.credentials!==void 0?{credentials:this.credentials}:{}})}async create(t){t.nda&&!t.ownerEmail&&fe("ownerEmail is required when nda=true"),t.tier&&!t.onPaymentRequired&&fe("onPaymentRequired is required with tier");let{files:n,relativePaths:r,ndaDocument:a,secretAlone:s}=bc(t),o=t.message?.trim()?t.message:void 0;o&&o.length>Ue.MAX_MESSAGE_LENGTH&&fe(`message: ${o.length} characters, at most ${Ue.MAX_MESSAGE_LENGTH}`),o&&a&&fe("message and ndaFile: the NDA is its text or its document, give one of them");let i=o??(a?`NDA document attached: ${a.name} (${Es(a.size)})`:t.nda?yc:void 0),l=gc(t,s);"to"in t&&!t.to&&fe("to: empty: an address holds a value");let u=(I,K)=>{if(K!==void 0)try{return rs(K)}catch(v){throw new $(`${I}: ${v instanceof Error?v.message:String(v)}`,"VALIDATION_ERROR",400)}},f=u("to",t.to),d=u("owner",t.owner),h=t.signal?{signal:t.signal}:{},p=async I=>{let K=await this.api.getBundle(I,h);return K&&await as(K,I)?K:null},_=null;if(f){try{_=await p(f)}catch(I){throw he(I,"Failed to read the recipient key")}if(!_)throw new $(`to: ${f} has no published key: ask the recipient for their address again`,"RESOURCE_NOT_FOUND",404)}let g=d?await p(d).catch(()=>null):null,w=t.keyPair?ue(t.keyPair.secretKey):null,m=I=>w?hn(this.api,w,t.signal,I):I(),y=await _s(),x={...gs(this.baseUrl,ys(l,y,t.tier)),...this.credentials!==void 0?{credentials:this.credentials}:{}},T=null,D=I=>({sealId:I,ownerToken:y.ownerTokenB64,ownerLinkKey:y.linkKeyB64}),B=!1,P=!1,Q=null,pe=t.onProgress;try{let I=await bs({keys:y,ndaFileName:a?.name??null,message:i,api:{writeOwnerBlob:async(ee,Te,oe)=>{if(d&&g&&!P){let Ee=await dn(y.linkKey,{bundle:g,address:d},es,ee),ie=!1,z=await m(_e=>this.api.writeOwnerBlob(ee,Te,oe,{...h,to:d,fragment:Ee,label:"sealnet",..._e?{sender:_e}:{}})).catch(_e=>(ie=!(_e instanceof F),null));return z?(B=!0,z):(P=!0,this.api.writeOwnerBlob(ee,Te,oe,h).catch(_e=>{if(!ie||!(_e instanceof F)||_e.appCode!=="blob.precondition_required")throw _e;return B=!0,{etag:null}}))}return this.api.writeOwnerBlob(ee,Te,oe,h)},createShareLink:(ee,Te,oe,Ee,ie={})=>this.api.createShareLink(ee,Te,oe,Ee,{...ie,...h})},registered:ee=>{T=ee},upload:async ee=>{let Te={onRegistered:ee,...pe?{onProgress:ie=>pe({phase:ie.fileProgress.phase,percent:ie.overallPercent,fileIndex:ie.fileIndex,totalFiles:ie.totalFiles,fileName:ie.fileName})}:{},...h},oe,Ee;try{oe=r?await Ha(x,n,"",He,Te,r):await Ka(x,n,He,Te),Ee=oe.expiresAt}catch(ie){let z=za(ie);if(!z||!t.tier||!t.onPaymentRequired)throw ie;await t.onPaymentRequired(await this.api.createCheckout(z.sealId,y.ownerTokenB64,t.tier,h));let _e=Ga(z instanceof Yn?z.expiresAt:void 0),xe=await ja(this.api,z.sealId,y.ownerTokenB64,{deadline:_e,...h});if(!xe){let ge=await Ya(this.api,z.sealId,y.ownerTokenB64,h);if(ge==="unanswered")throw new $("The seal may be paid and was kept, not revoked","PAYMENT_REQUIRED",402,D(z.sealId));ge!=="unpaid"&&(xe=ge)}if(!xe)throw await this.api.revoke(z.sealId,y.ownerTokenB64).catch(()=>{}),new $("The seal was not paid in time and was revoked","PAYMENT_REQUIRED",402,D(z.sealId));oe=await z.resume(Te),Ee=xe.expires_at}if(!Ee)throw new $(`Seal ${oe.sealId}: the server sent no expiry`,"INTERNAL_ERROR",500,D(oe.sealId));return Q={result:oe,expiresAt:Ee},{sealId:oe.sealId,encryptionKeys:oe.encryptionKeys,fileResults:oe.files,verification:oe.verification}},...f&&_?{to:{address:f,bundle:_,label:"sealnet",...w?{sender:ee=>rn(this.api,w,{...h,fresh:ee})}:{}}}:{}}),{result:K,expiresAt:v}=Q,N=I.shareCode;if(N===null)try{N=await this.api.createShareLink(I.sealId,y.ownerTokenB64,I.share.blobB64,ue(I.share.linkKeyB64),h)}catch(ee){throw he(ee,"Seal created but share link mint failed",D(I.sealId))}let se=Qa(I.sealId,N,I.share.linkKeyB64),Y=`${this.shareUrlBase}${f?se.split("#")[0]:se}`,V=`${this.shareUrlBase}${Ja(I.sealId,y.linkKeyB64)}`,[me]=K.files,X=me&&K.encryptionKeys.get(me.sha256_hex);if(!me||!X)throw new $(`Seal ${I.sealId}: the upload returned no key for its first file`,"INTERNAL_ERROR",500,D(I.sealId));let rt=r??n.map(ee=>ee.name);return{sealId:I.sealId,shareUrl:Y,ownerUrl:V,ownerToken:y.ownerTokenB64,expiresAt:v,encryptionKey:De(X),fileId:me.fileId,files:K.files.map((ee,Te)=>({fileId:ee.fileId,name:rt[Te]})),delivered:f!==void 0,ownerCopy:B}}catch(I){if(I instanceof $)throw I;if(!T)throw!_c(I)&&(I instanceof F||I instanceof k)?he(I,"The seal was not created"):I;let K=I instanceof Tt?I.cause:I;if(K instanceof F||K instanceof k)throw he(K,`Seal ${T} was created but its send did not finish`,D(T));let v=K instanceof Error?K.message:String(K);throw new $(`Seal ${T} was created but the create flow was interrupted: ${v}`,"INTERNAL_ERROR",500,D(T),{cause:I})}}async revoke(t,n,r={}){try{return await this.api.revoke(t,n,r.signal?{signal:r.signal}:{})}catch(a){throw he(a,"Failed to revoke seal")}}};function gc(e,t){if("otp"in e&&!e.otp&&fe("otp: empty: a password holds a value"),e.otp&&qa(e.otp)){let a=Ue.OTP_DIGITS.min_length;fe(`otp: a password of digits only needs ${a} digits: give ${a} digits, or add a letter`)}let n=e.maxOpens===void 0?void 0:Xa(String(e.maxOpens));n===null&&fe(`maxOpens: ${e.maxOpens}: a whole number from 1 to ${Ue.MAX_OPENS_PER_SEAL_FREE}`);let r=Za((e.geoAllowlist??[]).join(" "));return r.bad.length>0&&fe(`geoAllowlist: ${r.bad.join(", ")}: two-letter country codes such as DE, CH, US`),r.codes.length>Ue.MAX_GEO_COUNTRIES&&fe(`geoAllowlist: ${r.codes.length} countries, at most ${Ue.MAX_GEO_COUNTRIES}`),{ttl:e.ttl??(t?or.ttl:ws),otp:e.otp,nda:e.nda,ownerEmail:e.ownerEmail,singleUse:e.singleUse??(t&&n===void 0?or.singleUse:void 0),maxOpens:n,geo:r.codes}}function bc(e){let t=(a,s,o)=>o||(s instanceof File?s.name:"")||fe(`${a}: bytes need a filename`),n=[];if("secret"in e){(e.secret===void 0||e.secret.length===0)&&fe("secret: empty: a secret holds a value");let a=typeof e.secret=="string"?new Blob([e.secret]):e.secret;n.push({file:xt(a,wc,un),secret:!0})}e.file!==void 0&&n.push({file:xt(e.file,t("file",e.file,e.filename),e.mimeType),secret:!1});for(let[a,s]of(e.files??[]).entries()){let o=xt(s.file,t(`files[${a}]`,s.file,s.filename),s.secret?un:s.mimeType);s.secret&&o.size===0&&fe(`files[${a}]: an empty secret`),n.push({file:o,secret:s.secret===!0})}for(let[a,s]of(e.folder??[]).entries()){let o=As(s instanceof File?Ma(s)??s.name:s.path),i=o.at(-1);i||fe(`folder[${a}]: a file with no path`);let l=o.join("/");n.push(s instanceof File?{file:s,path:l,secret:!1}:{file:xt(s.file,i,s.mimeType),path:l,secret:!1})}let r=null;if(e.ndaFile!==void 0){e.nda||fe("ndaFile goes with nda: true");let{file:a,filename:s,mimeType:o}=e.ndaFile;r=xt(a,t("ndaFile",a,s),o),n.push({file:r,secret:!1})}return n.length===0&&fe("Nothing to seal: give file, files, folder or secret"),n.length>Ue.MAX_FILES_PER_SEAL&&fe(`A seal holds at most ${Ue.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 fe(e){throw new $(e,"VALIDATION_ERROR",400)}function xt(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 vs(e,t){let n=await import("fs/promises"),r=await import("path");await n.mkdir(e,{recursive:!0});let a=e;for(let s of t){let o=null;for(let i=0;i<1e3&&o===null;i++){let l=r.join(a,i===0?s:`${s} (${i})`);await n.mkdir(l).catch(u=>{if(u.code!=="EEXIST")throw u}),(await n.lstat(l)).isDirectory()&&(o=l)}if(o===null)throw new Error(`no free name for the folder ${s} in ${a}`);a=o}return a}async function Ts(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)),u=>u.toString(16).padStart(2,"0")).join(""),o=a.join(t,`.seal-partial-${s}`),i=await r.open(o,"wx",384),l=!1;try{await e.stream.pipeTo(new WritableStream({async write(p){await i.write(p)}}));let{sizeBytes:u,sha256:f}=await e.done;await i.sync(),await i.close();let d=a.extname(n),h=n.slice(0,n.length-d.length);for(let p=0;p<1e3;p++){let _=a.join(t,p===0?n:`${h} (${p})${d}`);try{await r.link(o,_)}catch(g){let w=g.code;if(w==="EEXIST")continue;if(w!=="EPERM"&&w!=="ENOTSUP"&&w!=="EOPNOTSUPP"&&w!=="ENOSYS")throw g;if(await r.access(_).then(()=>!0,()=>!1))continue;return await r.rename(o,_),l=!0,{path:_,sizeBytes:u,sha256:f}}return l=!0,await r.unlink(o).catch(()=>{}),{path:_,sizeBytes:u,sha256:f}}throw new Error(`no free name for ${n} in ${t}`)}finally{l||(await i.close().catch(()=>{}),await r.unlink(o).catch(()=>{}))}}var mc=/^[A-Za-z0-9_-]{86}$/;function kt(e){if(mc.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 $(t,"INVALID_KEY",400)}async function xs(e,t,n,r){let a=n.signal?{signal:n.signal}:{},s=await rr(e,t,{...n.keyPair?{seed:kt(n.keyPair)}:{},...r?{wrap:r}:{},...a});if(s.ndaRequired)throw new $("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 $("This seal is password-protected: pass `password`","AUTH_INVALID_KEY",401);o=(await e.verifyOtp(s.sealId,{code:n.password,shareCode:s.shareCode},a)).sessionCookie}let i=s.files.filter(d=>d.key!==null&&d.sha256Hex!==null),l={done:0,total:i.reduce((d,h)=>d+h.size,0),told(){n.onProgress?.(this.done,this.total)}},u=new xa;return{seal:s,covered:i,read:async d=>{let h=await u.ask(p=>e.downloadCiphertext(s.sealId,{fileId:d.id,shareCode:s.shareCode,visit:p,...o?{sessionCookie:o}:{}},a));if(!h.body)throw new $(`Download of ${d.name} returned no body`,"INTERNAL_ERROR",h.status);return sr(h.body,d.key,d.sha256Hex,p=>{l.done+=p,l.told()})},progress:l}}async function lr(e,t,n={},r=null){try{let{seal:a,covered:s,read:o}=await xs(e,t,n,r);return{sealId:a.sealId,expiresAt:a.expiresAt,message:a.message??null,files:s.map(i=>({name:i.name,mime:i.mime,size:i.size,secret:i.secret,read:()=>o(i).catch(l=>Promise.reject(he(l,"Download failed")))}))}}catch(a){throw he(a,"Failed to open the link")}}async function cr(e,t,n,r={},a=null){try{let{seal:s,covered:o,read:i,progress:l}=await xs(e,t,r,a),u=async _=>{let g=Da(_.name),w=g.pop()??Jt(_.name),m=g.length>0?await vs(n||".",g):n,y=await Ts(await i(_),m,w);return{name:_.name,mime:_.mime,secret:_.secret,...y}},f=[],d=[],h=null;for(let _ of o){r.signal?.throwIfAborted();let g=l.done;if(h){let w=h.details?.reason,m=new $(`${_.name} was not asked: ${h.message}`,h.code,h.status,w===void 0?null:{reason:w},{cause:h});d.push({name:_.name,error:m})}else try{f.push(await u(_).catch(async w=>{if(r.signal?.aborted||nr(w)!=="transient")throw w;return l.done=g,await ar(cs(w),r.signal),u(_)}));continue}catch(w){if(r.signal?.aborted)throw w;let m=he(w,`Download of ${_.name} failed`);nr(w)!=="file"&&(h=m),d.push({name:_.name,error:m})}l.done=g+_.size,l.told()}if(f.length===0&&d.length>0)throw h??d[0].error;let p={sealId:s.sealId,expiresAt:s.expiresAt,message:s.message??null,files:f};return d.length>0?{...p,refused:d}:p}catch(s){throw he(s,"Failed to open the link")}}async function ks(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}:{}),{address:a,words:s}=await cn(ue(n.recipientBundle));return{intakeId:r.id,url:tr(t,r.id,a),words:s,expiresAt:r.expires_at}}catch(r){throw he(r,"Failed to create the request")}}async function dr(e,t,n){try{return await ds(e,t,n?{signal:n}:{})}catch(r){throw he(r,"Failed to wait for the request")}}async function Is(e,t,n){let r,a;try{r=await e.createIntake({recipientBundle:n.keyPair.bundle,label:(n.name??"sealnet").slice(0,80),what:is,kind:"pair"},n.signal?{signal:n.signal}:{}),a=tr(t,r.id,(await cn(ue(n.keyPair.bundle))).address)}catch(o){throw he(o,"Failed to create the pairing request")}let s=async()=>{let{sharePath:o,wrap:i}=await dr(e,r.id,n.signal);try{let l=await us(e,`${t}${o}`,os,{seed:kt(n.keyPair),wrap:i,...n.signal?{signal:n.signal}:{}}),{bundle:u,name:f}=ls(l),{address:d,words:h}=await cn(u);return{address:d,name:f,words:h}}catch(l){throw he(l,"The answer of the inbox did not open")}};return{url:a,words:n.keyPair.words,expiresAt:r.expires_at,wait:s}}async function Os(){let e=ns(),{address:t,bundle:n,words:r}=await er(e);return{secretKey:ae(e),address:t,bundle:ae(n),words:r}}async function Rs(e,t){let n=kt(t.keyPair),r=Date.now()+(t.wait??0)*1e3;try{for(;;){let a=Math.ceil((r-Date.now())/1e3),s=await fn(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:ss(i.sender),label:i.label,receivedAt:i.at,expiresAt:i.expires_at}))}}}catch(a){throw he(a,"Failed to read the inbox")}}async function Ps(e,t,n,r){let a;try{a=(await fn(e,kt(r.keyPair),r.signal?{signal:r.signal}:{})).items}catch(o){throw he(o,"Failed to read the inbox")}let s=a.find(o=>o.id===n.id);if(!s)throw new $(`${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 Ls(e,t,n){try{await hs(e,kt(n.keyPair),t.id,n.signal?{signal:n.signal}:{})}catch(r){throw he(r,"Failed to remove the item")}}var[Ec="",Cs=""]="sdk-web/3.2.4".split("/");typeof globalThis.process?.versions?.node!="string"&&Sn(Se);var ur=class{seals;api;site;constructor(t={}){Ta(Ec,Cs);let n=t.apiUrl??"https://api.seal.net";this.site=(t.shareUrl??"https://seal.net").replace(/\/$/,"").replace(/\/s$/,""),this.seals=new pn({apiUrl:n,shareUrl:this.site,credentials:"omit"}),this.api=new vt({baseUrl:n,credentials:"same-origin"})}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 $("An inbox item opens with the seed it was sent to: pass `keyPair`","VALIDATION_ERROR",400);return r!==void 0?cr(this.api,s.url,r,a,s.wrap):lr(this.api,s.url,a,s.wrap)}async inbox(t){return Rs(this.api,t)}async dismiss(t,n){return Ls(this.api,t,n)}async request(t){return ks(this.api,this.site,t)}async waitFor(t,n){let{sharePath:r,wrap:a}=await dr(this.api,t,n.signal),{to:s,...o}=n,i=`${this.site}${r}`;return s!==void 0?cr(this.api,i,s,o,a):lr(this.api,i,o,a)}async pair(t){return Is(this.api,this.site,t)}async keygen(){return Os()}async revoke(t,n,r={}){return this.seals.revoke(t,n,r)}},Sc=Cs;return qs(Ac);})();
|
|
4
4
|
/*! Bundled license information:
|
|
5
5
|
|
|
6
6
|
@noble/hashes/esm/utils.js:
|