@tinycloud/web-sdk 3.8.0-beta.3 → 3.8.0-beta.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.
@@ -0,0 +1,3 @@
1
+ /** Named-key client loaded when the first key method is called. */
2
+ export { createNamedKeyClient } from "@tinycloud/node-sdk/encryption-keys";
3
+ //# sourceMappingURL=encryption-keys-entry.d.ts.map
@@ -0,0 +1,2 @@
1
+ /*! For license information please see encryption-keys.cjs.LICENSE.txt */
2
+ (()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createNamedKeyClient:()=>Kt});class n extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const i="2.45.1";let r=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,s=`viem@${i}`;class o extends Error{constructor(e,t={}){const n=t.cause instanceof o?t.cause.details:t.cause?.message?t.cause.message:t.details,c=t.cause instanceof o&&t.cause.docsPath||t.docsPath,a=r?.({...t,docsPath:c});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...n?[`Details: ${n}`]:[],...s?[`Version: ${s}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=c,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=i}walk(e){return c(this,e)}}function c(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?c(e.cause,t):t?null:e}class a extends o{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function d(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class u extends o{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function l(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const i=e.replace("0x","");if(i.length>2*n)throw new u({size:Math.ceil(i.length/2),targetSize:n,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new u({size:e.length,targetSize:n,type:"bytes"});const i=new Uint8Array(n);for(let r=0;r<n;r++){const s="right"===t;i[s?r:n-r-1]=e[s?r:e.length-r-1]}return i}(e,{dir:t,size:n})}class y extends o{constructor({max:e,min:t,signed:n,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class p extends o{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function h(e){return d(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function f(e,{size:t}){if(h(e)>t)throw new p({givenSize:h(e),maxSize:t})}function w(e,t={}){const{signed:n,size:i}=t,r=BigInt(e);let s;i?s=n?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&r>s||r<o){const t="bigint"==typeof e?"n":"";throw new y({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:i,value:`${e}${t}`})}const c=`0x${(n&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?l(c,{size:i}):c}const k=new TextEncoder;const v={zero:48,nine:57,A:65,F:70,a:97,f:102};function g(e){return e>=v.zero&&e<=v.nine?e-v.zero:e>=v.A&&e<=v.F?e-(v.A-10):e>=v.a&&e<=v.f?e-(v.a-10):void 0}function m(e,t={}){let n=e;t.size&&(f(n,{size:t.size}),n=l(n,{dir:"right",size:t.size}));let i=n.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,s=new Uint8Array(r);for(let e=0,t=0;e<r;e++){const n=g(i.charCodeAt(t++)),r=g(i.charCodeAt(t++));if(void 0===n||void 0===r)throw new o(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);s[e]=16*n+r}return s}function b(e,t={}){const n=k.encode(e);return"number"==typeof t.size?(f(n,{size:t.size}),l(n,{dir:"right",size:t.size})):n}const I=BigInt(2**32-1),E=BigInt(32);function N(e,t=!1){return t?{h:Number(e&I),l:Number(e>>E&I)}:{h:0|Number(e>>E&I),l:0|Number(e&I)}}function S(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function $(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function _(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 A(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function O(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const P=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=O(e[t]);return e};function x(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),$(e),e}class T{}const D=BigInt(0),K=BigInt(1),z=BigInt(2),R=BigInt(7),L=BigInt(256),C=BigInt(113),M=[],V=[],U=[];for(let e=0,t=K,n=1,i=0;e<24;e++){[n,i]=[i,(2*n+3*i)%5],M.push(2*(5*i+n)),V.push((e+1)*(e+2)/2%64);let r=D;for(let e=0;e<7;e++)t=(t<<K^(t>>R)*C)%L,t&z&&(r^=K<<(K<<BigInt(e))-K);U.push(r)}const H=function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=N(e[s],t);[i[s],r[s]]=[n,o]}return[i,r]}(U,!0),B=H[0],j=H[1],q=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),F=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class G extends T{constructor(e,t,n,i=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=r,S(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){P(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,s=n[r],o=n[r+1],c=q(s,o,1)^n[i],a=F(s,o,1)^n[i+1];for(let n=0;n<50;n+=10)e[t+n]^=c,e[t+n+1]^=a}let t=e[2],r=e[3];for(let n=0;n<24;n++){const i=V[n],s=q(t,r,i),o=F(t,r,i),c=M[n];t=e[c],r=e[c+1],e[c]=s,e[c+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)n[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~n[(i+2)%10]&n[(i+4)%10]}e[0]^=B[i],e[1]^=j[i]}A(n)}(this.state32,this.rounds),P(this.state32),this.posOut=0,this.pos=0}update(e){_(this),$(e=x(e));const{blockLen:t,state:n}=this,i=e.length;for(let r=0;r<i;){const s=Math.min(t-this.pos,i-r);for(let t=0;t<s;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,128&t&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){_(this,!1),$(e),this.finish();const t=this.state,{blockLen:n}=this;for(let i=0,r=e.length;i<r;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return S(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){$(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,A(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:i,rounds:r,enableXOF:s}=this;return e||(e=new G(t,n,i,s,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const Y=(e,t,n)=>function(e){const t=t=>e().update(x(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new G(t,e,n)),W=(()=>Y(1,136,32))(),J=new n(8192);function X(e,t){if(J.has(`${e}.${t}`))return J.get(`${e}.${t}`);const n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),i=function(e){const t=W(d(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return m(w(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(f(n,{size:t.size}),l(n,{size:t.size})):n}(e,t):d(e)?m(e,t):b(e,t)}(e):e);return t}(b(n)),r=(t?n.substring(`${t}0x`.length):n).split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const s=`0x${r.join("")}`;return J.set(`${e}.${t}`,s),s}const Z=/^0x[a-fA-F0-9]{40}$/,Q=new n(8192);function ee(e,t){const{strict:n=!0}=t??{},i=`${e}.${n}`;if(Q.has(i))return Q.get(i);const r=!(!Z.test(e)||e.toLowerCase()!==e&&n&&X(e)!==e);return Q.set(i,r),r}var te=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function ne(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function ie(e){return e.slice(10,e.indexOf("/"))}function re(e){return e.slice(e.indexOf("/")+1)}function se(e){const t={};for(const n of te)ie(n.urn)===e&&(t[ne(re(n.urn))]=n.urn);return t}var oe=se("kv"),ce={...se("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},ae=(se("duckdb"),se("capabilities")),de=(se("hooks"),se("encryption")),ue=se("space"),le="applications",ye="account",pe="applications/",he="secrets",fe="default",we="public",ke="agents",ve="tinycloud.encryption",ge=de.NETWORK_CREATE,me=[fe,le,ye,he,we,ke],be={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:fe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:fe,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:fe,path:"",actions:["read","write"]}]},Ie={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:le,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:le,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:le,path:"",actions:["read","write"]}]},Ee={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ye,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ye,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ye,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ye,path:"account",actions:["read","write","schema"]}]},Ne={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:he,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:he,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:he,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:he,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:he,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:he,path:"",actions:["read"],skipPrefix:!0}]},Se={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:we,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:we,path:"",actions:["get","list","metadata"]}]},$e={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ke,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ke,path:"",actions:["get","put","del","list","metadata"]}]},_e={[fe]:be,[le]:Ie,[ye]:Ee,[he]:Ne,[we]:Se,[ke]:$e};function Ae(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!ee(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!ee(e,{strict:!1}))throw new a({address:e});return X(e,void 0)}(e)}(e)}`}function Oe(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Pe(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function xe(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?oe.GET:"write"===n||"put"===n?oe.PUT:"delete"===n||"del"===n?oe.DEL:"list"===n?oe.LIST:"metadata"===n?oe.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const r=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${r}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>xe(e,t,n));const i=!0===e.skipPrefix||e.service===ve;return[{service:e.service,space:e.service===ve?"encryption":e.space??n,path:Pe(t,e.path,i),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Te(e){const t=new Set(e.filter(e=>e.service!==ve).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[ae.READ]}))])}function De(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(Oe),r=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??le;return(e.permissions??[]).flatMap(e=>xe(e,t,n))});n&&r.push(...Ke.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(Oe(e)),s.set(e.app_id,t)}return{manifests:i,resources:Te(r),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${pe}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([_e[e]],{includeAccountRegistryPermissions:!1})}me.map(e=>({name:e,manifest:_e[e],persistedAsApplication:e===he}));var Ke=Object.freeze([{service:"tinycloud.kv",space:ye,path:pe,actions:[oe.GET,oe.PUT,oe.LIST]},{service:"tinycloud.kv",space:ye,path:"spaces/",actions:[oe.GET,oe.PUT,oe.LIST]},{service:"tinycloud.kv",space:ye,path:"system/bootstrap/complete",actions:[oe.GET,oe.PUT]},{service:"tinycloud.delegation",space:ye,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ye,path:"account",actions:[ce.READ,ce.WRITE,ce.SCHEMA]},{service:"tinycloud.capabilities",space:ye,path:"",actions:[ae.READ]}]),ze=De(fe),Re={...ze,resources:[...ze.resources,...Ke.map(e=>({...e,actions:[...e.actions]}))]},Le=Object.freeze(Object.fromEntries(me.map(e=>[e,e===fe?Re:De(e)]))),Ce=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ge]}]);function Me(e){return void 0===e?"":Ve(e)}function Ve(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Ve).join(",")}]`;const t=Object.keys(e).sort(),n=[];for(const i of t){const t=e[i];void 0!==t&&n.push(`${JSON.stringify(i)}:${Ve(t)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}Object.freeze(me.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Le[e].resources,...e===ye?{rawAbilities:Ce}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[ue.HOST]}]));var Ue="0123456789abcdef";function He(e){let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=Ue[i>>4&15]+Ue[15&i]}return t}function Be(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let i=0;i<e.length;i+=3){const r=e[i],s=i+1<e.length?e[i+1]:0,o=i+2<e.length?e[i+2]:0;n+=t[r>>2&63],n+=t[63&(r<<4|s>>4)],n+=i+1<e.length?t[63&(s<<2|o>>6)]:"=",n+=i+2<e.length?t[63&o]:"="}return n}function je(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),n=t.length;if(n%4!=0)throw new Error("invalid base64 input");const i=n/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),r=new Uint8Array(i),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<n;e+=4){const n=s[t[e]]??0,c=s[t[e+1]]??0,a="="===t[e+2]?0:s[t[e+2]]??0,d=n<<2|c>>4,u=(15&c)<<4|a>>2,l=(3&a)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<i&&(r[o++]=d),o<i&&(r[o++]=u),o<i&&(r[o++]=l)}return r}function qe(e){return(new TextEncoder).encode(e)}function Fe(e,t){return He(e(qe(Me(t))))}var Ge="urn:tinycloud:encryption:",Ye=/^[a-z0-9][a-z0-9-]*$/,We=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Je(e){if("string"!=typeof e||0===e.length)throw new We("networkId must be a non-empty string");if(!e.startsWith(Ge))throw new We(`networkId must start with ${Ge} (got ${JSON.stringify(e)})`);const t=e.slice(25),n=t.lastIndexOf(":");if(n<=0||n===t.length-1)throw new We(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const i=t.slice(0,n),r=t.slice(n+1);if(!i.startsWith("did:"))throw new We(`networkId ownerDid must be a DID (got ${JSON.stringify(i)})`);const s=i.split(":");if(s.length<3||s.some(e=>0===e.length))throw new We(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(i)})`);if(!Ye.test(r))throw new We(`networkId name ${JSON.stringify(r)} must match ${Ye.source}`);return{networkId:e,ownerDid:i,name:r}}var Xe=Ge,Ze="tinycloud.encryption.decrypt/v1",Qe="tinycloud.encryption.decrypt-result/v1",et="tinycloud.encryption/decrypt";function tt(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message}}function nt(e){return{...e,service:"encryption",message:tt(e)}}var it="[a-z0-9][a-z0-9._-]{0,63}",rt=new RegExp(`^${it}(?:/${it}){0,7}$`),st=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ot=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,ct="did:pkh:eip155:",at="tinycloud.encryption/key.create",dt="tinycloud.encryption/key.block",ut="tinycloud.encryption/key.unblock",lt=(Object.freeze([et,at,dt,ut]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function yt(e){if(!e.startsWith(ct))return e;const t=e.slice(15),n=t.indexOf(":"),i=-1===n?"":t.slice(0,n),r=-1===n?"":t.slice(n+1);if(!/^\d+$/.test(i)||!/^0x[a-fA-F0-9]{40}$/.test(r))throw new lt("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(i);if(0n===s||s>18446744073709551615n)throw new lt("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(i)})`);const o=Ae(r,1).slice(17);return`${ct}${s}:${o}`}function pt(e){const t=yt(e);if(t!==e)throw new lt("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function ht(e,t){if(0===e.length)throw new lt("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new lt("path_too_long",`${t} exceeds 255 bytes`);if(!rt.test(e))throw new lt("bad_path",`${t} ${JSON.stringify(e)} must match ${rt.source}`);const n=e.split("/");if("apps"===n[0]&&n.length<("key path"===t?3:2))throw new lt("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function ft(e){if("string"!=typeof e||!e.startsWith(Xe))throw new lt("not_encryption_urn",`resource must start with ${Xe}`);const t=e.slice(25),n=ot.exec(t);if(null===n)throw new lt("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const i=n[1],r=n[2],s=n[3];if(void 0===s){const e=yt(i),t=`${Xe}${e}:${r}`;try{Je(t)}catch(e){if(e instanceof We)throw new lt("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:r,networkId:t}}if(!st.test(r))throw new lt("bad_network",`network ${JSON.stringify(r)} must match ${st.source}`);pt(i);const o=`${Xe}${i}:${r}`;if(s.endsWith("/")){const e=s.slice(0,-1);return ht(e,"prefix"),{kind:"prefix",ownerDid:i,network:r,networkId:o,prefix:e}}return ht(s,"key path"),{kind:"key",ownerDid:i,network:r,networkId:o,path:s}}function wt(e){let t="";for(const n of e){const e=n.codePointAt(0);t+=e>=32&&e<=126?n:`\\u{${e.toString(16).toUpperCase().padStart(4,"0")}}`}return t}function kt(e){const t="string"==typeof e?e:String(e),n=Array.from(t);return wt(n.length>120?`${n.slice(0,120).join("")}...`:t)}var vt=class extends Error{constructor(e,t,n={}){super(wt(t),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=e,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},gt=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),mt=Object.assign(Object.create(null),{key_deleted:!0}),bt=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function It(e,t,n){const i=bt.exec(t.trim()),r=i?.[1]?.slice(0,64),s=i?.[2]?.trim(),o={status:e,...void 0===r?{}:{nodeCode:r},...void 0===s||0===s.length?{}:{detail:s}};if(void 0!==r){const e=gt[r];if(void 0!==e)return new vt(e,`${n}: ${r}`,o);if(!0===mt[r])return new vt("KEY_UNAVAILABLE",`${n}: key unavailable (${r})`,{...o,rawState:r})}return new vt("NODE_ERROR",`${n}: node responded ${e}`,o)}function Et(e){let t;try{t=ft(e)}catch(t){throw new vt("INVALID_KEY_TARGET",`not a valid encryption key resource: ${kt(t instanceof Error?t.message:t)}`,{cause:t,input:e})}if("key"!==t.kind)throw new vt("INVALID_KEY_TARGET",`a ${t.kind} resource cannot be an invocation target; an exact key is required`,{input:e});return t}function Nt(e){const t=Et(e.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path,action:e.action,bodyHash:Fe(e.crypto.sha256,e.body)}}function St(e){const t=Et(e.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path}}var $t={[et]:!0,[at]:!0,[dt]:!0,[ut]:!0};function _t(e){return new vt("INVALID_RESPONSE",`node returned an invalid ${e}`)}function At(e,t,n){const i="object"==typeof e&&null!==e?e:{};if("string"!=typeof i.alg||"number"!=typeof i.keyVersion||!Number.isInteger(i.keyVersion)||"string"!=typeof i.publicEncryptionKey||0===i.publicEncryptionKey.length)throw _t("key descriptor");if(i.networkId!==t||i.keyPath!==n)throw new vt("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:t,keyPath:n,alg:i.alg,keyVersion:i.keyVersion,publicEncryptionKey:i.publicEncryptionKey}}function Ot(e,t,n){const i=At(e,t,n),r=e;if("string"!=typeof r.state||"string"!=typeof r.kind)throw _t("key descriptor (state/kind missing)");return{...i,state:r.state,kind:r.kind,..."string"==typeof r.createdAt?{createdAt:r.createdAt}:{},..."string"==typeof r.updatedAt?{updatedAt:r.updatedAt}:{}}}function Pt(e){return e.startsWith("apps/")}var xt=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],Tt=class{constructor(e){this.config=e}networkFor(e){return e?.networkId??this.config.defaultNetworkId()}keyUrn(e,t){try{return function(e,t){const n=function(e){let t;try{t=Je(e)}catch(e){if(e instanceof We)throw new lt("bad_network",e.message);throw e}return pt(t.ownerDid),t.networkId}(e);ht(t,"key path");const i=`${n}/${t}`;return function(e,t){if(ft(e).networkId!==t)throw new lt("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(i,n),i}(e,t)}catch(n){throw new vt("INVALID_KEY_TARGET",kt(n instanceof Error?n.message:n),{cause:n,input:`${e}/${t}`})}}requireNode(){if(void 0===this.nodeId){const e=this.readNodeInfo();this.nodeId=e,e.catch(()=>{this.nodeId===e&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const e=await this.config.fetch(`${this.config.host}/info`);if(!e.ok)throw It(e.status,await Dt(e),"failed to read node info");const t=await e.json();if(!function(e){const t=e?.features;return Array.isArray(t)&&t.includes("encryption-named-keys-v1")}(t))throw new vt("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof t.nodeId||0===t.nodeId.length)throw _t("/info response (nodeId missing)");return t.nodeId}keysUrl(e,t){return`${this.config.host}/encryption/networks/${e}/keys/${t}`}async getPublicKey(e,t){const n=this.networkFor(t);this.keyUrn(n,e),await this.requireNode();const i=await this.config.fetch(this.keysUrl(n,e),{method:"GET"});if(!i.ok)throw It(i.status,await Dt(i),"failed to read key");return At(await i.json(),n,e)}async describeKey(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);return null===i?null:Ot(i,n,e)}async describePublic(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);if(null===i)throw new vt("KEY_NOT_FOUND",`key ${kt(e)} does not exist`,{status:404});return At(i,n,e)}async describeBody(e,t){const n=this.networkFor(t),i=this.keyUrn(n,e),r=t?.ability??et;if(!0!==$t[r])throw new vt("INVALID_KEY_TARGET",`${kt(r)} cannot describe a key`,{input:r});const s=await this.requireNode(),o=await this.config.signInvocation({targetNode:s,resource:i,action:r,facts:St({targetNode:s,keyResource:i})}),c=await this.config.fetch(this.keysUrl(n,e),{method:"GET",headers:{Authorization:o.authorization}});if(404===c.status){const e=It(404,await Dt(c),"failed to describe key");if("KEY_NOT_FOUND"===e.code)return null;throw e}if(!c.ok)throw It(c.status,await Dt(c),"failed to describe key");return c.json()}async admin(e,t,n,i){const r=this.networkFor(i),s=this.keyUrn(r,n),o="keys"===e?{keyPath:n,deletable:Pt(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:s,action:t,facts:Nt({crypto:this.config.crypto,targetNode:c,keyResource:s,action:t,body:o})}),d=await this.config.fetch(`${this.config.host}/encryption/networks/${r}/${e}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Me(o)});if(!d.ok)throw It(d.status,await Dt(d),`failed to ${t}`);return Ot(function(e){const t="object"==typeof e&&null!==e?e:{};return"object"==typeof t.descriptor&&null!==t.descriptor?t.descriptor:e}(await d.json()),r,n)}createKey(e,t){return this.admin("keys",at,e,t)}blockKey(e,t){return this.admin("key-actions/block",dt,e,t)}unblockKey(e,t){return this.admin("key-actions/unblock",ut,e,t)}async ensureKey(e,t){const n=()=>this.describeKey(e,{...t,ability:at});let i=await n();if(null===i)try{i=await this.createKey(e,t)}catch(t){if(!(t instanceof vt)||"KEY_EXISTS"!==t.code)throw t;if(i=await n(),null===i)throw new vt("KEY_NOT_FOUND",`key ${kt(e)} reported as existing but could not be read back`)}return function(e,t){if("blocked"===e.state)throw new vt("KEY_BLOCKED",`key ${kt(e.keyPath)} is blocked`,{rawState:e.state});if("active"!==e.state)throw new vt("KEY_UNAVAILABLE",`key ${kt(e.keyPath)} is unavailable (state ${kt(e.state)})`,{rawState:e.state});if(e.kind!==t)throw new vt("KEY_KIND_MISMATCH",`key ${kt(e.keyPath)} exists with kind ${kt(e.kind)}, not ${t}`,{kind:e.kind});return e}(i,Pt(e)?"deletable":"deterministic")}async encrypt(e,t,n){const i=Pt(e)?await this.describePublic(e,n):await this.getPublicKey(e,n),{crypto:r}=this.config,s=r.randomBytes(32),o=r.authEncrypt(s,t,n?.aad),c=Be(r.sealToNetworkKey(je(i.publicEncryptionKey),s));return{v:2,networkId:i.networkId,keyPath:i.keyPath,alg:i.alg??"x25519-aes256gcm/v1",keyVersion:i.keyVersion,encryptedSymmetricKey:c,encryptedSymmetricKeyHash:Fe(r.sha256,c),ciphertext:Be(o),...void 0!==n?.aad?{aad:Be(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(e){const t="object"==typeof e&&null!==e?e:{};if(1===t.v&&void 0===t.keyPath)return this.decryptRoot(t);if(2===t.v&&"string"==typeof t.keyPath)return this.decryptKey(this.validateKeyEnvelope(t));throw new vt("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(e){const t=[];for(const n of e)try{t.push({ok:!0,data:await this.decrypt(n)})}catch(e){t.push({ok:!1,error:e instanceof vt?e:new vt("DECRYPT_FAILED","decrypt failed",{cause:e})})}return t}async decryptRoot(e){if(void 0===this.config.decryptRoot)throw new vt("DECRYPT_FAILED","no root-key decrypt path is configured");const t=await this.config.decryptRoot(e);if(!t.ok)throw new vt("DECRYPT_FAILED",kt(t.error.message),{cause:t.error});return t.data}validateKeyEnvelope(e){for(const t of xt)if("string"!=typeof e[t]||0===e[t].length)throw new vt("INVALID_ENVELOPE",`envelope.${t} must be a non-empty string`);if("number"!=typeof e.keyVersion||!Number.isInteger(e.keyVersion))throw new vt("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof e.networkId)throw new vt("INVALID_ENVELOPE","envelope.networkId must be a string");try{Je(e.networkId)}catch(e){throw new vt("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:e})}if(Fe(this.config.crypto.sha256,e.encryptedSymmetricKey)!==e.encryptedSymmetricKeyHash)throw new vt("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");return e}async decryptKey(e){const{crypto:t}=this.config,n=this.keyUrn(e.networkId,e.keyPath),i=await this.requireNode(),r=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:t}),s=Be(r.publicKey),o=Fe(t.sha256,s),c={type:Ze,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:o},a=Me(c),d={type:Ze,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,bodyHash:Fe(t.sha256,c),encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:o,alg:e.alg,keyVersion:e.keyVersion},u=await this.config.signInvocation({targetNode:i,resource:n,action:et,facts:d}),l=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:a});if(!l.ok)throw It(l.status,await Dt(l),"failed to decrypt");const y=function(e){const{crypto:t,request:n,facts:i,invocationCid:r,requestBodyHash:s,response:o}=e;if(o.type!==Qe)return{ok:!1,error:nt({code:"INVALID_RESPONSE",message:`response.type must be ${Qe}`})};if(o.targetNode!==n.targetNode)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==n.networkId)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==n.targetNode)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(o.alg!==n.alg)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==n.keyVersion)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==r)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=He(t.sha256(qe(`${r}${s}`)));if(o.requestHash!==c)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(i.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||i.receiverPublicKeyHash!==o.receiverPublicKeyHash||i.networkId!==o.networkId||i.targetNode!==o.targetNode||i.alg!==o.alg||i.keyVersion!==o.keyVersion)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(e){const{nodeSignature:t,...n}=e;return Me(n)}(o)),d=je(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,a,d)?{ok:!0,data:o}:{ok:!1,error:nt({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:t,request:c,facts:d,invocationCid:u.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!y.ok)throw new vt("INVALID_RESPONSE",kt(y.error.message),{cause:y.error});const p=function(e,t,n){const i=je(n.wrappedKey);return e.openWithReceiverKey(t,i)}(t,r.privateKey,y.data);try{return t.authDecrypt(p,je(e.ciphertext),void 0!==e.aad?je(e.aad):void 0)}catch(e){throw new vt("DECRYPT_FAILED","local decryption failed",{cause:e})}}};async function Dt(e){try{return await e.text()}catch{return""}}function Kt(e,t={}){const n=e;for(const e of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[e])throw new vt("NODE_HOOK_MISSING",`TinyCloudNode.${e} is not available; named keys cannot sign invocations`);const i=n,r=e.hosts[0];if(void 0===r)throw new Error("TinyCloud node host has not been resolved");const s={host:r,crypto:i.createEncryptionCrypto(),fetch:t.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>t.networkId??e.getDefaultEncryptionNetworkId(),signInvocation:e=>i.signRawNetworkAuthorization({targetNode:e.targetNode,networkId:e.resource,action:e.action,facts:e.facts}),decryptRoot:t=>{const n=e.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):e.encryption.decryptEnvelope(t,{proofs:[n]})}};return new Tt(s)}module.exports=t})();
@@ -0,0 +1 @@
1
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
@@ -0,0 +1,2 @@
1
+ /*! For license information please see encryption-keys.mjs.LICENSE.txt */
2
+ class e extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const t="2.45.1";let n=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,i=`viem@${t}`;class r extends Error{constructor(e,s={}){const o=s.cause instanceof r?s.cause.details:s.cause?.message?s.cause.message:s.details,c=s.cause instanceof r&&s.cause.docsPath||s.docsPath,a=n?.({...s,docsPath:c});super([e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...o?[`Details: ${o}`]:[],...i?[`Version: ${i}`]:[]].join("\n"),s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=o,this.docsPath=c,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=t}walk(e){return s(this,e)}}function s(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?s(e.cause,t):t?null:e}class o extends r{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function c(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class a extends r{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function d(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const i=e.replace("0x","");if(i.length>2*n)throw new a({size:Math.ceil(i.length/2),targetSize:n,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new a({size:e.length,targetSize:n,type:"bytes"});const i=new Uint8Array(n);for(let r=0;r<n;r++){const s="right"===t;i[s?r:n-r-1]=e[s?r:e.length-r-1]}return i}(e,{dir:t,size:n})}class u extends r{constructor({max:e,min:t,signed:n,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class l extends r{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function y(e){return c(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function p(e,{size:t}){if(y(e)>t)throw new l({givenSize:y(e),maxSize:t})}function h(e,t={}){const{signed:n,size:i}=t,r=BigInt(e);let s;i?s=n?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&r>s||r<o){const t="bigint"==typeof e?"n":"";throw new u({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:i,value:`${e}${t}`})}const c=`0x${(n&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?d(c,{size:i}):c}const f=new TextEncoder;const w={zero:48,nine:57,A:65,F:70,a:97,f:102};function k(e){return e>=w.zero&&e<=w.nine?e-w.zero:e>=w.A&&e<=w.F?e-(w.A-10):e>=w.a&&e<=w.f?e-(w.a-10):void 0}function v(e,t={}){let n=e;t.size&&(p(n,{size:t.size}),n=d(n,{dir:"right",size:t.size}));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let e=0,t=0;e<s;e++){const n=k(i.charCodeAt(t++)),s=k(i.charCodeAt(t++));if(void 0===n||void 0===s)throw new r(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=16*n+s}return o}function g(e,t={}){const n=f.encode(e);return"number"==typeof t.size?(p(n,{size:t.size}),d(n,{dir:"right",size:t.size})):n}const m=BigInt(2**32-1),b=BigInt(32);function I(e,t=!1){return t?{h:Number(e&m),l:Number(e>>b&m)}:{h:0|Number(e>>b&m),l:0|Number(e&m)}}function E(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function N(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function S(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 $(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const A=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=_(e[t]);return e};function O(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),N(e),e}class P{}const x=BigInt(0),T=BigInt(1),D=BigInt(2),K=BigInt(7),z=BigInt(256),R=BigInt(113),L=[],C=[],V=[];for(let e=0,t=T,n=1,i=0;e<24;e++){[n,i]=[i,(2*n+3*i)%5],L.push(2*(5*i+n)),C.push((e+1)*(e+2)/2%64);let r=x;for(let e=0;e<7;e++)t=(t<<T^(t>>K)*R)%z,t&D&&(r^=T<<(T<<BigInt(e))-T);V.push(r)}const M=function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=I(e[s],t);[i[s],r[s]]=[n,o]}return[i,r]}(V,!0),U=M[0],H=M[1],B=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),q=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class j extends P{constructor(e,t,n,i=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=r,E(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){A(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,s=n[r],o=n[r+1],c=B(s,o,1)^n[i],a=q(s,o,1)^n[i+1];for(let n=0;n<50;n+=10)e[t+n]^=c,e[t+n+1]^=a}let t=e[2],r=e[3];for(let n=0;n<24;n++){const i=C[n],s=B(t,r,i),o=q(t,r,i),c=L[n];t=e[c],r=e[c+1],e[c]=s,e[c+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)n[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~n[(i+2)%10]&n[(i+4)%10]}e[0]^=U[i],e[1]^=H[i]}$(n)}(this.state32,this.rounds),A(this.state32),this.posOut=0,this.pos=0}update(e){S(this),N(e=O(e));const{blockLen:t,state:n}=this,i=e.length;for(let r=0;r<i;){const s=Math.min(t-this.pos,i-r);for(let t=0;t<s;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,128&t&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){S(this,!1),N(e),this.finish();const t=this.state,{blockLen:n}=this;for(let i=0,r=e.length;i<r;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return E(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){N(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,$(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:i,rounds:r,enableXOF:s}=this;return e||(e=new j(t,n,i,s,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const F=(e,t,n)=>function(e){const t=t=>e().update(O(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new j(t,e,n)),G=(()=>F(1,136,32))(),Y=new e(8192);function W(e,t){if(Y.has(`${e}.${t}`))return Y.get(`${e}.${t}`);const n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),i=function(e){const t=G(c(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return v(h(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(p(n,{size:t.size}),d(n,{size:t.size})):n}(e,t):c(e)?v(e,t):g(e,t)}(e):e);return t}(g(n)),r=(t?n.substring(`${t}0x`.length):n).split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const s=`0x${r.join("")}`;return Y.set(`${e}.${t}`,s),s}const J=/^0x[a-fA-F0-9]{40}$/,X=new e(8192);function Z(e,t){const{strict:n=!0}=t??{},i=`${e}.${n}`;if(X.has(i))return X.get(i);const r=!(!J.test(e)||e.toLowerCase()!==e&&n&&W(e)!==e);return X.set(i,r),r}var Q=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function ee(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function te(e){return e.slice(10,e.indexOf("/"))}function ne(e){return e.slice(e.indexOf("/")+1)}function ie(e){const t={};for(const n of Q)te(n.urn)===e&&(t[ee(ne(n.urn))]=n.urn);return t}var re=ie("kv"),se={...ie("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},oe=(ie("duckdb"),ie("capabilities")),ce=(ie("hooks"),ie("encryption")),ae=ie("space"),de="applications",ue="account",le="applications/",ye="secrets",pe="default",he="public",fe="agents",we="tinycloud.encryption",ke=ce.NETWORK_CREATE,ve=[pe,de,ue,ye,he,fe],ge={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:pe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:pe,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:pe,path:"",actions:["read","write"]}]},me={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:de,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:de,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:de,path:"",actions:["read","write"]}]},be={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ue,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ue,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:["read","write","schema"]}]},Ie={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ye,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ye,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ye,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ye,path:"",actions:["read"],skipPrefix:!0}]},Ee={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:he,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:he,path:"",actions:["get","list","metadata"]}]},Ne={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:fe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:fe,path:"",actions:["get","put","del","list","metadata"]}]},Se={[pe]:ge,[de]:me,[ue]:be,[ye]:Ie,[he]:Ee,[fe]:Ne};function $e(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!Z(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!Z(e,{strict:!1}))throw new o({address:e});return W(e,void 0)}(e)}(e)}`}function _e(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Ae(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function Oe(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?re.GET:"write"===n||"put"===n?re.PUT:"delete"===n||"del"===n?re.DEL:"list"===n?re.LIST:"metadata"===n?re.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const r=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${r}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>Oe(e,t,n));const i=!0===e.skipPrefix||e.service===we;return[{service:e.service,space:e.service===we?"encryption":e.space??n,path:Ae(t,e.path,i),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Pe(e){const t=new Set(e.filter(e=>e.service!==we).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[oe.READ]}))])}function xe(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(_e),r=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??de;return(e.permissions??[]).flatMap(e=>Oe(e,t,n))});n&&r.push(...Te.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(_e(e)),s.set(e.app_id,t)}return{manifests:i,resources:Pe(r),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${le}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([Se[e]],{includeAccountRegistryPermissions:!1})}ve.map(e=>({name:e,manifest:Se[e],persistedAsApplication:e===ye}));var Te=Object.freeze([{service:"tinycloud.kv",space:ue,path:le,actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"system/bootstrap/complete",actions:[re.GET,re.PUT]},{service:"tinycloud.delegation",space:ue,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:[se.READ,se.WRITE,se.SCHEMA]},{service:"tinycloud.capabilities",space:ue,path:"",actions:[oe.READ]}]),De=xe(pe),Ke={...De,resources:[...De.resources,...Te.map(e=>({...e,actions:[...e.actions]}))]},ze=Object.freeze(Object.fromEntries(ve.map(e=>[e,e===pe?Ke:xe(e)]))),Re=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ke]}]);function Le(e){return void 0===e?"":Ce(e)}function Ce(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Ce).join(",")}]`;const t=Object.keys(e).sort(),n=[];for(const i of t){const t=e[i];void 0!==t&&n.push(`${JSON.stringify(i)}:${Ce(t)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}Object.freeze(ve.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:ze[e].resources,...e===ue?{rawAbilities:Re}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[ae.HOST]}]));var Ve="0123456789abcdef";function Me(e){let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=Ve[i>>4&15]+Ve[15&i]}return t}function Ue(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let i=0;i<e.length;i+=3){const r=e[i],s=i+1<e.length?e[i+1]:0,o=i+2<e.length?e[i+2]:0;n+=t[r>>2&63],n+=t[63&(r<<4|s>>4)],n+=i+1<e.length?t[63&(s<<2|o>>6)]:"=",n+=i+2<e.length?t[63&o]:"="}return n}function He(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),n=t.length;if(n%4!=0)throw new Error("invalid base64 input");const i=n/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),r=new Uint8Array(i),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<n;e+=4){const n=s[t[e]]??0,c=s[t[e+1]]??0,a="="===t[e+2]?0:s[t[e+2]]??0,d=n<<2|c>>4,u=(15&c)<<4|a>>2,l=(3&a)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<i&&(r[o++]=d),o<i&&(r[o++]=u),o<i&&(r[o++]=l)}return r}function Be(e){return(new TextEncoder).encode(e)}function qe(e,t){return Me(e(Be(Le(t))))}var je="urn:tinycloud:encryption:",Fe=/^[a-z0-9][a-z0-9-]*$/,Ge=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Ye(e){if("string"!=typeof e||0===e.length)throw new Ge("networkId must be a non-empty string");if(!e.startsWith(je))throw new Ge(`networkId must start with ${je} (got ${JSON.stringify(e)})`);const t=e.slice(25),n=t.lastIndexOf(":");if(n<=0||n===t.length-1)throw new Ge(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const i=t.slice(0,n),r=t.slice(n+1);if(!i.startsWith("did:"))throw new Ge(`networkId ownerDid must be a DID (got ${JSON.stringify(i)})`);const s=i.split(":");if(s.length<3||s.some(e=>0===e.length))throw new Ge(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(i)})`);if(!Fe.test(r))throw new Ge(`networkId name ${JSON.stringify(r)} must match ${Fe.source}`);return{networkId:e,ownerDid:i,name:r}}var We=je,Je="tinycloud.encryption.decrypt/v1",Xe="tinycloud.encryption.decrypt-result/v1",Ze="tinycloud.encryption/decrypt";function Qe(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message}}function et(e){return{...e,service:"encryption",message:Qe(e)}}var tt="[a-z0-9][a-z0-9._-]{0,63}",nt=new RegExp(`^${tt}(?:/${tt}){0,7}$`),it=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,rt=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,st="did:pkh:eip155:",ot="tinycloud.encryption/key.create",ct="tinycloud.encryption/key.block",at="tinycloud.encryption/key.unblock",dt=(Object.freeze([Ze,ot,ct,at]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function ut(e){if(!e.startsWith(st))return e;const t=e.slice(15),n=t.indexOf(":"),i=-1===n?"":t.slice(0,n),r=-1===n?"":t.slice(n+1);if(!/^\d+$/.test(i)||!/^0x[a-fA-F0-9]{40}$/.test(r))throw new dt("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(i);if(0n===s||s>18446744073709551615n)throw new dt("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(i)})`);const o=$e(r,1).slice(17);return`${st}${s}:${o}`}function lt(e){const t=ut(e);if(t!==e)throw new dt("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function yt(e,t){if(0===e.length)throw new dt("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new dt("path_too_long",`${t} exceeds 255 bytes`);if(!nt.test(e))throw new dt("bad_path",`${t} ${JSON.stringify(e)} must match ${nt.source}`);const n=e.split("/");if("apps"===n[0]&&n.length<("key path"===t?3:2))throw new dt("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function pt(e){if("string"!=typeof e||!e.startsWith(We))throw new dt("not_encryption_urn",`resource must start with ${We}`);const t=e.slice(25),n=rt.exec(t);if(null===n)throw new dt("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const i=n[1],r=n[2],s=n[3];if(void 0===s){const e=ut(i),t=`${We}${e}:${r}`;try{Ye(t)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:r,networkId:t}}if(!it.test(r))throw new dt("bad_network",`network ${JSON.stringify(r)} must match ${it.source}`);lt(i);const o=`${We}${i}:${r}`;if(s.endsWith("/")){const e=s.slice(0,-1);return yt(e,"prefix"),{kind:"prefix",ownerDid:i,network:r,networkId:o,prefix:e}}return yt(s,"key path"),{kind:"key",ownerDid:i,network:r,networkId:o,path:s}}function ht(e){let t="";for(const n of e){const e=n.codePointAt(0);t+=e>=32&&e<=126?n:`\\u{${e.toString(16).toUpperCase().padStart(4,"0")}}`}return t}function ft(e){const t="string"==typeof e?e:String(e),n=Array.from(t);return ht(n.length>120?`${n.slice(0,120).join("")}...`:t)}var wt=class extends Error{constructor(e,t,n={}){super(ht(t),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=e,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},kt=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),vt=Object.assign(Object.create(null),{key_deleted:!0}),gt=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function mt(e,t,n){const i=gt.exec(t.trim()),r=i?.[1]?.slice(0,64),s=i?.[2]?.trim(),o={status:e,...void 0===r?{}:{nodeCode:r},...void 0===s||0===s.length?{}:{detail:s}};if(void 0!==r){const e=kt[r];if(void 0!==e)return new wt(e,`${n}: ${r}`,o);if(!0===vt[r])return new wt("KEY_UNAVAILABLE",`${n}: key unavailable (${r})`,{...o,rawState:r})}return new wt("NODE_ERROR",`${n}: node responded ${e}`,o)}function bt(e){let t;try{t=pt(e)}catch(t){throw new wt("INVALID_KEY_TARGET",`not a valid encryption key resource: ${ft(t instanceof Error?t.message:t)}`,{cause:t,input:e})}if("key"!==t.kind)throw new wt("INVALID_KEY_TARGET",`a ${t.kind} resource cannot be an invocation target; an exact key is required`,{input:e});return t}function It(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path,action:e.action,bodyHash:qe(e.crypto.sha256,e.body)}}function Et(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path}}var Nt={[Ze]:!0,[ot]:!0,[ct]:!0,[at]:!0};function St(e){return new wt("INVALID_RESPONSE",`node returned an invalid ${e}`)}function $t(e,t,n){const i="object"==typeof e&&null!==e?e:{};if("string"!=typeof i.alg||"number"!=typeof i.keyVersion||!Number.isInteger(i.keyVersion)||"string"!=typeof i.publicEncryptionKey||0===i.publicEncryptionKey.length)throw St("key descriptor");if(i.networkId!==t||i.keyPath!==n)throw new wt("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:t,keyPath:n,alg:i.alg,keyVersion:i.keyVersion,publicEncryptionKey:i.publicEncryptionKey}}function _t(e,t,n){const i=$t(e,t,n),r=e;if("string"!=typeof r.state||"string"!=typeof r.kind)throw St("key descriptor (state/kind missing)");return{...i,state:r.state,kind:r.kind,..."string"==typeof r.createdAt?{createdAt:r.createdAt}:{},..."string"==typeof r.updatedAt?{updatedAt:r.updatedAt}:{}}}function At(e){return e.startsWith("apps/")}var Ot=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],Pt=class{constructor(e){this.config=e}networkFor(e){return e?.networkId??this.config.defaultNetworkId()}keyUrn(e,t){try{return function(e,t){const n=function(e){let t;try{t=Ye(e)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return lt(t.ownerDid),t.networkId}(e);yt(t,"key path");const i=`${n}/${t}`;return function(e,t){if(pt(e).networkId!==t)throw new dt("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(i,n),i}(e,t)}catch(n){throw new wt("INVALID_KEY_TARGET",ft(n instanceof Error?n.message:n),{cause:n,input:`${e}/${t}`})}}requireNode(){if(void 0===this.nodeId){const e=this.readNodeInfo();this.nodeId=e,e.catch(()=>{this.nodeId===e&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const e=await this.config.fetch(`${this.config.host}/info`);if(!e.ok)throw mt(e.status,await xt(e),"failed to read node info");const t=await e.json();if(!function(e){const t=e?.features;return Array.isArray(t)&&t.includes("encryption-named-keys-v1")}(t))throw new wt("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof t.nodeId||0===t.nodeId.length)throw St("/info response (nodeId missing)");return t.nodeId}keysUrl(e,t){return`${this.config.host}/encryption/networks/${e}/keys/${t}`}async getPublicKey(e,t){const n=this.networkFor(t);this.keyUrn(n,e),await this.requireNode();const i=await this.config.fetch(this.keysUrl(n,e),{method:"GET"});if(!i.ok)throw mt(i.status,await xt(i),"failed to read key");return $t(await i.json(),n,e)}async describeKey(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);return null===i?null:_t(i,n,e)}async describePublic(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);if(null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} does not exist`,{status:404});return $t(i,n,e)}async describeBody(e,t){const n=this.networkFor(t),i=this.keyUrn(n,e),r=t?.ability??Ze;if(!0!==Nt[r])throw new wt("INVALID_KEY_TARGET",`${ft(r)} cannot describe a key`,{input:r});const s=await this.requireNode(),o=await this.config.signInvocation({targetNode:s,resource:i,action:r,facts:Et({targetNode:s,keyResource:i})}),c=await this.config.fetch(this.keysUrl(n,e),{method:"GET",headers:{Authorization:o.authorization}});if(404===c.status){const e=mt(404,await xt(c),"failed to describe key");if("KEY_NOT_FOUND"===e.code)return null;throw e}if(!c.ok)throw mt(c.status,await xt(c),"failed to describe key");return c.json()}async admin(e,t,n,i){const r=this.networkFor(i),s=this.keyUrn(r,n),o="keys"===e?{keyPath:n,deletable:At(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:s,action:t,facts:It({crypto:this.config.crypto,targetNode:c,keyResource:s,action:t,body:o})}),d=await this.config.fetch(`${this.config.host}/encryption/networks/${r}/${e}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Le(o)});if(!d.ok)throw mt(d.status,await xt(d),`failed to ${t}`);return _t(function(e){const t="object"==typeof e&&null!==e?e:{};return"object"==typeof t.descriptor&&null!==t.descriptor?t.descriptor:e}(await d.json()),r,n)}createKey(e,t){return this.admin("keys",ot,e,t)}blockKey(e,t){return this.admin("key-actions/block",ct,e,t)}unblockKey(e,t){return this.admin("key-actions/unblock",at,e,t)}async ensureKey(e,t){const n=()=>this.describeKey(e,{...t,ability:ot});let i=await n();if(null===i)try{i=await this.createKey(e,t)}catch(t){if(!(t instanceof wt)||"KEY_EXISTS"!==t.code)throw t;if(i=await n(),null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} reported as existing but could not be read back`)}return function(e,t){if("blocked"===e.state)throw new wt("KEY_BLOCKED",`key ${ft(e.keyPath)} is blocked`,{rawState:e.state});if("active"!==e.state)throw new wt("KEY_UNAVAILABLE",`key ${ft(e.keyPath)} is unavailable (state ${ft(e.state)})`,{rawState:e.state});if(e.kind!==t)throw new wt("KEY_KIND_MISMATCH",`key ${ft(e.keyPath)} exists with kind ${ft(e.kind)}, not ${t}`,{kind:e.kind});return e}(i,At(e)?"deletable":"deterministic")}async encrypt(e,t,n){const i=At(e)?await this.describePublic(e,n):await this.getPublicKey(e,n),{crypto:r}=this.config,s=r.randomBytes(32),o=r.authEncrypt(s,t,n?.aad),c=Ue(r.sealToNetworkKey(He(i.publicEncryptionKey),s));return{v:2,networkId:i.networkId,keyPath:i.keyPath,alg:i.alg??"x25519-aes256gcm/v1",keyVersion:i.keyVersion,encryptedSymmetricKey:c,encryptedSymmetricKeyHash:qe(r.sha256,c),ciphertext:Ue(o),...void 0!==n?.aad?{aad:Ue(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(e){const t="object"==typeof e&&null!==e?e:{};if(1===t.v&&void 0===t.keyPath)return this.decryptRoot(t);if(2===t.v&&"string"==typeof t.keyPath)return this.decryptKey(this.validateKeyEnvelope(t));throw new wt("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(e){const t=[];for(const n of e)try{t.push({ok:!0,data:await this.decrypt(n)})}catch(e){t.push({ok:!1,error:e instanceof wt?e:new wt("DECRYPT_FAILED","decrypt failed",{cause:e})})}return t}async decryptRoot(e){if(void 0===this.config.decryptRoot)throw new wt("DECRYPT_FAILED","no root-key decrypt path is configured");const t=await this.config.decryptRoot(e);if(!t.ok)throw new wt("DECRYPT_FAILED",ft(t.error.message),{cause:t.error});return t.data}validateKeyEnvelope(e){for(const t of Ot)if("string"!=typeof e[t]||0===e[t].length)throw new wt("INVALID_ENVELOPE",`envelope.${t} must be a non-empty string`);if("number"!=typeof e.keyVersion||!Number.isInteger(e.keyVersion))throw new wt("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof e.networkId)throw new wt("INVALID_ENVELOPE","envelope.networkId must be a string");try{Ye(e.networkId)}catch(e){throw new wt("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:e})}if(qe(this.config.crypto.sha256,e.encryptedSymmetricKey)!==e.encryptedSymmetricKeyHash)throw new wt("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");return e}async decryptKey(e){const{crypto:t}=this.config,n=this.keyUrn(e.networkId,e.keyPath),i=await this.requireNode(),r=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:t}),s=Ue(r.publicKey),o=qe(t.sha256,s),c={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:o},a=Le(c),d={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,bodyHash:qe(t.sha256,c),encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:o,alg:e.alg,keyVersion:e.keyVersion},u=await this.config.signInvocation({targetNode:i,resource:n,action:Ze,facts:d}),l=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:a});if(!l.ok)throw mt(l.status,await xt(l),"failed to decrypt");const y=function(e){const{crypto:t,request:n,facts:i,invocationCid:r,requestBodyHash:s,response:o}=e;if(o.type!==Xe)return{ok:!1,error:et({code:"INVALID_RESPONSE",message:`response.type must be ${Xe}`})};if(o.targetNode!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==n.networkId)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(o.alg!==n.alg)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==n.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==r)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=Me(t.sha256(Be(`${r}${s}`)));if(o.requestHash!==c)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(i.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||i.receiverPublicKeyHash!==o.receiverPublicKeyHash||i.networkId!==o.networkId||i.targetNode!==o.targetNode||i.alg!==o.alg||i.keyVersion!==o.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(e){const{nodeSignature:t,...n}=e;return Le(n)}(o)),d=He(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,a,d)?{ok:!0,data:o}:{ok:!1,error:et({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:t,request:c,facts:d,invocationCid:u.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!y.ok)throw new wt("INVALID_RESPONSE",ft(y.error.message),{cause:y.error});const p=function(e,t,n){const i=He(n.wrappedKey);return e.openWithReceiverKey(t,i)}(t,r.privateKey,y.data);try{return t.authDecrypt(p,He(e.ciphertext),void 0!==e.aad?He(e.aad):void 0)}catch(e){throw new wt("DECRYPT_FAILED","local decryption failed",{cause:e})}}};async function xt(e){try{return await e.text()}catch{return""}}function Tt(e,t={}){const n=e;for(const e of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[e])throw new wt("NODE_HOOK_MISSING",`TinyCloudNode.${e} is not available; named keys cannot sign invocations`);const i=n,r=e.hosts[0];if(void 0===r)throw new Error("TinyCloud node host has not been resolved");const s={host:r,crypto:i.createEncryptionCrypto(),fetch:t.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>t.networkId??e.getDefaultEncryptionNetworkId(),signInvocation:e=>i.signRawNetworkAuthorization({targetNode:e.targetNode,networkId:e.resource,action:e.action,facts:e.facts}),decryptRoot:t=>{const n=e.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):e.encryption.decryptEnvelope(t,{proofs:[n]})}};return new Pt(s)}export{Tt as createNamedKeyClient};
@@ -0,0 +1 @@
1
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */