@hermenics/deepseek-code 0.13.2 → 0.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,7 +20,7 @@
20
20
  <div align="center">
21
21
  <img src="https://raw.githubusercontent.com/Hermenics/deepseek-code/main/src/public/demo.gif" alt="DeepSeek Code demo" width="80%" />
22
22
  <br/>
23
- <sub><i>Simulated output for demonstration purposes.</i></sub>
23
+ <sub><i>Real DeepSeek Code CLI with a deterministic local model and an isolated demo project.</i></sub>
24
24
  </div>
25
25
 
26
26
  ---
@@ -69,7 +69,7 @@ The host account must have passwordless `sudo` for one-time OS package installat
69
69
 
70
70
  ### Requirements
71
71
 
72
- - [Bun](https://bun.sh) 1.1+
72
+ - [Bun](https://bun.sh) 1.4.0+
73
73
  - Node.js 18+ (starts Bun without loading the current project's `.env` or `bunfig.toml`)
74
74
  - A supported LLM provider (see below)
75
75
 
@@ -162,7 +162,7 @@ The same `configurations` format works in either launch file. `.deepseek/launch.
162
162
 
163
163
  ### Prerequisites
164
164
 
165
- - [Bun](https://bun.sh) >= 1.1
165
+ - [Bun](https://bun.sh) >= 1.4.0
166
166
  - Node.js >= 18
167
167
 
168
168
  ### Setup
@@ -180,7 +180,7 @@ bun run dev # Start in dev mode (watch)
180
180
  bun run start # Run from source
181
181
  bun run build # Production build
182
182
  bun run typecheck # Type check (tsc --noEmit)
183
- bun test # Run tests
183
+ bun run test # Isolated serial suite, matching CI
184
184
  ```
185
185
 
186
186
  ### Background task recovery
@@ -252,7 +252,7 @@ Contributions are welcome! Here's how to get started:
252
252
  3. **Make your changes** — keep files under 500 lines
253
253
  4. **Run checks** before submitting:
254
254
  ```bash
255
- bun run typecheck && bun test
255
+ bun run typecheck && bun run test
256
256
  ```
257
257
  5. **Open a PR** with a clear description of what changed and why
258
258
 
@@ -1,25 +1,25 @@
1
- import{createSecureContext as zw}from"node:tls";import{createServer as b,request as l}from"node:http";import{request as c}from"node:https";import{TLSSocket as a}from"node:tls";import{connect as o,createServer as t,isIP as B}from"node:net";import{randomBytes as L,timingSafeEqual as U}from"node:crypto";import{mkdtempSync as r,rmSync as s}from"node:fs";import{tmpdir as e}from"node:os";import{join as x}from"node:path";import{lookup as n}from"dns/promises";import{isIP as R}from"node:net";import{BlockList as m,isIP as q}from"node:net";var i=20000,Zw=i*4;var h=[["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.31.196.0",24],["192.52.193.0",24],["192.88.99.0",24],["192.168.0.0",16],["192.175.48.0",24],["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]],p=[["::",96],["::1",128],["::ffff:0:0",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",23],["2001:db8::",32],["2002::",16],["3fff::",20],["fc00::",7],["fe80::",10],["ff00::",8]];function I(z,w){let Q=new m;for(let[Z,J]of z)Q.addSubnet(Z,J,w);return Q}var k=I(h,"ipv4"),d=I(p,"ipv6");function D(z){let w=q(z);if(w===4)return k.check(z,"ipv4");if(w===6&&/^::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}$/i.test(z))return!0;if(w===6)return d.check(z,"ipv6");return!0}var u=2000,H=2048,Y=async(z)=>{let w;try{return(await Promise.race([n(z,{all:!0}),new Promise((Z,J)=>{w=setTimeout(()=>J(Error("DNS timeout")),u)})])).map((Z)=>Z.address)}finally{clearTimeout(w)}};function f(z){return z.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}function O(z){let w=f(z);if(w==="localhost"||w.endsWith(".localhost"))return!0;if(R(w)===4)return w.startsWith("127.");return w==="::1"}async function E(z,w=Y){if(z==="about:blank")return{kind:"loopback",origin:"about:blank"};if(z.length>H)return{kind:"blocked",reason:`URL longer than ${H} characters`};let Q;try{Q=new URL(z)}catch{return{kind:"blocked",reason:"not a valid URL"}}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return{kind:"blocked",reason:`${Q.protocol} URLs are not allowed; use http or https`};if(Q.username||Q.password)return{kind:"blocked",reason:"URLs with embedded credentials are not allowed"};let Z=Q.origin,J=f(Q.hostname);if(O(J))return{kind:"loopback",origin:Z};if(J==="metadata.google.internal")return{kind:"blocked",origin:Z,reason:"cloud metadata endpoints are blocked"};if(R(J))return D(J)?{kind:"blocked",origin:Z,reason:`${J} is not a public address`}:{kind:"public",origin:Z};let G;try{G=await w(J)}catch{return{kind:"blocked",origin:Z,reason:`could not resolve ${J}`}}if(G.length===0)return{kind:"blocked",origin:Z,reason:`could not resolve ${J}`};let $=G.find((K)=>D(K));return $?{kind:"blocked",origin:Z,reason:`${J} resolves to non-public address ${$}`}:{kind:"public",origin:Z}}var ww=["connection","proxy-connection","proxy-authorization","proxy-authenticate","keep-alive","te","trailer","transfer-encoding","upgrade"];function M(z){let w={...z},Q=String(z.connection??"").split(",").map((Z)=>Z.trim().toLowerCase());for(let Z of[...ww,...Q])delete w[Z];return w}function _(z){return z.replace(/^\[|\]$/g,"").replace(/\.$/,"")}class P{certificate;authorize;resolve;certificateAuthority;username="codimium";password=L(32).toString("hex");realm=L(16).toString("hex");authorization=Buffer.from(`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`);sockets=new Set;tunnel=new WeakMap;authenticated=new WeakSet;server=b();inner=b();innerTls=t((z)=>this.acceptTls(z));privateDirectory=r(x(e(),"deepseek-egress-tls-"));stopped=!1;_url="";constructor(z,w,Q,Z){this.certificate=z;this.authorize=w;this.resolve=Q;this.certificateAuthority=Z;this.inner.setTimeout(30000);for(let[J,G]of[[this.server,!1],[this.inner,!0]])J.maxHeadersCount=100,J.headersTimeout=15000,J.requestTimeout=30000,J.on("request",($,K)=>{this.forward($,K,G).catch(()=>{if(!K.headersSent)K.writeHead(502);K.end()})}),J.on("upgrade",($,K,N)=>{this.upgrade($,K,N,G).catch(()=>K.destroy())}),J.on("connection",($)=>this.track($)),J.on("clientError",($,K)=>K.destroy());this.server.on("connect",(J,G,$)=>{this.connect(J,G,$).catch(()=>G.destroy())})}static async start(z,w,Q=Y,Z){let J=new P(z,w,Q,Z);try{await new Promise(($,K)=>{J.innerTls.once("error",K),J.innerTls.listen(x(J.privateDirectory,"tls"),()=>{J.innerTls.off("error",K),$()})}),await new Promise(($,K)=>{J.server.once("error",K),J.server.listen(0,"127.0.0.1",()=>{J.server.off("error",K),$()})});let G=J.server.address();if(!G||typeof G==="string")throw J.stop(),Error("Codimium network protection did not bind");return J._url=`http://127.0.0.1:${G.port}`,J}catch(G){throw J.stop(),G}}get url(){return this._url}get cleanupDirectory(){return this.privateDirectory}launchOptions(){return{proxyServer:this.url,proxyBypassList:"<-loopback>",certificateSPKI:this.certificate.spki}}stop(){if(this.stopped)return;this.stopped=!0,this.server.close(),this.innerTls.close();for(let z of this.sockets)z.destroy();this.sockets.clear(),s(this.privateDirectory,{recursive:!0,force:!0})}track(z){this.sockets.add(z),z.once("close",()=>this.sockets.delete(z)),z.on("error",()=>z.destroy())}hasAuth(z,w=!1){if(w&&this.authenticated.has(z.socket))return!0;let Q=Buffer.from(String(z.headers["proxy-authorization"]??""));return Q.length===this.authorization.length&&U(Q,this.authorization)}challenge(z){z.end(`HTTP/1.1 407 Proxy Authentication Required\r
1
+ import{createSecureContext as re}from"node:tls";import{createServer as U,request as G}from"node:http";import{request as X}from"node:https";import{TLSSocket as V}from"node:tls";import{connect as J,createServer as Y,isIP as P}from"node:net";import{randomBytes as C,timingSafeEqual as _}from"node:crypto";import{mkdtempSync as Q,rmSync as Z}from"node:fs";import{tmpdir as ee}from"node:os";import{join as b}from"node:path";import{lookup as F}from"dns/promises";import{isIP as k}from"node:net";import{BlockList as H,isIP as N}from"node:net";var O=20000,se=O*4;var z=[["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.31.196.0",24],["192.52.193.0",24],["192.88.99.0",24],["192.168.0.0",16],["192.175.48.0",24],["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]],W=[["::",96],["::1",128],["::ffff:0:0",96],["64:ff9b::",96],["64:ff9b:1::",48],["100::",64],["2001::",23],["2001:db8::",32],["2002::",16],["3fff::",20],["fc00::",7],["fe80::",10],["ff00::",8]];function R(t,e){let o=new H;for(let[n,r]of t)o.addSubnet(n,r,e);return o}var j=R(z,"ipv4"),q=R(W,"ipv6");function w(t){let e=N(t);if(e===4)return j.check(t,"ipv4");if(e===6&&/^::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}$/i.test(t))return!0;if(e===6)return q.check(t,"ipv6");return!0}var K=2000,S=2048,h=async(t)=>{let e;try{return(await Promise.race([F(t,{all:!0}),new Promise((n,r)=>{e=setTimeout(()=>r(Error("DNS timeout")),K)})])).map((n)=>n.address)}finally{clearTimeout(e)}};function L(t){return t.replace(/^\[|\]$/g,"").replace(/\.$/,"").toLowerCase()}function v(t){let e=L(t);if(e==="localhost"||e.endsWith(".localhost"))return!0;if(k(e)===4)return e.startsWith("127.");return e==="::1"}async function x(t,e=h){if(t==="about:blank")return{kind:"loopback",origin:"about:blank"};if(t.length>S)return{kind:"blocked",reason:`URL longer than ${S} characters`};let o;try{o=new URL(t)}catch{return{kind:"blocked",reason:"not a valid URL"}}if(o.protocol!=="http:"&&o.protocol!=="https:")return{kind:"blocked",reason:`${o.protocol} URLs are not allowed; use http or https`};if(o.username||o.password)return{kind:"blocked",reason:"URLs with embedded credentials are not allowed"};let n=o.origin,r=L(o.hostname);if(v(r))return{kind:"loopback",origin:n};if(r==="metadata.google.internal")return{kind:"blocked",origin:n,reason:"cloud metadata endpoints are blocked"};if(k(r))return w(r)?{kind:"blocked",origin:n,reason:`${r} is not a public address`}:{kind:"public",origin:n};let i;try{i=await e(r)}catch{return{kind:"blocked",origin:n,reason:`could not resolve ${r}`}}if(i.length===0)return{kind:"blocked",origin:n,reason:`could not resolve ${r}`};let s=i.find((a)=>w(a));return s?{kind:"blocked",origin:n,reason:`${r} resolves to non-public address ${s}`}:{kind:"public",origin:n}}var te=["connection","proxy-connection","proxy-authorization","proxy-authenticate","keep-alive","te","trailer","transfer-encoding","upgrade"];function T(t){let e={...t},o=String(t.connection??"").split(",").map((n)=>n.trim().toLowerCase());for(let n of[...te,...o])delete e[n];return e}function I(t){return t.replace(/^\[|\]$/g,"").replace(/\.$/,"")}class f{certificate;authorize;resolve;certificateAuthority;username="codimium";password=C(32).toString("hex");realm=C(16).toString("hex");authorization=Buffer.from(`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`);sockets=new Set;tunnel=new WeakMap;authenticated=new WeakSet;server=U();inner=U();innerTls=Y((t)=>this.acceptTls(t));privateDirectory=Q(b(ee(),"deepseek-egress-tls-"));stopped=!1;_url="";constructor(t,e,o,n){this.certificate=t;this.authorize=e;this.resolve=o;this.certificateAuthority=n;this.inner.setTimeout(30000);for(let[r,i]of[[this.server,!1],[this.inner,!0]])r.maxHeadersCount=100,r.headersTimeout=15000,r.requestTimeout=30000,r.on("request",(s,a)=>{this.forward(s,a,i).catch(()=>{if(!a.headersSent)a.writeHead(502);a.end()})}),r.on("upgrade",(s,a,c)=>{this.upgrade(s,a,c,i).catch(()=>a.destroy())}),r.on("connection",(s)=>this.track(s)),r.on("clientError",(s,a)=>a.destroy());this.server.on("connect",(r,i,s)=>{this.connect(r,i,s).catch(()=>i.destroy())})}static async start(t,e,o=h,n){let r=new f(t,e,o,n);try{await new Promise((s,a)=>{r.innerTls.once("error",a),r.innerTls.listen(b(r.privateDirectory,"tls"),()=>{r.innerTls.off("error",a),s()})}),await new Promise((s,a)=>{r.server.once("error",a),r.server.listen(0,"127.0.0.1",()=>{r.server.off("error",a),s()})});let i=r.server.address();if(!i||typeof i==="string")throw r.stop(),Error("Codimium network protection did not bind");return r._url=`http://127.0.0.1:${i.port}`,r}catch(i){throw r.stop(),i}}get url(){return this._url}get cleanupDirectory(){return this.privateDirectory}launchOptions(){return{proxyServer:this.url,proxyBypassList:"<-loopback>",certificateSPKI:this.certificate.spki}}stop(){if(this.stopped)return;this.stopped=!0,this.server.close(),this.innerTls.close();for(let t of this.sockets)t.destroy();this.sockets.clear(),Z(this.privateDirectory,{recursive:!0,force:!0})}track(t){this.sockets.add(t),t.once("close",()=>this.sockets.delete(t)),t.on("error",()=>t.destroy())}hasAuth(t,e=!1){if(e&&this.authenticated.has(t.socket))return!0;let o=Buffer.from(String(t.headers["proxy-authorization"]??""));return o.length===this.authorization.length&&_(o,this.authorization)}challenge(t){t.end(`HTTP/1.1 407 Proxy Authentication Required\r
2
2
  Proxy-Authenticate: Basic realm="${this.realm}"\r
3
3
  Connection: close\r
4
4
  Content-Length: 0\r
5
5
  \r
6
- `)}destination(z){let w=this.tunnel.get(z.socket),Q=w?new URL(z.url??"/",w):new URL(z.url??"");if(!["http:","https:","ws:","wss:"].includes(Q.protocol)||Q.username||Q.password)throw Error("Unsupported proxy URL");if(w&&(Q.host!==w.host||Q.protocol!==w.protocol))throw Error("Tunnel authority changed");if(w&&new URL(`${w.protocol}//${z.headers.host??""}`).host!==w.host)throw Error("Tunnel Host changed");return Q}async endpoint(z){let w=new URL(z);w.protocol=z.protocol==="ws:"?"http:":z.protocol==="wss:"?"https:":z.protocol;let Q=[];if((await E(w.href,async(K)=>{return Q=await this.resolve(K),Q})).kind==="blocked")throw Error("Blocked egress address");let J=_(z.hostname);if(B(J))Q=[J];else if(O(J))Q=["127.0.0.1"];if(!Q.length)throw Error("No verified egress address");let G=Q[0],$=B(G);if(!$||G==="127.0.0.1"&&Number(z.port)===Number(new URL(this.url).port))throw Error("Invalid or recursive egress address");return{address:G,family:$}}async connect(z,w,Q){if(this.stopped){w.destroy();return}if(!this.hasAuth(z)){this.challenge(w);return}let Z=new URL(`https://${z.url}`);if(Z.username||Z.password||Z.pathname!=="/"||Z.search||Z.hash)throw Error("Invalid CONNECT authority");if(await this.endpoint(Z),this.stopped){w.destroy();return}w.write(`HTTP/1.1 200 Connection Established\r
6
+ `)}destination(t){let e=this.tunnel.get(t.socket),o=e?new URL(t.url??"/",e):new URL(t.url??"");if(!["http:","https:","ws:","wss:"].includes(o.protocol)||o.username||o.password)throw Error("Unsupported proxy URL");if(e&&(o.host!==e.host||o.protocol!==e.protocol))throw Error("Tunnel authority changed");if(e&&new URL(`${e.protocol}//${t.headers.host??""}`).host!==e.host)throw Error("Tunnel Host changed");return o}async endpoint(t){let e=new URL(t);e.protocol=t.protocol==="ws:"?"http:":t.protocol==="wss:"?"https:":t.protocol;let o=[];if((await x(e.href,async(a)=>(o=await this.resolve(a),o))).kind==="blocked")throw Error("Blocked egress address");let r=I(t.hostname);if(P(r))o=[r];else if(v(r))o=["127.0.0.1"];if(!o.length)throw Error("No verified egress address");let i=o[0],s=P(i);if(!s||i==="127.0.0.1"&&Number(t.port)===Number(new URL(this.url).port))throw Error("Invalid or recursive egress address");return{address:i,family:s}}async connect(t,e,o){if(this.stopped){e.destroy();return}if(!this.hasAuth(t)){this.challenge(e);return}let n=new URL(`https://${t.url}`);if(n.username||n.password||n.pathname!=="/"||n.search||n.hash)throw Error("Invalid CONNECT authority");if(await this.endpoint(n),this.stopped){e.destroy();return}e.write(`HTTP/1.1 200 Connection Established\r
7
7
  \r
8
- `),w.setTimeout(1e4,()=>w.destroy());let J=(G)=>{if(w.pause(),w.setTimeout(0),G[0]===22){let $=o(x(this.privateDirectory,"tls"));this.track($),$.once("connect",()=>$.write(JSON.stringify({password:this.password,target:Z.href})+`
9
- `));let K="",N=(V)=>{if(K+=V.toString(),!`OK
10
- `.startsWith(K)){$.destroy();return}if(K!==`OK
11
- `)return;$.off("data",N),$.write(G),w.pipe($),$.pipe(w)};$.on("data",N),w.once("close",()=>$.destroy()),$.once("close",()=>w.destroy())}else{let $=new URL(`http://${z.url}`);this.authenticated.add(w),this.tunnel.set(w,$),w.unshift(G),this.inner.emit("connection",w),w.resume()}};if(Q.length)J(Q);else w.once("data",J),w.resume()}acceptTls(z){this.track(z),z.setTimeout(5000,()=>z.destroy());let w="",Q=(Z)=>{if(w+=Z.toString(),w.length>4096){z.destroy();return}if(!w.endsWith(`
12
- `))return;z.off("data",Q);try{let J=JSON.parse(w),G=Buffer.from(J.password??""),$=Buffer.from(this.password);if(G.length!==$.length||!U(G,$)||typeof J.target!=="string")throw Error("Unowned TLS bridge");let K=new URL(J.target);if(K.protocol!=="https:"||K.username||K.password)throw Error("Invalid TLS authority");z.pause(),z.write(`OK
13
- `);let N=new a(z,{isServer:!0,secureContext:this.certificate.context,ALPNProtocols:["http/1.1"]});this.track(N),this.authenticated.add(N),this.tunnel.set(N,K),N.setTimeout(15000,()=>N.destroy()),N.once("secure",()=>N.setTimeout(30000)),this.inner.emit("connection",N),z.resume()}catch{z.destroy()}};z.on("data",Q)}async forward(z,w,Q){if(this.stopped){w.writeHead(503),w.end();return}if(!this.hasAuth(z,Q)){w.writeHead(407,{"proxy-authenticate":`Basic realm="${this.realm}"`}),w.end();return}let Z=this.destination(z);if(!["http:","https:"].includes(Z.protocol)){w.writeHead(400),w.end();return}let J=await this.endpoint(Z);if(!await this.authorize(Z.href)||this.stopped){w.writeHead(403),w.end();return}let G=this.outgoing(z,Z,J,!1);G.on("response",($)=>{w.writeHead($.statusCode??502,M($.headers)),$.on("error",()=>w.destroy()),$.pipe(w)}),G.on("error",()=>{if(!w.headersSent)w.writeHead(502);w.end()}),z.on("aborted",()=>G.destroy()),w.on("close",()=>G.destroy()),z.pipe(G)}outgoing(z,w,Q,Z){let J=M(z.headers);if(J.host=w.host,Z)J.connection="Upgrade",J.upgrade="websocket";let G=["https:","wss:"].includes(w.protocol),K=(G?c:l)({hostname:_(w.hostname),port:w.port||(G?443:80),path:w.pathname+w.search,method:z.method,headers:J,agent:!1,rejectUnauthorized:!0,ca:this.certificateAuthority,lookup:(N,V,C)=>{if(V.all)C(null,[Q]);else C(null,Q.address,Q.family)}});return K.setTimeout(30000,()=>K.destroy()),K}async upgrade(z,w,Q,Z){if(this.stopped){w.destroy();return}if(!this.hasAuth(z,Z)){this.challenge(w);return}if(String(z.headers.upgrade).toLowerCase()!=="websocket")throw Error("Unsupported upgrade");let J=this.destination(z),G=z.headers.origin;if(typeof G!=="string"||!await this.authorize(J.href,G)){w.end(`HTTP/1.1 403 Forbidden\r
8
+ `),e.setTimeout(1e4,()=>e.destroy());let r=(i)=>{if(e.pause(),e.setTimeout(0),i[0]===22){let s=J(b(this.privateDirectory,"tls"));this.track(s),s.once("connect",()=>s.write(JSON.stringify({password:this.password,target:n.href})+`
9
+ `));let a="",c=(l)=>{if(a+=l.toString(),!`OK
10
+ `.startsWith(a)){s.destroy();return}if(a!==`OK
11
+ `)return;s.off("data",c),s.write(i),e.pipe(s),s.pipe(e)};s.on("data",c),e.once("close",()=>s.destroy()),s.once("close",()=>e.destroy())}else{let s=new URL(`http://${t.url}`);this.authenticated.add(e),this.tunnel.set(e,s),e.unshift(i),this.inner.emit("connection",e),e.resume()}};if(o.length)r(o);else e.once("data",r),e.resume()}acceptTls(t){this.track(t),t.setTimeout(5000,()=>t.destroy());let e="",o=(n)=>{if(e+=n.toString(),e.length>4096){t.destroy();return}if(!e.endsWith(`
12
+ `))return;t.off("data",o);try{let r=JSON.parse(e),i=Buffer.from(r.password??""),s=Buffer.from(this.password);if(i.length!==s.length||!_(i,s)||typeof r.target!=="string")throw Error("Unowned TLS bridge");let a=new URL(r.target);if(a.protocol!=="https:"||a.username||a.password)throw Error("Invalid TLS authority");t.pause(),t.write(`OK
13
+ `);let c=new V(t,{isServer:!0,secureContext:this.certificate.context,ALPNProtocols:["http/1.1"]});this.track(c),this.authenticated.add(c),this.tunnel.set(c,a),c.setTimeout(15000,()=>c.destroy()),c.once("secure",()=>c.setTimeout(30000)),this.inner.emit("connection",c),t.resume()}catch{t.destroy()}};t.on("data",o)}async forward(t,e,o){if(this.stopped){e.writeHead(503),e.end();return}if(!this.hasAuth(t,o)){e.writeHead(407,{"proxy-authenticate":`Basic realm="${this.realm}"`}),e.end();return}let n=this.destination(t);if(!["http:","https:"].includes(n.protocol)){e.writeHead(400),e.end();return}let r=await this.endpoint(n);if(!await this.authorize(n.href)||this.stopped){e.writeHead(403),e.end();return}let i=this.outgoing(t,n,r,!1);i.on("response",(s)=>{e.writeHead(s.statusCode??502,T(s.headers)),s.on("error",()=>e.destroy()),s.pipe(e)}),i.on("error",()=>{if(!e.headersSent)e.writeHead(502);e.end()}),t.on("aborted",()=>i.destroy()),e.on("close",()=>i.destroy()),t.pipe(i)}outgoing(t,e,o,n){let r=T(t.headers);if(r.host=e.host,n)r.connection="Upgrade",r.upgrade="websocket";let i=["https:","wss:"].includes(e.protocol),a=(i?X:G)({hostname:I(e.hostname),port:e.port||(i?443:80),path:e.pathname+e.search,method:t.method,headers:r,agent:!1,rejectUnauthorized:!0,ca:this.certificateAuthority,lookup:(c,l,p)=>{if(l.all)p(null,[o]);else p(null,o.address,o.family)}});return a.setTimeout(30000,()=>a.destroy()),a}async upgrade(t,e,o,n){if(this.stopped){e.destroy();return}if(!this.hasAuth(t,n)){this.challenge(e);return}if(String(t.headers.upgrade).toLowerCase()!=="websocket")throw Error("Unsupported upgrade");let r=this.destination(t),i=t.headers.origin;if(typeof i!=="string"||!await this.authorize(r.href,i)){e.end(`HTTP/1.1 403 Forbidden\r
14
14
  Connection: close\r
15
15
  Content-Length: 0\r
16
16
  \r
17
- `);return}let $=await this.endpoint(J);if(this.stopped){w.destroy();return}let K=this.outgoing(z,J,$,!0);K.on("upgrade",(N,V,C)=>{if(K.setTimeout(0),V.setTimeout(0),w.setTimeout(0),this.track(V),this.stopped||w.destroyed){V.destroy();return}let W=M(N.headers);W.connection="Upgrade",W.upgrade="websocket";let v=Object.entries(W).flatMap(([g,X])=>(Array.isArray(X)?X:[X]).filter((j)=>j!==void 0).map((j)=>`${g}: ${j}`));if(w.write(`HTTP/1.1 101 Switching Protocols\r
18
- ${v.join(`\r
17
+ `);return}let s=await this.endpoint(r);if(this.stopped){e.destroy();return}let a=this.outgoing(t,r,s,!0);a.on("upgrade",(c,l,p)=>{if(a.setTimeout(0),l.setTimeout(0),e.setTimeout(0),this.track(l),this.stopped||e.destroyed){l.destroy();return}let m=T(c.headers);m.connection="Upgrade",m.upgrade="websocket";let A=Object.entries(m).flatMap(([M,g])=>(Array.isArray(g)?g:[g]).filter((y)=>y!==void 0).map((y)=>`${M}: ${y}`));if(e.write(`HTTP/1.1 101 Switching Protocols\r
18
+ ${A.join(`\r
19
19
  `)}\r
20
20
  \r
21
- `),C.length)w.write(C);if(Q.length)V.write(Q);w.once("close",()=>V.destroy()),V.once("close",()=>w.destroy()),V.pipe(w),w.pipe(V)}),K.on("response",(N)=>{N.resume(),w.end(`HTTP/1.1 502 Bad Gateway\r
21
+ `),p.length)e.write(p);if(o.length)l.write(o);e.once("close",()=>l.destroy()),l.once("close",()=>e.destroy()),l.pipe(e),e.pipe(l)}),a.on("response",(c)=>{c.resume(),e.end(`HTTP/1.1 502 Bad Gateway\r
22
22
  Connection: close\r
23
23
  Content-Length: 0\r
24
24
  \r
25
- `)}),K.on("error",()=>w.destroy()),w.once("close",()=>K.destroy()),K.end()}}var F,S=!1,Jw=0,y=new Map;function T(z,w){if(!process.connected||y.size>=512)return Promise.reject(Error("Network owner unavailable"));let Q=++Jw;return new Promise((Z,J)=>{let G=setTimeout(()=>{y.delete(Q),J(Error("Network owner timed out"))},5000);y.set(Q,{done($){clearTimeout(G),Z($)},fail(){clearTimeout(G),J(Error("Network owner disconnected"))}}),process.send({type:z,id:Q,...w})})}function A(){F?.stop();for(let z of y.values())z.fail();y.clear(),process.exit(0)}process.on("disconnect",A);process.on("SIGTERM",A);process.on("SIGINT",A);process.on("message",(z)=>{let w=z;if(w.type==="reply"&&typeof w.id==="number"){let Q=y.get(w.id);y.delete(w.id),Q?.done(w.value);return}if(w.type!=="init"||S)return;S=!0,(async()=>{if(!w.key||!w.cert||!w.spki)throw Error("Missing private network identity");let Q={key:w.key,cert:w.cert,spki:w.spki,context:zw({key:w.key,cert:w.cert})};F=await P.start(Q,async(Z,J)=>await T("authorize",{url:Z,origin:J})===!0,w.customResolver?async(Z)=>{let J=await T("resolve",{host:Z});if(!Array.isArray(J)||!J.every((G)=>typeof G==="string"))throw Error("Invalid resolver result");return J}:Y,w.certificateAuthority),process.send({type:"ready",url:F.url,username:F.username,password:F.password,realm:F.realm,cleanupDirectory:F.cleanupDirectory})})().catch(()=>{process.send?.({type:"error"}),F?.stop(),process.exit(1)})});
25
+ `)}),a.on("error",()=>e.destroy()),e.once("close",()=>a.destroy()),a.end()}}var d,B=!1,oe=0,u=new Map;function D(t,e){if(!process.connected||u.size>=512)return Promise.reject(Error("Network owner unavailable"));let o=++oe;return new Promise((n,r)=>{let i=setTimeout(()=>{u.delete(o),r(Error("Network owner timed out"))},5000);u.set(o,{done(s){clearTimeout(i),n(s)},fail(){clearTimeout(i),r(Error("Network owner disconnected"))}}),process.send({type:t,id:o,...e})})}function E(){d?.stop();for(let t of u.values())t.fail();u.clear(),process.exit(0)}process.on("disconnect",E);process.on("SIGTERM",E);process.on("SIGINT",E);process.on("message",(t)=>{let e=t;if(e.type==="reply"&&typeof e.id==="number"){let o=u.get(e.id);u.delete(e.id),o?.done(e.value);return}if(e.type!=="init"||B)return;B=!0,(async()=>{if(!e.key||!e.cert||!e.spki)throw Error("Missing private network identity");let o={key:e.key,cert:e.cert,spki:e.spki,context:re({key:e.key,cert:e.cert})};d=await f.start(o,async(n,r)=>await D("authorize",{url:n,origin:r})===!0,e.customResolver?async(n)=>{let r=await D("resolve",{host:n});if(!Array.isArray(r)||!r.every((i)=>typeof i==="string"))throw Error("Invalid resolver result");return r}:h,e.certificateAuthority),process.send({type:"ready",url:d.url,username:d.username,password:d.password,realm:d.realm,cleanupDirectory:d.cleanupDirectory})})().catch(()=>{process.send?.({type:"error"}),d?.stop(),process.exit(1)})});