buckyos 0.7.136 → 0.7.138

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.
@@ -1,4 +1,4 @@
1
- "use strict";var e,t=Object.defineProperty,r=(e,r,i)=>(((e,r,i)=>{r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(e,"symbol"!=typeof r?r+"":r,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./ndn_types-324121ae.js"),n=require("node:buffer"),o=require("node:crypto"),s="device_doc.jwt",a="device_mini_doc.jwt",c="node_gateway_params.json";function u(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 device_identity cannot load builtin module ${e} in this runtime`)}function l(e){return e instanceof i.DID?e:i.DID.fromStr(e)}function p(e,t){const r=u("node:fs"),i=u("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,JSON.stringify(t,null,2))}function h(e){return{schema:i.NODE_IDENTITY_SCHEMA_V2,zone_did:l(e.zoneDid).toString(),owner_did:l(e.ownerDid).toString(),owner_public_key:e.ownerPublicKey,device_name:e.deviceName,device_did:l(e.deviceDid).toString(),zone_iat:e.zoneIat}}function d(e){const t=u("node:fs"),r=JSON.parse(t.readFileSync(e,"utf8"));if(r.schema!==i.NODE_IDENTITY_SCHEMA_V2)throw new Error(`unsupported node_identity schema '${r.schema}', expected '${i.NODE_IDENTITY_SCHEMA_V2}'`);return r}function f(e,t){const r=u("node:path"),i=l(t).toString(),n=e.publicDir(i);return{publicDir:n,securityDir:e.securityDir(i),didJson:e.publicFile(i,"authentication","did-json"),deviceDocJwt:r.join(n,s),deviceMiniDocJwt:r.join(n,a),authenticationPrivateKey:e.securityFile(i,"authentication","private")}}function y(e,t){const r=e.trim();if(!r)throw new Error("device name is empty");const n=l(t),o="web"===n.method?n.toRawHostName():n.id.split(":")[0]??n.id;if(!o.trim())throw new Error(`zone DID ${n.toString()} has empty host/name`);return new i.DID(n.method,`${r}.${o}`)}function g(e,t){const r=l(t).toString();if(e.id=r,!Array.isArray(e.verificationMethod))throw new Error("device document verificationMethod is missing");for(const i of e.verificationMethod)i.controller=r;return e}function m(e,t,r,n){return g(i.newDeviceDocumentByJwk(e,t,n),r)}function v(e,t){return u("node:fs").readFileSync(f(e,t).deviceDocJwt,"utf8")}function w(e,t){p(u("node:path").join(e,c),{params:{device_did:l(t).toString()}})}function b(e,t,r,n,o,s,a){const c=u("node:fs"),l=u("node:path"),h=f(t,r.device_did);return c.mkdirSync(h.publicDir,{recursive:!0}),c.mkdirSync(h.securityDir,{recursive:!0}),p(l.join(e,"node_identity.json"),r),w(e,r.device_did),p(h.didJson,i.deviceDocumentToOrderedJson(n)),c.writeFileSync(h.deviceDocJwt,o),c.writeFileSync(h.deviceMiniDocJwt,s),c.writeFileSync(h.authenticationPrivateKey,a),h}function S(e){return i.decodeJwtClaimWithoutVerify(e)}
1
+ "use strict";var e,t=Object.defineProperty,r=(e,r,i)=>(((e,r,i)=>{r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(e,"symbol"!=typeof r?r+"":r,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./ndn_types-324121ae.js"),n=require("node:buffer"),o=require("node:crypto"),s="device_doc.jwt",a="device_mini_doc.jwt",c="node_gateway_params.json";function u(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 device_identity cannot load builtin module ${e} in this runtime`)}function l(e){return e instanceof i.DID?e:i.DID.fromStr(e)}function p(e,t){const r=u("node:fs"),i=u("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,JSON.stringify(t,null,2))}function h(e){return{schema:i.NODE_IDENTITY_SCHEMA_V2,zone_did:l(e.zoneDid).toString(),owner_did:l(e.ownerDid).toString(),owner_public_key:e.ownerPublicKey,device_name:e.deviceName,device_did:l(e.deviceDid).toString(),zone_iat:e.zoneIat}}function d(e){const t=u("node:fs"),r=JSON.parse(t.readFileSync(e,"utf8"));if(r.schema!==i.NODE_IDENTITY_SCHEMA_V2)throw new Error(`unsupported node_identity schema '${r.schema}', expected '${i.NODE_IDENTITY_SCHEMA_V2}'`);return r}function f(e,t){const r=u("node:path"),i=l(t).toString(),n=e.publicDir(i);return{publicDir:n,securityDir:e.securityDir(i),didJson:e.publicFile(i,"authentication","did-json"),deviceDocJwt:r.join(n,s),deviceMiniDocJwt:r.join(n,a),authenticationPrivateKey:e.securityFile(i,"authentication","private")}}function y(e,t){const r=e.trim();if(!r)throw new Error("device name is empty");const n=l(t),o="web"===n.method?n.toRawHostName():n.id.split(":")[0]??n.id;if(!o.trim())throw new Error(`zone DID ${n.toString()} has empty host/name`);return new i.DID(n.method,`${r}.${o}`)}function g(e,t){const r=l(t).toString();if(e.id=r,!Array.isArray(e.verificationMethod))throw new Error("device document verificationMethod is missing");for(const i of e.verificationMethod)i.controller=r;return e}function m(e,t,r,n){return g(i.newDeviceDocumentByJwk(e,t,n),r)}function v(e,t){return u("node:fs").readFileSync(f(e,t).deviceDocJwt,"utf8")}function w(e,t,r=2980){if(!Number.isInteger(r)||r<1||r>65535)throw new Error(`invalid device RTCP port: ${r}`);p(u("node:path").join(e,c),{params:{device_did:l(t).toString(),rtcp_port:String(r)}})}function b(e,t,r,n,o,s,a){const c=u("node:fs"),l=u("node:path"),h=f(t,r.device_did);return c.mkdirSync(h.publicDir,{recursive:!0}),c.mkdirSync(h.securityDir,{recursive:!0}),p(l.join(e,"node_identity.json"),r),w(e,r.device_did,n.rtcp_port),p(h.didJson,i.deviceDocumentToOrderedJson(n)),c.writeFileSync(h.deviceDocJwt,o),c.writeFileSync(h.deviceMiniDocJwt,s),c.writeFileSync(h.authenticationPrivateKey,a),h}function S(e){return i.decodeJwtClaimWithoutVerify(e)}
2
2
  /*! *****************************************************************************
3
3
  Copyright (C) Microsoft. All rights reserved.
4
4
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -88,5 +88,5 @@ PERFORMANCE OF THIS SOFTWARE.
88
88
  * SOFTWARE.
89
89
  *
90
90
  */
91
- const pu="crypto.algorithm";const hu="crypto.algorithmProvider";var du;uc.registerSingleton(hu,class{getAlgorithms(){return uc.resolveAll(pu)}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 Fn({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 fu="1.3.36.3.3.2.8.1.1",yu=`${fu}.1`,gu=`${fu}.2`,mu=`${fu}.3`,vu=`${fu}.4`,wu=`${fu}.5`,bu=`${fu}.6`,Su=`${fu}.7`,Au=`${fu}.8`,Eu=`${fu}.9`,ku=`${fu}.10`,xu=`${fu}.11`,_u=`${fu}.12`,Nu=`${fu}.13`,Iu=`${fu}.14`,Tu="brainpoolP160r1",Bu="brainpoolP160t1",Ou="brainpoolP192r1",Cu="brainpoolP192t1",Du="brainpoolP224r1",ju="brainpoolP224t1",Pu="brainpoolP256r1",Ru="brainpoolP256t1",Uu="brainpoolP320r1",$u="brainpoolP320t1",Mu="brainpoolP384r1",Lu="brainpoolP384t1",Vu="brainpoolP512r1",Hu="brainpoolP512t1",Ku="ECDSA";let Fu=du=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Ku.toLowerCase())if("hash"in e){switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Js;case"sha-256":return qs;case"sha-384":return Gs;case"sha-512":return Xs}}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Ks;break;case"K-256":t=du.SECP256K1;break;case"P-384":t=Fs;break;case"P-521":t=zs;break;case Tu:t=yu;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}if(t)return new Fn({algorithm:Us,parameters:Kr.serialize(new ra({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case $s:return{name:Ku,hash:{name:"SHA-1"}};case Ls:return{name:Ku,hash:{name:"SHA-256"}};case Vs:return{name:Ku,hash:{name:"SHA-384"}};case Hs:return{name:Ku,hash:{name:"SHA-512"}};case Us:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Kr.parse(e.parameters,ra).namedCurve){case Ks:return{name:Ku,namedCurve:"P-256"};case du.SECP256K1:return{name:Ku,namedCurve:"K-256"};case Fs:return{name:Ku,namedCurve:"P-384"};case zs:return{name:Ku,namedCurve:"P-521"};case yu:return{name:Ku,namedCurve:Tu};case gu:return{name:Ku,namedCurve:Bu};case mu:return{name:Ku,namedCurve:Ou};case vu:return{name:Ku,namedCurve:Cu};case wu:return{name:Ku,namedCurve:Du};case bu:return{name:Ku,namedCurve:ju};case Su:return{name:Ku,namedCurve:Pu};case Au:return{name:Ku,namedCurve:Ru};case Eu:return{name:Ku,namedCurve:Uu};case ku:return{name:Ku,namedCurve:$u};case xu:return{name:Ku,namedCurve:Mu};case _u:return{name:Ku,namedCurve:Lu};case Nu:return{name:Ku,namedCurve:Vu};case Iu:return{name:Ku,namedCurve:Hu}}}return null}};Fu.SECP256K1="1.3.132.0.10",Fu=du=Fr([lc()],Fu),uc.registerSingleton(pu,Fu);const zu=Symbol("name"),Wu=Symbol("value");class Ju{constructor(e,t={},r=""){this[zu]=e,this[Wu]=r;for(const i in t)this[i]=t[i]}}Ju.NAME=zu,Ju.VALUE=Wu;class qu{static toString(e){const t=this.items[e];return t||e}}qu.items={[wa]:"sha1",[ba]:"sha224",[Sa]:"sha256",[Aa]:"sha384",[Ea]:"sha512",[sa]:"rsaEncryption",[ha]:"sha1WithRSAEncryption",[da]:"sha224WithRSAEncryption",[fa]:"sha256WithRSAEncryption",[ya]:"sha384WithRSAEncryption",[ga]:"sha512WithRSAEncryption",[Us]:"ecPublicKey",[$s]:"ecdsaWithSHA1",[Ms]:"ecdsaWithSHA224",[Ls]:"ecdsaWithSHA256",[Vs]:"ecdsaWithSHA384",[Hs]:"ecdsaWithSHA512",[sn]:"TLS WWW server authentication",[an]:"TLS WWW client authentication",[cn]:"Code Signing",[un]:"E-mail Protection",[ln]:"Time Stamping",[pn]:"OCSP Signing",[Ds]:"Signed Data"};class Gu{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[Ju.VALUE];o&&(n=` ${o}`),r.push(`${i}${e[Ju.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[Ju.NAME]=s,r.push(...this.serializeObj(e,t));else if(n instanceof Ju)n[Ju.NAME]=s,r.push(...this.serializeObj(n,t));else if(k.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[Ju.NAME]=s,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),i=k.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 Xu,Yu;Gu.oidSerializer=qu,Gu.algorithmSerializer=class{static toTextObject(e){const t=new Ju("Algorithm Identifier",{},qu.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Us:{const r=(new Fu).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Zu{get rawData(){return zr(this,Xu,"f")||Wr(this,Xu,Kr.serialize(this.asn),"f"),zr(this,Xu,"f")}constructor(...e){Xu.set(this,void 0),k.isBufferSource(e[0])?(this.asn=Kr.parse(e[0],e[1]),Wr(this,Xu,k.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Zu&&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 Kr.toString(this.rawData);case"text":return Gu.serialize(this.toTextObject());case"hex":return O.ToHex(this.rawData);case"base64":return O.ToBase64(this.rawData);case"base64url":return O.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 Ju(this.getTextName(),{},e)}}Xu=new WeakMap,Zu.NAME="ASN";class Qu extends Zu{constructor(...e){let t;t=k.isBufferSource(e[0])?k.toArrayBuffer(e[0]):Kr.serialize(new Gn({extnID:e[0],critical:e[1],extnValue:new sr(k.toArrayBuffer(e[2]))})),super(t,Gn)}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[Ju.NAME]===Qu.NAME&&(e[Ju.NAME]=qu.toString(this.type)),e}}class el{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[Yu]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(el.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(el.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=el.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(el.DEFAULT,e);return this}}Yu=Symbol.toStringTag,el.DEFAULT="default";const tl=new el,rl=/^[0-2](?:\.[1-9][0-9]*)+$/;class il{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(rl).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const nl=new il;function ol(e,t){return`\\${O.ToHex(O.FromUtf8String(t)).toUpperCase()}`}nl.register("CN","2.5.4.3"),nl.register("L","2.5.4.7"),nl.register("ST","2.5.4.8"),nl.register("O","2.5.4.10"),nl.register("OU","2.5.4.11"),nl.register("C","2.5.4.6"),nl.register("DC","0.9.2342.19200300.100.1.25"),nl.register("E","1.2.840.113549.1.9.1"),nl.register("G","2.5.4.42"),nl.register("I","2.5.4.43"),nl.register("SN","2.5.4.4"),nl.register("T","2.5.4.12");class sl{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 il,this.asn=new ni;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 ni?this.asn=e:k.isBufferSource(e)?this.asn=Kr.parse(e,ni):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||nl.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)||nl.get(e)}toString(){return this.asn.map((e=>e.map((e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${O.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,ol)}`)).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?`#${O.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(i)}return t}fromString(e){const t=new ni,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 ri([a])),n=s}return t}fromJSON(e){const t=new ni;for(const r of e){const e=new ri;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 ti({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=O.FromHex(t.slice(1));else{const i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:sl.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 Kr.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]||tl.get()):r=e[0]||tl.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const al="Cannot initialize GeneralName from ASN.1 data.",cl=`${al} Unsupported string format in use.`,ul=`${al} Value doesn't match to GUID regular expression.`,ll=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,pl="1.3.6.1.4.1.311.25.1",hl="1.3.6.1.4.1.311.20.2.3",dl="dns",fl="dn",yl="email",gl="ip",ml="url",vl="guid",wl="upn",bl="id";class Sl extends Zu{constructor(...e){let t;if(2===e.length)switch(e[0]){case fl:{const r=new sl(e[1]).toArrayBuffer(),i=Kr.parse(r,ni);t=new ci({directoryName:i});break}case dl:t=new ci({dNSName:e[1]});break;case yl:t=new ci({rfc822Name:e[1]});break;case vl:{const r=new RegExp(ll,"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?O.ToHex(new Uint8Array(O.FromHex(e)).reverse()):e)).join("");t=new ci({otherName:new si({typeId:pl,value:Kr.serialize(new sr(O.FromHex(i)))})});break}case gl:t=new ci({iPAddress:e[1]});break;case bl:t=new ci({registeredID:e[1]});break;case wl:t=new ci({otherName:new si({typeId:hl,value:Kr.serialize(mr.toASN(e[1]))})});break;case ml:t=new ci({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=k.isBufferSource(e[0])?Kr.parse(e[0],ci):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=dl,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=yl,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=gl,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=ml,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=bl,this.value=e.registeredID;else if(null!=e.directoryName)this.type=fl,this.value=new sl(e.directoryName).toString();else{if(null==e.otherName)throw new Error(cl);if(e.otherName.typeId===pl){this.type=vl;const t=Kr.parse(e.otherName.value,sr),r=new RegExp(ll,"i").exec(O.ToHex(t));if(!r)throw new Error(ul);this.value=r.slice(1).map(((e,t)=>t<3?O.ToHex(new Uint8Array(O.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==hl)throw new Error(cl);this.type=wl,this.value=Kr.parse(e.otherName.value,Qr).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case fl:case dl:case vl:case gl:case bl:case wl:case ml:e=this.type.toUpperCase();break;case yl:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===bl&&(t=qu.toString(t)),new Ju(e,void 0,t)}}class Al extends Zu{constructor(e){let t;if(e instanceof Ni)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof ci)r.push(t);else{const e=Kr.parse(new Sl(t.type,t.value).rawData,ci);r.push(e)}t=new Ni(r)}else{if(!k.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Kr.parse(e,Ni)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new Sl(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[Ju.NAME]];Array.isArray(i)||(i=[],e[r[Ju.NAME]]=i),i.push(r)}return e}}Al.NAME="GeneralNames";const El="-{5}",kl="\\n",xl="\\n",_l=`${`${El}BEGIN (${`[^${kl}]+`}(?=${El}))${El}`}${xl}(?:((?:${`[^:${kl}]+`}: ${`(?:[^${kl}]+${xl}(?: +[^${kl}]+${xl})*)`})+))?${xl}?(${`(?:[a-zA-Z0-9=+/]+${xl})+`})${`${El}END \\1${El}`}`;class Nl{static isPem(e){return"string"==typeof e&&new RegExp(_l,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(_l,"g"),r=[];let i=null;for(;i=t.exec(e);){const e=i[3].replace(new RegExp(`[${kl}]+`,"g"),""),t={type:i[1],headers:[],rawData:O.FromBase64(e)},n=i[2];if(n){const e=n.split(new RegExp(xl,"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(!k.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:k.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:k.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=O.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")}}Nl.CertificateTag="CERTIFICATE",Nl.CrlTag="CRL",Nl.CertificateRequestTag="CERTIFICATE REQUEST",Nl.PublicKeyTag="PUBLIC KEY",Nl.PrivateKeyTag="PRIVATE KEY";class Il extends Zu{static isAsnEncoded(e){return k.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(Nl.isPem(e))return Nl.decode(e)[0];if(O.isHex(e))return O.FromHex(e);if(O.isBase64(e))return O.FromBase64(e);if(O.isBase64Url(e))return O.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=k.toUint8Array(e);if(t.length>0&&48===t[0])return k.toArrayBuffer(e);const r=O.ToBinary(e);if(Nl.isPem(r))return Nl.decode(r)[0];if(O.isHex(r))return O.FromHex(r);if(O.isBase64(r))return O.FromBase64(r);if(O.isBase64Url(r))return O.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){Il.isAsnEncoded(e[0])?super(Il.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?Nl.encode(this.rawData,this.tag):super.toString(e)}}class Tl extends Il{static async create(e,t=tl.get()){if(e instanceof Tl)return e;if(el.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new Tl(r)}if(e.publicKey)return e.publicKey;if(k.isBufferSource(e))return new Tl(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){Il.isAsnEncoded(e)?super(e,zn):super(e),this.tag=Nl.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]||tl.get()):t=e[0]||tl.get();let n=this.rawData;const o=Kr.parse(this.rawData,zn);return o.algorithm.algorithm===ua&&(n=function(e,t){return e.algorithm=new Fn({algorithm:sa,parameters:null}),t=Kr.serialize(e),t}(o,n)),t.subtle.importKey("spki",n,i,!0,r)}onInit(e){const t=uc.resolve(hu),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case sa:{const t=Kr.parse(e.subjectPublicKey,Ra),i=k.toUint8Array(t.modulus);r.publicExponent=k.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]||tl.get()):r=e[0]||tl.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=tl.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=tl.get();const i=Kr.parse(this.rawData,zn);return await t.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Kr.parse(this.rawData,zn);if(e.Algorithm=Gu.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===Us)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class Bl extends Qu{static async create(e,t=!1,r=tl.get()){if("name"in e&&"serialNumber"in e)return new Bl(e,t);const i=await Tl.create(e,r),n=await i.getKeyIdentifier(r);return new Bl(O.ToHex(n),t)}constructor(...e){if(k.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Ei({keyIdentifier:new Ai(O.FromHex(e[0]))});super(Si,e[1],Kr.serialize(t))}else{const t=e[0],r=t.name instanceof Al?Kr.parse(t.name.rawData,Ni):t.name,i=new Ei({authorityCertIssuer:r,authorityCertSerialNumber:O.FromHex(t.serialNumber)});super(Si,e[1],Kr.serialize(i))}}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,Ei);t.keyIdentifier&&(this.keyId=O.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?O.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Ei);return t.authorityCertIssuer&&(e["Authority Issuer"]=new Al(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}Bl.NAME="Authority Key Identifier";class Ol extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,xi);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new xi({cA:e[0],pathLenConstraint:e[1]});super(ki,e[2],Kr.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 Cl,Dl,jl;Ol.NAME="Basic Constraints",(Dl=Cl||(Cl={})).serverAuth="1.3.6.1.5.5.7.3.1",Dl.clientAuth="1.3.6.1.5.5.7.3.2",Dl.codeSigning="1.3.6.1.5.5.7.3.3",Dl.emailProtection="1.3.6.1.5.5.7.3.4",Dl.timeStamping="1.3.6.1.5.5.7.3.8",Dl.ocspSigning="1.3.6.1.5.5.7.3.9";class Pl extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,on);this.usages=t.map((e=>e))}else{const t=new on(e[0]);super(nn,e[1],Kr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>qu.toString(e))).join(", "),e}}Pl.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"}(jl||(jl={}));class Rl extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,Sn);this.usages=t.toNumber()}else{const t=new Sn(e[0]);super(mn,e[1],Kr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Sn);return e[""]=t.toJSON().join(", "),e}}Rl.NAME="Key Usages";class Ul extends Qu{static async create(e,t=!1,r=tl.get()){const i=await Tl.create(e,r),n=await i.getKeyIdentifier(r);return new Ul(O.ToHex(n),t)}constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,Rn);this.keyId=O.ToHex(t)}else{const t="string"==typeof e[0]?O.FromHex(e[0]):e[0],r=new Rn(t);super(Pn,e[1],Kr.serialize(r)),this.keyId=O.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Rn);return e[""]=t,e}}Ul.NAME="Subject Key Identifier";class $l extends Qu{constructor(...e){k.isBufferSource(e[0])?super(e[0]):super(Bn,e[1],new Al(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,On);this.names=new Al(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}$l.NAME="Subject Alternative Name";class Ml{static register(e,t){this.items.set(e,t)}static create(e){const t=new Qu(e),r=this.items.get(t.type);return r?new r(e):t}}Ml.items=new Map;class Ll extends Qu{constructor(...e){var t;if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,$i);this.policies=t.map((e=>e.policyIdentifier))}else{const r=e[0],i=null!==(t=e[1])&&void 0!==t&&t,n=new $i(r.map((e=>new Ui({policyIdentifier:e}))));super(Oi,i,Kr.serialize(n)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new Ju("",{},qu.toString(e)))),e}}Ll.NAME="Certificate Policies",Ml.register(Oi,Ll);class Vl extends Qu{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map((e=>new Ji({distributionPoint:new Wi({fullName:[new ci({uniformResourceIdentifier:e})]})}))),r=new qi(t);super(Hi,e[1],Kr.serialize(r))}else{const t=new qi(e[0]);super(Hi,e[1],Kr.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,qi);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 Sl(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}Vl.NAME="CRL Distribution Points";class Hl extends Qu{constructor(...e){var t,r,i,n;if(k.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof bi){const t=new bi(e[0]);super(vi,e[1],Kr.serialize(t))}else{const t=e[0],r=new bi;Fl(r,t,hi,"ocsp"),Fl(r,t,di,"caIssuers"),Fl(r,t,fi,"timeStamping"),Fl(r,t,yi,"caRepository"),super(vi,e[1],Kr.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=[];Kr.parse(e.extnValue,bi).forEach((e=>{switch(e.accessMethod){case hi:this.ocsp.push(new Sl(e.accessLocation));break;case di:this.caIssuers.push(new Sl(e.accessLocation));break;case fi:this.timeStamping.push(new Sl(e.accessLocation));break;case yi:this.caRepository.push(new Sl(e.accessLocation))}}))}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Kl(e,"OCSP",this.ocsp),this.caIssuers.length&&Kl(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Kl(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Kl(e,"CA Repository",this.caRepository),e}}function Kl(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const i=new Ju("");r.forEach(((e,t)=>{const r=e.toTextObject(),n=`${r[Ju.NAME]} ${t+1}`;let o=i[n];Array.isArray(o)||(o=[],i[n]=o),o.push(r)})),e[t]=i}}function Fl(e,t,r,i){const n=t[i];if(n){(Array.isArray(n)?n:[n]).forEach((t=>{"string"==typeof t&&(t=new Sl("url",t)),e.push(new wi({accessMethod:r,accessLocation:Kr.parse(t.rawData,ci)}))}))}}Hl.NAME="Authority Info Access";class zl extends Qu{constructor(...e){k.isBufferSource(e[0])?super(e[0]):super(yn,e[1],new Al(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,Ni);this.names=new Al(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}zl.NAME="Issuer Alternative Name";class Wl extends Zu{constructor(...e){let t;if(k.isBufferSource(e[0]))t=k.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map((e=>k.toArrayBuffer(e))):[];t=Kr.serialize(new Cn({type:r,values:i}))}super(t,Cn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new Ju("",{"":e}))),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[Ju.NAME]===Wl.NAME&&(e[Ju.NAME]=qu.toString(this.type)),e}}Wl.NAME="Attribute";class Jl extends Wl{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else{const t=new tu({printableString:e[0]});super(Rc,[Kr.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Kr.parse(this.values[0],tu);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[Ju.VALUE]=this.password,e}}Jl.NAME="Challenge Password";class ql extends Wl{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Xn;for(const e of t)r.push(Kr.parse(e.rawData,Gn));super(Uc,[Kr.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Kr.parse(this.values[0],Xn);this.items=e.map((e=>Ml.create(Kr.serialize(e))))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(const r of t)e[r[Ju.NAME]]=r;return e}}ql.NAME="Extensions";class Gl{static register(e,t){this.items.set(e,t)}static create(e){const t=new Wl(e),r=this.items.get(t.type);return r?new r(e):t}}Gl.items=new Map;const Xl="crypto.signatureFormatter";var Yl;let Zl=Yl=class{static createPssParams(e,t){const r=Yl.getHashAlgorithm(e);return r?new Ba({hashAlgorithm:r,maskGenAlgorithm:new Fn({algorithm:ka,parameters:Kr.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=uc.resolve(hu);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 Fn({algorithm:sa,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 Fn({algorithm:ha,parameters:null});case"sha-256":return new Fn({algorithm:fa,parameters:null});case"sha-384":return new Fn({algorithm:ya,parameters:null});case"sha-512":return new Fn({algorithm:ga,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=Yl.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Fn({algorithm:ua,parameters:Kr.serialize(t)})}return new Fn({algorithm:ua,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case sa:return{name:"RSASSA-PKCS1-v1_5"};case ha:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case fa:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case ya:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ga:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case ua:if(e.parameters){const t=Kr.parse(e.parameters,Ba);return{name:"RSA-PSS",hash:uc.resolve(hu).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Zl=Yl=Fr([lc()],Zl),uc.registerSingleton(pu,Zl);let Ql=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Fn({algorithm:wa});case"sha-256":return new Fn({algorithm:Sa});case"sha-384":return new Fn({algorithm:Aa});case"sha-512":return new Fn({algorithm:Ea})}return null}toWebAlgorithm(e){switch(e.algorithm){case wa:return{name:"SHA-1"};case Sa:return{name:"SHA-256"};case Aa:return{name:"SHA-384"};case Ea:return{name:"SHA-512"}}return null}};Ql=Fr([lc()],Ql),uc.registerSingleton(pu,Ql);class ep{addPadding(e,t){const r=k.toUint8Array(t),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,t=!1){let r=k.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=ep.namedCurveSize.get(r)||ep.defaultNamedCurveSize,n=new na,o=k.toUint8Array(t);return n.r=this.removePadding(o.slice(0,i),!0),n.s=this.removePadding(o.slice(i,i+i),!0),Kr.serialize(n)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Kr.parse(t,na),i=e.namedCurve,n=ep.namedCurveSize.get(i)||ep.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}}ep.namedCurveSize=new Map,ep.defaultNamedCurveSize=32;const tp="1.3.101.110",rp="1.3.101.111",ip="1.3.101.112",np="1.3.101.113";let op=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=ip;break;case"x25519":t=tp;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=ip;break;case"ed448":t=np}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=tp;break;case"x448":t=rp}}return t?new Fn({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case ip:return{name:"Ed25519"};case np:return{name:"EdDSA",namedCurve:"Ed448"};case tp:return{name:"X25519"};case rp:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};var sp,ap,cp,up,lp,pp,hp,dp,fp,yp,gp,mp,vp,wp,bp,Sp,Ap,Ep,kp,xp,_p,Np;op=Fr([lc()],op),uc.registerSingleton(pu,op);sp=new WeakMap,ap=new WeakMap,cp=new WeakMap,up=new WeakMap,lp=new WeakMap,pp=new WeakMap,hp=new WeakMap,dp=new WeakMap,class extends Il{get subjectName(){return zr(this,ap,"f")||Wr(this,ap,new sl(this.asn.certificationRequestInfo.subject),"f"),zr(this,ap,"f")}get subject(){return zr(this,cp,"f")||Wr(this,cp,this.subjectName.toString(),"f"),zr(this,cp,"f")}get signatureAlgorithm(){if(!zr(this,up,"f")){const e=uc.resolve(hu);Wr(this,up,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return zr(this,up,"f")}get signature(){return zr(this,lp,"f")||Wr(this,lp,this.asn.signature,"f"),zr(this,lp,"f")}get publicKey(){return zr(this,pp,"f")||Wr(this,pp,new Tl(this.asn.certificationRequestInfo.subjectPKInfo),"f"),zr(this,pp,"f")}get attributes(){return zr(this,hp,"f")||Wr(this,hp,this.asn.certificationRequestInfo.attributes.map((e=>Gl.create(Kr.serialize(e)))),"f"),zr(this,hp,"f")}get extensions(){if(!zr(this,dp,"f")){Wr(this,dp,[],"f");const e=this.getAttribute(Uc);e instanceof ql&&Wr(this,dp,e.items,"f")}return zr(this,dp,"f")}get tbs(){return zr(this,sp,"f")||Wr(this,sp,this.asn.certificationRequestInfoRaw||Kr.serialize(this.asn.certificationRequestInfo),"f"),zr(this,sp,"f")}constructor(e){const t=Il.isAsnEncoded(e)?[e,lu]:[e];super(t[0],t[1]),sp.set(this,void 0),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),this.tag=Nl.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=tl.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),i=uc.resolveAll(Xl).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=Kr.parse(this.rawData,lu),r=t.certificationRequestInfo,i=new Ju("",{Version:`${Yn[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new Ju("");for(const t of this.attributes){const r=t.toTextObject();e[r[Ju.NAME]]=r}i.Attributes=e}return e.Data=i,e.Signature=new Ju("",{Algorithm:Gu.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}.NAME="PKCS#10 Certificate Request";class Ip extends Il{get publicKey(){return zr(this,xp,"f")||Wr(this,xp,new Tl(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),zr(this,xp,"f")}get serialNumber(){if(!zr(this,yp,"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)),Wr(this,yp,O.ToHex(t),"f")}return zr(this,yp,"f")}get subjectName(){return zr(this,gp,"f")||Wr(this,gp,new sl(this.asn.tbsCertificate.subject),"f"),zr(this,gp,"f")}get subject(){return zr(this,mp,"f")||Wr(this,mp,this.subjectName.toString(),"f"),zr(this,mp,"f")}get issuerName(){return zr(this,vp,"f")||Wr(this,vp,new sl(this.asn.tbsCertificate.issuer),"f"),zr(this,vp,"f")}get issuer(){return zr(this,wp,"f")||Wr(this,wp,this.issuerName.toString(),"f"),zr(this,wp,"f")}get notBefore(){if(!zr(this,bp,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Wr(this,bp,e,"f")}return zr(this,bp,"f")}get notAfter(){if(!zr(this,Sp,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Wr(this,Sp,e,"f")}return zr(this,Sp,"f")}get signatureAlgorithm(){if(!zr(this,Ap,"f")){const e=uc.resolve(hu);Wr(this,Ap,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return zr(this,Ap,"f")}get signature(){return zr(this,Ep,"f")||Wr(this,Ep,this.asn.signatureValue,"f"),zr(this,Ep,"f")}get extensions(){return zr(this,kp,"f")||(Wr(this,kp,[],"f"),this.asn.tbsCertificate.extensions&&Wr(this,kp,this.asn.tbsCertificate.extensions.map((e=>Ml.create(Kr.serialize(e)))),"f")),zr(this,kp,"f")}get tbs(){return zr(this,fp,"f")||Wr(this,fp,this.asn.tbsCertificateRaw||Kr.serialize(this.asn.tbsCertificate),"f"),zr(this,fp,"f")}constructor(e){const t=Il.isAsnEncoded(e)?[e,eo]:[e];super(t[0],t[1]),fp.set(this,void 0),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),this.tag=Nl.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=tl.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 Tl)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"],t);else if(k.isBufferSource(n)){const e=new Tl(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=uc.resolveAll(Xl).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=tl.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=tl.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Kr.parse(this.rawData,eo),r=t.tbsCertificate,i=new Ju("",{Version:`${Yn[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Gu.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Ju("",{"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 Ju("");for(const t of this.extensions){const r=t.toTextObject();e[r[Ju.NAME]]=r}i.Extensions=e}return e.Data=i,e.Signature=new Ju("",{Algorithm:Gu.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}fp=new WeakMap,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,Ip.NAME="Certificate";class Tp{static async createSelfSigned(e,t=tl.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=tl.get()){var r;let i;i=e.publicKey instanceof Tl?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:k.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const n=function(e,t=tl.get()){const r=k.toUint8Array(O.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 eo({tbsCertificate:new Qn({version:Yn.v3,serialNumber:n,validity:new Jn({notBefore:o,notAfter:s}),extensions:new Xn((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>Kr.parse(e.rawData,Gn))))||[]),subjectPublicKeyInfo:Kr.parse(i,zn)})});if(e.subject){const t=e.subject instanceof sl?e.subject:new sl(e.subject);a.tbsCertificate.subject=Kr.parse(t.toArrayBuffer(),ni)}if(e.issuer){const t=e.issuer instanceof sl?e.issuer:new sl(e.issuer);a.tbsCertificate.issuer=Kr.parse(t.toArrayBuffer(),ni)}const c={hash:"SHA-256"},u="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},l=uc.resolve(hu);a.tbsCertificate.signature=a.signatureAlgorithm=l.toAsnAlgorithm(u);const p=Kr.serialize(a.tbsCertificate),h="signingKey"in e?await t.subtle.sign(u,e.signingKey,p):e.signature,d=uc.resolveAll(Xl).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 Ip(Kr.serialize(a))}}function Bp(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 Op(){const e=globalThis.crypto;if(null==e?void 0:e.subtle)return e;return Bp("node:crypto").webcrypto}(Np=_p||(_p={}))[Np.unspecified=0]="unspecified",Np[Np.keyCompromise=1]="keyCompromise",Np[Np.cACompromise=2]="cACompromise",Np[Np.affiliationChanged=3]="affiliationChanged",Np[Np.superseded=4]="superseded",Np[Np.cessationOfOperation=5]="cessationOfOperation",Np[Np.certificateHold=6]="certificateHold",Np[Np.removeFromCRL=8]="removeFromCRL",Np[Np.privilegeWithdrawn=9]="privilegeWithdrawn",Np[Np.aACompromise=10]="aACompromise",Ml.register(ki,Ol),Ml.register(nn,Pl),Ml.register(mn,Rl),Ml.register(Pn,Ul),Ml.register(Si,Bl),Ml.register(Bn,$l),Ml.register(Hi,Vl),Ml.register(vi,Hl),Ml.register(yn,zl),Gl.register(Rc,Jl),Gl.register(Uc,ql),uc.registerSingleton(Xl,class{toAsnSignature(e,t){return k.toArrayBuffer(t)}toWebSignature(e,t){return k.toArrayBuffer(t)}}),uc.registerSingleton(Xl,ep),ep.namedCurveSize.set("P-256",32),ep.namedCurveSize.set("K-256",32),ep.namedCurveSize.set("P-384",48),ep.namedCurveSize.set("P-521",66);const Cp={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:4096},Dp={...Cp,modulusLength:2048},jp=["server","client","authentication","assertion","key-agreement","capability"],Pp=["did-json","did-meta","cert","chain","fullchain","ca","public","csr","meta","private","keyref","verification-method"];function Rp(){const e=new Uint8Array(16);return Op().getRandomValues(e),e[0]&=127,e[0]|=1,Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Up(e){return new Date(Date.now()+24*e*3600*1e3)}async function $p(e){const t=new Uint8Array(await Op().subtle.exportKey("pkcs8",e));return Nl.encode(t,"PRIVATE KEY")}function Mp(e){return Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Lp(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=Bp("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 Vp(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 Hp(e){return Vp(e).toRawHostUri()}function Kp(e){return Lp(Hp(e))}function Fp(e){const t=Vp(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 zp(e,t){switch(function(e){if(!jp.includes(e))throw new Error(`Unsupported identity usage: ${e}`)}(e),function(e){if(!Pp.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 Wp(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function Jp(e,t,r){const i=Bp("node:path");return{cert:i.join(e,zp(r,"cert")),chain:i.join(e,zp(r,"chain")),fullchain:i.join(e,zp(r,"fullchain")),ca:i.join(e,zp(r,"ca")),metadata:i.join(e,zp(r,"meta")),keyref:i.join(t,zp(r,"keyref")),privateKey:i.join(t,zp(r,"private"))}}class qp{constructor(e,t){const r=Bp("node:path");this.publicRoot=r.resolve(e),this.securityRoot=r.resolve(t)}static fromEnvOrBuckyosRoot(e={}){const t=Bp("node:path"),r=function(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}(),i=Wp(e.buckyosRoot)??Wp(r.BUCKYOS_ROOT)??"/opt/buckyos",n=Wp(e.publicRoot)??Wp(r.BUCKYOS_IDENTITY_ROOT)??t.join(i,"local","identity"),o=Wp(e.securityRoot)??Wp(r.BUCKYOS_SECURITY_ROOT)??t.join(i,"security");return new qp(n,o)}rawHostUri(e){return Hp(e)}dirName(e){return Kp(e)}publicDir(e){return Bp("node:path").join(this.publicRoot,this.dirName(e))}securityDir(e){return Bp("node:path").join(this.securityRoot,this.dirName(e))}publicFile(e,t,r){return Bp("node:path").join(this.publicDir(e),zp(t,r))}securityFile(e,t,r){return Bp("node:path").join(this.securityDir(e),zp(t,r))}x509Paths(e,t="server"){return Jp(this.publicDir(e),this.securityDir(e),t)}identityDirMatch(e){const t=this.rawHostUri(e),r=Lp(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=Bp("node:fs"),i=this.identityDirMatch(e),n=Jp(i.publicDir,i.securityDir,t);if(r.existsSync(n.fullchain)||r.existsSync(n.cert))return{match:i,paths:n};const o=Vp(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=Lp(a),u=Bp("node:path"),l=u.join(this.publicRoot,c),p=u.join(this.securityRoot,c),h=Jp(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 Gp(e){const t=Op();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=Xp(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),Xp(48,n)}(new Uint8Array(Nl.decode(e)[0]));return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}const r=new Uint8Array(Nl.decode(e)[0]);return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}function Xp(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 Yp(e){const t=e.extensions.find((e=>e instanceof Ol));if(!(null==t?void 0:t.ca))return"missing basicConstraints CA:TRUE";const r=e.extensions.find((e=>e instanceof Rl));return!r||r.usages&jl.keyCertSign?void 0:"keyUsage does not allow certificate signing"}async function Zp(e,t="devtest"){const r=Bp("node:fs"),i=Bp("node:path"),n=Op();tl.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(Cp,!0,["sign","verify"]),u=await Tp.createSelfSigned({serialNumber:Rp(),name:a,notBefore:new Date,notAfter:Up(3650),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},keys:c,extensions:[new Ol(!0,void 0,!0),new Rl(jl.keyCertSign|jl.cRLSign|jl.digitalSignature,!0),await Ul.create(c.publicKey)]});return r.writeFileSync(o,await $p(c.privateKey)),r.writeFileSync(s,u.toString("pem")),console.log(`CA certificate created: ${s}`),{caCertPath:s,caKeyPath:o}}async function Qp(e,t,r=[],i="server"){const n=Bp("node:fs"),o=Op();tl.set(o);const{caCertPath:s,caKeyPath:a}=function(e){const t=Bp("node:fs"),r=Bp("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 Ip(c),l=Yp(u);if(l)throw new Error(`Invalid CA certificate at ${s}: ${l}`);const p=await Gp(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(Dp,!0,["sign","verify"]),f=new Uint8Array(await o.subtle.exportKey("spki",d.publicKey)),y=await async function(e){const t=await Op().subtle.digest("SHA-256",e);return`sha256:${Mp(new Uint8Array(t))}`}(f),g=[...t.map((e=>({type:"dns",value:e}))),...r.map((e=>({type:"url",value:e})))],m=await Tp.create({serialNumber:Rp(),subject:`CN=${h}`,issuer:u.subjectName,notBefore:new Date,notAfter:Up(365),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},publicKey:d.publicKey,signingKey:p,extensions:[new Rl(jl.digitalSignature|jl.keyEncipherment,!0),new Pl(["client"===i?Cl.clientAuth:Cl.serverAuth]),new $l(g),await Ul.create(d.publicKey),await Bl.create(u)]});return{cert:m,certPem:m.toString("pem"),privateKeyPem:await $p(d.privateKey),caCertPem:c,publicKeyFingerprint:y}}function eh(e){return`${e.trimEnd()}\n`}function th(e,t,r){const i=Bp("node:fs"),n=Bp("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 rh(e){const t=e.toRawHostName();return t.startsWith("_.")?`*.${t.slice(2)}`:t}function ih(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:Fp(t)}}async function nh(e,t,r,i,n){const o=function(e){const t=e.extensions.find((e=>e instanceof $l)),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",Op());return`sha256:${Mp(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:zp(t,"cert"),chain:zp(t,"chain"),fullchain:zp(t,"fullchain"),ca:zp(t,"ca")},did_binding:ih(e),updated_at:c,generation:`${c.replace(/[-:.]/g,"")}-${s}`}}const oh="test test test test test test test test test test test junk",sh=2147483648,ah=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ch=(1n<<64n)-1n,uh=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],lh=[[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 ph(e,t=""){return o.pbkdf2Sync(n.Buffer.from(e.normalize("NFKD"),"utf8"),n.Buffer.from(`mnemonic${t}`.normalize("NFKD"),"utf8"),2048,64,"sha512")}function hh(e,t){return o.createHmac("sha512",e).update(t).digest()}function dh(e){const t=n.Buffer.alloc(4);return t.writeUInt32BE(e>>>0,0),t}function fh(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 yh(e,t,r){const i=hh(t,n.Buffer.concat([n.Buffer.from([0]),e,dh(r+sh)]));return{key:i.subarray(0,32),chainCode:i.subarray(32)}}function gh(e,t,r){let i=function(e){const t=hh("ed25519 seed",e);return{key:t.subarray(0,32),chainCode:t.subarray(32)}}(ph(e,t));for(const n of[9777,0,r])i=yh(i.key,i.chainCode,n);return n.Buffer.from(i.key)}function mh(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`}(gh(e,t??"",r));return{privateKeyPem:i,publicKeyX:fh(i)}}function vh(e){return mh(oh,void 0,e)}function wh(e){const t=e.toString(16).padStart(64,"0");return n.Buffer.from(t,"hex")}function bh(e){return BigInt(`0x${e.toString("hex")}`)}function Sh(e,t){const r=o.createECDH("secp256k1");return r.setPrivateKey(e),r.getPublicKey(void 0,t?"compressed":"uncompressed")}function Ah(e,t,r){const i=hh(t,r>=sh?n.Buffer.concat([n.Buffer.from([0]),e,dh(r)]):n.Buffer.concat([Sh(e,!0),dh(r)])),o=bh(i.subarray(0,32));if(o>=ah)throw new Error(`invalid secp256k1 child tweak at index ${r}`);const s=(o+bh(e))%ah;if(0n===s)throw new Error(`invalid secp256k1 child key at index ${r}`);return{privateKey:wh(s),chainCode:i.subarray(32)}}function Eh(e){return`m/44'/60'/0'/0/${e}`}function kh(e,t){if(0===t)return e&ch;const r=BigInt(t);return(e<<r|e>>64n-r)&ch}function xh(e){for(const t of uh){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]^kh(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])&ch;for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)n[r+(2*t+3*r)%5*5]=kh(e[t+5*r],lh[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]&ch&n[(t+2)%5+5*r])&ch;e[0]=(e[0]^t)&ch}}function _h(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);xh(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 Nh(e){const t=e.toString("hex"),r=_h(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 Ih(e,t,r){let i=function(e){const t=hh("Bitcoin seed",e),r=t.subarray(0,32),i=bh(r);if(i<=0n||i>=ah)throw new Error("invalid secp256k1 master key");return{privateKey:n.Buffer.from(r),chainCode:t.subarray(32)}}(ph(e,t??""));for(const n of function(e){return[2147483692,2147483708,sh,0,e]}(r))i=Ah(i.privateKey,i.chainCode,n);const o=Sh(i.privateKey,!1),s=Sh(i.privateKey,!0),a=_h(o.subarray(1)),c=i.privateKey.toString("hex");return{derivationPath:Eh(r),privateKey:`0x${c}`,privateKeyHex:c,publicKeyCompressedHex:s.toString("hex"),publicKeyUncompressedHex:o.toString("hex"),address:Nh(a.subarray(12))}}function Th(e){return Ih(oh,void 0,e)}const Bh={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},Oh={alice:1,bob:2,charlie:3,dave:4},Ch=Object.fromEntries(Object.entries(Bh).map((([e,t])=>[e,vh(t)]))),Dh=Object.fromEntries(Object.entries(Oh).map((([e,t])=>[e,Th(t)]))),jh=Th(0);function Ph(e){const t=Ch[e];if(!t)throw new Error(`unknown dev test key pair id: ${e}`);return t}const Rh="ood1",Uh="wan",$h=i.DEFAULT_EXPIRE_TIME,Mh="provision_activation.lock",Lh="zone_dns_records.json",Vh="zone_document.jwt";class Hh extends Error{constructor(e,t,r={}){super(t),this.name="ActivationError",this.code=e,this.details=r}}function Kh(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 Hh("RUNTIME_UNSUPPORTED",`buckyos provision cannot load builtin module ${e} in this runtime (Node >= 22.13 or Deno >= 2.2 is required)`)}function Fh(){var e;return"win32"===(null==(e=globalThis.process)?void 0:e.platform)}function zh(e,t){const r=Kh("node:path");return r.relative(e,t).split(r.sep).join("/")}function Wh(e){return Kh("node:crypto").createHash("sha256").update(e,"utf8").digest("hex")}function Jh(){return Kh("node:crypto").randomBytes(6).toString("hex")}function qh(e){const t=Kh("node:fs");try{return t.lstatSync(e)}catch(r){const e=r.code;if("ENOENT"===e||"ENOTDIR"===e)return null;throw r}}function Gh(e){const t=Kh("node:fs");try{return t.statSync(e)}catch(r){if("ENOENT"===r.code||"ENOTDIR"===r.code)return null;throw r}}function Xh(e){var t;return!0===(null==(t=Gh(e))?void 0:t.isDirectory())}function Yh(e){var t;return!0===(null==(t=Gh(e))?void 0:t.isFile())}function Zh(e){const t=Kh("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 Qh(e){return JSON.stringify(e,null,2)}function ed(e,t,r,i){const n=Kh("node:fs"),o=Kh("node:path"),s=o.dirname(e);if(n.mkdirSync(s,{recursive:!0,mode:i}),Fh()||n.chmodSync(s,i),qh(e))throw new Error(`refusing to overwrite existing file: ${e}`);const a=o.join(s,`.${o.basename(e)}.provision-${Jh()}`);try{n.writeFileSync(a,t,{mode:r,flag:"wx"}),Fh()||n.chmodSync(a,r),n.renameSync(a,e)}finally{qh(a)&&n.rmSync(a,{force:!0})}}function td(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 Hh("INVALID_ARGUMENT",`invalid did:web domain: ${e}`,{field:"domain"});return t}function rd(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 Hh("INVALID_ARGUMENT","owner name must be a lowercase DNS label (letters, digits, and hyphens)",{field:"owner_name"});return t}function id(e){const t=e??2980;if(!Number.isInteger(t)||t<1||t>65535)throw new Hh("INVALID_ARGUMENT",`invalid RTCP port: ${String(e)}`,{field:"rtcp_port"});return t}function nd(e){const t=(null==e?void 0:e.trim())||void 0;if(void 0===t)return;if(0===Kh("node:net").isIP(t))throw new Hh("INVALID_ARGUMENT",`invalid public IP address: ${t}`,{field:"public_ip"});return t}function od(e){if("string"!=typeof e||e.length<8)throw new Hh("INVALID_ARGUMENT","administrator password must contain at least 8 characters",{field:"admin_password"});return e}function sd(e,t){return i.hashPassword(e,t,null)}function ad(e,t){const r=[];if(t){const i=Kh("node:net");r.push({type:6===i.isIP(t)?"AAAA":"A",name:e,value:t})}return r}function cd(){const e=Kh("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 Hh("KEY_GENERATION_FAILED","generated Ed25519 public key has no x coordinate");return{privateKeyPem:t.export({format:"pem",type:"pkcs8"}).toString(),publicKeyX:i.x}}function ud(e){const t=Kh("node:path");if("string"!=typeof e.rootDir||0===e.rootDir.trim().length)throw new Hh("INVALID_ARGUMENT","target root is required",{field:"root"});if("string"!=typeof e.ownerKeyBackupPath||0===e.ownerKeyBackupPath.trim().length)throw new Hh("INVALID_ARGUMENT","owner key backup path is required",{field:"owner_key_backup"});const r=td(e.domain),n=new i.DID("web",r);return{rootDir:t.resolve(e.rootDir),domain:r,ownerName:rd(e.ownerName),ownerKeyBackupPath:t.resolve(e.ownerKeyBackupPath),rtcpPort:id(e.rtcpPort),guestAccess:e.guestAccess??!1,publicIp:nd(e.publicIp),ownerDid:n,zoneDid:n,deviceDid:y(Rh,n)}}function ld(e){const t=Kh("node:path");return new qp(t.join(e,"local","identity"),t.join(e,"security"))}function pd(e,t,r){const i=Kh("node:path"),n=i.join(e,"etc"),o=f(ld(e),r);return{etcDir:n,lockPath:i.join(n,Mh),nodeIdentityPath:i.join(n,"node_identity.json"),startConfigPath:i.join(n,"start_config.json"),zoneDocumentJwtPath:i.join(n,Vh),gatewayParamsPath:i.join(n,"node_gateway_params.json"),dnsRecordsPath:i.join(n,Lh),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 hd(e,t){const r=(t,r,i,n)=>({path:zh(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,!1),r(t.gatewayParamsPath,"gateway_params",!0,!1),r(t.nodeIdentityPath,"node_identity",!0,!1)]}function dd(e){return{path:e.path,role:e.role,required:e.required,secret:e.secret}}function fd(e){if(!qh(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=Zh(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 yd(e,t){const r=Kh("node:fs"),i=Kh("node:path"),n=i.join(i.dirname(e),`.${Mh}.${Jh()}`);try{r.writeFileSync(n,Qh(t),{mode:384,flag:"wx"}),r.renameSync(n,e)}finally{qh(n)&&r.rmSync(n,{force:!0})}}function gd(e){const t=Kh("node:fs");return Xh(e)?t.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name)).sort():[]}function md(e){try{return i.getXFromJwk(e)}catch{return null}}async function vd(e){const t=Kh("node:path"),r=t.resolve(String(e??"")),n=i.buckyosGetUnixTimestamp(),o=[],s=[],a=e=>({rootDir:r,state:e,startupRequired:"configured"===e,observedAt:n,zoneDid:null,ownerDid:null,deviceDid:null,deviceName:null,accessHostname:null,files:[],problems:o,warnings:s,lock:null});if(!Xh(r))return o.push({code:"ROOT_MISSING",message:`BUCKYOS_ROOT does not exist: ${r}`}),a("not_installed");const c=["bin","etc"].filter((e=>!Xh(t.join(r,e))));if(c.length>0){for(const e of c)o.push({code:"INSTALL_INCOMPLETE",message:`installed BuckyOS directory is missing: ${t.join(r,e)}`});return a("not_installed")}const u=t.join(r,"etc"),l=fd(t.join(u,Mh)),p=function(e,t){if(!Yh(e))return{nodeIdentity:null,zoneDid:null,deviceDid:null};try{const r=Zh(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}}}(t.join(u,"node_identity.json"),o);let h=p.zoneDid,d=p.deviceDid;const g=gd(t.join(r,"local","identity")),m=gd(t.join(r,"security")),v=function(e,t){const r=Kh("node:fs");return Xh(e)?r.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isFile()&&t(e.name))).map((e=>e.name)).sort():[]}(u,(e=>e.endsWith(".zone.json")));if(!h&&v.length>0){const e=v[0].slice(0,-10);e.endsWith(".did")||(h=new i.DID("web",e))}!d&&h&&(d=y(Rh,h));const w=[...g,...m].filter((e=>!d||e!==t.basename(f(ld(r),d).publicDir))),b=[];let S=null;if(h&&d){S=pd(r,h,d);for(const e of hd(r,S))b.push({...dd(e),present:Yh(e.absolutePath)})}else{for(const[e,r,i]of[["node_identity.json","node_identity",!0],["start_config.json","start_config",!0],[Vh,"zone_document_jwt",!0],["node_gateway_params.json","gateway_params",!0],[Lh,"dns_records",!1]])b.push({path:`etc/${e}`,role:r,required:i,secret:!1,present:Yh(t.join(u,e))});for(const e of v)b.push({path:`etc/${e}`,role:"zone_boot_override",required:!0,secret:!1,present:!0})}const A=b.find((e=>"gateway_params"===e.role)),E=!0===(null==A?void 0:A.present)&&function(e){try{const t=Zh(e).params;return!!t&&"object"==typeof t&&"did:bns:unactivated.local"===t.device_did}catch{return!1}}(t.join(u,"node_gateway_params.json"));A&&E&&(A.present=!1);const k=b.filter((e=>e.present&&"dns_records"!==e.role)),x=b.filter((e=>e.required&&!e.present)),_=a("unactivated");_.files=b,_.lock=l,_.zoneDid=(null==h?void 0:h.toString())??null,_.deviceDid=(null==d?void 0:d.toString())??null,_.deviceName=p.nodeIdentity?String(p.nodeIdentity.device_name):d?Rh:null,_.ownerDid=p.nodeIdentity?String(p.nodeIdentity.owner_did):null,l&&s.push(l.corrupt?`activation lock ${l.path} exists but cannot be parsed`:`activation lock ${l.path} exists (stage=${l.stage??"unknown"}, committed=${l.committedFiles.length})`);for(const i of w)s.push(`unexpected identity directory: ${i}`);if(0===k.length&&0===w.length&&!l&&0===o.length)return _.state="unactivated",_;if(x.length>0||!S||w.length>0&&0===k.length){for(const e of x)o.push({code:"FILE_MISSING",message:`${e.path} is missing`});return _.state="partial",_}const N=await async function(e,t,r,n){var o,s,a;const c=Kh("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 g=y(String(u.device_name),p).toString();if(h.toString()!==g&&l("DEVICE_DID_MISMATCH",`device DID ${h.toString()} is not ${g}`),!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=Zh(t.startConfigPath)}catch(O){l("START_CONFIG_UNREADABLE",`etc/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",`etc/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",`etc/start_config.json is missing ${t}`);m.zone_name!==p.toString()&&l("START_CONFIG_ZONE",`etc/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",`etc/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&&md(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","etc/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","etc/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",`etc/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,zh(e,t.deviceDocJwtPath)))?void 0:s.trim())??null,E=(null==(a=b(t.deviceMiniDocJwtPath,zh(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=Zh(t.zoneBootOverridePath);JSON.stringify(r)!==JSON.stringify(x)&&l("BOOT_OVERRIDE_MISMATCH",`${zh(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?md(r.publicKeyJwk):null,B||l("DEVICE_DOCUMENT","device document has no #main_key");try{Zh(t.didJsonPath).id!==h.toString()&&l("DEVICE_DID_JSON",`${zh(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(!Fh()){const e=qh(t.devicePrivateKeyPath);e&&63&e.mode&&l("DEVICE_PRIVATE_KEY_MODE","device private key is readable by other users")}}return{ownerDid:d,accessHostname:v}}(r,S,p,o);return _.ownerDid=N.ownerDid??_.ownerDid,_.accessHostname=N.accessHostname??(h?h.toRawHostName():null),l&&"committed"!==l.stage&&o.push({code:"ACTIVATION_INTERRUPTED",message:`activation lock is still at stage ${l.stage??"unknown"}; the commit did not finish cleanly`}),_.state=0===o.length?"configured":"invalid",_.startupRequired="configured"===_.state,_}async function wd(e){const t=ud(e),r=await vd(t.rootDir),i=[],n=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`}}}(r);n&&i.push(n);const o=function(e,t){const r=Kh("node:path").dirname(e),i=Xh(r),n=null!==qh(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}}(t.ownerKeyBackupPath,i),s=pd(t.rootDir,t.zoneDid,t.deviceDid);return{ready:0===i.length,rootDir:t.rootDir,state:r.state,domain:t.domain,ownerName:t.ownerName,ownerDid:t.ownerDid.toString(),zoneDid:t.zoneDid.toString(),deviceDid:t.deviceDid.toString(),deviceName:Rh,accessHostname:t.domain,rtcpPort:t.rtcpPort,guestAccess:t.guestAccess,publicIp:t.publicIp??null,dnsRecords:ad(t.domain,t.publicIp),ownerKeyBackup:o,plannedFiles:hd(t.rootDir,s).map(dd),problems:i,status:r}}function bd(e){const t=e.problems[0];return new Hh(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})}function Sd(e,t,r,i){switch(e.role){case"device_private_key":return r.privateKeyPem;case"device_document":return Qh(t.deviceDocument);case"device_document_jwt":return t.deviceDocJwt;case"device_mini_document_jwt":return t.deviceMiniDocJwt;case"zone_boot_override":return Qh(t.bootDocument);case"zone_document_jwt":return t.zoneDocumentJwt;case"dns_records":return Qh({hostname:i,records:t.dnsRecords});case"start_config":return Qh(t.startConfig);case"gateway_params":return Qh(t.gatewayParams);case"node_identity":return Qh(t.nodeIdentity)}}function Ad(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 Ed=1743478939,kd=2058838939;function xd(e){const t=e.split(".");return[Number(t[0])||0,Number(t[1])||0]}function _d(){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]=xd(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]=xd(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 Nd(e){_d();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 Id(e,t){const r=Nd("node:fs"),i=Nd("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,t),console.log(`# Write file: ${e}`)}function Td(e,t){Id(e,JSON.stringify(t,null,2))}function Bd(e){const t=Nd("node:fs");return JSON.parse(t.readFileSync(e,"utf8"))}function Od(e){if(Array.isArray(e))return e.map(Od);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=Od(e[r]);return t}return e}function Cd(e,t){return t||(Ch[e]?Ch[e]:Ch[`${e}.owner`]?Ch[`${e}.owner`]:(console.log(`Warning: Key pair for user ${e} not found, using devtest key pair`),Ph("devtest")))}function Dd(e,t,r){return r||Ph(`${e}.${t}`)}function jd(e){const t=Nd("node:path");return new qp(t.join(e,"local","identity"),t.join(e,"security"))}class Pd{constructor(e){_d(),this.dbPath=e}connect(){const{DatabaseSync:e}=Nd("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 Rd(){var e;const t=(null==(e=globalThis.process)?void 0:e.arch)??"";return"x64"===t?"amd64":"arm64"===t?"aarch64":t}function Ud(){var e;const t=(null==(e=globalThis.process)?void 0:e.platform)??"";return"darwin"===t?"apple":"win32"===t?"windows":t}function $d(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}function Md(e){const t={...e},r=(e,r)=>{e in t&&r(t[e])&&delete t[e]};return r("did",(e=>null==e)),r("name",(e=>""===e)),r("author",(e=>""===e)),r("owner",(e=>null==e||"did:undefined:undefined"===e)),r("copyright",(e=>null==e)),r("tags",(e=>Array.isArray(e)&&0===e.length)),r("categories",(e=>Array.isArray(e)&&0===e.length)),r("base_on",(e=>null==e)),r("directory",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),r("references",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),r("exp",(e=>0===e)),r("size",(e=>0===e)),r("content",(e=>""===e)),r("version_tag",(e=>null==e)),r("deps",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),t}function Ld(e){const t=Md(e),[r]=i.buildNamedObjectByJson("pkg",t);return r.toString()}class Vd{constructor(e){_d(),this.dbPath=e}connect(){const{DatabaseSync:e}=Nd("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=$d(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 Hd=[{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"}],Kd="0.7.0";function Fd(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.ACTIVATION_DEFAULT_RTCP_PORT=2980,exports.ACTIVATION_DEVICE_NAME=Rh,exports.ACTIVATION_DOCUMENT_VALIDITY_SECONDS=$h,exports.ACTIVATION_LOCK_FILE_NAME=Mh,exports.ACTIVATION_MIN_PASSWORD_LENGTH=8,exports.ACTIVATION_NET_ID=Uh,exports.ActivationError=Hh,exports.DEVICE_DOC_JWT_FILE_NAME=s,exports.DEVICE_MINI_DOC_JWT_FILE_NAME=a,exports.DEV_TEST_EVM_ACCOUNTS=Dh,exports.DEV_TEST_EVM_SEED_SENDER=jh,exports.DEV_TEST_EVM_SEED_SENDER_INDEX=0,exports.DEV_TEST_EVM_USER_INDEXES=Oh,exports.DEV_TEST_KEYS=Ch,exports.DEV_TEST_KEY_INDEXES=Bh,exports.DEV_TEST_MNEMONIC=oh,exports.DevSnDb=Pd,exports.IDENTITY_MATERIALS=Pp,exports.IDENTITY_USAGES=jp,exports.IdentityRoots=qp,exports.KERNEL_SERVICE_DOC_VERSION=Kd,exports.MetaIndexDb=Vd,exports.NODE_GATEWAY_PARAMS_FILE_NAME=c,exports.PROVISION_BASE_TIME=Ed,exports.PROVISION_DEFAULT_EXP=kd,exports.ZONE_DNS_RECORDS_FILE_NAME=Lh,exports.ZONE_DOCUMENT_JWT_FILE_NAME=Vh,exports.activateOfflineZone=async function(e){const t=Kh("node:fs"),r=ud(e),n=od(e.adminPassword),o=await wd(e);if(!o.ready)throw bd(o);const s=e.ownerKeyPair??cd(),a=e.deviceKeyPair??cd(),c=await async function(e,t,r,n){const o=i.buckyosGetUnixTimestamp(),s=o+$h,a=i.createJwkByX(r.publicKeyX),c=i.createJwkByX(n.publicKeyX),u=e.ownerDid.toString(),l=e.zoneDid.toString(),p=e.deviceDid.toString(),d=i.newOwnerDocument({did:e.ownerDid,name:e.ownerName,displayName:e.ownerName,publicKeyJwk:a,now:o});d.exp=s,i.ownerDocumentSetDefaultZoneDid(d,e.zoneDid);const f=i.ownerDocumentToOrderedJson(d),y=i.oodDescriptionToString(i.parseOODDescription(`${Rh}@${Uh}`)),g=await i.encodeZoneBootDocument(i.newZoneBootDocument({id:e.zoneDid,oods:[y],exp:s}),r.privateKeyPem),v=i.decodeJwtClaimWithoutVerify(g),w=m(Rh,c,e.deviceDid,o);delete w.support_container,w.owner=u,w.zone_did=l,w.net_id=Uh,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={[Rh]:b},k.mini_device_jwts={[Rh]: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 Hh("ZONE_DOCUMENT_TOO_LARGE","zone document JWT exceeds the 4096 byte inline limit");return{documentIat:o,documentExp:s,ownerDocument:f,bootDocument:v,bootJwt:g,deviceDocument:b,deviceDocJwt:S,deviceMiniDocJwt:E,zoneDocumentJwt:x,nodeIdentity:h({zoneDid:e.zoneDid,ownerDid:e.ownerDid,ownerPublicKey:a,deviceName:Rh,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:sd(e.ownerName,t),guest_access:e.guestAccess,friend_passcode:"",enabled_features:{},ai_provider_config:{},owner_telegram_account_id:""},gatewayParams:{params:{device_did:p}},dnsRecords:ad(e.domain,e.publicIp)}}(r,n,s,a),u=pd(r.rootDir,r.zoneDid,r.deviceDid),l=hd(r.rootDir,u),p=[],d={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=Kh("node:fs");try{r.writeFileSync(e,Qh(t),{mode:384,flag:"wx"})}catch(i){if("EEXIST"===i.code)throw new Hh("ACTIVATION_IN_PROGRESS",`another activation holds the lock ${e}; inspect it with provision status`,{lock_file:e,lock:fd(e)});throw i}}(u.lockPath,d);const f=()=>{try{t.rmSync(u.lockPath,{force:!0})}catch{}};let y;try{y=await wd(e)}catch(b){throw f(),b}const g=y.problems.filter((e=>"ACTIVATION_IN_PROGRESS"!==e.code));if(g.length>0)throw f(),bd({...y,problems:g});for(const i of l)if(qh(i.absolutePath))throw f(),new Hh("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=Kh("node:fs");r.writeFileSync(e,t,{mode:384,flag:"wx"}),Fh()||r.chmodSync(e,384)}(r.ownerKeyBackupPath,s.privateKeyPem)}catch(b){f();const e=b.code;throw new Hh("EEXIST"===e?"OWNER_KEY_BACKUP_EXISTS":"OWNER_KEY_BACKUP_FAILED",`owner key backup could not be saved: ${b instanceof Error?b.message:String(b)}`,{owner_key_backup:{path:r.ownerKeyBackupPath,saved:!1},committed_files:[]})}d.stage="backup_saved";const v=[],w=(e,t)=>{throw new Hh("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:v,lock_file:u.lockPath,recovery:Ad(u.lockPath,r.ownerKeyBackupPath,v.map((e=>e.path)))})};try{yd(u.lockPath,d)}catch(b){w(b,"lock:backup_saved")}d.stage="committing";for(const i of l){const e=Sd(i,c,a,r.domain);try{ed(i.absolutePath,e,i.mode,i.dirMode)}catch(b){w(b,i.path)}v.push({...dd(i),sha256:i.secret?null:Wh(e)}),d.committed=v.map((e=>e.path));try{yd(u.lockPath,d)}catch(b){w(b,`lock:${i.path}`)}}d.stage="committed";try{yd(u.lockPath,d),t.rmSync(u.lockPath,{force:!0})}catch(b){p.push(`activation completed but the lock ${u.lockPath} could not be removed: ${b instanceof Error?b.message:String(b)}`)}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:Rh,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:v,warnings:p}},exports.assertProvisionRuntime=_d,exports.bindDeviceDocumentDid=g,exports.buildActivationDnsRecords=ad,exports.buildDeviceDid=y,exports.buildDidDocs=function(e,t){_d();const r=Nd("node:path"),n=(null==t?void 0:t.version)??Kd,o=(null==t?void 0:t.now)??i.buckyosGetUnixTimestamp(),s=[];for(const i of Hd){const t=Fd(i.uniqueId),a=Od({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`);Td(c,a),s.push(c)}return s},exports.calcPkgMetaObjId=Ld,exports.checkOfflineActivation=wd,exports.createCa=Zp,exports.createCertFromCa=async function(e,t,r,i){const n=Bp("node:fs"),o=Bp("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 Qp(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=Bp("node:fs"),o=function(e){return e instanceof qp?e:qp.fromEnvOrBuckyosRoot(e)}(r),s=i.usage??"server",a=Vp(t),c=a.toRawHostUri(),u=Lp(c),l=o.publicDir(a.toString()),p=o.securityDir(a.toString()),h=Jp(l,p,s),d=i.hostnames&&i.hostnames.length>0?i.hostnames:[rh(a)],f=i.uriSans??[a.toString()];n.mkdirSync(l,{recursive:!0,mode:493}),n.mkdirSync(p,{recursive:!0,mode:448});const y=await Qp(e,d,f,s),g=eh(y.certPem),m=eh(y.caCertPem),v=m,w=`${g}${v}`;var b,S,A;return th(h.privateKey,y.privateKeyPem,384),th(h.cert,g,420),th(h.chain,v,420),th(h.fullchain,w,420),th(h.ca,m,420),b=h.metadata,S=await nh(a,s,c,u,y),A=420,th(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){_d();const t=Nd("node:path"),r=e.envDir,n=Bd(t.join(r,"user_config.json")).name;if("string"!=typeof n||!n)throw new Error("user_config.json missing name field");const o=Bd(t.join(r,"zone_config.json")),s=i.DID.fromStr(o.id),a=Cd(n,e.ownerKeyPair),c=Dd(n,e.deviceName,e.deviceKeyPair),u=t.join(r,e.deviceName),l=new i.DID("bns",n),p=y(e.deviceName,s),d=m(e.deviceName,i.createJwkByX(c.publicKeyX),p,e.now);d.support_container=!0,delete d.support_container,void 0!==e.netId&&(d.net_id=e.netId),d.owner=l.toString(),d.zone_did=s.toString(),console.log(`input net_id: ${e.netId}, device_config.net_id: ${d.net_id}`);const f=await i.encodeDeviceDocument(d,a.privateKeyPem);console.log(`${e.deviceName} device jwt: ${f}`);const g=i.newDeviceMiniDocumentByDeviceDocument(d),v=await i.deviceMiniDocumentToJwt(g,a.privateKeyPem);Id(t.join(u,"device_mini_config.jwt"),v);const w=h({zoneDid:s,ownerDid:l,ownerPublicKey:i.createJwkByX(a.publicKeyX),deviceName:e.deviceName,deviceDid:p,zoneIat:Ed});if(b(u,jd(u),w,d,f,v,c.privateKeyPem),e.deviceName.startsWith("ood")){const e=Od({admin_password_hash:sd(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"});Td(t.join(u,"start_config.json"),e)}return console.log(`Successfully created node configuration: ${n}.${e.deviceName}`),i.encodeDeviceDocument(d,c.privateKeyPem)},exports.createSnConfigs=async function(e){_d();const t=Nd("node:path"),r=t.join(e.outputDir,"sn_server"),n=Ph("sn_owner"),o=Ph("sn_server"),s=kd;Id(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)});Td(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",Td(t.join(r,"sn_device_config.json"),i.deviceDocumentToOrderedJson(l)),Id(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=Od({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"}});Td(t.join(r,"params.json"),h),console.log("- Created params.json.");const d=new Pd(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){_d();const t=Nd("node:path"),r=e.rtcpPort??2980,n=e.outputDir,o=kd,s=Cd(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}`}Id(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});Td(t.join(n,"user_config.json"),i.ownerDocumentToOrderedJson(p)),console.log(`Created owner config for ${e.username}`);const h=i.parseOODDescription(e.oodName),d=Dd(e.username,h.name,e.deviceKeyPair);let f,g=c;h.netId&&(h.netId.startsWith("wan")&&(g=void 0),h.netId.startsWith("wan_dyn")&&c&&(f=`https://${c}/kapi/sn`));const v=i.oodDescriptionToString(h),w=i.newZoneBootDocument({oods:[v],sn:g,exp:o}),b=u.toRawHostName();Td(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),Td(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=y(h.name,u),I=m(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 Td(t.join(n,"zone_txt_record.json"),T),console.log(`Successfully created user environment configuration: ${e.username}`),T},exports.decodeDeviceDocumentWithoutVerify=S,exports.deriveDevTestEvmAccount=Th,exports.deriveDevTestEvmAccountFromMnemonic=Ih,exports.deriveDevTestKeyPair=vh,exports.deriveDevTestKeyPairFromMnemonic=mh,exports.devTestKeccak256=_h,exports.deviceIdentityPathsForRoots=f,exports.didWebDocumentUrl=Fp,exports.encodeIdentityDirName=Lp,exports.ensureCa=async function(e,t="devtest"){const r=Bp("node:fs"),i=Bp("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 Yp(new Ip(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`),Zp(e,t)):(console.log(`Use existing CA at: ${n}`),{caCertPath:n,caKeyPath:o})}return Zp(e,t)},exports.generateProvisionKeyPair=cd,exports.getDevTestEvmAccountByIndex=function(e){return Th(e)},exports.getDevTestEvmAccountByUsername=function(e){const t=Dh[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=Ph,exports.getDevTestKeyPairByIndex=function(e){return vh(e)},exports.hashAdminPassword=sd,exports.identityDirName=Kp,exports.identityFileName=zp,exports.identityRawHostUri=Hp,exports.inspectActivationRoot=vd,exports.loadDeviceDocJwtForRoots=v,exports.loadDeviceMiniDocJwtForRoots=function(e,t){return u("node:fs").readFileSync(f(e,t).deviceMiniDocJwt,"utf8")},exports.loadLocalDeviceDocumentForRoots=async function(e,t,r){const n=v(e,t.device_did),o=r?await i.verifyJwtEdDSA(n,t.owner_public_key):S(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=d,exports.newDeviceDocumentByJwkWithDid=m,exports.newLocalNodeIdentityConfig=h,exports.nodeTestIdentityRoots=jd,exports.normalizePackageMetaForObjId=Md,exports.registerDeviceToSn=async function(e,t,r,n){_d();const o=Nd("node:path"),s=Nd("node:fs"),a=Nd("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=d(u),p=i.DID.fromStr(l.owner_did).id,h=f(jd(c),l.device_did),y=s.readFileSync(h.deviceDocJwt,"utf8"),g=s.readFileSync(h.deviceMiniDocJwt,"utf8"),m=await i.verifyJwtEdDSA(y,l.owner_public_key),v=m.id;let w;try{w=i.parseOODDescription(r)}catch{w={name:r,nodeType:"Device"}}try{const n=Bd(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=Nd("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:Rd(),os:Ud(),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 Pd(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){_d();const n=Nd("node:path"),o=Bd(n.join(e,t,"user_config.json")).name;if("string"!=typeof o||!o)throw new Error("user_config.json missing name field");const s=Bd(n.join(e,t,"zone_config.json")),a=i.DID.fromStr(s.id);let c;"bns"!==a.method&&(c=a.toHostName());const u=Bd(n.join(e,t,"zone_txt_record.json")),l=new Pd(r),p=JSON.stringify(Od({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=b,exports.saveNodeGatewayParams=w,exports.setPkgMeta=async function(e,t){_d();const r=Nd("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=Ld(o),a=new Vd(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=Fd,exports.validateAdminPassword=od,exports.validateOwnerName=rd,exports.validatePublicIp=nd,exports.validateRtcpPort=id,exports.validateZoneDomain=td,exports.versionToInt=$d;
91
+ const pu="crypto.algorithm";const hu="crypto.algorithmProvider";var du;uc.registerSingleton(hu,class{getAlgorithms(){return uc.resolveAll(pu)}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 Fn({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 fu="1.3.36.3.3.2.8.1.1",yu=`${fu}.1`,gu=`${fu}.2`,mu=`${fu}.3`,vu=`${fu}.4`,wu=`${fu}.5`,bu=`${fu}.6`,Su=`${fu}.7`,Au=`${fu}.8`,Eu=`${fu}.9`,ku=`${fu}.10`,xu=`${fu}.11`,_u=`${fu}.12`,Nu=`${fu}.13`,Iu=`${fu}.14`,Tu="brainpoolP160r1",Bu="brainpoolP160t1",Ou="brainpoolP192r1",Cu="brainpoolP192t1",Du="brainpoolP224r1",ju="brainpoolP224t1",Pu="brainpoolP256r1",Ru="brainpoolP256t1",Uu="brainpoolP320r1",$u="brainpoolP320t1",Mu="brainpoolP384r1",Lu="brainpoolP384t1",Vu="brainpoolP512r1",Hu="brainpoolP512t1",Ku="ECDSA";let Fu=du=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Ku.toLowerCase())if("hash"in e){switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Js;case"sha-256":return qs;case"sha-384":return Gs;case"sha-512":return Xs}}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Ks;break;case"K-256":t=du.SECP256K1;break;case"P-384":t=Fs;break;case"P-521":t=zs;break;case Tu:t=yu;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}if(t)return new Fn({algorithm:Us,parameters:Kr.serialize(new ra({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case $s:return{name:Ku,hash:{name:"SHA-1"}};case Ls:return{name:Ku,hash:{name:"SHA-256"}};case Vs:return{name:Ku,hash:{name:"SHA-384"}};case Hs:return{name:Ku,hash:{name:"SHA-512"}};case Us:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Kr.parse(e.parameters,ra).namedCurve){case Ks:return{name:Ku,namedCurve:"P-256"};case du.SECP256K1:return{name:Ku,namedCurve:"K-256"};case Fs:return{name:Ku,namedCurve:"P-384"};case zs:return{name:Ku,namedCurve:"P-521"};case yu:return{name:Ku,namedCurve:Tu};case gu:return{name:Ku,namedCurve:Bu};case mu:return{name:Ku,namedCurve:Ou};case vu:return{name:Ku,namedCurve:Cu};case wu:return{name:Ku,namedCurve:Du};case bu:return{name:Ku,namedCurve:ju};case Su:return{name:Ku,namedCurve:Pu};case Au:return{name:Ku,namedCurve:Ru};case Eu:return{name:Ku,namedCurve:Uu};case ku:return{name:Ku,namedCurve:$u};case xu:return{name:Ku,namedCurve:Mu};case _u:return{name:Ku,namedCurve:Lu};case Nu:return{name:Ku,namedCurve:Vu};case Iu:return{name:Ku,namedCurve:Hu}}}return null}};Fu.SECP256K1="1.3.132.0.10",Fu=du=Fr([lc()],Fu),uc.registerSingleton(pu,Fu);const zu=Symbol("name"),Wu=Symbol("value");class Ju{constructor(e,t={},r=""){this[zu]=e,this[Wu]=r;for(const i in t)this[i]=t[i]}}Ju.NAME=zu,Ju.VALUE=Wu;class qu{static toString(e){const t=this.items[e];return t||e}}qu.items={[wa]:"sha1",[ba]:"sha224",[Sa]:"sha256",[Aa]:"sha384",[Ea]:"sha512",[sa]:"rsaEncryption",[ha]:"sha1WithRSAEncryption",[da]:"sha224WithRSAEncryption",[fa]:"sha256WithRSAEncryption",[ya]:"sha384WithRSAEncryption",[ga]:"sha512WithRSAEncryption",[Us]:"ecPublicKey",[$s]:"ecdsaWithSHA1",[Ms]:"ecdsaWithSHA224",[Ls]:"ecdsaWithSHA256",[Vs]:"ecdsaWithSHA384",[Hs]:"ecdsaWithSHA512",[sn]:"TLS WWW server authentication",[an]:"TLS WWW client authentication",[cn]:"Code Signing",[un]:"E-mail Protection",[ln]:"Time Stamping",[pn]:"OCSP Signing",[Ds]:"Signed Data"};class Gu{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[Ju.VALUE];o&&(n=` ${o}`),r.push(`${i}${e[Ju.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[Ju.NAME]=s,r.push(...this.serializeObj(e,t));else if(n instanceof Ju)n[Ju.NAME]=s,r.push(...this.serializeObj(n,t));else if(k.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[Ju.NAME]=s,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),i=k.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 Xu,Yu;Gu.oidSerializer=qu,Gu.algorithmSerializer=class{static toTextObject(e){const t=new Ju("Algorithm Identifier",{},qu.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Us:{const r=(new Fu).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Zu{get rawData(){return zr(this,Xu,"f")||Wr(this,Xu,Kr.serialize(this.asn),"f"),zr(this,Xu,"f")}constructor(...e){Xu.set(this,void 0),k.isBufferSource(e[0])?(this.asn=Kr.parse(e[0],e[1]),Wr(this,Xu,k.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Zu&&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 Kr.toString(this.rawData);case"text":return Gu.serialize(this.toTextObject());case"hex":return O.ToHex(this.rawData);case"base64":return O.ToBase64(this.rawData);case"base64url":return O.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 Ju(this.getTextName(),{},e)}}Xu=new WeakMap,Zu.NAME="ASN";class Qu extends Zu{constructor(...e){let t;t=k.isBufferSource(e[0])?k.toArrayBuffer(e[0]):Kr.serialize(new Gn({extnID:e[0],critical:e[1],extnValue:new sr(k.toArrayBuffer(e[2]))})),super(t,Gn)}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[Ju.NAME]===Qu.NAME&&(e[Ju.NAME]=qu.toString(this.type)),e}}class el{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[Yu]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(el.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(el.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=el.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(el.DEFAULT,e);return this}}Yu=Symbol.toStringTag,el.DEFAULT="default";const tl=new el,rl=/^[0-2](?:\.[1-9][0-9]*)+$/;class il{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(rl).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const nl=new il;function ol(e,t){return`\\${O.ToHex(O.FromUtf8String(t)).toUpperCase()}`}nl.register("CN","2.5.4.3"),nl.register("L","2.5.4.7"),nl.register("ST","2.5.4.8"),nl.register("O","2.5.4.10"),nl.register("OU","2.5.4.11"),nl.register("C","2.5.4.6"),nl.register("DC","0.9.2342.19200300.100.1.25"),nl.register("E","1.2.840.113549.1.9.1"),nl.register("G","2.5.4.42"),nl.register("I","2.5.4.43"),nl.register("SN","2.5.4.4"),nl.register("T","2.5.4.12");class sl{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 il,this.asn=new ni;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 ni?this.asn=e:k.isBufferSource(e)?this.asn=Kr.parse(e,ni):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||nl.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)||nl.get(e)}toString(){return this.asn.map((e=>e.map((e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${O.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,ol)}`)).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?`#${O.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(i)}return t}fromString(e){const t=new ni,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 ri([a])),n=s}return t}fromJSON(e){const t=new ni;for(const r of e){const e=new ri;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 ti({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=O.FromHex(t.slice(1));else{const i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:sl.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 Kr.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]||tl.get()):r=e[0]||tl.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const al="Cannot initialize GeneralName from ASN.1 data.",cl=`${al} Unsupported string format in use.`,ul=`${al} Value doesn't match to GUID regular expression.`,ll=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,pl="1.3.6.1.4.1.311.25.1",hl="1.3.6.1.4.1.311.20.2.3",dl="dns",fl="dn",yl="email",gl="ip",ml="url",vl="guid",wl="upn",bl="id";class Sl extends Zu{constructor(...e){let t;if(2===e.length)switch(e[0]){case fl:{const r=new sl(e[1]).toArrayBuffer(),i=Kr.parse(r,ni);t=new ci({directoryName:i});break}case dl:t=new ci({dNSName:e[1]});break;case yl:t=new ci({rfc822Name:e[1]});break;case vl:{const r=new RegExp(ll,"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?O.ToHex(new Uint8Array(O.FromHex(e)).reverse()):e)).join("");t=new ci({otherName:new si({typeId:pl,value:Kr.serialize(new sr(O.FromHex(i)))})});break}case gl:t=new ci({iPAddress:e[1]});break;case bl:t=new ci({registeredID:e[1]});break;case wl:t=new ci({otherName:new si({typeId:hl,value:Kr.serialize(mr.toASN(e[1]))})});break;case ml:t=new ci({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=k.isBufferSource(e[0])?Kr.parse(e[0],ci):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=dl,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=yl,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=gl,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=ml,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=bl,this.value=e.registeredID;else if(null!=e.directoryName)this.type=fl,this.value=new sl(e.directoryName).toString();else{if(null==e.otherName)throw new Error(cl);if(e.otherName.typeId===pl){this.type=vl;const t=Kr.parse(e.otherName.value,sr),r=new RegExp(ll,"i").exec(O.ToHex(t));if(!r)throw new Error(ul);this.value=r.slice(1).map(((e,t)=>t<3?O.ToHex(new Uint8Array(O.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==hl)throw new Error(cl);this.type=wl,this.value=Kr.parse(e.otherName.value,Qr).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case fl:case dl:case vl:case gl:case bl:case wl:case ml:e=this.type.toUpperCase();break;case yl:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===bl&&(t=qu.toString(t)),new Ju(e,void 0,t)}}class Al extends Zu{constructor(e){let t;if(e instanceof Ni)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof ci)r.push(t);else{const e=Kr.parse(new Sl(t.type,t.value).rawData,ci);r.push(e)}t=new Ni(r)}else{if(!k.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Kr.parse(e,Ni)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new Sl(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[Ju.NAME]];Array.isArray(i)||(i=[],e[r[Ju.NAME]]=i),i.push(r)}return e}}Al.NAME="GeneralNames";const El="-{5}",kl="\\n",xl="\\n",_l=`${`${El}BEGIN (${`[^${kl}]+`}(?=${El}))${El}`}${xl}(?:((?:${`[^:${kl}]+`}: ${`(?:[^${kl}]+${xl}(?: +[^${kl}]+${xl})*)`})+))?${xl}?(${`(?:[a-zA-Z0-9=+/]+${xl})+`})${`${El}END \\1${El}`}`;class Nl{static isPem(e){return"string"==typeof e&&new RegExp(_l,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(_l,"g"),r=[];let i=null;for(;i=t.exec(e);){const e=i[3].replace(new RegExp(`[${kl}]+`,"g"),""),t={type:i[1],headers:[],rawData:O.FromBase64(e)},n=i[2];if(n){const e=n.split(new RegExp(xl,"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(!k.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:k.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:k.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=O.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")}}Nl.CertificateTag="CERTIFICATE",Nl.CrlTag="CRL",Nl.CertificateRequestTag="CERTIFICATE REQUEST",Nl.PublicKeyTag="PUBLIC KEY",Nl.PrivateKeyTag="PRIVATE KEY";class Il extends Zu{static isAsnEncoded(e){return k.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(Nl.isPem(e))return Nl.decode(e)[0];if(O.isHex(e))return O.FromHex(e);if(O.isBase64(e))return O.FromBase64(e);if(O.isBase64Url(e))return O.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=k.toUint8Array(e);if(t.length>0&&48===t[0])return k.toArrayBuffer(e);const r=O.ToBinary(e);if(Nl.isPem(r))return Nl.decode(r)[0];if(O.isHex(r))return O.FromHex(r);if(O.isBase64(r))return O.FromBase64(r);if(O.isBase64Url(r))return O.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){Il.isAsnEncoded(e[0])?super(Il.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?Nl.encode(this.rawData,this.tag):super.toString(e)}}class Tl extends Il{static async create(e,t=tl.get()){if(e instanceof Tl)return e;if(el.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new Tl(r)}if(e.publicKey)return e.publicKey;if(k.isBufferSource(e))return new Tl(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){Il.isAsnEncoded(e)?super(e,zn):super(e),this.tag=Nl.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]||tl.get()):t=e[0]||tl.get();let n=this.rawData;const o=Kr.parse(this.rawData,zn);return o.algorithm.algorithm===ua&&(n=function(e,t){return e.algorithm=new Fn({algorithm:sa,parameters:null}),t=Kr.serialize(e),t}(o,n)),t.subtle.importKey("spki",n,i,!0,r)}onInit(e){const t=uc.resolve(hu),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case sa:{const t=Kr.parse(e.subjectPublicKey,Ra),i=k.toUint8Array(t.modulus);r.publicExponent=k.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]||tl.get()):r=e[0]||tl.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=tl.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=tl.get();const i=Kr.parse(this.rawData,zn);return await t.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Kr.parse(this.rawData,zn);if(e.Algorithm=Gu.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===Us)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class Bl extends Qu{static async create(e,t=!1,r=tl.get()){if("name"in e&&"serialNumber"in e)return new Bl(e,t);const i=await Tl.create(e,r),n=await i.getKeyIdentifier(r);return new Bl(O.ToHex(n),t)}constructor(...e){if(k.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Ei({keyIdentifier:new Ai(O.FromHex(e[0]))});super(Si,e[1],Kr.serialize(t))}else{const t=e[0],r=t.name instanceof Al?Kr.parse(t.name.rawData,Ni):t.name,i=new Ei({authorityCertIssuer:r,authorityCertSerialNumber:O.FromHex(t.serialNumber)});super(Si,e[1],Kr.serialize(i))}}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,Ei);t.keyIdentifier&&(this.keyId=O.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?O.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Ei);return t.authorityCertIssuer&&(e["Authority Issuer"]=new Al(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}Bl.NAME="Authority Key Identifier";class Ol extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,xi);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new xi({cA:e[0],pathLenConstraint:e[1]});super(ki,e[2],Kr.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 Cl,Dl,jl;Ol.NAME="Basic Constraints",(Dl=Cl||(Cl={})).serverAuth="1.3.6.1.5.5.7.3.1",Dl.clientAuth="1.3.6.1.5.5.7.3.2",Dl.codeSigning="1.3.6.1.5.5.7.3.3",Dl.emailProtection="1.3.6.1.5.5.7.3.4",Dl.timeStamping="1.3.6.1.5.5.7.3.8",Dl.ocspSigning="1.3.6.1.5.5.7.3.9";class Pl extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,on);this.usages=t.map((e=>e))}else{const t=new on(e[0]);super(nn,e[1],Kr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>qu.toString(e))).join(", "),e}}Pl.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"}(jl||(jl={}));class Rl extends Qu{constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,Sn);this.usages=t.toNumber()}else{const t=new Sn(e[0]);super(mn,e[1],Kr.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Sn);return e[""]=t.toJSON().join(", "),e}}Rl.NAME="Key Usages";class Ul extends Qu{static async create(e,t=!1,r=tl.get()){const i=await Tl.create(e,r),n=await i.getKeyIdentifier(r);return new Ul(O.ToHex(n),t)}constructor(...e){if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,Rn);this.keyId=O.ToHex(t)}else{const t="string"==typeof e[0]?O.FromHex(e[0]):e[0],r=new Rn(t);super(Pn,e[1],Kr.serialize(r)),this.keyId=O.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Kr.parse(this.value,Rn);return e[""]=t,e}}Ul.NAME="Subject Key Identifier";class $l extends Qu{constructor(...e){k.isBufferSource(e[0])?super(e[0]):super(Bn,e[1],new Al(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,On);this.names=new Al(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}$l.NAME="Subject Alternative Name";class Ml{static register(e,t){this.items.set(e,t)}static create(e){const t=new Qu(e),r=this.items.get(t.type);return r?new r(e):t}}Ml.items=new Map;class Ll extends Qu{constructor(...e){var t;if(k.isBufferSource(e[0])){super(e[0]);const t=Kr.parse(this.value,$i);this.policies=t.map((e=>e.policyIdentifier))}else{const r=e[0],i=null!==(t=e[1])&&void 0!==t&&t,n=new $i(r.map((e=>new Ui({policyIdentifier:e}))));super(Oi,i,Kr.serialize(n)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new Ju("",{},qu.toString(e)))),e}}Ll.NAME="Certificate Policies",Ml.register(Oi,Ll);class Vl extends Qu{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map((e=>new Ji({distributionPoint:new Wi({fullName:[new ci({uniformResourceIdentifier:e})]})}))),r=new qi(t);super(Hi,e[1],Kr.serialize(r))}else{const t=new qi(e[0]);super(Hi,e[1],Kr.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,qi);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 Sl(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}Vl.NAME="CRL Distribution Points";class Hl extends Qu{constructor(...e){var t,r,i,n;if(k.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof bi){const t=new bi(e[0]);super(vi,e[1],Kr.serialize(t))}else{const t=e[0],r=new bi;Fl(r,t,hi,"ocsp"),Fl(r,t,di,"caIssuers"),Fl(r,t,fi,"timeStamping"),Fl(r,t,yi,"caRepository"),super(vi,e[1],Kr.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=[];Kr.parse(e.extnValue,bi).forEach((e=>{switch(e.accessMethod){case hi:this.ocsp.push(new Sl(e.accessLocation));break;case di:this.caIssuers.push(new Sl(e.accessLocation));break;case fi:this.timeStamping.push(new Sl(e.accessLocation));break;case yi:this.caRepository.push(new Sl(e.accessLocation))}}))}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Kl(e,"OCSP",this.ocsp),this.caIssuers.length&&Kl(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Kl(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Kl(e,"CA Repository",this.caRepository),e}}function Kl(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const i=new Ju("");r.forEach(((e,t)=>{const r=e.toTextObject(),n=`${r[Ju.NAME]} ${t+1}`;let o=i[n];Array.isArray(o)||(o=[],i[n]=o),o.push(r)})),e[t]=i}}function Fl(e,t,r,i){const n=t[i];if(n){(Array.isArray(n)?n:[n]).forEach((t=>{"string"==typeof t&&(t=new Sl("url",t)),e.push(new wi({accessMethod:r,accessLocation:Kr.parse(t.rawData,ci)}))}))}}Hl.NAME="Authority Info Access";class zl extends Qu{constructor(...e){k.isBufferSource(e[0])?super(e[0]):super(yn,e[1],new Al(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Kr.parse(e.extnValue,Ni);this.names=new Al(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}zl.NAME="Issuer Alternative Name";class Wl extends Zu{constructor(...e){let t;if(k.isBufferSource(e[0]))t=k.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map((e=>k.toArrayBuffer(e))):[];t=Kr.serialize(new Cn({type:r,values:i}))}super(t,Cn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new Ju("",{"":e}))),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[Ju.NAME]===Wl.NAME&&(e[Ju.NAME]=qu.toString(this.type)),e}}Wl.NAME="Attribute";class Jl extends Wl{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else{const t=new tu({printableString:e[0]});super(Rc,[Kr.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Kr.parse(this.values[0],tu);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[Ju.VALUE]=this.password,e}}Jl.NAME="Challenge Password";class ql extends Wl{constructor(...e){var t;if(k.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Xn;for(const e of t)r.push(Kr.parse(e.rawData,Gn));super(Uc,[Kr.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Kr.parse(this.values[0],Xn);this.items=e.map((e=>Ml.create(Kr.serialize(e))))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(const r of t)e[r[Ju.NAME]]=r;return e}}ql.NAME="Extensions";class Gl{static register(e,t){this.items.set(e,t)}static create(e){const t=new Wl(e),r=this.items.get(t.type);return r?new r(e):t}}Gl.items=new Map;const Xl="crypto.signatureFormatter";var Yl;let Zl=Yl=class{static createPssParams(e,t){const r=Yl.getHashAlgorithm(e);return r?new Ba({hashAlgorithm:r,maskGenAlgorithm:new Fn({algorithm:ka,parameters:Kr.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=uc.resolve(hu);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 Fn({algorithm:sa,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 Fn({algorithm:ha,parameters:null});case"sha-256":return new Fn({algorithm:fa,parameters:null});case"sha-384":return new Fn({algorithm:ya,parameters:null});case"sha-512":return new Fn({algorithm:ga,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=Yl.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Fn({algorithm:ua,parameters:Kr.serialize(t)})}return new Fn({algorithm:ua,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case sa:return{name:"RSASSA-PKCS1-v1_5"};case ha:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case fa:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case ya:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ga:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case ua:if(e.parameters){const t=Kr.parse(e.parameters,Ba);return{name:"RSA-PSS",hash:uc.resolve(hu).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Zl=Yl=Fr([lc()],Zl),uc.registerSingleton(pu,Zl);let Ql=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Fn({algorithm:wa});case"sha-256":return new Fn({algorithm:Sa});case"sha-384":return new Fn({algorithm:Aa});case"sha-512":return new Fn({algorithm:Ea})}return null}toWebAlgorithm(e){switch(e.algorithm){case wa:return{name:"SHA-1"};case Sa:return{name:"SHA-256"};case Aa:return{name:"SHA-384"};case Ea:return{name:"SHA-512"}}return null}};Ql=Fr([lc()],Ql),uc.registerSingleton(pu,Ql);class ep{addPadding(e,t){const r=k.toUint8Array(t),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,t=!1){let r=k.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=ep.namedCurveSize.get(r)||ep.defaultNamedCurveSize,n=new na,o=k.toUint8Array(t);return n.r=this.removePadding(o.slice(0,i),!0),n.s=this.removePadding(o.slice(i,i+i),!0),Kr.serialize(n)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Kr.parse(t,na),i=e.namedCurve,n=ep.namedCurveSize.get(i)||ep.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}}ep.namedCurveSize=new Map,ep.defaultNamedCurveSize=32;const tp="1.3.101.110",rp="1.3.101.111",ip="1.3.101.112",np="1.3.101.113";let op=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=ip;break;case"x25519":t=tp;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=ip;break;case"ed448":t=np}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=tp;break;case"x448":t=rp}}return t?new Fn({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case ip:return{name:"Ed25519"};case np:return{name:"EdDSA",namedCurve:"Ed448"};case tp:return{name:"X25519"};case rp:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};var sp,ap,cp,up,lp,pp,hp,dp,fp,yp,gp,mp,vp,wp,bp,Sp,Ap,Ep,kp,xp,_p,Np;op=Fr([lc()],op),uc.registerSingleton(pu,op);sp=new WeakMap,ap=new WeakMap,cp=new WeakMap,up=new WeakMap,lp=new WeakMap,pp=new WeakMap,hp=new WeakMap,dp=new WeakMap,class extends Il{get subjectName(){return zr(this,ap,"f")||Wr(this,ap,new sl(this.asn.certificationRequestInfo.subject),"f"),zr(this,ap,"f")}get subject(){return zr(this,cp,"f")||Wr(this,cp,this.subjectName.toString(),"f"),zr(this,cp,"f")}get signatureAlgorithm(){if(!zr(this,up,"f")){const e=uc.resolve(hu);Wr(this,up,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return zr(this,up,"f")}get signature(){return zr(this,lp,"f")||Wr(this,lp,this.asn.signature,"f"),zr(this,lp,"f")}get publicKey(){return zr(this,pp,"f")||Wr(this,pp,new Tl(this.asn.certificationRequestInfo.subjectPKInfo),"f"),zr(this,pp,"f")}get attributes(){return zr(this,hp,"f")||Wr(this,hp,this.asn.certificationRequestInfo.attributes.map((e=>Gl.create(Kr.serialize(e)))),"f"),zr(this,hp,"f")}get extensions(){if(!zr(this,dp,"f")){Wr(this,dp,[],"f");const e=this.getAttribute(Uc);e instanceof ql&&Wr(this,dp,e.items,"f")}return zr(this,dp,"f")}get tbs(){return zr(this,sp,"f")||Wr(this,sp,this.asn.certificationRequestInfoRaw||Kr.serialize(this.asn.certificationRequestInfo),"f"),zr(this,sp,"f")}constructor(e){const t=Il.isAsnEncoded(e)?[e,lu]:[e];super(t[0],t[1]),sp.set(this,void 0),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),this.tag=Nl.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=tl.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),i=uc.resolveAll(Xl).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=Kr.parse(this.rawData,lu),r=t.certificationRequestInfo,i=new Ju("",{Version:`${Yn[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new Ju("");for(const t of this.attributes){const r=t.toTextObject();e[r[Ju.NAME]]=r}i.Attributes=e}return e.Data=i,e.Signature=new Ju("",{Algorithm:Gu.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}.NAME="PKCS#10 Certificate Request";class Ip extends Il{get publicKey(){return zr(this,xp,"f")||Wr(this,xp,new Tl(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),zr(this,xp,"f")}get serialNumber(){if(!zr(this,yp,"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)),Wr(this,yp,O.ToHex(t),"f")}return zr(this,yp,"f")}get subjectName(){return zr(this,gp,"f")||Wr(this,gp,new sl(this.asn.tbsCertificate.subject),"f"),zr(this,gp,"f")}get subject(){return zr(this,mp,"f")||Wr(this,mp,this.subjectName.toString(),"f"),zr(this,mp,"f")}get issuerName(){return zr(this,vp,"f")||Wr(this,vp,new sl(this.asn.tbsCertificate.issuer),"f"),zr(this,vp,"f")}get issuer(){return zr(this,wp,"f")||Wr(this,wp,this.issuerName.toString(),"f"),zr(this,wp,"f")}get notBefore(){if(!zr(this,bp,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Wr(this,bp,e,"f")}return zr(this,bp,"f")}get notAfter(){if(!zr(this,Sp,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Wr(this,Sp,e,"f")}return zr(this,Sp,"f")}get signatureAlgorithm(){if(!zr(this,Ap,"f")){const e=uc.resolve(hu);Wr(this,Ap,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return zr(this,Ap,"f")}get signature(){return zr(this,Ep,"f")||Wr(this,Ep,this.asn.signatureValue,"f"),zr(this,Ep,"f")}get extensions(){return zr(this,kp,"f")||(Wr(this,kp,[],"f"),this.asn.tbsCertificate.extensions&&Wr(this,kp,this.asn.tbsCertificate.extensions.map((e=>Ml.create(Kr.serialize(e)))),"f")),zr(this,kp,"f")}get tbs(){return zr(this,fp,"f")||Wr(this,fp,this.asn.tbsCertificateRaw||Kr.serialize(this.asn.tbsCertificate),"f"),zr(this,fp,"f")}constructor(e){const t=Il.isAsnEncoded(e)?[e,eo]:[e];super(t[0],t[1]),fp.set(this,void 0),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),this.tag=Nl.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=tl.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 Tl)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"],t);else if(k.isBufferSource(n)){const e=new Tl(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=uc.resolveAll(Xl).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=tl.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=tl.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Kr.parse(this.rawData,eo),r=t.tbsCertificate,i=new Ju("",{Version:`${Yn[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Gu.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Ju("",{"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 Ju("");for(const t of this.extensions){const r=t.toTextObject();e[r[Ju.NAME]]=r}i.Extensions=e}return e.Data=i,e.Signature=new Ju("",{Algorithm:Gu.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}fp=new WeakMap,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,Ip.NAME="Certificate";class Tp{static async createSelfSigned(e,t=tl.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=tl.get()){var r;let i;i=e.publicKey instanceof Tl?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:k.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const n=function(e,t=tl.get()){const r=k.toUint8Array(O.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 eo({tbsCertificate:new Qn({version:Yn.v3,serialNumber:n,validity:new Jn({notBefore:o,notAfter:s}),extensions:new Xn((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>Kr.parse(e.rawData,Gn))))||[]),subjectPublicKeyInfo:Kr.parse(i,zn)})});if(e.subject){const t=e.subject instanceof sl?e.subject:new sl(e.subject);a.tbsCertificate.subject=Kr.parse(t.toArrayBuffer(),ni)}if(e.issuer){const t=e.issuer instanceof sl?e.issuer:new sl(e.issuer);a.tbsCertificate.issuer=Kr.parse(t.toArrayBuffer(),ni)}const c={hash:"SHA-256"},u="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},l=uc.resolve(hu);a.tbsCertificate.signature=a.signatureAlgorithm=l.toAsnAlgorithm(u);const p=Kr.serialize(a.tbsCertificate),h="signingKey"in e?await t.subtle.sign(u,e.signingKey,p):e.signature,d=uc.resolveAll(Xl).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 Ip(Kr.serialize(a))}}function Bp(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 Op(){const e=globalThis.crypto;if(null==e?void 0:e.subtle)return e;return Bp("node:crypto").webcrypto}(Np=_p||(_p={}))[Np.unspecified=0]="unspecified",Np[Np.keyCompromise=1]="keyCompromise",Np[Np.cACompromise=2]="cACompromise",Np[Np.affiliationChanged=3]="affiliationChanged",Np[Np.superseded=4]="superseded",Np[Np.cessationOfOperation=5]="cessationOfOperation",Np[Np.certificateHold=6]="certificateHold",Np[Np.removeFromCRL=8]="removeFromCRL",Np[Np.privilegeWithdrawn=9]="privilegeWithdrawn",Np[Np.aACompromise=10]="aACompromise",Ml.register(ki,Ol),Ml.register(nn,Pl),Ml.register(mn,Rl),Ml.register(Pn,Ul),Ml.register(Si,Bl),Ml.register(Bn,$l),Ml.register(Hi,Vl),Ml.register(vi,Hl),Ml.register(yn,zl),Gl.register(Rc,Jl),Gl.register(Uc,ql),uc.registerSingleton(Xl,class{toAsnSignature(e,t){return k.toArrayBuffer(t)}toWebSignature(e,t){return k.toArrayBuffer(t)}}),uc.registerSingleton(Xl,ep),ep.namedCurveSize.set("P-256",32),ep.namedCurveSize.set("K-256",32),ep.namedCurveSize.set("P-384",48),ep.namedCurveSize.set("P-521",66);const Cp={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:4096},Dp={...Cp,modulusLength:2048},jp=["server","client","authentication","assertion","key-agreement","capability"],Pp=["did-json","did-meta","cert","chain","fullchain","ca","public","csr","meta","private","keyref","verification-method"];function Rp(){const e=new Uint8Array(16);return Op().getRandomValues(e),e[0]&=127,e[0]|=1,Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Up(e){return new Date(Date.now()+24*e*3600*1e3)}async function $p(e){const t=new Uint8Array(await Op().subtle.exportKey("pkcs8",e));return Nl.encode(t,"PRIVATE KEY")}function Mp(e){return Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Lp(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=Bp("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 Vp(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 Hp(e){return Vp(e).toRawHostUri()}function Kp(e){return Lp(Hp(e))}function Fp(e){const t=Vp(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 zp(e,t){switch(function(e){if(!jp.includes(e))throw new Error(`Unsupported identity usage: ${e}`)}(e),function(e){if(!Pp.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 Wp(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function Jp(e,t,r){const i=Bp("node:path");return{cert:i.join(e,zp(r,"cert")),chain:i.join(e,zp(r,"chain")),fullchain:i.join(e,zp(r,"fullchain")),ca:i.join(e,zp(r,"ca")),metadata:i.join(e,zp(r,"meta")),keyref:i.join(t,zp(r,"keyref")),privateKey:i.join(t,zp(r,"private"))}}class qp{constructor(e,t){const r=Bp("node:path");this.publicRoot=r.resolve(e),this.securityRoot=r.resolve(t)}static fromEnvOrBuckyosRoot(e={}){const t=Bp("node:path"),r=function(){const e=globalThis.process;return(null==e?void 0:e.env)??{}}(),i=Wp(e.buckyosRoot)??Wp(r.BUCKYOS_ROOT)??"/opt/buckyos",n=Wp(e.publicRoot)??Wp(r.BUCKYOS_IDENTITY_ROOT)??t.join(i,"local","identity"),o=Wp(e.securityRoot)??Wp(r.BUCKYOS_SECURITY_ROOT)??t.join(i,"security");return new qp(n,o)}rawHostUri(e){return Hp(e)}dirName(e){return Kp(e)}publicDir(e){return Bp("node:path").join(this.publicRoot,this.dirName(e))}securityDir(e){return Bp("node:path").join(this.securityRoot,this.dirName(e))}publicFile(e,t,r){return Bp("node:path").join(this.publicDir(e),zp(t,r))}securityFile(e,t,r){return Bp("node:path").join(this.securityDir(e),zp(t,r))}x509Paths(e,t="server"){return Jp(this.publicDir(e),this.securityDir(e),t)}identityDirMatch(e){const t=this.rawHostUri(e),r=Lp(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=Bp("node:fs"),i=this.identityDirMatch(e),n=Jp(i.publicDir,i.securityDir,t);if(r.existsSync(n.fullchain)||r.existsSync(n.cert))return{match:i,paths:n};const o=Vp(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=Lp(a),u=Bp("node:path"),l=u.join(this.publicRoot,c),p=u.join(this.securityRoot,c),h=Jp(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 Gp(e){const t=Op();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=Xp(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),Xp(48,n)}(new Uint8Array(Nl.decode(e)[0]));return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}const r=new Uint8Array(Nl.decode(e)[0]);return t.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])}function Xp(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 Yp(e){const t=e.extensions.find((e=>e instanceof Ol));if(!(null==t?void 0:t.ca))return"missing basicConstraints CA:TRUE";const r=e.extensions.find((e=>e instanceof Rl));return!r||r.usages&jl.keyCertSign?void 0:"keyUsage does not allow certificate signing"}async function Zp(e,t="devtest"){const r=Bp("node:fs"),i=Bp("node:path"),n=Op();tl.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(Cp,!0,["sign","verify"]),u=await Tp.createSelfSigned({serialNumber:Rp(),name:a,notBefore:new Date,notAfter:Up(3650),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},keys:c,extensions:[new Ol(!0,void 0,!0),new Rl(jl.keyCertSign|jl.cRLSign|jl.digitalSignature,!0),await Ul.create(c.publicKey)]});return r.writeFileSync(o,await $p(c.privateKey)),r.writeFileSync(s,u.toString("pem")),console.log(`CA certificate created: ${s}`),{caCertPath:s,caKeyPath:o}}async function Qp(e,t,r=[],i="server"){const n=Bp("node:fs"),o=Op();tl.set(o);const{caCertPath:s,caKeyPath:a}=function(e){const t=Bp("node:fs"),r=Bp("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 Ip(c),l=Yp(u);if(l)throw new Error(`Invalid CA certificate at ${s}: ${l}`);const p=await Gp(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(Dp,!0,["sign","verify"]),f=new Uint8Array(await o.subtle.exportKey("spki",d.publicKey)),y=await async function(e){const t=await Op().subtle.digest("SHA-256",e);return`sha256:${Mp(new Uint8Array(t))}`}(f),g=[...t.map((e=>({type:"dns",value:e}))),...r.map((e=>({type:"url",value:e})))],m=await Tp.create({serialNumber:Rp(),subject:`CN=${h}`,issuer:u.subjectName,notBefore:new Date,notAfter:Up(365),signingAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},publicKey:d.publicKey,signingKey:p,extensions:[new Rl(jl.digitalSignature|jl.keyEncipherment,!0),new Pl(["client"===i?Cl.clientAuth:Cl.serverAuth]),new $l(g),await Ul.create(d.publicKey),await Bl.create(u)]});return{cert:m,certPem:m.toString("pem"),privateKeyPem:await $p(d.privateKey),caCertPem:c,publicKeyFingerprint:y}}function eh(e){return`${e.trimEnd()}\n`}function th(e,t,r){const i=Bp("node:fs"),n=Bp("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 rh(e){const t=e.toRawHostName();return t.startsWith("_.")?`*.${t.slice(2)}`:t}function ih(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:Fp(t)}}async function nh(e,t,r,i,n){const o=function(e){const t=e.extensions.find((e=>e instanceof $l)),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",Op());return`sha256:${Mp(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:zp(t,"cert"),chain:zp(t,"chain"),fullchain:zp(t,"fullchain"),ca:zp(t,"ca")},did_binding:ih(e),updated_at:c,generation:`${c.replace(/[-:.]/g,"")}-${s}`}}const oh="test test test test test test test test test test test junk",sh=2147483648,ah=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ch=(1n<<64n)-1n,uh=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],lh=[[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 ph(e,t=""){return o.pbkdf2Sync(n.Buffer.from(e.normalize("NFKD"),"utf8"),n.Buffer.from(`mnemonic${t}`.normalize("NFKD"),"utf8"),2048,64,"sha512")}function hh(e,t){return o.createHmac("sha512",e).update(t).digest()}function dh(e){const t=n.Buffer.alloc(4);return t.writeUInt32BE(e>>>0,0),t}function fh(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 yh(e,t,r){const i=hh(t,n.Buffer.concat([n.Buffer.from([0]),e,dh(r+sh)]));return{key:i.subarray(0,32),chainCode:i.subarray(32)}}function gh(e,t,r){let i=function(e){const t=hh("ed25519 seed",e);return{key:t.subarray(0,32),chainCode:t.subarray(32)}}(ph(e,t));for(const n of[9777,0,r])i=yh(i.key,i.chainCode,n);return n.Buffer.from(i.key)}function mh(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`}(gh(e,t??"",r));return{privateKeyPem:i,publicKeyX:fh(i)}}function vh(e){return mh(oh,void 0,e)}function wh(e){const t=e.toString(16).padStart(64,"0");return n.Buffer.from(t,"hex")}function bh(e){return BigInt(`0x${e.toString("hex")}`)}function Sh(e,t){const r=o.createECDH("secp256k1");return r.setPrivateKey(e),r.getPublicKey(void 0,t?"compressed":"uncompressed")}function Ah(e,t,r){const i=hh(t,r>=sh?n.Buffer.concat([n.Buffer.from([0]),e,dh(r)]):n.Buffer.concat([Sh(e,!0),dh(r)])),o=bh(i.subarray(0,32));if(o>=ah)throw new Error(`invalid secp256k1 child tweak at index ${r}`);const s=(o+bh(e))%ah;if(0n===s)throw new Error(`invalid secp256k1 child key at index ${r}`);return{privateKey:wh(s),chainCode:i.subarray(32)}}function Eh(e){return`m/44'/60'/0'/0/${e}`}function kh(e,t){if(0===t)return e&ch;const r=BigInt(t);return(e<<r|e>>64n-r)&ch}function xh(e){for(const t of uh){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]^kh(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])&ch;for(let t=0;t<5;t+=1)for(let r=0;r<5;r+=1)n[r+(2*t+3*r)%5*5]=kh(e[t+5*r],lh[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]&ch&n[(t+2)%5+5*r])&ch;e[0]=(e[0]^t)&ch}}function _h(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);xh(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 Nh(e){const t=e.toString("hex"),r=_h(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 Ih(e,t,r){let i=function(e){const t=hh("Bitcoin seed",e),r=t.subarray(0,32),i=bh(r);if(i<=0n||i>=ah)throw new Error("invalid secp256k1 master key");return{privateKey:n.Buffer.from(r),chainCode:t.subarray(32)}}(ph(e,t??""));for(const n of function(e){return[2147483692,2147483708,sh,0,e]}(r))i=Ah(i.privateKey,i.chainCode,n);const o=Sh(i.privateKey,!1),s=Sh(i.privateKey,!0),a=_h(o.subarray(1)),c=i.privateKey.toString("hex");return{derivationPath:Eh(r),privateKey:`0x${c}`,privateKeyHex:c,publicKeyCompressedHex:s.toString("hex"),publicKeyUncompressedHex:o.toString("hex"),address:Nh(a.subarray(12))}}function Th(e){return Ih(oh,void 0,e)}const Bh={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},Oh={alice:1,bob:2,charlie:3,dave:4},Ch=Object.fromEntries(Object.entries(Bh).map((([e,t])=>[e,vh(t)]))),Dh=Object.fromEntries(Object.entries(Oh).map((([e,t])=>[e,Th(t)]))),jh=Th(0);function Ph(e){const t=Ch[e];if(!t)throw new Error(`unknown dev test key pair id: ${e}`);return t}const Rh="ood1",Uh="wan",$h=i.DEFAULT_EXPIRE_TIME,Mh="provision_activation.lock",Lh="zone_dns_records.json",Vh="zone_document.jwt";class Hh extends Error{constructor(e,t,r={}){super(t),this.name="ActivationError",this.code=e,this.details=r}}function Kh(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 Hh("RUNTIME_UNSUPPORTED",`buckyos provision cannot load builtin module ${e} in this runtime (Node >= 22.13 or Deno >= 2.2 is required)`)}function Fh(){var e;return"win32"===(null==(e=globalThis.process)?void 0:e.platform)}function zh(e,t){const r=Kh("node:path");return r.relative(e,t).split(r.sep).join("/")}function Wh(e){return Kh("node:crypto").createHash("sha256").update(e,"utf8").digest("hex")}function Jh(){return Kh("node:crypto").randomBytes(6).toString("hex")}function qh(e){const t=Kh("node:fs");try{return t.lstatSync(e)}catch(r){const e=r.code;if("ENOENT"===e||"ENOTDIR"===e)return null;throw r}}function Gh(e){const t=Kh("node:fs");try{return t.statSync(e)}catch(r){if("ENOENT"===r.code||"ENOTDIR"===r.code)return null;throw r}}function Xh(e){var t;return!0===(null==(t=Gh(e))?void 0:t.isDirectory())}function Yh(e){var t;return!0===(null==(t=Gh(e))?void 0:t.isFile())}function Zh(e){const t=Kh("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 Qh(e){return JSON.stringify(e,null,2)}function ed(e,t,r,i){const n=Kh("node:fs"),o=Kh("node:path"),s=o.dirname(e);if(n.mkdirSync(s,{recursive:!0,mode:i}),Fh()||n.chmodSync(s,i),qh(e))throw new Error(`refusing to overwrite existing file: ${e}`);const a=o.join(s,`.${o.basename(e)}.provision-${Jh()}`);try{n.writeFileSync(a,t,{mode:r,flag:"wx"}),Fh()||n.chmodSync(a,r),n.renameSync(a,e)}finally{qh(a)&&n.rmSync(a,{force:!0})}}function td(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 Hh("INVALID_ARGUMENT",`invalid did:web domain: ${e}`,{field:"domain"});return t}function rd(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 Hh("INVALID_ARGUMENT","owner name must be a lowercase DNS label (letters, digits, and hyphens)",{field:"owner_name"});return t}function id(e){const t=e??2980;if(!Number.isInteger(t)||t<1||t>65535)throw new Hh("INVALID_ARGUMENT",`invalid RTCP port: ${String(e)}`,{field:"rtcp_port"});return t}function nd(e){const t=(null==e?void 0:e.trim())||void 0;if(void 0===t)return;if(0===Kh("node:net").isIP(t))throw new Hh("INVALID_ARGUMENT",`invalid public IP address: ${t}`,{field:"public_ip"});return t}function od(e){if("string"!=typeof e||e.length<8)throw new Hh("INVALID_ARGUMENT","administrator password must contain at least 8 characters",{field:"admin_password"});return e}function sd(e,t){return i.hashPassword(e,t,null)}function ad(e,t){const r=[];if(t){const i=Kh("node:net");r.push({type:6===i.isIP(t)?"AAAA":"A",name:e,value:t})}return r}function cd(){const e=Kh("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 Hh("KEY_GENERATION_FAILED","generated Ed25519 public key has no x coordinate");return{privateKeyPem:t.export({format:"pem",type:"pkcs8"}).toString(),publicKeyX:i.x}}function ud(e){const t=Kh("node:path");if("string"!=typeof e.rootDir||0===e.rootDir.trim().length)throw new Hh("INVALID_ARGUMENT","target root is required",{field:"root"});if("string"!=typeof e.ownerKeyBackupPath||0===e.ownerKeyBackupPath.trim().length)throw new Hh("INVALID_ARGUMENT","owner key backup path is required",{field:"owner_key_backup"});const r=td(e.domain),n=new i.DID("web",r);return{rootDir:t.resolve(e.rootDir),domain:r,ownerName:rd(e.ownerName),ownerKeyBackupPath:t.resolve(e.ownerKeyBackupPath),rtcpPort:id(e.rtcpPort),guestAccess:e.guestAccess??!1,publicIp:nd(e.publicIp),ownerDid:n,zoneDid:n,deviceDid:y(Rh,n)}}function ld(e){const t=Kh("node:path");return new qp(t.join(e,"local","identity"),t.join(e,"security"))}function pd(e,t,r){const i=Kh("node:path"),n=i.join(e,"etc"),o=f(ld(e),r);return{etcDir:n,lockPath:i.join(n,Mh),nodeIdentityPath:i.join(n,"node_identity.json"),startConfigPath:i.join(n,"start_config.json"),zoneDocumentJwtPath:i.join(n,Vh),gatewayParamsPath:i.join(n,"node_gateway_params.json"),dnsRecordsPath:i.join(n,Lh),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 hd(e,t){const r=(t,r,i,n)=>({path:zh(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,!1),r(t.gatewayParamsPath,"gateway_params",!0,!1),r(t.nodeIdentityPath,"node_identity",!0,!1)]}function dd(e){return{path:e.path,role:e.role,required:e.required,secret:e.secret}}function fd(e){if(!qh(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=Zh(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 yd(e,t){const r=Kh("node:fs"),i=Kh("node:path"),n=i.join(i.dirname(e),`.${Mh}.${Jh()}`);try{r.writeFileSync(n,Qh(t),{mode:384,flag:"wx"}),r.renameSync(n,e)}finally{qh(n)&&r.rmSync(n,{force:!0})}}function gd(e){const t=Kh("node:fs");return Xh(e)?t.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name)).sort():[]}function md(e){try{return i.getXFromJwk(e)}catch{return null}}async function vd(e){const t=Kh("node:path"),r=t.resolve(String(e??"")),n=i.buckyosGetUnixTimestamp(),o=[],s=[],a=e=>({rootDir:r,state:e,startupRequired:"configured"===e,observedAt:n,zoneDid:null,ownerDid:null,deviceDid:null,deviceName:null,accessHostname:null,files:[],problems:o,warnings:s,lock:null});if(!Xh(r))return o.push({code:"ROOT_MISSING",message:`BUCKYOS_ROOT does not exist: ${r}`}),a("not_installed");const c=["bin","etc"].filter((e=>!Xh(t.join(r,e))));if(c.length>0){for(const e of c)o.push({code:"INSTALL_INCOMPLETE",message:`installed BuckyOS directory is missing: ${t.join(r,e)}`});return a("not_installed")}const u=t.join(r,"etc"),l=fd(t.join(u,Mh)),p=function(e,t){if(!Yh(e))return{nodeIdentity:null,zoneDid:null,deviceDid:null};try{const r=Zh(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}}}(t.join(u,"node_identity.json"),o);let h=p.zoneDid,d=p.deviceDid;const g=gd(t.join(r,"local","identity")),m=gd(t.join(r,"security")),v=function(e,t){const r=Kh("node:fs");return Xh(e)?r.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isFile()&&t(e.name))).map((e=>e.name)).sort():[]}(u,(e=>e.endsWith(".zone.json")));if(!h&&v.length>0){const e=v[0].slice(0,-10);e.endsWith(".did")||(h=new i.DID("web",e))}!d&&h&&(d=y(Rh,h));const w=[...g,...m].filter((e=>!d||e!==t.basename(f(ld(r),d).publicDir))),b=[];let S=null;if(h&&d){S=pd(r,h,d);for(const e of hd(r,S))b.push({...dd(e),present:Yh(e.absolutePath)})}else{for(const[e,r,i]of[["node_identity.json","node_identity",!0],["start_config.json","start_config",!0],[Vh,"zone_document_jwt",!0],["node_gateway_params.json","gateway_params",!0],[Lh,"dns_records",!1]])b.push({path:`etc/${e}`,role:r,required:i,secret:!1,present:Yh(t.join(u,e))});for(const e of v)b.push({path:`etc/${e}`,role:"zone_boot_override",required:!0,secret:!1,present:!0})}const A=b.find((e=>"gateway_params"===e.role)),E=!0===(null==A?void 0:A.present)&&function(e){try{const t=Zh(e).params;return!!t&&"object"==typeof t&&"did:bns:unactivated.local"===t.device_did}catch{return!1}}(t.join(u,"node_gateway_params.json"));A&&E&&(A.present=!1);const k=b.filter((e=>e.present&&"dns_records"!==e.role)),x=b.filter((e=>e.required&&!e.present)),_=a("unactivated");_.files=b,_.lock=l,_.zoneDid=(null==h?void 0:h.toString())??null,_.deviceDid=(null==d?void 0:d.toString())??null,_.deviceName=p.nodeIdentity?String(p.nodeIdentity.device_name):d?Rh:null,_.ownerDid=p.nodeIdentity?String(p.nodeIdentity.owner_did):null,l&&s.push(l.corrupt?`activation lock ${l.path} exists but cannot be parsed`:`activation lock ${l.path} exists (stage=${l.stage??"unknown"}, committed=${l.committedFiles.length})`);for(const i of w)s.push(`unexpected identity directory: ${i}`);if(0===k.length&&0===w.length&&!l&&0===o.length)return _.state="unactivated",_;if(x.length>0||!S||w.length>0&&0===k.length){for(const e of x)o.push({code:"FILE_MISSING",message:`${e.path} is missing`});return _.state="partial",_}const N=await async function(e,t,r,n){var o,s,a;const c=Kh("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 g=y(String(u.device_name),p).toString();if(h.toString()!==g&&l("DEVICE_DID_MISMATCH",`device DID ${h.toString()} is not ${g}`),!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=Zh(t.startConfigPath)}catch(O){l("START_CONFIG_UNREADABLE",`etc/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",`etc/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",`etc/start_config.json is missing ${t}`);m.zone_name!==p.toString()&&l("START_CONFIG_ZONE",`etc/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",`etc/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&&md(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","etc/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","etc/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",`etc/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,zh(e,t.deviceDocJwtPath)))?void 0:s.trim())??null,E=(null==(a=b(t.deviceMiniDocJwtPath,zh(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=Zh(t.zoneBootOverridePath);JSON.stringify(r)!==JSON.stringify(x)&&l("BOOT_OVERRIDE_MISMATCH",`${zh(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?md(r.publicKeyJwk):null,B||l("DEVICE_DOCUMENT","device document has no #main_key");try{Zh(t.didJsonPath).id!==h.toString()&&l("DEVICE_DID_JSON",`${zh(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(!Fh()){const e=qh(t.devicePrivateKeyPath);e&&63&e.mode&&l("DEVICE_PRIVATE_KEY_MODE","device private key is readable by other users")}}return{ownerDid:d,accessHostname:v}}(r,S,p,o);return _.ownerDid=N.ownerDid??_.ownerDid,_.accessHostname=N.accessHostname??(h?h.toRawHostName():null),l&&"committed"!==l.stage&&o.push({code:"ACTIVATION_INTERRUPTED",message:`activation lock is still at stage ${l.stage??"unknown"}; the commit did not finish cleanly`}),_.state=0===o.length?"configured":"invalid",_.startupRequired="configured"===_.state,_}async function wd(e){const t=ud(e),r=await vd(t.rootDir),i=[],n=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`}}}(r);n&&i.push(n);const o=function(e,t){const r=Kh("node:path").dirname(e),i=Xh(r),n=null!==qh(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}}(t.ownerKeyBackupPath,i),s=pd(t.rootDir,t.zoneDid,t.deviceDid);return{ready:0===i.length,rootDir:t.rootDir,state:r.state,domain:t.domain,ownerName:t.ownerName,ownerDid:t.ownerDid.toString(),zoneDid:t.zoneDid.toString(),deviceDid:t.deviceDid.toString(),deviceName:Rh,accessHostname:t.domain,rtcpPort:t.rtcpPort,guestAccess:t.guestAccess,publicIp:t.publicIp??null,dnsRecords:ad(t.domain,t.publicIp),ownerKeyBackup:o,plannedFiles:hd(t.rootDir,s).map(dd),problems:i,status:r}}function bd(e){const t=e.problems[0];return new Hh(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})}function Sd(e,t,r,i){switch(e.role){case"device_private_key":return r.privateKeyPem;case"device_document":return Qh(t.deviceDocument);case"device_document_jwt":return t.deviceDocJwt;case"device_mini_document_jwt":return t.deviceMiniDocJwt;case"zone_boot_override":return Qh(t.bootDocument);case"zone_document_jwt":return t.zoneDocumentJwt;case"dns_records":return Qh({hostname:i,records:t.dnsRecords});case"start_config":return Qh(t.startConfig);case"gateway_params":return Qh(t.gatewayParams);case"node_identity":return Qh(t.nodeIdentity)}}function Ad(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 Ed=1743478939,kd=2058838939;function xd(e){const t=e.split(".");return[Number(t[0])||0,Number(t[1])||0]}function _d(){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]=xd(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]=xd(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 Nd(e){_d();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 Id(e,t){const r=Nd("node:fs"),i=Nd("node:path");r.mkdirSync(i.dirname(e),{recursive:!0}),r.writeFileSync(e,t),console.log(`# Write file: ${e}`)}function Td(e,t){Id(e,JSON.stringify(t,null,2))}function Bd(e){const t=Nd("node:fs");return JSON.parse(t.readFileSync(e,"utf8"))}function Od(e){if(Array.isArray(e))return e.map(Od);if(null!==e&&"object"==typeof e){const t={};for(const r of Object.keys(e).sort())t[r]=Od(e[r]);return t}return e}function Cd(e,t){return t||(Ch[e]?Ch[e]:Ch[`${e}.owner`]?Ch[`${e}.owner`]:(console.log(`Warning: Key pair for user ${e} not found, using devtest key pair`),Ph("devtest")))}function Dd(e,t,r){return r||Ph(`${e}.${t}`)}function jd(e){const t=Nd("node:path");return new qp(t.join(e,"local","identity"),t.join(e,"security"))}class Pd{constructor(e){_d(),this.dbPath=e}connect(){const{DatabaseSync:e}=Nd("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 Rd(){var e;const t=(null==(e=globalThis.process)?void 0:e.arch)??"";return"x64"===t?"amd64":"arm64"===t?"aarch64":t}function Ud(){var e;const t=(null==(e=globalThis.process)?void 0:e.platform)??"";return"darwin"===t?"apple":"win32"===t?"windows":t}function $d(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}function Md(e){const t={...e},r=(e,r)=>{e in t&&r(t[e])&&delete t[e]};return r("did",(e=>null==e)),r("name",(e=>""===e)),r("author",(e=>""===e)),r("owner",(e=>null==e||"did:undefined:undefined"===e)),r("copyright",(e=>null==e)),r("tags",(e=>Array.isArray(e)&&0===e.length)),r("categories",(e=>Array.isArray(e)&&0===e.length)),r("base_on",(e=>null==e)),r("directory",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),r("references",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),r("exp",(e=>0===e)),r("size",(e=>0===e)),r("content",(e=>""===e)),r("version_tag",(e=>null==e)),r("deps",(e=>e&&"object"==typeof e&&0===Object.keys(e).length)),t}function Ld(e){const t=Md(e),[r]=i.buildNamedObjectByJson("pkg",t);return r.toString()}class Vd{constructor(e){_d(),this.dbPath=e}connect(){const{DatabaseSync:e}=Nd("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=$d(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 Hd=[{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"}],Kd="0.7.0";function Fd(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.ACTIVATION_DEFAULT_RTCP_PORT=2980,exports.ACTIVATION_DEVICE_NAME=Rh,exports.ACTIVATION_DOCUMENT_VALIDITY_SECONDS=$h,exports.ACTIVATION_LOCK_FILE_NAME=Mh,exports.ACTIVATION_MIN_PASSWORD_LENGTH=8,exports.ACTIVATION_NET_ID=Uh,exports.ActivationError=Hh,exports.DEVICE_DOC_JWT_FILE_NAME=s,exports.DEVICE_MINI_DOC_JWT_FILE_NAME=a,exports.DEV_TEST_EVM_ACCOUNTS=Dh,exports.DEV_TEST_EVM_SEED_SENDER=jh,exports.DEV_TEST_EVM_SEED_SENDER_INDEX=0,exports.DEV_TEST_EVM_USER_INDEXES=Oh,exports.DEV_TEST_KEYS=Ch,exports.DEV_TEST_KEY_INDEXES=Bh,exports.DEV_TEST_MNEMONIC=oh,exports.DevSnDb=Pd,exports.IDENTITY_MATERIALS=Pp,exports.IDENTITY_USAGES=jp,exports.IdentityRoots=qp,exports.KERNEL_SERVICE_DOC_VERSION=Kd,exports.MetaIndexDb=Vd,exports.NODE_GATEWAY_PARAMS_FILE_NAME=c,exports.PROVISION_BASE_TIME=Ed,exports.PROVISION_DEFAULT_EXP=kd,exports.ZONE_DNS_RECORDS_FILE_NAME=Lh,exports.ZONE_DOCUMENT_JWT_FILE_NAME=Vh,exports.activateOfflineZone=async function(e){const t=Kh("node:fs"),r=ud(e),n=od(e.adminPassword),o=await wd(e);if(!o.ready)throw bd(o);const s=e.ownerKeyPair??cd(),a=e.deviceKeyPair??cd(),c=await async function(e,t,r,n){const o=i.buckyosGetUnixTimestamp(),s=o+$h,a=i.createJwkByX(r.publicKeyX),c=i.createJwkByX(n.publicKeyX),u=e.ownerDid.toString(),l=e.zoneDid.toString(),p=e.deviceDid.toString(),d=i.newOwnerDocument({did:e.ownerDid,name:e.ownerName,displayName:e.ownerName,publicKeyJwk:a,now:o});d.exp=s,i.ownerDocumentSetDefaultZoneDid(d,e.zoneDid);const f=i.ownerDocumentToOrderedJson(d),y=i.oodDescriptionToString(i.parseOODDescription(`${Rh}@${Uh}`)),g=await i.encodeZoneBootDocument(i.newZoneBootDocument({id:e.zoneDid,oods:[y],exp:s}),r.privateKeyPem),v=i.decodeJwtClaimWithoutVerify(g),w=m(Rh,c,e.deviceDid,o);delete w.support_container,w.owner=u,w.zone_did=l,w.net_id=Uh,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={[Rh]:b},k.mini_device_jwts={[Rh]: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 Hh("ZONE_DOCUMENT_TOO_LARGE","zone document JWT exceeds the 4096 byte inline limit");return{documentIat:o,documentExp:s,ownerDocument:f,bootDocument:v,bootJwt:g,deviceDocument:b,deviceDocJwt:S,deviceMiniDocJwt:E,zoneDocumentJwt:x,nodeIdentity:h({zoneDid:e.zoneDid,ownerDid:e.ownerDid,ownerPublicKey:a,deviceName:Rh,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:sd(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:ad(e.domain,e.publicIp)}}(r,n,s,a),u=pd(r.rootDir,r.zoneDid,r.deviceDid),l=hd(r.rootDir,u),p=[],d={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=Kh("node:fs");try{r.writeFileSync(e,Qh(t),{mode:384,flag:"wx"})}catch(i){if("EEXIST"===i.code)throw new Hh("ACTIVATION_IN_PROGRESS",`another activation holds the lock ${e}; inspect it with provision status`,{lock_file:e,lock:fd(e)});throw i}}(u.lockPath,d);const f=()=>{try{t.rmSync(u.lockPath,{force:!0})}catch{}};let y;try{y=await wd(e)}catch(b){throw f(),b}const g=y.problems.filter((e=>"ACTIVATION_IN_PROGRESS"!==e.code));if(g.length>0)throw f(),bd({...y,problems:g});for(const i of l)if(qh(i.absolutePath))throw f(),new Hh("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=Kh("node:fs");r.writeFileSync(e,t,{mode:384,flag:"wx"}),Fh()||r.chmodSync(e,384)}(r.ownerKeyBackupPath,s.privateKeyPem)}catch(b){f();const e=b.code;throw new Hh("EEXIST"===e?"OWNER_KEY_BACKUP_EXISTS":"OWNER_KEY_BACKUP_FAILED",`owner key backup could not be saved: ${b instanceof Error?b.message:String(b)}`,{owner_key_backup:{path:r.ownerKeyBackupPath,saved:!1},committed_files:[]})}d.stage="backup_saved";const v=[],w=(e,t)=>{throw new Hh("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:v,lock_file:u.lockPath,recovery:Ad(u.lockPath,r.ownerKeyBackupPath,v.map((e=>e.path)))})};try{yd(u.lockPath,d)}catch(b){w(b,"lock:backup_saved")}d.stage="committing";for(const i of l){const e=Sd(i,c,a,r.domain);try{ed(i.absolutePath,e,i.mode,i.dirMode)}catch(b){w(b,i.path)}v.push({...dd(i),sha256:i.secret?null:Wh(e)}),d.committed=v.map((e=>e.path));try{yd(u.lockPath,d)}catch(b){w(b,`lock:${i.path}`)}}d.stage="committed";try{yd(u.lockPath,d),t.rmSync(u.lockPath,{force:!0})}catch(b){p.push(`activation completed but the lock ${u.lockPath} could not be removed: ${b instanceof Error?b.message:String(b)}`)}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:Rh,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:v,warnings:p}},exports.assertProvisionRuntime=_d,exports.bindDeviceDocumentDid=g,exports.buildActivationDnsRecords=ad,exports.buildDeviceDid=y,exports.buildDidDocs=function(e,t){_d();const r=Nd("node:path"),n=(null==t?void 0:t.version)??Kd,o=(null==t?void 0:t.now)??i.buckyosGetUnixTimestamp(),s=[];for(const i of Hd){const t=Fd(i.uniqueId),a=Od({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`);Td(c,a),s.push(c)}return s},exports.calcPkgMetaObjId=Ld,exports.checkOfflineActivation=wd,exports.createCa=Zp,exports.createCertFromCa=async function(e,t,r,i){const n=Bp("node:fs"),o=Bp("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 Qp(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=Bp("node:fs"),o=function(e){return e instanceof qp?e:qp.fromEnvOrBuckyosRoot(e)}(r),s=i.usage??"server",a=Vp(t),c=a.toRawHostUri(),u=Lp(c),l=o.publicDir(a.toString()),p=o.securityDir(a.toString()),h=Jp(l,p,s),d=i.hostnames&&i.hostnames.length>0?i.hostnames:[rh(a)],f=i.uriSans??[a.toString()];n.mkdirSync(l,{recursive:!0,mode:493}),n.mkdirSync(p,{recursive:!0,mode:448});const y=await Qp(e,d,f,s),g=eh(y.certPem),m=eh(y.caCertPem),v=m,w=`${g}${v}`;var b,S,A;return th(h.privateKey,y.privateKeyPem,384),th(h.cert,g,420),th(h.chain,v,420),th(h.fullchain,w,420),th(h.ca,m,420),b=h.metadata,S=await nh(a,s,c,u,y),A=420,th(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){_d();const t=Nd("node:path"),r=e.envDir,n=Bd(t.join(r,"user_config.json")).name;if("string"!=typeof n||!n)throw new Error("user_config.json missing name field");const o=Bd(t.join(r,"zone_config.json")),s=i.DID.fromStr(o.id),a=Cd(n,e.ownerKeyPair),c=Dd(n,e.deviceName,e.deviceKeyPair),u=t.join(r,e.deviceName),l=new i.DID("bns",n),p=y(e.deviceName,s),d=m(e.deviceName,i.createJwkByX(c.publicKeyX),p,e.now);d.support_container=!0,delete d.support_container,void 0!==e.netId&&(d.net_id=e.netId),d.owner=l.toString(),d.zone_did=s.toString(),console.log(`input net_id: ${e.netId}, device_config.net_id: ${d.net_id}`);const f=await i.encodeDeviceDocument(d,a.privateKeyPem);console.log(`${e.deviceName} device jwt: ${f}`);const g=i.newDeviceMiniDocumentByDeviceDocument(d),v=await i.deviceMiniDocumentToJwt(g,a.privateKeyPem);Id(t.join(u,"device_mini_config.jwt"),v);const w=h({zoneDid:s,ownerDid:l,ownerPublicKey:i.createJwkByX(a.publicKeyX),deviceName:e.deviceName,deviceDid:p,zoneIat:Ed});if(b(u,jd(u),w,d,f,v,c.privateKeyPem),e.deviceName.startsWith("ood")){const e=Od({admin_password_hash:sd(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"});Td(t.join(u,"start_config.json"),e)}return console.log(`Successfully created node configuration: ${n}.${e.deviceName}`),i.encodeDeviceDocument(d,c.privateKeyPem)},exports.createSnConfigs=async function(e){_d();const t=Nd("node:path"),r=t.join(e.outputDir,"sn_server"),n=Ph("sn_owner"),o=Ph("sn_server"),s=kd;Id(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)});Td(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",Td(t.join(r,"sn_device_config.json"),i.deviceDocumentToOrderedJson(l)),Id(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=Od({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"}});Td(t.join(r,"params.json"),h),console.log("- Created params.json.");const d=new Pd(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){_d();const t=Nd("node:path"),r=e.rtcpPort??2980,n=e.outputDir,o=kd,s=Cd(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}`}Id(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});Td(t.join(n,"user_config.json"),i.ownerDocumentToOrderedJson(p)),console.log(`Created owner config for ${e.username}`);const h=i.parseOODDescription(e.oodName),d=Dd(e.username,h.name,e.deviceKeyPair);let f,g=c;h.netId&&(h.netId.startsWith("wan")&&(g=void 0),h.netId.startsWith("wan_dyn")&&c&&(f=`https://${c}/kapi/sn`));const v=i.oodDescriptionToString(h),w=i.newZoneBootDocument({oods:[v],sn:g,exp:o}),b=u.toRawHostName();Td(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),Td(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=y(h.name,u),I=m(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 Td(t.join(n,"zone_txt_record.json"),T),console.log(`Successfully created user environment configuration: ${e.username}`),T},exports.decodeDeviceDocumentWithoutVerify=S,exports.deriveDevTestEvmAccount=Th,exports.deriveDevTestEvmAccountFromMnemonic=Ih,exports.deriveDevTestKeyPair=vh,exports.deriveDevTestKeyPairFromMnemonic=mh,exports.devTestKeccak256=_h,exports.deviceIdentityPathsForRoots=f,exports.didWebDocumentUrl=Fp,exports.encodeIdentityDirName=Lp,exports.ensureCa=async function(e,t="devtest"){const r=Bp("node:fs"),i=Bp("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 Yp(new Ip(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`),Zp(e,t)):(console.log(`Use existing CA at: ${n}`),{caCertPath:n,caKeyPath:o})}return Zp(e,t)},exports.generateProvisionKeyPair=cd,exports.getDevTestEvmAccountByIndex=function(e){return Th(e)},exports.getDevTestEvmAccountByUsername=function(e){const t=Dh[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=Ph,exports.getDevTestKeyPairByIndex=function(e){return vh(e)},exports.hashAdminPassword=sd,exports.identityDirName=Kp,exports.identityFileName=zp,exports.identityRawHostUri=Hp,exports.inspectActivationRoot=vd,exports.loadDeviceDocJwtForRoots=v,exports.loadDeviceMiniDocJwtForRoots=function(e,t){return u("node:fs").readFileSync(f(e,t).deviceMiniDocJwt,"utf8")},exports.loadLocalDeviceDocumentForRoots=async function(e,t,r){const n=v(e,t.device_did),o=r?await i.verifyJwtEdDSA(n,t.owner_public_key):S(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=d,exports.newDeviceDocumentByJwkWithDid=m,exports.newLocalNodeIdentityConfig=h,exports.nodeTestIdentityRoots=jd,exports.normalizePackageMetaForObjId=Md,exports.registerDeviceToSn=async function(e,t,r,n){_d();const o=Nd("node:path"),s=Nd("node:fs"),a=Nd("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=d(u),p=i.DID.fromStr(l.owner_did).id,h=f(jd(c),l.device_did),y=s.readFileSync(h.deviceDocJwt,"utf8"),g=s.readFileSync(h.deviceMiniDocJwt,"utf8"),m=await i.verifyJwtEdDSA(y,l.owner_public_key),v=m.id;let w;try{w=i.parseOODDescription(r)}catch{w={name:r,nodeType:"Device"}}try{const n=Bd(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=Nd("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:Rd(),os:Ud(),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 Pd(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){_d();const n=Nd("node:path"),o=Bd(n.join(e,t,"user_config.json")).name;if("string"!=typeof o||!o)throw new Error("user_config.json missing name field");const s=Bd(n.join(e,t,"zone_config.json")),a=i.DID.fromStr(s.id);let c;"bns"!==a.method&&(c=a.toHostName());const u=Bd(n.join(e,t,"zone_txt_record.json")),l=new Pd(r),p=JSON.stringify(Od({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=b,exports.saveNodeGatewayParams=w,exports.setPkgMeta=async function(e,t){_d();const r=Nd("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=Ld(o),a=new Vd(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=Fd,exports.validateAdminPassword=od,exports.validateOwnerName=rd,exports.validatePublicIp=nd,exports.validateRtcpPort=id,exports.validateZoneDomain=td,exports.versionToInt=$d;
92
92
  //# sourceMappingURL=provision.cjs.map