codex-copilot-dx 0.9.24 → 0.9.26
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 +15 -12
- package/bin/cli.mjs +24 -32
- package/docs/ARCHITECTURE.md +69 -0
- package/docs/README.md +6 -0
- package/docs/REFERENCE.md +112 -10
- package/package.json +3 -2
- package/src/adapter.mjs +1 -0
- package/src/cli-image.mjs +13 -10
- package/src/cli-options.mjs +1 -1
- package/src/cli-status.mjs +5 -0
- package/src/client-integration.mjs +41 -0
- package/src/codex-config-doctor.mjs +3 -3
- package/src/codex-paths.mjs +10 -0
- package/src/codex-thread-compression.mjs +11 -6
- package/src/config.mjs +10 -6
- package/src/copilot-responses-compat.mjs +30 -2
- package/src/copilot-responses-policy.mjs +14 -3
- package/src/dashboard/index.html +18 -9
- package/src/dashboard/language.js +14 -0
- package/src/dashboard/ui.css +2 -0
- package/src/dashboard/ui.js +10 -0
- package/src/launcher.mjs +50 -2
- package/src/lock.mjs +29 -0
- package/src/native-prediction-profile.mjs +46 -23
- package/src/native-prediction-state.mjs +29 -0
- package/src/native-prediction-transport.mjs +24 -9
- package/src/native-prediction-windows.mjs +174 -0
- package/src/native-prediction.mjs +102 -28
- package/src/network-route.mjs +102 -0
- package/src/observability.mjs +2 -0
- package/src/operation-error.mjs +37 -0
- package/src/package-update.mjs +2 -3
- package/src/prediction-retirement.mjs +13 -2
- package/src/proxy-tunnel.mjs +102 -0
- package/src/responses-proxy.mjs +13 -3
- package/src/responses-request.mjs +35 -2
- package/src/user-settings.mjs +17 -4
- package/src/version.mjs +23 -46
- package/src/windows-prediction-network.cs +154 -0
- package/src/windows-prediction-network.mjs +123 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// App-only worker. Windows owns PAC/WPAD, proxy authentication and TLS trust.
|
|
2
|
+
// Requests and response chunks exist only in anonymous pipes, never files.
|
|
3
|
+
using System;
|
|
4
|
+
using System.Collections.Generic;
|
|
5
|
+
using System.Collections.Concurrent;
|
|
6
|
+
using System.IO;
|
|
7
|
+
using System.Runtime.InteropServices;
|
|
8
|
+
using System.Text;
|
|
9
|
+
using System.Threading;
|
|
10
|
+
using System.Threading.Tasks;
|
|
11
|
+
using System.Web.Script.Serialization;
|
|
12
|
+
|
|
13
|
+
public static class CCDXPredictionNetwork {
|
|
14
|
+
[DllImport("winhttp.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr WinHttpOpen(string agent, uint access, string proxy, string bypass, uint flags);
|
|
15
|
+
[DllImport("winhttp.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr WinHttpConnect(IntPtr session, string host, ushort port, uint reserved);
|
|
16
|
+
[DllImport("winhttp.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr WinHttpOpenRequest(IntPtr connection, string method, string path, string version, string referer, IntPtr accept, uint flags);
|
|
17
|
+
[DllImport("winhttp.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WinHttpSendRequest(IntPtr request, string headers, uint headerLength, byte[] body, uint bodyLength, uint total, IntPtr context);
|
|
18
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpReceiveResponse(IntPtr request, IntPtr reserved);
|
|
19
|
+
[DllImport("winhttp.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WinHttpQueryHeaders(IntPtr request, uint info, string name, IntPtr buffer, ref uint length, IntPtr index);
|
|
20
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpReadData(IntPtr request, byte[] buffer, uint length, out uint read);
|
|
21
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpWriteData(IntPtr request, byte[] buffer, uint length, out uint written);
|
|
22
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpSetOption(IntPtr handle, uint option, ref uint value, uint size);
|
|
23
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpSetTimeouts(IntPtr handle, int resolve, int connect, int send, int receive);
|
|
24
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpCloseHandle(IntPtr handle);
|
|
25
|
+
[DllImport("winhttp.dll", SetLastError=true)] static extern bool WinHttpDetectAutoProxyConfigUrl(uint flags, out IntPtr url);
|
|
26
|
+
[DllImport("kernel32.dll")] static extern IntPtr GlobalFree(IntPtr pointer);
|
|
27
|
+
static readonly object outputLock = new object(), stateLock = new object();
|
|
28
|
+
static readonly Dictionary<int, Work> active = new Dictionary<int, Work>();
|
|
29
|
+
static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength=2*1024*1024 };
|
|
30
|
+
static IntPtr session;
|
|
31
|
+
class Work { public IntPtr handle; public ManualResetEventSlim ack = new ManualResetEventSlim(false); public BlockingCollection<byte[]> upload = new BlockingCollection<byte[]>(2); public bool cancelled; }
|
|
32
|
+
static void Check(bool ok) { if(!ok) throw new IOException("winhttp_" + Marshal.GetLastWin32Error()); }
|
|
33
|
+
static void Emit(object value) { lock(outputLock) { Console.Out.WriteLine(json.Serialize(value)); Console.Out.Flush(); } }
|
|
34
|
+
static string Headers(IntPtr request) {
|
|
35
|
+
uint length=0;
|
|
36
|
+
WinHttpQueryHeaders(request,22,null,IntPtr.Zero,ref length,IntPtr.Zero);
|
|
37
|
+
if(length>65536 || length==0) throw new IOException("winhttp_headers_limit");
|
|
38
|
+
IntPtr memory=Marshal.AllocHGlobal((int)length);
|
|
39
|
+
try { Check(WinHttpQueryHeaders(request,22,null,memory,ref length,IntPtr.Zero)); return Marshal.PtrToStringUni(memory); }
|
|
40
|
+
finally { Marshal.FreeHGlobal(memory); }
|
|
41
|
+
}
|
|
42
|
+
static IntPtr Open(Uri url, string method, out IntPtr connection) {
|
|
43
|
+
connection=WinHttpConnect(session,url.Host,(ushort)url.Port,0);
|
|
44
|
+
Check(connection!=IntPtr.Zero);
|
|
45
|
+
IntPtr request=WinHttpOpenRequest(connection,method,url.PathAndQuery,null,null,IntPtr.Zero,url.Scheme=="https"?0x00800000u:0u);
|
|
46
|
+
Check(request!=IntPtr.Zero);
|
|
47
|
+
// Disable cookies and automatic redirects. Never relax certificate checks
|
|
48
|
+
// or broaden the OS default-credential policy to arbitrary origin servers.
|
|
49
|
+
uint disable=3;
|
|
50
|
+
if(!WinHttpSetOption(request,63,ref disable,4)){WinHttpCloseHandle(request);throw new IOException("winhttp_request_options_failed");}
|
|
51
|
+
return request;
|
|
52
|
+
}
|
|
53
|
+
static string ReadPac(string address) {
|
|
54
|
+
Uri uri;
|
|
55
|
+
if(!Uri.TryCreate(address,UriKind.Absolute,out uri) || (uri.Scheme!="http"&&uri.Scheme!="https") || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0)
|
|
56
|
+
throw new IOException("winhttp_pac_url_invalid");
|
|
57
|
+
IntPtr connection=IntPtr.Zero, request=IntPtr.Zero;
|
|
58
|
+
try {
|
|
59
|
+
request=Open(uri,"GET",out connection);
|
|
60
|
+
Check(WinHttpSendRequest(request,"Accept-Encoding: identity\r\n",uint.MaxValue,null,0,0,IntPtr.Zero));
|
|
61
|
+
Check(WinHttpReceiveResponse(request,IntPtr.Zero));
|
|
62
|
+
string headers=Headers(request);
|
|
63
|
+
if(!headers.StartsWith("HTTP/1.1 200 ")&&!headers.StartsWith("HTTP/1.0 200 ")&&!headers.StartsWith("HTTP/2 200 ")) throw new IOException("winhttp_pac_http_error");
|
|
64
|
+
using(var stream=new MemoryStream()) {
|
|
65
|
+
byte[] bytes=new byte[16384];uint read;
|
|
66
|
+
while(true) { Check(WinHttpReadData(request,bytes,(uint)bytes.Length,out read));if(read==0)break;
|
|
67
|
+
if(stream.Length+read>1024*1024)throw new IOException("winhttp_pac_limit");stream.Write(bytes,0,(int)read); }
|
|
68
|
+
return Convert.ToBase64String(stream.ToArray());
|
|
69
|
+
}
|
|
70
|
+
} finally { if(request!=IntPtr.Zero)WinHttpCloseHandle(request);if(connection!=IntPtr.Zero)WinHttpCloseHandle(connection); }
|
|
71
|
+
}
|
|
72
|
+
static void Request(Dictionary<string,object> data, int id, Work work) {
|
|
73
|
+
IntPtr connection=IntPtr.Zero;
|
|
74
|
+
try {
|
|
75
|
+
var uri=new Uri((string)data["url"]);
|
|
76
|
+
if(uri.Scheme!="https" || uri.Port!=443 || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com")) throw new IOException("winhttp_target_invalid");
|
|
77
|
+
var method=(string)data["method"];
|
|
78
|
+
if(method!="GET"&&method!="POST"&&method!="HEAD"&&method!="PUT"&&method!="DELETE"&&method!="OPTIONS"&&method!="PATCH")throw new IOException("winhttp_method_invalid");
|
|
79
|
+
var headers=(string)data["headers"];
|
|
80
|
+
long length=Convert.ToInt64(data["length"]);
|
|
81
|
+
if(headers.Length>32768 || length>uint.MaxValue)throw new IOException("winhttp_request_limit");
|
|
82
|
+
bool chunked=length<0;
|
|
83
|
+
if(chunked)headers+="Transfer-Encoding: chunked\r\n";
|
|
84
|
+
IntPtr request=Open(uri,method,out connection);
|
|
85
|
+
lock(stateLock) { if(work.cancelled) {WinHttpCloseHandle(request);return;}work.handle=request; }
|
|
86
|
+
Check(WinHttpSendRequest(request,headers,uint.MaxValue,null,0,chunked?0:(uint)length,IntPtr.Zero));
|
|
87
|
+
long uploaded=0;
|
|
88
|
+
foreach(var part in work.upload.GetConsumingEnumerable()) {
|
|
89
|
+
if(work.cancelled)return;
|
|
90
|
+
uploaded+=part.Length;
|
|
91
|
+
if(!chunked&&uploaded>length)throw new IOException("winhttp_upload_length_invalid");
|
|
92
|
+
byte[] bytes=part;
|
|
93
|
+
if(chunked) {
|
|
94
|
+
byte[] prefix=Encoding.ASCII.GetBytes(part.Length.ToString("X")+"\r\n");
|
|
95
|
+
bytes=new byte[prefix.Length+part.Length+2];Buffer.BlockCopy(prefix,0,bytes,0,prefix.Length);Buffer.BlockCopy(part,0,bytes,prefix.Length,part.Length);bytes[bytes.Length-2]=13;bytes[bytes.Length-1]=10;
|
|
96
|
+
}
|
|
97
|
+
uint written;Check(WinHttpWriteData(request,bytes,(uint)bytes.Length,out written));
|
|
98
|
+
if(written!=bytes.Length)throw new IOException("winhttp_upload_write_failed");
|
|
99
|
+
Emit(new {id=id,type="upload_ack"});
|
|
100
|
+
}
|
|
101
|
+
if(work.cancelled)return;
|
|
102
|
+
if(!chunked&&uploaded!=length)throw new IOException("winhttp_upload_length_invalid");
|
|
103
|
+
if(chunked){byte[] last=Encoding.ASCII.GetBytes("0\r\n\r\n");uint written;Check(WinHttpWriteData(request,last,(uint)last.Length,out written));}
|
|
104
|
+
Check(WinHttpReceiveResponse(request,IntPtr.Zero));
|
|
105
|
+
Emit(new {id=id,type="headers",headers=Headers(request)});
|
|
106
|
+
byte[] buffer=new byte[16384];uint read;
|
|
107
|
+
while(true) {
|
|
108
|
+
Check(WinHttpReadData(request,buffer,(uint)buffer.Length,out read));if(read==0)break;
|
|
109
|
+
work.ack.Reset();Emit(new {id=id,type="data",body=Convert.ToBase64String(buffer,0,(int)read)});
|
|
110
|
+
if(!work.ack.Wait(30000))throw new IOException("winhttp_consumer_timeout");
|
|
111
|
+
if(work.cancelled)return;
|
|
112
|
+
}
|
|
113
|
+
Emit(new {id=id,type="end"});
|
|
114
|
+
} catch(Exception error) {
|
|
115
|
+
// Native error codes only: no URLs, headers, cookies or account details.
|
|
116
|
+
Emit(new {id=id,type="error",code=error is IOException?error.Message:"winhttp_request_failed"});
|
|
117
|
+
} finally {
|
|
118
|
+
lock(stateLock) { if(work.handle!=IntPtr.Zero)WinHttpCloseHandle(work.handle);active.Remove(id); }
|
|
119
|
+
if(connection!=IntPtr.Zero)WinHttpCloseHandle(connection);
|
|
120
|
+
work.ack.Dispose();work.upload.Dispose();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
public static void Run() {
|
|
124
|
+
Console.InputEncoding=new UTF8Encoding(false);Console.OutputEncoding=new UTF8Encoding(false);
|
|
125
|
+
session=WinHttpOpen("CCDX native prediction",4,null,null,0);
|
|
126
|
+
try {
|
|
127
|
+
Check(session!=IntPtr.Zero);Check(WinHttpSetTimeouts(session,10000,10000,30000,30000));
|
|
128
|
+
uint protocols=0x800;Check(WinHttpSetOption(session,84,ref protocols,4));
|
|
129
|
+
var initial=json.Deserialize<Dictionary<string,object>>(Console.ReadLine());
|
|
130
|
+
string pac=(string)initial["pac"];
|
|
131
|
+
if(string.IsNullOrWhiteSpace(pac)&&(bool)initial["autoDetect"]) {
|
|
132
|
+
IntPtr address;
|
|
133
|
+
if(WinHttpDetectAutoProxyConfigUrl(3,out address)) {try{pac=Marshal.PtrToStringUni(address);}finally{GlobalFree(address);}}
|
|
134
|
+
else if(Marshal.GetLastWin32Error()!=12180)throw new IOException("winhttp_wpad_discovery_failed");
|
|
135
|
+
}
|
|
136
|
+
Emit(new {type="ready",pac=string.IsNullOrWhiteSpace(pac)?null:ReadPac(pac)});
|
|
137
|
+
string line;
|
|
138
|
+
while((line=Console.ReadLine())!=null) {
|
|
139
|
+
if(line.Length>800000)throw new IOException("winhttp_input_limit");
|
|
140
|
+
var data=json.Deserialize<Dictionary<string,object>>(line);int id=Convert.ToInt32(data["id"]);string op=(string)data["op"];
|
|
141
|
+
lock(stateLock) {
|
|
142
|
+
Work existing;
|
|
143
|
+
if(op=="ack") {if(active.TryGetValue(id,out existing))existing.ack.Set();continue;}
|
|
144
|
+
if(op=="cancel") {if(active.TryGetValue(id,out existing)){existing.cancelled=true;existing.ack.Set();existing.upload.CompleteAdding();if(existing.handle!=IntPtr.Zero){WinHttpCloseHandle(existing.handle);existing.handle=IntPtr.Zero;}}continue;}
|
|
145
|
+
if(op=="upload") {if(active.TryGetValue(id,out existing)){var bytes=Convert.FromBase64String((string)data["body"]);if(bytes.Length>65536||!existing.upload.TryAdd(bytes))throw new IOException("winhttp_upload_limit");}continue;}
|
|
146
|
+
if(op=="upload_end") {if(active.TryGetValue(id,out existing))existing.upload.CompleteAdding();continue;}
|
|
147
|
+
if(op!="request"||id<1||active.ContainsKey(id)||active.Count>=32){Emit(new {id=id,type="error",code="winhttp_admission_limit"});continue;}
|
|
148
|
+
var work=new Work();active.Add(id,work);Task.Run(()=>Request(data,id,work));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch(Exception error) { Emit(new {type="error",code=error is IOException?error.Message:"winhttp_worker_failed"}); }
|
|
152
|
+
finally { lock(stateLock) {foreach(var work in active.Values){work.cancelled=true;work.ack.Set();work.upload.CompleteAdding();if(work.handle!=IntPtr.Zero){WinHttpCloseHandle(work.handle);work.handle=IntPtr.Zero;}}}if(session!=IntPtr.Zero)WinHttpCloseHandle(session); }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { PassThrough, Writable } from "node:stream";
|
|
5
|
+
import { Script } from "node:vm";
|
|
6
|
+
import { windowsPowerShellEnvironment } from "./native-prediction-windows.mjs";
|
|
7
|
+
|
|
8
|
+
function failure(code) {
|
|
9
|
+
return Object.assign(new Error(`Windows prediction network failed (${code}); existing company routes were preserved`), { code });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function companyPredictionPac(script, port) {
|
|
13
|
+
if (typeof script !== "string" || Buffer.byteLength(script) > 1024 * 1024 || !Number.isInteger(port) || port < 1 || port > 65535) throw failure("proxy_pac_invalid");
|
|
14
|
+
// Compile only for syntax validation; never execute a downloaded PAC in Node.
|
|
15
|
+
const combined = `var ccdxCompanyRoute=(function(){\n${script}\n;return FindProxyForURL;})();\nfunction FindProxyForURL(url,host){var original=ccdxCompanyRoute(url,host);if(url.indexOf('https:')===0&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return 'PROXY 127.0.0.1:${port}; '+original;return original;}\n`;
|
|
16
|
+
try { new Script(combined); } catch { throw failure("proxy_pac_invalid"); }
|
|
17
|
+
return combined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// One private child process, reused only by the opted-in prediction bridge.
|
|
21
|
+
// Credit-based response chunks bound buffering when the client reads slowly.
|
|
22
|
+
export async function startWindowsPredictionNetwork({ settings, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {} } = {}) {
|
|
23
|
+
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
24
|
+
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
25
|
+
const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
26
|
+
"$ErrorActionPreference='Stop';Add-Type -Path $env:CCDX_PREDICTION_NETWORK_SOURCE -ReferencedAssemblies System.dll,System.Core.dll,System.Web.Extensions.dll;[CCDXPredictionNetwork]::Run()"],
|
|
27
|
+
{ env: { ...windowsPowerShellEnvironment(env), CCDX_PREDICTION_NETWORK_SOURCE: source }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false });
|
|
28
|
+
const requests = new Map();let sequence = 0, buffer = "", stopped = false, initialized = false, closing = false;
|
|
29
|
+
let resolveReady, rejectReady;
|
|
30
|
+
const ready = new Promise((resolve, reject) => { resolveReady = resolve;rejectReady = reject; });
|
|
31
|
+
const write = value => { if (!stopped && !child.stdin.destroyed) child.stdin.write(JSON.stringify(value) + "\n"); };
|
|
32
|
+
const stop = error => {
|
|
33
|
+
if(stopped)return;stopped=true;rejectReady(error);
|
|
34
|
+
for(const req of [...requests.values()])req.destroy(error);
|
|
35
|
+
child.stdin.destroy();child.kill();
|
|
36
|
+
if(initialized&&!closing)onFailure(error);
|
|
37
|
+
};
|
|
38
|
+
child.on("error", () => stop(failure("proxy_worker_start_failed")));
|
|
39
|
+
child.on("exit", () => stop(failure("proxy_worker_exited")));
|
|
40
|
+
// Consume, but never retain or log compiler stderr (it can include paths).
|
|
41
|
+
child.stderr.resume();child.stdin.on("error", () => stop(failure("proxy_worker_pipe_failed")));
|
|
42
|
+
child.stdout.setEncoding("utf8");
|
|
43
|
+
child.stdout.on("data", chunk => {
|
|
44
|
+
buffer += chunk;
|
|
45
|
+
if(buffer.length > 2*1024*1024)return stop(failure("proxy_worker_output_limit"));
|
|
46
|
+
let boundary;
|
|
47
|
+
while((boundary=buffer.indexOf("\n"))>=0) {
|
|
48
|
+
const line=buffer.slice(0,boundary);buffer=buffer.slice(boundary+1);let event;
|
|
49
|
+
try{event=JSON.parse(line);}catch{return stop(failure("proxy_worker_protocol_error"));}
|
|
50
|
+
if(event.type==="ready") {
|
|
51
|
+
if(event.pac!==null && typeof event.pac!=="string")return stop(failure("proxy_worker_protocol_error"));
|
|
52
|
+
const script=event.pac===null?null:Buffer.from(event.pac,"base64").toString("utf8").replace(/^\uFEFF/, "");
|
|
53
|
+
try{if(script!==null)companyPredictionPac(script,1);}catch(error){return stop(error);}
|
|
54
|
+
resolveReady(script);continue;
|
|
55
|
+
}
|
|
56
|
+
const req=requests.get(event.id);
|
|
57
|
+
if(!req){if(event.type==="error"&&!event.id)return stop(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_worker_failed"));continue;}
|
|
58
|
+
req.frame(event);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
write({autoDetect:settings.autoDetect===true,pac:settings.pac||""});
|
|
62
|
+
const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
|
|
63
|
+
let script;
|
|
64
|
+
try{script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);}
|
|
65
|
+
initialized=true;
|
|
66
|
+
const requestImpl=(options,callback)=>{
|
|
67
|
+
const id=++sequence;let reply,done=false,started=false,uploadCallback;
|
|
68
|
+
const finish=()=>{clearTimeout(deadline);requests.delete(id);done=true;};
|
|
69
|
+
const deadline=setTimeout(()=>req.destroy(failure("proxy_request_timeout")),timeoutMs);
|
|
70
|
+
const start=()=>{
|
|
71
|
+
if(started)return;started=true;
|
|
72
|
+
const host=options.hostname;
|
|
73
|
+
if(!["chatgpt.com","ab.chatgpt.com"].includes(host)||!String(options.path).startsWith("/")||String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
74
|
+
const headers=[];
|
|
75
|
+
for(const [name,value]of Object.entries(options.headers||{})){
|
|
76
|
+
if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
|
|
77
|
+
for(const item of Array.isArray(value)?value:[value]){
|
|
78
|
+
if(/[\r\n]/.test(String(item)))throw failure("proxy_headers_invalid");headers.push(`${name}: ${item}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const headerText=headers.join("\r\n")+"\r\n";
|
|
82
|
+
if(headerText.length>32768)throw failure("proxy_headers_limit");
|
|
83
|
+
if(requests.size>=32)throw failure("proxy_admission_limit");
|
|
84
|
+
const rawLength=options.headers?.["content-length"];
|
|
85
|
+
const length=rawLength===undefined?(["GET","HEAD"].includes(options.method||"GET")?0:-1):Number(rawLength);
|
|
86
|
+
if(!Number.isSafeInteger(length)||length < -1)throw failure("proxy_upload_length_invalid");
|
|
87
|
+
requests.set(id,req);write({op:"request",id,url:`https://${host}${options.path}`,method:options.method||"GET",headers:headerText,length});
|
|
88
|
+
};
|
|
89
|
+
const req=new Writable({highWaterMark:32*1024,autoDestroy:false,
|
|
90
|
+
write(chunk,_encoding,complete){
|
|
91
|
+
try{start();}catch(error){complete(error);return;}
|
|
92
|
+
let offset=0;
|
|
93
|
+
const next=()=>{if(offset>=chunk.length){uploadCallback=undefined;complete();return;}
|
|
94
|
+
const bytes=chunk.subarray(offset,offset+65536);offset+=bytes.length;
|
|
95
|
+
uploadCallback=next;write({op:"upload",id,body:bytes.toString("base64")});};next();
|
|
96
|
+
},
|
|
97
|
+
final(complete){try{start();write({op:"upload_end",id});complete();}catch(error){complete(error);}},
|
|
98
|
+
destroy(error,complete){if(!done){write({op:"cancel",id});finish();reply?.destroy(error);uploadCallback=undefined;}complete(error);},
|
|
99
|
+
});
|
|
100
|
+
req.setTimeout=(milliseconds,handler)=>{if(handler)req.once("timeout",handler);return req;};
|
|
101
|
+
req.frame=event=>{
|
|
102
|
+
deadline.refresh();
|
|
103
|
+
if(event.type==="headers"){
|
|
104
|
+
if(reply||typeof event.headers!=="string"||event.headers.length>65536)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
105
|
+
const lines=event.headers.split("\r\n"),match=/^HTTP\/\S+ (\d{3})(?: (.*))?$/.exec(lines.shift());
|
|
106
|
+
if(!match)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
107
|
+
reply=new PassThrough({highWaterMark:32*1024});reply.statusCode=Number(match[1]);reply.statusMessage=match[2]||"";reply.headers={};
|
|
108
|
+
for(const line of lines){const colon=line.indexOf(":");if(colon<1)continue;const name=line.slice(0,colon).toLowerCase(),value=line.slice(colon+1).trim();
|
|
109
|
+
if(name==="set-cookie")(reply.headers[name]||=[]).push(value);else reply.headers[name]=reply.headers[name]?reply.headers[name]+", "+value:value;}
|
|
110
|
+
reply.once("close",()=>{if(!done)req.destroy();});callback(reply);
|
|
111
|
+
}else if(event.type==="upload_ack"){if(!uploadCallback)return req.destroy(failure("proxy_worker_protocol_error"));uploadCallback();}
|
|
112
|
+
else if(event.type==="data"){
|
|
113
|
+
if(!reply||typeof event.body!=="string"||event.body.length>22000)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
114
|
+
const ack=()=>write({op:"ack",id});if(reply.write(Buffer.from(event.body,"base64")))ack();else reply.once("drain",ack);
|
|
115
|
+
}else if(event.type==="end"){if(!reply)return req.destroy(failure("proxy_worker_protocol_error"));finish();reply.end();}
|
|
116
|
+
else if(event.type==="error")req.destroy(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_request_failed"));
|
|
117
|
+
else req.destroy(failure("proxy_worker_protocol_error"));
|
|
118
|
+
};
|
|
119
|
+
if(stopped)queueMicrotask(()=>req.destroy(failure("proxy_worker_closed")));
|
|
120
|
+
return req;
|
|
121
|
+
};
|
|
122
|
+
return {script,requestImpl,pac:port=>companyPredictionPac(script,port),close(){closing=true;stop(failure("proxy_worker_closed"));}};
|
|
123
|
+
}
|