@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.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.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,686 @@
1
+ /**
2
+ * The CONNECT proxy warp puts in front of the child process.
3
+ *
4
+ * Ported from wardex proxy.go, with two deliberate narrowings:
5
+ *
6
+ * - wardex decrypts every host once --mitm is on; warp decrypts only hosts a
7
+ * route could match and blindly tunnels the rest. Under warp the agent
8
+ * believes it is talking straight to api.anthropic.com, so the less we
9
+ * terminate, the fewer ways that belief can break.
10
+ * - wardex owns its listener; warp attaches to the proxy server fiche is
11
+ * already running. CONNECT is a distinct event from a normal request, so one
12
+ * port serves both the origin-form traffic fiche handles and the
13
+ * absolute-form/CONNECT traffic a forward proxy handles.
14
+ */
15
+ import { Agent as HttpAgent, createServer as createHttpServer, request as httpRequest, } from 'node:http';
16
+ import { Agent as HttpsAgent, request as httpsRequest, } from 'node:https';
17
+ import { connect as netConnect, isIP } from 'node:net';
18
+ import { connect as tlsConnect, TLSSocket } from 'node:tls';
19
+ import { hostCouldMatch, matchRoute, normalizeRoutePath, rewriteUrl } from './route.js';
20
+ const DNS_HOST_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i;
21
+ function isValidSniHost(name) {
22
+ if (isIP(name) !== 0)
23
+ return true;
24
+ return name.length > 0 && name.length <= 253 && DNS_HOST_RE.test(name);
25
+ }
26
+ function normalizeHostKey(host) {
27
+ const stripped = host.replace(/\.$/, '');
28
+ return isIP(stripped) !== 0 ? stripped : stripped.toLowerCase();
29
+ }
30
+ function isLoopbackHost(host) {
31
+ const norm = normalizeHostKey(host);
32
+ return norm === 'localhost' || norm === '::1' || norm.startsWith('127.');
33
+ }
34
+ const FAIL_OPEN_ERRNO = new Set(['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT']);
35
+ const FAIL_OPEN_CONNECT_TIMEOUT_MS = 1500;
36
+ const FAIL_OPEN_REPLAY_CAP_BYTES = 4 * 1024 * 1024;
37
+ function isFailOpenError(err) {
38
+ if (err instanceof AggregateError) {
39
+ return err.errors.length > 0 && err.errors.every((inner) => isFailOpenError(inner));
40
+ }
41
+ const code = err?.code;
42
+ return typeof code === 'string' && FAIL_OPEN_ERRNO.has(code);
43
+ }
44
+ /** Canonical Host header value for `protocol` (`https:` omits `:443`, `http:` omits `:80`). */
45
+ function canonicalHostHeader(host, port, protocol) {
46
+ const normHost = normalizeHostKey(host);
47
+ const bracketed = normHost.includes(':') && !normHost.startsWith('[') ? `[${normHost}]` : normHost;
48
+ const isDefaultPort = (protocol === 'https:' && port === '443') || (protocol === 'http:' && port === '80');
49
+ return isDefaultPort ? bracketed : `${bracketed}:${port}`;
50
+ }
51
+ /** Validate client-supplied `Host` header against expected `host:port` (when present). */
52
+ function hostHeaderMatches(rawHostHeader, expectedHost, expectedPort) {
53
+ if (rawHostHeader === undefined)
54
+ return true;
55
+ if (Array.isArray(rawHostHeader))
56
+ return false;
57
+ const trimmed = rawHostHeader.trim();
58
+ if (!trimmed)
59
+ return false;
60
+ const parsed = splitHostPort(trimmed, expectedPort);
61
+ return normalizeHostKey(parsed.host) === normalizeHostKey(expectedHost) && parsed.port === expectedPort;
62
+ }
63
+ /**
64
+ * Hop-by-hop headers are meaningful only on a single connection, so they must
65
+ * not be copied onto the re-originated request (RFC 9110 7.6.1).
66
+ */
67
+ const HOP_HEADERS = new Set([
68
+ 'connection',
69
+ 'proxy-connection',
70
+ 'keep-alive',
71
+ 'proxy-authenticate',
72
+ 'proxy-authorization',
73
+ 'te',
74
+ 'trailer',
75
+ 'transfer-encoding',
76
+ 'upgrade',
77
+ ]);
78
+ /**
79
+ * A CONNECT handler reachable off-host is an open relay, and fiche's HOST env
80
+ * var permits a non-loopback bind. The dashboard already refuses non-loopback
81
+ * callers; the proxy duty needs the same guard for the same reason.
82
+ */
83
+ function isLoopbackAddress(address) {
84
+ if (!address)
85
+ return false;
86
+ const lower = address.toLowerCase();
87
+ return (lower === '::1' || lower.startsWith('127.') || lower.startsWith('::ffff:127.'));
88
+ }
89
+ function splitHostPort(value, fallbackPort) {
90
+ if (value.startsWith('[')) {
91
+ const end = value.indexOf(']');
92
+ if (end < 0)
93
+ return { host: value, port: fallbackPort };
94
+ const rest = value.slice(end + 1);
95
+ return {
96
+ host: value.slice(1, end),
97
+ port: rest.startsWith(':') && rest.length > 1 ? rest.slice(1) : fallbackPort,
98
+ };
99
+ }
100
+ const i = value.lastIndexOf(':');
101
+ if (i < 0)
102
+ return { host: value, port: fallbackPort };
103
+ return { host: value.slice(0, i), port: value.slice(i + 1) || fallbackPort };
104
+ }
105
+ function parsePort(port) {
106
+ if (!/^\d+$/.test(port))
107
+ return null;
108
+ const n = Number(port);
109
+ return Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null;
110
+ }
111
+ /** `host:port`, bracketing IPv6 literals so the result is URL-parseable. */
112
+ function authority(host, port) {
113
+ return host.includes(':') ? `[${host}]:${port}` : `${host}:${port}`;
114
+ }
115
+ function forwardHeaders(headers, canonicalHost) {
116
+ const out = {};
117
+ for (const [key, value] of Object.entries(headers)) {
118
+ const lower = key.toLowerCase();
119
+ if (value === undefined || HOP_HEADERS.has(lower) || lower === 'x-fiche-warp-auth')
120
+ continue;
121
+ if (canonicalHost !== undefined && lower === 'host')
122
+ continue;
123
+ out[key] = value;
124
+ }
125
+ if (canonicalHost !== undefined) {
126
+ out.host = canonicalHost;
127
+ }
128
+ return out;
129
+ }
130
+ function pipeSockets(a, b) {
131
+ a.setNoDelay?.(true);
132
+ b.setNoDelay?.(true);
133
+ a.pipe(b);
134
+ b.pipe(a);
135
+ const destroy = () => {
136
+ a.destroy();
137
+ b.destroy();
138
+ };
139
+ a.on('error', destroy);
140
+ b.on('error', destroy);
141
+ a.on('close', () => b.destroy());
142
+ b.on('close', () => a.destroy());
143
+ }
144
+ /**
145
+ * Every request the agent makes crosses this hop. Node's global agents default
146
+ * to keepAlive:false, so without these each call pays a fresh TCP handshake —
147
+ * plus a full TLS handshake to the real host on the passthrough path.
148
+ */
149
+ const httpAgent = new HttpAgent({ keepAlive: true });
150
+ const httpsAgent = new HttpsAgent({ keepAlive: true });
151
+ export function createWarpHandlers(options) {
152
+ const { ca, onDivert } = options;
153
+ const getRoutes = () => typeof options.routes === 'function' ? options.routes() : options.routes;
154
+ const isSelfLoop = (host, portNum, socketLocalPort) => {
155
+ if (!isLoopbackHost(host))
156
+ return false;
157
+ const configuredSelf = typeof options.selfPort === 'function' ? options.selfPort() : options.selfPort;
158
+ if (configuredSelf !== undefined && portNum === configuredSelf)
159
+ return true;
160
+ if (socketLocalPort !== undefined && portNum === socketLocalPort)
161
+ return true;
162
+ return false;
163
+ };
164
+ const announced = new Set();
165
+ /** Re-originate one request, to a route target or to the real host. */
166
+ const forward = (req, res,
167
+ /** "host" or "host:port": routes may select on the port. */
168
+ hostPort, requestUri,
169
+ // Where the bytes actually go when no route matches. Passed in rather than
170
+ // rebuilt from `host`: a plain `http://host:8080` request reaching us in
171
+ // absolute form must not be re-originated as `https://host:443`.
172
+ origin) => {
173
+ req.socket?.setNoDelay?.(true);
174
+ res.socket?.setNoDelay?.(true);
175
+ let normalizedOrigin;
176
+ let resolvedReq;
177
+ let path;
178
+ let normalizedUri;
179
+ let directTarget;
180
+ let divertTarget = null;
181
+ try {
182
+ normalizedOrigin = new URL(origin);
183
+ resolvedReq = new URL(requestUri, normalizedOrigin);
184
+ if (resolvedReq.origin !== normalizedOrigin.origin) {
185
+ throw new Error('origin mismatch');
186
+ }
187
+ path = normalizeRoutePath(resolvedReq.pathname);
188
+ normalizedUri = path + resolvedReq.search;
189
+ const route = matchRoute(getRoutes(), hostPort, path);
190
+ directTarget = new URL(`${origin}${normalizedUri}`);
191
+ if (route) {
192
+ divertTarget = new URL(rewriteUrl(route, normalizedUri));
193
+ if (!announced.has(route.pattern)) {
194
+ announced.add(route.pattern);
195
+ onDivert?.(hostPort, path, divertTarget.origin);
196
+ }
197
+ }
198
+ }
199
+ catch {
200
+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {
201
+ res.writeHead(400, { 'content-type': 'text/plain' });
202
+ res.end('fiche warp: bad request target');
203
+ }
204
+ return;
205
+ }
206
+ const expectedHost = normalizedOrigin.hostname.startsWith('[') && normalizedOrigin.hostname.endsWith(']')
207
+ ? normalizedOrigin.hostname.slice(1, -1)
208
+ : normalizedOrigin.hostname;
209
+ const expectedPort = normalizedOrigin.port || (normalizedOrigin.protocol === 'https:' ? '443' : '80');
210
+ if (!hostHeaderMatches(req.headers.host, expectedHost, expectedPort)) {
211
+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {
212
+ res.writeHead(421, { 'content-type': 'text/plain' });
213
+ res.end('fiche warp: Misdirected Request');
214
+ }
215
+ return;
216
+ }
217
+ const targetPortNum = parsePort(expectedPort);
218
+ if (targetPortNum !== null && isSelfLoop(expectedHost, targetPortNum, req.socket?.localPort)) {
219
+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {
220
+ res.writeHead(508, { 'content-type': 'text/plain' });
221
+ res.end('fiche warp: proxy loop detected');
222
+ }
223
+ return;
224
+ }
225
+ if (divertTarget) {
226
+ const divHost = divertTarget.hostname.startsWith('[') && divertTarget.hostname.endsWith(']')
227
+ ? divertTarget.hostname.slice(1, -1)
228
+ : divertTarget.hostname;
229
+ const divPort = Number(divertTarget.port || (divertTarget.protocol === 'https:' ? 443 : 80));
230
+ if (isSelfLoop(divHost, divPort, req.socket?.localPort)) {
231
+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {
232
+ res.writeHead(508, { 'content-type': 'text/plain' });
233
+ res.end('fiche warp: route self-loop detected');
234
+ }
235
+ return;
236
+ }
237
+ }
238
+ const authoritativeHost = canonicalHostHeader(expectedHost, expectedPort, normalizedOrigin.protocol);
239
+ let activeOutbound;
240
+ let activeUpstreamRes;
241
+ let downstreamClosed = false;
242
+ let responseStarted = false;
243
+ const cleanupActive = () => {
244
+ downstreamClosed = true;
245
+ activeUpstreamRes?.destroy();
246
+ activeOutbound?.destroy();
247
+ };
248
+ res.on('close', () => {
249
+ if (res.writableFinished)
250
+ return;
251
+ cleanupActive();
252
+ });
253
+ res.on('error', cleanupActive);
254
+ req.on('error', (err) => {
255
+ downstreamClosed = true;
256
+ if (activeOutbound && !activeOutbound.destroyed)
257
+ activeOutbound.destroy(err);
258
+ });
259
+ const abortDownstream = (err) => {
260
+ if (!res.writableEnded && !res.destroyed) {
261
+ res.destroy(err);
262
+ }
263
+ };
264
+ const allowInitialFailOpen = Boolean(divertTarget && options.failOpenOnDivertRefused);
265
+ const bufferedChunks = [];
266
+ let bufferedBytes = 0;
267
+ let bufferOverflowed = false;
268
+ let reqStreamEnded = Boolean(req.readableEnded);
269
+ let activeSink;
270
+ if (allowInitialFailOpen) {
271
+ req.on('data', (chunk) => {
272
+ if (downstreamClosed)
273
+ return;
274
+ if (!responseStarted && !bufferOverflowed) {
275
+ if (bufferedBytes + chunk.byteLength <= FAIL_OPEN_REPLAY_CAP_BYTES) {
276
+ bufferedChunks.push(chunk);
277
+ bufferedBytes += chunk.byteLength;
278
+ }
279
+ else {
280
+ bufferOverflowed = true;
281
+ bufferedChunks.length = 0;
282
+ }
283
+ }
284
+ if (activeSink && !activeSink.destroyed && !activeSink.writableEnded) {
285
+ const ok = activeSink.write(chunk);
286
+ if (!ok && bufferOverflowed)
287
+ req.pause?.();
288
+ }
289
+ });
290
+ req.on('end', () => {
291
+ reqStreamEnded = true;
292
+ if (activeSink && !activeSink.destroyed && !activeSink.writableEnded) {
293
+ activeSink.end();
294
+ }
295
+ });
296
+ }
297
+ const sendToTarget = (target, allowFailOpen, isDivert) => {
298
+ const send = target.protocol === 'https:' ? httpsRequest : httpRequest;
299
+ const hostname = target.hostname.startsWith('[') && target.hostname.endsWith(']')
300
+ ? target.hostname.slice(1, -1)
301
+ : target.hostname;
302
+ const outHeaders = forwardHeaders(req.headers, authoritativeHost);
303
+ if (isDivert && options.warpAuthToken) {
304
+ outHeaders['x-fiche-warp-auth'] = options.warpAuthToken;
305
+ }
306
+ if (allowFailOpen) {
307
+ req.pause?.();
308
+ }
309
+ const outbound = send({
310
+ protocol: target.protocol,
311
+ hostname,
312
+ port: target.port || (target.protocol === 'https:' ? 443 : 80),
313
+ method: req.method,
314
+ path: target.pathname + target.search,
315
+ // Keep the authoritative Host (stripped of default :443/:80) so downstream
316
+ // routes on the vhost rather than the divert loopback port.
317
+ headers: outHeaders,
318
+ setHost: false,
319
+ agent: allowFailOpen ? false : (target.protocol === 'https:' ? httpsAgent : httpAgent),
320
+ });
321
+ activeOutbound = outbound;
322
+ outbound.setNoDelay?.(true);
323
+ let piped = false;
324
+ let retried = false;
325
+ let connectTimer;
326
+ const clearConnectTimer = () => {
327
+ if (connectTimer !== undefined) {
328
+ clearTimeout(connectTimer);
329
+ connectTimer = undefined;
330
+ }
331
+ };
332
+ const startPipe = () => {
333
+ clearConnectTimer();
334
+ if (piped || downstreamClosed || outbound.destroyed)
335
+ return;
336
+ piped = true;
337
+ if (allowInitialFailOpen) {
338
+ activeSink = outbound;
339
+ for (const chunk of bufferedChunks) {
340
+ if (outbound.destroyed || outbound.writableEnded)
341
+ break;
342
+ outbound.write(chunk);
343
+ }
344
+ if (reqStreamEnded) {
345
+ if (!outbound.destroyed && !outbound.writableEnded)
346
+ outbound.end();
347
+ }
348
+ else {
349
+ outbound.on('drain', () => {
350
+ if (!downstreamClosed)
351
+ req.resume?.();
352
+ });
353
+ req.resume?.();
354
+ }
355
+ return;
356
+ }
357
+ if (req.readableEnded)
358
+ outbound.end();
359
+ else
360
+ req.pipe(outbound);
361
+ };
362
+ const onResponse = (upstream) => {
363
+ clearConnectTimer();
364
+ responseStarted = true;
365
+ bufferedChunks.length = 0;
366
+ activeUpstreamRes = upstream;
367
+ upstream.socket?.setNoDelay?.(true);
368
+ upstream.on('error', abortDownstream);
369
+ upstream.on('aborted', () => abortDownstream());
370
+ upstream.on('close', () => {
371
+ if (!upstream.complete)
372
+ abortDownstream();
373
+ });
374
+ res.writeHead(upstream.statusCode ?? 502, forwardHeaders(upstream.headers));
375
+ res.flushHeaders?.();
376
+ // Streamed, never buffered: /v1/messages is SSE and must arrive token by
377
+ // token or the agent appears to hang until the response completes.
378
+ upstream.pipe(res);
379
+ };
380
+ const onError = (err) => {
381
+ clearConnectTimer();
382
+ if (allowFailOpen
383
+ && !retried
384
+ && !responseStarted
385
+ && !bufferOverflowed
386
+ && !downstreamClosed
387
+ && !res.headersSent
388
+ && !res.writableEnded
389
+ && !res.destroyed
390
+ && isFailOpenError(err)) {
391
+ retried = true;
392
+ if (activeSink === outbound)
393
+ activeSink = undefined;
394
+ outbound.off('response', onResponse);
395
+ outbound.off('error', onError);
396
+ outbound.on('error', () => { });
397
+ if (!outbound.destroyed)
398
+ outbound.destroy();
399
+ const failKey = `${hostPort}${path}:failopen`;
400
+ if (!announced.has(failKey)) {
401
+ announced.add(failKey);
402
+ if (!process.stdout.isTTY) {
403
+ console.error(`[fiche] warp: ${target.origin} failed (${hostPort}${path}) — failing open direct`);
404
+ }
405
+ }
406
+ sendToTarget(directTarget, false, false);
407
+ return;
408
+ }
409
+ bufferedChunks.length = 0;
410
+ if (!req.destroyed)
411
+ req.destroy?.();
412
+ // Our own teardown below surfaces here as ECONNRESET; the client is
413
+ // already gone, so writing a 502 into it would throw.
414
+ if (res.writableEnded || res.destroyed)
415
+ return;
416
+ if (res.headersSent) {
417
+ res.destroy?.(err);
418
+ return;
419
+ }
420
+ res.writeHead(502, { 'content-type': 'text/plain' });
421
+ res.end('fiche warp: upstream error');
422
+ };
423
+ outbound.on('response', onResponse);
424
+ outbound.on('error', onError);
425
+ outbound.once('close', clearConnectTimer);
426
+ if (allowFailOpen) {
427
+ outbound.once('socket', (sock) => {
428
+ if (!sock.connecting) {
429
+ startPipe();
430
+ }
431
+ else {
432
+ connectTimer = setTimeout(() => {
433
+ connectTimer = undefined;
434
+ const timeoutErr = Object.assign(new Error('connect timeout'), { code: 'ETIMEDOUT' });
435
+ outbound.destroy(timeoutErr);
436
+ }, FAIL_OPEN_CONNECT_TIMEOUT_MS);
437
+ connectTimer.unref?.();
438
+ sock.once('connect', startPipe);
439
+ }
440
+ });
441
+ }
442
+ else {
443
+ startPipe();
444
+ }
445
+ };
446
+ const initialTarget = divertTarget ?? directTarget;
447
+ sendToTarget(initialTarget, allowInitialFailOpen, Boolean(divertTarget));
448
+ };
449
+ const connectTargets = new WeakMap();
450
+ const PROXY_ONLY_UPGRADE_HEADERS = new Set([
451
+ 'proxy-authorization',
452
+ 'proxy-connection',
453
+ 'proxy-authenticate',
454
+ ]);
455
+ const handleDecrypted = (req, res) => {
456
+ const bound = connectTargets.get(req.socket);
457
+ const servername = req.socket.servername || '';
458
+ // Prefer the authoritative CONNECT authority over the HTTP Host header so
459
+ // an inner request cannot domain-front across an already-established tunnel.
460
+ const { host, port } = bound ?? splitHostPort(servername || req.headers.host || '', '443');
461
+ forward(req, res, authority(host, port), req.url ?? '/', `https://${authority(host, port)}`);
462
+ };
463
+ /**
464
+ * Unmatched upgrades (such as Claude Code `/remote-control` or ChatGPT UI
465
+ * sockets) splice directly to the real host so first-party pairing stays
466
+ * intact. WebSocket upgrades on a *matched* HTTP-diverted route (such as
467
+ * `chatgpt.com/backend-api/codex/responses*` or `api.openai.com/v1/responses*`)
468
+ * return `426 Upgrade Required` (`websocket_unsupported`, matching `proxy.ts`),
469
+ * telling Codex to switch immediately to HTTP POST through Fiche.
470
+ */
471
+ const handleUpgrade = (req, clientSocket, head) => {
472
+ const bound = connectTargets.get(req.socket) ?? connectTargets.get(clientSocket);
473
+ const servername = req.socket.servername || '';
474
+ const { host, port } = bound ?? splitHostPort(servername || req.headers.host || '', '443');
475
+ const portNum = parsePort(port);
476
+ if (!host || portNum === null) {
477
+ clientSocket.destroy();
478
+ return;
479
+ }
480
+ if (String(req.headers.upgrade ?? '').toLowerCase().includes('websocket')) {
481
+ try {
482
+ const hostPort = authority(host, port);
483
+ if (!hostHeaderMatches(req.headers.host, host, port)) {
484
+ clientSocket.end('HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\n\r\n');
485
+ return;
486
+ }
487
+ const resolved = new URL(req.url ?? '/', `https://${hostPort}`);
488
+ const reqPath = normalizeRoutePath(resolved.pathname);
489
+ if (matchRoute(getRoutes(), hostPort, reqPath)) {
490
+ const body = JSON.stringify({
491
+ error: {
492
+ type: 'websocket_unsupported',
493
+ message: 'fiche proxies HTTP only; retry over HTTP',
494
+ },
495
+ });
496
+ clientSocket.end('HTTP/1.1 426 Upgrade Required\r\n' +
497
+ 'Content-Type: application/json\r\n' +
498
+ `Content-Length: ${Buffer.byteLength(body)}\r\n` +
499
+ 'Connection: close\r\n\r\n' +
500
+ body);
501
+ return;
502
+ }
503
+ }
504
+ catch {
505
+ clientSocket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
506
+ return;
507
+ }
508
+ }
509
+ const upstream = tlsConnect({ host, port: portNum, servername: isIP(host) !== 0 ? undefined : host }, () => {
510
+ if (clientSocket.destroyed) {
511
+ upstream.destroy();
512
+ return;
513
+ }
514
+ const lines = [`${req.method} ${req.url} HTTP/${req.httpVersion}`];
515
+ for (const [key, value] of Object.entries(req.headers)) {
516
+ if (PROXY_ONLY_UPGRADE_HEADERS.has(key.toLowerCase()))
517
+ continue;
518
+ for (const v of Array.isArray(value) ? value : [value]) {
519
+ if (v !== undefined)
520
+ lines.push(`${key}: ${v}`);
521
+ }
522
+ }
523
+ upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
524
+ if (head?.length)
525
+ upstream.write(head);
526
+ pipeSockets(clientSocket, upstream);
527
+ });
528
+ upstream.on('error', () => clientSocket.destroy());
529
+ clientSocket.on('error', () => upstream.destroy());
530
+ clientSocket.once('close', () => {
531
+ if (!upstream.destroyed)
532
+ upstream.destroy();
533
+ });
534
+ };
535
+ // Non-listening HTTP parser fed per-CONNECT TLSSockets once TLS handshake completes.
536
+ const decryptedServer = createHttpServer();
537
+ decryptedServer.on('request', handleDecrypted);
538
+ decryptedServer.on('upgrade', handleUpgrade);
539
+ decryptedServer.on('clientError', (_err, socket) => socket.destroy());
540
+ const handleConnect = (req, clientSocket, head) => {
541
+ clientSocket.setNoDelay?.(true);
542
+ if (!isLoopbackAddress(req.socket.remoteAddress)) {
543
+ clientSocket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
544
+ return;
545
+ }
546
+ const { host, port } = splitHostPort(req.url ?? '', '443');
547
+ const portNum = parsePort(port);
548
+ if (!host || portNum === null) {
549
+ clientSocket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
550
+ return;
551
+ }
552
+ if (isSelfLoop(host, portNum, req.socket?.localPort)) {
553
+ clientSocket.end('HTTP/1.1 508 Loop Detected\r\n\r\n');
554
+ return;
555
+ }
556
+ if (!hostCouldMatch(getRoutes(), authority(host, port))) {
557
+ const upstream = netConnect({ host, port: portNum }, () => {
558
+ if (clientSocket.destroyed) {
559
+ upstream.destroy();
560
+ return;
561
+ }
562
+ clientSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
563
+ if (head?.length)
564
+ upstream.write(head);
565
+ pipeSockets(clientSocket, upstream);
566
+ });
567
+ upstream.on('error', () => clientSocket.destroy());
568
+ clientSocket.on('error', () => upstream.destroy());
569
+ clientSocket.once('close', () => {
570
+ if (!upstream.destroyed)
571
+ upstream.destroy();
572
+ });
573
+ return;
574
+ }
575
+ // Mint a fallback SecureContext bound to the CONNECT target host before replying 200
576
+ // so no-SNI clients (e.g., IP literals) complete TLS cleanly and failures return 502.
577
+ let fallbackContext;
578
+ try {
579
+ fallbackContext = ca.secureContextFor(host);
580
+ }
581
+ catch {
582
+ clientSocket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n');
583
+ return;
584
+ }
585
+ clientSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
586
+ if (head?.length)
587
+ clientSocket.unshift(head);
588
+ const hostNorm = normalizeHostKey(host);
589
+ const hostIsIp = isIP(hostNorm) !== 0;
590
+ const tlsSocket = new TLSSocket(clientSocket, {
591
+ isServer: true,
592
+ secureContext: fallbackContext,
593
+ SNICallback: (name, cb) => {
594
+ try {
595
+ if (!name) {
596
+ cb(null, fallbackContext);
597
+ return;
598
+ }
599
+ if (!isValidSniHost(name)) {
600
+ cb(new Error('invalid SNI hostname'));
601
+ return;
602
+ }
603
+ const sniNorm = normalizeHostKey(name);
604
+ if (!hostIsIp) {
605
+ if (sniNorm !== hostNorm) {
606
+ cb(new Error('SNI mismatch with CONNECT target'));
607
+ return;
608
+ }
609
+ }
610
+ else if (sniNorm !== hostNorm && !hostCouldMatch(getRoutes(), authority(sniNorm, port))) {
611
+ cb(new Error('SNI not permitted for IP CONNECT target'));
612
+ return;
613
+ }
614
+ cb(null, ca.secureContextFor(sniNorm));
615
+ }
616
+ catch (err) {
617
+ cb(err);
618
+ }
619
+ },
620
+ ALPNProtocols: ['http/1.1'],
621
+ });
622
+ connectTargets.set(tlsSocket, { host, port });
623
+ const handshakeTimer = setTimeout(() => {
624
+ if (!tlsSocket.destroyed)
625
+ tlsSocket.destroy();
626
+ if (!clientSocket.destroyed)
627
+ clientSocket.destroy();
628
+ }, 30_000);
629
+ handshakeTimer.unref();
630
+ const clearHandshakeTimer = () => clearTimeout(handshakeTimer);
631
+ clientSocket.on('error', () => {
632
+ clearHandshakeTimer();
633
+ if (!tlsSocket.destroyed)
634
+ tlsSocket.destroy();
635
+ });
636
+ tlsSocket.on('error', () => {
637
+ clearHandshakeTimer();
638
+ if (!tlsSocket.destroyed)
639
+ tlsSocket.destroy();
640
+ if (!clientSocket.destroyed)
641
+ clientSocket.destroy();
642
+ });
643
+ tlsSocket.once('close', clearHandshakeTimer);
644
+ tlsSocket.once('secure', () => {
645
+ clearHandshakeTimer();
646
+ if (!tlsSocket.destroyed)
647
+ decryptedServer.emit('connection', tlsSocket);
648
+ });
649
+ };
650
+ const handleAbsoluteForm = (req, res) => {
651
+ if (!isLoopbackAddress(req.socket.remoteAddress)) {
652
+ res.writeHead(403, { 'content-type': 'text/plain' });
653
+ res.end('fiche warp: forward proxy is loopback-only');
654
+ return;
655
+ }
656
+ let target;
657
+ try {
658
+ target = new URL(req.url ?? '');
659
+ }
660
+ catch {
661
+ res.writeHead(400, { 'content-type': 'text/plain' });
662
+ res.end('fiche warp: bad absolute URI');
663
+ return;
664
+ }
665
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') {
666
+ res.writeHead(400, { 'content-type': 'text/plain' });
667
+ res.end('fiche warp: unsupported scheme');
668
+ return;
669
+ }
670
+ // A pattern that names a port is matched against "host:port", and the
671
+ // CONNECT path always supplies one via authority(host, port) — but
672
+ // URL.host omits a DEFAULT port, so `api.anthropic.com:443/v1/*` matched
673
+ // a CONNECT and then silently missed the very same request in absolute
674
+ // form. Put the implied port back so both paths hand matchRoute the same
675
+ // authority. target.host already brackets an IPv6 literal and already
676
+ // carries a non-default port, so it only ever needs the default appended.
677
+ const hostPort = target.port
678
+ ? target.host
679
+ : `${target.host}:${target.protocol === 'https:' ? 443 : 80}`;
680
+ // target.origin, not a rebuilt https:// URL: scheme and non-default port
681
+ // are part of where this request was actually going.
682
+ forward(req, res, hostPort, target.pathname + target.search, target.origin);
683
+ };
684
+ return { handleConnect, handleAbsoluteForm };
685
+ }
686
+ //# sourceMappingURL=connect.js.map