codex-copilot-dx 0.9.26 → 0.9.28
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 +21 -6
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +52 -2
- package/package.json +1 -1
- package/src/copilot-responses-compat.mjs +72 -43
- package/src/http-transport.mjs +1 -1
- package/src/local-compaction-recovery.mjs +246 -0
- package/src/native-prediction-profile.mjs +10 -2
- package/src/native-prediction-windows.mjs +0 -12
- package/src/responses-handler.mjs +10 -1
- package/src/responses-proxy.mjs +5 -3
- package/src/responses-request.mjs +1 -1
- package/src/windows-prediction-certificate.cs +60 -0
- package/src/windows-prediction-certificate.mjs +33 -0
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ The dashboard does not poll in the background; refresh when needed.
|
|
|
57
57
|
CCDX does not claim it can verify the App's internal model cache externally.
|
|
58
58
|
- After a package upgrade, restart the running CCDX adapter. Choosing a model or
|
|
59
59
|
effort on a current adapter takes effect on its next Auto-review request.
|
|
60
|
-
- Request-body bytes, local-history bytes and the model's token window are
|
|
60
|
+
- `0.9.28` adds verified local plaintext recovery after connection-owned compaction rejection; see the reference for strict source and safety limits. Request-body bytes, local-history bytes and the model's token window are
|
|
61
61
|
different limits. Request-context figures are observed metadata, not exact
|
|
62
62
|
live session occupancy. Prompts and images are not retained by that panel.
|
|
63
63
|
- `ccdx cache --clean --history` also clears active response history and can
|
|
@@ -74,7 +74,7 @@ The dashboard does not poll in the background; refresh when needed.
|
|
|
74
74
|
hosts is decrypted locally, but only prediction configuration is changed.
|
|
75
75
|
Other domains and the CCDX model endpoint stay on their existing routes.
|
|
76
76
|
No program files or OS trust are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are retained.
|
|
77
|
-
Windows supports company PAC/WPAD
|
|
77
|
+
Windows supports company PAC/WPAD; macOS dynamic routing remains unsupported. Windows setup needs the official MSIX App, Windows PowerShell and .NET Framework 4.7.2+—not Git/OpenSSL. See the reference for limits.
|
|
78
78
|
- CCDX adds experimental local history compression only when installed App
|
|
79
79
|
runtimes support it and report it off. Existing choices are preserved; an
|
|
80
80
|
already-enabled default, unavailable runtime or failed check is skipped.
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -24,10 +24,18 @@ on those hosts are forwarded unchanged. The bridge does not replace Copilot or
|
|
|
24
24
|
image-provider networking, modify client program files, or install system trust.
|
|
25
25
|
Static upstream proxy routes and bypass rules are preserved. macOS dynamic
|
|
26
26
|
PAC/WPAD and static CIDR bypass rules are reported as unsupported, not discarded.
|
|
27
|
-
The Windows adapter isolates registration, process, proxy
|
|
27
|
+
The Windows adapter isolates registration, process, proxy and NTFS
|
|
28
28
|
interfaces in `native-prediction-windows.mjs`. The bridge, overlay, model selection
|
|
29
29
|
and lifecycle remain shared. Windows discovery requires verified registration
|
|
30
30
|
and an existing unambiguous profile; no generalized OS framework is introduced.
|
|
31
|
+
Windows certificate issuance is a separate one-shot helper
|
|
32
|
+
(`windows-prediction-certificate.mjs` / `.cs`), not part of the network worker.
|
|
33
|
+
Node generates RSA keys and sends them through stdin to the system .NET
|
|
34
|
+
`CertificateRequest` API; only public certificates return through stdout.
|
|
35
|
+
The existing PEM reader, App-profile trust schema and transactional activation
|
|
36
|
+
remain shared. Issuance requires neither external OpenSSL nor a Windows
|
|
37
|
+
certificate store. Valid existing credentials skip issuance; default-off startup
|
|
38
|
+
does not invoke it. macOS keeps the existing system OpenSSL implementation.
|
|
31
39
|
Windows automatic-proxy support has one isolated native WinHTTP worker
|
|
32
40
|
(`windows-prediction-network.mjs` / `.cs`) for company routing, authentication and
|
|
33
41
|
TLS trust. Its private, credit-based pipes stream data without transcript files.
|
|
@@ -39,10 +47,17 @@ optional boundary. Core inference keeps its existing service port and lifecycle.
|
|
|
39
47
|
|
|
40
48
|
Connection-ownership replay rejection is a provider-owned retry policy. It
|
|
41
49
|
removes only unavailable reasoning once, preserving visible history and tools.
|
|
42
|
-
Opaque compaction cannot be assumed equivalent to remaining plaintext
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
Opaque compaction cannot be assumed equivalent to remaining plaintext. The
|
|
51
|
+
`0.9.28` injects a lazy, asynchronous local recovery capability
|
|
52
|
+
at the HTTP boundary, while preserving the synchronous provider-selector API.
|
|
53
|
+
`local-compaction-recovery.mjs` owns source lookup, readonly decoding and verified
|
|
54
|
+
reassembly; it is not a general transcript service or startup scanner. The
|
|
55
|
+
provider policy decides whether to retry. HTTP and pre-output SSE/JSON failures
|
|
56
|
+
share the single-use policy, byte admission and cancellation boundaries.
|
|
57
|
+
Without a complete verified local source, rejection still returns
|
|
58
|
+
`ccdx_history_rebuild_required`, without modifying stored history. Diagnostic
|
|
59
|
+
metadata cannot reconstruct unavailable encrypted memory. LAN/browser callers
|
|
60
|
+
and referenced/split histories do not gain filesystem recovery access.
|
|
46
61
|
|
|
47
62
|
## Configuration ownership
|
|
48
63
|
|
|
@@ -52,7 +67,7 @@ per-file lock, reread current contents and preserve unrelated values. Locks do
|
|
|
52
67
|
not coordinate editors or other applications that ignore them. Read-only status
|
|
53
68
|
and doctor commands do not write configuration.
|
|
54
69
|
|
|
55
|
-
|
|
70
|
+
Core inference interfaces remain unchanged. This change adds a concrete
|
|
56
71
|
composition boundary; it does not relocate every file or add speculative APIs.
|
|
57
72
|
|
|
58
73
|
## Evidence and verification
|
package/docs/README.md
CHANGED
|
@@ -17,6 +17,8 @@ These reports record a specific release and test environment. Their version,
|
|
|
17
17
|
test counts, timings, live-provider observations, and limitations remain
|
|
18
18
|
historical facts rather than current guarantees.
|
|
19
19
|
|
|
20
|
+
- [0.9.28: verified local plaintext recovery and validation boundaries](RELEASE_0.9.28.md)
|
|
21
|
+
- [0.9.27: Windows certificate setup without Git/OpenSSL](RELEASE_0.9.27.md)
|
|
20
22
|
- [0.9.26: Windows native predictions, safe ownership recovery and dashboard disclosures](RELEASE_0.9.26.md)
|
|
21
23
|
- [Windows prediction validation history](WINDOWS_PREDICTION_PREVIEW.md)
|
|
22
24
|
- [0.9.25: static proxy compatibility, integration boundaries and release diagnostics](RELEASE_0.9.25.md)
|
package/docs/REFERENCE.md
CHANGED
|
@@ -35,8 +35,17 @@ Version `0.9.26` adds Windows platform adapters. Native gray suggestions,
|
|
|
35
35
|
adoption/sending and switching predictions off were verified on Windows with the
|
|
36
36
|
`.4` candidate. Windows setup
|
|
37
37
|
requires a current-user, Store-signed `OpenAI.Codex` MSIX registration (Store and
|
|
38
|
-
official offline MSIX use the same registration), an initialized Codex profile
|
|
39
|
-
|
|
38
|
+
official offline MSIX use the same registration), an initialized Codex profile,
|
|
39
|
+
Windows PowerShell and .NET Framework 4.7.2 or later. Since `0.9.27`, prediction
|
|
40
|
+
setup and renewal do not require Git or OpenSSL. Node generates ephemeral RSA
|
|
41
|
+
keys; the Windows .NET certificate API signs the same scoped CA/leaf certificate
|
|
42
|
+
pair. Private keys travel only through a child-process stdin pipe; only the leaf
|
|
43
|
+
key and public certificates are saved in CCDX's private directory. No Windows
|
|
44
|
+
certificate store is opened. Existing valid PEM credentials are reused without
|
|
45
|
+
conversion or reauthorization. macOS retains its system OpenSSL setup path.
|
|
46
|
+
CCDX does not download a runtime or bypass company PowerShell policy; unavailable
|
|
47
|
+
system APIs fail the optional setup without preventing core service startup.
|
|
48
|
+
This does not remove Git from the separate `ccdx update github` installation path.
|
|
40
49
|
Run CCDX using Windows-native Node, not inside WSL. The App's agent may still use
|
|
41
50
|
WSL independently. No administrator prompt or execution-policy change is added.
|
|
42
51
|
AppData may be virtualized by MSIX: setup selects an existing `Codex/Local State`
|
|
@@ -194,6 +203,47 @@ Responses-only models and compaction use Copilot's Responses transport directly.
|
|
|
194
203
|
|
|
195
204
|
The adapter handles response history, encrypted reasoning state, function/custom tools, images, compaction, cancellation, retries, and usage metadata within the compatibility boundaries below. Routing prefers endpoint metadata from Copilot's live or cached catalog; when metadata is unavailable, a small built-in set identifies known Responses-only GPT models.
|
|
196
205
|
|
|
206
|
+
### Local compaction recovery
|
|
207
|
+
|
|
208
|
+
`0.9.28` adds bounded local recovery; the affected user's real chat still needs
|
|
209
|
+
verification. After the exact decoded HTTP 400 `input item does not belong
|
|
210
|
+
to this connection` rejection, or its HTTP-200/pre-output Responses failure
|
|
211
|
+
equivalent, a request containing encrypted compaction can attempt one verified
|
|
212
|
+
plaintext rebuild. Healthy encrypted histories remain unchanged.
|
|
213
|
+
|
|
214
|
+
The reader is loaded only after this failure. It requires a loopback peer and
|
|
215
|
+
Host, no browser Origin, and LAN mode disabled. It binds a UUID from native
|
|
216
|
+
`thread-id` / `client_metadata.thread_id`, or an exact UUID session/cache key
|
|
217
|
+
when primary metadata is absent. Conflicting primary IDs are rejected. It reads
|
|
218
|
+
only UUID-matching rollout filenames under the service's configured
|
|
219
|
+
`CODEX_HOME/sessions` and `archived_sessions`; it does not search by conversation
|
|
220
|
+
title, similarity, arbitrary request paths or another machine's filesystem.
|
|
221
|
+
|
|
222
|
+
Supported source files are complete JSONL logs and their `.jsonl.zst` variants,
|
|
223
|
+
decoded with Node's built-in Zstandard support. Header identity, the exact
|
|
224
|
+
compaction ciphertext, retained message order and function/custom-tool pairs
|
|
225
|
+
must match. A history-base reference, fork reference, rollback/reset marker,
|
|
226
|
+
missing plaintext tool content, malformed data or multiple matching sources
|
|
227
|
+
stops recovery. Referenced/split histories are not assembled by this recovery;
|
|
228
|
+
the caller must have a complete standalone source prefix.
|
|
229
|
+
|
|
230
|
+
The request replaces the rejected compaction with recorded plaintext before it,
|
|
231
|
+
retains current instructions and post-compaction input, and removes unavailable
|
|
232
|
+
reasoning. It does not decrypt or claim to reproduce hidden encrypted reasoning.
|
|
233
|
+
Normal preparation, image limits and upstream model/context limits still apply.
|
|
234
|
+
The reader has a five-second deadline, a 4,096-entry directory lookup bound and
|
|
235
|
+
a 16-candidate bound. Decoded reads and the rebuilt body are bounded by the
|
|
236
|
+
running adapter's decoded-body limit; history admission reservations cover
|
|
237
|
+
recovery preparation. Requests cannot retry after visible output has begun.
|
|
238
|
+
|
|
239
|
+
Neither the original rollout nor client configuration is rewritten. Recovery
|
|
240
|
+
diagnostics contain type/count/status metadata, not transcript text, ciphertext
|
|
241
|
+
or file paths. If verification fails, `ccdx_history_rebuild_required` includes
|
|
242
|
+
`recovery.local_status`; "not modified" does not imply CCDX has backed up complete
|
|
243
|
+
plaintext. Cross-machine/LAN recovery is intentionally unavailable. A full
|
|
244
|
+
plaintext replay can still exceed the upstream context window; this recovery
|
|
245
|
+
does not silently truncate it or add chunked re-compaction.
|
|
246
|
+
|
|
197
247
|
### Fast and Standard modes
|
|
198
248
|
|
|
199
249
|
Codex can select Standard or Fast without changing CCDX configuration. When the client requests a model with `service_tier: "priority"`, CCDX uses its exact `-fast` model only when the live Copilot catalog advertises that variant as enabled, selectable, OpenAI-owned, and Responses-only. Standard mode continues to use the base model; CCDX does not invent Fast availability when the upstream catalog does not provide it. This retains the established `gpt-5.6-sol` / `gpt-5.6-sol-fast` mapping and applies the same exact-match rule to future models.
|
package/package.json
CHANGED
|
@@ -72,53 +72,82 @@ export function selectCopilotResponseRetry(
|
|
|
72
72
|
return null;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
// Preserve the synchronous selector contract; disk recovery is an explicitly
|
|
76
|
+
// injected, asynchronous capability at the HTTP boundary, never a blanket retry.
|
|
77
|
+
export async function selectCopilotResponseRetryWithHistory(reqContext, statusCode, errorText, usedPolicies = new Set(), options = {}) {
|
|
78
|
+
try { return selectCopilotResponseRetry(reqContext, statusCode, errorText, usedPolicies); }
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error.code !== "ccdx_history_rebuild_required" || !options.restorePlaintextHistory) throw error;
|
|
81
|
+
let restored;
|
|
82
|
+
try { restored = await options.restorePlaintextHistory(reqContext, { reserveHistory: options.reserveHistory }); }
|
|
83
|
+
catch (failure) {
|
|
84
|
+
options.assertPrepareActive?.();
|
|
85
|
+
if (options.signal?.aborted) throw options.signal.reason || failure;
|
|
86
|
+
const reason = /^[a-z][a-z_]{1,60}$/.test(failure.code || "") ? failure.code : "local_history_unavailable";
|
|
87
|
+
error.jsonBody.error.recovery.local_status = reason;
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
usedPolicies.add("encrypted-connection-rejected");
|
|
91
|
+
return { ...restored, policyId: "encrypted-connection-rejected", usedPolicies,
|
|
92
|
+
warning: "saved compaction rejected; retrying once with verified complete local plaintext history" };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
75
96
|
export async function openCopilotResponse(reqContext, upstream = copilotResponses, options = {}) {
|
|
76
97
|
const usedPolicies = options.usedRetryPolicies || new Set();
|
|
77
98
|
let payloadPrepared = false;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
99
|
+
let releaseRecovery;
|
|
100
|
+
try {
|
|
101
|
+
for (let attempt = 0; attempt <= RETRY_POLICIES.length; attempt += 1) {
|
|
102
|
+
let resp;
|
|
103
|
+
try {
|
|
104
|
+
options.assertPrepareActive?.();
|
|
105
|
+
resp = await upstream(reqContext.body, {
|
|
106
|
+
assertActive: options.assertPrepareActive,
|
|
107
|
+
signal: options.signal,
|
|
108
|
+
currentInputStart: reqContext.currentInputStart,
|
|
109
|
+
onUpstreamStart: options.onUpstreamStart,
|
|
110
|
+
payloadPrepared,
|
|
111
|
+
});
|
|
112
|
+
} finally { releaseRecovery?.();releaseRecovery = null; }
|
|
113
|
+
markUpstreamHeaders();
|
|
114
|
+
options.assertPrepareActive?.();
|
|
115
|
+
payloadPrepared = true;
|
|
116
|
+
if (resp.ok) {
|
|
117
|
+
reqContext = finalizeEncryptedHistoryRebase(reqContext);
|
|
118
|
+
return { resp, reqContext, usedRetryPolicies: usedPolicies };
|
|
119
|
+
}
|
|
94
120
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
121
|
+
const errorText = await readBoundedResponseText(resp, {
|
|
122
|
+
maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
123
|
+
label: "Copilot Responses error body",
|
|
124
|
+
});
|
|
125
|
+
options.assertPrepareActive?.();
|
|
126
|
+
let retry;
|
|
127
|
+
try { retry = await selectCopilotResponseRetryWithHistory(reqContext, resp.status, errorText, usedPolicies, options); }
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (error.code === "ccdx_history_rebuild_required") {
|
|
130
|
+
const details = responseFailureDetails({ error: error.jsonBody.error }, "upstream.http_error", {
|
|
131
|
+
model: reqContext.body.model, headers: resp.headers, retrySkipped: error.code });
|
|
132
|
+
error.jsonBody.error.upstream_request_id = details.upstream_request_id;
|
|
133
|
+
options.responseFailures?.record?.({ ...details, recovery: error.jsonBody.error.recovery });
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
108
136
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
137
|
+
releaseRecovery = retry?.releasePreparation;
|
|
138
|
+
if (retry?.policyId === "encrypted-connection-rejected") {
|
|
139
|
+
options.responseFailures?.record?.({ ...responseFailureDetails(JSON.parse(errorText), "upstream.http_error", {
|
|
140
|
+
model: reqContext.body.model, headers: resp.headers, retried: true, retryPolicy: retry.policyId }),
|
|
141
|
+
recovery: retry.recovery });
|
|
142
|
+
}
|
|
143
|
+
if (retry) {
|
|
144
|
+
reqContext = retry.reqContext;
|
|
145
|
+
if (retry.recovery?.source === "local_codex_rollout") payloadPrepared = false;
|
|
146
|
+
console.warn(status("warn", retry.warning));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
return { resp, reqContext, errorText, usedRetryPolicies: usedPolicies };
|
|
120
150
|
}
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
throw httpError("Responses compatibility retry limit exceeded", 502);
|
|
151
|
+
throw httpError("Responses compatibility retry limit exceeded", 502);
|
|
152
|
+
} finally { releaseRecovery?.(); }
|
|
124
153
|
}
|
package/src/http-transport.mjs
CHANGED
|
@@ -19,7 +19,7 @@ const zstdDecompressAsync = zlib.zstdDecompress ? promisify(zlib.zstdDecompress)
|
|
|
19
19
|
|
|
20
20
|
const HTTP_RUNTIME_CONFIG = loadRuntimeConfig();
|
|
21
21
|
const MAX_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxBodyBytes;
|
|
22
|
-
const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
22
|
+
export const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
23
23
|
|
|
24
24
|
export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
|
|
25
25
|
export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { createZstdDecompress } from "node:zlib";
|
|
6
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
7
|
+
import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./security.mjs";
|
|
8
|
+
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
9
|
+
import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
|
|
10
|
+
import { prepareResponsesRequest } from "./responses-request.mjs";
|
|
11
|
+
|
|
12
|
+
const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
13
|
+
const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
|
|
14
|
+
|
|
15
|
+
function unavailable(code) {
|
|
16
|
+
return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function threadId(request, body) {
|
|
20
|
+
const metadata = body?.client_metadata;
|
|
21
|
+
const primary = [request.headers?.["thread-id"], request.headers?.["x-codex-thread-id"], metadata?.thread_id];
|
|
22
|
+
const values = primary.filter(value => value !== undefined);
|
|
23
|
+
if (!values.length) values.push(metadata?.session_id ?? request.headers?.["session-id"] ?? body?.prompt_cache_key);
|
|
24
|
+
if (values.some(value => typeof value !== "string" || !UUID.test(value))) throw unavailable("thread_binding_missing");
|
|
25
|
+
const ids = new Set(values.map(value => value.toLowerCase()));
|
|
26
|
+
if (ids.size !== 1) throw unavailable("thread_binding_conflict");
|
|
27
|
+
return [...ids][0];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function opaque(value) {
|
|
31
|
+
if (Array.isArray(value)) return value.some(opaque);
|
|
32
|
+
if (!value || typeof value !== "object") return false;
|
|
33
|
+
return Object.hasOwn(value, "encrypted_content") || value.type === "encrypted_content" || Object.values(value).some(opaque);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function plaintext(item) {
|
|
37
|
+
if (!item || typeof item !== "object" || typeof item.type !== "string") throw unavailable("unsupported_rollout_item");
|
|
38
|
+
if (["reasoning", "compaction"].includes(item.type)) return null;
|
|
39
|
+
const out = structuredClone(item);
|
|
40
|
+
for (const key of Object.keys(out)) if (key === "id" || key.startsWith("internal_")) delete out[key];
|
|
41
|
+
// This field is replay metadata, not a replacement for a visible item. Never
|
|
42
|
+
// omit opaque content parts or invent plaintext for an encrypted tool result.
|
|
43
|
+
if ((out.type === "message" && out.content?.length) || (isResponsesToolOutputItem(out) && out.output !== undefined)) {
|
|
44
|
+
delete out.encrypted_content;
|
|
45
|
+
}
|
|
46
|
+
if (opaque(out) || (isResponsesToolOutputItem(out) && opaque(readResponsesToolOutputParts(out)?.parts))) {
|
|
47
|
+
throw unavailable("plaintext_content_missing");
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fingerprint(item) {
|
|
53
|
+
const normalized = { ...item };
|
|
54
|
+
delete normalized.id;delete normalized.status;
|
|
55
|
+
if (item.type === "message" && Array.isArray(item.content)) normalized.content = item.content.map(part => {
|
|
56
|
+
if (!["input_text", "output_text"].includes(part?.type)) return part;
|
|
57
|
+
const text = { ...part };delete text.annotations;return text;
|
|
58
|
+
});
|
|
59
|
+
return createHash("sha256").update(JSON.stringify(normalized, (_key, value) => {
|
|
60
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
61
|
+
return Object.fromEntries(Object.keys(value).sort().map(name => [name, value[name]]));
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
})).digest("hex");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function candidateFiles(directory, id, check) {
|
|
68
|
+
const found = [];
|
|
69
|
+
let entries = 0;
|
|
70
|
+
async function walk(parent, depth) {
|
|
71
|
+
check();
|
|
72
|
+
const stat = await fs.lstat(parent);
|
|
73
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
|
|
74
|
+
const iterator = await fs.opendir(parent);
|
|
75
|
+
for await (const entry of iterator) {
|
|
76
|
+
check();
|
|
77
|
+
if (++entries > 4096) throw unavailable("rollout_lookup_limit");
|
|
78
|
+
const file = path.join(parent, entry.name);
|
|
79
|
+
if (entry.isDirectory() && depth < 3) await walk(file, depth + 1);
|
|
80
|
+
else if (entry.isFile() && /^rollout-.*\.jsonl(?:\.zst)?$/.test(entry.name) && entry.name.toLowerCase().includes(id)) {
|
|
81
|
+
if (found.length >= 16) throw unavailable("rollout_lookup_limit");
|
|
82
|
+
found.push(file);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const name of ["sessions", "archived_sessions"]) {
|
|
87
|
+
try { await walk(path.join(directory, name), 0); }
|
|
88
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
89
|
+
}
|
|
90
|
+
return found;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function readPrefix(file, directory, id, ciphertext, budget, check, signal) {
|
|
94
|
+
const real = await fs.realpath(file);
|
|
95
|
+
if (!real.startsWith(directory + path.sep)) throw unavailable("unsafe_rollout_path");
|
|
96
|
+
const before = await fs.lstat(file);
|
|
97
|
+
if (!before.isFile() || before.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
|
|
98
|
+
if (!before.size) throw unavailable("incomplete_rollout");
|
|
99
|
+
const handle = await fs.open(file, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW || 0));
|
|
100
|
+
let stream, raw;
|
|
101
|
+
try {
|
|
102
|
+
const stat = await handle.stat();
|
|
103
|
+
// Older Windows libuv reports the device number differently for lstat and
|
|
104
|
+
// fstat. The validated path, file ID and snapshot size remain mandatory.
|
|
105
|
+
if (!stat.isFile() || stat.ino !== before.ino || stat.size !== before.size
|
|
106
|
+
|| (process.platform !== "win32" && stat.dev !== before.dev)) throw unavailable("rollout_changed");
|
|
107
|
+
raw = handle.createReadStream({ autoClose: false, end: stat.size - 1, highWaterMark: 64 * 1024, signal });
|
|
108
|
+
stream = file.endsWith(".zst") ? raw.pipe(createZstdDecompress()) : raw;
|
|
109
|
+
if (stream !== raw) raw.on("error", error => stream.destroy(error));
|
|
110
|
+
const items = [];
|
|
111
|
+
let metadata = false, matched = false, parts = [], length = 0, bytesRead = 0;
|
|
112
|
+
const record = bytes => {
|
|
113
|
+
check();
|
|
114
|
+
const line = bytes.toString("utf8").replace(/^\uFEFF/, "").trim();
|
|
115
|
+
if (!line) return;
|
|
116
|
+
let row;
|
|
117
|
+
try { row = JSON.parse(line); } catch { throw unavailable("invalid_rollout"); }
|
|
118
|
+
const value = row.payload;
|
|
119
|
+
if (!metadata) {
|
|
120
|
+
if (row.type !== "session_meta" || value?.id?.toLowerCase() !== id) throw unavailable("rollout_identity_mismatch");
|
|
121
|
+
if (value.history_base || value.forked_from_id || (row.ordinal !== undefined && row.ordinal !== 0)
|
|
122
|
+
|| (value.history_mode && !["full", "paginated"].includes(value.history_mode))) throw unavailable("incomplete_rollout");
|
|
123
|
+
metadata = true;return;
|
|
124
|
+
}
|
|
125
|
+
if (row.type === "session_meta" || (row.type === "event_msg" && /rollback|rolled_back|rewind|history_reset|context_reset/.test(value?.type || ""))) {
|
|
126
|
+
throw unavailable("unsupported_history_change");
|
|
127
|
+
}
|
|
128
|
+
if (row.type === "compacted" || row.type === "response_item") {
|
|
129
|
+
const candidates = row.type === "compacted" ? value?.replacement_history : [value];
|
|
130
|
+
if (Array.isArray(candidates) && candidates.some(item => item?.type === "compaction" && item.encrypted_content === ciphertext)) {
|
|
131
|
+
matched = true;return;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (row.type === "response_item") {
|
|
135
|
+
const item = plaintext(value);
|
|
136
|
+
if (item) items.push(item);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
for await (const chunk of stream) {
|
|
140
|
+
check();budget.remaining -= chunk.length;bytesRead += chunk.length;
|
|
141
|
+
if (budget.remaining < 0) throw unavailable("rollout_read_limit");
|
|
142
|
+
let start = 0;
|
|
143
|
+
while (start < chunk.length) {
|
|
144
|
+
const end = chunk.indexOf(10, start);
|
|
145
|
+
const part = chunk.subarray(start, end < 0 ? chunk.length : end);
|
|
146
|
+
parts.push(part);length += part.length;
|
|
147
|
+
if (end < 0) break;
|
|
148
|
+
record(Buffer.concat(parts, length));parts = [];length = 0;
|
|
149
|
+
if (matched) return { items, bytes: bytesRead };
|
|
150
|
+
start = end + 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (length) record(Buffer.concat(parts, length));
|
|
154
|
+
return matched ? { items, bytes: bytesRead } : null;
|
|
155
|
+
} finally {
|
|
156
|
+
stream?.destroy();raw?.destroy();await handle.close();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function joinHistory(source, input, compactionIndex, check) {
|
|
161
|
+
if (!source.length || !source.some(item => item.type === "message" && item.role === "user")) throw unavailable("incomplete_rollout");
|
|
162
|
+
const signatures = source.map(fingerprint);
|
|
163
|
+
let cursor = 0;
|
|
164
|
+
const instructions = [];
|
|
165
|
+
for (const original of input.slice(0, compactionIndex)) {
|
|
166
|
+
check();
|
|
167
|
+
const item = plaintext(original);
|
|
168
|
+
if (!item) continue;
|
|
169
|
+
const match = signatures.indexOf(fingerprint(item), cursor);
|
|
170
|
+
if (match >= 0) cursor = match + 1;
|
|
171
|
+
else if (item.type === "message" && ["system", "developer"].includes(item.role)) instructions.push(item);
|
|
172
|
+
else throw unavailable("retained_prefix_mismatch");
|
|
173
|
+
}
|
|
174
|
+
const suffix = input.slice(compactionIndex + 1).map(plaintext).filter(Boolean);
|
|
175
|
+
const items = [...source, ...instructions, ...suffix];
|
|
176
|
+
const calls = new Map();
|
|
177
|
+
for (const item of items) {
|
|
178
|
+
check();
|
|
179
|
+
if (CALLS.has(item.type)) {
|
|
180
|
+
if (!item.call_id || calls.has(item.call_id)) throw unavailable("invalid_tool_pairs");
|
|
181
|
+
calls.set(item.call_id, { type: CALLS.get(item.type), completed: false });
|
|
182
|
+
} else if ([...CALLS.values()].includes(item.type)) {
|
|
183
|
+
const call = calls.get(item.call_id);
|
|
184
|
+
if (!call || call.type !== item.type || call.completed) throw unavailable("invalid_tool_pairs");
|
|
185
|
+
call.completed = true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if ([...calls.values()].some(call => !call.completed)) throw unavailable("invalid_tool_pairs");
|
|
189
|
+
return { items, currentInputStart: source.length + instructions.length };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Loaded only after a confirmed provider ownership rejection, never on startup
|
|
193
|
+
// or healthy requests. It cannot serve remote/browser callers or mutate logs.
|
|
194
|
+
export async function recoverLocalCompaction(reqContext, { request, env = process.env,
|
|
195
|
+
signal, assertActive, reserveHistory, maxBytes, timeoutMs = 5000 } = {}) {
|
|
196
|
+
const started = Date.now();
|
|
197
|
+
const check = () => {
|
|
198
|
+
assertActive?.();
|
|
199
|
+
if (signal?.aborted) throw signal.reason || new DOMException("Aborted", "AbortError");
|
|
200
|
+
if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
|
|
201
|
+
};
|
|
202
|
+
check();
|
|
203
|
+
if (isLanAllowed(env) || !isLoopbackAddress(request?.socket?.remoteAddress)
|
|
204
|
+
|| !isLoopbackHostHeader(request?.headers?.host) || request?.headers?.origin !== undefined) {
|
|
205
|
+
throw unavailable("local_request_required");
|
|
206
|
+
}
|
|
207
|
+
const id = threadId(request, reqContext.body);
|
|
208
|
+
const input = reqContext.body?.input;
|
|
209
|
+
const compactions = Array.isArray(input) ? input.filter(item => item?.type === "compaction" && item.encrypted_content) : [];
|
|
210
|
+
if (compactions.length !== 1) throw unavailable("multiple_compactions");
|
|
211
|
+
if (typeof compactions[0].encrypted_content !== "string") throw unavailable("invalid_compaction");
|
|
212
|
+
const limit = maxBytes ?? decodedBodyLimitPreference({ env }).bytes;
|
|
213
|
+
let release, transferred = false;
|
|
214
|
+
try {
|
|
215
|
+
release = await reserveHistory?.(limit, { signal });
|
|
216
|
+
check();
|
|
217
|
+
const directory = await fs.realpath(codexPaths({ env }).directory);
|
|
218
|
+
const files = await candidateFiles(directory, id, check);
|
|
219
|
+
const budget = { remaining: limit };
|
|
220
|
+
let source;
|
|
221
|
+
for (const file of files) {
|
|
222
|
+
check();
|
|
223
|
+
const candidate = await readPrefix(file, directory, id, compactions[0].encrypted_content, budget, check, signal);
|
|
224
|
+
if (!candidate) continue;
|
|
225
|
+
if (source) throw unavailable("ambiguous_rollout");
|
|
226
|
+
source = candidate;
|
|
227
|
+
}
|
|
228
|
+
if (!source) throw unavailable("matching_rollout_missing");
|
|
229
|
+
const restored = joinHistory(source.items, input, input.indexOf(compactions[0]), check);
|
|
230
|
+
const body = { ...reqContext.body, input: restored.items };
|
|
231
|
+
delete body.previous_response_id;
|
|
232
|
+
const bodyBytes = Buffer.byteLength(JSON.stringify(body));
|
|
233
|
+
if (bodyBytes > limit) throw unavailable("restored_payload_limit");
|
|
234
|
+
release?.resize?.(bodyBytes);
|
|
235
|
+
const currentItems = new Set(body.input.slice(restored.currentInputStart));
|
|
236
|
+
const prepared = prepareResponsesRequest(body, { mutate: true, copilotBoundary: false, assertActive: check });
|
|
237
|
+
const currentInputStart = prepared.body.input.findIndex(item => currentItems.has(item));
|
|
238
|
+
prepared.currentInputStart = currentInputStart < 0 ? prepared.body.input.length : currentInputStart;
|
|
239
|
+
prepared.surface = reqContext.surface;
|
|
240
|
+
prepared.routePlan = reqContext.routePlan;
|
|
241
|
+
transferred = true;
|
|
242
|
+
return { reqContext: prepared, releasePreparation: release, recovery: { source: "local_codex_rollout", restored_items: restored.items.length,
|
|
243
|
+
compaction_items_removed: 1, reasoning_items_removed: input.filter(item => item?.type === "reasoning").length,
|
|
244
|
+
source_bytes: source.bytes } };
|
|
245
|
+
} finally { if (!transferred) release?.(); }
|
|
246
|
+
}
|
|
@@ -8,7 +8,8 @@ import { userSettingsPath } from "./user-settings.mjs";
|
|
|
8
8
|
import { resolveNetworkRoute } from "./network-route.mjs";
|
|
9
9
|
import { codexPaths } from "./codex-paths.mjs";
|
|
10
10
|
import { assertWindowsCodexClosed, installedWindowsPredictionApp, windowsPredictionProfile,
|
|
11
|
-
|
|
11
|
+
windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
12
|
+
import { windowsPredictionCertificate } from "./windows-prediction-certificate.mjs";
|
|
12
13
|
|
|
13
14
|
export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
|
|
14
15
|
const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
|
|
@@ -136,7 +137,14 @@ export function readPredictionCertificate(directory, { allowExpired = false, pla
|
|
|
136
137
|
|
|
137
138
|
export function createPredictionCertificate(directory, { exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
138
139
|
privateDirectory(directory, { ...options, exec, platform });
|
|
139
|
-
|
|
140
|
+
if (platform === "win32") {
|
|
141
|
+
const { cert, key, ca } = windowsPredictionCertificate({ ...options, exec });
|
|
142
|
+
atomicWriteFileSync(path.join(directory, "bridge.key"), key, { preserveMode: false });
|
|
143
|
+
atomicWriteFileSync(path.join(directory, "bridge.pem"), cert, { preserveMode: false });
|
|
144
|
+
atomicWriteFileSync(path.join(directory, "ca.pem"), ca, { preserveMode: false });
|
|
145
|
+
return readPredictionCertificate(directory, { ...options, exec, platform });
|
|
146
|
+
}
|
|
147
|
+
const openssl = "/usr/bin/openssl";
|
|
140
148
|
const temporary = fs.mkdtempSync(path.join(directory, "certificate-"));
|
|
141
149
|
try {
|
|
142
150
|
const config = `[req]\nprompt=no\ndistinguished_name=dn\nx509_extensions=ext\n[dn]\nCN=CCDX native prediction local bridge\n[ext]\nbasicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:chatgpt.com,DNS:ab.chatgpt.com\nnameConstraints=critical,permitted;DNS:chatgpt.com\n`;
|
|
@@ -97,18 +97,6 @@ export function windowsPredictionProfile({ app, env = process.env, preferredProf
|
|
|
97
97
|
return profiles[0];
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
-
export function windowsPredictionOpenSSL(options = {}) {
|
|
101
|
-
const raw = powershell(`$found=Get-Command openssl.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
|
|
102
|
-
if($found){$found.Source}else{
|
|
103
|
-
$paths=@("$env:ProgramFiles\\Git\\usr\\bin\\openssl.exe", "$env:LOCALAPPDATA\\Programs\\Git\\usr\\bin\\openssl.exe");
|
|
104
|
-
$paths | Where-Object {Test-Path -LiteralPath $_ -PathType Leaf} | Select-Object -First 1
|
|
105
|
-
}`, options);
|
|
106
|
-
if (!path.win32.isAbsolute(raw) || !/openssl\.exe$/i.test(path.win32.basename(raw))) {
|
|
107
|
-
throw new Error("Native prediction needs OpenSSL on Windows; install Git for Windows (includes OpenSSL) and retry");
|
|
108
|
-
}
|
|
109
|
-
return raw;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
100
|
export function windowsPrivatePredictionPath(filePath, { create = false, env = process.env, ...options } = {}) {
|
|
113
101
|
powershell(`$p=$env:CCDX_PREDICTION_PRIVATE_PATH;$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User;
|
|
114
102
|
$acl=Get-Acl -LiteralPath $p;
|
|
@@ -3,6 +3,7 @@ import { applyCopilotResponsesRequestPolicies } from "./copilot-responses-policy
|
|
|
3
3
|
import {
|
|
4
4
|
createRequestAbort,
|
|
5
5
|
logRequestFailure,
|
|
6
|
+
MAX_DECODED_BODY_BYTES,
|
|
6
7
|
MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES,
|
|
7
8
|
MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
8
9
|
readJsonBody,
|
|
@@ -189,7 +190,7 @@ export function createResponsesHandler(options) {
|
|
|
189
190
|
}
|
|
190
191
|
}
|
|
191
192
|
assertPrepareActive();
|
|
192
|
-
return { historySnapshot: retrySnapshot, release };
|
|
193
|
+
return { historySnapshot: retrySnapshot, reserveHistory: releaseRetryRequest.reserveResponseHistory, release };
|
|
193
194
|
} catch (error) {
|
|
194
195
|
release();
|
|
195
196
|
throw error;
|
|
@@ -308,6 +309,12 @@ export function createResponsesHandler(options) {
|
|
|
308
309
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
309
310
|
applyCopilotResponsesRequestPolicies(prepared.body);
|
|
310
311
|
if (routePlan.protocol === "openai-responses") {
|
|
312
|
+
const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
|
|
313
|
+
assertPrepareActive();
|
|
314
|
+
const { recoverLocalCompaction } = await import("./local-compaction-recovery.mjs");
|
|
315
|
+
return recoverLocalCompaction(context, { request: req, env: openAIModelEnv,
|
|
316
|
+
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
|
|
317
|
+
};
|
|
311
318
|
const result = await proxyCopilotResponses(prepared, req, res, responsesFn, {
|
|
312
319
|
acquireRetryPreparation,
|
|
313
320
|
assertPrepareActive,
|
|
@@ -317,6 +324,8 @@ export function createResponsesHandler(options) {
|
|
|
317
324
|
onStreamStart: startStream,
|
|
318
325
|
releaseRequest: releaseUpstreamPayload,
|
|
319
326
|
responseFailures,
|
|
327
|
+
restorePlaintextHistory,
|
|
328
|
+
reserveHistory: releaseRequest.reserveResponseHistory,
|
|
320
329
|
streamIdleTimeoutMs,
|
|
321
330
|
keepaliveIntervalMs,
|
|
322
331
|
});
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { httpError } from "./http-errors.mjs";
|
|
|
11
11
|
import {
|
|
12
12
|
hasCopilotResponseRetryPolicy,
|
|
13
13
|
openCopilotResponse,
|
|
14
|
-
|
|
14
|
+
selectCopilotResponseRetryWithHistory,
|
|
15
15
|
} from "./copilot-responses-compat.mjs";
|
|
16
16
|
import {
|
|
17
17
|
dropMaterializedResponseHistory,
|
|
@@ -345,11 +345,13 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
|
|
|
345
345
|
assertActive: options.assertPrepareActive,
|
|
346
346
|
historySnapshot: preparation?.historySnapshot,
|
|
347
347
|
});
|
|
348
|
-
const retry =
|
|
348
|
+
const retry = await selectCopilotResponseRetryWithHistory(restored, 400, errorText, usedRetryPolicies, {
|
|
349
|
+
...options, reserveHistory: preparation?.reserveHistory || options.reserveHistory,
|
|
350
|
+
});
|
|
349
351
|
options.assertPrepareActive?.();
|
|
350
352
|
keepReservation = Boolean(retry);
|
|
351
353
|
return {
|
|
352
|
-
retry: retry ? { ...retry, releasePreparation: preparation?.release } : null,
|
|
354
|
+
retry: retry ? { ...retry, releasePreparation: () => { retry.releasePreparation?.();preparation?.release(); } } : null,
|
|
353
355
|
retrySkipped: null,
|
|
354
356
|
};
|
|
355
357
|
} catch (error) {
|
|
@@ -200,7 +200,7 @@ export function sanitizeConnectionOwnedReasoningRequest(reqContext) {
|
|
|
200
200
|
const compactions = input.filter(item => item?.type === "compaction" && item.encrypted_content);
|
|
201
201
|
const reasoning = input.filter(item => item?.type === "reasoning" && item.encrypted_content);
|
|
202
202
|
if (compactions.length) {
|
|
203
|
-
const message = "
|
|
203
|
+
const message = "The request contains encrypted compaction and upstream rejected saved state. Verified local recovery was unavailable; restore the full plaintext conversation history before retrying. CCDX has not modified the original history.";
|
|
204
204
|
throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_history_rebuild_required",
|
|
205
205
|
jsonBody: { error: { type: "invalid_request_error", code: "ccdx_history_rebuild_required", message,
|
|
206
206
|
recoverable: true, recovery: { action: "restore_plaintext_history", compaction_items: compactions.length, reasoning_items: reasoning.length } } } });
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// One-shot certificate issuance using the Windows .NET Framework. Keys remain
|
|
2
|
+
// ephemeral; only public certificates return through stdout. No store is opened.
|
|
3
|
+
using System;
|
|
4
|
+
using System.Collections.Generic;
|
|
5
|
+
using System.Security.Cryptography;
|
|
6
|
+
using System.Security.Cryptography.X509Certificates;
|
|
7
|
+
using System.Web.Script.Serialization;
|
|
8
|
+
|
|
9
|
+
public static class CCDXPredictionCertificate {
|
|
10
|
+
static byte[] Decode(Dictionary<string, object> key, string name, int size = 0) {
|
|
11
|
+
string value = ((string)key[name]).Replace('-', '+').Replace('_', '/');
|
|
12
|
+
var bytes = Convert.FromBase64String(value.PadRight((value.Length + 3) / 4 * 4, '='));
|
|
13
|
+
if (size == 0 || bytes.Length == size) return bytes;
|
|
14
|
+
if (bytes.Length > size) throw new InvalidOperationException("Invalid RSA component length");
|
|
15
|
+
var padded = new byte[size]; Buffer.BlockCopy(bytes, 0, padded, size - bytes.Length, bytes.Length); return padded;
|
|
16
|
+
}
|
|
17
|
+
static void Import(RSACng rsa, Dictionary<string, object> key) {
|
|
18
|
+
var modulus = Decode(key, "n"); var half = modulus.Length / 2;
|
|
19
|
+
rsa.ImportParameters(new RSAParameters { Modulus = modulus, Exponent = Decode(key, "e"),
|
|
20
|
+
D = Decode(key, "d", modulus.Length), P = Decode(key, "p", half), Q = Decode(key, "q", half),
|
|
21
|
+
DP = Decode(key, "dp", half), DQ = Decode(key, "dq", half), InverseQ = Decode(key, "qi", half) });
|
|
22
|
+
if (!rsa.Key.IsEphemeral) throw new InvalidOperationException("An ephemeral key is required");
|
|
23
|
+
}
|
|
24
|
+
static CertificateRequest Request(string name, RSA key, bool ca) {
|
|
25
|
+
var request = new CertificateRequest(name, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
26
|
+
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(ca, ca, 0, true));
|
|
27
|
+
request.CertificateExtensions.Add(new X509KeyUsageExtension(ca
|
|
28
|
+
? X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.DigitalSignature
|
|
29
|
+
: X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
|
|
30
|
+
var usages = new OidCollection(); usages.Add(new Oid("1.3.6.1.5.5.7.3.1"));
|
|
31
|
+
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(usages, false));
|
|
32
|
+
var names = new SubjectAlternativeNameBuilder();
|
|
33
|
+
names.AddDnsName("chatgpt.com"); names.AddDnsName("ab.chatgpt.com");
|
|
34
|
+
request.CertificateExtensions.Add(names.Build(false));
|
|
35
|
+
if (ca) {
|
|
36
|
+
// DER NameConstraints: permitted DNS chatgpt.com, matching the existing CA.
|
|
37
|
+
request.CertificateExtensions.Add(new X509Extension("2.5.29.30", new byte[] {
|
|
38
|
+
0x30, 0x11, 0xa0, 0x0f, 0x30, 0x0d, 0x82, 0x0b,
|
|
39
|
+
0x63, 0x68, 0x61, 0x74, 0x67, 0x70, 0x74, 0x2e, 0x63, 0x6f, 0x6d }, true));
|
|
40
|
+
}
|
|
41
|
+
return request;
|
|
42
|
+
}
|
|
43
|
+
public static void Run() {
|
|
44
|
+
var json = new JavaScriptSerializer { MaxJsonLength = 16 * 1024 };
|
|
45
|
+
var input = json.Deserialize<Dictionary<string, object>>(Console.In.ReadToEnd());
|
|
46
|
+
using (var caKey = new RSACng())
|
|
47
|
+
using (var leafKey = new RSACng())
|
|
48
|
+
using (var random = RandomNumberGenerator.Create()) {
|
|
49
|
+
Import(caKey, (Dictionary<string, object>)input["ca"]);
|
|
50
|
+
Import(leafKey, (Dictionary<string, object>)input["leaf"]);
|
|
51
|
+
var now = DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
|
52
|
+
var before = now.AddMinutes(-5); var after = now.AddDays(90);
|
|
53
|
+
var serial = new byte[16]; random.GetBytes(serial); serial[0] = (byte)((serial[0] & 0x7f) | 1);
|
|
54
|
+
using (var ca = Request("CN=CCDX native prediction local bridge", caKey, true).CreateSelfSigned(before, after))
|
|
55
|
+
using (var leaf = Request("CN=CCDX local prediction bridge", leafKey, false).Create(ca, before, after, serial)) {
|
|
56
|
+
Console.Out.WriteLine(json.Serialize(new { ca = Convert.ToBase64String(ca.RawData), cert = Convert.ToBase64String(leaf.RawData) }));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { generateKeyPairSync } from "node:crypto";
|
|
5
|
+
import { windowsPowerShellEnvironment } from "./native-prediction-windows.mjs";
|
|
6
|
+
|
|
7
|
+
// Explicit Windows setup only. Private keys use stdin, never command arguments,
|
|
8
|
+
// environment variables, compiler source, or the Windows certificate store.
|
|
9
|
+
export function windowsPredictionCertificate({ env = process.env, exec = execFileSync } = {}) {
|
|
10
|
+
const ca = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
11
|
+
const leaf = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
12
|
+
const input = JSON.stringify({ ca: ca.privateKey.export({ format: "jwk" }), leaf: leaf.privateKey.export({ format: "jwk" }) });
|
|
13
|
+
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
14
|
+
const source = fileURLToPath(new URL("./windows-prediction-certificate.cs", import.meta.url));
|
|
15
|
+
let certificates;
|
|
16
|
+
try {
|
|
17
|
+
const raw = exec(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
18
|
+
"$ErrorActionPreference='Stop';Add-Type -Path $env:CCDX_PREDICTION_CERTIFICATE_SOURCE -ReferencedAssemblies System.dll,System.Core.dll,System.Security.dll,System.Web.Extensions.dll;[CCDXPredictionCertificate]::Run()"],
|
|
19
|
+
{ env: { ...windowsPowerShellEnvironment(env), CCDX_PREDICTION_CERTIFICATE_SOURCE: source }, input,
|
|
20
|
+
encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024, windowsHide: true });
|
|
21
|
+
certificates = JSON.parse(raw);
|
|
22
|
+
for (const name of ["ca", "cert"]) {
|
|
23
|
+
if (typeof certificates?.[name] !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(certificates[name])
|
|
24
|
+
|| certificates[name].length > 16 * 1024) throw new Error();
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
// Do not expose child-process diagnostics: they can contain private input.
|
|
28
|
+
throw new Error("Windows prediction certificate generation failed; verify Windows PowerShell, .NET Framework 4.7.2 or later and current-user policy");
|
|
29
|
+
}
|
|
30
|
+
const pem = value => `-----BEGIN CERTIFICATE-----\n${value.match(/.{1,64}/g).join("\n")}\n-----END CERTIFICATE-----\n`;
|
|
31
|
+
return { ca: pem(certificates.ca), cert: pem(certificates.cert),
|
|
32
|
+
key: leaf.privateKey.export({ type: "pkcs8", format: "pem" }) };
|
|
33
|
+
}
|