buckyos 0.7.197 → 0.7.203
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/cli/dist/cli.mjs +42 -1
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/modules/pikg.ts +7 -0
- package/cli/modules/pikg_protocol.ts +37 -0
- package/cli/version.ts +1 -1
- package/dist/aiworkspace_client.d.ts +20 -2
- package/dist/aiworkspace_client.d.ts.map +1 -1
- package/dist/aiws_bind-4fe77108.js +2 -0
- package/dist/aiws_bind-4fe77108.js.map +1 -0
- package/dist/{aiws_bind-a96cb506.mjs → aiws_bind-b851d4db.mjs} +3 -3
- package/dist/aiws_bind-b851d4db.mjs.map +1 -0
- package/dist/aiws_ext.cjs +1 -1
- package/dist/aiws_ext.mjs +1 -1
- package/dist/aiws_schedule.d.ts +2 -0
- package/dist/aiws_schedule.d.ts.map +1 -1
- package/dist/{aiws_write-7078045b.mjs → aiws_write-0606e098.mjs} +708 -292
- package/dist/aiws_write-0606e098.mjs.map +1 -0
- package/dist/aiws_write-7a9d71d1.js +13 -0
- package/dist/aiws_write-7a9d71d1.js.map +1 -0
- package/dist/aiws_write.d.ts +1 -0
- package/dist/aiws_write.d.ts.map +1 -1
- package/dist/app-frame.cjs +1 -1
- package/dist/app-frame.cjs.map +1 -1
- package/dist/app-frame.d.ts +129 -24
- package/dist/app-frame.d.ts.map +1 -1
- package/dist/app-frame.mjs +229 -70
- package/dist/app-frame.mjs.map +1 -1
- package/dist/audio.d.ts +84 -0
- package/dist/audio.d.ts.map +1 -0
- package/dist/browser.cjs +1 -1
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +5 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.mjs +249 -219
- package/dist/browser.mjs.map +1 -1
- package/dist/content.cjs +1 -1
- package/dist/content.cjs.map +1 -1
- package/dist/content.mjs +357 -34
- package/dist/content.mjs.map +1 -1
- package/dist/{content_objid-d1d089a6.js → content_objid-c69251aa.js} +2 -2
- package/dist/{content_objid-d1d089a6.js.map → content_objid-c69251aa.js.map} +1 -1
- package/dist/{content_objid-20b82f52.mjs → content_objid-e3fc56dd.mjs} +2 -2
- package/dist/{content_objid-20b82f52.mjs.map → content_objid-e3fc56dd.mjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +249 -219
- package/dist/index.mjs.map +1 -1
- package/dist/msg_center_client.d.ts +37 -0
- package/dist/msg_center_client.d.ts.map +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.ts +5 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.mjs +246 -215
- package/dist/node.mjs.map +1 -1
- package/dist/open-app.cjs +2 -0
- package/dist/open-app.cjs.map +1 -0
- package/dist/open-app.mjs +160 -0
- package/dist/open-app.mjs.map +1 -0
- package/dist/open_app.d.ts +95 -0
- package/dist/open_app.d.ts.map +1 -0
- package/dist/owner-extensions/scripts/schedule.mjs +2 -2
- package/dist/provision.cjs +1 -1
- package/dist/provision.cjs.map +1 -1
- package/dist/provision.mjs +1 -3
- package/dist/provision.mjs.map +1 -1
- package/dist/provision_activate.d.ts.map +1 -1
- package/dist/runtime_env-39e4df98.mjs +44 -0
- package/dist/runtime_env-39e4df98.mjs.map +1 -0
- package/dist/runtime_env-6396e1eb.js +2 -0
- package/dist/runtime_env-6396e1eb.js.map +1 -0
- package/dist/runtime_env.d.ts +53 -0
- package/dist/runtime_env.d.ts.map +1 -0
- package/dist/sdk_core.d.ts +4 -2
- package/dist/sdk_core.d.ts.map +1 -1
- package/dist/task_mgr_client.d.ts +2 -0
- package/dist/task_mgr_client.d.ts.map +1 -1
- package/dist/zone_clients.d.ts +35 -0
- package/dist/zone_clients.d.ts.map +1 -0
- package/package.json +6 -1
- package/dist/aiws_bind-a96cb506.mjs.map +0 -1
- package/dist/aiws_bind-fb4caf43.js +0 -2
- package/dist/aiws_bind-fb4caf43.js.map +0 -1
- package/dist/aiws_write-189e4c0e.js +0 -13
- package/dist/aiws_write-189e4c0e.js.map +0 -1
- package/dist/aiws_write-7078045b.mjs.map +0 -1
- package/dist/content_mime-dc80d960.js +0 -2
- package/dist/content_mime-dc80d960.js.map +0 -1
- package/dist/content_mime-e42d5f8d.mjs +0 -335
- package/dist/content_mime-e42d5f8d.mjs.map +0 -1
package/dist/provision.cjs
CHANGED
|
@@ -88,5 +88,5 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
88
88
|
* SOFTWARE.
|
|
89
89
|
*
|
|
90
90
|
*/
|
|
91
|
-
const hu="crypto.algorithm";const du="crypto.algorithmProvider";var fu;lc.registerSingleton(du,class{getAlgorithms(){return lc.resolveAll(hu)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new zn({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const yu="1.3.36.3.3.2.8.1.1",gu=`${yu}.1`,mu=`${yu}.2`,vu=`${yu}.3`,wu=`${yu}.4`,bu=`${yu}.5`,Su=`${yu}.6`,Au=`${yu}.7`,Eu=`${yu}.8`,ku=`${yu}.9`,xu=`${yu}.10`,_u=`${yu}.11`,Nu=`${yu}.12`,Iu=`${yu}.13`,Tu=`${yu}.14`,Bu="brainpoolP160r1",Ou="brainpoolP160t1",Cu="brainpoolP192r1",Du="brainpoolP192t1",ju="brainpoolP224r1",Pu="brainpoolP224t1",Ru="brainpoolP256r1",Uu="brainpoolP256t1",$u="brainpoolP320r1",Mu="brainpoolP320t1",Lu="brainpoolP384r1",Vu="brainpoolP384t1",Hu="brainpoolP512r1",Ku="brainpoolP512t1",Fu="ECDSA";let zu=fu=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Fu.toLowerCase())if("hash"in e){switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return qs;case"sha-256":return Gs;case"sha-384":return Xs;case"sha-512":return Ys}}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Fs;break;case"K-256":t=fu.SECP256K1;break;case"P-384":t=zs;break;case"P-521":t=Ws;break;case Bu:t=gu;break;case Ou:t=mu;break;case Cu:t=vu;break;case Du:t=wu;break;case ju:t=bu;break;case Pu:t=Su;break;case Ru:t=Au;break;case Uu:t=Eu;break;case $u:t=ku;break;case Mu:t=xu;break;case Lu:t=_u;break;case Vu:t=Nu;break;case Hu:t=Iu;break;case Ku:t=Tu}if(t)return new zn({algorithm:$s,parameters:Fr.serialize(new ia({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ms:return{name:Fu,hash:{name:"SHA-1"}};case Vs:return{name:Fu,hash:{name:"SHA-256"}};case Hs:return{name:Fu,hash:{name:"SHA-384"}};case Ks:return{name:Fu,hash:{name:"SHA-512"}};case $s:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Fr.parse(e.parameters,ia).namedCurve){case Fs:return{name:Fu,namedCurve:"P-256"};case fu.SECP256K1:return{name:Fu,namedCurve:"K-256"};case zs:return{name:Fu,namedCurve:"P-384"};case Ws:return{name:Fu,namedCurve:"P-521"};case gu:return{name:Fu,namedCurve:Bu};case mu:return{name:Fu,namedCurve:Ou};case vu:return{name:Fu,namedCurve:Cu};case wu:return{name:Fu,namedCurve:Du};case bu:return{name:Fu,namedCurve:ju};case Su:return{name:Fu,namedCurve:Pu};case Au:return{name:Fu,namedCurve:Ru};case Eu:return{name:Fu,namedCurve:Uu};case ku:return{name:Fu,namedCurve:$u};case xu:return{name:Fu,namedCurve:Mu};case _u:return{name:Fu,namedCurve:Lu};case Nu:return{name:Fu,namedCurve:Vu};case Iu:return{name:Fu,namedCurve:Hu};case Tu:return{name:Fu,namedCurve:Ku}}}return null}};zu.SECP256K1="1.3.132.0.10",zu=fu=zr([pc()],zu),lc.registerSingleton(hu,zu);const Wu=Symbol("name"),Ju=Symbol("value");class qu{constructor(e,t={},r=""){this[Wu]=e,this[Ju]=r;for(const i in t)this[i]=t[i]}}qu.NAME=Wu,qu.VALUE=Ju;class Gu{static toString(e){const t=this.items[e];return t||e}}Gu.items={[ba]:"sha1",[Sa]:"sha224",[Aa]:"sha256",[Ea]:"sha384",[ka]:"sha512",[aa]:"rsaEncryption",[da]:"sha1WithRSAEncryption",[fa]:"sha224WithRSAEncryption",[ya]:"sha256WithRSAEncryption",[ga]:"sha384WithRSAEncryption",[ma]:"sha512WithRSAEncryption",[$s]:"ecPublicKey",[Ms]:"ecdsaWithSHA1",[Ls]:"ecdsaWithSHA224",[Vs]:"ecdsaWithSHA256",[Hs]:"ecdsaWithSHA384",[Ks]:"ecdsaWithSHA512",[an]:"TLS WWW server authentication",[cn]:"TLS WWW client authentication",[un]:"Code Signing",[ln]:"E-mail Protection",[pn]:"Time Stamping",[hn]:"OCSP Signing",[js]:"Signed Data"};class Xu{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let i=this.pad(t++),n="";const o=e[qu.VALUE];o&&(n=` ${o}`),r.push(`${i}${e[qu.NAME]}:${n}`),i=this.pad(t);for(const s in e){if("symbol"==typeof s)continue;const n=e[s],o=s?`${s}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${i}${o}${n}`);else if(n instanceof Date)r.push(`${i}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[qu.NAME]=s,r.push(...this.serializeObj(e,t));else if(n instanceof qu)n[qu.NAME]=s,r.push(...this.serializeObj(n,t));else if(x.isBufferSource(n))s?(r.push(`${i}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[qu.NAME]=s,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),i=x.toUint8Array(e),n=[];for(let o=0;o<i.length;){const e=[];for(let t=0;t<16&&o<i.length;t++){8===t&&e.push("");const r=i[o++].toString(16).padStart(2,"0");e.push(r)}n.push(`${r}${e.join(" ")}`)}return n}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}var Yu,Zu;Xu.oidSerializer=Gu,Xu.algorithmSerializer=class{static toTextObject(e){const t=new qu("Algorithm Identifier",{},Gu.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case $s:{const r=(new zu).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Qu{get rawData(){return Wr(this,Yu,"f")||Jr(this,Yu,Fr.serialize(this.asn),"f"),Wr(this,Yu,"f")}constructor(...e){Yu.set(this,void 0),x.isBufferSource(e[0])?(this.asn=Fr.parse(e[0],e[1]),Jr(this,Yu,x.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Qu&&function(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),i=new Uint8Array(t);for(let n=0;n<e.byteLength;n++)if(r[n]!==i[n])return!1;return!0}(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Fr.toString(this.rawData);case"text":return Xu.serialize(this.toTextObject());case"hex":return C.ToHex(this.rawData);case"base64":return C.ToBase64(this.rawData);case"base64url":return C.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new qu(this.getTextName(),{},e)}}Yu=new WeakMap,Qu.NAME="ASN";class el extends Qu{constructor(...e){let t;t=x.isBufferSource(e[0])?x.toArrayBuffer(e[0]):Fr.serialize(new Xn({extnID:e[0],critical:e[1],extnValue:new ar(x.toArrayBuffer(e[2]))})),super(t,Xn)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[qu.NAME]===el.NAME&&(e[qu.NAME]=Gu.toString(this.type)),e}}class tl{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[Zu]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(tl.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(tl.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=tl.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(tl.DEFAULT,e);return this}}Zu=Symbol.toStringTag,tl.DEFAULT="default";const rl=new tl,il=/^[0-2](?:\.[1-9][0-9]*)+$/;class nl{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(il).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const ol=new nl;function sl(e,t){return`\\${C.ToHex(C.FromUtf8String(t)).toUpperCase()}`}ol.register("CN","2.5.4.3"),ol.register("L","2.5.4.7"),ol.register("ST","2.5.4.8"),ol.register("O","2.5.4.10"),ol.register("OU","2.5.4.11"),ol.register("C","2.5.4.6"),ol.register("DC","0.9.2342.19200300.100.1.25"),ol.register("E","1.2.840.113549.1.9.1"),ol.register("G","2.5.4.42"),ol.register("I","2.5.4.43"),ol.register("SN","2.5.4.4"),ol.register("T","2.5.4.12");class al{static isASCII(e){for(let t=0;t<e.length;t++){if(e.charCodeAt(t)>255)return!1}return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new nl,this.asn=new oi;for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const e=t[r];this.extraNames.register(r,e)}"string"==typeof e?this.asn=this.fromString(e):e instanceof oi?this.asn=e:x.isBufferSource(e)?this.asn=Fr.parse(e,oi):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||ol.findId(e),r=[];for(const i of this.asn)for(const e of i)e.type===t&&r.push(e.value.toString());return r}getName(e){return this.extraNames.get(e)||ol.get(e)}toString(){return this.asn.map((e=>e.map((e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${C.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,sl)}`)).join("+"))).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const i={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=i[r])&&void 0!==e||(i[r]=[]),i[r].push(t.value.anyValue?`#${C.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(i)}return t}fromString(e){const t=new oi,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,n=",";for(;i=r.exec(`${e},`);){let[,e,r]=i;const o=r[r.length-1];","!==o&&"+"!==o||(r=r.slice(0,r.length-1),i[3]=o);const s=i[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===n?t[t.length-1].push(a):t.push(new ii([a])),n=s}return t}fromJSON(e){const t=new oi;for(const r of e){const e=new ii;for(const t in r){const i=this.getTypeOid(t),n=r[t];for(const t of n){const r=this.createAttribute(i,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new ri({type:e});if("object"==typeof t)for(const i in t)switch(i){case"ia5String":r.value.ia5String=t[i];break;case"utf8String":r.value.utf8String=t[i];break;case"universalString":r.value.universalString=t[i];break;case"bmpString":r.value.bmpString=t[i];break;case"printableString":r.value.printableString=t[i]}else if("#"===t[0])r.value.anyValue=C.FromHex(t.slice(1));else{const i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:al.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Fr.serialize(this.asn)}async getThumbprint(...e){var t;let r,i="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(i=e[0]||i,r=e[1]||rl.get()):r=e[0]||rl.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const cl="Cannot initialize GeneralName from ASN.1 data.",ul=`${cl} Unsupported string format in use.`,ll=`${cl} Value doesn't match to GUID regular expression.`,pl=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,hl="1.3.6.1.4.1.311.25.1",dl="1.3.6.1.4.1.311.20.2.3",fl="dns",yl="dn",gl="email",ml="ip",vl="url",wl="guid",bl="upn",Sl="id";class Al extends Qu{constructor(...e){let t;if(2===e.length)switch(e[0]){case yl:{const r=new al(e[1]).toArrayBuffer(),i=Fr.parse(r,oi);t=new ui({directoryName:i});break}case fl:t=new ui({dNSName:e[1]});break;case gl:t=new ui({rfc822Name:e[1]});break;case wl:{const r=new RegExp(pl,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map(((e,t)=>t<3?C.ToHex(new Uint8Array(C.FromHex(e)).reverse()):e)).join("");t=new ui({otherName:new ai({typeId:hl,value:Fr.serialize(new ar(C.FromHex(i)))})});break}case ml:t=new ui({iPAddress:e[1]});break;case Sl:t=new ui({registeredID:e[1]});break;case bl:t=new ui({otherName:new ai({typeId:dl,value:Fr.serialize(vr.toASN(e[1]))})});break;case vl:t=new ui({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=x.isBufferSource(e[0])?Fr.parse(e[0],ui):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=fl,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=gl,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=ml,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=vl,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=Sl,this.value=e.registeredID;else if(null!=e.directoryName)this.type=yl,this.value=new al(e.directoryName).toString();else{if(null==e.otherName)throw new Error(ul);if(e.otherName.typeId===hl){this.type=wl;const t=Fr.parse(e.otherName.value,ar),r=new RegExp(pl,"i").exec(C.ToHex(t));if(!r)throw new Error(ll);this.value=r.slice(1).map(((e,t)=>t<3?C.ToHex(new Uint8Array(C.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==dl)throw new Error(ul);this.type=bl,this.value=Fr.parse(e.otherName.value,ei).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case yl:case fl:case wl:case ml:case Sl:case bl:case vl:e=this.type.toUpperCase();break;case gl:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Sl&&(t=Gu.toString(t)),new qu(e,void 0,t)}}class El extends Qu{constructor(e){let t;if(e instanceof Ii)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof ui)r.push(t);else{const e=Fr.parse(new Al(t.type,t.value).rawData,ui);r.push(e)}t=new Ii(r)}else{if(!x.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Fr.parse(e,Ii)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new Al(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map((e=>e.toJSON()))}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let i=e[r[qu.NAME]];Array.isArray(i)||(i=[],e[r[qu.NAME]]=i),i.push(r)}return e}}El.NAME="GeneralNames";const kl="-{5}",xl="\\n",_l="\\n",Nl=`${`${kl}BEGIN (${`[^${xl}]+`}(?=${kl}))${kl}`}${_l}(?:((?:${`[^:${xl}]+`}: ${`(?:[^${xl}]+${_l}(?: +[^${xl}]+${_l})*)`})+))?${_l}?(${`(?:[a-zA-Z0-9=+/]+${_l})+`})${`${kl}END \\1${kl}`}`;class Il{static isPem(e){return"string"==typeof e&&new RegExp(Nl,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(Nl,"g"),r=[];let i=null;for(;i=t.exec(e);){const e=i[3].replace(new RegExp(`[${xl}]+`,"g"),""),t={type:i[1],headers:[],rawData:C.FromBase64(e)},n=i[2];if(n){const e=n.split(new RegExp(_l,"g"));let r=null;for(const i of e){const[e,n]=i.split(/:(.*)/);if(void 0===n){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:n.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map((e=>e.rawData))}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach((e=>{if(!x.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:x.toArrayBuffer(e)}))})):e.forEach((e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))})),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:x.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)i.push(`${t.key}: ${t.value}`);i.push("")}const n=C.ToBase64(e.rawData);let o,s=0;const a=Array();for(;s<n.length&&(n.length-s<64?o=n.substring(s):(o=n.substring(s,s+64),s+=64),0!==o.length)&&(a.push(o),!(o.length<64)););return i.push(...a),i.push(`-----END ${r}-----`),i.join("\n")}}Il.CertificateTag="CERTIFICATE",Il.CrlTag="CRL",Il.CertificateRequestTag="CERTIFICATE REQUEST",Il.PublicKeyTag="PUBLIC KEY",Il.PrivateKeyTag="PRIVATE KEY";class Tl extends Qu{static isAsnEncoded(e){return x.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(Il.isPem(e))return Il.decode(e)[0];if(C.isHex(e))return C.FromHex(e);if(C.isBase64(e))return C.FromBase64(e);if(C.isBase64Url(e))return C.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=x.toUint8Array(e);if(t.length>0&&48===t[0])return x.toArrayBuffer(e);const r=C.ToBinary(e);if(Il.isPem(r))return Il.decode(r)[0];if(C.isHex(r))return C.FromHex(r);if(C.isBase64(r))return C.FromBase64(r);if(C.isBase64Url(r))return C.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){Tl.isAsnEncoded(e[0])?super(Tl.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?Il.encode(this.rawData,this.tag):super.toString(e)}}class Bl extends Tl{static async create(e,t=rl.get()){if(e instanceof Bl)return e;if(tl.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new Bl(r)}if(e.publicKey)return e.publicKey;if(x.isBufferSource(e))return new Bl(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){Tl.isAsnEncoded(e)?super(e,Wn):super(e),this.tag=Il.PublicKeyTag}async export(...e){let t,r=["verify"],i={hash:"SHA-256",...this.algorithm};e.length>1?(i=e[0]||i,r=e[1]||r,t=e[2]||rl.get()):t=e[0]||rl.get();let n=this.rawData;const o=Fr.parse(this.rawData,Wn);return o.algorithm.algorithm===la&&(n=function(e,t){return e.algorithm=new zn({algorithm:aa,parameters:null}),t=Fr.serialize(e),t}(o,n)),t.subtle.importKey("spki",n,i,!0,r)}onInit(e){const t=lc.resolve(du),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case aa:{const t=Fr.parse(e.subjectPublicKey,Ua),i=x.toUint8Array(t.modulus);r.publicExponent=x.toUint8Array(t.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,i="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(i=e[0]||i,r=e[1]||rl.get()):r=e[0]||rl.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=rl.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=rl.get();const i=Fr.parse(this.rawData,Wn);return await t.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,Wn);if(e.Algorithm=Xu.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===$s)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class Ol extends el{static async create(e,t=!1,r=rl.get()){if("name"in e&&"serialNumber"in e)return new Ol(e,t);const i=await Bl.create(e,r),n=await i.getKeyIdentifier(r);return new Ol(C.ToHex(n),t)}constructor(...e){if(x.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new ki({keyIdentifier:new Ei(C.FromHex(e[0]))});super(Ai,e[1],Fr.serialize(t))}else{const t=e[0],r=t.name instanceof El?Fr.parse(t.name.rawData,Ii):t.name,i=new ki({authorityCertIssuer:r,authorityCertSerialNumber:C.FromHex(t.serialNumber)});super(Ai,e[1],Fr.serialize(i))}}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,ki);t.keyIdentifier&&(this.keyId=C.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?C.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,ki);return t.authorityCertIssuer&&(e["Authority Issuer"]=new El(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}Ol.NAME="Authority Key Identifier";class Cl extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,_i);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new _i({cA:e[0],pathLenConstraint:e[1]});super(xi,e[2],Fr.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var Dl,jl,Pl;Cl.NAME="Basic Constraints",(jl=Dl||(Dl={})).serverAuth="1.3.6.1.5.5.7.3.1",jl.clientAuth="1.3.6.1.5.5.7.3.2",jl.codeSigning="1.3.6.1.5.5.7.3.3",jl.emailProtection="1.3.6.1.5.5.7.3.4",jl.timeStamping="1.3.6.1.5.5.7.3.8",jl.ocspSigning="1.3.6.1.5.5.7.3.9";class Rl extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,sn);this.usages=t.map((e=>e))}else{const t=new sn(e[0]);super(on,e[1],Fr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>Gu.toString(e))).join(", "),e}}Rl.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Pl||(Pl={}));class Ul extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,An);this.usages=t.toNumber()}else{const t=new An(e[0]);super(vn,e[1],Fr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,An);return e[""]=t.toJSON().join(", "),e}}Ul.NAME="Key Usages";class $l extends el{static async create(e,t=!1,r=rl.get()){const i=await Bl.create(e,r),n=await i.getKeyIdentifier(r);return new $l(C.ToHex(n),t)}constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,Un);this.keyId=C.ToHex(t)}else{const t="string"==typeof e[0]?C.FromHex(e[0]):e[0],r=new Un(t);super(Rn,e[1],Fr.serialize(r)),this.keyId=C.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,Un);return e[""]=t,e}}$l.NAME="Subject Key Identifier";class Ml extends el{constructor(...e){x.isBufferSource(e[0])?super(e[0]):super(On,e[1],new El(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Cn);this.names=new El(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}Ml.NAME="Subject Alternative Name";class Ll{static register(e,t){this.items.set(e,t)}static create(e){const t=new el(e),r=this.items.get(t.type);return r?new r(e):t}}Ll.items=new Map;class Vl extends el{constructor(...e){var t;if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,Mi);this.policies=t.map((e=>e.policyIdentifier))}else{const r=e[0],i=null!==(t=e[1])&&void 0!==t&&t,n=new Mi(r.map((e=>new $i({policyIdentifier:e}))));super(Ci,i,Fr.serialize(n)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new qu("",{},Gu.toString(e)))),e}}Vl.NAME="Certificate Policies",Ll.register(Ci,Vl);class Hl extends el{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map((e=>new qi({distributionPoint:new Ji({fullName:[new ui({uniformResourceIdentifier:e})]})}))),r=new Gi(t);super(Ki,e[1],Fr.serialize(r))}else{const t=new Gi(e[0]);super(Ki,e[1],Fr.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Gi);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map((e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map((e=>new Al(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}Hl.NAME="CRL Distribution Points";class Kl extends el{constructor(...e){var t,r,i,n;if(x.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Si){const t=new Si(e[0]);super(wi,e[1],Fr.serialize(t))}else{const t=e[0],r=new Si;zl(r,t,di,"ocsp"),zl(r,t,fi,"caIssuers"),zl(r,t,yi,"timeStamping"),zl(r,t,gi,"caRepository"),super(wi,e[1],Fr.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(i=this.timeStamping)&&void 0!==i||(this.timeStamping=[]),null!==(n=this.caRepository)&&void 0!==n||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[];Fr.parse(e.extnValue,Si).forEach((e=>{switch(e.accessMethod){case di:this.ocsp.push(new Al(e.accessLocation));break;case fi:this.caIssuers.push(new Al(e.accessLocation));break;case yi:this.timeStamping.push(new Al(e.accessLocation));break;case gi:this.caRepository.push(new Al(e.accessLocation))}}))}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Fl(e,"OCSP",this.ocsp),this.caIssuers.length&&Fl(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Fl(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Fl(e,"CA Repository",this.caRepository),e}}function Fl(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const i=new qu("");r.forEach(((e,t)=>{const r=e.toTextObject(),n=`${r[qu.NAME]} ${t+1}`;let o=i[n];Array.isArray(o)||(o=[],i[n]=o),o.push(r)})),e[t]=i}}function zl(e,t,r,i){const n=t[i];if(n){(Array.isArray(n)?n:[n]).forEach((t=>{"string"==typeof t&&(t=new Al("url",t)),e.push(new bi({accessMethod:r,accessLocation:Fr.parse(t.rawData,ui)}))}))}}Kl.NAME="Authority Info Access";class Wl extends el{constructor(...e){x.isBufferSource(e[0])?super(e[0]):super(gn,e[1],new El(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Ii);this.names=new El(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}Wl.NAME="Issuer Alternative Name";class Jl extends Qu{constructor(...e){let t;if(x.isBufferSource(e[0]))t=x.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map((e=>x.toArrayBuffer(e))):[];t=Fr.serialize(new Dn({type:r,values:i}))}super(t,Dn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new qu("",{"":e}))),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[qu.NAME]===Jl.NAME&&(e[qu.NAME]=Gu.toString(this.type)),e}}Jl.NAME="Attribute";class ql extends Jl{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else{const t=new ru({printableString:e[0]});super(Uc,[Fr.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Fr.parse(this.values[0],ru);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[qu.VALUE]=this.password,e}}ql.NAME="Challenge Password";class Gl extends Jl{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Yn;for(const e of t)r.push(Fr.parse(e.rawData,Xn));super($c,[Fr.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Fr.parse(this.values[0],Yn);this.items=e.map((e=>Ll.create(Fr.serialize(e))))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(const r of t)e[r[qu.NAME]]=r;return e}}Gl.NAME="Extensions";class Xl{static register(e,t){this.items.set(e,t)}static create(e){const t=new Jl(e),r=this.items.get(t.type);return r?new r(e):t}}Xl.items=new Map;const Yl="crypto.signatureFormatter";var Zl;let Ql=Zl=class{static createPssParams(e,t){const r=Zl.getHashAlgorithm(e);return r?new Oa({hashAlgorithm:r,maskGenAlgorithm:new zn({algorithm:xa,parameters:Fr.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=lc.resolve(du);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new zn({algorithm:aa,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new zn({algorithm:da,parameters:null});case"sha-256":return new zn({algorithm:ya,parameters:null});case"sha-384":return new zn({algorithm:ga,parameters:null});case"sha-512":return new zn({algorithm:ma,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=Zl.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new zn({algorithm:la,parameters:Fr.serialize(t)})}return new zn({algorithm:la,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case aa:return{name:"RSASSA-PKCS1-v1_5"};case da:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ya:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case ga:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ma:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case la:if(e.parameters){const t=Fr.parse(e.parameters,Oa);return{name:"RSA-PSS",hash:lc.resolve(du).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Ql=Zl=zr([pc()],Ql),lc.registerSingleton(hu,Ql);let ep=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new zn({algorithm:ba});case"sha-256":return new zn({algorithm:Aa});case"sha-384":return new zn({algorithm:Ea});case"sha-512":return new zn({algorithm:ka})}return null}toWebAlgorithm(e){switch(e.algorithm){case ba:return{name:"SHA-1"};case Aa:return{name:"SHA-256"};case Ea:return{name:"SHA-384"};case ka:return{name:"SHA-512"}}return null}};ep=zr([pc()],ep),lc.registerSingleton(hu,ep);class tp{addPadding(e,t){const r=x.toUint8Array(t),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,t=!1){let r=x.toUint8Array(e);for(let i=0;i<r.length;i++)if(r[i]){r=r.slice(i);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,i=tp.namedCurveSize.get(r)||tp.defaultNamedCurveSize,n=new oa,o=x.toUint8Array(t);return n.r=this.removePadding(o.slice(0,i),!0),n.s=this.removePadding(o.slice(i,i+i),!0),Fr.serialize(n)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Fr.parse(t,oa),i=e.namedCurve,n=tp.namedCurveSize.get(i)||tp.defaultNamedCurveSize;return function(...e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),r=new Uint8Array(t);let i=0;return e.map((e=>new Uint8Array(e))).forEach((e=>{for(const t of e)r[i++]=t})),r.buffer}(this.addPadding(n,this.removePadding(r.r)),this.addPadding(n,this.removePadding(r.s)))}return null}}tp.namedCurveSize=new Map,tp.defaultNamedCurveSize=32;const rp="1.3.101.110",ip="1.3.101.111",np="1.3.101.112",op="1.3.101.113";let sp=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=np;break;case"x25519":t=rp;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=np;break;case"ed448":t=op}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=rp;break;case"x448":t=ip}}return t?new zn({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case np:return{name:"Ed25519"};case op:return{name:"EdDSA",namedCurve:"Ed448"};case rp:return{name:"X25519"};case ip:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};var ap,cp,up,lp,pp,hp,dp,fp,yp,gp,mp,vp,wp,bp,Sp,Ap,Ep,kp,xp,_p,Np,Ip;sp=zr([pc()],sp),lc.registerSingleton(hu,sp);ap=new WeakMap,cp=new WeakMap,up=new WeakMap,lp=new WeakMap,pp=new WeakMap,hp=new WeakMap,dp=new WeakMap,fp=new WeakMap,class extends Tl{get subjectName(){return Wr(this,cp,"f")||Jr(this,cp,new al(this.asn.certificationRequestInfo.subject),"f"),Wr(this,cp,"f")}get subject(){return Wr(this,up,"f")||Jr(this,up,this.subjectName.toString(),"f"),Wr(this,up,"f")}get signatureAlgorithm(){if(!Wr(this,lp,"f")){const e=lc.resolve(du);Jr(this,lp,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Wr(this,lp,"f")}get signature(){return Wr(this,pp,"f")||Jr(this,pp,this.asn.signature,"f"),Wr(this,pp,"f")}get publicKey(){return Wr(this,hp,"f")||Jr(this,hp,new Bl(this.asn.certificationRequestInfo.subjectPKInfo),"f"),Wr(this,hp,"f")}get attributes(){return Wr(this,dp,"f")||Jr(this,dp,this.asn.certificationRequestInfo.attributes.map((e=>Xl.create(Fr.serialize(e)))),"f"),Wr(this,dp,"f")}get extensions(){if(!Wr(this,fp,"f")){Jr(this,fp,[],"f");const e=this.getAttribute($c);e instanceof Gl&&Jr(this,fp,e.items,"f")}return Wr(this,fp,"f")}get tbs(){return Wr(this,ap,"f")||Jr(this,ap,this.asn.certificationRequestInfoRaw||Fr.serialize(this.asn.certificationRequestInfo),"f"),Wr(this,ap,"f")}constructor(e){const t=Tl.isAsnEncoded(e)?[e,pu]:[e];super(t[0],t[1]),ap.set(this,void 0),cp.set(this,void 0),up.set(this,void 0),lp.set(this,void 0),pp.set(this,void 0),hp.set(this,void 0),dp.set(this,void 0),fp.set(this,void 0),this.tag=Il.CertificateRequestTag}onInit(e){}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t=>t.type===e))}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t=>t.type===e))}async verify(e=rl.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),i=lc.resolveAll(Yl).reverse();let n=null;for(const o of i)if(n=o.toWebSignature(t,this.signature),n)break;if(!n)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,n,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,pu),r=t.certificationRequestInfo,i=new qu("",{Version:`${Zn[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new qu("");for(const t of this.attributes){const r=t.toTextObject();e[r[qu.NAME]]=r}i.Attributes=e}return e.Data=i,e.Signature=new qu("",{Algorithm:Xu.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}.NAME="PKCS#10 Certificate Request";class Tp extends Tl{get publicKey(){return Wr(this,_p,"f")||Jr(this,_p,new Bl(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),Wr(this,_p,"f")}get serialNumber(){if(!Wr(this,gp,"f")){const e=this.asn.tbsCertificate;let t=new Uint8Array(e.serialNumber);t.length>1&&0===t[0]&&t[1]>127&&(t=t.slice(1)),Jr(this,gp,C.ToHex(t),"f")}return Wr(this,gp,"f")}get subjectName(){return Wr(this,mp,"f")||Jr(this,mp,new al(this.asn.tbsCertificate.subject),"f"),Wr(this,mp,"f")}get subject(){return Wr(this,vp,"f")||Jr(this,vp,this.subjectName.toString(),"f"),Wr(this,vp,"f")}get issuerName(){return Wr(this,wp,"f")||Jr(this,wp,new al(this.asn.tbsCertificate.issuer),"f"),Wr(this,wp,"f")}get issuer(){return Wr(this,bp,"f")||Jr(this,bp,this.issuerName.toString(),"f"),Wr(this,bp,"f")}get notBefore(){if(!Wr(this,Sp,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Jr(this,Sp,e,"f")}return Wr(this,Sp,"f")}get notAfter(){if(!Wr(this,Ap,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Jr(this,Ap,e,"f")}return Wr(this,Ap,"f")}get signatureAlgorithm(){if(!Wr(this,Ep,"f")){const e=lc.resolve(du);Jr(this,Ep,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Wr(this,Ep,"f")}get signature(){return Wr(this,kp,"f")||Jr(this,kp,this.asn.signatureValue,"f"),Wr(this,kp,"f")}get extensions(){return Wr(this,xp,"f")||(Jr(this,xp,[],"f"),this.asn.tbsCertificate.extensions&&Jr(this,xp,this.asn.tbsCertificate.extensions.map((e=>Ll.create(Fr.serialize(e)))),"f")),Wr(this,xp,"f")}get tbs(){return Wr(this,yp,"f")||Jr(this,yp,this.asn.tbsCertificateRaw||Fr.serialize(this.asn.tbsCertificate),"f"),Wr(this,yp,"f")}constructor(e){const t=Tl.isAsnEncoded(e)?[e,to]:[e];super(t[0],t[1]),yp.set(this,void 0),gp.set(this,void 0),mp.set(this,void 0),vp.set(this,void 0),wp.set(this,void 0),bp.set(this,void 0),Sp.set(this,void 0),Ap.set(this,void 0),Ep.set(this,void 0),kp.set(this,void 0),xp.set(this,void 0),_p.set(this,void 0),this.tag=Il.CertificateTag}onInit(e){}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t=>"string"==typeof e?t.type===e:t instanceof e))}async verify(e={},t=rl.get()){let r,i;const n=e.publicKey;try{if(n)if("publicKey"in n)r={...n.publicKey.algorithm,...this.signatureAlgorithm},i=await n.publicKey.export(r,["verify"],t);else if(n instanceof Bl)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"],t);else if(x.isBufferSource(n)){const e=new Bl(n);r={...e.algorithm,...this.signatureAlgorithm},i=await e.export(r,["verify"],t)}else r={...n.algorithm,...this.signatureAlgorithm},i=n;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],t)}catch{return!1}const o=lc.resolveAll(Yl).reverse();let s=null;for(const c of o)if(s=c.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,i,s,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=rl.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=rl.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,to),r=t.tbsCertificate,i=new qu("",{Version:`${Zn[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Xu.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new qu("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(i["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(i["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new qu("");for(const t of this.extensions){const r=t.toTextObject();e[r[qu.NAME]]=r}i.Extensions=e}return e.Data=i,e.Signature=new qu("",{Algorithm:Xu.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}yp=new WeakMap,gp=new WeakMap,mp=new WeakMap,vp=new WeakMap,wp=new WeakMap,bp=new WeakMap,Sp=new WeakMap,Ap=new WeakMap,Ep=new WeakMap,kp=new WeakMap,xp=new WeakMap,_p=new WeakMap,Tp.NAME="Certificate";class Bp{static async createSelfSigned(e,t=rl.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=rl.get()){var r;let i;i=e.publicKey instanceof Bl?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:x.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const n=function(e,t=rl.get()){const r=x.toUint8Array(C.FromHex(e||""));let i=r&&r.length&&r.some((e=>e>0))?new Uint8Array(r):void 0;i||(i=t.getRandomValues(new Uint8Array(16)));let n=0;for(;n<i.length-1&&0===i[n];)n++;if(i=i.slice(n),i[0]>127){const e=new Uint8Array(i.length+1);e[0]=0,e.set(i,1),i=e}return i.buffer}(e.serialNumber,t),o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),a=new to({tbsCertificate:new eo({version:Zn.v3,serialNumber:n,validity:new qn({notBefore:o,notAfter:s}),extensions:new Yn((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>Fr.parse(e.rawData,Xn))))||[]),subjectPublicKeyInfo:Fr.parse(i,Wn)})});if(e.subject){const t=e.subject instanceof al?e.subject:new al(e.subject);a.tbsCertificate.subject=Fr.parse(t.toArrayBuffer(),oi)}if(e.issuer){const t=e.issuer instanceof al?e.issuer:new al(e.issuer);a.tbsCertificate.issuer=Fr.parse(t.toArrayBuffer(),oi)}const c={hash:"SHA-256"},u="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},l=lc.resolve(du);a.tbsCertificate.signature=a.signatureAlgorithm=l.toAsnAlgorithm(u);const p=Fr.serialize(a.tbsCertificate),h="signingKey"in e?await t.subtle.sign(u,e.signingKey,p):e.signature,d=lc.resolveAll(Yl).reverse();let f=null;for(const y of d)if(f=y.toAsnSignature(u,h),f)break;if(!f)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return a.signatureValue=f,new Tp(Fr.serialize(a))}}function Op(e){const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Error(`buckyos cert cannot load builtin module ${e} in this runtime`)}function Cp(){const e=globalThis.crypto;if(null==e?void 0:e.subtle)return e;return Op("node:crypto").webcrypto}(Ip=Np||(Np={}))[Ip.unspecified=0]="unspecified",Ip[Ip.keyCompromise=1]="keyCompromise",Ip[Ip.cACompromise=2]="cACompromise",Ip[Ip.affiliationChanged=3]="affiliationChanged",Ip[Ip.superseded=4]="superseded",Ip[Ip.cessationOfOperation=5]="cessationOfOperation",Ip[Ip.certificateHold=6]="certificateHold",Ip[Ip.removeFromCRL=8]="removeFromCRL",Ip[Ip.privilegeWithdrawn=9]="privilegeWithdrawn",Ip[Ip.aACompromise=10]="aACompromise",Ll.register(xi,Cl),Ll.register(on,Rl),Ll.register(vn,Ul),Ll.register(Rn,$l),Ll.register(Ai,Ol),Ll.register(On,Ml),Ll.register(Ki,Hl),Ll.register(wi,Kl),Ll.register(gn,Wl),Xl.register(Uc,ql),Xl.register($c,Gl),lc.registerSingleton(Yl,class{toAsnSignature(e,t){return x.toArrayBuffer(t)}toWebSignature(e,t){return x.toArrayBuffer(t)}}),lc.registerSingleton(Yl,tp),tp.namedCurveSize.set("P-256",32),tp.namedCurveSize.set("K-256",32),tp.namedCurveSize.set("P-384",48),tp.namedCurveSize.set("P-521",66);const Dp={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:4096},jp={...Dp,modulusLength:2048},Pp=["server","client","authentication","assertion","key-agreement","capability"],Rp=["did-json","did-meta","cert","chain","fullchain","ca","public","csr","meta","private","keyref","verification-method"];function Up(){const e=new Uint8Array(16);return Cp().getRandomValues(e),e[0]&=127,e[0]|=1,Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function $p(e){return new Date(Date.now()+24*e*3600*1e3)}async function Mp(e){const t=new Uint8Array(await Cp().subtle.exportKey("pkcs8",e));return Il.encode(t,"PRIVATE KEY")}function Lp(e){return Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Vp(e){const t=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||46===e||95===e||45===e;let r="";for(const i of function(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=Op("node:buffer").Buffer;return new Uint8Array(t.from(e,"utf8"))}(e))t(i)?r+=String.fromCharCode(i):r+=`%${i.toString(16).toUpperCase().padStart(2,"0")}`;if(!r||"."===r||".."===r||/[\\/]/.test(r)||r.includes("\0"))throw new Error(`Invalid encoded identity directory name for raw host URI: ${e}`);return r}function Hp(e){const t=e.trim();if(!t)throw new Error("identity DID or hostname is empty");return i.DID.fromStr(function(e){return e.startsWith("did:web:*.")?`did:web:_.${e.slice(10)}`:e.startsWith("*.")?`_.${e.slice(2)}`:e}(t))}function Kp(e){return Hp(e).toRawHostUri()}function Fp(e){return Vp(Kp(e))}function zp(e){const t=Hp(e);if("web"!==t.method)return null;const r=t.toRawHostName(),i=t.getPathFromId();return i?`https://${r}/${i}/did.json`:`https://${r}/.well-known/did.json`}function Wp(e,t){switch(function(e){if(!Pp.includes(e))throw new Error(`Unsupported identity usage: ${e}`)}(e),function(e){if(!Rp.includes(e))throw new Error(`Unsupported identity material: ${e}`)}(t),t){case"did-json":return"did.json";case"did-meta":return"did.meta.json";case"cert":return`${e}.cert.pem`;case"chain":return`${e}.chain.pem`;case"fullchain":return`${e}.fullchain.pem`;case"ca":return`${e}.ca.pem`;case"public":return"server"===e||"client"===e?`${e}.public.pem`:`${e}.public.jwk`;case"csr":return`${e}.csr.pem`;case"meta":return`${e}.meta.json`;case"private":return`${e}.private.pem`;case"keyref":return`${e}.keyref.json`;case"verification-method":return`${e}.verification-method.json`}}function Jp(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function qp(e,t,r){const i=Op("node:path");return{cert:i.join(e,Wp(r,"cert")),chain:i.join(e,Wp(r,"chain")),fullchain:i.join(e,Wp(r,"fullchain")),ca:i.join(e,Wp(r,"ca")),metadata:i.join(e,Wp(r,"meta")),keyref:i.join(t,Wp(r,"keyref")),privateKey:i.join(t,Wp(r,"private"))}}class Gp{constructor(e,t){const r=Op("node:path");this.publicRoot=r.resolve(e),this.securityRoot=r.resolve(t)}static fromEnvOrBuckyosRoot(e={}){const t=Op("node:path"),r=function(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}(),i=Jp(e.buckyosRoot)??Jp(r.BUCKYOS_ROOT)??"/opt/buckyos",n=Jp(e.publicRoot)??Jp(r.BUCKYOS_IDENTITY_ROOT)??t.join(i,"local","identity"),o=Jp(e.securityRoot)??Jp(r.BUCKYOS_SECURITY_ROOT)??t.join(i,"security");return new Gp(n,o)}rawHostUri(e){return Kp(e)}dirName(e){return Fp(e)}publicDir(e){return Op("node:path").join(this.publicRoot,this.dirName(e))}securityDir(e){return Op("node:path").join(this.securityRoot,this.dirName(e))}publicFile(e,t,r){return Op("node:path").join(this.publicDir(e),Wp(t,r))}securityFile(e,t,r){return Op("node:path").join(this.securityDir(e),Wp(t,r))}x509Paths(e,t="server"){return qp(this.publicDir(e),this.securityDir(e),t)}identityDirMatch(e){const t=this.rawHostUri(e),r=Vp(t);return{type:t.startsWith("_.")?"wildcard":"exact",rawHostUri:t,dirName:r,publicDir:this.publicDir(e),securityDir:this.securityDir(e),...t.startsWith("_.")?{hostPattern:`*.${t.slice(2)}`}:{host:t}}}findX509Paths(e,t="server"){const r=Op("node:fs"),i=this.identityDirMatch(e),n=qp(i.publicDir,i.securityDir,t);if(r.existsSync(n.fullchain)||r.existsSync(n.cert))return{match:i,paths:n};const o=Hp(e);if("web"!==o.method)return null;const s=o.toRawHostName().split(".");if(s.length<3)return null;const a=`_.${s.slice(1).join(".")}`,c=Vp(a),u=Op("node:path"),l=u.join(this.publicRoot,c),p=u.join(this.securityRoot,c),h=qp(l,p,t);return r.existsSync(h.fullchain)||r.existsSync(h.cert)?{match:{type:"wildcard",rawHostUri:a,dirName:c,publicDir:l,securityDir:p,hostPattern:`*.${s.slice(1).join(".")}`},paths:h}:null}}async function Xp(e){const t=Cp();if(e.includes("BEGIN RSA PRIVATE KEY")){const r=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),r=new Uint8Array([2,1,0]),i=Yp(4,e),n=new Uint8Array(r.length+t.length+i.length);return n.set(r,0),n.set(t,r.length),n.set(i,r.length+t.length),Yp(48,n)}(new Uint8Array(Il.decode(e)[0]));return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}const r=new Uint8Array(Il.decode(e)[0]);return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}function Yp(e,t){let r;r=t.length<128?[e,t.length]:t.length<256?[e,129,t.length]:[e,130,t.length>>8,255&t.length];const i=new Uint8Array(r.length+t.length);return i.set(r,0),i.set(t,r.length),i}function Zp(e){const t=e.extensions.find((e=>e instanceof Cl));if(!(null==t?void 0:t.ca))return"missing basicConstraints CA:TRUE";const r=e.extensions.find((e=>e instanceof Ul));return!r||r.usages&Pl.keyCertSign?void 0:"keyUsage does not allow certificate signing"}async function Qp(e,t="devtest"){const r=Op("node:fs"),i=Op("node:path"),n=Cp();rl.set(n),r.mkdirSync(e,{recursive:!0});const o=i.join(e,`${t}_ca_key.pem`),s=i.join(e,`${t}_ca_cert.pem`),a=`C=US, ST=California, L=San Jose, O=${`${t}'s Dev Test Environment`}, OU=Test, CN=${t}`,c=await n.subtle.generateKey(Dp,!0,["sign","verify"]),u=await Bp.createSelfSigned({serialNumber:Up(),name:a,notBefore:new Date,notAfter:$p(3650),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},keys:c,extensions:[new Cl(!0,void 0,!0),new Ul(Pl.keyCertSign|Pl.cRLSign|Pl.digitalSignature,!0),await $l.create(c.publicKey)]});return r.writeFileSync(o,await Mp(c.privateKey)),r.writeFileSync(s,u.toString("pem")),console.log(`CA certificate created: ${s}`),{caCertPath:s,caKeyPath:o}}async function eh(e,t,r=[],i="server"){const n=Op("node:fs"),o=Cp();rl.set(o);const{caCertPath:s,caKeyPath:a}=function(e){const t=Op("node:fs"),r=Op("node:path"),i=t.readdirSync(e).filter((e=>e.endsWith("_ca_cert.pem")));if(0===i.length)throw new Error(`No CA certificate found matching *_ca_cert.pem pattern in ${e}`);if(i.length>1)throw new Error(`Multiple CA certificates found in ${e}: ${i.join(", ")}`);const n=r.join(e,i[0]),o=r.join(e,i[0].replace("_ca_cert.pem","_ca_key.pem"));if(!t.existsSync(o))throw new Error(`CA key not found: ${o}`);return{caCertPath:n,caKeyPath:o}}(e),c=n.readFileSync(s,"utf8"),u=new Tp(c),l=Zp(u);if(l)throw new Error(`Invalid CA certificate at ${s}: ${l}`);const p=await Xp(n.readFileSync(a,"utf8")),h=t[0];if(!h)throw new Error("At least one DNS SAN is required when creating an X.509 certificate");const d=await o.subtle.generateKey(jp,!0,["sign","verify"]),f=new Uint8Array(await o.subtle.exportKey("spki",d.publicKey)),y=await async function(e){const t=await Cp().subtle.digest("SHA-256",e);return`sha256:${Lp(new Uint8Array(t))}`}(f),g=[...t.map((e=>({type:"dns",value:e}))),...r.map((e=>({type:"url",value:e})))],m=await Bp.create({serialNumber:Up(),subject:`CN=${h}`,issuer:u.subjectName,notBefore:new Date,notAfter:$p(365),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},publicKey:d.publicKey,signingKey:p,extensions:[new Ul(Pl.digitalSignature|Pl.keyEncipherment,!0),new Rl(["client"===i?Dl.clientAuth:Dl.serverAuth]),new Ml(g),await $l.create(d.publicKey),await Ol.create(u)]});return{cert:m,certPem:m.toString("pem"),privateKeyPem:await Mp(d.privateKey),caCertPem:c,publicKeyFingerprint:y}}function th(e){return`${e.trimEnd()}\n`}function rh(e,t,r){const i=Op("node:fs"),n=Op("node:path"),o=n.dirname(e),s=n.join(o,`.${n.basename(e)}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{i.writeFileSync(s,t,void 0===r?void 0:{mode:r});try{const e=i.openSync(s,"r");try{i.fsyncSync(e)}finally{i.closeSync(e)}}catch{}i.renameSync(s,e)}catch(a){try{i.existsSync(s)&&i.unlinkSync(s)}catch{}throw a}}function ih(e){const t=e.toRawHostName();return t.startsWith("_.")?`*.${t.slice(2)}`:t}function nh(e){if("web"!==e.method||e.toRawHostName().startsWith("_."))return;const t=e.toString();return{type:"did-web-domain",did:t,web_origin:`https://${e.toRawHostName()}`,did_document_url:zp(t)}}async function oh(e,t,r,i,n){const o=function(e){const t=e.extensions.find((e=>e instanceof Ml)),r=(null==t?void 0:t.names.toJSON())??[];return{dns:r.filter((e=>"dns"===e.type)).map((e=>e.value)),uri:r.filter((e=>"url"===e.type)).map((e=>e.value))}}(n.cert),s=await async function(e){const t=await e.getThumbprint("SHA-256",Cp());return`sha256:${Lp(new Uint8Array(t))}`}(n.cert),a=r.startsWith("_."),c=(new Date).toISOString();return{schema:"buckyos.identity.x509.metadata.v1",did:e.toString(),raw_host_uri:r,dir_name:i,usage:t,match:a?{type:"wildcard",host_pattern:`*.${r.slice(2)}`}:{type:"exact",host:r},certificate:{serial_number:n.cert.serialNumber,issuer:n.cert.issuer,subject:n.cert.subject,not_before:n.cert.notBefore.toISOString(),not_after:n.cert.notAfter.toISOString(),fingerprint_sha256:s,public_key_fingerprint:n.publicKeyFingerprint},san:o,paths:{cert:Wp(t,"cert"),chain:Wp(t,"chain"),fullchain:Wp(t,"fullchain"),ca:Wp(t,"ca")},did_binding:nh(e),updated_at:c,generation:`${c.replace(/[-:.]/g,"")}-${s}`}}const sh="test test test test test test test test test test test junk",ah=2147483648,ch=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),uh=(1n<<64n)-1n,lh=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],ph=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];function hh(e,t=""){return o.pbkdf2Sync(n.Buffer.from(e.normalize("NFKD"),"utf8"),n.Buffer.from(`mnemonic${t}`.normalize("NFKD"),"utf8"),2048,64,"sha512")}function dh(e,t){return o.createHmac("sha512",e).update(t).digest()}function fh(e){const t=n.Buffer.alloc(4);return t.writeUInt32BE(e>>>0,0),t}function yh(e){const t=o.createPublicKey(o.createPrivateKey(e)).export({format:"jwk"});if(!t.x)throw new Error("failed to derive Ed25519 public key x");return t.x}function gh(e,t,r){const i=dh(t,n.Buffer.concat([n.Buffer.from([0]),e,fh(r+ah)]));return{key:i.subarray(0,32),chainCode:i.subarray(32)}}function mh(e,t,r){let i=function(e){const t=dh("ed25519 seed",e);return{key:t.subarray(0,32),chainCode:t.subarray(32)}}(hh(e,t));for(const n of[9777,0,r])i=gh(i.key,i.chainCode,n);return n.Buffer.from(i.key)}function vh(e,t,r){const i=function(e){return`-----BEGIN PRIVATE KEY-----\n${n.Buffer.concat([n.Buffer.from("302e020100300506032b657004220420","hex"),e]).toString("base64")}\n-----END PRIVATE KEY-----\n`}(mh(e,t??"",r));return{privateKeyPem:i,publicKeyX:yh(i)}}function wh(e){return vh(sh,void 0,e)}function bh(e){const t=e.toString(16).padStart(64,"0");return n.Buffer.from(t,"hex")}function Sh(e){return BigInt(`0x${e.toString("hex")}`)}function Ah(e,t){const r=o.createECDH("secp256k1");return r.setPrivateKey(e),r.getPublicKey(void 0,t?"compressed":"uncompressed")}function Eh(e,t,r){const i=dh(t,r>=ah?n.Buffer.concat([n.Buffer.from([0]),e,fh(r)]):n.Buffer.concat([Ah(e,!0),fh(r)])),o=Sh(i.subarray(0,32));if(o>=ch)throw new Error(`invalid secp256k1 child tweak at index ${r}`);const s=(o+Sh(e))%ch;if(0n===s)throw new Error(`invalid secp256k1 child key at index ${r}`);return{privateKey:bh(s),chainCode:i.subarray(32)}}function kh(e){return`m/44'/60'/0'/0/${e}`}function xh(e,t){if(0===t)return e&uh;const r=BigInt(t);return(e<<r|e>>64n-r)&uh}function _h(e){for(const t of lh){const r=new Array(5),i=new Array(5),n=new Array(25).fill(0n);for(let t=0;t<5;t+=1)r[t]=e[t]^e[t+5]^e[t+10]^e[t+15]^e[t+20];for(let e=0;e<5;e+=1)i[e]=r[(e+4)%5]^xh(r[(e+1)%5],1);for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)e[t+5*r]=(e[t+5*r]^i[t])&uh;for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)n[r+(2*t+3*r)%5*5]=xh(e[t+5*r],ph[t][r]);for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)e[t+5*r]=(n[t+5*r]^~n[(t+1)%5+5*r]&uh&n[(t+2)%5+5*r])&uh;e[0]=(e[0]^t)&uh}}function Nh(e){const t=136,r=new Array(25).fill(0n),i=n.Buffer.concat([e,n.Buffer.from([1]),n.Buffer.alloc((t-(e.length+1)%t)%t)]);i[i.length-1]^=128;for(let n=0;n<i.length;n+=t){for(let e=0;e<t;e+=1)r[Math.floor(e/8)]^=BigInt(i[n+e])<<BigInt(e%8*8);_h(r)}const o=n.Buffer.alloc(32);for(let n=0;n<o.length;n+=1)o[n]=Number(r[Math.floor(n/8)]>>BigInt(n%8*8)&0xffn);return o}function Ih(e){const t=e.toString("hex"),r=Nh(n.Buffer.from(t,"ascii"));let i="0x";for(let n=0;n<t.length;n+=1){const e=t[n],o=r[Math.floor(n/2)]>>4*(1-n%2)&15;i+=/[a-f]/.test(e)&&o>7?e.toUpperCase():e}return i}function Th(e,t,r){let i=function(e){const t=dh("Bitcoin seed",e),r=t.subarray(0,32),i=Sh(r);if(i<=0n||i>=ch)throw new Error("invalid secp256k1 master key");return{privateKey:n.Buffer.from(r),chainCode:t.subarray(32)}}(hh(e,t??""));for(const n of function(e){return[2147483692,2147483708,ah,0,e]}(r))i=Eh(i.privateKey,i.chainCode,n);const o=Ah(i.privateKey,!1),s=Ah(i.privateKey,!0),a=Nh(o.subarray(1)),c=i.privateKey.toString("hex");return{derivationPath:kh(r),privateKey:`0x${c}`,privateKeyHex:c,publicKeyCompressedHex:s.toString("hex"),publicKeyUncompressedHex:o.toString("hex"),address:Ih(a.subarray(12))}}function Bh(e){return Th(sh,void 0,e)}const Oh={devtest:0,alice:1,bob:2,charlie:3,dave:4,sn_owner:5,devtests:5,"devtest.ood1":100,devtest_ood1:100,"devtest.node1":101,devtest_node1:101,"alice.ood1":102,alice_ood1:102,"bob.ood1":103,bob_ood1:103,"charlie.ood1":104,charlie_ood1:104,"dave.ood1":105,dave_ood1:105,sn:106,sn_server:106,"devtests.ood1":107,devtests_ood1:107,sn_web:107},Ch={alice:1,bob:2,charlie:3,dave:4},Dh=Object.fromEntries(Object.entries(Oh).map((([e,t])=>[e,wh(t)]))),jh=Object.fromEntries(Object.entries(Ch).map((([e,t])=>[e,Bh(t)]))),Ph=Bh(0);function Rh(e){const t=Dh[e];if(!t)throw new Error(`unknown dev test key pair id: ${e}`);return t}const Uh="ood1",$h="wan",Mh=i.DEFAULT_EXPIRE_TIME,Lh="provision_activation.lock",Vh="zone_dns_records.json",Hh="zone_document.jwt";class Kh extends Error{constructor(e,t,r={}){super(t),this.name="ActivationError",this.code=e,this.details=r}}function Fh(e){const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Kh("RUNTIME_UNSUPPORTED",`buckyos provision cannot load builtin module ${e} in this runtime (Node >= 22.13 or Deno >= 2.2 is required)`)}function zh(){var e;return"win32"===(null==(e=globalThis.process)?void 0:e.platform)}function Wh(e,t){const r=Fh("node:path");return r.relative(e,t).split(r.sep).join("/")}function Jh(e){return Fh("node:crypto").createHash("sha256").update(e,"utf8").digest("hex")}function qh(){return Fh("node:crypto").randomBytes(6).toString("hex")}function Gh(e){const t=Fh("node:fs");try{return t.lstatSync(e)}catch(r){const e=r.code;if("ENOENT"===e||"ENOTDIR"===e)return null;throw r}}function Xh(e){const t=Fh("node:fs");try{return t.statSync(e)}catch(r){if("ENOENT"===r.code||"ENOTDIR"===r.code)return null;throw r}}function Yh(e){var t;return!0===(null==(t=Xh(e))?void 0:t.isDirectory())}function Zh(e){var t;return!0===(null==(t=Xh(e))?void 0:t.isFile())}function Qh(e){const t=Fh("node:fs"),r=JSON.parse(t.readFileSync(e,"utf8"));if(!r||"object"!=typeof r||Array.isArray(r))throw new Error(`${e} is not a JSON object`);return r}function ed(e){return JSON.stringify(e,null,2)}function td(e,t,r,i,n){const o=Fh("node:fs"),s=Fh("node:path"),a=s.dirname(e);o.mkdirSync(a,{recursive:!0,mode:i}),zh()||o.chmodSync(a,i);const c=()=>{if(void 0!==n){if(vd(e)!==n)throw new Error(`gateway placeholder changed during activation: ${e}`)}else if(Gh(e))throw new Error(`refusing to overwrite existing file: ${e}`)};c();const u=s.join(a,`.${s.basename(e)}.provision-${qh()}`);try{o.writeFileSync(u,t,{mode:r,flag:"wx"}),zh()||o.chmodSync(u,r),c(),o.renameSync(u,e)}finally{Gh(u)&&o.rmSync(u,{force:!0})}}function rd(e){const t=function(e){return e.trim().toLowerCase().replace(/\.$/,"")}(String(e??""));if(0===t.length||t.length>253||!t.includes(".")||t.split(".").some((e=>0===e.length||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-z0-9-]+$/.test(e))))throw new Kh("INVALID_ARGUMENT",`invalid did:web domain: ${e}`,{field:"domain"});return t}function id(e){const t=String(e??"").trim().toLowerCase();if(0===t.length||t.length>63||!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(t))throw new Kh("INVALID_ARGUMENT","owner name must be a lowercase DNS label (letters, digits, and hyphens)",{field:"owner_name"});return t}function nd(e){const t=e??2980;if(!Number.isInteger(t)||t<1||t>65535)throw new Kh("INVALID_ARGUMENT",`invalid RTCP port: ${String(e)}`,{field:"rtcp_port"});return t}function od(e){const t=(null==e?void 0:e.trim())||void 0;if(void 0===t)return;if(0===Fh("node:net").isIP(t))throw new Kh("INVALID_ARGUMENT",`invalid public IP address: ${t}`,{field:"public_ip"});return t}function sd(e){if("string"!=typeof e||e.length<8)throw new Kh("INVALID_ARGUMENT","administrator password must contain at least 8 characters",{field:"admin_password"});return e}function ad(e,t){return s.hashPassword(e,t,null)}function cd(e,t){const r=[];if(t){const i=Fh("node:net");r.push({type:6===i.isIP(t)?"AAAA":"A",name:e,value:t})}return r}function ud(){const e=Fh("node:crypto"),{privateKey:t,publicKey:r}=e.generateKeyPairSync("ed25519"),i=r.export({format:"jwk"});if("string"!=typeof i.x||0===i.x.length)throw new Kh("KEY_GENERATION_FAILED","generated Ed25519 public key has no x coordinate");return{privateKeyPem:t.export({format:"pem",type:"pkcs8"}).toString(),publicKeyX:i.x}}function ld(e){const t=Fh("node:path");if("string"!=typeof e.rootDir||0===e.rootDir.trim().length)throw new Kh("INVALID_ARGUMENT","target root is required",{field:"root"});if("string"!=typeof e.ownerKeyBackupPath||0===e.ownerKeyBackupPath.trim().length)throw new Kh("INVALID_ARGUMENT","owner key backup path is required",{field:"owner_key_backup"});const r=rd(e.domain),n=new i.DID("web",r);return{rootDir:t.resolve(e.rootDir),domain:r,ownerName:id(e.ownerName),ownerKeyBackupPath:t.resolve(e.ownerKeyBackupPath),rtcpPort:nd(e.rtcpPort),guestAccess:e.guestAccess??!1,publicIp:od(e.publicIp),ownerDid:n,zoneDid:n,deviceDid:g(Uh,n)}}function pd(e){const t=Fh("node:path");return new Gp(t.join(e,"local","identity"),t.join(e,"security"))}function hd(e,t,r){const i=Fh("node:path"),n=i.join(e,"etc"),o=y(pd(e),r);return{etcDir:n,lockPath:i.join(n,Lh),nodeIdentityPath:i.join(n,"node_identity.json"),startConfigPath:i.join(e,"security","start_config.json"),zoneDocumentJwtPath:i.join(n,Hh),gatewayParamsPath:i.join(n,"node_gateway_params.json"),dnsRecordsPath:i.join(n,Vh),zoneBootOverridePath:i.join(n,`${t.toRawHostName()}.zone.json`),didJsonPath:o.didJson,deviceDocJwtPath:o.deviceDocJwt,deviceMiniDocJwtPath:o.deviceMiniDocJwt,devicePrivateKeyPath:o.authenticationPrivateKey,publicDir:o.publicDir,securityDir:o.securityDir}}function dd(e,t){const r=(t,r,i,n)=>({path:Wh(e,t),role:r,required:i,secret:n,absolutePath:t,mode:n?384:420,dirMode:n?448:493});return[r(t.devicePrivateKeyPath,"device_private_key",!0,!0),r(t.didJsonPath,"device_document",!0,!1),r(t.deviceDocJwtPath,"device_document_jwt",!0,!1),r(t.deviceMiniDocJwtPath,"device_mini_document_jwt",!0,!1),r(t.zoneBootOverridePath,"zone_boot_override",!0,!1),r(t.zoneDocumentJwtPath,"zone_document_jwt",!0,!1),r(t.dnsRecordsPath,"dns_records",!1,!1),r(t.startConfigPath,"start_config",!0,!0),r(t.gatewayParamsPath,"gateway_params",!0,!1),r(t.nodeIdentityPath,"node_identity",!0,!1)]}function fd(e){return{path:e.path,role:e.role,required:e.required,secret:e.secret}}function yd(e){if(!Gh(e))return null;const t={path:e,schemaVersion:null,traceId:null,startedAt:null,domain:null,stage:null,committedFiles:[],ownerKeyBackupPath:null,corrupt:!1};try{const r=Qh(e),i=r.stage;return{...t,schemaVersion:"number"==typeof r.schema_version?r.schema_version:null,traceId:"string"==typeof r.trace_id?r.trace_id:null,startedAt:"number"==typeof r.started_at?r.started_at:null,domain:"string"==typeof r.domain?r.domain:null,stage:"locked"===i||"backup_saved"===i||"committing"===i||"committed"===i?i:null,committedFiles:Array.isArray(r.committed)?r.committed.filter((e=>"string"==typeof e)):[],ownerKeyBackupPath:"string"==typeof r.owner_key_backup?r.owner_key_backup:null}}catch{return{...t,corrupt:!0}}}function gd(e,t){const r=Fh("node:fs"),i=Fh("node:path"),n=i.join(i.dirname(e),`.${Lh}.${qh()}`);try{r.writeFileSync(n,ed(t),{mode:384,flag:"wx"}),r.renameSync(n,e)}finally{Gh(n)&&r.rmSync(n,{force:!0})}}function md(e){const t=Fh("node:fs");return Yh(e)?t.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name)).sort():[]}function vd(e){var t;try{if(!(null==(t=Gh(e))?void 0:t.isFile()))return;const r=Fh("node:fs").readFileSync(e,"utf8"),i=JSON.parse(r);if(!i||"object"!=typeof i||Array.isArray(i)||Object.keys(i).some((e=>"params"!==e)))return;const n=i.params;if(!n||"object"!=typeof n||Array.isArray(n)||"did:bns:unactivated.local"!==n.device_did||Object.keys(n).some((e=>"device_did"!==e&&"rtcp_port"!==e)))return;if(void 0!==n.rtcp_port&&("string"!=typeof n.rtcp_port||!/^\d+$/.test(n.rtcp_port)||Number(n.rtcp_port)<1||Number(n.rtcp_port)>65535))return;return r}catch{return}}function wd(e){try{return i.getXFromJwk(e)}catch{return null}}async function bd(e,t=!1){const r=Fh("node:path"),n=r.resolve(String(e??"")),o=i.buckyosGetUnixTimestamp(),s=[],a=[],c=e=>({rootDir:n,state:e,startupRequired:"configured"===e,observedAt:o,zoneDid:null,ownerDid:null,deviceDid:null,deviceName:null,accessHostname:null,files:[],problems:s,warnings:a,lock:null});if(!Yh(n))return s.push({code:"ROOT_MISSING",message:`BUCKYOS_ROOT does not exist: ${n}`}),c("not_installed");const u=["bin","etc"].filter((e=>!Yh(r.join(n,e))));if(u.length>0){for(const e of u)s.push({code:"INSTALL_INCOMPLETE",message:`installed BuckyOS directory is missing: ${r.join(n,e)}`});return c("not_installed")}const l=r.join(n,"etc"),p=t?null:yd(r.join(l,Lh)),h=function(e,t){if(!Zh(e))return{nodeIdentity:null,zoneDid:null,deviceDid:null};try{const r=Qh(e);if(r.schema!==i.NODE_IDENTITY_SCHEMA_V2)return t.push({code:"NODE_IDENTITY_SCHEMA",message:`etc/node_identity.json schema '${String(r.schema)}' is not ${i.NODE_IDENTITY_SCHEMA_V2}`}),{nodeIdentity:r,zoneDid:null,deviceDid:null};return{nodeIdentity:r,zoneDid:i.DID.fromStr(String(r.zone_did)),deviceDid:i.DID.fromStr(String(r.device_did))}}catch(r){return t.push({code:"NODE_IDENTITY_UNREADABLE",message:`etc/node_identity.json cannot be parsed: ${r instanceof Error?r.message:String(r)}`}),{nodeIdentity:null,zoneDid:null,deviceDid:null}}}(r.join(l,"node_identity.json"),s);let d=h.zoneDid,f=h.deviceDid;const m=md(r.join(n,"local","identity")),v=md(r.join(n,"security")),w=function(e,t){const r=Fh("node:fs");return Yh(e)?r.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isFile()&&t(e.name))).map((e=>e.name)).sort():[]}(l,(e=>e.endsWith(".zone.json")));if(!d&&w.length>0){const e=w[0].slice(0,-10);e.endsWith(".did")||(d=new i.DID("web",e))}!f&&d&&(f=g(Uh,d));const b=[...m,...v].filter((e=>!f||e!==r.basename(y(pd(n),f).publicDir))),S=[];let A=null;if(d&&f){A=hd(n,d,f);for(const e of dd(n,A))S.push({...fd(e),present:Zh(e.absolutePath)})}else{for(const[e,t,i]of[["node_identity.json","node_identity",!0],[Hh,"zone_document_jwt",!0],["node_gateway_params.json","gateway_params",!0],[Vh,"dns_records",!1]])S.push({path:`etc/${e}`,role:t,required:i,secret:!1,present:Zh(r.join(l,e))});S.push({path:"security/start_config.json",role:"start_config",required:!0,secret:!0,present:Zh(r.join(n,"security","start_config.json"))});for(const e of w)S.push({path:`etc/${e}`,role:"zone_boot_override",required:!0,secret:!1,present:!0})}const E=S.find((e=>"gateway_params"===e.role)),k=!0===(null==E?void 0:E.present)&&void 0!==vd(r.join(l,"node_gateway_params.json"));E&&k&&(E.present=!1);const x=S.filter((e=>e.present&&"dns_records"!==e.role)),_=S.filter((e=>e.required&&!e.present)),N=c("unactivated");N.files=S,N.lock=p,N.zoneDid=(null==d?void 0:d.toString())??null,N.deviceDid=(null==f?void 0:f.toString())??null,N.deviceName=h.nodeIdentity?String(h.nodeIdentity.device_name):f?Uh:null,N.ownerDid=h.nodeIdentity?String(h.nodeIdentity.owner_did):null,p&&a.push(p.corrupt?`activation lock ${p.path} exists but cannot be parsed`:`activation lock ${p.path} exists (stage=${p.stage??"unknown"}, committed=${p.committedFiles.length})`);for(const i of b)a.push(`unexpected identity directory: ${i}`);if(0===x.length&&0===b.length&&!p&&0===s.length)return N.state="unactivated",N;if(_.length>0||!A||b.length>0&&0===x.length){for(const e of _)s.push({code:"FILE_MISSING",message:`${e.path} is missing`});return N.state="partial",N}const I=await async function(e,t,r,n){var o,s,a;const c=Fh("node:fs"),u=r.nodeIdentity;if(!u||!r.zoneDid||!r.deviceDid)return{ownerDid:null,accessHostname:null};const l=(e,t)=>n.push({code:e,message:t}),p=r.zoneDid,h=r.deviceDid,d=String(u.owner_did),f=u.owner_public_key;"web"!==p.method&&l("IDENTITY_NOT_DID_WEB",`zone DID ${p.toString()} is not a did:web identity`),d!==p.toString()&&l("OWNER_ZONE_MISMATCH",`owner DID ${d} differs from zone DID ${p.toString()}`);const y=g(String(u.device_name),p).toString();if(h.toString()!==y&&l("DEVICE_DID_MISMATCH",`device DID ${h.toString()} is not ${y}`),!f||"object"!=typeof f||"string"!=typeof f.x)return l("OWNER_KEY_MISSING","etc/node_identity.json owner_public_key is not an Ed25519 JWK"),{ownerDid:d,accessHostname:null};let m=null;try{m=Qh(t.startConfigPath)}catch(O){l("START_CONFIG_UNREADABLE",`security/start_config.json cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}let v=null;const w={};if(m){for(const t of["user_name","zone_name","access_hostname","admin_password_hash"])"string"==typeof m[t]&&0!==m[t].length||l("START_CONFIG_FIELD",`security/start_config.json is missing ${t}`);for(const t of["boot_config_jwt","device_doc_jwt","device_mini_doc_jwt","zone_document_jwt","ood_jwt"])"string"==typeof m[t]&&m[t].length>0?w[t]=m[t]:l("START_CONFIG_FIELD",`security/start_config.json is missing ${t}`);m.zone_name!==p.toString()&&l("START_CONFIG_ZONE",`security/start_config.json zone_name is not ${p.toString()}`),"string"==typeof m.access_hostname&&(v=m.access_hostname,v!==p.toRawHostName()&&l("START_CONFIG_HOSTNAME",`security/start_config.json access_hostname is not ${p.toRawHostName()}`));const e=m.owner_document;if(e&&"object"==typeof e){e.id!==d&&l("START_CONFIG_OWNER",`owner_document id ${String(e.id)} is not ${d}`);const t=Array.isArray(e.verificationMethod)?e.verificationMethod.find((e=>e&&"#main_key"===e.id)):void 0;t&&wd(t.publicKeyJwk)===f.x||l("START_CONFIG_OWNER_KEY","owner_document #main_key differs from node_identity owner_public_key")}else l("START_CONFIG_OWNER","security/start_config.json is missing owner_document");w.ood_jwt&&w.device_doc_jwt&&w.ood_jwt!==w.device_doc_jwt&&l("START_CONFIG_OOD_JWT","security/start_config.json ood_jwt differs from device_doc_jwt");for(const[t,r]of[["private_key",!0],["device_private_key",!0],["sn_access_token",!0],["bns_evm_private_key",!0]])r&&t in m&&l("START_CONFIG_SECRET",`security/start_config.json must not contain ${t}`)}const b=(e,t)=>{try{return String(c.readFileSync(e,"utf8"))}catch(O){return l("FILE_UNREADABLE",`${t} cannot be read: ${O instanceof Error?O.message:String(O)}`),null}},S=(null==(o=b(t.zoneDocumentJwtPath,"etc/zone_document.jwt"))?void 0:o.trim())??null,A=(null==(s=b(t.deviceDocJwtPath,Wh(e,t.deviceDocJwtPath)))?void 0:s.trim())??null,E=(null==(a=b(t.deviceMiniDocJwtPath,Wh(e,t.deviceMiniDocJwtPath)))?void 0:a.trim())??null;S&&w.zone_document_jwt&&S!==w.zone_document_jwt&&l("ZONE_DOCUMENT_MISMATCH","etc/zone_document.jwt differs from start_config zone_document_jwt"),A&&w.device_doc_jwt&&A!==w.device_doc_jwt&&l("DEVICE_DOCUMENT_MISMATCH","device_doc.jwt differs from start_config device_doc_jwt"),E&&w.device_mini_doc_jwt&&E!==w.device_mini_doc_jwt&&l("DEVICE_MINI_DOCUMENT_MISMATCH","device_mini_doc.jwt differs from start_config device_mini_doc_jwt");const k=async(e,t)=>{if(!e)return null;try{return await i.verifyJwtEdDSA(e,f)}catch(O){return l("JWT_SIGNATURE",`${t} is not signed by the owner key: ${O instanceof Error?O.message:String(O)}`),null}},x=await k(w.boot_config_jwt??null,"boot_config_jwt"),_=await k(A??w.device_doc_jwt??null,"device_doc.jwt"),N=await k(E??w.device_mini_doc_jwt??null,"device_mini_doc.jwt"),I=await k(S??w.zone_document_jwt??null,"zone_document.jwt"),T=i.buckyosGetUnixTimestamp();if(x){x.id!==p.toString()&&l("BOOT_DOCUMENT","boot document id differs from zone DID"),Array.isArray(x.oods)&&0!==x.oods.length||l("BOOT_DOCUMENT","boot document has no oods"),"sn"in x&&l("BOOT_DOCUMENT","boot document must not reference an SN in offline mode"),("number"!=typeof x.exp||x.exp<=T)&&l("BOOT_DOCUMENT","boot document has expired");try{const r=Qh(t.zoneBootOverridePath);JSON.stringify(r)!==JSON.stringify(x)&&l("BOOT_OVERRIDE_MISMATCH",`${Wh(e,t.zoneBootOverridePath)} differs from boot_config_jwt`)}catch(O){l("BOOT_OVERRIDE_UNREADABLE",`local boot override cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}}let B=null;if(_){_.id!==h.toString()&&l("DEVICE_DOCUMENT","device document id differs from node_identity device_did"),_.owner!==d&&l("DEVICE_DOCUMENT","device document owner differs from owner DID"),_.zone_did!==p.toString()&&l("DEVICE_DOCUMENT","device document zone_did differs from zone DID"),("number"!=typeof _.exp||_.exp<=T)&&l("DEVICE_DOCUMENT","device document has expired");const r=Array.isArray(_.verificationMethod)?_.verificationMethod.find((e=>e&&"#main_key"===e.id)):void 0;B=r?wd(r.publicKeyJwk):null,B||l("DEVICE_DOCUMENT","device document has no #main_key");try{Qh(t.didJsonPath).id!==h.toString()&&l("DEVICE_DID_JSON",`${Wh(e,t.didJsonPath)} id differs from node_identity device_did`)}catch(O){l("DEVICE_DID_JSON",`device did.json cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}}if(N&&B&&N.x!==B&&l("DEVICE_MINI_DOCUMENT","device mini document key differs from device document key"),I&&(I.id!==p.toString()&&l("ZONE_DOCUMENT","zone document id differs from zone DID"),I.owner!==d&&l("ZONE_DOCUMENT","zone document owner differs from owner DID"),w.boot_config_jwt&&I.boot_jwt!==w.boot_config_jwt&&l("ZONE_DOCUMENT","zone document boot_jwt differs from start_config boot_config_jwt"),"sn"in I&&l("ZONE_DOCUMENT","zone document must not reference an SN in offline mode")),B){try{const e=String(c.readFileSync(t.devicePrivateKeyPath,"utf8"));await i.getPublicKeyXFromPrivatePem(e)!==B&&l("DEVICE_PRIVATE_KEY","device private key does not match the device document key")}catch(O){l("DEVICE_PRIVATE_KEY",`device private key cannot be loaded: ${O instanceof Error?O.message:String(O)}`)}if(!zh()){const e=Gh(t.devicePrivateKeyPath);e&&63&e.mode&&l("DEVICE_PRIVATE_KEY_MODE","device private key is readable by other users")}}return{ownerDid:d,accessHostname:v}}(n,A,h,s);return N.ownerDid=I.ownerDid??N.ownerDid,N.accessHostname=I.accessHostname??(d?d.toRawHostName():null),p&&"committed"!==p.stage&&s.push({code:"ACTIVATION_INTERRUPTED",message:`activation lock is still at stage ${p.stage??"unknown"}; the commit did not finish cleanly`}),N.state=0===s.length?"configured":"invalid",N.startupRequired="configured"===N.state,N}async function Sd(e){return Ad(e)}async function Ad(e,t=!1){const r=ld(e),i=await bd(r.rootDir,t),n=[],o=function(e){if(e.lock)return{code:"ACTIVATION_IN_PROGRESS",message:`activation lock exists: ${e.lock.path} (stage=${e.lock.stage??"unknown"})`};switch(e.state){case"unactivated":return null;case"not_installed":return{code:"TARGET_NOT_INSTALLED",message:`BuckyOS is not installed at ${e.rootDir}`};case"configured":return{code:"TARGET_ALREADY_ACTIVATED",message:`BuckyOS is already activated at ${e.rootDir}`};case"invalid":return{code:"TARGET_ALREADY_ACTIVATED",message:`BuckyOS activation material exists but is invalid at ${e.rootDir}; it is not overwritten`};case"partial":return{code:"TARGET_PARTIALLY_ACTIVATED",message:`BuckyOS is partially activated at ${e.rootDir}; remove the partial material or reinstall`}}}(i);o&&n.push(o);const s=function(e,t){const r=Fh("node:path").dirname(e),i=Yh(r),n=null!==Gh(e);return i||t.push({code:"OWNER_KEY_BACKUP_DIRECTORY_MISSING",message:`owner key backup directory does not exist: ${r}`}),n&&t.push({code:"OWNER_KEY_BACKUP_EXISTS",message:`owner key backup already exists: ${e}`}),{path:e,directoryExists:i,exists:n}}(r.ownerKeyBackupPath,n),a=hd(r.rootDir,r.zoneDid,r.deviceDid);return{ready:0===n.length,rootDir:r.rootDir,state:i.state,domain:r.domain,ownerName:r.ownerName,ownerDid:r.ownerDid.toString(),zoneDid:r.zoneDid.toString(),deviceDid:r.deviceDid.toString(),deviceName:Uh,accessHostname:r.domain,rtcpPort:r.rtcpPort,guestAccess:r.guestAccess,publicIp:r.publicIp??null,dnsRecords:cd(r.domain,r.publicIp),ownerKeyBackup:s,plannedFiles:dd(r.rootDir,a).map(fd),problems:n,status:i}}function Ed(e){const t=e.problems[0];return new Kh(1===e.problems.length?t.code:"ACTIVATION_PRECHECK_FAILED",1===e.problems.length?t.message:`activation precheck failed: ${e.problems.map((e=>e.message)).join("; ")}`,{state:e.state,problems:e.problems})}async function kd(e,t,r,n){const o=i.buckyosGetUnixTimestamp(),s=o+Mh,a=i.createJwkByX(r.publicKeyX),c=i.createJwkByX(n.publicKeyX),u=e.ownerDid.toString(),l=e.zoneDid.toString(),p=e.deviceDid.toString(),h=i.newOwnerDocument({did:e.ownerDid,name:e.ownerName,displayName:e.ownerName,publicKeyJwk:a,now:o});h.exp=s,i.ownerDocumentSetDefaultZoneDid(h,e.zoneDid);const f=i.ownerDocumentToOrderedJson(h),y=i.oodDescriptionToString(i.parseOODDescription(`${Uh}@${$h}`)),g=await i.encodeZoneBootDocument(i.newZoneBootDocument({id:e.zoneDid,oods:[y],exp:s}),r.privateKeyPem),m=i.decodeJwtClaimWithoutVerify(g),w=v(Uh,c,e.deviceDid,o);!function(e){var t;const r=Fh("node:fs"),i=Fh("node:path").join(e,"etc","product.json");return!r.existsSync(i)||!1!==(null==(t=JSON.parse(r.readFileSync(i,"utf8")).capabilities)?void 0:t.container)}(e.rootDir)?w.support_container=!1:delete w.support_container,w.owner=u,w.zone_did=l,w.net_id=$h,w.rtcp_port=e.rtcpPort,w.iat=o,w.exp=s,w.version_seq=0;const b=i.deviceDocumentToOrderedJson(w),S=await i.encodeDeviceDocument(w,r.privateKeyPem),A=i.newDeviceMiniDocumentByDeviceDocument(w);A.iat=o;const E=await i.deviceMiniDocumentToJwt(A,r.privateKeyPem),k=i.newZoneDocument({id:e.zoneDid,ownerDid:e.ownerDid,publicKeyJwk:a,now:o});k.hostname=e.domain,k.owner=u,k.oods=[y],k.boot_jwt=g,k.devices={[Uh]:b},k.mini_device_jwts={[Uh]:E},k.iat=o,k.exp=s,k.version_seq=0,delete k.sn;const x=await i.encodeZoneDocument(k,r.privateKeyPem);if((new TextEncoder).encode(x).length>=4096)throw new Kh("ZONE_DOCUMENT_TOO_LARGE","zone document JWT exceeds the 4096 byte inline limit");return{documentIat:o,documentExp:s,ownerDocument:f,bootDocument:m,bootJwt:g,deviceDocument:b,deviceDocJwt:S,deviceMiniDocJwt:E,zoneDocumentJwt:x,nodeIdentity:d({zoneDid:e.zoneDid,ownerDid:e.ownerDid,ownerPublicKey:a,deviceName:Uh,deviceDid:e.deviceDid,zoneIat:o}),startConfig:{user_name:e.ownerName,owner_document:f,zone_name:l,access_hostname:e.domain,zone_document_jwt:x,boot_config_jwt:g,device_doc_jwt:S,device_mini_doc_jwt:E,ood_jwt:S,admin_password_hash:ad(e.ownerName,t),guest_access:e.guestAccess,friend_passcode:"",enabled_features:{},ai_provider_config:{},owner_telegram_account_id:""},gatewayParams:{params:{device_did:p,rtcp_port:String(e.rtcpPort)}},dnsRecords:cd(e.domain,e.publicIp)}}function xd(e,t,r,i){switch(e.role){case"device_private_key":return r.privateKeyPem;case"device_document":return ed(t.deviceDocument);case"device_document_jwt":return t.deviceDocJwt;case"device_mini_document_jwt":return t.deviceMiniDocJwt;case"zone_boot_override":return ed(t.bootDocument);case"zone_document_jwt":return t.zoneDocumentJwt;case"dns_records":return ed({hostname:i,records:t.dnsRecords});case"start_config":return ed(t.startConfig);case"gateway_params":return ed(t.gatewayParams);case"node_identity":return ed(t.nodeIdentity)}}function _d(e,t,r){return["inspect the target with: buckyos provision status --root <root>",r.length>0?`the following files were committed and are left in place: ${r.join(", ")}`:"no activation file was committed to the target root",`the owner private key backup was saved at ${t}; keep it or delete it before retrying (the backup path must not exist)`,`remove the committed files and the lock file ${e} (or reinstall BuckyOS), then run provision check again`,"the generated identity is not deleted or regenerated automatically"]}const Nd=1743478939,Id=2058838939;function Td(e){const t=e.split(".");return[Number(t[0])||0,Number(t[1])||0]}function Bd(){var e,t,r,i;const n=globalThis,o=null==(t=null==(e=n.Deno)?void 0:e.version)?void 0:t.deno;if(o){const[e,t]=Td(o);if(e>2||2===e&&t>=2)return;throw new Error(`buckyos provision requires Deno >= 2.2 (node:sqlite), current: ${o}`)}const s=null==(i=null==(r=n.process)?void 0:r.versions)?void 0:i.node;if(s){const[e,t]=Td(s);if(e>22||22===e&&t>=13)return;throw new Error(`buckyos provision requires Node >= 22.13 (node:sqlite), current: ${s}`)}throw new Error("buckyos provision requires a Node >= 22.13 or Deno >= 2.2 runtime (browser is not supported)")}function Od(e){Bd();const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Error(`buckyos provision cannot load builtin module ${e} in this runtime`)}function Cd(e,t){const r=Od("node:fs"),i=Od("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,t),console.log(`# Write file: ${e}`)}function Dd(e,t){Cd(e,JSON.stringify(t,null,2))}function jd(e){const t=Od("node:fs");return JSON.parse(t.readFileSync(e,"utf8"))}function Pd(e){if(Array.isArray(e))return e.map(Pd);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=Pd(e[r]);return t}return e}function Rd(e,t){return t||(Dh[e]?Dh[e]:Dh[`${e}.owner`]?Dh[`${e}.owner`]:(console.log(`Warning: Key pair for user ${e} not found, using devtest key pair`),Rh("devtest")))}function Ud(e,t,r){return r||Rh(`${e}.${t}`)}function $d(e){const t=Od("node:path");return new Gp(t.join(e,"local","identity"),t.join(e,"security"))}class Md{constructor(e){Bd(),this.dbPath=e}connect(){const{DatabaseSync:e}=Od("node:sqlite");return new e(this.dbPath)}initializeDatabase(){const e=this.connect();try{e.exec("CREATE TABLE IF NOT EXISTS activation_codes (code TEXT PRIMARY KEY, used INTEGER);\n CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, state TEXT, public_key TEXT, activation_code TEXT, zone_config TEXT, self_cert boolean, user_domain TEXT, sn_ips TEXT);\n CREATE TABLE IF NOT EXISTS user_auth_v2 (username TEXT PRIMARY KEY, password_hash TEXT NOT NULL, password_salt TEXT NOT NULL, password_algo TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, last_login_at INTEGER NULL);\n CREATE TABLE IF NOT EXISTS devices (owner TEXT, device_name TEXT, did TEXT PRIMARY KEY, ip TEXT, description TEXT, mini_config_jwt TEXT, created_at INTEGER, updated_at INTEGER);\n CREATE TABLE IF NOT EXISTS user_dns_records (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT, domain TEXT, record_type TEXT, record TEXT, ttl INTEGER, created_at INTEGER, updated_at INTEGER);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_user_domain_record_type ON user_dns_records (owner, domain, record_type);\n CREATE INDEX IF NOT EXISTS user_dns_records_domain_index ON user_dns_records (domain, id);\n CREATE TABLE IF NOT EXISTS user_domain_history (domain TEXT PRIMARY KEY, owner TEXT NOT NULL, created_at INTEGER NOT NULL);\n CREATE TABLE IF NOT EXISTS did_documents (id INTEGER PRIMARY KEY AUTOINCREMENT, obj_id TEXT, owner_user TEXT, obj_name TEXT, did_document TEXT, doc_type TEXT, update_time INTEGER);\n CREATE INDEX IF NOT EXISTS idx_did_documents_owner_obj ON did_documents (owner_user, obj_name, update_time);")}finally{e.close()}}insertActivationCode(e){const t=this.connect();try{t.prepare("INSERT INTO activation_codes (code, used) VALUES (?, 0)").run(e)}finally{t.close()}}registerUserDirectly(e,t,r,i){const n=this.connect();try{n.prepare("INSERT INTO users (username, state, public_key, activation_code, zone_config, user_domain, self_cert, sn_ips) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,"active",t,"DIRECT",r,i??null,1,null)}finally{n.close()}}registerDevice(e,t,r,n,o,s){const a=i.buckyosGetUnixTimestamp(),c=this.connect();try{c.prepare("INSERT INTO devices (owner, device_name, did, ip, description, mini_config_jwt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,t,r,o,s,n,a,a)}finally{c.close()}}}function Ld(){var e;const t=(null==(e=globalThis.process)?void 0:e.arch)??"";return"x64"===t?"amd64":"arm64"===t?"aarch64":t}function Vd(){var e;const t=(null==(e=globalThis.process)?void 0:e.platform)??"";return"darwin"===t?"apple":"win32"===t?"windows":t}function Hd(e){const t=e.search(/[-+]/),r=(t>=0?e.slice(0,t):e).split(".");if(r.length<1||r.length>4)throw new Error(`invalid version format: ${e}`);3===r.length&&t>=0&&r.push(e.slice(t));const i=e=>{if(void 0===e)return 0n;const t=e.replace(/^[^0-9]*/,"").match(/^\d+/);return t?BigInt(t[0]):0n},n=e=>void 0===e?0n:/^\d+$/.test(e)?BigInt(e):0n,o=i(r[0]);if(o>0xffn)throw new Error(`major version out of range: ${e}`);const s=n(r[1]);if(s>0xffffn)throw new Error(`minor version out of range: ${e}`);const a=n(r[2]);if(a>0xffffn)throw new Error(`patch version out of range: ${e}`);const c=i(r[3]);if(c>0xffffffn)throw new Error(`build number out of range: ${e}`);return o<<56n|s<<40n|a<<24n|c}class Kd{constructor(e){Bd(),this.dbPath=e}connect(){const{DatabaseSync:e}=Od("node:sqlite");return new e(this.dbPath)}initializeDatabase(){const e=this.connect();try{e.exec("CREATE TABLE IF NOT EXISTS pkg_metas (\n metaobjid TEXT PRIMARY KEY,\n pkg_meta TEXT NOT NULL,\n author TEXT NOT NULL,\n author_pk TEXT NOT NULL,\n update_time INTEGER NOT NULL\n )"),e.exec("CREATE TABLE IF NOT EXISTS pkg_versions (\n pkg_name TEXT NOT NULL,\n author TEXT ,\n version TEXT NOT NULL,\n version_int INTEGER NOT NULL,\n metaobjid TEXT NOT NULL,\n tag TEXT,\n update_time INTEGER NOT NULL,\n PRIMARY KEY (pkg_name, version)\n )"),e.exec("CREATE TABLE IF NOT EXISTS author_info (\n author_name TEXT PRIMARY KEY,\n author_owner_config TEXT,\n author_zone_config TEXT\n )"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_versions_pkgname ON pkg_versions (pkg_name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_metas_author ON pkg_metas (author)"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_versions_version_int ON pkg_versions (pkg_name, version_int)")}finally{e.close()}}addPkgMetaBatch(e){const t=this.connect();try{const n=i.buckyosGetUnixTimestamp();t.exec("BEGIN");try{for(const[r,i]of Object.entries(e)){t.prepare("INSERT OR REPLACE INTO pkg_metas (metaobjid, pkg_meta, author, author_pk, update_time) VALUES (?, ?, ?, ?, ?)").run(r,i.metaJwt,i.author,i.authorPk,n);const e=Hd(i.version);t.prepare("SELECT 1 FROM pkg_versions WHERE pkg_name = ? AND author = ? AND version = ?").get(i.pkgName,i.author,i.version)?t.prepare("UPDATE pkg_versions SET metaobjid = ?, tag = ?, update_time = ? WHERE pkg_name = ? AND author = ? AND version = ?").run(r,i.tag??null,n,i.pkgName,i.author,i.version):t.prepare("INSERT INTO pkg_versions (pkg_name, author, version, version_int, metaobjid, tag, update_time) VALUES (?, ?, ?, ?, ?, ?, ?)").run(i.pkgName,i.author,i.version,e,r,i.tag??null,n)}t.exec("COMMIT")}catch(r){throw t.exec("ROLLBACK"),r}}finally{t.close()}}}const Fd=[{uniqueId:"verify-hub",showName:"Verify Hub",description:"Verify Hub",selectorType:"random"},{uniqueId:"scheduler",showName:"Scheduler",description:"Scheduler",selectorType:"single"},{uniqueId:"smb-service",showName:"Samba Service",description:"Samba Service",selectorType:"random"},{uniqueId:"msg-center",showName:"Message Center",description:"Message Center",selectorType:"single"},{uniqueId:"opendan",showName:"OpenDAN Runtime",description:"OpenDAN Runtime",selectorType:"single"},{uniqueId:"workflow",showName:"Workflow Service",description:"Workflow Service",selectorType:"single"}],zd="0.7.0";function Wd(e){const t=e.split("_");return 2===t.length?i.DID.fromStr(`did:bns:${t[1]}.${t[0]}`):i.DID.fromStr(`did:bns:${e}`)}exports.NODE_IDENTITY_SCHEMA_V2=i.NODE_IDENTITY_SCHEMA_V2,exports.calcPkgMetaObjId=i.calcPkgMetaObjId,exports.normalizePackageMetaForObjId=i.normalizePackageMetaForObjId,exports.ACTIVATION_DEFAULT_RTCP_PORT=2980,exports.ACTIVATION_DEVICE_NAME=Uh,exports.ACTIVATION_DOCUMENT_VALIDITY_SECONDS=Mh,exports.ACTIVATION_LOCK_FILE_NAME=Lh,exports.ACTIVATION_MIN_PASSWORD_LENGTH=8,exports.ACTIVATION_NET_ID=$h,exports.ActivationError=Kh,exports.DEVICE_DOC_JWT_FILE_NAME=a,exports.DEVICE_MINI_DOC_JWT_FILE_NAME=c,exports.DEV_TEST_EVM_ACCOUNTS=jh,exports.DEV_TEST_EVM_SEED_SENDER=Ph,exports.DEV_TEST_EVM_SEED_SENDER_INDEX=0,exports.DEV_TEST_EVM_USER_INDEXES=Ch,exports.DEV_TEST_KEYS=Dh,exports.DEV_TEST_KEY_INDEXES=Oh,exports.DEV_TEST_MNEMONIC=sh,exports.DevSnDb=Md,exports.IDENTITY_MATERIALS=Rp,exports.IDENTITY_USAGES=Pp,exports.IdentityRoots=Gp,exports.KERNEL_SERVICE_DOC_VERSION=zd,exports.MetaIndexDb=Kd,exports.NODE_GATEWAY_PARAMS_FILE_NAME=u,exports.PROVISION_BASE_TIME=Nd,exports.PROVISION_DEFAULT_EXP=Id,exports.ZONE_DNS_RECORDS_FILE_NAME=Vh,exports.ZONE_DOCUMENT_JWT_FILE_NAME=Hh,exports.activateOfflineZone=async function(e){const t=Fh("node:fs"),r=ld(e),n=sd(e.adminPassword),o=await Sd(e);if(!o.ready)throw Ed(o);const s=e.ownerKeyPair??ud(),a=e.deviceKeyPair??ud(),c=await kd(r,n,s,a),u=hd(r.rootDir,r.zoneDid,r.deviceDid),l=dd(r.rootDir,u),p=[],h={schema_version:1,trace_id:e.traceId??null,started_at:i.buckyosGetUnixTimestamp(),domain:r.domain,owner_key_backup:r.ownerKeyBackupPath,stage:"locked",committed:[]};!function(e,t){const r=Fh("node:fs");try{r.writeFileSync(e,ed(t),{mode:384,flag:"wx"})}catch(i){if("EEXIST"===i.code)throw new Kh("ACTIVATION_IN_PROGRESS",`another activation holds the lock ${e}; inspect it with provision status`,{lock_file:e,lock:yd(e)});throw i}}(u.lockPath,h);const d=()=>{try{t.rmSync(u.lockPath,{force:!0})}catch{}};let f;try{f=await Ad(e,!0)}catch(v){throw d(),v}if(!f.ready)throw d(),Ed(f);const y=vd(u.gatewayParamsPath);for(const i of l)if(Gh(i.absolutePath)){if("gateway_params"===i.role&&void 0!==y)continue;throw d(),new Kh("TARGET_PARTIALLY_ACTIVATED",`activation file already exists: ${i.path}`,{state:"partial",problems:[{code:"FILE_EXISTS",message:`${i.path} already exists`}]})}try{!function(e,t){const r=Fh("node:fs");r.writeFileSync(e,t,{mode:384,flag:"wx"}),zh()||r.chmodSync(e,384)}(r.ownerKeyBackupPath,s.privateKeyPem)}catch(v){d();const e=v.code;throw new Kh("EEXIST"===e?"OWNER_KEY_BACKUP_EXISTS":"OWNER_KEY_BACKUP_FAILED",`owner key backup could not be saved: ${v instanceof Error?v.message:String(v)}`,{owner_key_backup:{path:r.ownerKeyBackupPath,saved:!1},committed_files:[]})}h.stage="backup_saved";const g=[],m=(e,t)=>{throw new Kh("ACTIVATION_COMMIT_FAILED",`activation commit failed at ${t}: ${e instanceof Error?e.message:String(e)}`,{stage:t,owner_key_backup:{path:r.ownerKeyBackupPath,saved:!0},committed_files:g,lock_file:u.lockPath,recovery:_d(u.lockPath,r.ownerKeyBackupPath,g.map((e=>e.path)))})};try{gd(u.lockPath,h)}catch(v){m(v,"lock:backup_saved")}h.stage="committing";for(const i of l){const e=xd(i,c,a,r.domain);try{td(i.absolutePath,e,i.mode,i.dirMode,"gateway_params"===i.role?y:void 0)}catch(v){m(v,i.path)}g.push({...fd(i),sha256:i.secret?null:Jh(e)}),h.committed=g.map((e=>e.path));try{gd(u.lockPath,h)}catch(v){m(v,`lock:${i.path}`)}}h.stage="committed";try{gd(u.lockPath,h),t.rmSync(u.lockPath,{force:!0})}catch(v){p.push(`activation completed but the lock ${u.lockPath} could not be removed: ${v instanceof Error?v.message:String(v)}`)}return{rootDir:r.rootDir,state:"configured",startupRequired:!0,domain:r.domain,ownerName:r.ownerName,ownerDid:r.ownerDid.toString(),zoneDid:r.zoneDid.toString(),deviceDid:r.deviceDid.toString(),deviceName:Uh,accessHostname:r.domain,rtcpPort:r.rtcpPort,guestAccess:r.guestAccess,publicIp:r.publicIp??null,documentIat:c.documentIat,documentExp:c.documentExp,ownerKeyBackup:{path:r.ownerKeyBackupPath,saved:!0},dnsRecords:c.dnsRecords,committedFiles:g,warnings:p}},exports.assertProvisionRuntime=Bd,exports.bindDeviceDocumentDid=m,exports.buildActivationDnsRecords=cd,exports.buildDeviceDid=g,exports.buildDidDocs=function(e,t){Bd();const r=Od("node:path"),n=(null==t?void 0:t.version)??zd,o=(null==t?void 0:t.now)??i.buckyosGetUnixTimestamp(),s=[];for(const i of Fd){const t=Wd(i.uniqueId),a=Pd({name:i.uniqueId,show_name:i.showName,version:n,author:"did:bns:buckyos",owner:"did:bns:buckyos",create_time:o,last_update_time:o,description:{detail:{en:i.description}},categories:["service"],selector_type:i.selectorType,install_config_tips:{data_mount_point:[],local_cache_mount_point:[],rdb_instances:{},service_ports:{}},pkg_list:{}}),c=r.join(e,`${t.toRawHostName()}.doc.json`);Dd(c,a),s.push(c)}return s},exports.checkOfflineActivation=Sd,exports.createCa=Qp,exports.createCertFromCa=async function(e,t,r,i){const n=Op("node:fs"),o=Op("node:path"),s=i&&i.length>0?i:[t],a=s[0].replace(/\*/g,"wildcard").replace(/\./g,"_");n.mkdirSync(r,{recursive:!0});const c=o.join(r,`${a}.crt`),u=o.join(r,`${a}.key`),l=await eh(e,s);return n.writeFileSync(u,l.privateKeyPem),n.writeFileSync(c,l.certPem),console.log(`Certificate created: ${c}`),{certPath:c,keyPath:u}},exports.createIdentityCertFromCa=async function(e,t,r,i={}){const n=Op("node:fs"),o=function(e){return e instanceof Gp?e:Gp.fromEnvOrBuckyosRoot(e)}(r),s=i.usage??"server",a=Hp(t),c=a.toRawHostUri(),u=Vp(c),l=o.publicDir(a.toString()),p=o.securityDir(a.toString()),h=qp(l,p,s),d=i.hostnames&&i.hostnames.length>0?i.hostnames:[ih(a)],f=i.uriSans??[a.toString()];n.mkdirSync(l,{recursive:!0,mode:493}),n.mkdirSync(p,{recursive:!0,mode:448});const y=await eh(e,d,f,s),g=th(y.certPem),m=th(y.caCertPem),v=m,w=`${g}${v}`;var b,S,A;return rh(h.privateKey,y.privateKeyPem,384),rh(h.cert,g,420),rh(h.chain,v,420),rh(h.fullchain,w,420),rh(h.ca,m,420),b=h.metadata,S=await oh(a,s,c,u,y),A=420,rh(b,`${JSON.stringify(S,null,2)}\n`,A),console.log(`Identity certificate created: ${h.fullchain}`),{did:a.toString(),rawHostUri:c,dirName:u,paths:h,certPath:h.cert,chainPath:h.chain,fullchainPath:h.fullchain,caPath:h.ca,keyPath:h.privateKey,metadataPath:h.metadata}},exports.createNodeConfigs=async function(e){Bd();const t=Od("node:path"),r=e.envDir,n=jd(t.join(r,"user_config.json")).name;if("string"!=typeof n||!n)throw new Error("user_config.json missing name field");const o=jd(t.join(r,"zone_config.json")),s=i.DID.fromStr(o.id),a=Rd(n,e.ownerKeyPair),c=Ud(n,e.deviceName,e.deviceKeyPair),u=t.join(r,e.deviceName),l=new i.DID("bns",n),p=g(e.deviceName,s),h=v(e.deviceName,i.createJwkByX(c.publicKeyX),p,e.now);h.support_container=!0,delete h.support_container,void 0!==e.netId&&(h.net_id=e.netId),h.owner=l.toString(),h.zone_did=s.toString(),console.log(`input net_id: ${e.netId}, device_config.net_id: ${h.net_id}`);const f=await i.encodeDeviceDocument(h,a.privateKeyPem);console.log(`${e.deviceName} device jwt: ${f}`);const y=i.newDeviceMiniDocumentByDeviceDocument(h),m=await i.deviceMiniDocumentToJwt(y,a.privateKeyPem);Cd(t.join(u,"device_mini_config.jwt"),m);const w=d({zoneDid:s,ownerDid:l,ownerPublicKey:i.createJwkByX(a.publicKeyX),deviceName:e.deviceName,deviceDid:p,zoneIat:Nd});if(S(u,$d(u),w,h,f,m,c.privateKeyPem),e.deviceName.startsWith("ood")){const e=Pd({admin_password_hash:ad(n,"bucky2025"),device_private_key:c.privateKeyPem,device_public_key:i.createJwkByX(c.publicKeyX),ood_jwt:f,friend_passcode:"sdfsdfsdf",gateway_type:"PortForward",guest_access:!0,private_key:a.privateKeyPem,public_key:i.createJwkByX(a.publicKeyX),user_name:n,zone_name:s.toHostName(),BUCKYOS_ROOT:"/opt/buckyos"});Dd(t.join(u,"start_config.json"),e)}return console.log(`Successfully created node configuration: ${n}.${e.deviceName}`),i.encodeDeviceDocument(h,c.privateKeyPem)},exports.createSnConfigs=async function(e){Bd();const t=Od("node:path"),r=t.join(e.outputDir,"sn_server"),n=Rh("sn_owner"),o=Rh("sn_server"),s=Id;Cd(t.join(r,".buckycli","user_private_key.pem"),n.privateKeyPem);const a=i.newOwnerDocument({did:new i.DID("bns","sn"),name:"root",displayName:"sn admin",publicKeyJwk:i.createJwkByX(n.publicKeyX)});Dd(t.join(r,".buckycli","user_config.json"),i.ownerDocumentToOrderedJson(a)),console.log("- Created owner config for sn admin.");const c=i.newDeviceMiniDocument({name:"sn",x:o.publicKeyX,exp:s}),u=await i.deviceMiniDocumentToJwt(c,n.privateKeyPem),l=i.newDeviceDocumentByMiniDocument(u,c,"did:web:sn.devtests.org","did:bns:sn");l.net_id="wan",Dd(t.join(r,"sn_device_config.json"),i.deviceDocumentToOrderedJson(l)),Cd(t.join(r,"sn_private_key.pem"),o.privateKeyPem),console.log("- Created sn device config & private key.");const p=i.newZoneBootDocument({oods:["sn"],exp:s}),h=Pd({params:{sn_boot_jwt:await i.encodeZoneBootDocument(p,n.privateKeyPem),sn_owner_pk:n.publicKeyX,sn_device_jwt:u,sn_host:e.snBaseHost,sn_ip:e.snIp,sn_cer:"fullchain.cert",sn_pem:"fullchain.pem",web3_cer:"fullchain.cert",web3_pem:"fullchain.pem"}});Dd(t.join(r,"params.json"),h),console.log("- Created params.json.");const d=new Md(t.join(r,"sn_db.sqlite3"));d.initializeDatabase();for(let i=0;i<9;i++){const e=`sndevtest${i}`;console.log(`insert activation code: ${e}`),d.insertActivationCode(e)}console.log("- Created SN database."),console.log("Successfully created SN configuration")},exports.createUserEnv=async function(e){Bd();const t=Od("node:path"),r=e.rtcpPort??2980,n=e.outputDir,o=Id,s=Rd(e.username,e.ownerKeyPair),a=new i.DID("bns",e.username);let c,u=new i.DID("web",e.hostname);if(e.snBaseHost&&e.snBaseHost.includes(".")){const t=`web3.${e.snBaseHost}`;u=i.DID.fromHostNameByBridge(e.hostname,"bns",t),c=`sn.${e.snBaseHost}`}Cd(t.join(n,"user_private_key.pem"),s.privateKeyPem);const l=i.createJwkByX(s.publicKeyX),p=i.newOwnerDocument({did:a,name:e.username,displayName:e.username,publicKeyJwk:l});Dd(t.join(n,"user_config.json"),i.ownerDocumentToOrderedJson(p)),console.log(`Created owner config for ${e.username}`);const h=i.parseOODDescription(e.oodName),d=Ud(e.username,h.name,e.deviceKeyPair);let f,y=c;h.netId&&(h.netId.startsWith("wan")&&(y=void 0),h.netId.startsWith("wan_dyn")&&c&&(f=`https://${c}/kapi/sn`));const m=i.oodDescriptionToString(h),w=i.newZoneBootDocument({oods:[m],sn:y,exp:o}),b=u.toRawHostName();Dd(t.join(n,`${b}.zone.json`),w),w.id=u.toString();const S=i.newZoneDocument({id:u,ownerDid:a,publicKeyJwk:l}),A=await i.encodeZoneBootDocument(w,s.privateKeyPem);S.boot_jwt=A,S.id=w.id,S.oods=[...w.oods],void 0!==w.sn?S.sn=w.sn:delete S.sn,S.exp=w.exp,S.iat=w.exp-i.DEFAULT_EXPIRE_TIME,S.version_seq=0,S.owner=w.owner??i.DID.undefined().toString(),void 0!==w.owner_key&&(S.verificationMethod[0].publicKeyJwk=w.owner_key),Dd(t.join(n,"zone_config.json"),i.zoneDocumentToOrderedJson(S));const E=s.publicKeyX;console.log(`=> ${b} TXT Record(${A.length+6}): BOOT=${A};`),console.log(`=> ${b} TXT Record(${E.length+5}): PKX=${E};`);const k=2980===r?void 0:r,x=i.newDeviceMiniDocument({name:h.name,x:d.publicKeyX,rtcpPort:k,exp:o}),_=await i.deviceMiniDocumentToJwt(x,s.privateKeyPem);console.log(`=> ${b} TXT Record(${_.length+5}): DEV=${_};`);const N=g(h.name,u),I=v(h.name,i.createJwkByX(d.publicKeyX),N);I.support_container=!0,void 0!==h.netId&&(I.net_id=h.netId),I.owner=a.toString(),I.zone_did=u.toString(),void 0!==f&&(I.ddns_sn_url=f),console.log(`${h.name} device config: ${JSON.stringify(i.deviceDocumentToOrderedJson(I),null,2)}`);const T={boot_config_jwt:A,device_mini_doc_jwt:_,pkx:E};return Dd(t.join(n,"zone_txt_record.json"),T),console.log(`Successfully created user environment configuration: ${e.username}`),T},exports.decodeDeviceDocumentWithoutVerify=A,exports.deriveDevTestEvmAccount=Bh,exports.deriveDevTestEvmAccountFromMnemonic=Th,exports.deriveDevTestKeyPair=wh,exports.deriveDevTestKeyPairFromMnemonic=vh,exports.devTestKeccak256=Nh,exports.deviceIdentityPathsForRoots=y,exports.didWebDocumentUrl=zp,exports.encodeIdentityDirName=Vp,exports.ensureCa=async function(e,t="devtest"){const r=Op("node:fs"),i=Op("node:path"),n=i.join(e,`${t}_ca_cert.pem`),o=i.join(e,`${t}_ca_key.pem`);if(r.existsSync(n)&&r.existsSync(o)){const i=function(e){try{return Zp(new Tp(e))}catch(t){return t instanceof Error?`cannot parse CA certificate: ${t.message}`:"cannot parse CA certificate"}}(r.readFileSync(n,"utf8"));return i?(console.log(`Existing CA at ${n} is invalid (${i}); regenerating`),Qp(e,t)):(console.log(`Use existing CA at: ${n}`),{caCertPath:n,caKeyPath:o})}return Qp(e,t)},exports.generateProvisionKeyPair=ud,exports.getDevTestEvmAccountByIndex=function(e){return Bh(e)},exports.getDevTestEvmAccountByUsername=function(e){const t=jh[e];if(!t)throw new Error(`no deterministic EVM account for seed user ${e}; register it in DEV_TEST_EVM_USER_INDEXES`);return t},exports.getDevTestKeyPairById=Rh,exports.getDevTestKeyPairByIndex=function(e){return wh(e)},exports.hashAdminPassword=ad,exports.identityDirName=Fp,exports.identityFileName=Wp,exports.identityRawHostUri=Kp,exports.inspectActivationRoot=async function(e){return bd(e)},exports.loadDeviceDocJwtForRoots=w,exports.loadDeviceMiniDocJwtForRoots=function(e,t){return l("node:fs").readFileSync(y(e,t).deviceMiniDocJwt,"utf8")},exports.loadLocalDeviceDocumentForRoots=async function(e,t,r){const n=w(e,t.device_did),o=r?await i.verifyJwtEdDSA(n,t.owner_public_key):A(n);if(o.id!==t.device_did)throw new Error(`device_doc.jwt id ${o.id} does not match node_identity device_did ${t.device_did}`);return[n,o]},exports.loadLocalNodeIdentityConfig=f,exports.newDeviceDocumentByJwkWithDid=v,exports.newLocalNodeIdentityConfig=d,exports.nodeTestIdentityRoots=$d,exports.registerDeviceToSn=async function(e,t,r,n){Bd();const o=Od("node:path"),s=Od("node:fs"),a=Od("node:os"),c=o.join(e,t,r),u=o.join(c,"node_identity.json");if(!s.existsSync(u))throw new Error(`Device config not found: ${u}`);const l=f(u),p=i.DID.fromStr(l.owner_did).id,h=y($d(c),l.device_did),d=s.readFileSync(h.deviceDocJwt,"utf8"),g=s.readFileSync(h.deviceMiniDocJwt,"utf8"),m=await i.verifyJwtEdDSA(d,l.owner_public_key),v=m.id;let w;try{w=i.parseOODDescription(r)}catch{w={name:r,nodeType:"Device"}}try{const n=jd(o.join(e,t,"zone_config.json")).oods.map(i.parseOODDescription).find((e=>e.name===r));n&&(w=n)}catch{}const b=function(){const e=[],t=Od("node:os").networkInterfaces();for(const r of Object.values(t))for(const t of r??[])t.internal||"IPv6"===t.family&&t.address.startsWith("fe80")||e.includes(t.address)||e.push(t.address);return e}(),S={...m};w.ip&&(S.ips=[w.ip]),void 0!==w.netId&&(S.net_id=w.netId);const A={...S,arch:Ld(),os:Vd(),update_time:i.buckyosGetUnixTimestamp(),state:"Ready",sys_hostname:a.hostname(),base_os_info:`${a.type()} ${a.release()}`,all_ip:b,cpu_num:a.cpus().length,total_mem:a.totalmem(),mem_usage:a.totalmem()-a.freemem()};let E="127.0.0.1";b.length>0&&(E=b[0]),w.ip&&(E=w.ip),new Md(n).registerDevice(p,r,v,g,E,JSON.stringify(A,null,2)),console.log(`Successfully registered device ${p}.${r} (DID: ${v}) to SN database at ${n}`)},exports.registerUserToSn=async function(e,t,r){Bd();const n=Od("node:path"),o=jd(n.join(e,t,"user_config.json")).name;if("string"!=typeof o||!o)throw new Error("user_config.json missing name field");const s=jd(n.join(e,t,"zone_config.json")),a=i.DID.fromStr(s.id);let c;"bns"!==a.method&&(c=a.toHostName());const u=jd(n.join(e,t,"zone_txt_record.json")),l=new Md(r),p=JSON.stringify(Pd({kty:"OKP",crv:"Ed25519",x:u.pkx}));l.registerUserDirectly(o,p,u.boot_config_jwt,c),console.log(`Successfully registered user ${o}@${t} to SN database at ${r}`)},exports.saveLocalDeviceIdentityForRoots=S,exports.saveNodeGatewayParams=b,exports.setPkgMeta=async function(e,t){Bd();const r=Od("node:fs");if(!r.existsSync(e))throw new Error(`meta_path ${e} does not exist`);if(!r.existsSync(t))throw new Error(`db_path ${t} does not exist`);const n=r.readFileSync(e,"utf8"),o=n.trimStart().startsWith("{")?JSON.parse(n):i.decodeJwtClaimWithoutVerify(n.trim()),s=i.calcPkgMetaObjId(o),a=new Kd(t);return a.initializeDatabase(),a.addPkgMetaBatch({[s]:{metaJwt:n,pkgName:o.name,version:o.version,tag:o.version_tag??void 0,author:o.author,authorPk:""}}),s},exports.uniqueNameToDid=Wd,exports.validateAdminPassword=sd,exports.validateOwnerName=id,exports.validatePublicIp=od,exports.validateRtcpPort=nd,exports.validateZoneDomain=rd,exports.versionToInt=Hd;
|
|
91
|
+
const hu="crypto.algorithm";const du="crypto.algorithmProvider";var fu;lc.registerSingleton(du,class{getAlgorithms(){return lc.resolveAll(hu)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new zn({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const yu="1.3.36.3.3.2.8.1.1",gu=`${yu}.1`,mu=`${yu}.2`,vu=`${yu}.3`,wu=`${yu}.4`,bu=`${yu}.5`,Su=`${yu}.6`,Au=`${yu}.7`,Eu=`${yu}.8`,ku=`${yu}.9`,xu=`${yu}.10`,_u=`${yu}.11`,Nu=`${yu}.12`,Iu=`${yu}.13`,Tu=`${yu}.14`,Bu="brainpoolP160r1",Ou="brainpoolP160t1",Cu="brainpoolP192r1",Du="brainpoolP192t1",ju="brainpoolP224r1",Pu="brainpoolP224t1",Ru="brainpoolP256r1",Uu="brainpoolP256t1",$u="brainpoolP320r1",Mu="brainpoolP320t1",Lu="brainpoolP384r1",Vu="brainpoolP384t1",Hu="brainpoolP512r1",Ku="brainpoolP512t1",Fu="ECDSA";let zu=fu=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Fu.toLowerCase())if("hash"in e){switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return qs;case"sha-256":return Gs;case"sha-384":return Xs;case"sha-512":return Ys}}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Fs;break;case"K-256":t=fu.SECP256K1;break;case"P-384":t=zs;break;case"P-521":t=Ws;break;case Bu:t=gu;break;case Ou:t=mu;break;case Cu:t=vu;break;case Du:t=wu;break;case ju:t=bu;break;case Pu:t=Su;break;case Ru:t=Au;break;case Uu:t=Eu;break;case $u:t=ku;break;case Mu:t=xu;break;case Lu:t=_u;break;case Vu:t=Nu;break;case Hu:t=Iu;break;case Ku:t=Tu}if(t)return new zn({algorithm:$s,parameters:Fr.serialize(new ia({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ms:return{name:Fu,hash:{name:"SHA-1"}};case Vs:return{name:Fu,hash:{name:"SHA-256"}};case Hs:return{name:Fu,hash:{name:"SHA-384"}};case Ks:return{name:Fu,hash:{name:"SHA-512"}};case $s:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Fr.parse(e.parameters,ia).namedCurve){case Fs:return{name:Fu,namedCurve:"P-256"};case fu.SECP256K1:return{name:Fu,namedCurve:"K-256"};case zs:return{name:Fu,namedCurve:"P-384"};case Ws:return{name:Fu,namedCurve:"P-521"};case gu:return{name:Fu,namedCurve:Bu};case mu:return{name:Fu,namedCurve:Ou};case vu:return{name:Fu,namedCurve:Cu};case wu:return{name:Fu,namedCurve:Du};case bu:return{name:Fu,namedCurve:ju};case Su:return{name:Fu,namedCurve:Pu};case Au:return{name:Fu,namedCurve:Ru};case Eu:return{name:Fu,namedCurve:Uu};case ku:return{name:Fu,namedCurve:$u};case xu:return{name:Fu,namedCurve:Mu};case _u:return{name:Fu,namedCurve:Lu};case Nu:return{name:Fu,namedCurve:Vu};case Iu:return{name:Fu,namedCurve:Hu};case Tu:return{name:Fu,namedCurve:Ku}}}return null}};zu.SECP256K1="1.3.132.0.10",zu=fu=zr([pc()],zu),lc.registerSingleton(hu,zu);const Wu=Symbol("name"),Ju=Symbol("value");class qu{constructor(e,t={},r=""){this[Wu]=e,this[Ju]=r;for(const i in t)this[i]=t[i]}}qu.NAME=Wu,qu.VALUE=Ju;class Gu{static toString(e){const t=this.items[e];return t||e}}Gu.items={[ba]:"sha1",[Sa]:"sha224",[Aa]:"sha256",[Ea]:"sha384",[ka]:"sha512",[aa]:"rsaEncryption",[da]:"sha1WithRSAEncryption",[fa]:"sha224WithRSAEncryption",[ya]:"sha256WithRSAEncryption",[ga]:"sha384WithRSAEncryption",[ma]:"sha512WithRSAEncryption",[$s]:"ecPublicKey",[Ms]:"ecdsaWithSHA1",[Ls]:"ecdsaWithSHA224",[Vs]:"ecdsaWithSHA256",[Hs]:"ecdsaWithSHA384",[Ks]:"ecdsaWithSHA512",[an]:"TLS WWW server authentication",[cn]:"TLS WWW client authentication",[un]:"Code Signing",[ln]:"E-mail Protection",[pn]:"Time Stamping",[hn]:"OCSP Signing",[js]:"Signed Data"};class Xu{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let i=this.pad(t++),n="";const o=e[qu.VALUE];o&&(n=` ${o}`),r.push(`${i}${e[qu.NAME]}:${n}`),i=this.pad(t);for(const s in e){if("symbol"==typeof s)continue;const n=e[s],o=s?`${s}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${i}${o}${n}`);else if(n instanceof Date)r.push(`${i}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[qu.NAME]=s,r.push(...this.serializeObj(e,t));else if(n instanceof qu)n[qu.NAME]=s,r.push(...this.serializeObj(n,t));else if(x.isBufferSource(n))s?(r.push(`${i}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[qu.NAME]=s,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),i=x.toUint8Array(e),n=[];for(let o=0;o<i.length;){const e=[];for(let t=0;t<16&&o<i.length;t++){8===t&&e.push("");const r=i[o++].toString(16).padStart(2,"0");e.push(r)}n.push(`${r}${e.join(" ")}`)}return n}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}var Yu,Zu;Xu.oidSerializer=Gu,Xu.algorithmSerializer=class{static toTextObject(e){const t=new qu("Algorithm Identifier",{},Gu.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case $s:{const r=(new zu).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Qu{get rawData(){return Wr(this,Yu,"f")||Jr(this,Yu,Fr.serialize(this.asn),"f"),Wr(this,Yu,"f")}constructor(...e){Yu.set(this,void 0),x.isBufferSource(e[0])?(this.asn=Fr.parse(e[0],e[1]),Jr(this,Yu,x.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Qu&&function(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),i=new Uint8Array(t);for(let n=0;n<e.byteLength;n++)if(r[n]!==i[n])return!1;return!0}(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Fr.toString(this.rawData);case"text":return Xu.serialize(this.toTextObject());case"hex":return C.ToHex(this.rawData);case"base64":return C.ToBase64(this.rawData);case"base64url":return C.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new qu(this.getTextName(),{},e)}}Yu=new WeakMap,Qu.NAME="ASN";class el extends Qu{constructor(...e){let t;t=x.isBufferSource(e[0])?x.toArrayBuffer(e[0]):Fr.serialize(new Xn({extnID:e[0],critical:e[1],extnValue:new ar(x.toArrayBuffer(e[2]))})),super(t,Xn)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[qu.NAME]===el.NAME&&(e[qu.NAME]=Gu.toString(this.type)),e}}class tl{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[Zu]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(tl.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(tl.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=tl.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(tl.DEFAULT,e);return this}}Zu=Symbol.toStringTag,tl.DEFAULT="default";const rl=new tl,il=/^[0-2](?:\.[1-9][0-9]*)+$/;class nl{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(il).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const ol=new nl;function sl(e,t){return`\\${C.ToHex(C.FromUtf8String(t)).toUpperCase()}`}ol.register("CN","2.5.4.3"),ol.register("L","2.5.4.7"),ol.register("ST","2.5.4.8"),ol.register("O","2.5.4.10"),ol.register("OU","2.5.4.11"),ol.register("C","2.5.4.6"),ol.register("DC","0.9.2342.19200300.100.1.25"),ol.register("E","1.2.840.113549.1.9.1"),ol.register("G","2.5.4.42"),ol.register("I","2.5.4.43"),ol.register("SN","2.5.4.4"),ol.register("T","2.5.4.12");class al{static isASCII(e){for(let t=0;t<e.length;t++){if(e.charCodeAt(t)>255)return!1}return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new nl,this.asn=new oi;for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const e=t[r];this.extraNames.register(r,e)}"string"==typeof e?this.asn=this.fromString(e):e instanceof oi?this.asn=e:x.isBufferSource(e)?this.asn=Fr.parse(e,oi):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||ol.findId(e),r=[];for(const i of this.asn)for(const e of i)e.type===t&&r.push(e.value.toString());return r}getName(e){return this.extraNames.get(e)||ol.get(e)}toString(){return this.asn.map((e=>e.map((e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${C.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,sl)}`)).join("+"))).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const i={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=i[r])&&void 0!==e||(i[r]=[]),i[r].push(t.value.anyValue?`#${C.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(i)}return t}fromString(e){const t=new oi,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,n=",";for(;i=r.exec(`${e},`);){let[,e,r]=i;const o=r[r.length-1];","!==o&&"+"!==o||(r=r.slice(0,r.length-1),i[3]=o);const s=i[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===n?t[t.length-1].push(a):t.push(new ii([a])),n=s}return t}fromJSON(e){const t=new oi;for(const r of e){const e=new ii;for(const t in r){const i=this.getTypeOid(t),n=r[t];for(const t of n){const r=this.createAttribute(i,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new ri({type:e});if("object"==typeof t)for(const i in t)switch(i){case"ia5String":r.value.ia5String=t[i];break;case"utf8String":r.value.utf8String=t[i];break;case"universalString":r.value.universalString=t[i];break;case"bmpString":r.value.bmpString=t[i];break;case"printableString":r.value.printableString=t[i]}else if("#"===t[0])r.value.anyValue=C.FromHex(t.slice(1));else{const i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:al.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Fr.serialize(this.asn)}async getThumbprint(...e){var t;let r,i="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(i=e[0]||i,r=e[1]||rl.get()):r=e[0]||rl.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const cl="Cannot initialize GeneralName from ASN.1 data.",ul=`${cl} Unsupported string format in use.`,ll=`${cl} Value doesn't match to GUID regular expression.`,pl=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,hl="1.3.6.1.4.1.311.25.1",dl="1.3.6.1.4.1.311.20.2.3",fl="dns",yl="dn",gl="email",ml="ip",vl="url",wl="guid",bl="upn",Sl="id";class Al extends Qu{constructor(...e){let t;if(2===e.length)switch(e[0]){case yl:{const r=new al(e[1]).toArrayBuffer(),i=Fr.parse(r,oi);t=new ui({directoryName:i});break}case fl:t=new ui({dNSName:e[1]});break;case gl:t=new ui({rfc822Name:e[1]});break;case wl:{const r=new RegExp(pl,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map(((e,t)=>t<3?C.ToHex(new Uint8Array(C.FromHex(e)).reverse()):e)).join("");t=new ui({otherName:new ai({typeId:hl,value:Fr.serialize(new ar(C.FromHex(i)))})});break}case ml:t=new ui({iPAddress:e[1]});break;case Sl:t=new ui({registeredID:e[1]});break;case bl:t=new ui({otherName:new ai({typeId:dl,value:Fr.serialize(vr.toASN(e[1]))})});break;case vl:t=new ui({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=x.isBufferSource(e[0])?Fr.parse(e[0],ui):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=fl,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=gl,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=ml,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=vl,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=Sl,this.value=e.registeredID;else if(null!=e.directoryName)this.type=yl,this.value=new al(e.directoryName).toString();else{if(null==e.otherName)throw new Error(ul);if(e.otherName.typeId===hl){this.type=wl;const t=Fr.parse(e.otherName.value,ar),r=new RegExp(pl,"i").exec(C.ToHex(t));if(!r)throw new Error(ll);this.value=r.slice(1).map(((e,t)=>t<3?C.ToHex(new Uint8Array(C.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==dl)throw new Error(ul);this.type=bl,this.value=Fr.parse(e.otherName.value,ei).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case yl:case fl:case wl:case ml:case Sl:case bl:case vl:e=this.type.toUpperCase();break;case gl:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Sl&&(t=Gu.toString(t)),new qu(e,void 0,t)}}class El extends Qu{constructor(e){let t;if(e instanceof Ii)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof ui)r.push(t);else{const e=Fr.parse(new Al(t.type,t.value).rawData,ui);r.push(e)}t=new Ii(r)}else{if(!x.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Fr.parse(e,Ii)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new Al(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map((e=>e.toJSON()))}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let i=e[r[qu.NAME]];Array.isArray(i)||(i=[],e[r[qu.NAME]]=i),i.push(r)}return e}}El.NAME="GeneralNames";const kl="-{5}",xl="\\n",_l="\\n",Nl=`${`${kl}BEGIN (${`[^${xl}]+`}(?=${kl}))${kl}`}${_l}(?:((?:${`[^:${xl}]+`}: ${`(?:[^${xl}]+${_l}(?: +[^${xl}]+${_l})*)`})+))?${_l}?(${`(?:[a-zA-Z0-9=+/]+${_l})+`})${`${kl}END \\1${kl}`}`;class Il{static isPem(e){return"string"==typeof e&&new RegExp(Nl,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(Nl,"g"),r=[];let i=null;for(;i=t.exec(e);){const e=i[3].replace(new RegExp(`[${xl}]+`,"g"),""),t={type:i[1],headers:[],rawData:C.FromBase64(e)},n=i[2];if(n){const e=n.split(new RegExp(_l,"g"));let r=null;for(const i of e){const[e,n]=i.split(/:(.*)/);if(void 0===n){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:n.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map((e=>e.rawData))}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach((e=>{if(!x.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:x.toArrayBuffer(e)}))})):e.forEach((e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))})),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:x.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)i.push(`${t.key}: ${t.value}`);i.push("")}const n=C.ToBase64(e.rawData);let o,s=0;const a=Array();for(;s<n.length&&(n.length-s<64?o=n.substring(s):(o=n.substring(s,s+64),s+=64),0!==o.length)&&(a.push(o),!(o.length<64)););return i.push(...a),i.push(`-----END ${r}-----`),i.join("\n")}}Il.CertificateTag="CERTIFICATE",Il.CrlTag="CRL",Il.CertificateRequestTag="CERTIFICATE REQUEST",Il.PublicKeyTag="PUBLIC KEY",Il.PrivateKeyTag="PRIVATE KEY";class Tl extends Qu{static isAsnEncoded(e){return x.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(Il.isPem(e))return Il.decode(e)[0];if(C.isHex(e))return C.FromHex(e);if(C.isBase64(e))return C.FromBase64(e);if(C.isBase64Url(e))return C.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=x.toUint8Array(e);if(t.length>0&&48===t[0])return x.toArrayBuffer(e);const r=C.ToBinary(e);if(Il.isPem(r))return Il.decode(r)[0];if(C.isHex(r))return C.FromHex(r);if(C.isBase64(r))return C.FromBase64(r);if(C.isBase64Url(r))return C.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){Tl.isAsnEncoded(e[0])?super(Tl.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?Il.encode(this.rawData,this.tag):super.toString(e)}}class Bl extends Tl{static async create(e,t=rl.get()){if(e instanceof Bl)return e;if(tl.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new Bl(r)}if(e.publicKey)return e.publicKey;if(x.isBufferSource(e))return new Bl(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){Tl.isAsnEncoded(e)?super(e,Wn):super(e),this.tag=Il.PublicKeyTag}async export(...e){let t,r=["verify"],i={hash:"SHA-256",...this.algorithm};e.length>1?(i=e[0]||i,r=e[1]||r,t=e[2]||rl.get()):t=e[0]||rl.get();let n=this.rawData;const o=Fr.parse(this.rawData,Wn);return o.algorithm.algorithm===la&&(n=function(e,t){return e.algorithm=new zn({algorithm:aa,parameters:null}),t=Fr.serialize(e),t}(o,n)),t.subtle.importKey("spki",n,i,!0,r)}onInit(e){const t=lc.resolve(du),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case aa:{const t=Fr.parse(e.subjectPublicKey,Ua),i=x.toUint8Array(t.modulus);r.publicExponent=x.toUint8Array(t.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,i="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(i=e[0]||i,r=e[1]||rl.get()):r=e[0]||rl.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=rl.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=rl.get();const i=Fr.parse(this.rawData,Wn);return await t.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,Wn);if(e.Algorithm=Xu.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===$s)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class Ol extends el{static async create(e,t=!1,r=rl.get()){if("name"in e&&"serialNumber"in e)return new Ol(e,t);const i=await Bl.create(e,r),n=await i.getKeyIdentifier(r);return new Ol(C.ToHex(n),t)}constructor(...e){if(x.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new ki({keyIdentifier:new Ei(C.FromHex(e[0]))});super(Ai,e[1],Fr.serialize(t))}else{const t=e[0],r=t.name instanceof El?Fr.parse(t.name.rawData,Ii):t.name,i=new ki({authorityCertIssuer:r,authorityCertSerialNumber:C.FromHex(t.serialNumber)});super(Ai,e[1],Fr.serialize(i))}}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,ki);t.keyIdentifier&&(this.keyId=C.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?C.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,ki);return t.authorityCertIssuer&&(e["Authority Issuer"]=new El(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}Ol.NAME="Authority Key Identifier";class Cl extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,_i);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new _i({cA:e[0],pathLenConstraint:e[1]});super(xi,e[2],Fr.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var Dl,jl,Pl;Cl.NAME="Basic Constraints",(jl=Dl||(Dl={})).serverAuth="1.3.6.1.5.5.7.3.1",jl.clientAuth="1.3.6.1.5.5.7.3.2",jl.codeSigning="1.3.6.1.5.5.7.3.3",jl.emailProtection="1.3.6.1.5.5.7.3.4",jl.timeStamping="1.3.6.1.5.5.7.3.8",jl.ocspSigning="1.3.6.1.5.5.7.3.9";class Rl extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,sn);this.usages=t.map((e=>e))}else{const t=new sn(e[0]);super(on,e[1],Fr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>Gu.toString(e))).join(", "),e}}Rl.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Pl||(Pl={}));class Ul extends el{constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,An);this.usages=t.toNumber()}else{const t=new An(e[0]);super(vn,e[1],Fr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,An);return e[""]=t.toJSON().join(", "),e}}Ul.NAME="Key Usages";class $l extends el{static async create(e,t=!1,r=rl.get()){const i=await Bl.create(e,r),n=await i.getKeyIdentifier(r);return new $l(C.ToHex(n),t)}constructor(...e){if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,Un);this.keyId=C.ToHex(t)}else{const t="string"==typeof e[0]?C.FromHex(e[0]):e[0],r=new Un(t);super(Rn,e[1],Fr.serialize(r)),this.keyId=C.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Fr.parse(this.value,Un);return e[""]=t,e}}$l.NAME="Subject Key Identifier";class Ml extends el{constructor(...e){x.isBufferSource(e[0])?super(e[0]):super(On,e[1],new El(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Cn);this.names=new El(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}Ml.NAME="Subject Alternative Name";class Ll{static register(e,t){this.items.set(e,t)}static create(e){const t=new el(e),r=this.items.get(t.type);return r?new r(e):t}}Ll.items=new Map;class Vl extends el{constructor(...e){var t;if(x.isBufferSource(e[0])){super(e[0]);const t=Fr.parse(this.value,Mi);this.policies=t.map((e=>e.policyIdentifier))}else{const r=e[0],i=null!==(t=e[1])&&void 0!==t&&t,n=new Mi(r.map((e=>new $i({policyIdentifier:e}))));super(Ci,i,Fr.serialize(n)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new qu("",{},Gu.toString(e)))),e}}Vl.NAME="Certificate Policies",Ll.register(Ci,Vl);class Hl extends el{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map((e=>new qi({distributionPoint:new Ji({fullName:[new ui({uniformResourceIdentifier:e})]})}))),r=new Gi(t);super(Ki,e[1],Fr.serialize(r))}else{const t=new Gi(e[0]);super(Ki,e[1],Fr.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Gi);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map((e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map((e=>new Al(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}Hl.NAME="CRL Distribution Points";class Kl extends el{constructor(...e){var t,r,i,n;if(x.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Si){const t=new Si(e[0]);super(wi,e[1],Fr.serialize(t))}else{const t=e[0],r=new Si;zl(r,t,di,"ocsp"),zl(r,t,fi,"caIssuers"),zl(r,t,yi,"timeStamping"),zl(r,t,gi,"caRepository"),super(wi,e[1],Fr.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(i=this.timeStamping)&&void 0!==i||(this.timeStamping=[]),null!==(n=this.caRepository)&&void 0!==n||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[];Fr.parse(e.extnValue,Si).forEach((e=>{switch(e.accessMethod){case di:this.ocsp.push(new Al(e.accessLocation));break;case fi:this.caIssuers.push(new Al(e.accessLocation));break;case yi:this.timeStamping.push(new Al(e.accessLocation));break;case gi:this.caRepository.push(new Al(e.accessLocation))}}))}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Fl(e,"OCSP",this.ocsp),this.caIssuers.length&&Fl(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Fl(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Fl(e,"CA Repository",this.caRepository),e}}function Fl(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const i=new qu("");r.forEach(((e,t)=>{const r=e.toTextObject(),n=`${r[qu.NAME]} ${t+1}`;let o=i[n];Array.isArray(o)||(o=[],i[n]=o),o.push(r)})),e[t]=i}}function zl(e,t,r,i){const n=t[i];if(n){(Array.isArray(n)?n:[n]).forEach((t=>{"string"==typeof t&&(t=new Al("url",t)),e.push(new bi({accessMethod:r,accessLocation:Fr.parse(t.rawData,ui)}))}))}}Kl.NAME="Authority Info Access";class Wl extends el{constructor(...e){x.isBufferSource(e[0])?super(e[0]):super(gn,e[1],new El(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Fr.parse(e.extnValue,Ii);this.names=new El(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}Wl.NAME="Issuer Alternative Name";class Jl extends Qu{constructor(...e){let t;if(x.isBufferSource(e[0]))t=x.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map((e=>x.toArrayBuffer(e))):[];t=Fr.serialize(new Dn({type:r,values:i}))}super(t,Dn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new qu("",{"":e}))),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[qu.NAME]===Jl.NAME&&(e[qu.NAME]=Gu.toString(this.type)),e}}Jl.NAME="Attribute";class ql extends Jl{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else{const t=new ru({printableString:e[0]});super(Uc,[Fr.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Fr.parse(this.values[0],ru);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[qu.VALUE]=this.password,e}}ql.NAME="Challenge Password";class Gl extends Jl{constructor(...e){var t;if(x.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Yn;for(const e of t)r.push(Fr.parse(e.rawData,Xn));super($c,[Fr.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Fr.parse(this.values[0],Yn);this.items=e.map((e=>Ll.create(Fr.serialize(e))))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(const r of t)e[r[qu.NAME]]=r;return e}}Gl.NAME="Extensions";class Xl{static register(e,t){this.items.set(e,t)}static create(e){const t=new Jl(e),r=this.items.get(t.type);return r?new r(e):t}}Xl.items=new Map;const Yl="crypto.signatureFormatter";var Zl;let Ql=Zl=class{static createPssParams(e,t){const r=Zl.getHashAlgorithm(e);return r?new Oa({hashAlgorithm:r,maskGenAlgorithm:new zn({algorithm:xa,parameters:Fr.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=lc.resolve(du);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new zn({algorithm:aa,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new zn({algorithm:da,parameters:null});case"sha-256":return new zn({algorithm:ya,parameters:null});case"sha-384":return new zn({algorithm:ga,parameters:null});case"sha-512":return new zn({algorithm:ma,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=Zl.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new zn({algorithm:la,parameters:Fr.serialize(t)})}return new zn({algorithm:la,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case aa:return{name:"RSASSA-PKCS1-v1_5"};case da:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ya:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case ga:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ma:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case la:if(e.parameters){const t=Fr.parse(e.parameters,Oa);return{name:"RSA-PSS",hash:lc.resolve(du).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Ql=Zl=zr([pc()],Ql),lc.registerSingleton(hu,Ql);let ep=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new zn({algorithm:ba});case"sha-256":return new zn({algorithm:Aa});case"sha-384":return new zn({algorithm:Ea});case"sha-512":return new zn({algorithm:ka})}return null}toWebAlgorithm(e){switch(e.algorithm){case ba:return{name:"SHA-1"};case Aa:return{name:"SHA-256"};case Ea:return{name:"SHA-384"};case ka:return{name:"SHA-512"}}return null}};ep=zr([pc()],ep),lc.registerSingleton(hu,ep);class tp{addPadding(e,t){const r=x.toUint8Array(t),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,t=!1){let r=x.toUint8Array(e);for(let i=0;i<r.length;i++)if(r[i]){r=r.slice(i);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,i=tp.namedCurveSize.get(r)||tp.defaultNamedCurveSize,n=new oa,o=x.toUint8Array(t);return n.r=this.removePadding(o.slice(0,i),!0),n.s=this.removePadding(o.slice(i,i+i),!0),Fr.serialize(n)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Fr.parse(t,oa),i=e.namedCurve,n=tp.namedCurveSize.get(i)||tp.defaultNamedCurveSize;return function(...e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),r=new Uint8Array(t);let i=0;return e.map((e=>new Uint8Array(e))).forEach((e=>{for(const t of e)r[i++]=t})),r.buffer}(this.addPadding(n,this.removePadding(r.r)),this.addPadding(n,this.removePadding(r.s)))}return null}}tp.namedCurveSize=new Map,tp.defaultNamedCurveSize=32;const rp="1.3.101.110",ip="1.3.101.111",np="1.3.101.112",op="1.3.101.113";let sp=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=np;break;case"x25519":t=rp;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=np;break;case"ed448":t=op}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=rp;break;case"x448":t=ip}}return t?new zn({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case np:return{name:"Ed25519"};case op:return{name:"EdDSA",namedCurve:"Ed448"};case rp:return{name:"X25519"};case ip:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};var ap,cp,up,lp,pp,hp,dp,fp,yp,gp,mp,vp,wp,bp,Sp,Ap,Ep,kp,xp,_p,Np,Ip;sp=zr([pc()],sp),lc.registerSingleton(hu,sp);ap=new WeakMap,cp=new WeakMap,up=new WeakMap,lp=new WeakMap,pp=new WeakMap,hp=new WeakMap,dp=new WeakMap,fp=new WeakMap,class extends Tl{get subjectName(){return Wr(this,cp,"f")||Jr(this,cp,new al(this.asn.certificationRequestInfo.subject),"f"),Wr(this,cp,"f")}get subject(){return Wr(this,up,"f")||Jr(this,up,this.subjectName.toString(),"f"),Wr(this,up,"f")}get signatureAlgorithm(){if(!Wr(this,lp,"f")){const e=lc.resolve(du);Jr(this,lp,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Wr(this,lp,"f")}get signature(){return Wr(this,pp,"f")||Jr(this,pp,this.asn.signature,"f"),Wr(this,pp,"f")}get publicKey(){return Wr(this,hp,"f")||Jr(this,hp,new Bl(this.asn.certificationRequestInfo.subjectPKInfo),"f"),Wr(this,hp,"f")}get attributes(){return Wr(this,dp,"f")||Jr(this,dp,this.asn.certificationRequestInfo.attributes.map((e=>Xl.create(Fr.serialize(e)))),"f"),Wr(this,dp,"f")}get extensions(){if(!Wr(this,fp,"f")){Jr(this,fp,[],"f");const e=this.getAttribute($c);e instanceof Gl&&Jr(this,fp,e.items,"f")}return Wr(this,fp,"f")}get tbs(){return Wr(this,ap,"f")||Jr(this,ap,this.asn.certificationRequestInfoRaw||Fr.serialize(this.asn.certificationRequestInfo),"f"),Wr(this,ap,"f")}constructor(e){const t=Tl.isAsnEncoded(e)?[e,pu]:[e];super(t[0],t[1]),ap.set(this,void 0),cp.set(this,void 0),up.set(this,void 0),lp.set(this,void 0),pp.set(this,void 0),hp.set(this,void 0),dp.set(this,void 0),fp.set(this,void 0),this.tag=Il.CertificateRequestTag}onInit(e){}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t=>t.type===e))}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t=>t.type===e))}async verify(e=rl.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),i=lc.resolveAll(Yl).reverse();let n=null;for(const o of i)if(n=o.toWebSignature(t,this.signature),n)break;if(!n)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,n,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,pu),r=t.certificationRequestInfo,i=new qu("",{Version:`${Zn[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new qu("");for(const t of this.attributes){const r=t.toTextObject();e[r[qu.NAME]]=r}i.Attributes=e}return e.Data=i,e.Signature=new qu("",{Algorithm:Xu.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}.NAME="PKCS#10 Certificate Request";class Tp extends Tl{get publicKey(){return Wr(this,_p,"f")||Jr(this,_p,new Bl(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),Wr(this,_p,"f")}get serialNumber(){if(!Wr(this,gp,"f")){const e=this.asn.tbsCertificate;let t=new Uint8Array(e.serialNumber);t.length>1&&0===t[0]&&t[1]>127&&(t=t.slice(1)),Jr(this,gp,C.ToHex(t),"f")}return Wr(this,gp,"f")}get subjectName(){return Wr(this,mp,"f")||Jr(this,mp,new al(this.asn.tbsCertificate.subject),"f"),Wr(this,mp,"f")}get subject(){return Wr(this,vp,"f")||Jr(this,vp,this.subjectName.toString(),"f"),Wr(this,vp,"f")}get issuerName(){return Wr(this,wp,"f")||Jr(this,wp,new al(this.asn.tbsCertificate.issuer),"f"),Wr(this,wp,"f")}get issuer(){return Wr(this,bp,"f")||Jr(this,bp,this.issuerName.toString(),"f"),Wr(this,bp,"f")}get notBefore(){if(!Wr(this,Sp,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Jr(this,Sp,e,"f")}return Wr(this,Sp,"f")}get notAfter(){if(!Wr(this,Ap,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Jr(this,Ap,e,"f")}return Wr(this,Ap,"f")}get signatureAlgorithm(){if(!Wr(this,Ep,"f")){const e=lc.resolve(du);Jr(this,Ep,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Wr(this,Ep,"f")}get signature(){return Wr(this,kp,"f")||Jr(this,kp,this.asn.signatureValue,"f"),Wr(this,kp,"f")}get extensions(){return Wr(this,xp,"f")||(Jr(this,xp,[],"f"),this.asn.tbsCertificate.extensions&&Jr(this,xp,this.asn.tbsCertificate.extensions.map((e=>Ll.create(Fr.serialize(e)))),"f")),Wr(this,xp,"f")}get tbs(){return Wr(this,yp,"f")||Jr(this,yp,this.asn.tbsCertificateRaw||Fr.serialize(this.asn.tbsCertificate),"f"),Wr(this,yp,"f")}constructor(e){const t=Tl.isAsnEncoded(e)?[e,to]:[e];super(t[0],t[1]),yp.set(this,void 0),gp.set(this,void 0),mp.set(this,void 0),vp.set(this,void 0),wp.set(this,void 0),bp.set(this,void 0),Sp.set(this,void 0),Ap.set(this,void 0),Ep.set(this,void 0),kp.set(this,void 0),xp.set(this,void 0),_p.set(this,void 0),this.tag=Il.CertificateTag}onInit(e){}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t=>"string"==typeof e?t.type===e:t instanceof e))}async verify(e={},t=rl.get()){let r,i;const n=e.publicKey;try{if(n)if("publicKey"in n)r={...n.publicKey.algorithm,...this.signatureAlgorithm},i=await n.publicKey.export(r,["verify"],t);else if(n instanceof Bl)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"],t);else if(x.isBufferSource(n)){const e=new Bl(n);r={...e.algorithm,...this.signatureAlgorithm},i=await e.export(r,["verify"],t)}else r={...n.algorithm,...this.signatureAlgorithm},i=n;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],t)}catch{return!1}const o=lc.resolveAll(Yl).reverse();let s=null;for(const c of o)if(s=c.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,i,s,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=rl.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=rl.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Fr.parse(this.rawData,to),r=t.tbsCertificate,i=new qu("",{Version:`${Zn[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Xu.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new qu("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(i["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(i["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new qu("");for(const t of this.extensions){const r=t.toTextObject();e[r[qu.NAME]]=r}i.Extensions=e}return e.Data=i,e.Signature=new qu("",{Algorithm:Xu.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}yp=new WeakMap,gp=new WeakMap,mp=new WeakMap,vp=new WeakMap,wp=new WeakMap,bp=new WeakMap,Sp=new WeakMap,Ap=new WeakMap,Ep=new WeakMap,kp=new WeakMap,xp=new WeakMap,_p=new WeakMap,Tp.NAME="Certificate";class Bp{static async createSelfSigned(e,t=rl.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=rl.get()){var r;let i;i=e.publicKey instanceof Bl?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:x.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const n=function(e,t=rl.get()){const r=x.toUint8Array(C.FromHex(e||""));let i=r&&r.length&&r.some((e=>e>0))?new Uint8Array(r):void 0;i||(i=t.getRandomValues(new Uint8Array(16)));let n=0;for(;n<i.length-1&&0===i[n];)n++;if(i=i.slice(n),i[0]>127){const e=new Uint8Array(i.length+1);e[0]=0,e.set(i,1),i=e}return i.buffer}(e.serialNumber,t),o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),a=new to({tbsCertificate:new eo({version:Zn.v3,serialNumber:n,validity:new qn({notBefore:o,notAfter:s}),extensions:new Yn((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>Fr.parse(e.rawData,Xn))))||[]),subjectPublicKeyInfo:Fr.parse(i,Wn)})});if(e.subject){const t=e.subject instanceof al?e.subject:new al(e.subject);a.tbsCertificate.subject=Fr.parse(t.toArrayBuffer(),oi)}if(e.issuer){const t=e.issuer instanceof al?e.issuer:new al(e.issuer);a.tbsCertificate.issuer=Fr.parse(t.toArrayBuffer(),oi)}const c={hash:"SHA-256"},u="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},l=lc.resolve(du);a.tbsCertificate.signature=a.signatureAlgorithm=l.toAsnAlgorithm(u);const p=Fr.serialize(a.tbsCertificate),h="signingKey"in e?await t.subtle.sign(u,e.signingKey,p):e.signature,d=lc.resolveAll(Yl).reverse();let f=null;for(const y of d)if(f=y.toAsnSignature(u,h),f)break;if(!f)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return a.signatureValue=f,new Tp(Fr.serialize(a))}}function Op(e){const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Error(`buckyos cert cannot load builtin module ${e} in this runtime`)}function Cp(){const e=globalThis.crypto;if(null==e?void 0:e.subtle)return e;return Op("node:crypto").webcrypto}(Ip=Np||(Np={}))[Ip.unspecified=0]="unspecified",Ip[Ip.keyCompromise=1]="keyCompromise",Ip[Ip.cACompromise=2]="cACompromise",Ip[Ip.affiliationChanged=3]="affiliationChanged",Ip[Ip.superseded=4]="superseded",Ip[Ip.cessationOfOperation=5]="cessationOfOperation",Ip[Ip.certificateHold=6]="certificateHold",Ip[Ip.removeFromCRL=8]="removeFromCRL",Ip[Ip.privilegeWithdrawn=9]="privilegeWithdrawn",Ip[Ip.aACompromise=10]="aACompromise",Ll.register(xi,Cl),Ll.register(on,Rl),Ll.register(vn,Ul),Ll.register(Rn,$l),Ll.register(Ai,Ol),Ll.register(On,Ml),Ll.register(Ki,Hl),Ll.register(wi,Kl),Ll.register(gn,Wl),Xl.register(Uc,ql),Xl.register($c,Gl),lc.registerSingleton(Yl,class{toAsnSignature(e,t){return x.toArrayBuffer(t)}toWebSignature(e,t){return x.toArrayBuffer(t)}}),lc.registerSingleton(Yl,tp),tp.namedCurveSize.set("P-256",32),tp.namedCurveSize.set("K-256",32),tp.namedCurveSize.set("P-384",48),tp.namedCurveSize.set("P-521",66);const Dp={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:4096},jp={...Dp,modulusLength:2048},Pp=["server","client","authentication","assertion","key-agreement","capability"],Rp=["did-json","did-meta","cert","chain","fullchain","ca","public","csr","meta","private","keyref","verification-method"];function Up(){const e=new Uint8Array(16);return Cp().getRandomValues(e),e[0]&=127,e[0]|=1,Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function $p(e){return new Date(Date.now()+24*e*3600*1e3)}async function Mp(e){const t=new Uint8Array(await Cp().subtle.exportKey("pkcs8",e));return Il.encode(t,"PRIVATE KEY")}function Lp(e){return Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Vp(e){const t=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||46===e||95===e||45===e;let r="";for(const i of function(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=Op("node:buffer").Buffer;return new Uint8Array(t.from(e,"utf8"))}(e))t(i)?r+=String.fromCharCode(i):r+=`%${i.toString(16).toUpperCase().padStart(2,"0")}`;if(!r||"."===r||".."===r||/[\\/]/.test(r)||r.includes("\0"))throw new Error(`Invalid encoded identity directory name for raw host URI: ${e}`);return r}function Hp(e){const t=e.trim();if(!t)throw new Error("identity DID or hostname is empty");return i.DID.fromStr(function(e){return e.startsWith("did:web:*.")?`did:web:_.${e.slice(10)}`:e.startsWith("*.")?`_.${e.slice(2)}`:e}(t))}function Kp(e){return Hp(e).toRawHostUri()}function Fp(e){return Vp(Kp(e))}function zp(e){const t=Hp(e);if("web"!==t.method)return null;const r=t.toRawHostName(),i=t.getPathFromId();return i?`https://${r}/${i}/did.json`:`https://${r}/.well-known/did.json`}function Wp(e,t){switch(function(e){if(!Pp.includes(e))throw new Error(`Unsupported identity usage: ${e}`)}(e),function(e){if(!Rp.includes(e))throw new Error(`Unsupported identity material: ${e}`)}(t),t){case"did-json":return"did.json";case"did-meta":return"did.meta.json";case"cert":return`${e}.cert.pem`;case"chain":return`${e}.chain.pem`;case"fullchain":return`${e}.fullchain.pem`;case"ca":return`${e}.ca.pem`;case"public":return"server"===e||"client"===e?`${e}.public.pem`:`${e}.public.jwk`;case"csr":return`${e}.csr.pem`;case"meta":return`${e}.meta.json`;case"private":return`${e}.private.pem`;case"keyref":return`${e}.keyref.json`;case"verification-method":return`${e}.verification-method.json`}}function Jp(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function qp(e,t,r){const i=Op("node:path");return{cert:i.join(e,Wp(r,"cert")),chain:i.join(e,Wp(r,"chain")),fullchain:i.join(e,Wp(r,"fullchain")),ca:i.join(e,Wp(r,"ca")),metadata:i.join(e,Wp(r,"meta")),keyref:i.join(t,Wp(r,"keyref")),privateKey:i.join(t,Wp(r,"private"))}}class Gp{constructor(e,t){const r=Op("node:path");this.publicRoot=r.resolve(e),this.securityRoot=r.resolve(t)}static fromEnvOrBuckyosRoot(e={}){const t=Op("node:path"),r=function(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}(),i=Jp(e.buckyosRoot)??Jp(r.BUCKYOS_ROOT)??"/opt/buckyos",n=Jp(e.publicRoot)??Jp(r.BUCKYOS_IDENTITY_ROOT)??t.join(i,"local","identity"),o=Jp(e.securityRoot)??Jp(r.BUCKYOS_SECURITY_ROOT)??t.join(i,"security");return new Gp(n,o)}rawHostUri(e){return Kp(e)}dirName(e){return Fp(e)}publicDir(e){return Op("node:path").join(this.publicRoot,this.dirName(e))}securityDir(e){return Op("node:path").join(this.securityRoot,this.dirName(e))}publicFile(e,t,r){return Op("node:path").join(this.publicDir(e),Wp(t,r))}securityFile(e,t,r){return Op("node:path").join(this.securityDir(e),Wp(t,r))}x509Paths(e,t="server"){return qp(this.publicDir(e),this.securityDir(e),t)}identityDirMatch(e){const t=this.rawHostUri(e),r=Vp(t);return{type:t.startsWith("_.")?"wildcard":"exact",rawHostUri:t,dirName:r,publicDir:this.publicDir(e),securityDir:this.securityDir(e),...t.startsWith("_.")?{hostPattern:`*.${t.slice(2)}`}:{host:t}}}findX509Paths(e,t="server"){const r=Op("node:fs"),i=this.identityDirMatch(e),n=qp(i.publicDir,i.securityDir,t);if(r.existsSync(n.fullchain)||r.existsSync(n.cert))return{match:i,paths:n};const o=Hp(e);if("web"!==o.method)return null;const s=o.toRawHostName().split(".");if(s.length<3)return null;const a=`_.${s.slice(1).join(".")}`,c=Vp(a),u=Op("node:path"),l=u.join(this.publicRoot,c),p=u.join(this.securityRoot,c),h=qp(l,p,t);return r.existsSync(h.fullchain)||r.existsSync(h.cert)?{match:{type:"wildcard",rawHostUri:a,dirName:c,publicDir:l,securityDir:p,hostPattern:`*.${s.slice(1).join(".")}`},paths:h}:null}}async function Xp(e){const t=Cp();if(e.includes("BEGIN RSA PRIVATE KEY")){const r=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),r=new Uint8Array([2,1,0]),i=Yp(4,e),n=new Uint8Array(r.length+t.length+i.length);return n.set(r,0),n.set(t,r.length),n.set(i,r.length+t.length),Yp(48,n)}(new Uint8Array(Il.decode(e)[0]));return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}const r=new Uint8Array(Il.decode(e)[0]);return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}function Yp(e,t){let r;r=t.length<128?[e,t.length]:t.length<256?[e,129,t.length]:[e,130,t.length>>8,255&t.length];const i=new Uint8Array(r.length+t.length);return i.set(r,0),i.set(t,r.length),i}function Zp(e){const t=e.extensions.find((e=>e instanceof Cl));if(!(null==t?void 0:t.ca))return"missing basicConstraints CA:TRUE";const r=e.extensions.find((e=>e instanceof Ul));return!r||r.usages&Pl.keyCertSign?void 0:"keyUsage does not allow certificate signing"}async function Qp(e,t="devtest"){const r=Op("node:fs"),i=Op("node:path"),n=Cp();rl.set(n),r.mkdirSync(e,{recursive:!0});const o=i.join(e,`${t}_ca_key.pem`),s=i.join(e,`${t}_ca_cert.pem`),a=`C=US, ST=California, L=San Jose, O=${`${t}'s Dev Test Environment`}, OU=Test, CN=${t}`,c=await n.subtle.generateKey(Dp,!0,["sign","verify"]),u=await Bp.createSelfSigned({serialNumber:Up(),name:a,notBefore:new Date,notAfter:$p(3650),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},keys:c,extensions:[new Cl(!0,void 0,!0),new Ul(Pl.keyCertSign|Pl.cRLSign|Pl.digitalSignature,!0),await $l.create(c.publicKey)]});return r.writeFileSync(o,await Mp(c.privateKey)),r.writeFileSync(s,u.toString("pem")),console.log(`CA certificate created: ${s}`),{caCertPath:s,caKeyPath:o}}async function eh(e,t,r=[],i="server"){const n=Op("node:fs"),o=Cp();rl.set(o);const{caCertPath:s,caKeyPath:a}=function(e){const t=Op("node:fs"),r=Op("node:path"),i=t.readdirSync(e).filter((e=>e.endsWith("_ca_cert.pem")));if(0===i.length)throw new Error(`No CA certificate found matching *_ca_cert.pem pattern in ${e}`);if(i.length>1)throw new Error(`Multiple CA certificates found in ${e}: ${i.join(", ")}`);const n=r.join(e,i[0]),o=r.join(e,i[0].replace("_ca_cert.pem","_ca_key.pem"));if(!t.existsSync(o))throw new Error(`CA key not found: ${o}`);return{caCertPath:n,caKeyPath:o}}(e),c=n.readFileSync(s,"utf8"),u=new Tp(c),l=Zp(u);if(l)throw new Error(`Invalid CA certificate at ${s}: ${l}`);const p=await Xp(n.readFileSync(a,"utf8")),h=t[0];if(!h)throw new Error("At least one DNS SAN is required when creating an X.509 certificate");const d=await o.subtle.generateKey(jp,!0,["sign","verify"]),f=new Uint8Array(await o.subtle.exportKey("spki",d.publicKey)),y=await async function(e){const t=await Cp().subtle.digest("SHA-256",e);return`sha256:${Lp(new Uint8Array(t))}`}(f),g=[...t.map((e=>({type:"dns",value:e}))),...r.map((e=>({type:"url",value:e})))],m=await Bp.create({serialNumber:Up(),subject:`CN=${h}`,issuer:u.subjectName,notBefore:new Date,notAfter:$p(365),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},publicKey:d.publicKey,signingKey:p,extensions:[new Ul(Pl.digitalSignature|Pl.keyEncipherment,!0),new Rl(["client"===i?Dl.clientAuth:Dl.serverAuth]),new Ml(g),await $l.create(d.publicKey),await Ol.create(u)]});return{cert:m,certPem:m.toString("pem"),privateKeyPem:await Mp(d.privateKey),caCertPem:c,publicKeyFingerprint:y}}function th(e){return`${e.trimEnd()}\n`}function rh(e,t,r){const i=Op("node:fs"),n=Op("node:path"),o=n.dirname(e),s=n.join(o,`.${n.basename(e)}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{i.writeFileSync(s,t,void 0===r?void 0:{mode:r});try{const e=i.openSync(s,"r");try{i.fsyncSync(e)}finally{i.closeSync(e)}}catch{}i.renameSync(s,e)}catch(a){try{i.existsSync(s)&&i.unlinkSync(s)}catch{}throw a}}function ih(e){const t=e.toRawHostName();return t.startsWith("_.")?`*.${t.slice(2)}`:t}function nh(e){if("web"!==e.method||e.toRawHostName().startsWith("_."))return;const t=e.toString();return{type:"did-web-domain",did:t,web_origin:`https://${e.toRawHostName()}`,did_document_url:zp(t)}}async function oh(e,t,r,i,n){const o=function(e){const t=e.extensions.find((e=>e instanceof Ml)),r=(null==t?void 0:t.names.toJSON())??[];return{dns:r.filter((e=>"dns"===e.type)).map((e=>e.value)),uri:r.filter((e=>"url"===e.type)).map((e=>e.value))}}(n.cert),s=await async function(e){const t=await e.getThumbprint("SHA-256",Cp());return`sha256:${Lp(new Uint8Array(t))}`}(n.cert),a=r.startsWith("_."),c=(new Date).toISOString();return{schema:"buckyos.identity.x509.metadata.v1",did:e.toString(),raw_host_uri:r,dir_name:i,usage:t,match:a?{type:"wildcard",host_pattern:`*.${r.slice(2)}`}:{type:"exact",host:r},certificate:{serial_number:n.cert.serialNumber,issuer:n.cert.issuer,subject:n.cert.subject,not_before:n.cert.notBefore.toISOString(),not_after:n.cert.notAfter.toISOString(),fingerprint_sha256:s,public_key_fingerprint:n.publicKeyFingerprint},san:o,paths:{cert:Wp(t,"cert"),chain:Wp(t,"chain"),fullchain:Wp(t,"fullchain"),ca:Wp(t,"ca")},did_binding:nh(e),updated_at:c,generation:`${c.replace(/[-:.]/g,"")}-${s}`}}const sh="test test test test test test test test test test test junk",ah=2147483648,ch=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),uh=(1n<<64n)-1n,lh=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],ph=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];function hh(e,t=""){return o.pbkdf2Sync(n.Buffer.from(e.normalize("NFKD"),"utf8"),n.Buffer.from(`mnemonic${t}`.normalize("NFKD"),"utf8"),2048,64,"sha512")}function dh(e,t){return o.createHmac("sha512",e).update(t).digest()}function fh(e){const t=n.Buffer.alloc(4);return t.writeUInt32BE(e>>>0,0),t}function yh(e){const t=o.createPublicKey(o.createPrivateKey(e)).export({format:"jwk"});if(!t.x)throw new Error("failed to derive Ed25519 public key x");return t.x}function gh(e,t,r){const i=dh(t,n.Buffer.concat([n.Buffer.from([0]),e,fh(r+ah)]));return{key:i.subarray(0,32),chainCode:i.subarray(32)}}function mh(e,t,r){let i=function(e){const t=dh("ed25519 seed",e);return{key:t.subarray(0,32),chainCode:t.subarray(32)}}(hh(e,t));for(const n of[9777,0,r])i=gh(i.key,i.chainCode,n);return n.Buffer.from(i.key)}function vh(e,t,r){const i=function(e){return`-----BEGIN PRIVATE KEY-----\n${n.Buffer.concat([n.Buffer.from("302e020100300506032b657004220420","hex"),e]).toString("base64")}\n-----END PRIVATE KEY-----\n`}(mh(e,t??"",r));return{privateKeyPem:i,publicKeyX:yh(i)}}function wh(e){return vh(sh,void 0,e)}function bh(e){const t=e.toString(16).padStart(64,"0");return n.Buffer.from(t,"hex")}function Sh(e){return BigInt(`0x${e.toString("hex")}`)}function Ah(e,t){const r=o.createECDH("secp256k1");return r.setPrivateKey(e),r.getPublicKey(void 0,t?"compressed":"uncompressed")}function Eh(e,t,r){const i=dh(t,r>=ah?n.Buffer.concat([n.Buffer.from([0]),e,fh(r)]):n.Buffer.concat([Ah(e,!0),fh(r)])),o=Sh(i.subarray(0,32));if(o>=ch)throw new Error(`invalid secp256k1 child tweak at index ${r}`);const s=(o+Sh(e))%ch;if(0n===s)throw new Error(`invalid secp256k1 child key at index ${r}`);return{privateKey:bh(s),chainCode:i.subarray(32)}}function kh(e){return`m/44'/60'/0'/0/${e}`}function xh(e,t){if(0===t)return e&uh;const r=BigInt(t);return(e<<r|e>>64n-r)&uh}function _h(e){for(const t of lh){const r=new Array(5),i=new Array(5),n=new Array(25).fill(0n);for(let t=0;t<5;t+=1)r[t]=e[t]^e[t+5]^e[t+10]^e[t+15]^e[t+20];for(let e=0;e<5;e+=1)i[e]=r[(e+4)%5]^xh(r[(e+1)%5],1);for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)e[t+5*r]=(e[t+5*r]^i[t])&uh;for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)n[r+(2*t+3*r)%5*5]=xh(e[t+5*r],ph[t][r]);for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)e[t+5*r]=(n[t+5*r]^~n[(t+1)%5+5*r]&uh&n[(t+2)%5+5*r])&uh;e[0]=(e[0]^t)&uh}}function Nh(e){const t=136,r=new Array(25).fill(0n),i=n.Buffer.concat([e,n.Buffer.from([1]),n.Buffer.alloc((t-(e.length+1)%t)%t)]);i[i.length-1]^=128;for(let n=0;n<i.length;n+=t){for(let e=0;e<t;e+=1)r[Math.floor(e/8)]^=BigInt(i[n+e])<<BigInt(e%8*8);_h(r)}const o=n.Buffer.alloc(32);for(let n=0;n<o.length;n+=1)o[n]=Number(r[Math.floor(n/8)]>>BigInt(n%8*8)&0xffn);return o}function Ih(e){const t=e.toString("hex"),r=Nh(n.Buffer.from(t,"ascii"));let i="0x";for(let n=0;n<t.length;n+=1){const e=t[n],o=r[Math.floor(n/2)]>>4*(1-n%2)&15;i+=/[a-f]/.test(e)&&o>7?e.toUpperCase():e}return i}function Th(e,t,r){let i=function(e){const t=dh("Bitcoin seed",e),r=t.subarray(0,32),i=Sh(r);if(i<=0n||i>=ch)throw new Error("invalid secp256k1 master key");return{privateKey:n.Buffer.from(r),chainCode:t.subarray(32)}}(hh(e,t??""));for(const n of function(e){return[2147483692,2147483708,ah,0,e]}(r))i=Eh(i.privateKey,i.chainCode,n);const o=Ah(i.privateKey,!1),s=Ah(i.privateKey,!0),a=Nh(o.subarray(1)),c=i.privateKey.toString("hex");return{derivationPath:kh(r),privateKey:`0x${c}`,privateKeyHex:c,publicKeyCompressedHex:s.toString("hex"),publicKeyUncompressedHex:o.toString("hex"),address:Ih(a.subarray(12))}}function Bh(e){return Th(sh,void 0,e)}const Oh={devtest:0,alice:1,bob:2,charlie:3,dave:4,sn_owner:5,devtests:5,"devtest.ood1":100,devtest_ood1:100,"devtest.node1":101,devtest_node1:101,"alice.ood1":102,alice_ood1:102,"bob.ood1":103,bob_ood1:103,"charlie.ood1":104,charlie_ood1:104,"dave.ood1":105,dave_ood1:105,sn:106,sn_server:106,"devtests.ood1":107,devtests_ood1:107,sn_web:107},Ch={alice:1,bob:2,charlie:3,dave:4},Dh=Object.fromEntries(Object.entries(Oh).map((([e,t])=>[e,wh(t)]))),jh=Object.fromEntries(Object.entries(Ch).map((([e,t])=>[e,Bh(t)]))),Ph=Bh(0);function Rh(e){const t=Dh[e];if(!t)throw new Error(`unknown dev test key pair id: ${e}`);return t}const Uh="ood1",$h="wan",Mh=i.DEFAULT_EXPIRE_TIME,Lh="provision_activation.lock",Vh="zone_dns_records.json",Hh="zone_document.jwt";class Kh extends Error{constructor(e,t,r={}){super(t),this.name="ActivationError",this.code=e,this.details=r}}function Fh(e){const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Kh("RUNTIME_UNSUPPORTED",`buckyos provision cannot load builtin module ${e} in this runtime (Node >= 22.13 or Deno >= 2.2 is required)`)}function zh(){var e;return"win32"===(null==(e=globalThis.process)?void 0:e.platform)}function Wh(e,t){const r=Fh("node:path");return r.relative(e,t).split(r.sep).join("/")}function Jh(e){return Fh("node:crypto").createHash("sha256").update(e,"utf8").digest("hex")}function qh(){return Fh("node:crypto").randomBytes(6).toString("hex")}function Gh(e){const t=Fh("node:fs");try{return t.lstatSync(e)}catch(r){const e=r.code;if("ENOENT"===e||"ENOTDIR"===e)return null;throw r}}function Xh(e){const t=Fh("node:fs");try{return t.statSync(e)}catch(r){if("ENOENT"===r.code||"ENOTDIR"===r.code)return null;throw r}}function Yh(e){var t;return!0===(null==(t=Xh(e))?void 0:t.isDirectory())}function Zh(e){var t;return!0===(null==(t=Xh(e))?void 0:t.isFile())}function Qh(e){const t=Fh("node:fs"),r=JSON.parse(t.readFileSync(e,"utf8"));if(!r||"object"!=typeof r||Array.isArray(r))throw new Error(`${e} is not a JSON object`);return r}function ed(e){return JSON.stringify(e,null,2)}function td(e,t,r,i,n){const o=Fh("node:fs"),s=Fh("node:path"),a=s.dirname(e);o.mkdirSync(a,{recursive:!0,mode:i}),zh()||o.chmodSync(a,i);const c=()=>{if(void 0!==n){if(vd(e)!==n)throw new Error(`gateway placeholder changed during activation: ${e}`)}else if(Gh(e))throw new Error(`refusing to overwrite existing file: ${e}`)};c();const u=s.join(a,`.${s.basename(e)}.provision-${qh()}`);try{o.writeFileSync(u,t,{mode:r,flag:"wx"}),zh()||o.chmodSync(u,r),c(),o.renameSync(u,e)}finally{Gh(u)&&o.rmSync(u,{force:!0})}}function rd(e){const t=function(e){return e.trim().toLowerCase().replace(/\.$/,"")}(String(e??""));if(0===t.length||t.length>253||!t.includes(".")||t.split(".").some((e=>0===e.length||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-z0-9-]+$/.test(e))))throw new Kh("INVALID_ARGUMENT",`invalid did:web domain: ${e}`,{field:"domain"});return t}function id(e){const t=String(e??"").trim().toLowerCase();if(0===t.length||t.length>63||!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(t))throw new Kh("INVALID_ARGUMENT","owner name must be a lowercase DNS label (letters, digits, and hyphens)",{field:"owner_name"});return t}function nd(e){const t=e??2980;if(!Number.isInteger(t)||t<1||t>65535)throw new Kh("INVALID_ARGUMENT",`invalid RTCP port: ${String(e)}`,{field:"rtcp_port"});return t}function od(e){const t=(null==e?void 0:e.trim())||void 0;if(void 0===t)return;if(0===Fh("node:net").isIP(t))throw new Kh("INVALID_ARGUMENT",`invalid public IP address: ${t}`,{field:"public_ip"});return t}function sd(e){if("string"!=typeof e||e.length<8)throw new Kh("INVALID_ARGUMENT","administrator password must contain at least 8 characters",{field:"admin_password"});return e}function ad(e,t){return s.hashPassword(e,t,null)}function cd(e,t){const r=[];if(t){const i=Fh("node:net");r.push({type:6===i.isIP(t)?"AAAA":"A",name:e,value:t})}return r}function ud(){const e=Fh("node:crypto"),{privateKey:t,publicKey:r}=e.generateKeyPairSync("ed25519"),i=r.export({format:"jwk"});if("string"!=typeof i.x||0===i.x.length)throw new Kh("KEY_GENERATION_FAILED","generated Ed25519 public key has no x coordinate");return{privateKeyPem:t.export({format:"pem",type:"pkcs8"}).toString(),publicKeyX:i.x}}function ld(e){const t=Fh("node:path");if("string"!=typeof e.rootDir||0===e.rootDir.trim().length)throw new Kh("INVALID_ARGUMENT","target root is required",{field:"root"});if("string"!=typeof e.ownerKeyBackupPath||0===e.ownerKeyBackupPath.trim().length)throw new Kh("INVALID_ARGUMENT","owner key backup path is required",{field:"owner_key_backup"});const r=rd(e.domain),n=new i.DID("web",r);return{rootDir:t.resolve(e.rootDir),domain:r,ownerName:id(e.ownerName),ownerKeyBackupPath:t.resolve(e.ownerKeyBackupPath),rtcpPort:nd(e.rtcpPort),guestAccess:e.guestAccess??!1,publicIp:od(e.publicIp),ownerDid:n,zoneDid:n,deviceDid:g(Uh,n)}}function pd(e){const t=Fh("node:path");return new Gp(t.join(e,"local","identity"),t.join(e,"security"))}function hd(e,t,r){const i=Fh("node:path"),n=i.join(e,"etc"),o=y(pd(e),r);return{etcDir:n,lockPath:i.join(n,Lh),nodeIdentityPath:i.join(n,"node_identity.json"),startConfigPath:i.join(e,"security","start_config.json"),zoneDocumentJwtPath:i.join(n,Hh),gatewayParamsPath:i.join(n,"node_gateway_params.json"),dnsRecordsPath:i.join(n,Vh),zoneBootOverridePath:i.join(n,`${t.toRawHostName()}.zone.json`),didJsonPath:o.didJson,deviceDocJwtPath:o.deviceDocJwt,deviceMiniDocJwtPath:o.deviceMiniDocJwt,devicePrivateKeyPath:o.authenticationPrivateKey,publicDir:o.publicDir,securityDir:o.securityDir}}function dd(e,t){const r=(t,r,i,n)=>({path:Wh(e,t),role:r,required:i,secret:n,absolutePath:t,mode:n?384:420,dirMode:n?448:493});return[r(t.devicePrivateKeyPath,"device_private_key",!0,!0),r(t.didJsonPath,"device_document",!0,!1),r(t.deviceDocJwtPath,"device_document_jwt",!0,!1),r(t.deviceMiniDocJwtPath,"device_mini_document_jwt",!0,!1),r(t.zoneBootOverridePath,"zone_boot_override",!0,!1),r(t.zoneDocumentJwtPath,"zone_document_jwt",!0,!1),r(t.dnsRecordsPath,"dns_records",!1,!1),r(t.startConfigPath,"start_config",!0,!0),r(t.gatewayParamsPath,"gateway_params",!0,!1),r(t.nodeIdentityPath,"node_identity",!0,!1)]}function fd(e){return{path:e.path,role:e.role,required:e.required,secret:e.secret}}function yd(e){if(!Gh(e))return null;const t={path:e,schemaVersion:null,traceId:null,startedAt:null,domain:null,stage:null,committedFiles:[],ownerKeyBackupPath:null,corrupt:!1};try{const r=Qh(e),i=r.stage;return{...t,schemaVersion:"number"==typeof r.schema_version?r.schema_version:null,traceId:"string"==typeof r.trace_id?r.trace_id:null,startedAt:"number"==typeof r.started_at?r.started_at:null,domain:"string"==typeof r.domain?r.domain:null,stage:"locked"===i||"backup_saved"===i||"committing"===i||"committed"===i?i:null,committedFiles:Array.isArray(r.committed)?r.committed.filter((e=>"string"==typeof e)):[],ownerKeyBackupPath:"string"==typeof r.owner_key_backup?r.owner_key_backup:null}}catch{return{...t,corrupt:!0}}}function gd(e,t){const r=Fh("node:fs"),i=Fh("node:path"),n=i.join(i.dirname(e),`.${Lh}.${qh()}`);try{r.writeFileSync(n,ed(t),{mode:384,flag:"wx"}),r.renameSync(n,e)}finally{Gh(n)&&r.rmSync(n,{force:!0})}}function md(e){const t=Fh("node:fs");return Yh(e)?t.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name)).sort():[]}function vd(e){var t;try{if(!(null==(t=Gh(e))?void 0:t.isFile()))return;const r=Fh("node:fs").readFileSync(e,"utf8"),i=JSON.parse(r);if(!i||"object"!=typeof i||Array.isArray(i)||Object.keys(i).some((e=>"params"!==e)))return;const n=i.params;if(!n||"object"!=typeof n||Array.isArray(n)||"did:bns:unactivated.local"!==n.device_did||Object.keys(n).some((e=>"device_did"!==e&&"rtcp_port"!==e)))return;if(void 0!==n.rtcp_port&&("string"!=typeof n.rtcp_port||!/^\d+$/.test(n.rtcp_port)||Number(n.rtcp_port)<1||Number(n.rtcp_port)>65535))return;return r}catch{return}}function wd(e){try{return i.getXFromJwk(e)}catch{return null}}async function bd(e,t=!1){const r=Fh("node:path"),n=r.resolve(String(e??"")),o=i.buckyosGetUnixTimestamp(),s=[],a=[],c=e=>({rootDir:n,state:e,startupRequired:"configured"===e,observedAt:o,zoneDid:null,ownerDid:null,deviceDid:null,deviceName:null,accessHostname:null,files:[],problems:s,warnings:a,lock:null});if(!Yh(n))return s.push({code:"ROOT_MISSING",message:`BUCKYOS_ROOT does not exist: ${n}`}),c("not_installed");const u=["bin","etc"].filter((e=>!Yh(r.join(n,e))));if(u.length>0){for(const e of u)s.push({code:"INSTALL_INCOMPLETE",message:`installed BuckyOS directory is missing: ${r.join(n,e)}`});return c("not_installed")}const l=r.join(n,"etc"),p=t?null:yd(r.join(l,Lh)),h=function(e,t){if(!Zh(e))return{nodeIdentity:null,zoneDid:null,deviceDid:null};try{const r=Qh(e);if(r.schema!==i.NODE_IDENTITY_SCHEMA_V2)return t.push({code:"NODE_IDENTITY_SCHEMA",message:`etc/node_identity.json schema '${String(r.schema)}' is not ${i.NODE_IDENTITY_SCHEMA_V2}`}),{nodeIdentity:r,zoneDid:null,deviceDid:null};return{nodeIdentity:r,zoneDid:i.DID.fromStr(String(r.zone_did)),deviceDid:i.DID.fromStr(String(r.device_did))}}catch(r){return t.push({code:"NODE_IDENTITY_UNREADABLE",message:`etc/node_identity.json cannot be parsed: ${r instanceof Error?r.message:String(r)}`}),{nodeIdentity:null,zoneDid:null,deviceDid:null}}}(r.join(l,"node_identity.json"),s);let d=h.zoneDid,f=h.deviceDid;const m=md(r.join(n,"local","identity")),v=md(r.join(n,"security")),w=function(e,t){const r=Fh("node:fs");return Yh(e)?r.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isFile()&&t(e.name))).map((e=>e.name)).sort():[]}(l,(e=>e.endsWith(".zone.json")));if(!d&&w.length>0){const e=w[0].slice(0,-10);e.endsWith(".did")||(d=new i.DID("web",e))}!f&&d&&(f=g(Uh,d));const b=[...m,...v].filter((e=>!f||e!==r.basename(y(pd(n),f).publicDir))),S=[];let A=null;if(d&&f){A=hd(n,d,f);for(const e of dd(n,A))S.push({...fd(e),present:Zh(e.absolutePath)})}else{for(const[e,t,i]of[["node_identity.json","node_identity",!0],[Hh,"zone_document_jwt",!0],["node_gateway_params.json","gateway_params",!0],[Vh,"dns_records",!1]])S.push({path:`etc/${e}`,role:t,required:i,secret:!1,present:Zh(r.join(l,e))});S.push({path:"security/start_config.json",role:"start_config",required:!0,secret:!0,present:Zh(r.join(n,"security","start_config.json"))});for(const e of w)S.push({path:`etc/${e}`,role:"zone_boot_override",required:!0,secret:!1,present:!0})}const E=S.find((e=>"gateway_params"===e.role)),k=!0===(null==E?void 0:E.present)&&void 0!==vd(r.join(l,"node_gateway_params.json"));E&&k&&(E.present=!1);const x=S.filter((e=>e.present&&"dns_records"!==e.role)),_=S.filter((e=>e.required&&!e.present)),N=c("unactivated");N.files=S,N.lock=p,N.zoneDid=(null==d?void 0:d.toString())??null,N.deviceDid=(null==f?void 0:f.toString())??null,N.deviceName=h.nodeIdentity?String(h.nodeIdentity.device_name):f?Uh:null,N.ownerDid=h.nodeIdentity?String(h.nodeIdentity.owner_did):null,p&&a.push(p.corrupt?`activation lock ${p.path} exists but cannot be parsed`:`activation lock ${p.path} exists (stage=${p.stage??"unknown"}, committed=${p.committedFiles.length})`);for(const i of b)a.push(`unexpected identity directory: ${i}`);if(0===x.length&&0===b.length&&!p&&0===s.length)return N.state="unactivated",N;if(_.length>0||!A||b.length>0&&0===x.length){for(const e of _)s.push({code:"FILE_MISSING",message:`${e.path} is missing`});return N.state="partial",N}const I=await async function(e,t,r,n){var o,s,a;const c=Fh("node:fs"),u=r.nodeIdentity;if(!u||!r.zoneDid||!r.deviceDid)return{ownerDid:null,accessHostname:null};const l=(e,t)=>n.push({code:e,message:t}),p=r.zoneDid,h=r.deviceDid,d=String(u.owner_did),f=u.owner_public_key;"web"!==p.method&&l("IDENTITY_NOT_DID_WEB",`zone DID ${p.toString()} is not a did:web identity`),d!==p.toString()&&l("OWNER_ZONE_MISMATCH",`owner DID ${d} differs from zone DID ${p.toString()}`);const y=g(String(u.device_name),p).toString();if(h.toString()!==y&&l("DEVICE_DID_MISMATCH",`device DID ${h.toString()} is not ${y}`),!f||"object"!=typeof f||"string"!=typeof f.x)return l("OWNER_KEY_MISSING","etc/node_identity.json owner_public_key is not an Ed25519 JWK"),{ownerDid:d,accessHostname:null};let m=null;try{m=Qh(t.startConfigPath)}catch(O){l("START_CONFIG_UNREADABLE",`security/start_config.json cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}let v=null;const w={};if(m){for(const t of["user_name","zone_name","access_hostname","admin_password_hash"])"string"==typeof m[t]&&0!==m[t].length||l("START_CONFIG_FIELD",`security/start_config.json is missing ${t}`);for(const t of["boot_config_jwt","device_doc_jwt","device_mini_doc_jwt","zone_document_jwt","ood_jwt"])"string"==typeof m[t]&&m[t].length>0?w[t]=m[t]:l("START_CONFIG_FIELD",`security/start_config.json is missing ${t}`);m.zone_name!==p.toString()&&l("START_CONFIG_ZONE",`security/start_config.json zone_name is not ${p.toString()}`),"string"==typeof m.access_hostname&&(v=m.access_hostname,v!==p.toRawHostName()&&l("START_CONFIG_HOSTNAME",`security/start_config.json access_hostname is not ${p.toRawHostName()}`));const e=m.owner_document;if(e&&"object"==typeof e){e.id!==d&&l("START_CONFIG_OWNER",`owner_document id ${String(e.id)} is not ${d}`);const t=Array.isArray(e.verificationMethod)?e.verificationMethod.find((e=>e&&"#main_key"===e.id)):void 0;t&&wd(t.publicKeyJwk)===f.x||l("START_CONFIG_OWNER_KEY","owner_document #main_key differs from node_identity owner_public_key")}else l("START_CONFIG_OWNER","security/start_config.json is missing owner_document");w.ood_jwt&&w.device_doc_jwt&&w.ood_jwt!==w.device_doc_jwt&&l("START_CONFIG_OOD_JWT","security/start_config.json ood_jwt differs from device_doc_jwt");for(const[t,r]of[["private_key",!0],["device_private_key",!0],["sn_access_token",!0],["bns_evm_private_key",!0]])r&&t in m&&l("START_CONFIG_SECRET",`security/start_config.json must not contain ${t}`)}const b=(e,t)=>{try{return String(c.readFileSync(e,"utf8"))}catch(O){return l("FILE_UNREADABLE",`${t} cannot be read: ${O instanceof Error?O.message:String(O)}`),null}},S=(null==(o=b(t.zoneDocumentJwtPath,"etc/zone_document.jwt"))?void 0:o.trim())??null,A=(null==(s=b(t.deviceDocJwtPath,Wh(e,t.deviceDocJwtPath)))?void 0:s.trim())??null,E=(null==(a=b(t.deviceMiniDocJwtPath,Wh(e,t.deviceMiniDocJwtPath)))?void 0:a.trim())??null;S&&w.zone_document_jwt&&S!==w.zone_document_jwt&&l("ZONE_DOCUMENT_MISMATCH","etc/zone_document.jwt differs from start_config zone_document_jwt"),A&&w.device_doc_jwt&&A!==w.device_doc_jwt&&l("DEVICE_DOCUMENT_MISMATCH","device_doc.jwt differs from start_config device_doc_jwt"),E&&w.device_mini_doc_jwt&&E!==w.device_mini_doc_jwt&&l("DEVICE_MINI_DOCUMENT_MISMATCH","device_mini_doc.jwt differs from start_config device_mini_doc_jwt");const k=async(e,t)=>{if(!e)return null;try{return await i.verifyJwtEdDSA(e,f)}catch(O){return l("JWT_SIGNATURE",`${t} is not signed by the owner key: ${O instanceof Error?O.message:String(O)}`),null}},x=await k(w.boot_config_jwt??null,"boot_config_jwt"),_=await k(A??w.device_doc_jwt??null,"device_doc.jwt"),N=await k(E??w.device_mini_doc_jwt??null,"device_mini_doc.jwt"),I=await k(S??w.zone_document_jwt??null,"zone_document.jwt"),T=i.buckyosGetUnixTimestamp();if(x){x.id!==p.toString()&&l("BOOT_DOCUMENT","boot document id differs from zone DID"),Array.isArray(x.oods)&&0!==x.oods.length||l("BOOT_DOCUMENT","boot document has no oods"),"sn"in x&&l("BOOT_DOCUMENT","boot document must not reference an SN in offline mode"),("number"!=typeof x.exp||x.exp<=T)&&l("BOOT_DOCUMENT","boot document has expired");try{const r=Qh(t.zoneBootOverridePath);JSON.stringify(r)!==JSON.stringify(x)&&l("BOOT_OVERRIDE_MISMATCH",`${Wh(e,t.zoneBootOverridePath)} differs from boot_config_jwt`)}catch(O){l("BOOT_OVERRIDE_UNREADABLE",`local boot override cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}}let B=null;if(_){_.id!==h.toString()&&l("DEVICE_DOCUMENT","device document id differs from node_identity device_did"),_.owner!==d&&l("DEVICE_DOCUMENT","device document owner differs from owner DID"),_.zone_did!==p.toString()&&l("DEVICE_DOCUMENT","device document zone_did differs from zone DID"),("number"!=typeof _.exp||_.exp<=T)&&l("DEVICE_DOCUMENT","device document has expired");const r=Array.isArray(_.verificationMethod)?_.verificationMethod.find((e=>e&&"#main_key"===e.id)):void 0;B=r?wd(r.publicKeyJwk):null,B||l("DEVICE_DOCUMENT","device document has no #main_key");try{Qh(t.didJsonPath).id!==h.toString()&&l("DEVICE_DID_JSON",`${Wh(e,t.didJsonPath)} id differs from node_identity device_did`)}catch(O){l("DEVICE_DID_JSON",`device did.json cannot be parsed: ${O instanceof Error?O.message:String(O)}`)}}if(N&&B&&N.x!==B&&l("DEVICE_MINI_DOCUMENT","device mini document key differs from device document key"),I&&(I.id!==p.toString()&&l("ZONE_DOCUMENT","zone document id differs from zone DID"),I.owner!==d&&l("ZONE_DOCUMENT","zone document owner differs from owner DID"),w.boot_config_jwt&&I.boot_jwt!==w.boot_config_jwt&&l("ZONE_DOCUMENT","zone document boot_jwt differs from start_config boot_config_jwt"),"sn"in I&&l("ZONE_DOCUMENT","zone document must not reference an SN in offline mode")),B){try{const e=String(c.readFileSync(t.devicePrivateKeyPath,"utf8"));await i.getPublicKeyXFromPrivatePem(e)!==B&&l("DEVICE_PRIVATE_KEY","device private key does not match the device document key")}catch(O){l("DEVICE_PRIVATE_KEY",`device private key cannot be loaded: ${O instanceof Error?O.message:String(O)}`)}if(!zh()){const e=Gh(t.devicePrivateKeyPath);e&&63&e.mode&&l("DEVICE_PRIVATE_KEY_MODE","device private key is readable by other users")}}return{ownerDid:d,accessHostname:v}}(n,A,h,s);return N.ownerDid=I.ownerDid??N.ownerDid,N.accessHostname=I.accessHostname??(d?d.toRawHostName():null),p&&"committed"!==p.stage&&s.push({code:"ACTIVATION_INTERRUPTED",message:`activation lock is still at stage ${p.stage??"unknown"}; the commit did not finish cleanly`}),N.state=0===s.length?"configured":"invalid",N.startupRequired="configured"===N.state,N}async function Sd(e){return Ad(e)}async function Ad(e,t=!1){const r=ld(e),i=await bd(r.rootDir,t),n=[],o=function(e){if(e.lock)return{code:"ACTIVATION_IN_PROGRESS",message:`activation lock exists: ${e.lock.path} (stage=${e.lock.stage??"unknown"})`};switch(e.state){case"unactivated":return null;case"not_installed":return{code:"TARGET_NOT_INSTALLED",message:`BuckyOS is not installed at ${e.rootDir}`};case"configured":return{code:"TARGET_ALREADY_ACTIVATED",message:`BuckyOS is already activated at ${e.rootDir}`};case"invalid":return{code:"TARGET_ALREADY_ACTIVATED",message:`BuckyOS activation material exists but is invalid at ${e.rootDir}; it is not overwritten`};case"partial":return{code:"TARGET_PARTIALLY_ACTIVATED",message:`BuckyOS is partially activated at ${e.rootDir}; remove the partial material or reinstall`}}}(i);o&&n.push(o);const s=function(e,t){const r=Fh("node:path").dirname(e),i=Yh(r),n=null!==Gh(e);return i||t.push({code:"OWNER_KEY_BACKUP_DIRECTORY_MISSING",message:`owner key backup directory does not exist: ${r}`}),n&&t.push({code:"OWNER_KEY_BACKUP_EXISTS",message:`owner key backup already exists: ${e}`}),{path:e,directoryExists:i,exists:n}}(r.ownerKeyBackupPath,n),a=hd(r.rootDir,r.zoneDid,r.deviceDid);return{ready:0===n.length,rootDir:r.rootDir,state:i.state,domain:r.domain,ownerName:r.ownerName,ownerDid:r.ownerDid.toString(),zoneDid:r.zoneDid.toString(),deviceDid:r.deviceDid.toString(),deviceName:Uh,accessHostname:r.domain,rtcpPort:r.rtcpPort,guestAccess:r.guestAccess,publicIp:r.publicIp??null,dnsRecords:cd(r.domain,r.publicIp),ownerKeyBackup:s,plannedFiles:dd(r.rootDir,a).map(fd),problems:n,status:i}}function Ed(e){const t=e.problems[0];return new Kh(1===e.problems.length?t.code:"ACTIVATION_PRECHECK_FAILED",1===e.problems.length?t.message:`activation precheck failed: ${e.problems.map((e=>e.message)).join("; ")}`,{state:e.state,problems:e.problems})}async function kd(e,t,r,n){const o=i.buckyosGetUnixTimestamp(),s=o+Mh,a=i.createJwkByX(r.publicKeyX),c=i.createJwkByX(n.publicKeyX),u=e.ownerDid.toString(),l=e.zoneDid.toString(),p=e.deviceDid.toString(),h=i.newOwnerDocument({did:e.ownerDid,name:e.ownerName,displayName:e.ownerName,publicKeyJwk:a,now:o});h.exp=s,i.ownerDocumentSetDefaultZoneDid(h,e.zoneDid);const f=i.ownerDocumentToOrderedJson(h),y=i.oodDescriptionToString(i.parseOODDescription(`${Uh}@${$h}`)),g=await i.encodeZoneBootDocument(i.newZoneBootDocument({id:e.zoneDid,oods:[y],exp:s}),r.privateKeyPem),m=i.decodeJwtClaimWithoutVerify(g),w=v(Uh,c,e.deviceDid,o);!function(e){var t;const r=Fh("node:fs"),i=Fh("node:path").join(e,"etc","product.json");return!r.existsSync(i)||!1!==(null==(t=JSON.parse(r.readFileSync(i,"utf8")).capabilities)?void 0:t.container)}(e.rootDir)?w.support_container=!1:delete w.support_container,w.owner=u,w.zone_did=l,w.net_id=$h,w.rtcp_port=e.rtcpPort,w.iat=o,w.exp=s,w.version_seq=0;const b=i.deviceDocumentToOrderedJson(w),S=await i.encodeDeviceDocument(w,r.privateKeyPem),A=i.newDeviceMiniDocumentByDeviceDocument(w);A.iat=o;const E=await i.deviceMiniDocumentToJwt(A,r.privateKeyPem),k=i.newZoneDocument({id:e.zoneDid,ownerDid:e.ownerDid,publicKeyJwk:a,now:o});k.hostname=e.domain,k.owner=u,k.oods=[y],k.boot_jwt=g,k.devices={[Uh]:b},k.mini_device_jwts={[Uh]:E},k.iat=o,k.exp=s,k.version_seq=0,delete k.sn;const x=await i.encodeZoneDocument(k,r.privateKeyPem);if((new TextEncoder).encode(x).length>=4096)throw new Kh("ZONE_DOCUMENT_TOO_LARGE","zone document JWT exceeds the 4096 byte inline limit");return{documentIat:o,documentExp:s,ownerDocument:f,bootDocument:m,bootJwt:g,deviceDocument:b,deviceDocJwt:S,deviceMiniDocJwt:E,zoneDocumentJwt:x,nodeIdentity:d({zoneDid:e.zoneDid,ownerDid:e.ownerDid,ownerPublicKey:a,deviceName:Uh,deviceDid:e.deviceDid,zoneIat:o}),startConfig:{user_name:e.ownerName,owner_document:f,zone_name:l,access_hostname:e.domain,zone_document_jwt:x,boot_config_jwt:g,device_doc_jwt:S,device_mini_doc_jwt:E,ood_jwt:S,admin_password_hash:ad(e.ownerName,t),guest_access:e.guestAccess,friend_passcode:"",enabled_features:{}},gatewayParams:{params:{device_did:p,rtcp_port:String(e.rtcpPort)}},dnsRecords:cd(e.domain,e.publicIp)}}function xd(e,t,r,i){switch(e.role){case"device_private_key":return r.privateKeyPem;case"device_document":return ed(t.deviceDocument);case"device_document_jwt":return t.deviceDocJwt;case"device_mini_document_jwt":return t.deviceMiniDocJwt;case"zone_boot_override":return ed(t.bootDocument);case"zone_document_jwt":return t.zoneDocumentJwt;case"dns_records":return ed({hostname:i,records:t.dnsRecords});case"start_config":return ed(t.startConfig);case"gateway_params":return ed(t.gatewayParams);case"node_identity":return ed(t.nodeIdentity)}}function _d(e,t,r){return["inspect the target with: buckyos provision status --root <root>",r.length>0?`the following files were committed and are left in place: ${r.join(", ")}`:"no activation file was committed to the target root",`the owner private key backup was saved at ${t}; keep it or delete it before retrying (the backup path must not exist)`,`remove the committed files and the lock file ${e} (or reinstall BuckyOS), then run provision check again`,"the generated identity is not deleted or regenerated automatically"]}const Nd=1743478939,Id=2058838939;function Td(e){const t=e.split(".");return[Number(t[0])||0,Number(t[1])||0]}function Bd(){var e,t,r,i;const n=globalThis,o=null==(t=null==(e=n.Deno)?void 0:e.version)?void 0:t.deno;if(o){const[e,t]=Td(o);if(e>2||2===e&&t>=2)return;throw new Error(`buckyos provision requires Deno >= 2.2 (node:sqlite), current: ${o}`)}const s=null==(i=null==(r=n.process)?void 0:r.versions)?void 0:i.node;if(s){const[e,t]=Td(s);if(e>22||22===e&&t>=13)return;throw new Error(`buckyos provision requires Node >= 22.13 (node:sqlite), current: ${s}`)}throw new Error("buckyos provision requires a Node >= 22.13 or Deno >= 2.2 runtime (browser is not supported)")}function Od(e){Bd();const t=globalThis.process;if("function"==typeof(null==t?void 0:t.getBuiltinModule)){const r=t.getBuiltinModule(e);if(r)return r}if("function"==typeof require)return require(e);throw new Error(`buckyos provision cannot load builtin module ${e} in this runtime`)}function Cd(e,t){const r=Od("node:fs"),i=Od("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,t),console.log(`# Write file: ${e}`)}function Dd(e,t){Cd(e,JSON.stringify(t,null,2))}function jd(e){const t=Od("node:fs");return JSON.parse(t.readFileSync(e,"utf8"))}function Pd(e){if(Array.isArray(e))return e.map(Pd);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=Pd(e[r]);return t}return e}function Rd(e,t){return t||(Dh[e]?Dh[e]:Dh[`${e}.owner`]?Dh[`${e}.owner`]:(console.log(`Warning: Key pair for user ${e} not found, using devtest key pair`),Rh("devtest")))}function Ud(e,t,r){return r||Rh(`${e}.${t}`)}function $d(e){const t=Od("node:path");return new Gp(t.join(e,"local","identity"),t.join(e,"security"))}class Md{constructor(e){Bd(),this.dbPath=e}connect(){const{DatabaseSync:e}=Od("node:sqlite");return new e(this.dbPath)}initializeDatabase(){const e=this.connect();try{e.exec("CREATE TABLE IF NOT EXISTS activation_codes (code TEXT PRIMARY KEY, used INTEGER);\n CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, state TEXT, public_key TEXT, activation_code TEXT, zone_config TEXT, self_cert boolean, user_domain TEXT, sn_ips TEXT);\n CREATE TABLE IF NOT EXISTS user_auth_v2 (username TEXT PRIMARY KEY, password_hash TEXT NOT NULL, password_salt TEXT NOT NULL, password_algo TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, last_login_at INTEGER NULL);\n CREATE TABLE IF NOT EXISTS devices (owner TEXT, device_name TEXT, did TEXT PRIMARY KEY, ip TEXT, description TEXT, mini_config_jwt TEXT, created_at INTEGER, updated_at INTEGER);\n CREATE TABLE IF NOT EXISTS user_dns_records (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT, domain TEXT, record_type TEXT, record TEXT, ttl INTEGER, created_at INTEGER, updated_at INTEGER);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_user_domain_record_type ON user_dns_records (owner, domain, record_type);\n CREATE INDEX IF NOT EXISTS user_dns_records_domain_index ON user_dns_records (domain, id);\n CREATE TABLE IF NOT EXISTS user_domain_history (domain TEXT PRIMARY KEY, owner TEXT NOT NULL, created_at INTEGER NOT NULL);\n CREATE TABLE IF NOT EXISTS did_documents (id INTEGER PRIMARY KEY AUTOINCREMENT, obj_id TEXT, owner_user TEXT, obj_name TEXT, did_document TEXT, doc_type TEXT, update_time INTEGER);\n CREATE INDEX IF NOT EXISTS idx_did_documents_owner_obj ON did_documents (owner_user, obj_name, update_time);")}finally{e.close()}}insertActivationCode(e){const t=this.connect();try{t.prepare("INSERT INTO activation_codes (code, used) VALUES (?, 0)").run(e)}finally{t.close()}}registerUserDirectly(e,t,r,i){const n=this.connect();try{n.prepare("INSERT INTO users (username, state, public_key, activation_code, zone_config, user_domain, self_cert, sn_ips) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,"active",t,"DIRECT",r,i??null,1,null)}finally{n.close()}}registerDevice(e,t,r,n,o,s){const a=i.buckyosGetUnixTimestamp(),c=this.connect();try{c.prepare("INSERT INTO devices (owner, device_name, did, ip, description, mini_config_jwt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,t,r,o,s,n,a,a)}finally{c.close()}}}function Ld(){var e;const t=(null==(e=globalThis.process)?void 0:e.arch)??"";return"x64"===t?"amd64":"arm64"===t?"aarch64":t}function Vd(){var e;const t=(null==(e=globalThis.process)?void 0:e.platform)??"";return"darwin"===t?"apple":"win32"===t?"windows":t}function Hd(e){const t=e.search(/[-+]/),r=(t>=0?e.slice(0,t):e).split(".");if(r.length<1||r.length>4)throw new Error(`invalid version format: ${e}`);3===r.length&&t>=0&&r.push(e.slice(t));const i=e=>{if(void 0===e)return 0n;const t=e.replace(/^[^0-9]*/,"").match(/^\d+/);return t?BigInt(t[0]):0n},n=e=>void 0===e?0n:/^\d+$/.test(e)?BigInt(e):0n,o=i(r[0]);if(o>0xffn)throw new Error(`major version out of range: ${e}`);const s=n(r[1]);if(s>0xffffn)throw new Error(`minor version out of range: ${e}`);const a=n(r[2]);if(a>0xffffn)throw new Error(`patch version out of range: ${e}`);const c=i(r[3]);if(c>0xffffffn)throw new Error(`build number out of range: ${e}`);return o<<56n|s<<40n|a<<24n|c}class Kd{constructor(e){Bd(),this.dbPath=e}connect(){const{DatabaseSync:e}=Od("node:sqlite");return new e(this.dbPath)}initializeDatabase(){const e=this.connect();try{e.exec("CREATE TABLE IF NOT EXISTS pkg_metas (\n metaobjid TEXT PRIMARY KEY,\n pkg_meta TEXT NOT NULL,\n author TEXT NOT NULL,\n author_pk TEXT NOT NULL,\n update_time INTEGER NOT NULL\n )"),e.exec("CREATE TABLE IF NOT EXISTS pkg_versions (\n pkg_name TEXT NOT NULL,\n author TEXT ,\n version TEXT NOT NULL,\n version_int INTEGER NOT NULL,\n metaobjid TEXT NOT NULL,\n tag TEXT,\n update_time INTEGER NOT NULL,\n PRIMARY KEY (pkg_name, version)\n )"),e.exec("CREATE TABLE IF NOT EXISTS author_info (\n author_name TEXT PRIMARY KEY,\n author_owner_config TEXT,\n author_zone_config TEXT\n )"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_versions_pkgname ON pkg_versions (pkg_name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_metas_author ON pkg_metas (author)"),e.exec("CREATE INDEX IF NOT EXISTS idx_pkg_versions_version_int ON pkg_versions (pkg_name, version_int)")}finally{e.close()}}addPkgMetaBatch(e){const t=this.connect();try{const n=i.buckyosGetUnixTimestamp();t.exec("BEGIN");try{for(const[r,i]of Object.entries(e)){t.prepare("INSERT OR REPLACE INTO pkg_metas (metaobjid, pkg_meta, author, author_pk, update_time) VALUES (?, ?, ?, ?, ?)").run(r,i.metaJwt,i.author,i.authorPk,n);const e=Hd(i.version);t.prepare("SELECT 1 FROM pkg_versions WHERE pkg_name = ? AND author = ? AND version = ?").get(i.pkgName,i.author,i.version)?t.prepare("UPDATE pkg_versions SET metaobjid = ?, tag = ?, update_time = ? WHERE pkg_name = ? AND author = ? AND version = ?").run(r,i.tag??null,n,i.pkgName,i.author,i.version):t.prepare("INSERT INTO pkg_versions (pkg_name, author, version, version_int, metaobjid, tag, update_time) VALUES (?, ?, ?, ?, ?, ?, ?)").run(i.pkgName,i.author,i.version,e,r,i.tag??null,n)}t.exec("COMMIT")}catch(r){throw t.exec("ROLLBACK"),r}}finally{t.close()}}}const Fd=[{uniqueId:"verify-hub",showName:"Verify Hub",description:"Verify Hub",selectorType:"random"},{uniqueId:"scheduler",showName:"Scheduler",description:"Scheduler",selectorType:"single"},{uniqueId:"smb-service",showName:"Samba Service",description:"Samba Service",selectorType:"random"},{uniqueId:"msg-center",showName:"Message Center",description:"Message Center",selectorType:"single"},{uniqueId:"opendan",showName:"OpenDAN Runtime",description:"OpenDAN Runtime",selectorType:"single"},{uniqueId:"workflow",showName:"Workflow Service",description:"Workflow Service",selectorType:"single"}],zd="0.7.0";function Wd(e){const t=e.split("_");return 2===t.length?i.DID.fromStr(`did:bns:${t[1]}.${t[0]}`):i.DID.fromStr(`did:bns:${e}`)}exports.NODE_IDENTITY_SCHEMA_V2=i.NODE_IDENTITY_SCHEMA_V2,exports.calcPkgMetaObjId=i.calcPkgMetaObjId,exports.normalizePackageMetaForObjId=i.normalizePackageMetaForObjId,exports.ACTIVATION_DEFAULT_RTCP_PORT=2980,exports.ACTIVATION_DEVICE_NAME=Uh,exports.ACTIVATION_DOCUMENT_VALIDITY_SECONDS=Mh,exports.ACTIVATION_LOCK_FILE_NAME=Lh,exports.ACTIVATION_MIN_PASSWORD_LENGTH=8,exports.ACTIVATION_NET_ID=$h,exports.ActivationError=Kh,exports.DEVICE_DOC_JWT_FILE_NAME=a,exports.DEVICE_MINI_DOC_JWT_FILE_NAME=c,exports.DEV_TEST_EVM_ACCOUNTS=jh,exports.DEV_TEST_EVM_SEED_SENDER=Ph,exports.DEV_TEST_EVM_SEED_SENDER_INDEX=0,exports.DEV_TEST_EVM_USER_INDEXES=Ch,exports.DEV_TEST_KEYS=Dh,exports.DEV_TEST_KEY_INDEXES=Oh,exports.DEV_TEST_MNEMONIC=sh,exports.DevSnDb=Md,exports.IDENTITY_MATERIALS=Rp,exports.IDENTITY_USAGES=Pp,exports.IdentityRoots=Gp,exports.KERNEL_SERVICE_DOC_VERSION=zd,exports.MetaIndexDb=Kd,exports.NODE_GATEWAY_PARAMS_FILE_NAME=u,exports.PROVISION_BASE_TIME=Nd,exports.PROVISION_DEFAULT_EXP=Id,exports.ZONE_DNS_RECORDS_FILE_NAME=Vh,exports.ZONE_DOCUMENT_JWT_FILE_NAME=Hh,exports.activateOfflineZone=async function(e){const t=Fh("node:fs"),r=ld(e),n=sd(e.adminPassword),o=await Sd(e);if(!o.ready)throw Ed(o);const s=e.ownerKeyPair??ud(),a=e.deviceKeyPair??ud(),c=await kd(r,n,s,a),u=hd(r.rootDir,r.zoneDid,r.deviceDid),l=dd(r.rootDir,u),p=[],h={schema_version:1,trace_id:e.traceId??null,started_at:i.buckyosGetUnixTimestamp(),domain:r.domain,owner_key_backup:r.ownerKeyBackupPath,stage:"locked",committed:[]};!function(e,t){const r=Fh("node:fs");try{r.writeFileSync(e,ed(t),{mode:384,flag:"wx"})}catch(i){if("EEXIST"===i.code)throw new Kh("ACTIVATION_IN_PROGRESS",`another activation holds the lock ${e}; inspect it with provision status`,{lock_file:e,lock:yd(e)});throw i}}(u.lockPath,h);const d=()=>{try{t.rmSync(u.lockPath,{force:!0})}catch{}};let f;try{f=await Ad(e,!0)}catch(v){throw d(),v}if(!f.ready)throw d(),Ed(f);const y=vd(u.gatewayParamsPath);for(const i of l)if(Gh(i.absolutePath)){if("gateway_params"===i.role&&void 0!==y)continue;throw d(),new Kh("TARGET_PARTIALLY_ACTIVATED",`activation file already exists: ${i.path}`,{state:"partial",problems:[{code:"FILE_EXISTS",message:`${i.path} already exists`}]})}try{!function(e,t){const r=Fh("node:fs");r.writeFileSync(e,t,{mode:384,flag:"wx"}),zh()||r.chmodSync(e,384)}(r.ownerKeyBackupPath,s.privateKeyPem)}catch(v){d();const e=v.code;throw new Kh("EEXIST"===e?"OWNER_KEY_BACKUP_EXISTS":"OWNER_KEY_BACKUP_FAILED",`owner key backup could not be saved: ${v instanceof Error?v.message:String(v)}`,{owner_key_backup:{path:r.ownerKeyBackupPath,saved:!1},committed_files:[]})}h.stage="backup_saved";const g=[],m=(e,t)=>{throw new Kh("ACTIVATION_COMMIT_FAILED",`activation commit failed at ${t}: ${e instanceof Error?e.message:String(e)}`,{stage:t,owner_key_backup:{path:r.ownerKeyBackupPath,saved:!0},committed_files:g,lock_file:u.lockPath,recovery:_d(u.lockPath,r.ownerKeyBackupPath,g.map((e=>e.path)))})};try{gd(u.lockPath,h)}catch(v){m(v,"lock:backup_saved")}h.stage="committing";for(const i of l){const e=xd(i,c,a,r.domain);try{td(i.absolutePath,e,i.mode,i.dirMode,"gateway_params"===i.role?y:void 0)}catch(v){m(v,i.path)}g.push({...fd(i),sha256:i.secret?null:Jh(e)}),h.committed=g.map((e=>e.path));try{gd(u.lockPath,h)}catch(v){m(v,`lock:${i.path}`)}}h.stage="committed";try{gd(u.lockPath,h),t.rmSync(u.lockPath,{force:!0})}catch(v){p.push(`activation completed but the lock ${u.lockPath} could not be removed: ${v instanceof Error?v.message:String(v)}`)}return{rootDir:r.rootDir,state:"configured",startupRequired:!0,domain:r.domain,ownerName:r.ownerName,ownerDid:r.ownerDid.toString(),zoneDid:r.zoneDid.toString(),deviceDid:r.deviceDid.toString(),deviceName:Uh,accessHostname:r.domain,rtcpPort:r.rtcpPort,guestAccess:r.guestAccess,publicIp:r.publicIp??null,documentIat:c.documentIat,documentExp:c.documentExp,ownerKeyBackup:{path:r.ownerKeyBackupPath,saved:!0},dnsRecords:c.dnsRecords,committedFiles:g,warnings:p}},exports.assertProvisionRuntime=Bd,exports.bindDeviceDocumentDid=m,exports.buildActivationDnsRecords=cd,exports.buildDeviceDid=g,exports.buildDidDocs=function(e,t){Bd();const r=Od("node:path"),n=(null==t?void 0:t.version)??zd,o=(null==t?void 0:t.now)??i.buckyosGetUnixTimestamp(),s=[];for(const i of Fd){const t=Wd(i.uniqueId),a=Pd({name:i.uniqueId,show_name:i.showName,version:n,author:"did:bns:buckyos",owner:"did:bns:buckyos",create_time:o,last_update_time:o,description:{detail:{en:i.description}},categories:["service"],selector_type:i.selectorType,install_config_tips:{data_mount_point:[],local_cache_mount_point:[],rdb_instances:{},service_ports:{}},pkg_list:{}}),c=r.join(e,`${t.toRawHostName()}.doc.json`);Dd(c,a),s.push(c)}return s},exports.checkOfflineActivation=Sd,exports.createCa=Qp,exports.createCertFromCa=async function(e,t,r,i){const n=Op("node:fs"),o=Op("node:path"),s=i&&i.length>0?i:[t],a=s[0].replace(/\*/g,"wildcard").replace(/\./g,"_");n.mkdirSync(r,{recursive:!0});const c=o.join(r,`${a}.crt`),u=o.join(r,`${a}.key`),l=await eh(e,s);return n.writeFileSync(u,l.privateKeyPem),n.writeFileSync(c,l.certPem),console.log(`Certificate created: ${c}`),{certPath:c,keyPath:u}},exports.createIdentityCertFromCa=async function(e,t,r,i={}){const n=Op("node:fs"),o=function(e){return e instanceof Gp?e:Gp.fromEnvOrBuckyosRoot(e)}(r),s=i.usage??"server",a=Hp(t),c=a.toRawHostUri(),u=Vp(c),l=o.publicDir(a.toString()),p=o.securityDir(a.toString()),h=qp(l,p,s),d=i.hostnames&&i.hostnames.length>0?i.hostnames:[ih(a)],f=i.uriSans??[a.toString()];n.mkdirSync(l,{recursive:!0,mode:493}),n.mkdirSync(p,{recursive:!0,mode:448});const y=await eh(e,d,f,s),g=th(y.certPem),m=th(y.caCertPem),v=m,w=`${g}${v}`;var b,S,A;return rh(h.privateKey,y.privateKeyPem,384),rh(h.cert,g,420),rh(h.chain,v,420),rh(h.fullchain,w,420),rh(h.ca,m,420),b=h.metadata,S=await oh(a,s,c,u,y),A=420,rh(b,`${JSON.stringify(S,null,2)}\n`,A),console.log(`Identity certificate created: ${h.fullchain}`),{did:a.toString(),rawHostUri:c,dirName:u,paths:h,certPath:h.cert,chainPath:h.chain,fullchainPath:h.fullchain,caPath:h.ca,keyPath:h.privateKey,metadataPath:h.metadata}},exports.createNodeConfigs=async function(e){Bd();const t=Od("node:path"),r=e.envDir,n=jd(t.join(r,"user_config.json")).name;if("string"!=typeof n||!n)throw new Error("user_config.json missing name field");const o=jd(t.join(r,"zone_config.json")),s=i.DID.fromStr(o.id),a=Rd(n,e.ownerKeyPair),c=Ud(n,e.deviceName,e.deviceKeyPair),u=t.join(r,e.deviceName),l=new i.DID("bns",n),p=g(e.deviceName,s),h=v(e.deviceName,i.createJwkByX(c.publicKeyX),p,e.now);h.support_container=!0,delete h.support_container,void 0!==e.netId&&(h.net_id=e.netId),h.owner=l.toString(),h.zone_did=s.toString(),console.log(`input net_id: ${e.netId}, device_config.net_id: ${h.net_id}`);const f=await i.encodeDeviceDocument(h,a.privateKeyPem);console.log(`${e.deviceName} device jwt: ${f}`);const y=i.newDeviceMiniDocumentByDeviceDocument(h),m=await i.deviceMiniDocumentToJwt(y,a.privateKeyPem);Cd(t.join(u,"device_mini_config.jwt"),m);const w=d({zoneDid:s,ownerDid:l,ownerPublicKey:i.createJwkByX(a.publicKeyX),deviceName:e.deviceName,deviceDid:p,zoneIat:Nd});if(S(u,$d(u),w,h,f,m,c.privateKeyPem),e.deviceName.startsWith("ood")){const e=Pd({admin_password_hash:ad(n,"bucky2025"),device_private_key:c.privateKeyPem,device_public_key:i.createJwkByX(c.publicKeyX),ood_jwt:f,friend_passcode:"sdfsdfsdf",gateway_type:"PortForward",guest_access:!0,private_key:a.privateKeyPem,public_key:i.createJwkByX(a.publicKeyX),user_name:n,zone_name:s.toHostName(),BUCKYOS_ROOT:"/opt/buckyos"});Dd(t.join(u,"start_config.json"),e)}return console.log(`Successfully created node configuration: ${n}.${e.deviceName}`),i.encodeDeviceDocument(h,c.privateKeyPem)},exports.createSnConfigs=async function(e){Bd();const t=Od("node:path"),r=t.join(e.outputDir,"sn_server"),n=Rh("sn_owner"),o=Rh("sn_server"),s=Id;Cd(t.join(r,".buckycli","user_private_key.pem"),n.privateKeyPem);const a=i.newOwnerDocument({did:new i.DID("bns","sn"),name:"root",displayName:"sn admin",publicKeyJwk:i.createJwkByX(n.publicKeyX)});Dd(t.join(r,".buckycli","user_config.json"),i.ownerDocumentToOrderedJson(a)),console.log("- Created owner config for sn admin.");const c=i.newDeviceMiniDocument({name:"sn",x:o.publicKeyX,exp:s}),u=await i.deviceMiniDocumentToJwt(c,n.privateKeyPem),l=i.newDeviceDocumentByMiniDocument(u,c,"did:web:sn.devtests.org","did:bns:sn");l.net_id="wan",Dd(t.join(r,"sn_device_config.json"),i.deviceDocumentToOrderedJson(l)),Cd(t.join(r,"sn_private_key.pem"),o.privateKeyPem),console.log("- Created sn device config & private key.");const p=i.newZoneBootDocument({oods:["sn"],exp:s}),h=Pd({params:{sn_boot_jwt:await i.encodeZoneBootDocument(p,n.privateKeyPem),sn_owner_pk:n.publicKeyX,sn_device_jwt:u,sn_host:e.snBaseHost,sn_ip:e.snIp,sn_cer:"fullchain.cert",sn_pem:"fullchain.pem",web3_cer:"fullchain.cert",web3_pem:"fullchain.pem"}});Dd(t.join(r,"params.json"),h),console.log("- Created params.json.");const d=new Md(t.join(r,"sn_db.sqlite3"));d.initializeDatabase();for(let i=0;i<9;i++){const e=`sndevtest${i}`;console.log(`insert activation code: ${e}`),d.insertActivationCode(e)}console.log("- Created SN database."),console.log("Successfully created SN configuration")},exports.createUserEnv=async function(e){Bd();const t=Od("node:path"),r=e.rtcpPort??2980,n=e.outputDir,o=Id,s=Rd(e.username,e.ownerKeyPair),a=new i.DID("bns",e.username);let c,u=new i.DID("web",e.hostname);if(e.snBaseHost&&e.snBaseHost.includes(".")){const t=`web3.${e.snBaseHost}`;u=i.DID.fromHostNameByBridge(e.hostname,"bns",t),c=`sn.${e.snBaseHost}`}Cd(t.join(n,"user_private_key.pem"),s.privateKeyPem);const l=i.createJwkByX(s.publicKeyX),p=i.newOwnerDocument({did:a,name:e.username,displayName:e.username,publicKeyJwk:l});Dd(t.join(n,"user_config.json"),i.ownerDocumentToOrderedJson(p)),console.log(`Created owner config for ${e.username}`);const h=i.parseOODDescription(e.oodName),d=Ud(e.username,h.name,e.deviceKeyPair);let f,y=c;h.netId&&(h.netId.startsWith("wan")&&(y=void 0),h.netId.startsWith("wan_dyn")&&c&&(f=`https://${c}/kapi/sn`));const m=i.oodDescriptionToString(h),w=i.newZoneBootDocument({oods:[m],sn:y,exp:o}),b=u.toRawHostName();Dd(t.join(n,`${b}.zone.json`),w),w.id=u.toString();const S=i.newZoneDocument({id:u,ownerDid:a,publicKeyJwk:l}),A=await i.encodeZoneBootDocument(w,s.privateKeyPem);S.boot_jwt=A,S.id=w.id,S.oods=[...w.oods],void 0!==w.sn?S.sn=w.sn:delete S.sn,S.exp=w.exp,S.iat=w.exp-i.DEFAULT_EXPIRE_TIME,S.version_seq=0,S.owner=w.owner??i.DID.undefined().toString(),void 0!==w.owner_key&&(S.verificationMethod[0].publicKeyJwk=w.owner_key),Dd(t.join(n,"zone_config.json"),i.zoneDocumentToOrderedJson(S));const E=s.publicKeyX;console.log(`=> ${b} TXT Record(${A.length+6}): BOOT=${A};`),console.log(`=> ${b} TXT Record(${E.length+5}): PKX=${E};`);const k=2980===r?void 0:r,x=i.newDeviceMiniDocument({name:h.name,x:d.publicKeyX,rtcpPort:k,exp:o}),_=await i.deviceMiniDocumentToJwt(x,s.privateKeyPem);console.log(`=> ${b} TXT Record(${_.length+5}): DEV=${_};`);const N=g(h.name,u),I=v(h.name,i.createJwkByX(d.publicKeyX),N);I.support_container=!0,void 0!==h.netId&&(I.net_id=h.netId),I.owner=a.toString(),I.zone_did=u.toString(),void 0!==f&&(I.ddns_sn_url=f),console.log(`${h.name} device config: ${JSON.stringify(i.deviceDocumentToOrderedJson(I),null,2)}`);const T={boot_config_jwt:A,device_mini_doc_jwt:_,pkx:E};return Dd(t.join(n,"zone_txt_record.json"),T),console.log(`Successfully created user environment configuration: ${e.username}`),T},exports.decodeDeviceDocumentWithoutVerify=A,exports.deriveDevTestEvmAccount=Bh,exports.deriveDevTestEvmAccountFromMnemonic=Th,exports.deriveDevTestKeyPair=wh,exports.deriveDevTestKeyPairFromMnemonic=vh,exports.devTestKeccak256=Nh,exports.deviceIdentityPathsForRoots=y,exports.didWebDocumentUrl=zp,exports.encodeIdentityDirName=Vp,exports.ensureCa=async function(e,t="devtest"){const r=Op("node:fs"),i=Op("node:path"),n=i.join(e,`${t}_ca_cert.pem`),o=i.join(e,`${t}_ca_key.pem`);if(r.existsSync(n)&&r.existsSync(o)){const i=function(e){try{return Zp(new Tp(e))}catch(t){return t instanceof Error?`cannot parse CA certificate: ${t.message}`:"cannot parse CA certificate"}}(r.readFileSync(n,"utf8"));return i?(console.log(`Existing CA at ${n} is invalid (${i}); regenerating`),Qp(e,t)):(console.log(`Use existing CA at: ${n}`),{caCertPath:n,caKeyPath:o})}return Qp(e,t)},exports.generateProvisionKeyPair=ud,exports.getDevTestEvmAccountByIndex=function(e){return Bh(e)},exports.getDevTestEvmAccountByUsername=function(e){const t=jh[e];if(!t)throw new Error(`no deterministic EVM account for seed user ${e}; register it in DEV_TEST_EVM_USER_INDEXES`);return t},exports.getDevTestKeyPairById=Rh,exports.getDevTestKeyPairByIndex=function(e){return wh(e)},exports.hashAdminPassword=ad,exports.identityDirName=Fp,exports.identityFileName=Wp,exports.identityRawHostUri=Kp,exports.inspectActivationRoot=async function(e){return bd(e)},exports.loadDeviceDocJwtForRoots=w,exports.loadDeviceMiniDocJwtForRoots=function(e,t){return l("node:fs").readFileSync(y(e,t).deviceMiniDocJwt,"utf8")},exports.loadLocalDeviceDocumentForRoots=async function(e,t,r){const n=w(e,t.device_did),o=r?await i.verifyJwtEdDSA(n,t.owner_public_key):A(n);if(o.id!==t.device_did)throw new Error(`device_doc.jwt id ${o.id} does not match node_identity device_did ${t.device_did}`);return[n,o]},exports.loadLocalNodeIdentityConfig=f,exports.newDeviceDocumentByJwkWithDid=v,exports.newLocalNodeIdentityConfig=d,exports.nodeTestIdentityRoots=$d,exports.registerDeviceToSn=async function(e,t,r,n){Bd();const o=Od("node:path"),s=Od("node:fs"),a=Od("node:os"),c=o.join(e,t,r),u=o.join(c,"node_identity.json");if(!s.existsSync(u))throw new Error(`Device config not found: ${u}`);const l=f(u),p=i.DID.fromStr(l.owner_did).id,h=y($d(c),l.device_did),d=s.readFileSync(h.deviceDocJwt,"utf8"),g=s.readFileSync(h.deviceMiniDocJwt,"utf8"),m=await i.verifyJwtEdDSA(d,l.owner_public_key),v=m.id;let w;try{w=i.parseOODDescription(r)}catch{w={name:r,nodeType:"Device"}}try{const n=jd(o.join(e,t,"zone_config.json")).oods.map(i.parseOODDescription).find((e=>e.name===r));n&&(w=n)}catch{}const b=function(){const e=[],t=Od("node:os").networkInterfaces();for(const r of Object.values(t))for(const t of r??[])t.internal||"IPv6"===t.family&&t.address.startsWith("fe80")||e.includes(t.address)||e.push(t.address);return e}(),S={...m};w.ip&&(S.ips=[w.ip]),void 0!==w.netId&&(S.net_id=w.netId);const A={...S,arch:Ld(),os:Vd(),update_time:i.buckyosGetUnixTimestamp(),state:"Ready",sys_hostname:a.hostname(),base_os_info:`${a.type()} ${a.release()}`,all_ip:b,cpu_num:a.cpus().length,total_mem:a.totalmem(),mem_usage:a.totalmem()-a.freemem()};let E="127.0.0.1";b.length>0&&(E=b[0]),w.ip&&(E=w.ip),new Md(n).registerDevice(p,r,v,g,E,JSON.stringify(A,null,2)),console.log(`Successfully registered device ${p}.${r} (DID: ${v}) to SN database at ${n}`)},exports.registerUserToSn=async function(e,t,r){Bd();const n=Od("node:path"),o=jd(n.join(e,t,"user_config.json")).name;if("string"!=typeof o||!o)throw new Error("user_config.json missing name field");const s=jd(n.join(e,t,"zone_config.json")),a=i.DID.fromStr(s.id);let c;"bns"!==a.method&&(c=a.toHostName());const u=jd(n.join(e,t,"zone_txt_record.json")),l=new Md(r),p=JSON.stringify(Pd({kty:"OKP",crv:"Ed25519",x:u.pkx}));l.registerUserDirectly(o,p,u.boot_config_jwt,c),console.log(`Successfully registered user ${o}@${t} to SN database at ${r}`)},exports.saveLocalDeviceIdentityForRoots=S,exports.saveNodeGatewayParams=b,exports.setPkgMeta=async function(e,t){Bd();const r=Od("node:fs");if(!r.existsSync(e))throw new Error(`meta_path ${e} does not exist`);if(!r.existsSync(t))throw new Error(`db_path ${t} does not exist`);const n=r.readFileSync(e,"utf8"),o=n.trimStart().startsWith("{")?JSON.parse(n):i.decodeJwtClaimWithoutVerify(n.trim()),s=i.calcPkgMetaObjId(o),a=new Kd(t);return a.initializeDatabase(),a.addPkgMetaBatch({[s]:{metaJwt:n,pkgName:o.name,version:o.version,tag:o.version_tag??void 0,author:o.author,authorPk:""}}),s},exports.uniqueNameToDid=Wd,exports.validateAdminPassword=sd,exports.validateOwnerName=id,exports.validatePublicIp=od,exports.validateRtcpPort=nd,exports.validateZoneDomain=rd,exports.versionToInt=Hd;
|
|
92
92
|
//# sourceMappingURL=provision.cjs.map
|