benchgo-plugin 0.0.0-stage → 0.0.3

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.
Files changed (180) hide show
  1. package/DEEPSEEK-LICENSE +21 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +17 -0
  4. package/PASEO-LICENSE +211 -0
  5. package/README.md +256 -2
  6. package/TOOL-CONFIG.md +33 -0
  7. package/VERIFICATION.md +297 -0
  8. package/assets/fonts/README.md +13 -0
  9. package/assets/fonts/manifest.json +437 -0
  10. package/assets/fonts/web/fangyuan-latin-238bc49130b1.woff2 +0 -0
  11. package/assets/fonts/web/fangyuan-u30-0fe8d99641c3.woff2 +0 -0
  12. package/assets/fonts/web/fangyuan-u32-202a573131a1.woff2 +0 -0
  13. package/assets/fonts/web/fangyuan-u4e-cc2f8b20be49.woff2 +0 -0
  14. package/assets/fonts/web/fangyuan-u4f-9189b5f2d321.woff2 +0 -0
  15. package/assets/fonts/web/fangyuan-u50-e2560e003872.woff2 +0 -0
  16. package/assets/fonts/web/fangyuan-u51-a9c5e7a8c7c4.woff2 +0 -0
  17. package/assets/fonts/web/fangyuan-u52-0cfd00b473c8.woff2 +0 -0
  18. package/assets/fonts/web/fangyuan-u53-18122a07f60a.woff2 +0 -0
  19. package/assets/fonts/web/fangyuan-u54-8ca41aa9cff2.woff2 +0 -0
  20. package/assets/fonts/web/fangyuan-u55-7bd55e14647e.woff2 +0 -0
  21. package/assets/fonts/web/fangyuan-u56-26f093e8a810.woff2 +0 -0
  22. package/assets/fonts/web/fangyuan-u57-36bde83a8378.woff2 +0 -0
  23. package/assets/fonts/web/fangyuan-u58-d1df14217098.woff2 +0 -0
  24. package/assets/fonts/web/fangyuan-u59-4e41ab22c51a.woff2 +0 -0
  25. package/assets/fonts/web/fangyuan-u5a-746a367174e6.woff2 +0 -0
  26. package/assets/fonts/web/fangyuan-u5b-3d1dd404d70c.woff2 +0 -0
  27. package/assets/fonts/web/fangyuan-u5c-fe0a273f69e7.woff2 +0 -0
  28. package/assets/fonts/web/fangyuan-u5d-af1f0a1c8d2d.woff2 +0 -0
  29. package/assets/fonts/web/fangyuan-u5e-598c65420e17.woff2 +0 -0
  30. package/assets/fonts/web/fangyuan-u5f-a92eaaa5265a.woff2 +0 -0
  31. package/assets/fonts/web/fangyuan-u60-48ee3d26462d.woff2 +0 -0
  32. package/assets/fonts/web/fangyuan-u61-7a57f35bc077.woff2 +0 -0
  33. package/assets/fonts/web/fangyuan-u62-d2d0b7b36631.woff2 +0 -0
  34. package/assets/fonts/web/fangyuan-u63-cade7c6635e6.woff2 +0 -0
  35. package/assets/fonts/web/fangyuan-u64-ed34e40d7f65.woff2 +0 -0
  36. package/assets/fonts/web/fangyuan-u65-e13e83e69c38.woff2 +0 -0
  37. package/assets/fonts/web/fangyuan-u66-1dbcfa5da147.woff2 +0 -0
  38. package/assets/fonts/web/fangyuan-u67-6b0a26b82da6.woff2 +0 -0
  39. package/assets/fonts/web/fangyuan-u68-1b8217cfceed.woff2 +0 -0
  40. package/assets/fonts/web/fangyuan-u69-673e63627790.woff2 +0 -0
  41. package/assets/fonts/web/fangyuan-u6a-3c94008a4640.woff2 +0 -0
  42. package/assets/fonts/web/fangyuan-u6b-44572c410fa0.woff2 +0 -0
  43. package/assets/fonts/web/fangyuan-u6c-1b323b366e88.woff2 +0 -0
  44. package/assets/fonts/web/fangyuan-u6d-cbc376d6fe3f.woff2 +0 -0
  45. package/assets/fonts/web/fangyuan-u6e-7f7e211e2fee.woff2 +0 -0
  46. package/assets/fonts/web/fangyuan-u6f-ff280ce052fa.woff2 +0 -0
  47. package/assets/fonts/web/fangyuan-u70-cb727eaf73b6.woff2 +0 -0
  48. package/assets/fonts/web/fangyuan-u71-0bb1747439fe.woff2 +0 -0
  49. package/assets/fonts/web/fangyuan-u72-cccd39590d69.woff2 +0 -0
  50. package/assets/fonts/web/fangyuan-u73-e67705133584.woff2 +0 -0
  51. package/assets/fonts/web/fangyuan-u74-03a4e7ac9df5.woff2 +0 -0
  52. package/assets/fonts/web/fangyuan-u75-a2d30b327e65.woff2 +0 -0
  53. package/assets/fonts/web/fangyuan-u76-c08fe029c988.woff2 +0 -0
  54. package/assets/fonts/web/fangyuan-u77-76f03be1f4cb.woff2 +0 -0
  55. package/assets/fonts/web/fangyuan-u78-5b721deaf582.woff2 +0 -0
  56. package/assets/fonts/web/fangyuan-u79-db7713c2eda4.woff2 +0 -0
  57. package/assets/fonts/web/fangyuan-u7a-3e40d3726a09.woff2 +0 -0
  58. package/assets/fonts/web/fangyuan-u7b-a8204d1c9dba.woff2 +0 -0
  59. package/assets/fonts/web/fangyuan-u7c-89bcdae046de.woff2 +0 -0
  60. package/assets/fonts/web/fangyuan-u7d-bcc45fa6351a.woff2 +0 -0
  61. package/assets/fonts/web/fangyuan-u7e-49fab96d9269.woff2 +0 -0
  62. package/assets/fonts/web/fangyuan-u7f-dc110e1ecbf3.woff2 +0 -0
  63. package/assets/fonts/web/fangyuan-u80-c5ce9be0335e.woff2 +0 -0
  64. package/assets/fonts/web/fangyuan-u81-b026091b3779.woff2 +0 -0
  65. package/assets/fonts/web/fangyuan-u82-a7c6960e875d.woff2 +0 -0
  66. package/assets/fonts/web/fangyuan-u83-4b7d1c2c50d4.woff2 +0 -0
  67. package/assets/fonts/web/fangyuan-u84-4119128100c8.woff2 +0 -0
  68. package/assets/fonts/web/fangyuan-u85-ca43dd4c5411.woff2 +0 -0
  69. package/assets/fonts/web/fangyuan-u86-54fc0e3158fb.woff2 +0 -0
  70. package/assets/fonts/web/fangyuan-u87-b64f5eb55720.woff2 +0 -0
  71. package/assets/fonts/web/fangyuan-u88-00feb1251f08.woff2 +0 -0
  72. package/assets/fonts/web/fangyuan-u89-db419435b316.woff2 +0 -0
  73. package/assets/fonts/web/fangyuan-u8a-06c11d45fb87.woff2 +0 -0
  74. package/assets/fonts/web/fangyuan-u8b-5c2f6fda436a.woff2 +0 -0
  75. package/assets/fonts/web/fangyuan-u8c-2b46d2d1f4cc.woff2 +0 -0
  76. package/assets/fonts/web/fangyuan-u8d-1a67d064000d.woff2 +0 -0
  77. package/assets/fonts/web/fangyuan-u8e-eb87baf0091c.woff2 +0 -0
  78. package/assets/fonts/web/fangyuan-u8f-96c1f0632da6.woff2 +0 -0
  79. package/assets/fonts/web/fangyuan-u90-86752dba8cbe.woff2 +0 -0
  80. package/assets/fonts/web/fangyuan-u91-0573b8548552.woff2 +0 -0
  81. package/assets/fonts/web/fangyuan-u92-f85ecf735974.woff2 +0 -0
  82. package/assets/fonts/web/fangyuan-u93-e7e0451735db.woff2 +0 -0
  83. package/assets/fonts/web/fangyuan-u94-f3957ff98bcd.woff2 +0 -0
  84. package/assets/fonts/web/fangyuan-u95-b31129d29013.woff2 +0 -0
  85. package/assets/fonts/web/fangyuan-u96-ca7f779c2c13.woff2 +0 -0
  86. package/assets/fonts/web/fangyuan-u97-100a25198b2c.woff2 +0 -0
  87. package/assets/fonts/web/fangyuan-u98-59e4b784a94f.woff2 +0 -0
  88. package/assets/fonts/web/fangyuan-u99-d35af6e30868.woff2 +0 -0
  89. package/assets/fonts/web/fangyuan-u9a-1eb6f7cdfcfe.woff2 +0 -0
  90. package/assets/fonts/web/fangyuan-u9b-8f428d81dcbb.woff2 +0 -0
  91. package/assets/fonts/web/fangyuan-u9c-e10f7f8f0274.woff2 +0 -0
  92. package/assets/fonts/web/fangyuan-u9e-2be65003b759.woff2 +0 -0
  93. package/assets/fonts/web/fangyuan-u9f-02c3d5224fdb.woff2 +0 -0
  94. package/assets/fonts/web/fangyuan-ufb-3eaee54bc476.woff2 +0 -0
  95. package/assets/fonts/web/fangyuan-ufe-f64da8a3acce.woff2 +0 -0
  96. package/assets/fonts/web/fangyuan-uff-0a6dcfb689fd.woff2 +0 -0
  97. package/client/assets/iconsax/LICENSE +16 -0
  98. package/client/assets/iconsax/SOURCE.md +14 -0
  99. package/config/routergo-deepseek.example.yml +25 -0
  100. package/config.example.json +24 -0
  101. package/cordis.patch.yml +5 -0
  102. package/lib/LINK-THIRD-PARTY-LICENSES.txt +1197 -0
  103. package/lib/client.js +3577 -0
  104. package/lib/link-web/app.css +92 -0
  105. package/lib/link-web/app.js +599 -0
  106. package/lib/link-web/index.html +1 -0
  107. package/lib/link-web/workbench.js +118 -0
  108. package/lib/link.mjs +244 -0
  109. package/lib/relay/ip-certificate.mjs +559 -0
  110. package/lib/relay/relay.example.json +8 -0
  111. package/lib/relay/run-relay-server.cjs +4100 -0
  112. package/lib/server/bootstrap.mjs +147 -0
  113. package/lib/server/bootstrap.sh +39 -0
  114. package/lib/server/manifest.json +8 -0
  115. package/lib/server/server-seed.tar.gz +0 -0
  116. package/locale/en.json +6 -0
  117. package/locale/zh-CN.json +6 -0
  118. package/openapi.json +629 -0
  119. package/package.json +104 -4
  120. package/shared/plugin-install.mjs +198 -0
  121. package/shared/tool-quick-settings.mjs +70 -0
  122. package/shared/update-feed.mjs +191 -0
  123. package/shared/update-public-key.pem +3 -0
  124. package/src/cli.mjs +102 -0
  125. package/src/commands.mjs +17 -0
  126. package/src/delegation.mjs +47 -0
  127. package/src/fonts.mjs +17 -0
  128. package/src/harness-adapter.mjs +228 -0
  129. package/src/harness-commands.mjs +39 -0
  130. package/src/harness-selection.mjs +5 -0
  131. package/src/harness-usage.mjs +31 -0
  132. package/src/isolated-launch.mjs +22 -0
  133. package/src/line-process.mjs +114 -0
  134. package/src/link-plugin.mjs +21 -0
  135. package/src/mcp.mjs +21 -0
  136. package/src/model-providers.mjs +125 -0
  137. package/src/models.mjs +37 -0
  138. package/src/native-auth.mjs +32 -0
  139. package/src/picker-catalog.mjs +82 -0
  140. package/src/plugin.mjs +138 -0
  141. package/src/projects.mjs +96 -0
  142. package/src/provider-access.mjs +11 -0
  143. package/src/providers/acp.mjs +138 -0
  144. package/src/providers/claude.mjs +115 -0
  145. package/src/providers/codex.mjs +134 -0
  146. package/src/providers/opencode.mjs +138 -0
  147. package/src/providers/pi-permissions.ts +24 -0
  148. package/src/providers/pi.mjs +97 -0
  149. package/src/questions.mjs +34 -0
  150. package/src/recent-workspace.mjs +36 -0
  151. package/src/runtime.mjs +421 -0
  152. package/src/session-routes.mjs +89 -0
  153. package/src/store.mjs +98 -0
  154. package/src/tool-catalog.mjs +22 -0
  155. package/src/tool-config.mjs +94 -0
  156. package/src/tool-install.mjs +31 -0
  157. package/src/tool-profiles.mjs +114 -0
  158. package/src/tooling.mjs +90 -0
  159. package/src/updates.mjs +156 -0
  160. package/src/usage-import-parsers.mjs +37 -0
  161. package/src/usage-import.mjs +114 -0
  162. package/src/usage-timeline.mjs +36 -0
  163. package/src/usage.mjs +142 -0
  164. package/src/web.mjs +274 -0
  165. package/voice/README.md +49 -0
  166. package/voice/STREAMING.md +141 -0
  167. package/voice/VERIFICATION.md +36 -0
  168. package/voice/client/audio-worklet.js +35 -0
  169. package/voice/locale/en.json +1 -0
  170. package/voice/locale/zh-CN.json +1 -0
  171. package/voice/src/asr.mjs +44 -0
  172. package/voice/src/calls.mjs +37 -0
  173. package/voice/src/config.mjs +139 -0
  174. package/voice/src/media.mjs +70 -0
  175. package/voice/src/plugin.mjs +10 -0
  176. package/voice/src/realtime-protocols.mjs +30 -0
  177. package/voice/src/realtime-socket.mjs +86 -0
  178. package/voice/src/realtime.mjs +130 -0
  179. package/voice/src/tts.mjs +16 -0
  180. package/voice/src/web.mjs +171 -0
package/lib/link.mjs ADDED
@@ -0,0 +1,244 @@
1
+ import { createRequire as linkCreateRequire } from 'node:module'; const require = linkCreateRequire(import.meta.url);
2
+ var il=Object.create;var Ii=Object.defineProperty;var sl=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var cl=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty;var Qa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,a)=>(typeof require<"u"?require:t)[a]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ie=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ul=(e,t,a,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ol(t))!ll.call(e,n)&&n!==a&&Ii(e,n,{get:()=>t[n],enumerable:!(r=sl(t,n))||r.enumerable});return e};var fl=(e,t,a)=>(a=e!=null?il(cl(e)):{},ul(t||!e||!e.__esModule?Ii(a,"default",{value:e,enumerable:!0}):a,e));var ue=ie((kp,_i)=>{_i.exports={options:{usePureJavaScript:!1}}});var Ri=ie((Rp,ki)=>{var Ja={};ki.exports=Ja;var Ni={};Ja.encode=function(e,t,a){if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');if(a!==void 0&&typeof a!="number")throw new TypeError('"maxline" must be a number.');var r="";if(!(e instanceof Uint8Array))r=wl(e,t);else{var n=0,i=t.length,s=t.charAt(0),o=[0];for(n=0;n<e.length;++n){for(var c=0,l=e[n];c<o.length;++c)l+=o[c]<<8,o[c]=l%i,l=l/i|0;for(;l>0;)o.push(l%i),l=l/i|0}for(n=0;e[n]===0&&n<e.length-1;++n)r+=s;for(n=o.length-1;n>=0;--n)r+=t[o[n]]}if(a){var u=new RegExp(".{1,"+a+"}","g");r=r.match(u).join(`\r
3
+ `)}return r};Ja.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var a=Ni[t];if(!a){a=Ni[t]=[];for(var r=0;r<t.length;++r)a[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");for(var n=t.length,i=t.charAt(0),s=[0],r=0;r<e.length;r++){var o=a[e.charCodeAt(r)];if(o===void 0)return;for(var c=0,l=o;c<s.length;++c)l+=s[c]*n,s[c]=l&255,l>>=8;for(;l>0;)s.push(l&255),l>>=8}for(var u=0;e[u]===i&&u<e.length-1;++u)s.push(0);return typeof Buffer<"u"?Buffer.from(s.reverse()):new Uint8Array(s.reverse())};function wl(e,t){var a=0,r=t.length,n=t.charAt(0),i=[0];for(a=0;a<e.length();++a){for(var s=0,o=e.at(a);s<i.length;++s)o+=i[s]<<8,i[s]=o%r,o=o/r|0;for(;o>0;)i.push(o%r),o=o/r|0}var c="";for(a=0;e.at(a)===0&&a<e.length()-1;++a)c+=n;for(a=i.length-1;a>=0;--a)c+=t[i[a]];return c}});var Ce=ie((Lp,Ui)=>{var Li=ue(),Di=Ri(),_=Ui.exports=Li.util=Li.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){_.nextTick=process.nextTick,typeof setImmediate=="function"?_.setImmediate=setImmediate:_.setImmediate=_.nextTick;return}if(typeof setImmediate=="function"){_.setImmediate=function(){return setImmediate.apply(void 0,arguments)},_.nextTick=function(o){return setImmediate(o)};return}if(_.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage=="function"){let o=function(c){if(c.source===window&&c.data===e){c.stopPropagation();var l=t.slice();t.length=0,l.forEach(function(u){u()})}};var s=o,e="forge.setImmediate",t=[];_.setImmediate=function(c){t.push(c),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var a=Date.now(),r=!0,n=document.createElement("div"),t=[];new MutationObserver(function(){var c=t.slice();t.length=0,c.forEach(function(l){l()})}).observe(n,{attributes:!0});var i=_.setImmediate;_.setImmediate=function(c){Date.now()-a>15?(a=Date.now(),i(c)):(t.push(c),t.length===1&&n.setAttribute("a",r=!r))}}_.nextTick=_.setImmediate})();_.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;_.globalScope=(function(){return _.isNodejs?global:typeof self>"u"?window:self})();_.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};_.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};_.isArrayBufferView=function(e){return e&&_.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function Pr(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}_.ByteBuffer=Za;function Za(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(_.isArrayBuffer(e)||_.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var a=0;a<t.length;++a)this.putByte(t[a])}}else(e instanceof Za||typeof e=="object"&&typeof e.data=="string"&&typeof e.read=="number")&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}_.ByteStringBuffer=Za;var xl=4096;_.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>xl&&(this.data.substr(0,1),this._constructedStringLength=0)};_.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};_.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};_.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};_.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var a=this.data;t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return this.data=a,this._optimizeConstructedString(t),this};_.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};_.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(_.encodeUtf8(e))};_.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};_.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};_.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};_.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};_.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};_.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};_.ByteStringBuffer.prototype.putInt=function(e,t){Pr(t);var a="";do t-=8,a+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(a)};_.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)};_.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};_.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};_.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};_.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};_.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};_.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};_.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};_.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};_.ByteStringBuffer.prototype.getInt=function(e){Pr(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};_.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};_.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};_.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};_.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};_.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};_.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};_.ByteStringBuffer.prototype.copy=function(){var e=_.createBuffer(this.data);return e.read=this.read,e};_.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};_.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};_.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};_.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var a=this.data.charCodeAt(t);a<16&&(e+="0"),e+=a.toString(16)}return e};_.ByteStringBuffer.prototype.toString=function(){return _.decodeUtf8(this.bytes())};function Sl(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var a=_.isArrayBuffer(e),r=_.isArrayBufferView(e);if(a||r){a?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!=null&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)}_.DataBuffer=Sl;_.DataBuffer.prototype.length=function(){return this.write-this.read};_.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};_.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var a=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(a),this.data=new DataView(r.buffer),this};_.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};_.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var a=0;a<t;++a)this.data.setUint8(e);return this};_.DataBuffer.prototype.putBytes=function(e,t){if(_.isArrayBufferView(e)){var a=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=a.byteLength-a.byteOffset;this.accommodate(r);var n=new Uint8Array(this.data.buffer,this.write);return n.set(a),this.write+=r,this}if(_.isArrayBuffer(e)){var a=new Uint8Array(e);this.accommodate(a.byteLength);var n=new Uint8Array(this.data.buffer);return n.set(a,this.write),this.write+=a.byteLength,this}if(e instanceof _.DataBuffer||typeof e=="object"&&typeof e.read=="number"&&typeof e.write=="number"&&_.isArrayBufferView(e.data)){var a=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(a.byteLength);var n=new Uint8Array(e.data.byteLength,this.write);return n.set(a),this.write+=a.byteLength,this}if(e instanceof _.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary",typeof e=="string"){var i;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),i=new Uint8Array(this.data.buffer,this.write),this.write+=_.binary.hex.decode(e,i,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),i=new Uint8Array(this.data.buffer,this.write),this.write+=_.binary.base64.decode(e,i,this.write),this;if(t==="utf8"&&(e=_.encodeUtf8(e),t="binary"),t==="binary"||t==="raw")return this.accommodate(e.length),i=new Uint8Array(this.data.buffer,this.write),this.write+=_.binary.raw.decode(i),this;if(t==="utf16")return this.accommodate(e.length*2),i=new Uint16Array(this.data.buffer,this.write),this.write+=_.text.utf16.encode(i),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};_.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};_.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};_.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};_.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};_.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};_.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};_.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};_.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};_.DataBuffer.prototype.putInt=function(e,t){Pr(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};_.DataBuffer.prototype.putSignedInt=function(e,t){return Pr(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)};_.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};_.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};_.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};_.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};_.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};_.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};_.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};_.DataBuffer.prototype.getInt=function(e){Pr(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};_.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};_.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};_.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};_.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};_.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};_.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};_.DataBuffer.prototype.copy=function(){return new _.DataBuffer(this)};_.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};_.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};_.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};_.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var a=this.data.getUint8(t);a<16&&(e+="0"),e+=a.toString(16)}return e};_.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return _.binary.raw.encode(t);if(e==="hex")return _.binary.hex.encode(t);if(e==="base64")return _.binary.base64.encode(t);if(e==="utf8")return _.text.utf8.decode(t);if(e==="utf16")return _.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)};_.createBuffer=function(e,t){return t=t||"raw",e!==void 0&&t==="utf8"&&(e=_.encodeUtf8(e)),new _.ByteBuffer(e)};_.fillString=function(e,t){for(var a="";t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return a};_.xorBytes=function(e,t,a){for(var r="",n="",i="",s=0,o=0;a>0;--a,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(r+=i,i="",o=0),i+=String.fromCharCode(n),++o;return r+=i,r};_.hexToBytes=function(e){var t="",a=0;for(e.length&!0&&(a=1,t+=String.fromCharCode(parseInt(e[0],16)));a<e.length;a+=2)t+=String.fromCharCode(parseInt(e.substr(a,2),16));return t};_.bytesToHex=function(e){return _.createBuffer(e).toHex()};_.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ft=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Pi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";_.encode64=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.length;)n=e.charCodeAt(o++),i=e.charCodeAt(o++),s=e.charCodeAt(o++),a+=Kt.charAt(n>>2),a+=Kt.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Kt.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Kt.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
4
+ `,a=a.substr(t));return r+=a,r};_.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",a,r,n,i,s=0;s<e.length;)a=Ft[e.charCodeAt(s++)-43],r=Ft[e.charCodeAt(s++)-43],n=Ft[e.charCodeAt(s++)-43],i=Ft[e.charCodeAt(s++)-43],t+=String.fromCharCode(a<<2|r>>4),n!==64&&(t+=String.fromCharCode((r&15)<<4|n>>2),i!==64&&(t+=String.fromCharCode((n&3)<<6|i)));return t};_.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};_.decodeUtf8=function(e){return decodeURIComponent(escape(e))};_.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Di.encode,decode:Di.decode}};_.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};_.binary.raw.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};_.binary.hex.encode=_.bytesToHex;_.binary.hex.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/2))),a=a||0;var n=0,i=a;for(e.length&1&&(n=1,r[i++]=parseInt(e[0],16));n<e.length;n+=2)r[i++]=parseInt(e.substr(n,2),16);return t?i-a:r};_.binary.base64.encode=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.byteLength;)n=e[o++],i=e[o++],s=e[o++],a+=Kt.charAt(n>>2),a+=Kt.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Kt.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Kt.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
5
+ `,a=a.substr(t));return r+=a,r};_.binary.base64.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),a=a||0;for(var n,i,s,o,c=0,l=a;c<e.length;)n=Ft[e.charCodeAt(c++)-43],i=Ft[e.charCodeAt(c++)-43],s=Ft[e.charCodeAt(c++)-43],o=Ft[e.charCodeAt(c++)-43],r[l++]=n<<2|i>>4,s!==64&&(r[l++]=(i&15)<<4|s>>2,o!==64&&(r[l++]=(s&3)<<6|o));return t?l-a:r.subarray(0,l)};_.binary.base58.encode=function(e,t){return _.binary.baseN.encode(e,Pi,t)};_.binary.base58.decode=function(e,t){return _.binary.baseN.decode(e,Pi,t)};_.text={utf8:{},utf16:{}};_.text.utf8.encode=function(e,t,a){e=_.encodeUtf8(e);var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};_.text.utf8.decode=function(e){return _.decodeUtf8(String.fromCharCode.apply(null,e))};_.text.utf16.encode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length*2));var n=new Uint16Array(r.buffer);a=a||0;for(var i=a,s=a,o=0;o<e.length;++o)n[s++]=e.charCodeAt(o),i+=2;return t?i-a:r};_.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};_.deflate=function(e,t,a){if(t=_.decode64(e.deflate(_.encode64(t)).rval),a){var r=2,n=t.charCodeAt(1);n&32&&(r=6),t=t.substring(r,t.length-4)}return t};_.inflate=function(e,t,a){var r=e.inflate(_.encode64(t)).rval;return r===null?null:_.decode64(r)};var en=function(e,t,a){if(!e)throw new Error("WebStorage not available.");var r;if(a===null?r=e.removeItem(t):(a=_.encode64(JSON.stringify(a)),r=e.setItem(t,a)),typeof r<"u"&&r.rval!==!0){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}},tn=function(e,t){if(!e)throw new Error("WebStorage not available.");var a=e.getItem(t);if(e.init)if(a.rval===null){if(a.error){var r=new Error(a.error.message);throw r.id=a.error.id,r.name=a.error.name,r}a=null}else a=a.rval;return a!==null&&(a=JSON.parse(_.decode64(a))),a},bl=function(e,t,a,r){var n=tn(e,t);n===null&&(n={}),n[a]=r,en(e,t,n)},Tl=function(e,t,a){var r=tn(e,t);return r!==null&&(r=a in r?r[a]:null),r},Il=function(e,t,a){var r=tn(e,t);if(r!==null&&a in r){delete r[a];var n=!0;for(var i in r){n=!1;break}n&&(r=null),en(e,t,r)}},Al=function(e,t){en(e,t,null)},ca=function(e,t,a){var r=null;typeof a>"u"&&(a=["web","flash"]);var n,i=!1,s=null;for(var o in a){n=a[o];try{if(n==="flash"||n==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");r=e.apply(this,t),i=n==="flash"}(n==="web"||n==="both")&&(t[0]=localStorage,r=e.apply(this,t),i=!0)}catch(c){s=c}if(i)break}if(!i)throw s;return r};_.setItem=function(e,t,a,r,n){ca(bl,arguments,n)};_.getItem=function(e,t,a,r){return ca(Tl,arguments,r)};_.removeItem=function(e,t,a,r){ca(Il,arguments,r)};_.clearItems=function(e,t,a){ca(Al,arguments,a)};_.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};_.format=function(e){for(var t=/%./g,a,r,n=0,i=[],s=0;a=t.exec(e);){r=e.substring(s,t.lastIndex-2),r.length>0&&i.push(r),s=t.lastIndex;var o=a[0][1];switch(o){case"s":case"o":n<arguments.length?i.push(arguments[n+++1]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")};_.formatNumber=function(e,t,a,r){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=a===void 0?",":a,o=r===void 0?".":r,c=n<0?"-":"",l=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+o:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-l).toFixed(i).slice(2):"")};_.formatSize=function(e){return e>=1073741824?e=_.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=_.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=_.formatNumber(e/1024,0)+" KiB":e=_.formatNumber(e,0)+" bytes",e};_.bytesFromIP=function(e){return e.indexOf(".")!==-1?_.bytesFromIPv4(e):e.indexOf(":")!==-1?_.bytesFromIPv6(e):null};_.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=_.createBuffer(),a=0;a<e.length;++a){var r=parseInt(e[a],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};_.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(s){return s.length===0&&++t,!0});for(var a=(8-e.length+t)*2,r=_.createBuffer(),n=0;n<8;++n){if(!e[n]||e[n].length===0){r.fillWithByte(0,a),a=0;continue}var i=_.hexToBytes(e[n]);i.length<2&&r.putByte(0),r.putBytes(i)}return r.getBytes()};_.bytesToIP=function(e){return e.length===4?_.bytesToIPv4(e):e.length===16?_.bytesToIPv6(e):null};_.bytesToIPv4=function(e){if(e.length!==4)return null;for(var t=[],a=0;a<e.length;++a)t.push(e.charCodeAt(a));return t.join(".")};_.bytesToIPv6=function(e){if(e.length!==16)return null;for(var t=[],a=[],r=0,n=0;n<e.length;n+=2){for(var i=_.bytesToHex(e[n]+e[n+1]);i[0]==="0"&&i!=="0";)i=i.substr(1);if(i==="0"){var s=a[a.length-1],o=t.length;!s||o!==s.end+1?a.push({start:o,end:o}):(s.end=o,s.end-s.start>a[r].end-a[r].start&&(r=a.length-1))}t.push(i)}if(a.length>0){var c=a[r];c.end-c.start>0&&(t.splice(c.start,c.end-c.start+1,""),c.start===0&&t.unshift(""),c.end===7&&t.push(""))}return t.join(":")};_.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in _&&!e.update)return t(null,_.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return _.cores=navigator.hardwareConcurrency,t(null,_.cores);if(typeof Worker>"u")return _.cores=1,t(null,_.cores);if(typeof Blob>"u")return _.cores=2,t(null,_.cores);var a=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){for(var o=Date.now(),c=o+4;Date.now()<c;);self.postMessage({st:o,et:c})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,o,c){if(o===0){var l=Math.floor(s.reduce(function(u,f){return u+f},0)/s.length);return _.cores=Math.max(1,l),URL.revokeObjectURL(a),t(null,_.cores)}n(c,function(u,f){s.push(i(c,f)),r(s,o-1,c)})}function n(s,o){for(var c=[],l=[],u=0;u<s;++u){var f=new Worker(a);f.addEventListener("message",function(h){if(l.push(h.data),l.length===s){for(var m=0;m<s;++m)c[m].terminate();o(null,l)}}),c.push(f)}for(var u=0;u<s;++u)c[u].postMessage(u)}function i(s,o){for(var c=[],l=0;l<s;++l)for(var u=o[l],f=c[l]=[],h=0;h<s;++h)if(l!==h){var m=o[h];(u.st>m.st&&u.st<m.et||m.st>u.st&&m.st<u.et)&&f.push(h)}return c.reduce(function(d,p){return Math.max(d,p.length)},0)}}});var la=ie((Dp,Oi)=>{var Fe=ue();Ce();Oi.exports=Fe.cipher=Fe.cipher||{};Fe.cipher.algorithms=Fe.cipher.algorithms||{};Fe.cipher.createCipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Fe.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Fe.cipher.BlockCipher({algorithm:a,key:t,decrypt:!1})};Fe.cipher.createDecipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Fe.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Fe.cipher.BlockCipher({algorithm:a,key:t,decrypt:!0})};Fe.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),Fe.cipher.algorithms[e]=t};Fe.cipher.getAlgorithm=function(e){return e=e.toUpperCase(),e in Fe.cipher.algorithms?Fe.cipher.algorithms[e]:null};var rn=Fe.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};rn.prototype.start=function(e){e=e||{};var t={};for(var a in e)t[a]=e[a];t.decrypt=this._decrypt,this._finish=!1,this._input=Fe.util.createBuffer(),this.output=e.output||Fe.util.createBuffer(),this.mode.start(t)};rn.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};rn.prototype.finish=function(e){e&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(a){return e(this.blockSize,a,!1)},this.mode.unpad=function(a){return e(this.blockSize,a,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t))}});var nn=ie((Pp,Vi)=>{var Me=ue();Ce();Me.cipher=Me.cipher||{};var de=Vi.exports=Me.cipher.modes=Me.cipher.modes||{};de.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};de.ecb.prototype.start=function(e){};de.ecb.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};de.ecb.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};de.ecb.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};de.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};de.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};de.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=ua(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};de.cbc.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=this._prev[r]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r]);this._prev=this._outBlock};de.cbc.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._prev[r]^this._outBlock[r]);this._prev=this._inBlock.slice(0)};de.cbc.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};de.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};de.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=Me.util.createBuffer(),this._partialBytes=0};de.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ua(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};de.cfb.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32()^this._outBlock[n],t.putInt32(this._inBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32()^this._outBlock[n],this._partialOutput.putInt32(this._partialBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};de.cfb.prototype.decrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32(),t.putInt32(this._inBlock[n]^this._outBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[n]^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};de.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Me.util.createBuffer(),this._partialBytes=0};de.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ua(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};de.ofb.prototype.encrypt=function(e,t,a){var r=e.length();if(e.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]),this._inBlock[n]=this._outBlock[n];return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._outBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};de.ofb.prototype.decrypt=de.ofb.prototype.encrypt;de.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Me.util.createBuffer(),this._partialBytes=0};de.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ua(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};de.ctr.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize)for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]);else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}fa(this._inBlock)};de.ctr.prototype.decrypt=de.ctr.prototype.encrypt;de.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=Me.util.createBuffer(),this._partialBytes=0,this._R=3774873600};de.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=Me.util.createBuffer(e.iv);this._cipherLength=0;var a;if("additionalData"in e?a=Me.util.createBuffer(e.additionalData):a=Me.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=Me.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(an(r*8)))}this._inBlock=this._j0.slice(0),fa(this._inBlock),this._partialBytes=0,a=Me.util.createBuffer(a),this._aDataLength=an(a.length()*8);var n=a.length()%this.blockSize;for(n&&a.fillWithByte(0,this.blockSize-n),this._s=[0,0,0,0];a.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[a.getInt32(),a.getInt32(),a.getInt32(),a.getInt32()])};de.gcm.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^=e.getInt32());this._cipherLength+=this.blockSize}else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i<=0||a){if(a){var s=r%this.blockSize;this._cipherLength+=s,this._partialOutput.truncate(this.blockSize-s)}else this._cipherLength+=this.blockSize;for(var n=0;n<this._ints;++n)this._outBlock[n]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),fa(this._inBlock)};de.gcm.prototype.decrypt=function(e,t,a){var r=e.length();if(r<this.blockSize&&!(a&&r>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),fa(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^this._hashBlock[n]);r<this.blockSize?this._cipherLength+=r%this.blockSize:this._cipherLength+=this.blockSize};de.gcm.prototype.afterFinish=function(e,t){var a=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=Me.util.createBuffer();var r=this._aDataLength.concat(an(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var n=[];this.cipher.encrypt(this._j0,n);for(var i=0;i<this._ints;++i)this.tag.putInt32(this._s[i]^n[i]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(a=!1),a};de.gcm.prototype.multiply=function(e,t){for(var a=[0,0,0,0],r=t.slice(0),n=0;n<128;++n){var i=e[n/32|0]&1<<31-n%32;i&&(a[0]^=r[0],a[1]^=r[1],a[2]^=r[2],a[3]^=r[3]),this.pow(r,r)}return a};de.gcm.prototype.pow=function(e,t){for(var a=e[3]&1,r=3;r>0;--r)t[r]=e[r]>>>1|(e[r-1]&1)<<31;t[0]=e[0]>>>1,a&&(t[0]^=this._R)};de.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],a=0;a<32;++a){var r=a/8|0,n=e[r]>>>(7-a%8)*4&15,i=this._m[a][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t};de.gcm.prototype.ghash=function(e,t,a){return t[0]^=a[0],t[1]^=a[1],t[2]^=a[2],t[3]^=a[3],this.tableMultiply(t)};de.gcm.prototype.generateHashTable=function(e,t){for(var a=8/t,r=4*a,n=16*a,i=new Array(n),s=0;s<n;++s){var o=[0,0,0,0],c=s/r|0,l=(r-1-s%r)*t;o[c]=1<<t-1<<l,i[s]=this.generateSubHashTable(this.multiply(o,e),t)}return i};de.gcm.prototype.generateSubHashTable=function(e,t){var a=1<<t,r=a>>>1,n=new Array(a);n[r]=e.slice(0);for(var i=r>>>1;i>0;)this.pow(n[2*i],n[i]=[]),i>>=1;for(i=2;i<r;){for(var s=1;s<i;++s){var o=n[i],c=n[s];n[i+s]=[o[0]^c[0],o[1]^c[1],o[2]^c[2],o[3]^c[3]]}i*=2}for(n[0]=[0,0,0,0],i=r+1;i<a;++i){var l=n[i^r];n[i]=[e[0]^l[0],e[1]^l[1],e[2]^l[2],e[3]^l[3]]}return n};function ua(e,t){if(typeof e=="string"&&(e=Me.util.createBuffer(e)),Me.util.isArray(e)&&e.length>4){var a=e;e=Me.util.createBuffer();for(var r=0;r<a.length;++r)e.putByte(a[r])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!Me.util.isArray(e)){for(var n=[],i=t/4,r=0;r<i;++r)n.push(e.getInt32());e=n}return e}function fa(e){e[e.length-1]=e[e.length-1]+1&4294967295}function an(e){return[e/4294967296|0,e&4294967295]}});var Mt=ie((Up,Hi)=>{var Ae=ue();la();nn();Ce();Hi.exports=Ae.aes=Ae.aes||{};Ae.aes.startEncrypting=function(e,t,a,r){var n=da({key:e,output:a,decrypt:!1,mode:r});return n.start(t),n};Ae.aes.createEncryptionCipher=function(e,t){return da({key:e,output:null,decrypt:!1,mode:t})};Ae.aes.startDecrypting=function(e,t,a,r){var n=da({key:e,output:a,decrypt:!0,mode:r});return n.start(t),n};Ae.aes.createDecryptionCipher=function(e,t){return da({key:e,output:null,decrypt:!0,mode:t})};Ae.aes.Algorithm=function(e,t){cn||Fi();var a=this;a.name=e,a.mode=new t({blockSize:16,cipher:{encrypt:function(r,n){return on(a._w,r,n,!1)},decrypt:function(r,n){return on(a._w,r,n,!0)}}}),a._init=!1};Ae.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t=e.key,a;if(typeof t=="string"&&(t.length===16||t.length===24||t.length===32))t=Ae.util.createBuffer(t);else if(Ae.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){a=t,t=Ae.util.createBuffer();for(var r=0;r<a.length;++r)t.putByte(a[r])}if(!Ae.util.isArray(t)){a=t,t=[];var n=a.length();if(n===16||n===24||n===32){n=n>>>2;for(var r=0;r<n;++r)t.push(a.getInt32())}}if(!Ae.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw new Error("Invalid key parameter.");var i=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(i)!==-1;this._w=Mi(t,e.decrypt&&!s),this._init=!0}};Ae.aes._expandKey=function(e,t){return cn||Fi(),Mi(e,t)};Ae.aes._updateBlock=on;pr("AES-ECB",Ae.cipher.modes.ecb);pr("AES-CBC",Ae.cipher.modes.cbc);pr("AES-CFB",Ae.cipher.modes.cfb);pr("AES-OFB",Ae.cipher.modes.ofb);pr("AES-CTR",Ae.cipher.modes.ctr);pr("AES-GCM",Ae.cipher.modes.gcm);function pr(e,t){var a=function(){return new Ae.aes.Algorithm(e,t)};Ae.cipher.registerAlgorithm(e,a)}var cn=!1,hr=4,Ze,sn,Ki,Zt,yt;function Fi(){cn=!0,Ki=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;Ze=new Array(256),sn=new Array(256),Zt=new Array(4),yt=new Array(4);for(var t=0;t<4;++t)Zt[t]=new Array(256),yt[t]=new Array(256);for(var a=0,r=0,n,i,s,o,c,l,u,t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,Ze[a]=o,sn[o]=a,c=e[o],n=e[a],i=e[n],s=e[i],l=c<<24^o<<16^o<<8^(o^c),u=(n^i^s)<<24^(a^s)<<16^(a^i^s)<<8^(a^n^s);for(var f=0;f<4;++f)Zt[f][a]=l,yt[f][o]=u,l=l<<24|l>>>8,u=u<<24|u>>>8;a===0?a=r=1:(a=n^e[e[e[n^s]]],r^=e[e[r]])}}function Mi(e,t){for(var a=e.slice(0),r,n=1,i=a.length,s=i+6+1,o=hr*s,c=i;c<o;++c)r=a[c-1],c%i===0?(r=Ze[r>>>16&255]<<24^Ze[r>>>8&255]<<16^Ze[r&255]<<8^Ze[r>>>24]^Ki[n]<<24,n++):i>6&&c%i===4&&(r=Ze[r>>>24]<<24^Ze[r>>>16&255]<<16^Ze[r>>>8&255]<<8^Ze[r&255]),a[c]=a[c-i]^r;if(t){var l,u=yt[0],f=yt[1],h=yt[2],m=yt[3],d=a.slice(0);o=a.length;for(var c=0,p=o-hr;c<o;c+=hr,p-=hr)if(c===0||c===o-hr)d[c]=a[p],d[c+1]=a[p+3],d[c+2]=a[p+2],d[c+3]=a[p+1];else for(var E=0;E<hr;++E)l=a[p+E],d[c+(3&-E)]=u[Ze[l>>>24]]^f[Ze[l>>>16&255]]^h[Ze[l>>>8&255]]^m[Ze[l&255]];a=d}return a}function on(e,t,a,r){var n=e.length/4-1,i,s,o,c,l;r?(i=yt[0],s=yt[1],o=yt[2],c=yt[3],l=sn):(i=Zt[0],s=Zt[1],o=Zt[2],c=Zt[3],l=Ze);var u,f,h,m,d,p,E;u=t[0]^e[0],f=t[r?3:1]^e[1],h=t[2]^e[2],m=t[r?1:3]^e[3];for(var b=3,N=1;N<n;++N)d=i[u>>>24]^s[f>>>16&255]^o[h>>>8&255]^c[m&255]^e[++b],p=i[f>>>24]^s[h>>>16&255]^o[m>>>8&255]^c[u&255]^e[++b],E=i[h>>>24]^s[m>>>16&255]^o[u>>>8&255]^c[f&255]^e[++b],m=i[m>>>24]^s[u>>>16&255]^o[f>>>8&255]^c[h&255]^e[++b],u=d,f=p,h=E;a[0]=l[u>>>24]<<24^l[f>>>16&255]<<16^l[h>>>8&255]<<8^l[m&255]^e[++b],a[r?3:1]=l[f>>>24]<<24^l[h>>>16&255]<<16^l[m>>>8&255]<<8^l[u&255]^e[++b],a[2]=l[h>>>24]<<24^l[m>>>16&255]<<16^l[u>>>8&255]<<8^l[f&255]^e[++b],a[r?1:3]=l[m>>>24]<<24^l[u>>>16&255]<<16^l[f>>>8&255]<<8^l[h&255]^e[++b]}function da(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="AES-"+t,r;e.decrypt?r=Ae.cipher.createDecipher(a,e.key):r=Ae.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof Ae.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var Ht=ie((Op,qi)=>{var Ur=ue();Ur.pki=Ur.pki||{};var ln=qi.exports=Ur.pki.oids=Ur.oids=Ur.oids||{};function H(e,t){ln[e]=t,ln[t]=e}function we(e,t){ln[e]=t}H("1.2.840.113549.1.1.1","rsaEncryption");H("1.2.840.113549.1.1.4","md5WithRSAEncryption");H("1.2.840.113549.1.1.5","sha1WithRSAEncryption");H("1.2.840.113549.1.1.7","RSAES-OAEP");H("1.2.840.113549.1.1.8","mgf1");H("1.2.840.113549.1.1.9","pSpecified");H("1.2.840.113549.1.1.10","RSASSA-PSS");H("1.2.840.113549.1.1.11","sha256WithRSAEncryption");H("1.2.840.113549.1.1.12","sha384WithRSAEncryption");H("1.2.840.113549.1.1.13","sha512WithRSAEncryption");H("1.3.101.112","EdDSA25519");H("1.2.840.10040.4.3","dsa-with-sha1");H("1.3.14.3.2.7","desCBC");H("1.3.14.3.2.26","sha1");H("1.3.14.3.2.29","sha1WithRSASignature");H("2.16.840.1.101.3.4.2.1","sha256");H("2.16.840.1.101.3.4.2.2","sha384");H("2.16.840.1.101.3.4.2.3","sha512");H("2.16.840.1.101.3.4.2.4","sha224");H("2.16.840.1.101.3.4.2.5","sha512-224");H("2.16.840.1.101.3.4.2.6","sha512-256");H("1.2.840.113549.2.2","md2");H("1.2.840.113549.2.5","md5");H("1.2.840.113549.1.7.1","data");H("1.2.840.113549.1.7.2","signedData");H("1.2.840.113549.1.7.3","envelopedData");H("1.2.840.113549.1.7.4","signedAndEnvelopedData");H("1.2.840.113549.1.7.5","digestedData");H("1.2.840.113549.1.7.6","encryptedData");H("1.2.840.113549.1.9.1","emailAddress");H("1.2.840.113549.1.9.2","unstructuredName");H("1.2.840.113549.1.9.3","contentType");H("1.2.840.113549.1.9.4","messageDigest");H("1.2.840.113549.1.9.5","signingTime");H("1.2.840.113549.1.9.6","counterSignature");H("1.2.840.113549.1.9.7","challengePassword");H("1.2.840.113549.1.9.8","unstructuredAddress");H("1.2.840.113549.1.9.14","extensionRequest");H("1.2.840.113549.1.9.20","friendlyName");H("1.2.840.113549.1.9.21","localKeyId");H("1.2.840.113549.1.9.22.1","x509Certificate");H("1.2.840.113549.1.12.10.1.1","keyBag");H("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");H("1.2.840.113549.1.12.10.1.3","certBag");H("1.2.840.113549.1.12.10.1.4","crlBag");H("1.2.840.113549.1.12.10.1.5","secretBag");H("1.2.840.113549.1.12.10.1.6","safeContentsBag");H("1.2.840.113549.1.5.13","pkcs5PBES2");H("1.2.840.113549.1.5.12","pkcs5PBKDF2");H("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");H("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");H("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");H("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");H("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");H("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");H("1.2.840.113549.2.7","hmacWithSHA1");H("1.2.840.113549.2.8","hmacWithSHA224");H("1.2.840.113549.2.9","hmacWithSHA256");H("1.2.840.113549.2.10","hmacWithSHA384");H("1.2.840.113549.2.11","hmacWithSHA512");H("1.2.840.113549.3.7","des-EDE3-CBC");H("2.16.840.1.101.3.4.1.2","aes128-CBC");H("2.16.840.1.101.3.4.1.22","aes192-CBC");H("2.16.840.1.101.3.4.1.42","aes256-CBC");H("2.5.4.3","commonName");H("2.5.4.4","surname");H("2.5.4.5","serialNumber");H("2.5.4.6","countryName");H("2.5.4.7","localityName");H("2.5.4.8","stateOrProvinceName");H("2.5.4.9","streetAddress");H("2.5.4.10","organizationName");H("2.5.4.11","organizationalUnitName");H("2.5.4.12","title");H("2.5.4.13","description");H("2.5.4.15","businessCategory");H("2.5.4.17","postalCode");H("2.5.4.42","givenName");H("2.5.4.65","pseudonym");H("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");H("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");H("2.16.840.1.113730.1.1","nsCertType");H("2.16.840.1.113730.1.13","nsComment");we("2.5.29.1","authorityKeyIdentifier");we("2.5.29.2","keyAttributes");we("2.5.29.3","certificatePolicies");we("2.5.29.4","keyUsageRestriction");we("2.5.29.5","policyMapping");we("2.5.29.6","subtreesConstraint");we("2.5.29.7","subjectAltName");we("2.5.29.8","issuerAltName");we("2.5.29.9","subjectDirectoryAttributes");we("2.5.29.10","basicConstraints");we("2.5.29.11","nameConstraints");we("2.5.29.12","policyConstraints");we("2.5.29.13","basicConstraints");H("2.5.29.14","subjectKeyIdentifier");H("2.5.29.15","keyUsage");we("2.5.29.16","privateKeyUsagePeriod");H("2.5.29.17","subjectAltName");H("2.5.29.18","issuerAltName");H("2.5.29.19","basicConstraints");we("2.5.29.20","cRLNumber");we("2.5.29.21","cRLReason");we("2.5.29.22","expirationDate");we("2.5.29.23","instructionCode");we("2.5.29.24","invalidityDate");we("2.5.29.25","cRLDistributionPoints");we("2.5.29.26","issuingDistributionPoint");we("2.5.29.27","deltaCRLIndicator");we("2.5.29.28","issuingDistributionPoint");we("2.5.29.29","certificateIssuer");we("2.5.29.30","nameConstraints");H("2.5.29.31","cRLDistributionPoints");H("2.5.29.32","certificatePolicies");we("2.5.29.33","policyMappings");we("2.5.29.34","policyConstraints");H("2.5.29.35","authorityKeyIdentifier");we("2.5.29.36","policyConstraints");H("2.5.29.37","extKeyUsage");we("2.5.29.46","freshestCRL");we("2.5.29.54","inhibitAnyPolicy");H("1.3.6.1.4.1.11129.2.4.2","timestampList");H("1.3.6.1.5.5.7.1.1","authorityInfoAccess");H("1.3.6.1.5.5.7.3.1","serverAuth");H("1.3.6.1.5.5.7.3.2","clientAuth");H("1.3.6.1.5.5.7.3.3","codeSigning");H("1.3.6.1.5.5.7.3.4","emailProtection");H("1.3.6.1.5.5.7.3.8","timeStamping")});var gt=ie((Vp,ji)=>{var _e=ue();Ce();Ht();var Q=ji.exports=_e.asn1=_e.asn1||{};Q.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};Q.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};Q.maxDepth=256;Q.create=function(e,t,a,r,n){if(_e.util.isArray(r)){for(var i=[],s=0;s<r.length;++s)r[s]!==void 0&&i.push(r[s]);r=i}var o={tagClass:e,type:t,constructed:a,composed:a||_e.util.isArray(r),value:r};return n&&"bitStringContents"in n&&(o.bitStringContents=n.bitStringContents,o.original=Q.copy(o)),o};Q.copy=function(e,t){var a;if(_e.util.isArray(e)){a=[];for(var r=0;r<e.length;++r)a.push(Q.copy(e[r],t));return a}return typeof e=="string"?e:(a={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:Q.copy(e.value,t)},t&&!t.excludeBitStringContents&&(a.bitStringContents=e.bitStringContents),a)};Q.equals=function(e,t,a){if(_e.util.isArray(e)){if(!_e.util.isArray(t)||e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!Q.equals(e[r],t[r]))return!1;return!0}if(typeof e!=typeof t)return!1;if(typeof e=="string")return e===t;var n=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&Q.equals(e.value,t.value);return a&&a.includeBitStringContents&&(n=n&&e.bitStringContents===t.bitStringContents),n};Q.getBerValueLength=function(e){var t=e.getByte();if(t!==128){var a,r=t&128;return r?a=e.getInt((t&127)<<3):a=t,a}};function Or(e,t,a){if(a>t){var r=new Error("Too few bytes to parse DER.");throw r.available=e.length(),r.remaining=t,r.requested=a,r}}var Bl=function(e,t){var a=e.getByte();if(t--,a!==128){var r,n=a&128;if(!n)r=a;else{var i=a&127;Or(e,t,i),r=e.getInt(i<<3)}if(r<0)throw new Error("Negative length: "+r);return r}};Q.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"maxDepth"in t||(t.maxDepth=Q.maxDepth),typeof e=="string"&&(e=_e.util.createBuffer(e));var a=e.length(),r=ha(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var n=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw n.byteCount=a,n.remaining=e.length(),n}return r};function ha(e,t,a,r){if(a>=r.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var n;Or(e,t,2);var i=e.getByte();t--;var s=i&192,o=i&31;n=e.length();var c=Bl(e,t);if(t-=n-e.length(),c!==void 0&&c>t){if(r.strict){var l=new Error("Too few bytes to read ASN.1 value.");throw l.available=e.length(),l.remaining=t,l.requested=c,l}c=t}var u,f,h=(i&32)===32;if(h)if(u=[],c===void 0)for(;;){if(Or(e,t,2),e.bytes(2)==="\0\0"){e.getBytes(2),t-=2;break}n=e.length(),u.push(ha(e,t,a+1,r)),t-=n-e.length()}else for(;c>0;)n=e.length(),u.push(ha(e,c,a+1,r)),t-=n-e.length(),c-=n-e.length();if(u===void 0&&s===Q.Class.UNIVERSAL&&o===Q.Type.BITSTRING&&(f=e.bytes(c)),u===void 0&&r.decodeBitStrings&&s===Q.Class.UNIVERSAL&&o===Q.Type.BITSTRING&&c>1){var m=e.read,d=t,p=0;if(o===Q.Type.BITSTRING&&(Or(e,t,1),p=e.getByte(),t--),p===0)try{n=e.length();var E={strict:!0,decodeBitStrings:!0},b=ha(e,t,a+1,E),N=n-e.length();t-=N,o==Q.Type.BITSTRING&&N++;var T=b.tagClass;N===c&&(T===Q.Class.UNIVERSAL||T===Q.Class.CONTEXT_SPECIFIC)&&(u=[b])}catch{}u===void 0&&(e.read=m,t=d)}if(u===void 0){if(c===void 0){if(r.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");c=t}if(o===Q.Type.BMPSTRING)for(u="";c>0;c-=2)Or(e,t,2),u+=String.fromCharCode(e.getInt16()),t-=2;else u=e.getBytes(c),t-=c}var S=f===void 0?null:{bitStringContents:f};return Q.create(s,o,h,u,S)}Q.toDer=function(e){var t=_e.util.createBuffer(),a=e.tagClass|e.type,r=_e.util.createBuffer(),n=!1;if("bitStringContents"in e&&(n=!0,e.original&&(n=Q.equals(e,e.original))),n)r.putBytes(e.bitStringContents);else if(e.composed){e.constructed?a|=32:r.putByte(0);for(var i=0;i<e.value.length;++i)e.value[i]!==void 0&&r.putBuffer(Q.toDer(e.value[i]))}else if(e.type===Q.Type.BMPSTRING)for(var i=0;i<e.value.length;++i)r.putInt16(e.value.charCodeAt(i));else e.type===Q.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&(e.value.charCodeAt(1)&128)===0||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?r.putBytes(e.value.substr(1)):r.putBytes(e.value);if(t.putByte(a),r.length()<=127)t.putByte(r.length()&127);else{var s=r.length(),o="";do o+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(o.length|128);for(var i=o.length-1;i>=0;--i)t.putByte(o.charCodeAt(i))}return t.putBuffer(r),t};Q.oidToDer=function(e){var t=e.split("."),a=_e.util.createBuffer();a.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var r,n,i,s,o=2;o<t.length;++o){if(r=!0,n=[],i=parseInt(t[o],10),i>4294967295)throw new Error("OID value too large; max is 32-bits.");do s=i&127,i=i>>>7,r||(s|=128),n.push(s),r=!1;while(i>0);for(var c=n.length-1;c>=0;--c)a.putByte(n[c])}return a};Q.derToOid=function(e){var t;typeof e=="string"&&(e=_e.util.createBuffer(e));var a=e.getByte();t=Math.floor(a/40)+"."+a%40;for(var r=0;e.length()>0;){if(r>70368744177663)throw new Error("OID value too large; max is 53-bits.");a=e.getByte(),r=r*128,a&128?r+=a&127:(t+="."+(r+a),r=0)}return t};Q.utcTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,2),10);a=a>=50?1900+a:2e3+a;var r=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),l=10;c!=="+"&&c!=="-"&&(o=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,0),l&&(c=e.charAt(l),c==="+"||c==="-")){var u=parseInt(e.substr(l+1,2),10),f=parseInt(e.substr(l+4,2),10),h=u*60+f;h*=6e4,c==="+"?t.setTime(+t-h):t.setTime(+t+h)}return t};Q.generalizedTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;e.charAt(e.length-1)==="Z"&&(u=!0);var f=e.length-5,h=e.charAt(f);if(h==="+"||h==="-"){var m=parseInt(e.substr(f+1,2),10),d=parseInt(e.substr(f+4,2),10);l=m*60+d,l*=6e4,h==="+"&&(l*=-1),u=!0}return e.charAt(14)==="."&&(c=parseFloat(e.substr(14),10)*1e3),u?(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,c),t.setTime(+t+l)):(t.setFullYear(a,r,n),t.setHours(i,s,o,c)),t};Q.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push((""+e.getUTCFullYear()).substr(2)),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};Q.dateToGeneralizedTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push(""+e.getUTCFullYear()),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};Q.integerToDer=function(e){var t=_e.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var a=new Error("Integer too large; max is 32-bits.");throw a.integer=e,a};Q.derToInteger=function(e){typeof e=="string"&&(e=_e.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};Q.validate=function(e,t,a,r){var n=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(n=!0,t.value&&_e.util.isArray(t.value))for(var i=0,s=0;n&&s<t.value.length;++s){var o=t.value[s];n=!!o.optional;var c=e.value[i];if(!c){o.optional||(n=!1,r&&r.push("["+t.name+'] Missing required element. Expected tag class "'+o.tagClass+'", type "'+o.type+'"'));continue}var l=typeof o.tagClass<"u"&&typeof o.type<"u";if(l&&(c.tagClass!==o.tagClass||c.type!==o.type))if(o.optional){n=!0;continue}else{n=!1,r&&r.push("["+t.name+"] Tag mismatch. Expected ("+o.tagClass+","+o.type+"), got ("+c.tagClass+","+c.type+")");break}var u=Q.validate(c,o,a,r);if(u)++i,n=!0;else if(o.optional)n=!0;else{n=!1;break}}if(n&&a&&(t.capture&&(a[t.capture]=e.value),t.captureAsn1&&(a[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(a[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e)){var f;if(e.bitStringContents.length<2)a[t.captureBitStringValue]="";else{var h=e.bitStringContents.charCodeAt(0);if(h!==0)throw new Error("captureBitStringValue only supported for zero unused bits");a[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}else r&&r.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');else r&&(e.tagClass!==t.tagClass&&r.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&r.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return n};var Gi=/[^\\u0000-\\u00ff]/;Q.prettyPrint=function(e,t,a){var r="";t=t||0,a=a||2,t>0&&(r+=`
6
+ `);for(var n="",i=0;i<t*a;++i)n+=" ";switch(r+=n+"Tag: ",e.tagClass){case Q.Class.UNIVERSAL:r+="Universal:";break;case Q.Class.APPLICATION:r+="Application:";break;case Q.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case Q.Class.PRIVATE:r+="Private:";break}if(e.tagClass===Q.Class.UNIVERSAL)switch(r+=e.type,e.type){case Q.Type.NONE:r+=" (None)";break;case Q.Type.BOOLEAN:r+=" (Boolean)";break;case Q.Type.INTEGER:r+=" (Integer)";break;case Q.Type.BITSTRING:r+=" (Bit string)";break;case Q.Type.OCTETSTRING:r+=" (Octet string)";break;case Q.Type.NULL:r+=" (Null)";break;case Q.Type.OID:r+=" (Object Identifier)";break;case Q.Type.ODESC:r+=" (Object Descriptor)";break;case Q.Type.EXTERNAL:r+=" (External or Instance of)";break;case Q.Type.REAL:r+=" (Real)";break;case Q.Type.ENUMERATED:r+=" (Enumerated)";break;case Q.Type.EMBEDDED:r+=" (Embedded PDV)";break;case Q.Type.UTF8:r+=" (UTF8)";break;case Q.Type.ROID:r+=" (Relative Object Identifier)";break;case Q.Type.SEQUENCE:r+=" (Sequence)";break;case Q.Type.SET:r+=" (Set)";break;case Q.Type.PRINTABLESTRING:r+=" (Printable String)";break;case Q.Type.IA5String:r+=" (IA5String (ASCII))";break;case Q.Type.UTCTIME:r+=" (UTC time)";break;case Q.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case Q.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
7
+ `,r+=n+"Constructed: "+e.constructed+`
8
+ `,e.composed){for(var s=0,o="",i=0;i<e.value.length;++i)e.value[i]!==void 0&&(s+=1,o+=Q.prettyPrint(e.value[i],t+1,a),i+1<e.value.length&&(o+=","));r+=n+"Sub values: "+s+o}else{if(r+=n+"Value: ",e.type===Q.Type.OID){var c=Q.derToOid(e.value);r+=c,_e.pki&&_e.pki.oids&&c in _e.pki.oids&&(r+=" ("+_e.pki.oids[c]+") ")}if(e.type===Q.Type.INTEGER)try{r+=Q.derToInteger(e.value)}catch{r+="0x"+_e.util.bytesToHex(e.value)}else if(e.type===Q.Type.BITSTRING){if(e.value.length>1?r+="0x"+_e.util.bytesToHex(e.value.slice(1)):r+="(none)",e.value.length>0){var l=e.value.charCodeAt(0);l==1?r+=" (1 unused bit shown)":l>1&&(r+=" ("+l+" unused bits shown)")}}else if(e.type===Q.Type.OCTETSTRING)Gi.test(e.value)||(r+="("+e.value+") "),r+="0x"+_e.util.bytesToHex(e.value);else if(e.type===Q.Type.UTF8)try{r+=_e.util.decodeUtf8(e.value)}catch(u){if(u.message==="URI malformed")r+="0x"+_e.util.bytesToHex(e.value)+" (malformed UTF8)";else throw u}else e.type===Q.Type.PRINTABLESTRING||e.type===Q.Type.IA5String?r+=e.value:Gi.test(e.value)?r+="0x"+_e.util.bytesToHex(e.value):e.value.length===0?r+="[null]":r+=e.value}return r}});var mt=ie((Kp,$i)=>{var pa=ue();$i.exports=pa.md=pa.md||{};pa.md.algorithms=pa.md.algorithms||{}});var yr=ie((Fp,zi)=>{var Rt=ue();mt();Ce();var _l=zi.exports=Rt.hmac=Rt.hmac||{};_l.create=function(){var e=null,t=null,a=null,r=null,n={};return n.start=function(i,s){if(i!==null)if(typeof i=="string")if(i=i.toLowerCase(),i in Rt.md.algorithms)t=Rt.md.algorithms[i].create();else throw new Error('Unknown hash algorithm "'+i+'"');else t=i;if(s===null)s=e;else{if(typeof s=="string")s=Rt.util.createBuffer(s);else if(Rt.util.isArray(s)){var o=s;s=Rt.util.createBuffer();for(var c=0;c<o.length;++c)s.putByte(o[c])}var l=s.length();l>t.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),a=Rt.util.createBuffer(),r=Rt.util.createBuffer(),l=s.length();for(var c=0;c<l;++c){var o=s.at(c);a.putByte(54^o),r.putByte(92^o)}if(l<t.blockLength)for(var o=t.blockLength-l,c=0;c<o;++c)a.putByte(54),r.putByte(92);e=s,a=a.bytes(),r=r.bytes()}t.start(),t.update(a)},n.update=function(i){t.update(i)},n.getMac=function(){var i=t.digest().bytes();return t.start(),t.update(r),t.update(i),t.digest()},n.digest=n.getMac,n}});var ga=ie((Mp,Xi)=>{var Et=ue();mt();Ce();var Qi=Xi.exports=Et.md5=Et.md5||{};Et.md.md5=Et.md.algorithms.md5=Qi;Qi.create=function(){Yi||Nl();var e=null,t=Et.util.createBuffer(),a=new Array(16),r={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=Et.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=Et.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),Wi(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=Et.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(un.substr(0,r.blockLength-s));for(var o,c=0,l=r.fullMessageLength.length-1;l>=0;--l)o=r.fullMessageLength[l]*8+c,c=o/4294967296>>>0,n.putInt32Le(o>>>0);var u={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};Wi(u,a,n);var f=Et.util.createBuffer();return f.putInt32Le(u.h0),f.putInt32Le(u.h1),f.putInt32Le(u.h2),f.putInt32Le(u.h3),f},r};var un=null,ya=null,Vr=null,gr=null,Yi=!1;function Nl(){un="\x80",un+=Et.util.fillString("\0",64),ya=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],Vr=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],gr=new Array(64);for(var e=0;e<64;++e)gr[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);Yi=!0}function Wi(e,t,a){for(var r,n,i,s,o,c,l,u,f=a.length();f>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,u=0;u<16;++u)t[u]=a.getInt32Le(),c=o^i&(s^o),r=n+c+gr[u]+t[u],l=Vr[u],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;u<32;++u)c=s^o&(i^s),r=n+c+gr[u]+t[ya[u]],l=Vr[u],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;u<48;++u)c=i^s^o,r=n+c+gr[u]+t[ya[u]],l=Vr[u],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;u<64;++u)c=s^(i|~o),r=n+c+gr[u]+t[ya[u]],l=Vr[u],n=o,o=s,s=i,i+=r<<l|r>>>32-l;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,f-=64}}});var er=ie((Hp,Zi)=>{var ma=ue();Ce();var Ji=Zi.exports=ma.pem=ma.pem||{};Ji.encode=function(e,t){t=t||{};var a="-----BEGIN "+e.type+`-----\r
9
+ `,r;if(e.procType&&(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},a+=va(r)),e.contentDomain&&(r={name:"Content-Domain",values:[e.contentDomain]},a+=va(r)),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),a+=va(r)),e.headers)for(var n=0;n<e.headers.length;++n)a+=va(e.headers[n]);return e.procType&&(a+=`\r
10
+ `),a+=ma.util.encode64(e.body,t.maxline||64)+`\r
11
+ `,a+="-----END "+e.type+`-----\r
12
+ `,a};Ji.decode=function(e){for(var t=[],a=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,r=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,n=/\r?\n/,i;i=a.exec(e),!!i;){var s=i[1];s==="NEW CERTIFICATE REQUEST"&&(s="CERTIFICATE REQUEST");var o={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:ma.util.decode64(i[3])};if(t.push(o),!!i[2]){for(var c=i[2].split(n),l=0;i&&l<c.length;){for(var u=c[l].replace(/\s+$/,""),f=l+1;f<c.length;++f){var h=c[f];if(!/\s/.test(h[0]))break;u+=h,l=f}if(i=u.match(r),i){for(var m={name:i[1],values:[]},d=i[2].split(","),p=0;p<d.length;++p)m.values.push(kl(d[p]));if(o.procType)if(!o.contentDomain&&m.name==="Content-Domain")o.contentDomain=d[0]||"";else if(!o.dekInfo&&m.name==="DEK-Info"){if(m.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');o.dekInfo={algorithm:d[0],parameters:d[1]||null}}else o.headers.push(m);else{if(m.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(m.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');o.procType={version:d[0],type:d[1]}}}++l}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(t.length===0)throw new Error("Invalid PEM formatted message.");return t};function va(e){for(var t=e.name+": ",a=[],r=function(c,l){return" "+l},n=0;n<e.values.length;++n)a.push(e.values[n].replace(/^(\S+\r\n)/,r));t+=a.join(",")+`\r
13
+ `;for(var i=0,s=-1,n=0;n<t.length;++n,++i)if(i>65&&s!==-1){var o=t[s];o===","?(++s,t=t.substr(0,s)+`\r
14
+ `+t.substr(s)):t=t.substr(0,s)+`\r
15
+ `+o+t.substr(s+1),i=n-s-1,s=-1,++n}else(t[n]===" "||t[n]===" "||t[n]===",")&&(s=n);return t}function kl(e){return e.replace(/^\s+/,"")}});var Kr=ie((qp,ts)=>{var Re=ue();la();nn();Ce();ts.exports=Re.des=Re.des||{};Re.des.startEncrypting=function(e,t,a,r){var n=Ea({key:e,output:a,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};Re.des.createEncryptionCipher=function(e,t){return Ea({key:e,output:null,decrypt:!1,mode:t})};Re.des.startDecrypting=function(e,t,a,r){var n=Ea({key:e,output:a,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};Re.des.createDecryptionCipher=function(e,t){return Ea({key:e,output:null,decrypt:!0,mode:t})};Re.des.Algorithm=function(e,t){var a=this;a.name=e,a.mode=new t({blockSize:8,cipher:{encrypt:function(r,n){return es(a._keys,r,n,!1)},decrypt:function(r,n){return es(a._keys,r,n,!0)}}}),a._init=!1};Re.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=Re.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0&&t.length()!==24)throw new Error("Invalid Triple-DES key size: "+t.length()*8);this._keys=Fl(t),this._init=!0}};Ct("DES-ECB",Re.cipher.modes.ecb);Ct("DES-CBC",Re.cipher.modes.cbc);Ct("DES-CFB",Re.cipher.modes.cfb);Ct("DES-OFB",Re.cipher.modes.ofb);Ct("DES-CTR",Re.cipher.modes.ctr);Ct("3DES-ECB",Re.cipher.modes.ecb);Ct("3DES-CBC",Re.cipher.modes.cbc);Ct("3DES-CFB",Re.cipher.modes.cfb);Ct("3DES-OFB",Re.cipher.modes.ofb);Ct("3DES-CTR",Re.cipher.modes.ctr);function Ct(e,t){var a=function(){return new Re.des.Algorithm(e,t)};Re.cipher.registerAlgorithm(e,a)}var Rl=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],Ll=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],Dl=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],Pl=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],Ul=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],Ol=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],Vl=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],Kl=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function Fl(e){for(var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],a=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],r=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],i=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],m=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],d=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],p=e.length()>8?3:1,E=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],N=0,T,S=0;S<p;S++){var I=e.getInt32(),x=e.getInt32();T=(I>>>4^x)&252645135,x^=T,I^=T<<4,T=(x>>>-16^I)&65535,I^=T,x^=T<<-16,T=(I>>>2^x)&858993459,x^=T,I^=T<<2,T=(x>>>-16^I)&65535,I^=T,x^=T<<-16,T=(I>>>1^x)&1431655765,x^=T,I^=T<<1,T=(x>>>8^I)&16711935,I^=T,x^=T<<8,T=(I>>>1^x)&1431655765,x^=T,I^=T<<1,T=I<<8|x>>>20&240,I=x<<24|x<<8&16711680|x>>>8&65280|x>>>24&240,x=T;for(var w=0;w<b.length;++w){b[w]?(I=I<<2|I>>>26,x=x<<2|x>>>26):(I=I<<1|I>>>27,x=x<<1|x>>>27),I&=-15,x&=-15;var C=t[I>>>28]|a[I>>>24&15]|r[I>>>20&15]|n[I>>>16&15]|i[I>>>12&15]|s[I>>>8&15]|o[I>>>4&15],k=c[x>>>28]|l[x>>>24&15]|u[x>>>20&15]|f[x>>>16&15]|h[x>>>12&15]|m[x>>>8&15]|d[x>>>4&15];T=(k>>>16^C)&65535,E[N++]=C^T,E[N++]=k^T<<16}}return E}function es(e,t,a,r){var n=e.length===32?3:9,i;n===3?i=r?[30,-2,-2]:[0,32,2]:i=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],c=t[1];s=(o>>>4^c)&252645135,c^=s,o^=s<<4,s=(o>>>16^c)&65535,c^=s,o^=s<<16,s=(c>>>2^o)&858993459,o^=s,c^=s<<2,s=(c>>>8^o)&16711935,o^=s,c^=s<<8,s=(o>>>1^c)&1431655765,c^=s,o^=s<<1,o=o<<1|o>>>31,c=c<<1|c>>>31;for(var l=0;l<n;l+=3){for(var u=i[l+1],f=i[l+2],h=i[l];h!=u;h+=f){var m=c^e[h],d=(c>>>4|c<<28)^e[h+1];s=o,o=c,c=s^(Ll[m>>>24&63]|Pl[m>>>16&63]|Ol[m>>>8&63]|Kl[m&63]|Rl[d>>>24&63]|Dl[d>>>16&63]|Ul[d>>>8&63]|Vl[d&63])}s=o,o=c,c=s}o=o>>>1|o<<31,c=c>>>1|c<<31,s=(o>>>1^c)&1431655765,c^=s,o^=s<<1,s=(c>>>8^o)&16711935,o^=s,c^=s<<8,s=(c>>>2^o)&858993459,o^=s,c^=s<<2,s=(o>>>16^c)&65535,c^=s,o^=s<<16,s=(o>>>4^c)&252645135,c^=s,o^=s<<4,a[0]=o,a[1]=c}function Ea(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="DES-"+t,r;e.decrypt?r=Re.cipher.createDecipher(a,e.key):r=Re.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof Re.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var Ca=ie((Gp,rs)=>{var et=ue();yr();mt();Ce();var Ml=et.pkcs5=et.pkcs5||{},Lt;et.util.isNodejs&&!et.options.usePureJavaScript&&(Lt=Qa("crypto"));rs.exports=et.pbkdf2=Ml.pbkdf2=function(e,t,a,r,n,i){if(typeof n=="function"&&(i=n,n=null),et.util.isNodejs&&!et.options.usePureJavaScript&&Lt.pbkdf2&&(n===null||typeof n!="object")&&(Lt.pbkdf2Sync.length>4||!n||n==="sha1"))return typeof n!="string"&&(n="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),i?Lt.pbkdf2Sync.length===4?Lt.pbkdf2(e,t,a,r,function(T,S){if(T)return i(T);i(null,S.toString("binary"))}):Lt.pbkdf2(e,t,a,r,n,function(T,S){if(T)return i(T);i(null,S.toString("binary"))}):Lt.pbkdf2Sync.length===4?Lt.pbkdf2Sync(e,t,a,r).toString("binary"):Lt.pbkdf2Sync(e,t,a,r,n).toString("binary");if((typeof n>"u"||n===null)&&(n="sha1"),typeof n=="string"){if(!(n in et.md.algorithms))throw new Error("Unknown hash algorithm: "+n);n=et.md[n].create()}var s=n.digestLength;if(r>4294967295*s){var o=new Error("Derived key is too long.");if(i)return i(o);throw o}var c=Math.ceil(r/s),l=r-(c-1)*s,u=et.hmac.create();u.start(n,e);var f="",h,m,d;if(!i){for(var p=1;p<=c;++p){u.start(null,null),u.update(t),u.update(et.util.int32ToBytes(p)),h=d=u.digest().getBytes();for(var E=2;E<=a;++E)u.start(null,null),u.update(d),m=u.digest().getBytes(),h=et.util.xorBytes(h,m,s),d=m;f+=p<c?h:h.substr(0,l)}return f}var p=1,E;function b(){if(p>c)return i(null,f);u.start(null,null),u.update(t),u.update(et.util.int32ToBytes(p)),h=d=u.digest().getBytes(),E=2,N()}function N(){if(E<=a)return u.start(null,null),u.update(d),m=u.digest().getBytes(),h=et.util.xorBytes(h,m,s),d=m,++E,et.util.setImmediate(N);f+=p<c?h:h.substr(0,l),++p,b()}b()}});var dn=ie((jp,os)=>{var wt=ue();mt();Ce();var ns=os.exports=wt.sha256=wt.sha256||{};wt.md.sha256=wt.md.algorithms.sha256=ns;ns.create=function(){is||Hl();var e=null,t=wt.util.createBuffer(),a=new Array(64),r={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=wt.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=wt.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),as(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=wt.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(fn.substr(0,r.blockLength-s));for(var o,c,l=r.fullMessageLength[0]*8,u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,c=o/4294967296>>>0,l+=c,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};as(f,a,n);var h=wt.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h.putInt32(f.h5),h.putInt32(f.h6),h.putInt32(f.h7),h},r};var fn=null,is=!1,ss=null;function Hl(){fn="\x80",fn+=wt.util.fillString("\0",64),ss=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],is=!0}function as(e,t,a){for(var r,n,i,s,o,c,l,u,f,h,m,d,p,E,b,N=a.length();N>=64;){for(l=0;l<16;++l)t[l]=a.getInt32();for(;l<64;++l)r=t[l-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,n=t[l-15],n=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[l]=r+t[l-7]+n+t[l-16]|0;for(u=e.h0,f=e.h1,h=e.h2,m=e.h3,d=e.h4,p=e.h5,E=e.h6,b=e.h7,l=0;l<64;++l)s=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),o=E^d&(p^E),i=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),c=u&f|h&(u^f),r=b+s+o+ss[l]+t[l],n=i+c,b=E,E=p,p=d,d=m+r>>>0,m=h,h=f,f=u,u=r+n>>>0;e.h0=e.h0+u|0,e.h1=e.h1+f|0,e.h2=e.h2+h|0,e.h3=e.h3+m|0,e.h4=e.h4+d|0,e.h5=e.h5+p|0,e.h6=e.h6+E|0,e.h7=e.h7+b|0,N-=64}}});var hn=ie(($p,cs)=>{var xt=ue();Ce();var wa=null;xt.util.isNodejs&&!xt.options.usePureJavaScript&&!process.versions["node-webkit"]&&(wa=Qa("crypto"));var ql=cs.exports=xt.prng=xt.prng||{};ql.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},a=e.md,r=new Array(32),n=0;n<32;++n)r[n]=a.create();t.pools=r,t.pool=0,t.generate=function(l,u){if(!u)return t.generateSync(l);var f=t.plugin.cipher,h=t.plugin.increment,m=t.plugin.formatKey,d=t.plugin.formatSeed,p=xt.util.createBuffer();t.key=null,E();function E(b){if(b)return u(b);if(p.length()>=l)return u(null,p.getBytes(l));if(t.generated>1048575&&(t.key=null),t.key===null)return xt.util.nextTick(function(){i(E)});var N=f(t.key,t.seed);t.generated+=N.length,p.putBytes(N),t.key=m(f(t.key,h(t.seed))),t.seed=d(f(t.key,t.seed)),xt.util.setImmediate(E)}},t.generateSync=function(l){var u=t.plugin.cipher,f=t.plugin.increment,h=t.plugin.formatKey,m=t.plugin.formatSeed;t.key=null;for(var d=xt.util.createBuffer();d.length()<l;){t.generated>1048575&&(t.key=null),t.key===null&&s();var p=u(t.key,t.seed);t.generated+=p.length,d.putBytes(p),t.key=h(u(t.key,f(t.seed))),t.seed=m(u(t.key,t.seed))}return d.getBytes(l)};function i(l){if(t.pools[0].messageLength>=32)return o(),l();var u=32-t.pools[0].messageLength<<5;t.seedFile(u,function(f,h){if(f)return l(f);t.collect(h),o(),l()})}function s(){if(t.pools[0].messageLength>=32)return o();var l=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(l)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var l=t.plugin.md.create();l.update(t.keyBytes);for(var u=1,f=0;f<32;++f)t.reseeds%u===0&&(l.update(t.pools[f].digest().getBytes()),t.pools[f].start()),u=u<<1;t.keyBytes=l.digest().getBytes(),l.start(),l.update(t.keyBytes);var h=l.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(h),t.generated=0}function c(l){var u=null,f=xt.util.globalScope,h=f.crypto||f.msCrypto;h&&h.getRandomValues&&(u=function(I){return h.getRandomValues(I)});var m=xt.util.createBuffer();if(u)for(;m.length()<l;){var d=Math.max(1,Math.min(l-m.length(),65536)/4),p=new Uint32Array(Math.floor(d));try{u(p);for(var E=0;E<p.length;++E)m.putInt32(p[E])}catch(I){if(!(typeof QuotaExceededError<"u"&&I instanceof QuotaExceededError))throw I}}if(m.length()<l)for(var b,N,T,S=Math.floor(Math.random()*65536);m.length()<l;){N=16807*(S&65535),b=16807*(S>>16),N+=(b&32767)<<16,N+=b>>15,N=(N&2147483647)+(N>>31),S=N&4294967295;for(var E=0;E<3;++E)T=S>>>(E<<3),T^=Math.floor(Math.random()*256),m.putByte(T&255)}return m.getBytes(l)}return wa?(t.seedFile=function(l,u){wa.randomBytes(l,function(f,h){if(f)return u(f);u(null,h.toString())})},t.seedFileSync=function(l){return wa.randomBytes(l).toString()}):(t.seedFile=function(l,u){try{u(null,c(l))}catch(f){u(f)}},t.seedFileSync=c),t.collect=function(l){for(var u=l.length,f=0;f<u;++f)t.pools[t.pool].update(l.substr(f,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(l,u){for(var f="",h=0;h<u;h+=8)f+=String.fromCharCode(l>>h&255);t.collect(f)},t.registerWorker=function(l){if(l===self)t.seedFile=function(f,h){function m(d){var p=d.data;p.forge&&p.forge.prng&&(self.removeEventListener("message",m),h(p.forge.prng.err,p.forge.prng.bytes))}self.addEventListener("message",m),self.postMessage({forge:{prng:{needed:f}}})};else{var u=function(f){var h=f.data;h.forge&&h.forge.prng&&t.seedFile(h.forge.prng.needed,function(m,d){l.postMessage({forge:{prng:{err:m,bytes:d}}})})};l.addEventListener("message",u)}},t}});var lt=ie((zp,pn)=>{var He=ue();Mt();dn();hn();Ce();(function(){if(He.random&&He.random.getBytes){pn.exports=He.random;return}(function(e){var t={},a=new Array(4),r=He.util.createBuffer();t.formatKey=function(f){var h=He.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),He.aes._expandKey(f,!1)},t.formatSeed=function(f){var h=He.util.createBuffer(f);return f=new Array(4),f[0]=h.getInt32(),f[1]=h.getInt32(),f[2]=h.getInt32(),f[3]=h.getInt32(),f},t.cipher=function(f,h){return He.aes._updateBlock(f,h,a,!1),r.putInt32(a[0]),r.putInt32(a[1]),r.putInt32(a[2]),r.putInt32(a[3]),r.getBytes()},t.increment=function(f){return++f[3],f},t.md=He.md.sha256;function n(){var f=He.prng.create(t);return f.getBytes=function(h,m){return f.generate(h,m)},f.getBytesSync=function(h){return f.generate(h)},f}var i=n(),s=null,o=He.util.globalScope,c=o.crypto||o.msCrypto;if(c&&c.getRandomValues&&(s=function(f){return c.getRandomValues(f)}),He.options.usePureJavaScript||!He.util.isNodejs&&!s){if(typeof window>"u"||window.document,i.collectInt(+new Date,32),typeof navigator<"u"){var l="";for(var u in navigator)try{typeof navigator[u]=="string"&&(l+=navigator[u])}catch{}i.collect(l),l=null}e&&(e().mousemove(function(f){i.collectInt(f.clientX,16),i.collectInt(f.clientY,16)}),e().keypress(function(f){i.collectInt(f.charCode,8)}))}if(!He.random)He.random=i;else for(var u in i)He.random[u]=i[u];He.random.createInstance=n,pn.exports=He.random})(typeof jQuery<"u"?jQuery:null)})()});var gn=ie((Wp,fs)=>{var nt=ue();Ce();var yn=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],ls=[1,2,3,5],Gl=function(e,t){return e<<t&65535|(e&65535)>>16-t},jl=function(e,t){return(e&65535)>>t|e<<16-t&65535};fs.exports=nt.rc2=nt.rc2||{};nt.rc2.expandKey=function(e,t){typeof e=="string"&&(e=nt.util.createBuffer(e)),t=t||128;var a=e,r=e.length(),n=t,i=Math.ceil(n/8),s=255>>(n&7),o;for(o=r;o<128;o++)a.putByte(yn[a.at(o-1)+a.at(o-r)&255]);for(a.setAt(128-i,yn[a.at(128-i)&s]),o=127-i;o>=0;o--)a.setAt(o,yn[a.at(o+1)^a.at(o+i)]);return a};var us=function(e,t,a){var r=!1,n=null,i=null,s=null,o,c,l,u,f=[];for(e=nt.rc2.expandKey(e,t),l=0;l<64;l++)f.push(e.getInt16Le());a?(o=function(d){for(l=0;l<4;l++)d[l]+=f[u]+(d[(l+3)%4]&d[(l+2)%4])+(~d[(l+3)%4]&d[(l+1)%4]),d[l]=Gl(d[l],ls[l]),u++},c=function(d){for(l=0;l<4;l++)d[l]+=f[d[(l+3)%4]&63]}):(o=function(d){for(l=3;l>=0;l--)d[l]=jl(d[l],ls[l]),d[l]-=f[u]+(d[(l+3)%4]&d[(l+2)%4])+(~d[(l+3)%4]&d[(l+1)%4]),u--},c=function(d){for(l=3;l>=0;l--)d[l]-=f[d[(l+3)%4]&63]});var h=function(d){var p=[];for(l=0;l<4;l++){var E=n.getInt16Le();s!==null&&(a?E^=s.getInt16Le():s.putInt16Le(E)),p.push(E&65535)}u=a?0:63;for(var b=0;b<d.length;b++)for(var N=0;N<d[b][0];N++)d[b][1](p);for(l=0;l<4;l++)s!==null&&(a?s.putInt16Le(p[l]):p[l]^=s.getInt16Le()),i.putInt16Le(p[l])},m=null;return m={start:function(d,p){d&&typeof d=="string"&&(d=nt.util.createBuffer(d)),r=!1,n=nt.util.createBuffer(),i=p||new nt.util.createBuffer,s=d,m.output=i},update:function(d){for(r||n.putBuffer(d);n.length()>=8;)h([[5,o],[1,c],[6,o],[1,c],[5,o]])},finish:function(d){var p=!0;if(a)if(d)p=d(8,n,!a);else{var E=n.length()===8?8:8-n.length();n.fillWithByte(E,E)}if(p&&(r=!0,m.update()),!a&&(p=n.length()===0,p))if(d)p=d(8,i,!a);else{var b=i.length(),N=i.at(b-1);N>b?p=!1:i.truncate(N)}return p}},m};nt.rc2.startEncrypting=function(e,t,a){var r=nt.rc2.createEncryptionCipher(e,128);return r.start(t,a),r};nt.rc2.createEncryptionCipher=function(e,t){return us(e,t,!0)};nt.rc2.startDecrypting=function(e,t,a){var r=nt.rc2.createDecryptionCipher(e,128);return r.start(t,a),r};nt.rc2.createDecryptionCipher=function(e,t){return us(e,t,!1)}});var Mr=ie((Qp,Es)=>{var vn=ue();Es.exports=vn.jsbn=vn.jsbn||{};var Dt,$l=0xdeadbeefcafe,ds=($l&16777215)==15715070;function K(e,t,a){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,a):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}vn.jsbn.BigInteger=K;function ge(){return new K(null)}function zl(e,t,a,r,n,i){for(;--i>=0;){var s=t*this.data[e++]+a.data[r]+n;n=Math.floor(s/67108864),a.data[r++]=s&67108863}return n}function Wl(e,t,a,r,n,i){for(var s=t&32767,o=t>>15;--i>=0;){var c=this.data[e]&32767,l=this.data[e++]>>15,u=o*c+l*s;c=s*c+((u&32767)<<15)+a.data[r]+(n&1073741823),n=(c>>>30)+(u>>>15)+o*l+(n>>>30),a.data[r++]=c&1073741823}return n}function hs(e,t,a,r,n,i){for(var s=t&16383,o=t>>14;--i>=0;){var c=this.data[e]&16383,l=this.data[e++]>>14,u=o*c+l*s;c=s*c+((u&16383)<<14)+a.data[r]+n,n=(c>>28)+(u>>14)+o*l,a.data[r++]=c&268435455}return n}typeof navigator>"u"?(K.prototype.am=hs,Dt=28):ds&&navigator.appName=="Microsoft Internet Explorer"?(K.prototype.am=Wl,Dt=30):ds&&navigator.appName!="Netscape"?(K.prototype.am=zl,Dt=26):(K.prototype.am=hs,Dt=28);K.prototype.DB=Dt;K.prototype.DM=(1<<Dt)-1;K.prototype.DV=1<<Dt;var mn=52;K.prototype.FV=Math.pow(2,mn);K.prototype.F1=mn-Dt;K.prototype.F2=2*Dt-mn;var Ql="0123456789abcdefghijklmnopqrstuvwxyz",xa=new Array,vr,ut;vr=48;for(ut=0;ut<=9;++ut)xa[vr++]=ut;vr=97;for(ut=10;ut<36;++ut)xa[vr++]=ut;vr=65;for(ut=10;ut<36;++ut)xa[vr++]=ut;function ps(e){return Ql.charAt(e)}function ys(e,t){var a=xa[e.charCodeAt(t)];return a??-1}function Yl(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function Xl(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function qt(e){var t=ge();return t.fromInt(e),t}function Jl(e,t){var a;if(t==16)a=4;else if(t==8)a=3;else if(t==256)a=8;else if(t==2)a=1;else if(t==32)a=5;else if(t==4)a=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var r=e.length,n=!1,i=0;--r>=0;){var s=a==8?e[r]&255:ys(e,r);if(s<0){e.charAt(r)=="-"&&(n=!0);continue}n=!1,i==0?this.data[this.t++]=s:i+a>this.DB?(this.data[this.t-1]|=(s&(1<<this.DB-i)-1)<<i,this.data[this.t++]=s>>this.DB-i):this.data[this.t-1]|=s<<i,i+=a,i>=this.DB&&(i-=this.DB)}a==8&&(e[0]&128)!=0&&(this.s=-1,i>0&&(this.data[this.t-1]|=(1<<this.DB-i)-1<<i)),this.clamp(),n&&K.ZERO.subTo(this,this)}function Zl(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t}function eu(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var a=(1<<t)-1,r,n=!1,i="",s=this.t,o=this.DB-s*this.DB%t;if(s-- >0)for(o<this.DB&&(r=this.data[s]>>o)>0&&(n=!0,i=ps(r));s>=0;)o<t?(r=(this.data[s]&(1<<o)-1)<<t-o,r|=this.data[--s]>>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&a,o<=0&&(o+=this.DB,--s)),r>0&&(n=!0),n&&(i+=ps(r));return n?i:"0"}function tu(){var e=ge();return K.ZERO.subTo(this,e),e}function ru(){return this.s<0?this.negate():this}function au(e){var t=this.s-e.s;if(t!=0)return t;var a=this.t;if(t=a-e.t,t!=0)return this.s<0?-t:t;for(;--a>=0;)if((t=this.data[a]-e.data[a])!=0)return t;return 0}function Sa(e){var t=1,a;return(a=e>>>16)!=0&&(e=a,t+=16),(a=e>>8)!=0&&(e=a,t+=8),(a=e>>4)!=0&&(e=a,t+=4),(a=e>>2)!=0&&(e=a,t+=2),(a=e>>1)!=0&&(e=a,t+=1),t}function nu(){return this.t<=0?0:this.DB*(this.t-1)+Sa(this.data[this.t-1]^this.s&this.DM)}function iu(e,t){var a;for(a=this.t-1;a>=0;--a)t.data[a+e]=this.data[a];for(a=e-1;a>=0;--a)t.data[a]=0;t.t=this.t+e,t.s=this.s}function su(e,t){for(var a=e;a<this.t;++a)t.data[a-e]=this.data[a];t.t=Math.max(this.t-e,0),t.s=this.s}function ou(e,t){var a=e%this.DB,r=this.DB-a,n=(1<<r)-1,i=Math.floor(e/this.DB),s=this.s<<a&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+i+1]=this.data[o]>>r|s,s=(this.data[o]&n)<<a;for(o=i-1;o>=0;--o)t.data[o]=0;t.data[i]=s,t.t=this.t+i+1,t.s=this.s,t.clamp()}function cu(e,t){t.s=this.s;var a=Math.floor(e/this.DB);if(a>=this.t){t.t=0;return}var r=e%this.DB,n=this.DB-r,i=(1<<r)-1;t.data[0]=this.data[a]>>r;for(var s=a+1;s<this.t;++s)t.data[s-a-1]|=(this.data[s]&i)<<n,t.data[s-a]=this.data[s]>>r;r>0&&(t.data[this.t-a-1]|=(this.s&i)<<n),t.t=this.t-a,t.clamp()}function lu(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]-e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r-=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t.data[a++]=this.DV+r:r>0&&(t.data[a++]=r),t.t=a,t.clamp()}function uu(e,t){var a=this.abs(),r=e.abs(),n=a.t;for(t.t=n+r.t;--n>=0;)t.data[n]=0;for(n=0;n<r.t;++n)t.data[n+a.t]=a.am(0,r.data[n],t,n,0,a.t);t.s=0,t.clamp(),this.s!=e.s&&K.ZERO.subTo(t,t)}function fu(e){for(var t=this.abs(),a=e.t=2*t.t;--a>=0;)e.data[a]=0;for(a=0;a<t.t-1;++a){var r=t.am(a,t.data[a],e,2*a,0,1);(e.data[a+t.t]+=t.am(a+1,2*t.data[a],e,2*a+1,r,t.t-a-1))>=t.DV&&(e.data[a+t.t]-=t.DV,e.data[a+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(a,t.data[a],e,2*a,0,1)),e.s=0,e.clamp()}function du(e,t,a){var r=e.abs();if(!(r.t<=0)){var n=this.abs();if(n.t<r.t){t?.fromInt(0),a!=null&&this.copyTo(a);return}a==null&&(a=ge());var i=ge(),s=this.s,o=e.s,c=this.DB-Sa(r.data[r.t-1]);c>0?(r.lShiftTo(c,i),n.lShiftTo(c,a)):(r.copyTo(i),n.copyTo(a));var l=i.t,u=i.data[l-1];if(u!=0){var f=u*(1<<this.F1)+(l>1?i.data[l-2]>>this.F2:0),h=this.FV/f,m=(1<<this.F1)/f,d=1<<this.F2,p=a.t,E=p-l,b=t??ge();for(i.dlShiftTo(E,b),a.compareTo(b)>=0&&(a.data[a.t++]=1,a.subTo(b,a)),K.ONE.dlShiftTo(l,b),b.subTo(i,i);i.t<l;)i.data[i.t++]=0;for(;--E>=0;){var N=a.data[--p]==u?this.DM:Math.floor(a.data[p]*h+(a.data[p-1]+d)*m);if((a.data[p]+=i.am(0,N,a,E,0,l))<N)for(i.dlShiftTo(E,b),a.subTo(b,a);a.data[p]<--N;)a.subTo(b,a)}t!=null&&(a.drShiftTo(l,t),s!=o&&K.ZERO.subTo(t,t)),a.t=l,a.clamp(),c>0&&a.rShiftTo(c,a),s<0&&K.ZERO.subTo(a,a)}}}function hu(e){var t=ge();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(K.ZERO)>0&&e.subTo(t,t),t}function tr(e){this.m=e}function pu(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function yu(e){return e}function gu(e){e.divRemTo(this.m,null,e)}function vu(e,t,a){e.multiplyTo(t,a),this.reduce(a)}function mu(e,t){e.squareTo(t),this.reduce(t)}tr.prototype.convert=pu;tr.prototype.revert=yu;tr.prototype.reduce=gu;tr.prototype.mulTo=vu;tr.prototype.sqrTo=mu;function Eu(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function rr(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function Cu(e){var t=ge();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(K.ZERO)>0&&this.m.subTo(t,t),t}function wu(e){var t=ge();return e.copyTo(t),this.reduce(t),t}function xu(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var a=e.data[t]&32767,r=a*this.mpl+((a*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(a=t+this.m.t,e.data[a]+=this.m.am(0,r,e,t,0,this.m.t);e.data[a]>=e.DV;)e.data[a]-=e.DV,e.data[++a]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function Su(e,t){e.squareTo(t),this.reduce(t)}function bu(e,t,a){e.multiplyTo(t,a),this.reduce(a)}rr.prototype.convert=Cu;rr.prototype.revert=wu;rr.prototype.reduce=xu;rr.prototype.mulTo=bu;rr.prototype.sqrTo=Su;function Tu(){return(this.t>0?this.data[0]&1:this.s)==0}function Iu(e,t){if(e>4294967295||e<1)return K.ONE;var a=ge(),r=ge(),n=t.convert(this),i=Sa(e)-1;for(n.copyTo(a);--i>=0;)if(t.sqrTo(a,r),(e&1<<i)>0)t.mulTo(r,n,a);else{var s=a;a=r,r=s}return t.revert(a)}function Au(e,t){var a;return e<256||t.isEven()?a=new tr(t):a=new rr(t),this.exp(e,a)}K.prototype.copyTo=Yl;K.prototype.fromInt=Xl;K.prototype.fromString=Jl;K.prototype.clamp=Zl;K.prototype.dlShiftTo=iu;K.prototype.drShiftTo=su;K.prototype.lShiftTo=ou;K.prototype.rShiftTo=cu;K.prototype.subTo=lu;K.prototype.multiplyTo=uu;K.prototype.squareTo=fu;K.prototype.divRemTo=du;K.prototype.invDigit=Eu;K.prototype.isEven=Tu;K.prototype.exp=Iu;K.prototype.toString=eu;K.prototype.negate=tu;K.prototype.abs=ru;K.prototype.compareTo=au;K.prototype.bitLength=nu;K.prototype.mod=hu;K.prototype.modPowInt=Au;K.ZERO=qt(0);K.ONE=qt(1);function Bu(){var e=ge();return this.copyTo(e),e}function _u(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function Nu(){return this.t==0?this.s:this.data[0]<<24>>24}function ku(){return this.t==0?this.s:this.data[0]<<16>>16}function Ru(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Lu(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function Du(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),a=Math.pow(e,t),r=qt(a),n=ge(),i=ge(),s="";for(this.divRemTo(r,n,i);n.signum()>0;)s=(a+i.intValue()).toString(e).substr(1)+s,n.divRemTo(r,n,i);return i.intValue().toString(e)+s}function Pu(e,t){this.fromInt(0),t==null&&(t=10);for(var a=this.chunkSize(t),r=Math.pow(t,a),n=!1,i=0,s=0,o=0;o<e.length;++o){var c=ys(e,o);if(c<0){e.charAt(o)=="-"&&this.signum()==0&&(n=!0);continue}s=t*s+c,++i>=a&&(this.dMultiply(r),this.dAddOffset(s,0),i=0,s=0)}i>0&&(this.dMultiply(Math.pow(t,i)),this.dAddOffset(s,0)),n&&K.ZERO.subTo(this,this)}function Uu(e,t,a){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,a),this.testBit(e-1)||this.bitwiseTo(K.ONE.shiftLeft(e-1),En,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(K.ONE.shiftLeft(e-1),this);else{var r=new Array,n=e&7;r.length=(e>>3)+1,t.nextBytes(r),n>0?r[0]&=(1<<n)-1:r[0]=0,this.fromString(r,256)}}function Ou(){var e=this.t,t=new Array;t[0]=this.s;var a=this.DB-e*this.DB%8,r,n=0;if(e-- >0)for(a<this.DB&&(r=this.data[e]>>a)!=(this.s&this.DM)>>a&&(t[n++]=r|this.s<<this.DB-a);e>=0;)a<8?(r=(this.data[e]&(1<<a)-1)<<8-a,r|=this.data[--e]>>(a+=this.DB-8)):(r=this.data[e]>>(a-=8)&255,a<=0&&(a+=this.DB,--e)),(r&128)!=0&&(r|=-256),n==0&&(this.s&128)!=(r&128)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t}function Vu(e){return this.compareTo(e)==0}function Ku(e){return this.compareTo(e)<0?this:e}function Fu(e){return this.compareTo(e)>0?this:e}function Mu(e,t,a){var r,n,i=Math.min(e.t,this.t);for(r=0;r<i;++r)a.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){for(n=e.s&this.DM,r=i;r<this.t;++r)a.data[r]=t(this.data[r],n);a.t=this.t}else{for(n=this.s&this.DM,r=i;r<e.t;++r)a.data[r]=t(n,e.data[r]);a.t=e.t}a.s=t(this.s,e.s),a.clamp()}function Hu(e,t){return e&t}function qu(e){var t=ge();return this.bitwiseTo(e,Hu,t),t}function En(e,t){return e|t}function Gu(e){var t=ge();return this.bitwiseTo(e,En,t),t}function gs(e,t){return e^t}function ju(e){var t=ge();return this.bitwiseTo(e,gs,t),t}function vs(e,t){return e&~t}function $u(e){var t=ge();return this.bitwiseTo(e,vs,t),t}function zu(){for(var e=ge(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function Wu(e){var t=ge();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t}function Qu(e){var t=ge();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t}function Yu(e){if(e==0)return-1;var t=0;return(e&65535)==0&&(e>>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function Xu(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+Yu(this.data[e]);return this.s<0?this.t*this.DB:-1}function Ju(e){for(var t=0;e!=0;)e&=e-1,++t;return t}function Zu(){for(var e=0,t=this.s&this.DM,a=0;a<this.t;++a)e+=Ju(this.data[a]^t);return e}function ef(e){var t=Math.floor(e/this.DB);return t>=this.t?this.s!=0:(this.data[t]&1<<e%this.DB)!=0}function tf(e,t){var a=K.ONE.shiftLeft(e);return this.bitwiseTo(a,t,a),a}function rf(e){return this.changeBit(e,En)}function af(e){return this.changeBit(e,vs)}function nf(e){return this.changeBit(e,gs)}function sf(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]+e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r+=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t.data[a++]=r:r<-1&&(t.data[a++]=this.DV+r),t.t=a,t.clamp()}function of(e){var t=ge();return this.addTo(e,t),t}function cf(e){var t=ge();return this.subTo(e,t),t}function lf(e){var t=ge();return this.multiplyTo(e,t),t}function uf(){var e=ge();return this.squareTo(e),e}function ff(e){var t=ge();return this.divRemTo(e,t,null),t}function df(e){var t=ge();return this.divRemTo(e,null,t),t}function hf(e){var t=ge(),a=ge();return this.divRemTo(e,t,a),new Array(t,a)}function pf(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function yf(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function Fr(){}function ms(e){return e}function gf(e,t,a){e.multiplyTo(t,a)}function vf(e,t){e.squareTo(t)}Fr.prototype.convert=ms;Fr.prototype.revert=ms;Fr.prototype.mulTo=gf;Fr.prototype.sqrTo=vf;function mf(e){return this.exp(e,new Fr)}function Ef(e,t,a){var r=Math.min(this.t+e.t,t);for(a.s=0,a.t=r;r>0;)a.data[--r]=0;var n;for(n=a.t-this.t;r<n;++r)a.data[r+this.t]=this.am(0,e.data[r],a,r,0,this.t);for(n=Math.min(e.t,t);r<n;++r)this.am(0,e.data[r],a,r,0,t-r);a.clamp()}function Cf(e,t,a){--t;var r=a.t=this.t+e.t-t;for(a.s=0;--r>=0;)a.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)a.data[this.t+r-t]=this.am(t-r,e.data[r],a,0,0,this.t+r-t);a.clamp(),a.drShiftTo(1,a)}function mr(e){this.r2=ge(),this.q3=ge(),K.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function wf(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=ge();return e.copyTo(t),this.reduce(t),t}function xf(e){return e}function Sf(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function bf(e,t){e.squareTo(t),this.reduce(t)}function Tf(e,t,a){e.multiplyTo(t,a),this.reduce(a)}mr.prototype.convert=wf;mr.prototype.revert=xf;mr.prototype.reduce=Sf;mr.prototype.mulTo=Tf;mr.prototype.sqrTo=bf;function If(e,t){var a=e.bitLength(),r,n=qt(1),i;if(a<=0)return n;a<18?r=1:a<48?r=3:a<144?r=4:a<768?r=5:r=6,a<8?i=new tr(t):t.isEven()?i=new mr(t):i=new rr(t);var s=new Array,o=3,c=r-1,l=(1<<r)-1;if(s[1]=i.convert(this),r>1){var u=ge();for(i.sqrTo(s[1],u);o<=l;)s[o]=ge(),i.mulTo(u,s[o-2],s[o]),o+=2}var f=e.t-1,h,m=!0,d=ge(),p;for(a=Sa(e.data[f])-1;f>=0;){for(a>=c?h=e.data[f]>>a-c&l:(h=(e.data[f]&(1<<a+1)-1)<<c-a,f>0&&(h|=e.data[f-1]>>this.DB+a-c)),o=r;(h&1)==0;)h>>=1,--o;if((a-=o)<0&&(a+=this.DB,--f),m)s[h].copyTo(n),m=!1;else{for(;o>1;)i.sqrTo(n,d),i.sqrTo(d,n),o-=2;o>0?i.sqrTo(n,d):(p=n,n=d,d=p),i.mulTo(d,s[h],n)}for(;f>=0&&(e.data[f]&1<<a)==0;)i.sqrTo(n,d),p=n,n=d,d=p,--a<0&&(a=this.DB-1,--f)}return i.revert(n)}function Af(e){var t=this.s<0?this.negate():this.clone(),a=e.s<0?e.negate():e.clone();if(t.compareTo(a)<0){var r=t;t=a,a=r}var n=t.getLowestSetBit(),i=a.getLowestSetBit();if(i<0)return t;for(n<i&&(i=n),i>0&&(t.rShiftTo(i,t),a.rShiftTo(i,a));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=a.getLowestSetBit())>0&&a.rShiftTo(n,a),t.compareTo(a)>=0?(t.subTo(a,t),t.rShiftTo(1,t)):(a.subTo(t,a),a.rShiftTo(1,a));return i>0&&a.lShiftTo(i,a),a}function Bf(e){if(e<=0)return 0;var t=this.DV%e,a=this.s<0?e-1:0;if(this.t>0)if(t==0)a=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)a=(t*a+this.data[r])%e;return a}function _f(e){if(this.signum()==0)return K.ZERO;var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return K.ZERO;for(var a=e.clone(),r=this.clone(),n=qt(1),i=qt(0),s=qt(0),o=qt(1);a.signum()!=0;){for(;a.isEven();)a.rShiftTo(1,a),t?((!n.isEven()||!i.isEven())&&(n.addTo(this,n),i.subTo(e,i)),n.rShiftTo(1,n)):i.isEven()||i.subTo(e,i),i.rShiftTo(1,i);for(;r.isEven();)r.rShiftTo(1,r),t?((!s.isEven()||!o.isEven())&&(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);a.compareTo(r)>=0?(a.subTo(r,a),t&&n.subTo(s,n),i.subTo(o,i)):(r.subTo(a,r),t&&s.subTo(n,s),o.subTo(i,o))}if(r.compareTo(K.ONE)!=0)return K.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;return o.signum()<0?o.add(e):o}var vt=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],Nf=(1<<26)/vt[vt.length-1];function kf(e){var t,a=this.abs();if(a.t==1&&a.data[0]<=vt[vt.length-1]){for(t=0;t<vt.length;++t)if(a.data[0]==vt[t])return!0;return!1}if(a.isEven())return!1;for(t=1;t<vt.length;){for(var r=vt[t],n=t+1;n<vt.length&&r<Nf;)r*=vt[n++];for(r=a.modInt(r);t<n;)if(r%vt[t++]==0)return!1}return a.millerRabin(e)}function Rf(e){var t=this.subtract(K.ONE),a=t.getLowestSetBit();if(a<=0)return!1;for(var r=t.shiftRight(a),n=Lf(),i,s=0;s<e;++s){do i=new K(this.bitLength(),n);while(i.compareTo(K.ONE)<=0||i.compareTo(t)>=0);var o=i.modPow(r,this);if(o.compareTo(K.ONE)!=0&&o.compareTo(t)!=0){for(var c=1;c++<a&&o.compareTo(t)!=0;)if(o=o.modPowInt(2,this),o.compareTo(K.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function Lf(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}K.prototype.chunkSize=Ru;K.prototype.toRadix=Du;K.prototype.fromRadix=Pu;K.prototype.fromNumber=Uu;K.prototype.bitwiseTo=Mu;K.prototype.changeBit=tf;K.prototype.addTo=sf;K.prototype.dMultiply=pf;K.prototype.dAddOffset=yf;K.prototype.multiplyLowerTo=Ef;K.prototype.multiplyUpperTo=Cf;K.prototype.modInt=Bf;K.prototype.millerRabin=Rf;K.prototype.clone=Bu;K.prototype.intValue=_u;K.prototype.byteValue=Nu;K.prototype.shortValue=ku;K.prototype.signum=Lu;K.prototype.toByteArray=Ou;K.prototype.equals=Vu;K.prototype.min=Ku;K.prototype.max=Fu;K.prototype.and=qu;K.prototype.or=Gu;K.prototype.xor=ju;K.prototype.andNot=$u;K.prototype.not=zu;K.prototype.shiftLeft=Wu;K.prototype.shiftRight=Qu;K.prototype.getLowestSetBit=Xu;K.prototype.bitCount=Zu;K.prototype.testBit=ef;K.prototype.setBit=rf;K.prototype.clearBit=af;K.prototype.flipBit=nf;K.prototype.add=of;K.prototype.subtract=cf;K.prototype.multiply=lf;K.prototype.divide=ff;K.prototype.remainder=df;K.prototype.divideAndRemainder=hf;K.prototype.modPow=If;K.prototype.modInverse=_f;K.prototype.pow=mf;K.prototype.gcd=Af;K.prototype.isProbablePrime=kf;K.prototype.square=uf});var Er=ie((Yp,Ss)=>{var St=ue();mt();Ce();var ws=Ss.exports=St.sha1=St.sha1||{};St.md.sha1=St.md.algorithms.sha1=ws;ws.create=function(){xs||Df();var e=null,t=St.util.createBuffer(),a=new Array(80),r={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=St.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=St.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),Cs(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=St.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(Cn.substr(0,r.blockLength-s));for(var o,c,l=r.fullMessageLength[0]*8,u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,c=o/4294967296>>>0,l+=c,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Cs(f,a,n);var h=St.util.createBuffer();return h.putInt32(f.h0),h.putInt32(f.h1),h.putInt32(f.h2),h.putInt32(f.h3),h.putInt32(f.h4),h},r};var Cn=null,xs=!1;function Df(){Cn="\x80",Cn+=St.util.fillString("\0",64),xs=!0}function Cs(e,t,a){for(var r,n,i,s,o,c,l,u,f=a.length();f>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,c=e.h4,u=0;u<16;++u)r=a.getInt32(),t[u]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+c+1518500249+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;u<20;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+c+1518500249+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;u<32;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,l=i^s^o,r=(n<<5|n>>>27)+l+c+1859775393+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;u<40;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,l=i^s^o,r=(n<<5|n>>>27)+l+c+1859775393+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;u<60;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,l=i&s|o&(i^s),r=(n<<5|n>>>27)+l+c+2400959708+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;u<80;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,l=i^s^o,r=(n<<5|n>>>27)+l+c+3395469782+r,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+c|0,f-=64}}});var wn=ie((Xp,Ts)=>{var bt=ue();Ce();lt();Er();var bs=Ts.exports=bt.pkcs1=bt.pkcs1||{};bs.encode_rsa_oaep=function(e,t,a){var r,n,i,s;typeof a=="string"?(r=a,n=arguments[3]||void 0,i=arguments[4]||void 0):a&&(r=a.label||void 0,n=a.seed||void 0,i=a.md||void 0,a.mgf1&&a.mgf1.md&&(s=a.mgf1.md)),i?i.start():i=bt.md.sha1.create(),s||(s=i);var o=Math.ceil(e.n.bitLength()/8),c=o-2*i.digestLength-2;if(t.length>c){var l=new Error("RSAES-OAEP input message length is too long.");throw l.length=t.length,l.maxLength=c,l}r||(r=""),i.update(r,"raw");for(var u=i.digest(),f="",h=c-t.length,m=0;m<h;m++)f+="\0";var d=u.getBytes()+f+""+t;if(!n)n=bt.random.getBytes(i.digestLength);else if(n.length!==i.digestLength){var l=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw l.seedLength=n.length,l.digestLength=i.digestLength,l}var p=ba(n,o-i.digestLength-1,s),E=bt.util.xorBytes(d,p,d.length),b=ba(E,i.digestLength,s),N=bt.util.xorBytes(n,b,n.length);return"\0"+N+E};bs.decode_rsa_oaep=function(e,t,a){var r,n,i;typeof a=="string"?(r=a,n=arguments[3]||void 0):a&&(r=a.label||void 0,n=a.md||void 0,a.mgf1&&a.mgf1.md&&(i=a.mgf1.md));var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var E=new Error("RSAES-OAEP encoded message length is invalid.");throw E.length=t.length,E.expectedLength=s,E}if(n===void 0?n=bt.md.sha1.create():n.start(),i||(i=n),s<2*n.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");r||(r=""),n.update(r,"raw");for(var o=n.digest().getBytes(),c=t.charAt(0),l=t.substring(1,n.digestLength+1),u=t.substring(1+n.digestLength),f=ba(u,n.digestLength,i),h=bt.util.xorBytes(l,f,l.length),m=ba(h,s-n.digestLength-1,i),d=bt.util.xorBytes(u,m,u.length),p=d.substring(0,n.digestLength),E=c!=="\0",b=0;b<n.digestLength;++b)E|=o.charAt(b)!==p.charAt(b);for(var N=1,T=n.digestLength,S=n.digestLength;S<d.length;S++){var I=d.charCodeAt(S),x=I&1^1,w=N?65534:0;E|=I&w,N=N&x,T+=N}if(E||d.charCodeAt(T)!==1)throw new Error("Invalid RSAES-OAEP padding.");return d.substring(T+1)};function ba(e,t,a){a||(a=bt.md.sha1.create());for(var r="",n=Math.ceil(t/a.digestLength),i=0;i<n;++i){var s=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);a.start(),a.update(e+s),r+=a.digest().getBytes()}return r.substring(0,t)}});var Sn=ie((Jp,xn)=>{var Gt=ue();Ce();Mr();lt();(function(){if(Gt.prime){xn.exports=Gt.prime;return}var e=xn.exports=Gt.prime=Gt.prime||{},t=Gt.jsbn.BigInteger,a=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var n=function(f,h){return f|h};e.generateProbablePrime=function(f,h,m){typeof h=="function"&&(m=h,h={}),h=h||{};var d=h.algorithm||"PRIMEINC";typeof d=="string"&&(d={name:d}),d.options=d.options||{};var p=h.prng||Gt.random,E={nextBytes:function(b){for(var N=p.getBytesSync(b.length),T=0;T<b.length;++T)b[T]=N.charCodeAt(T)}};if(d.name==="PRIMEINC")return i(f,E,d.options,m);throw new Error("Invalid prime generation algorithm: "+d.name)};function i(f,h,m,d){return"workers"in m?c(f,h,m,d):s(f,h,m,d)}function s(f,h,m,d){var p=l(f,h),E=0,b=u(p.bitLength());"millerRabinTests"in m&&(b=m.millerRabinTests);var N=10;"maxBlockTime"in m&&(N=m.maxBlockTime),o(p,f,h,E,b,N,d)}function o(f,h,m,d,p,E,b){var N=+new Date;do{if(f.bitLength()>h&&(f=l(h,m)),f.isProbablePrime(p))return b(null,f);f.dAddOffset(a[d++%8],0)}while(E<0||+new Date-N<E);Gt.util.setImmediate(function(){o(f,h,m,d,p,E,b)})}function c(f,h,m,d){if(typeof Worker>"u")return s(f,h,m,d);var p=l(f,h),E=m.workers,b=m.workLoad||100,N=b*30/8,T=m.workerScript||"forge/prime.worker.js";if(E===-1)return Gt.util.estimateCores(function(I,x){I&&(x=2),E=x-1,S()});S();function S(){E=Math.max(1,E);for(var I=[],x=0;x<E;++x)I[x]=new Worker(T);for(var w=E,x=0;x<E;++x)I[x].addEventListener("message",k);var C=!1;function k(D){if(!C){--w;var L=D.data;if(L.found){for(var R=0;R<I.length;++R)I[R].terminate();return C=!0,d(null,new t(L.prime,16))}p.bitLength()>f&&(p=l(f,h));var M=p.toString(16);D.target.postMessage({hex:M,workLoad:b}),p.dAddOffset(N,0)}}}}function l(f,h){var m=new t(f,h),d=f-1;return m.testBit(d)||m.bitwiseTo(t.ONE.shiftLeft(d),n,m),m.dAddOffset(31-m.mod(r).byteValue(),0),m}function u(f){return f<=100?27:f<=150?18:f<=200?15:f<=250?12:f<=300?9:f<=350?8:f<=400?7:f<=500?6:f<=600?5:f<=800?4:f<=1250?3:2}})()});var Hr=ie((Zp,Rs)=>{var re=ue();gt();Mr();Ht();wn();Sn();lt();Ce();typeof ve>"u"&&(ve=re.jsbn.BigInteger);var ve,bn=re.util.isNodejs?Qa("crypto"):null,P=re.asn1,ft=re.util;re.pki=re.pki||{};Rs.exports=re.pki.rsa=re.rsa=re.rsa||{};var se=re.pki,Pf=[6,4,2,4,2,4,6,2],Uf={name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},Of={name:"RSAPrivateKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Vf={name:"RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Kf=re.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Ff={name:"DigestInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:P.Class.UNIVERSAL,type:P.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Mf=function(e){var t;if(e.algorithm in se.oids)t=se.oids[e.algorithm];else{var a=new Error("Unknown message digest algorithm.");throw a.algorithm=e.algorithm,a}var r=P.oidToDer(t).getBytes(),n=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]),i=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]);i.value.push(P.create(P.Class.UNIVERSAL,P.Type.OID,!1,r)),i.value.push(P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,""));var s=P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,e.digest().getBytes());return n.value.push(i),n.value.push(s),P.toDer(n).getBytes()},Ns=function(e,t,a){if(a)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(ve.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(ve.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var r;do r=new ve(re.util.bytesToHex(re.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ve.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);for(var n=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);n.compareTo(i)<0;)n=n.add(t.p);var s=n.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};se.rsa.encrypt=function(e,t,a){var r=a,n,i=Math.ceil(t.n.bitLength()/8);a!==!1&&a!==!0?(r=a===2,n=ks(e,t,a)):(n=re.util.createBuffer(),n.putBytes(e));for(var s=new ve(n.toHex(),16),o=Ns(s,t,r),c=o.toString(16),l=re.util.createBuffer(),u=i-Math.ceil(c.length/2);u>0;)l.putByte(0),--u;return l.putBytes(re.util.hexToBytes(c)),l.getBytes()};se.rsa.decrypt=function(e,t,a,r){var n=Math.ceil(t.n.bitLength()/8);if(e.length!==n){var i=new Error("Encrypted message length is invalid.");throw i.length=e.length,i.expected=n,i}var s=new ve(re.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var o=Ns(s,t,a),c=o.toString(16),l=re.util.createBuffer(),u=n-Math.ceil(c.length/2);u>0;)l.putByte(0),--u;return l.putBytes(re.util.hexToBytes(c)),r!==!1?Ta(l.getBytes(),t,a):l.getBytes()};se.rsa.createKeyPairGenerationState=function(e,t,a){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,a=a||{};var r=a.prng||re.random,n={nextBytes:function(o){for(var c=r.getBytesSync(o.length),l=0;l<o.length;++l)o[l]=c.charCodeAt(l)}},i=a.algorithm||"PRIMEINC",s;if(i==="PRIMEINC")s={algorithm:i,state:0,bits:e,rng:n,eInt:t||65537,e:new ve(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+i);return s};se.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var a=new ve(null);a.fromInt(30);for(var r=0,n=function(f,h){return f|h},i=+new Date,s,o=0;e.keys===null&&(t<=0||o<t);){if(e.state===0){var c=e.p===null?e.pBits:e.qBits,l=c-1;e.pqState===0?(e.num=new ve(c,e.rng),e.num.testBit(l)||e.num.bitwiseTo(ve.ONE.shiftLeft(l),n,e.num),e.num.dAddOffset(31-e.num.mod(a).byteValue(),0),r=0,++e.pqState):e.pqState===1?e.num.bitLength()>c?e.pqState=0:e.num.isProbablePrime(qf(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(Pf[r++%8],0):e.pqState===2?e.pqState=e.num.subtract(ve.ONE).gcd(e.e).compareTo(ve.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(ve.ONE),e.q1=e.q.subtract(ve.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(ve.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var u=e.e.modInverse(e.phi);e.keys={privateKey:se.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:se.rsa.setPublicKey(e.n,e.e)}}s=+new Date,o+=s-i,i=s}return e.keys!==null};se.rsa.generateKeyPair=function(e,t,a,r){if(arguments.length===1?typeof e=="object"?(a=e,e=void 0):typeof e=="function"&&(r=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(r=t,t=void 0):typeof t!="number"&&(a=t,t=void 0):(a=e,r=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof a=="function"&&(r=a,a=void 0):(r=a,a=t,t=void 0)),a=a||{},e===void 0&&(e=a.bits||2048),t===void 0&&(t=a.e||65537),!re.options.usePureJavaScript&&!a.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(Is("generateKeyPair"))return bn.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,c,l){if(o)return r(o);r(null,{privateKey:se.privateKeyFromPem(l),publicKey:se.publicKeyFromPem(c)})});if(As("generateKey")&&As("exportKey"))return ft.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_s(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return ft.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var c=se.privateKeyFromAsn1(P.fromDer(re.util.createBuffer(o)));r(null,{privateKey:c,publicKey:se.setRsaPublicKey(c.n,c.e)})}});if(Bs("generateKey")&&Bs("exportKey")){var n=ft.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:_s(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);n.oncomplete=function(o){var c=o.target.result,l=ft.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);l.oncomplete=function(u){var f=u.target.result,h=se.privateKeyFromAsn1(P.fromDer(re.util.createBuffer(f)));r(null,{privateKey:h,publicKey:se.setRsaPublicKey(h.n,h.e)})},l.onerror=function(u){r(u)}},n.onerror=function(o){r(o)};return}}else if(Is("generateKeyPairSync")){var i=bn.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:se.privateKeyFromPem(i.privateKey),publicKey:se.publicKeyFromPem(i.publicKey)}}}var s=se.rsa.createKeyPairGenerationState(e,t,a);if(!r)return se.rsa.stepKeyPairGenerationState(s,0),s.keys;Hf(s,a,r)};se.setRsaPublicKey=se.rsa.setPublicKey=function(e,t){var a={n:e,e:t};return a.encrypt=function(r,n,i){if(typeof n=="string"?n=n.toUpperCase():n===void 0&&(n="RSAES-PKCS1-V1_5"),n==="RSAES-PKCS1-V1_5")n={encode:function(o,c,l){return ks(o,c,2).getBytes()}};else if(n==="RSA-OAEP"||n==="RSAES-OAEP")n={encode:function(o,c){return re.pkcs1.encode_rsa_oaep(c,o,i)}};else if(["RAW","NONE","NULL",null].indexOf(n)!==-1)n={encode:function(o){return o}};else if(typeof n=="string")throw new Error('Unsupported encryption scheme: "'+n+'".');var s=n.encode(r,a,!0);return se.rsa.encrypt(s,a,!0)},a.verify=function(r,n,i,s){typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0,_skipPaddingChecks:!1}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"_skipPaddingChecks"in s||(s._skipPaddingChecks=!1),i==="RSASSA-PKCS1-V1_5"?i={verify:function(c,l){l=Ta(l,a,!0,void 0,s);var u=P.fromDer(l,{parseAllBytes:s._parseAllDigestBytes}),f={},h=[];if(!P.validate(u,Ff,f,h)||u.value.length!==2){var m=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw m.errors=h,m}var d=P.derToOid(f.algorithmIdentifier);if(!(d===re.oids.md2||d===re.oids.md5||d===re.oids.sha1||d===re.oids.sha224||d===re.oids.sha256||d===re.oids.sha384||d===re.oids.sha512||d===re.oids["sha512-224"]||d===re.oids["sha512-256"])){var m=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw m.oid=d,m}if((d===re.oids.md2||d===re.oids.md5)&&!("parameters"in f))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.");return c===f.digest}}:(i==="NONE"||i==="NULL"||i===null)&&(i={verify:function(c,l){return l=Ta(l,a,!0,void 0,s),c===l}});var o=se.rsa.decrypt(n,a,!0,!1);return i.verify(r,o,a.n.bitLength())},a};se.setRsaPrivateKey=se.rsa.setPrivateKey=function(e,t,a,r,n,i,s,o){var c={n:e,e:t,d:a,p:r,q:n,dP:i,dQ:s,qInv:o};return c.decrypt=function(l,u,f){typeof u=="string"?u=u.toUpperCase():u===void 0&&(u="RSAES-PKCS1-V1_5");var h=se.rsa.decrypt(l,c,!1,!1);if(u==="RSAES-PKCS1-V1_5")u={decode:Ta};else if(u==="RSA-OAEP"||u==="RSAES-OAEP")u={decode:function(m,d){return re.pkcs1.decode_rsa_oaep(d,m,f)}};else if(["RAW","NONE","NULL",null].indexOf(u)!==-1)u={decode:function(m){return m}};else throw new Error('Unsupported encryption scheme: "'+u+'".');return u.decode(h,c,!1)},c.sign=function(l,u){var f=!1;typeof u=="string"&&(u=u.toUpperCase()),u===void 0||u==="RSASSA-PKCS1-V1_5"?(u={encode:Mf},f=1):(u==="NONE"||u==="NULL"||u===null)&&(u={encode:function(){return l}},f=1);var h=u.encode(l,c.n.bitLength());return se.rsa.encrypt(h,c,f)},c};se.wrapRsaPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(se.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,P.toDer(e).getBytes())])};se.privateKeyFromAsn1=function(e){var t={},a=[];if(P.validate(e,Uf,t,a)&&(e=P.fromDer(re.util.createBuffer(t.privateKey))),t={},a=[],!P.validate(e,Of,t,a)){var r=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=a,r}var n,i,s,o,c,l,u,f;return n=re.util.createBuffer(t.privateKeyModulus).toHex(),i=re.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=re.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=re.util.createBuffer(t.privateKeyPrime1).toHex(),c=re.util.createBuffer(t.privateKeyPrime2).toHex(),l=re.util.createBuffer(t.privateKeyExponent1).toHex(),u=re.util.createBuffer(t.privateKeyExponent2).toHex(),f=re.util.createBuffer(t.privateKeyCoefficient).toHex(),se.setRsaPrivateKey(new ve(n,16),new ve(i,16),new ve(s,16),new ve(o,16),new ve(c,16),new ve(l,16),new ve(u,16),new ve(f,16))};se.privateKeyToAsn1=se.privateKeyToRSAPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.e)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.d)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.p)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.q)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.dP)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.dQ)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.qInv))])};se.publicKeyFromAsn1=function(e){var t={},a=[];if(P.validate(e,Kf,t,a)){var r=P.derToOid(t.publicKeyOid);if(r!==se.oids.rsaEncryption){var n=new Error("Cannot read public key. Unknown OID.");throw n.oid=r,n}e=t.rsaPublicKey}if(a=[],!P.validate(e,Vf,t,a)){var n=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw n.errors=a,n}var i=re.util.createBuffer(t.publicKeyModulus).toHex(),s=re.util.createBuffer(t.publicKeyExponent).toHex();return se.setRsaPublicKey(new ve(i,16),new ve(s,16))};se.publicKeyToAsn1=se.publicKeyToSubjectPublicKeyInfo=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(se.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.BITSTRING,!1,[se.publicKeyToRSAPublicKey(e)])])};se.publicKeyToRSAPublicKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,Tt(e.e))])};function ks(e,t,a){var r=re.util.createBuffer(),n=Math.ceil(t.n.bitLength()/8);if(e.length>n-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=n-11,i}r.putByte(0),r.putByte(a);var s=n-3-e.length,o;if(a===0||a===1){o=a===0?0:255;for(var c=0;c<s;++c)r.putByte(o)}else for(;s>0;){for(var l=0,u=re.random.getBytes(s),c=0;c<s;++c)o=u.charCodeAt(c),o===0?++l:r.putByte(o);s=l}return r.putByte(0),r.putBytes(e),r}function Ta(e,t,a,r,n){var i=Math.ceil(t.n.bitLength()/8),s=re.util.createBuffer(e),o=s.getByte(),c=s.getByte();if(o!==0||a&&c!==0&&c!==1||!a&&c!==2||a&&c===0&&typeof r>"u")throw new Error("Encryption block is invalid.");var l=0;if(c===0){l=i-3-r;for(var u=0;u<l;++u)if(s.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(c===1){for(l=0;s.length()>1;){if(s.getByte()!==255){--s.read;break}++l}if(l<8&&!(n&&n._skipPaddingChecks))throw new Error("Encryption block is invalid.")}else if(c===2){for(l=0;s.length()>1;){if(s.getByte()===0){--s.read;break}++l}if(l<8&&!(n&&n._skipPaddingChecks))throw new Error("Encryption block is invalid.")}var f=s.getByte();if(f!==0||l!==i-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function Hf(e,t,a){typeof t=="function"&&(a=t,t={}),t=t||{};var r={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(r.prng=t.prng),n();function n(){i(e.pBits,function(o,c){if(o)return a(o);if(e.p=c,e.q!==null)return s(o,e.q);i(e.qBits,s)})}function i(o,c){re.prime.generateProbablePrime(o,r,c)}function s(o,c){if(o)return a(o);if(e.q=c,e.p.compareTo(e.q)<0){var l=e.p;e.p=e.q,e.q=l}if(e.p.subtract(ve.ONE).gcd(e.e).compareTo(ve.ONE)!==0){e.p=null,n();return}if(e.q.subtract(ve.ONE).gcd(e.e).compareTo(ve.ONE)!==0){e.q=null,i(e.qBits,s);return}if(e.p1=e.p.subtract(ve.ONE),e.q1=e.q.subtract(ve.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ve.ONE)!==0){e.p=e.q=null,n();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,i(e.qBits,s);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:se.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:se.rsa.setPublicKey(e.n,e.e)},a(null,e.keys)}}function Tt(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var a=re.util.hexToBytes(t);return a.length>1&&(a.charCodeAt(0)===0&&(a.charCodeAt(1)&128)===0||a.charCodeAt(0)===255&&(a.charCodeAt(1)&128)===128)?a.substr(1):a}function qf(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function Is(e){return re.util.isNodejs&&typeof bn[e]=="function"}function As(e){return typeof ft.globalScope<"u"&&typeof ft.globalScope.crypto=="object"&&typeof ft.globalScope.crypto.subtle=="object"&&typeof ft.globalScope.crypto.subtle[e]=="function"}function Bs(e){return typeof ft.globalScope<"u"&&typeof ft.globalScope.msCrypto=="object"&&typeof ft.globalScope.msCrypto.subtle=="object"&&typeof ft.globalScope.msCrypto.subtle[e]=="function"}function _s(e){for(var t=re.util.hexToBytes(e.toString(16)),a=new Uint8Array(t.length),r=0;r<t.length;++r)a[r]=t.charCodeAt(r);return a}});var Tn=ie((ey,Os)=>{var X=ue();Mt();gt();Kr();mt();Ht();Ca();er();lt();gn();Hr();Ce();typeof Ls>"u"&&(Ls=X.jsbn.BigInteger);var Ls,O=X.asn1,le=X.pki=X.pki||{};Os.exports=le.pbe=X.pbe=X.pbe||{};var ar=le.oids,Gf={name:"EncryptedPrivateKeyInfo",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:O.Class.UNIVERSAL,type:O.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:O.Class.UNIVERSAL,type:O.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},jf={name:"PBES2Algorithms",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:O.Class.UNIVERSAL,type:O.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:O.Class.UNIVERSAL,type:O.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:O.Class.UNIVERSAL,type:O.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:O.Class.UNIVERSAL,type:O.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:O.Class.UNIVERSAL,type:O.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:O.Class.UNIVERSAL,type:O.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:O.Class.UNIVERSAL,type:O.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},$f={name:"pkcs-12PbeParams",tagClass:O.Class.UNIVERSAL,type:O.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:O.Class.UNIVERSAL,type:O.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:O.Class.UNIVERSAL,type:O.Type.INTEGER,constructed:!1,capture:"iterations"}]};le.encryptPrivateKeyInfo=function(e,t,a){a=a||{},a.saltSize=a.saltSize||8,a.count=a.count||2048,a.algorithm=a.algorithm||"aes128",a.prfAlgorithm=a.prfAlgorithm||"sha1";var r=X.random.getBytesSync(a.saltSize),n=a.count,i=O.integerToDer(n),s,o,c;if(a.algorithm.indexOf("aes")===0||a.algorithm==="des"){var l,u,f;switch(a.algorithm){case"aes128":s=16,l=16,u=ar["aes128-CBC"],f=X.aes.createEncryptionCipher;break;case"aes192":s=24,l=16,u=ar["aes192-CBC"],f=X.aes.createEncryptionCipher;break;case"aes256":s=32,l=16,u=ar["aes256-CBC"],f=X.aes.createEncryptionCipher;break;case"des":s=8,l=8,u=ar.desCBC,f=X.des.createEncryptionCipher;break;default:var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=a.algorithm,h}var m="hmacWith"+a.prfAlgorithm.toUpperCase(),d=Us(m),p=X.pkcs5.pbkdf2(t,r,n,s,d),E=X.random.getBytesSync(l),b=f(p);b.start(E),b.update(O.toDer(e)),b.finish(),c=b.output.getBytes();var N=zf(r,i,s,m);o=O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OID,!1,O.oidToDer(ar.pkcs5PBES2).getBytes()),O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OID,!1,O.oidToDer(ar.pkcs5PBKDF2).getBytes()),N]),O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OID,!1,O.oidToDer(u).getBytes()),O.create(O.Class.UNIVERSAL,O.Type.OCTETSTRING,!1,E)])])])}else if(a.algorithm==="3des"){s=24;var T=new X.util.ByteBuffer(r),p=le.pbe.generatePkcs12Key(t,T,1,n,s),E=le.pbe.generatePkcs12Key(t,T,2,n,s),b=X.des.createEncryptionCipher(p);b.start(E),b.update(O.toDer(e)),b.finish(),c=b.output.getBytes(),o=O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OID,!1,O.oidToDer(ar["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OCTETSTRING,!1,r),O.create(O.Class.UNIVERSAL,O.Type.INTEGER,!1,i.getBytes())])])}else{var h=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw h.algorithm=a.algorithm,h}var S=O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[o,O.create(O.Class.UNIVERSAL,O.Type.OCTETSTRING,!1,c)]);return S};le.decryptPrivateKeyInfo=function(e,t){var a=null,r={},n=[];if(!O.validate(e,Gf,r,n)){var i=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=O.derToOid(r.encryptionOid),o=le.pbe.getCipher(s,r.encryptionParams,t),c=X.util.createBuffer(r.encryptedData);return o.update(c),o.finish()&&(a=O.fromDer(o.output)),a};le.encryptedPrivateKeyToPem=function(e,t){var a={type:"ENCRYPTED PRIVATE KEY",body:O.toDer(e).getBytes()};return X.pem.encode(a,{maxline:t})};le.encryptedPrivateKeyFromPem=function(e){var t=X.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var a=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return O.fromDer(t.body)};le.encryptRsaPrivateKey=function(e,t,a){if(a=a||{},!a.legacy){var r=le.wrapRsaPrivateKey(le.privateKeyToAsn1(e));return r=le.encryptPrivateKeyInfo(r,t,a),le.encryptedPrivateKeyToPem(r)}var n,i,s,o;switch(a.algorithm){case"aes128":n="AES-128-CBC",s=16,i=X.random.getBytesSync(16),o=X.aes.createEncryptionCipher;break;case"aes192":n="AES-192-CBC",s=24,i=X.random.getBytesSync(16),o=X.aes.createEncryptionCipher;break;case"aes256":n="AES-256-CBC",s=32,i=X.random.getBytesSync(16),o=X.aes.createEncryptionCipher;break;case"3des":n="DES-EDE3-CBC",s=24,i=X.random.getBytesSync(8),o=X.des.createEncryptionCipher;break;case"des":n="DES-CBC",s=8,i=X.random.getBytesSync(8),o=X.des.createEncryptionCipher;break;default:var c=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+a.algorithm+'".');throw c.algorithm=a.algorithm,c}var l=X.pbe.opensslDeriveBytes(t,i.substr(0,8),s),u=o(l);u.start(i),u.update(O.toDer(le.privateKeyToAsn1(e))),u.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:n,parameters:X.util.bytesToHex(i).toUpperCase()},body:u.output.getBytes()};return X.pem.encode(f)};le.decryptRsaPrivateKey=function(e,t){var a=null,r=X.pem.decode(e)[0];if(r.type!=="ENCRYPTED PRIVATE KEY"&&r.type!=="PRIVATE KEY"&&r.type!=="RSA PRIVATE KEY"){var n=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw n.headerType=n,n}if(r.procType&&r.procType.type==="ENCRYPTED"){var i,s;switch(r.dekInfo.algorithm){case"DES-CBC":i=8,s=X.des.createDecryptionCipher;break;case"DES-EDE3-CBC":i=24,s=X.des.createDecryptionCipher;break;case"AES-128-CBC":i=16,s=X.aes.createDecryptionCipher;break;case"AES-192-CBC":i=24,s=X.aes.createDecryptionCipher;break;case"AES-256-CBC":i=32,s=X.aes.createDecryptionCipher;break;case"RC2-40-CBC":i=5,s=function(f){return X.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":i=8,s=function(f){return X.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":i=16,s=function(f){return X.rc2.createDecryptionCipher(f,128)};break;default:var n=new Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw n.algorithm=r.dekInfo.algorithm,n}var o=X.util.hexToBytes(r.dekInfo.parameters),c=X.pbe.opensslDeriveBytes(t,o.substr(0,8),i),l=s(c);if(l.start(o),l.update(X.util.createBuffer(r.body)),l.finish())a=l.output.getBytes();else return a}else a=r.body;return r.type==="ENCRYPTED PRIVATE KEY"?a=le.decryptPrivateKeyInfo(O.fromDer(a),t):a=O.fromDer(a),a!==null&&(a=le.privateKeyFromAsn1(a)),a};le.pbe.generatePkcs12Key=function(e,t,a,r,n,i){var s,o;if(typeof i>"u"||i===null){if(!("sha1"in X.md))throw new Error('"sha1" hash algorithm unavailable.');i=X.md.sha1.create()}var c=i.digestLength,l=i.blockLength,u=new X.util.ByteBuffer,f=new X.util.ByteBuffer;if(e!=null){for(o=0;o<e.length;o++)f.putInt16(e.charCodeAt(o));f.putInt16(0)}var h=f.length(),m=t.length(),d=new X.util.ByteBuffer;d.fillWithByte(a,l);var p=l*Math.ceil(m/l),E=new X.util.ByteBuffer;for(o=0;o<p;o++)E.putByte(t.at(o%m));var b=l*Math.ceil(h/l),N=new X.util.ByteBuffer;for(o=0;o<b;o++)N.putByte(f.at(o%h));var T=E;T.putBuffer(N);for(var S=Math.ceil(n/c),I=1;I<=S;I++){var x=new X.util.ByteBuffer;x.putBytes(d.bytes()),x.putBytes(T.bytes());for(var w=0;w<r;w++)i.start(),i.update(x.getBytes()),x=i.digest();var C=new X.util.ByteBuffer;for(o=0;o<l;o++)C.putByte(x.at(o%c));var k=Math.ceil(m/l)+Math.ceil(h/l),D=new X.util.ByteBuffer;for(s=0;s<k;s++){var L=new X.util.ByteBuffer(T.getBytes(l)),R=511;for(o=C.length()-1;o>=0;o--)R=R>>8,R+=C.at(o)+L.at(o),L.setAt(o,R&255);D.putBuffer(L)}T=D,u.putBuffer(x)}return u.truncate(u.length()-n),u};le.pbe.getCipher=function(e,t,a){switch(e){case le.oids.pkcs5PBES2:return le.pbe.getCipherForPBES2(e,t,a);case le.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case le.oids["pbewithSHAAnd40BitRC2-CBC"]:return le.pbe.getCipherForPKCS12PBE(e,t,a);default:var r=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw r.oid=e,r.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],r}};le.pbe.getCipherForPBES2=function(e,t,a){var r={},n=[];if(!O.validate(t,jf,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}if(e=O.derToOid(r.kdfOid),e!==le.oids.pkcs5PBKDF2){var i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw i.oid=e,i.supportedOids=["pkcs5PBKDF2"],i}if(e=O.derToOid(r.encOid),e!==le.oids["aes128-CBC"]&&e!==le.oids["aes192-CBC"]&&e!==le.oids["aes256-CBC"]&&e!==le.oids["des-EDE3-CBC"]&&e!==le.oids.desCBC){var i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw i.oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i}var s=r.kdfSalt,o=X.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var c,l;switch(le.oids[e]){case"aes128-CBC":c=16,l=X.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,l=X.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,l=X.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,l=X.des.createDecryptionCipher;break;case"desCBC":c=8,l=X.des.createDecryptionCipher;break}var u=Ps(r.prfOid),f=X.pkcs5.pbkdf2(a,s,o,c,u),h=r.encIv,m=l(f);return m.start(h),m};le.pbe.getCipherForPKCS12PBE=function(e,t,a){var r={},n=[];if(!O.validate(t,$f,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=X.util.createBuffer(r.salt),o=X.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var c,l,u;switch(e){case le.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,u=X.des.startDecrypting;break;case le.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,u=function(p,E){var b=X.rc2.createDecryptionCipher(p,40);return b.start(E,null),b};break;default:var i=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw i.oid=e,i}var f=Ps(r.prfOid),h=le.pbe.generatePkcs12Key(a,s,1,o,c,f);f.start();var m=le.pbe.generatePkcs12Key(a,s,2,o,l,f);return u(h,m)};le.pbe.opensslDeriveBytes=function(e,t,a,r){if(typeof r>"u"||r===null){if(!("md5"in X.md))throw new Error('"md5" hash algorithm unavailable.');r=X.md.md5.create()}t===null&&(t="");for(var n=[Ds(r,e+t)],i=16,s=1;i<a;++s,i+=16)n.push(Ds(r,n[s-1]+e+t));return n.join("").substr(0,a)};function Ds(e,t){return e.start().update(t).digest().getBytes()}function Ps(e){var t;if(!e)t="hmacWithSHA1";else if(t=le.oids[O.derToOid(e)],!t){var a=new Error("Unsupported PRF OID.");throw a.oid=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}return Us(t)}function Us(e){var t=X.md;switch(e){case"hmacWithSHA224":t=X.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var a=new Error("Unsupported PRF algorithm.");throw a.algorithm=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function zf(e,t,a,r){var n=O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OCTETSTRING,!1,e),O.create(O.Class.UNIVERSAL,O.Type.INTEGER,!1,t.getBytes())]);return r!=="hmacWithSHA1"&&n.value.push(O.create(O.Class.UNIVERSAL,O.Type.INTEGER,!1,X.util.hexToBytes(a.toString(16))),O.create(O.Class.UNIVERSAL,O.Type.SEQUENCE,!0,[O.create(O.Class.UNIVERSAL,O.Type.OID,!1,O.oidToDer(le.oids[r]).getBytes()),O.create(O.Class.UNIVERSAL,O.Type.NULL,!1,"")])),n}});var In=ie((ty,Fs)=>{var Cr=ue();gt();Ce();var Y=Cr.asn1,wr=Fs.exports=Cr.pkcs7asn1=Cr.pkcs7asn1||{};Cr.pkcs7=Cr.pkcs7||{};Cr.pkcs7.asn1=wr;var Vs={name:"ContentInfo",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:Y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};wr.contentInfoValidator=Vs;var Ks={name:"EncryptedContentInfo",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:Y.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:Y.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};wr.envelopedDataValidator={name:"EnvelopedData",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(Ks)};wr.encryptedDataValidator={name:"EncryptedData",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"version"}].concat(Ks)};var Wf={name:"SignerInfo",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:Y.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:Y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:Y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};wr.signedDataValidator={name:"SignedData",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},Vs,{name:"SignedData.Certificates",tagClass:Y.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:Y.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SET,capture:"signerInfos",optional:!0,value:[Wf]}]};wr.recipientInfoValidator={name:"RecipientInfo",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:Y.Class.UNIVERSAL,type:Y.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:Y.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:Y.Class.UNIVERSAL,type:Y.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var An=ie((ry,Ms)=>{var nr=ue();Ce();nr.mgf=nr.mgf||{};var Qf=Ms.exports=nr.mgf.mgf1=nr.mgf1=nr.mgf1||{};Qf.create=function(e){var t={generate:function(a,r){for(var n=new nr.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s<i;s++){var o=new nr.util.ByteBuffer;o.putInt32(s),e.start(),e.update(a+o.getBytes()),n.putBuffer(e.digest())}return n.truncate(n.length()-r),n.getBytes()}};return t}});var qs=ie((ay,Hs)=>{var Ia=ue();An();Hs.exports=Ia.mgf=Ia.mgf||{};Ia.mgf.mgf1=Ia.mgf1});var Aa=ie((ny,Gs)=>{var ir=ue();lt();Ce();var Yf=Gs.exports=ir.pss=ir.pss||{};Yf.create=function(e){arguments.length===3&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,a=e.mgf,r=t.digestLength,n=e.salt||null;typeof n=="string"&&(n=ir.util.createBuffer(n));var i;if("saltLength"in e)i=e.saltLength;else if(n!==null)i=n.length();else throw new Error("Salt length not specified or specific salt not given.");if(n!==null&&n.length()!==i)throw new Error("Given salt length does not match length of given salt.");var s=e.prng||ir.random,o={};return o.encode=function(c,l){var u,f=l-1,h=Math.ceil(f/8),m=c.digest().getBytes();if(h<r+i+2)throw new Error("Message is too long to encrypt.");var d;n===null?d=s.getBytesSync(i):d=n.bytes();var p=new ir.util.ByteBuffer;p.fillWithByte(0,8),p.putBytes(m),p.putBytes(d),t.start(),t.update(p.getBytes());var E=t.digest().getBytes(),b=new ir.util.ByteBuffer;b.fillWithByte(0,h-i-r-2),b.putByte(1),b.putBytes(d);var N=b.getBytes(),T=h-r-1,S=a.generate(E,T),I="";for(u=0;u<T;u++)I+=String.fromCharCode(N.charCodeAt(u)^S.charCodeAt(u));var x=65280>>8*h-f&255;return I=String.fromCharCode(I.charCodeAt(0)&~x)+I.substr(1),I+E+"\xBC"},o.verify=function(c,l,u){var f,h=u-1,m=Math.ceil(h/8);if(l=l.substr(-m),m<r+i+2)throw new Error("Inconsistent parameters to PSS signature verification.");if(l.charCodeAt(m-1)!==188)throw new Error("Encoded message does not end in 0xBC.");var d=m-r-1,p=l.substr(0,d),E=l.substr(d,r),b=65280>>8*m-h&255;if((p.charCodeAt(0)&b)!==0)throw new Error("Bits beyond keysize not zero as expected.");var N=a.generate(E,d),T="";for(f=0;f<d;f++)T+=String.fromCharCode(p.charCodeAt(f)^N.charCodeAt(f));T=String.fromCharCode(T.charCodeAt(0)&~b)+T.substr(1);var S=m-r-i-2;for(f=0;f<S;f++)if(T.charCodeAt(f)!==0)throw new Error("Leftmost octets not zero as expected");if(T.charCodeAt(S)!==1)throw new Error("Inconsistent PSS signature, 0x01 marker not found");var I=T.substr(-i),x=new ir.util.ByteBuffer;x.fillWithByte(0,8),x.putBytes(c),x.putBytes(I),t.start(),t.update(x.getBytes());var w=t.digest().getBytes();return E===w},o}});var Na=ie((iy,Qs)=>{var ae=ue();Mt();gt();Kr();mt();qs();Ht();er();Aa();Hr();Ce();var y=ae.asn1,$=Qs.exports=ae.pki=ae.pki||{},me=$.oids,De={};De.CN=me.commonName;De.commonName="CN";De.C=me.countryName;De.countryName="C";De.L=me.localityName;De.localityName="L";De.ST=me.stateOrProvinceName;De.stateOrProvinceName="ST";De.O=me.organizationName;De.organizationName="O";De.OU=me.organizationalUnitName;De.organizationalUnitName="OU";De.E=me.emailAddress;De.emailAddress="E";var $s=ae.pki.rsa.publicKeyValidator,Xf={name:"Certificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:y.Class.UNIVERSAL,type:y.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:y.Class.UNIVERSAL,type:y.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},$s,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},Jf={name:"rsapss",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:y.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:y.Class.UNIVERSAL,type:y.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:y.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:y.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:y.Class.UNIVERSAL,type:y.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},Zf={name:"CertificationRequestInfo",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:y.Class.UNIVERSAL,type:y.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},$s,{name:"CertificationRequestInfo.attributes",tagClass:y.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:y.Class.UNIVERSAL,type:y.Type.SET,constructed:!0}]}]}]},e0={name:"CertificationRequest",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[Zf,{name:"CertificationRequest.signatureAlgorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:y.Class.UNIVERSAL,type:y.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:y.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:y.Class.UNIVERSAL,type:y.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};$.RDNAttributesAsArray=function(e,t){for(var a=[],r,n,i,s=0;s<e.value.length;++s){r=e.value[s];for(var o=0;o<r.value.length;++o)i={},n=r.value[o],i.type=y.derToOid(n.value[0].value),i.value=n.value[1].value,i.valueTagClass=n.value[1].type,i.type in me&&(i.name=me[i.type],i.name in De&&(i.shortName=De[i.name])),t&&(t.update(i.type),t.update(i.value)),a.push(i)}return a};$.CRIAttributesAsArray=function(e){for(var t=[],a=0;a<e.length;++a)for(var r=e[a],n=y.derToOid(r.value[0].value),i=r.value[1].value,s=0;s<i.length;++s){var o={};if(o.type=n,o.value=i[s].value,o.valueTagClass=i[s].type,o.type in me&&(o.name=me[o.type],o.name in De&&(o.shortName=De[o.name])),o.type===me.extensionRequest){o.extensions=[];for(var c=0;c<o.value.length;++c)o.extensions.push($.certificateExtensionFromAsn1(o.value[c]))}t.push(o)}return t};function jt(e,t){typeof t=="string"&&(t={shortName:t});for(var a=null,r,n=0;a===null&&n<e.attributes.length;++n)r=e.attributes[n],(t.type&&t.type===r.type||t.name&&t.name===r.name||t.shortName&&t.shortName===r.shortName)&&(a=r);return a}var Ba=function(e,t,a){var r={};if(e!==me["RSASSA-PSS"])return r;a&&(r={hash:{algorithmOid:me.sha1},mgf:{algorithmOid:me.mgf1,hash:{algorithmOid:me.sha1}},saltLength:20});var n={},i=[];if(!y.validate(t,Jf,n,i)){var s=new Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=i,s}return n.hashOid!==void 0&&(r.hash=r.hash||{},r.hash.algorithmOid=y.derToOid(n.hashOid)),n.maskGenOid!==void 0&&(r.mgf=r.mgf||{},r.mgf.algorithmOid=y.derToOid(n.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=y.derToOid(n.maskGenHashOid)),n.saltLength!==void 0&&(r.saltLength=n.saltLength.charCodeAt(0)),r},_a=function(e){switch(me[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return ae.md.sha1.create();case"md5WithRSAEncryption":return ae.md.md5.create();case"sha256WithRSAEncryption":return ae.md.sha256.create();case"sha384WithRSAEncryption":return ae.md.sha384.create();case"sha512WithRSAEncryption":return ae.md.sha512.create();case"RSASSA-PSS":return ae.md.sha256.create();default:var t=new Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},zs=function(e){var t=e.certificate,a;switch(t.signatureOid){case me.sha1WithRSAEncryption:case me.sha1WithRSASignature:break;case me["RSASSA-PSS"]:var r,n;if(r=me[t.signatureParameters.mgf.hash.algorithmOid],r===void 0||ae.md[r]===void 0){var i=new Error("Unsupported MGF hash function.");throw i.oid=t.signatureParameters.mgf.hash.algorithmOid,i.name=r,i}if(n=me[t.signatureParameters.mgf.algorithmOid],n===void 0||ae.mgf[n]===void 0){var i=new Error("Unsupported MGF function.");throw i.oid=t.signatureParameters.mgf.algorithmOid,i.name=n,i}if(n=ae.mgf[n].create(ae.md[r].create()),r=me[t.signatureParameters.hash.algorithmOid],r===void 0||ae.md[r]===void 0){var i=new Error("Unsupported RSASSA-PSS hash function.");throw i.oid=t.signatureParameters.hash.algorithmOid,i.name=r,i}a=ae.pss.create(ae.md[r].create(),n,t.signatureParameters.saltLength);break}return t.publicKey.verify(e.md.digest().getBytes(),e.signature,a)};$.certificateFromPem=function(e,t,a){var r=ae.pem.decode(e)[0];if(r.type!=="CERTIFICATE"&&r.type!=="X509 CERTIFICATE"&&r.type!=="TRUSTED CERTIFICATE"){var n=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var i=y.fromDer(r.body,a);return $.certificateFromAsn1(i,t)};$.certificateToPem=function(e,t){var a={type:"CERTIFICATE",body:y.toDer($.certificateToAsn1(e)).getBytes()};return ae.pem.encode(a,{maxline:t})};$.publicKeyFromPem=function(e){var t=ae.pem.decode(e)[0];if(t.type!=="PUBLIC KEY"&&t.type!=="RSA PUBLIC KEY"){var a=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert public key from PEM; PEM is encrypted.");var r=y.fromDer(t.body);return $.publicKeyFromAsn1(r)};$.publicKeyToPem=function(e,t){var a={type:"PUBLIC KEY",body:y.toDer($.publicKeyToAsn1(e)).getBytes()};return ae.pem.encode(a,{maxline:t})};$.publicKeyToRSAPublicKeyPem=function(e,t){var a={type:"RSA PUBLIC KEY",body:y.toDer($.publicKeyToRSAPublicKey(e)).getBytes()};return ae.pem.encode(a,{maxline:t})};$.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||ae.md.sha1.create(),r=t.type||"RSAPublicKey",n;switch(r){case"RSAPublicKey":n=y.toDer($.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":n=y.toDer($.publicKeyToAsn1(e)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+t.type+'".')}a.start(),a.update(n);var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};$.certificationRequestFromPem=function(e,t,a){var r=ae.pem.decode(e)[0];if(r.type!=="CERTIFICATE REQUEST"){var n=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var i=y.fromDer(r.body,a);return $.certificationRequestFromAsn1(i,t)};$.certificationRequestToPem=function(e,t){var a={type:"CERTIFICATE REQUEST",body:y.toDer($.certificationRequestToAsn1(e)).getBytes()};return ae.pem.encode(a,{maxline:t})};$.createCertificate=function(){var e={};return e.version=2,e.serialNumber="00",e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.validity={},e.validity.notBefore=new Date,e.validity.notAfter=new Date,e.issuer={},e.issuer.getField=function(t){return jt(e.issuer,t)},e.issuer.addField=function(t){dt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return jt(e.subject,t)},e.subject.addField=function(t){dt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.extensions=[],e.publicKey=null,e.md=null,e.setSubject=function(t,a){dt(t),e.subject.attributes=t,delete e.subject.uniqueId,a&&(e.subject.uniqueId=a),e.subject.hash=null},e.setIssuer=function(t,a){dt(t),e.issuer.attributes=t,delete e.issuer.uniqueId,a&&(e.issuer.uniqueId=a),e.issuer.hash=null},e.setExtensions=function(t){for(var a=0;a<t.length;++a)Ws(t[a],{cert:e});e.extensions=t},e.getExtension=function(t){typeof t=="string"&&(t={name:t});for(var a=null,r,n=0;a===null&&n<e.extensions.length;++n)r=e.extensions[n],(t.id&&r.id===t.id||t.name&&r.name===t.name)&&(a=r);return a},e.sign=function(t,a){e.md=a||ae.md.sha1.create();var r=me[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.tbsCertificate=$.getTBSCertificate(e);var i=y.toDer(e.tbsCertificate);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(t){var a=!1;if(!e.issued(t)){var r=t.issuer,n=e.subject,i=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw i.expectedIssuer=n.attributes,i.actualIssuer=r.attributes,i}var s=t.md;if(s===null){s=_a({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||$.getTBSCertificate(t),c=y.toDer(o);s.update(c.getBytes())}return s!==null&&(a=zs({certificate:e,md:s,signature:t.signature})),a},e.isIssuer=function(t){var a=!1,r=e.issuer,n=t.subject;if(r.hash&&n.hash)a=r.hash===n.hash;else if(r.attributes.length===n.attributes.length){a=!0;for(var i,s,o=0;a&&o<r.attributes.length;++o)i=r.attributes[o],s=n.attributes[o],(i.type!==s.type||i.value!==s.value)&&(a=!1)}return a},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return $.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){for(var t=me.subjectKeyIdentifier,a=0;a<e.extensions.length;++a){var r=e.extensions[a];if(r.id===t){var n=e.generateSubjectKeyIdentifier().getBytes();return ae.util.hexToBytes(r.subjectKeyIdentifier)===n}}return!1},e};$.certificateFromAsn1=function(e,t){var a={},r=[];if(!y.validate(e,Xf,a,r)){var n=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw n.errors=r,n}var i=y.derToOid(a.publicKeyOid);if(i!==$.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=$.createCertificate();s.version=a.certVersion?a.certVersion.charCodeAt(0):0;var o=ae.util.createBuffer(a.certSerialNumber);s.serialNumber=o.toHex(),s.signatureOid=ae.asn1.derToOid(a.certSignatureOid),s.signatureParameters=Ba(s.signatureOid,a.certSignatureParams,!0),s.siginfo.algorithmOid=ae.asn1.derToOid(a.certinfoSignatureOid),s.siginfo.parameters=Ba(s.siginfo.algorithmOid,a.certinfoSignatureParams,!1),s.signature=a.certSignature;var c=[];if(a.certValidity1UTCTime!==void 0&&c.push(y.utcTimeToDate(a.certValidity1UTCTime)),a.certValidity2GeneralizedTime!==void 0&&c.push(y.generalizedTimeToDate(a.certValidity2GeneralizedTime)),a.certValidity3UTCTime!==void 0&&c.push(y.utcTimeToDate(a.certValidity3UTCTime)),a.certValidity4GeneralizedTime!==void 0&&c.push(y.generalizedTimeToDate(a.certValidity4GeneralizedTime)),c.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=c[0],s.validity.notAfter=c[1],s.tbsCertificate=a.tbsCertificate,t){s.md=_a({signatureOid:s.signatureOid,type:"certificate"});var l=y.toDer(s.tbsCertificate);s.md.update(l.getBytes())}var u=ae.md.sha1.create(),f=y.toDer(a.certIssuer);u.update(f.getBytes()),s.issuer.getField=function(d){return jt(s.issuer,d)},s.issuer.addField=function(d){dt([d]),s.issuer.attributes.push(d)},s.issuer.attributes=$.RDNAttributesAsArray(a.certIssuer),a.certIssuerUniqueId&&(s.issuer.uniqueId=a.certIssuerUniqueId),s.issuer.hash=u.digest().toHex();var h=ae.md.sha1.create(),m=y.toDer(a.certSubject);return h.update(m.getBytes()),s.subject.getField=function(d){return jt(s.subject,d)},s.subject.addField=function(d){dt([d]),s.subject.attributes.push(d)},s.subject.attributes=$.RDNAttributesAsArray(a.certSubject),a.certSubjectUniqueId&&(s.subject.uniqueId=a.certSubjectUniqueId),s.subject.hash=h.digest().toHex(),a.certExtensions?s.extensions=$.certificateExtensionsFromAsn1(a.certExtensions):s.extensions=[],s.publicKey=$.publicKeyFromAsn1(a.subjectPublicKeyInfo),s};$.certificateExtensionsFromAsn1=function(e){for(var t=[],a=0;a<e.value.length;++a)for(var r=e.value[a],n=0;n<r.value.length;++n)t.push($.certificateExtensionFromAsn1(r.value[n]));return t};$.certificateExtensionFromAsn1=function(e){var t={};if(t.id=y.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===y.Type.BOOLEAN?(t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value):t.value=e.value[1].value,t.id in me){if(t.name=me[t.id],t.name==="keyUsage"){var a=y.fromDer(t.value),r=0,n=0;a.value.length>1&&(r=a.value.charCodeAt(1),n=a.value.length>2?a.value.charCodeAt(2):0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(n&128)===128}else if(t.name==="basicConstraints"){var a=y.fromDer(t.value);a.value.length>0&&a.value[0].type===y.Type.BOOLEAN?t.cA=a.value[0].value.charCodeAt(0)!==0:t.cA=!1;var i=null;a.value.length>0&&a.value[0].type===y.Type.INTEGER?i=a.value[0].value:a.value.length>1&&(i=a.value[1].value),i!==null&&(t.pathLenConstraint=y.derToInteger(i))}else if(t.name==="extKeyUsage")for(var a=y.fromDer(t.value),s=0;s<a.value.length;++s){var o=y.derToOid(a.value[s].value);o in me?t[me[o]]=!0:t[o]=!0}else if(t.name==="nsCertType"){var a=y.fromDer(t.value),r=0;a.value.length>1&&(r=a.value.charCodeAt(1)),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];for(var c,a=y.fromDer(t.value),l=0;l<a.value.length;++l){c=a.value[l];var u={type:c.type,value:c.value};switch(t.altNames.push(u),c.type){case 1:case 2:case 6:break;case 7:u.ip=ae.util.bytesToIP(c.value);break;case 8:u.oid=y.derToOid(c.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var a=y.fromDer(t.value);t.subjectKeyIdentifier=ae.util.bytesToHex(a.value)}}return t};$.certificationRequestFromAsn1=function(e,t){var a={},r=[];if(!y.validate(e,e0,a,r)){var n=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw n.errors=r,n}var i=y.derToOid(a.publicKeyOid);if(i!==$.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=$.createCertificationRequest();if(s.version=a.csrVersion?a.csrVersion.charCodeAt(0):0,s.signatureOid=ae.asn1.derToOid(a.csrSignatureOid),s.signatureParameters=Ba(s.signatureOid,a.csrSignatureParams,!0),s.siginfo.algorithmOid=ae.asn1.derToOid(a.csrSignatureOid),s.siginfo.parameters=Ba(s.siginfo.algorithmOid,a.csrSignatureParams,!1),s.signature=a.csrSignature,s.certificationRequestInfo=a.certificationRequestInfo,t){s.md=_a({signatureOid:s.signatureOid,type:"certification request"});var o=y.toDer(s.certificationRequestInfo);s.md.update(o.getBytes())}var c=ae.md.sha1.create();return s.subject.getField=function(l){return jt(s.subject,l)},s.subject.addField=function(l){dt([l]),s.subject.attributes.push(l)},s.subject.attributes=$.RDNAttributesAsArray(a.certificationRequestInfoSubject,c),s.subject.hash=c.digest().toHex(),s.publicKey=$.publicKeyFromAsn1(a.subjectPublicKeyInfo),s.getAttribute=function(l){return jt(s,l)},s.addAttribute=function(l){dt([l]),s.attributes.push(l)},s.attributes=$.CRIAttributesAsArray(a.certificationRequestInfoAttributes||[]),s};$.createCertificationRequest=function(){var e={};return e.version=0,e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.subject={},e.subject.getField=function(t){return jt(e.subject,t)},e.subject.addField=function(t){dt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return jt(e,t)},e.addAttribute=function(t){dt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){dt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){dt(t),e.attributes=t},e.sign=function(t,a){e.md=a||ae.md.sha1.create();var r=me[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.certificationRequestInfo=$.getCertificationRequestInfo(e);var i=y.toDer(e.certificationRequestInfo);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,a=e.md;if(a===null){a=_a({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||$.getCertificationRequestInfo(e),n=y.toDer(r);a.update(n.getBytes())}return a!==null&&(t=zs({certificate:e,md:a,signature:e.signature})),t},e};function xr(e){for(var t=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),a,r,n=e.attributes,i=0;i<n.length;++i){a=n[i];var s=a.value,o=y.Type.PRINTABLESTRING;"valueTagClass"in a&&(o=a.valueTagClass,o===y.Type.UTF8&&(s=ae.util.encodeUtf8(s))),r=y.create(y.Class.UNIVERSAL,y.Type.SET,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(a.type).getBytes()),y.create(y.Class.UNIVERSAL,o,!1,s)])]),t.value.push(r)}return t}function dt(e){for(var t,a=0;a<e.length;++a){if(t=e[a],typeof t.name>"u"&&(t.type&&t.type in $.oids?t.name=$.oids[t.type]:t.shortName&&t.shortName in De&&(t.name=$.oids[De[t.shortName]])),typeof t.type>"u")if(t.name&&t.name in $.oids)t.type=$.oids[t.name];else{var r=new Error("Attribute type not specified.");throw r.attribute=t,r}if(typeof t.shortName>"u"&&t.name&&t.name in De&&(t.shortName=De[t.name]),t.type===me.extensionRequest&&(t.valueConstructed=!0,t.valueTagClass=y.Type.SEQUENCE,!t.value&&t.extensions)){t.value=[];for(var n=0;n<t.extensions.length;++n)t.value.push($.certificateExtensionToAsn1(Ws(t.extensions[n])))}if(typeof t.value>"u"){var r=new Error("Attribute value not specified.");throw r.attribute=t,r}}}function Ws(e,t){if(t=t||{},typeof e.name>"u"&&e.id&&e.id in $.oids&&(e.name=$.oids[e.id]),typeof e.id>"u")if(e.name&&e.name in $.oids)e.id=$.oids[e.name];else{var a=new Error("Extension ID not specified.");throw a.extension=e,a}if(typeof e.value<"u")return e;if(e.name==="keyUsage"){var r=0,n=0,i=0;e.digitalSignature&&(n|=128,r=7),e.nonRepudiation&&(n|=64,r=6),e.keyEncipherment&&(n|=32,r=5),e.dataEncipherment&&(n|=16,r=4),e.keyAgreement&&(n|=8,r=3),e.keyCertSign&&(n|=4,r=2),e.cRLSign&&(n|=2,r=1),e.encipherOnly&&(n|=1,r=0),e.decipherOnly&&(i|=128,r=7);var s=String.fromCharCode(r);i!==0?s+=String.fromCharCode(n)+String.fromCharCode(i):n!==0&&(s+=String.fromCharCode(n)),e.value=y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints")e.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),e.cA&&e.value.value.push(y.create(y.Class.UNIVERSAL,y.Type.BOOLEAN,!1,"\xFF")),"pathLenConstraint"in e&&e.value.value.push(y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(e.pathLenConstraint).getBytes()));else if(e.name==="extKeyUsage"){e.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var c in e)e[c]===!0&&(c in me?o.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(me[c]).getBytes())):c.indexOf(".")!==-1&&o.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(c).getBytes())))}else if(e.name==="nsCertType"){var r=0,n=0;e.client&&(n|=128,r=7),e.server&&(n|=64,r=6),e.email&&(n|=32,r=5),e.objsign&&(n|=16,r=4),e.reserved&&(n|=8,r=3),e.sslCA&&(n|=4,r=2),e.emailCA&&(n|=2,r=1),e.objCA&&(n|=1,r=0);var s=String.fromCharCode(r);n!==0&&(s+=String.fromCharCode(n)),e.value=y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);for(var l,u=0;u<e.altNames.length;++u){l=e.altNames[u];var s=l.value;if(l.type===7&&l.ip){if(s=ae.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=y.oidToDer(y.oidToDer(l.oid)):s=y.oidToDer(s));e.value.value.push(y.create(y.Class.CONTEXT_SPECIFIC,l.type,!1,s))}}else if(e.name==="nsComment"&&t.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw new Error('Invalid "nsComment" content.');e.value=y.create(y.Class.UNIVERSAL,y.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,f.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var h=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!1,h))}if(e.authorityCertIssuer){var m=[y.create(y.Class.CONTEXT_SPECIFIC,4,!0,[xr(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var d=ae.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!1,d))}}else if(e.name==="cRLDistributionPoints"){e.value=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);for(var o=e.value.value,p=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]),E=y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[]),l,u=0;u<e.altNames.length;++u){l=e.altNames[u];var s=l.value;if(l.type===7&&l.ip){if(s=ae.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=y.oidToDer(y.oidToDer(l.oid)):s=y.oidToDer(s));E.value.push(y.create(y.Class.CONTEXT_SPECIFIC,l.type,!1,s))}p.value.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[E])),o.push(p)}if(typeof e.value>"u"){var a=new Error("Extension value not specified.");throw a.extension=e,a}return e}function Bn(e,t){switch(e){case me["RSASSA-PSS"]:var a=[];return t.hash.algorithmOid!==void 0&&a.push(y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.hash.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")])])),t.mgf.algorithmOid!==void 0&&a.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.mgf.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(t.mgf.hash.algorithmOid).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")])])])),t.saltLength!==void 0&&a.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(t.saltLength).getBytes())])),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,a);default:return y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")}}function t0(e){var t=y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[]);if(e.attributes.length===0)return t;for(var a=e.attributes,r=0;r<a.length;++r){var n=a[r],i=n.value,s=y.Type.UTF8;"valueTagClass"in n&&(s=n.valueTagClass),s===y.Type.UTF8&&(i=ae.util.encodeUtf8(i));var o=!1;"valueConstructed"in n&&(o=n.valueConstructed);var c=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(n.type).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SET,!0,[y.create(y.Class.UNIVERSAL,s,o,i)])]);t.value.push(c)}return t}var r0=new Date("1950-01-01T00:00:00Z"),a0=new Date("2050-01-01T00:00:00Z");function js(e){return e>=r0&&e<a0?y.create(y.Class.UNIVERSAL,y.Type.UTCTIME,!1,y.dateToUtcTime(e)):y.create(y.Class.UNIVERSAL,y.Type.GENERALIZEDTIME,!1,y.dateToGeneralizedTime(e))}$.getTBSCertificate=function(e){var t=js(e.validity.notBefore),a=js(e.validity.notAfter),r=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.CONTEXT_SPECIFIC,0,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(e.version).getBytes())]),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,ae.util.hexToBytes(e.serialNumber)),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.siginfo.algorithmOid).getBytes()),Bn(e.siginfo.algorithmOid,e.siginfo.parameters)]),xr(e.issuer),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[t,a]),xr(e.subject),$.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&r.value.push(y.create(y.Class.CONTEXT_SPECIFIC,1,!0,[y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,"\0"+e.issuer.uniqueId)])),e.subject.uniqueId&&r.value.push(y.create(y.Class.CONTEXT_SPECIFIC,2,!0,[y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,"\0"+e.subject.uniqueId)])),e.extensions.length>0&&r.value.push($.certificateExtensionsToAsn1(e.extensions)),r};$.getCertificationRequestInfo=function(e){var t=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(e.version).getBytes()),xr(e.subject),$.publicKeyToAsn1(e.publicKey),t0(e)]);return t};$.distinguishedNameToAsn1=function(e){return xr(e)};$.certificateToAsn1=function(e){var t=e.tbsCertificate||$.getTBSCertificate(e);return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[t,y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.signatureOid).getBytes()),Bn(e.signatureOid,e.signatureParameters)]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,"\0"+e.signature)])};$.certificateExtensionsToAsn1=function(e){var t=y.create(y.Class.CONTEXT_SPECIFIC,3,!0,[]),a=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);t.value.push(a);for(var r=0;r<e.length;++r)a.value.push($.certificateExtensionToAsn1(e[r]));return t};$.certificateExtensionToAsn1=function(e){var t=y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[]);t.value.push(y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.id).getBytes())),e.critical&&t.value.push(y.create(y.Class.UNIVERSAL,y.Type.BOOLEAN,!1,"\xFF"));var a=e.value;return typeof e.value!="string"&&(a=y.toDer(a).getBytes()),t.value.push(y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,a)),t};$.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||$.getCertificationRequestInfo(e);return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[t,y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(e.signatureOid).getBytes()),Bn(e.signatureOid,e.signatureParameters)]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,"\0"+e.signature)])};$.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var o=a(s.issuer);return o},t.addCertificate=function(s){if(typeof s=="string"&&(s=ae.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var o=t.certs[s.subject.hash];ae.util.isArray(o)||(o=[o]),o.push(s),t.certs[s.subject.hash]=o}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){typeof s=="string"&&(s=ae.pki.certificateFromPem(s));var o=a(s.subject);if(!o)return!1;ae.util.isArray(o)||(o=[o]);for(var c=y.toDer($.certificateToAsn1(s)).getBytes(),l=0;l<o.length;++l){var u=y.toDer($.certificateToAsn1(o[l])).getBytes();if(c===u)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var c=t.certs[o];if(!ae.util.isArray(c))s.push(c);else for(var l=0;l<c.length;++l)s.push(c[l])}return s},t.removeCertificate=function(s){var o;if(typeof s=="string"&&(s=ae.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))return null;var c=a(s.subject);if(!ae.util.isArray(c))return o=t.certs[s.subject.hash],delete t.certs[s.subject.hash],o;for(var l=y.toDer($.certificateToAsn1(s)).getBytes(),u=0;u<c.length;++u){var f=y.toDer($.certificateToAsn1(c[u])).getBytes();l===f&&(o=c[u],c.splice(u,1))}return c.length===0&&delete t.certs[s.subject.hash],o};function a(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var o=ae.md.sha1.create();s.attributes=$.RDNAttributesAsArray(xr(s),o),s.hash=o.digest().toHex()}}if(e)for(var n=0;n<e.length;++n){var i=e[n];t.addCertificate(i)}return t};$.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};$.verifyCertificateChain=function(e,t,a){typeof a=="function"&&(a={verify:a}),a=a||{},t=t.slice(0);var r=t.slice(0),n=a.validityCheckDate;typeof n>"u"&&(n=new Date);var i=!0,s=null,o=0;do{var c=t.shift(),l=null,u=!1;if(n&&(n<c.validity.notBefore||n>c.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:$.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:n}),s===null){if(l=t[0]||e.getIssuer(c),l===null&&c.isIssuer(c)&&(u=!0,l=c),l){var f=l;ae.util.isArray(f)||(f=[f]);for(var h=!1;!h&&f.length>0;){l=f.shift();try{h=l.verify(c)}catch{}}h||(s={message:"Certificate signature is invalid.",error:$.certificateError.bad_certificate})}s===null&&(!l||u)&&!e.hasCertificate(c)&&(s={message:"Certificate is not trusted.",error:$.certificateError.unknown_ca})}if(s===null&&l&&!c.isIssuer(l)&&(s={message:"Certificate issuer is invalid.",error:$.certificateError.bad_certificate}),s===null)for(var m={keyUsage:!0,basicConstraints:!0},d=0;s===null&&d<c.extensions.length;++d){var p=c.extensions[d];p.critical&&!(p.name in m)&&(s={message:"Certificate has an unsupported critical extension.",error:$.certificateError.unsupported_certificate})}if(s===null&&(!i||t.length===0&&(!l||u))){var E=c.getExtension("basicConstraints"),b=c.getExtension("keyUsage");if(b!==null&&(!b.keyCertSign||E===null)&&(s={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:$.certificateError.bad_certificate}),s===null&&E===null&&(s={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:$.certificateError.bad_certificate}),s===null&&E!==null&&!E.cA&&(s={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:$.certificateError.bad_certificate}),s===null&&b!==null&&"pathLenConstraint"in E){var N=o-1;N>E.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:$.certificateError.bad_certificate})}}var T=s===null?!0:s.error,S=a.verify?a.verify(T,o,r):T;if(S===!0)s=null;else throw T===!0&&(s={message:"The application rejected the certificate.",error:$.certificateError.bad_certificate}),(S||S===0)&&(typeof S=="object"&&!ae.util.isArray(S)?(S.message&&(s.message=S.message),S.error&&(s.error=S.error)):typeof S=="string"&&(s.error=S)),s;i=!1,++o}while(t.length>0);return!0}});var Nn=ie((sy,Xs)=>{var Be=ue();gt();yr();Ht();In();Tn();lt();Hr();Er();Ce();Na();var A=Be.asn1,he=Be.pki,Gr=Xs.exports=Be.pkcs12=Be.pkcs12||{},Ys={name:"ContentInfo",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:A.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},n0={name:"PFX",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,capture:"version"},Ys,{name:"PFX.macData",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:A.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:A.Class.UNIVERSAL,type:A.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:A.Class.UNIVERSAL,type:A.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:A.Class.UNIVERSAL,type:A.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},i0={name:"SafeBag",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:A.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:A.Class.UNIVERSAL,type:A.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},s0={name:"Attribute",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:A.Class.UNIVERSAL,type:A.Type.SET,constructed:!0,capture:"values"}]},o0={name:"CertBag",tagClass:A.Class.UNIVERSAL,type:A.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:A.Class.UNIVERSAL,type:A.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:A.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:A.Class.UNIVERSAL,type:A.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function qr(e,t,a,r){for(var n=[],i=0;i<e.length;i++)for(var s=0;s<e[i].safeBags.length;s++){var o=e[i].safeBags[s];if(!(r!==void 0&&o.type!==r)){if(t===null){n.push(o);continue}o.attributes[t]!==void 0&&o.attributes[t].indexOf(a)>=0&&n.push(o)}}return n}Gr.pkcs12FromAsn1=function(e,t,a){typeof t=="string"?(a=t,t=!0):t===void 0&&(t=!0);var r={},n=[];if(!A.validate(e,n0,r,n)){var i=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw i.errors=i,i}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(E){var b={},N;return"localKeyId"in E?N=E.localKeyId:"localKeyIdHex"in E&&(N=Be.util.hexToBytes(E.localKeyIdHex)),N===void 0&&!("friendlyName"in E)&&"bagType"in E&&(b[E.bagType]=qr(s.safeContents,null,null,E.bagType)),N!==void 0&&(b.localKeyId=qr(s.safeContents,"localKeyId",N,E.bagType)),"friendlyName"in E&&(b.friendlyName=qr(s.safeContents,"friendlyName",E.friendlyName,E.bagType)),b},getBagsByFriendlyName:function(E,b){return qr(s.safeContents,"friendlyName",E,b)},getBagsByLocalKeyId:function(E,b){return qr(s.safeContents,"localKeyId",E,b)}};if(r.version.charCodeAt(0)!==3){var i=new Error("PKCS#12 PFX of version other than 3 not supported.");throw i.version=r.version.charCodeAt(0),i}if(A.derToOid(r.contentType)!==he.oids.data){var i=new Error("Only PKCS#12 PFX in password integrity mode supported.");throw i.oid=A.derToOid(r.contentType),i}var o=r.content.value[0];if(o.tagClass!==A.Class.UNIVERSAL||o.type!==A.Type.OCTETSTRING)throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=_n(o),r.mac){var c=null,l=0,u=A.derToOid(r.macAlgorithm);switch(u){case he.oids.sha1:c=Be.md.sha1.create(),l=20;break;case he.oids.sha256:c=Be.md.sha256.create(),l=32;break;case he.oids.sha384:c=Be.md.sha384.create(),l=48;break;case he.oids.sha512:c=Be.md.sha512.create(),l=64;break;case he.oids.md5:c=Be.md.md5.create(),l=16;break}if(c===null)throw new Error("PKCS#12 uses unsupported MAC algorithm: "+u);var f=new Be.util.ByteBuffer(r.macSalt),h="macIterations"in r?parseInt(Be.util.bytesToHex(r.macIterations),16):1,m=Gr.generateKey(a,f,3,h,l,c),d=Be.hmac.create();d.start(c,m),d.update(o.value);var p=d.getMac();if(p.getBytes()!==r.macDigest)throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(e.value)&&e.value.length>2)throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.");return c0(s,o.value,t,a),s};function _n(e){if(e.composed||e.constructed){for(var t=Be.util.createBuffer(),a=0;a<e.value.length;++a)t.putBytes(e.value[a].value);e.composed=e.constructed=!1,e.value=t.getBytes()}return e}function c0(e,t,a,r){if(t=A.fromDer(t,a),t.tagClass!==A.Class.UNIVERSAL||t.type!==A.Type.SEQUENCE||t.constructed!==!0)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var n=0;n<t.value.length;n++){var i=t.value[n],s={},o=[];if(!A.validate(i,Ys,s,o)){var c=new Error("Cannot read ContentInfo.");throw c.errors=o,c}var l={encrypted:!1},u=null,f=s.content.value[0];switch(A.derToOid(s.contentType)){case he.oids.data:if(f.tagClass!==A.Class.UNIVERSAL||f.type!==A.Type.OCTETSTRING)throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");u=_n(f).value;break;case he.oids.encryptedData:u=l0(f,r),l.encrypted=!0;break;default:var c=new Error("Unsupported PKCS#12 contentType.");throw c.contentType=A.derToOid(s.contentType),c}l.safeBags=u0(u,a,r),e.safeContents.push(l)}}function l0(e,t){var a={},r=[];if(!A.validate(e,Be.pkcs7.asn1.encryptedDataValidator,a,r)){var n=new Error("Cannot read EncryptedContentInfo.");throw n.errors=r,n}var i=A.derToOid(a.contentType);if(i!==he.oids.data){var n=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw n.oid=i,n}i=A.derToOid(a.encAlgorithm);var s=he.pbe.getCipher(i,a.encParameter,t),o=_n(a.encryptedContentAsn1),c=Be.util.createBuffer(o.value);if(s.update(c),!s.finish())throw new Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function u0(e,t,a){if(!t&&e.length===0)return[];if(e=A.fromDer(e,t),e.tagClass!==A.Class.UNIVERSAL||e.type!==A.Type.SEQUENCE||e.constructed!==!0)throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");for(var r=[],n=0;n<e.value.length;n++){var i=e.value[n],s={},o=[];if(!A.validate(i,i0,s,o)){var c=new Error("Cannot read SafeBag.");throw c.errors=o,c}var l={type:A.derToOid(s.bagId),attributes:f0(s.bagAttributes)};r.push(l);var u,f,h=s.bagValue.value[0];switch(l.type){case he.oids.pkcs8ShroudedKeyBag:if(h=he.decryptPrivateKeyInfo(h,a),h===null)throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case he.oids.keyBag:try{l.key=he.privateKeyFromAsn1(h)}catch{l.key=null,l.asn1=h}continue;case he.oids.certBag:u=o0,f=function(){if(A.derToOid(s.certId)!==he.oids.x509Certificate){var d=new Error("Unsupported certificate type, only X.509 supported.");throw d.oid=A.derToOid(s.certId),d}var p=A.fromDer(s.cert,t);try{l.cert=he.certificateFromAsn1(p,!0)}catch{l.cert=null,l.asn1=p}};break;default:var c=new Error("Unsupported PKCS#12 SafeBag type.");throw c.oid=l.type,c}if(u!==void 0&&!A.validate(h,u,s,o)){var c=new Error("Cannot read PKCS#12 "+u.name);throw c.errors=o,c}f()}return r}function f0(e){var t={};if(e!==void 0)for(var a=0;a<e.length;++a){var r={},n=[];if(!A.validate(e[a],s0,r,n)){var i=new Error("Cannot read PKCS#12 BagAttribute.");throw i.errors=n,i}var s=A.derToOid(r.oid);if(he.oids[s]!==void 0){t[he.oids[s]]=[];for(var o=0;o<r.values.length;++o)t[he.oids[s]].push(r.values[o].value)}}return t}Gr.toPkcs12Asn1=function(e,t,a,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||r.encAlgorithm||"aes128","useMac"in r||(r.useMac=!0),"localKeyId"in r||(r.localKeyId=null),"generateLocalKeyId"in r||(r.generateLocalKeyId=!0);var n=r.localKeyId,i;if(n!==null)n=Be.util.hexToBytes(n);else if(r.generateLocalKeyId)if(t){var s=Be.util.isArray(t)?t[0]:t;typeof s=="string"&&(s=he.certificateFromPem(s));var o=Be.md.sha1.create();o.update(A.toDer(he.certificateToAsn1(s)).getBytes()),n=o.digest().getBytes()}else n=Be.random.getBytes(20);var c=[];n!==null&&c.push(A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.localKeyId).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.SET,!0,[A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,n)])])),"friendlyName"in r&&c.push(A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.friendlyName).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.SET,!0,[A.create(A.Class.UNIVERSAL,A.Type.BMPSTRING,!1,r.friendlyName)])])),c.length>0&&(i=A.create(A.Class.UNIVERSAL,A.Type.SET,!0,c));var l=[],u=[];t!==null&&(Be.util.isArray(t)?u=t:u=[t]);for(var f=[],h=0;h<u.length;++h){t=u[h],typeof t=="string"&&(t=he.certificateFromPem(t));var m=h===0?i:void 0,d=he.certificateToAsn1(t),p=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.certBag).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.x509Certificate).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,A.toDer(d).getBytes())])])]),m]);f.push(p)}if(f.length>0){var E=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,f),b=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.data).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,A.toDer(E).getBytes())])]);l.push(b)}var N=null;if(e!==null){var T=he.wrapRsaPrivateKey(he.privateKeyToAsn1(e));a===null?N=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.keyBag).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[T]),i]):N=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.pkcs8ShroudedKeyBag).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[he.encryptPrivateKeyInfo(T,a,r)]),i]);var S=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[N]),I=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.data).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,A.toDer(S).getBytes())])]);l.push(I)}var x=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,l),w;if(r.useMac){var o=Be.md.sha1.create(),C=new Be.util.ByteBuffer(Be.random.getBytes(r.saltSize)),k=r.count,e=Gr.generateKey(a,C,3,k,20),D=Be.hmac.create();D.start(o,e),D.update(A.toDer(x).getBytes());var L=D.getMac();w=A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.sha1).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.NULL,!1,"")]),A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,L.getBytes())]),A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,C.getBytes()),A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,A.integerToDer(k).getBytes())])}return A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.INTEGER,!1,A.integerToDer(3).getBytes()),A.create(A.Class.UNIVERSAL,A.Type.SEQUENCE,!0,[A.create(A.Class.UNIVERSAL,A.Type.OID,!1,A.oidToDer(he.oids.data).getBytes()),A.create(A.Class.CONTEXT_SPECIFIC,0,!0,[A.create(A.Class.UNIVERSAL,A.Type.OCTETSTRING,!1,A.toDer(x).getBytes())])]),w])};Gr.generateKey=Be.pbe.generatePkcs12Key});var Rn=ie((oy,Js)=>{var $t=ue();gt();Ht();Tn();er();Ca();Nn();Aa();Hr();Ce();Na();var kn=$t.asn1,Sr=Js.exports=$t.pki=$t.pki||{};Sr.pemToDer=function(e){var t=$t.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PEM to DER; PEM is encrypted.");return $t.util.createBuffer(t.body)};Sr.privateKeyFromPem=function(e){var t=$t.pem.decode(e)[0];if(t.type!=="PRIVATE KEY"&&t.type!=="RSA PRIVATE KEY"){var a=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert private key from PEM; PEM is encrypted.");var r=kn.fromDer(t.body);return Sr.privateKeyFromAsn1(r)};Sr.privateKeyToPem=function(e,t){var a={type:"RSA PRIVATE KEY",body:kn.toDer(Sr.privateKeyToAsn1(e)).getBytes()};return $t.pem.encode(a,{maxline:t})};Sr.privateKeyInfoToPem=function(e,t){var a={type:"PRIVATE KEY",body:kn.toDer(e).getBytes()};return $t.pem.encode(a,{maxline:t})}});var Vn=ie((cy,so)=>{var F=ue();gt();yr();ga();er();Rn();lt();Er();Ce();var Da=function(e,t,a,r){var n=F.util.createBuffer(),i=e.length>>1,s=i+(e.length&1),o=e.substr(0,s),c=e.substr(i,s),l=F.util.createBuffer(),u=F.hmac.create();a=t+a;var f=Math.ceil(r/16),h=Math.ceil(r/20);u.start("MD5",o);var m=F.util.createBuffer();l.putBytes(a);for(var d=0;d<f;++d)u.start(null,null),u.update(l.getBytes()),l.putBuffer(u.digest()),u.start(null,null),u.update(l.bytes()+a),m.putBuffer(u.digest());u.start("SHA1",c);var p=F.util.createBuffer();l.clear(),l.putBytes(a);for(var d=0;d<h;++d)u.start(null,null),u.update(l.getBytes()),l.putBuffer(u.digest()),u.start(null,null),u.update(l.bytes()+a),p.putBuffer(u.digest());return n.putBytes(F.util.xorBytes(m.getBytes(),p.getBytes(),r)),n},d0=function(e,t,a){var r=F.hmac.create();r.start("SHA1",e);var n=F.util.createBuffer();return n.putInt32(t[0]),n.putInt32(t[1]),n.putByte(a.type),n.putByte(a.version.major),n.putByte(a.version.minor),n.putInt16(a.length),n.putBytes(a.fragment.bytes()),r.update(n.getBytes()),r.digest().getBytes()},h0=function(e,t,a){var r=!1;try{var n=e.deflate(t.fragment.getBytes());t.fragment=F.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},p0=function(e,t,a){var r=!1;try{var n=e.inflate(t.fragment.getBytes());t.fragment=F.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},ot=function(e,t){var a=0;switch(t){case 1:a=e.getByte();break;case 2:a=e.getInt16();break;case 3:a=e.getInt24();break;case 4:a=e.getInt32();break}return F.util.createBuffer(e.getBytes(a))},ht=function(e,t,a){e.putInt(a.length(),t<<3),e.putBuffer(a)},v={};v.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};v.SupportedVersions=[v.Versions.TLS_1_1,v.Versions.TLS_1_0];v.Version=v.SupportedVersions[0];v.MaxFragment=15360;v.ConnectionEnd={server:0,client:1};v.PRFAlgorithm={tls_prf_sha256:0};v.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};v.CipherType={stream:0,block:1,aead:2};v.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};v.CompressionMethod={none:0,deflate:1};v.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};v.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};v.Alert={};v.Alert.Level={warning:1,fatal:2};v.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};v.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};v.CipherSuites={};v.getCipherSuite=function(e){var t=null;for(var a in v.CipherSuites){var r=v.CipherSuites[a];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};v.handleUnexpected=function(e,t){var a=!e.open&&e.entity===v.ConnectionEnd.client;a||e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unexpected_message}})};v.handleHelloRequest=function(e,t,a){!e.handshaking&&e.handshakes>0&&(v.queue(e,v.createAlert(e,{level:v.Alert.Level.warning,description:v.Alert.Description.no_renegotiation})),v.flush(e)),e.process()};v.parseHelloMessage=function(e,t,a){var r=null,n=e.entity===v.ConnectionEnd.client;if(a<38)e.error(e,{message:n?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});else{var i=t.fragment,s=i.length();if(r={version:{major:i.getByte(),minor:i.getByte()},random:F.util.createBuffer(i.getBytes(32)),session_id:ot(i,1),extensions:[]},n?(r.cipher_suite=i.getBytes(2),r.compression_method=i.getByte()):(r.cipher_suites=ot(i,2),r.compression_methods=ot(i,1)),s=a-(s-i.length()),s>0){for(var o=ot(i,2);o.length()>0;)r.extensions.push({type:[o.getByte(),o.getByte()],data:ot(o,2)});if(!n)for(var c=0;c<r.extensions.length;++c){var l=r.extensions[c];if(l.type[0]===0&&l.type[1]===0)for(var u=ot(l.data,2);u.length()>0;){var f=u.getByte();if(f!==0)break;e.session.extensions.server_name.serverNameList.push(ot(u,2).getBytes())}}}if(e.session.version&&(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.protocol_version}});if(n)e.session.cipherSuite=v.getCipherSuite(r.cipher_suite);else for(var h=F.util.createBuffer(r.cipher_suites.bytes());h.length()>0&&(e.session.cipherSuite=v.getCipherSuite(h.getBytes(2)),e.session.cipherSuite===null););if(e.session.cipherSuite===null)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.handshake_failure},cipherSuite:F.util.bytesToHex(r.cipher_suite)});n?e.session.compressionMethod=r.compression_method:e.session.compressionMethod=v.CompressionMethod.none}return r};v.createSecurityParameters=function(e,t){var a=e.entity===v.ConnectionEnd.client,r=t.random.bytes(),n=a?e.session.sp.client_random:r,i=a?r:v.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:v.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:i}};v.handleServerHello=function(e,t,a){var r=v.parseHelloMessage(e,t,a);if(!e.fail){if(r.version.minor<=e.version.minor)e.version.minor=r.version.minor;else return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.protocol_version}});e.session.version=e.version;var n=r.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=to,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes()):(e.expect=g0,e.session.resuming=!1,v.createSecurityParameters(e,r)),e.session.id=n,e.process()}};v.handleClientHello=function(e,t,a){var r=v.parseHelloMessage(e,t,a);if(!e.fail){var n=r.session_id.bytes(),i=null;if(e.sessionCache&&(i=e.sessionCache.getSession(n),i===null?n="":(i.version.major!==r.version.major||i.version.minor>r.version.minor)&&(i=null,n="")),n.length===0&&(n=F.random.getBytes(32)),e.session.id=n,e.session.clientHelloVersion=r.version,e.session.sp={},i)e.version=e.session.version=i.version,e.session.sp=i.sp;else{for(var s,o=1;o<v.SupportedVersions.length&&(s=v.SupportedVersions[o],!(s.minor<=r.version.minor));++o);e.version={major:s.major,minor:s.minor},e.session.version=e.version}i!==null?(e.expect=Un,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes()):(e.expect=e.verifyClient!==!1?S0:Pn,e.session.resuming=!1,v.createSecurityParameters(e,r)),e.open=!0,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerHello(e)})),e.session.resuming?(v.queue(e,v.createRecord(e,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),e.state.pending=v.createConnectionState(e),e.state.current.write=e.state.pending.write,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createFinished(e)}))):(v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificate(e)})),e.fail||(v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerKeyExchange(e)})),e.verifyClient!==!1&&v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificateRequest(e)})),v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerHelloDone(e)})))),v.flush(e),e.process()}};v.handleCertificate=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_list:ot(r,3)},i,s,o=[];try{for(;n.certificate_list.length()>0;)i=ot(n.certificate_list,3),s=F.asn1.fromDer(i),i=F.pki.certificateFromAsn1(s,!0),o.push(i)}catch(l){return e.error(e,{message:"Could not parse certificate list.",cause:l,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate}})}var c=e.entity===v.ConnectionEnd.client;(c||e.verifyClient===!0)&&o.length===0?e.error(e,{message:c?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}}):o.length===0?e.expect=c?Zs:Pn:(c?e.session.serverCertificate=o[0]:e.session.clientCertificate=o[0],v.verifyCertificateChain(e,o)&&(e.expect=c?Zs:Pn)),e.process()};v.handleServerKeyExchange=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unsupported_certificate}});e.expect=v0,e.process()};v.handleClientKeyExchange=function(e,t,a){if(a<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unsupported_certificate}});var r=t.fragment,n={enc_pre_master_secret:ot(r,2).getBytes()},i=null;if(e.getPrivateKey)try{i=e.getPrivateKey(e,e.session.serverCertificate),i=F.pki.privateKeyFromPem(i)}catch(c){e.error(e,{message:"Could not get private key.",cause:c,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}})}if(i===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=i.decrypt(n.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==s.pre_master_secret.charCodeAt(0)||o.minor!==s.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch{s.pre_master_secret=F.random.getBytes(48)}e.expect=Un,e.session.clientCertificate!==null&&(e.expect=b0),e.process()};v.handleCertificateRequest=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_types:ot(r,1),certificate_authorities:ot(r,2)};e.session.certificateRequest=n,e.expect=m0,e.process()};v.handleCertificateVerify=function(e,t,a){if(a<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i={signature:ot(r,2).getBytes()},s=F.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(s,i.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(n),e.session.sha1.update(n)}catch{return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.handshake_failure}})}e.expect=Un,e.process()};v.handleServerHelloDone=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.record_overflow}});if(e.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.insufficient_security}},n=0,i=e.verify(e,r.alert.description,n,[]);if(i!==!0)return(i||i===0)&&(typeof i=="object"&&!F.util.isArray(i)?(i.message&&(r.message=i.message),i.alert&&(r.alert.description=i.alert)):typeof i=="number"&&(r.alert.description=i)),e.error(e,r)}e.session.certificateRequest!==null&&(t=v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificate(e)}),v.queue(e,t)),t=v.createRecord(e,{type:v.ContentType.handshake,data:v.createClientKeyExchange(e)}),v.queue(e,t),e.expect=w0;var s=function(o,c){o.session.certificateRequest!==null&&o.session.clientCertificate!==null&&v.queue(o,v.createRecord(o,{type:v.ContentType.handshake,data:v.createCertificateVerify(o,c)})),v.queue(o,v.createRecord(o,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),o.state.pending=v.createConnectionState(o),o.state.current.write=o.state.pending.write,v.queue(o,v.createRecord(o,{type:v.ContentType.handshake,data:v.createFinished(o)})),o.expect=to,v.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);v.getClientSignature(e,s)};v.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var a=e.entity===v.ConnectionEnd.client;(e.session.resuming&&a||!e.session.resuming&&!a)&&(e.state.pending=v.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&a||e.session.resuming&&!a)&&(e.state.pending=null),e.expect=a?E0:T0,e.process()};v.handleFinished=function(e,t,a){var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i=t.fragment.getBytes();r=F.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===v.ConnectionEnd.client,o=s?"server finished":"client finished",c=e.session.sp,l=12,u=Da;if(r=u(c.master_secret,o,r.getBytes(),l),r.getBytes()!==i)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.decrypt_error}});e.session.md5.update(n),e.session.sha1.update(n),(e.session.resuming&&s||!e.session.resuming&&!s)&&(v.queue(e,v.createRecord(e,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createFinished(e)}))),e.expect=s?C0:I0,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,v.flush(e),e.isConnected=!0,e.connected(e),e.process()};v.handleAlert=function(e,t){var a=t.fragment,r={level:a.getByte(),description:a.getByte()},n;switch(r.description){case v.Alert.Description.close_notify:n="Connection closed.";break;case v.Alert.Description.unexpected_message:n="Unexpected message.";break;case v.Alert.Description.bad_record_mac:n="Bad record MAC.";break;case v.Alert.Description.decryption_failed:n="Decryption failed.";break;case v.Alert.Description.record_overflow:n="Record overflow.";break;case v.Alert.Description.decompression_failure:n="Decompression failed.";break;case v.Alert.Description.handshake_failure:n="Handshake failure.";break;case v.Alert.Description.bad_certificate:n="Bad certificate.";break;case v.Alert.Description.unsupported_certificate:n="Unsupported certificate.";break;case v.Alert.Description.certificate_revoked:n="Certificate revoked.";break;case v.Alert.Description.certificate_expired:n="Certificate expired.";break;case v.Alert.Description.certificate_unknown:n="Certificate unknown.";break;case v.Alert.Description.illegal_parameter:n="Illegal parameter.";break;case v.Alert.Description.unknown_ca:n="Unknown certificate authority.";break;case v.Alert.Description.access_denied:n="Access denied.";break;case v.Alert.Description.decode_error:n="Decode error.";break;case v.Alert.Description.decrypt_error:n="Decrypt error.";break;case v.Alert.Description.export_restriction:n="Export restriction.";break;case v.Alert.Description.protocol_version:n="Unsupported protocol version.";break;case v.Alert.Description.insufficient_security:n="Insufficient security.";break;case v.Alert.Description.internal_error:n="Internal error.";break;case v.Alert.Description.user_canceled:n="User canceled.";break;case v.Alert.Description.no_renegotiation:n="Renegotiation not supported.";break;default:n="Unknown error.";break}if(r.description===v.Alert.Description.close_notify)return e.close();e.error(e,{message:n,send:!1,origin:e.entity===v.ConnectionEnd.client?"server":"client",alert:r}),e.process()};v.handleHandshake=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt24();if(n>a.length())return e.fragmented=t,t.fragment=F.util.createBuffer(),a.read-=4,e.process();e.fragmented=null,a.read-=4;var i=a.bytes(n+4);a.read+=4,r in La[e.entity][e.expect]?(e.entity===v.ConnectionEnd.server&&!e.open&&!e.fail&&(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:F.md.md5.create(),sha1:F.md.sha1.create()}),r!==v.HandshakeType.hello_request&&r!==v.HandshakeType.certificate_verify&&r!==v.HandshakeType.finished&&(e.session.md5.update(i),e.session.sha1.update(i)),La[e.entity][e.expect][r](e,t,n)):v.handleUnexpected(e,t)};v.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};v.handleHeartbeat=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt16(),i=a.getBytes(n);if(r===v.HeartbeatMessageType.heartbeat_request){if(e.handshaking||n>i.length)return e.process();v.queue(e,v.createRecord(e,{type:v.ContentType.heartbeat,data:v.createHeartbeat(v.HeartbeatMessageType.heartbeat_response,i)})),v.flush(e)}else if(r===v.HeartbeatMessageType.heartbeat_response){if(i!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,F.util.createBuffer(i))}e.process()};var y0=0,g0=1,Zs=2,v0=3,m0=4,to=5,E0=6,C0=7,w0=8,x0=0,S0=1,Pn=2,b0=3,Un=4,T0=5,I0=6,g=v.handleUnexpected,ro=v.handleChangeCipherSpec,Ge=v.handleAlert,tt=v.handleHandshake,ao=v.handleApplicationData,je=v.handleHeartbeat,On=[];On[v.ConnectionEnd.client]=[[g,Ge,tt,g,je],[g,Ge,tt,g,je],[g,Ge,tt,g,je],[g,Ge,tt,g,je],[g,Ge,tt,g,je],[ro,Ge,g,g,je],[g,Ge,tt,g,je],[g,Ge,tt,ao,je],[g,Ge,tt,g,je]];On[v.ConnectionEnd.server]=[[g,Ge,tt,g,je],[g,Ge,tt,g,je],[g,Ge,tt,g,je],[g,Ge,tt,g,je],[ro,Ge,g,g,je],[g,Ge,tt,g,je],[g,Ge,tt,ao,je],[g,Ge,tt,g,je]];var zt=v.handleHelloRequest,A0=v.handleServerHello,no=v.handleCertificate,eo=v.handleServerKeyExchange,Ln=v.handleCertificateRequest,ka=v.handleServerHelloDone,io=v.handleFinished,La=[];La[v.ConnectionEnd.client]=[[g,g,A0,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,no,eo,Ln,ka,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,eo,Ln,ka,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,g,Ln,ka,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,g,g,ka,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,io],[zt,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[zt,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g]];var B0=v.handleClientHello,_0=v.handleClientKeyExchange,N0=v.handleCertificateVerify;La[v.ConnectionEnd.server]=[[g,B0,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,no,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,_0,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,N0,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,io],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g]];v.generateKeys=function(e,t){var a=Da,r=t.client_random+t.server_random;e.session.resuming||(t.master_secret=a(t.pre_master_secret,"master secret",r,48).bytes(),t.pre_master_secret=null),r=t.server_random+t.client_random;var n=2*t.mac_key_length+2*t.enc_key_length,i=e.version.major===v.Versions.TLS_1_0.major&&e.version.minor===v.Versions.TLS_1_0.minor;i&&(n+=2*t.fixed_iv_length);var s=a(t.master_secret,"key expansion",r,n),o={client_write_MAC_key:s.getBytes(t.mac_key_length),server_write_MAC_key:s.getBytes(t.mac_key_length),client_write_key:s.getBytes(t.enc_key_length),server_write_key:s.getBytes(t.enc_key_length)};return i&&(o.client_write_IV=s.getBytes(t.fixed_iv_length),o.server_write_IV=s.getBytes(t.fixed_iv_length)),o};v.createConnectionState=function(e){var t=e.entity===v.ConnectionEnd.client,a=function(){var i={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(s){return!0},compressionState:null,compressFunction:function(s){return!0},updateSequenceNumber:function(){i.sequenceNumber[1]===4294967295?(i.sequenceNumber[1]=0,++i.sequenceNumber[0]):++i.sequenceNumber[1]}};return i},r={read:a(),write:a()};if(r.read.update=function(i,s){return r.read.cipherFunction(s,r.read)?r.read.compressFunction(i,s,r.read)||i.error(i,{message:"Could not decompress record.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.decompression_failure}}):i.error(i,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_record_mac}}),!i.fail},r.write.update=function(i,s){return r.write.compressFunction(i,s,r.write)?r.write.cipherFunction(s,r.write)||i.error(i,{message:"Could not encrypt record.",send:!1,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}}):i.error(i,{message:"Could not compress record.",send:!1,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}}),!i.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=v.generateKeys(e,n),r.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,r.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,n),n.compression_algorithm){case v.CompressionMethod.none:break;case v.CompressionMethod.deflate:r.read.compressFunction=p0,r.write.compressFunction=h0;break;default:throw new Error("Unsupported compression algorithm.")}}return r};v.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*6e4,a=F.util.createBuffer();return a.putInt32(t),a.putBytes(F.random.getBytes(28)),a};v.createRecord=function(e,t){if(!t.data)return null;var a={type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data};return a};v.createAlert=function(e,t){var a=F.util.createBuffer();return a.putByte(t.level),a.putByte(t.description),v.createRecord(e,{type:v.ContentType.alert,data:a})};v.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=F.util.createBuffer(),a=0;a<e.cipherSuites.length;++a){var r=e.cipherSuites[a];t.putByte(r.id[0]),t.putByte(r.id[1])}var n=t.length(),i=F.util.createBuffer();i.putByte(v.CompressionMethod.none);var s=i.length(),o=F.util.createBuffer();if(e.virtualHost){var c=F.util.createBuffer();c.putByte(0),c.putByte(0);var l=F.util.createBuffer();l.putByte(0),ht(l,2,F.util.createBuffer(e.virtualHost));var u=F.util.createBuffer();ht(u,2,l),ht(c,2,u),o.putBuffer(c)}var f=o.length();f>0&&(f+=2);var h=e.session.id,m=h.length+1+2+4+28+2+n+1+s+f,d=F.util.createBuffer();return d.putByte(v.HandshakeType.client_hello),d.putInt24(m),d.putByte(e.version.major),d.putByte(e.version.minor),d.putBytes(e.session.sp.client_random),ht(d,1,F.util.createBuffer(h)),ht(d,2,t),ht(d,1,i),f>0&&ht(d,2,o),d};v.createServerHello=function(e){var t=e.session.id,a=t.length+1+2+4+28+2+1,r=F.util.createBuffer();return r.putByte(v.HandshakeType.server_hello),r.putInt24(a),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),ht(r,1,F.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};v.createCertificate=function(e){var t=e.entity===v.ConnectionEnd.client,a=null;if(e.getCertificate){var r;t?r=e.session.certificateRequest:r=e.session.extensions.server_name.serverNameList,a=e.getCertificate(e,r)}var n=F.util.createBuffer();if(a!==null)try{F.util.isArray(a)||(a=[a]);for(var i=null,s=0;s<a.length;++s){var o=F.pem.decode(a[s])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var c=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw c.headerType=o.type,c}if(o.procType&&o.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var l=F.util.createBuffer(o.body);i===null&&(i=F.asn1.fromDer(l.bytes(),!1));var u=F.util.createBuffer();ht(u,3,l),n.putBuffer(u)}a=F.pki.certificateFromAsn1(i),t?e.session.clientCertificate=a:e.session.serverCertificate=a}catch(m){return e.error(e,{message:"Could not send certificate list.",cause:m,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate}})}var f=3+n.length(),h=F.util.createBuffer();return h.putByte(v.HandshakeType.certificate),h.putInt24(f),ht(h,3,n),h};v.createClientKeyExchange=function(e){var t=F.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(F.random.getBytes(46));var a=e.session.sp;a.pre_master_secret=t.getBytes();var r=e.session.serverCertificate.publicKey;t=r.encrypt(a.pre_master_secret);var n=t.length+2,i=F.util.createBuffer();return i.putByte(v.HandshakeType.client_key_exchange),i.putInt24(n),i.putInt16(t.length),i.putBytes(t),i};v.createServerKeyExchange=function(e){var t=0,a=F.util.createBuffer();return t>0&&(a.putByte(v.HandshakeType.server_key_exchange),a.putInt24(t)),a};v.getClientSignature=function(e,t){var a=F.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes(),e.getSignature=e.getSignature||function(r,n,i){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=F.pki.privateKeyFromPem(s)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}})}s===null?r.error(r,{message:"No private key set.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}}):n=s.sign(n,null),i(r,n)},e.getSignature(e,a,t)};v.createCertificateVerify=function(e,t){var a=t.length+2,r=F.util.createBuffer();return r.putByte(v.HandshakeType.certificate_verify),r.putInt24(a),r.putInt16(t.length),r.putBytes(t),r};v.createCertificateRequest=function(e){var t=F.util.createBuffer();t.putByte(1);var a=F.util.createBuffer();for(var r in e.caStore.certs){var n=e.caStore.certs[r],i=F.pki.distinguishedNameToAsn1(n.subject),s=F.asn1.toDer(i);a.putInt16(s.length()),a.putBuffer(s)}var o=1+t.length()+2+a.length(),c=F.util.createBuffer();return c.putByte(v.HandshakeType.certificate_request),c.putInt24(o),ht(c,1,t),ht(c,2,a),c};v.createServerHelloDone=function(e){var t=F.util.createBuffer();return t.putByte(v.HandshakeType.server_hello_done),t.putInt24(0),t};v.createChangeCipherSpec=function(){var e=F.util.createBuffer();return e.putByte(1),e};v.createFinished=function(e){var t=F.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var a=e.entity===v.ConnectionEnd.client,r=e.session.sp,n=12,i=Da,s=a?"client finished":"server finished";t=i(r.master_secret,s,t.getBytes(),n);var o=F.util.createBuffer();return o.putByte(v.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};v.createHeartbeat=function(e,t,a){typeof a>"u"&&(a=t.length);var r=F.util.createBuffer();r.putByte(e),r.putInt16(a),r.putBytes(t);var n=r.length(),i=Math.max(16,n-a-3);return r.putBytes(F.random.getBytes(i)),r};v.queue=function(e,t){if(t&&!(t.fragment.length()===0&&(t.type===v.ContentType.handshake||t.type===v.ContentType.alert||t.type===v.ContentType.change_cipher_spec))){if(t.type===v.ContentType.handshake){var a=t.fragment.bytes();e.session.md5.update(a),e.session.sha1.update(a),a=null}var r;if(t.fragment.length()<=v.MaxFragment)r=[t];else{r=[];for(var n=t.fragment.bytes();n.length>v.MaxFragment;)r.push(v.createRecord(e,{type:t.type,data:F.util.createBuffer(n.slice(0,v.MaxFragment))})),n=n.slice(v.MaxFragment);n.length>0&&r.push(v.createRecord(e,{type:t.type,data:F.util.createBuffer(n)}))}for(var i=0;i<r.length&&!e.fail;++i){var s=r[i],o=e.state.current.write;o.update(e,s)&&e.records.push(s)}}};v.flush=function(e){for(var t=0;t<e.records.length;++t){var a=e.records[t];e.tlsData.putByte(a.type),e.tlsData.putByte(a.version.major),e.tlsData.putByte(a.version.minor),e.tlsData.putInt16(a.fragment.length()),e.tlsData.putBuffer(e.records[t].fragment)}return e.records=[],e.tlsDataReady(e)};var Dn=function(e){switch(e){case!0:return!0;case F.pki.certificateError.bad_certificate:return v.Alert.Description.bad_certificate;case F.pki.certificateError.unsupported_certificate:return v.Alert.Description.unsupported_certificate;case F.pki.certificateError.certificate_revoked:return v.Alert.Description.certificate_revoked;case F.pki.certificateError.certificate_expired:return v.Alert.Description.certificate_expired;case F.pki.certificateError.certificate_unknown:return v.Alert.Description.certificate_unknown;case F.pki.certificateError.unknown_ca:return v.Alert.Description.unknown_ca;default:return v.Alert.Description.bad_certificate}},k0=function(e){switch(e){case!0:return!0;case v.Alert.Description.bad_certificate:return F.pki.certificateError.bad_certificate;case v.Alert.Description.unsupported_certificate:return F.pki.certificateError.unsupported_certificate;case v.Alert.Description.certificate_revoked:return F.pki.certificateError.certificate_revoked;case v.Alert.Description.certificate_expired:return F.pki.certificateError.certificate_expired;case v.Alert.Description.certificate_unknown:return F.pki.certificateError.certificate_unknown;case v.Alert.Description.unknown_ca:return F.pki.certificateError.unknown_ca;default:return F.pki.certificateError.bad_certificate}};v.verifyCertificateChain=function(e,t){try{var a={};for(var r in e.verifyOptions)a[r]=e.verifyOptions[r];a.verify=function(i,s,o){var c=Dn(i),l=e.verify(e,i,s,o);if(l!==!0){if(typeof l=="object"&&!F.util.isArray(l)){var u=new Error("The application rejected the certificate.");throw u.send=!0,u.alert={level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate},l.message&&(u.message=l.message),l.alert&&(u.alert.description=l.alert),u}l!==i&&(l=k0(l))}return l},F.pki.verifyCertificateChain(e.caStore,t,a)}catch(i){var n=i;(typeof n!="object"||F.util.isArray(n))&&(n={send:!0,alert:{level:v.Alert.Level.fatal,description:Dn(i)}}),"send"in n||(n.send=!0),"alert"in n||(n.alert={level:v.Alert.Level.fatal,description:Dn(n.error)}),e.error(e,n)}return!e.fail};v.createSessionCache=function(e,t){var a=null;if(e&&e.getSession&&e.setSession&&e.order)a=e;else{a={},a.cache=e||{},a.capacity=Math.max(t||100,1),a.order=[];for(var r in e)a.order.length<=t?a.order.push(r):delete e[r];a.getSession=function(n){var i=null,s=null;if(n?s=F.util.bytesToHex(n):a.order.length>0&&(s=a.order[0]),s!==null&&s in a.cache){i=a.cache[s],delete a.cache[s];for(var o in a.order)if(a.order[o]===s){a.order.splice(o,1);break}}return i},a.setSession=function(n,i){if(a.order.length===a.capacity){var s=a.order.shift();delete a.cache[s]}var s=F.util.bytesToHex(n);a.order.push(s),a.cache[s]=i}}return a};v.createConnection=function(e){var t=null;e.caStore?F.util.isArray(e.caStore)?t=F.pki.createCaStore(e.caStore):t=e.caStore:t=F.pki.createCaStore();var a=e.cipherSuites||null;if(a===null){a=[];for(var r in v.CipherSuites)a.push(v.CipherSuites[r])}var n=e.server?v.ConnectionEnd.server:v.ConnectionEnd.client,i=e.sessionCache?v.createSessionCache(e.sessionCache):null,s={version:{major:v.Version.major,minor:v.Version.minor},entity:n,sessionId:e.sessionId,caStore:t,sessionCache:i,cipherSuites:a,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(u,f,h,m){return f},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:F.util.createBuffer(),tlsData:F.util.createBuffer(),data:F.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(u,f){f.origin=f.origin||(u.entity===v.ConnectionEnd.client?"client":"server"),f.send&&(v.queue(u,v.createAlert(u,f.alert)),v.flush(u));var h=f.fatal!==!1;h&&(u.fail=!0),e.error(u,f),h&&u.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(u){s.version={major:v.Version.major,minor:v.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===v.ConnectionEnd.client?y0:x0,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(u||typeof u>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=v.createConnectionState(s)},s.reset();var o=function(u,f){var h=f.type-v.ContentType.change_cipher_spec,m=On[u.entity][u.expect];h in m?m[h](u,f):v.handleUnexpected(u,f)},c=function(u){var f=0,h=u.input,m=h.length();if(m<5)f=5-m;else{u.record={type:h.getByte(),version:{major:h.getByte(),minor:h.getByte()},length:h.getInt16(),fragment:F.util.createBuffer(),ready:!1};var d=u.record.version.major===u.version.major;d&&u.session&&u.session.version&&(d=u.record.version.minor===u.version.minor),d||u.error(u,{message:"Incompatible TLS version.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.protocol_version}})}return f},l=function(u){var f=0,h=u.input,m=h.length();if(m<u.record.length)f=u.record.length-m;else{u.record.fragment.putBytes(h.getBytes(u.record.length)),h.compact();var d=u.state.current.read;d.update(u,u.record)&&(u.fragmented!==null&&(u.fragmented.type===u.record.type?(u.fragmented.fragment.putBuffer(u.record.fragment),u.record=u.fragmented):u.error(u,{message:"Invalid fragmented record.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unexpected_message}})),u.record.ready=!0)}return f};return s.handshake=function(u){if(s.entity!==v.ConnectionEnd.client)s.error(s,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(s.handshaking)s.error(s,{message:"Handshake already in progress.",fatal:!1});else{s.fail&&!s.open&&s.handshakes===0&&(s.fail=!1),s.handshaking=!0,u=u||"";var f=null;u.length>0&&(s.sessionCache&&(f=s.sessionCache.getSession(u)),f===null&&(u="")),u.length===0&&s.sessionCache&&(f=s.sessionCache.getSession(),f!==null&&(u=f.id)),s.session={id:u,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:F.md.md5.create(),sha1:F.md.sha1.create()},f&&(s.version=f.version,s.session.sp=f.sp),s.session.sp.client_random=v.createRandom().getBytes(),s.open=!0,v.queue(s,v.createRecord(s,{type:v.ContentType.handshake,data:v.createClientHello(s)})),v.flush(s)}},s.process=function(u){var f=0;return u&&s.input.putBytes(u),s.fail||(s.record!==null&&s.record.ready&&s.record.fragment.isEmpty()&&(s.record=null),s.record===null&&(f=c(s)),!s.fail&&s.record!==null&&!s.record.ready&&(f=l(s)),!s.fail&&s.record!==null&&s.record.ready&&o(s,s.record)),f},s.prepare=function(u){return v.queue(s,v.createRecord(s,{type:v.ContentType.application_data,data:F.util.createBuffer(u)})),v.flush(s)},s.prepareHeartbeatRequest=function(u,f){return u instanceof F.util.ByteBuffer&&(u=u.bytes()),typeof f>"u"&&(f=u.length),s.expectedHeartbeatPayload=u,v.queue(s,v.createRecord(s,{type:v.ContentType.heartbeat,data:v.createHeartbeat(v.HeartbeatMessageType.heartbeat_request,u,f)})),v.flush(s)},s.close=function(u){if(!s.fail&&s.sessionCache&&s.session){var f={id:s.session.id,version:s.session.version,sp:s.session.sp};f.sp.keys=null,s.sessionCache.setSession(f.id,f)}s.open&&(s.open=!1,s.input.clear(),(s.isConnected||s.handshaking)&&(s.isConnected=s.handshaking=!1,v.queue(s,v.createAlert(s,{level:v.Alert.Level.warning,description:v.Alert.Description.close_notify})),v.flush(s)),s.closed(s)),s.reset(u)},s};so.exports=F.tls=F.tls||{};for(Ra in v)typeof v[Ra]!="function"&&(F.tls[Ra]=v[Ra]);var Ra;F.tls.prf_tls1=Da;F.tls.hmac_sha1=d0;F.tls.createSessionCache=v.createSessionCache;F.tls.createConnection=v.createConnection});var lo=ie((ly,co)=>{var Wt=ue();Mt();Vn();var pt=co.exports=Wt.tls;pt.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=pt.BulkCipherAlgorithm.aes,e.cipher_type=pt.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=pt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:oo};pt.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=pt.BulkCipherAlgorithm.aes,e.cipher_type=pt.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=pt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:oo};function oo(e,t,a){var r=t.entity===Wt.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Wt.cipher.createDecipher("AES-CBC",r?a.keys.server_write_key:a.keys.client_write_key),iv:r?a.keys.server_write_IV:a.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Wt.cipher.createCipher("AES-CBC",r?a.keys.client_write_key:a.keys.server_write_key),iv:r?a.keys.client_write_IV:a.keys.server_write_IV},e.read.cipherFunction=P0,e.write.cipherFunction=R0,e.read.macLength=e.write.macLength=a.mac_length,e.read.macFunction=e.write.macFunction=pt.hmac_sha1}function R0(e,t){var a=!1,r=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(r),t.updateSequenceNumber();var n;e.version.minor===pt.Versions.TLS_1_0.minor?n=t.cipherState.init?null:t.cipherState.iv:n=Wt.random.getBytesSync(16),t.cipherState.init=!0;var i=t.cipherState.cipher;return i.start({iv:n}),e.version.minor>=pt.Versions.TLS_1_1.minor&&i.output.putBytes(n),i.update(e.fragment),i.finish(L0)&&(e.fragment=i.output,e.length=e.fragment.length(),a=!0),a}function L0(e,t,a){if(!a){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function D0(e,t,a){var r=!0;if(a){for(var n=t.length(),i=t.last(),s=n-1-i;s<n-1;++s)r=r&&t.at(s)==i;r&&t.truncate(i+1)}return r}function P0(e,t){var a=!1,r;e.version.minor===pt.Versions.TLS_1_0.minor?r=t.cipherState.init?null:t.cipherState.iv:r=e.fragment.getBytes(16),t.cipherState.init=!0;var n=t.cipherState.cipher;n.start({iv:r}),n.update(e.fragment),a=n.finish(D0);var i=t.macLength,s=Wt.random.getBytesSync(i),o=n.output.length();o>=i?(e.fragment=n.output.getBytes(o-i),s=n.output.getBytes(i)):e.fragment=n.output.getBytes(),e.fragment=Wt.util.createBuffer(e.fragment),e.length=e.fragment.length();var c=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),a=U0(t.macKey,s,c)&&a,a}function U0(e,t,a){var r=Wt.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(a),a=r.digest().getBytes(),t===a}});var Mn=ie((uy,po)=>{var Ne=ue();mt();Ce();var jr=po.exports=Ne.sha512=Ne.sha512||{};Ne.md.sha512=Ne.md.algorithms.sha512=jr;var fo=Ne.sha384=Ne.sha512.sha384=Ne.sha512.sha384||{};fo.create=function(){return jr.create("SHA-384")};Ne.md.sha384=Ne.md.algorithms.sha384=fo;Ne.sha512.sha256=Ne.sha512.sha256||{create:function(){return jr.create("SHA-512/256")}};Ne.md["sha512/256"]=Ne.md.algorithms["sha512/256"]=Ne.sha512.sha256;Ne.sha512.sha224=Ne.sha512.sha224||{create:function(){return jr.create("SHA-512/224")}};Ne.md["sha512/224"]=Ne.md.algorithms["sha512/224"]=Ne.sha512.sha224;jr.create=function(e){if(ho||O0(),typeof e>"u"&&(e="SHA-512"),!(e in sr))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=sr[e],a=null,r=Ne.util.createBuffer(),n=new Array(80),i=0;i<80;++i)n[i]=new Array(2);var s=64;switch(e){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];for(var c=o.messageLengthSize/4,l=0;l<c;++l)o.fullMessageLength.push(0);r=Ne.util.createBuffer(),a=new Array(t.length);for(var l=0;l<t.length;++l)a[l]=t[l].slice(0);return o},o.start(),o.update=function(c,l){l==="utf8"&&(c=Ne.util.encodeUtf8(c));var u=c.length;o.messageLength+=u,u=[u/4294967296>>>0,u>>>0];for(var f=o.fullMessageLength.length-1;f>=0;--f)o.fullMessageLength[f]+=u[1],u[1]=u[0]+(o.fullMessageLength[f]/4294967296>>>0),o.fullMessageLength[f]=o.fullMessageLength[f]>>>0,u[0]=u[1]/4294967296>>>0;return r.putBytes(c),uo(a,n,r),(r.read>2048||r.length()===0)&&r.compact(),o},o.digest=function(){var c=Ne.util.createBuffer();c.putBytes(r.bytes());var l=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,u=l&o.blockLength-1;c.putBytes(Kn.substr(0,o.blockLength-u));for(var f,h,m=o.fullMessageLength[0]*8,d=0;d<o.fullMessageLength.length-1;++d)f=o.fullMessageLength[d+1]*8,h=f/4294967296>>>0,m+=h,c.putInt32(m>>>0),m=f>>>0;c.putInt32(m);for(var p=new Array(a.length),d=0;d<a.length;++d)p[d]=a[d].slice(0);uo(p,n,c);var E=Ne.util.createBuffer(),b;e==="SHA-512"?b=p.length:e==="SHA-384"?b=p.length-2:b=p.length-4;for(var d=0;d<b;++d)E.putInt32(p[d][0]),(d!==b-1||e!=="SHA-512/224")&&E.putInt32(p[d][1]);return E},o};var Kn=null,ho=!1,Fn=null,sr=null;function O0(){Kn="\x80",Kn+=Ne.util.fillString("\0",128),Fn=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],sr={},sr["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],sr["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],sr["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],sr["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],ho=!0}function uo(e,t,a){for(var r,n,i,s,o,c,l,u,f,h,m,d,p,E,b,N,T,S,I,x,w,C,k,D,L,R,M,z,V,q,U,j,J,G,Z,te=a.length();te>=128;){for(V=0;V<16;++V)t[V][0]=a.getInt32()>>>0,t[V][1]=a.getInt32()>>>0;for(;V<80;++V)j=t[V-2],q=j[0],U=j[1],r=((q>>>19|U<<13)^(U>>>29|q<<3)^q>>>6)>>>0,n=((q<<13|U>>>19)^(U<<3|q>>>29)^(q<<26|U>>>6))>>>0,G=t[V-15],q=G[0],U=G[1],i=((q>>>1|U<<31)^(q>>>8|U<<24)^q>>>7)>>>0,s=((q<<31|U>>>1)^(q<<24|U>>>8)^(q<<25|U>>>7))>>>0,J=t[V-7],Z=t[V-16],U=n+J[1]+s+Z[1],t[V][0]=r+J[0]+i+Z[0]+(U/4294967296>>>0)>>>0,t[V][1]=U>>>0;for(p=e[0][0],E=e[0][1],b=e[1][0],N=e[1][1],T=e[2][0],S=e[2][1],I=e[3][0],x=e[3][1],w=e[4][0],C=e[4][1],k=e[5][0],D=e[5][1],L=e[6][0],R=e[6][1],M=e[7][0],z=e[7][1],V=0;V<80;++V)l=((w>>>14|C<<18)^(w>>>18|C<<14)^(C>>>9|w<<23))>>>0,u=((w<<18|C>>>14)^(w<<14|C>>>18)^(C<<23|w>>>9))>>>0,f=(L^w&(k^L))>>>0,h=(R^C&(D^R))>>>0,o=((p>>>28|E<<4)^(E>>>2|p<<30)^(E>>>7|p<<25))>>>0,c=((p<<4|E>>>28)^(E<<30|p>>>2)^(E<<25|p>>>7))>>>0,m=(p&b|T&(p^b))>>>0,d=(E&N|S&(E^N))>>>0,U=z+u+h+Fn[V][1]+t[V][1],r=M+l+f+Fn[V][0]+t[V][0]+(U/4294967296>>>0)>>>0,n=U>>>0,U=c+d,i=o+m+(U/4294967296>>>0)>>>0,s=U>>>0,M=L,z=R,L=k,R=D,k=w,D=C,U=x+n,w=I+r+(U/4294967296>>>0)>>>0,C=U>>>0,I=T,x=S,T=b,S=N,b=p,N=E,U=n+s,p=r+i+(U/4294967296>>>0)>>>0,E=U>>>0;U=e[0][1]+E,e[0][0]=e[0][0]+p+(U/4294967296>>>0)>>>0,e[0][1]=U>>>0,U=e[1][1]+N,e[1][0]=e[1][0]+b+(U/4294967296>>>0)>>>0,e[1][1]=U>>>0,U=e[2][1]+S,e[2][0]=e[2][0]+T+(U/4294967296>>>0)>>>0,e[2][1]=U>>>0,U=e[3][1]+x,e[3][0]=e[3][0]+I+(U/4294967296>>>0)>>>0,e[3][1]=U>>>0,U=e[4][1]+C,e[4][0]=e[4][0]+w+(U/4294967296>>>0)>>>0,e[4][1]=U>>>0,U=e[5][1]+D,e[5][0]=e[5][0]+k+(U/4294967296>>>0)>>>0,e[5][1]=U>>>0,U=e[6][1]+R,e[6][0]=e[6][0]+L+(U/4294967296>>>0)>>>0,e[6][1]=U>>>0,U=e[7][1]+z,e[7][0]=e[7][0]+M+(U/4294967296>>>0)>>>0,e[7][1]=U>>>0,te-=128}}});var yo=ie(Hn=>{var V0=ue();gt();var qe=V0.asn1;Hn.privateKeyValidator={name:"PrivateKeyInfo",tagClass:qe.Class.UNIVERSAL,type:qe.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:qe.Class.UNIVERSAL,type:qe.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:qe.Class.UNIVERSAL,type:qe.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:qe.Class.UNIVERSAL,type:qe.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:qe.Class.UNIVERSAL,type:qe.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};Hn.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:qe.Class.UNIVERSAL,type:qe.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:qe.Class.UNIVERSAL,type:qe.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:qe.Class.UNIVERSAL,type:qe.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:qe.Class.UNIVERSAL,type:qe.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Bo=ie((dy,Ao)=>{var $e=ue();Mr();lt();Mn();Ce();var wo=yo(),K0=wo.publicKeyValidator,F0=wo.privateKeyValidator;typeof go>"u"&&(go=$e.jsbn.BigInteger);var go,Gn=$e.util.ByteBuffer,it=typeof Buffer>"u"?Uint8Array:Buffer;$e.pki=$e.pki||{};Ao.exports=$e.pki.ed25519=$e.ed25519=$e.ed25519||{};var pe=$e.ed25519;pe.constants={};pe.constants.PUBLIC_KEY_BYTE_LENGTH=32;pe.constants.PRIVATE_KEY_BYTE_LENGTH=64;pe.constants.SEED_BYTE_LENGTH=32;pe.constants.SIGN_BYTE_LENGTH=64;pe.constants.HASH_BYTE_LENGTH=64;pe.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=$e.random.getBytesSync(pe.constants.SEED_BYTE_LENGTH);else if(typeof t=="string"){if(t.length!==pe.constants.SEED_BYTE_LENGTH)throw new TypeError('"seed" must be '+pe.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');t=Pt({message:t,encoding:"binary"});for(var a=new it(pe.constants.PUBLIC_KEY_BYTE_LENGTH),r=new it(pe.constants.PRIVATE_KEY_BYTE_LENGTH),n=0;n<32;++n)r[n]=t[n];return G0(a,r),{publicKey:a,privateKey:r}};pe.privateKeyFromAsn1=function(e){var t={},a=[],r=$e.asn1.validate(e,F0,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=$e.asn1.derToOid(t.privateKeyOid),s=$e.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.privateKey,c=Pt({message:$e.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:c}};pe.publicKeyFromAsn1=function(e){var t={},a=[],r=$e.asn1.validate(e,K0,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=$e.asn1.derToOid(t.publicKeyOid),s=$e.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.ed25519PublicKey;if(o.length!==pe.constants.PUBLIC_KEY_BYTE_LENGTH)throw new Error("Key length is invalid.");return Pt({message:o,encoding:"binary"})};pe.publicKeyFromPrivateKey=function(e){e=e||{};var t=Pt({message:e.privateKey,encoding:"binary"});if(t.length!==pe.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+pe.constants.PRIVATE_KEY_BYTE_LENGTH);for(var a=new it(pe.constants.PUBLIC_KEY_BYTE_LENGTH),r=0;r<a.length;++r)a[r]=t[32+r];return a};pe.sign=function(e){e=e||{};var t=Pt(e),a=Pt({message:e.privateKey,encoding:"binary"});if(a.length===pe.constants.SEED_BYTE_LENGTH){var r=pe.generateKeyPair({seed:a});a=r.privateKey}else if(a.length!==pe.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+pe.constants.SEED_BYTE_LENGTH+" or "+pe.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new it(pe.constants.SIGN_BYTE_LENGTH+t.length);j0(n,t,t.length,a);for(var i=new it(pe.constants.SIGN_BYTE_LENGTH),s=0;s<i.length;++s)i[s]=n[s];return i};pe.verify=function(e){e=e||{};var t=Pt(e);if(e.signature===void 0)throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var a=Pt({message:e.signature,encoding:"binary"});if(a.length!==pe.constants.SIGN_BYTE_LENGTH)throw new TypeError('"options.signature" must have a byte length of '+pe.constants.SIGN_BYTE_LENGTH);var r=Pt({message:e.publicKey,encoding:"binary"});if(r.length!==pe.constants.PUBLIC_KEY_BYTE_LENGTH)throw new TypeError('"options.publicKey" must have a byte length of '+pe.constants.PUBLIC_KEY_BYTE_LENGTH);var n=new it(pe.constants.SIGN_BYTE_LENGTH+t.length),i=new it(pe.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<pe.constants.SIGN_BYTE_LENGTH;++s)n[s]=a[s];for(s=0;s<t.length;++s)n[s+pe.constants.SIGN_BYTE_LENGTH]=t[s];return $0(i,n,n.length,r)>=0};function Pt(e){var t=e.message;if(t instanceof Uint8Array||t instanceof it)return t;var a=e.encoding;if(t===void 0)if(e.md)t=e.md.digest().getBytes(),a="binary";else throw new TypeError('"options.message" or "options.md" not specified.');if(typeof t=="string"&&!a)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.from(t,a);t=new Gn(t,a)}else if(!(t instanceof Gn))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var r=new it(t.length()),n=0;n<r.length;++n)r[n]=t.at(n);return r}var jn=ne(),Pa=ne([1]),M0=ne([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),H0=ne([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),vo=ne([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),mo=ne([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),$r=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),q0=ne([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function zr(e,t){var a=$e.md.sha512.create(),r=new Gn(e);a.update(r.getBytes(t),"binary");var n=a.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(n,"binary");for(var i=new it(pe.constants.HASH_BYTE_LENGTH),s=0;s<64;++s)i[s]=n.charCodeAt(s);return i}function G0(e,t){var a=[ne(),ne(),ne(),ne()],r,n=zr(t,32);for(n[0]&=248,n[31]&=127,n[31]|=64,Qn(a,n),Wn(e,a),r=0;r<32;++r)t[r+32]=e[r];return 0}function j0(e,t,a,r){var n,i,s=new Float64Array(64),o=[ne(),ne(),ne(),ne()],c=zr(r,32);c[0]&=248,c[31]&=127,c[31]|=64;var l=a+64;for(n=0;n<a;++n)e[64+n]=t[n];for(n=0;n<32;++n)e[32+n]=c[32+n];var u=zr(e.subarray(32),a+32);for($n(u),Qn(o,u),Wn(e,o),n=32;n<64;++n)e[n]=r[n];var f=zr(e,a+64);for($n(f),n=32;n<64;++n)s[n]=0;for(n=0;n<32;++n)s[n]=u[n];for(n=0;n<32;++n)for(i=0;i<32;i++)s[n+i]+=f[n]*c[i];return xo(e.subarray(32),s),l}function $0(e,t,a,r){var n,i,s=new it(32),o=[ne(),ne(),ne(),ne()],c=[ne(),ne(),ne(),ne()];if(i=-1,a<64||W0(c,r)||!z0(t,32))return-1;for(n=0;n<a;++n)e[n]=t[n];for(n=0;n<32;++n)e[n+32]=r[n];var l=zr(e,a);if($n(l),To(o,c,l),Qn(c,t.subarray(32)),zn(o,c),Wn(s,o),a-=64,So(t,0,s,0)){for(n=0;n<a;++n)e[n]=0;return-1}for(n=0;n<a;++n)e[n]=t[n+64];return i=a,i}function z0(e,t){var a;for(a=31;a>=0;--a){if(e[t+a]<$r[a])return!0;if(e[t+a]>$r[a])return!1}return!1}function xo(e,t){var a,r,n,i;for(r=63;r>=32;--r){for(a=0,n=r-32,i=r-12;n<i;++n)t[n]+=a-16*t[r]*$r[n-(r-32)],a=t[n]+128>>8,t[n]-=a*256;t[n]+=a,t[r]=0}for(a=0,n=0;n<32;++n)t[n]+=a-(t[31]>>4)*$r[n],a=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=a*$r[n];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function $n(e){for(var t=new Float64Array(64),a=0;a<64;++a)t[a]=e[a],e[a]=0;xo(e,t)}function zn(e,t){var a=ne(),r=ne(),n=ne(),i=ne(),s=ne(),o=ne(),c=ne(),l=ne(),u=ne();Tr(a,e[1],e[0]),Tr(u,t[1],t[0]),Ie(a,a,u),br(r,e[0],e[1]),br(u,t[0],t[1]),Ie(r,r,u),Ie(n,e[3],t[3]),Ie(n,n,H0),Ie(i,e[2],t[2]),br(i,i,i),Tr(s,r,a),Tr(o,i,n),br(c,i,n),br(l,r,a),Ie(e[0],s,o),Ie(e[1],l,c),Ie(e[2],c,o),Ie(e[3],s,l)}function Eo(e,t,a){for(var r=0;r<4;++r)Io(e[r],t[r],a)}function Wn(e,t){var a=ne(),r=ne(),n=ne();J0(n,t[2]),Ie(a,t[0],n),Ie(r,t[1],n),Ua(e,r),e[31]^=bo(a)<<7}function Ua(e,t){var a,r,n,i=ne(),s=ne();for(a=0;a<16;++a)s[a]=t[a];for(qn(s),qn(s),qn(s),r=0;r<2;++r){for(i[0]=s[0]-65517,a=1;a<15;++a)i[a]=s[a]-65535-(i[a-1]>>16&1),i[a-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),n=i[15]>>16&1,i[14]&=65535,Io(s,i,1-n)}for(a=0;a<16;a++)e[2*a]=s[a]&255,e[2*a+1]=s[a]>>8}function W0(e,t){var a=ne(),r=ne(),n=ne(),i=ne(),s=ne(),o=ne(),c=ne();return Qt(e[2],Pa),Q0(e[1],t),or(n,e[1]),Ie(i,n,M0),Tr(n,n,e[2]),br(i,e[2],i),or(s,i),or(o,s),Ie(c,o,s),Ie(a,c,n),Ie(a,a,i),Y0(a,a),Ie(a,a,n),Ie(a,a,i),Ie(a,a,i),Ie(e[0],a,i),or(r,e[0]),Ie(r,r,i),Co(r,n)&&Ie(e[0],e[0],q0),or(r,e[0]),Ie(r,r,i),Co(r,n)?-1:(bo(e[0])===t[31]>>7&&Tr(e[0],jn,e[0]),Ie(e[3],e[0],e[1]),0)}function Q0(e,t){var a;for(a=0;a<16;++a)e[a]=t[2*a]+(t[2*a+1]<<8);e[15]&=32767}function Y0(e,t){var a=ne(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=250;r>=0;--r)or(a,a),r!==1&&Ie(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function Co(e,t){var a=new it(32),r=new it(32);return Ua(a,e),Ua(r,t),So(a,0,r,0)}function So(e,t,a,r){return X0(e,t,a,r,32)}function X0(e,t,a,r,n){var i,s=0;for(i=0;i<n;++i)s|=e[t+i]^a[r+i];return(1&s-1>>>8)-1}function bo(e){var t=new it(32);return Ua(t,e),t[0]&1}function To(e,t,a){var r,n;for(Qt(e[0],jn),Qt(e[1],Pa),Qt(e[2],Pa),Qt(e[3],jn),n=255;n>=0;--n)r=a[n/8|0]>>(n&7)&1,Eo(e,t,r),zn(t,e),zn(e,e),Eo(e,t,r)}function Qn(e,t){var a=[ne(),ne(),ne(),ne()];Qt(a[0],vo),Qt(a[1],mo),Qt(a[2],Pa),Ie(a[3],vo,mo),To(e,a,t)}function Qt(e,t){var a;for(a=0;a<16;a++)e[a]=t[a]|0}function J0(e,t){var a=ne(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=253;r>=0;--r)or(a,a),r!==2&&r!==4&&Ie(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function qn(e){var t,a,r=1;for(t=0;t<16;++t)a=e[t]+r+65535,r=Math.floor(a/65536),e[t]=a-r*65536;e[0]+=r-1+37*(r-1)}function Io(e,t,a){for(var r,n=~(a-1),i=0;i<16;++i)r=n&(e[i]^t[i]),e[i]^=r,t[i]^=r}function ne(e){var t,a=new Float64Array(16);if(e)for(t=0;t<e.length;++t)a[t]=e[t];return a}function br(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]+a[r]}function Tr(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]-a[r]}function or(e,t){Ie(e,t,t)}function Ie(e,t,a){var r,n,i=0,s=0,o=0,c=0,l=0,u=0,f=0,h=0,m=0,d=0,p=0,E=0,b=0,N=0,T=0,S=0,I=0,x=0,w=0,C=0,k=0,D=0,L=0,R=0,M=0,z=0,V=0,q=0,U=0,j=0,J=0,G=a[0],Z=a[1],te=a[2],fe=a[3],ce=a[4],Ee=a[5],be=a[6],Te=a[7],ke=a[8],xe=a[9],Ke=a[10],ze=a[11],We=a[12],Qe=a[13],Ye=a[14],Xe=a[15];r=t[0],i+=r*G,s+=r*Z,o+=r*te,c+=r*fe,l+=r*ce,u+=r*Ee,f+=r*be,h+=r*Te,m+=r*ke,d+=r*xe,p+=r*Ke,E+=r*ze,b+=r*We,N+=r*Qe,T+=r*Ye,S+=r*Xe,r=t[1],s+=r*G,o+=r*Z,c+=r*te,l+=r*fe,u+=r*ce,f+=r*Ee,h+=r*be,m+=r*Te,d+=r*ke,p+=r*xe,E+=r*Ke,b+=r*ze,N+=r*We,T+=r*Qe,S+=r*Ye,I+=r*Xe,r=t[2],o+=r*G,c+=r*Z,l+=r*te,u+=r*fe,f+=r*ce,h+=r*Ee,m+=r*be,d+=r*Te,p+=r*ke,E+=r*xe,b+=r*Ke,N+=r*ze,T+=r*We,S+=r*Qe,I+=r*Ye,x+=r*Xe,r=t[3],c+=r*G,l+=r*Z,u+=r*te,f+=r*fe,h+=r*ce,m+=r*Ee,d+=r*be,p+=r*Te,E+=r*ke,b+=r*xe,N+=r*Ke,T+=r*ze,S+=r*We,I+=r*Qe,x+=r*Ye,w+=r*Xe,r=t[4],l+=r*G,u+=r*Z,f+=r*te,h+=r*fe,m+=r*ce,d+=r*Ee,p+=r*be,E+=r*Te,b+=r*ke,N+=r*xe,T+=r*Ke,S+=r*ze,I+=r*We,x+=r*Qe,w+=r*Ye,C+=r*Xe,r=t[5],u+=r*G,f+=r*Z,h+=r*te,m+=r*fe,d+=r*ce,p+=r*Ee,E+=r*be,b+=r*Te,N+=r*ke,T+=r*xe,S+=r*Ke,I+=r*ze,x+=r*We,w+=r*Qe,C+=r*Ye,k+=r*Xe,r=t[6],f+=r*G,h+=r*Z,m+=r*te,d+=r*fe,p+=r*ce,E+=r*Ee,b+=r*be,N+=r*Te,T+=r*ke,S+=r*xe,I+=r*Ke,x+=r*ze,w+=r*We,C+=r*Qe,k+=r*Ye,D+=r*Xe,r=t[7],h+=r*G,m+=r*Z,d+=r*te,p+=r*fe,E+=r*ce,b+=r*Ee,N+=r*be,T+=r*Te,S+=r*ke,I+=r*xe,x+=r*Ke,w+=r*ze,C+=r*We,k+=r*Qe,D+=r*Ye,L+=r*Xe,r=t[8],m+=r*G,d+=r*Z,p+=r*te,E+=r*fe,b+=r*ce,N+=r*Ee,T+=r*be,S+=r*Te,I+=r*ke,x+=r*xe,w+=r*Ke,C+=r*ze,k+=r*We,D+=r*Qe,L+=r*Ye,R+=r*Xe,r=t[9],d+=r*G,p+=r*Z,E+=r*te,b+=r*fe,N+=r*ce,T+=r*Ee,S+=r*be,I+=r*Te,x+=r*ke,w+=r*xe,C+=r*Ke,k+=r*ze,D+=r*We,L+=r*Qe,R+=r*Ye,M+=r*Xe,r=t[10],p+=r*G,E+=r*Z,b+=r*te,N+=r*fe,T+=r*ce,S+=r*Ee,I+=r*be,x+=r*Te,w+=r*ke,C+=r*xe,k+=r*Ke,D+=r*ze,L+=r*We,R+=r*Qe,M+=r*Ye,z+=r*Xe,r=t[11],E+=r*G,b+=r*Z,N+=r*te,T+=r*fe,S+=r*ce,I+=r*Ee,x+=r*be,w+=r*Te,C+=r*ke,k+=r*xe,D+=r*Ke,L+=r*ze,R+=r*We,M+=r*Qe,z+=r*Ye,V+=r*Xe,r=t[12],b+=r*G,N+=r*Z,T+=r*te,S+=r*fe,I+=r*ce,x+=r*Ee,w+=r*be,C+=r*Te,k+=r*ke,D+=r*xe,L+=r*Ke,R+=r*ze,M+=r*We,z+=r*Qe,V+=r*Ye,q+=r*Xe,r=t[13],N+=r*G,T+=r*Z,S+=r*te,I+=r*fe,x+=r*ce,w+=r*Ee,C+=r*be,k+=r*Te,D+=r*ke,L+=r*xe,R+=r*Ke,M+=r*ze,z+=r*We,V+=r*Qe,q+=r*Ye,U+=r*Xe,r=t[14],T+=r*G,S+=r*Z,I+=r*te,x+=r*fe,w+=r*ce,C+=r*Ee,k+=r*be,D+=r*Te,L+=r*ke,R+=r*xe,M+=r*Ke,z+=r*ze,V+=r*We,q+=r*Qe,U+=r*Ye,j+=r*Xe,r=t[15],S+=r*G,I+=r*Z,x+=r*te,w+=r*fe,C+=r*ce,k+=r*Ee,D+=r*be,L+=r*Te,R+=r*ke,M+=r*xe,z+=r*Ke,V+=r*ze,q+=r*We,U+=r*Qe,j+=r*Ye,J+=r*Xe,i+=38*I,s+=38*x,o+=38*w,c+=38*C,l+=38*k,u+=38*D,f+=38*L,h+=38*R,m+=38*M,d+=38*z,p+=38*V,E+=38*q,b+=38*U,N+=38*j,T+=38*J,n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=d+n+65535,n=Math.floor(r/65536),d=r-n*65536,r=p+n+65535,n=Math.floor(r/65536),p=r-n*65536,r=E+n+65535,n=Math.floor(r/65536),E=r-n*65536,r=b+n+65535,n=Math.floor(r/65536),b=r-n*65536,r=N+n+65535,n=Math.floor(r/65536),N=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=S+n+65535,n=Math.floor(r/65536),S=r-n*65536,i+=n-1+37*(n-1),n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=d+n+65535,n=Math.floor(r/65536),d=r-n*65536,r=p+n+65535,n=Math.floor(r/65536),p=r-n*65536,r=E+n+65535,n=Math.floor(r/65536),E=r-n*65536,r=b+n+65535,n=Math.floor(r/65536),b=r-n*65536,r=N+n+65535,n=Math.floor(r/65536),N=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=S+n+65535,n=Math.floor(r/65536),S=r-n*65536,i+=n-1+37*(n-1),e[0]=i,e[1]=s,e[2]=o,e[3]=c,e[4]=l,e[5]=u,e[6]=f,e[7]=h,e[8]=m,e[9]=d,e[10]=p,e[11]=E,e[12]=b,e[13]=N,e[14]=T,e[15]=S}});var Ro=ie((hy,ko)=>{var ct=ue();Ce();lt();Mr();ko.exports=ct.kem=ct.kem||{};var _o=ct.jsbn.BigInteger;ct.kem.rsa={};ct.kem.rsa.create=function(e,t){t=t||{};var a=t.prng||ct.random,r={};return r.encrypt=function(n,i){var s=Math.ceil(n.n.bitLength()/8),o;do o=new _o(ct.util.bytesToHex(a.getBytesSync(s)),16).mod(n.n);while(o.compareTo(_o.ONE)<=0);o=ct.util.hexToBytes(o.toString(16));var c=s-o.length;c>0&&(o=ct.util.fillString("\0",c)+o);var l=n.encrypt(o,"NONE"),u=e.generate(o,i);return{encapsulation:l,key:u}},r.decrypt=function(n,i,s){var o=n.decrypt(i,"NONE");return e.generate(o,s)},r};ct.kem.kdf1=function(e,t){No(this,e,0,t||e.digestLength)};ct.kem.kdf2=function(e,t){No(this,e,1,t||e.digestLength)};function No(e,t,a,r){e.generate=function(n,i){for(var s=new ct.util.ByteBuffer,o=Math.ceil(i/r)+a,c=new ct.util.ByteBuffer,l=a;l<o;++l){c.putInt32(l),t.start(),t.update(n+c.getBytes());var u=t.digest();s.putBytes(u.getBytes(r))}return s.truncate(s.length()-i),s.getBytes()}}});var Uo=ie((py,Po)=>{var ye=ue();Ce();Po.exports=ye.log=ye.log||{};ye.log.levels=["none","error","warning","info","debug","verbose","max"];var Oa={},Jn=[],Qr=null;ye.log.LEVEL_LOCKED=2;ye.log.NO_LEVEL_CHECK=4;ye.log.INTERPOLATE=8;for(It=0;It<ye.log.levels.length;++It)Yn=ye.log.levels[It],Oa[Yn]={index:It,name:Yn.toUpperCase()};var Yn,It;ye.log.logMessage=function(e){for(var t=Oa[e.level].index,a=0;a<Jn.length;++a){var r=Jn[a];if(r.flags&ye.log.NO_LEVEL_CHECK)r.f(e);else{var n=Oa[r.level].index;t<=n&&r.f(r,e)}}};ye.log.prepareStandard=function(e){"standard"in e||(e.standard=Oa[e.level].name+" ["+e.category+"] "+e.message)};ye.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=ye.util.format.apply(this,t)}};ye.log.prepareStandardFull=function(e){"standardFull"in e||(ye.log.prepareStandard(e),e.standardFull=e.standard)};for(Xn=["error","warning","info","debug","verbose"],It=0;It<Xn.length;++It)(function(t){ye.log[t]=function(a,r){var n=Array.prototype.slice.call(arguments).slice(2),i={timestamp:new Date,level:t,category:a,message:r,arguments:n};ye.log.logMessage(i)}})(Xn[It]);var Xn,It;ye.log.makeLogger=function(e){var t={flags:0,f:e};return ye.log.setLevel(t,"none"),t};ye.log.setLevel=function(e,t){var a=!1;if(e&&!(e.flags&ye.log.LEVEL_LOCKED))for(var r=0;r<ye.log.levels.length;++r){var n=ye.log.levels[r];if(t==n){e.level=t,a=!0;break}}return a};ye.log.lock=function(e,t){typeof t>"u"||t?e.flags|=ye.log.LEVEL_LOCKED:e.flags&=~ye.log.LEVEL_LOCKED};ye.log.addLogger=function(e){Jn.push(e)};typeof console<"u"&&"log"in console?(console.error&&console.warn&&console.info&&console.debug?(Lo={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Yr=function(e,t){ye.log.prepareStandard(t);var a=Lo[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),a.apply(console,r)},Ir=ye.log.makeLogger(Yr)):(Yr=function(t,a){ye.log.prepareStandardFull(a),console.log(a.standardFull)},Ir=ye.log.makeLogger(Yr)),ye.log.setLevel(Ir,"debug"),ye.log.addLogger(Ir),Qr=Ir):console={log:function(){}};var Ir,Lo,Yr;Qr!==null&&typeof window<"u"&&window.location&&(Wr=new URL(window.location.href).searchParams,Wr.has("console.level")&&ye.log.setLevel(Qr,Wr.get("console.level").slice(-1)[0]),Wr.has("console.lock")&&(Do=Wr.get("console.lock").slice(-1)[0],Do=="true"&&ye.log.lock(Qr)));var Wr,Do;ye.log.consoleLogger=Qr});var Vo=ie((yy,Oo)=>{Oo.exports=mt();ga();Er();dn();Mn()});var Mo=ie((gy,Fo)=>{var W=ue();Mt();gt();Kr();Ht();er();In();lt();Ce();Na();var B=W.asn1,rt=Fo.exports=W.pkcs7=W.pkcs7||{};rt.messageFromPem=function(e){var t=W.pem.decode(e)[0];if(t.type!=="PKCS7"){var a=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var r=B.fromDer(t.body);return rt.messageFromAsn1(r)};rt.messageToPem=function(e,t){var a={type:"PKCS7",body:B.toDer(e.toAsn1()).getBytes()};return W.pem.encode(a,{maxline:t})};rt.messageFromAsn1=function(e){var t={},a=[];if(!B.validate(e,rt.asn1.contentInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw r.errors=a,r}var n=B.derToOid(t.contentType),i;switch(n){case W.pki.oids.envelopedData:i=rt.createEnvelopedData();break;case W.pki.oids.encryptedData:i=rt.createEncryptedData();break;case W.pki.oids.signedData:i=rt.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+n+" is not (yet) supported.")}return i.fromAsn1(t.content.value[0]),i};rt.createSignedData=function(){var e=null;return e={type:W.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(ei(e,r,rt.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates)for(var n=e.rawCapture.certificates.value,i=0;i<n.length;++i)e.certificates.push(W.pki.certificateFromAsn1(n[i]))},toAsn1:function(){e.contentInfo||e.sign();for(var r=[],n=0;n<e.certificates.length;++n)r.push(W.pki.certificateToAsn1(e.certificates[n]));var i=[],s=B.create(B.Class.CONTEXT_SPECIFIC,0,!0,[B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,B.integerToDer(e.version).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);return r.length>0&&s.value[0].value.push(B.create(B.Class.CONTEXT_SPECIFIC,0,!0,r)),i.length>0&&s.value[0].value.push(B.create(B.Class.CONTEXT_SPECIFIC,1,!0,i)),s.value[0].value.push(B.create(B.Class.UNIVERSAL,B.Type.SET,!0,e.signerInfos)),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var n=r.issuer,i=r.serialNumber;if(r.certificate){var s=r.certificate;typeof s=="string"&&(s=W.pki.certificateFromPem(s)),n=s.issuer.attributes,i=s.serialNumber}var o=r.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof o=="string"&&(o=W.pki.privateKeyFromPem(o));var c=r.digestAlgorithm||W.pki.oids.sha1;switch(c){case W.pki.oids.sha1:case W.pki.oids.sha256:case W.pki.oids.sha384:case W.pki.oids.sha512:case W.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var l=r.authenticatedAttributes||[];if(l.length>0){for(var u=!1,f=!1,h=0;h<l.length;++h){var m=l[h];if(!u&&m.type===W.pki.oids.contentType){if(u=!0,f)break;continue}if(!f&&m.type===W.pki.oids.messageDigest){if(f=!0,u)break;continue}}if(!u||!f)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:n,serialNumber:i,digestAlgorithm:c,signatureAlgorithm:W.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:l,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},(typeof e.content!="object"||e.contentInfo===null)&&(e.contentInfo=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(W.pki.oids.data).getBytes())]),"content"in e)){var n;e.content instanceof W.util.ByteBuffer?n=e.content.bytes():typeof e.content=="string"&&(n=W.util.encodeUtf8(e.content)),r.detached?e.detachedContent=B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,n):e.contentInfo.value.push(B.create(B.Class.CONTEXT_SPECIFIC,0,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,n)]))}if(e.signers.length!==0){var i=t();a(i)}},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){typeof r=="string"&&(r=W.pki.certificateFromPem(r)),e.certificates.push(r)},addCertificateRevokationList:function(r){throw new Error("PKCS#7 CRL support not yet implemented.")}},e;function t(){for(var r={},n=0;n<e.signers.length;++n){var i=e.signers[n],s=i.digestAlgorithm;s in r||(r[s]=W.md[W.pki.oids[s]].create()),i.authenticatedAttributes.length===0?i.md=r[s]:i.md=W.md[W.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(s).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return r}function a(r){var n;if(e.detachedContent?n=e.detachedContent:(n=e.contentInfo.value[1],n=n.value[0]),!n)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var i=B.derToOid(e.contentInfo.value[0].value),s=B.toDer(n);s.getByte(),B.getBerValueLength(s),s=s.getBytes();for(var o in r)r[o].start().update(s);for(var c=new Date,l=0;l<e.signers.length;++l){var u=e.signers[l];if(u.authenticatedAttributes.length===0){if(i!==W.pki.oids.data)throw new Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{u.authenticatedAttributesAsn1=B.create(B.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var f=B.create(B.Class.UNIVERSAL,B.Type.SET,!0,[]),h=0;h<u.authenticatedAttributes.length;++h){var m=u.authenticatedAttributes[h];m.type===W.pki.oids.messageDigest?m.value=r[u.digestAlgorithm].digest():m.type===W.pki.oids.signingTime&&(m.value||(m.value=c)),f.value.push(Zn(m)),u.authenticatedAttributesAsn1.value.push(Zn(m))}s=B.toDer(f).getBytes(),u.md.start().update(s)}u.signature=u.key.sign(u.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=nd(e.signers)}};rt.createEncryptedData=function(){var e=null;return e={type:W.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:W.pki.oids["aes256-CBC"]},fromAsn1:function(t){ei(e,t,rt.asn1.encryptedDataValidator)},decrypt:function(t){t!==void 0&&(e.encryptedContent.key=t),Ko(e)}},e};rt.createEnvelopedData=function(){var e=null;return e={type:W.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:W.pki.oids["aes256-CBC"]},fromAsn1:function(t){var a=ei(e,t,rt.asn1.envelopedDataValidator);e.recipients=td(a.recipientInfos.value)},toAsn1:function(){return B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.type).getBytes()),B.create(B.Class.CONTEXT_SPECIFIC,0,!0,[B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,B.integerToDer(e.version).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SET,!0,rd(e.recipients)),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,id(e.encryptedContent))])])])},findRecipient:function(t){for(var a=t.issuer.attributes,r=0;r<e.recipients.length;++r){var n=e.recipients[r],i=n.issuer;if(n.serialNumber===t.serialNumber&&i.length===a.length){for(var s=!0,o=0;o<a.length;++o)if(i[o].type!==a[o].type||i[o].value!==a[o].value){s=!1;break}if(s)return n}}return null},decrypt:function(t,a){if(e.encryptedContent.key===void 0&&t!==void 0&&a!==void 0)switch(t.encryptedContent.algorithm){case W.pki.oids.rsaEncryption:case W.pki.oids.desCBC:var r=a.decrypt(t.encryptedContent.content);e.encryptedContent.key=W.util.createBuffer(r);break;default:throw new Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Ko(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:W.pki.oids.rsaEncryption,key:t.publicKey}})},encrypt:function(t,a){if(e.encryptedContent.content===void 0){a=a||e.encryptedContent.algorithm,t=t||e.encryptedContent.key;var r,n,i;switch(a){case W.pki.oids["aes128-CBC"]:r=16,n=16,i=W.aes.createEncryptionCipher;break;case W.pki.oids["aes192-CBC"]:r=24,n=16,i=W.aes.createEncryptionCipher;break;case W.pki.oids["aes256-CBC"]:r=32,n=16,i=W.aes.createEncryptionCipher;break;case W.pki.oids["des-EDE3-CBC"]:r=24,n=8,i=W.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+a)}if(t===void 0)t=W.util.createBuffer(W.random.getBytes(r));else if(t.length()!=r)throw new Error("Symmetric key has wrong length; got "+t.length()+" bytes, expected "+r+".");e.encryptedContent.algorithm=a,e.encryptedContent.key=t,e.encryptedContent.parameter=W.util.createBuffer(W.random.getBytes(n));var s=i(t);if(s.start(e.encryptedContent.parameter.copy()),s.update(e.content),!s.finish())throw new Error("Symmetric encryption failed.");e.encryptedContent.content=s.output}for(var o=0;o<e.recipients.length;++o){var c=e.recipients[o];if(c.encryptedContent.content===void 0)switch(c.encryptedContent.algorithm){case W.pki.oids.rsaEncryption:c.encryptedContent.content=c.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+c.encryptedContent.algorithm)}}}},e};function Z0(e){var t={},a=[];if(!B.validate(e,rt.asn1.recipientInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw r.errors=a,r}return{version:t.version.charCodeAt(0),issuer:W.pki.RDNAttributesAsArray(t.issuer),serialNumber:W.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:B.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function ed(e){return B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,B.integerToDer(e.version).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[W.pki.distinguishedNameToAsn1({attributes:e.issuer}),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,W.util.hexToBytes(e.serialNumber))]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.encryptedContent.algorithm).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function td(e){for(var t=[],a=0;a<e.length;++a)t.push(Z0(e[a]));return t}function rd(e){for(var t=[],a=0;a<e.length;++a)t.push(ed(e[a]));return t}function ad(e){var t=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,B.integerToDer(e.version).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[W.pki.distinguishedNameToAsn1({attributes:e.issuer}),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,W.util.hexToBytes(e.serialNumber))]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.digestAlgorithm).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1&&t.value.push(e.authenticatedAttributesAsn1),t.value.push(B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.signatureAlgorithm).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")])),t.value.push(B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){for(var a=B.create(B.Class.CONTEXT_SPECIFIC,1,!0,[]),r=0;r<e.unauthenticatedAttributes.length;++r){var n=e.unauthenticatedAttributes[r];a.values.push(Zn(n))}t.value.push(a)}return t}function nd(e){for(var t=[],a=0;a<e.length;++a)t.push(ad(e[a]));return t}function Zn(e){var t;if(e.type===W.pki.oids.contentType)t=B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.value).getBytes());else if(e.type===W.pki.oids.messageDigest)t=B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===W.pki.oids.signingTime){var a=new Date("1950-01-01T00:00:00Z"),r=new Date("2050-01-01T00:00:00Z"),n=e.value;if(typeof n=="string"){var i=Date.parse(n);isNaN(i)?n.length===13?n=B.utcTimeToDate(n):n=B.generalizedTimeToDate(n):n=new Date(i)}n>=a&&n<r?t=B.create(B.Class.UNIVERSAL,B.Type.UTCTIME,!1,B.dateToUtcTime(n)):t=B.create(B.Class.UNIVERSAL,B.Type.GENERALIZEDTIME,!1,B.dateToGeneralizedTime(n))}return B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.type).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SET,!0,[t])])}function id(e){return[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(W.pki.oids.data).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(e.algorithm).getBytes()),e.parameter?B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e.parameter.getBytes()):void 0]),B.create(B.Class.CONTEXT_SPECIFIC,0,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e.content.getBytes())])]}function ei(e,t,a){var r={},n=[];if(!B.validate(t,a,r,n)){var i=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw i.errors=i,i}var s=B.derToOid(r.contentType);if(s!==W.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(W.util.isArray(r.encryptedContent))for(var c=0;c<r.encryptedContent.length;++c){if(r.encryptedContent[c].type!==B.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[c].value}else o=r.encryptedContent;e.encryptedContent={algorithm:B.derToOid(r.encAlgorithm),parameter:W.util.createBuffer(r.encParameter.value),content:W.util.createBuffer(o)}}if(r.content){var o="";if(W.util.isArray(r.content))for(var c=0;c<r.content.length;++c){if(r.content[c].type!==B.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[c].value}else o=r.content;e.content=W.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function Ko(e){if(e.encryptedContent.key===void 0)throw new Error("Symmetric key not available.");if(e.content===void 0){var t;switch(e.encryptedContent.algorithm){case W.pki.oids["aes128-CBC"]:case W.pki.oids["aes192-CBC"]:case W.pki.oids["aes256-CBC"]:t=W.aes.createDecryptionCipher(e.encryptedContent.key);break;case W.pki.oids.desCBC:case W.pki.oids["des-EDE3-CBC"]:t=W.des.createDecryptionCipher(e.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+e.encryptedContent.algorithm)}if(t.start(e.encryptedContent.parameter),t.update(e.encryptedContent.content),!t.finish())throw new Error("Symmetric decryption failed.");e.content=t.output}}});var qo=ie((vy,Ho)=>{var Oe=ue();Mt();yr();ga();Er();Ce();var Ka=Ho.exports=Oe.ssh=Oe.ssh||{};Ka.privateKeyToPutty=function(e,t,a){a=a||"",t=t||"";var r="ssh-rsa",n=t===""?"none":"aes256-cbc",i="PuTTY-User-Key-File-2: "+r+`\r
16
+ `;i+="Encryption: "+n+`\r
17
+ `,i+="Comment: "+a+`\r
18
+ `;var s=Oe.util.createBuffer();Ar(s,r),At(s,e.e),At(s,e.n);var o=Oe.util.encode64(s.bytes(),64),c=Math.floor(o.length/66)+1;i+="Public-Lines: "+c+`\r
19
+ `,i+=o;var l=Oe.util.createBuffer();At(l,e.d),At(l,e.p),At(l,e.q),At(l,e.qInv);var u;if(!t)u=Oe.util.encode64(l.bytes(),64);else{var f=l.length()+16-1;f-=f%16;var h=Va(l.bytes());h.truncate(h.length()-f+l.length()),l.putBuffer(h);var m=Oe.util.createBuffer();m.putBuffer(Va("\0\0\0\0",t)),m.putBuffer(Va("\0\0\0",t));var d=Oe.aes.createEncryptionCipher(m.truncate(8),"CBC");d.start(Oe.util.createBuffer().fillWithByte(0,16)),d.update(l.copy()),d.finish();var p=d.output;p.truncate(16),u=Oe.util.encode64(p.bytes(),64)}c=Math.floor(u.length/66)+1,i+=`\r
20
+ Private-Lines: `+c+`\r
21
+ `,i+=u;var E=Va("putty-private-key-file-mac-key",t),b=Oe.util.createBuffer();Ar(b,r),Ar(b,n),Ar(b,a),b.putInt32(s.length()),b.putBuffer(s),b.putInt32(l.length()),b.putBuffer(l);var N=Oe.hmac.create();return N.start("sha1",E),N.update(b.bytes()),i+=`\r
22
+ Private-MAC: `+N.digest().toHex()+`\r
23
+ `,i};Ka.publicKeyToOpenSSH=function(e,t){var a="ssh-rsa";t=t||"";var r=Oe.util.createBuffer();return Ar(r,a),At(r,e.e),At(r,e.n),a+" "+Oe.util.encode64(r.bytes())+" "+t};Ka.privateKeyToOpenSSH=function(e,t){return t?Oe.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"}):Oe.pki.privateKeyToPem(e)};Ka.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||Oe.md.md5.create(),r="ssh-rsa",n=Oe.util.createBuffer();Ar(n,r),At(n,e.e),At(n,e.n),a.start(),a.update(n.getBytes());var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};function At(e,t){var a=t.toString(16);a[0]>="8"&&(a="00"+a);var r=Oe.util.hexToBytes(a);e.putInt32(r.length),e.putBytes(r)}function Ar(e,t){e.putInt32(t.length),e.putString(t)}function Va(){for(var e=Oe.md.sha1.create(),t=arguments.length,a=0;a<t;++a)e.update(arguments[a]);return e.digest()}});var jo=ie((my,Go)=>{Go.exports=ue();Mt();lo();gt();la();Kr();Bo();yr();Ro();Uo();Vo();An();Ca();er();wn();Nn();Mo();Rn();Sn();hn();Aa();lt();gn();qo();Vn();Ce()});var Wo=ie(zo=>{var Se=jo();function $o(e){var t=parseInt(e[0],16);return t<8?e:(t-=8,t.toString()+e.substring(1))}function sd(e){switch(e){case"sha256":return Se.md.sha256.create();default:return Se.md.sha1.create()}}zo.generate=function(t,a,r){typeof t=="function"?(r=t,t=void 0):typeof a=="function"&&(r=a,a={}),a=a||{};var n=function(o){var c=Se.pki.createCertificate();c.serialNumber=$o(Se.util.bytesToHex(Se.random.getBytesSync(9))),c.validity.notBefore=a.notBeforeDate||new Date;var l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+(a.days||365)),t=t||[{name:"commonName",value:"example.org"},{name:"countryName",value:"US"},{shortName:"ST",value:"Virginia"},{name:"localityName",value:"Blacksburg"},{name:"organizationName",value:"Test"},{shortName:"OU",value:"Test"}],c.setSubject(t),c.setIssuer(t),c.publicKey=o.publicKey,c.setExtensions(a.extensions||[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"subjectAltName",altNames:[{type:6,value:"http://example.org/webid#me"}]}]),c.sign(o.privateKey,sd(a&&a.algorithm));let u=Se.md.sha1.create().update(Se.asn1.toDer(Se.pki.certificateToAsn1(c)).getBytes()).digest().toHex().match(/.{2}/g).join(":");var f={private:Se.pki.privateKeyToPem(o.privateKey),public:Se.pki.publicKeyToPem(o.publicKey),cert:Se.pki.certificateToPem(c),fingerprint:u};if(a&&a.pkcs7){var h=Se.pkcs7.createSignedData();h.addCertificate(c),f.pkcs7=Se.pkcs7.messageToPem(h)}if(a&&a.clientCertificate){var m=Se.pki.rsa.generateKeyPair(a.clientCertificateKeySize||1024),d=Se.pki.createCertificate();d.serialNumber=$o(Se.util.bytesToHex(Se.random.getBytesSync(9))),d.validity.notBefore=new Date,d.validity.notAfter=new Date,d.validity.notAfter.setFullYear(d.validity.notBefore.getFullYear()+1);for(var p=JSON.parse(JSON.stringify(t)),E=0;E<p.length;E++)p[E].name==="commonName"&&(a.clientCertificateCN?p[E]={name:"commonName",value:a.clientCertificateCN}:p[E]={name:"commonName",value:"John Doe jdoe123"});if(d.setSubject(p),d.setIssuer(t),d.publicKey=m.publicKey,d.sign(o.privateKey),f.clientprivate=Se.pki.privateKeyToPem(m.privateKey),f.clientpublic=Se.pki.publicKeyToPem(m.publicKey),f.clientcert=Se.pki.certificateToPem(d),a.pkcs7){var b=Se.pkcs7.createSignedData();b.addCertificate(d),f.clientpkcs7=Se.pkcs7.messageToPem(b)}}var N=Se.pki.createCaStore();N.addCertificate(c);try{Se.pki.verifyCertificateChain(N,[c],function(T,S,I){if(T!==!0)throw new Error("Certificate could not be verified.");return!0})}catch(T){throw new Error(T)}return f},i=a.keySize||1024;if(r)return Se.pki.rsa.generateKeyPair({bits:i},function(o,c){if(o)return r(o);try{return r(null,n(c))}catch(l){return r(l)}});var s=a.keyPair?{privateKey:Se.pki.privateKeyFromPem(a.keyPair.privateKey),publicKey:Se.pki.publicKeyFromPem(a.keyPair.publicKey)}:Se.pki.rsa.generateKeyPair(i);return n(s)}});import{join as Ti}from"node:path";import{hostname as Tp}from"node:os";import{createHash as dl,randomBytes as hl,randomUUID as Ya,timingSafeEqual as pl}from"node:crypto";import{mkdir as yl,readFile as gl,writeFile as vl,rename as ml,rm as El}from"node:fs/promises";import{join as Cl}from"node:path";var Xa=()=>hl(32).toString("base64url"),Dr=e=>dl("sha256").update(e).digest("hex");function Ai(e,t){if(typeof e!="string"||typeof t!="string")return!1;let a=Buffer.from(Dr(e)),r=Buffer.from(t);return a.length===r.length&&pl(a,r)}var at=(e,t,a=200)=>{if(typeof e!="string"||!e.trim()||e.length>a)throw new Error(`\u65E0\u6548\u7684 ${t}`);return e.trim()};async function Bi(e){await yl(e,{recursive:!0,mode:448});let t=Cl(e,"devices.json"),a={};try{a=JSON.parse(await gl(t,"utf8"))}catch(l){if(l.code!=="ENOENT")throw l}let r={enabled:!1,host:"0.0.0.0",port:48721,publicUrl:"",...a};r.devices??=[];let n=new Map,i=new Map,s=Promise.resolve();function o(){let l=JSON.stringify(r,null,2),u=s.then(async()=>{let f=`${t}.${Ya()}.tmp`;try{await vl(f,l,{mode:384}),await ml(f,t)}finally{await El(f,{force:!0})}});return s=u.catch(()=>{}),u}function c(){for(let[l,u]of n)u.expiresAt<=Date.now()&&n.delete(l);for(let[l,u]of i)u.expiresAt<=Date.now()&&i.delete(l)}return{state:r,persist:o,flush:()=>s,pending(){return c(),[...i.values()].filter(l=>l.status==="pending").map(({id:l,name:u,createdAt:f,expiresAt:h})=>({id:l,name:u,createdAt:f,expiresAt:h}))},begin(){if(c(),n.size+i.size>=32)throw new Error("\u914D\u5BF9\u8BF7\u6C42\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let l=Xa(),u=Date.now()+3e5;return n.set(Dr(l),{expiresAt:u}),{code:l,expiresAt:u}},request(l,u,f="unknown"){c();let h=Dr(at(l,"\u914D\u5BF9\u7801",128)),m=n.get(h);if(!m)throw new Error("\u914D\u5BF9\u7801\u5DF2\u4F7F\u7528\u6216\u8FC7\u671F");n.delete(h);let d=Xa(),p=Ya();return i.set(p,{id:p,name:at(u,"\u8BBE\u5907\u540D\u79F0",100),deviceType:["mobile","computer","tablet"].includes(f)?f:"unknown",createdAt:Date.now(),expiresAt:m.expiresAt,pollHash:Dr(d),status:"pending"}),{requestId:p,pollToken:d,expiresAt:m.expiresAt}},poll(l,u){c();let f=i.get(l);if(!f||!Ai(u,f.pollHash))throw new Error("\u914D\u5BF9\u8BF7\u6C42\u5DF2\u8FC7\u671F\u6216\u9A8C\u8BC1\u5931\u8D25");return{status:f.status,...f.status==="approved"?{token:f.token,deviceId:f.deviceId}:{}}},async decide(l,u){c();let f=i.get(l);if(!f||f.status!=="pending")throw new Error("\u914D\u5BF9\u8BF7\u6C42\u5DF2\u5931\u6548");if(!u){f.status="rejected";return}if(r.devices.length>=32)throw new Error("\u6700\u591A\u914D\u5BF9 32 \u53F0\u8BBE\u5907\uFF0C\u8BF7\u5148\u64A4\u9500\u4E0D\u7528\u7684\u8BBE\u5907");f.status="approving";let h=Xa(),m={id:Ya(),name:f.name,deviceType:f.deviceType,tokenHash:Dr(h),pairedAt:Date.now(),lastSeenAt:Date.now()};r.devices.push(m);try{await o()}catch(d){throw r.devices=r.devices.filter(p=>p!==m),f.status="pending",d}f.token=h,f.deviceId=m.id,f.status="approved"},authenticate(l){if(typeof l!="string"||l.length>256)return;let u=r.devices.find(f=>Ai(l,f.tokenHash));return u&&(u.lastSeenAt=Date.now()),u},async revoke(l){r.devices=r.devices.filter(u=>u.id!==l);for(let[u,f]of i)f.deviceId===l&&i.delete(u);await o()},clearPairings(){n.clear(),i.clear()}}}var Xo=fl(Wo(),1);import{X509Certificate as od,createHash as cd,createPrivateKey as ld,createPublicKey as ud,generateKeyPair as fd}from"node:crypto";import{readFile as dd,writeFile as Qo,rename as hd}from"node:fs/promises";import{join as Yo}from"node:path";import{promisify as pd}from"node:util";async function Jo(e){let t=Yo(e,"tls.json"),a;try{a=JSON.parse(await dd(t,"utf8"))}catch(i){if(i.code!=="ENOENT")throw i}if(!a){let i=await pd(fd)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=Xo.default.generate([{name:"commonName",value:"DSH Link"}],{keyPair:i,keySize:2048,days:3650,algorithm:"sha256",extensions:[{name:"basicConstraints",cA:!1},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0},{name:"extKeyUsage",serverAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"},{type:7,ip:"::1"}]}]});a={key:s.private,cert:s.cert},await Qo(`${t}.tmp`,JSON.stringify(a),{mode:384}),await hd(`${t}.tmp`,t)}let r=new od(a.cert);if(!r.checkPrivateKey(ld(a.key)))throw new Error("Link TLS \u5BC6\u94A5\u4E0E\u8BC1\u4E66\u4E0D\u5339\u914D");if(Date.parse(r.validTo)<Date.now())throw new Error("Link TLS \u8BC1\u4E66\u5DF2\u5230\u671F");let n=cd("sha256").update(ud(a.cert).export({type:"spki",format:"der"})).digest("base64");return await Qo(Yo(e,"host-cert.pem"),a.cert,{mode:384}),{...a,pin:n}}import{createSecureServer as yd}from"node:http2";import{readFile as gd}from"node:fs/promises";import{networkInterfaces as Zo}from"node:os";import{isIP as ri}from"node:net";var vd=()=>[...new Set(Object.values(Zo()).flatMap(e=>(e??[]).filter(t=>!t.internal&&!t.address.includes("%")).map(t=>t.address)))],md=/^(?:docker\d+|br-[0-9a-f]+|veth.*|virbr\d+(?:-nic)?|vboxnet\d+|vmnet\d+|cni\d+|flannel.*|podman\d+)$|^vEthernet \((?:Default Switch|WSL.*|Docker.*)\)$/i;function ai(e="::",t=Zo()){if(e!=="0.0.0.0"&&e!=="::")return[e];let a=new Set,r=new Set;for(let[i,s]of Object.entries(t))if(!md.test(i))for(let o of s??[]){if(o.internal||o.address.includes("%"))continue;let c=ri(o.address);if(c===4){let[l,u]=o.address.split(".").map(Number);if(l===0||l===127||l>=224||l===169&&u===254)continue;a.add(o.address)}else if(c===6&&e==="::"){let l=new URL(`https://[${o.address}]`).hostname.slice(1,-1);if(l==="::"||l==="::1"||/^fe[89ab][0-9a-f]:|^ff/i.test(l))continue;r.add(l)}}let n=i=>{let[s,o]=i.split(".").map(Number);return s===10||s===172&&o>=16&&o<=31||s===192&&o===168};return[...[...a].filter(n),...[...a].filter(i=>!n(i)),...r]}var Ma=(e,t)=>`${ri(e)===6?`[${e}]`:e}:${t}`;function ni(e,t){let a={...t};for(let r of["enabled","host","port","publicUrl"])e[r]!==void 0&&(a[r]=e[r]);if(typeof a.enabled!="boolean")throw new Error("\u542F\u7528\u72B6\u6001\u5FC5\u987B\u662F\u5E03\u5C14\u503C");if(!ri(a.host)&&a.host!=="localhost")throw new Error("\u76D1\u542C\u5730\u5740\u5FC5\u987B\u662F IP \u6216 localhost");if(!Number.isInteger(a.port)||a.port<0||a.port>65535)throw new Error("\u7AEF\u53E3\u5FC5\u987B\u5728 0 \u81F3 65535 \u4E4B\u95F4");if(typeof a.publicUrl!="string")throw new Error("\u516C\u7F51\u5730\u5740\u65E0\u6548");if(a.publicUrl=a.publicUrl.trim().replace(/\/$/,""),a.publicUrl){let r=new URL(a.publicUrl);if(r.protocol!=="https:"||r.username||r.password||r.pathname!=="/"||r.search||r.hash)throw new Error("\u8BF7\u8F93\u5165 HTTPS \u516C\u7F51\u5730\u5740\uFF0C\u4F8B\u5982 https://desk.example.com\uFF0C\u4E0D\u5305\u542B\u5B50\u8DEF\u5F84");a.publicUrl=r.origin}return a}var ti={"cache-control":"no-store","x-content-type-options":"nosniff","referrer-policy":"no-referrer","content-security-policy":"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"},Ve=(e,t=400)=>Object.assign(new Error(e),{status:t});async function Fa(e){if(!e.headers["content-type"]?.startsWith("application/json"))throw Ve("\u9700\u8981 application/json",415);let t=0,a=[];for await(let n of e){if(t+=n.length,t>256*1024)throw Ve("\u8BF7\u6C42\u8FC7\u5927",413);a.push(n)}let r=JSON.parse(Buffer.concat(a).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw Ve("\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");return r}async function ec({identity:e,config:t,webRoot:a,store:r,dispatch:n,workbench:i,onError:s,routes:o}){let c=new Map,l=new Set,u=new Set,f=!0,h=(p,E,b,N="application/json; charset=utf-8")=>{p.destroyed||(p.writeHead(E,{...ti,"content-type":N}),p.end(N.startsWith("application/json")?JSON.stringify(b):b))},m=(p,E=!1)=>{if(!f)throw Ve("Link \u5DF2\u5173\u95ED",503);let b=t.publicUrl?new URL(t.publicUrl).host:void 0,N=new Set(["localhost","127.0.0.1","::1",...vd(),t.host].map(C=>Ma(C,d.address().port)));b&&N.add(b);let T=p.headers[":authority"]||p.headers.host;if(p.headers.host&&p.headers[":authority"]&&p.headers.host!==p.headers[":authority"])throw Ve("\u4E3B\u673A\u5730\u5740\u4E0D\u4E00\u81F4",403);if(!T||!N.has(T))throw Ve("\u4E3B\u673A\u5730\u5740\u672A\u6388\u6743",403);if((E||p.headers.origin)&&p.headers.origin!==`https://${T}`)throw Ve("\u6765\u6E90\u672A\u6388\u6743",403);let S=new URL(p.url,`https://${T}`),I=p.socket.remoteAddress??"unknown",x=Math.floor(Date.now()/6e4);if(c.size>1024)for(let[C,k]of c)k.tick!==x&&c.delete(C);if(c.size>1024&&!c.has(I))throw Ve("\u8BF7\u6C42\u8FC7\u591A",429);let w=c.get(I)?.tick===x?c.get(I):{tick:x,count:0,pairs:0};if(c.set(I,w),++w.count>600)throw Ve("\u8BF7\u6C42\u8FC7\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",429);return{url:S,rate:w}},d=yd({key:e.key,cert:e.cert,minVersion:"TLSv1.2",allowHTTP1:!0},async(p,E)=>{try{let{url:b,rate:N}=m(p);if(b.pathname.startsWith("/link/workbench/")){if(!i)throw Ve("\u7F51\u9875\u5DE5\u4F5C\u53F0\u5C1A\u672A\u5C31\u7EEA",503);return await i.handle(p,E,b,ti)}if(p.method==="GET"){if(b.pathname==="/link/api/info")return h(E,200,{name:"DSH Link",version:"0.1.0"});let I={"/link":"index.html","/link/":"index.html","/link/index.html":"index.html","/link/app.js":"app.js","/link/app.css":"app.css"}[b.pathname];if(!I)throw Ve("\u672A\u627E\u5230",404);if(b.pathname==="/link")return E.writeHead(308,{location:"/link/",...ti}),E.end();let x;try{x=await gd(new URL(I,a))}catch(w){throw w.code==="ENOENT"?Ve("\u8BF7\u5148\u6784\u5EFA Link \u7F51\u9875\u8D44\u6E90",503):w}return h(E,200,x,I.endsWith(".js")?"text/javascript; charset=utf-8":I.endsWith(".css")?"text/css; charset=utf-8":"text/html; charset=utf-8")}if(p.method!=="POST")throw Ve("\u4E0D\u652F\u6301\u7684\u65B9\u6CD5",405);if(b.pathname==="/link/api/pair"){if(++N.pairs>12)throw Ve("\u914D\u5BF9\u8BF7\u6C42\u8FC7\u591A",429);let I=await Fa(p),x=p.headers["user-agent"]||"",w=/iPad|Tablet/i.test(x)?"tablet":/Android|iPhone|Mobile/i.test(x)?"mobile":/Windows|Macintosh|X11/i.test(x)?"computer":"unknown";return h(E,200,r.request(I.code,I.name,w))}if(b.pathname==="/link/api/pair/status"){let I=await Fa(p),x=r.poll(I.requestId,I.pollToken);return h(E,200,{...x,...x.status==="approved"&&o?{routes:o()}:{}})}if(!["/link/api/rpc","/link/api/workbench"].includes(b.pathname))throw Ve("\u672A\u627E\u5230",404);let T=r.authenticate(p.headers.authorization?.replace(/^Bearer\s+/i,""));if(!T)throw Ve("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u914D\u5BF9",401);if(b.pathname==="/link/api/workbench"){if(!i)throw Ve("\u7F51\u9875\u5DE5\u4F5C\u53F0\u5C1A\u672A\u5C31\u7EEA",503);return await Fa(p),h(E,200,i.begin(T,E))}let S=await Fa(p);if(!f||!r.state.devices.some(I=>I.id===T.id))throw Ve("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548",401);return h(E,200,await n(S,T))}catch(b){E.headersSent?E.destroy():h(E,b.status??400,{error:b.message})}});return d.on("upgrade",(p,E,b)=>{E.on("error",()=>{});try{let{url:N}=m(p,!0);if(N.pathname!=="/link/workbench/api/voice/realtime")throw Ve("\u672A\u627E\u5230",404);if(!i?.upgrade)throw Ve("\u5B9E\u65F6\u8BED\u97F3\u5C1A\u672A\u5C31\u7EEA",503);i.upgrade(p,E,b)}catch(N){let T=N.status??400;E.end(`HTTP/1.1 ${T} Rejected\r
24
+ Connection: close\r
25
+ Content-Length: 0\r
26
+ \r
27
+ `)}}),d.on("connection",p=>{l.add(p),p.once("close",()=>l.delete(p))}),d.on("session",p=>{u.add(p),p.once("close",()=>u.delete(p))}),d.requestTimeout=6e4,d.headersTimeout=15e3,d.keepAliveTimeout=1e4,await new Promise((p,E)=>{d.once("error",E),d.listen(t.port,t.host,()=>{d.off("error",E),p()})}),d.on("error",s),{port:d.address().port,timeouts:{request:d.requestTimeout,headers:d.headersTimeout,keepAlive:d.keepAliveTimeout},close:async()=>{f=!1,await i?.close();let p=new Promise(E=>d.close(E));for(let E of u)E.destroy();for(let E of l)E.destroy();await p,c.clear()}}}import{createHash as Ed,randomUUID as Cd}from"node:crypto";import{hostname as wd}from"node:os";var xd={async*[Symbol.asyncIterator](){}},Bt=(e,t,a=200)=>{if(typeof e!="string"||!e.trim()||e.length>a)throw new Error(`Invalid ${t}`);return e},Sd=e=>(e?.content??[]).filter(t=>t.type==="text").map(t=>t.text).join(`
28
+ `),bd=e=>(e??[]).map(t=>t.type==="text-chunks"?t.texts.join(""):t.type==="chunk"&&t.chunk.type==="text-delta"?t.chunk.text:"").join("");function tc(e,t={}){let a=new Map,r=new Map,n=()=>e.workspaceRegistry.list(),i=x=>n().find(w=>w.sessionIds.includes(x)),s=x=>{Bt(x,"session id");let w=i(x);if(!w)throw new Error("Session is not registered in an available workspace");return w},o=(x,w,C,k)=>e.typertGateway.invoke({peer:x.peer,namespace:w,method:C,args:k}),c=x=>{a.get(x.id)===x&&a.delete(x.id),clearTimeout(x.timer),x.abort.abort();for(let w of x.waits.values())w.abort();return x.pending.clear(),x.cleanup??=Promise.resolve().then(()=>x.peer.dispose())},l=async x=>{let w=a.get(x);w&&(await c(w),await w.loop?.catch(()=>{}))},u=async(x,w,C)=>{let D=await e.connection.createSharedFetchHandler("/api").fetch(new Request("http://localhost/api/$events/result",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:Cd(),method:"$events/result",payload:{args:{clientId:x.clientId,eventId:w,outcome:C}}})}),x.peer),L=await D.json();if(!D.ok||L.result?.ok===!1||L.ok===!1)throw new Error(L.result?.error?.message||L.error?.message||"Harness rejected interaction")},f=x=>{clearTimeout(x.timer),x.timer=setTimeout(()=>{x.active?f(x):l(x.id).catch(()=>{})},45e3),x.timer.unref?.()},h=async(x,w)=>{let C=new AbortController;x.waits.set(w.eventId,C);try{let k=await e.typertGateway.stream({peer:x.peer,namespace:"userQuestions",method:"attachWait",args:{agentId:w.agentId,callId:w.request.wait.callId},signal:AbortSignal.any([x.abort.signal,C.signal])});for await(let D of k);}catch(k){!C.signal.aborted&&!x.abort.signal.aborted&&x.waitErrors.set(w.eventId,k)}finally{x.waits.delete(w.eventId)}},m=async x=>{let w=Bt(x?.id,"device id"),C=a.get(w);if(C){if(C.error)throw C.error;return f(C),C}C={id:w,peer:e.connection.createPeer({principal:{kind:"owner"},interactions:"answer"}),abort:new AbortController,pending:new Map,waits:new Map,waitErrors:new Map,active:0},a.set(w,C),f(C);let k,D;if(C.ready=new Promise((L,R)=>{k=L,D=R}),C.ready.catch(()=>{}),C.loop=(async()=>{try{let L=await e.typertGateway.wireStream.open("$events",{args:{}},xd,C.peer,C.abort.signal);for await(let R of L)if(R.type==="ready"&&(C.clientId=R.clientId,k()),R.type==="cancel"&&(C.pending.delete(R.eventId),C.waits.get(R.eventId)?.abort(),C.waitErrors.delete(R.eventId)),R.type==="waterfall"){if(!i(R.agentId)||!["approval/request","user-questions/request"].includes(R.event)||C.pending.size>=100){await u(C,R.eventId,{kind:"next"});continue}C.pending.set(R.eventId,R),R.event==="user-questions/request"&&R.request.wait?.timed&&h(C,R)}if(!C.abort.signal.aborted)throw new Error("Harness interaction stream ended")}catch(L){C.error=L;let R=c(C);D(L),await R.catch(()=>{})}finally{await c(C).catch(()=>{}),C.clientId||D(new Error("Harness interaction stream is unavailable"))}})(),await Promise.resolve(),C.error)throw C.error;return C},d=async x=>{try{await x.ready}catch(w){throw x.error??w}},p=async x=>(await o(x,"session","modelCatalog",{})).groups.flatMap(C=>C.models.map(k=>({provider:C.id,model:k.id,label:`${C.name} \xB7 ${k.name}`}))),E=async x=>(await o(x,"session","list",{_request:{}})).items.filter(C=>!C.parentSessionId&&C.origin!=="subagent"&&i(C.sessionId)).map(C=>({id:C.sessionId,projectId:i(C.sessionId).id,title:C.projections?.values?.title?.title||C.projections?.values?.title||"\u65B0\u4F1A\u8BDD",running:C.running,updatedAt:C.updatedAt})),b=async(x,w)=>{let C=new AbortController,k;try{k=(await e.typertGateway.stream({peer:x.peer,namespace:"session",method:"follow",args:{request:{address:{kind:"session",sessionId:w},assistantStream:!0,maxMessages:100}},signal:AbortSignal.any([C.signal,x.abort.signal])}))[Symbol.asyncIterator]();let L=await k.next();if(L.done||L.value.type!=="snapshot")throw new Error("Harness history snapshot is unavailable");return L.value}finally{C.abort(),await k?.return?.()}},N=(x,w)=>[...x.pending.values()].filter(C=>C.agentId===w).map(C=>C.event==="approval/request"?{id:C.eventId,kind:"permission",title:C.request.reason||C.request.toolName||"\u9700\u8981\u6279\u51C6",toolName:C.request.toolName,options:[{id:"allow",label:"\u5141\u8BB8\u4E00\u6B21"},{id:"reject",label:"\u62D2\u7EDD"}]}:{id:C.eventId,kind:"question",title:"\u9700\u8981\u4F60\u7684\u56DE\u7B54",questions:C.request.questions,...x.waitErrors.has(C.eventId)?{error:"Unable to claim timed question; answer in the desktop application"}:{}}),T=async(x,w)=>{let C=Bt(w.interactionId,"interaction id");if(C.startsWith("continued:")){let L=C.slice(10),M=(await b(x,w.id)).projections?.values?.userQuestions?.active?.find(V=>V.callId===L&&V.state==="continued");if(!M)throw new Error("Question is no longer pending");if(Ha(w.answer,M.questions),!await o(x,"userQuestions","answer",{agentId:w.id,callId:L,answer:w.answer}))throw new Error("Question is no longer pending");return{accepted:!0}}let k=x.pending.get(C);if(!k||k.agentId!==w.id)throw new Error("Interaction expired or belongs to another session");if(x.waitErrors.has(C))throw new Error("Timed question could not be claimed; answer in the desktop application");let D=w.answer;if(k.event==="approval/request"){if(typeof D?.allow!="boolean")throw new Error("Expected an explicit allow decision");D=D.allow?"allowed-once":"rejected"}else Ha(D,k.request.questions);return await u(x,C,{kind:"result",value:D}),x.pending.delete(C),x.waits.get(C)?.abort(),{accepted:!0}},S=async(x,w)=>{if(!x||typeof x!="object"||Array.isArray(x))throw new Error("Expected an object");let C=Bt(x.action,"action");if(!["state","models","create","history","send","cancel","respond"].includes(C))throw new Error("Unsupported Link action");let k=await m(w);if(C==="models")return{models:await p(k)};if(C==="state"){let[U,j]=await Promise.all([E(k),p(k)]);return{host:{name:wd()},projects:n().map(J=>({id:J.id,name:J.title||J.id,path:J.path})),sessions:U,models:j}}if(C==="create"){let U=n().find(Ee=>Ee.id===Bt(x.projectId,"project id"));if(!U)throw new Error("Project is unavailable");let j=Bt(x.requestId,"request id");if(x.provider===void 0!=(x.model===void 0))throw new Error("Provider and model must be selected together");x.provider!==void 0&&(Bt(x.provider,"provider"),Bt(x.model,"model"));let J=`${k.id}:${j}`,G=JSON.stringify([U.id,x.provider??null,x.model??null]),Z=r.get(J);if(Z){if(Z.fingerprint!==G)throw new Error("Request id was used for another session configuration");return Z.promise}if(r.size>2e3)throw new Error("Creation receipt capacity reached; reconnect the host before creating more sessions");let te=Ed("sha256").update(J).digest("hex"),fe=`${te.slice(0,8)}-${te.slice(8,12)}-4${te.slice(13,16)}-a${te.slice(17,20)}-${te.slice(20,32)}`,ce=(async()=>{if(i(fe)?.id===U.id)return{id:fe,title:"\u65B0\u4F1A\u8BDD",projectId:U.id};let Ee=await o(k,"session","create",{request:{workspaceId:U.id,sessionId:fe}});return x.provider!==void 0&&await o(k,"session","selectModel",{request:{sessionId:Ee.sessionId,provider:x.provider,model:x.model}}),{id:Ee.sessionId,title:"\u65B0\u4F1A\u8BDD",projectId:U.id}})();return r.set(J,{fingerprint:G,promise:ce}),ce}if(s(x.id),C==="send")return o(k,"session","prompt",{request:{sessionId:x.id,requestId:Bt(x.requestId,"request id"),mode:"queue",content:[{type:"text",text:Bt(x.text,"text",2e4)}]}});if(C==="cancel")return o(k,"session","cancel",{request:{sessionId:x.id}});if(C==="respond")return await d(k),T(k,x);let D=await b(k,x.id),L=D;if(x.before!==void 0){if(!Number.isSafeInteger(x.before)||x.before<0)throw new Error("Invalid history cursor");L=await o(k,"session","page",{request:{address:{kind:"session",sessionId:x.id},throughSeq:D.cursor,beforeSeq:x.before,maxMessages:100}})}let R=L.records.flatMap(({event:U})=>{if(U.surfaceOp!=="append"||!["user/message","assistant/message","tool/result"].includes(U.type))return[];let j=U.type==="user/message"?U.data:U.data.message,J=Sd(j);return J?[{id:`${x.id}:${U.seq}`,role:U.type==="user/message"?"user":U.type==="tool/result"?"tool":"assistant",text:J}]:[]}),M=D.assistantStream?.activeAttempt;if(x.before===void 0&&M){let U=bd(M.stream);U&&R.push({id:`live:${M.attemptId}`,role:"assistant",text:U})}let z=N(k,x.id),V=D.projections?.values?.userQuestions?.active??[];for(let U of V.filter(j=>j.state==="continued"))z.push({id:`continued:${U.callId}`,kind:"question",title:"\u9700\u8981\u4F60\u7684\u56DE\u7B54",questions:U.questions});let q=(await E(k)).find(U=>U.id===x.id);return{messages:R,interactions:z,running:!!(M||q?.running),hasMore:L.hasMore,cursor:L.records[0]?.event.seq??0}};return{dispatch:async(x,w)=>{let C=await m(w);C.active++;try{return await S(x,w)}finally{C.active--,a.get(C.id)===C&&f(C)}},revoke:l,close:async()=>{await Promise.all([...a.keys()].map(l)),r.clear()}}}function Ha(e,t){if(!Array.isArray(e?.answers)||!Array.isArray(t))throw new Error("Expected a structured question answer");let a=new Set;for(let r of e.answers){let n=t.find(i=>i.id===r.id);if(!n||a.has(r.id)||!Array.isArray(r.selected)||r.selected.some(i=>typeof i!="string")||r.custom!==void 0&&typeof r.custom!="string")throw new Error("Invalid question answer");if(a.add(r.id),!n.multiSelect&&r.selected.length>1)throw new Error("Question allows only one selection");if(r.selected.some(i=>!n.options?.some(s=>s.label===i)))throw new Error("Unknown question option");if(!r.selected.length&&!r.custom?.trim())throw new Error("Answer cannot be empty")}if(a.size!==t.length)throw new Error("Answer each question exactly once")}async function rc(e,t,a){let r=t.details;if(e==="pi"){let l=(await a({questions:[{id:"value",question:r.title??"Pi question",...r.message?{detail:r.message}:{},...r.options?{options:r.options.map(f=>({label:f}))}:{}}]})).answers.find(f=>f.id==="value"),u=l?.custom??l?.selected?.[0];return{allow:!1,...u===void 0?{}:{value:u}}}let n=r.questions;if(!Array.isArray(n)||!n.length)throw new Error("Native question list is empty or unsupported");let i=n.map((c,l)=>({id:e==="codex"?c.id:String(l),question:c.question,...c.header?{header:c.header}:{},...c.options?.length?{options:c.options.map(u=>({label:u.label,...u.description?{description:u.description}:{}}))}:{},multiSelect:c.multiSelect===!0||c.multiple===!0})),s=await a({questions:i}),o=i.map(c=>{let l=s.answers.find(u=>u.id===c.id);if(!l)throw new Error("Human did not answer every native question");return[...l.selected,...l.custom!==void 0?[l.custom]:[]]});if(e==="codex")return{allow:!1,answers:Object.fromEntries(i.map((c,l)=>[c.id,{answers:o[l]}]))};if(e==="opencode")return{allow:!1,answers:o};if(e==="claude")return{allow:!0,answers:Object.fromEntries(n.map((c,l)=>[c.question,o[l].join(", ")]))};throw new Error(`Unsupported native question provider: ${e}`)}function ac(e){let t=e.get("commander"),a=o=>e.workspaceRegistry.list().find(c=>c.id===o.projectId&&c.path===o.cwd),r=o=>o.ownerSessionId?.startsWith("commander-web:")&&!o.archived&&a(o),n=o=>({id:`native:${o.id}`,projectId:o.projectId,title:o.title||o.provider,running:["running","waiting","connecting"].includes(o.status),updatedAt:o.updatedAt,engine:o.provider});return{list:()=>t?t.list().filter(r).map(n):[],dispatch:async o=>{if(!t||!o.id?.startsWith("native:"))throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let c=o.id.slice(7),l=t.snapshot(c);if(!r(l))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u53EF\u7528\u7684\u76F4\u63A5\u5DE5\u4F5C\u533A\uFF0C\u8BF7\u901A\u8FC7\u5B98\u65B9 Harness \u4F1A\u8BDD\u64CD\u4F5C");if(o.action==="send")return at(o.text,"\u6D88\u606F",2e4),at(o.requestId,"requestId"),["disconnected","closed"].includes(l.status)&&await t.connect(c),t.submit(c,o.text,{requestId:o.requestId});if(o.action==="cancel")return await t.interrupt(c),{accepted:!0};if(o.action==="respond"){let p=l.pendingApprovals.find(b=>b.id===o.interactionId);if(!p)throw new Error("\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u8FC7\u671F");if(p.kind==="permission"&&typeof o.answer?.allow!="boolean")throw new Error("\u9700\u8981\u660E\u786E\u5141\u8BB8\u6216\u62D2\u7EDD");let E=o.answer;return p.kind==="question"&&(E=await rc(l.provider,p,async({questions:b})=>(Ha(o.answer,b),o.answer))),t.approve(c,p.id,E),{accepted:!0}}if(o.action!=="history")throw new Error("\u4E0D\u652F\u6301\u7684\u539F\u751F\u4F1A\u8BDD\u64CD\u4F5C");let u=t.get(c).events,f=[],h;for(let p of u)(p.type==="input.accepted"||p.type==="input.steer")&&(f.push({id:`${o.id}:${p.seq}`,role:"user",text:p.data.text}),h=void 0),p.type==="text.delta"&&((!h||h.turnId!==p.turnId)&&(h={id:`${o.id}:${p.seq}`,role:"assistant",text:"",turnId:p.turnId},f.push(h)),h.text+=p.data.text),(p.type==="session.error"||p.type==="provider.error")&&f.push({id:`${o.id}:${p.seq}`,role:"system",text:p.data.message||"\u539F\u751F\u5DE5\u5177\u8FDE\u63A5\u5931\u8D25"});let m=p=>l.provider==="pi"?[{id:"value",question:p.details?.title||"Pi \u95EE\u9898",options:p.details?.options?.map(E=>({label:E}))}]:(p.details?.questions||[]).map((E,b)=>({...E,id:l.provider==="codex"?E.id:String(b),multiSelect:E.multiSelect===!0||E.multiple===!0})),d=l.pendingApprovals.map(p=>({id:p.id,kind:p.kind,title:p.details?.title||p.method||"\u7B49\u5F85\u786E\u8BA4",details:p.details,...p.kind==="question"?{questions:m(p)}:{}}));return{messages:f,running:n(l).running,interactions:d,hasMore:!1,cursor:u[0]?.seq??0,truncated:u[0]?.seq>1}}}}import{createServer as Fh}from"node:http";import{readFile as Mh}from"node:fs/promises";import{randomBytes as Hh,randomUUID as qh}from"node:crypto";import{hostname as Gh}from"node:os";import{randomUUID as nc}from"node:crypto";import{mkdir as Td,readFile as Id,writeFile as Ad,rename as Bd,rm as _d,chmod as Nd}from"node:fs/promises";import{join as kd}from"node:path";var ic=e=>{if(typeof e!="string"||!e.trim()||e.length>100)throw new Error("\u8BBE\u5907\u540D\u79F0\u5E94\u4E3A 1\u2013100 \u4E2A\u5B57\u7B26");return e.trim()};function cr(e){let t=new URL(e.url);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||!["","/"].includes(t.pathname))throw new Error("\u8BBE\u5907\u5730\u5740\u5FC5\u987B\u662F HTTPS \u4E3B\u673A\u5730\u5740");let a=String(e.pin||"").replace(/^sha256\//,"");if(a&&(!/^[A-Za-z0-9+/]{43}=$/.test(a)||Buffer.from(a,"base64").length!==32))throw new Error("\u4E3B\u673A\u516C\u94A5\u6307\u7EB9\u65E0\u6548");return{url:t.origin,pin:a}}function ii(e){if(e!==void 0){if(!Array.isArray(e)||e.length>16)throw new Error("\u8BBE\u5907\u8FDE\u63A5\u8DEF\u7EBF\u65E0\u6548");return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u8BBE\u5907\u8FDE\u63A5\u8DEF\u7EBF\u65E0\u6548");let a=t.kind==="direct"?["kind","url","pin"]:t.kind==="relay"?["kind","url","relayId","id","priority","health","cooldownUntil","lastError"]:[];if(!a.length||Object.keys(t).some(i=>!a.includes(i)))throw new Error("\u8BBE\u5907\u8FDE\u63A5\u8DEF\u7EBF\u65E0\u6548");let r=cr({url:t.url,pin:t.pin});if(t.kind==="direct"&&!r.pin)throw new Error("\u76F4\u8FDE\u8DEF\u7EBF\u5FC5\u987B\u56FA\u5B9A\u4E3B\u673A\u6307\u7EB9");if(t.kind==="relay"&&t.pin)throw new Error("\u4E2D\u7EE7\u8DEF\u7EBF\u5FC5\u987B\u4F7F\u7528\u7CFB\u7EDF CA \u9A8C\u8BC1");if(t.kind==="direct")return{kind:"direct",...r};let n=t.relayId??t.id;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(n)))throw new Error("\u4E2D\u7EE7 ID \u65E0\u6548");if(t.relayId!==void 0&&t.id!==void 0&&t.relayId!==t.id)throw new Error("\u4E2D\u7EE7 ID \u4E0D\u4E00\u81F4");if(t.priority!==void 0&&(!Number.isInteger(t.priority)||t.priority<0||t.priority>1e6))throw new Error("\u4E2D\u7EE7\u4F18\u5148\u7EA7\u65E0\u6548");if(t.health!==void 0&&!["unknown","healthy","degraded","unhealthy"].includes(t.health))throw new Error("\u4E2D\u7EE7\u5065\u5EB7\u72B6\u6001\u65E0\u6548");if(t.cooldownUntil!==void 0&&(!Number.isInteger(t.cooldownUntil)||t.cooldownUntil<0))throw new Error("\u4E2D\u7EE7\u51B7\u5374\u65F6\u95F4\u65E0\u6548");if(t.lastError!==void 0&&(typeof t.lastError!="string"||t.lastError.length>200))throw new Error("\u4E2D\u7EE7\u9519\u8BEF\u4FE1\u606F\u65E0\u6548");return{kind:"relay",url:r.url,...n===void 0?{}:{relayId:n},...t.priority===void 0?{}:{priority:t.priority},...t.health===void 0?{}:{health:t.health},...t.cooldownUntil===void 0?{}:{cooldownUntil:t.cooldownUntil},...t.lastError===void 0?{}:{lastError:t.lastError}}})}}async function sc(e){await Td(e,{recursive:!0,mode:448});let t=kd(e,"connections.json"),a={version:1,activeId:"local",devices:[]};try{a=JSON.parse(await Id(t,"utf8")),await Nd(t,384)}catch(o){if(o.code!=="ENOENT")throw o}if(a.version!==1||!Array.isArray(a.devices))throw new Error("\u8BBE\u5907\u914D\u7F6E\u683C\u5F0F\u4E0D\u53D7\u652F\u6301");a.devices.forEach(o=>{o.status="unknown",o.lastError=null,o.currentPath=null});let r=Promise.resolve(),n=()=>{let o=JSON.stringify({...a,devices:a.devices.map(({currentPath:u,...f})=>f)},null,2),c=t+"."+nc()+".tmp",l=r.then(async()=>{try{await Ad(c,o,{mode:384}),await Bd(c,t)}finally{await _d(c,{force:!0})}});return r=l.catch(()=>{}),l},i=o=>{let c=a.devices.find(l=>l.id===o);if(!c)throw new Error("\u8BBE\u5907\u4E0D\u5B58\u5728");return c},s=o=>({id:o.id,name:o.name,kind:o.kind,url:o.kind==="ssh"?o.ssh?.host:o.url,status:o.status||"unknown",lastError:o.lastError||null,currentPath:o.currentPath??null,...o.warning?{warning:o.warning}:{}});return{get:i,publicDevice:s,list(){return{activeId:a.activeId,devices:[{id:"local",name:"\u672C\u673A",kind:"local",status:"online"},...a.devices.map(s)]}},async upsert(o){let c=cr(o),l=ii(o.routes),u=o.id?a.devices.find(h=>h.id===o.id):a.devices.find(h=>h.kind!=="ssh"&&h.url===c.url&&h.pin===c.pin);if(a.devices.length>=32&&!u)throw new Error("\u6700\u591A\u4FDD\u5B58 32 \u53F0\u8BBE\u5907");if(typeof o.token!="string"||!o.token||o.token.length>4096)throw new Error("\u8BBE\u5907\u6388\u6743\u65E0\u6548");let f={...u,...o,...c,...l===void 0?{}:{routes:l},id:u?.id||o.id||nc(),name:ic(o.name||u?.name||new URL(c.url).hostname),kind:o.kind==="ssh"?"ssh":"computer",status:"online",lastError:null,currentPath:u?.currentPath??null};return a.devices=[...a.devices.filter(h=>h.id!==f.id),f],await n(),s(f)},async select(o){return o!=="local"&&i(o),a.activeId=o,await n(),o==="local"?{id:o,name:"\u672C\u673A",kind:"local",status:"online"}:s(i(o))},async rename(o,c){let l=i(o);return l.name=ic(c),await n(),s(l)},async remove(o){i(o),a.devices=a.devices.filter(c=>c.id!==o),a.activeId===o&&(a.activeId="local"),await n()},mark(o,c,l=null){let u=i(o);u.status=c,u.lastError=l},markRoute(o,c){if(c!=="direct"&&c!=="relay")throw new Error("\u8BBE\u5907\u8FDE\u63A5\u8DEF\u7EBF\u65E0\u6548");i(o).currentPath=c},async markRouteHealth(o,c,l,{cooldownUntil:u=0,lastError:f=null}={}){if(!["unknown","healthy","degraded","unhealthy"].includes(l))throw new Error("\u4E2D\u7EE7\u5065\u5EB7\u72B6\u6001\u65E0\u6548");let h=i(o),m=h.routes?.find(d=>d.kind==="relay"&&(d.relayId||d.id||d.url)===c);if(!m)throw new Error("\u4E2D\u7EE7\u8DEF\u7EBF\u4E0D\u5B58\u5728");if(!Number.isInteger(u)||u<0)throw new Error("\u4E2D\u7EE7\u51B7\u5374\u65F6\u95F4\u65E0\u6548");if(m.health=l,m.cooldownUntil=u,f==null)delete m.lastError;else{if(typeof f!="string"||f.length>200)throw new Error("\u4E2D\u7EE7\u9519\u8BEF\u4FE1\u606F\u65E0\u6548");m.lastError=f}return await n(),s(h)},flush:()=>r}}import{Agent as Rd,request as Ld}from"node:https";import{connect as oc}from"node:tls";import{createHash as Dd,timingSafeEqual as Pd}from"node:crypto";import{isIP as Ud}from"node:net";function cc(e,t){let a=e.getPeerCertificate(!0),r=Buffer.from(t,"base64");if(!a.pubkey||!Number.isFinite(Date.parse(a.valid_to))||!Number.isFinite(Date.parse(a.valid_from))||Date.parse(a.valid_to)<=Date.now()||Date.parse(a.valid_from)>Date.now())throw Object.assign(new Error("\u4E3B\u673A\u8BC1\u4E66\u65E0\u6548\u6216\u5DF2\u8FC7\u671F"),{code:"ERR_LINK_CERTIFICATE"});let n=Dd("sha256").update(a.pubkey).digest();if(n.length!==r.length||!Pd(n,r))throw Object.assign(new Error("\u4E3B\u673A\u516C\u94A5\u4E0E\u4FDD\u5B58\u7684\u6307\u7EB9\u4E0D\u4E00\u81F4"),{code:"ERR_LINK_CERTIFICATE"})}function lc(e,{timeout:t=2500,signal:a}={}){let r=new URL(e.url),n=r.hostname.replace(/^\[|\]$/g,"");return new Promise((i,s)=>{let o=oc({host:n,port:Number(r.port||443),servername:Ud(n)?void 0:n,rejectUnauthorized:!e.pin,signal:a}),c=!1,l=u=>{c||(c=!0,o.destroy(),u?s(u):i())};o.once("error",l),o.setTimeout(t,()=>l(Object.assign(new Error("\u8FDE\u63A5\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u4E3B\u673A\u662F\u5426\u5728\u7EBF"),{code:"ETIMEDOUT"}))),o.once("secureConnect",()=>{try{e.pin&&cc(o,e.pin),l()}catch(u){l(u)}})})}function lr(e){let t=new Rd({keepAlive:!0,maxSockets:64});return e.pin&&(t.createConnection=(a,r)=>{let n=oc({...a,rejectUnauthorized:!1,servername:void 0}),i=s=>{n.destroy(),r(s)};n.once("error",i),n.once("secureConnect",()=>{try{cc(n,e.pin),n.removeListener("error",i),r(null,n)}catch(s){i(s)}})}),t}function ur(e,t,a,{agent:r,token:n=e.token,signal:i}={}){let s=!r;return r??=lr(e),new Promise((o,c)=>{let l=Ld(new URL(t,e.url),{method:"POST",agent:r,signal:i,timeout:2e4,headers:{"content-type":"application/json",...n?{authorization:"Bearer "+n}:{}}},u=>{let f="",h=0;u.on("data",m=>{h+=m.length,h>1048576?l.destroy(new Error("\u4E3B\u673A\u54CD\u5E94\u8FC7\u5927")):f+=m}),u.on("error",c),u.on("end",()=>{try{let m=JSON.parse(f);if(u.statusCode>=400)throw Object.assign(new Error(m.error||"\u4E3B\u673A\u8FD4\u56DE HTTP "+u.statusCode),{statusCode:u.statusCode});o({value:m,headers:u.headers})}catch(m){c(m)}})});l.on("error",c),l.on("timeout",()=>l.destroy(new Error("\u8FDE\u63A5\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u4E3B\u673A\u662F\u5426\u5728\u7EBF"))),l.end(JSON.stringify(a))}).finally(()=>{s&&r.destroy()})}var Od=new Set(["ECONNREFUSED","ETIMEDOUT","ENETUNREACH","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ECONNRESET"]),uc=(e,t)=>Number.isInteger(e.priority)?e.priority:t,Vd=(e,t)=>Number.isInteger(e.cooldownUntil)&&e.cooldownUntil>t;function Kd(e,t=Date.now()){let a=e.map((n,i)=>({route:n,index:i})).filter(({route:n})=>n.kind==="direct"),r=e.map((n,i)=>({route:n,index:i})).filter(({route:n})=>n.kind==="relay").sort((n,i)=>uc(n.route,n.index)-uc(i.route,i.index)||n.index-i.index);return[...a,...r].filter(({route:n})=>!Vd(n,t)).map(({route:n})=>n)}async function fc(e,{timeout:t=2500,signal:a,probe:r=lc,onHealth:n}={}){let i=ii(e.routes);if(!i?.length)return{...e,...cr(e)};let s=Date.now(),o=Kd(i,s);if(!o.length){let l=Math.min(...i.filter(f=>f.kind==="relay").map(f=>f.cooldownUntil).filter(Number.isInteger));throw Object.assign(new Error("\u6240\u6709\u4E2D\u7EE7\u8DEF\u7EBF\u6B63\u5728\u51B7\u5374\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"),{code:"ROUTES_COOLDOWN",retryAt:l})}let c;for(let l of o){a?.throwIfAborted();let u={...e,url:l.url,pin:l.kind==="direct"?l.pin:""};try{return await r({url:u.url,pin:u.pin},{timeout:t,signal:a}),l.kind==="relay"&&await n?.(l,"healthy",{cooldownUntil:0,lastError:null}),u}catch(f){if(!Od.has(f.code)||f.statusCode===401||f.statusCode===403)throw f;c=f,l.kind==="relay"&&await n?.(l,"unhealthy",{cooldownUntil:Date.now()+1e4,lastError:f.message})}}throw c}import{createServer as Fd}from"node:http";import{WebSocket as Xr,WebSocketServer as dc}from"ws";import{request as hc}from"node:https";import{readFile as Md}from"node:fs/promises";import{randomBytes as Hd,createHash as qd}from"node:crypto";var pc=()=>Hd(32).toString("base64url");async function yc(e,{parentOrigin:t,onFailure:a,webRoot:r,publicOrigin:n,publicPrefix:i=""}={}){let s=lr(e),o=new Map,c=new Set,l=new Set,u,f,h=!1,m=async()=>{let{headers:T}=await ur(e,"/link/api/workbench",{},{agent:s}),S=T["set-cookie"]?.find(I=>I.startsWith("dsh_link_workbench="))?.split(";")[0];if(!S)throw new Error("\u4E3B\u673A\u672A\u7B7E\u53D1\u5DE5\u4F5C\u53F0\u6388\u6743");f=S};await m();let d=Fd(async(T,S)=>{try{if(h||T.headers.host!==new URL(u).host)throw Object.assign(new Error("\u8BBE\u5907\u8FDE\u63A5\u5730\u5740\u65E0\u6548"),{status:403});let I=new URL(T.url,u);if(I.pathname==="/enter"&&T.method==="GET"){let D=I.searchParams.get("ticket"),L=o.get(D);if(o.delete(D),!L||L<Date.now())throw Object.assign(new Error("\u5DE5\u4F5C\u53F0\u5165\u53E3\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BBE\u5907"),{status:401});let R=c.values().next().value||pc();c.add(R),c.size>16&&c.delete(c.values().next().value),S.writeHead(303,{location:i+"/s/"+R+"/link/workbench/","cache-control":"no-store","referrer-policy":"no-referrer"}),S.end();return}let x=I.pathname.match(/^\/s\/([A-Za-z0-9_-]{43})(\/.*)$/);if(!x||!c.has(x[1])||T.headers.origin&&T.headers.origin!==u)throw Object.assign(new Error("\u8BBE\u5907\u5DE5\u4F5C\u53F0\u672A\u6388\u6743"),{status:403});let w=i+"/s/"+x[1];if(I.pathname=x[2],I.pathname==="/local-proxy.js"&&T.method==="GET"){S.writeHead(200,{"content-type":"text/javascript","cache-control":"no-store"}),S.end("globalThis.__DSH_LINK_LOCAL_PROXY__=true;");return}if(r&&I.pathname==="/link/workbench/workbench.js"&&T.method==="GET"){S.writeHead(200,{"content-type":"text/javascript","cache-control":"no-store"}),S.end(await Md(new URL("workbench.js",r)));return}if(!I.pathname.startsWith("/link/workbench/")||!["GET","HEAD","POST"].includes(T.method))throw Object.assign(new Error("\u8DEF\u5F84\u672A\u6388\u6743"),{status:403});let C={};for(let[D,L]of Object.entries(T.headers))L!==void 0&&!["cookie","authorization","host","origin","referer","connection","upgrade","sec-websocket-key","sec-websocket-version"].includes(D)&&(C[D]=L);C["accept-encoding"]="identity",C.cookie=f,C.origin=new URL(e.url).origin;let k=hc(new URL(I.pathname+I.search,e.url),{agent:s,method:T.method,headers:C},D=>{let L={...D.headers,"cache-control":"no-store","referrer-policy":"no-referrer"};if(delete L["set-cookie"],delete L["x-frame-options"],delete L["strict-transport-security"],L["content-security-policy"]&&(L["content-security-policy"]=L["content-security-policy"].replace(/frame-ancestors[^;]*/g,"frame-ancestors "+t+" dsh-app:")),D.statusCode>=300&&D.statusCode<400){let R=new URL(D.headers.location||"/",e.url);if(R.origin!==new URL(e.url).origin||!R.pathname.startsWith("/link/workbench/")){D.resume(),S.writeHead(401,{"content-type":"text/plain; charset=utf-8"}),S.end("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548\uFF0C\u8BF7\u8FD4\u56DE\u8BBE\u5907\u5217\u8868\u91CD\u65B0\u8FDE\u63A5");return}L.location=w+R.pathname+R.search}if(String(L["content-type"]).startsWith("text/html")){let R=[],M=0;D.on("data",z=>{M+=z.length,M>8*1024*1024?D.destroy(new Error("\u5DE5\u4F5C\u53F0\u9875\u9762\u8FC7\u5927")):R.push(z)}),D.on("end",()=>{if(S.destroyed)return;let z=Buffer.concat(R).toString().replaceAll("/link/workbench/",w+"/link/workbench/").replace("<head>",'<head><script src="'+w+'/local-proxy.js"></script>'),V=[...z.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].map(q=>"'sha256-"+qd("sha256").update(q[1]).digest("base64")+"'");L["content-security-policy"]&&(L["content-security-policy"]=L["content-security-policy"].replace(/'sha256-[^']+'/g,"").replace(/script-src([^;]*)/,(q,U)=>"script-src"+U+" "+V.join(" ")).replace(/connect-src([^;]*)/,(q,U)=>"connect-src"+U+" "+(n||u).replace(/^http/,"ws"))),delete L["content-length"],S.writeHead(D.statusCode,L),S.end(z)})}else S.writeHead(D.statusCode,L),D.pipe(S);D.on("error",R=>S.destroy(R))});k.on("error",D=>{a?.(D),S.headersSent?S.destroy():(S.writeHead(502,{"content-type":"text/plain; charset=utf-8"}),S.end("\u4E3B\u673A\u6682\u65F6\u4E0D\u53EF\u8FBE\uFF0C\u8BF7\u8FD4\u56DE\u8BBE\u5907\u5217\u8868\u91CD\u8BD5"))}),k.setTimeout(9e4,()=>k.destroy(new Error("\u5DE5\u4F5C\u53F0\u54CD\u5E94\u8D85\u65F6"))),S.on("close",()=>{S.writableEnded||k.destroy()}),T.pipe(k)}catch(I){S.headersSent||S.writeHead(I.status||502,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),S.end(I.message)}}),p=new dc({noServer:!0,maxPayload:1024*1024}),E=new Set,b=new dc({noServer:!0,maxPayload:64*1024,perMessageDeflate:!1}),N=T=>{E.add(T);let S=new URL("/link/workbench/api/voice/realtime",e.url);S.protocol="wss:";let I=new Xr(S,{agent:s,origin:new URL(e.url).origin,headers:{cookie:f},handshakeTimeout:1e4,maxPayload:64*1024,perMessageDeflate:!1}),x=[],w=0,C=!1,k=L=>{C||(C=!0,x.length=0,w=0,E.delete(T),L&&a?.(L),T.readyState!==Xr.CLOSED&&T.terminate(),I.readyState!==Xr.CLOSED&&I.terminate())},D=(L,R,M)=>{if(L.readyState!==Xr.OPEN||L.bufferedAmount+R.length>64*1024){k(new Error("\u5B9E\u65F6\u8BED\u97F3\u7F13\u51B2\u533A\u5DF2\u6EE1"));return}L.send(R,{binary:M},z=>{z&&k(z)})};T.on("message",(L,R)=>{if(!C)if(I.readyState===Xr.CONNECTING){if(w+L.length>64*1024||x.length>=40){k(new Error("\u5B9E\u65F6\u8BED\u97F3\u8FDE\u63A5\u5C1A\u672A\u5C31\u7EEA"));return}x.push({data:L,binary:R}),w+=L.length}else D(I,L,R)}),I.once("open",()=>{for(let L of x){if(C)break;D(I,L.data,L.binary)}x.length=0,w=0}),I.on("message",(L,R)=>{C||D(T,L,R)}),T.on("error",k),I.on("error",k),T.once("close",()=>k()),I.once("close",()=>k())};return d.on("upgrade",(T,S,I)=>{S.on("error",()=>{});let x=T.url?.match(/^\/s\/([A-Za-z0-9_-]{43})(\/socket|\/link\/workbench\/api\/voice\/realtime)$/);if(h||T.headers.host!==new URL(u).host||T.headers.origin!==u||!x||!c.has(x[1])){S.destroy();return}if(x[2]==="/link/workbench/api/voice/realtime"){b.handleUpgrade(T,S,I,N);return}p.handleUpgrade(T,S,I,w=>{E.add(w);let C=new Map,k=D=>{w.readyState===1&&(w.bufferedAmount>8*1024*1024?w.terminate():w.send(JSON.stringify(D)))};w.on("message",D=>{let L;try{if(L=JSON.parse(D.toString()),L.type==="cancel"){C.get(L.id)?.destroy(),C.delete(L.id);return}if(typeof L.id!="string"||!/^[A-Za-z0-9_-]{1,100}$/.test(L.id)||C.has(L.id)||C.size>=64)throw new Error("\u6D41\u8BF7\u6C42\u65E0\u6548");let R=JSON.stringify(L.body);if(L.type!=="open"||typeof L.body!="object"||R.length>1024*1024)throw new Error("\u6D41\u8BF7\u6C42\u65E0\u6548");let M=hc(new URL("/link/workbench/remote/open",e.url),{agent:s,method:"POST",headers:{cookie:f,origin:new URL(e.url).origin,"content-type":"application/json"}},z=>{k({id:L.id,type:"headers",status:z.statusCode});let V="";z.setEncoding("utf8"),z.on("data",q=>{if(V+=q,V.length>4*1024*1024){M.destroy(new Error("\u6D41\u54CD\u5E94\u8FC7\u5927"));return}let U;for(;(U=V.indexOf(`
29
+ `))>=0;){let j=V.slice(0,U);if(V=V.slice(U+1),j.trim())try{k({id:L.id,type:"data",value:JSON.parse(j)})}catch{M.destroy(new Error("\u6D41\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF"))}}}),z.on("end",()=>{C.delete(L.id),k({id:L.id,type:"end"})}),z.on("error",q=>M.destroy(q))});C.set(L.id,M),M.setTimeout(9e4,()=>M.destroy(new Error("\u6D41\u8FDE\u63A5\u8D85\u65F6"))),M.on("error",z=>{C.delete(L.id),k({id:L.id,type:"error",error:z.message})}),M.end(R)}catch(R){k({id:L?.id,type:"error",error:R.message})}}),w.on("error",()=>{}),w.on("close",()=>{E.delete(w);for(let D of C.values())D.destroy();C.clear()})})}),d.on("connection",T=>{l.add(T),T.on("close",()=>l.delete(T))}),await new Promise((T,S)=>{d.once("error",S),d.listen(0,"127.0.0.1",T)}),u="http://127.0.0.1:"+d.address().port,{origin:u,async enter(){await m();for(let[S,I]of o)I<Date.now()&&o.delete(S);let T=pc();return o.set(T,Date.now()+6e4),(n||u)+i+"/enter?ticket="+T},async close(){h=!0;for(let S of E)S.terminate();p.close(),b.close(),o.clear(),c.clear(),s.destroy();let T=new Promise(S=>d.close(S));for(let S of l)S.destroy();await T}}}import{createHash as Sh,randomBytes as bh,randomUUID as vi}from"node:crypto";import{access as kc,mkdir as Th,readFile as Ih,rename as Ah,rm as Bh,writeFile as _h}from"node:fs/promises";import{createServer as Nh,isIP as kh}from"node:net";import{join as aa}from"node:path";import{fileURLToPath as $a}from"node:url";import Rh from"ssh2";import{request as Lh}from"node:https";import{randomBytes as yi}from"node:crypto";import{isIP as Bc}from"node:net";import{request as gh}from"node:https";import{resolve4 as vh,resolve6 as mh}from"node:dns/promises";import{join as Eh}from"node:path";import{spawn as Gd}from"node:child_process";import{createHash as jd,randomUUID as wc,X509Certificate as $d,createPrivateKey as zd}from"node:crypto";import{access as li,link as Wd,lstat as Nt,mkdir as Yt,readFile as ta,readdir as Qd,readlink as Yd,realpath as ui,rename as xc,rm as Ut,symlink as Xd,writeFile as Xt}from"node:fs/promises";import{isIP as fi}from"node:net";import{homedir as Jd}from"node:os";import{join as oe,resolve as ra}from"node:path";import{fileURLToPath as Zd,pathToFileURL as eh}from"node:url";var th=[5,4,0],fr="dsh-link-ip",rh="dsh-link-ip-certificate",st="benchgo-relay-cert-renew.service",Je="benchgo-relay-cert-renew.timer",dr="benchgo-relay.service",oi="# Managed by DSH Link IP certificate tool.",di=".dsh-link-ip-certificate-renew.json",ee=e=>{throw new Error(e)};function ah(e){let[t,...a]=e;["issue","renew","dry-run","status","install-timer","uninstall-timer"].includes(t)||ee("\u7528\u6CD5\uFF1Aip-certificate.mjs <issue|renew|dry-run|status|install-timer|uninstall-timer> [\u9009\u9879]");let r=new Set(["--ip","--domain","--email","--webroot","--state-dir","--challenge-port","--relay-port","--confirm-public-ip","--certbot","--restart-relay-unit"]),n={};for(let i=0;i<a.length;i+=2){let s=a[i],o=a[i+1];(!r.has(s)||s in n||!o||o.startsWith("--"))&&ee("\u8BC1\u4E66\u53C2\u6570\u65E0\u6548\uFF1A"+s),n[s]=o}if(t==="uninstall-timer")return Object.keys(n).length&&ee("uninstall-timer \u4E0D\u63A5\u53D7\u53C2\u6570"),{operation:t,values:n};if(n["--state-dir"]||ee("\u5FC5\u987B\u6307\u5B9A --state-dir"),["status","install-timer"].includes(t)&&Object.keys(n).some(i=>i!=="--state-dir")&&ee(t+" \u53EA\u63A5\u53D7 --state-dir"),!["status","install-timer"].includes(t))for(let i of["--webroot","--challenge-port","--relay-port","--confirm-public-ip"])n[i]||ee("\u5FC5\u987B\u6307\u5B9A "+i);return!["status","install-timer"].includes(t)&&(!n["--ip"]&&!n["--domain"]||n["--ip"]&&n["--domain"])&&ee("\u5FC5\u987B\u6307\u5B9A IP \u6216\u57DF\u540D"),n["--restart-relay-unit"]&&(t!=="renew"||n["--restart-relay-unit"]!==dr)&&ee("\u7EED\u671F\u53EA\u5141\u8BB8\u91CD\u542F\u672C\u5DE5\u5177\u7BA1\u7406\u7684 "+dr),{operation:t,values:n}}function gc(e){return/^\d{1,5}$/.test(e??"")||ee("\u7AEF\u53E3\u5FC5\u987B\u4F7F\u7528\u5341\u8FDB\u5236\u6570\u5B57"),Number(e)}function ci(e){return e.split(".").reduce((t,a)=>t<<8n|BigInt(a),0n)}function Jr(e,t,a,r){return e>>BigInt(r-a)===t>>BigInt(r-a)}function Zr(e){let t=e.toLowerCase();if(t.includes(".")){let s=t.lastIndexOf(":"),o=t.slice(s+1);if(fi(o)!==4)return null;let c=ci(o);t=t.slice(0,s)+":"+(c>>16n).toString(16)+":"+(c&0xffffn).toString(16)}let a=t.split("::"),r=a[0]?a[0].split(":"):[],n=a.length>1&&a[1]?a[1].split(":"):[];if(a.length>2)return null;let i=a.length===1?r:[...r,...Array(8-r.length-n.length).fill("0"),...n];return i.length!==8||i.some(s=>!/^[0-9a-f]{1,4}$/.test(s))?null:i.reduce((s,o)=>s<<16n|BigInt("0x"+o),0n)}function Ga(e){let t=e.ip,a=e.domain;a&&(/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(a)||ee("\u57DF\u540D\u683C\u5F0F\u65E0\u6548"),e.confirmPublicIp!==!0&&ee("\u8BF7\u786E\u8BA4\u57DF\u540D\u5DF2\u89E3\u6790\u5230\u6B64\u670D\u52A1\u5668"));let r=typeof t=="string"?fi(t):0;if(!r&&!a&&ee("\u5FC5\u987B\u586B\u5199\u6709\u6548\u7684 IP \u5730\u5740\u6216\u57DF\u540D"),e.confirmPublicIp!==!0&&ee("\u8BF7\u786E\u8BA4\u8BE5 IP \u662F\u6B64\u670D\u52A1\u5668\u5B9E\u9645\u4F7F\u7528\u7684\u516C\u7F51 IP"),!a)if(r===4){let i=ci(t);[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]].some(([o,c])=>Jr(i,ci(o),c,32))&&ee("\u8BE5 IPv4 \u5730\u5740\u4E0D\u662F\u53EF\u7B7E\u53D1\u8BC1\u4E66\u7684\u516C\u7F51\u5355\u64AD\u5730\u5740")}else{let i=Zr(t);(i===null||i>>125n!==1n||Jr(i,Zr("2001::"),23,128)||Jr(i,Zr("2001:db8::"),32,128)||Jr(i,Zr("2001:20::"),28,128)||Jr(i,Zr("3fff::"),20,128))&&ee("\u8BE5 IPv6 \u5730\u5740\u4E0D\u662F\u53EF\u7B7E\u53D1\u8BC1\u4E66\u7684\u516C\u7F51\u5355\u64AD\u5730\u5740")}let n=e.email??"";return n&&!/^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,63}$/.test(n)&&ee("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u8054\u7CFB\u90AE\u7BB1"),e.challengePort!==80&&ee("Let\u2019s Encrypt HTTP-01 \u56FA\u5B9A\u4F7F\u7528\u516C\u7F51 80 \u7AEF\u53E3\uFF1B\u8BF7\u8BA9\u73B0\u6709\u53CD\u5411\u4EE3\u7406\u5C06\u6311\u6218\u76EE\u5F55\u6620\u5C04\u5230 webroot"),(!Number.isInteger(e.relayPort)||e.relayPort<2e4||e.relayPort>49151||[22,80,443,8080,8443].includes(e.relayPort))&&ee("\u4E2D\u7EE7\u4E1A\u52A1\u7AEF\u53E3\u987B\u4E3A 20000\u201349151 \u7684\u4E13\u7528\u9AD8\u4F4D\u7AEF\u53E3"),(typeof e.webroot!="string"||!e.webroot||!e.stateDir)&&ee("\u5FC5\u987B\u6307\u5B9A\u5DF2\u5B58\u5728\u7684 webroot \u548C\u72B6\u6001\u76EE\u5F55"),e.certbot!==void 0&&(typeof e.certbot!="string"||!e.certbot||e.certbot.includes("\0"))&&ee("Certbot \u8DEF\u5F84\u65E0\u6548"),{ip:t,domain:a,family:r,email:n,challengePort:80,relayPort:e.relayPort,webroot:ra(e.webroot),stateDir:ra(e.stateDir),certbot:e.certbot??"certbot"}}async function vc(e,t,a=!1){let r=await ui(e).catch(()=>ee(t+" \u5FC5\u987B\u662F\u5DF2\u5B58\u5728\u7684\u76EE\u5F55"));return(await Nt(r)).isDirectory()||ee(t+" \u5FC5\u987B\u662F\u76EE\u5F55"),await li(r,a?2:4).catch(()=>ee(t+(a?" \u4E0D\u53EF\u5199":" \u4E0D\u53EF\u8BFB"))),r}async function nh(e,{create:t=!1}={}){let a=ra(e);t&&await Yt(a,{recursive:!0,mode:448});let r=await ui(a).catch(i=>i.code==="ENOENT"&&!t?null:ee("\u72B6\u6001\u76EE\u5F55\u5FC5\u987B\u662F\u53EF\u8BBF\u95EE\u7684\u76EE\u5F55"));return r?((await Nt(r)).isDirectory()||ee("\u72B6\u6001\u76EE\u5F55\u5FC5\u987B\u662F\u76EE\u5F55"),await li(r,t?2:4).catch(()=>ee(t?"\u72B6\u6001\u76EE\u5F55\u4E0D\u53EF\u5199":"\u72B6\u6001\u76EE\u5F55\u4E0D\u53EF\u8BFB")),r):null}function Sc(e){return jd("sha256").update(e).digest("hex")}function ih(e){let t=String(e);return/[\0\r\n]/.test(t)&&ee("systemd \u53C2\u6570\u4E0D\u80FD\u5305\u542B\u6362\u884C\u6216\u7A7A\u5B57\u7B26"),'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"$$").replace(/%/g,"%%")+'"'}function bc(){let e=process.env.XDG_CONFIG_HOME?ra(process.env.XDG_CONFIG_HOME):oe(Jd(),".config");return oe(e,"systemd","user")}function sh(e,t){let a=Zd(import.meta.url),r=[process.execPath,a,"renew","--state-dir",t,...e.domain?["--domain",e.domain]:["--ip",e.ip],...e.email?["--email",e.email]:[],"--webroot",e.webroot,"--challenge-port","80","--relay-port",String(e.relayPort),"--confirm-public-ip","true","--certbot",e.certbot??"certbot","--restart-relay-unit",dr],n=[oi,"[Unit]","Description=Renew the DSH Link IP certificate","After=network-online.target","","[Service]","Type=oneshot","UMask=0077","TimeoutStartSec=25min","ExecStart="+r.map(ih).join(" "),""].join(`
30
+ `),i=[oi,"[Unit]","Description=Daily renewal of the DSH Link IP certificate","","[Timer]","OnCalendar=daily","RandomizedDelaySec=1h","Persistent=true","Unit="+st,"","[Install]","WantedBy=timers.target",""].join(`
31
+ `);return{[st]:n,[Je]:i}}async function Tc(e,t,a){let r;try{r=await Nt(e)}catch(i){if(i.code==="ENOENT")return null;throw i}(!r.isFile()||r.isSymbolicLink()||typeof process.getuid=="function"&&r.uid!==process.getuid())&&ee(a+" \u4E0D\u662F\u672C\u5DE5\u5177\u62E5\u6709\u7684\u666E\u901A\u6587\u4EF6");let n=await ta(e,"utf8");return(!n.startsWith(oi)||Sc(n)!==t)&&ee(a+" \u5DF2\u88AB\u4FEE\u6539\uFF0C\u62D2\u7EDD\u8986\u76D6\u6216\u5220\u9664"),n}async function Ic(e){let t=oe(e,di),a;try{a=await Nt(t)}catch(n){if(n.code==="ENOENT")return null;throw n}(!a.isFile()||a.isSymbolicLink()||(a.mode&63)!==0||typeof process.getuid=="function"&&a.uid!==process.getuid())&&ee("\u7EED\u671F timer \u5F52\u5C5E\u6E05\u5355\u6743\u9650\u6216\u6587\u4EF6\u7C7B\u578B\u65E0\u6548");let r=JSON.parse(await ta(t,"utf8"));return(r.schemaVersion!==1||r.tool!=="dsh-link-ip-certificate"||!r.units||typeof r.units[st]!="string"||typeof r.units[Je]!="string")&&ee("\u7EED\u671F timer \u5F52\u5C5E\u6E05\u5355\u65E0\u6548"),[r.units[st],r.units[Je]].every(n=>/^[a-f0-9]{64}$/.test(n))||ee("\u7EED\u671F timer \u5F52\u5C5E\u6E05\u5355\u54C8\u5E0C\u65E0\u6548"),r}async function si(e,t){let a=e+"."+wc()+".tmp";await Xt(a,t,{mode:384,flag:"wx"});try{await Wd(a,e)}finally{await Ut(a,{force:!0})}}async function Br(e){return ja("systemctl",["--user",...e],{timeout:3e4,label:"systemctl"})}async function oh(){let{stdout:e}=await Br(["show","--property=LoadState","--value",dr]);e.trim()!=="loaded"&&ee("\u5F53\u524D\u7528\u6237\u7684 systemd \u5C1A\u672A\u52A0\u8F7D "+dr+"\uFF0C\u8BF7\u5148\u914D\u7F6E\u5E76\u542F\u52A8\u4E2D\u7EE7\u670D\u52A1")}async function ch(e,t){await oh();let a=bc();await Yt(a,{recursive:!0,mode:448});let r=sh(e,t),n=Object.fromEntries(Object.entries(r).map(([o,c])=>[o,Sc(c)])),i=oe(a,di),s=await Ic(a);if(s){(s.units[st]!==n[st]||s.units[Je]!==n[Je])&&ee("\u7EED\u671F timer \u5DF2\u5B89\u88C5\u4F46\u914D\u7F6E\u4E0D\u540C\uFF0C\u8BF7\u5148\u5378\u8F7D\u518D\u5B89\u88C5");for(let o of[st,Je])await Tc(oe(a,o),s.units[o],o)||await si(oe(a,o),r[o])}else{for(let l of[st,Je])try{await Nt(oe(a,l)),ee(l+" \u5DF2\u5B58\u5728\u4E14\u4E0D\u5C5E\u4E8E\u672C\u5DE5\u5177\uFF0C\u62D2\u7EDD\u8986\u76D6")}catch(u){if(u.code!=="ENOENT")throw u}let o=!1,c=!1;try{await si(oe(a,st),r[st]),o=!0,await si(oe(a,Je),r[Je]),c=!0,await Xt(i,JSON.stringify({schemaVersion:1,tool:"dsh-link-ip-certificate",units:n})+`
32
+ `,{mode:384,flag:"wx"})}catch(l){throw c&&await Ut(oe(a,Je),{force:!0}),o&&await Ut(oe(a,st),{force:!0}),l}}await Br(["daemon-reload"]),await Br(["enable","--now",Je])}async function lh(){let e=bc(),t=await Ic(e);if(!t){for(let a of[st,Je])try{await Nt(oe(e,a)),ee(a+" \u5B58\u5728\u4F46\u6CA1\u6709\u672C\u5DE5\u5177\u5F52\u5C5E\u6E05\u5355\uFF0C\u62D2\u7EDD\u5220\u9664")}catch(r){if(r.code!=="ENOENT")throw r}return!1}for(let a of[st,Je])await Tc(oe(e,a),t.units[a],a);await Br(["disable","--now",Je]);for(let a of[st,Je])await Ut(oe(e,a),{force:!0});return await Ut(oe(e,di)),await Br(["daemon-reload"]),!0}async function uh(e){let t=oe(e,"relay-reload-pending");try{await Xt(t,`pending
33
+ `,{mode:384,flag:"wx"})}catch(a){if(a.code!=="EEXIST")throw a;let r=await Nt(t);(!r.isFile()||r.isSymbolicLink()||(r.mode&63)!==0)&&ee("\u4E2D\u7EE7 reload \u6807\u8BB0\u6587\u4EF6\u6743\u9650\u6216\u7C7B\u578B\u65E0\u6548")}}async function mc(e){let t=oe(e,"relay-reload-pending"),a;try{a=await Nt(t)}catch(r){if(r.code==="ENOENT")return!1;throw r}return(!a.isFile()||a.isSymbolicLink()||(a.mode&63)!==0)&&ee("\u4E2D\u7EE7 reload \u6807\u8BB0\u6587\u4EF6\u6743\u9650\u6216\u7C7B\u578B\u65E0\u6548"),await Br(["try-restart",dr]),await Ut(t),!0}function ja(e,t,{timeout:a=1200*1e3,env:r=process.env,label:n="Certbot"}={}){return new Promise((i,s)=>{let o=Gd(e,t,{shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:r}),c="",l="",u=!1,f=(d,p)=>{u||(u=!0,clearTimeout(m),d?s(d):i(p))},h=(d,p)=>(d+p.toString()).slice(-16e3);o.stdout.on("data",d=>{c=h(c,d)}),o.stderr.on("data",d=>{l=h(l,d)}),o.once("error",d=>f(new Error(d.code==="ENOENT"?n==="Certbot"?"\u672A\u627E\u5230 Certbot\uFF0C\u8BF7\u5148\u624B\u52A8\u5B89\u88C5 Certbot 5.4 \u6216\u66F4\u9AD8\u7248\u672C":"\u672A\u627E\u5230 "+n:n+" \u65E0\u6CD5\u542F\u52A8\uFF1A"+d.message))),o.once("close",d=>d===0?f(null,{stdout:c,stderr:l}):f(new Error(n+" \u6267\u884C\u5931\u8D25\uFF08"+d+"\uFF09\uFF1A"+(l.trim()||c.trim()).slice(-1200))));let m=setTimeout(()=>{o.kill("SIGTERM"),f(new Error(n+" \u64CD\u4F5C\u8D85\u65F6"))},a);m.unref?.()})}async function fh(e){let{stdout:t,stderr:a}=await ja(e,["--version"],{timeout:15e3}),r=(t+a).match(/certbot\s+(\d+)\.(\d+)\.(\d+)/i);return(!r||dh(r.slice(1).map(Number),th)<0)&&ee("IP webroot \u8BC1\u4E66\u9700\u8981 Certbot 5.4.0 \u6216\u66F4\u9AD8\u7248\u672C"),r.slice(1).join(".")}function dh(e,t){for(let a=0;a<3;a++)if(e[a]!==t[a])return e[a]-t[a];return 0}var hi=e=>oe(e,rh),pi=e=>oe(hi(e),"managed.json");async function Ac(e){try{let t=pi(e),a=await Nt(t);(!a.isFile()||a.isSymbolicLink()||(a.mode&63)!==0)&&ee("\u8BC1\u4E66\u72B6\u6001\u5F52\u5C5E\u6807\u8BB0\u6743\u9650\u65E0\u6548");let r=JSON.parse(await ta(t,"utf8"));return(r.schemaVersion!==1||r.tool!=="dsh-link-ip-certificate")&&ee("\u8BC1\u4E66\u72B6\u6001\u76EE\u5F55\u5F52\u5C5E\u6807\u8BB0\u65E0\u6548"),r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function hh(e){let t=hi(e);try{await Yt(t,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}let a=await Nt(t);(!a.isDirectory()||a.isSymbolicLink()||(a.mode&63)!==0)&&ee("\u8BC1\u4E66\u72B6\u6001\u76EE\u5F55\u5FC5\u987B\u662F\u4EC5\u5F53\u524D\u7528\u6237\u53EF\u8BBF\u95EE\u7684\u771F\u5B9E\u76EE\u5F55");let r=await Ac(e);return r||((await Qd(t)).length&&ee("\u8BC1\u4E66\u72B6\u6001\u76EE\u5F55\u5DF2\u6709\u975E\u672C\u5DE5\u5177\u6570\u636E\uFF0C\u62D2\u7EDD\u63A5\u7BA1"),r={schemaVersion:1,tool:"dsh-link-ip-certificate"},await Xt(pi(e),JSON.stringify(r)+`
34
+ `,{mode:384,flag:"wx"})),t}async function Ec(e,t){let a=pi(e),r=a+"."+wc()+".tmp";await Xt(r,JSON.stringify(t,null,2)+`
35
+ `,{mode:384,flag:"wx"});try{await xc(r,a)}catch(n){throw await Ut(r,{force:!0}),n}}function Cc(e,t,a,r=!1){let i=["--non-interactive","--agree-tos",...t.email?["--no-eff-email","--email",t.email]:["--register-unsafely-without-email"],"--config-dir",oe(a,"certbot"),"--work-dir",oe(a,"work"),"--logs-dir",oe(a,"logs")],s=t.domain?["--domains",t.domain]:["--ip-address",t.ip,"--preferred-profile","shortlived"];if(e==="issue")return["certonly","--authenticator","webroot","--webroot-path",t.webroot,"--preferred-challenges","http",...s,"--cert-name",fr,...i];let o=t.domain?[]:["--preferred-profile","shortlived"];return e==="dry-run"?r?["renew","--cert-name",fr,"--webroot-path",t.webroot,...o,"--dry-run",...i]:["certonly","--authenticator","webroot","--webroot-path",t.webroot,"--preferred-challenges","http",...s,"--cert-name",fr,"--dry-run",...i]:["renew","--cert-name",fr,"--webroot-path",t.webroot,...o,...i]}async function qa(e,t,a,{allowExpired:r=!1}={}){let[n,i]=await Promise.all([ta(e,"utf8"),ta(t,"utf8")]),s;try{s=new $d(n),s.checkPrivateKey(zd(i))||ee("\u8BC1\u4E66\u4E0E\u79C1\u94A5\u4E0D\u5339\u914D")}catch(u){if(/证书与私钥/.test(u.message))throw u;ee("Certbot \u8FD4\u56DE\u7684\u8BC1\u4E66\u6216\u79C1\u94A5\u65E0\u6548")}a&&(fi(a)?!s.checkIP(a):!s.checkHost(a))&&ee("\u7B7E\u53D1\u8BC1\u4E66\u7684\u6807\u8BC6\u4E0E\u914D\u7F6E\u4E0D\u5339\u914D");let o=Date.parse(s.validFrom),c=Date.parse(s.validTo),l=Date.now();return(!Number.isFinite(o)||!Number.isFinite(c)||o>l+5*6e4||!r&&c<=l)&&ee("\u8BC1\u4E66\u5C1A\u672A\u751F\u6548\u6216\u5DF2\u7ECF\u8FC7\u671F"),{cert:n,key:i,notBefore:new Date(o).toISOString(),notAfter:new Date(c).toISOString(),daysRemaining:Math.floor((c-l)/864e5),expired:c<=l}}async function ea(e){let t=oe(e,"active"),a;try{a=await Yd(t)}catch(i){if(i.code==="ENOENT")return null;throw new Error("\u6D3B\u52A8\u8BC1\u4E66\u8DEF\u5F84\u4E0D\u662F\u672C\u5DE5\u5177\u521B\u5EFA\u7684\u94FE\u63A5")}/^releases\/[A-Za-z0-9-]+$/.test(a)||ee("\u6D3B\u52A8\u8BC1\u4E66\u94FE\u63A5\u6307\u5411\u72B6\u6001\u76EE\u5F55\u4E4B\u5916");let r=oe(e,a),n=await ui(r).catch(()=>ee("\u6D3B\u52A8\u8BC1\u4E66\u7248\u672C\u76EE\u5F55\u7F3A\u5931"));return n.startsWith(oe(e,"releases")+"/")||ee("\u6D3B\u52A8\u8BC1\u4E66\u7248\u672C\u76EE\u5F55\u8D8A\u754C"),{cert:oe(n,"fullchain.pem"),key:oe(n,"privkey.pem"),link:a}}async function ph(e,t,a){let r=oe(e,"releases");await Yt(r,{recursive:!0,mode:448});let n=new Date().toISOString().replace(/[:.]/g,"-")+"-"+process.pid,i=oe(r,n);await Yt(i,{mode:448});try{await Xt(oe(i,"fullchain.pem"),t.cert,{mode:420,flag:"wx"}),await Xt(oe(i,"privkey.pem"),t.key,{mode:384,flag:"wx"}),await Xt(oe(i,"metadata.json"),JSON.stringify({subject:a,notBefore:t.notBefore,notAfter:t.notAfter})+`
36
+ `,{mode:384,flag:"wx"});let s=oe(e,"active"),o=await ea(e),c=oe(e,".active-"+process.pid+"-"+Date.now());await Xd("releases/"+n,c);try{await xc(c,s)}catch(l){throw await Ut(c,{force:!0}),l}return{cert:oe(s,"fullchain.pem"),key:oe(s,"privkey.pem"),release:"releases/"+n,previous:o?.link}}catch(s){throw await Ut(i,{recursive:!0,force:!0}),s}}function _t(e){process.stdout.write(JSON.stringify(e)+`
37
+ `)}async function yh(){let e=ah(process.argv.slice(2)),{operation:t,values:a}=e;if(t==="uninstall-timer"){_t({state:await lh()?"timer-removed":"timer-not-installed"});return}let r=await nh(a["--state-dir"],{create:!["status","install-timer"].includes(t)});if(!r){t==="install-timer"&&ee("\u8BF7\u5148\u6210\u529F\u7B7E\u53D1\u8BC1\u4E66\uFF0C\u518D\u5B89\u88C5\u81EA\u52A8\u7EED\u671F"),_t({state:"not-configured"});return}let n=hi(r),i=await Ac(r);if(t==="install-timer"){i?.config||ee("\u8BF7\u5148\u6210\u529F\u7B7E\u53D1\u8BC1\u4E66\uFF0C\u518D\u5B89\u88C5\u81EA\u52A8\u7EED\u671F");let p=i.config,E=Ga({ip:p.ip,domain:p.domain,email:p.email,webroot:p.webroot,stateDir:r,challengePort:80,relayPort:p.relayPort,confirmPublicIp:!0,certbot:p.certbot});E.webroot=await vc(E.webroot,"webroot",!0);let b=await ea(n);b||ee("\u5C1A\u65E0\u672C\u5DE5\u5177\u7BA1\u7406\u7684\u6709\u6548\u8BC1\u4E66\uFF0C\u8BF7\u5148\u8FD0\u884C issue"),await qa(b.cert,b.key,E.domain||E.ip,{allowExpired:!0}),await ch(E,r),_t({state:"timer-installed",timer:Je,relayUnit:dr});return}if(t==="status"){if(!i){_t({state:"not-configured"});return}let p=i.config;if(!p){_t({state:"not-configured"});return}let E=await ea(n);if(!E){_t({state:"certificate-missing",config:p});return}let b=await qa(E.cert,E.key,p.domain||p.ip,{allowExpired:!0});_t({state:b.expired?"expired":"ready",...p,notBefore:b.notBefore,notAfter:b.notAfter,daysRemaining:b.daysRemaining,cert:E.cert,key:E.key,renewalRecommended:b.daysRemaining<=2});return}let s=Ga({ip:a["--ip"],domain:a["--domain"],email:a["--email"],webroot:a["--webroot"],stateDir:r,challengePort:gc(a["--challenge-port"]),relayPort:gc(a["--relay-port"]),confirmPublicIp:a["--confirm-public-ip"]==="true",certbot:a["--certbot"]});s.webroot=await vc(s.webroot,"webroot",!0),t==="renew"&&(!i?.config||!await ea(n))&&ee("\u5C1A\u65E0\u672C\u5DE5\u5177\u7BA1\u7406\u7684\u6709\u6548\u8BC1\u4E66\uFF0C\u8BF7\u5148\u8FD0\u884C issue"),i?.config&&(i.config.ip!==s.ip||i.config.domain!==s.domain)&&ee("\u540C\u4E00\u8BC1\u4E66\u72B6\u6001\u76EE\u5F55\u4E0D\u80FD\u66F4\u6362\u8BC1\u4E66\u6807\u8BC6\uFF0C\u8BF7\u4F7F\u7528\u72EC\u7ACB\u72B6\u6001\u76EE\u5F55"),i?.config&&t!=="issue"&&(i.config.domain!==s.domain||i.config.webroot!==s.webroot||i.config.relayPort!==s.relayPort)&&ee("\u7EED\u671F\u914D\u7F6E\u5FC5\u987B\u4E0E\u5F53\u524D\u8BC1\u4E66\u7684 webroot \u548C\u4E2D\u7EE7\u7AEF\u53E3\u4E00\u81F4");let o=await fh(s.certbot),c=await hh(r);if(t==="dry-run"){let p=!1;try{await li(oe(c,"certbot/live",fr,"fullchain.pem")),p=!0}catch{}await ja(s.certbot,Cc("dry-run",s,c,p)),await Ec(r,{schemaVersion:1,tool:"dsh-link-ip-certificate",certbot:o,config:{ip:s.ip,domain:s.domain,email:s.email,webroot:s.webroot,challengePort:80,relayPort:s.relayPort,certbot:s.certbot}}),_t({state:"dry-run-passed",certbot:o,challenge:"http-01",challengePort:80,relayPort:s.relayPort});return}let l=t==="renew"?await ea(n):null,u=l?await qa(l.cert,l.key,s.domain||s.ip,{allowExpired:!0}):null;await Yt(oe(c,"certbot"),{recursive:!0,mode:448}),await Yt(oe(c,"work"),{recursive:!0,mode:448}),await Yt(oe(c,"logs"),{recursive:!0,mode:448}),await ja(s.certbot,Cc(t,s,c));let f=await qa(oe(c,"certbot/live",fr,"fullchain.pem"),oe(c,"certbot/live",fr,"privkey.pem"),s.domain||s.ip);if(!(t==="issue"||!u||u.cert!==f.cert||u.key!==f.key)){a["--restart-relay-unit"]&&await mc(n),_t({state:"ready",changed:!1,certbot:o,challenge:"http-01",challengePort:80,relayPort:s.relayPort,ip:s.ip,domain:s.domain,notBefore:f.notBefore,notAfter:f.notAfter,daysRemaining:f.daysRemaining,cert:l.cert,key:l.key});return}let m={schemaVersion:1,tool:"dsh-link-ip-certificate",certbot:o,config:{ip:s.ip,domain:s.domain,email:s.email,webroot:s.webroot,challengePort:80,relayPort:s.relayPort,certbot:s.certbot}};await Ec(r,m);let d=await ph(c,f,s.domain||s.ip);a["--restart-relay-unit"]&&(await uh(n),await mc(n)),_t({state:"ready",changed:!0,certbot:o,challenge:"http-01",challengePort:80,relayPort:s.relayPort,ip:s.ip,domain:s.domain,notBefore:f.notBefore,notAfter:f.notAfter,daysRemaining:f.daysRemaining,cert:d.cert,key:d.key})}process.argv[1]&&import.meta.url===eh(ra(process.argv[1])).href&&yh().catch(e=>{process.stderr.write((e?.message??"\u8BC1\u4E66\u64CD\u4F5C\u5931\u8D25")+`
38
+ `),process.exitCode=1});var Jt="/opt/benchgo-relay",_r="# Managed by BenchGo relay deployment v1",Pe=e=>"'"+String(e).replaceAll("'","'\\''")+"'",Ch=String.raw`import glob, os, re, sys
39
+ domain=sys.argv[1]
40
+ files=[]
41
+ for pattern in ['/www/server/panel/vhost/nginx/*.conf','/etc/nginx/sites-enabled/*','/etc/nginx/conf.d/*.conf','/etc/apache2/sites-enabled/*','/etc/httpd/conf.d/*.conf']:
42
+ files.extend(glob.glob(pattern))
43
+ text='\n'.join(open(path,errors='ignore').read() for path in files if os.path.isfile(path))
44
+ for match in re.finditer(r'\bserver\s*\{',text):
45
+ start=match.end(); depth=1; i=start
46
+ while i<len(text) and depth:
47
+ if text[i]=='{': depth+=1
48
+ elif text[i]=='}': depth-=1
49
+ i+=1
50
+ block=text[start:i-1]
51
+ names=re.search(r'(?m)^\s*server_name\s+([^;]+);',block)
52
+ if names and domain in names.group(1).split():
53
+ for root in re.findall(r'(?m)^\s*root\s+([^;]+);',block):
54
+ root=root.strip("\"'")
55
+ if root.startswith('/') and os.path.isdir(root): print(root); sys.exit(0)
56
+ for match in re.finditer(r'(?is)<VirtualHost\b[^>]*>(.*?)</VirtualHost>',text):
57
+ block=match.group(1)
58
+ names=re.findall(r'(?im)^\s*Server(?:Name|Alias)\s+([^\s#]+)',block)
59
+ if domain in names:
60
+ for root in re.findall(r'(?im)^\s*DocumentRoot\s+([^\s#]+)',block):
61
+ if root.startswith('/') and os.path.isdir(root): print(root); sys.exit(0)`;function gi(e){let t=String(e.publicIp??"").trim(),a=String(e.domain??"").trim().toLowerCase();if(a&&!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(a))throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u57DF\u540D");if(!Bc(t)||/^(?:0\.|10\.|127\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/.test(t)||t==="::1"||/^(?:f[cd]|fe80:)/i.test(t))throw new Error("\u8BF7\u8F93\u5165\u670D\u52A1\u5668\u5B9E\u9645\u516C\u7F51 IP");let r=Number(e.relayPort??48730);if(!Number.isInteger(r)||r<2e4||r>49151)throw new Error("\u4E2D\u7EE7\u7AEF\u53E3\u987B\u4E3A 20000\u201349151");let n=String(e.email??"").trim();if(n&&!/^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,63}$/.test(n))throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u8054\u7CFB\u90AE\u7BB1");let i=e.challengeMode??(a?"webroot":"standalone");if(!["standalone","webroot"].includes(i))throw new Error("\u4E0D\u652F\u6301\u7684\u8BC1\u4E66\u9A8C\u8BC1\u65B9\u5F0F");let s=i==="webroot"&&!String(e.webroot??"").trim(),o=i==="standalone"?Jt+"/challenge":String(e.webroot??"").trim()||(a?"/www/wwwroot/"+a:"");if(typeof o!="string"||!o.startsWith("/")||/[\x00-\x1f]/.test(o)||o.split("/").includes(".."))throw new Error("\u8BF7\u586B\u5199\u73B0\u6709\u53CD\u5411\u4EE3\u7406\u7684\u7EDD\u5BF9 webroot \u8DEF\u5F84");return a||Ga({ip:t,email:n,webroot:o,stateDir:Jt+"/state",challengePort:80,relayPort:r,confirmPublicIp:!0}),{publicIp:t,domain:a,relayPort:r,email:n,challengeMode:i,webroot:o,webrootAuto:s,url:"https://"+(a||(Bc(t)===6?"["+t+"]":t))+":"+r}}function wh(e){return new Promise((t,a)=>{let r=gh(new URL("/",e),{timeout:15e3},n=>{let i="";n.on("data",s=>{i+=s,i.length>4096&&r.destroy(new Error("\u4E2D\u7EE7\u5065\u5EB7\u54CD\u5E94\u5F02\u5E38"))}),n.on("end",()=>n.statusCode===404&&i==="Link \u8DEF\u5F84\u672A\u6388\u6743"?t():a(new Error("\u516C\u7F51 TLS \u53EF\u8FDE\u63A5\uFF0C\u4F46\u670D\u52A1\u8EAB\u4EFD\u54CD\u5E94\u4E0D\u7B26"))),n.on("error",a)});r.on("error",a),r.on("timeout",()=>r.destroy(new Error("\u516C\u7F51 TLS \u68C0\u67E5\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u4E2D\u7EE7\u7AEF\u53E3\u548C\u5B89\u5168\u7EC4"))),r.end()})}function xh(e,t){let a=Buffer.from(JSON.stringify(e)).toString("base64");return`set -eu
62
+ [ "$(id -u)" = 0 ] || { echo '\u9700\u8981 root \u6216\u514D\u5BC6 sudo'; exit 1; }
63
+ command -v systemctl >/dev/null
64
+ systemctl show-environment >/dev/null
65
+ command -v python3 >/dev/null
66
+ NODE=$(command -v node)
67
+ case "$NODE" in /root/*|/home/*) echo "\u8BF7\u5148\u5C06 Node 22+ \u5B89\u88C5\u5230\u7CFB\u7EDF\u8DEF\u5F84\uFF0C\u518D\u90E8\u7F72\u72EC\u7ACB\u4E2D\u7EE7\u670D\u52A1"; exit 1;; esac
68
+ node -e 'if(Number(process.versions.node.split(".")[0])<22)process.exit(1)'
69
+ ROOT=${Pe(Jt)}
70
+ MARKER=${Pe(_r)}
71
+ if [ -e "$ROOT" ]; then [ ! -L "$ROOT" ] && [ "$(cat "$ROOT/.managed" 2>/dev/null)" = "$MARKER" ] || { echo '\u76EE\u6807\u76EE\u5F55\u975E\u672C\u5DE5\u5177\u6240\u6709\uFF0C\u62D2\u7EDD\u63A5\u7BA1'; exit 1; }; fi
72
+ for unit in benchgo-relay.service benchgo-relay-challenge.service benchgo-relay-cert-renew.service benchgo-relay-cert-renew.timer; do
73
+ if [ -e "/etc/systemd/system/$unit" ] || [ -L "/etc/systemd/system/$unit" ]; then [ ! -L "/etc/systemd/system/$unit" ] && [ "$(head -n 1 "/etc/systemd/system/$unit")" = "$MARKER" ] || { echo '\u5DF2\u6709\u540C\u540D\u5355\u5143\uFF0C\u62D2\u7EDD\u8986\u76D6'; exit 1; }; fi
74
+ done
75
+ mkdir -p "$ROOT"
76
+ printf '%s\\n' "$MARKER" > "$ROOT/.managed"
77
+ chmod 711 "$ROOT"
78
+ id benchgo-relay >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin benchgo-relay
79
+ cp ${Pe(t+"/run-relay-server.cjs")} "$ROOT/run-relay-server.cjs"
80
+ cp ${Pe(t+"/ip-certificate.mjs")} "$ROOT/ip-certificate.mjs"
81
+ chmod 644 "$ROOT/run-relay-server.cjs" "$ROOT/ip-certificate.mjs"
82
+ node --input-type=module - "$ROOT" ${Pe(a)} <<'JS'
83
+ import {writeFileSync} from 'node:fs';
84
+ const [root,data]=process.argv.slice(2);const c=JSON.parse(Buffer.from(data,'base64'));
85
+ writeFileSync(root+'/deploy.json',JSON.stringify(c),{mode:0o600});
86
+ JS
87
+ cd "$ROOT"
88
+ echo 'BENCHGO_STAGE:\u5B89\u88C5\u8BC1\u4E66\u5DE5\u5177'
89
+ if ! python3 -m venv "$ROOT/certbot" 2>"$ROOT/venv-error.log"; then
90
+ PYTHON_VERSION=$(python3 -c 'import sys; print(str(sys.version_info[0])+"."+str(sys.version_info[1]))')
91
+ VENV_PACKAGE="python\${PYTHON_VERSION}-venv"
92
+ command -v apt-get >/dev/null || { echo "\u5F53\u524D\u7CFB\u7EDF\u7F3A\u5C11 Python venv\uFF08ensurepip\uFF09\uFF0C\u4E14\u6CA1\u6709 apt-get\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5B89\u88C5 $VENV_PACKAGE\uFF1B\u8BF7\u624B\u52A8\u5B89\u88C5\u540E\u91CD\u8BD5" >&2; exit 1; }
93
+ echo "BENCHGO_STAGE:\u5B89\u88C5 $VENV_PACKAGE"
94
+ DEBIAN_FRONTEND=noninteractive apt-get update -qq
95
+ DEBIAN_FRONTEND=noninteractive apt-get install -y -q "$VENV_PACKAGE" || DEBIAN_FRONTEND=noninteractive apt-get install -y -q python3-venv
96
+ python3 -m venv "$ROOT/certbot"
97
+ fi
98
+ rm -f "$ROOT/venv-error.log"
99
+ if ! env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy "$ROOT/certbot/bin/pip" install --disable-pip-version-check 'certbot>=5.4,<6' 2>"$ROOT/pip-error.log"; then
100
+ if grep -qi 'SOCKS support' "$ROOT/pip-error.log"; then
101
+ echo '\u68C0\u6D4B\u5230\u8FDC\u7AEF SOCKS \u4EE3\u7406\u7F3A\u5C11 Python \u652F\u6301\uFF0C\u6539\u7528\u76F4\u8FDE\u5B89\u88C5\u8BC1\u4E66\u5DE5\u5177'
102
+ env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy "$ROOT/certbot/bin/pip" install --disable-pip-version-check 'certbot>=5.4,<6'
103
+ else
104
+ cat "$ROOT/pip-error.log" >&2
105
+ exit 1
106
+ fi
107
+ fi
108
+ rm -f "$ROOT/pip-error.log"
109
+ echo 'BENCHGO_STAGE:\u68C0\u67E5\u516C\u7F51\u7AEF\u53E3'
110
+ node --input-type=module - "$ROOT" "$NODE" <<'JS'
111
+ import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';
112
+ import {createServer} from 'node:net';
113
+ import {spawnSync} from 'node:child_process';
114
+ const [root,node]=process.argv.slice(2),c=JSON.parse(readFileSync(root+'/deploy.json'));
115
+ const marker=${JSON.stringify(_r)};
116
+ const unit=(name,value)=>writeFileSync('/etc/systemd/system/'+name,marker+'\\n'+value,{mode:0o644});
117
+ const test=port=>new Promise((ok,bad)=>{const s=createServer();s.once('error',()=>bad(new Error('\u7AEF\u53E3 '+port+' \u5DF2\u5360\u7528\uFF1B\u4E0D\u4F1A\u505C\u6B62\u73B0\u6709\u670D\u52A1')));s.listen(port,'::',()=>s.close(ok));});
118
+ const prior=spawnSync('systemctl',['is-active','--quiet','benchgo-relay.service']).status===0;
119
+ if(!prior)await test(c.relayPort);
120
+ if(c.challengeMode==='standalone'){
121
+ const challengeActive=spawnSync('systemctl',['is-active','--quiet','benchgo-relay-challenge.service']).status===0;
122
+ if(!challengeActive)await test(80);mkdirSync(c.webroot,{recursive:true});
123
+ const script="import http.server,os,socket;os.chdir("+JSON.stringify(c.webroot)+");S=type('S',(http.server.ThreadingHTTPServer,),{'address_family':socket.AF_INET6});S.address_family=socket.AF_INET6;S(('::',80),http.server.SimpleHTTPRequestHandler).serve_forever()";
124
+ writeFileSync(root+'/challenge.py',script,{mode:0o600});
125
+ unit('benchgo-relay-challenge.service','[Service]\\nExecStart=/usr/bin/python3 '+root+'/challenge.py\\nProtectSystem=strict\\nProtectHome=true\\nNoNewPrivileges=true\\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\\n[Install]\\nWantedBy=multi-user.target\\n');
126
+ }
127
+ JS
128
+ systemctl daemon-reload
129
+ ${e.challengeMode==="standalone"?`CHALLENGE_STARTED=0
130
+ if ! systemctl is-active --quiet benchgo-relay-challenge.service; then
131
+ systemctl enable --now benchgo-relay-challenge.service
132
+ CHALLENGE_STARTED=1
133
+ fi
134
+ cleanup_challenge() {
135
+ code=$?
136
+ if [ "$code" -ne 0 ] && [ "$CHALLENGE_STARTED" = 1 ]; then
137
+ systemctl disable --now benchgo-relay-challenge.service 2>/dev/null || true
138
+ rm -f /etc/systemd/system/benchgo-relay-challenge.service
139
+ systemctl daemon-reload 2>/dev/null || true
140
+ fi
141
+ exit "$code"
142
+ }
143
+ trap cleanup_challenge EXIT`:`WEBROOT=${Pe(e.webroot)}
144
+ if [ "${e.webrootAuto?"1":"0"}" = 1 ]; then
145
+ DETECTED_WEBROOT=$(python3 - ${Pe(e.domain)} <<'PYWEBROOT'
146
+ ${Ch}
147
+ PYWEBROOT
148
+ )
149
+ if [ -n "$DETECTED_WEBROOT" ]; then WEBROOT=$DETECTED_WEBROOT; fi
150
+ if [ ! -d "$WEBROOT" ]; then
151
+ for candidate in "/var/www/${e.domain}" "/var/www/html" "/srv/www/${e.domain}" "/www/server/nginx/html/${e.domain}"; do
152
+ if [ -d "$candidate" ]; then WEBROOT="$candidate"; break; fi
153
+ done
154
+ fi
155
+ fi
156
+ if [ ! -d "$WEBROOT" ] && command -v nginx >/dev/null; then
157
+ WEBROOT="$ROOT/acme-webroot"
158
+ mkdir -p "$WEBROOT/.well-known/acme-challenge"
159
+ NGINX_RELAY_CONF=/www/server/panel/vhost/nginx/benchgo-relay-${e.domain}.conf
160
+ if [ -e "$NGINX_RELAY_CONF" ] && ! grep -q '^# Managed by BenchGo relay deployment v1$' "$NGINX_RELAY_CONF"; then
161
+ echo '\u76EE\u6807\u57DF\u540D\u5DF2\u6709\u672A\u5F52\u5C5E\u7684 Nginx \u914D\u7F6E\uFF0C\u62D2\u7EDD\u8986\u76D6'; exit 1
162
+ fi
163
+ cat > "$NGINX_RELAY_CONF" <<NGINX
164
+ # Managed by BenchGo relay deployment v1
165
+ server {
166
+ listen 80;
167
+ listen [::]:80;
168
+ server_name ${e.domain};
169
+ root $WEBROOT;
170
+ location ^~ /.well-known/acme-challenge/ { try_files \\$uri =404; }
171
+ location / { return 404; }
172
+ }
173
+ NGINX
174
+ nginx -t >/dev/null && (systemctl reload nginx 2>/dev/null || service nginx reload 2>/dev/null)
175
+ fi
176
+ if ! command -v nginx >/dev/null && ! command -v apache2 >/dev/null && ! command -v httpd >/dev/null && ! command -v caddy >/dev/null; then
177
+ WEBROOT="$ROOT/challenge"
178
+ mkdir -p "$WEBROOT"
179
+ cat > /etc/systemd/system/benchgo-relay-challenge.service <<CHALLENGE
180
+ # Managed by BenchGo relay deployment v1
181
+ [Service]
182
+ ExecStart=/usr/bin/python3 -m http.server 80 --bind :: --directory $WEBROOT
183
+ Restart=on-failure
184
+ CHALLENGE
185
+ systemctl daemon-reload
186
+ systemctl enable --now benchgo-relay-challenge.service || { echo '80 \u7AEF\u53E3\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5B8C\u6210\u57DF\u540D\u8BC1\u4E66\u9A8C\u8BC1'; exit 1; }
187
+ fi
188
+ test -d "$WEBROOT" || { echo '\u672A\u627E\u5230\u57DF\u540D\u7AD9\u70B9 webroot\uFF0C\u8BF7\u586B\u5199\u5B9D\u5854/Nginx/Apache/Caddy \u7684\u7AD9\u70B9\u6839\u76EE\u5F55'; exit 1; }
189
+ test -w "$WEBROOT" || { echo '\u57DF\u540D\u7AD9\u70B9 webroot \u4E0D\u53EF\u5199\uFF0C\u8BF7\u68C0\u67E5 SSH \u7528\u6237\u6743\u9650'; exit 1; }
190
+ mkdir -p "$WEBROOT/.well-known/acme-challenge"
191
+ test -w "$WEBROOT/.well-known/acme-challenge" || { echo '\u57DF\u540D\u7AD9\u70B9 challenge \u76EE\u5F55\u4E0D\u53EF\u5199'; exit 1; }
192
+ if [ "$WEBROOT" != ${Pe(e.webroot)} ]; then
193
+ node --input-type=module - "$ROOT" "$WEBROOT" <<'JS'
194
+ import {readFileSync,writeFileSync} from 'node:fs';
195
+ const [root,webroot]=process.argv.slice(2), config=JSON.parse(readFileSync(root+'/deploy.json'));
196
+ config.webroot=webroot; writeFileSync(root+'/deploy.json',JSON.stringify(config),{mode:0o600});
197
+ JS
198
+ fi
199
+ CHALLENGE_FILE="$WEBROOT/.well-known/acme-challenge/.benchgo-${yi(8).toString("hex")}"
200
+ printf '%s' 'benchgo-http01-check' > "$CHALLENGE_FILE"
201
+ cleanup_webroot() { rm -f "$CHALLENGE_FILE"; }
202
+ trap cleanup_webroot EXIT
203
+ if ! command -v curl >/dev/null; then echo '\u57DF\u540D\u6A21\u5F0F\u9700\u8981 curl \u68C0\u67E5\u73B0\u6709\u7F51\u7AD9\u7684 challenge \u8DEF\u5F84'; exit 1; fi
204
+ if ! env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy curl --fail --silent --show-error --location --insecure --max-time 10 -H ${Pe("Host: "+e.domain)} http://127.0.0.1/.well-known/acme-challenge/$(basename "$CHALLENGE_FILE") | grep -Fx 'benchgo-http01-check' >/dev/null; then
205
+ echo '\u57DF\u540D\u7684 webroot \u672A\u88AB\u73B0\u6709\u7F51\u7AD9\u6620\u5C04\uFF0C\u65E0\u6CD5\u901A\u8FC7 HTTP-01 \u9A8C\u8BC1\uFF1B\u8BF7\u68C0\u67E5\u5B9D\u5854\u7AD9\u70B9\u6839\u76EE\u5F55\u548C 80 \u7AEF\u53E3'; exit 1
206
+ fi`}
207
+ echo 'BENCHGO_STAGE:\u7533\u8BF7\u516C\u7F51\u8BC1\u4E66'
208
+ env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy node "$ROOT/ip-certificate.mjs" issue --state-dir "$ROOT/state" ${e.domain?"--domain "+Pe(e.domain):"--ip "+Pe(e.publicIp)} ${e.email?"--email "+Pe(e.email):""} --webroot "$WEBROOT" --challenge-port 80 --relay-port ${e.relayPort} --confirm-public-ip true --certbot "$ROOT/certbot/bin/certbot"
209
+ echo 'BENCHGO_STAGE:\u914D\u7F6E\u5E76\u542F\u52A8\u4E2D\u7EE7'
210
+ node --input-type=module - "$ROOT" "$NODE" <<'JS'
211
+ import {readFileSync,writeFileSync} from 'node:fs';
212
+ const [root,node]=process.argv.slice(2),c=JSON.parse(readFileSync(root+'/deploy.json'));
213
+ const marker=${JSON.stringify(_r)};
214
+ const unit=(name,value)=>writeFileSync('/etc/systemd/system/'+name,marker+'\\n'+value,{mode:0o644});
215
+ const certDir=root+'/service-certs';
216
+ writeFileSync(root+'/relay.json',JSON.stringify({host:c.publicIp.includes(':')?'::':'0.0.0.0',port:c.relayPort,publicUrl:c.url,token:c.token,keyFile:certDir+'/privkey.pem',certFile:certDir+'/fullchain.pem'}),{mode:0o600});
217
+ const publish="import {copyFileSync,chmodSync,chownSync,renameSync} from 'node:fs';import {spawnSync} from 'node:child_process';const [root]=process.argv.slice(2),src=root+'/state/dsh-link-ip-certificate/active/',dst=root+'/service-certs/';for(const n of ['fullchain.pem','privkey.pem']){const t=dst+'.'+n+'.tmp';copyFileSync(src+n,t);chmodSync(t,n==='privkey.pem'?0o600:0o644);const r=spawnSync('chown',['benchgo-relay:benchgo-relay',t]);if(r.status!==0)throw new Error('\u8BC1\u4E66\u6743\u9650\u8BBE\u7F6E\u5931\u8D25');renameSync(t,dst+n)}";
218
+ import {mkdirSync} from 'node:fs';mkdirSync(certDir,{recursive:true,mode:0o755});writeFileSync(root+'/publish-cert.mjs',publish,{mode:0o600});
219
+ unit('benchgo-relay.service','[Unit]\\nAfter=network-online.target\\n[Service]\\nUser=benchgo-relay\\nExecStart='+node+' '+root+'/run-relay-server.cjs --config '+root+'/relay.json\\nRestart=on-failure\\nRestartSec=5\\nUMask=0077\\nNoNewPrivileges=true\\nCapabilityBoundingSet=\\nProtectSystem=strict\\nProtectHome=true\\nPrivateTmp=true\\n[Install]\\nWantedBy=multi-user.target\\n');
220
+ const args=['renew','--state-dir',root+'/state',...(c.domain?['--domain',c.domain]:['--ip',c.publicIp]),...(c.email?['--email',c.email]:[]),'--webroot',c.webroot,'--challenge-port','80','--relay-port',String(c.relayPort),'--confirm-public-ip','true','--certbot',root+'/certbot/bin/certbot'];
221
+ // Shell quoting then systemd escaping is unnecessary: persist a fixed script with JSON argv.
222
+ writeFileSync(root+'/renew.mjs',"import {spawnSync} from 'node:child_process';import {existsSync,writeFileSync,unlinkSync} from 'node:fs';const pending="+JSON.stringify(root+'/renew-pending')+";const env=Object.fromEntries(Object.entries(process.env).filter(([k])=>!/^(?:HTTP|HTTPS|ALL)_PROXY$|^(?:http|https|all)_proxy$/.test(k)));const r=spawnSync(process.execPath,"+JSON.stringify([root+'/ip-certificate.mjs',...args])+",{encoding:'utf8',env});if(r.status!==0){process.stderr.write(r.stderr||'\u8BC1\u4E66\u7EED\u671F\u5931\u8D25');process.exit(1)};process.stdout.write(r.stdout);const changed=JSON.parse(r.stdout.trim()).changed;if(changed||existsSync(pending)){writeFileSync(pending,'1',{mode:0o600});const p=spawnSync(process.execPath,["+JSON.stringify(root+'/publish-cert.mjs')+","+JSON.stringify(root)+"],{stdio:'inherit'});if(p.status!==0)process.exit(1);const s=spawnSync('systemctl',['try-restart','benchgo-relay.service'],{stdio:'inherit'});if(s.status!==0)process.exit(s.status??1);unlinkSync(pending)}",{mode:0o600});
223
+ unit('benchgo-relay-cert-renew.service','[Service]\\nType=oneshot\\nUMask=0077\\nExecStart='+node+' '+root+'/renew.mjs\\n');
224
+ unit('benchgo-relay-cert-renew.timer','[Timer]\\nOnCalendar=daily\\nRandomizedDelaySec=1h\\nPersistent=true\\n[Install]\\nWantedBy=timers.target\\n');
225
+ JS
226
+ mkdir -p "$ROOT/service-certs"
227
+ node "$ROOT/publish-cert.mjs" "$ROOT"
228
+ chown benchgo-relay:benchgo-relay "$ROOT/relay.json"
229
+ systemctl daemon-reload
230
+ systemctl enable --now benchgo-relay-cert-renew.timer
231
+ systemctl enable benchgo-relay.service
232
+ systemctl restart benchgo-relay.service
233
+ systemctl is-active --quiet benchgo-relay.service
234
+ `}async function _c({client:e,input:t,execute:a,upload:r,assets:n,step:i,onRelay:s,verify:o=wh}){let c=gi(t),l=yi(32).toString("base64url");if(c.domain){let[d,p]=await Promise.all([vh(c.domain).catch(()=>[]),mh(c.domain).catch(()=>[])]),E=[...d,...p];if(!E.length||E.some(b=>b!==c.publicIp))throw new Error("\u57DF\u540D DNS \u672A\u89E3\u6790\u5230\u670D\u52A1\u5668\u516C\u7F51 IP\uFF0C\u6216\u5B58\u5728\u6307\u5411\u5176\u4ED6\u670D\u52A1\u5668\u7684\u8BB0\u5F55\uFF0C\u8BF7\u5148\u5B8C\u6210\u89E3\u6790\u540E\u91CD\u8BD5")}let u=await a(e,'if [ "$(id -u)" = 0 ]; then bash -s; else sudo -n bash -s; fi',{stdin:"if [ ! -L "+Pe(Jt)+' ] && [ "$(cat '+Pe(Jt+"/.managed")+' 2>/dev/null)" = '+Pe(_r)+" ] && [ -f "+Pe(Jt+"/relay.json")+" ]; then cat "+Pe(Jt+"/relay.json")+"; fi"});if(u.code!==0)throw new Error("\u9700\u8981 root \u6216\u514D\u5BC6 sudo \u624D\u80FD\u90E8\u7F72\u4E2D\u7EE7");if(u.stdout.trim()){let d;try{d=JSON.parse(u.stdout)}catch{throw new Error("\u73B0\u6709\u4E2D\u7EE7\u914D\u7F6E\u635F\u574F\uFF0C\u8BF7\u5148\u68C0\u67E5\u670D\u52A1\u5668")}if(d.publicUrl!==c.url)throw new Error("\u73B0\u6709\u4E2D\u7EE7\u5730\u5740\u4E0D\u540C\uFF0C\u8BF7\u5148\u5378\u8F7D\u539F\u4E2D\u7EE7");if(!/^[A-Za-z0-9_-]{6,256}$/.test(d.token??""))throw new Error("\u73B0\u6709\u4E2D\u7EE7\u8EAB\u4EFD\u65E0\u6548");l=d.token}let f=yi(16).toString("hex"),h=await a(e,"umask 077; mktemp -d /tmp/benchgo-relay-"+f+"-XXXXXX"),m=h.stdout.trim();if(h.code!==0||!new RegExp("^/tmp/benchgo-relay-"+f+"-[A-Za-z0-9]+$").test(m))throw new Error("\u65E0\u6CD5\u5EFA\u7ACB\u4E2D\u7EE7\u4E34\u65F6\u76EE\u5F55");try{i("\u4E0A\u4F20\u4E2D\u7EE7\u4E0E\u8BC1\u4E66\u5DE5\u5177");for(let E of["run-relay-server.cjs","ip-certificate.mjs"])await r(e,Eh(n,E),m+"/"+E);i("\u68C0\u67E5\u7AEF\u53E3\u3001\u7533\u8BF7\u516C\u7F51\u8BC1\u4E66\u5E76\u5B89\u88C5\u670D\u52A1");let d="",p=await a(e,'if [ "$(id -u)" = 0 ]; then bash -s; else sudo -n bash -s; fi',{stdin:xh({...c,token:l},m),timeout:1500*1e3,onData:E=>{d+=E;let b=d.split(/\r?\n/);d=b.pop()??"";for(let N of b)N.startsWith("BENCHGO_STAGE:")&&i(N.slice(14))}});if(p.code!==0)throw new Error((p.stderr||p.stdout||"\u4E2D\u7EE7\u90E8\u7F72\u5931\u8D25").split(l).join("[redacted]").slice(-3e3));i("\u9A8C\u8BC1\u516C\u7F51\u53EF\u4FE1 TLS"),await o(c.url),i("\u63A5\u5165\u672C\u673A Link");try{await s({...c,token:l})}catch{throw new Error("\u4E2D\u7EE7\u670D\u52A1\u53CA\u53EF\u4FE1 TLS \u5DF2\u90E8\u7F72\uFF0C\u4F46\u672C\u673A\u63A5\u5165\u5931\u8D25\uFF1B\u8BF7\u4FEE\u6B63\u672C\u673A\u914D\u7F6E\u540E\u91CD\u8BD5\u90E8\u7F72")}return{relay:{url:c.url,publicIp:c.publicIp,port:c.relayPort,tls:"verified",host:"pending"}}}finally{await a(e,"rm -rf -- "+Pe(m),{timeout:1e4}).catch(()=>{})}}function Nc(e){let t="set -eu; ROOT="+Pe(Jt)+'; [ ! -L "$ROOT" ] && [ "$(cat "$ROOT/.managed")" = '+Pe(_r)+" ]; ",a={status:"systemctl is-active benchgo-relay.service",logs:"journalctl -u benchgo-relay.service -n 80 --no-pager -o cat",start:"systemctl start benchgo-relay.service",stop:"systemctl stop benchgo-relay.service",restart:"systemctl restart benchgo-relay.service",renew:"systemctl start benchgo-relay-cert-renew.service","renew-status":"systemctl is-active benchgo-relay-cert-renew.timer",diagnose:'printf "service=%s\\n" "$(systemctl is-active benchgo-relay.service || true)"; printf "renew_timer=%s\\n" "$(systemctl is-active benchgo-relay-cert-renew.timer || true)"; printf "port=%s\\n" "$(node -e "const c=require("fs").readFileSync("/opt/benchgo-relay/relay.json","utf8"); process.stdout.write(JSON.parse(c).port+"\\n")" 2>/dev/null || true)"; systemctl --no-pager --failed --type=service || true'};if(Object.hasOwn(a,e))return t+a[e];if(e!=="uninstall")throw new Error("\u4E0D\u652F\u6301\u7684\u4E2D\u7EE7\u64CD\u4F5C");return t+`for unit in benchgo-relay.service benchgo-relay-challenge.service benchgo-relay-cert-renew.service benchgo-relay-cert-renew.timer; do if [ -e "/etc/systemd/system/$unit" ] || [ -L "/etc/systemd/system/$unit" ]; then [ ! -L "/etc/systemd/system/$unit" ] && [ "$(head -n 1 "/etc/systemd/system/$unit")" = ${Pe(_r)} ]; fi; done; for unit in benchgo-relay.service benchgo-relay-challenge.service benchgo-relay-cert-renew.timer; do systemctl disable --now "$unit" 2>/dev/null || true; done; rm -f /etc/systemd/system/benchgo-relay.service /etc/systemd/system/benchgo-relay-challenge.service /etc/systemd/system/benchgo-relay-cert-renew.service /etc/systemd/system/benchgo-relay-cert-renew.timer; systemctl daemon-reload; rm -rf -- "$ROOT"`}var{Client:Dh}=Rh,Ph=e=>"SHA256:"+Sh("sha256").update(e).digest("base64").replace(/=+$/,""),za=e=>"'"+String(e).replaceAll("'","'\\''")+"'";function kr(e,{credentials:t=!1}={}){let a=typeof e?.host=="string"?e.host.trim().replace(/^\[|\]$/g,""):"",r=typeof e?.username=="string"?e.username.trim():"",n=e?.port===void 0||e.port===""?22:Number(e.port);if(!a||a.length>253||!(kh(a)||/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(a)))throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u670D\u52A1\u5668 IP \u6216\u57DF\u540D");if(!Number.isInteger(n)||n<1||n>65535)throw new Error("SSH \u7AEF\u53E3\u5FC5\u987B\u4E3A 1\u201365535");if(!r||r.length>64||/[\x00-\x20\x7f]/.test(r))throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684 SSH \u7528\u6237\u540D");if(t&&!/^SHA256:[A-Za-z0-9+/]{43}$/.test(e.fingerprint??""))throw new Error("\u8BF7\u5148\u786E\u8BA4\u670D\u52A1\u5668 SSH \u6307\u7EB9");if(t&&!e.password&&!e.privateKey)throw new Error("\u8BF7\u8F93\u5165 SSH \u5BC6\u7801\u6216\u79C1\u94A5");for(let s of["password","privateKey","passphrase"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].length>(s==="privateKey"?65536:4096)))throw new Error("SSH \u8BA4\u8BC1\u4FE1\u606F\u65E0\u6548");let i=e.source??"mirror";if(!["mirror","github"].includes(i))throw new Error("\u4E0D\u652F\u6301\u7684\u4E0B\u8F7D\u6E90");return{host:a,port:n,username:r,source:i}}var mi=e=>({id:e.id,name:e.name,kind:"ssh",url:e.url,pin:e.pin,token:e.token,status:e.status,ssh:e.ssh,...e.warning?{warning:e.warning}:{},...e.lastError?{lastError:e.lastError}:{}}),Uh=e=>({id:e.id,name:e.name,kind:"ssh",url:e.url,status:e.status,...e.warning?{warning:e.warning}:{},...e.lastError?{lastError:e.lastError}:{}});function na(e,t=[]){let a=String(e).replace(/([?&](?:token|code)=)[^\s&]+/gi,"$1[redacted]").replace(/(Bearer\s+)[A-Za-z0-9._-]+/gi,"$1[redacted]").replace(/("(?:password|passphrase|privateKey|token)"\s*:\s*")[^"]*/gi,"$1[redacted]");for(let r of t.filter(Boolean))a=a.split(r).join("[redacted]");return a.slice(-12e3)}var Lc=e=>/host denied|hostkey|fingerprint/i.test(e?.message??"")?"SSH \u4E3B\u673A\u6307\u7EB9\u4E0D\u5339\u914D\uFF0C\u5DF2\u963B\u6B62\u8BA4\u8BC1":/authentication|auth|password/i.test(e?.message??"")?"SSH \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u540D\u3001\u5BC6\u7801\u6216\u79C1\u94A5":/timed out|timeout/i.test(e?.message??"")?"SSH \u8FDE\u63A5\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u5730\u5740\u548C\u7F51\u7EDC":e?.message??"\u670D\u52A1\u5668\u8FDE\u63A5\u5931\u8D25";function Oh(e,t,a=!1){return new Promise((r,n)=>{let i=t(),s=!1,o=!1,c=(f,h)=>{s||(s=!0,clearTimeout(l),f?n(f):r(h))},l=setTimeout(()=>{i.destroy(),c(new Error("SSH \u8FDE\u63A5\u8D85\u65F6"))},25e3);l.unref?.(),i.on("error",f=>c(new Error(o?"SSH \u4E3B\u673A\u6307\u7EB9\u4E0D\u5339\u914D\uFF0C\u5DF2\u963B\u6B62\u8BA4\u8BC1":Lc(f)))),i.on("close",()=>{s||c(new Error("SSH \u8FDE\u63A5\u5DF2\u5173\u95ED"))}),i.on("ready",()=>c(null,i));let u=kr(e,{credentials:!a});try{i.connect({...u,readyTimeout:2e4,keepaliveInterval:15e3,keepaliveCountMax:3,...a?{authHandler:()=>!1}:{password:e.password,privateKey:e.privateKey,passphrase:e.passphrase,authHandler:e.privateKey?["publickey"]:["password","keyboard-interactive"],tryKeyboard:!!e.password},hostVerifier(f){let h=Ph(f);return a?(c(null,{fingerprint:h}),queueMicrotask(()=>i.destroy()),!1):(o=h!==e.fingerprint,!o)}}),!a&&e.password&&i.on("keyboard-interactive",(f,h,m,d,p)=>p(d.map(()=>e.password)))}catch(f){i.destroy(),c(f)}})}async function Nr(e,t,{timeout:a=6e4,stdin:r,maximum:n=2*1024*1024,onData:i}={}){return new Promise((s,o)=>{e.exec(t,(c,l)=>{if(c){o(c);return}let u="",f="",h=!1,m=(E,b)=>{h||(h=!0,clearTimeout(d),E?o(E):s(b))},d=setTimeout(()=>{l.close(),m(new Error("\u670D\u52A1\u5668\u64CD\u4F5C\u8D85\u65F6"))},a);d.unref?.();let p=(E,b)=>{let N=E+b;return Buffer.byteLength(N)>n&&(l.close(),m(new Error("\u670D\u52A1\u5668\u8FD4\u56DE\u5185\u5BB9\u8FC7\u5927"))),N};l.on("data",E=>{u=p(u,E),i?.(E.toString(),"stdout")}),l.stderr.on("data",E=>{f=p(f,E),i?.(E.toString(),"stderr")}),l.once("error",E=>m(E)),l.once("close",E=>m(null,{code:E,stdout:u,stderr:f})),l.end(r)})})}async function Rc(e,t,a){let r=await new Promise((n,i)=>e.sftp((s,o)=>s?i(s):n(o)));try{await new Promise((n,i)=>r.fastPut(t,a,{mode:384},s=>s?i(s):n()))}finally{r.end()}}async function Vh(e,t){if(!Number.isInteger(t)||t<1||t>65535)throw new Error("\u670D\u52A1\u5668\u7AEF\u53E3\u65E0\u6548");let a=new Set,r=Nh(n=>{a.add(n),n.on("error",()=>{}),n.on("close",()=>a.delete(n)),e.forwardOut("127.0.0.1",n.localPort||0,"127.0.0.1",t,(i,s)=>{if(i||n.destroyed){s?.destroy(),n.destroy();return}s.on("error",()=>n.destroy()),n.on("close",()=>s.destroy()),s.on("close",()=>n.destroy()),n.pipe(s).pipe(n)})});return await new Promise((n,i)=>{r.once("error",i),r.listen(0,"127.0.0.1",n)}),{url:"https://127.0.0.1:"+r.address().port,close:async()=>{for(let n of a)n.destroy();await new Promise(n=>r.close(n))}}}async function Kh(e){let t=lr(e);try{let{value:a,headers:r}=await ur(e,"/link/api/workbench",{},{agent:t}),n=r["set-cookie"]?.find(i=>i.startsWith("dsh_link_workbench="))?.split(";")[0];if(a?.url!=="/link/workbench/"||!n)throw new Error("\u670D\u52A1\u5668\u672A\u8FD4\u56DE\u6709\u6548\u5DE5\u4F5C\u53F0\u6388\u6743");await new Promise((i,s)=>{let o=Lh(new URL("/link/workbench/",e.url),{agent:t,timeout:2e4,headers:{cookie:n}},c=>{let l=0;c.on("data",u=>{l+=u.length,l>2097152&&o.destroy(new Error("\u670D\u52A1\u5668\u5DE5\u4F5C\u53F0\u54CD\u5E94\u8FC7\u5927"))}),c.once("error",s),c.once("end",()=>c.statusCode===200&&/text\/html/i.test(c.headers["content-type"]??"")&&l>0?i():s(new Error("\u670D\u52A1\u5668\u5DE5\u4F5C\u53F0\u5C1A\u672A\u5C31\u7EEA")))});o.once("error",s),o.once("timeout",()=>o.destroy(new Error("\u670D\u52A1\u5668\u5DE5\u4F5C\u53F0\u9A8C\u8BC1\u8D85\u65F6"))),o.end()})}finally{t.destroy()}}function Dc({directory:e,onDevice:t=async()=>{},runtimeRoot:a,assetsRoot:r,relayAssetsRoot:n,onRelay:i=async()=>{throw new Error("\u672C\u673A\u4E2D\u7EE7\u63A5\u5165\u672A\u914D\u7F6E")},clientFactory:s=()=>new Dh}={}){if(!e)throw new Error("\u670D\u52A1\u5668\u7BA1\u7406\u76EE\u5F55\u672A\u914D\u7F6E");let o=new Set,c=aa(e,"servers.json"),l=new Map,u=new Map,f=new Map,h=new Set,m=Promise.resolve(),d=!1,p=r??(a?a instanceof URL?$a(a):a:$a(new URL("../../../dist/server/",import.meta.url))),E=Th(e,{recursive:!0,mode:448}).then(async()=>{try{for(let w of JSON.parse(await Ih(c,"utf8")))w.kind==="ssh"&&w.ssh?.host&&w.id&&l.set(w.id,{...w,status:"offline"})}catch(w){if(w.code!=="ENOENT")throw w}});function b(){let w=JSON.stringify([...l.values()].map(k=>({...mi(k),url:"",status:"offline"}))),C=m.then(async()=>{let k=c+"."+vi()+".tmp";try{await _h(k,w,{mode:384}),await Ah(k,c)}finally{await Bh(k,{force:!0})}});return m=C.catch(()=>{}),C}let N=()=>{if(d)throw new Error("\u670D\u52A1\u5668\u7BA1\u7406\u5DF2\u5173\u95ED")},T=async(w,C=!1)=>{let k=await Oh(w,()=>{let D=s();return o.add(D),D.once("close",()=>o.delete(D)),D},C);return N(),k};async function S(w,C,k){let D=bh(16).toString("hex"),L='umask 077; directory="$HOME/.cache/benchgo-bootstrap-'+D+`"; mkdir -p -- "$directory"; printf "%s
235
+ " "$directory"`,R=await Nr(w,L),M=R.stdout.trim();if(R.code!==0||!M.startsWith("/")||/[\r\n\0]/.test(M)||!M.endsWith("benchgo-bootstrap-"+D))throw new Error("\u65E0\u6CD5\u521B\u5EFA\u670D\u52A1\u5668\u5B89\u88C5\u76EE\u5F55");try{for(let q of["bootstrap.sh","bootstrap.mjs","manifest.json","server-seed.tar.gz"])await Rc(w,aa(p,q),M+"/"+q);let z=await Nr(w,"bash "+za(M+"/bootstrap.sh")+" "+za(C.source??"mirror")+" "+za(k),{timeout:1200*1e3});if(z.code!==0)throw new Error(na(z.stderr||"\u670D\u52A1\u5668\u5B89\u88C5\u5931\u8D25",[C.password,C.privateKey,C.passphrase]));let V;try{V=JSON.parse(z.stdout.trim().split(/\r?\n/).at(-1))}catch{throw new Error("\u670D\u52A1\u5668\u5B89\u88C5\u5668\u672A\u8FD4\u56DE\u6709\u6548\u7ED3\u679C")}if(!Number.isInteger(V.port)||V.port<1||V.port>65535||!/^[A-Za-z0-9+/]{43}=$/.test(V.pin??"")||k!=="update"&&!/^[A-Za-z0-9_-]{20,256}$/.test(V.token??""))throw new Error("\u670D\u52A1\u5668\u6388\u6743\u7ED3\u679C\u65E0\u6548");return V}finally{await Nr(w,"rm -rf -- "+za(M),{timeout:1e4}).catch(()=>{})}}function I(w,C="server"){if(N(),f.size>=64){for(let[L,R]of f)if(R.state!=="running"&&f.delete(L),f.size<32)break}let k={id:vi(),kind:C,state:"running",steps:[{name:"\u8FDE\u63A5 SSH",state:"running"}]};f.set(k.id,k);let D=L=>{for(let R of k.steps)R.state==="running"&&(R.state="done");k.steps.push({name:L,state:"running"})};return Promise.resolve().then(()=>w(k,D)).then(L=>{k.state="done";for(let R of k.steps)R.state==="running"&&(R.state="done");L?.relay?k.relay=L.relay:k.device=Uh(L)}).catch(L=>{k.state="error",k.error=Lc(L);for(let R of k.steps)R.state==="running"&&(R.state="error")}),{jobId:k.id}}async function x(w,C){let k=await Vh(w,C.ssh.remotePort),D=u.get(C.id);try{await Kh({...C,url:k.url}),N()}catch(M){throw await k.close(),M}let L={client:w,tunnel:k};u.set(C.id,L),C.url=k.url,C.status="online",delete C.lastError;let R=()=>{u.get(C.id)===L&&(u.delete(C.id),k.close().catch(()=>{}),C.status="offline",C.lastError="SSH \u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5",Promise.resolve(t(mi(C))).catch(()=>{}))};w.on("error",R),w.on("close",R);try{await t(mi(C)),l.set(C.id,C),await b()}catch(M){throw u.delete(C.id),await k.close(),w.end(),M}return D&&(await D.tunnel.close(),D.client!==w&&D.client.end()),C}return{async relayProbe(w){return this.probe(w)},async deployRelay(w){N(),kr(w,{credentials:!0}),gi(w);let C="relay|"+[w.host,w.port??22,w.username].join("|");if(h.has(C))throw new Error("\u6B64\u4E2D\u7EE7\u6B63\u5728\u90E8\u7F72");return h.add(C),I(async(k,D)=>{let L;try{L=await T(w);let R=n;if(!R){let M=[$a(new URL("../relay/",import.meta.url)),$a(new URL("../../../commander/lib/relay/",import.meta.url)),aa(p,"..","relay")];for(let z of M)try{await kc(aa(z,"run-relay-server.cjs")),await kc(aa(z,"ip-certificate.mjs")),R=z;break}catch{}}if(!R)throw new Error("\u672A\u627E\u5230\u6253\u5305\u7684\u4E2D\u7EE7\u90E8\u7F72\u5DE5\u5177");return await _c({client:L,input:w,execute:Nr,upload:Rc,assets:R,step:D,onRelay:i})}catch(R){throw new Error(na(R.message,[w.password,w.privateKey,w.passphrase]))}finally{L?.end(),h.delete(C)}},"relay")},async manageRelay(w){N(),kr(w,{credentials:!0});let C=Nc(w.operation),k=await T(w);try{let D=await Nr(k,'if [ "$(id -u)" = 0 ]; then bash -s; else sudo -n bash -s; fi',{stdin:C});if(D.code!==0&&!["status","renew-status","diagnose"].includes(w.operation))throw new Error("\u4E2D\u7EE7\u7BA1\u7406\u5931\u8D25\uFF1A"+na(D.stderr,[w.password,w.privateKey,w.passphrase]));return{operation:w.operation,...["status","renew-status"].includes(w.operation)?{status:D.code===0?D.stdout.trim():"inactive"}:{},...w.operation==="logs"||w.operation==="diagnose"?{logs:na(D.stdout+(D.stderr||""))}:{}}}finally{k.end()}},async probe(w){return N(),kr(w),T(w,!0)},async connect(w){N(),await E;let C=kr(w,{credentials:!0}),k=String(w.name||C.host).trim();if(!k||k.length>100)throw new Error("\u8BBE\u5907\u540D\u79F0\u987B\u4E3A 1\u2013100 \u4E2A\u5B57\u7B26");let D=[C.host,C.port,C.username].join("|"),L=[...l.values()].find(R=>[R.ssh.host,R.ssh.port,R.ssh.username].join("|")===D);if(L){if(L.ssh.fingerprint!==w.fingerprint)throw new Error("SSH \u4E3B\u673A\u6307\u7EB9\u5DF2\u6539\u53D8\uFF0C\u5DF2\u4FDD\u7559\u539F\u8FDE\u63A5");return this.reconnect({...w,id:L.id,device:{name:k}})}if(h.has(D))throw new Error("\u6B64\u670D\u52A1\u5668\u6B63\u5728\u8FDE\u63A5");return h.add(D),I(async(R,M)=>{let z;try{z=await T(w),N(),M("\u68C0\u67E5\u4E0E\u5B89\u88C5");let V=await S(z,w,"connect");N(),M("\u9A8C\u8BC1\u5B89\u5168\u5DE5\u4F5C\u53F0");let q=[...l.values()].find(U=>[U.ssh.host,U.ssh.port,U.ssh.username].join("|")===D);return await x(z,{id:q?.id??vi(),name:k,kind:"ssh",pin:V.pin,token:V.token,ssh:{...C,fingerprint:w.fingerprint,remotePort:V.port},...V.warning?{warning:V.warning}:{}})}catch(V){throw z?.end(),V}finally{h.delete(D)}})},async reconnect(w){N(),await E;let C=l.get(w.id);if(C&&w.device?.name&&(C.name=w.device.name),!C)throw new Error("\u672A\u627E\u5230\u6B64\u670D\u52A1\u5668");let k={...C.ssh,password:w.password,privateKey:w.privateKey,passphrase:w.passphrase};return kr(k,{credentials:!0}),I(async(D,L)=>{let R=await T(k);try{return N(),L("\u9A8C\u8BC1\u5B89\u5168\u5DE5\u4F5C\u53F0"),(await new Promise((z,V)=>R.forwardOut("127.0.0.1",0,"127.0.0.1",C.ssh.remotePort,(q,U)=>q?V(q):z(U)))).destroy(),await x(R,{...C})}catch(M){throw R.end(),M}})},async job(w){N();let C=f.get(typeof w=="string"?w:w?.id);if(!C)throw new Error("\u4EFB\u52A1\u5DF2\u8FC7\u671F");return structuredClone(C)},activeRelayJob(){N();let w=[...f.values()].reverse().find(C=>C.kind==="relay");return w?structuredClone(w):null},dismissRelayJob(w){N();let C=f.get(w);if(!C||C.kind!=="relay")return{ok:!0};if(C.state==="running")throw new Error("\u90E8\u7F72\u4ECD\u5728\u8FDB\u884C\uFF0C\u6682\u65F6\u4E0D\u80FD\u5173\u95ED\u4EFB\u52A1");return f.delete(w),{ok:!0}},async manage(w){N(),await E;let C=l.get(w.id),k=u.get(w.id);if(C&&w.device?.name&&(C.name=w.device.name),!C||!k)throw new Error("\u8BF7\u5148\u91CD\u65B0\u8FDE\u63A5\u670D\u52A1\u5668");let D=w.operation;if(D==="update")return I(async(z,V)=>{V("\u5347\u7EA7 BenchGo");let q=await S(k.client,{source:C.ssh.source},"update");return x(k.client,{...C,pin:q.pin,token:q.token??C.token,ssh:{...C.ssh,remotePort:q.port}})});let L='export XDG_RUNTIME_DIR="/run/user/$(id -u)"; export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"; ',R={status:"systemctl --user is-active benchgo.service",start:"systemctl --user start benchgo.service",stop:"systemctl --user stop benchgo.service",restart:"systemctl --user restart benchgo.service",logs:"journalctl --user -u benchgo.service --no-pager -n 80 -o cat"};if(!Object.hasOwn(R,D))throw new Error("\u4E0D\u652F\u6301\u7684\u670D\u52A1\u5668\u64CD\u4F5C");let M=await Nr(k.client,L+R[D]);if(M.code!==0&&D!=="status")throw new Error("\u670D\u52A1\u5668\u670D\u52A1\u64CD\u4F5C\u5931\u8D25");return{operation:D,status:D==="status"?M.stdout.trim():D==="stop"?"stopped":void 0,...D==="logs"?{logs:na(M.stdout)}:{}}},async disconnect(w){await E;let C=u.get(w);u.delete(w),C&&(await C.tunnel.close(),C.client.end()),l.delete(w),await b()},async close(){if(!d){d=!0;for(let w of o)w.destroy();await E;for(let w of u.values())await w.tunnel.close(),w.client.end();u.clear(),await m}}}}var Pc=()=>Hh(32).toString("base64url"),Ue=(e,t=400)=>Object.assign(new Error(e),{status:t});function jh(e){let t;try{t=new URL(e)}catch{throw Ue("\u8BF7\u7C98\u8D34\u5B8C\u6574 Link \u914D\u5BF9\u5730\u5740")}let a,r;if(t.protocol==="dshlink:"&&t.hostname==="pair")a=cr({url:t.searchParams.get("url"),pin:t.searchParams.get("pin")}),r=t.searchParams.get("code");else if(t.protocol==="https:"&&!t.username&&!t.password&&t.pathname==="/link/"&&!t.search){a=cr({url:t.origin});let n=new URLSearchParams(t.hash.slice(1));if([...n.keys()].some(i=>i!=="code")||n.getAll("code").length!==1)throw Ue("\u8BF7\u7C98\u8D34\u5B8C\u6574 Link \u914D\u5BF9\u5730\u5740");r=n.get("code")}else throw Ue("\u8BF7\u7C98\u8D34\u5B8C\u6574 Link \u914D\u5BF9\u5730\u5740");if(!r||r.length>256)throw Ue("\u914D\u5BF9\u7801\u65E0\u6548");return{target:a,code:r}}async function $h(e){if(!e.headers["content-type"]?.startsWith("application/json"))throw Ue("\u9700\u8981 application/json",415);let t=0,a=[];for await(let n of e){if(t+=n.length,t>128*1024)throw Ue("\u8BF7\u6C42\u8FC7\u5927",413);a.push(n)}let r=JSON.parse(Buffer.concat(a).toString());if(!r||typeof r!="object"||Array.isArray(r))throw Ue("\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");return r}async function Ei({directory:e,webRoot:t,managerFactory:a=Dc,hostAdmin:r,publicOrigin:n,workbenchOrigin:i,registerProxy:s}){let o=await sc(e),c=new Map,l=new Map,u=new Map,f=new Map,h=new Set,m=new Set,d,p=!1,E=await a({directory:e,onRelay:async S=>{if(typeof r!="function")throw Ue("\u6B64\u5BA2\u6237\u7AEF\u4E0D\u652F\u6301\u914D\u7F6E\u4E3B\u673A\u4E2D\u7EE7");let I=await r({action:"status"}),x=Array.isArray(I.relay?.nodes)?I.relay.nodes:[];await r({action:"relay-pool-configure",nodes:[...x,{id:"relay-"+Date.now().toString(36),url:S.url,token:S.token,priority:x.length,enabled:!0}]})},runtimeRoot:new URL("../server/",t),onDevice:async S=>{if(S.status==="offline"){try{o.mark(S.id,"offline",S.lastError)}catch{}return}let I=l.get(S.id);return I&&(l.delete(S.id),await I.close()),o.upsert(S)}}),b=S=>S.deviceId||S.targetId||S.id,N=async S=>{let I=b(S);if(S.action==="list")return{...o.list(),relayJob:E?.activeRelayJob?.()??null,capabilities:{ssh:!!E,relayDeploy:!!E?.deployRelay&&typeof r=="function",hostAdmin:typeof r=="function"}};let x={hostRelayConfigure:"relay-configure",hostRelayPoolConfigure:"relay-pool-configure",hostStatus:"status",hostConfigure:"configure",hostPairing:"pairing",hostConfirm:"confirm",hostReject:"reject",hostRevoke:"revoke"};if(Object.hasOwn(x,S.action)){if(typeof r!="function")throw Ue("\u6B64\u5BA2\u6237\u7AEF\u4E0D\u652F\u6301\u672C\u673A\u8FDE\u63A5\u7BA1\u7406\uFF0C\u8BF7\u66F4\u65B0\u5E94\u7528");let w={hostRelayConfigure:["url","token","enabled"],hostRelayPoolConfigure:["nodes"],hostStatus:[],hostConfigure:["enabled","host","port","publicUrl"],hostPairing:["mode","address"],hostConfirm:["id"],hostReject:["id"],hostRevoke:["id"]}[S.action];return r({action:x[S.action],...Object.fromEntries(w.filter(C=>Object.hasOwn(S,C)).map(C=>[C,S[C]]))})}if(S.action==="pair"){for(let[L,R]of c)R.expiresAt<Date.now()&&c.delete(L);if(c.size>=16)throw Ue("\u914D\u5BF9\u8BF7\u6C42\u8FC7\u591A");let{target:w,code:C}=jh(S.uri),{value:k}=await ur(w,"/link/api/pair",{code:C,name:S.name||Gh().slice(0,100)}),D=qh();return c.set(D,{...w,remote:k,expiresAt:Math.min(k.expiresAt||Date.now()+3e5,Date.now()+3e5)}),{requestId:D,expiresAt:k.expiresAt}}if(S.action==="pairStatus"){let w=c.get(S.requestId);if(!w||w.expiresAt<Date.now())throw c.delete(S.requestId),Ue("\u914D\u5BF9\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u626B\u7801");if(w.device)return{status:"approved",device:w.device};let{value:C}=await ur(w,"/link/api/pair/status",{requestId:w.remote.requestId,pollToken:w.remote.pollToken});return C.status!=="approved"?{status:C.status}:(w.device=await o.upsert({...w,remote:void 0,token:C.token,routes:C.routes,kind:"computer",name:new URL(w.url).hostname}),{status:"approved",device:w.device})}if(S.action==="select"){if(I==="local")return{device:await o.select(I),url:null};if(n&&!i)throw Ue("\u8BF7\u5148\u914D\u7F6E\u72EC\u7ACB HTTPS \u5DE5\u4F5C\u53F0\u57DF\u540D\uFF0C\u4E91\u7AEF\u8FDE\u63A5\u4E0D\u80FD\u4F7F\u7528\u672C\u673A\u5730\u5740",409);let w=o.get(I),C=await fc(w,{onHealth:(D,L,R)=>o.markRouteHealth(I,D.relayId||D.id||D.url,L,R)}),k=l.get(I);k&&k.routeKey!==`${C.url}|${C.pin||""}`&&(l.delete(I),await k.close(),k=void 0);try{if(!k){let L=n?s():null;try{k=await yc(C,{webRoot:t,...L?{publicOrigin:i,publicPrefix:L.prefix}:{},parentOrigin:[d,n,...h].filter(Boolean).join(" "),onFailure:R=>o.mark(I,"offline",R.message)}),k.routeKey=`${C.url}|${C.pin||""}`,L?.attach(k),l.set(I,k)}catch(R){throw L?.remove(),R}}let D=await k.enter();return o.markRoute(I,C.routes?.find(L=>L.url===C.url&&(L.pin||"")===(C.pin||""))?.kind||"direct"),o.mark(I,"online"),{device:await o.select(I),url:D}}catch(D){throw o.mark(I,"offline",D.message),D}}if(S.action==="rename")return{device:await o.rename(I,S.name)};if(S.action==="remove"){await o.remove(I);let w=l.get(I);return l.delete(I),await w?.close(),await E?.disconnect?.(I),{ok:!0}}if(!E)throw Ue("\u6B64\u5BA2\u6237\u7AEF\u4E0D\u652F\u6301 SSH\uFF0C\u8BF7\u66F4\u65B0\u5E94\u7528");if(S.action==="relayProbe")return E.relayProbe(S);if(S.action==="relayDeploy"){if(typeof r!="function")throw Ue("\u6B64\u5BA2\u6237\u7AEF\u4E0D\u652F\u6301\u914D\u7F6E\u4E3B\u673A\u4E2D\u7EE7");return E.deployRelay(S)}if(S.action==="relayAction")return E.manageRelay(S);if(S.action==="relayJobDismiss")return E.dismissRelayJob(S.jobId);if(S.action==="sshProbe")return E.probe(S);if(S.action==="sshConnect")return E.connect(S);if(S.action==="job")return E.job(S.jobId||S.id);if(S.action==="reconnect")return E.reconnect({...S,id:I,device:o.get(I)});if(S.action==="serverAction")return E.manage({...S,id:I,device:o.get(I)});throw Ue("\u4E0D\u652F\u6301\u7684\u64CD\u4F5C")},T=Fh(async(S,I)=>{let x={"cache-control":"no-store","x-content-type-options":"nosniff","referrer-policy":"no-referrer"};try{if(p||S.headers.host!==new URL(d).host)throw Ue("\u672C\u673A\u8BBE\u5907\u5730\u5740\u65E0\u6548",403);let w=new URL(S.url,d);if(w.pathname==="/enter"&&S.method==="GET"){let R=w.searchParams.get("ticket"),M=u.get(R);if(u.delete(R),!M||M.expires<Date.now())throw Ue("\u8BBE\u5907\u5165\u53E3\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u4ECE\u4FA7\u680F\u91CD\u65B0\u6253\u5F00",401);let z=Pc();f.set(z,M.parentOrigin),f.size>16&&f.delete(f.keys().next().value),M.parentOrigin&&h.add(M.parentOrigin),I.writeHead(303,{...x,location:(n?"/devices":"")+"/s/"+z+"/"}),I.end();return}let C=w.pathname.match(/^\/s\/([A-Za-z0-9_-]{43})(\/.*)$/);if(!C||!f.has(C[1]))throw Ue("\u8BBE\u5907\u4E2D\u5FC3\u672A\u6388\u6743",401);if(w.pathname=C[2],w.pathname==="/device-config.js"&&S.method==="GET"){I.writeHead(200,{...x,"content-type":"text/javascript"}),I.end("globalThis.__DSH_DEVICE_CENTER__=true;globalThis.__DSH_DEVICE_PARENT_ORIGIN__="+JSON.stringify(f.get(C[1]))+";");return}if(S.method==="POST"&&w.pathname==="/api/devices"){if(![d,n].filter(Boolean).includes(S.headers.origin))throw Ue("\u6765\u6E90\u672A\u6388\u6743",403);let R=await N(await $h(S));I.writeHead(200,{...x,"content-type":"application/json"}),I.end(JSON.stringify(R));return}if(S.method!=="GET")throw Ue("\u4E0D\u652F\u6301\u7684\u65B9\u6CD5",405);let k={"/":"index.html","/index.html":"index.html","/app.js":"app.js","/app.css":"app.css"}[w.pathname];if(!k)throw Ue("\u672A\u627E\u5230",404);let D=await Mh(new URL(k,t));k==="index.html"&&(D=Buffer.from(D.toString().replace("<head>",'<head><script src="./device-config.js"></script>')));let L="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-src "+(n?i||"'none'":"http://127.0.0.1:*")+"; connect-src 'self'; frame-ancestors "+[...h,"dsh-app:"].join(" ")+"; base-uri 'none'; form-action 'self'";I.writeHead(200,{...x,"content-type":k.endsWith(".js")?"text/javascript":k.endsWith(".css")?"text/css":"text/html; charset=utf-8","content-security-policy":L}),I.end(D)}catch(w){I.headersSent||I.writeHead(w.status||400,{...x,"content-type":"application/json"}),I.end(JSON.stringify({error:w.message}))}});return T.on("connection",S=>{m.add(S),S.on("close",()=>m.delete(S))}),await new Promise((S,I)=>{T.once("error",I),T.listen(0,"127.0.0.1",S)}),d="http://127.0.0.1:"+T.address().port,{origin:d,api:N,launch(S){for(let[x,w]of u)w.expires<Date.now()&&u.delete(x);let I=Pc();return u.set(I,{expires:Date.now()+6e4,parentOrigin:S}),{url:(n||d)+(n?"/devices":"")+"/enter?ticket="+I}},summary(){return{devices:o.list().devices.map(({id:S,name:I,kind:x,status:w})=>({id:S,name:I,kind:x,status:w}))}},async close(){p=!0,u.clear(),f.clear(),await Promise.all([...l.values()].map(I=>I.close())),await E?.close(),await o.flush();let S=new Promise(I=>T.close(I));m.forEach(I=>I.destroy()),await S}}}import{createHash as Hc,randomBytes as zh}from"node:crypto";import{readFile as Uc,realpath as Oc,stat as Wh}from"node:fs/promises";import{createRequire as Ci}from"node:module";import{dirname as Vc,extname as Qh,join as wi,relative as Yh,resolve as qc,sep as Xh}from"node:path";import{fileURLToPath as Jh}from"node:url";import{Readable as Zh}from"node:stream";import{WebSocketServer as ep}from"ws";var Ot="/link/workbench/",Rr="dsh_link_workbench",tp=300*1024*1024,Kc=720*60*60*1e3,Wa=e=>Hc("sha256").update(e).digest("hex"),Le=(e,t=400)=>Object.assign(new Error(e),{status:t}),Fc={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".json":"application/json",".webmanifest":"application/manifest+json"};function rp(e,t){if(t)return t instanceof URL?Jh(t):qc(t);let a=[e.baseUrl,...Array.from(e.loader?.entries?.()??[],r=>r.parent?.tree?.ctx?.baseUrl)].filter(Boolean);for(let r of a)try{let n=Ci(r);try{return wi(Vc(n.resolve("@deepseek-ai/dsh-web-frontend/package.json")),"dist")}catch{}let i=e.loader?.internal,s="@deepseek-ai/dsh-web-app",o=i?.resolveSync?(i.version==="v2"?i.resolveSync(r,{specifier:s,attributes:{}}):i.resolveSync(s,r,{})).url:Ci(r).resolve(s),c=Ci(o);return wi(Vc(c.resolve("@deepseek-ai/dsh-web-frontend/package.json")),"dist")}catch{}throw Le("\u7F51\u9875\u5DE5\u4F5C\u53F0\u8D44\u6E90\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u5148\u6784\u5EFA\u5B98\u65B9\u7F51\u9875\u524D\u7AEF",503)}async function Gc(e,t=256*1024){let a=[],r=0;for await(let n of e){if(r+=n.length,r>t)throw Le("\u8BF7\u6C42\u8FC7\u5927",413);a.push(n)}return Buffer.concat(a)}async function Mc(e){if(!e.headers["content-type"]?.startsWith("application/json"))throw Le("\u9700\u8981 application/json",415);let t=JSON.parse((await Gc(e)).toString());if(!t||typeof t!="object"||Array.isArray(t))throw Le("\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");return t}async function ia(e,t,a){a.aborted||e.destroyed||e.write(t)||await new Promise(r=>{let n=()=>{e.off("drain",n),e.off("close",n),r()};e.once("drain",n),e.once("close",n)})}function jc(e,t,{webRoot:a,workbenchRoot:r}={}){let n=new Map,i=new Map,s=new ep({noServer:!0,maxPayload:64*1024,perMessageDeflate:!1}),o=!1,c=d=>{let p=d.headers.cookie?.split(";").map(N=>N.trim()).find(N=>N.startsWith(Rr+"="))?.slice(Rr.length+1);if(!p||p.length>128)return;let E=n.get(Wa(p));if(!E)return;let b=t.state.devices.find(N=>N.id===E.id&&N.tokenHash===E.tokenHash);if(!b||E.expires<=Date.now()){n.delete(Wa(p));return}return b.lastSeenAt=Date.now(),b},l=d=>{let p=i.get(d.id);if(!p){if(i.size>=32)throw Le("\u8FDE\u63A5\u8BBE\u5907\u8FC7\u591A",429);p={peer:e.connection.createPeer({principal:{kind:"owner"},interactions:"answer"}),abort:new AbortController,streams:new Map,realtime:new Set},i.set(d.id,p)}return p},u=async d=>{for(let[E,b]of n)b.id===d&&n.delete(E);let p=i.get(d);if(p){i.delete(d),p.abort.abort();for(let E of p.realtime)E.terminate();p.realtime.clear();for(let E of p.streams.values())E.abort.abort(),E.wake?.();await p.peer.dispose()}};return{begin:(d,p)=>{if(o)throw Le("Link \u5DF2\u5173\u95ED",503);for(let[N,T]of n)(T.expires<=Date.now()||!t.state.devices.some(S=>S.id===T.id))&&n.delete(N);let E=[...n].filter(([,N])=>N.id===d.id);for(;E.length>=8;)n.delete(E.shift()[0]);let b=zh(32).toString("base64url");return n.set(Wa(b),{id:d.id,tokenHash:d.tokenHash,expires:Date.now()+Kc}),p.setHeader("set-cookie",Rr+"="+b+"; Path="+Ot+"; HttpOnly; Secure; SameSite=Strict; Max-Age="+Kc/1e3),{url:Ot}},handle:async(d,p,E,b)=>{if(o)throw Le("Link \u5DF2\u5173\u95ED",503);let N=c(d);if(!N){if((d.method==="GET"||d.method==="HEAD")&&(E.pathname===Ot||E.pathname===Ot+"index.html")){p.writeHead(303,{...b,location:"/link/"}),p.end();return}throw Le("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u914D\u5BF9",401)}let T=E.pathname.slice(Ot.length),S=l(N),I=new AbortController,x=AbortSignal.any([S.abort.signal,I.signal]),w=()=>{p.writableEnded||I.abort()};p.once("close",w);let C=()=>{p.writableEnded||p.destroy()};S.abort.signal.addEventListener("abort",C,{once:!0});let k=async D=>{if(p.writeHead(D.status,{...b,...Object.fromEntries(D.headers),"cache-control":"no-store","x-accel-buffering":"no"}),d.method!=="HEAD"&&D.body)for await(let L of D.body)await ia(p,L,x);p.end()};try{if(T==="remote/open"&&d.method==="POST"){let V=await Mc(d);if(typeof V.id!="string"||!/^[a-zA-Z0-9_-]{1,100}$/.test(V.id)||typeof V.endpoint!="string"||!/^[a-zA-Z0-9_$.-]+(?:\/[a-zA-Z0-9_$.-]+)*$/.test(V.endpoint))throw Le("\u6D41\u8BF7\u6C42\u65E0\u6548");if(S.streams.has(V.id)||S.streams.size>=64)throw Le("\u6D3B\u8DC3\u6D41\u8FC7\u591A\u6216\u91CD\u590D",429);let q={abort:new AbortController,items:[],bytes:0,ended:!1,wake:void 0},U=AbortSignal.any([x,q.abort.signal]);S.streams.set(V.id,q);let j={async*[Symbol.asyncIterator](){for(;!U.aborted;)if(q.items.length){let G=q.items.shift();q.bytes-=G.bytes,yield G.value}else{if(q.ended)break;await new Promise(G=>{let Z=()=>{U.removeEventListener("abort",Z),q.wake=void 0,G()};q.wake=Z,U.addEventListener("abort",Z,{once:!0}),U.aborted&&Z()})}}};p.writeHead(200,{...b,"content-type":"application/x-ndjson","x-accel-buffering":"no"}),p.flushHeaders?.(),await ia(p,`{"type":"ready"}
236
+ `,U);let J=setInterval(()=>{!U.aborted&&!p.destroyed&&p.writableLength<65536&&p.write(`{"type":"heartbeat"}
237
+ `)},15e3);J.unref?.();try{let G=await e.typertGateway.wireStream.open(V.endpoint,V.payload,j,S.peer,U);for await(let Z of G)await ia(p,JSON.stringify({type:"item",value:Z})+`
238
+ `,U);await ia(p,`{"type":"end"}
239
+ `,U)}catch(G){U.aborted||await ia(p,JSON.stringify({type:"error",error:e.typertGateway.wireStream.failure(G)})+`
240
+ `,U)}finally{clearInterval(J),q.abort.abort(),q.wake?.(),S.streams.get(V.id)===q&&S.streams.delete(V.id),p.end()}return}if(T==="remote/uplink"&&d.method==="POST"){let V=await Mc(d),q=S.streams.get(V.id);if(!q)throw Le("\u6D41\u5DF2\u7ED3\u675F",410);if(V.type==="cancel")q.abort.abort();else if(V.type==="end")q.ended=!0;else if(V.type==="item"&&!q.ended){let U=Buffer.byteLength(JSON.stringify(V.value)??"null");if(q.items.length>=64||q.bytes+U>1024*1024)throw q.abort.abort(),Le("\u6D41\u7F13\u51B2\u533A\u5DF2\u6EE1",429);q.items.push({value:V.value,bytes:U}),q.bytes+=U}else throw Le("\u6D41\u5E27\u65E0\u6548");q.wake?.(),p.writeHead(200,{...b,"content-type":"application/json"}),p.end('{"ok":true}');return}if(T==="disconnect"&&d.method==="POST"){let V=d.headers.cookie?.split(";").map(q=>q.trim()).find(q=>q.startsWith(Rr+"="))?.slice(Rr.length+1);V&&n.delete(Wa(V)),p.setHeader("set-cookie",Rr+"=; Path="+Ot+"; HttpOnly; Secure; SameSite=Strict; Max-Age=0"),p.writeHead(200,{...b,"content-type":"application/json"}),p.end('{"ok":true}');return}if(T==="open-in-app/apps"&&d.method==="GET"){p.writeHead(200,{...b,"content-type":"application/json; charset=utf-8"}),p.end('{"apps":[]}');return}if(T.startsWith("api/")){if(["api/commander-link","api/commander-devices"].some(G=>T===G||T.startsWith(G+"/")))throw Le("\u8BF7\u5728\u7535\u8111\u4E0A\u7BA1\u7406\u914D\u5BF9\u8BBE\u5907",403);if(!["GET","HEAD","POST"].includes(d.method))throw Le("\u4E0D\u652F\u6301\u7684\u65B9\u6CD5",405);let V=new URL("/"+T+E.search,E.origin),q=e.connection.createSharedFetchHandler("/api"),U=q.requestBodyMode?.({method:d.method,url:V})??"buffered",j=new Headers;for(let[G,Z]of Object.entries(d.headers))typeof Z=="string"&&!G.startsWith(":")&&!["authorization","cookie"].includes(G)&&j.set(G,Z);let J={method:d.method,headers:j,signal:x};if(["GET","HEAD"].includes(d.method)||(U==="streaming"?(J.body=Zh.toWeb(d),J.duplex="half"):J.body=await Gc(d,tp)),!t.state.devices.some(G=>G.id===N.id&&G.tokenHash===N.tokenHash))throw Le("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548",401);await k(await q.fetch(new Request(V,J),S.peer));return}if(!["GET","HEAD"].includes(d.method))throw Le("\u4E0D\u652F\u6301\u7684\u65B9\u6CD5",405);if(T.startsWith("plugins/")){if(!e.clientModules?.fetchBundle)throw Le("\u7F51\u9875\u6A21\u5757\u5C1A\u672A\u5C31\u7EEA",503);await k(await e.clientModules.fetchBundle(new Request(new URL("/"+T+E.search,E.origin),{method:d.method,signal:x})));return}if(T==="workbench.js"){let V=await Uc(new URL("workbench.js",a));p.writeHead(200,{...b,"content-type":Fc[".js"]}),p.end(d.method==="HEAD"?void 0:V);return}let D=await Oc(rp(e,r)),L;try{L=await Oc(wi(D,decodeURIComponent(T||"index.html")))}catch(V){throw V.code==="ENOENT"?Le("\u672A\u627E\u5230",404):V}let R=Yh(D,L);if(R===".."||R.startsWith(".."+Xh)||qc(D,R)!==L||!(await Wh(L)).isFile())throw Le("\u672A\u627E\u5230",404);let M=await Uc(L),z=b["content-security-policy"];if(T===""||T==="index.html"){let V=e.webServer.renderIndex(M.toString()).replace(/<base\b[^>]*>/gi,"").replace(/(["'])\/(plugins|api)\//g,(U,j,J)=>j+Ot+J+"/").replace(/<head(?:\s[^>]*)?>/i,U=>U+'<base href="'+Ot+'"><script src="'+Ot+'workbench.js"></script>').replace("width=device-width, initial-scale=1","width=device-width, initial-scale=1, viewport-fit=cover");z="default-src 'self'; script-src 'self' 'unsafe-eval' "+[...V.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].map(U=>"'sha256-"+Hc("sha256").update(U[1]).digest("base64")+"'").join(" ")+"; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",M=Buffer.from(V)}p.writeHead(200,{...b,"content-security-policy":z,"permissions-policy":"microphone=(self), camera=(self)","content-type":Fc[Qh(L)]??"application/octet-stream"}),p.end(d.method==="HEAD"?void 0:M)}finally{S.abort.signal.removeEventListener("abort",C),p.off("close",w)}},upgrade:(d,p,E)=>{if(o)throw Le("Link \u5DF2\u5173\u95ED",503);let b=c(d);if(!b)throw Le("\u8BBE\u5907\u6388\u6743\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u914D\u5BF9",401);let N=e.get("voice");if(typeof N?.acceptRealtimeSocket!="function")throw Le("\u5B9E\u65F6\u8BED\u97F3\u5C1A\u672A\u5C31\u7EEA",503);let T=l(b);s.handleUpgrade(d,p,E,S=>{T.realtime.add(S),S.on("error",()=>{}),S.once("close",()=>T.realtime.delete(S));try{N.acceptRealtimeSocket(S)}catch{S.terminate()}})},revoke:u,close:async()=>{o=!0,await Promise.all([...i.keys()].map(u)),s.close(),n.clear()}}}import{createServer as ap}from"node:http";import{randomBytes as np,scrypt as ip,timingSafeEqual as sp,createHash as op}from"node:crypto";import{promisify as cp}from"node:util";import{mkdir as lp,readFile as up,writeFile as fp,rename as dp,rm as hp,chmod as pp}from"node:fs/promises";import{join as yp}from"node:path";var $c=cp(ip),sa=()=>np(32).toString("base64url"),xi=e=>op("sha256").update(e).digest("hex"),oa="__Host-dsh_access",Wc=720*60*1e3,Vt=(e,t=400)=>Object.assign(new Error(e),{status:t}),Si=e=>{if(typeof e!="string"||!e.startsWith("/")||e.length>4096)return"/";try{let t=decodeURIComponent(e);if(t.startsWith("//")||t.startsWith("/__dsh_access")||[...t].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===92||r.charCodeAt(0)===127))return"/";let a=new URL(e,"https://redirect.invalid");return a.origin==="https://redirect.invalid"?a.pathname+a.search+a.hash:"/"}catch{return"/"}},zc=(e,t=Wc/1e3)=>oa+"="+e+"; Path=/; Max-Age="+t+"; Secure; HttpOnly; SameSite=Strict",gp=e=>new Promise((t,a)=>{let r=0,n=[];e.on("data",i=>{r+=i.length,r>4096?(n=[],a(Vt("\u8BF7\u6C42\u8FC7\u5927",413))):n.push(i)}),e.on("end",()=>{try{r<=4096&&t(JSON.parse(Buffer.concat(n).toString("utf8")||"{}"))}catch{a(Vt("\u8BF7\u6C42\u683C\u5F0F\u65E0\u6548"))}}),e.on("error",a)});async function Qc(e,{env:t=process.env,probe:a=fetch}={}){let r=yp(e,"cloud-access.json"),n={enabled:!1},i,s="",o=0,c="",l=new Map,u=Promise.resolve(),f=0,h=0,m=0,d=!1,p,E="",b=!1,N=0,T="",S,I=sa();try{if(n=JSON.parse(await up(r,"utf8")),await pp(r,384),!n||typeof n!="object"||typeof n.enabled!="boolean"||n.enabled&&(!/^[A-Za-z0-9_-]{43}$/.test(n.salt||"")||!/^[a-f0-9]{64}$/.test(n.hash||"")))throw Error("invalid cloud access file")}catch(R){R.code!=="ENOENT"&&(n={enabled:!0},E="\u4E91\u7AEF\u8BBF\u95EE\u914D\u7F6E\u635F\u574F\uFF0C\u9274\u6743\u5DF2\u62D2\u7EDD\u8BBF\u95EE\uFF1B\u8BF7\u901A\u8FC7\u672C\u673A\u7BA1\u7406\u4FEE\u590D\u914D\u7F6E")}if(t.DSH_LINK_CLOUD_ORIGIN||t.DSH_LINK_CLOUD_AUTH_PORT)try{let R=new URL(t.DSH_LINK_CLOUD_ORIGIN);if(R.protocol!=="https:"||R.origin!==t.DSH_LINK_CLOUD_ORIGIN||R.username||R.password||!/^[0-9]+$/.test(String(t.DSH_LINK_CLOUD_AUTH_PORT))||Number(t.DSH_LINK_CLOUD_AUTH_PORT)>65535)throw Error();s=R.origin,o=Number(t.DSH_LINK_CLOUD_AUTH_PORT)}catch{c="\u9700\u914D\u7F6E\u7CBE\u786E HTTPS \u6E90 DSH_LINK_CLOUD_ORIGIN \u4E0E\u72EC\u7ACB\u7AEF\u53E3 DSH_LINK_CLOUD_AUTH_PORT"}let x=async(R=!1)=>d||!i?.listening||E?!1:S||(!R&&N&&Date.now()-N<3e4?b:(S=(async()=>{try{let M=new URL("/__dsh_access/login",s),z=await a(M,{method:"GET",redirect:"manual",signal:AbortSignal.timeout(3e3),headers:{accept:"text/html"}}),V=z.status===200&&(!z.url||new URL(z.url).origin===s)&&z.headers.get("x-dsh-cloud-ready")===I;if(await z.body?.cancel(),!V)throw Error("proxy mismatch");d||(b=!0,T="")}catch{d||(b=!1,T="\u4E91\u7AEF\u767B\u5F55\u5165\u53E3\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")}return N=Date.now(),!d&&b})().finally(()=>{S=void 0}),S)),w=()=>(d||x(),{configured:!!(!d&&i?.listening),enabled:!!(!d&&i?.listening&&n.enabled),origin:s||null,error:E||c||null,ready:!d&&b,readinessError:T||null}),C=async R=>{if(d)throw Error("\u4E91\u7AEF\u9274\u6743\u670D\u52A1\u5DF2\u5173\u95ED");await lp(e,{recursive:!0,mode:448});let M=r+"."+sa()+".tmp";try{if(await fp(M,JSON.stringify(R),{mode:384}),d)throw Error("\u4E91\u7AEF\u9274\u6743\u670D\u52A1\u5DF2\u5173\u95ED");await dp(M,r)}finally{await hp(M,{force:!0})}n=R,l.clear(),f=0,h=0},k=()=>{if(d||E||!i?.listening||!n.enabled)throw Error("\u4E91\u7AEF\u9274\u6743\u4F1A\u8BDD\u4E0D\u53EF\u7528");let R=sa(),M=Date.now();for(let[z,V]of l)V<=M&&l.delete(z);return l.size>=256&&l.delete(l.keys().next().value),l.set(xi(R),M+Wc),zc(R)},D=R=>{if(d||E)return!1;if(!n.enabled)return!0;let M=String(R.headers.cookie||"").split(";").map(U=>U.trim()).filter(U=>U.startsWith(oa+"="));if(M.length!==1)return!1;let z=M[0].slice(oa.length+1);if(!/^[A-Za-z0-9_-]{43}$/.test(z))return!1;let V=xi(z),q=l.get(V);return!q||q<=Date.now()?(l.delete(V),!1):!0},L=R=>{if(d)return Promise.reject(Error("\u4E91\u7AEF\u9274\u6743\u670D\u52A1\u5DF2\u5173\u95ED"));let M=u.then(async()=>{if(d)throw Error("\u4E91\u7AEF\u9274\u6743\u670D\u52A1\u5DF2\u5173\u95ED");if(E)throw Error(E);if(!i?.listening)throw Error(c||"\u672A\u914D\u7F6E\u4E91\u7AEF\u9274\u6743\u670D\u52A1\uFF0C\u8BF7\u5148\u63A5\u5165\u5168\u7AD9\u53CD\u5411\u4EE3\u7406");if(R.operation==="disable")await C({enabled:!1});else if(["enable","rotate"].includes(R.operation)){if(typeof R.key!="string"||R.key.length<16||R.key.length>512||!R.key.trim())throw Error("\u8BBF\u95EE\u5BC6\u94A5\u9700\u4E3A 16\u2013512 \u4E2A\u5B57\u7B26");if(R.operation==="rotate"&&!n.enabled)throw Error("\u8BF7\u5148\u542F\u7528\u4E91\u7AEF\u8BBF\u95EE\u5BC6\u94A5");if(!await x(!0))throw Error("\u4E91\u7AEF\u767B\u5F55\u5165\u53E3\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let z=sa(),V=(await $c(R.key,z,32)).toString("hex");await C({enabled:!0,salt:z,hash:V})}else throw Error("\u4E0D\u652F\u6301\u7684\u4E91\u7AEF\u8BBF\u95EE\u64CD\u4F5C");return w()});return u=M.catch(()=>{}),M};if(s&&!c){i=ap(async(R,M)=>{let z={"cache-control":"no-store","x-content-type-options":"nosniff","referrer-policy":"no-referrer"},V=(q,U,j={})=>{M.writeHead(q,{...z,"content-type":"application/json; charset=utf-8",...j}),M.end(U===void 0?void 0:JSON.stringify(U))};try{if(d||E)throw Vt(E||"\u4E91\u7AEF\u9274\u6743\u670D\u52A1\u5DF2\u5173\u95ED",503);if(R.headers.host!==new URL(s).host)throw Vt("\u8BF7\u6C42\u4E3B\u673A\u65E0\u6548",403);let q=new URL(R.url,s);if(q.origin!==s)throw Vt("\u8BF7\u6C42\u4E3B\u673A\u65E0\u6548",403);if(q.pathname==="/__dsh_access/check"&&R.method==="GET"){V(D(R)?204:401);return}if(q.pathname==="/__dsh_access/login"&&R.method==="GET"){let G=q.search.startsWith("?next=/")?q.search.slice(6):q.searchParams.get("next"),Z=sa(),te=Si(G),fe=vp(Z,te);M.writeHead(200,{...z,"x-dsh-cloud-ready":I,"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'nonce-"+Z+"'; script-src 'nonce-"+Z+"'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"}),M.end(fe);return}if(q.pathname!=="/__dsh_access/session"||!["POST","DELETE"].includes(R.method))throw Vt("\u672A\u627E\u5230",404);if(R.headers.origin!==s||R.headers["x-dsh-access"]!=="1"||!String(R.headers["content-type"]||"").startsWith("application/json"))throw Vt("\u6765\u6E90\u672A\u6388\u6743",403);if(R.method==="DELETE"){let G=String(R.headers.cookie||"").split(";").map(Z=>Z.trim()).find(Z=>Z.startsWith(oa+"="))?.slice(oa.length+1);G&&l.delete(xi(G)),V(200,{ok:!0},{"set-cookie":zc("",0)});return}if(Date.now()<h||m>=4){V(429,{error:"\u5C1D\u8BD5\u8FC7\u591A\uFF0C\u8BF7\u4E00\u5206\u949F\u540E\u91CD\u8BD5"},{"retry-after":"60"});return}let U=await gp(R);if(Date.now()<h||m>=4){V(429,{error:"\u5C1D\u8BD5\u8FC7\u591A\uFF0C\u8BF7\u4E00\u5206\u949F\u540E\u91CD\u8BD5"},{"retry-after":"60"});return}if(!n.enabled){V(200,{next:Si(U.next)});return}if(typeof U.key!="string"||U.key.length<16||U.key.length>512)throw f++,f>=5&&(h=Date.now()+6e4,f=0),Vt("\u8BBF\u95EE\u5BC6\u94A5\u65E0\u6548",401);m++;let j,J=n;try{let G=await $c(U.key,J.salt,32);j=n===J&&sp(G,Buffer.from(J.hash,"hex"))}finally{m--}if(!j)throw f++,f>=5&&(h=Date.now()+6e4,f=0),Vt("\u8BBF\u95EE\u5BC6\u94A5\u4E0D\u6B63\u786E",401);f=0,V(200,{next:Si(U.next)},{"set-cookie":k()})}catch(q){V(q.status||500,{error:q.status?q.message:"\u9274\u6743\u670D\u52A1\u6682\u4E0D\u53EF\u7528"})}}),i.requestTimeout=1e4,i.headersTimeout=1e4;try{await new Promise((R,M)=>{let z=q=>{i.removeListener("listening",V),M(q)},V=()=>{i.removeListener("error",z),R()};i.once("error",z),i.once("listening",V),i.listen(o,"127.0.0.1")})}catch{c="\u4E91\u7AEF\u9274\u6743\u7AEF\u53E3\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u72EC\u7ACB\u7AEF\u53E3\u914D\u7F6E",i.closeAllConnections(),await new Promise(R=>i.close(R)),i=void 0}}return{status:w,manage:L,sessionCookie:k,checkReady:x,origin:s,get port(){return i?.address()?.port},close(){return p||(d=!0,b=!1,l.clear(),p=(async()=>{i?.listening&&await new Promise(R=>{i.close(R),i.closeAllConnections()}),await u,await S})(),p)}}}function vp(e,t){let a=JSON.stringify(t).replace(/</g,"\\u003c");return'<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>\u767B\u5F55\u5C0F\u89D2</title><style nonce="'+e+'">:root{font:15px system-ui;color-scheme:light dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:light-dark(#fffdf8,#171b1d)}main{box-sizing:border-box;width:min(420px,100%);padding:32px}h1{font-size:26px}p{line-height:1.7;color:light-dark(#647074,#a0abab)}label{display:grid;gap:10px}input,button{box-sizing:border-box;width:100%;font:inherit;padding:13px;border:1px solid #8886;border-radius:10px}input{background:transparent}button{margin-top:18px;background:#2c6ee8;color:#fff;border:0;cursor:pointer}#error{color:light-dark(#b34845,#f0928d);min-height:1.5em}</style></head><body><main><h1>\u767B\u5F55\u5C0F\u89D2</h1><p>\u8F93\u5165\u6B64\u5DE5\u4F5C\u533A\u7684\u4E91\u7AEF\u8BBF\u95EE\u5BC6\u94A5\u3002</p><form><label>\u8BBF\u95EE\u5BC6\u94A5<input type="password" name="key" autocomplete="current-password" minlength="16" maxlength="512" required autofocus></label><button>\u8FDB\u5165\u5DE5\u4F5C\u533A</button><p id="error" role="alert"></p></form></main><script nonce="'+e+'">const f=document.querySelector("form"),e=document.querySelector("#error"),b=document.querySelector("button");f.addEventListener("submit",async v=>{v.preventDefault();b.disabled=true;e.textContent="";try{const r=await fetch("/__dsh_access/session",{method:"POST",headers:{"content-type":"application/json","x-dsh-access":"1"},body:JSON.stringify({key:f.elements.key.value,next:'+a+'})});const x=await r.json();f.elements.key.value="";if(!r.ok)throw Error(x.error||"\u767B\u5F55\u5931\u8D25");const target=new URL(x.next,location.origin);if(!target.hash)target.hash=location.hash;location.replace(target.href)}catch(x){e.textContent=x.message}finally{b.disabled=false}});</script></body></html>'}import{createServer as mp,request as Yc}from"node:http";import{randomBytes as Ep}from"node:crypto";async function Xc({ownerOrigin:e,workbenchOrigin:t,port:a,getCenter:r}){let n=new URL(e),i=t?new URL(t):null;if(n.protocol!=="https:"||n.origin!==e||n.username||n.password||i&&(i.protocol!=="https:"||i.origin!==t||i.origin===n.origin||i.username||i.password))throw Error("\u8BBE\u5907\u4E2D\u5FC3\u9700\u7CBE\u786E HTTPS owner \u4E0E\u72EC\u7ACB\u5DE5\u4F5C\u53F0\u6E90");if(!Number.isInteger(a)||a<1||a>65535)throw Error("\u8BBE\u5907\u7F51\u5173\u7AEF\u53E3\u65E0\u6548");let s=new Map,o=new Set,c=!1,l=async h=>{if(c)throw Error("\u8BBE\u5907\u7F51\u5173\u5DF2\u5173\u95ED");let m=new URL(h.url,e);if(h.headers.host===n.host&&m.pathname.startsWith("/devices/"))return{target:(await r()).origin,path:m.pathname.slice(8)+m.search};let d=m.pathname.match(/^\/p\/([A-Za-z0-9_-]{32})(\/.*)$/),p=d&&s.get(d[1]);if(!i||h.headers.host!==i.host||!p)throw Error("\u8BBE\u5907\u5DE5\u4F5C\u53F0\u5730\u5740\u672A\u6388\u6743");if(h.headers.origin&&h.headers.origin!==i.origin)throw Error("\u6765\u6E90\u672A\u6388\u6743");return{target:p.origin,path:d[2]+m.search}},u=(h,m)=>{let d={...h.headers,host:new URL(m).host};for(let p of["cookie","authorization","x-forwarded-for","x-forwarded-host","x-real-ip"])delete d[p];return h.headers.origin&&(d.origin=new URL(m).origin),d},f=mp(async(h,m)=>{try{let d=await l(h);if(h.headers.origin&&h.headers.host===n.host&&h.headers.origin!==n.origin)throw Error("\u6765\u6E90\u672A\u6388\u6743");let p=Yc(new URL(d.path,d.target),{method:h.method,headers:u(h,d.target)},E=>{let b={...E.headers};delete b["set-cookie"],m.writeHead(E.statusCode,b),E.pipe(m),E.on("error",N=>m.destroy(N))});p.on("error",()=>{m.headersSent?m.destroy():(m.writeHead(502),m.end())}),m.on("close",()=>{m.writableEnded||p.destroy()}),h.pipe(p)}catch{m.writeHead(403,{"cache-control":"no-store"}),m.end("\u8BBE\u5907\u5730\u5740\u672A\u6388\u6743")}});return f.on("upgrade",async(h,m,d)=>{m.on("error",()=>{});try{if(!i||h.headers.host!==i.host||h.headers.origin!==i.origin)throw Error();let p=await l(h),E=Yc(new URL(p.path,p.target),{headers:u(h,p.target)});E.on("upgrade",(b,N,T)=>{o.add(N),N.once("close",()=>o.delete(N)),N.on("error",()=>m.destroy()),m.write(`HTTP/1.1 101 Switching Protocols\r
241
+ `+Object.entries(b.headers).map(([S,I])=>S+": "+I).join(`\r
242
+ `)+`\r
243
+ \r
244
+ `),T.length&&m.write(T),d.length&&N.write(d),m.pipe(N),N.pipe(m),m.once("close",()=>N.destroy())}),E.on("response",()=>m.destroy()),E.on("error",()=>m.destroy()),E.end()}catch{m.destroy()}}),f.on("connection",h=>{o.add(h),h.once("close",()=>o.delete(h))}),await new Promise((h,m)=>{f.once("error",m),f.listen(a,"127.0.0.1",h)}),{registerProxy(){let h=Ep(24).toString("base64url");return{prefix:"/p/"+h,attach(m){s.set(h,m);let d=m.close.bind(m);m.close=async()=>{s.delete(h),await d()}},remove(){s.delete(h)}}},async close(){c=!0,s.clear();let h=new Promise(m=>f.close(m));for(let m of o)m.destroy();await h}}}import{request as Cp}from"node:https";import{WebSocket as kt}from"ws";var Zc="/__link/relay/control",el="/__link/relay/data",Jc="/link/workbench/",tl="/link/workbench/api/voice/realtime";function rl(e,t){if(typeof e!="string"||typeof t!="string"||!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/%(?:2f|5c|00)/i.test(t))return!1;let a;try{a=decodeURIComponent(t.split("?")[0])}catch{return!1}if(a.split("/").some(i=>i==="."||i===".."))return!1;let r=t.split("?")[0];if(r==="/link/api/info")return e==="GET";if(["/link/api/pair","/link/api/pair/status","/link/api/rpc","/link/api/workbench"].includes(r))return e==="POST";if(["/link","/link/","/link/index.html","/link/app.js","/link/app.css"].includes(r))return e==="GET"||e==="HEAD";if(!r.startsWith(Jc)||!["GET","HEAD","POST"].includes(e))return!1;let n=r.slice(Jc.length);return!/^(?:api\/commander-(?:link|devices)|api\/(?:owner|admin)(?:\/|$))/i.test(n)}var wp=256*1024,xp=e=>Object.assign(new Error(e),{status:502}),Lr=async(e,t,a={})=>{for(;e.readyState===kt.OPEN&&e.bufferedAmount>wp;)await new Promise(r=>setTimeout(r,5));if(e.readyState!==kt.OPEN)throw xp("\u4E2D\u7EE7\u6570\u636E\u901A\u9053\u5DF2\u5173\u95ED");await new Promise((r,n)=>e.send(t,a,i=>i?n(i):r()))},nl=e=>new URL(e.url).origin;function Sp(e){let{relayUrl:t,token:a,target:r}=e,n,i;try{n=new URL(t),i=new URL(r?.url)}catch{throw new Error("\u4E2D\u7EE7\u6216 Link \u4E3B\u673A\u5730\u5740\u65E0\u6548")}if(n.protocol!=="https:"||n.origin!==t||n.username||n.password||n.pathname!=="/"||n.search||n.hash)throw new Error("\u4E2D\u7EE7\u5730\u5740\u5FC5\u987B\u662F\u72EC\u7ACB HTTPS origin");if(i.protocol!=="https:"||i.origin!==r.url||i.username||i.password||i.pathname!=="/"||i.search||i.hash||!["localhost","127.0.0.1","[::1]"].includes(i.hostname))throw new Error("Link \u4E0A\u6E38\u5FC5\u987B\u662F\u56FA\u5B9A HTTPS loopback \u5730\u5740");if(typeof a!="string"||a.length<6||a.length>256)throw new Error("\u4E2D\u7EE7\u4E3B\u673A\u5BC6\u94A5\u81F3\u5C11\u9700\u8981 6 \u4E2A\u5B57\u7B26");if(typeof r.pin!="string"||!/^[A-Za-z0-9+/]{43}=$/.test(r.pin)||Buffer.from(r.pin,"base64").length!==32)throw new Error("Link \u4E3B\u673A SPKI \u6307\u7EB9\u65E0\u6548");if(e.relayCa!==void 0&&typeof e.relayCa!="string"&&!Buffer.isBuffer(e.relayCa))throw new Error("\u4E2D\u7EE7 CA \u8BC1\u4E66\u65E0\u6548");return{relay:n.origin,target:{url:i.origin,pin:r.pin}}}function bp(e,t){let a={};for(let r of["accept","accept-language","content-type","content-length","range","if-none-match","if-modified-since","cookie"])typeof e.headers?.[r]=="string"&&(a[r]=e.headers[r]);return["/link/api/rpc","/link/api/workbench"].includes(e.path.split("?")[0])&&typeof e.headers?.authorization=="string"&&(a.authorization=e.headers.authorization),a.host=new URL(t.url).host,a.origin=nl(t),a}function bi(e){let{relay:t,target:a}=Sp(e),r=lr(a),n=new Set,i=new Set,s=!1,o=!1,c=null,l,u,f,h,m=(T,S)=>{T.readyState===kt.OPEN&&Lr(T,JSON.stringify({type:"error",error:"\u76EE\u6807 Link \u8BF7\u6C42\u5931\u8D25"})).catch(()=>{}),T.close(1011,"upstream failed"),c=S?.message||"\u76EE\u6807 Link \u8BF7\u6C42\u5931\u8D25",e.onError?.(new Error(c))},d=(T,S)=>{if(!rl(S.method,S.path)){T.close(1008);return}let I=new URL(S.path,a.url);if(I.origin!==a.url||!["GET","HEAD","POST"].includes(S.method)){T.close(1008);return}let x=!1,w=Cp(I,{agent:r,method:S.method,headers:bp(S,a),timeout:12e4},C=>{Lr(T,JSON.stringify({type:"response",status:C.statusCode,headers:C.headers})).catch(k=>w.destroy(k)),C.on("data",k=>{C.pause(),(async()=>{for(let D=0;D<k.length;D+=49152)await Lr(T,k.subarray(D,D+49152),{binary:!0});C.resume()})().catch(D=>C.destroy(D))}),C.once("end",()=>{x=!0,Lr(T,JSON.stringify({type:"end"})).catch(()=>{})}),C.once("error",k=>m(T,k))});w.on("timeout",()=>w.destroy(new Error("upstream timeout"))),w.on("error",C=>{x||m(T,C)}),T.on("message",(C,k)=>{if(k){w.write(C)||(T.pause(),w.once("drain",()=>T.resume()));return}let D;try{D=JSON.parse(C.toString())}catch{w.destroy(new Error("invalid relay frame"));return}D.type==="request-end"?w.end():w.destroy(new Error("unexpected relay frame"))}),T.once("close",()=>w.destroy()),T.once("error",()=>w.destroy())},p=(T,S)=>{if(S.path!==tl||typeof S.cookie!="string"||S.cookie.length>4096){T.close(1008);return}let I=new URL(S.path,a.url);I.protocol="wss:";let x=new kt(I,{agent:r,origin:nl(a),headers:{...S.cookie?{cookie:S.cookie}:{}},handshakeTimeout:1e4,maxPayload:64*1024,perMessageDeflate:!1});n.add(x),x.once("close",()=>n.delete(x));let w=!1,C=k=>{w||(w=!0,k&&(c=k.message),T.readyState!==kt.CLOSED&&T.terminate(),x.readyState!==kt.CLOSED&&x.terminate())};x.once("open",()=>{Lr(T,JSON.stringify({type:"voice-ready"})).catch(C)}),x.on("message",(k,D)=>{let L=Buffer.from([D?1:0]);Lr(T,Buffer.concat([L,Buffer.from(k)]),{binary:!0}).catch(C)}),T.on("message",(k,D)=>{if(D){let L=Buffer.from(k);if(L.length<1||L[0]>1||x.readyState!==kt.OPEN)return C(new Error("voice frame invalid"));if(x.bufferedAmount+L.length-1>256*1024)return C(new Error("voice buffer full"));x.send(L.subarray(1),{binary:L[0]===1},R=>{R&&C(R)})}else D||C(new Error("unexpected voice relay frame"))}),T.once("close",()=>C()),x.once("close",()=>C()),T.on("error",C),x.on("error",C)},E=T=>{if(T.length>16*1024)return l?.close(1009,"control frame too large");let S;try{S=JSON.parse(T.toString())}catch{return l?.close(1008,"invalid control frame")}if(!["http","voice"].includes(S.type)||typeof S.ticket!="string"||S.ticket.length>128)return l?.close(1008,"invalid control frame");let I=new URL(el,t);I.protocol="wss:";let x=new kt(I,{headers:{authorization:"Bearer "+S.ticket},...e.relayCa?{ca:e.relayCa}:{},handshakeTimeout:1e4,maxPayload:128*1024,perMessageDeflate:!1});n.add(x),x.once("close",()=>n.delete(x)),x.once("open",()=>S.type==="http"?d(x,S):p(x,S)),x.once("error",w=>{c=w.message})},N=(async()=>{let T=1e3;for(;!s;){try{let S=new URL(Zc,t);S.protocol="wss:",l=new kt(S,{headers:{authorization:"Bearer "+e.token},...e.relayCa?{ca:e.relayCa}:{},handshakeTimeout:1e4,maxPayload:16*1024,perMessageDeflate:!1});let I=l;n.add(I),I.once("close",()=>n.delete(I)),await new Promise((w,C)=>{let k=!1,D=V=>{k||(k=!0,clearTimeout(z),I.off("open",L),I.off("error",R),I.off("close",M),V?C(V):w())},L=()=>{o=!0,c=null,T=1e3,D()},R=V=>D(V),M=()=>D(new Error("\u4E2D\u7EE7\u5728\u63E1\u624B\u5B8C\u6210\u524D\u5173\u95ED")),z=setTimeout(()=>{I.terminate(),D(new Error("\u4E2D\u7EE7\u8FDE\u63A5\u8D85\u65F6"))},1e4);z.unref?.(),I.once("open",L),I.once("error",R),I.once("close",M)});let x=Date.now();I.on("error",w=>{s||(c=w.message,e.onError?.(w))}),l.on("pong",()=>{x=Date.now()}),h=setInterval(()=>{if(I.readyState===kt.OPEN){if(Date.now()-x>45e3){I.terminate();return}I.ping()}},15e3),h.unref?.(),I.on("message",E),await new Promise(w=>I.once("close",w))}catch(S){s||(c=S.message,e.onError?.(S))}clearInterval(h),o=!1,s||await new Promise(S=>{f=S,u=setTimeout(()=>{f=void 0,S()},T),u.unref?.()}),T=Math.min(T*2,3e4)}})();return i.add(N),{status:()=>({connected:o,lastError:c}),async close(){if(!s){s=!0,clearTimeout(u),f?.(),f=void 0,o=!1,clearInterval(h),l?.close(1001,"host stopped");for(let T of n)T.terminate();r.destroy(),await Promise.allSettled([...i]),i.clear()}}}}async function Ev(e,t={}){let a=t.env??process.env,r,n="",i,s,o=t.directory??Ti(e.get("commander").store.directory,"link"),c=await Bi(o),l=Array.isArray(c.state.relayPool)&&c.state.relayPool.length?c.state.relayPool:c.state.relay?.url||a.DSH_LINK_RELAY_URL?[{id:"primary",url:c.state.relay?.url||a.DSH_LINK_RELAY_URL,token:c.state.relay?.token||a.DSH_LINK_RELAY_TOKEN,priority:0,enabled:c.state.relay?.enabled!==!1}]:[],u=new Map,f=async()=>{await Promise.all([...u.values()].map(j=>j.instance?.close())),u.clear(),r=void 0};i=c.state.relay?.url??a.DSH_LINK_RELAY_URL??l[0]?.url??"",s=c.state.relay?.token??a.DSH_LINK_RELAY_TOKEN??l[0]?.token??"";let h=c.state.relay?.enabled??!!i;ni({},c.state);let m=tc(e),d=ac(e),p=await Qc(o,{env:t.env??process.env,probe:t.cloudProbe}),E=async(j,J)=>{if(j?.id?.startsWith("native:"))return d.dispatch(j);let G=await m.dispatch(j,J);return j.action==="state"&&G.sessions.push(...d.list()),G},b,N,T,S="",I=!1,x,w=Promise.resolve(),C=t.webRoot??new URL("../dist/web/",import.meta.url),k=async()=>{if(!b||!h||!l.length)return;let j=["::","::1"].includes(c.state.host)?"[::1]":c.state.host==="0.0.0.0"?"127.0.0.1":c.state.host;for(let[J,G]of l.entries())if(G.enabled!==!1&&G.url&&G.token)try{let Z=await bi({relayUrl:G.url,token:G.token,target:{url:`https://${j}:${b.port}`,pin:N.pin},onError:()=>{}});u.set(G.id||`relay-${J+1}`,{...G,id:G.id||`relay-${J+1}`,instance:Z}),r||(r=Z)}catch{n="\u4E2D\u7EE7\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 HTTPS \u5730\u5740\u3001\u4E3B\u673A\u5BC6\u94A5\u53CA\u672C\u673A\u76D1\u542C\u5730\u5740"}},D=async()=>{N??=await Jo(o),T=jc(e,c,{webRoot:C,workbenchRoot:t.workbenchRoot}),b=await ec({identity:N,config:{...c.state},webRoot:C,store:c,dispatch:E,workbench:T,routes:()=>[...ai(c.state.host).slice(0,15).map(j=>({url:`https://${Ma(j,b?.port??c.state.port)}`,pin:N.pin,kind:"direct"})),...l.filter(j=>j.enabled!==!1&&j.url&&j.token).map((j,J)=>({url:j.url,kind:"relay",relayId:j.id||`relay-${J+1}`,priority:Number.isInteger(j.priority)?j.priority:J}))],onError:j=>{S=j.message}}),S="",n="",await k()},L=()=>({enabled:!!b,host:c.state.host,port:b?.port??c.state.port,publicUrl:c.state.publicUrl,hostName:Tp(),error:S||null,addresses:ai(c.state.host).map(j=>`https://${Ma(j,b?.port??c.state.port)}`),devices:c.state.devices.map(({tokenHash:j,...J})=>J),pending:c.pending(),relay:{configured:!!(l.length||i),enabled:h,url:i,nodes:l.map((j,J)=>{let G=u.get(j.id||`relay-${J+1}`),{token:Z,instance:te,...fe}=j;return{...fe,id:j.id||`relay-${J+1}`,...G?.instance?.status()??{connected:!1,lastError:n||null}}}),...r?.status()??{connected:!1,lastError:n||null}}}),R=async j=>{if(I)throw new Error("Link \u5DF2\u5173\u95ED");let J=at(j?.action,"\u64CD\u4F5C");if(J==="status")return L();if(J==="relay-pool-configure"){let G=j.nodes;if(!Array.isArray(G)||!G.length||G.length>8)throw new Error("\u4E2D\u7EE7\u6C60\u8282\u70B9\u6570\u91CF\u65E0\u6548");let Z=Array.isArray(c.state.relayPool)?c.state.relayPool:[],te=G.map((ce,Ee)=>{let be=Z.find(Ke=>Ke.id===ce.id),Te=at(ce.url||be?.url,"\u4E2D\u7EE7\u5730\u5740",2048),ke=at(ce.token||be?.token,"\u4E2D\u7EE7\u4E3B\u673A\u5BC6\u94A5",256),xe;try{xe=new URL(Te)}catch{throw new Error("\u4E2D\u7EE7\u5730\u5740\u65E0\u6548")}if(xe.protocol!=="https:"||xe.origin!==Te||xe.username||xe.password)throw new Error("\u4E2D\u7EE7\u5FC5\u987B\u4F7F\u7528\u72EC\u7ACB HTTPS origin");if(ke.length<6)throw new Error("\u4E2D\u7EE7\u4E3B\u673A\u5BC6\u94A5\u81F3\u5C11\u9700\u8981 6 \u4E2A\u5B57\u7B26");return{id:at(ce.id||`relay-${Ee+1}`,"\u4E2D\u7EE7 ID",128),url:Te,token:ke,priority:Number.isInteger(ce.priority)?ce.priority:Ee,enabled:ce.enabled!==!1}}),fe=w.then(async()=>{let ce=c.state.relayPool;c.state.relayPool=te,c.state.relay={url:te[0].url,token:te[0].token,enabled:te[0].enabled};try{await c.persist()}catch(Ee){throw c.state.relayPool=ce,Ee}return await f(),l.splice(0,l.length,...te),i=te[0].url,s=te[0].token,h=te.some(Ee=>Ee.enabled),h&&!b?(c.state.enabled=!0,await D(),await c.persist()):h&&b&&await k(),L()});return w=fe.catch(()=>{}),fe}if(J==="relay-configure"){let G=w.then(async()=>{if(I)throw new Error("Link \u5DF2\u5173\u95ED");let Z=j.url===void 0?i:at(j.url,"\u4E2D\u7EE7\u5730\u5740",2048),te;try{te=new URL(Z)}catch{throw new Error("\u4E2D\u7EE7\u5730\u5740\u65E0\u6548")}if(te.protocol!=="https:"||te.origin!==Z||te.username||te.password)throw new Error("\u4E2D\u7EE7\u5FC5\u987B\u4F7F\u7528\u72EC\u7ACB HTTPS origin");let fe=j.token===void 0?s:at(j.token,"\u4E2D\u7EE7\u4E3B\u673A\u5BC6\u94A5",256);if(fe.length<6)throw new Error("\u4E2D\u7EE7\u4E3B\u673A\u5BC6\u94A5\u81F3\u5C11\u9700\u8981 6 \u4E2A\u5B57\u7B26");let ce=j.enabled===void 0?!0:j.enabled;if(typeof ce!="boolean")throw new Error("\u4E2D\u7EE7\u542F\u7528\u72B6\u6001\u65E0\u6548");if(ce&&!["0.0.0.0","::","127.0.0.1","localhost","::1"].includes(c.state.host))throw new Error("\u542F\u7528\u4E2D\u7EE7\u9700\u8981 Link \u76D1\u542C\u5168\u90E8\u7F51\u5361\u6216 loopback");let Ee=c.state.relay;c.state.relay={url:Z,token:fe,enabled:ce};let be={id:l[0]?.id||"primary",url:Z,token:fe,priority:0,enabled:ce};l.splice(0,l.length,be),c.state.relayPool=l.map(({instance:Te,...ke})=>ke);try{await c.persist()}catch(Te){throw c.state.relay=Ee,Te}if(i=Z,s=fe,h=ce,c.clearPairings(),await f(),ce)if(!b)c.state.enabled=!0,await D(),await c.persist();else{n="";let Te=c.state.host==="::"||c.state.host==="::1"?"[::1]":"127.0.0.1";r=await bi({relayUrl:i,token:s,target:{url:`https://${Te}:${b.port}`,pin:N.pin}})}return L()});return w=G.catch(()=>{}),G}if(J==="configure"){let G=w.then(async()=>{if(I)throw new Error("Link \u5DF2\u5173\u95ED");let Z=ni(j,c.state);c.clearPairings(),await f(),await b?.close(),b=void 0,await m.close(),Object.assign(c.state,Z);try{Z.enabled&&await D()}catch(te){throw S=te.message,c.state.enabled=!1,await c.persist(),te}return await c.persist(),L()});return w=G.catch(()=>{}),G}if(J==="pairing"){if(!b)throw new Error("\u8BF7\u5148\u542F\u7528 Link");let G=j.mode??"lan";if(!["lan","public","relay"].includes(G))throw new Error("\u8FDE\u63A5\u6A21\u5F0F\u65E0\u6548");if(G==="relay"&&!r?.status().connected)throw new Error("\u81EA\u6709\u4E2D\u7EE7\u5C1A\u672A\u8FDE\u63A5\uFF0C\u8BF7\u68C0\u67E5\u4E2D\u7EE7\u914D\u7F6E\u548C\u7F51\u7EDC");let Z=L().addresses,te=G==="relay"?i:G==="public"?c.state.publicUrl:Z[0];if(G==="public"&&!c.state.publicUrl)throw new Error("\u8BF7\u5148\u4FDD\u5B58\u53EF\u8FBE\u7684\u516C\u7F51 HTTPS \u5730\u5740");if(j.address!==void 0){if(G!=="lan"||!Z.includes(j.address))throw new Error("\u5C40\u57DF\u7F51\u5730\u5740\u65E0\u6548");te=j.address}if(!te)throw new Error("\u672A\u627E\u5230\u53EF\u7528\u7684\u8FDE\u63A5\u5730\u5740\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u6216\u5728\u9AD8\u7EA7\u8BBE\u7F6E\u4E2D\u6307\u5B9A\u76D1\u542C\u5730\u5740");let fe=c.begin(),ce=new URLSearchParams({url:te,pin:G==="lan"?N.pin:"",code:fe.code});return{...fe,mode:G,uri:`dshlink://pair?${ce}`,...G!=="lan"?{webUrl:`${te}/link/#code=${encodeURIComponent(fe.code)}`}:{},url:te}}if(J==="confirm"||J==="reject")return await c.decide(at(j.id,"\u8BBE\u5907 ID"),J==="confirm"),L();if(J==="revoke"){let G=at(j.id,"\u8BBE\u5907 ID");return await c.revoke(G),await Promise.all([m.revoke(G),T?.revoke(G)]),L()}throw new Error("\u4E0D\u652F\u6301\u7684\u7BA1\u7406\u64CD\u4F5C")},M,z,V,q=()=>z??=Ei({directory:Ti(o,"cloud-outgoing"),webRoot:C,hostAdmin:R,publicOrigin:p.origin,workbenchOrigin:a.DSH_LINK_WORKBENCH_ORIGIN,registerProxy:()=>V.registerProxy()}).catch(j=>{throw z=void 0,j});a.DSH_LINK_DEVICE_GATEWAY_PORT&&p.origin&&a.DSH_LINK_WORKBENCH_ORIGIN&&(V=await Xc({ownerOrigin:p.origin,workbenchOrigin:a.DSH_LINK_WORKBENCH_ORIGIN,port:Number(a.DSH_LINK_DEVICE_GATEWAY_PORT),getCenter:q})),e.effect(()=>e.connection.fetch.register({path:"/api/commander-devices",methods:["POST"],requestBody:"buffered",async fetch(j){try{if(I)throw new Error("Link \u5DF2\u5173\u95ED");let J=await j.json();if(!["launch","devices"].includes(J.action))throw new Error("\u4E0D\u652F\u6301\u7684\u8BBE\u5907\u64CD\u4F5C");let G=J.parentOrigin,Z=j.headers.get("origin"),te=j.headers.get("host"),fe=te?new URL("http://"+te):new URL(j.url),ce=xe=>["127.0.0.1","localhost","[::1]"].includes(xe.hostname),Ee=!Z&&ce(fe)&&["dsh-app://app","dsh-app://localhost"].includes(G),be=Z?new URL(Z):fe,Te=Ee?G:be.origin;if(!Ee&&(!["http:","https:"].includes(be.protocol)||!ce(be))){if(!V||be.origin!==p.origin)return Response.json({error:"\u8BF7\u914D\u7F6E\u4E91\u7AEF\u8BBE\u5907\u7F51\u5173\u540E\u91CD\u8BD5\uFF1B\u672C\u673A BenchGo \u53EF\u7EE7\u7EED\u7BA1\u7406\u8BBE\u5907\u3002",code:"CLOUD_DEVICE_GATEWAY_REQUIRED"},{status:409,headers:{"cache-control":"no-store"}});let xe=await q();return Response.json(xe.launch(be.origin),{headers:{"cache-control":"no-store"}})}M??=Ei({directory:Ti(o,"outgoing"),webRoot:C,hostAdmin:R}).catch(xe=>{throw M=void 0,xe});let ke=await M;if(I)throw new Error("Link \u5DF2\u5173\u95ED");return Response.json(J.action==="devices"?ke.summary():ke.launch(Te),{headers:{"cache-control":"no-store"}})}catch(J){return Response.json({error:J.message},{status:400,headers:{"cache-control":"no-store"}})}}}));let U=()=>x||(I=!0,x=(async()=>{let j=p.close();await(await M?.catch(()=>{}))?.close(),await V?.close(),await(await z?.catch(()=>{}))?.close(),await j,await w,await f(),await b?.close(),b=void 0,await m.close(),c.clearPairings(),await c.flush()})(),x);try{c.state.enabled&&await D()}catch(j){S=j.message}return e.effect(()=>()=>U()),e.effect(()=>e.connection.fetch.register({path:"/api/commander-link",methods:["POST"],requestBody:"buffered",async fetch(j){try{let J=await j.json(),G=await R(J),Z={"cache-control":"no-store"};return J.action==="cloud-access"&&["enable","rotate"].includes(J.operation)&&j.headers.get("origin")===p.origin&&(Z["set-cookie"]=p.sessionCookie()),Response.json(G,{headers:Z})}catch(J){return Response.json({error:J.message},{status:400,headers:{"cache-control":"no-store"}})}}})),{admin:R,status:L,close:U}}export{Ev as mountLink};