@nodatachat/sdk 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ var F=class extends Error{constructor(t,r,s,o){super(t);this.status=r;this.code=s;this.retryAfter=o;this.name="NoDataError"}};var qr="https://www.nodatacapsule.com",Nr=3e4,jr=2,Qe=class{apiKey;baseUrl;timeout;retries;customHeaders;onRequest;onResponse;onError;constructor(e){if(!e.apiKey)throw new Error("NoData SDK: apiKey is required. Get one at https://www.nodatacapsule.com/developers");this.apiKey=e.apiKey,this.baseUrl=(e.baseUrl||qr).replace(/\/+$/,""),this.timeout=e.timeout||Nr,this.retries=e.retries??jr,this.customHeaders=e.headers||{},this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.onError=e.onError}async request(e,t,r,s){let o=`${this.baseUrl}${t}`;if(s){let l=new URLSearchParams(Object.fromEntries(Object.entries(s).filter(([,d])=>d!=null))).toString();l&&(o+=`?${l}`)}let i={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...this.customHeaders},signal:AbortSignal.timeout(this.timeout)};r&&e!=="GET"&&(i.body=JSON.stringify(r)),this.onRequest?.(o,i);let a=null,u=1+this.retries;for(let c=1;c<=u;c++){let l=Date.now();try{let d=await fetch(o,i),h=Date.now()-l;if(this.onResponse?.(o,d.status,h),d.status===429&&c<u){let w=parseInt(d.headers.get("Retry-After")||"5",10);await It(w*1e3);continue}if(d.status>=500&&c<u){await It(1e3*c);continue}let p=await d.json().catch(()=>({}));if(!d.ok)throw new F(p.error||`HTTP ${d.status}`,d.status,p.code,d.status===429?parseInt(d.headers.get("Retry-After")||"60",10):void 0);return p}catch(d){if(a=d instanceof Error?d:new Error(String(d)),this.onError?.(o,a),d instanceof F)throw d;if(c<u){await It(1e3*c);continue}}}throw a||new Error("Request failed")}get baseURL(){return this.baseUrl}get(e,t){return this.request("GET",e,void 0,t)}post(e,t){return this.request("POST",e,t)}del(e,t){return this.request("DELETE",e,t)}async raw(e,t,r){let s=`${this.baseUrl}${t}`,o={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...r!==void 0?{"Content-Type":"application/json"}:{},...this.customHeaders},signal:AbortSignal.timeout(this.timeout),...r!==void 0?{body:JSON.stringify(r)}:{}};this.onRequest?.(s,o);let i=Date.now(),a=await fetch(s,o);this.onResponse?.(s,a.status,Date.now()-i);let u=await a.json().catch(()=>({})),c=u&&typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:u;return{ok:a.ok,status:a.status,data:{...c,...u.error?{error:u.error}:{}}}}};function It(n){return new Promise(e=>setTimeout(e,n))}var Re=class{constructor(e){this.http=e}async encrypt(e){return this.http.post("/api/v1/encrypt",{field:e.field,value:e.value,context:e.context})}async decrypt(e){return this.http.post("/api/v1/decrypt",{ciphertext:e.ciphertext,field:e.field,requester:e.requester,purpose:e.purpose})}async batchEncrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.encrypt({...o,context:o.context||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,ciphertext:"",field:e[i].field,audit_id:"",algorithm:"",error:o.reason?.message||"Encryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchDecrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.decrypt({...o,requester:o.requester||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,value:"",field:e[i].field,audit_id:"",error:o.reason?.message||"Decryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchNative(e,t){return this.http.post("/api/v1/batch",{items:e,context:t})}async encryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.encrypt({field:o,value:s,context:r})).ciphertext)}async decryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.decrypt({ciphertext:s,field:o,requester:r})).value)}async processObject(e,t,r){if(e==null)return e;if(Array.isArray(e))return Promise.all(e.map(s=>this.processObject(s,t,r)));if(typeof e=="object"){let s={};for(let[o,i]of Object.entries(e))t.includes(o)&&typeof i=="string"&&i.length>0?s[o]=await r(i,o):typeof i=="object"?s[o]=await this.processObject(i,t,r):s[o]=i;return s}return e}};var Ce=class{constructor(e){this.http=e}async registerTable(e){return this.http.post("/api/v1/governance/tables",{table_name:e.table,encrypted_columns:e.encryptedColumns??[],plaintext_columns:e.plaintextColumns??[],classification_column:e.classificationColumn,hkdf_prefix:e.hkdfPrefix,ui_label:e.uiLabel})}async listTables(){return this.http.get("/api/v1/governance/tables")}async grant(e){return this.http.post("/api/v1/governance/grant",{agent:e.agent,table:e.table,columns:e.columns,where:e.where,classifications:e.classifications,ttl_seconds:e.ttlSeconds})}async revoke(e){return this.http.post("/api/v1/governance/revoke",{handle:e.agent,jti:e.jti,reason:e.reason})}},Be=class{constructor(e,t){this.baseURL=e;this.grantToken=t}async read(e){let t=e.handle??$r(this.grantToken);if(!t)throw new F("AgentReader.read: could not derive agent handle from token; pass { handle }",400);let r=`${this.baseURL}/api/agents/${encodeURIComponent(t)}/read`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.grantToken}`,"Content-Type":"application/json"},body:JSON.stringify({table:e.table,columns:e.columns,where:e.where,limit:e.limit})}),o=await s.json().catch(()=>({}));if(!s.ok)throw new F(o.error||`HTTP ${s.status}`,s.status,o.reason);return o}};function $r(n){try{let t=(n.startsWith("ndca-")?n.slice(5):n).split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r)).handle??null}catch{return null}}var Je=class{constructor(e,t){this.http=e;this.ref=t}add(e){let t=e.sections?.length?e.sections:[{label:e.title||"Document",classification:e.classification||"confidential",text:e.content??""}];return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`,{title:e.title,sections:t,recipients:e.recipients,zero_knowledge:e.zero_knowledge,inherit_access:e.inherit_access})}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`)}},et=class{constructor(e,t){this.http=e;this.ref=t}add(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`)}},tt=class{constructor(e,t){this.http=e;this.ref=t}get(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.limit&&(t.limit=String(e.limit)),this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/audit`,Object.keys(t).length?t:void 0)}},nt=class{constructor(e,t){this.http=e;this.ref=t}grant(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,{action:"revoke",agent_id:e})}read(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-read`,e)}},Te=class{constructor(e,t){this.http=e;this.summary=t;this.documents=new Je(e,t.slug),this.members=new et(e,t.slug),this.audit=new tt(e,t.slug),this.ai=new nt(e,t.slug)}documents;members;audit;ai;get id(){return this.summary.capsule_id}get slug(){return this.summary.slug}get status(){return this.summary.status}embed(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/embed-token`,e)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/revoke`,{reason:e?.reason})}},Oe=class{constructor(e){this.http=e}async create(e){let t=await this.http.post("/api/v1/capsules",e);return new Te(this.http,t)}async get(e){let t=await this.http.get(`/api/v1/capsules/${encodeURIComponent(e)}`);return new Te(this.http,t)}list(e){return this.http.get("/api/v1/capsules",e?.limit?{limit:String(e.limit)}:void 0)}overview(){return this.http.get("/api/v1/overview")}};var Ie=class{constructor(e){this.http=e}create(e){return this.http.post("/api/v1/tenants",e)}get(e){return this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`)}};var De=class{constructor(e){this.http=e}async orgId(){let e=await this.http.get("/api/v1/partner/me");if(!e?.org_id)throw new Error("nd.scan: could not resolve the org from this API key.");return e.org_id}async enable(e){let t=await this.orgId(),r=await this.http.post(`/api/v1/tenants/${encodeURIComponent(t)}/capsule/install-token`,{}),s=r.install_token??"",o=(e.api_base??this.http.baseURL).replace(/\/+$/,""),i=e.source==="folder"?`--source folder --path ${e.path??"./"}`:e.source==="drive"?`--source drive --folder ${e.folder_id??"<folder-id>"}`:`--source ${e.source}`,a=e.per_customer?` --per-customer ${e.per_customer}`:"";return{ok:!0,scan_id:s.slice(0,12),install_token:s,install_command:`npx @nodatachat/capsule-agent --token ${s} --vault-api --api ${o} ${i}${a}`,expires_at:r.expires_at??null}}async status(){let e=await this.orgId(),t=await this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`);return{deployments:t.capsule?.deployments??[],last_scan_at:t.capsule?.last_scan_at??null,open_findings_count:t.capsule?.open_findings_count??0}}findings(e){let t={};return e?.limit&&(t.limit=String(e.limit)),e?.all&&(t.all="true"),this.http.get("/api/v1/scan/findings",Object.keys(t).length?t:void 0)}approve(e){return this.http.post("/api/v1/scan/approve",{finding_ids:e})}execute(e){return this.http.post("/api/v1/scan/execute",{finding_ids:e})}};var rt=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/secure-channel/init",{label:e.label,ttl:e.ttl||"24h",max_transfers:e.maxTransfers||10,require_verification:e.requireVerification??!1})}async send(e){let t=typeof e.data=="string"?e.data:JSON.stringify(e.data);return this.http.post("/api/secure-channel/upload",{channel_token:e.token,content:t,content_type:e.contentType||"application/json",burn_after_read:e.burnAfterRead??!0})}async receive(e){return this.http.post("/api/secure-channel/download",{channel_token:e.token,verification_code:e.verificationCode})}async verify(e,t){return this.http.post("/api/secure-channel/verify-code",{channel_token:e,code:t})}async proof(e){return this.http.post("/api/secure-channel/delivery-proof",{channel_token:e})}};var st=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/webhook/channel/create",{label:e.label,ttl:e.ttl||"30d",max_events:e.maxEvents||1e4,burn_after_read:e.burnAfterRead??!1})}async events(e,t){return this.http.post("/api/webhook/channel/events",{channel_token:e,limit:t?.limit||50,since:t?.since})}async list(){return this.http.get("/api/webhook/dashboard")}};var ot=class{constructor(e){this.http=e}async send(e){return this.http.post("/api/v1/deliver",{content:e.content,to:e.to,ttl:e.ttl||"24h",burn:e.burn??!0,maxViews:e.maxViews||1})}async burn(e,t){return this.http.post("/api/burn/create",{content:e,ttl_hours:t?.ttlHours||24,burn_after_read:t?.burnAfterRead??!0,available_at:t?.availableAt})}async read(e){return this.http.post("/api/burn/read",{drop_id:e})}};var it=class{constructor(e){this.http=e}async query(e={}){return this.http.get("/api/v1/evidence",{from:e.from||"",to:e.to||"",action:e.action||"",field:e.field||"",limit:String(e.limit||100)})}async certificate(e){return this.http.post("/api/proof-certificate",{audit_id:e})}async verify(e){return this.http.post("/api/receipt/verify",{proof_hash:e})}};var at=class{constructor(e){this.http=e}async create(e){return this.http.post("/api/vault/create",e)}async read(e){return this.http.post("/api/vault/read",{vault_id:e})}async delete(e){return this.http.post("/api/vault/delete",{vault_id:e})}async status(){return this.http.get("/api/vault/status")}};var Le=class{governance;blindRelay;channel;deliver;evidence;vault;webhook;constructor(e){this.governance=new Ce(e),this.blindRelay=new Re(e),this.channel=new rt(e),this.deliver=new ot(e),this.evidence=new it(e),this.vault=new at(e),this.webhook=new st(e)}};var He=class{constructor(e){this.http=e}async run(e){let t=await this.http.post("/api/v1/documents/compute",{question:e.question,clearance:e.clearance??"internal",...e.sections?{sections:e.sections}:{},...e.text?{text:e.text}:{}}),r=(t.sections??[]).map(s=>({title:s.title??"",classification:s.classification??"internal",sent:!!s.sent}));return{decision:t.decision??(r.some(s=>s.sent)?"allow":"deny"),answer:t.answer??null,model:t.model??null,sections:r,proof:{id:t.proof?.receipt_id??t.proof?.id??null,hash:t.proof?.hash??null,persisted:!!t.proof?.persisted}}}async verify(e){let t=await this.http.post("/api/access/verify",{proof_id:e});return{authentic:!!t.authentic,unaltered:!!t.unaltered,signer:t.signer,surface:t.surface,decision:t.decision,issuedAt:t.issued_at}}};function Dt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ie(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof n}`)}if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${n}`)}}function $(n,e,t=""){let r=Dt(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",u=r?`length=${s}`:`type=${typeof n}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):new TypeError(c)}return n}function Ue(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ie(n.outputLen),ie(n.blockLen),n.outputLen<1)throw new Error('"outputLen" must be >= 1');if(n.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ve(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function ct(n,e){$(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function X(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function ut(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Y(n,e){return n<<32-e|n>>>e}var Sn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function lt(n){if($(n),Sn)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Vr[n[t]];return e}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function An(n){if(n>=ee._0&&n<=ee._9)return n-ee._0;if(n>=ee.A&&n<=ee.F)return n-(ee.A-10);if(n>=ee.a&&n<=ee.f)return n-(ee.a-10)}function Pe(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Sn)try{return Uint8Array.fromHex(n)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=An(n.charCodeAt(o)),a=An(n.charCodeAt(o+1));if(i===void 0||a===void 0){let u=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+a}return r}function Lt(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];$(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function Ht(n,e={}){let t=(s,o)=>n(o).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Cn(n=32){ie(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Ut=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Bn(n,e,t){return n&e^~n&t}function Tn(n,e,t){return n&e^n&t^e&t}var Me=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){ve(this),$(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let u=ut(e);for(;s<=o-i;i+=s)this.process(u,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let d=i;d<s;d++)t[d]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let a=ut(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var q=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var dt=BigInt(4294967295),On=BigInt(32);function Gr(n,e=!1){return e?{h:Number(n&dt),l:Number(n>>On&dt)}:{h:Number(n>>On&dt)|0,l:Number(n&dt)|0}}function In(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Gr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Pt=(n,e,t)=>n>>>t,Mt=(n,e,t)=>n<<32-t|e>>>t,ge=(n,e,t)=>n>>>t|e<<32-t,be=(n,e,t)=>n<<32-t|e>>>t,Fe=(n,e,t)=>n<<64-t|e>>>t-32,qe=(n,e,t)=>n>>>t-32|e<<64-t;function W(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Dn=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),Ln=(n,e,t,r)=>e+t+r+(n/2**32|0)|0,Hn=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Un=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,Pn=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),Mn=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;var Kr=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]),ae=new Uint32Array(64),Ft=class extends Me{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:u}=this;return[e,t,r,s,o,i,a,u]}set(e,t,r,s,o,i,a,u){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let d=0;d<16;d++,t+=4)ae[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=ae[d-15],p=ae[d-2],w=Y(h,7)^Y(h,18)^h>>>3,R=Y(p,17)^Y(p,19)^p>>>10;ae[d]=R+ae[d-7]+w+ae[d-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:u,G:c,H:l}=this;for(let d=0;d<64;d++){let h=Y(a,6)^Y(a,11)^Y(a,25),p=l+h+Bn(a,u,c)+Kr[d]+ae[d]|0,R=(Y(r,2)^Y(r,13)^Y(r,22))+Tn(r,s,o)|0;l=c,c=u,u=a,a=i+p|0,i=o,o=s,s=r,r=p+R|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,u,c,l)}roundClean(){X(ae)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),X(this.buffer)}},qt=class extends Ft{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var Fn=In(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),Zr=Fn[0],Xr=Fn[1],ce=new Uint32Array(80),ue=new Uint32Array(80),Nt=class extends Me{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:u,Eh:c,El:l,Fh:d,Fl:h,Gh:p,Gl:w,Hh:R,Hl:f}=this;return[e,t,r,s,o,i,a,u,c,l,d,h,p,w,R,f]}set(e,t,r,s,o,i,a,u,c,l,d,h,p,w,R,f){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=w|0,this.Hh=R|0,this.Hl=f|0}process(e,t){for(let x=0;x<16;x++,t+=4)ce[x]=e.getUint32(t),ue[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let k=ce[x-15]|0,A=ue[x-15]|0,B=ge(k,A,1)^ge(k,A,8)^Pt(k,A,7),E=be(k,A,1)^be(k,A,8)^Mt(k,A,7),C=ce[x-2]|0,S=ue[x-2]|0,D=ge(C,S,19)^Fe(C,S,61)^Pt(C,S,6),L=be(C,S,19)^qe(C,S,61)^Mt(C,S,6),b=Hn(E,L,ue[x-7],ue[x-16]),_=Un(b,B,D,ce[x-7],ce[x-16]);ce[x]=_|0,ue[x]=b|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:u,Dh:c,Dl:l,Eh:d,El:h,Fh:p,Fl:w,Gh:R,Gl:f,Hh:g,Hl:y}=this;for(let x=0;x<80;x++){let k=ge(d,h,14)^ge(d,h,18)^Fe(d,h,41),A=be(d,h,14)^be(d,h,18)^qe(d,h,41),B=d&p^~d&R,E=h&w^~h&f,C=Pn(y,A,E,Xr[x],ue[x]),S=Mn(C,g,k,B,Zr[x],ce[x]),D=C|0,L=ge(r,s,28)^Fe(r,s,34)^Fe(r,s,39),b=be(r,s,28)^qe(r,s,34)^qe(r,s,39),_=r&o^r&a^o&a,m=s&i^s&u^i&u;g=R|0,y=f|0,R=p|0,f=w|0,p=d|0,w=h|0,{h:d,l:h}=W(c|0,l|0,S|0,D|0),c=a|0,l=u|0,a=o|0,u=i|0,o=r|0,i=s|0;let v=Dn(D,b,m);r=Ln(v,S,L,_),s=v|0}({h:r,l:s}=W(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=W(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:u}=W(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l}=W(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:h}=W(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:w}=W(this.Fh|0,this.Fl|0,p|0,w|0),{h:R,l:f}=W(this.Gh|0,this.Gl|0,R|0,f|0),{h:g,l:y}=W(this.Hh|0,this.Hl|0,g|0,y|0),this.set(r,s,o,i,a,u,c,l,d,h,p,w,R,f,g,y)}roundClean(){X(ce,ue)}destroy(){this.destroyed=!0,X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},jt=class extends Nt{Ah=q[0]|0;Al=q[1]|0;Bh=q[2]|0;Bl=q[3]|0;Ch=q[4]|0;Cl=q[5]|0;Dh=q[6]|0;Dl=q[7]|0;Eh=q[8]|0;El=q[9]|0;Fh=q[10]|0;Fl=q[11]|0;Gh=q[12]|0;Gl=q[13]|0;Hh=q[14]|0;Hl=q[15]|0;constructor(){super(64)}};var Ne=Ht(()=>new qt,Ut(1));var ft=Ht(()=>new jt,Ut(3));var O=(n,e,t)=>$(n,e,t),Vt=ie,Gt=lt,Q=(...n)=>Lt(...n),qn=n=>Pe(n),gt=Dt,bt=n=>Cn(n),ht=BigInt(0),$t=BigInt(1);function Ee(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof n)}return n}function Yr(n){if(typeof n=="bigint"){if(!pt(n))throw new RangeError("positive bigint expected, got "+n)}else Vt(n);return n}function ne(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function Nn(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?ht:BigInt("0x"+n)}function zt(n){return Nn(lt(n))}function K(n){return Nn(lt(le($(n)).reverse()))}function Kt(n,e){if(ie(e),e===0)throw new RangeError("zero length");n=Yr(n);let t=n.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pe(t.padStart(e*2,"0"))}function mt(n,e){return Kt(n,e).reverse()}function jn(n,e){if(n=O(n),e=O(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function le(n){return Uint8Array.from(O(n))}function yt(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var pt=n=>typeof n=="bigint"&&ht<=n;function Wr(n,e,t){return pt(n)&&pt(e)&&pt(t)&&e<=n&&n<t}function ke(n,e,t,r){if(!Wr(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Zt(n){if(n<ht)throw new Error("expected non-negative bigint, got "+n);let e;for(e=0;n>ht;n>>=$t,e+=1);return e}var $n=n=>($t<<BigInt(n))-$t;function re(n,e={},t={}){if(Object.prototype.toString.call(n)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(n,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=n[o];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${c}`)}let s=(o,i)=>Object.entries(o).forEach(([a,u])=>r(a,u,i));s(e,!1),s(t,!0)}var Xt=()=>{throw new Error("not implemented")};var N=BigInt(0),P=BigInt(1),me=BigInt(2),Kn=BigInt(3),Zn=BigInt(4),Xn=BigInt(5),Qr=BigInt(7),Yn=BigInt(8),Jr=BigInt(9),Wn=BigInt(16);function I(n,e){if(e<=N)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=N?t:e+t}function Z(n,e,t){if(e<N)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >N;)r*=r,r%=t;return r}function Vn(n,e){if(n===N)throw new Error("invert: expected non-zero number");if(e<=N)throw new Error("invert: expected positive modulus, got "+e);let t=I(n,e),r=e,s=N,o=P,i=P,a=N;for(;t!==N;){let c=r/t,l=r-t*c,d=s-i*c,h=o-a*c;r=t,t=l,s=i,o=a,i=d,a=h}if(r!==P)throw new Error("invert: does not exist");return I(s,e)}function Yt(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Qn(n,e){let t=n,r=(t.ORDER+P)/Zn,s=t.pow(e,r);return Yt(t,s,e),s}function es(n,e){let t=n,r=(t.ORDER-Xn)/Yn,s=t.mul(e,me),o=t.pow(s,r),i=t.mul(e,o),a=t.mul(t.mul(i,me),o),u=t.mul(i,t.sub(a,t.ONE));return Yt(t,u,e),u}function ts(n){let e=wt(n),t=Jn(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+Qr)/Wn;return((a,u)=>{let c=a,l=c.pow(u,i),d=c.mul(l,r),h=c.mul(l,s),p=c.mul(l,o),w=c.eql(c.sqr(d),u),R=c.eql(c.sqr(h),u);l=c.cmov(l,d,w),d=c.cmov(p,h,R);let f=c.eql(c.sqr(d),u),g=c.cmov(l,d,f);return Yt(c,g,u),g})}function Jn(n){if(n<Kn)throw new Error("sqrt is not defined for small field");let e=n-P,t=0;for(;e%me===N;)e/=me,t++;let r=me,s=wt(n);for(;Gn(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Qn;let o=s.pow(r,e),i=(e+P)/me;return function(u,c){let l=u;if(l.is0(c))return c;if(Gn(l,c)!==1)throw new Error("Cannot find square root");let d=t,h=l.mul(l.ONE,o),p=l.pow(c,e),w=l.pow(c,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let R=1,f=l.sqr(p);for(;!l.eql(f,l.ONE);)if(R++,f=l.sqr(f),R===d)throw new Error("Cannot find square root");let g=P<<BigInt(d-R-1),y=l.pow(h,g);d=R,h=l.sqr(y),p=l.mul(p,h),w=l.mul(w,y)}return w}}function ns(n){return n%Zn===Kn?Qn:n%Yn===Xn?es:n%Wn===Jr?ts(n):Jn(n)}var se=(n,e)=>(I(n,e)&P)===P,rs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function er(n){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=rs.reduce((r,s)=>(r[s]="function",r),e);if(re(n,t),ne(n.BYTES,"BYTES"),ne(n.BITS,"BITS"),n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ss(n,e,t){let r=n;if(t<N)throw new Error("invalid exponent, negatives unsupported");if(t===N)return r.ONE;if(t===P)return e;let s=r.ONE,o=e;for(;t>N;)t&P&&(s=r.mul(s,o)),o=r.sqr(o),t>>=P;return s}function _t(n,e,t=!1){let r=n,s=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,u,c)=>r.is0(u)?a:(s[c]=a,r.mul(a,u)),r.ONE),i=r.inv(o);return e.reduceRight((a,u,c)=>r.is0(u)?a:(s[c]=r.mul(a,s[c]),r.mul(a,u)),i),s}function Gn(n,e){let t=n,r=(t.ORDER-P)/me,s=t.pow(e,r),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function os(n,e){if(e!==void 0&&Vt(e),n<=N)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Zt(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}var zn=new WeakMap,xt=class{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=P;_lengths;_mod;constructor(e,t={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=os(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return I(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return N<=e&&e<this.ORDER}is0(e){return e===N}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&P)===P}neg(e){return I(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return I(e*e,this.ORDER)}add(e,t){return I(e+t,this.ORDER)}sub(e,t){return I(e-t,this.ORDER)}mul(e,t){return I(e*t,this.ORDER)}pow(e,t){return ss(this,e,t)}div(e,t){return I(e*Vn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Vn(e,this.ORDER)}sqrt(e){let t=zn.get(this);return t||zn.set(this,t=ns(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?mt(e,this.BYTES):Kt(e,this.BYTES)}fromBytes(e,t=!1){O(e);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let u=o?K(e):zt(e);if(a&&(u=I(u,i)),!t&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return _t(this,e)}cmov(e,t,r){return Ee(r,"condition"),r?t:e}};Object.freeze(xt.prototype);function wt(n,e={}){return new xt(n,e)}var Rt=BigInt(0),en=BigInt(1);function tr(n,e){let t=e.negate();return n?t:e}function Et(n,e){let t=_t(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function or(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Wt(n,e){or(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=$n(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function nr(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),u=n>>i;a>r&&(a-=o,u+=en);let c=e*r,l=c+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:u,offset:l,isZero:d,isNeg:h,isNegF:p,offsetF:c}}var Qt=new WeakMap,ir=new WeakMap;function Jt(n){return ir.get(n)||1}function rr(n){if(n!==Rt)throw new Error("invalid wNAF")}var vt=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Rt;)t&en&&(r=r.add(s)),s=s.double(),t>>=en;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Wt(t,this.bits),o=[],i=e,a=i;for(let u=0;u<r;u++){a=i,o.push(a);for(let c=1;c<s;c++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Wt(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:l,isNeg:d,isNegF:h,offsetF:p}=nr(r,a,i);r=u,l?o=o.add(tr(h,t[p])):s=s.add(tr(d,t[c]))}return rr(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Wt(e,this.bits);for(let i=0;i<o.windows&&r!==Rt;i++){let{nextN:a,offset:u,isZero:c,isNeg:l}=nr(r,i,o);if(r=a,!c){let d=t[u];s=s.add(l?d.negate():d)}}return rr(r),s}getPrecomputes(e,t,r){let s=Qt.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),Qt.set(t,s))),s}cached(e,t,r){let s=Jt(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=Jt(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){or(t,this.bits),ir.set(e,t),Qt.delete(e)}hasCache(e){return Jt(e)!==1}};function sr(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return er(e),e}else return wt(n,{isLE:t})}function ar(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let u of["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Rt))throw new Error(`CURVE.${u} must be positive bigint`)}let s=sr(e.p,t.Fp,r),o=sr(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let u of a)if(!s.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function kt(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var de=BigInt(0),M=BigInt(1),tn=BigInt(2),is=BigInt(8);function as(n,e,t,r){let s=n.sqr(t),o=n.sqr(r),i=n.add(n.mul(e.a,s),o),a=n.add(n.ONE,n.mul(e.d,n.mul(s,o)));return n.eql(i,a)}function cr(n,e={}){let t=e,r=ar("edwards",n,t,t.FpFnLE),{Fp:s,Fn:o}=r,i=r.CURVE,{h:a}=i;re(t,{},{uvRatio:"function"});let u=tn<<BigInt(o.BYTES*8)-M,c=R=>s.create(R),l=t.uvRatio===void 0?(R,f)=>{try{return{isValid:!0,value:s.sqrt(s.div(R,f))}}catch{return{isValid:!1,value:de}}}:t.uvRatio;if(!as(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(R,f,g=!1){let y=g?M:de;return ke("coordinate "+R,f,y,u),f}function h(R){if(!(R instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,M,c(i.Gx*i.Gy));static ZERO=new p(de,M,M,de);static Fp=s;static Fn=o;X;Y;Z;T;constructor(f,g,y,x){this.X=d("x",f),this.Y=d("y",g),this.Z=d("z",y,!0),this.T=d("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(f){if(f instanceof p)throw new Error("extended point not allowed");let{x:g,y}=f||{};return d("x",g),d("y",y),new p(g,y,M,c(g*y))}static fromBytes(f,g=!1){let y=s.BYTES,{a:x,d:k}=i;f=le(O(f,y,"point")),Ee(g,"zip215");let A=le(f),B=f[y-1];A[y-1]=B&-129;let E=K(A),C=g?u:s.ORDER;ke("point.y",E,de,C);let S=c(E*E),D=c(S-M),L=c(k*S-x),{isValid:b,value:_}=l(D,L);if(!b)throw new Error("bad point: invalid y coordinate");let m=(_&M)===M,v=(B&128)!==0;if(!g&&_===de&&v)throw new Error("bad point: x=0 and x_0=1");return v!==m&&(_=c(-_)),p.fromAffine({x:_,y:E})}static fromHex(f,g=!1){return p.fromBytes(qn(f),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,g=!0){return w.createCache(this,f),g||this.multiply(tn),this}assertValidity(){let f=this,{a:g,d:y}=i;if(f.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:A,T:B}=f,E=c(x*x),C=c(k*k),S=c(A*A),D=c(S*S),L=c(E*g),b=c(S*c(L+C)),_=c(D+c(y*c(E*C)));if(b!==_)throw new Error("bad point: equation left != right (1)");let m=c(x*k),v=c(A*B);if(m!==v)throw new Error("bad point: equation left != right (2)")}equals(f){h(f);let{X:g,Y:y,Z:x}=this,{X:k,Y:A,Z:B}=f,E=c(g*B),C=c(k*x),S=c(y*B),D=c(A*x);return E===C&&S===D}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:f}=i,{X:g,Y:y,Z:x}=this,k=c(g*g),A=c(y*y),B=c(tn*c(x*x)),E=c(f*k),C=g+y,S=c(c(C*C)-k-A),D=E+A,L=D-B,b=E-A,_=c(S*L),m=c(D*b),v=c(S*b),T=c(L*D);return new p(_,m,T,v)}add(f){h(f);let{a:g,d:y}=i,{X:x,Y:k,Z:A,T:B}=this,{X:E,Y:C,Z:S,T:D}=f,L=c(x*E),b=c(k*C),_=c(B*y*D),m=c(A*S),v=c((x+k)*(E+C)-L-b),T=m-_,H=m+_,U=c(b-g*L),j=c(v*T),V=c(H*U),G=c(v*U),z=c(T*H);return new p(j,V,z,G)}subtract(f){return h(f),this.add(f.negate())}multiply(f){if(!o.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:y}=w.cached(this,f,x=>Et(p,x));return Et(p,[g,y])[0]}multiplyUnsafe(f){if(!o.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===de?p.ZERO:this.is0()||f===M?this:w.unsafe(this,f,g=>Et(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(f){let g=this,y=f,{X:x,Y:k,Z:A}=g,B=g.is0();y==null&&(y=B?is:s.inv(A));let E=c(x*y),C=c(k*y),S=s.mul(A,y);if(B)return{x:de,y:M};if(S!==M)throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===M?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:g}=this.toAffine(),y=s.toBytes(g);return y[y.length-1]|=f&M?128:0,y}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new vt(p,o.BITS);return o.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Xt()}static fromHex(e){Xt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Gt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function ur(n,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,s=t;re(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:u}=n,c=r.outputLen,l=2*a.BYTES;if(c!==void 0&&(ne(c,"hash.outputLen"),c!==l))throw new Error(`hash.outputLen must be ${l}, got ${c}`);let d=s.randomBytes===void 0?bt:s.randomBytes,h=s.adjustScalarBytes===void 0?b=>b:s.adjustScalarBytes,p=s.domain===void 0?(b,_,m)=>{if(Ee(m,"phflag"),_.length||m)throw new Error("Contexts/pre-hash are not supported");return b}:s.domain;function w(b){return u.create(K(b))}function R(b){let _=E.secretKey;O(b,E.secretKey,"secretKey");let m=O(r(b),2*_,"hashedSecretKey"),v=h(m.slice(0,_)),T=m.slice(_,2*_),H=w(v);return{head:v,prefix:T,scalar:H}}function f(b){let{head:_,prefix:m,scalar:v}=R(b),T=i.multiply(v),H=T.toBytes();return{head:_,prefix:m,scalar:v,point:T,pointBytes:H}}function g(b){return f(b).pointBytes}function y(b=Uint8Array.of(),..._){let m=Q(..._);return w(r(p(m,O(b,void 0,"context"),!!o)))}function x(b,_,m={}){b=O(b,void 0,"message"),o&&(b=o(b));let{prefix:v,scalar:T,pointBytes:H}=f(_),U=y(m.context,v,b),j=i.multiply(U).toBytes(),V=y(m.context,j,H,b),G=u.create(U+V*T);if(!u.isValid(G))throw new Error("sign failed: invalid s");let z=Q(j,u.toBytes(G));return O(z,E.signature,"result")}let k={zip215:s.zip215};function A(b,_,m,v=k){let{context:T}=v,H=v.zip215===void 0?!!k.zip215:v.zip215,U=E.signature;b=O(b,U,"signature"),_=O(_,void 0,"message"),m=O(m,E.publicKey,"publicKey"),H!==void 0&&Ee(H,"zip215"),o&&(_=o(_));let j=U/2,V=b.subarray(0,j),G=K(b.subarray(j,U)),z,Ze,we;try{z=n.fromBytes(m,H),Ze=n.fromBytes(V,H),we=i.multiplyUnsafe(G)}catch{return!1}if(!H&&z.isSmallOrder())return!1;let Xe=y(T,V,m,_);return Ze.add(z.multiplyUnsafe(Xe)).subtract(we).clearCofactor().is0()}let B=a.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function C(b){return b=b===void 0?d(E.seed):b,O(b,E.seed,"seed")}function S(b){return gt(b)&&b.length===E.secretKey}function D(b,_){try{return!!n.fromBytes(b,_===void 0?k.zip215:_)}catch{return!1}}let L={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:S,isValidPublicKey:D,toMontgomery(b){let{y:_}=n.fromBytes(b),m=E.publicKey,v=m===32;if(!v&&m!==57)throw new Error("only defined for 25519 and 448");let T=v?a.div(M+_,M-_):a.div(_-M,_+M);return a.toBytes(T)},toMontgomerySecret(b){let _=E.secretKey;O(b,_);let m=r(b.subarray(0,_));return h(m).subarray(0,_)}};return Object.freeze(E),Object.freeze(L),Object.freeze({keygen:kt(C,g),getPublicKey:g,sign:x,verify:A,utils:L,Point:n,lengths:E})}function je(n,e){if(ne(n),ne(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(n<0||n>2**(8*e)-1)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function cs(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function us(n){if(!gt(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof n=="string"?yt(n):n;if(e.length===0)throw new Error("DST must be non-empty");return e}function nn(n,e,t,r){O(n),ne(t),e=us(e),e.length>255&&(e=r(Q(yt("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=r,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Q(e,je(e.length,1)),u=new Uint8Array(o),c=je(t,2),l=new Array(i),d=r(Q(u,n,c,je(0,1),a));l[0]=r(Q(d,je(1,1),a));for(let p=1;p<i;p++){let w=[cs(d,l[p-1]),je(p+1,1),a];l[p]=r(Q(...w))}return Q(...l).slice(0,t)}var lr="HashToScalar-";var $e=BigInt(0),Ae=BigInt(1),St=BigInt(2);function ls(n){return re(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...n})}function dr(n){let e=ls(n),{P:t,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");let u=i===void 0?bt:i,c=a?255:448,l=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?St**BigInt(254):St**BigInt(447),w=a?BigInt(8)*St**BigInt(251)-Ae:BigInt(4)*St**BigInt(445)-Ae,R=p+w+Ae,f=m=>I(m,t),g=y(d);function y(m){return mt(f(m),l)}function x(m){let v=le(O(m,l,"uCoordinate"));return a&&(v[31]&=127),f(K(v))}function k(m){return K(s(le(O(m,l,"scalar"))))}function A(m,v){let T=D(x(v),k(m));if(T===$e)throw new Error("invalid private or public key received");return y(T)}function B(m){return A(m,g)}let E=B,C=A;function S(m,v,T){let H=f(m*(v-T));return v=f(v-H),T=f(T+H),{x_2:v,x_3:T}}function D(m,v){ke("u",m,$e,t),ke("scalar",v,p,R);let T=v,H=m,U=Ae,j=$e,V=m,G=Ae,z=$e;for(let we=BigInt(c-1);we>=$e;we--){let Xe=T>>we&Ae;z^=Xe,{x_2:U,x_3:V}=S(z,U,V),{x_2:j,x_3:G}=S(z,j,G),z=Xe;let Ye=U+j,We=f(Ye*Ye),Ot=U-j,_n=f(Ot*Ot),wn=We-_n,Mr=V+G,Fr=V-G,Rn=f(Fr*Ye),vn=f(Mr*Ot),En=Rn+vn,kn=Rn-vn;V=f(En*En),G=f(H*f(kn*kn)),U=f(We*_n),j=f(wn*(We+f(h*wn)))}({x_2:U,x_3:V}=S(z,U,V)),{x_2:j,x_3:G}=S(z,j,G);let Ze=o(j);return f(U*Ze)}let L={secretKey:l,publicKey:l,seed:l},b=m=>(m=m===void 0?u(l):m,O(m,L.seed,"seed"),m),_={randomSecretKey:b};return Object.freeze(L),Object.freeze(_),Object.freeze({keygen:kt(b,E),getSharedSecret:C,getPublicKey:E,scalarMult:A,scalarMultBase:B,utils:_,GuBytes:g.slice(),lengths:L})}var ds=BigInt(0),oe=BigInt(1),fr=BigInt(2),fs=BigInt(3),ps=BigInt(5),hs=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),an={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:hs,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gr(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),o=ye,a=n*n%o*n%o,u=Z(a,fr,o)*a%o,c=Z(u,oe,o)*n%o,l=Z(c,ps,o)*c%o,d=Z(l,e,o)*l%o,h=Z(d,t,o)*d%o,p=Z(h,r,o)*h%o,w=Z(p,s,o)*p%o,R=Z(w,s,o)*p%o,f=Z(R,e,o)*l%o;return{pow_p_5_8:Z(f,fr,o)*n%o,b2:a}}function br(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var rn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function cn(n,e){let t=ye,r=I(e*e*e,t),s=I(r*r*e,t),o=gr(n*s).pow_p_5_8,i=I(n*r*o,t),a=I(e*i*i,t),u=i,c=I(i*rn,t),l=a===n,d=a===I(-n,t),h=a===I(-n*rn,t);return l&&(i=u),(d||h)&&(i=c),se(i,t)&&(i=I(-i,t)),{isValid:l||d,value:i}}var pe=cr(an,{uvRatio:cn}),fe=pe.Fp,mr=pe.Fn;function gs(n){return ur(pe,ft,Object.assign({adjustScalarBytes:br,zip215:!0},n))}var yr=gs({});var xe=(()=>{let n=ye;return dr({P:n,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:r}=gr(e);return I(Z(t,fs,n)*r,n)},adjustScalarBytes:br})})();var sn=rn,bs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ms=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ys=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),xs=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),pr=n=>cn(oe,n),_s=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),on=n=>fe.create(K(n)&_s);function hr(n){let{d:e}=an,t=ye,r=g=>fe.create(g),s=r(sn*n*n),o=r((s+oe)*ys),i=BigInt(-1),a=r((i-e*s)*r(s+e)),{isValid:u,value:c}=cn(o,a),l=r(c*n);se(l,t)||(l=r(-l)),u||(c=l),u||(i=s);let d=r(i*(s-oe)*xs-a),h=c*c,p=r((c+c)*a),w=r(d*bs),R=r(oe-h),f=r(oe+h);return new pe(r(p*f),r(R*w),r(w*f),r(p*R))}var he=class n extends At{static BASE=new n(pe.BASE);static ZERO=new n(pe.ZERO);static Fp=fe;static Fn=mr;constructor(e){super(e)}static fromAffine(e){return new n(pe.fromAffine(e))}assertSame(e){if(!(e instanceof n))throw new Error("RistrettoPoint expected")}init(e){return new n(e)}static fromBytes(e){$(e,32);let{a:t,d:r}=an,s=ye,o=k=>fe.create(k),i=on(e);if(!jn(fe.toBytes(i),e)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),u=o(oe+t*a),c=o(oe-t*a),l=o(u*u),d=o(c*c),h=o(t*r*l-d),{isValid:p,value:w}=pr(o(h*d)),R=o(w*c),f=o(w*R*h),g=o((i+i)*R);se(g,s)&&(g=o(-g));let y=o(u*f),x=o(g*y);if(!p||se(x,s)||y===ds)throw new Error("invalid ristretto255 encoding 2");return new n(new pe(g,y,oe,x))}static fromHex(e){return n.fromBytes(Pe(e))}toBytes(){let{X:e,Y:t,Z:r,T:s}=this.ep,o=ye,i=f=>fe.create(f),a=i(i(r+t)*i(r-t)),u=i(e*t),c=i(u*u),{value:l}=pr(i(a*c)),d=i(l*a),h=i(l*u),p=i(d*h*s),w;if(se(s*p,o)){let f=i(t*sn),g=i(e*sn);e=f,t=g,w=i(d*ms)}else w=h;se(e*p,o)&&(t=i(-t));let R=i((r-t)*w);return se(R,o)&&(R=i(-R)),fe.toBytes(R)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:s,Y:o}=e.ep,i=c=>fe.create(c),a=i(t*o)===i(r*s),u=i(r*o)===i(t*s);return a||u}is0(){return this.equals(n.ZERO)}};Object.freeze(he.BASE);Object.freeze(he.ZERO);Object.freeze(he.prototype);Object.freeze(he);var ws=Object.freeze({Point:he,hashToCurve(n,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=nn(n,t,64,ft);return ws.deriveToCurve(r)},hashToScalar(n,e={DST:lr}){let t=nn(n,e.DST,64,ft);return mr.create(K(t))},deriveToCurve(n){$(n,64);let e=on(n.subarray(0,32)),t=hr(e),r=on(n.subarray(32,64)),s=hr(r);return new he(t.add(s))}});var Ct=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ue(e),$(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),X(s)}update(e){return ve(this),this.iHash.update(e),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},un=(()=>{let n=((e,t,r)=>new Ct(e,t).update(r).digest());return n.create=(e,t)=>new Ct(e,t),n})();function Rs(n,e,t){return Ue(n),t===void 0&&(t=new Uint8Array(n.outputLen)),un(n,t,e)}var ln=Uint8Array.of(0),xr=Uint8Array.of();function vs(n,e,t,r=32){Ue(n),ie(r,"length"),$(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(r/s);t===void 0?t=xr:$(t,void 0,"info");let i=new Uint8Array(o*s),a=un.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let l=0;l<o;l++)ln[0]=l+1,u.update(l===0?xr:c).update(t).update(ln).digestInto(c),i.set(c,s*l),a._cloneInto(u);return a.destroy(),u.destroy(),X(c,ln),i.slice(0,r)}var _r=(n,e,t,r,s)=>vs(n,Rs(n,e,t),r,s);var Es=new TextEncoder().encode("mygate-e2e-sealed-box-v1"),Ve=32,Se=12;function dn(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function fn(n){if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}return new Uint8Array(Buffer.from(n,"base64"))}function Ge(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function _e(n){if(n.length%2!==0)throw new Error("hex length must be even");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function wr(...n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Rr(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function vr(){return xe.utils.randomSecretKey()}function pn(n){return xe.getPublicKey(n)}async function Er(n){if(n.length!==32)throw new Error(`AES-256-GCM key must be 32 bytes, got ${n.length}`);return globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function kr(n,e){let t=await Er(n),r=Rr(Se),s=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,e);return{ciphertext:new Uint8Array(s),nonce:r}}async function Ar(n,e,t){if(t.length!==Se)throw new Error(`AES-GCM nonce must be ${Se} bytes`);let r=await Er(n),s=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:t},r,e);return new Uint8Array(s)}function Sr(n,e,t){return _r(Ne,n,wr(e,t),Es,32)}async function ks(n,e){if(n.length!==32)throw new Error("X25519 recipient public key must be 32 bytes");let t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=xe.getSharedSecret(t,n),o=Sr(s,r,n),{ciphertext:i,nonce:a}=await kr(o,e);return wr(r,a,i)}async function As(n,e,t){if(t.length<Ve+Se+16)throw new Error("sealed box payload too short");let r=t.slice(0,Ve),s=t.slice(Ve,Ve+Se),o=t.slice(Ve+Se),i=xe.getSharedSecret(n,r),a=Sr(i,r,e);return Ar(a,o,s)}async function Cr(n,e){let t=Rr(32),{ciphertext:r,nonce:s}=await kr(t,e),o=await ks(_e(n),t);return{ciphertext_b64:dn(r),wrapped_key_b64:dn(o),payload_iv_b64:dn(s)}}async function Br(n,e){let t=_e(n),r=pn(t),s=await As(t,r,fn(e.wrapped_key_b64));return Ar(s,fn(e.ciphertext_b64),fn(e.payload_iv_b64))}var Tr="application/vnd.nodata.command+json",Or="nodata.command/1";var Ss=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Cs=/^[a-z][a-z0-9_]{0,63}$/;function hn(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not_an_object"};let e=n,t=new Set(["nodata","id","cmd","fields","reply_to","issued_at"]),r=Object.keys(e).filter(i=>!t.has(i));if(r.length)return{ok:!1,reason:`unexpected_keys:${r.join(",")}`};if(e.nodata!==Or)return{ok:!1,reason:"not_a_command"};if(typeof e.id!="string"||!/^[0-9a-f-]{36}$/i.test(e.id))return{ok:!1,reason:"bad_id"};if(typeof e.cmd!="string"||!Ss.test(e.cmd))return{ok:!1,reason:"bad_cmd"};if(e.reply_to!==null&&(typeof e.reply_to!="string"||!/^[0-9a-f-]{36}$/i.test(e.reply_to)))return{ok:!1,reason:"bad_reply_to"};if(typeof e.issued_at!="string"||Number.isNaN(Date.parse(e.issued_at)))return{ok:!1,reason:"bad_issued_at"};if(!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return{ok:!1,reason:"bad_fields"};let s=e.fields,o=Object.keys(s);if(o.length>64)return{ok:!1,reason:"too_many_fields"};for(let i of o){if(!Cs.test(i))return{ok:!1,reason:`bad_field_name:${i}`};let a=s[i];if(!(a===null||typeof a=="boolean"||typeof a=="number"||typeof a=="string"))return{ok:!1,reason:`field_not_flat:${i}`};if(typeof a=="string"&&a.length>2e3)return{ok:!1,reason:`field_too_long:${i}`}}return{ok:!0,envelope:e}}function Ir(n,e,t=null,r=new Date){let s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():Bs();return{nodata:Or,id:s,cmd:n,fields:e,reply_to:t,issued_at:r.toISOString()}}function Bs(){let n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function gn(n){let e=t=>t===null||typeof t!="object"?t:Array.isArray(t)?t.map(e):Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])]));return JSON.stringify(e(n))}var Ko={"read-request":{name:"request.json",maxBytes:16384},"read-refused":{name:"refused.json",maxBytes:16384},"folder-projection":{name:"projection.json",maxBytes:48*1024}};var bn={version:1,note:"NoData's public signing keys, pinned. chain_keys sign receipts and epoch seal roots; pack_envelope_signers sign evidence-pack envelopes. Source: https://nodatachat.com/api/chain/pubkey at publish time. A key counts only once a published version of this package lists it. receipt_context_since: when the key began signing receipts in their signing context (server mig 612, read from production 2026-10-19); a context-free receipt it signed after that (+15 min) fails verification.",pinned_from:"https://nodatachat.com/api/chain/pubkey (chain key, read 2026-09-30) \xB7 claude_identities where admin_user_id = the pack-signing identity (envelope signer, read 2026-09-30)",chain_keys:[{kid:"nd-chain-2026-05-03-bc58",ed25519_pubkey_hex:"b525adfa0035d5c7351b514a0316142586de9468ec5ee3b708cff0c4585b5036",ml_dsa65_pubkey_hex:"cc46f06f86d1b4a608a4c1167f1494a4cd1a837d215ff88e7b1aca49e82be3f32e190e1836d477670bae2c8a6f7648d3ce0d93b2f51ab0d3150d7dd45b0cf8217f119388e5a4b3770459654c4b0caab4d8a0ccdafdbc5231cd6c26410c38cd0ec62b21bf73b8e1e82daca3b1e4d520d9d25041917f4fd2b92bb19ffbe50f569ca29fa0185923732949daf5f832805303ef5a020cf3ea9de395d66e54d9bf52a56875087096cd8470918b7f25d623335c8662e7c8e6cefce7b88cc4cc6f7d32ed0f1a00332606af78332e9febb72b7e77b396b9da5ff96167055305595327ead40d2084a50f0d3fcd2423d8ed46edc5459ed1b0ff5a14f142bb38511b99a6da841895ccd65c19ab856bbdee270b48bc01ee8b0243fbc6e806851831409e5ae90d9c3300a9125042fd9b6d381c3eb09d5ee6f33e36bd5b41572bcce0350af8e217963154b550a163c5203f9a38a65312f23088c568d5af720c2ff4e979491109ca9ffdb9edc46f31410939e0264cbc02ea0106f9d6c8616222655e6593f8be5b9fa4423afec46aea9d53e42eb5d3f976cdd86d978a4599b87198d4fb8054bc40828f4d0100131537030053645616ecf48d013f8bbafb3a404735b7ffd6c88273765af340e84207f48be92e909ece357fa6ea2050e085570f413e48179a5aaac2bf216e54714d3ee1102e91fd23305b50b14b133299be4517d074732976b003a6669ecbceb2e40a8a1b2f4ca2b2a25d017b404b21672a0de61a45fd153684d730dc126f30a406d6b06447180258a9659cb3de926abd997b3f740c2783e334dd914ac663abc7f96217844ef0611619c35e30ed55f1563d8183b9f586d6c34715ce68708806105426e897df1473d53da835bed6288951238ed694c154655455ff61e13caeb592cc2857537fe9d2eb723bcad3898396af9673ba5b2f722092f0d2a9388e960ccde7272df5e2fe0ea9e499a909b655a59c85cfa1c622c651c8af20b4fb8bab9ab78d951c621d4b75c812246b2e925bcde42cc6a0a13467b4bcfb9aea5e4949effc71769dccc619eafc6d229cba478e3ad7289dc14b0c4842b4cf0cadd30deb9375fc1659d084779819705a6da7bccbf8d21ecd82391de5b61126d5b872f7d95514717b6fdc218dc0a048364c46142b114ee10d582740668f5b105edc034eb794c7e3906c77a44677e67709dbb1d3078783b488473e83e457e6ab98d2d659cf50066bc7f01190e065a9ef955e0257535bd5fab8ad007673637b2d005349e7f19fea2eeea82597867d5e366e41993775e4f4f70869fb1f9989d6d9902787f8233e9c7e586fe6bcf799ecf2da02ce08232ef1315b4e8857bcdb58bda53991f529d2ff023d0279552396dd0bb0fceaaf5dfb9eda0160bb09dd92b8085bc92c6006c20409cf9a5079072a09df221a76efc5ec13c97d154d22e382018ed8eb767f77aae578121c2231fe964338e637e7c060d555a2574b49c08956c729e79090b917e162488b1c9e962a3a921ac6f98a8c020c48aa2812f2f7a205a2d23aa2be1a953d9e33fbdea94688cf3d44200ed2cb009be8b684e99a96f0bc59eff5490eee0636b8b5665d7ddbb6ad44b90caa62b524f8a1caf6d0dbbc5e2ef0c2e65976d94e80e8dbd5ab8a420fdb638562bd2181c0ca243496582bab2847394e1e2dd4a24d4b24794b770b2475916746fb2bdc50f7994b4b346bfcfc5b4a99266cdf551340903d6994206ae1edb968c15d89f2a4cc6f3cb27b88989489b598f76fb6d1afa52e3a4c73175a216fa30d76acfccade7adb5628a88931b37bcff93c615a78a0b47827e385395e0b53c683f2ff07dd6cc636a086c295f06766570fc7652568676ecc5869378bdc0a63753807f1c7de7e5525d48328fa4103ed2ce9abafe0dc861055be6943cf2a87371ec1f9205c1955ddcf2f2ca982d877040dc92bf64278273c5ebbe3de0ef9d5eae255359e7ac97123b92488ffd0f1ea7deca36110135e02988be06bba4a3bf1b0da067976a6bc0c166ac349b2a853eb204fec6c142cad3decb05da15448f0d82d5faed3bc4beb400c51e05de06d950c128e2d3323a2d47dbf88684970084ed6608b95d7d585c3762c714c063c0a4ce1cacd5b31f261376bd972982957150dbbeb158999c1f60a76c6233a8749c10c016e0ad69bdac19e8c4d28126b7cc79c79aa82c25cef5521afdd759ca198b77c1a4a5f2c0497a4136e9818113c612d109de2cfaba691e05b791474599bf5cb918097f07b95dde658d2c5c01bf2bb6715dcb40c4c5686ec1642f9fd84377a90ea2456561ff91ba798d98211975c3da57be1b1e57a4660f979407e5f8616c4f62730161d2dcd86cf5383665c64cb77abbcf2e1406bc189e9575e3c1407aa6a467e6bd7a8edf7affde32b88dfa178902163a37c6b6c6bacb777a0bfbf46a0324c0ae5de7c2bdb6aad6ce51c0f5b4a5ab7c139d6bcdacc8ea46e37e040b785dbfc3145e408593c6f143dc1b4fde763e32e6d60c32d1a5c6d0bdf2d7d97f2bdeeba4a439abe7c75daced72a7678af1412f6c2917e39d6419c103f3a32e964369136a1183feb8d484712bcde8b14e2e8a7374dfb0dd7ee07dd15727b340005ed98bf5850b9de92b1912639e15f91d16968cd8bc336afc132ec6c93deba843e636de52f32be6e3c1e0ea50fdf03206c8dfa74f4c600e7d4d133c2ccc61ac50ae2f54e4f1ad02dc7ec86d8732cf12f0ac2c2ee10de6829695e539a6f76f9d9a4cda9d2ed1377c7a203baff1b",created_at:"2026-05-03T08:06:17.512936+00:00",retired_at:null,receipt_context_since:"2026-10-19T09:50:04.571Z"}],pack_envelope_signers:[{kid:"pack-signer-2026-04-29",ed25519_pubkey_hex:"853a62cb452a35fd6499d8fedb97448e0e24ef0d071343b2c9652aa2831bbdf6",status:"active",created_at:"2026-04-29T18:20:16.11538+00:00"}]};var xn=[...bn.chain_keys.filter(n=>!n.retired_at).map(n=>n.ed25519_pubkey_hex.toLowerCase()),...bn.pack_envelope_signers.map(n=>n.ed25519_pubkey_hex.toLowerCase())];function Ur(n){return Ge(Ne(_e(n))).slice(0,16)}var Dr="connect-command",ze=/^[0-9a-f]{16}$/,Os=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Bt=class extends F{constructor(t,r,s,o){super(o,428,"approval_required");this.approveUrl=t;this.approvalId=r;this.orgApprovalId=s;this.name="FabricApprovalRequired"}};function mn(){return Ge(vr())}var Ke=class{constructor(e){this.http=e}newSecret(){return mn()}async open(e={}){let t=(e.secret??mn()).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("nd.fabric: secret must be 64 hex characters (nd.fabric.newSecret())");let r=Ge(pn(_e(t))),s=await this.http.raw("POST",`/api/v1/relay/enroll${e.replace?"?replace=true":""}`,{ecdh_pubkey_hex:r});if(!s.ok)throw J("enroll",s);let o=String(s.data.ecdh_kid??"");if(!ze.test(o))throw new F("enroll answered without an address",s.status);if(o!==Ur(r))throw new F("enroll answered an address that is not this key's",s.status,"address_mismatch");return new Tt(this.http,t,o,(e.trustedReceiptKeys??xn).map(i=>i.toLowerCase()))}},Tt=class{constructor(e,t,r,s=xn){this.http=e;this.secret=t;this.address=r;this.trustedReceiptKeys=s}async invite(e={}){let t=await this.http.raw("POST","/api/v1/fabric-grants",{action:"invite",my_kid:this.address,template:"ping",...e.note?{note:e.note}:{},...e.days?{grant_days:e.days}:{},...Hr(e)});if(!t.ok)throw J("invite",t);return{url:String(t.data.invite_url??""),expiresAt:typeof t.data.expires_at=="string"?t.data.expires_at:null,grantDays:typeof t.data.grant_days=="number"?t.data.grant_days:null}}async accept(e,t={}){let r=e.match(/invite=([^&\s]+)/),s=decodeURIComponent(r?r[1]:e.trim());if(!s.includes("."))throw new Error("nd.fabric.accept: give the invitation link or its token");let o=await this.http.raw("POST","/api/v1/fabric-grants",{action:"accept",token:s,subject_kid:this.address,mutual:t.oneWay!==!0,...t.termsAccepted?{terms_accepted:!0}:{},...Hr(t)});if(!o.ok)throw J("accept",o);let i=o.data.partner??{};if(!i.sender_kid||!ze.test(i.sender_kid))throw new F("connected, but the invitation named no address of theirs to send to (they invited without one)",o.status,"no_partner_address");return{kid:i.sender_kid,name:i.name??null}}async partners(){let e=await this.http.raw("GET","/api/v1/fabric-grants");if(!e.ok)throw J("partners",e);return Is(e.data)}async send(e,t,r={},s={}){if(!Os.test(t))throw new Error(`nd.fabric.send: '${t}' is not a command name (e.g. order.create)`);let o=await this.addressOf(e),i=Ir(t,r,s.replyTo??null),a=hn(i);if(!a.ok)throw new Error(`nd.fabric.send: not a command (${a.reason})`);let u=gn(i),c=await this.http.raw("GET",`/api/v1/relay/resolve?handle=${encodeURIComponent(o)}`);if(!c.ok)throw J("resolve",c);let l=String(c.data.recipient_pubkey??"");if(!/^[0-9a-f]{64}$/.test(l))throw new F(`${o} has no public key to seal to`,c.status,"no_public_key");if(Ur(l)!==o)throw new F(`the key the directory gave for ${o} is not that address's key; nothing was sent`,c.status,"key_mismatch");let d=await Cr(l,new TextEncoder().encode(u)),h=await this.http.raw("POST","/api/v1/relay/send",{recipient_kid:o,...d,route_taken:"capsule",content_type_hint:Tr,purpose:Dr,ttl_hours:Math.min(Math.max(s.ttlHours??24,1),720),max_fetches:Math.min(Math.max(s.opens??1,1),20),released_sha256:Lr(u)});if(!h.ok)throw J("send",h);return{id:String(h.data.id??""),commandId:i.id,to:o}}reply(e,t,r={}){if(!e.commandId)throw new Error("nd.fabric.reply: this message was not an opened command");return this.send(e.from,t,r,{replyTo:e.commandId})}async inbox(e={}){let t=await this.http.raw("GET","/api/v1/relay/inbox");if(!t.ok)throw J("inbox",t);let r=(t.data.items??[]).filter(i=>i.purpose===Dr),s=e.accept?new Set(e.accept):null,o=[];for(let i of r){let a={relayId:i.id,from:i.sender_kid,fromOrg:i.sender?.org??null},u=await this.http.raw("GET",`/api/v1/relay/fetch/${encodeURIComponent(i.id)}`);if(!u.ok){o.push({...a,status:"unopened",reason:String(u.data.refused??u.data.error??u.status),verified:{committed:null,receiptSignature:null}});continue}let c=Ds(u.data.receipt,this.trustedReceiptKeys),l=null;try{let p=await Br(this.secret,u.data),w=hn(JSON.parse(new TextDecoder().decode(p)));l=w.ok?w.envelope:null}catch{l=null}if(!l){o.push({...a,status:"refused",reason:"not_a_command",verified:{committed:null,receiptSignature:c}});continue}let h={committed:typeof u.data.released_sha256=="string"?Lr(gn(l))===u.data.released_sha256:null,receiptSignature:c};if(s&&!s.has(l.cmd)){o.push({...a,status:"refused",reason:`not_accepted:${l.cmd}`,cmd:l.cmd,commandId:l.id,verified:h});continue}o.push({...a,status:"accepted",cmd:l.cmd,fields:l.fields,replyTo:l.reply_to,commandId:l.id,issuedAt:l.issued_at,verified:h})}return o}onCommand(e,t={}){let r=Math.max(t.everyMs??5e3,250),s=new Set,o=!1,i=null,a=()=>{o=!0,i?.()};t.signal?.aborted&&(o=!0),t.signal?.addEventListener("abort",a,{once:!0});let u=()=>new Promise(l=>{let d=setTimeout(l,r);i=()=>{clearTimeout(d),l()}}),c=(async()=>{for(;!o;){try{for(let l of await this.inbox({accept:t.accept})){if(o)break;if(!(l.status==="unopened"||s.has(l.relayId))){s.add(l.relayId),s.size>5e3&&s.delete(s.values().next().value);try{l.status==="accepted"?await e(l):await t.onRefused?.(l)}catch(d){await t.onError?.(d)}}}}catch(l){await t.onError?.(l)}o||await u()}})();return{stop:async()=>{a(),await c},get running(){return!o}}}async disconnect(e){let t=await this.addressOf(e),r=await this.http.raw("GET","/api/v1/fabric-grants");if(!r.ok)throw J("partners",r);let s=(r.data.grants??[]).filter(a=>!a.revoked_at&&a.subject_kid===t),o=(r.data.inbound??[]).filter(a=>a.subject_kid===this.address&&(a.allowed_sender_kids??[]).includes(t)),i=0;for(let a of s){let u=await this.http.raw("PATCH","/api/v1/fabric-grants",{grant_id:a.id,reason:"disconnected from the SDK"});if(!u.ok)throw J("disconnect",u);i++}for(let a of o){let u=await this.http.raw("POST","/api/v1/fabric-grants",{action:"leave",grant_id:a.id});if(!u.ok)throw J("disconnect",u);i++}return{ended:i}}async addressOf(e){if(typeof e!="string")return e.kid;let t=e.trim().toLowerCase();if(ze.test(t))return t;let r=(await this.partners()).filter(s=>(s.name??"").toLowerCase()===t);if(r.length===1)return r[0].kid;throw new Error(r.length?`nd.fabric: '${e}' names ${r.length} connections; use the address`:`nd.fabric: no connection named '${e}'`)}};function Is(n){let e=new Map;for(let t of n.grants??[])!t.revoked_at&&ze.test(t.subject_kid)&&e.set(t.subject_kid,{kid:t.subject_kid,name:t.partner_name??null});for(let t of n.inbound??[])for(let r of t.allowed_sender_kids??[]){if(!ze.test(r))continue;let s=e.get(r);e.set(r,{kid:r,name:s?.name??t.partner_name??null})}return[...e.values()]}function Lr(n){return Ge(Ne(new TextEncoder().encode(n)))}function yn(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return"["+n.map(yn).join(",")+"]";let e=n;return"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+yn(e[t])).join(",")+"}"}function Ds(n,e=xn){let t=n;if(!t?.payload||!t.signature_hex||!t.signing_pubkey_hex)return null;if(!e.includes(t.signing_pubkey_hex.toLowerCase()))return!1;try{return yr.verify(_e(t.signature_hex),new TextEncoder().encode(yn(t.payload)),_e(t.signing_pubkey_hex))}catch{return!1}}function Hr(n){return n.orgApprovalId?{org_approval_id:n.orgApprovalId}:n.approvalId?{approval_id:n.approvalId}:{}}function J(n,e){let t=e.data;if(e.status===428){let s=typeof t.approval=="object"&&t.approval!==null?t.approval:{},o=typeof t.lock=="object"&&t.lock!==null?t.lock:{};return new Bt((s.approve_url??(typeof t.approve_url=="string"?t.approve_url:null))||null,s.approval_id??null,o.lock_id??null,`${n}: waiting for a person's approval${t.why?` (${String(t.why)})`:""}. Approve it in the browser, then call again with the approval id.`)}let r=String(t.refused??t.error??`HTTP ${e.status}`);return new F(`${n} refused: ${r}${t.reason?` (${String(t.reason)})`:t.why?` (${String(t.why)})`:""}`,e.status,String(t.refused??t.error??""))}var Pr=class{http;_encrypt;capsules;tenants;scan;fabric;engines;_compute;constructor(e){this.http=new Qe(e),this._compute=new He(this.http),this._encrypt=new Re(this.http),this.capsules=new Oe(this.http),this.tenants=new Ie(this.http),this.scan=new De(this.http),this.fabric=new Ke(this.http),this.engines=new Le(this.http)}compute(e){return this._compute.run(e)}verify(e){return this._compute.verify(e)}authorize(e){return this.http.post("/api/v1/authorize",e)}get channel(){return this.engines.channel}get webhook(){return this.engines.webhook}get deliver(){return this.engines.deliver}get evidence(){return this.engines.evidence}get vault(){return this.engines.vault}get governance(){return this.engines.governance}agent(e){return new Be(this.http.baseURL,e)}encrypt(e){return this._encrypt.encrypt(e)}decrypt(e){return this._encrypt.decrypt(e)}batchEncrypt(e,t){return this._encrypt.batchEncrypt(e,t)}batchDecrypt(e,t){return this._encrypt.batchDecrypt(e,t)}batchNative(e,t){return this._encrypt.batchNative(e,t)}encryptObject(e,t,r){return this._encrypt.encryptObject(e,t,r)}decryptObject(e,t,r){return this._encrypt.decryptObject(e,t,r)}async ping(){let e=Date.now();return await this.http.get("/api/health"),{success:!0,latencyMs:Date.now()-e}}};export{F as a,Ce as b,Be as c,Je as d,et as e,tt as f,nt as g,Te as h,Oe as i,Ie as j,De as k,Le as l,He as m,Bt as n,mn as o,Ke as p,Tt as q,Pr as r};
2
+ /*! Bundled license information:
3
+
4
+ @noble/curves/utils.js:
5
+ @noble/curves/abstract/modular.js:
6
+ @noble/curves/abstract/curve.js:
7
+ @noble/curves/abstract/edwards.js:
8
+ @noble/curves/abstract/montgomery.js:
9
+ @noble/curves/ed25519.js:
10
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
11
+ */
package/dist/index.d.mts CHANGED
@@ -318,6 +318,8 @@ interface CapsuleSummary {
318
318
  member_count: number;
319
319
  portable_mode: PortableMode;
320
320
  created_at: string;
321
+ /** Set when the capsule was just created: the first receipt on its own chain. */
322
+ receipt_id?: string;
321
323
  }
322
324
  interface CreateCapsuleRequest {
323
325
  /** Tenant-scoped opaque handle, /^[a-z0-9-]{3,64}$/, e.g. "case-4471". */
@@ -361,6 +363,19 @@ interface AddDocumentRequest {
361
363
  recipients?: DocumentRecipient[];
362
364
  /** Use the tenant zero-knowledge path (existing behavior; per-capsule zk is Phase 1). */
363
365
  zero_knowledge?: boolean;
366
+ /** The capsule's existing members and AI agents reach this document too. Default true. */
367
+ inherit_access?: boolean;
368
+ }
369
+ /** What a new document took on from its capsule. */
370
+ interface InheritedAccess {
371
+ members: number;
372
+ agents: number;
373
+ /** Members whose rule needs an owner code: not inherited; add them with `members.add` and the code. */
374
+ needs_code: string[];
375
+ /** On the capsule's own chain, written before the access was copied. */
376
+ receipt_id: string | null;
377
+ /** Set when the receipt could not be written: nothing was inherited. */
378
+ error?: string;
364
379
  }
365
380
  interface AddDocumentResponse {
366
381
  ok: boolean;
@@ -369,6 +384,8 @@ interface AddDocumentResponse {
369
384
  sections_count: number;
370
385
  classifications: string[];
371
386
  recipients_saved: number;
387
+ /** Absent when `inherit_access: false` was sent. */
388
+ inherited?: InheritedAccess;
372
389
  recipient_codes: Array<{
373
390
  email: string;
374
391
  classifications: string[];
@@ -432,6 +449,8 @@ interface AddMemberResponse {
432
449
  capsule_id: string;
433
450
  member: CapsuleMember;
434
451
  recipient_code?: string;
452
+ /** The receipt on the capsule's own chain, written before the member got access. */
453
+ receipt_id: string;
435
454
  }
436
455
  interface ListMembersResponse {
437
456
  ok: boolean;
@@ -465,6 +484,16 @@ interface CapsuleReceipt {
465
484
  created_at: string;
466
485
  payload: Record<string, unknown> | null;
467
486
  }
487
+ /** A receipt on the capsule's own chain: minted, a member or AI agent granted/revoked, revoked. */
488
+ interface CapsuleChainReceipt {
489
+ id: string;
490
+ chain_index: number;
491
+ surface: 'capsule.mint' | 'capsule.access' | string;
492
+ decision: 'grant' | 'revoke' | string;
493
+ event_hash: string;
494
+ signature_hex: string | null;
495
+ created_at: string;
496
+ }
468
497
  interface CapsuleAuditResponse {
469
498
  ok: boolean;
470
499
  capsule_id: string;
@@ -473,9 +502,12 @@ interface CapsuleAuditResponse {
473
502
  opens: number;
474
503
  receipts: number;
475
504
  denied: number;
505
+ chain: number;
476
506
  };
477
507
  opens: CapsuleOpen[];
478
508
  receipts: CapsuleReceipt[];
509
+ /** Every change to who may reach the capsule, in chain order. */
510
+ chain: CapsuleChainReceipt[];
479
511
  verification: string;
480
512
  }
481
513
  /** Audit sub-resource on a capsule handle. */
@@ -497,6 +529,8 @@ interface RevokeCapsuleResponse {
497
529
  revoked_documents: string[];
498
530
  sessions_revoked: number;
499
531
  receipt_id: string | null;
532
+ /** The revoke on the capsule's own chain; null if it could not be written (the revoke still happened). */
533
+ chain_receipt_id: string | null;
500
534
  key_kid_blocked: boolean;
501
535
  customer_frozen: boolean;
502
536
  capsule_marked: boolean;
@@ -508,20 +542,24 @@ interface CapsuleAiGrant {
508
542
  denied_classifications: string[];
509
543
  documents: number;
510
544
  }
545
+ /** `receipt_id`: on the capsule's own chain, written before the grant was applied. */
511
546
  interface GrantAiResponse extends CapsuleAiGrant {
512
547
  ok: boolean;
513
548
  capsule_id: string;
549
+ receipt_id: string;
514
550
  }
515
551
  interface ListAiGrantsResponse {
516
552
  ok: boolean;
517
553
  capsule_id: string;
518
554
  agents: CapsuleAiGrant[];
519
555
  }
556
+ /** `revoked_documents` is a count. `receipt_id` is null when nothing was revoked or its receipt could not be written. */
520
557
  interface RevokeAiGrantResponse {
521
558
  ok: boolean;
522
559
  capsule_id: string;
523
560
  agent_id: string;
524
- revoked_documents: string[];
561
+ revoked_documents: number;
562
+ receipt_id: string | null;
525
563
  }
526
564
  interface AiReadSection {
527
565
  label: string;
@@ -968,6 +1006,11 @@ interface Message {
968
1006
  receiptSignature: boolean | null;
969
1007
  };
970
1008
  }
1009
+ /** A running onCommand watch. stop() ends it after the pass in flight. */
1010
+ interface CommandWatch {
1011
+ stop(): Promise<void>;
1012
+ readonly running: boolean;
1013
+ }
971
1014
  /** A held request: a person must approve it in the browser before it goes through. The SDK never approves. */
972
1015
  declare class FabricApprovalRequired extends NoDataError {
973
1016
  approveUrl: string | null;
@@ -1041,6 +1084,25 @@ declare class Fabric {
1041
1084
  inbox(opts?: {
1042
1085
  accept?: string[];
1043
1086
  }): Promise<Message[]>;
1087
+ /**
1088
+ * Run `handler` for every command that arrives. It polls inbox() (pull, the way
1089
+ * the MCP's partner-watch does), so NoData never calls into your systems: there
1090
+ * is no webhook to expose or secure. Only accepted commands reach the handler;
1091
+ * refused ones go to onRefused when given. Each relay envelope is handed over
1092
+ * once. A handler that throws does not stop the watch; onError hears it.
1093
+ *
1094
+ * const watch = fabric.onCommand(async (m) => {
1095
+ * await fabric.reply(m, 'order.ack', { ok: true });
1096
+ * }, { accept: ['order.create'] });
1097
+ * // later: await watch.stop();
1098
+ */
1099
+ onCommand(handler: (message: Message) => unknown, opts?: {
1100
+ accept?: string[];
1101
+ everyMs?: number;
1102
+ onRefused?: (message: Message) => unknown;
1103
+ onError?: (error: unknown) => unknown;
1104
+ signal?: AbortSignal;
1105
+ }): CommandWatch;
1044
1106
  /**
1045
1107
  * End the connection with a partner, both directions this side holds: a grant
1046
1108
  * we gave is revoked, a grant they gave us is left. Narrowing only; receipted on
@@ -1197,4 +1259,4 @@ interface AuthorizeResult {
1197
1259
  proof_url: string | null;
1198
1260
  }
1199
1261
 
1200
- export { type AddDocumentRequest, type AddDocumentResponse, type AddMemberRequest, type AddMemberResponse, AgentReadRequest, AgentReadResponse, AgentReader, type AiReadDocument, type AiReadResponse, type AiReadSection, type AuthorizeRequest, type AuthorizeResult, BatchResult, Capsule, CapsuleAi, type CapsuleAiGrant, CapsuleAudit, type CapsuleAuditResponse, CapsuleDocuments, type CapsuleKeyMode, type CapsuleMember, CapsuleMembers, CapsuleModule, type CapsuleOpen, type CapsuleReceipt, type CapsuleStatus, type CapsuleSummary, ChannelCreateRequest, ChannelCreateResponse, ChannelReceiveRequest, ChannelReceiveResponse, ChannelSendRequest, ChannelSendResponse, ComputeDecision, ComputeEngine, ComputeRequest, type CreateCapsuleRequest, type CreateTenantRequest, type CreateTenantResponse, DecryptRequest, DecryptResponse, DeliverRequest, DeliverResponse, type DocumentRecipient, type DocumentSection, type DocumentSummary, type EmbedTokenRequest, type EmbedTokenResponse, type EnableScanRequest, type EnableScanResponse, EncryptRequest, EncryptResponse, EnginesModule, EvidenceQuery, EvidenceResponse, Fabric, FabricApprovalRequired, FabricModule, type FieldValue, GovernanceModule, type GrantAiResponse, GrantRequest, GrantResponse, type Invitation, type ListAiGrantsResponse, type ListCapsulesResponse, type ListDocumentsResponse, type ListMembersResponse, type Message, NoData, NoDataConfig, NoDataError, type OverviewResponse, type Partner, type PortableMode, RegisterTableRequest, RegisterTableResponse, type RevokeAiGrantResponse, type RevokeCapsuleResponse, RevokeRequest, RevokeResponse, type ScanDeployment, type ScanFinding, type ScanFindingsResponse, ScanModule, type ScanSource, type ScanStatus, type Sent, TenantModule, type TenantState, VaultCreateRequest, VaultCreateResponse, VaultReadResponse, VerifyResult, WebhookChannelCreateRequest, WebhookChannelCreateResponse, WebhookEventsResponse, newFabricSecret };
1262
+ export { type AddDocumentRequest, type AddDocumentResponse, type AddMemberRequest, type AddMemberResponse, AgentReadRequest, AgentReadResponse, AgentReader, type AiReadDocument, type AiReadResponse, type AiReadSection, type AuthorizeRequest, type AuthorizeResult, BatchResult, Capsule, CapsuleAi, type CapsuleAiGrant, CapsuleAudit, type CapsuleAuditResponse, CapsuleDocuments, type CapsuleKeyMode, type CapsuleMember, CapsuleMembers, CapsuleModule, type CapsuleOpen, type CapsuleReceipt, type CapsuleStatus, type CapsuleSummary, ChannelCreateRequest, ChannelCreateResponse, ChannelReceiveRequest, ChannelReceiveResponse, ChannelSendRequest, ChannelSendResponse, type CommandWatch, ComputeDecision, ComputeEngine, ComputeRequest, type CreateCapsuleRequest, type CreateTenantRequest, type CreateTenantResponse, DecryptRequest, DecryptResponse, DeliverRequest, DeliverResponse, type DocumentRecipient, type DocumentSection, type DocumentSummary, type EmbedTokenRequest, type EmbedTokenResponse, type EnableScanRequest, type EnableScanResponse, EncryptRequest, EncryptResponse, EnginesModule, EvidenceQuery, EvidenceResponse, Fabric, FabricApprovalRequired, FabricModule, type FieldValue, GovernanceModule, type GrantAiResponse, GrantRequest, GrantResponse, type Invitation, type ListAiGrantsResponse, type ListCapsulesResponse, type ListDocumentsResponse, type ListMembersResponse, type Message, NoData, NoDataConfig, NoDataError, type OverviewResponse, type Partner, type PortableMode, RegisterTableRequest, RegisterTableResponse, type RevokeAiGrantResponse, type RevokeCapsuleResponse, RevokeRequest, RevokeResponse, type ScanDeployment, type ScanFinding, type ScanFindingsResponse, ScanModule, type ScanSource, type ScanStatus, type Sent, TenantModule, type TenantState, VaultCreateRequest, VaultCreateResponse, VaultReadResponse, VerifyResult, WebhookChannelCreateRequest, WebhookChannelCreateResponse, WebhookEventsResponse, newFabricSecret };
package/dist/index.d.ts CHANGED
@@ -318,6 +318,8 @@ interface CapsuleSummary {
318
318
  member_count: number;
319
319
  portable_mode: PortableMode;
320
320
  created_at: string;
321
+ /** Set when the capsule was just created: the first receipt on its own chain. */
322
+ receipt_id?: string;
321
323
  }
322
324
  interface CreateCapsuleRequest {
323
325
  /** Tenant-scoped opaque handle, /^[a-z0-9-]{3,64}$/, e.g. "case-4471". */
@@ -361,6 +363,19 @@ interface AddDocumentRequest {
361
363
  recipients?: DocumentRecipient[];
362
364
  /** Use the tenant zero-knowledge path (existing behavior; per-capsule zk is Phase 1). */
363
365
  zero_knowledge?: boolean;
366
+ /** The capsule's existing members and AI agents reach this document too. Default true. */
367
+ inherit_access?: boolean;
368
+ }
369
+ /** What a new document took on from its capsule. */
370
+ interface InheritedAccess {
371
+ members: number;
372
+ agents: number;
373
+ /** Members whose rule needs an owner code: not inherited; add them with `members.add` and the code. */
374
+ needs_code: string[];
375
+ /** On the capsule's own chain, written before the access was copied. */
376
+ receipt_id: string | null;
377
+ /** Set when the receipt could not be written: nothing was inherited. */
378
+ error?: string;
364
379
  }
365
380
  interface AddDocumentResponse {
366
381
  ok: boolean;
@@ -369,6 +384,8 @@ interface AddDocumentResponse {
369
384
  sections_count: number;
370
385
  classifications: string[];
371
386
  recipients_saved: number;
387
+ /** Absent when `inherit_access: false` was sent. */
388
+ inherited?: InheritedAccess;
372
389
  recipient_codes: Array<{
373
390
  email: string;
374
391
  classifications: string[];
@@ -432,6 +449,8 @@ interface AddMemberResponse {
432
449
  capsule_id: string;
433
450
  member: CapsuleMember;
434
451
  recipient_code?: string;
452
+ /** The receipt on the capsule's own chain, written before the member got access. */
453
+ receipt_id: string;
435
454
  }
436
455
  interface ListMembersResponse {
437
456
  ok: boolean;
@@ -465,6 +484,16 @@ interface CapsuleReceipt {
465
484
  created_at: string;
466
485
  payload: Record<string, unknown> | null;
467
486
  }
487
+ /** A receipt on the capsule's own chain: minted, a member or AI agent granted/revoked, revoked. */
488
+ interface CapsuleChainReceipt {
489
+ id: string;
490
+ chain_index: number;
491
+ surface: 'capsule.mint' | 'capsule.access' | string;
492
+ decision: 'grant' | 'revoke' | string;
493
+ event_hash: string;
494
+ signature_hex: string | null;
495
+ created_at: string;
496
+ }
468
497
  interface CapsuleAuditResponse {
469
498
  ok: boolean;
470
499
  capsule_id: string;
@@ -473,9 +502,12 @@ interface CapsuleAuditResponse {
473
502
  opens: number;
474
503
  receipts: number;
475
504
  denied: number;
505
+ chain: number;
476
506
  };
477
507
  opens: CapsuleOpen[];
478
508
  receipts: CapsuleReceipt[];
509
+ /** Every change to who may reach the capsule, in chain order. */
510
+ chain: CapsuleChainReceipt[];
479
511
  verification: string;
480
512
  }
481
513
  /** Audit sub-resource on a capsule handle. */
@@ -497,6 +529,8 @@ interface RevokeCapsuleResponse {
497
529
  revoked_documents: string[];
498
530
  sessions_revoked: number;
499
531
  receipt_id: string | null;
532
+ /** The revoke on the capsule's own chain; null if it could not be written (the revoke still happened). */
533
+ chain_receipt_id: string | null;
500
534
  key_kid_blocked: boolean;
501
535
  customer_frozen: boolean;
502
536
  capsule_marked: boolean;
@@ -508,20 +542,24 @@ interface CapsuleAiGrant {
508
542
  denied_classifications: string[];
509
543
  documents: number;
510
544
  }
545
+ /** `receipt_id`: on the capsule's own chain, written before the grant was applied. */
511
546
  interface GrantAiResponse extends CapsuleAiGrant {
512
547
  ok: boolean;
513
548
  capsule_id: string;
549
+ receipt_id: string;
514
550
  }
515
551
  interface ListAiGrantsResponse {
516
552
  ok: boolean;
517
553
  capsule_id: string;
518
554
  agents: CapsuleAiGrant[];
519
555
  }
556
+ /** `revoked_documents` is a count. `receipt_id` is null when nothing was revoked or its receipt could not be written. */
520
557
  interface RevokeAiGrantResponse {
521
558
  ok: boolean;
522
559
  capsule_id: string;
523
560
  agent_id: string;
524
- revoked_documents: string[];
561
+ revoked_documents: number;
562
+ receipt_id: string | null;
525
563
  }
526
564
  interface AiReadSection {
527
565
  label: string;
@@ -968,6 +1006,11 @@ interface Message {
968
1006
  receiptSignature: boolean | null;
969
1007
  };
970
1008
  }
1009
+ /** A running onCommand watch. stop() ends it after the pass in flight. */
1010
+ interface CommandWatch {
1011
+ stop(): Promise<void>;
1012
+ readonly running: boolean;
1013
+ }
971
1014
  /** A held request: a person must approve it in the browser before it goes through. The SDK never approves. */
972
1015
  declare class FabricApprovalRequired extends NoDataError {
973
1016
  approveUrl: string | null;
@@ -1041,6 +1084,25 @@ declare class Fabric {
1041
1084
  inbox(opts?: {
1042
1085
  accept?: string[];
1043
1086
  }): Promise<Message[]>;
1087
+ /**
1088
+ * Run `handler` for every command that arrives. It polls inbox() (pull, the way
1089
+ * the MCP's partner-watch does), so NoData never calls into your systems: there
1090
+ * is no webhook to expose or secure. Only accepted commands reach the handler;
1091
+ * refused ones go to onRefused when given. Each relay envelope is handed over
1092
+ * once. A handler that throws does not stop the watch; onError hears it.
1093
+ *
1094
+ * const watch = fabric.onCommand(async (m) => {
1095
+ * await fabric.reply(m, 'order.ack', { ok: true });
1096
+ * }, { accept: ['order.create'] });
1097
+ * // later: await watch.stop();
1098
+ */
1099
+ onCommand(handler: (message: Message) => unknown, opts?: {
1100
+ accept?: string[];
1101
+ everyMs?: number;
1102
+ onRefused?: (message: Message) => unknown;
1103
+ onError?: (error: unknown) => unknown;
1104
+ signal?: AbortSignal;
1105
+ }): CommandWatch;
1044
1106
  /**
1045
1107
  * End the connection with a partner, both directions this side holds: a grant
1046
1108
  * we gave is revoked, a grant they gave us is left. Narrowing only; receipted on
@@ -1197,4 +1259,4 @@ interface AuthorizeResult {
1197
1259
  proof_url: string | null;
1198
1260
  }
1199
1261
 
1200
- export { type AddDocumentRequest, type AddDocumentResponse, type AddMemberRequest, type AddMemberResponse, AgentReadRequest, AgentReadResponse, AgentReader, type AiReadDocument, type AiReadResponse, type AiReadSection, type AuthorizeRequest, type AuthorizeResult, BatchResult, Capsule, CapsuleAi, type CapsuleAiGrant, CapsuleAudit, type CapsuleAuditResponse, CapsuleDocuments, type CapsuleKeyMode, type CapsuleMember, CapsuleMembers, CapsuleModule, type CapsuleOpen, type CapsuleReceipt, type CapsuleStatus, type CapsuleSummary, ChannelCreateRequest, ChannelCreateResponse, ChannelReceiveRequest, ChannelReceiveResponse, ChannelSendRequest, ChannelSendResponse, ComputeDecision, ComputeEngine, ComputeRequest, type CreateCapsuleRequest, type CreateTenantRequest, type CreateTenantResponse, DecryptRequest, DecryptResponse, DeliverRequest, DeliverResponse, type DocumentRecipient, type DocumentSection, type DocumentSummary, type EmbedTokenRequest, type EmbedTokenResponse, type EnableScanRequest, type EnableScanResponse, EncryptRequest, EncryptResponse, EnginesModule, EvidenceQuery, EvidenceResponse, Fabric, FabricApprovalRequired, FabricModule, type FieldValue, GovernanceModule, type GrantAiResponse, GrantRequest, GrantResponse, type Invitation, type ListAiGrantsResponse, type ListCapsulesResponse, type ListDocumentsResponse, type ListMembersResponse, type Message, NoData, NoDataConfig, NoDataError, type OverviewResponse, type Partner, type PortableMode, RegisterTableRequest, RegisterTableResponse, type RevokeAiGrantResponse, type RevokeCapsuleResponse, RevokeRequest, RevokeResponse, type ScanDeployment, type ScanFinding, type ScanFindingsResponse, ScanModule, type ScanSource, type ScanStatus, type Sent, TenantModule, type TenantState, VaultCreateRequest, VaultCreateResponse, VaultReadResponse, VerifyResult, WebhookChannelCreateRequest, WebhookChannelCreateResponse, WebhookEventsResponse, newFabricSecret };
1262
+ export { type AddDocumentRequest, type AddDocumentResponse, type AddMemberRequest, type AddMemberResponse, AgentReadRequest, AgentReadResponse, AgentReader, type AiReadDocument, type AiReadResponse, type AiReadSection, type AuthorizeRequest, type AuthorizeResult, BatchResult, Capsule, CapsuleAi, type CapsuleAiGrant, CapsuleAudit, type CapsuleAuditResponse, CapsuleDocuments, type CapsuleKeyMode, type CapsuleMember, CapsuleMembers, CapsuleModule, type CapsuleOpen, type CapsuleReceipt, type CapsuleStatus, type CapsuleSummary, ChannelCreateRequest, ChannelCreateResponse, ChannelReceiveRequest, ChannelReceiveResponse, ChannelSendRequest, ChannelSendResponse, type CommandWatch, ComputeDecision, ComputeEngine, ComputeRequest, type CreateCapsuleRequest, type CreateTenantRequest, type CreateTenantResponse, DecryptRequest, DecryptResponse, DeliverRequest, DeliverResponse, type DocumentRecipient, type DocumentSection, type DocumentSummary, type EmbedTokenRequest, type EmbedTokenResponse, type EnableScanRequest, type EnableScanResponse, EncryptRequest, EncryptResponse, EnginesModule, EvidenceQuery, EvidenceResponse, Fabric, FabricApprovalRequired, FabricModule, type FieldValue, GovernanceModule, type GrantAiResponse, GrantRequest, GrantResponse, type Invitation, type ListAiGrantsResponse, type ListCapsulesResponse, type ListDocumentsResponse, type ListMembersResponse, type Message, NoData, NoDataConfig, NoDataError, type OverviewResponse, type Partner, type PortableMode, RegisterTableRequest, RegisterTableResponse, type RevokeAiGrantResponse, type RevokeCapsuleResponse, RevokeRequest, RevokeResponse, type ScanDeployment, type ScanFinding, type ScanFindingsResponse, ScanModule, type ScanSource, type ScanStatus, type Sent, TenantModule, type TenantState, VaultCreateRequest, VaultCreateResponse, VaultReadResponse, VerifyResult, WebhookChannelCreateRequest, WebhookChannelCreateResponse, WebhookEventsResponse, newFabricSecret };