codex-copilot-dx 1.3.11 → 1.3.13
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 +2 -2
- package/docs/ARCHITECTURE.md +13 -7
- package/docs/REFERENCE.md +10 -6
- package/package.json +1 -1
- package/src/cli-command-spec.mjs +1 -1
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/features.js +2 -1
- package/src/dashboard/index.html +6 -7
- package/src/dashboard/language.js +4 -3
- package/src/dashboard/privacy.js +2 -0
- package/src/dashboard/ui.css +4 -4
- package/src/http-transport.mjs +2 -1
- package/src/local-privacy.mjs +32 -72
- package/src/privacy-detection.mjs +130 -0
- package/src/privacy-findings.mjs +16 -0
- package/src/privacy-model.mjs +37 -8
- package/src/privacy-stream.mjs +287 -0
- package/src/privacy-transform.mjs +44 -112
- package/src/stream-performance.mjs +6 -2
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { createHash, createHmac } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { createPrivacyStream } from "./privacy-stream.mjs";
|
|
3
|
+
export { createPrivacyStream };
|
|
3
4
|
import { privacyFailure } from "./privacy-model.mjs";
|
|
5
|
+
import { validatePrivacyFindings } from "./privacy-findings.mjs";
|
|
6
|
+
export { validatePrivacyFindings };
|
|
7
|
+
import { markRequestObservation, markResponseTerminal } from "./stream-performance.mjs";
|
|
4
8
|
|
|
5
9
|
const TOKEN_START = "{{CCDX_", tokenPattern = /\{\{CCDX_[a-f0-9]{24}\}\}/g;
|
|
6
10
|
const secretPatterns = [
|
|
@@ -63,7 +67,17 @@ function ruleSpans(text, personal) {
|
|
|
63
67
|
const spans = [];
|
|
64
68
|
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
69
|
secretField.lastIndex = 0;
|
|
66
|
-
|
|
70
|
+
let match;
|
|
71
|
+
while ((match = secretField.exec(text))) {
|
|
72
|
+
const at = match.indices[1] || match.indices[2] || match.indices[3];
|
|
73
|
+
// An empty unquoted value followed by another assignment belongs to the
|
|
74
|
+
// next field. Restart there so its own secret field is still checked.
|
|
75
|
+
if (match.indices[3] && /\s/.test(text[at[0] - 1] || "")
|
|
76
|
+
&& /^[A-Za-z_][\w.-]*=(?=\S)/.test(text.slice(at[0], at[1]))) {
|
|
77
|
+
secretField.lastIndex = at[0];continue;
|
|
78
|
+
}
|
|
79
|
+
spans.push({ start: at[0], end: at[1], kind: "secret" });
|
|
80
|
+
}
|
|
67
81
|
if (personal) for (const m of text.matchAll(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi)) {
|
|
68
82
|
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
83
|
}
|
|
@@ -92,6 +106,8 @@ export function createPrivacyRuleCache({ maxBytes = 1024 * 1024, maxEntries = 20
|
|
|
92
106
|
}
|
|
93
107
|
function modelSpanFits(text, start, end, label) {
|
|
94
108
|
const value = text.slice(start, end);
|
|
109
|
+
if (label === "common_secret" && text[end] === "("
|
|
110
|
+
&& /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(value)) return false;
|
|
95
111
|
if (label === "common_secret" && /^\d+$/.test(value)) {
|
|
96
112
|
return /(?:\b(?:api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|password|passwd|passcode|secret|token|pin)|密钥|密码|令牌|口令)["'`]?[\s:=:]*(?:(?:is|was|是|为|為)\s*)?["'`]?$/i.test(text.slice(Math.max(0, start - 96), start));
|
|
97
113
|
}
|
|
@@ -99,24 +115,10 @@ function modelSpanFits(text, start, end, label) {
|
|
|
99
115
|
&& /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
|
|
100
116
|
return true;
|
|
101
117
|
}
|
|
102
|
-
export function
|
|
103
|
-
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
104
|
-
return found.map((items, index) => {
|
|
105
|
-
if (items === null) return [];
|
|
106
|
-
if (!Array.isArray(items)) throw privacyFailure("engine_invalid");
|
|
107
|
-
const bytes = Buffer.byteLength(texts[index]);
|
|
108
|
-
for (const span of items) {
|
|
109
|
-
if (!span || !Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start
|
|
110
|
-
|| span.end > bytes || !Number.isFinite(span.score) || span.score < 0 || span.score > 1 || typeof span.label !== "string") throw privacyFailure("engine_invalid");
|
|
111
|
-
}
|
|
112
|
-
return items;
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, rules = ruleSpans }) {
|
|
118
|
+
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, rules = ruleSpans }) {
|
|
117
119
|
const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
118
120
|
if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
119
|
-
const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
121
|
+
const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
120
122
|
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
121
123
|
for (let i = 0; i < items.length; i++) {
|
|
122
124
|
const item = items[i], bytes = Buffer.from(item.text), spans = rules(item.text, personal);
|
|
@@ -157,99 +159,17 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
157
159
|
restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
|
|
158
160
|
}
|
|
159
161
|
|
|
160
|
-
function
|
|
161
|
-
let written = false;
|
|
162
|
-
const lines = wire.split(/(?<=\n)/).map(line => {
|
|
163
|
-
if (!line.startsWith("data:")) return line;
|
|
164
|
-
if (written) return "";
|
|
165
|
-
written = true;
|
|
166
|
-
return `data: ${JSON.stringify(value)}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
167
|
-
}).join("");
|
|
168
|
-
return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
|
|
172
|
-
const fail = code => privacyFailure(code, "response");
|
|
173
|
-
let pending = "", bytes = 0, bufferedBytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
174
|
-
const forget = id => { bufferedBytes -= channels.get(id)?.bytes || 0;channels.delete(id); };
|
|
175
|
-
const clear = () => { channels.clear();bufferedBytes = 0; };
|
|
176
|
-
function transform(wire) {
|
|
177
|
-
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
178
|
-
if (!data || data === "[DONE]") return wire;
|
|
179
|
-
let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
180
|
-
if (["error", "response.failed", "response.incomplete"].includes(event.type)) { clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
|
|
181
|
-
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
182
|
-
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
183
|
-
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
184
|
-
const text = delta?.type === "text_delta" || ["response.output_text.delta", "response.custom_tool_call_input.delta"].includes(event.type);
|
|
185
|
-
let before = "";
|
|
186
|
-
const key = isMessages ? `m:${event.index}` : `r:${event.item_id || event.item?.id || event.output_index}:${event.content_index || 0}`;
|
|
187
|
-
if (tool || text) {
|
|
188
|
-
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
189
|
-
if (typeof delta[field] !== "string") throw fail("stream_invalid");
|
|
190
|
-
const channel = channels.get(key) || { tail: "", tool, field };
|
|
191
|
-
const last = channel.tail.charCodeAt(channel.tail.length - 1), first = delta[field].charCodeAt(0);
|
|
192
|
-
const joinsPair = last >= 0xD800 && last <= 0xDBFF && first >= 0xDC00 && first <= 0xDFFF;
|
|
193
|
-
const valueBytes = (channel.tailBytes || 0) + Buffer.byteLength(delta[field]) - (joinsPair ? 2 : 0);
|
|
194
|
-
let value = channel.tail + delta[field];
|
|
195
|
-
if (valueBytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
196
|
-
if (tool) { channel.tail = value;channel.tailBytes = valueBytes; }
|
|
197
|
-
else {
|
|
198
|
-
let cut = value.length;
|
|
199
|
-
const at = value.lastIndexOf("{{CCDX_");
|
|
200
|
-
if (at >= 0 && !value.slice(at).includes("}}")) cut = at;
|
|
201
|
-
else for (let n = 1; n < TOKEN_START.length; n++) if (value.endsWith(TOKEN_START.slice(0, n))) cut = value.length - n;
|
|
202
|
-
channel.tail = value.slice(cut);delta[field] = session.restoreText(value.slice(0, cut));
|
|
203
|
-
channel.tailBytes = cut === 0 ? valueBytes : Buffer.byteLength(channel.tail);
|
|
204
|
-
}
|
|
205
|
-
if (tool || channel.tail) {
|
|
206
|
-
// Retain metadata and the unfinished value once, rather than retaining
|
|
207
|
-
// the full latest delta in both the template and its original frame.
|
|
208
|
-
channel.template = isMessages ? { ...event, delta: { ...delta, [field]: "" } } : { ...event, [field]: "" };
|
|
209
|
-
channel.wire = rewritePrivacyFrame(wire, channel.template);
|
|
210
|
-
const cost = channel.tailBytes + Buffer.byteLength(channel.wire) + Buffer.byteLength(JSON.stringify(channel.template));
|
|
211
|
-
bufferedBytes += cost - (channel.bytes || 0);channel.bytes = cost;channels.set(key, channel);
|
|
212
|
-
if (bufferedBytes > maxBufferedBytes || channels.size > maxChannels) throw fail("stream_limit");
|
|
213
|
-
} else forget(key);
|
|
214
|
-
if (tool) return "";
|
|
215
|
-
}
|
|
216
|
-
const stopKey = event.type === "content_block_stop" ? `m:${event.index}` : /\.done$/.test(event.type || "") ? key : null;
|
|
217
|
-
const terminal = ["message_stop", "response.completed", "response.incomplete", "error", "response.failed"].includes(event.type);
|
|
218
|
-
for (const [id, channel] of channels) if (terminal || id === stopKey) {
|
|
219
|
-
if (channel.tail) {
|
|
220
|
-
const value = structuredClone(channel.template), target = value.type === "content_block_delta" ? value.delta : value;
|
|
221
|
-
try { target[channel.field] = channel.tool ? JSON.stringify(session.restoreToolValue(JSON.parse(channel.tail))) : session.restoreText(channel.tail); }
|
|
222
|
-
catch { throw fail("stream_invalid"); }
|
|
223
|
-
before += rewritePrivacyFrame(channel.wire, value, true);
|
|
224
|
-
}
|
|
225
|
-
forget(id);
|
|
226
|
-
}
|
|
227
|
-
event = session.restoreValue(event);
|
|
228
|
-
return before + rewritePrivacyFrame(wire, event);
|
|
229
|
-
}
|
|
230
|
-
return {
|
|
231
|
-
push(chunk) {
|
|
232
|
-
try {
|
|
233
|
-
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
234
|
-
let output = "", match;
|
|
235
|
-
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); }
|
|
236
|
-
return output;
|
|
237
|
-
} catch (error) { clear();pending = "";bytes = 0;throw error; }
|
|
238
|
-
},
|
|
239
|
-
finish() {
|
|
240
|
-
try {
|
|
241
|
-
pending += decoder.end();const output = pending ? transform(pending + "\n\n") : "";pending = "";
|
|
242
|
-
if (channels.size) throw fail("stream_incomplete");return output;
|
|
243
|
-
} finally { clear();pending = "";bytes = 0; }
|
|
244
|
-
},
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
export function protectPrivacyResponse(res, session) {
|
|
162
|
+
export function protectPrivacyResponse(res, session, { onFailure, onComplete } = {}) {
|
|
249
163
|
if (!session.count) return;
|
|
250
164
|
const write = res.write.bind(res), end = res.end.bind(res), writeHead = res.writeHead.bind(res), stream = createPrivacyStream(session);
|
|
251
|
-
let mode = null, parts = [], size = 0;
|
|
165
|
+
let mode = null, parts = [], size = 0, released = false;
|
|
252
166
|
const detach = () => { res.write = write;res.end = end;res.writeHead = writeHead;parts = [];session.release(); };
|
|
167
|
+
const failed = error => {
|
|
168
|
+
const details = error.privacyDiagnostic || { privacy_error: error.code || "ccdx_privacy_response_invalid" };
|
|
169
|
+
markRequestObservation(details);markResponseTerminal("failed", { origin: "privacy" });
|
|
170
|
+
try { onFailure?.(details); } catch { /* A diagnostic observer cannot replace the original failure. */ }
|
|
171
|
+
detach();
|
|
172
|
+
};
|
|
253
173
|
res.writeHead = (code, ...args) => {
|
|
254
174
|
const headers = args.find(value => value && typeof value === "object" && !Array.isArray(value));
|
|
255
175
|
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; }
|
|
@@ -258,16 +178,28 @@ export function protectPrivacyResponse(res, session) {
|
|
|
258
178
|
};
|
|
259
179
|
res.write = (value, encoding, callback) => {
|
|
260
180
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, typeof encoding === "string" ? encoding : undefined);
|
|
261
|
-
if (mode === "stream") {
|
|
181
|
+
if (mode === "stream") {
|
|
182
|
+
let output;try { output = stream.push(bytes); } catch (error) { failed(error);throw error; }
|
|
183
|
+
return output ? write(output, typeof encoding === "function" ? encoding : callback) : true;
|
|
184
|
+
}
|
|
262
185
|
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit", "response");parts.push(bytes);return true;
|
|
263
186
|
};
|
|
264
187
|
res.end = (value, encoding, callback) => {
|
|
265
188
|
if (value !== undefined && value !== null) res.write(value, encoding);
|
|
266
189
|
let output;
|
|
267
|
-
if (mode === "stream") { try { output = stream.finish(); }catch (error) {
|
|
190
|
+
if (mode === "stream") { try { output = stream.finish(); }catch (error) { failed(error);throw error; } }
|
|
268
191
|
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 = []; }
|
|
269
192
|
return end(output || undefined, typeof encoding === "function" ? encoding : callback);
|
|
270
193
|
};
|
|
271
|
-
const release = () => {
|
|
272
|
-
|
|
194
|
+
const release = () => {
|
|
195
|
+
if (released) return;released = true;
|
|
196
|
+
session.release();parts = [];
|
|
197
|
+
};
|
|
198
|
+
res.once("finish", () => {
|
|
199
|
+
if (!released && mode === "stream" && stream.completed() && res.statusCode >= 200 && res.statusCode < 300) {
|
|
200
|
+
try { onComplete?.(); } catch { /* Diagnostic-only callback. */ }
|
|
201
|
+
}
|
|
202
|
+
release();
|
|
203
|
+
});
|
|
204
|
+
res.once("close", release);
|
|
273
205
|
}
|
|
@@ -342,9 +342,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
342
342
|
observeContext(values) {
|
|
343
343
|
if (finished || !values || typeof values !== "object") return;
|
|
344
344
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
345
|
-
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "client_tool_errors_received"]) {
|
|
345
|
+
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
346
346
|
const value = values[key];
|
|
347
347
|
if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
|
|
348
|
+
if (["privacy_error", "privacy_event_type", "privacy_channel_type"].includes(key)) {
|
|
349
|
+
if (typeof value === "string" && /^[a-z0-9_.]{1,80}$/.test(value)) context[key] = value;continue;
|
|
350
|
+
}
|
|
348
351
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
349
352
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|
|
350
353
|
}
|
|
@@ -355,7 +358,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
355
358
|
if (TERMINAL_ORIGINS.has(value)) errorOrigin = value;
|
|
356
359
|
},
|
|
357
360
|
terminal(outcome, { model: terminalModel, origin, reason, stopReason: stopped } = {}) {
|
|
358
|
-
if (finished ||
|
|
361
|
+
if (finished || !TERMINAL_OUTCOMES.includes(outcome)
|
|
362
|
+
|| terminalOutcome && !(terminalOutcome === "completed" && outcome === "failed" && origin === "privacy")) return;
|
|
359
363
|
terminalOutcome = outcome;
|
|
360
364
|
terminalAt = now();
|
|
361
365
|
if (terminalModel !== undefined) model = modelLabel(terminalModel);
|