context-doctor 0.36.0 → 0.37.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.
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Guards for the MCP server's --http mode, kept apart from mcp.ts (which
3
+ * starts a server on import) so they can be tested directly.
4
+ *
5
+ * A server on 127.0.0.1 is still reachable from a browser: a page can POST to
6
+ * it (a cross-origin "simple" request needs no preflight), and with DNS
7
+ * rebinding a page on attacker.example can even make the browser treat the
8
+ * server as same-origin. A QA pass did exactly that: a foreign origin saved
9
+ * 101 handoffs through --store-handoffs, evicted the user's own and planted
10
+ * handoff://latest. So every /mcp request is checked:
11
+ *
12
+ * - Host must name this server: localhost, 127.0.0.1, [::1], the --host it
13
+ * was given, or a name in --allowed-hosts (a tunnel's host name, say).
14
+ * `--allowed-hosts '*'` turns the check off, explicitly.
15
+ * - Origin, when a browser sends one, must be a loopback origin, one whose
16
+ * host is allowed above, or one in --allowed-origins. ChatGPT's own
17
+ * origins are allowed by default; requests without an Origin (servers,
18
+ * CLIs, ChatGPT's connector backend) are not affected.
19
+ * - The body is read here, capped (10 MB, else 413), and parsed (else 400),
20
+ * then handed to the transport, so no request can make the server buffer
21
+ * an unbounded body.
22
+ */
23
+ export const HTTP_LIMITS = { bodyBytes: 10 * 1024 * 1024, bodyMs: 30_000 };
24
+ /** Origins a browser may call from without being listed: ChatGPT's. */
25
+ export const DEFAULT_ALLOWED_ORIGINS = ["https://chatgpt.com", "https://chat.openai.com"];
26
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1"];
27
+ function list(value) {
28
+ return (value ?? "").split(",").map((x) => x.trim()).filter(Boolean);
29
+ }
30
+ /** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
31
+ export function hostName(hostHeader) {
32
+ let h = hostHeader.trim().toLowerCase();
33
+ if (h.startsWith("["))
34
+ h = h.slice(1, h.indexOf("]") > 0 ? h.indexOf("]") : undefined);
35
+ else if (h.split(":").length === 2)
36
+ h = h.split(":")[0];
37
+ return h.replace(/\.$/, "");
38
+ }
39
+ /**
40
+ * The guard for a server bound to `bindHost`, from --allowed-hosts and
41
+ * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
42
+ * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
43
+ */
44
+ export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env) {
45
+ const extra = [...list(allowedHosts), ...list(env.CONTEXT_DOCTOR_ALLOWED_HOSTS)];
46
+ const origins = new Set([...DEFAULT_ALLOWED_ORIGINS, ...list(allowedOrigins), ...list(env.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map((o) => o.toLowerCase().replace(/\/+$/, "")));
47
+ if (extra.includes("*"))
48
+ return { hosts: "*", origins };
49
+ const bind = hostName(bindHost);
50
+ const hosts = new Set([...LOOPBACK_HOSTS, ...extra.map(hostName)]);
51
+ // A specific bind address or name is one the server answers to; a wildcard is not a name.
52
+ if (bind && bind !== "0.0.0.0" && bind !== "::")
53
+ hosts.add(bind);
54
+ return { hosts, origins };
55
+ }
56
+ /** Why this request may not reach /mcp, or undefined when it may. */
57
+ export function refusal(guard, headers) {
58
+ if (guard.hosts !== "*") {
59
+ const host = hostName(String(headers.host ?? ""));
60
+ if (!host)
61
+ return "the request has no Host header";
62
+ if (!guard.hosts.has(host)) {
63
+ return `Host "${host}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${host}`;
64
+ }
65
+ }
66
+ const origin = headers.origin;
67
+ if (origin !== undefined) {
68
+ const o = String(origin).toLowerCase().replace(/\/+$/, "");
69
+ if (guard.origins.has(o))
70
+ return undefined;
71
+ let url;
72
+ try {
73
+ url = new URL(o);
74
+ }
75
+ catch {
76
+ return `Origin "${o}" is not allowed`;
77
+ }
78
+ const h = hostName(url.host);
79
+ const ok = LOOPBACK_HOSTS.includes(h) || (guard.hosts !== "*" && guard.hosts.has(h));
80
+ if (!ok)
81
+ return `Origin "${o}" is not allowed. To let a web page call this server, start it with --allowed-origins ${o}`;
82
+ }
83
+ return undefined;
84
+ }
85
+ /**
86
+ * The request body as JSON, at most `limit` bytes and within `ms` (a client
87
+ * that declares more than it sends must not hold a request open); otherwise
88
+ * the status and reason to answer with.
89
+ */
90
+ export function readJsonBody(req, limit = HTTP_LIMITS.bodyBytes, ms = HTTP_LIMITS.bodyMs) {
91
+ return new Promise((resolve) => {
92
+ let done = false;
93
+ const timer = setTimeout(() => {
94
+ if (done)
95
+ return;
96
+ done = true;
97
+ resolve({ status: 408, code: -32600, message: `the request body did not arrive within ${Math.round(ms / 1000)} s` });
98
+ }, ms);
99
+ const settle = (r) => {
100
+ clearTimeout(timer);
101
+ resolve(r);
102
+ };
103
+ const tooLarge = { status: 413, code: -32600, message: `request body over ${Math.round(limit / 1024 / 1024)} MB` };
104
+ const declared = Number(req.headers["content-length"]);
105
+ if (Number.isFinite(declared) && declared > limit) {
106
+ req.resume();
107
+ return settle(tooLarge);
108
+ }
109
+ const parts = [];
110
+ let size = 0;
111
+ req.on("data", (d) => {
112
+ if (done)
113
+ return;
114
+ size += d.length;
115
+ if (size > limit) {
116
+ done = true;
117
+ parts.length = 0;
118
+ req.resume();
119
+ return settle(tooLarge);
120
+ }
121
+ parts.push(d);
122
+ });
123
+ req.on("end", () => {
124
+ if (done)
125
+ return;
126
+ done = true;
127
+ try {
128
+ settle({ value: JSON.parse(Buffer.concat(parts).toString("utf8")) });
129
+ }
130
+ catch {
131
+ settle({ status: 400, code: -32700, message: "Parse error: the body is not JSON" });
132
+ }
133
+ });
134
+ req.on("error", () => {
135
+ if (done)
136
+ return;
137
+ done = true;
138
+ settle({ status: 400, code: -32700, message: "the request body could not be read" });
139
+ });
140
+ });
141
+ }
package/dist/ledger.d.ts CHANGED
@@ -57,5 +57,7 @@ export interface CarriedTotals {
57
57
  export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
58
58
  export declare function statePath(): string;
59
59
  export declare function ledgerPath(): string;
60
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
61
+ export declare const LEDGER_STRING_MAX = 100;
60
62
  export declare function recordLedger(entry: Omit<LedgerEntry, "ts">): void;
61
63
  export declare function readLedger(): LedgerEntry[];
package/dist/ledger.js CHANGED
@@ -84,16 +84,32 @@ export function statePath() {
84
84
  export function ledgerPath() {
85
85
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
86
86
  }
87
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
88
+ export const LEDGER_STRING_MAX = 100;
89
+ /** On rotation: what is kept, by bytes and by entries; longer lines are folded, not kept. */
90
+ const LEDGER_ROTATE_AT = 256 * 1024;
91
+ const LEDGER_KEEP_BYTES = 128 * 1024;
92
+ const LEDGER_KEEP_LINES = 500;
93
+ const LEDGER_LINE_MAX = 4 * 1024;
94
+ /** A string field as the ledger keeps it: no control characters, at most LEDGER_STRING_MAX. */
95
+ function cap(v) {
96
+ if (typeof v !== "string")
97
+ return undefined;
98
+ // eslint-disable-next-line no-control-regex
99
+ const clean = v.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
100
+ return clean.length > LEDGER_STRING_MAX ? clean.slice(0, LEDGER_STRING_MAX) : clean;
101
+ }
87
102
  export function recordLedger(entry) {
88
103
  const path = ledgerPath();
89
104
  try {
90
105
  // Claude-Desktop-only machines have no ~/.claude — create it so their
91
106
  // optimize events count in `context-doctor report` too.
92
107
  mkdirSync(dirname(path), { recursive: true });
93
- // Cap growth: past ~256KB keep the most recent 500 entries — but fold the
94
- // dropped ones into a rollup first, or every lifetime total in the reports
95
- // silently shrinks the moment a heavy user crosses the cap.
96
- if (existsSync(path) && statSync(path).size > 256 * 1024) {
108
+ // Cap growth by bytes, not lines: past 256KB keep the newest entries that
109
+ // fit 128KB (at most 500), and fold the rest into a rollup first, or every
110
+ // lifetime total in the reports silently shrinks the moment a heavy user
111
+ // crosses the cap. A line too long to be a real entry is folded, never kept.
112
+ if (existsSync(path) && statSync(path).size > LEDGER_ROTATE_AT) {
97
113
  const lines = readFileSync(path, "utf8").trimEnd().split("\n");
98
114
  const parse = (line) => {
99
115
  try {
@@ -103,13 +119,34 @@ export function recordLedger(entry) {
103
119
  return [];
104
120
  }
105
121
  };
106
- const kept = lines.slice(-500);
107
- const dropped = lines.slice(0, -500).flatMap(parse);
122
+ const keptAt = new Set();
123
+ let bytes = 0;
124
+ for (let i = lines.length - 1; i >= 0 && keptAt.size < LEDGER_KEEP_LINES; i--) {
125
+ const n = Buffer.byteLength(lines[i]) + 1;
126
+ if (n > LEDGER_LINE_MAX)
127
+ continue;
128
+ if (bytes + n > LEDGER_KEEP_BYTES)
129
+ break;
130
+ keptAt.add(i);
131
+ bytes += n;
132
+ }
133
+ const kept = lines.filter((_, i) => keptAt.has(i));
134
+ const dropped = lines.filter((_, i) => !keptAt.has(i)).flatMap(parse);
108
135
  const carried = foldTotals(dropped);
109
136
  const rollup = { ts: Date.now(), ev: "rollup", carried };
110
137
  writeFileSync(path, [JSON.stringify(rollup), ...kept].join("\n") + "\n");
111
138
  }
112
- appendFileSync(path, JSON.stringify({ ts: Date.now(), ...entry }) + "\n");
139
+ const clean = { ...entry };
140
+ for (const k of ["model", "sid", "cv", "app"]) {
141
+ if (k in clean) {
142
+ const v = cap(clean[k]);
143
+ if (v === undefined)
144
+ delete clean[k];
145
+ else
146
+ clean[k] = v;
147
+ }
148
+ }
149
+ appendFileSync(path, JSON.stringify({ ts: Date.now(), ...clean }) + "\n");
113
150
  }
114
151
  catch {
115
152
  /* best-effort */
package/dist/mcp.d.ts CHANGED
@@ -15,5 +15,7 @@
15
15
  * optimize_context — apply safe strategies, return the slimmed conversation
16
16
  * context_best_practices — curated checklist for a given provider/use case
17
17
  * pack_context — only the chunks of big files a question needs, within a token budget
18
+ * save_handoff — store a handoff brief the next chat starts from (a chat's history cannot be cut)
19
+ * Prompts: context_checkup, handoff, ask_file. Resources (stdio): handoff://latest, handoff://<id>.
18
20
  */
19
21
  export {};