codex-copilot-dx 1.3.5 → 1.3.7
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 +15 -0
- package/docs/README.md +1 -0
- package/docs/REFERENCE.md +21 -1
- package/package.json +6 -2
- package/src/adapter.mjs +9 -4
- package/src/claude-capability-config.mjs +5 -6
- package/src/claude-client-config.mjs +2 -2
- package/src/claude-gateway.mjs +12 -10
- package/src/connection-runtime.mjs +7 -1
- package/src/dashboard/console.js +2 -0
- package/src/dashboard/index.html +13 -0
- package/src/dashboard/language.js +6 -0
- package/src/dashboard/preferences.js +2 -2
- package/src/dashboard/privacy.js +67 -0
- package/src/dashboard/status.js +4 -2
- package/src/dashboard/ui.css +4 -0
- package/src/dashboard/ui.js +1 -0
- package/src/dashboard-api.mjs +15 -0
- package/src/dashboard.mjs +1 -0
- package/src/local-privacy.mjs +136 -0
- package/src/optional-routes.mjs +2 -2
- package/src/privacy-model.mjs +163 -0
- package/src/privacy-notices.txt +104 -0
- package/src/privacy-transform.mjs +206 -0
- package/src/provider-runtime.mjs +4 -3
- package/src/response-failures.mjs +8 -2
- package/src/responses-handler.mjs +13 -4
- package/src/responses-proxy.mjs +4 -4
- package/src/service-control.mjs +2 -1
- package/src/settings-preferences.mjs +3 -2
- package/src/stream-performance.mjs +2 -2
- package/src/user-settings.mjs +1 -1
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
import { readUserSettings, userSettingsPath } from "./user-settings.mjs";
|
|
5
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
6
|
+
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
7
|
+
import { createChangeSignal } from "./activity-events.mjs";
|
|
8
|
+
import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
|
|
9
|
+
import { maskPrivacyRequest, protectPrivacyResponse } from "./privacy-transform.mjs";
|
|
10
|
+
import { markRequestObservation } from "./stream-performance.mjs";
|
|
11
|
+
|
|
12
|
+
export function createLocalPrivacy(options = {}) {
|
|
13
|
+
const changes = createChangeSignal(), secret = randomBytes(32), cache = new Map(), flights = new Map(), responses = new WeakMap(), policies = new WeakMap();
|
|
14
|
+
const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
|
|
15
|
+
let cacheBytes = 0, generation = 0, pending = null, disposed = false;
|
|
16
|
+
let keyLoaded = false, actionError = null;
|
|
17
|
+
const settings = () => {
|
|
18
|
+
const saved = readUserSettings({ ...options, strict: true });
|
|
19
|
+
return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
|
|
20
|
+
};
|
|
21
|
+
const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
|
|
22
|
+
const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
|
|
23
|
+
function loadKey() {
|
|
24
|
+
if (keyLoaded) return;
|
|
25
|
+
const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
26
|
+
withFileLockSync(file + ".lock", () => {
|
|
27
|
+
try { const bytes = fs.readFileSync(file);if (bytes.length !== 32) throw privacyFailure("key_invalid");bytes.copy(secret); }
|
|
28
|
+
catch (error) { if (error.code !== "ENOENT") throw error;fs.writeFileSync(file, secret, { mode: 0o600, flag: "wx" }); }
|
|
29
|
+
});keyLoaded = true;
|
|
30
|
+
}
|
|
31
|
+
function save(values, expected) {
|
|
32
|
+
const file = userSettingsPath(options);fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
33
|
+
withFileLockSync(file + ".lock", () => {
|
|
34
|
+
const saved = readUserSettings({ ...options, strict: true });
|
|
35
|
+
if (expected && revision(settings()) !== expected) throw privacyFailure("settings_changed");
|
|
36
|
+
atomicWriteFileIfChangedSync(file, JSON.stringify({ ...saved, ...values }, null, 2) + "\n", { mode: 0o600 });
|
|
37
|
+
});changes.changed();
|
|
38
|
+
}
|
|
39
|
+
async function find(texts, { signal } = {}) {
|
|
40
|
+
const waiting = [], fresh = [], entries = [];
|
|
41
|
+
for (const text of texts) {
|
|
42
|
+
const key = createHash("sha256").update(text).digest("hex");
|
|
43
|
+
if (cache.has(key)) {
|
|
44
|
+
const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
|
|
45
|
+
} else if (flights.has(key)) waiting.push(flights.get(key).promise);
|
|
46
|
+
else {
|
|
47
|
+
const entry = Promise.withResolvers();entry.key = key;flights.set(key, entry);
|
|
48
|
+
waiting.push(entry.promise);fresh.push(text);entries.push(entry);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (fresh.length) void model.find(fresh).then(found => {
|
|
52
|
+
if (!Array.isArray(found) || found.length !== fresh.length) throw privacyFailure("engine_invalid");
|
|
53
|
+
for (let i = 0; i < found.length; i++) {
|
|
54
|
+
const cost = Buffer.byteLength(JSON.stringify(found[i] || [])) + 128, entry = entries[i];
|
|
55
|
+
if (cost <= 1024 * 1024) {
|
|
56
|
+
const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
|
|
57
|
+
cache.set(entry.key, { found: found[i] || [], bytes: cost });cacheBytes += cost;
|
|
58
|
+
while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
|
|
59
|
+
}
|
|
60
|
+
entry.resolve(found[i] || []);
|
|
61
|
+
}
|
|
62
|
+
}).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }));
|
|
63
|
+
let listener;
|
|
64
|
+
const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
|
|
65
|
+
try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
|
|
66
|
+
finally { signal?.removeEventListener("abort", listener); }
|
|
67
|
+
}
|
|
68
|
+
async function prepare(body, { protocol, client, signal, res, policy } = {}) {
|
|
69
|
+
const saved = policy || settings();if (!saved.enabled) return body;
|
|
70
|
+
if (disposed) throw privacyFailure("engine_unavailable");
|
|
71
|
+
loadKey();
|
|
72
|
+
const start = performance.now();
|
|
73
|
+
const deadline = AbortSignal.timeout(15000);let session;
|
|
74
|
+
try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
|
|
75
|
+
catch (error) { if (deadline.aborted && !signal?.aborted) throw privacyFailure("check_timeout");throw error; }
|
|
76
|
+
if (signal?.aborted) { session.release();throw signal.reason; }
|
|
77
|
+
markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
|
|
78
|
+
if (res && session.count) {
|
|
79
|
+
let current = responses.get(res);
|
|
80
|
+
if (!current) {
|
|
81
|
+
const sessions = [];
|
|
82
|
+
current = { count: session.count, sessions,
|
|
83
|
+
restoreText: value => sessions.reduce((text, item) => item.restoreText(text), value),
|
|
84
|
+
restoreValue: value => sessions.reduce((text, item) => item.restoreValue(text), value),
|
|
85
|
+
restoreToolValue: value => sessions.reduce((text, item) => item.restoreToolValue(text), value),
|
|
86
|
+
release: () => { sessions.forEach(item => item.release());sessions.length = 0;responses.delete(res); } };
|
|
87
|
+
responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current);
|
|
88
|
+
} else current.sessions.push(session);
|
|
89
|
+
}
|
|
90
|
+
return session.body;
|
|
91
|
+
}
|
|
92
|
+
async function action(input) {
|
|
93
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["action", "revision", "personal", "text"].includes(key))) throw privacyFailure("action_invalid");
|
|
94
|
+
if (input.action === "try") {
|
|
95
|
+
if (typeof input.text !== "string" || Buffer.byteLength(input.text) > 8192 || model.snapshot().state !== "ready") throw privacyFailure("preview_unavailable");
|
|
96
|
+
const start = performance.now(), session = await maskPrivacyRequest({ input: input.text }, { protocol: "responses", client: "preview", personal: settings().personal, secret, find });
|
|
97
|
+
const output = { text: session.body.input, count: session.count, elapsed_ms: Math.round(performance.now() - start) };session.release();return output;
|
|
98
|
+
}
|
|
99
|
+
const before = settings();if (input.revision !== revision(before)) throw privacyFailure("settings_changed");
|
|
100
|
+
if (input.action === "personal") {
|
|
101
|
+
if (typeof input.personal !== "boolean") throw privacyFailure("action_invalid");save({ privacy_personal: input.personal }, input.revision);
|
|
102
|
+
} else if (input.action === "disable" || input.action === "remove") {
|
|
103
|
+
generation++;actionError = null;save({ privacy_enabled: false }, input.revision);model.stop();
|
|
104
|
+
if (input.action === "remove") await model.remove();
|
|
105
|
+
} else if (input.action === "enable") {
|
|
106
|
+
if (pending) return snapshot();
|
|
107
|
+
const current = ++generation;
|
|
108
|
+
const work = (async () => {
|
|
109
|
+
actionError = null;loadKey();
|
|
110
|
+
if (!await model.installed()) await model.download();
|
|
111
|
+
if (current !== generation) return;
|
|
112
|
+
await model.load();if (current !== generation) return;
|
|
113
|
+
save({ privacy_enabled: true }, input.revision);
|
|
114
|
+
})();pending = work;
|
|
115
|
+
void work.catch(error => { if (current === generation) actionError = /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable"; }).finally(() => { if (pending === work) pending = null;changes.changed(); });
|
|
116
|
+
} else throw privacyFailure("action_invalid");
|
|
117
|
+
changes.changed();return snapshot();
|
|
118
|
+
}
|
|
119
|
+
function warm() { const current = generation;if (settings().enabled) void model.load().catch(error => { if (current !== generation || !settings().enabled) return;actionError = /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable";changes.changed(); }); }
|
|
120
|
+
try { warm(); } catch { /* Invalid preferences remain visible and are never rewritten. */ }
|
|
121
|
+
return { snapshot, action, prepare, subscribe: changes.subscribe, busy: () => Boolean(pending || flights.size || model.busy()),
|
|
122
|
+
wrap(fn, context) {
|
|
123
|
+
if (!fn) return fn;
|
|
124
|
+
const policy = context.res && policies.get(context.res) || settings();if (context.res) policies.set(context.res, policy);
|
|
125
|
+
if (!policy.enabled) return fn;
|
|
126
|
+
return async (body, options = {}) => {
|
|
127
|
+
const masked = await prepare(body, { ...context, policy, signal: options.signal });
|
|
128
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
129
|
+
if (!settings().enabled) model.stop();
|
|
130
|
+
return fn(masked, masked === body ? options : { ...options, bodyText: undefined });
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
|
|
134
|
+
settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
|
|
135
|
+
close() { disposed = true;generation++;model.close();cache.clear();cacheBytes = 0;secret.fill(0); } };
|
|
136
|
+
}
|
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,163 @@
|
|
|
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 function privacyFailure(code, phase = "check") {
|
|
19
|
+
const message = phase === "response" ? "Local privacy response restoration failed. The response was stopped; review Settings."
|
|
20
|
+
: "Local privacy check could not finish. Nothing was sent; review Settings.";
|
|
21
|
+
return Object.assign(new Error(message), { code: `ccdx_privacy_${code}`, statusCode: 503, origin: "privacy",
|
|
22
|
+
jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message } } });
|
|
23
|
+
}
|
|
24
|
+
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
25
|
+
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
26
|
+
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");
|
|
27
|
+
const name = `ccdx-privacy-guard-1-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
|
|
28
|
+
return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(root, name), receipt: path.join(root, name + ".json") };
|
|
29
|
+
}
|
|
30
|
+
async function downloader(env) {
|
|
31
|
+
const names = [env.npm_execpath];
|
|
32
|
+
for (const dir of (env.PATH || "").split(path.delimiter)) {
|
|
33
|
+
try { names.push(await fs.realpath(path.join(dir, process.platform === "win32" ? "npm.cmd" : "npm"))); } catch {}
|
|
34
|
+
}
|
|
35
|
+
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"));
|
|
36
|
+
for (let file of names.filter(Boolean)) {
|
|
37
|
+
if (file.endsWith("npm.cmd")) file = path.join(path.dirname(file), "node_modules/npm/bin/npm-cli.js");
|
|
38
|
+
try { await fs.access(file); } catch { continue; }
|
|
39
|
+
try {
|
|
40
|
+
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 });
|
|
41
|
+
return createNpmReleaseFetch(file, { env, exec: () => stdout });
|
|
42
|
+
} catch { throw privacyFailure("download_unavailable"); }
|
|
43
|
+
}
|
|
44
|
+
throw privacyFailure("download_unavailable");
|
|
45
|
+
}
|
|
46
|
+
export function createPrivacyModel(options = {}) {
|
|
47
|
+
const env = options.env || process.env, paths = privacyPaths(options), changed = options.changed || (() => {});
|
|
48
|
+
let child, serial = 0, ready = null, install = null, downloadAbort, line = "", stopped = false;
|
|
49
|
+
let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
|
|
50
|
+
const jobs = new Map();
|
|
51
|
+
const set = next => { state = { ...state, ...next };changed(); };
|
|
52
|
+
async function installed() {
|
|
53
|
+
try {
|
|
54
|
+
const receipt = JSON.parse(await fs.readFile(paths.receipt, "utf8"));
|
|
55
|
+
if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== PRIVACY_COMPONENT_RELEASE) return false;
|
|
56
|
+
if (digest(await fs.readFile(paths.runner)) !== receipt.sha256) return false;
|
|
57
|
+
for (const file of PRIVACY_MODEL_FILES) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
|
|
58
|
+
return true;
|
|
59
|
+
} catch { return false; }
|
|
60
|
+
}
|
|
61
|
+
async function download() {
|
|
62
|
+
if (install) return install;
|
|
63
|
+
stopped = false;downloadAbort = new AbortController();const signal = downloadAbort.signal;
|
|
64
|
+
install = (async () => {
|
|
65
|
+
set({ state: "downloading", error: null, downloaded_bytes: 0 });
|
|
66
|
+
const fetchImpl = options.fetchImpl || await downloader(env);
|
|
67
|
+
await fs.mkdir(paths.model, { recursive: true, mode: 0o700 });
|
|
68
|
+
const base = `${RELEASE_BASE}/v${PRIVACY_COMPONENT_RELEASE}`;
|
|
69
|
+
const sums = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
70
|
+
const expected = releaseChecksum(sums, paths.name);
|
|
71
|
+
const runner = await releaseBytes(`${base}/${paths.name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024, signal });
|
|
72
|
+
if (digest(runner) !== expected) throw privacyFailure("download_invalid");
|
|
73
|
+
const tempRunner = paths.runner + "." + randomUUID();
|
|
74
|
+
try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
|
|
75
|
+
finally { await fs.rm(tempRunner, { force: true }); }
|
|
76
|
+
await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, sha256: expected }) + "\n", { mode: 0o600 });
|
|
77
|
+
for (const file of PRIVACY_MODEL_FILES) {
|
|
78
|
+
const target = path.join(paths.model, file.name);
|
|
79
|
+
try { if (digest(await fs.readFile(target)) === file.sha256) { set({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
|
|
80
|
+
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" });
|
|
81
|
+
const host = response.url && new URL(response.url);
|
|
82
|
+
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"); }
|
|
83
|
+
const temp = target + "." + randomUUID(), hash = createHash("sha256"), output = await fs.open(temp, "wx", 0o600);let total = 0;
|
|
84
|
+
try {
|
|
85
|
+
for await (const bytes of response.body || []) {
|
|
86
|
+
if (signal.aborted) throw signal.reason;
|
|
87
|
+
total += bytes.length;if (total > file.bytes) throw privacyFailure("download_invalid");
|
|
88
|
+
hash.update(bytes);await output.write(bytes);set({ downloaded_bytes: state.downloaded_bytes + bytes.length });
|
|
89
|
+
}
|
|
90
|
+
if (total !== file.bytes || hash.digest("hex") !== file.sha256) throw privacyFailure("download_invalid");
|
|
91
|
+
await output.sync();await output.close();await fs.rename(temp, target);
|
|
92
|
+
} finally { await output.close().catch(() => {});await fs.rm(temp, { force: true }); }
|
|
93
|
+
}
|
|
94
|
+
if (signal.aborted || stopped) throw privacyFailure("cancelled");
|
|
95
|
+
set({ state: "installed" });
|
|
96
|
+
})().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"); })
|
|
97
|
+
.finally(() => { install = null;downloadAbort = null; });
|
|
98
|
+
return install;
|
|
99
|
+
}
|
|
100
|
+
function fail() {
|
|
101
|
+
child?.kill();child = null;ready = null;line = "";
|
|
102
|
+
for (const job of jobs.values()) { clearTimeout(job.timer);job.reject(privacyFailure("engine_unavailable")); }
|
|
103
|
+
jobs.clear();set({ state: stopped ? "installed" : "error", error: stopped ? null : "ccdx_privacy_engine_unavailable" });
|
|
104
|
+
}
|
|
105
|
+
function load() {
|
|
106
|
+
stopped = false;
|
|
107
|
+
if (ready) return ready;
|
|
108
|
+
ready = (async () => {
|
|
109
|
+
if (!await installed()) { set({ state: "not_downloaded" });throw privacyFailure("not_downloaded"); }
|
|
110
|
+
if (stopped) throw privacyFailure("cancelled");
|
|
111
|
+
set({ state: "loading", error: null });
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
|
|
114
|
+
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]]));
|
|
115
|
+
const current = child = (options.spawnImpl || spawn)(paths.runner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
116
|
+
current.stdout.on("data", bytes => {
|
|
117
|
+
if (current !== child) return;
|
|
118
|
+
line += bytes.toString("utf8");if (Buffer.byteLength(line) > 8 * 1024 * 1024) { fail();return; }
|
|
119
|
+
let end;
|
|
120
|
+
while ((end = line.indexOf("\n")) >= 0) {
|
|
121
|
+
const part = line.slice(0, end);line = line.slice(end + 1);
|
|
122
|
+
try {
|
|
123
|
+
const value = JSON.parse(part);
|
|
124
|
+
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(); }
|
|
125
|
+
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(); }
|
|
126
|
+
} catch { fail(); }
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
const ended = () => { clearTimeout(timer);reject(privacyFailure(stopped ? "cancelled" : "engine_unavailable"));if (current === child) fail(); };
|
|
130
|
+
current.on("error", ended);current.on("exit", ended);current.stdin.on("error", ended);
|
|
131
|
+
});
|
|
132
|
+
})().catch(error => { ready = null;throw error; });
|
|
133
|
+
return ready;
|
|
134
|
+
}
|
|
135
|
+
async function find(texts, { signal } = {}) {
|
|
136
|
+
if (signal?.aborted) throw signal.reason;await load();if (signal?.aborted) throw signal.reason;
|
|
137
|
+
if (jobs.size >= 8) throw privacyFailure("busy");
|
|
138
|
+
const id = ++serial, input = JSON.stringify({ id, texts }) + "\n";
|
|
139
|
+
if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
140
|
+
if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
const cancelled = () => { if (jobs.has(id)) { jobs.delete(id);clearTimeout(timer);reject(signal?.reason || privacyFailure("cancelled")); } };
|
|
143
|
+
const finish = fn => value => { signal?.removeEventListener("abort", cancelled);fn(value); };
|
|
144
|
+
const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
|
|
145
|
+
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
146
|
+
child.stdin.write(input, error => { if (error) fail(); });
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function stop() { stopped = true;downloadAbort?.abort();if (!jobs.size) { child?.kill();child = null;ready = null;line = "";set({ state: "installed", error: null }); } }
|
|
150
|
+
function snapshot() {
|
|
151
|
+
if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
|
|
152
|
+
try {
|
|
153
|
+
const stat = fsSync.lstatSync(paths.runner);
|
|
154
|
+
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);
|
|
155
|
+
state = { ...state, state: cached ? "installed" : "not_downloaded" };
|
|
156
|
+
} catch { state = { ...state, state: "not_downloaded" }; }
|
|
157
|
+
}
|
|
158
|
+
return { ...state, pending_checks: jobs.size };
|
|
159
|
+
}
|
|
160
|
+
return { paths, snapshot, installed, download, load, find, stop,
|
|
161
|
+
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 }); },
|
|
162
|
+
close() { stopped = true;downloadAbort?.abort();fail(); }, busy: () => Boolean(install || jobs.size || state.state === "loading") };
|
|
163
|
+
}
|
|
@@ -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.
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
import { privacyFailure } from "./privacy-model.mjs";
|
|
4
|
+
|
|
5
|
+
const TOKEN_START = "{{CCDX_", tokenPattern = /\{\{CCDX_[a-f0-9]{24}\}\}/g;
|
|
6
|
+
const secretPatterns = [
|
|
7
|
+
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|AIza[A-Za-z0-9_-]{25,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16}|hf_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,})\b/g,
|
|
8
|
+
/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g,
|
|
9
|
+
];
|
|
10
|
+
const secretField = /(?:["']?\b(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password)\b["']?\s*[:=]\s*)(?:"((?:\\.|[^"\\\r\n])+)"|'((?:\\.|[^'\\\r\n])+)'|([^\s,;\r\n}]+))/gdi;
|
|
11
|
+
const personalKinds = new Set(["email", "phone", "account", "payment_card", "private_address", "private_date", "private_person"]);
|
|
12
|
+
const kept = new Set(["model", "id", "type", "role", "name", "namespace", "server_label", "server_name", "call_id", "tool_use_id", "item_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id", "previous_response_id", "prompt_cache_key", "media_type", "mime_type", "stop_reason", "finish_reason", "status", "object", "event"]);
|
|
13
|
+
function leaves(value, add, inArguments = false) {
|
|
14
|
+
if (typeof value === "string") return;
|
|
15
|
+
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i], inArguments) : leaves(value[i], add, inArguments);return; }
|
|
16
|
+
if (!value || typeof value !== "object") return;
|
|
17
|
+
if (!inArguments && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return;
|
|
18
|
+
for (const [key, item] of Object.entries(value)) {
|
|
19
|
+
if (!inArguments && kept.has(key)) continue;
|
|
20
|
+
if (typeof item === "string") add(value, key, item, inArguments);
|
|
21
|
+
else leaves(item, add, inArguments);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function requestTexts(body, protocol) {
|
|
25
|
+
const items = [], nested = [];
|
|
26
|
+
const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|token)$/i.test(String(key)) }); };
|
|
27
|
+
const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
|
|
28
|
+
const args = (parent, key) => {
|
|
29
|
+
if (typeof parent[key] === "string") {
|
|
30
|
+
try { const value = JSON.parse(parent[key]);leaves(value, add, true);nested.push({ parent, key, value }); }
|
|
31
|
+
catch { throw privacyFailure("arguments_invalid"); }
|
|
32
|
+
} else leaves(parent[key], add, true);
|
|
33
|
+
};
|
|
34
|
+
const descriptions = value => {
|
|
35
|
+
if (!value || typeof value !== "object") return;
|
|
36
|
+
for (const [key, item] of Object.entries(value)) { if (key === "description" && typeof item === "string") add(value, key, item);else if (item && typeof item === "object") descriptions(item); }
|
|
37
|
+
};
|
|
38
|
+
descriptions(body.tools);
|
|
39
|
+
if (protocol === "messages" || protocol === "chat") {
|
|
40
|
+
text(body, "system");
|
|
41
|
+
for (const message of body.messages || []) {
|
|
42
|
+
text(message, "content");
|
|
43
|
+
for (const call of message.tool_calls || []) if (call?.function?.arguments) args(call.function, "arguments");
|
|
44
|
+
if (Array.isArray(message.content)) for (const block of message.content) {
|
|
45
|
+
if (block?.type === "tool_use") args(block, "input");
|
|
46
|
+
if (block?.type === "tool_result") text(block, "content");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
} else {
|
|
50
|
+
text(body, "instructions");
|
|
51
|
+
if (typeof body.input === "string") add(body, "input", body.input);
|
|
52
|
+
else for (const item of body.input || []) {
|
|
53
|
+
if (["additional_tools", "tool_search_output"].includes(item.type)) descriptions(item.tools);
|
|
54
|
+
else if (item.type === "function_call") args(item, "arguments");
|
|
55
|
+
else if (["function_call_output", "custom_tool_call_output"].includes(item.type)) text(item, "output");
|
|
56
|
+
else if (item.type === "custom_tool_call") text(item, "input");
|
|
57
|
+
else text(item, "content");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { items, nested };
|
|
61
|
+
}
|
|
62
|
+
function ruleSpans(text, personal) {
|
|
63
|
+
const spans = [];
|
|
64
|
+
for (const pattern of secretPatterns) { pattern.lastIndex = 0;for (const m of text.matchAll(pattern)) spans.push({ start: m.index, end: m.index + m[0].length, kind: "secret" }); }
|
|
65
|
+
secretField.lastIndex = 0;
|
|
66
|
+
for (const m of text.matchAll(secretField)) { const at = m.indices[1] || m.indices[2] || m.indices[3];spans.push({ start: at[0], end: at[1], kind: "secret" }); }
|
|
67
|
+
if (personal) for (const m of text.matchAll(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi)) {
|
|
68
|
+
if (!/@(?:example\.(?:com|org|net)|[^@]*\.(?:test|invalid))$/i.test(m[0])) spans.push({ start: m.index, end: m.index + m[0].length, kind: "email" });
|
|
69
|
+
}
|
|
70
|
+
return spans;
|
|
71
|
+
}
|
|
72
|
+
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal }) {
|
|
73
|
+
const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
74
|
+
if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
75
|
+
const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
76
|
+
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
77
|
+
for (let i = 0; i < items.length; i++) {
|
|
78
|
+
const item = items[i], bytes = Buffer.from(item.text), spans = ruleSpans(item.text, personal);
|
|
79
|
+
if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
|
|
80
|
+
for (const span of found[i] || []) {
|
|
81
|
+
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
|
|
82
|
+
if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
|
|
83
|
+
const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
|
|
84
|
+
spans.push({ start, end, kind: span.label === "common_secret" ? "secret" : span.label });
|
|
85
|
+
}
|
|
86
|
+
spans.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
87
|
+
let end = 0, output = "";
|
|
88
|
+
for (const span of spans) {
|
|
89
|
+
if (span.start < end) continue;
|
|
90
|
+
const value = item.text.slice(span.start, span.end);
|
|
91
|
+
if (!value || tokenPattern.test(value)) { tokenPattern.lastIndex = 0;continue; }
|
|
92
|
+
tokenPattern.lastIndex = 0;
|
|
93
|
+
const token = `{{CCDX_${createHmac("sha256", secret).update(client + "\0" + value).digest("hex").slice(0, 24)}}}`;
|
|
94
|
+
if (!values.has(token)) { total.bytes += Buffer.byteLength(value);if (values.size >= 8192 || total.bytes > 4 * 1024 * 1024) throw privacyFailure("mapping_limit");values.set(token, value); }
|
|
95
|
+
output += item.text.slice(end, span.start) + token;end = span.end;total.count++;kinds[span.kind] = (kinds[span.kind] || 0) + 1;
|
|
96
|
+
}
|
|
97
|
+
if (end) item.parent[item.key] = output + item.text.slice(end);
|
|
98
|
+
}
|
|
99
|
+
if (total.count) for (const item of nested) item.parent[item.key] = JSON.stringify(item.value);
|
|
100
|
+
const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
|
|
101
|
+
function restoreValue(value, inToolData = false) {
|
|
102
|
+
if (typeof value === "string") return restoreText(value);
|
|
103
|
+
if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
|
|
104
|
+
if (!value || typeof value !== "object") return value;
|
|
105
|
+
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
|
|
106
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
|
|
107
|
+
: !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
108
|
+
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
|
|
109
|
+
}
|
|
110
|
+
function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text), true)); } catch { return restoreText(text); } }
|
|
111
|
+
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
112
|
+
restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function rewritePrivacyFrame(wire, value, named = false) {
|
|
116
|
+
let written = false;
|
|
117
|
+
const lines = wire.split(/(?<=\n)/).map(line => {
|
|
118
|
+
if (!line.startsWith("data:")) return line;
|
|
119
|
+
if (written) return "";
|
|
120
|
+
written = true;
|
|
121
|
+
return `data: ${JSON.stringify(value)}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
122
|
+
}).join("");
|
|
123
|
+
return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function createPrivacyStream(session) {
|
|
127
|
+
const fail = code => privacyFailure(code, "response");
|
|
128
|
+
let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
129
|
+
function transform(wire) {
|
|
130
|
+
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
131
|
+
if (!data || data === "[DONE]") return wire;
|
|
132
|
+
let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
133
|
+
if (["error", "response.failed", "response.incomplete"].includes(event.type)) { channels.clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
|
|
134
|
+
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
135
|
+
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
136
|
+
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
137
|
+
const text = delta?.type === "text_delta" || ["response.output_text.delta", "response.custom_tool_call_input.delta"].includes(event.type);
|
|
138
|
+
let before = "";
|
|
139
|
+
const key = isMessages ? `m:${event.index}` : `r:${event.item_id || event.item?.id || event.output_index}:${event.content_index || 0}`;
|
|
140
|
+
if (tool || text) {
|
|
141
|
+
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
142
|
+
if (typeof delta[field] !== "string") throw fail("stream_invalid");
|
|
143
|
+
const channel = channels.get(key) || { tail: "", tool, field };channel.template = event;channel.wire = wire;
|
|
144
|
+
let value = channel.tail + delta[field];
|
|
145
|
+
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
146
|
+
if (tool) { channel.tail = value;channels.set(key, channel);return ""; }
|
|
147
|
+
else {
|
|
148
|
+
let cut = value.length;
|
|
149
|
+
const at = value.lastIndexOf("{{CCDX_");
|
|
150
|
+
if (at >= 0 && !value.slice(at).includes("}}")) cut = at;
|
|
151
|
+
else for (let n = 1; n < TOKEN_START.length; n++) if (value.endsWith(TOKEN_START.slice(0, n))) cut = value.length - n;
|
|
152
|
+
channel.tail = value.slice(cut);delta[field] = session.restoreText(value.slice(0, cut));
|
|
153
|
+
}
|
|
154
|
+
channels.set(key, channel);
|
|
155
|
+
}
|
|
156
|
+
const stopKey = event.type === "content_block_stop" ? `m:${event.index}` : /\.done$/.test(event.type || "") ? key : null;
|
|
157
|
+
const terminal = ["message_stop", "response.completed", "response.incomplete", "error", "response.failed"].includes(event.type);
|
|
158
|
+
for (const [id, channel] of channels) if (terminal || id === stopKey) {
|
|
159
|
+
if (channel.tail) {
|
|
160
|
+
const value = structuredClone(channel.template), target = value.type === "content_block_delta" ? value.delta : value;
|
|
161
|
+
try { target[channel.field] = channel.tool ? JSON.stringify(session.restoreToolValue(JSON.parse(channel.tail))) : session.restoreText(channel.tail); }
|
|
162
|
+
catch { throw fail("stream_invalid"); }
|
|
163
|
+
before += rewritePrivacyFrame(channel.wire, value, true);
|
|
164
|
+
}
|
|
165
|
+
channels.delete(id);
|
|
166
|
+
}
|
|
167
|
+
event = session.restoreValue(event);
|
|
168
|
+
return before + rewritePrivacyFrame(wire, event);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
push(chunk) {
|
|
172
|
+
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
173
|
+
let output = "", match;
|
|
174
|
+
while ((match = /\r?\n\r?\n/.exec(pending))) { const end = match.index + match[0].length;output += transform(pending.slice(0, end));pending = pending.slice(end);bytes = Buffer.byteLength(pending); }
|
|
175
|
+
return output;
|
|
176
|
+
},
|
|
177
|
+
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw fail("stream_incomplete");return ""; },
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function protectPrivacyResponse(res, session) {
|
|
182
|
+
if (!session.count) return;
|
|
183
|
+
const write = res.write.bind(res), end = res.end.bind(res), writeHead = res.writeHead.bind(res), stream = createPrivacyStream(session);
|
|
184
|
+
let mode = null, parts = [], size = 0;
|
|
185
|
+
const detach = () => { res.write = write;res.end = end;res.writeHead = writeHead;parts = [];session.release(); };
|
|
186
|
+
res.writeHead = (code, ...args) => {
|
|
187
|
+
const headers = args.find(value => value && typeof value === "object" && !Array.isArray(value));
|
|
188
|
+
if (headers) { const copy = { ...headers };for (const key of Object.keys(copy)) if (key.toLowerCase() === "content-length") delete copy[key];args[args.indexOf(headers)] = copy; }
|
|
189
|
+
res.removeHeader("Content-Length");mode = String(headers?.["Content-Type"] || headers?.["content-type"] || res.getHeader("Content-Type") || "").includes("text/event-stream") ? "stream" : "json";
|
|
190
|
+
return writeHead(code, ...args);
|
|
191
|
+
};
|
|
192
|
+
res.write = (value, encoding, callback) => {
|
|
193
|
+
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, typeof encoding === "string" ? encoding : undefined);
|
|
194
|
+
if (mode === "stream") { try { const output = stream.push(bytes);return output ? write(output, typeof encoding === "function" ? encoding : callback) : true; }catch (error) { detach();throw error; } }
|
|
195
|
+
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit", "response");parts.push(bytes);return true;
|
|
196
|
+
};
|
|
197
|
+
res.end = (value, encoding, callback) => {
|
|
198
|
+
if (value !== undefined && value !== null) res.write(value, encoding);
|
|
199
|
+
let output;
|
|
200
|
+
if (mode === "stream") { try { output = stream.finish(); }catch (error) { detach();throw error; } }
|
|
201
|
+
else if (parts.length) { const text = Buffer.concat(parts).toString("utf8");try { output = JSON.stringify(session.restoreValue(JSON.parse(text))); }catch { output = session.restoreText(text); }parts = []; }
|
|
202
|
+
return end(output || undefined, typeof encoding === "function" ? encoding : callback);
|
|
203
|
+
};
|
|
204
|
+
const release = () => { session.release();parts = []; };
|
|
205
|
+
res.once("finish", release);res.once("close", release);
|
|
206
|
+
}
|