omp-opencode-bridge 0.0.0-stage → 2.6.0

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/src/index.ts ADDED
@@ -0,0 +1,364 @@
1
+ /**
2
+ * omp/pi extension — registers the local opencode-free-bridge as an
3
+ * OpenAI-completions provider, so an OMP session can use the free model list
4
+ * with no account and no API key.
5
+ *
6
+ * The bridge itself ships inside this package (`server.ts` at the package
7
+ * root). The extension reuses a bridge that is already listening on the port,
8
+ * otherwise starts one under Bun, and keeps it for the session.
9
+ *
10
+ * Usage inside OMP:
11
+ * /opencode-free → bridge + provider status
12
+ * /opencode-free models → list the registered model ids
13
+ * /opencode-free refresh-models → re-fetch /v1/models and re-register
14
+ * /opencode-free start|stop|restart
15
+ * /opencode-free logs → tail the bridge log
16
+ * /opencode-free health → raw /health JSON
17
+ * /opencode-free help
18
+ *
19
+ * No runtime dependencies: node builtins only. The `pi` API surface used here
20
+ * is three calls (registerProvider, registerCommand, ui.notify), declared
21
+ * locally as structural types so this file never imports a package that is not
22
+ * installed.
23
+ */
24
+
25
+ import { spawn, type ChildProcess } from "node:child_process";
26
+ import fs from "node:fs";
27
+ import os from "node:os";
28
+ import path from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+
31
+ const EXTENSION_NAME = "opencode-free";
32
+ const HOST = "127.0.0.1";
33
+ const DEFAULT_PORT = Number(process.env.OPENCODE_BRIDGE_PORT) || 20129;
34
+ const START_TIMEOUT_MS = 20_000;
35
+
36
+ // Where the installed package keeps the bridge. `src/index.ts` → package root.
37
+ const PACKAGE_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
38
+
39
+ const STATE_DIR = process.env.OPENCODE_BRIDGE_STATE_DIR || path.join(os.homedir(), ".opencode-free-bridge");
40
+ const STATE_FILE = path.join(STATE_DIR, "omp-plugin.json");
41
+ const LOG_FILE = path.join(STATE_DIR, "omp-plugin.log");
42
+ const MODELS_CACHE_FILE = path.join(STATE_DIR, "omp-models.json");
43
+
44
+ /** The slice of `@earendil-works/pi-coding-agent` this extension calls. */
45
+ interface ProviderModelConfig {
46
+ id: string;
47
+ name: string;
48
+ api: string;
49
+ reasoning: boolean;
50
+ input: Array<"text" | "image">;
51
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
52
+ contextWindow: number;
53
+ maxTokens: number;
54
+ }
55
+
56
+ interface ExtensionAPI {
57
+ registerProvider(
58
+ name: string,
59
+ config: {
60
+ baseUrl: string;
61
+ apiKey: string;
62
+ api: string;
63
+ models: ProviderModelConfig[];
64
+ refreshModels?: () => Promise<ProviderModelConfig[]>;
65
+ }
66
+ ): void;
67
+ registerCommand(
68
+ name: string,
69
+ command: {
70
+ description: string;
71
+ getArgumentCompletions?: (prefix: string) => Array<{ value: string; label: string }>;
72
+ handler: (args: string, ctx: { ui: { notify: (message: string, level?: string) => void } }) => Promise<void>;
73
+ }
74
+ ): void;
75
+ setStatus?: (name: string, status: string) => void;
76
+ ui: { notify: (message: string, level?: string) => void };
77
+ }
78
+
79
+ interface BridgeState {
80
+ port: number;
81
+ pid?: number;
82
+ startedAt?: number;
83
+ }
84
+
85
+ const MODEL_BASE: Omit<ProviderModelConfig, "id" | "name"> = {
86
+ api: "openai-completions",
87
+ reasoning: true,
88
+ input: ["text"],
89
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
90
+ contextWindow: 128_000,
91
+ maxTokens: 16_384,
92
+ };
93
+
94
+ function readState(): BridgeState | null {
95
+ try {
96
+ const data = JSON.parse(fs.readFileSync(STATE_FILE, "utf8"));
97
+ if (typeof data?.port === "number") return data as BridgeState;
98
+ } catch {
99
+ // no state yet
100
+ }
101
+ return null;
102
+ }
103
+
104
+ function writeState(state: BridgeState): void {
105
+ try {
106
+ fs.mkdirSync(STATE_DIR, { recursive: true });
107
+ fs.writeFileSync(STATE_FILE, JSON.stringify(state));
108
+ } catch {
109
+ // a read-only home must not break the session
110
+ }
111
+ }
112
+
113
+ function pidAlive(pid: number): boolean {
114
+ if (!pid || pid <= 0) return false;
115
+ try {
116
+ process.kill(pid, 0);
117
+ return true;
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ async function healthz(port: number): Promise<Record<string, unknown> | null> {
124
+ try {
125
+ const res = await fetch(`http://${HOST}:${port}/health`, { signal: AbortSignal.timeout(1500) });
126
+ if (!res.ok) return null;
127
+ return (await res.json()) as Record<string, unknown>;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ async function fetchModels(port: number): Promise<ProviderModelConfig[]> {
134
+ try {
135
+ const res = await fetch(`http://${HOST}:${port}/v1/models`, {
136
+ headers: { Accept: "application/json" },
137
+ signal: AbortSignal.timeout(5000),
138
+ });
139
+ if (!res.ok) return [];
140
+ const payload = (await res.json()) as { data?: Array<{ id?: string }> };
141
+ const entries = Array.isArray(payload?.data) ? payload.data : [];
142
+ return entries
143
+ .map((m) => String(m?.id || ""))
144
+ .filter(Boolean)
145
+ .map((id) => ({ ...MODEL_BASE, id, name: id }));
146
+ } catch {
147
+ return [];
148
+ }
149
+ }
150
+
151
+ function saveModelsCache(models: ProviderModelConfig[]): void {
152
+ try {
153
+ fs.mkdirSync(STATE_DIR, { recursive: true });
154
+ fs.writeFileSync(MODELS_CACHE_FILE, JSON.stringify({ savedAt: Date.now(), models }));
155
+ } catch {
156
+ // ignore
157
+ }
158
+ }
159
+
160
+ function loadModelsCache(): ProviderModelConfig[] {
161
+ try {
162
+ const data = JSON.parse(fs.readFileSync(MODELS_CACHE_FILE, "utf8"));
163
+ if (Array.isArray(data?.models)) {
164
+ return data.models.filter((m: ProviderModelConfig) => typeof m?.id === "string");
165
+ }
166
+ } catch {
167
+ // no cache
168
+ }
169
+ return [];
170
+ }
171
+
172
+ /** Start the bridge from this package, detached, and wait for `/health`. */
173
+ async function startBridge(port: number): Promise<BridgeState> {
174
+ fs.mkdirSync(STATE_DIR, { recursive: true });
175
+ const out = fs.openSync(LOG_FILE, "a");
176
+ const child: ChildProcess = spawn(process.env.OPENCODE_BRIDGE_BUN || "bun", ["server.ts"], {
177
+ cwd: PACKAGE_ROOT,
178
+ env: {
179
+ ...process.env,
180
+ PORT: String(port),
181
+ HOST,
182
+ OPENCODE_BRIDGE_STATE_DIR: STATE_DIR,
183
+ },
184
+ detached: true,
185
+ stdio: ["ignore", out, out],
186
+ });
187
+ child.unref();
188
+ fs.closeSync(out);
189
+
190
+ const deadline = Date.now() + START_TIMEOUT_MS;
191
+ while (Date.now() < deadline) {
192
+ const health = await healthz(port);
193
+ if (health) {
194
+ const state: BridgeState = { port, pid: child.pid, startedAt: Date.now() };
195
+ writeState(state);
196
+ return state;
197
+ }
198
+ if (child.pid && !pidAlive(child.pid)) break;
199
+ await new Promise((r) => setTimeout(r, 250));
200
+ }
201
+ throw new Error(
202
+ `opencode-free-bridge did not answer /health on ${HOST}:${port} within ${START_TIMEOUT_MS}ms — inspect ${LOG_FILE}`
203
+ );
204
+ }
205
+
206
+ /** Reuse a healthy bridge, else start one. */
207
+ async function ensureBridge(port: number): Promise<BridgeState> {
208
+ const state = readState();
209
+ if (state && (await healthz(state.port))) {
210
+ return { ...state, port: state.port };
211
+ }
212
+ if (await healthz(port)) return { port };
213
+ return startBridge(port);
214
+ }
215
+
216
+ function stopBridge(): boolean {
217
+ const state = readState();
218
+ if (!state?.pid || !pidAlive(state.pid)) return false;
219
+ try {
220
+ process.kill(state.pid);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+
227
+ function tailLog(lines: number): string {
228
+ try {
229
+ const text = fs.readFileSync(LOG_FILE, "utf8").trimEnd().split(/\r?\n/);
230
+ return text.slice(-lines).join("\n");
231
+ } catch {
232
+ return "(no log yet — the bridge logs to " + LOG_FILE + ")";
233
+ }
234
+ }
235
+
236
+ export default async function (pi: ExtensionAPI): Promise<void> {
237
+ let port = DEFAULT_PORT;
238
+ let models: ProviderModelConfig[] = loadModelsCache();
239
+
240
+ const register = (list: ProviderModelConfig[], activePort: number): void => {
241
+ pi.registerProvider(EXTENSION_NAME, {
242
+ baseUrl: `http://${HOST}:${activePort}/v1`,
243
+ apiKey: "public",
244
+ api: "openai-completions",
245
+ models: list,
246
+ refreshModels: async () => {
247
+ const fresh = await fetchModels(activePort);
248
+ if (fresh.length > 0) {
249
+ models = fresh;
250
+ saveModelsCache(fresh);
251
+ }
252
+ return fresh;
253
+ },
254
+ });
255
+ pi.setStatus?.(EXTENSION_NAME, `${list.length} free models via ${HOST}:${activePort}`);
256
+ };
257
+
258
+ // Register with the cached list first so the provider exists even when the
259
+ // bridge refuses to start, then discover for real: OMP resolves `--model`
260
+ // before the first turn, so a background refresh would lose that race.
261
+ register(models, port);
262
+
263
+ const refresh = async (): Promise<void> => {
264
+ const state = await ensureBridge(port);
265
+ port = state.port;
266
+ const fresh = await fetchModels(port);
267
+ if (fresh.length > 0) {
268
+ models = fresh;
269
+ saveModelsCache(fresh);
270
+ }
271
+ register(models, port);
272
+ };
273
+
274
+ try {
275
+ await refresh();
276
+ } catch (err) {
277
+ pi.ui.notify(`${EXTENSION_NAME}: ${(err as Error).message}`, "warning");
278
+ }
279
+
280
+ pi.registerCommand(EXTENSION_NAME, {
281
+ description:
282
+ "opencode-free-bridge provider: status | models | refresh-models | start | stop | restart | health | logs | help",
283
+ getArgumentCompletions: (prefix: string) =>
284
+ ["status", "models", "refresh-models", "start", "stop", "restart", "health", "logs", "help"]
285
+ .filter((s) => s.startsWith(prefix))
286
+ .map((s) => ({ value: s, label: s })),
287
+ handler: async (args, ctx) => {
288
+ const sub = String(args || "").trim().split(/\s+/)[0] || "status";
289
+ const notify = (message: string, level = "info") =>
290
+ (ctx?.ui?.notify ? ctx.ui.notify(message, level) : pi.ui.notify(message, level));
291
+
292
+ switch (sub) {
293
+ case "status": {
294
+ const health = await healthz(port);
295
+ notify(
296
+ `${EXTENSION_NAME}: bridge ${health ? `online ${HOST}:${port}` : "offline"} · models=${models.length} · ` +
297
+ `runtime=${String(health?.runtime || "unknown")} · version=${String(health?.version || "?")}`
298
+ );
299
+ break;
300
+ }
301
+ case "models": {
302
+ notify(
303
+ models.length > 0
304
+ ? models.map((m) => `${EXTENSION_NAME}/${m.id}`).join("\n")
305
+ : "no models yet — /opencode-free refresh-models"
306
+ );
307
+ break;
308
+ }
309
+ case "refresh-models": {
310
+ await refresh();
311
+ notify(`re-registered ${models.length} model(s) from ${HOST}:${port}`);
312
+ break;
313
+ }
314
+ case "start": {
315
+ const state = await ensureBridge(port);
316
+ port = state.port;
317
+ notify(`bridge ${HOST}:${port} is ${state.pid ? "started by the plugin" : "already running"}`);
318
+ break;
319
+ }
320
+ case "stop": {
321
+ notify(stopBridge() ? "bridge stopped" : "no bridge started by the plugin (it may be running elsewhere)", "warning");
322
+ break;
323
+ }
324
+ case "restart": {
325
+ stopBridge();
326
+ await new Promise((r) => setTimeout(r, 500));
327
+ const state = await ensureBridge(port);
328
+ port = state.port;
329
+ await refresh();
330
+ notify(`bridge restarted on ${HOST}:${port}`);
331
+ break;
332
+ }
333
+ case "health": {
334
+ const health = await healthz(port);
335
+ notify(health ? JSON.stringify(health, null, 2).slice(0, 4000) : `no /health answer on ${HOST}:${port}`, health ? "info" : "warning");
336
+ break;
337
+ }
338
+ case "logs": {
339
+ notify(tailLog(40));
340
+ break;
341
+ }
342
+ case "help":
343
+ default: {
344
+ notify(
345
+ [
346
+ `${EXTENSION_NAME} — OpenCode free-tier models for OMP`,
347
+ " /opencode-free status bridge + provider state",
348
+ " /opencode-free models registered model ids",
349
+ " /opencode-free refresh-models re-read /v1/models",
350
+ " /opencode-free start|stop|restart",
351
+ " /opencode-free health raw /health JSON",
352
+ " /opencode-free logs tail " + LOG_FILE,
353
+ `Use: omp --model ${EXTENSION_NAME}/<model-id> -p "hello"`,
354
+ ].join("\n")
355
+ );
356
+ break;
357
+ }
358
+ }
359
+ },
360
+ });
361
+ }
362
+
363
+ // Exported for tests: the plugin's own promise surface, no OMP needed.
364
+ export { ensureBridge, fetchModels, healthz, startBridge, stopBridge, DEFAULT_PORT };
@@ -0,0 +1,116 @@
1
+ // Token budgeting for reasoning models.
2
+ //
3
+ // Reasoning models (Muse Spark, MiMo, Nemotron, LongCat, ...) emit
4
+ // chain-of-thought tokens that count against the SAME output budget as the
5
+ // visible answer. When a client asks for a small max_tokens — a probe, a
6
+ // title, a one-word reply — the model spends the whole budget thinking and
7
+ // returns finish_reason: "length" with empty content. The failure is silent:
8
+ // no error, no content, tokens still billed.
9
+ //
10
+ // OpenRouter documents the behaviour ("reasoning tokens count against
11
+ // max_tokens ... set max_tokens well above the expected reasoning length"),
12
+ // and the accepted fix in the wider ecosystem is an ADDITIVE budget:
13
+ //
14
+ // max_tokens = answer_budget + thinking_budget
15
+ //
16
+ // (see goose#11142, which adopts the pi coding agent's formula). This module
17
+ // applies that here, so a short request still returns a visible answer.
18
+ //
19
+ // Tuning notes, from measurements against the live OpenCode Zen gateway:
20
+ // - max_tokens 50 -> empty for Muse
21
+ // - max_tokens 100 -> empty for Muse and cat-jam
22
+ // - max_tokens 256 -> empty for big-pickle; longcat finished exactly on the cap
23
+ // - max_tokens 512 -> content returned, but truncated on long answers
24
+ // - max_tokens 2048 + thinking headroom -> complete answers
25
+ //
26
+ // Hence MIN_ANSWER_TOKENS = 1024 (matching pi and Anthropic's reservation)
27
+ // and THINKING_BUDGET = 4096, which covers the ~100-800 reasoning tokens
28
+ // observed here with room to spare.
29
+
30
+ const MIN_ANSWER_TOKENS = 1024;
31
+ const THINKING_BUDGET = 4096;
32
+ const MAX_OUTPUT_TOKENS = 131072;
33
+ // Non-reasoning models still get a floor, so a tiny client value cannot
34
+ // truncate a normal answer mid-sentence.
35
+ const MIN_PLAIN_TOKENS = 512;
36
+
37
+ // Models that think before answering. The provider catalog states this
38
+ // outright (`reasoning: true` on every live free model), and the catalog is
39
+ // cached on disk after its first fetch, so the bridge asks it instead of
40
+ // maintaining a hand-written substring list.
41
+ const REASONING_MODEL_HINTS: readonly string[] = Object.freeze([]);
42
+
43
+ /** The parts of a chat request body this module reads. */
44
+ interface ReasoningRequestBody {
45
+ reasoning_effort?: unknown;
46
+ }
47
+
48
+ function isReasoningModel(modelId: unknown): boolean {
49
+ const id = String(modelId || "").toLowerCase();
50
+ if (!id) return false;
51
+ try {
52
+ const facts = require("./identity").getModelFacts(id);
53
+ if (facts && typeof facts.reasoning === "boolean") return facts.reasoning;
54
+ } catch {
55
+ // identity unavailable: fall through.
56
+ }
57
+ return false;
58
+ }
59
+
60
+ // A request counts as reasoning-bound when it targets a known thinking model,
61
+ // or when the client explicitly asked for reasoning effort.
62
+ function isReasoningRequest(body: ReasoningRequestBody | null | undefined, modelId: unknown): boolean {
63
+ if (isReasoningModel(modelId)) return true;
64
+ const effort = body && body.reasoning_effort;
65
+ return Boolean(effort) && effort !== "none";
66
+ }
67
+
68
+ // Clamp the client's requested budget into a range that always leaves room for
69
+ // a visible answer. The client's value is never lowered — only raised when it
70
+ // is too small to survive the model's reasoning phase.
71
+ function parseRequestedTokens(requested: unknown): number {
72
+ if (requested === undefined || requested === null || typeof requested === "boolean") {
73
+ return MAX_OUTPUT_TOKENS;
74
+ }
75
+ if (typeof requested === "string" && requested.trim() === "") {
76
+ return MAX_OUTPUT_TOKENS;
77
+ }
78
+ const raw = Number(requested);
79
+ if (!Number.isFinite(raw) || raw < 0) {
80
+ return MAX_OUTPUT_TOKENS;
81
+ }
82
+ return Math.floor(raw);
83
+ }
84
+
85
+ function effectiveMaxTokens(
86
+ requested: unknown,
87
+ modelId?: unknown,
88
+ body?: ReasoningRequestBody | null
89
+ ): number {
90
+ const wanted = parseRequestedTokens(requested);
91
+
92
+ const effective = isReasoningRequest(body, modelId)
93
+ ? Math.max(wanted, MIN_ANSWER_TOKENS) + THINKING_BUDGET
94
+ : Math.max(wanted, MIN_PLAIN_TOKENS);
95
+
96
+ // The catalog states each model's output ceiling (`limit.output`). Asking for
97
+ // more than a model can emit is rejected or silently truncated upstream, so
98
+ // the cap follows the model rather than a single global constant.
99
+ let ceiling = MAX_OUTPUT_TOKENS;
100
+ try {
101
+ const facts = require("./identity").getModelFacts(modelId);
102
+ if (facts && facts.maxOutput > 0) ceiling = Math.min(ceiling, facts.maxOutput);
103
+ } catch {}
104
+ return Math.min(effective, ceiling);
105
+ }
106
+
107
+ module.exports = {
108
+ MIN_ANSWER_TOKENS,
109
+ THINKING_BUDGET,
110
+ MAX_OUTPUT_TOKENS,
111
+ MIN_PLAIN_TOKENS,
112
+ REASONING_MODEL_HINTS,
113
+ isReasoningModel,
114
+ isReasoningRequest,
115
+ effectiveMaxTokens,
116
+ };
@@ -0,0 +1,39 @@
1
+ {
2
+ "runtime": "bun 1.4.2",
3
+ "legacyVersion": "0x303",
4
+ "cipherCount": 17,
5
+ "extensionCount": 12,
6
+ "ciphers": [
7
+ "1301",
8
+ "1302",
9
+ "1303",
10
+ "c02b",
11
+ "c02f",
12
+ "c02c",
13
+ "c030",
14
+ "cca9",
15
+ "cca8",
16
+ "c009",
17
+ "c013",
18
+ "c00a",
19
+ "c014",
20
+ "009c",
21
+ "009d",
22
+ "002f",
23
+ "0035"
24
+ ],
25
+ "extensions": [
26
+ "0017",
27
+ "ff01",
28
+ "000a",
29
+ "000b",
30
+ "0023",
31
+ "0010",
32
+ "0005",
33
+ "000d",
34
+ "0012",
35
+ "0033",
36
+ "002d",
37
+ "002b"
38
+ ]
39
+ }
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * transport-fingerprint.ts — record and compare the outbound TLS ClientHello.
4
+ *
5
+ * Why this exists: the free-tier gate checks the transport, not just headers.
6
+ * Measured from one IP in one minute with identical requests:
7
+ *
8
+ * real CLI v2.0.32 (Bun) 200
9
+ * bridge on Bun 200 (6/6)
10
+ * bridge on Node 403 (0/6)
11
+ * curl, HTTP/1.1 or h2 403
12
+ *
13
+ * The bridge therefore depends on Bun's TLS stack matching the CLI's. Bun 1.4.2
14
+ * (the version bundled in CLI 2.0.32) and 1.4.3 produce identical ClientHellos
15
+ * today, but nothing guarantees that for 1.5. This script makes the drift
16
+ * visible: it opens a TCP listener, points a fetch at it, and parses the
17
+ * ClientHello without any TLS library.
18
+ *
19
+ * bun transport-fingerprint.ts print this runtime's fingerprint
20
+ * bun transport-fingerprint.ts --check exit 1 if it drifted from the baseline
21
+ * bun transport-fingerprint.ts --write-baseline record the current fingerprint
22
+ *
23
+ * The fingerprint is the cipher list and the extension set + order. The
24
+ * `random` and `key_share` fields differ on every connection by design and are
25
+ * not part of it.
26
+ */
27
+ const net = require("net");
28
+ const fs = require("fs");
29
+ const path = require("path");
30
+
31
+ const BASELINE = path.join(__dirname, "transport-baseline.json");
32
+
33
+ /** The transport-identifying part of a ClientHello. */
34
+ interface ClientHelloFingerprint {
35
+ legacyVersion: string;
36
+ ciphers: string[];
37
+ extensions: string[];
38
+ }
39
+
40
+ /** A fingerprint plus the runtime that produced it, as recorded in the baseline. */
41
+ interface FingerprintReport extends ClientHelloFingerprint {
42
+ runtime: string;
43
+ cipherCount: number;
44
+ extensionCount: number;
45
+ }
46
+
47
+ /** Parse a TLS ClientHello record. No TLS library: the bytes are the API. */
48
+ function parseClientHello(buf: Buffer): ClientHelloFingerprint {
49
+ if (!Buffer.isBuffer(buf) || buf.length < 43 || buf[0] !== 0x16) {
50
+ throw new Error("not a TLS handshake record");
51
+ }
52
+ let o = 5; // record header: type(1) version(2) length(2)
53
+ if (buf[o] !== 0x01) throw new Error("not a ClientHello");
54
+ o += 4; // handshake type + 3-byte length
55
+ const legacyVersion = buf.readUInt16BE(o);
56
+ o += 2 + 32; // version + random
57
+ if (o >= buf.length) throw new Error("truncated ClientHello");
58
+ o += 1 + buf[o]; // session id
59
+ if (o + 2 > buf.length) throw new Error("truncated ClientHello");
60
+ const csLen = buf.readUInt16BE(o);
61
+ o += 2;
62
+ if (csLen % 2 !== 0 || o + csLen >= buf.length) throw new Error("truncated ClientHello");
63
+ const ciphers = [];
64
+ for (let i = 0; i < csLen; i += 2) ciphers.push(buf.readUInt16BE(o + i).toString(16).padStart(4, "0"));
65
+ o += csLen;
66
+ o += 1 + buf[o]; // compression methods
67
+ if (o + 2 > buf.length) throw new Error("truncated ClientHello");
68
+ const extLen = buf.readUInt16BE(o);
69
+ o += 2;
70
+ if (o + extLen > buf.length) throw new Error("truncated ClientHello");
71
+ const extensions = [];
72
+ const end = o + extLen;
73
+ while (o < end) {
74
+ if (o + 4 > end) throw new Error("truncated ClientHello");
75
+ const type = buf.readUInt16BE(o);
76
+ const len = buf.readUInt16BE(o + 2);
77
+ if (o + 4 + len > end) throw new Error("truncated ClientHello");
78
+ extensions.push(type.toString(16).padStart(4, "0"));
79
+ o += 4 + len;
80
+ }
81
+ return {
82
+ legacyVersion: "0x" + legacyVersion.toString(16),
83
+ ciphers,
84
+ extensions,
85
+ };
86
+ }
87
+
88
+ /** Capture this runtime's ClientHello by pointing a fetch at a local listener. */
89
+ function capture(): Promise<ClientHelloFingerprint> {
90
+ return new Promise((resolve, reject) => {
91
+ const srv = net.createServer((sock) => {
92
+ sock.once("data", (buf: Buffer) => {
93
+ sock.destroy();
94
+ srv.close();
95
+ try {
96
+ resolve(parseClientHello(buf));
97
+ } catch (err) {
98
+ reject(err);
99
+ }
100
+ });
101
+ });
102
+ srv.on("error", reject);
103
+ srv.listen(0, "127.0.0.1", () => {
104
+ // `listen(0, ...)` with an IP always yields an AddressInfo.
105
+ const { port } = srv.address() as { port: number };
106
+ fetch(`https://127.0.0.1:${port}/`, { method: "POST" }).catch(() => {});
107
+ setTimeout(() => {
108
+ try {
109
+ srv.close();
110
+ } catch {}
111
+ reject(new Error("no ClientHello captured within 3s"));
112
+ }, 3000).unref();
113
+ });
114
+ });
115
+ }
116
+
117
+ function describe(fp: ClientHelloFingerprint): FingerprintReport {
118
+ const runtime = process.versions.bun ? `bun ${process.versions.bun}` : `node ${process.versions.node}`;
119
+ return {
120
+ runtime,
121
+ legacyVersion: fp.legacyVersion,
122
+ cipherCount: fp.ciphers.length,
123
+ extensionCount: fp.extensions.length,
124
+ ciphers: fp.ciphers,
125
+ extensions: fp.extensions,
126
+ };
127
+ }
128
+
129
+ async function main(): Promise<number> {
130
+ const fp = await capture();
131
+ const now = describe(fp);
132
+ const wantWrite = process.argv.includes("--write-baseline");
133
+ const wantCheck = process.argv.includes("--check");
134
+
135
+ if (wantWrite) {
136
+ fs.writeFileSync(BASELINE, JSON.stringify(now, null, 2) + "\n");
137
+ console.log(`baseline written: ${now.cipherCount} ciphers, ${now.extensionCount} extensions (${now.runtime})`);
138
+ return 0;
139
+ }
140
+
141
+ if (wantCheck) {
142
+ if (!fs.existsSync(BASELINE)) {
143
+ console.error(`no baseline at ${BASELINE}; run with --write-baseline first`);
144
+ return 2;
145
+ }
146
+ const base: FingerprintReport = JSON.parse(fs.readFileSync(BASELINE, "utf8"));
147
+ const sameCiphers = JSON.stringify(base.ciphers) === JSON.stringify(now.ciphers);
148
+ const sameExts = JSON.stringify(base.extensions) === JSON.stringify(now.extensions);
149
+ if (sameCiphers && sameExts) {
150
+ console.log(
151
+ `OK: ${now.runtime} matches the baseline (${now.cipherCount} ciphers, ${now.extensionCount} extensions)`
152
+ );
153
+ return 0;
154
+ }
155
+ console.error(`DRIFT: ${now.runtime} no longer matches the baseline (recorded on ${base.runtime})`);
156
+ if (!sameCiphers) {
157
+ console.error(` ciphers: baseline ${base.cipherCount} → now ${now.cipherCount}`);
158
+ console.error(` was: ${base.ciphers.join(" ")}`);
159
+ console.error(` now: ${now.ciphers.join(" ")}`);
160
+ }
161
+ if (!sameExts) {
162
+ console.error(` extensions: baseline ${base.extensionCount} → now ${now.extensionCount}`);
163
+ console.error(` was: ${base.extensions.join(" ")}`);
164
+ console.error(` now: ${now.extensions.join(" ")}`);
165
+ }
166
+ return 1;
167
+ }
168
+
169
+ console.log(JSON.stringify(now, null, 2));
170
+ return 0;
171
+ }
172
+
173
+ if (require.main === module) {
174
+ main()
175
+ .then((code) => process.exit(code))
176
+ .catch((err) => {
177
+ console.error(`error: ${err.message}`);
178
+ process.exit(2);
179
+ });
180
+ }
181
+
182
+ module.exports = { parseClientHello, capture, describe };