codex-copilot-dx 1.3.4 → 1.3.6
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 +4 -2
- package/docs/ARCHITECTURE.md +42 -5
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +31 -2
- package/package.json +1 -1
- package/src/adapter.mjs +13 -8
- package/src/claude-capability-config.mjs +5 -6
- package/src/claude-client-config.mjs +8 -5
- package/src/claude-gateway.mjs +10 -9
- package/src/cli-management.mjs +3 -2
- package/src/client-integration.mjs +1 -1
- package/src/client-model-plan.mjs +10 -0
- package/src/connection-runtime.mjs +31 -9
- package/src/dashboard/connections.js +2 -2
- package/src/dashboard/console.js +2 -0
- package/src/dashboard/index.html +15 -2
- package/src/dashboard/language.js +15 -0
- package/src/dashboard/preferences.js +2 -2
- package/src/dashboard/privacy.js +67 -0
- package/src/dashboard/status.js +3 -1
- package/src/dashboard/ui.css +11 -0
- package/src/dashboard/ui.js +6 -0
- package/src/dashboard-api.mjs +19 -0
- package/src/dashboard.mjs +1 -0
- package/src/local-privacy.mjs +135 -0
- package/src/native-prediction-app.mjs +67 -0
- package/src/native-prediction-fix.mjs +1 -1
- package/src/native-prediction-profile.mjs +2 -36
- package/src/native-prediction-state.mjs +4 -1
- package/src/native-prediction-transport.mjs +21 -7
- package/src/native-prediction-windows.mjs +28 -11
- package/src/native-prediction.mjs +5 -3
- package/src/optional-routes.mjs +2 -2
- package/src/privacy-model.mjs +161 -0
- package/src/privacy-notices.txt +104 -0
- package/src/privacy-transform.mjs +192 -0
- package/src/provider-runtime.mjs +4 -3
- package/src/response-failures.mjs +12 -1
- package/src/responses-handler.mjs +11 -2
- package/src/responses-proxy.mjs +3 -3
- package/src/service-control.mjs +2 -1
- package/src/settings-preferences.mjs +3 -2
- package/src/startup-ui.mjs +1 -1
- package/src/stream-performance.mjs +1 -1
- package/src/terminal-colors.mjs +9 -5
- package/src/usage-analysis.mjs +79 -36
- package/src/usage-analytics.mjs +1 -0
- package/src/usage-store.mjs +21 -11
- package/src/usage.mjs +2 -0
- package/src/user-settings.mjs +3 -3
- package/src/native-prediction-protocol.mjs +0 -45
|
@@ -9,6 +9,7 @@ import { PREDICTION_PAC_PATH, predictionProxyExpression } from "./prediction-pac
|
|
|
9
9
|
export const PREDICTION_HOSTS = Object.freeze(["chatgpt.com", "ab.chatgpt.com"]);
|
|
10
10
|
const CONFIG_LIMIT = 16 * 1024 * 1024;
|
|
11
11
|
const REQUEST_LIMIT = 512 * 1024;
|
|
12
|
+
export const PREDICTION_HEADER_LIMIT = 64 * 1024;
|
|
12
13
|
const decoders = { gzip: promisify(gunzip), deflate: promisify(inflate), br: promisify(brotliDecompress) };
|
|
13
14
|
|
|
14
15
|
export function predictionRoute(host, pathname) {
|
|
@@ -67,7 +68,7 @@ export async function startPredictionTransport({
|
|
|
67
68
|
const upstreams = new Set();
|
|
68
69
|
let closing = false;
|
|
69
70
|
let listenerError = false;
|
|
70
|
-
const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2" }, (req, res) => {
|
|
71
|
+
const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2", maxHeaderSize: PREDICTION_HEADER_LIMIT }, (req, res) => {
|
|
71
72
|
let target;
|
|
72
73
|
try {
|
|
73
74
|
target = new URL(req.url, `https://${req.headers.host}`);
|
|
@@ -82,8 +83,9 @@ export async function startPredictionTransport({
|
|
|
82
83
|
// No decoding/re-encoding on pass-through paths.
|
|
83
84
|
if (route && enabled()) headers["accept-encoding"] = "identity";
|
|
84
85
|
let upstream;
|
|
85
|
-
const fail = (error) => {
|
|
86
|
-
onEvent({ type: "upstream_error", error: operationErrorDetails(error)
|
|
86
|
+
const fail = (error, phase = error?.code === "HPE_HEADER_OVERFLOW" ? "response_headers" : "upstream_request") => {
|
|
87
|
+
onEvent({ type: "upstream_error", error: operationErrorDetails(error), phase,
|
|
88
|
+
target: route || "passthrough", host: target.hostname, header_limit: PREDICTION_HEADER_LIMIT });
|
|
87
89
|
if (!res.headersSent) { res.writeHead(502); res.end(); } else res.destroy();
|
|
88
90
|
};
|
|
89
91
|
const send = (body, streamRemainder = false) => {
|
|
@@ -93,13 +95,14 @@ export async function startPredictionTransport({
|
|
|
93
95
|
servername: target.hostname, method: req.method,
|
|
94
96
|
path: req.url, headers,
|
|
95
97
|
rejectUnauthorized: true,
|
|
98
|
+
maxHeaderSize: PREDICTION_HEADER_LIMIT,
|
|
96
99
|
...(agent ? { agent } : {}),
|
|
97
100
|
}, (reply) => {
|
|
98
101
|
const pass = () => {
|
|
99
102
|
res.writeHead(reply.statusCode, cleanHeaders(reply.headers));
|
|
100
103
|
reply.pipe(res);
|
|
101
104
|
};
|
|
102
|
-
reply.on("error", fail);
|
|
105
|
+
reply.on("error", error => fail(error, "response_body"));
|
|
103
106
|
// Error and non-JSON responses are forwarded as received. The overlay
|
|
104
107
|
// decides whether the narrowly allowed missing-config response applies.
|
|
105
108
|
const mediaType = String(reply.headers["content-type"] || "").split(";", 1)[0].trim();
|
|
@@ -192,11 +195,17 @@ export async function startPredictionTransport({
|
|
|
192
195
|
const upstream = requestImpl({
|
|
193
196
|
protocol: "https:", hostname: host, port: 443, servername: host,
|
|
194
197
|
method: req.method, path: req.url, rejectUnauthorized: true,
|
|
198
|
+
maxHeaderSize: PREDICTION_HEADER_LIMIT,
|
|
195
199
|
...(agent ? { agent } : {}),
|
|
196
200
|
headers: { ...cleanHeaders(req.headers), connection: "Upgrade", upgrade: req.headers.upgrade },
|
|
197
201
|
});
|
|
198
202
|
upstreams.add(upstream);
|
|
199
|
-
upstream.on("error",
|
|
203
|
+
upstream.on("error", error => {
|
|
204
|
+
onEvent({ type: "upstream_error", error: operationErrorDetails(error),
|
|
205
|
+
phase: error.code === "HPE_HEADER_OVERFLOW" ? "response_headers" : "upstream_request",
|
|
206
|
+
target: "upgrade", host, header_limit: PREDICTION_HEADER_LIMIT });
|
|
207
|
+
socket.destroy();
|
|
208
|
+
});
|
|
200
209
|
upstream.on("response", (reply) => {
|
|
201
210
|
const headers = Object.entries(cleanHeaders(reply.headers)).flatMap(([name, values]) =>
|
|
202
211
|
(Array.isArray(values) ? values : [values]).map((value) => `${name}: ${value}`));
|
|
@@ -219,8 +228,13 @@ export async function startPredictionTransport({
|
|
|
219
228
|
upstream.end();
|
|
220
229
|
});
|
|
221
230
|
gateway.on("tlsClientError", (error, socket) => { onEvent({ type: "tls_error", error: operationErrorDetails(error) }); socket.destroy(); });
|
|
222
|
-
gateway.on("clientError", (
|
|
223
|
-
|
|
231
|
+
gateway.on("clientError", (error, socket) => {
|
|
232
|
+
if (socket.destroyed || socket.writableEnded) return;
|
|
233
|
+
onEvent({ type: "client_error", error: operationErrorDetails(error), phase: "request_headers", header_limit: PREDICTION_HEADER_LIMIT });
|
|
234
|
+
if (error.code === "HPE_HEADER_OVERFLOW" && socket.writable) socket.end("HTTP/1.1 431 Request Header Fields Too Large\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
235
|
+
else socket.destroy();
|
|
236
|
+
});
|
|
237
|
+
const proxy = http.createServer({ maxHeaderSize: PREDICTION_HEADER_LIMIT }, (req, res) => {
|
|
224
238
|
if (req.method === "GET" && ["/proxy.pac", PREDICTION_PAC_PATH].includes(req.url) && !req.headers.origin
|
|
225
239
|
&& ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
|
|
226
240
|
res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
|
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
4
5
|
import { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
5
6
|
export { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
6
7
|
|
|
7
8
|
const WINDOWS_PUBLISHER = "CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B";
|
|
8
9
|
const WINDOWS_PACKAGE_FAMILY = "OpenAI.Codex_2p2nqsd0c76g0";
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
|
|
12
|
+
function powershellCommand(script, env) {
|
|
13
|
+
return [path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
|
|
14
|
+
["-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);" + script]];
|
|
15
|
+
}
|
|
9
16
|
|
|
10
17
|
function powershell(script, { env = process.env, exec = execFileSync, ...options } = {}) {
|
|
11
|
-
const command =
|
|
18
|
+
const [command, args] = powershellCommand(script, env);
|
|
12
19
|
try {
|
|
13
|
-
return exec(command,
|
|
14
|
-
"$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);" + script],
|
|
20
|
+
return exec(command, args,
|
|
15
21
|
{ encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024, env: windowsPowerShellEnvironment(env), windowsHide: true, ...options }).trim();
|
|
16
22
|
} catch {
|
|
17
23
|
throw new Error("Windows prediction check failed; verify PowerShell, App registration and current-user permissions");
|
|
@@ -44,13 +50,14 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
|
|
|
44
50
|
return rows;
|
|
45
51
|
}
|
|
46
52
|
|
|
47
|
-
|
|
48
|
-
const raw = powershell(`$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });
|
|
53
|
+
const WINDOWS_APP_SCRIPT = `$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });
|
|
49
54
|
if($p.Count -ne 1){throw 'A single official OpenAI.Codex MSIX registration is required'};
|
|
50
55
|
$m=Get-AppxPackageManifest -Package ([string]$p[0].PackageFullName);
|
|
51
56
|
$a=@($m.Package.Applications.Application | Where-Object { [System.IO.Path]::GetFileName($_.Executable) -in @('Codex.exe','ChatGPT.exe') });
|
|
52
57
|
if($a.Count -ne 1){throw 'Unknown Windows App executable'};
|
|
53
|
-
@{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress
|
|
58
|
+
@{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress`;
|
|
59
|
+
|
|
60
|
+
function registeredApp(raw) {
|
|
54
61
|
let metadata;
|
|
55
62
|
try { metadata = JSON.parse(raw); } catch { throw new Error("Could not read the registered Windows Codex App"); }
|
|
56
63
|
const { root, executable, family } = metadata;
|
|
@@ -61,10 +68,20 @@ export function installedWindowsPredictionApp(options = {}) {
|
|
|
61
68
|
throw new Error("Unknown Windows App registration; prediction setup was skipped");
|
|
62
69
|
}
|
|
63
70
|
const app = path.win32.join(root, executable);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
return { app, family };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function installedWindowsPredictionApp(options = {}) {
|
|
75
|
+
return registeredApp(powershell(WINDOWS_APP_SCRIPT, options));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function installedWindowsPredictionAppAsync({ env = process.env, exec = execFileAsync } = {}) {
|
|
79
|
+
const [command, args] = powershellCommand(WINDOWS_APP_SCRIPT, env);
|
|
80
|
+
let result;
|
|
81
|
+
try { result = await exec(command, args, { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024,
|
|
82
|
+
env: windowsPowerShellEnvironment(env), windowsHide: true }); }
|
|
83
|
+
catch { throw new Error("Windows prediction check failed; verify PowerShell, App registration and current-user permissions"); }
|
|
84
|
+
return registeredApp(String(result?.stdout ?? result).trim());
|
|
68
85
|
}
|
|
69
86
|
|
|
70
87
|
export function windowsPredictionProfile({ app, env = process.env, preferredProfile } = {}) {
|
|
@@ -48,6 +48,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
48
48
|
else if (result.status === "environment_preserved") output(`Network recheck failed; the existing bridge and routes were preserved. ${result.environment_error?.message || "Check ccdx app codex prediction status."}`);
|
|
49
49
|
else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
|
|
50
50
|
else if (prediction.environment?.status === "needs_app_relaunch") output("Network settings changed. The bridge uses the new snapshot, but the App may cache its earlier PAC. Fully quit Codex, then run ccdx; no App was restarted.");
|
|
51
|
+
else if (prediction.client_route === "observed") output("Prediction configuration traffic observed. Visible suggestions still need an App-side check.");
|
|
51
52
|
else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
|
|
52
53
|
else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
|
|
53
54
|
else if (result.status === "route_unverified") output("Bridge is ready, but App route inspection was unavailable or ambiguous. Check ccdx app codex prediction status; no App was restarted.");
|
|
@@ -105,7 +106,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
105
106
|
}
|
|
106
107
|
assertCodexClosed(opts);
|
|
107
108
|
inspectPredictionEnvironment(opts);
|
|
108
|
-
const app = resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
109
|
+
const app = await resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
109
110
|
paths = predictionPaths({ ...opts, app });
|
|
110
111
|
if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
|
|
111
112
|
let certificate, previous, generated = false;
|
|
@@ -168,9 +169,10 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
168
169
|
}
|
|
169
170
|
if (options.expectedPort !== undefined && settings.bridgePort !== options.expectedPort) throw new Error("Prediction route changed; automatic recovery was skipped");
|
|
170
171
|
if (!predictionAppMatches(settings.app)) {
|
|
171
|
-
const current = (options.resolveApp || installedPredictionApp)({ ...opts,
|
|
172
|
+
const current = await (options.resolveApp || installedPredictionApp)({ ...opts,
|
|
172
173
|
...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
173
|
-
|
|
174
|
+
const sameApp = current.app === settings.app?.app || platform === "win32" && current.family && current.family === settings.app?.family;
|
|
175
|
+
if (!sameApp || (platform === "win32" && current.profile !== settings.app?.profile)) {
|
|
174
176
|
throw new Error("Codex App identity/profile changed; run ccdx app codex prediction setup after quitting it to recheck compatibility");
|
|
175
177
|
}
|
|
176
178
|
const settingsFile = predictionPaths(opts).settings;
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js"]);
|
|
2
|
-
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
2
|
+
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
5
5
|
return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import fsSync from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { spawn, execFile } from "node:child_process";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE } from "./release-install.mjs";
|
|
9
|
+
|
|
10
|
+
export const PRIVACY_MODEL_REVISION = "7216b6a3b897ef903d4b1ba367ae6fb95b0fa5e4";
|
|
11
|
+
export const PRIVACY_COMPONENT_RELEASE = "1.3.6";
|
|
12
|
+
export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
13
|
+
{ name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
|
|
14
|
+
{ name: "model_int8.onnx_data", bytes: 37124608, sha256: "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067" },
|
|
15
|
+
{ name: "tokenizer.json", bytes: 1502881, sha256: "0cf3b235ef125658015a6c8026a5fe6f28088bf825101a990ec18a10200feef4" },
|
|
16
|
+
]);
|
|
17
|
+
export const PRIVACY_DOWNLOAD_BYTES = PRIVACY_MODEL_FILES.reduce((n, file) => n + file.bytes, 0);
|
|
18
|
+
export const privacyFailure = code => Object.assign(new Error("Local privacy check could not finish. Nothing was sent; review Settings."), {
|
|
19
|
+
code: `ccdx_privacy_${code}`, statusCode: 503,
|
|
20
|
+
jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message: "Local privacy check could not finish. Nothing was sent; review Settings." } },
|
|
21
|
+
});
|
|
22
|
+
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
23
|
+
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
24
|
+
const root = path.join(env.XDG_CACHE_HOME || (platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local") : path.join(home, ".cache")), "codex-copilot-dx", "privacy");
|
|
25
|
+
const name = `ccdx-privacy-guard-1-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
|
|
26
|
+
return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(root, name), receipt: path.join(root, name + ".json") };
|
|
27
|
+
}
|
|
28
|
+
async function downloader(env) {
|
|
29
|
+
const names = [env.npm_execpath];
|
|
30
|
+
for (const dir of (env.PATH || "").split(path.delimiter)) {
|
|
31
|
+
try { names.push(await fs.realpath(path.join(dir, process.platform === "win32" ? "npm.cmd" : "npm"))); } catch {}
|
|
32
|
+
}
|
|
33
|
+
names.push(path.join(path.dirname(process.execPath), "node_modules/npm/bin/npm-cli.js"), path.join(path.dirname(process.execPath), "../lib/node_modules/npm/bin/npm-cli.js"));
|
|
34
|
+
for (let file of names.filter(Boolean)) {
|
|
35
|
+
if (file.endsWith("npm.cmd")) file = path.join(path.dirname(file), "node_modules/npm/bin/npm-cli.js");
|
|
36
|
+
try { await fs.access(file); } catch { continue; }
|
|
37
|
+
try {
|
|
38
|
+
const { stdout } = await promisify(execFile)(process.execPath, [file, "config", "get", "--global", "https-proxy", "proxy", "noproxy", "cafile", "strict-ssl", "offline"], { env, encoding: "utf8", timeout: 5000, maxBuffer: 131072, windowsHide: true });
|
|
39
|
+
return createNpmReleaseFetch(file, { env, exec: () => stdout });
|
|
40
|
+
} catch { throw privacyFailure("download_unavailable"); }
|
|
41
|
+
}
|
|
42
|
+
throw privacyFailure("download_unavailable");
|
|
43
|
+
}
|
|
44
|
+
export function createPrivacyModel(options = {}) {
|
|
45
|
+
const env = options.env || process.env, paths = privacyPaths(options), changed = options.changed || (() => {});
|
|
46
|
+
let child, serial = 0, ready = null, install = null, downloadAbort, line = "", stopped = false;
|
|
47
|
+
let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
|
|
48
|
+
const jobs = new Map();
|
|
49
|
+
const set = next => { state = { ...state, ...next };changed(); };
|
|
50
|
+
async function installed() {
|
|
51
|
+
try {
|
|
52
|
+
const receipt = JSON.parse(await fs.readFile(paths.receipt, "utf8"));
|
|
53
|
+
if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== PRIVACY_COMPONENT_RELEASE) return false;
|
|
54
|
+
if (digest(await fs.readFile(paths.runner)) !== receipt.sha256) return false;
|
|
55
|
+
for (const file of PRIVACY_MODEL_FILES) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
|
|
56
|
+
return true;
|
|
57
|
+
} catch { return false; }
|
|
58
|
+
}
|
|
59
|
+
async function download() {
|
|
60
|
+
if (install) return install;
|
|
61
|
+
stopped = false;downloadAbort = new AbortController();const signal = downloadAbort.signal;
|
|
62
|
+
install = (async () => {
|
|
63
|
+
set({ state: "downloading", error: null, downloaded_bytes: 0 });
|
|
64
|
+
const fetchImpl = options.fetchImpl || await downloader(env);
|
|
65
|
+
await fs.mkdir(paths.model, { recursive: true, mode: 0o700 });
|
|
66
|
+
const base = `${RELEASE_BASE}/v${PRIVACY_COMPONENT_RELEASE}`;
|
|
67
|
+
const sums = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
68
|
+
const expected = releaseChecksum(sums, paths.name);
|
|
69
|
+
const runner = await releaseBytes(`${base}/${paths.name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024, signal });
|
|
70
|
+
if (digest(runner) !== expected) throw privacyFailure("download_invalid");
|
|
71
|
+
const tempRunner = paths.runner + "." + randomUUID();
|
|
72
|
+
try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
|
|
73
|
+
finally { await fs.rm(tempRunner, { force: true }); }
|
|
74
|
+
await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, sha256: expected }) + "\n", { mode: 0o600 });
|
|
75
|
+
for (const file of PRIVACY_MODEL_FILES) {
|
|
76
|
+
const target = path.join(paths.model, file.name);
|
|
77
|
+
try { if (digest(await fs.readFile(target)) === file.sha256) { set({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
|
|
78
|
+
const response = await fetchImpl(`https://huggingface.co/QuantumNous/astrlink-guard/resolve/${PRIVACY_MODEL_REVISION}/int8/${file.name}`, { signal: AbortSignal.any([signal, AbortSignal.timeout(180000)]), redirect: "follow" });
|
|
79
|
+
const host = response.url && new URL(response.url);
|
|
80
|
+
if (!response.ok || host && (host.protocol !== "https:" || !/^(?:huggingface\.co|[a-z0-9.-]+\.(?:huggingface\.co|hf\.co))$/.test(host.hostname))) { await response.body?.cancel();throw privacyFailure("download_unavailable"); }
|
|
81
|
+
const temp = target + "." + randomUUID(), hash = createHash("sha256"), output = await fs.open(temp, "wx", 0o600);let total = 0;
|
|
82
|
+
try {
|
|
83
|
+
for await (const bytes of response.body || []) {
|
|
84
|
+
if (signal.aborted) throw signal.reason;
|
|
85
|
+
total += bytes.length;if (total > file.bytes) throw privacyFailure("download_invalid");
|
|
86
|
+
hash.update(bytes);await output.write(bytes);set({ downloaded_bytes: state.downloaded_bytes + bytes.length });
|
|
87
|
+
}
|
|
88
|
+
if (total !== file.bytes || hash.digest("hex") !== file.sha256) throw privacyFailure("download_invalid");
|
|
89
|
+
await output.sync();await output.close();await fs.rename(temp, target);
|
|
90
|
+
} finally { await output.close().catch(() => {});await fs.rm(temp, { force: true }); }
|
|
91
|
+
}
|
|
92
|
+
if (signal.aborted || stopped) throw privacyFailure("cancelled");
|
|
93
|
+
set({ state: "installed" });
|
|
94
|
+
})().catch(error => { if (signal.aborted || stopped) { set({ state: "not_downloaded", error: null });throw privacyFailure("cancelled"); }set({ state: "error", error: error.code?.startsWith("ccdx_privacy_") ? error.code : "ccdx_privacy_download_unavailable" });throw privacyFailure("download_unavailable"); })
|
|
95
|
+
.finally(() => { install = null;downloadAbort = null; });
|
|
96
|
+
return install;
|
|
97
|
+
}
|
|
98
|
+
function fail() {
|
|
99
|
+
child?.kill();child = null;ready = null;line = "";
|
|
100
|
+
for (const job of jobs.values()) { clearTimeout(job.timer);job.reject(privacyFailure("engine_unavailable")); }
|
|
101
|
+
jobs.clear();set({ state: stopped ? "installed" : "error", error: stopped ? null : "ccdx_privacy_engine_unavailable" });
|
|
102
|
+
}
|
|
103
|
+
function load() {
|
|
104
|
+
stopped = false;
|
|
105
|
+
if (ready) return ready;
|
|
106
|
+
ready = (async () => {
|
|
107
|
+
if (!await installed()) { set({ state: "not_downloaded" });throw privacyFailure("not_downloaded"); }
|
|
108
|
+
if (stopped) throw privacyFailure("cancelled");
|
|
109
|
+
set({ state: "loading", error: null });
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
|
|
112
|
+
const workerEnv = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TMP", "TEMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "GOMAXPROCS"].filter(key => typeof env[key] === "string").map(key => [key, env[key]]));
|
|
113
|
+
const current = child = (options.spawnImpl || spawn)(paths.runner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
114
|
+
current.stdout.on("data", bytes => {
|
|
115
|
+
if (current !== child) return;
|
|
116
|
+
line += bytes.toString("utf8");if (Buffer.byteLength(line) > 8 * 1024 * 1024) { fail();return; }
|
|
117
|
+
let end;
|
|
118
|
+
while ((end = line.indexOf("\n")) >= 0) {
|
|
119
|
+
const part = line.slice(0, end);line = line.slice(end + 1);
|
|
120
|
+
try {
|
|
121
|
+
const value = JSON.parse(part);
|
|
122
|
+
if (value.ready === true) { clearTimeout(timer);set({ state: "ready", backend: value.backend === "CoreML" ? "CoreML" : "CPU", device: ["CPU", "GPU", "Neural Engine"].includes(value.device) ? value.device : null });resolve(); }
|
|
123
|
+
else if (jobs.has(value.id)) { const job = jobs.get(value.id);jobs.delete(value.id);clearTimeout(job.timer);job.resolve(value.found);changed();if (stopped && !jobs.size) stop(); }
|
|
124
|
+
} catch { fail(); }
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const ended = () => { clearTimeout(timer);reject(privacyFailure(stopped ? "cancelled" : "engine_unavailable"));if (current === child) fail(); };
|
|
128
|
+
current.on("error", ended);current.on("exit", ended);current.stdin.on("error", ended);
|
|
129
|
+
});
|
|
130
|
+
})().catch(error => { ready = null;throw error; });
|
|
131
|
+
return ready;
|
|
132
|
+
}
|
|
133
|
+
async function find(texts, { signal } = {}) {
|
|
134
|
+
if (signal?.aborted) throw signal.reason;await load();if (signal?.aborted) throw signal.reason;
|
|
135
|
+
if (jobs.size >= 8) throw privacyFailure("busy");
|
|
136
|
+
const id = ++serial, input = JSON.stringify({ id, texts }) + "\n";
|
|
137
|
+
if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
138
|
+
if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
const cancelled = () => { if (jobs.has(id)) { jobs.delete(id);clearTimeout(timer);reject(signal?.reason || privacyFailure("cancelled")); } };
|
|
141
|
+
const finish = fn => value => { signal?.removeEventListener("abort", cancelled);fn(value); };
|
|
142
|
+
const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
|
|
143
|
+
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
144
|
+
child.stdin.write(input, error => { if (error) fail(); });
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function stop() { stopped = true;downloadAbort?.abort();if (!jobs.size) { child?.kill();child = null;ready = null;line = "";set({ state: "installed", error: null }); } }
|
|
148
|
+
function snapshot() {
|
|
149
|
+
if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
|
|
150
|
+
try {
|
|
151
|
+
const stat = fsSync.lstatSync(paths.runner);
|
|
152
|
+
const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 && PRIVACY_MODEL_FILES.every(file => fsSync.lstatSync(path.join(paths.model, file.name)).size === file.bytes);
|
|
153
|
+
state = { ...state, state: cached ? "installed" : "not_downloaded" };
|
|
154
|
+
} catch { state = { ...state, state: "not_downloaded" }; }
|
|
155
|
+
}
|
|
156
|
+
return { ...state, pending_checks: jobs.size };
|
|
157
|
+
}
|
|
158
|
+
return { paths, snapshot, installed, download, load, find, stop,
|
|
159
|
+
async remove() { stop();await install?.catch(() => {});if (jobs.size) throw privacyFailure("busy");await fs.rm(paths.root, { recursive: true, force: true });set({ state: "not_downloaded", downloaded_bytes: 0 }); },
|
|
160
|
+
close() { stopped = true;downloadAbort?.abort();fail(); }, busy: () => Boolean(install || jobs.size || state.state === "loading") };
|
|
161
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
native/privacy-guard/LICENSE.magpie
|
|
2
|
+
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2026 yetone
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
native/privacy-guard/vendor/github.com/clipperhouse/uax29/v2/LICENSE
|
|
27
|
+
|
|
28
|
+
MIT License
|
|
29
|
+
|
|
30
|
+
Copyright (c) 2020 Matt Sherman
|
|
31
|
+
|
|
32
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
33
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
34
|
+
in the Software without restriction, including without limitation the rights
|
|
35
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
36
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
37
|
+
furnished to do so, subject to the following conditions:
|
|
38
|
+
|
|
39
|
+
The above copyright notice and this permission notice shall be included in all
|
|
40
|
+
copies or substantial portions of the Software.
|
|
41
|
+
|
|
42
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
43
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
44
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
45
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
46
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
47
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
48
|
+
SOFTWARE.
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
native/privacy-guard/vendor/github.com/clipperhouse/stringish/LICENSE
|
|
52
|
+
|
|
53
|
+
MIT License
|
|
54
|
+
|
|
55
|
+
Copyright (c) 2025 Matt Sherman
|
|
56
|
+
|
|
57
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
58
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
59
|
+
in the Software without restriction, including without limitation the rights
|
|
60
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
61
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
62
|
+
furnished to do so, subject to the following conditions:
|
|
63
|
+
|
|
64
|
+
The above copyright notice and this permission notice shall be included in all
|
|
65
|
+
copies or substantial portions of the Software.
|
|
66
|
+
|
|
67
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
68
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
69
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
70
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
71
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
72
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
73
|
+
SOFTWARE.
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
native/privacy-guard/vendor/golang.org/x/sys/LICENSE
|
|
77
|
+
|
|
78
|
+
Copyright 2009 The Go Authors.
|
|
79
|
+
|
|
80
|
+
Redistribution and use in source and binary forms, with or without
|
|
81
|
+
modification, are permitted provided that the following conditions are
|
|
82
|
+
met:
|
|
83
|
+
|
|
84
|
+
* Redistributions of source code must retain the above copyright
|
|
85
|
+
notice, this list of conditions and the following disclaimer.
|
|
86
|
+
* Redistributions in binary form must reproduce the above
|
|
87
|
+
copyright notice, this list of conditions and the following disclaimer
|
|
88
|
+
in the documentation and/or other materials provided with the
|
|
89
|
+
distribution.
|
|
90
|
+
* Neither the name of Google LLC nor the names of its
|
|
91
|
+
contributors may be used to endorse or promote products derived from
|
|
92
|
+
this software without specific prior written permission.
|
|
93
|
+
|
|
94
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
95
|
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
96
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
97
|
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
98
|
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
99
|
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
100
|
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
101
|
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
102
|
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
103
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
104
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|